diff --git a/README.md b/README.md index e2c0b91..e98b843 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,12 @@ +👍推荐[2021最新实战项目源码下载](https://mp.weixin.qq.com/s?__biz=Mzg2OTA0Njk0OA==&mid=100018862&idx=1&sn=858e00b60c6097e3ba061e79be472280&chksm=4ea1856579d60c73224e4d852af6b0188c3ab905069fc28f4b293963fd1ee55d2069fb229848#rd) + +👍[《JavaGuide 面试突击版》PDF 版本](#公众号) 。[图解计算机基础 PDF 版](#优质原创PDF资源) + +书单已经被移动到[awesome-cs](https://github.com/CodingDocs/awesome-cs) 这个仓库。 + + + +

@@ -10,55 +19,58 @@ 公众号 公众号

+**在线阅读** : https://snailclimb.gitee.io/springboot-guide (上面的地址访问速度缓慢的建议使用这个路径访问) -**在线阅读:** https://snailclimb.gitee.io/springboot-guide (上面的地址访问速度缓慢的建议使用这个路径访问) +**开源的目的是为了大家能一起完善,如果你觉得内容有任何需要完善/补充的地方,欢迎提交 issue/pr。** -## 重要知识点 - -### 开始 +- Github地址:https://github.com/CodingDocs/springboot-guide +- 码云地址:https://gitee.com/SnailClimb/springboot-guide(Github无法访问或者访问速度比较慢的小伙伴可以看码云上的对应内容) -1. **[Spring Boot 介绍](./docs/start/springboot-introduction.md)** -2. [SpringBoot 开发环境要求](./docs/start/springboot-system-requirements.md) -3. **[Spring Boot 版 Hello World & Spring Boot 项目结构分析](./docs/start/springboot-hello-world.md)** +## 重要知识点 ### 基础 -1. **[开发 RestFul Web 服务](./docs/basis/sringboot-restful-web-service.md)** -2. **[RestController VS Controller](./docs/basis/RestControllerVSController.md)** -3. **[Spring Boot 异常处理](./docs/advanced/springboot-handle-exception.md)** -4. **[实际项目中我们是这样做异常处理的](./docs/advanced/springboot-handle-exception-plus.md)** -5. [使用 spring-boot-devtools 进行热部署](./docs/basis/spring-boot-devtools.md) -6. **[ Spring Boot JPA 基础:常见操作解析](./docs/basis/springboot-jpa.md)** -7. **[JPA 中非常重要的连表查询就是这么简单](./docs/basis/springboot-jpa-lianbiao.md)** -8. [SpringBoot 实现过滤器](./docs/basis/springboot-filter.md) -9. [SpringBoot 实现拦截器](./docs/basis/springboot-interceptor.md) -10. [整合 SpringBoot+Mybatis](./docs/basis/springboot-mybatis.md) 、[SpirngBoot2.0+ 的 SpringBoot+Mybatis 多数据源配置](./docs/basis/springboot-mybatis-mutipledatasource.md) +1. [Spring Boot 介绍](./docs/start/springboot-introduction.md) +2. [第一个 Hello World](./docs/start/springboot-hello-world.md) +3. [第一个 RestFul Web 服务](./docs/basis/sringboot-restful-web-service.md) +4. [Spring 如何优雅读取配置文件?](./docs/basis/read-config-properties.md) +5. **异常处理** :[Spring Boot 异常处理的几种方式](./docs/advanced/springboot-handle-exception.md)、[Spring Boot 异常处理在实际项目中的应用](./docs/advanced/springboot-handle-exception-plus.md) +6. **JPA** : [ Spring Boot JPA 基础:常见操作解析](./docs/basis/springboot-jpa.md) 、 [JPA 中非常重要的连表查询就是这么简单](./docs/basis/springboot-jpa-lianbiao.md) +7. **拦截器和过滤器** :[SpringBoot 实现过滤器](./docs/basis/springboot-filter.md) 、[SpringBoot 实现拦截器](./docs/basis/springboot-interceptor.md) +8. **MyBatis** :[整合 SpringBoot+Mybatis](./docs/basis/springboot-mybatis.md) 、[SpirngBoot2.0+ 的 SpringBoot+Mybatis 多数据源配置](./docs/basis/springboot-mybatis-mutipledatasource.md) (TODO:早期文章,不建议阅读,待重构~) +9. [MyBatis-Plus 从入门到上手干事!](./docs/MyBatisPlus.md) +10. [SpringBoot 2.0+ 集成 Swagger 官方 Starter + knife4j 增强方案](./docs/basis/swagger.md) ### 进阶 -1. **[Bean映射工具之Apache BeanUtils VS Spring BeanUtils](./docs/advanced/Apache-BeanUtils-VS-SpringBean-Utils.md)** -2. [5种常见Bean映射工具的性能比对](./docs/advanced/Performance-of-Java-Mapping-Frameworks.md) -3. **[如何在 Spring/Spring Boot 中做参数校验?你需要了解的都在这里!](./docs/advanced/spring-bean-validation.md)** +1. Bean映射工具 :[Bean映射工具之Apache BeanUtils VS Spring BeanUtils](./docs/advanced/Apache-BeanUtils-VS-SpringBean-Utils.md) 、[5种常见Bean映射工具的性能比对](./docs/advanced/Performance-of-Java-Mapping-Frameworks.md) +3. [如何在 Spring/Spring Boot 中优雅地做参数校验?](./docs/spring-bean-validation.md) +3. [使用 PowerMockRunner 和 Mockito 编写单元测试用例](./docs/PowerMockRunnerAndMockito.md) 4. [5分钟搞懂如何在Spring Boot中Schedule Tasks](./docs/advanced/SpringBoot-ScheduleTasks.md) -5. **[新手也能看懂的 Spring Boot 异步编程指南](./docs/advanced/springboot-async.md)** -6. [Spring Boot 整合 阿里云OSS 存储服务,快来免费搭建一个自己的图床](./docs/advanced/springboot-oss.md) +5. [新手也能看懂的 Spring Boot 异步编程指南](./docs/advanced/springboot-async.md) +6. [Kafka 入门+SpringBoot整合Kafka系列](https://github.com/Snailclimb/springboot-kafka) 7. [超详细,新手都能看懂 !使用Spring Boot+Dubbo 搭建一个分布式服务](./docs/advanced/springboot-dubbo.md) 8. [从零入门 !Spring Security With JWT(含权限验证)](https://github.com/Snailclimb/spring-security-jwt-guide) -### 面试题 +### 补充 -- [几道简单的 SpringBoot面试题](./docs/interview/springboot-questions.md) +1. [`@PostConstruct`和`@PreDestroy` 简单使用以及Java9+中的替代方案](./docs/basis/@PostConstruct与@PreDestroy.md) + +## 实战项目 + +1. [使用 Spring Boot搭建一个在线文件预览系统!支持ppt、doc等多种类型文件预览](./docs/projects/kkFileView-SpringBoot在线文件预览系统.md) +2. [ SpringBoot 前后端分离后台管理系统分析!分模块开发、RBAC权限控制...](https://mp.weixin.qq.com/s?__biz=Mzg2OTA0Njk0OA==&mid=2247495011&idx=1&sn=f574f5d75c3720d8b2a665d1d5234d28&chksm=cea1a2a8f9d62bbe9f13f5a030893fe3da6956c4be41471513e6247f74cba5a8df9941798b6e&token=212861022&lang=zh_CN#rd) +3. [一个基于Spring Cloud 的面试刷题系统。](./docs/projects/SpringCloud刷题系统.md) +4. [一个基于 Spring Boot 的在线考试系统](./docs/projects/一个基于SpringBoot的在线考试系统.md) ## 说明 1. 项目 logo 由 [logoly](https://logoly.pro/#/) 生成。 -2. 利用 docsify 生成文档部署在 Github pages: [docsify 官网介绍](https://docsify.js.org/#/) - -### 联系我 +2. 利用 docsify 生成文档部署在 Github Pages 和 Gitee Pages: [docsify 官网介绍](https://docsify.js.org/#/) -添加我的微信备注“Github”,回复关键字 **“加群”** 即可入群。 +### 优质原创PDF资源 -![个人微信](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-7/wechat3.jpeg) +![](https://cdn.jsdelivr.net/gh/javaguide-tech/blog-images-2@main/%E8%AE%A1%E7%AE%97%E6%9C%BA%E4%B8%93%E4%B8%9A/image-20201027160348395.png) ### 公众号 @@ -66,6 +78,6 @@ **《Java面试突击》:** 由本文档衍生的专为面试而生的《Java面试突击》V2.0 PDF 版本[公众号](#公众号)后台回复 **"Java面试突击"** 即可免费领取! -**Java工程师必备学习资源:** 一些Java工程师常用学习资源公众号后台回复关键字 **“1”** 即可免费无套路获取。 +**Java工程师必备学习资源:** 一些Java工程师常用学习资源公众号后台回复关键字 **“1”** 即可免费无套路获取。 ![我的公众号](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-6/167598cd2e17b8ec.png) diff --git a/docs/MyBatisPlus.md b/docs/MyBatisPlus.md new file mode 100644 index 0000000..afd4043 --- /dev/null +++ b/docs/MyBatisPlus.md @@ -0,0 +1,975 @@ +`MyBatis` 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射,而实际开发中,我们都会选择使用 `MyBatisPlus`,它是对 `MyBatis` 框架的进一步增强,能够极大地简化我们的持久层代码,下面就一起来看看 `MyBatisPlus` 中的一些奇淫巧技吧。 + +> 说明:本篇文章需要一定的 `MyBatis` 与 `MyBatisPlus` 基础 + +MyBatis-Plus 官网地址 : https://baomidou.com/ 。 + +## CRUD + +使用 `MyBatisPlus` 实现业务的增删改查非常地简单,一起来看看吧。 + +**1.首先新建一个 SpringBoot 工程,然后引入依赖:** + +```xml + + com.baomidou + mybatis-plus-boot-starter + 3.4.2 + + + mysql + mysql-connector-java + runtime + + + org.projectlombok + lombok + +``` + +**2.配置一下数据源:** + +```yaml +spring: + datasource: + driver-class-name: com.mysql.cj.jdbc.Driver + username: root + url: jdbc:mysql:///mybatisplus?serverTimezone=UTC + password: 123456 +``` + +**3.创建一下数据表:** + +```sql +CREATE DATABASE `mybatisplus`; + +USE `mybatisplus`; + +DROP TABLE IF EXISTS `tbl_employee`; + +CREATE TABLE `tbl_employee` ( + `id` bigint(20) NOT NULL, + `last_name` varchar(255) DEFAULT NULL, + `email` varchar(255) DEFAULT NULL, + `gender` char(1) DEFAULT NULL, + `age` int(11) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=gbk; + +insert into `tbl_employee`(`id`,`last_name`,`email`,`gender`,`age`) values (1,'jack','jack@qq.com','1',35),(2,'tom','tom@qq.com','1',30),(3,'jerry','jerry@qq.com','1',40); +``` + +**4.创建对应的实体类:** + +```java +@Data +public class Employee { + + private Long id; + private String lastName; + private String email; + private Integer age; +} +``` + +**4.编写 `Mapper` 接口:** + +```java +public interface EmployeeMapper extends BaseMapper { +} +``` + +我们只需继承 `MyBatisPlus` 提供的 `BaseMapper` 接口即可,现在我们就拥有了对 `Employee` 进行增删改查的 API,比如: + +```java +@SpringBootTest +@MapperScan("com.wwj.mybatisplusdemo.mapper") +class MybatisplusDemoApplicationTests { + + @Autowired + private EmployeeMapper employeeMapper; + + @Test + void contextLoads() { + List employees = employeeMapper.selectList(null); + employees.forEach(System.out::println); + } +} +``` + +运行结果: + +```java +org.springframework.jdbc.BadSqlGrammarException: +### Error querying database. Cause: java.sql.SQLSyntaxErrorException: Table 'mybatisplus.employee' doesn't exist +``` + +程序报错了,原因是不存在 `employee` 表,这是因为我们的实体类名为 `Employee`,`MyBatisPlus` 默认是以类名作为表名进行操作的,可如果类名和表名不相同(实际开发中也确实可能不同),就需要在实体类中使用 `@TableName` 注解来声明表的名称: + +```java +@Data +@TableName("tbl_employee") // 声明表名称 +public class Employee { + + private Long id; + private String lastName; + private String email; + private Integer age; +} +``` + +重新执行测试代码,结果如下: + +```java +Employee(id=1, lastName=jack, email=jack@qq.com, age=35) +Employee(id=2, lastName=tom, email=tom@qq.com, age=30) +Employee(id=3, lastName=jerry, email=jerry@qq.com, age=40) +``` + +`BaseMapper` 提供了常用的一些增删改查方法: + +![](https://img-blog.csdnimg.cn/20210519084059865.png) + +具体细节可以查阅其源码自行体会,注释都是中文的,非常容易理解。 + +在开发过程中,我们通常会使用 `Service` 层来调用 `Mapper` 层的方法,而 `MyBatisPlus` 也为我们提供了通用的 `Service`: + +```java +public interface EmployeeService extends IService { +} + +@Service +public class EmployeeServiceImpl extends ServiceImpl implements EmployeeService { +} +``` + +事实上,我们只需让 `EmployeeServiceImpl` 继承 `ServiceImpl` 即可获得 `Service` 层的方法,**那么为什么还需要实现 `EmployeeService` 接口呢?** + +这是因为实现 `EmployeeService` 接口能够更方便地对业务进行扩展,一些复杂场景下的数据处理,`MyBatisPlus` 提供的 `Service` 方法可能无法处理,此时我们就需要自己编写代码,这时候只需在 `EmployeeService` 中定义自己的方法,并在 `EmployeeServiceImpl` 中实现即可。 + +先来测试一下 `MyBatisPlus` 提供的 `Service` 方法: + +```java +@SpringBootTest +@MapperScan("com.wwj.mybatisplusdemo.mapper") +class MybatisplusDemoApplicationTests { + + @Autowired + private EmployeeService employeeService; + + @Test + void contextLoads() { + List list = employeeService.list(); + list.forEach(System.out::println); + } +} +``` + +运行结果: + +```java +Employee(id=1, lastName=jack, email=jack@qq.com, age=35) +Employee(id=2, lastName=tom, email=tom@qq.com, age=30) +Employee(id=3, lastName=jerry, email=jerry@qq.com, age=40) +``` + +接下来模拟一个自定义的场景,我们来编写自定义的操作方法,首先在 `EmployeeMapper` 中进行声明: + +```java +public interface EmployeeMapper extends BaseMapper { + + List selectAllByLastName(@Param("lastName") String lastName); +} +``` + +此时我们需要自己编写配置文件实现该方法,在 `resource` 目录下新建一个 `mapper` 文件夹,然后在该文件夹下创建 `EmployeeMapper.xml` 文件: + +```xml + + + + + + id, last_name, email, gender, age + + + + +``` + +`MyBatisPlus` 默认扫描的是类路径下的 `mapper` 目录,这可以从源码中得到体现: + +![](https://img-blog.csdnimg.cn/20210519084046472.png) + +所以我们直接将 `Mapper` 配置文件放在该目录下就没有任何问题,可如果不是这个目录,我们就需要进行配置,比如: + +```yaml +mybatis-plus: + mapper-locations: classpath:xml/*.xml +``` + +编写好 `Mapper` 接口后,我们就需要定义 `Service` 方法了: + +```java +public interface EmployeeService extends IService { + + List listAllByLastName(String lastName); +} + +@Service +public class EmployeeServiceImpl extends ServiceImpl implements EmployeeService { + + @Override + public List listAllByLastName(String lastName) { + return baseMapper.selectAllByLastName(lastName); + } +} +``` + +在 `EmployeeServiceImpl` 中我们无需将 `EmployeeMapper` 注入进来,而是使用 `BaseMapper`,查看 `ServiceImpl` 的源码: + +![](https://img-blog.csdnimg.cn/2021051908403249.png) + +可以看到它为我们注入了一个 `BaseMapper` 对象,而它是第一个泛型类型,也就是 `EmployeeMapper` 类型,所以我们可以直接使用这个 `baseMapper` 来调用 `Mapper` 中的方法,此时编写测试代码: + +```java +@SpringBootTest +@MapperScan("com.wwj.mybatisplusdemo.mapper") +class MybatisplusDemoApplicationTests { + + @Autowired + private EmployeeService employeeService; + + @Test + void contextLoads() { + List list = employeeService.listAllByLastName("tom"); + list.forEach(System.out::println); + } +} +``` + +运行结果: + +```java +Employee(id=2, lastName=tom, email=tom@qq.com, age=30) +``` + +## ID 策略 + +在创建表的时候我故意没有设置主键的增长策略,现在我们来插入一条数据,看看主键是如何增长的: + +```java +@Test +void contextLoads() { + Employee employee = new Employee(); + employee.setLastName("lisa"); + employee.setEmail("lisa@qq.com"); + employee.setAge(20); + employeeService.save(employee); +} +``` + +插入成功后查询一下数据表: + +```sql +mysql> select * from tbl_employee; ++---------------------+-----------+--------------+--------+------+ +| id | last_name | email | gender | age | ++---------------------+-----------+--------------+--------+------+ +| 1 | jack | jack@qq.com | 1 | 35 | +| 2 | tom | tom@qq.com | 1 | 30 | +| 3 | jerry | jerry@qq.com | 1 | 40 | +| 1385934720849584129 | lisa | lisa@qq.com | NULL | 20 | ++---------------------+-----------+--------------+--------+------+ +4 rows in set (0.00 sec) +``` + +可以看到 id 是一串相当长的数字,这是什么意思呢?提前剧透一下,这其实是分布式 id,那又何为分布式 id 呢? + +我们知道,对于一个大型应用,其访问量是非常巨大的,就比如说一个网站每天都有人进行注册,注册的用户信息就需要存入数据表,随着日子一天天过去,数据表中的用户越来越多,此时数据库的查询速度就会受到影响,所以一般情况下,当数据量足够庞大时,数据都会做分库分表的处理。 + +然而,一旦分表,问题就产生了,很显然这些分表的数据都是属于同一张表的数据,只是因为数据量过大而分成若干张表,那么这几张表的主键 id 该怎么管理呢?每张表维护自己的 id?那数据将会有很多的 id 重复,这当然是不被允许的,其实,我们可以使用算法来生成一个绝对不会重复的 id,这样问题就迎刃而解了,事实上,分布式 id 的解决方案有很多: + +1. UUID +1. SnowFlake +1. TinyID +1. Uidgenerator +1. Leaf +6. Tinyid +7. ...... + +以 UUID 为例,它生成的是一串由数字和字母组成的字符串,显然并不适合作为数据表的 id,而且 id 保持递增有序会加快表的查询效率,基于此,`MyBatisPlus` 使用的就是 `SnowFlake`(雪花算法)。 + +`Snowflake` 是 Twitter 开源的分布式 ID 生成算法。`Snowflake` 由 64 bit 的二进制数字组成,这 64bit 的二进制被分成了几部分,每一部分存储的数据都有特定的含义: + +- **第 0 位**: 符号位(标识正负),始终为 0,没有用,不用管。 +- **第 1~41 位** :一共 41 位,用来表示时间戳,单位是毫秒,可以支撑 2 ^41 毫秒(约 69 年) +- **第 42~52 位** :一共 10 位,一般来说,前 5 位表示机房 ID,后 5 位表示机器 ID(实际项目中可以根据实际情况调整)。这样就可以区分不同集群/机房的节点。 +- **第 53~64 位** :一共 12 位,用来表示序列号。 序列号为自增值,代表单台机器每毫秒能够产生的最大 ID 数(2^12 = 4096),也就是说单台机器每毫秒最多可以生成 4096 个 唯一 ID。 + +![](https://oscimg.oschina.net/oscnet/up-a7e54a77b5ab1d9fa16d5ae3a3c50c5aee9.png) + +这也就是为什么插入数据后新的数据 id 是一长串数字的原因了,我们可以在实体类中使用 `@TableId` 来设置主键的策略: + +```java +@Data +@TableName("tbl_employee") +public class Employee { + + @TableId(type = IdType.AUTO) // 设置主键策略 + private Long id; + private String lastName; + private String email; + private Integer age; +} +``` + +`MyBatisPlus` 提供了几种主键的策略: +![](https://img-blog.csdnimg.cn/20210519084011745.png) +其中 `AUTO` 表示数据库自增策略,该策略下需要数据库实现主键的自增(auto_increment),`ASSIGN_ID` 是雪花算法,默认使用的是该策略,`ASSIGN_UUID` 是 UUID 策略,一般不会使用该策略。 + +这里多说一点, 当实体类的主键名为 id,并且数据表的主键名也为 id 时,此时 `MyBatisPlus` 会自动判定该属性为主键 id,倘若名字不是 id 时,就需要标注 `@TableId` 注解,若是实体类中主键名与数据表的主键名不一致,则可以进行声明: + +```java +@TableId(value = "uid",type = IdType.AUTO) // 设置主键策略 +private Long id; +``` + +还可以在配置文件中配置全局的主键策略: + +```yaml +mybatis-plus: + global-config: + db-config: + id-type: auto +``` + +这样能够避免在每个实体类中重复设置主键策略。 + +## 属性自动填充 + +翻阅《阿里巴巴Java开发手册》,在第 5 章 MySQL 数据库可以看到这样一条规范: +![](https://img-blog.csdnimg.cn/20210426214821389.png) +对于一张数据表,它必须具备三个字段: + +- `id` : 唯一ID +- `gmt_create` : 保存的是当前数据创建的时间 +- `gmt_modified` : 保存的是更新时间 + +我们改造一下数据表: + +```sql +alter table tbl_employee add column gmt_create datetime not null; +alter table tbl_employee add column gmt_modified datetime not null; +``` + +然后改造一下实体类: + +```java +@Data +@TableName("tbl_employee") +public class Employee { + + @TableId(type = IdType.AUTO) // 设置主键策略 + private Long id; + private String lastName; + private String email; + private Integer age; + private LocalDateTime gmtCreate; + private LocalDateTime gmtModified; +} +``` + +此时我们在插入数据和更新数据的时候就需要手动去维护这两个属性: + +```java +@Test +void contextLoads() { + Employee employee = new Employee(); + employee.setLastName("lisa"); + employee.setEmail("lisa@qq.com"); + employee.setAge(20); + // 设置创建时间 + employee.setGmtCreate(LocalDateTime.now()); + employee.setGmtModified(LocalDateTime.now()); + employeeService.save(employee); +} + +@Test +void contextLoads() { + Employee employee = new Employee(); + employee.setId(1385934720849584130L); + employee.setAge(50); + // 设置创建时间 + employee.setGmtModified(LocalDateTime.now()); + employeeService.updateById(employee); +} +``` + +每次都需要维护这两个属性未免过于麻烦,好在 `MyBatisPlus` 提供了字段自动填充功能来帮助我们进行管理,需要使用到的是 `@TableField` 注解: + +```java +@Data +@TableName("tbl_employee") +public class Employee { + + @TableId(type = IdType.AUTO) + private Long id; + private String lastName; + private String email; + private Integer age; + @TableField(fill = FieldFill.INSERT) // 插入的时候自动填充 + private LocalDateTime gmtCreate; + @TableField(fill = FieldFill.INSERT_UPDATE) // 插入和更新的时候自动填充 + private LocalDateTime gmtModified; +} +``` + +然后编写一个类实现 MetaObjectHandler 接口: + +```java +@Component +@Slf4j +public class MyMetaObjectHandler implements MetaObjectHandler { + + /** + * 实现插入时的自动填充 + * @param metaObject + */ + @Override + public void insertFill(MetaObject metaObject) { + log.info("insert开始属性填充"); + this.strictInsertFill(metaObject,"gmtCreate", LocalDateTime.class,LocalDateTime.now()); + this.strictInsertFill(metaObject,"gmtModified", LocalDateTime.class,LocalDateTime.now()); + } + + /** + * 实现更新时的自动填充 + * @param metaObject + */ + @Override + public void updateFill(MetaObject metaObject) { + log.info("update开始属性填充"); + this.strictInsertFill(metaObject,"gmtModified", LocalDateTime.class,LocalDateTime.now()); + } +} +``` + +该接口中有两个未实现的方法,分别为插入和更新时的填充方法,在方法中调用 `strictInsertFill()` 方法 即可实现属性的填充,它需要四个参数: + +1. `metaObject`:元对象,就是方法的入参 +1. `fieldName`:为哪个属性进行自动填充 +1. `fieldType`:属性的类型 +1. `fieldVal`:需要填充的属性值 + +此时在插入和更新数据之前,这两个方法会先被执行,以实现属性的自动填充,通过日志我们可以进行验证: + +```java +@Test +void contextLoads() { + Employee employee = new Employee(); + employee.setId(1385934720849584130L); + employee.setAge(15); + employeeService.updateById(employee); +} +``` + +运行结果: + +```java +INFO 15584 --- [ main] c.w.m.handler.MyMetaObjectHandler : update开始属性填充 +2021-04-24 21:32:19.788 INFO 15584 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting... +2021-04-24 21:32:21.244 INFO 15584 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed. +``` + +属性填充其实可以进行一些优化,考虑一些特殊情况,对于一些不存在的属性,就不需要进行属性填充,对于一些设置了值的属性,也不需要进行属性填充,这样可以提高程序的整体运行效率: + +```java +@Component +@Slf4j +public class MyMetaObjectHandler implements MetaObjectHandler { + + @Override + public void insertFill(MetaObject metaObject) { + boolean hasGmtCreate = metaObject.hasSetter("gmtCreate"); + boolean hasGmtModified = metaObject.hasSetter("gmtModified"); + if (hasGmtCreate) { + Object gmtCreate = this.getFieldValByName("gmtCreate", metaObject); + if (gmtCreate == null) { + this.strictInsertFill(metaObject, "gmtCreate", LocalDateTime.class, LocalDateTime.now()); + } + } + if (hasGmtModified) { + Object gmtModified = this.getFieldValByName("gmtModified", metaObject); + if (gmtModified == null) { + this.strictInsertFill(metaObject, "gmtModified", LocalDateTime.class, LocalDateTime.now()); + } + } + } + + @Override + public void updateFill(MetaObject metaObject) { + boolean hasGmtModified = metaObject.hasSetter("gmtModified"); + if (hasGmtModified) { + Object gmtModified = this.getFieldValByName("gmtModified", metaObject); + if (gmtModified == null) { + this.strictInsertFill(metaObject, "gmtModified", LocalDateTime.class, LocalDateTime.now()); + } + } + } +} +``` + +## 逻辑删除 + +逻辑删除对应的是物理删除,分别介绍一下这两个概念: + +1. **物理删除** :指的是真正的删除,即:当执行删除操作时,将数据表中的数据进行删除,之后将无法再查询到该数据 +1. **逻辑删除** :并不是真正意义上的删除,只是对于用户不可见了,它仍然存在与数据表中 + +在这个数据为王的时代,数据就是财富,所以一般并不会有哪个系统在删除某些重要数据时真正删掉了数据,通常都是在数据库中建立一个状态列,让其默认为 0,当为 0 时,用户可见;当执行了删除操作,就将状态列改为 1,此时用户不可见,但数据还是在表中的。 + +![](https://img-blog.csdnimg.cn/20210426215107210.png) + +按照《阿里巴巴Java开发手册》第 5 章 MySQL 数据库相关的建议,我们来为数据表新增一个`is_deleted` 字段: + +```sql +alter table tbl_employee add column is_deleted tinyint not null; +``` + +在实体类中也要添加这一属性: + +```java +@Data +@TableName("tbl_employee") +public class Employee { + + @TableId(type = IdType.AUTO) + private Long id; + private String lastName; + private String email; + private Integer age; + @TableField(fill = FieldFill.INSERT) + private LocalDateTime gmtCreate; + @TableField(fill = FieldFill.INSERT_UPDATE) + private LocalDateTime gmtModified; + /** + * 逻辑删除属性 + */ + @TableLogic + @TableField("is_deleted") + private Boolean deleted; +} +``` + +![](https://img-blog.csdnimg.cn/2021042621530162.png) + +还是参照《阿里巴巴Java开发手册》第 5 章 MySQL 数据库相关的建议,对于布尔类型变量,不能加 is 前缀,所以我们的属性被命名为 `deleted`,但此时就无法与数据表的字段进行对应了,所以我们需要使用 `@TableField` 注解来声明一下数据表的字段名,而 `@TableLogin` 注解用于设置逻辑删除属性;此时我们执行删除操作: + +```java +@Test +void contextLoads() { + employeeService.removeById(3); +} +``` + +查询数据表: + +```sql +mysql> select * from tbl_employee; ++---------------------+-----------+--------------+--------+------+---------------------+---------------------+------------+ +| id | last_name | email | gender | age | gmt_create | gmt_modified | is_deleted | ++---------------------+-----------+--------------+--------+------+---------------------+---------------------+------------+ +| 1 | jack | jack@qq.com | 1 | 35 | 0000-00-00 00:00:00 | 0000-00-00 00:00:00 | 0 | +| 2 | tom | tom@qq.com | 1 | 30 | 0000-00-00 00:00:00 | 0000-00-00 00:00:00 | 0 | +| 3 | jerry | jerry@qq.com | 1 | 40 | 0000-00-00 00:00:00 | 0000-00-00 00:00:00 | 1 | +| 1385934720849584129 | lisa | lisa@qq.com | NULL | 20 | 0000-00-00 00:00:00 | 0000-00-00 00:00:00 | 0 | +| 1385934720849584130 | lisa | lisa@qq.com | NULL | 15 | 2021-04-24 21:14:18 | 2021-04-24 21:32:19 | 0 | ++---------------------+-----------+--------------+--------+------+---------------------+---------------------+------------+ +5 rows in set (0.00 sec) +``` + +可以看到数据并没有被删除,只是 `is_deleted` 字段的属性值被更新成了 1,此时我们再来执行查询操作: + +```java +@Test +void contextLoads() { + List list = employeeService.list(); + list.forEach(System.out::println); +} +``` + +执行结果: + +```java +Employee(id=1, lastName=jack, email=jack@qq.com, age=35, gmtCreate=2021-04-24T21:14:18, gmtModified=2021-04-24T21:14:18, deleted=false) +Employee(id=2, lastName=tom, email=tom@qq.com, age=30, gmtCreate=2021-04-24T21:14:18, gmtModified=2021-04-24T21:14:18, deleted=false) +Employee(id=1385934720849584129, lastName=lisa, email=lisa@qq.com, age=20, gmtCreate=2021-04-24T21:14:18, gmtModified=2021-04-24T21:14:18, deleted=false) +Employee(id=1385934720849584130, lastName=lisa, email=lisa@qq.com, age=15, gmtCreate=2021-04-24T21:14:18, gmtModified=2021-04-24T21:32:19, deleted=false) +``` + +会发现第三条数据并没有被查询出来,它是如何实现的呢?我们可以输出 `MyBatisPlus` 生成的 SQL 来分析一下,在配置文件中进行配置: + +```yaml +mybatis-plus: + configuration: + log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 输出SQL日志 +``` + +运行结果: + +```java +==> Preparing: SELECT id,last_name,email,age,gmt_create,gmt_modified,is_deleted AS deleted FROM tbl_employee WHERE is_deleted=0 +==> Parameters: +<== Columns: id, last_name, email, age, gmt_create, gmt_modified, deleted +<== Row: 1, jack, jack@qq.com, 35, 2021-04-24 21:14:18, 2021-04-24 21:14:18, 0 +<== Row: 2, tom, tom@qq.com, 30, 2021-04-24 21:14:18, 2021-04-24 21:14:18, 0 +<== Row: 1385934720849584129, lisa, lisa@qq.com, 20, 2021-04-24 21:14:18, 2021-04-24 21:14:18, 0 +<== Row: 1385934720849584130, lisa, lisa@qq.com, 15, 2021-04-24 21:14:18, 2021-04-24 21:32:19, 0 +<== Total: 4 +``` + +原来它在查询时携带了一个条件: `is_deleted=0` ,这也说明了 `MyBatisPlus` 默认 0 为不删除,1 为删除。 +若是你想修改这个规定,比如设置-1 为删除,1 为不删除,也可以进行配置: + +```yaml +mybatis-plus: + global-config: + db-config: + id-type: auto + logic-delete-field: deleted # 逻辑删除属性名 + logic-delete-value: -1 # 删除值 + logic-not-delete-value: 1 # 不删除值 +``` + +但建议使用默认的配置,阿里巴巴开发手册也规定 1 表示删除,0 表示未删除。 + +## 分页插件 + +对于分页功能,`MyBatisPlus` 提供了分页插件,只需要进行简单的配置即可实现: + +```java +@Configuration +public class MyBatisConfig { + + /** + * 注册分页插件 + * @return + */ + @Bean + public MybatisPlusInterceptor mybatisPlusInterceptor() { + MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); + interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); + return interceptor; + } +} +``` + +接下来我们就可以使用分页插件提供的功能了: + +```java +@Test +void contextLoads() { + Page page = new Page<>(1,2); + employeeService.page(page, null); + List employeeList = page.getRecords(); + employeeList.forEach(System.out::println); + System.out.println("获取总条数:" + page.getTotal()); + System.out.println("获取当前页码:" + page.getCurrent()); + System.out.println("获取总页码:" + page.getPages()); + System.out.println("获取每页显示的数据条数:" + page.getSize()); + System.out.println("是否有上一页:" + page.hasPrevious()); + System.out.println("是否有下一页:" + page.hasNext()); +} +``` + +其中的 `Page` 对象用于指定分页查询的规则,这里表示按每页两条数据进行分页,并查询第一页的内容,运行结果: + +```java +Employee(id=1, lastName=jack, email=jack@qq.com, age=35, gmtCreate=2021-04-24T21:14:18, gmtModified=2021-04-24T21:14:18, deleted=0) +Employee(id=2, lastName=tom, email=tom@qq.com, age=30, gmtCreate=2021-04-24T21:14:18, gmtModified=2021-04-24T21:14:18, deleted=0) +获取总条数:4 +获取当前页码:1 +获取总页码:2 +获取每页显示的数据条数:2 +是否有上一页:false +是否有下一页:true +``` + +倘若在分页过程中需要限定一些条件,我们就需要构建 QueryWrapper 来实现: + +```java +@Test +void contextLoads() { + Page page = new Page<>(1, 2); + employeeService.page(page, new QueryWrapper() + .between("age", 20, 50) + .eq("gender", 1)); + List employeeList = page.getRecords(); + employeeList.forEach(System.out::println); +} +``` + +此时分页的数据就应该是年龄在 20~50 岁之间,且 gender 值为 1 的员工信息,然后再对这些数据进行分页。 + +## 乐观锁 + +当程序中出现并发访问时,就需要保证数据的一致性。以商品系统为例,现在有两个管理员均想对同一件售价为 100 元的商品进行修改,A 管理员正准备将商品售价改为 150 元,但此时出现了网络问题,导致 A 管理员的操作陷入了等待状态;此时 B 管理员也进行修改,将商品售价改为了 200 元,修改完成后 B 管理员退出了系统,此时 A 管理员的操作也生效了,这样便使得 A 管理员的操作直接覆盖了 B 管理员的操作,B 管理员后续再进行查询时会发现商品售价变为了 150 元,这样的情况是绝对不允许发生的。 + +要想解决这一问题,可以给数据表加锁,常见的方式有两种: + +1. 乐观锁 +1. 悲观锁 + +悲观锁认为并发情况一定会发生,所以在某条数据被修改时,为了避免其它人修改,会直接对数据表进行加锁,它依靠的是数据库本身提供的锁机制(表锁、行锁、读锁、写锁)。 + +而乐观锁则相反,它认为数据产生冲突的情况一般不会发生,所以在修改数据的时候并不会对数据表进行加锁的操作,而是在提交数据时进行校验,判断提交上来的数据是否会发生冲突,如果发生冲突,则提示用户重新进行操作,一般的实现方式为 `设置版本号字段` 。 + +就以商品售价为例,在该表中设置一个版本号字段,让其初始为 1,此时 A 管理员和 B 管理员同时需要修改售价,它们会先读取到数据表中的内容,此时两个管理员读取到的版本号都为 1,此时 B 管理员的操作先生效了,它就会将当前数据表中对应数据的版本号与最开始读取到的版本号作一个比对,发现没有变化,于是修改就生效了,此时版本号加 1。 + +而 A 管理员马上也提交了修改操作,但是此时的版本号为 2,与最开始读取到的版本号并不对应,这就说明数据发生了冲突,此时应该提示 A 管理员操作失败,并让 A 管理员重新查询一次数据。 + +![](https://img-blog.csdnimg.cn/20210426221408623.png) + +乐观锁的优势在于采取了更加宽松的加锁机制,能够提高程序的吞吐量,适用于读操作多的场景。 + +那么接下来我们就来模拟这一过程。 + +**1.创建一张新的数据表:** + +```sql +create table shop( + id bigint(20) not null auto_increment, + name varchar(30) not null, + price int(11) default 0, + version int(11) default 1, + primary key(id) +); + +insert into shop(id,name,price) values(1,'笔记本电脑',8000); +``` + +**2.创建实体类:** + +```java +@Data +public class Shop { + + private Long id; + private String name; + private Integer price; + private Integer version; +} +``` + +**3.创建对应的 `Mapper` 接口:** + +```java +public interface ShopMapper extends BaseMapper { +} +``` + +**4.编写测试代码:** + +```java +@SpringBootTest +@MapperScan("com.wwj.mybatisplusdemo.mapper") +class MybatisplusDemoApplicationTests { + + @Autowired + private ShopMapper shopMapper; + + /** + * 模拟并发场景 + */ + @Test + void contextLoads() { + // A、B管理员读取数据 + Shop A = shopMapper.selectById(1L); + Shop B = shopMapper.selectById(1L); + // B管理员先修改 + B.setPrice(9000); + int result = shopMapper.updateById(B); + if (result == 1) { + System.out.println("B管理员修改成功!"); + } else { + System.out.println("B管理员修改失败!"); + } + // A管理员后修改 + A.setPrice(8500); + int result2 = shopMapper.updateById(A); + if (result2 == 1) { + System.out.println("A管理员修改成功!"); + } else { + System.out.println("A管理员修改失败!"); + } + // 最后查询 + System.out.println(shopMapper.selectById(1L)); + } +} +``` + +执行结果: + +```java +B管理员修改成功! +A管理员修改成功! +Shop(id=1, name=笔记本电脑, price=8500, version=1) +``` + +**问题出现了,B 管理员的操作被 A 管理员覆盖,那么该如何解决这一问题呢?** + +其实 `MyBatisPlus` 已经提供了乐观锁机制,只需要在实体类中使用 `@Version` 声明版本号属性: + +```java +@Data +public class Shop { + + private Long id; + private String name; + private Integer price; + @Version // 声明版本号属性 + private Integer version; +} +``` + +然后注册乐观锁插件: + +```java +@Configuration +public class MyBatisConfig { + + /** + * 注册插件 + * @return + */ + @Bean + public MybatisPlusInterceptor mybatisPlusInterceptor() { + MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); + // 分页插件 + interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); + // 乐观锁插件 + interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); + return interceptor; + } +} +``` + +重新执行测试代码,结果如下: + +```java +B管理员修改成功! +A管理员修改失败! +Shop(id=1, name=笔记本电脑, price=9000, version=2) +``` + +此时 A 管理员的修改就失败了,它需要重新读取最新的数据才能再次进行修改。 + +## 条件构造器 + +在分页插件中我们简单地使用了一下条件构造器(`Wrapper`),下面我们来详细了解一下。 +先来看看 `Wrapper` 的继承体系: +![](https://img-blog.csdnimg.cn/20210519083944315.png) +分别介绍一下它们的作用: + +- `Wrapper`:条件构造器抽象类,最顶端的父类 + - `AbstractWrapper`:查询条件封装抽象类,生成 SQL 的 where 条件 + - `QueryWrapper`:用于对象封装 + - `UpdateWrapper`:用于条件封装 + - `AbstractLambdaWrapper`:Lambda 语法使用 Wrapper + - `LambdaQueryWrapper`:用于对象封装,使用 Lambda 语法 + - `LambdaUpdateWrapper`:用于条件封装,使用 Lambda 语法 + +通常我们使用的都是 `QueryWrapper` 和 `UpdateWrapper`,若是想使用 Lambda 语法来编写,也可以使用 `LambdaQueryWrapper` 和 `LambdaUpdateWrapper`,通过这些条件构造器,我们能够很方便地来实现一些复杂的筛选操作,比如: + +```java +@SpringBootTest +@MapperScan("com.wwj.mybatisplusdemo.mapper") +class MybatisplusDemoApplicationTests { + + @Autowired + private EmployeeMapper employeeMapper; + + @Test + void contextLoads() { + // 查询名字中包含'j',年龄大于20岁,邮箱不为空的员工信息 + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.like("last_name", "j"); + wrapper.gt("age", 20); + wrapper.isNotNull("email"); + List list = employeeMapper.selectList(wrapper); + list.forEach(System.out::println); + } +} +``` + +运行结果: + +```java +Employee(id=1, lastName=jack, email=jack@qq.com, age=35, gmtCreate=2021-04-24T21:14:18, gmtModified=2021-04-24T21:14:18, deleted=0) +``` + +条件构造器提供了丰富的条件方法帮助我们进行条件的构造,比如 `like` 方法会为我们建立模糊查询,查看一下控制台输出的 SQL: + +```sql +==> Preparing: SELECT id,last_name,email,age,gmt_create,gmt_modified,is_deleted AS deleted FROM tbl_employee WHERE is_deleted=0 AND (last_name LIKE ? AND age > ? AND email IS NOT NULL) +==> Parameters: %j%(String), 20(Integer) +``` + +可以看到它是对 `j` 的前后都加上了 `%` ,若是只想查询以 `j` 开头的名字,则可以使用 `likeRight` 方法,若是想查询以 `j` 结尾的名字,,则使用 `likeLeft` 方法。 + +年龄的比较也是如此, `gt` 是大于指定值,若是小于则调用 `lt` ,大于等于调用 `ge` ,小于等于调用 `le` ,不等于调用 `ne` ,还可以使用 `between` 方法实现这一过程,相关的其它方法都可以查阅源码进行学习。 + +因为这些方法返回的其实都是自身实例,所以可使用链式编程: + +```java +@Test +void contextLoads() { + // 查询名字中包含'j',年龄大于20岁,邮箱不为空的员工信息 + QueryWrapper wrapper = new QueryWrapper() + .likeLeft("last_name", "j") + .gt("age", 20) + .isNotNull("email"); + List list = employeeMapper.selectList(wrapper); + list.forEach(System.out::println); +} +``` + +也可以使用 `LambdaQueryWrapper` 实现: + +```java +@Test +void contextLoads() { + // 查询名字中包含'j',年龄大于20岁,邮箱不为空的员工信息 + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .like(Employee::getLastName,"j") + .gt(Employee::getAge,20) + .isNotNull(Employee::getEmail); + List list = employeeMapper.selectList(wrapper); + list.forEach(System.out::println); +} +``` + +这种方式的好处在于对字段的设置不是硬编码,而是采用方法引用的形式,效果与 `QueryWrapper` 是一样的。 + +`UpdateWrapper` 与 `QueryWrapper` 不同,它的作用是封装更新内容的,比如: + +```java +@Test +void contextLoads() { + UpdateWrapper wrapper = new UpdateWrapper() + .set("age", 50) + .set("email", "emp@163.com") + .like("last_name", "j") + .gt("age", 20); + employeeMapper.update(null, wrapper); +} +``` + +将名字中包含 `j` 且年龄大于 20 岁的员工年龄改为 50,邮箱改为 emp@163.com,`UpdateWrapper` 不仅能够封装更新内容,也能作为查询条件,所以在更新数据时可以直接构造一个 `UpdateWrapper` 来设置更新内容和条件。 \ No newline at end of file diff --git a/docs/PowerMockRunnerAndMockito.md b/docs/PowerMockRunnerAndMockito.md new file mode 100644 index 0000000..469e075 --- /dev/null +++ b/docs/PowerMockRunnerAndMockito.md @@ -0,0 +1,161 @@ +单元测试可以提高测试开发的效率,减少代码错误率,提高代码健壮性,提高代码质量。在 Spring 框架中常用的两种测试框架:`PowerMockRunner` 和 `SpringRunner` 两个单元测试,鉴于 `SpringRunner` 启动的一系列依赖和数据连接的问题,推荐使用 `PowerMockRunner`,这样能有效的提高测试的效率,并且其提供的 API 能覆盖的场景广泛,使用方便,可谓是 Java 单元测试之模拟利器。 + +## 1. PowerMock 是什么? + +`PowerMock` 是一个 Java 模拟框架,可用于解决通常认为很难甚至无法测试的测试问题。使用 `PowerMock`,可以模拟静态方法,删除静态初始化程序,允许模拟而不依赖于注入,等等。`PowerMock` 通过在执行测试时在运行时修改字节码来完成这些技巧。`PowerMock` 还包含一些实用程序,可让您更轻松地访问对象的内部状态。 + +举个例子,你在使用 `Junit` 进行单元测试时,并不想让测试数据进入数据库,怎么办?这个时候就可以使用 `PowerMock`,拦截数据库操作,并模拟返回参数。 + +## 2. PowerMock 包引入 + +```xml + + + org.powermock + powermock-core + 2.0.2 + test + + + org.mockito + mockito-core + 2.23.0 + + + org.powermock + powermock-module-junit4 + 2.0.4 + test + + + org.powermock + powermock-api-mockito2 + 2.0.2 + test + + + com.github.jsonzou + jmockdata + 4.3.0 + +``` + +## 3. 重要注解说明 + +```java +@RunWith(PowerMockRunner.class) // 告诉JUnit使用PowerMockRunner进行测试 +@PrepareForTest({RandomUtil.class}) // 所有需要测试的类列在此处,适用于模拟final类或有final, private, static, native方法的类 +@PowerMockIgnore("javax.management.*") //为了解决使用powermock后,提示classloader错误 +``` + +## 4. 使用示例 + +### 4.1 模拟接口返回 + +首先对接口进行 mock,然后录制相关行为 + +```java +InterfaceToMock mock = Powermockito.mock(InterfaceToMock.class) +Powermockito.when(mock.method(Params…)).thenReturn(value) +Powermockito.when(mock.method(Params..)).thenThrow(Exception) +``` + +### 4.2 设置对象的 private 属性 + +需要使用 `Whitebox` 向 class 或者对象中赋值。 + +如我们已经对接口尽心了 mock,现在需要将此 mock 加入到对象中,可以采用如下方法: + +```java +Whitebox.setInternalState(Object object, String fieldname, Object… value); +``` + +其中 object 为需要设置属性的静态类或对象。 + +### 4.3 模拟构造函数 + +对于模拟构造函数,也即当出现 `new InstanceClass()` 时可以将此构造函数拦截并替换结果为我们需要的 mock 对象。 + +注意:使用时需要加入标记: + +```java +@RunWith(PowerMockRunner.class) +@PrepareForTest({ InstanceClass.class }) +@PowerMockIgnore("javax.management.\*") + +Powermockito.whenNew(InstanceClass.class).thenReturn(Object value) +``` + +##### 4.4 模拟静态方法 + +模拟静态方法类似于模拟构造函数,也需要加入注释标记。 + +```java +@RunWith(PowerMockRunner.class) +@PrepareForTest({ StaticClassToMock.class }) +@PowerMockIgnore("javax.management.\*") + +Powermockito.mockStatic(StaticClassToMock.class); +Powermockito.when(StaticClassToMock.method(Object.. params)).thenReturn(Object value) +``` + +##### 4.5 模拟 final 方法 + +Final 方法的模拟类似于模拟静态方法。 + +```java +@RunWith(PowerMockRunner.class) +@PrepareForTest({ FinalClassToMock.class }) +@PowerMockIgnore("javax.management.\*") + +Powermockito.mockStatic(FinalClassToMock.class); +Powermockito.when(StaticClassToMock.method(Object.. params)).thenReturn(Object value) +``` + +### 4.6 模拟静态类 + +模拟静态类类似于模拟静态方法。 + +### 4.7 使用 spy 方法避免执行被测类中的成员函数 + +如被测试类为:TargetClass,想要屏蔽的方法为 targetMethod. + +```java +1) PowerMockito.spy(TargetClass.class); + +2) Powemockito.when(TargetClass.targetMethod()).doReturn() + +3) 注意加入 + +@RunWith(PowerMockRunner.class) +@PrepareForTest(DisplayMoRelationBuilder.class) +@PowerMockIgnore("javax.management.*") +``` + +### 4.8 参数匹配器 + +有时我们在处理 `doMethod(Param param)` 时,不想进行精确匹配,这时可以使用 `Mockito` 提供的模糊匹配方式。 + +如:`Mockito.anyInt()`,`Mockito.anyString()` + +### 4.9 处理 public void 型的静态方法 + +```java +Powermockito.doNothing.when(T class2mock, String method, … params> +``` + +## 5. 单元测试用例可选清单 + +输入数据验证:这些检查通常可以对输入到应用程序系统中的数据采用。 + +- 必传项测试 +- 唯一字段值测试 +- 空值测试 +- 字段只接受允许的字符 +- 负值测试 +- 字段限于字段长度规范 +- 不可能的值 +- 垃圾值测试 +- 检查字段之间的依赖性 +- 等效类划分和边界条件测试 +- 错误和异常处理测试单元测试可以提高测试开发的效率,减少代码错误率,提高代码健壮性,提高代码质量。在 Spring 框架中常用的两种测试框架:PowerMockRunner 和 SpringRunner 两个单元测试,鉴于 SpringRunner 启动的一系列依赖和数据连接的问题,推荐使用 PowerMockRunner,这样能有效的提高测试的效率,并且其提供的 API 能覆盖的场景广泛,使用方便,可谓是 Java 单元测试之模拟利器。 \ No newline at end of file diff --git a/docs/advanced/SpringBoot-ScheduleTasks.md b/docs/advanced/SpringBoot-ScheduleTasks.md index 135eb2d..a443545 100644 --- a/docs/advanced/SpringBoot-ScheduleTasks.md +++ b/docs/advanced/SpringBoot-ScheduleTasks.md @@ -12,7 +12,7 @@ > Cron 表达式: 主要用于定时作业(定时任务)系统定义执行时间或执行频率的表达式,非常厉害,你可以通过 Cron 表达式进行设置定时任务每天或者每个月什么时候执行等等操作。 > -> 推荐一个在线Cron表达式生成器:[http://cron.qqe2.com/](http://cron.qqe2.com/) +> 推荐一个在线Cron表达式生成器: [https://crontab.guru/](https://crontab.guru/) ```java import org.slf4j.Logger; diff --git a/docs/advanced/spring-bean-validation.md b/docs/advanced/spring-bean-validation.md deleted file mode 100644 index 902220a..0000000 --- a/docs/advanced/spring-bean-validation.md +++ /dev/null @@ -1,540 +0,0 @@ -**数据的校验的重要性就不用说了,即使在前端对数据进行校验的情况下,我们还是要对传入后端的数据再进行一遍校验,避免用户绕过浏览器直接通过一些 HTTP 工具直接向后端请求一些违法数据。** - -本文结合自己在项目中的实际使用经验,可以说**文章介绍的内容很实用,不了解的朋友可以学习一下,后面可以立马实践到项目上去。** - -下面我会通过实例程序演示如何在 Java 程序中尤其是 Spring 程序中优雅地的进行参数验证。 - -## 基础设施搭建 - -### 相关依赖 - -如果开发普通 Java 程序的的话,你需要可能需要像下面这样依赖: - -```xml - - org.hibernate.validator - hibernate-validator - 6.0.9.Final - - - javax.el - javax.el-api - 3.0.0 - - - org.glassfish.web - javax.el - 2.2.6 - -``` - -使用 Spring Boot 程序的话只需要`spring-boot-starter-web` 就够了,它的子依赖包含了我们所需要的东西。除了这个依赖,下面的演示还用到了 lombok ,所以不要忘记添加上相关依赖。 - -```xml - - - org.springframework.boot - spring-boot-starter-web - - - org.projectlombok - lombok - true - - - org.springframework.boot - spring-boot-starter-test - test - - -``` - -### 实体类 - -下面这个是示例用到的实体类。 - -```java -@Data -@AllArgsConstructor -@NoArgsConstructor -public class Person { - - @NotNull(message = "classId 不能为空") - private String classId; - - @Size(max = 33) - @NotNull(message = "name 不能为空") - private String name; - - @Pattern(regexp = "((^Man$|^Woman$|^UGM$))", message = "sex 值不在可选范围") - @NotNull(message = "sex 不能为空") - private String sex; - - @Email(message = "email 格式不正确") - @NotNull(message = "email 不能为空") - private String email; - -} -``` - -> 正则表达式说明: -> -> ``` -> - ^string : 匹配以 string 开头的字符串 -> - string$ :匹配以 string 结尾的字符串 -> - ^string$ :精确匹配 string 字符串 -> - ((^Man$|^Woman$|^UGM$)) : 值只能在 Man,Woman,UGM 这三个值中选择 -> ``` - -下面这部分校验注解说明内容参考自:https://www.cnkirito.moe/spring-validation/ ,感谢@[徐靖峰](https://github.com/lexburner)。 - -**JSR提供的校验注解**: - - -- `@Null` 被注释的元素必须为 null -- `@NotNull` 被注释的元素必须不为 null -- `@AssertTrue` 被注释的元素必须为 true -- `@AssertFalse` 被注释的元素必须为 false -- `@Min(value) ` 被注释的元素必须是一个数字,其值必须大于等于指定的最小值 -- `@Max(value) ` 被注释的元素必须是一个数字,其值必须小于等于指定的最大值 -- `@DecimalMin(value) ` 被注释的元素必须是一个数字,其值必须大于等于指定的最小值 -- `@DecimalMax(value)` 被注释的元素必须是一个数字,其值必须小于等于指定的最大值 -- `@Size(max=, min=) ` 被注释的元素的大小必须在指定的范围内 -- `@Digits (integer, fraction) ` 被注释的元素必须是一个数字,其值必须在可接受的范围内 -- `@Past ` 被注释的元素必须是一个过去的日期 -- `@Future` 被注释的元素必须是一个将来的日期 -- `@Pattern(regex=,flag=) ` 被注释的元素必须符合指定的正则表达式 - - -**Hibernate Validator提供的校验注解**: - - -- `@NotBlank(message =) ` 验证字符串非null,且长度必须大于0 -- `@Email` 被注释的元素必须是电子邮箱地址 -- `@Length(min=,max=) ` 被注释的字符串的大小必须在指定的范围内 -- `@NotEmpty ` 被注释的字符串的必须非空 -- `@Range(min=,max=,message=)` 被注释的元素必须在合适的范围内 - -## 验证Controller的输入 - -### 验证请求体(RequestBody) - -**Controller:** - -我们在需要验证的参数上加上了`@Valid`注解,如果验证失败,它将抛出`MethodArgumentNotValidException`。默认情况下,Spring会将此异常转换为HTTP Status 400(错误请求)。 - -```java - -@RestController -@RequestMapping("/api") -public class PersonController { - - @PostMapping("/person") - public ResponseEntity getPerson(@RequestBody @Valid Person person) { - return ResponseEntity.ok().body(person); - } -} -``` - -**ExceptionHandler:** - -自定义异常处理器可以帮助我们捕获异常,并进行一些简单的处理。如果对于下面的处理异常的代码不太理解的话,可以查看这篇文章 [《SpringBoot 处理异常的几种常见姿势》](https://mp.weixin.qq.com/s?__biz=Mzg2OTA0Njk0OA==&mid=2247485568&idx=2&sn=c5ba880fd0c5d82e39531fa42cb036ac&chksm=cea2474bf9d5ce5dcbc6a5f6580198fdce4bc92ef577579183a729cb5d1430e4994720d59b34&token=1924773784&lang=zh_CN#rd)。 - -```java -@ControllerAdvice(assignableTypes = {PersonController.class}) -public class GlobalExceptionHandler { - @ExceptionHandler(MethodArgumentNotValidException.class) - public ResponseEntity> handleValidationExceptions( - MethodArgumentNotValidException ex) { - Map errors = new HashMap<>(); - ex.getBindingResult().getAllErrors().forEach((error) -> { - String fieldName = ((FieldError) error).getField(); - String errorMessage = error.getDefaultMessage(); - errors.put(fieldName, errorMessage); - }); - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errors); - } -} -``` - -**通过测试验证:** - -下面我通过 MockMvc 模拟请求 Controller 的方式来验证是否生效,当然你也可以通过 Postman 这种工具来验证。 - -我们试一下所有参数输入正确的情况。 - -```java -@RunWith(SpringRunner.class) -@SpringBootTest -@AutoConfigureMockMvc -public class PersonControllerTest { - @Autowired - private MockMvc mockMvc; - - @Autowired - private ObjectMapper objectMapper; - - @Test - public void should_get_person_correctly() throws Exception { - Person person = new Person(); - person.setName("SnailClimb"); - person.setSex("Man"); - person.setClassId("82938390"); - person.setEmail("Snailclimb@qq.com"); - - mockMvc.perform(post("/api/person") - .contentType(MediaType.APPLICATION_JSON_UTF8) - .content(objectMapper.writeValueAsString(person))) - .andExpect(MockMvcResultMatchers.jsonPath("name").value("SnailClimb")) - .andExpect(MockMvcResultMatchers.jsonPath("classId").value("82938390")) - .andExpect(MockMvcResultMatchers.jsonPath("sex").value("Man")) - .andExpect(MockMvcResultMatchers.jsonPath("email").value("Snailclimb@qq.com")); - } -} -``` - -验证出现参数不合法的情况抛出异常并且可以正确被捕获。 - -```java - @Test - public void should_check_person_value() throws Exception { - Person person = new Person(); - person.setSex("Man22"); - person.setClassId("82938390"); - person.setEmail("SnailClimb"); - - mockMvc.perform(post("/api/person") - .contentType(MediaType.APPLICATION_JSON_UTF8) - .content(objectMapper.writeValueAsString(person))) - .andExpect(MockMvcResultMatchers.jsonPath("sex").value("sex 值不在可选范围")) - .andExpect(MockMvcResultMatchers.jsonPath("name").value("name 不能为空")) - .andExpect(MockMvcResultMatchers.jsonPath("email").value("email 格式不正确")); - } -``` - -使用 Postman 验证结果如下: - -![Postman 验证结果](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-7/postman-validation.png) - -### 验证请求参数(Path Variables 和 Request Parameters) - -**Controller:** - -**一定一定不要忘记在类上加上 `Validated` 注解了,这个参数可以告诉 Spring 去校验方法参数。** - -```java -@RestController -@RequestMapping("/api") -@Validated -public class PersonController { - - @GetMapping("/person/{id}") - public ResponseEntity getPersonByID(@Valid @PathVariable("id") @Max(value = 5,message = "超过 id 的范围了") Integer id) { - return ResponseEntity.ok().body(id); - } - - @PutMapping("/person") - public ResponseEntity getPersonByName(@Valid @RequestParam("name") @Size(max = 6,message = "超过 name 的范围了") String name) { - return ResponseEntity.ok().body(name); - } -} - -``` - -**ExceptionHandler:** - -```java - @ExceptionHandler(ConstraintViolationException.class) - ResponseEntity handleConstraintViolationException(ConstraintViolationException e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage()); - } -``` - -**通过测试验证:** - -```java - @Test - public void should_check_param_value() throws Exception { - - mockMvc.perform(get("/api/person/6") - .contentType(MediaType.APPLICATION_JSON_UTF8)) - .andExpect(status().isBadRequest()) - .andExpect(content().string("getPersonByID.id: 超过 id 的范围了")); - } - - @Test - public void should_check_param_value2() throws Exception { - - mockMvc.perform(put("/api/person") - .param("name","snailclimbsnailclimb") - .contentType(MediaType.APPLICATION_JSON_UTF8)) - .andExpect(status().isBadRequest()) - .andExpect(content().string("getPersonByName.name: 超过 name 的范围了")); - } -``` - -## 验证 Service 中的方法 - -我们还可以验证任何Spring组件的输入,而不是验证控制器级别的输入,我们可以使用`@Validated`和`@Valid`注释的组合来实现这一需求。 - -**一定一定不要忘记在类上加上 `Validated` 注解了,这个参数可以告诉 Spring 去校验方法参数。** - -```java -@Service -@Validated -public class PersonService { - - public void validatePerson(@Valid Person person){ - // do something - } -} -``` - -**通过测试验证:** - -```java -@RunWith(SpringRunner.class) -@SpringBootTest -@AutoConfigureMockMvc -public class PersonServiceTest { - @Autowired - private PersonService service; - - @Test(expected = ConstraintViolationException.class) - public void should_throw_exception_when_person_is_not_valid() { - Person person = new Person(); - person.setSex("Man22"); - person.setClassId("82938390"); - person.setEmail("SnailClimb"); - service.validatePerson(person); - } - -} -``` - -## Validator 编程方式手动进行参数验证 - -某些场景下可能会需要我们手动校验并获得校验结果。 - -```java - @Test - public void check_person_manually() { - - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Person person = new Person(); - person.setSex("Man22"); - person.setClassId("82938390"); - person.setEmail("SnailClimb"); - Set> violations = validator.validate(person); - //output: - //email 格式不正确 - //name 不能为空 - //sex 值不在可选范围 - for (ConstraintViolation constraintViolation : violations) { - System.out.println(constraintViolation.getMessage()); - } - } -``` - -上面我们是通过 `Validator` 工厂类获得的 `Validator` 示例,当然你也可以通过 `@Autowired` 直接注入的方式。但是在非 Spring Component 类中使用这种方式的话,只能通过工厂类来获得 `Validator`。 - -```java -@Autowired -Validator validate -``` - -## 自定以 Validator(实用) - -如果自带的校验注解无法满足你的需求的话,你还可以自定义实现注解。 - -### 案例一:校验特定字段的值是否在可选范围 - -比如我们现在多了这样一个需求:Person类多了一个 region 字段,region 字段只能是`China`、`China-Taiwan`、`China-HongKong`这三个中的一个。 - -第一步你需要创建一个注解: - -```java -@Target({FIELD}) -@Retention(RUNTIME) -@Constraint(validatedBy = RegionValidator.class) -@Documented -public @interface Region { - - String message() default "Region 值不在可选范围内"; - - Class[] groups() default {}; - - Class[] payload() default {}; -} -``` - -第二步你需要实现 `ConstraintValidator`接口,并重写`isValid` 方法: - -```java -import javax.validation.ConstraintValidator; -import javax.validation.ConstraintValidatorContext; -import java.util.HashSet; - -public class RegionValidator implements ConstraintValidator { - - @Override - public boolean isValid(String value, ConstraintValidatorContext context) { - HashSet regions = new HashSet<>(); - regions.add("China"); - regions.add("China-Taiwan"); - regions.add("China-HongKong"); - return regions.contains(value); - } -} - -``` - -现在你就可以使用这个注解: - -```java - @Region - private String region; -``` - -### 案例二:校验电话号码 - -校验我们的电话号码是否合法,这个可以通过正则表达式来做,相关的正则表达式都可以在网上搜到,你甚至可以搜索到针对特定运营商电话号码段的正则表达式。 - -`PhoneNumber.java` - -```java -import javax.validation.Constraint; -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.FIELD; -import static java.lang.annotation.ElementType.PARAMETER; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -@Documented -@Constraint(validatedBy = PhoneNumberValidator.class) -@Target({FIELD, PARAMETER}) -@Retention(RUNTIME) -public @interface PhoneNumber { - String message() default "Invalid phone number"; - Class[] groups() default {}; - Class[] payload() default {}; -} -``` - -`PhoneNumberValidator.java` - -```java -import javax.validation.ConstraintValidator; -import javax.validation.ConstraintValidatorContext; - -public class PhoneNumberValidator implements ConstraintValidator { - - @Override - public boolean isValid(String phoneField, ConstraintValidatorContext context) { - if (phoneField == null) { - // can be null - return true; - } - return phoneField.matches("^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\\d{8}$") && phoneField.length() > 8 && phoneField.length() < 14; - } -} -``` - -搞定,我们现在就可以使用这个注解了。 - -```java -@PhoneNumber(message = "phoneNumber 格式不正确") -@NotNull(message = "phoneNumber 不能为空") -private String phoneNumber; -``` - -## 使用验证组 - -某些场景下我们需要使用到验证组,这样说可能不太清楚,说简单点就是对对象操作的不同方法有不同的验证规则,示例如下(这个就我目前经历的项目来说使用的比较少,因为本身这个在代码层面理解起来是比较麻烦的,然后写起来也比较麻烦)。 - -先创建两个接口: - -```java -public interface AddPersonGroup { -} -public interface DeletePersonGroup { -} -``` -我们可以这样去使用验证组 - -```java -@NotNull(groups = DeletePersonGroup.class) -@Null(groups = AddPersonGroup.class) -private String group; -``` - -```java -@Service -@Validated -public class PersonService { - - public void validatePerson(@Valid Person person) { - // do something - } - - @Validated(AddPersonGroup.class) - public void validatePersonGroupForAdd(@Valid Person person) { - // do something - } - - @Validated(DeletePersonGroup.class) - public void validatePersonGroupForDelete(@Valid Person person) { - // do something - } - -} -``` - -通过测试验证: - -```java - @Test(expected = ConstraintViolationException.class) - public void should_check_person_with_groups() { - Person person = new Person(); - person.setSex("Man22"); - person.setClassId("82938390"); - person.setEmail("SnailClimb"); - person.setGroup("group1"); - service.validatePersonGroupForAdd(person); - } - - @Test(expected = ConstraintViolationException.class) - public void should_check_person_with_groups2() { - Person person = new Person(); - person.setSex("Man22"); - person.setClassId("82938390"); - person.setEmail("SnailClimb"); - service.validatePersonGroupForDelete(person); - } -``` - -使用验证组这种方式的时候一定要小心,这是一种反模式,还会造成代码逻辑性变差。 - -代码地址:https://github.com/Snailclimb/springboot-guide/tree/master/source-code/advanced/bean-validation-demo - -## `@NotNull` vs `@Column(nullable = false)`(重要) - -在使用 JPA 操作数据的时候会经常碰到 `@Column(nullable = false)` 这种类型的约束,那么它和 `@NotNull` 有何区别呢?搞清楚这个还是很重要的! - -- `@NotNull`是 JSR 303 Bean验证批注,它与数据库约束本身无关。 -- `@Column(nullable = false)` : 是JPA声明列为非空的方法。 - -总结来说就是即前者用于验证,而后者则用于指示数据库创建表的时候对表的约束。 - -## TODO - -- [ ] 原理分析 - -## 参考 - -- https://reflectoring.io/bean-validation-with-spring-boot/ -- https://www.cnkirito.moe/spring-validation// - diff --git a/docs/advanced/springboot-handle-exception-plus.md b/docs/advanced/springboot-handle-exception-plus.md index 84030d5..ad8a809 100644 --- a/docs/advanced/springboot-handle-exception-plus.md +++ b/docs/advanced/springboot-handle-exception-plus.md @@ -1,4 +1,8 @@ -在上一篇文章中我介绍了: + + +> 这篇文章鸽了很久,我在这篇文章 [《用好Java中的枚举,真的没有那么简单!》](https://mp.weixin.qq.com/s?__biz=Mzg2OTA0Njk0OA==&mid=2247486111&idx=2&sn=8299a42edc4733bdf012ebfe9ebf3fbb&chksm=cea24554f9d5cc42eac0e0ecd851c201831f3b149e64fe11f94b548031f10ff2dac1ea9743d3&token=1729829670&lang=zh_CN#rd) 中就提到要分享。还是昨天一个读者提醒我之后,我才发现自己没有将这篇文章发到公众号。说到这里,我发现自己一个很大的问题,就是有时候在文章里面说要更新什么,结果后面就忘记了,很多时候不是自己没写,就因为各种事情混杂导致忘记发了。以后要尽量改正这个问题! + +在上一篇文章[《SpringBoot 处理异常的几种常见姿势》](https://mp.weixin.qq.com/s?__biz=Mzg2OTA0Njk0OA==&mid=2247485568&idx=2&sn=c5ba880fd0c5d82e39531fa42cb036ac&chksm=cea2474bf9d5ce5dcbc6a5f6580198fdce4bc92ef577579183a729cb5d1430e4994720d59b34&token=1729829670&lang=zh_CN#rd)中我介绍了: 1. 使用 `@ControllerAdvice` 和 `@ExceptionHandler` 处理全局异常 2. `@ExceptionHandler` 处理 Controller 级别的异常 @@ -267,7 +271,7 @@ public class Person { } ``` -**`ExceptionController.java`(抛出一场的类)** +**`ExceptionController.java`(抛出异常的类)** ```java @RestController diff --git "a/docs/basis/@PostConstruct\344\270\216@PreDestroy.md" "b/docs/basis/@PostConstruct\344\270\216@PreDestroy.md" new file mode 100644 index 0000000..1e0fafb --- /dev/null +++ "b/docs/basis/@PostConstruct\344\270\216@PreDestroy.md" @@ -0,0 +1,110 @@ +`@PostConstruct`和`@PreDestroy` 是两个作用于 Servlet 生命周期的注解,相信从 Servlet 开始学 Java 后台开发的同学对他应该不陌生。 + +**被这两个注解修饰的方法可以保证在整个 Servlet 生命周期只被执行一次,即使 Web 容器在其内部中多次实例化该方法所在的 bean。** + +**这两个注解分别有什么作用呢**? + +1. **`@PostConstruct`** : 用来修饰方法,标记在项目启动的时候执行这个方法,一般用来执行某些初始化操作比如全局配置。`PostConstruct` 注解的方法会在构造函数之后执行,Servlet 的`init()`方法之前执行。 +2. **`@PreDestroy`** : 当 bean 被 Web 容器的时候被调用,一般用来释放 bean 所持有的资源。。`@PreDestroy` 注解的方法会在Servlet 的`destroy()`方法之前执行。 + +被这个注解修饰的方法需要满足下面这些基本条件: + +- 非静态 +- 该方法必须没有任何参数,除非在拦截器的情况下,在这种情况下,它接受一个由拦截器规范定义的InvocationContext对象 +- void()也就是没有返回值 +- 该方法抛出未检查的异常 +- ...... + +我们新建一个 Spring 程序,其中有一段代码是这样的,输出结果会是什么呢? + +```java + +import org.springframework.context.annotation.Configuration; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; + +@Configuration +public class MyConfiguration { + public MyConfiguration() { + System.out.println("构造方法被调用"); + } + + @PostConstruct + private void init() { + System.out.println("PostConstruct注解方法被调用"); + } + + @PreDestroy + private void shutdown() { + System.out.println("PreDestroy注解方法被调用"); + } +} + + +``` + +输出结果如下: + +![](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-11/life-cycle-annotation01.jpg) + +但是 J2EE已在Java 9中弃用 `@PostConstruct`和`@PreDestroy`这两个注解 ,并计划在Java 11中将其删除。我们有什么更好的替代方法吗?当然有! + +```java +package cn.javaguide.config; + +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class MyConfiguration2 implements InitializingBean, DisposableBean { + public MyConfiguration2() { + System.out.println("构造方法被调用"); + } + + @Override + public void afterPropertiesSet() { + System.out.println("afterPropertiesSet方法被调用"); + } + + @Override + public void destroy() { + System.out.println("destroy方法被调用"); + } + +} + +``` + +输出结果如下,可以看出实现Spring 提供的 `InitializingBean`和 `DisposableBean`接口的效果和使用`@PostConstruct`和`@PreDestroy` 注解的效果一样。 + +![](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-11/life-cycle-annotation02.jpg) + +但是,Spring 官方不推荐使用上面这种方式,[Spring 官方文档](https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-factory-lifecycle)是这样说的: + +> We recommend that you do not use the `InitializingBean` interface, because it unnecessarily couples the code to Spring. Alternatively, we suggest using the [`@PostConstruct`](https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-postconstruct-and-predestroy-annotations) annotation or specifying a POJO initialization method. (我们建议您不要使用 `InitializingBean`回调接口,因为它不必要地将代码耦合到 Spring。另外,我们建议使用`@PostConstruct`注解或指定bean定义支持的通用方法。) + +如果你还是非要使用 Java 9 及以后的版本使用 `@PostConstruct`和`@PreDestroy` 这两个注解的话,你也可以手动添加相关依赖。 + +Maven: + +```xml + + javax.annotation + javax.annotation-api + 1.3.2 + +``` + +Gradle: + +```groovy +compile group: 'javax.annotation', name: 'javax.annotation-api', version: '1.3.2' +``` + +> 源码地址:https://github.com/Snailclimb/springboot-guide/tree/master/source-code/basis/life-cycle-annotation + +推荐阅读: + +- [Spring Bean Life Cycle](https://netjs.blogspot.com/2016/03/spring-bean-life-cycle.html) diff --git a/docs/basis/read-config-properties.md b/docs/basis/read-config-properties.md new file mode 100644 index 0000000..b959952 --- /dev/null +++ b/docs/basis/read-config-properties.md @@ -0,0 +1,245 @@ +很多时候我们需要将一些常用的配置信息比如阿里云oss配置、发送短信的相关信息配置等等放到配置文件中。 + +下面我们来看一下 Spring 为我们提供了哪些方式帮助我们从配置文件中读取这些配置信息。 + +`application.yml` 内容如下: + +```yaml +wuhan2020: 2020年初武汉爆发了新型冠状病毒,疫情严重,但是,我相信一切都会过去!武汉加油!中国加油! + +my-profile: + name: Guide哥 + email: koushuangbwcx@163.com + +library: + location: 湖北武汉加油中国加油 + books: + - name: 天才基本法 + description: 二十二岁的林朝夕在父亲确诊阿尔茨海默病这天,得知自己暗恋多年的校园男神裴之即将出国深造的消息——对方考取的学校,恰是父亲当年为她放弃的那所。 + - name: 时间的秩序 + description: 为什么我们记得过去,而非未来?时间“流逝”意味着什么?是我们存在于时间之内,还是时间存在于我们之中?卡洛·罗韦利用诗意的文字,邀请我们思考这一亘古难题——时间的本质。 + - name: 了不起的我 + description: 如何养成一个新习惯?如何让心智变得更成熟?如何拥有高质量的关系? 如何走出人生的艰难时刻? + +``` + +### 1.通过 `@value` 读取比较简单的配置信息 + +使用 `@Value("${property}")` 读取比较简单的配置信息: + +```java +@Value("${wuhan2020}") +String wuhan2020; +``` + +> **需要注意的是 `@value`这种方式是不被推荐的,Spring 比较建议的是下面几种读取配置信息的方式。** + +### 2.通过`@ConfigurationProperties`读取并与 bean 绑定 + +> **`LibraryProperties` 类上加了 `@Component` 注解,我们可以像使用普通 bean 一样将其注入到类中使用。** + +```java + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Component +@ConfigurationProperties(prefix = "library") +@Setter +@Getter +@ToString +class LibraryProperties { + private String location; + private List books; + + @Setter + @Getter + @ToString + static class Book { + String name; + String description; + } +} + +``` + +这个时候你就可以像使用普通 bean 一样,将其注入到类中使用: + +```java +package cn.javaguide.readconfigproperties; + +import org.springframework.beans.factory.InitializingBean; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * @author shuang.kou + */ +@SpringBootApplication +public class ReadConfigPropertiesApplication implements InitializingBean { + + private final LibraryProperties library; + + public ReadConfigPropertiesApplication(LibraryProperties library) { + this.library = library; + } + + public static void main(String[] args) { + SpringApplication.run(ReadConfigPropertiesApplication.class, args); + } + + @Override + public void afterPropertiesSet() { + System.out.println(library.getLocation()); + System.out.println(library.getBooks()); } +} +``` + +控制台输出: + +``` +湖北武汉加油中国加油 +[LibraryProperties.Book(name=天才基本法, description........] +``` + +### 3.通过`@ConfigurationProperties`读取并校验 + +我们先将`application.yml`修改为如下内容,明显看出这不是一个正确的 email 格式: + +```yaml +my-profile: + name: Guide哥 + email: koushuangbwcx@ +``` + +>**`ProfileProperties` 类没有加 `@Component` 注解。我们在我们要使用`ProfileProperties` 的地方使用`@EnableConfigurationProperties`注册我们的配置bean:** + + ```java +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; +import org.springframework.validation.annotation.Validated; + +import javax.validation.constraints.Email; +import javax.validation.constraints.NotEmpty; + +/** + * @author shuang.kou + */ +@Getter +@Setter +@ToString +@ConfigurationProperties("my-profile") +@Validated +public class ProfileProperties { + @NotEmpty + private String name; + + @Email + @NotEmpty + private String email; + + //配置文件中没有读取到的话就用默认值 + private Boolean handsome = Boolean.TRUE; + +} + ``` + +具体使用: + +```java +package cn.javaguide.readconfigproperties; + +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.EnableConfigurationProperties; + +/** + * @author shuang.kou + */ +@SpringBootApplication +@EnableConfigurationProperties(ProfileProperties.class) +public class ReadConfigPropertiesApplication implements InitializingBean { + private final ProfileProperties profileProperties; + + public ReadConfigPropertiesApplication(ProfileProperties profileProperties) { + this.profileProperties = profileProperties; + } + + public static void main(String[] args) { + SpringApplication.run(ReadConfigPropertiesApplication.class, args); + } + + @Override + public void afterPropertiesSet() { + System.out.println(profileProperties.toString()); + } +} + +``` + +因为我们的邮箱格式不正确,所以程序运行的时候就报错,根本运行不起来,保证了数据类型的安全性: + +```visual basic +Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'my-profile' to cn.javaguide.readconfigproperties.ProfileProperties failed: + + Property: my-profile.email + Value: koushuangbwcx@ + Origin: class path resource [application.yml]:5:10 + Reason: must be a well-formed email address +``` + +我们把邮箱测试改为正确的之后再运行,控制台就能成功打印出读取到的信息: + +``` +ProfileProperties(name=Guide哥, email=koushuangbwcx@163.com, handsome=true) +``` + +### 4.`@PropertySource`读取指定 properties 文件 + +```java +import lombok.Getter; +import lombok.Setter; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.PropertySource; +import org.springframework.stereotype.Component; + +@Component +@PropertySource("classpath:website.properties") +@Getter +@Setter +class WebSite { + @Value("${url}") + private String url; +} +``` + +使用: + +```java +@Autowired +private WebSite webSite; + +System.out.println(webSite.getUrl());//https://javaguide.cn/ + +``` + +### 5.题外话:Spring加载配置文件的优先级 + +Spring 读取配置文件也是有优先级的,直接上图: + + + +更对内容请查看官方文档:https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config + +> 本文源码:https://github.com/Snailclimb/springboot-guide/tree/master/source-code/basis/read-config-properties \ No newline at end of file diff --git a/docs/basis/spring-boot-devtools.md b/docs/basis/spring-boot-devtools.md deleted file mode 100644 index 16c910e..0000000 --- a/docs/basis/spring-boot-devtools.md +++ /dev/null @@ -1,63 +0,0 @@ -后端开发中热部署有很多方式,但是在开发 SpringBoot 项目有一种 Spring Boot 给我们提供好的很方便的一种方式,配置起来也很简单。 - -> 热部署可以简单的这样理解:我们修改程序代码后不需要重新启动程序,就可以获取到最新的代码,更新程序对外的行为。 - -热部署在我们日常开发可以为我们节省很多时间,通常我们在开发后端的过程中,当我们修改了后端代码之后都需要重启一下项目,这为我们浪费了时间,特别是在项目比较庞大,需要耗费大量时间的启动的时候。**这种方式好像消耗性能挺大的,也需要慎重使用。** - -下面介绍一下如何通过 SpringBoot 提供的 spring-boot-devtools 实现简单的热部署。 - -**依赖:** - -Maven: - -```xml - - org.springframework.boot - spring-boot-devtools - runtime - true - -``` - -```xml - - org.springframework.boot - spring-boot-maven-plugin - -``` - -Gradle: - -```groovy - -configurations { - developmentOnly - runtimeClasspath { - extendsFrom developmentOnly - } -} -dependencies { - developmentOnly("org.springframework.boot:spring-boot-devtools") -} - -``` - - - -**添加配置:** - -ctrl+,(Win) / cmd+(Mac)打开项目配置: - -输入 Compiler , 并且勾选上 Build project automatically - -![dev-tools-idea1](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-7/dev-tools-idea1.png) - -输入快捷键 ctrl + shift + alt + / (Win)cmd+option+shift+/(Mac),并且选择 Registry - -![dev-tools-idea2](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-7/dev-tools-idea2.png) - -然后勾选上 Compiler autoMake allow when app running - -![dev-tools-idea3](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-7/dev-tools-idea3.png) - -很简单,这样你每次修改程序之后就不用重新启动了。 \ No newline at end of file diff --git a/docs/basis/springboot-jpa-lianbiao.md b/docs/basis/springboot-jpa-lianbiao.md index f5535fd..8e5ac19 100644 --- a/docs/basis/springboot-jpa-lianbiao.md +++ b/docs/basis/springboot-jpa-lianbiao.md @@ -1,8 +1,8 @@ # JPA 连表查询和分页 -对于连表查询,在 JPA 中还是非常常见的,由于 JPA 可以在 respository 层自定义 SQL 语句,所以通过自定义 SQL 语句的方式实现连表还是挺简单。这篇文章是在上一篇[入门 JPA](./springboot-jpa)的文章的基础上写的,不了解 JPA 的可以先看上一篇文章。 +对于连表查询,在 JPA 中还是非常常见的,由于 JPA 可以在 respository 层自定义 SQL 语句,所以通过自定义 SQL 语句的方式实现连表还是挺简单。这篇文章是在上一篇[入门 JPA](./springboot-jpa.md)的文章的基础上写的,不了解 JPA 的可以先看上一篇文章。 -在[上一节](./springboot-jpa)的基础上我们新建了两个实体类,如下: +在[上一节](./springboot-jpa.md)的基础上我们新建了两个实体类,如下: ## 相关实体类创建 @@ -158,5 +158,3 @@ List userDTOS = personRepository.filterUserInfoByAge(19,20); 1. 自定义 SQL 语句实现连表查询; 2. 自定义 SQL 语句连表查询并实现分页操作; 3. 条件查询:IN 查询,BETWEEN查询。 - -我们这一节是把 SQl 语句连表查询的逻辑放在 Dao 层直接写的,这样写的好处是比较方便,也比较简单明了。但是可能会不太好维护,很多时候我们会选择将这些逻辑放到 Service 层去做,这样也是可以实现的,下面文章我就会介绍到如何将这些写在 Dao 层的逻辑转移到 Service 层去。 \ No newline at end of file diff --git a/docs/basis/springboot-jpa.md b/docs/basis/springboot-jpa.md index c3484ab..de4d8c3 100644 --- a/docs/basis/springboot-jpa.md +++ b/docs/basis/springboot-jpa.md @@ -38,6 +38,8 @@ JPA 这部分内容上手很容易,但是涉及到的东西还是挺多的, ## 2.配置数据库连接信息和JPA配置 +由于使用的是 h2 内存数据库,所以你直接运行项目数据库就会自动创建好。 + 下面的配置中需要单独说一下 `spring.jpa.hibernate.ddl-auto=create`这个配置选项。 这个属性常用的选项有四种: @@ -50,15 +52,22 @@ JPA 这部分内容上手很容易,但是涉及到的东西还是挺多的, 但是,**一定要不要在生产环境使用 ddl 自动生成表结构,一般推荐手写 SQL 语句配合 Flyway 来做这些事情。** ```properties -spring.datasource.url=jdbc:mysql://localhost:3306/springboot_jpa?useSSL=false&serverTimezone=CTT +# 数据库url地址 +spring.datasource.url=jdbc:h2:mem:jpa-demo spring.datasource.username=root spring.datasource.password=123456 +spring.datasource.platform=h2 +spring.datasource.driverClassName =org.h2.Driver + +spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true # 打印出 sql 语句 spring.jpa.show-sql=true -spring.jpa.hibernate.ddl-auto=create +spring.jpa.hibernate.ddl-auto=update spring.jpa.open-in-view=false -# 创建的表的 ENGINE 为 InnoDB -spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL55Dialect +server.port=8080 +#H2控制台 +spring.h2.console.enabled=true + ``` ## 3.实体类 diff --git a/docs/basis/springboot-mybatis.md b/docs/basis/springboot-mybatis.md index 47e6bd4..1955c8c 100644 --- a/docs/basis/springboot-mybatis.md +++ b/docs/basis/springboot-mybatis.md @@ -35,8 +35,6 @@ SpringBoot 整合 Mybatis 有两种常用的方式,一种就是我们常见的 - 数据库:MySQL - SpringBoot版本:2.1.0 - - ### 1.2 创建工程 创建一个基本的 SpringBoot 项目,我这里就不多说这方面问题了,具体可以参考前面的文章。 diff --git a/docs/basis/swagger.md b/docs/basis/swagger.md new file mode 100644 index 0000000..3b83260 --- /dev/null +++ b/docs/basis/swagger.md @@ -0,0 +1,216 @@ +> 若图片无法显示,👉:[Swagger 官方 Starter 配上这个增强方案是真的香!](https://mp.weixin.qq.com/s?__biz=Mzg2OTA0Njk0OA==&mid=2247496557&idx=1&sn=77100461596999128e5d721e07f7fe3d&chksm=cea1bca6f9d635b01f45a68a6034faf76c2f5a54223b23b2dc5a0bdb15c7b7bfea0a20a76c1a&token=1835542145&lang=zh_CN#rd) + +这篇文章,我就简单给大家聊聊项目必备的 Swagger 该怎么玩。 + +**何为 Swagger ?** 简单来说,Swagger 就是一套基于 OpenAPI 规范构建的开源工具,可以帮助我们设计、构建、记录以及使用 Rest API。 + +**为何要用 Swagger ?** 前后端分离的情况下,一份 Rest API 文档将会极大的提高我们的工作效率。前端小伙伴只需要对照着 Rest API 文档就可以搞清楚一个接口需要的参数以及返回值。通过 Swagger 我们只需要少量注解即可生成一份自带 UI 界面的 Rest API 文档,不需要我们后端手动编写。并且,通过 UI 界面,我们还可以直接对相应的 API 进行调试,省去了准备复杂的调用参数的过程。 + +这篇文章的主要内容: + +1. SpringBoot 项目中如何使用? +2. Spring Security 项目中如何使用? +3. 使用 knife4j 增强 Swagger + +以下演示所用代码,你可以在这个仓库找到:[https://github.com/Snailclimb/spring-security-jwt-guide](https://github.com/Snailclimb/spring-security-jwt-guide) (从零入门 !Spring Security With JWT(含权限验证)后端部分代码) + +## SpringBoot 项目中如何使用? + +Swagger3.0 官方已经有了自己的 Spring Boot Starter,只需要添加一个 jar 包即可(SpringBoot 版本 2.3.6.RELEASE)。。 + +```xml + + + io.springfox + springfox-boot-starter + 3.0.0 + +``` + +什么都不用配置!直接在浏览器中访问 :[http://ip:port/swagger-ui/](http://ip:port/swagger-ui/) 即可。 + +![](https://cdn.jsdelivr.net/gh/javaguide-tech/blog-images-6@main/12-08-1/swagger%E5%9C%A8SpringBoot%E4%B8%AD%E7%AE%80%E5%8D%95%E4%BD%BF%E7%94%A8.png) + +## Spring Security 项目中如何使用? + +如果你的项目使用了 Spring Security 做权限认证的话,你需要为 Swagger 相关 url 添加白名单。 + +```java + String[] SWAGGER_WHITELIST = { + "/swagger-ui.html", + "/swagger-ui/*", + "/swagger-resources/**", + "/v2/api-docs", + "/v3/api-docs", + "/webjars/**" + }; + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.cors().and() + // 禁用 CSRF + .csrf().disable() + .authorizeRequests() + // swagger + .antMatchers(SWAGGER_WHITELIST).permitAll() + ...... + } +``` + +另外,某些请求需要认证之后才可以访问,为此,我们需要对 Swagger 做一些简单的配置。 + +配置的方式非常简单,我提供两种不同的方式给小伙伴们。 + +1. 登录后自动为请求添加 token。 +2. 为请求的 Header 添加一个认证参数,每次请求的时候,我们需要手动输入 token。 + +### 登录后自动为请求添加 token + +通过这种方式我们只需要授权一次即可使用所有需要授权的接口。 + +![](https://cdn.jsdelivr.net/gh/javaguide-tech/blog-images-6@main/12-15-1/%E7%99%BB%E5%BD%95%E5%90%8E%E8%87%AA%E5%8A%A8%E4%B8%BA%E8%AF%B7%E6%B1%82%E6%B7%BB%E5%8A%A0token.png) + +```java +/** + * @author shuang.kou + * @description swagger 相关配置 + */ +@Configuration +public class SwaggerConfig { + + @Bean + public Docket createRestApi() { + return new Docket(DocumentationType.SWAGGER_2) + .apiInfo(apiInfo()) + .select() + .apis(RequestHandlerSelectors.basePackage("github.javaguide.springsecurityjwtguide")) + .paths(PathSelectors.any()) + .build() + .securityContexts(securityContext()) + .securitySchemes(securitySchemes()); + } + + private List securitySchemes() { + return Collections.singletonList(new ApiKey("JWT", SecurityConstants.TOKEN_HEADER, "header")); + } + + private List securityContext() { + SecurityContext securityContext = SecurityContext.builder() + .securityReferences(defaultAuth()) + .build(); + return Collections.singletonList(securityContext); + } + + List defaultAuth() { + AuthorizationScope authorizationScope + = new AuthorizationScope("global", "accessEverything"); + AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; + authorizationScopes[0] = authorizationScope; + return Collections.singletonList(new SecurityReference("JWT", authorizationScopes)); + } + + private ApiInfo apiInfo() { + return new ApiInfoBuilder() + .title("Spring Security JWT Guide") + .build(); + } +} +``` + +**未登录前:** + +![](https://cdn.jsdelivr.net/gh/javaguide-tech/blog-images-6@main/12-15-1/%E8%87%AA%E5%8A%A8%E6%B7%BB%E5%8A%A0token-%E7%99%BB%E5%BD%95%E5%89%8D.png) + +**登录后:** + +![](https://cdn.jsdelivr.net/gh/javaguide-tech/blog-images-6@main/12-15-1/%E8%87%AA%E5%8A%A8%E6%B7%BB%E5%8A%A0token-%E7%99%BB%E5%BD%95%E5%90%8E.png) + +### 为请求的 Header 添加一个认证参数 + +每次请求的时候,我们需要手动输入 token 到指定位置。 + +![](https://cdn.jsdelivr.net/gh/javaguide-tech/blog-images-6@main/12-15-1/%E4%B8%BA%E8%AF%B7%E6%B1%82%E7%9A%84Header%E6%B7%BB%E5%8A%A0%E4%B8%80%E4%B8%AA%E8%AE%A4%E8%AF%81%E5%8F%82%E6%95%B0.png) + +```java +@Configuration +public class SwaggerConfig { + + @Bean + public Docket createRestApi() { + return new Docket(DocumentationType.SWAGGER_2) + .apiInfo(apiInfo()) + .select() + .apis(RequestHandlerSelectors.basePackage("github.javaguide.springsecurityjwtguide")) + .paths(PathSelectors.any()) + .build() + .globalRequestParameters(authorizationParameter()) + .securitySchemes(securitySchemes()); + } + + private List securitySchemes() { + return Collections.singletonList(new ApiKey("JWT", SecurityConstants.TOKEN_HEADER, "header")); + } + + private List authorizationParameter() { + RequestParameterBuilder tokenBuilder = new RequestParameterBuilder(); + tokenBuilder + .name("Authorization") + .description("JWT") + .required(false) + .in("header") + .accepts(Collections.singleton(MediaType.APPLICATION_JSON)) + .build(); + return Collections.singletonList(tokenBuilder.build()); + } + + private ApiInfo apiInfo() { + return new ApiInfoBuilder() + .title("Spring Security JWT Guide") + .build(); + } +} +``` + +## 使用 knife4j 增强 Swagger + +根据官网介绍,knife4j 是为 Java MVC 框架集成 Swagger 生成 Api 文档的增强解决方案。 + +项目地址:[https://gitee.com/xiaoym/knife4j](https://gitee.com/xiaoym/knife4j) 。 + +使用方式非常简单,添加到相关依赖即可(SpringBoot 版本 2.3.6.RELEASE)。 + +```xml + + com.github.xiaoymin + knife4j-spring-boot-starter + 3.0.2 + +``` + +完成之后,访问:[http://ip:port/doc.html](http://ip:port/doc.html) 即可。 + +效果如下。可以看出,相比于 swagger 原生 ui 确实好看实用了很多。 + +![](https://cdn.jsdelivr.net/gh/javaguide-tech/blog-images-6@main/12-08-1/image-20201211214120861.png) + +除了 UI 上的增强之外,knife4j 还提供了一些开箱即用的功能。 + +比如:**搜索 API 接口** (`knife4j` 版本>2.0.1 ) + +![](https://cdn.jsdelivr.net/gh/javaguide-tech/blog-images-6@main/12-08-1/image-20201211214620338.png) + +再比如:**导出离线文档** + +通过 `Knife4j` 我们可以非常方便地导出 Swagger 文档 ,并且支持多种格式。 + +> - markdown:导出当前逻辑分组下所有接口的 Markdown 格式的文档 +> - Html:导出当前逻辑分组下所有接口的 Html 格式的文档 +> - Word:导出当前逻辑分组下所有接口的 Word 格式的文档(自 2.0.5 版本开始) +> - OpenAPI:导出当前逻辑分组下的原始 OpenAPI 的规范 json 结构(自 2.0.6 版本开始) +> - PDF:未实现 + +以 HTML 格式导出的效果图如下。 + +![](https://cdn.jsdelivr.net/gh/javaguide-tech/blog-images-6@main/12-08-1/image-20201211215552314.png) + +还等什么?快去试试吧! \ No newline at end of file diff --git a/docs/interview/springboot-questions.md b/docs/interview/springboot-questions.md deleted file mode 100644 index 501cb05..0000000 --- a/docs/interview/springboot-questions.md +++ /dev/null @@ -1,197 +0,0 @@ -> 本文由JavaGuide整理翻译自(做了适当删减、修改和补充): -> -> - https://www.javaguides.net/2018/11/spring-boot-interview-questions-and-answers.html -> - https://www.algrim.co/posts/101-spring-boot-interview-questions - -### 1. 什么是 Spring Boot? - -首先,重要的是要理解 Spring Boot 并不是一个框架,它是一种创建独立应用程序的更简单方法,只需要很少或没有配置(相比于 Spring 来说)。Spring Boot最好的特性之一是它利用现有的 Spring 项目和第三方项目来开发适合生产的应用程序。 - -### 2. 说出使用Spring Boot的主要优点 - -1. 开发基于 Spring 的应用程序很容易。 -2. Spring Boot 项目所需的开发或工程时间明显减少,通常会提高整体生产力。 -3. Spring Boot不需要编写大量样板代码、XML配置和注释。 -4. Spring引导应用程序可以很容易地与Spring生态系统集成,如Spring JDBC、Spring ORM、Spring Data、Spring Security等。 -5. Spring Boot遵循“固执己见的默认配置”,以减少开发工作(默认配置可以修改)。 -6. Spring Boot 应用程序提供嵌入式HTTP服务器,如Tomcat和Jetty,可以轻松地开发和测试web应用程序。(这点很赞!普通运行Java程序的方式就能运行基于Spring Boot web 项目,省事很多) -7. Spring Boot提供命令行接口(CLI)工具,用于开发和测试Spring Boot应用程序,如Java或Groovy。 -8. Spring Boot提供了多种插件,可以使用内置工具(如Maven和Gradle)开发和测试Spring Boot应用程序。 - -### 3. 为什么需要Spring Boot? - -Spring Framework旨在简化J2EE企业应用程序开发。Spring Boot Framework旨在简化Spring开发。 - -![why-we-need-springboot](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-7/why-we-need-springboot.png) - -### 4. 什么是 Spring Boot Starters? - -Spring Boot Starters 是一系列依赖关系的集合,因为它的存在,项目的依赖之间的关系对我们来说变的更加简单了。举个例子:在没有Spring Boot Starters之前,我们开发REST服务或Web应用程序时; 我们需要使用像Spring MVC,Tomcat和Jackson这样的库,这些依赖我们需要手动一个一个添加。但是,有了 Spring Boot Starters 我们只需要一个只需添加一个**spring-boot-starter-web**一个依赖就可以了,这个依赖包含的字依赖中包含了我们开发REST 服务需要的所有依赖。 - -```xml - - org.springframework.boot - spring-boot-starter-web - -``` - -### 5. 如何在Spring Boot应用程序中使用Jetty而不是Tomcat? - -Spring Boot Web starter使用Tomcat作为默认的嵌入式servlet容器, 如果你想使用 Jetty 的话只需要修改pom.xml(Maven)或者build.gradle(Gradle)就可以了。 - -**Maven:** - -```xml - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - - org.springframework.boot - spring-boot-starter-jetty - -``` - -**Gradle:** - -```groovy -compile("org.springframework.boot:spring-boot-starter-web") { - exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat' -} -compile("org.springframework.boot:spring-boot-starter-jetty") -``` - -说个题外话,从上面可以看出使用 Gradle 更加简洁明了,但是国内目前还是 Maven 使用的多一点,我个人觉得 Gradle 在很多方面都要好很多。 - -### 6. 介绍一下@SpringBootApplication注解 - -```java -package org.springframework.boot.autoconfigure; -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Inherited -@SpringBootConfiguration -@EnableAutoConfiguration -@ComponentScan(excludeFilters = { - @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), - @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) }) -public @interface SpringBootApplication { - ...... -} -``` - -```java -package org.springframework.boot; -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Configuration -public @interface SpringBootConfiguration { - -} -``` - -可以看出大概可以把 `@SpringBootApplication `看作是 `@Configuration`、`@EnableAutoConfiguration`、`@ComponentScan ` 注解的集合。根据 SpringBoot官网,这三个注解的作用分别是: - -- `@EnableAutoConfiguration`:启用 SpringBoot 的自动配置机制 -- `@ComponentScan`: 扫描被`@Component` (`@Service`,`@Controller`)注解的bean,注解默认会扫描该类所在的包下所有的类。 -- `@Configuration`:允许在上下文中注册额外的bean或导入其他配置类 - -### 7. (重要)Spring Boot 的自动配置是如何实现的? - -这个是因为`@SpringBootApplication `注解的原因,在上一个问题中已经提到了这个注解。我们知道 `@SpringBootApplication `看作是 `@Configuration`、`@EnableAutoConfiguration`、`@ComponentScan ` 注解的集合。 - -- `@EnableAutoConfiguration`:启用 SpringBoot 的自动配置机制 -- `@ComponentScan`: 扫描被`@Component` (`@Service`,`@Controller`)注解的bean,注解默认会扫描该类所在的包下所有的类。 -- `@Configuration`:允许在上下文中注册额外的bean或导入其他配置类 - -`@EnableAutoConfiguration`是启动自动配置的关键,源码如下(建议自己打断点调试,走一遍基本的流程): - -```java -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import org.springframework.context.annotation.Import; - -@Target({ElementType.TYPE}) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Inherited -@AutoConfigurationPackage -@Import({AutoConfigurationImportSelector.class}) -public @interface EnableAutoConfiguration { - String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration"; - - Class[] exclude() default {}; - - String[] excludeName() default {}; -} -``` - -`@EnableAutoConfiguration` 注解通过Spring 提供的 `@Import` 注解导入了`AutoConfigurationImportSelector`类(`@Import` 注解可以导入配置类或者Bean到当前类中)。 - -` ``AutoConfigurationImportSelector`类中`getCandidateConfigurations`方法会将所有自动配置类的信息以 List 的形式返回。这些配置信息会被 Spring 容器作 bean 来管理。 - -```java - protected List getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) { - List configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(), - getBeanClassLoader()); - Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you " - + "are using a custom packaging, make sure that file is correct."); - return configurations; - } -``` - -自动配置信息有了,那么自动配置还差什么呢? - -`@Conditional` 注解。`@ConditionalOnClass`(指定的类必须存在于类路径下),`@ConditionalOnBean`(容器中是否有指定的Bean)等等都是对`@Conditional`注解的扩展。拿 Spring Security 的自动配置举个例子: - -`SecurityAutoConfiguration`中导入了`WebSecurityEnablerConfiguration`类,`WebSecurityEnablerConfiguration`源代码如下: - -```java -@Configuration -@ConditionalOnBean(WebSecurityConfigurerAdapter.class) -@ConditionalOnMissingBean(name = BeanIds.SPRING_SECURITY_FILTER_CHAIN) -@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) -@EnableWebSecurity -public class WebSecurityEnablerConfiguration { - -} -``` - -`WebSecurityEnablerConfiguration`类中使用`@ConditionalOnBean`指定了容器中必须还有`WebSecurityConfigurerAdapter` 类或其实现类。所以,一般情况下 Spring Security 配置类都会去实现 `WebSecurityConfigurerAdapter`,这样自动将配置就完成了。 - -更多内容可以参考这篇文章:https://sylvanassun.github.io/2018/01/08/2018-01-08-spring_boot_auto_configure/ - -### 8. Spring Boot支持哪些嵌入式web容器? - -Spring Boot支持以下嵌入式servlet容器: - -| **Name** | **Servlet Version** | -| ------------ | ------------------- | -| Tomcat 9.0 | 4.0 | -| Jetty 9.4 | 3.1 | -| Undertow 2.0 | 4.0 | - -您还可以将Spring引导应用程序部署到任何Servlet 3.1+兼容的 Web 容器中。 - -这就是你为什么可以通过直接像运行 普通 Java 项目一样运行 SpringBoot 项目。这样的确省事了很多,方便了我们进行开发,降低了学习难度。 - -### 9. 什么是Spring Security ? - -Spring Security 应该属于 Spring 全家桶中学习曲线比较陡峭的几个模块之一,下面我将从起源和定义这两个方面来简单介绍一下它。 - -- **起源:** Spring Security 实际上起源于 Acegi Security,这个框架能为基于 Spring 的企业应用提供强大而灵活安全访问控制解决方案,并且框架这个充分利用 Spring 的 IoC 和 AOP 功能,提供声明式安全访问控制的功能。后面,随着这个项目发展, Acegi Security 成为了Spring官方子项目,后来被命名为 “Spring Security”。 -- **定义:**Spring Security 是一个功能强大且高度可以定制的框架,侧重于为Java 应用程序提供身份验证和授权。——[官方介绍](https://spring.io/projects/spring-security)。 \ No newline at end of file diff --git "a/docs/projects/SpringCloud\345\210\267\351\242\230\347\263\273\347\273\237.md" "b/docs/projects/SpringCloud\345\210\267\351\242\230\347\263\273\347\273\237.md" new file mode 100644 index 0000000..2309eab --- /dev/null +++ "b/docs/projects/SpringCloud\345\210\267\351\242\230\347\263\273\347\273\237.md" @@ -0,0 +1,121 @@ +> 推荐👍: +> - [接近100K star 的 Java 学习/面试指南](https://github.com/Snailclimb/JavaGuide) +> - [Github 95k+点赞的 Java 面试/学习手册.PDF](https://www.yuque.com/docs/share/f0c5ffbc-48b5-45f3-af66-2a5e6f212595) + +今天给小伙伴们推荐一个朋友开源的面试刷题系统。 + +这篇文章我会从系统架构设计层面详解介绍这个开源项目,并且会把微服务常用的一些技术都介绍一下。即使你对这个项目不感兴趣,也能了解到很多微服务相关的知识。美滋滋! + +_昨晚肝了很久~原创不易,若有帮助,求赞求转发啊!_ + +不得不说,这个刷题系统确实是有点东西,你真的值得拥有!首先,这是一个微服务的项目,其次这个系统涵盖了市面上常用的主流技术比如 SpringBoot、Spring Cloud 等等(后面会详细介绍)。 + +不论是你想要学习分布式的技术,还是想找一个实战项目练手或者作为自己的项目经验,这个项目都非常适合你。 + +另外,因为项目作者提供了详细的技术文档,所以你不用担心上手太难! + +![PassJava文档](https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/2020-12-21/PassJava%E6%96%87%E6%A1%A3%E5%9C%B0%E5%9D%80.png) + +## 效果图 + +我们先来看看这个面试刷题系统的效果图。这里我们只展示的是这个系统的前端(微信小程序),后台管理系统这里就不展示了。 + +![PassJava前端展示](https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/2020-12-21/PassJava%E5%89%8D%E7%AB%AF%E5%B1%95%E7%A4%BA.png) + +可以看到,除了少部分地方的颜色搭配比较难看之外,页面整体 UI 还是比较美观的。 + +## 技术栈 + +再聊聊大家最关心的问题:“**这套系统的技术栈是什么样的呢?**”。 + +这套系统采用了目前企业都在用的主流技术:SpringBoot(基础框架)、Spring Cloud(微服务)、MyBatis(ORM框架)、Redis(缓存)、MySql(关系型数据库)、MongoDB(NoSQL)、RabbitMQ(消息队列)、Elasticsearch(搜索引擎)。并且,这个系统是以 Docker 容器化的方式进行部署的。非常实用! + +## 系统架构设计 + +了解了技术栈之后,那必然需要简单了解一下整个 **系统的架构设计** ,这是系统的灵魂所在了(图源:[PassJava 官方文档](http://jayh2018.gitee.io/passjava-learning/#/01.项目简介/2.项目微服务架构图 "PassJava官方文档"))。 + +![](http://cdn.jayh.club/blog/20200407/scg1XhlvGbUV.png?imageslim) + +### 网关 + +网关负责认证授权、限流、熔断、降级、请求分发、负载均衡等等操作。一般情况下,网关一般都会提供这些功能。 + +这里使用的是 **Spring Cloud Gateway** 作为网关。Spring Cloud Gateway 是 Spring Cloud 官方推出的第二代网关框架,目的是取代 netflix 的 Zuul 网关。 + +### 注册中心和配置中心 + +注册中心和配置中心这块使用的是阿里巴巴开源的 **Nacos** 。Nacos 目前属于 Spring Cloud Alibaba 中的一员。主要用于发现、配置和管理微服务,类似于 Consul、Eureka。并且,提供了分布式配置管理功能。 + +Nacos 的基本介绍如下(图源:[官网文档-什么是 Nacos](https://nacos.io/zh-cn/docs/what-is-nacos.html "官网文档-什么是 Nacos")): + +![nacos_map](https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/2020-12-21/nacosMap.jpg) + +详解介绍一下 Nacos 在这个项目中提供的两个核心功能: + +- **注册中心** :API 网关通过注册中心实时获取到服务的路由地址,准确地将请求路由到各个服务。 +- **配置中心** :传统的配置方式需要重新启动服务。如果服务很多,则需要重启所有服务,非常不方便。通过 Nacos,我们可以动态配置服务。并且,Nacos 提供了一个简洁易用的 UI 帮助我们管理所有的服务和应用的配置。 + +关于配置中心,我们这里再拓展一下,除了 Nacos ,还有 Apollo、SpringCloud Config、K8s ConfigMap 可供选择。 + +### 分布式链路追踪 + +> 不同于单体架构,在分布式架构下,请求需要在多个服务之间调用,排查问题会非常麻烦。我们需要分布式链路追踪系统来解决这个痛点。 + +分布式链路追踪这块使用的是 Twitter 的 **Zipkin** ,并且结合了 **Spring Cloud Sleuth** 。 + +Spring Cloud Sleuth 只是做一些链路追踪相关的数据记录,我们可以使用 Zipkin Server 来处理这些数据。 + +相关阅读:[《40 张图看懂分布式追踪系统原理及实践》](https://mp.weixin.qq.com/s?__biz=Mzg2OTA0Njk0OA==&mid=2247492112&idx=3&sn=4eb100f4ecef98a475d7f7650c993222&chksm=cea1addbf9d624cdc0e868d3b72edf40a7a6880218ecb1a9ddbac50423d20dceceb8dca804f4&token=2007747701&lang=zh_CN#rd) 。 + +### 监控系统 + +监控系统可以帮助我们监控应用程序的状态,并且能够在风险发生前告警。 + +监控系统这块使用的是 **Prometheus + Grafana**。Prometheus 负责收集监控数据,Grafana 用于展示监控数据。我们直接将 Grafana 的数据源选择为 Prometheus 即可。 + +关于监控系统更详细的技术选型,可以看这篇文章:[《监控系统选型看这一篇够了!选择 Prometheus 还是 Zabbix ?》](https://mp.weixin.qq.com/s?__biz=Mzg2OTA0Njk0OA==&mid=2247490068&idx=2&sn=3ac42f6891fec8906230cc9e0ec28ba7&chksm=cea255dff9d5dcc9369c9c30eb55925cd16045d914cbfe194ea7d5630c3339630d731d654527&token=2007747701&lang=zh_CN#rd) 。 + +### 消息队列 + +我们知道,消息队列主要能为系统带来三点好处: + +1. **通过异步处理提高系统性能(减少响应所需时间)。** +2. **削峰/限流** +3. **降低系统耦合性。** + +常用的消息队列有:RabbitMQ(本系统所采用的方案)、Kafka、RocketMQ。 + +### 缓存 + +缓存这里使用的是 Redis ,老生常谈了,这里就不再多做介绍。 + +另外, 为了保证缓存服务的高可用,我们使用 Redis 官方提供了一种 Redis 集群的解决方案 Redis Sentinel 来管理 Redis 集群。 + +### 数据库 + +数据库这里使用的是 MySQL ,并使用主从模式实现读写分离,以提高读性能。 + +### 对象存储 + +由于是分布式系统,传统的将文件上传到本机已经没办法满足我们的需求了。 + +由于自己搭建分布式文件系统也比较麻烦,所以对象存储这里我们使用的是阿里云 OSS,它主要用于存储一些文件比如图片。 + +### 快速开发脚手架 + +另外,为了后台的快速搭建这里使用的是 **[renren-fast](https://gitee.com/renrenio/renren-fast "renren-fast")** 快速开发脚手架。使用这个脚手架配合上代码生成器 **[renren-generator](https://gitee.com/renrenio/renren-generator "renren-generator")** ,我们可以快速生成 70%左右的前后端代码。绝对是快速开发项目并交付以及接私活的利器了! + +我在之前的也推荐过这个脚手架,详情请看下面这两篇文章: + +1. [听说你要接私活?Guide 连夜整理了 5 个开源免费的 Java 项目快速开发脚手架。](https://mp.weixin.qq.com/s?__biz=Mzg2OTA0Njk0OA==&mid=2247487002&idx=1&sn=e9db79f1bbd561b3ead1c9475f8fd7f5&chksm=cea241d1f9d5c8c72fa33764208a26a26de5d2d3e4ac2a6794e0792ba779bb11414b3fd506e3&token=2007747701&lang=zh_CN#rd) +2. [解放双手,再来推荐 5 个 Java 项目开发快速开发脚手架!项目经验和私活都不愁了!](https://mp.weixin.qq.com/s?__biz=Mzg2OTA0Njk0OA==&mid=2247487467&idx=1&sn=c2d2bd28918b58d8646f1441791aeaaf&chksm=cea24020f9d5c9364afc22013fac3266fabffcaa370f708434a6a304274c6b1d8bce235b7a24&token=2007747701&lang=zh_CN#rd) + +## 总结 + +这篇文章我主要从架构设计层面分析了朋友开源的这个基于微服务的刷题系统。 + +当然了,朋友使用微服务开发这个项目的主要目的也是为了自己实践微服务相关的知识,同时也是为了给需要微服务相关实战项目经验的小伙伴一个可以学习的项目。不然的话,直接用单体就完事了,完全可以支撑这个项目目前的并发量以及可预见的未来的并发量。 + +- 项目地址:https://github.com/Jackson0714/PassJava-Platform +- 文档地址:http://jayh2018.gitee.io/passjava-learning/#/ + diff --git "a/docs/projects/kkFileView-SpringBoot\345\234\250\347\272\277\346\226\207\344\273\266\351\242\204\350\247\210\347\263\273\347\273\237.md" "b/docs/projects/kkFileView-SpringBoot\345\234\250\347\272\277\346\226\207\344\273\266\351\242\204\350\247\210\347\263\273\347\273\237.md" new file mode 100644 index 0000000..19d09a0 --- /dev/null +++ "b/docs/projects/kkFileView-SpringBoot\345\234\250\347\272\277\346\226\207\344\273\266\351\242\204\350\247\210\347\263\273\347\273\237.md" @@ -0,0 +1,239 @@ +> 昨晚搭建环境都花了好一会时间,主要在浪费在了安装 openoffice 这个依赖环境上(_Mac 需要手动安装_)。 +> +> 然后,又一步一步功能演示,记录,调试项目,并且简单研究了一下核心代码之后才把这篇文章写完。 +> +> 另外,这篇文章我还会简单分析一下项目核心代码。 +> +> _如果有帮助,欢迎点赞/再看鼓励,我会开心很久 ღ( ´・ᴗ・` )比心_ + +## 项目介绍 + +官方是这样介绍 kkFileView 的: + +> kkFileView 是使用 spring boot 打造文件文档在线预览项目解决方案,支持 doc、docx、ppt、pptx、xls、xlsx、zip、rar、mp4、mp3 以及众多类文本如 txt、html、xml、java、properties、sql、js、md、json、conf、ini、vue、php、py、bat、gitignore 等文件在线预览 + +**简单来说 kkFileView 就是常见的文件类型的在线预览解决方案。** + +总的来说我觉得 kkFileView 是一个非常棒的开源项目,在线文件预览这个需求非常常见。感谢开源! + +下面, 我站在一个“上帝”的角度从多个维度来评价一下 kkFileView: + +1. 代码质量一般,有很多可以优化的地方比如: + - `Controller` 层代码嵌套太多逻辑 + - 没有进行全局异常处理(_代码中是直接返回错误信息的 json 数据给前端,我并不推荐这样做_) + - 返回值不需要通过`ObjectMapper`转换为 JSON 格式(`ResponseEntity`+`@RestController` 就行了) + - ...... +2. 使用的公司比较多,说明项目整体功能还是比较稳定和成熟的! +3. 代码整体逻辑还是比较清晰的,比较容易看懂,给作者们点个赞! + +## 环境搭建 + +### 克隆项目 + +通过以下命令即可将项目克隆到本地: + +```bash +git clone https://gitee.com/kekingcn/file-online-preview.git +``` + +### 安装 OpenOffice + +office 类型的文件的预览依赖了 OpenOffice ,所以我们首先要安装 OpenOffice(Windows 下已内置,Linux 会自动安装,Mac OS 下需要手动安装)。 + +下面演示一下如何在 Mac 上安装 OpenOffice。 + +你可以通过以下命令安装最新版的 OpenOffice: + +```bash +brew cask install openoffice +``` + +不过,这种方式下载可能会比较慢,你可以直接去官网下载 dmg 安装包。 + +官方下载地址:[https://www.openoffice.org/download/](https://www.openoffice.org/download/) + +![OpenOffice下载 ](https://img-blog.csdnimg.cn/20201015194327797.png) + +很多小伙伴就要问了:**OpenOffice 是什么呢?** + +[OpenOffice](https://www.openoffice.org/) 是 Apache 旗下的一款开源免费的文字处理软件,支持 Windows、Liunx、OS X 等主流操作系统。 + +OpenOffice 和 Windows 下 office 办公软件有点类似,不过其实开源免费的。 + +![why openoffice](https://img-blog.csdnimg.cn/20201015194328447.png) + +### 启动项目 + +运行`FilePreviewApplication`的 main 方法,服务启动后,访问[http://localhost:8012/](http://localhost:8012/) 会看到如下界面,代表服务启动成功。 + +![项目启动成功](https://img-blog.csdnimg.cn/20201015194328801.png) + +## 使用 + +我们首先上传了 3 个不同的类型的文件来分别演示一下图片、PDF、Word 文档的预览。 + +![](https://img-blog.csdnimg.cn/20201015194328978.png) + +### 图片的预览 + +**kkFileView 支持 jpg,jpeg,png,gif 等多种格式图片的预览,还包括了翻转,缩放图片等操作。** + +图片的预览效果如下。 + +![图片的预览效果](https://img-blog.csdnimg.cn/20201015194329517.png) + +### Word 文档的预览 + +**kkFileView 支持 doc,docx 文档预览。** + +另外,根据 Word 大小以及网速问题, Word 预览提供了两种模式: + +- 每页 Word 转为图片预览 +- 整个 Word 文档转成 PDF,再预览 PDF。 + +两种模式的适用场景如下 + +- **图片预览** :Word 文件大(加载 PDF 速度比较慢)的情况。 +- **PDF 预览** :内网访问(加载 PDF 速度比较快)的情况。 + +图片预览模式预览效果如下: + +![](https://img-blog.csdnimg.cn/20201015194329908.png) + +PDF 预览模式预览效果如下: + +![](https://img-blog.csdnimg.cn/20201015194330591.png) + +### PDF 文档的预览 + +kkFileView 支持 PDF 文档预览。类似 Word 文档预览, PDF 预览提供了两种模式: + +- 每页 Word 转为图片预览 +- 整个 Word 文档转成 PDF,再预览 PDF。 + +由于和 Word 文档的预览展示效果一致,这里就不放图片了。 + +## 文件预览核心代码分析 + +### API 层 + +文件预览调用的接口是 `/onlinePreview` 。 + +通过分析 `/onlinePreview` 接口我们发现, 后端接收到预览请求之后,会从 URL 和请求中筛选出自己需要的信息比如文件后缀、文件名。 + +之后会调用`FilePreview`类 的 `filePreviewHandle()` 方法。`filePreviewHandle()` 方法是实现文件预览的核心方法。 + +```java +@RequestMapping(value = "/onlinePreview") +public String onlinePreview(String url, Model model, HttpServletRequest req) { + FileAttribute fileAttribute = fileUtils.getFileAttribute(url); + req.setAttribute("fileKey", req.getParameter("fileKey")); + model.addAttribute("pdfDownloadDisable", ConfigConstants.getPdfDownloadDisable()); + model.addAttribute("officePreviewType", req.getParameter("officePreviewType")); + FilePreview filePreview = previewFactory.get(fileAttribute); + logger.info("预览文件url:{},previewType:{}", url, fileAttribute.getType()); + return filePreview.filePreviewHandle(url, model, fileAttribute); +} +``` + +`FilePreview` 是文件预览接口,不同的文件类型的预览都实现了 `FilePreview` 接口,并实现了 `filePreviewHandle()` 方法。 + +### 文件预览接口 + +```java +public interface FilePreview { + String filePreviewHandle(String url, Model model, FileAttribute fileAttribute); +} +``` + +不同的文件类型的预览都实现了 `FilePreview` 接口,如下图所示。 + +![](https://img-blog.csdnimg.cn/20201015194330836.png) + +不同文件类型的预览都会实现 `FilePreview` 接口,然后重写`filePreviewHandle()`方法。比如: `OfficeFilePreviewImpl` 这个主要负责处理 office 文件的预览、`PdfFilePreviewImpl` 主要负责处理 pdf 文件的预览。 + +### 文件预览具体实现分析 + +下面我们以 office 文件的预览为入口来分析。 + +首先要明确的是 excel 类型的预览是通过将 excel 文件转换为 HTML 实现的,其他类型 office 文件的预览是通过将文件转换为 PDF 或者是 图片的方式来预览的。 + +举个例子。我们上传了一份名为 `武汉市文化市场管理办法.docx` 的 Word 文件并预览的话,`jodconverter-web/src/main/file` 路径下会生成两个相关文件,这两个文件分别对应了我们提到的 PDF 预览 和 图片预览这两种方式。 + +- `武汉市文化市场管理办法.pdf` +- 由 Word 文件所转化得到的一系列图片 + +![](https://img-blog.csdnimg.cn/2020101519433136.png) + +我们以一个名为 `武汉市文化市场管理办法.docx` 的文件来举例说明一下代码中是如何做的。 + +通过分析代码, 我们定位到了 `OfficeFilePreviewImpl` 这个主要负责处理 office 文件预览的类。 + +```java +/** + * 处理office文件 + */ +@Service +public class OfficeFilePreviewImpl implements FilePreview { + +} +``` + +我们来简单分析一下 `OfficeFilePreviewImpl` 类中实现预览的核心方法是 `filePreviewHandle` 。 + +> 说明:这部分代码的逻辑不够清晰,还可以抽方法优化以让人更容易读懂,感兴趣的小伙伴可以自己动手重构一下,然后去给作者提个 PR。 + +```java + @Override + public String filePreviewHandle(String url, Model model, FileAttribute fileAttribute) { + // 1.获取预览类型(image/pdf/html),用户请求中传了officePreviewType参数就取参数的,没传取系统默认(image) + String officePreviewType = model.asMap().get("officePreviewType") == null ? ConfigConstants.getOfficePreviewType() : model.asMap().get("officePreviewType").toString(); + // 2.获取 URL 地址 + String baseUrl = BaseUrlFilter.getBaseUrl();// http://localhost:8012/ + // 3.获取图片相关信息 + String suffix=fileAttribute.getSuffix();//文件后缀如docx + String fileName=fileAttribute.getName();//文件名如:武汉市文化市场管理办法.docx + // 4. 判断是否为 html 格式预览也就是判断文件否为 excel + boolean isHtml = suffix.equalsIgnoreCase("xls") || suffix.equalsIgnoreCase("xlsx"); + // 5. 将文件的后缀名更换为 .pdf 或者 .html(excel文件的情况) + String pdfName = fileName.substring(0, fileName.lastIndexOf(".") + 1) + (isHtml ? "html" : "pdf"); + // 6. 转换后的文件输出的文件夹如 file-online-preview/jodconverter-web/src/main/file/武汉市文化市场管理办法.pdf) + String outFilePath = FILE_DIR + pdfName; + // 7 .判断之前是否已转换过,如果转换过,直接返回,否则执行转换 + // 文件第一次被预览的时候会首先对文件进行缓存处理 + if (!fileUtils.listConvertedFiles().containsKey(pdfName) || !ConfigConstants.isCacheEnabled()) { + String filePath; + // 下载文件 + ReturnResponse response = downloadUtils.downLoad(fileAttribute, null); + if (0 != response.getCode()) { + model.addAttribute("fileType", suffix); + model.addAttribute("msg", response.getMsg()); + return "fileNotSupported"; + } + filePath = response.getContent(); + if (StringUtils.hasText(outFilePath)) { + officeToPdf.openOfficeToPDF(filePath, outFilePath); + if (isHtml) { + // 对转换后的文件进行操作(改变编码方式) + fileUtils.doActionConvertedFile(outFilePath); + } + if (ConfigConstants.isCacheEnabled()) { + // 加入缓存 + fileUtils.addConvertedFile(pdfName, fileUtils.getRelativePath(outFilePath)); + } + } + } + // 8.根据预览类型officePreviewType,选择不同的预览方式 + // 比如,如果预览类型officePreviewType为pdf则进行pdf方式预览 + if (!isHtml && baseUrl != null && (OFFICE_PREVIEW_TYPE_IMAGE.equals(officePreviewType) || OFFICE_PREVIEW_TYPE_ALL_IMAGES.equals(officePreviewType))) { + return getPreviewType(model, fileAttribute, officePreviewType, baseUrl, pdfName, outFilePath, pdfUtils, OFFICE_PREVIEW_TYPE_IMAGE); + } + model.addAttribute("pdfUrl", pdfName); + return isHtml ? "html" : "pdf"; + } + +``` + +项目地址: [https://github.com/kekingcn/kkFileView](https://github.com/kekingcn/kkFileView) 。 + + diff --git "a/docs/projects/\344\270\200\344\270\252\345\237\272\344\272\216SpringBoot\347\232\204\345\234\250\347\272\277\350\200\203\350\257\225\347\263\273\347\273\237.md" "b/docs/projects/\344\270\200\344\270\252\345\237\272\344\272\216SpringBoot\347\232\204\345\234\250\347\272\277\350\200\203\350\257\225\347\263\273\347\273\237.md" new file mode 100644 index 0000000..0c92bf0 --- /dev/null +++ "b/docs/projects/\344\270\200\344\270\252\345\237\272\344\272\216SpringBoot\347\232\204\345\234\250\347\272\277\350\200\203\350\257\225\347\263\273\347\273\237.md" @@ -0,0 +1,174 @@ +[大家好!我是 Guide 哥,Java 后端开发。一个会一点前端,喜欢烹饪的自由少年。](https://www.yuque.com/docs/share/71251673-1fef-416e-93d7-489a25a9eda5?#%20%E3%80%8A%E8%B5%B0%E8%BF%91JavaGuide%E3%80%8B) + +## 前言 + +最近看到了一个考试系统,感觉做的挺不错,并且也比较成熟,所以我就简单玩了一下。另外,考试系统应用场景还挺多的,不论是对于在校大学生还是已经工作的小伙伴,并且,类似的私活也有很多。 + +![在线考试系统后台管理主页](https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/2020-9/FireShot%20Capture%20027%20-%20%E4%B8%BB%E9%A1%B5%20-%20localhost.png) + +下面我就把这个项目分享给小伙伴们,非常值得学习,拿来即用! + +_为了一步一步演示,让小伙伴们都能成功部署/运行项目, Guide 哥自己本地搭建了项目环境,并将项目成功跑了起来。照着我的步骤,新手也能成功把项目跑起来!_ + +_如果你“感动”的话,点个赞/在看,就是对我最大的支持!_ + +另外,以下内容不涉及代码分析,整体代码结构比较清晰,熟悉了基本功能之后会很容易看明白。 + +## 介绍 + +[uexam](https://gitee.com/mindskip/uexam) 是一款前后端分离的在线考试系统。这款在线考试系统,不光支持 web 端,同时还支持微信小程序端。 + +[uexam](https://gitee.com/mindskip/uexam) 界面设计美观,代码整体结构清晰,表设计比较规范。 + +[uexam](https://gitee.com/mindskip/uexam) 后端基于 Spring Boot 2.0+MySQL/PostgreSQL+Redis+MyBatis,前端基于 Vue,采用前端后端分离开发! + +另外,这个项目提供了 MySQL 和 PostgreSQL 两种不同的数据库版本,下面我以 PostgreSQL 数据库版本的来演示(_建议大家使用和体验 PostgreSQL 版本_)。 + +项目地址:[https://gitee.com/SnailClimb/uexam](https://gitee.com/SnailClimb/uexam) 。 + +## 软件架构 + +![软件架构图](https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/2020-9/%E8%BD%AF%E4%BB%B6%E6%9E%B6%E6%9E%84%E5%9B%BE.jpg) + +## 使用效果 + +样式以及操作体验都是非常不错的,这也是我推荐这个项目很重要的一个原因。 + +### 管理端 + +#### 添加学科 + +在创建题目之前,你需要首要创建学科。这里我们创建的学科是编程,年级是三年级。 + +![添加学科](https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/2020-9/%E6%B7%BB%E5%8A%A0%E5%AD%A6%E7%A7%91.jpg) + +#### 添加题目 + +可以看到这里可以添加多种题型: 单选题、多选题、判断题、填空题、简答题。 + +![添加题目](https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/2020-9/%E6%B7%BB%E5%8A%A0%E9%A2%98%E7%9B%AE.jpg) + +我们以单选题为例,添加题目界面如下。 + +![添加题目页面](https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/2020-9/iShot2020-09-03%E4%B8%8B%E5%8D%8805.25.30.jpg) + +添加成功之后,题目列表就会出现我们刚刚添加的题目。 + +![题目创建成功](https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/2020-9/%E9%A2%98%E7%9B%AE%E5%88%9B%E5%BB%BA%E6%88%90%E5%8A%9F.jpg) + +#### 添加试卷 + +有了学科和题目之后才能添加试卷。 + +![添加试卷](https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/2020-9/%E6%B7%BB%E5%8A%A0%E8%AF%95%E5%8D%B7.jpg) + +添加成功之后,试卷列表就会出现我们刚刚添加的试卷。 + +![试卷创建成功](https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/2020-9/%E8%AF%95%E5%8D%B7%E5%88%9B%E5%BB%BA%E6%88%90%E5%8A%9F.jpg) + +#### 添加学生 + +**注意:这里的学生要和我们前面创建的学科对应的年级对应上。** + +![添加学生](https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/2020-9/%E6%B7%BB%E5%8A%A0%E5%AD%A6%E7%94%9F.jpg) + +### 学生端 + +使用我们刚刚创建的学生账号登录,你会发现主页多了一个试卷。这个试卷就是我们刚刚在管理端创建的。 + +![学生端-主页](https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/2020-9/%E5%AD%A6%E7%94%9F%E7%AB%AF-%E4%B8%BB%E9%A1%B5.jpg) + +试卷答题界面如下。 + +![学生端-试卷](https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/2020-9/%E5%AD%A6%E7%94%9F%E7%AB%AF-%E8%AF%95%E5%8D%B7.jpg) + +## 启动 + +### 后端 + +我们这里以 PostgreSQL 数据库版本来演示。 + +#### 安装 PostgreSQL + +**这里我们使用 Docker 下载最近版的 PostgreSQL 镜像 ,默认大家已经安装了 Docker。** + +```bash +$ docker pull postgres +``` + +**查看 PostgreSQL 镜像:** + +```bash +$ docker images |grep postgres +postgres latest 62473370e7ee 2 weeks ago 314MB +``` + +**运行 PostgreSQL:** + +```bash +$ docker run -d -p 5432:5432 --name postgresql -e POSTGRES_PASSWORD=123456 postgres +``` + +#### 安装 Redis + +**这里我们使用 Docker 下载最近版的 Redis 镜像 ,默认大家已经安装了 Docker。** + +```bash +$ docker pull redis +``` + +**查看 Redis 镜像:** + +```bash +$ docker images |grep redis +``` + +**运行 Redis:** + +```bash +$ docker run -itd --name redis-test -p 6379:6379 redis +``` + +#### 创建数据库并执行数据库脚本 + +首先创建一个名字叫做`xzs` 的数据库,然后执行相应的数据库脚本即可(数据库脚本在 `uexam/source/xzs/sql` 目录下。)。 + +#### 配置文件修改 + +使用 IntelliJ IDEA 打开 `uexam/source/xzs` (后台代码),修改 `application-dev.yml` ,将 postgesql/mysql、redis 的服务地址改为自己本地的。 + +#### 启动项目 + +直接运行 `XzsApplication` 即可。 + +![](https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/2020-9/image-20200903180710467.png) + +启动成功后,打开下面的链接即可跳转到对应的端: + +- 学生系统地址:http://localhost:8000/student +- 管理端地址:http://localhost:8000/admin + +**注意:这种方式,前端虽然也启动了,也能访问,不过是内嵌在后端项目中。如果如果我们需要前后端分离的话,需要单独运行前端项目** + +### 前端 + +小程序端的就不演示了,我这里只演示一下 web 端的。 + +web 端代码在 `uexam/source/vue` 下,我们需要首先进入这个目录,然后分别对 `xzs-admin` (管理端) 和 `xzs-student` (学生端)执行下面两个命令。 + +**1.下载相关依赖** + +```bash +$ npm install +``` + +**2.启动项目** + +```bash +$ npm run serve +``` + +启动完成之后,打开下面的链接即可跳转到对应的端: + +- 学生系统地址:http://localhost:8001 +- 管理端地址:http://localhost:8002 \ No newline at end of file diff --git a/docs/spring-bean-validation.md b/docs/spring-bean-validation.md new file mode 100644 index 0000000..5839a28 --- /dev/null +++ b/docs/spring-bean-validation.md @@ -0,0 +1,584 @@ +数据的校验的重要性就不用说了,即使在前端对数据进行校验的情况下,我们还是要对传入后端的数据再进行一遍校验,避免用户绕过浏览器直接通过一些 HTTP 工具直接向后端请求一些违法数据。 + +最普通的做法就像下面这样。我们通过 `if/else` 语句对请求的每一个参数一一校验。 + +```java +@RestController +@RequestMapping("/api/person") +public class PersonController { + + @PostMapping + public ResponseEntity save(@RequestBody PersonRequest personRequest) { + if (personRequest.getClassId() == null + || personRequest.getName() == null + || !Pattern.matches("(^Man$|^Woman$|^UGM$)", personRequest.getSex())) { + + } + return ResponseEntity.ok().body(personRequest); + } +} +``` + +这样的代码,小伙伴们在日常开发中一定不少见,很多开源项目都是这样对请求入参做校验的。 + +但是,不太建议这样来写,这样的代码明显违背了 **单一职责原则**。大量的非业务代码混杂在业务代码中,非常难以维护,还会导致业务层代码冗杂! + +实际上,我们是可以通过一些简单的手段对上面的代码进行改进的!这也是本文主要要介绍的内容! + +废话不多说!下面我会结合自己在项目中的实际使用经验,通过实例程序演示如何在 SpringBoot 程序中优雅地的进行参数验证(普通的 Java 程序同样适用)。 + +不了解的朋友一定要好好看一下,学完马上就可以实践到项目上去。 + +并且,本文示例项目使用的是目前最新的 Spring Boot 版本 2.4.5!(截止到 2021-04-21) + +示例项目源代码地址:[https://github.com/CodingDocs/springboot-guide/tree/master/source-code/bean-validation-demo](https://github.com/CodingDocs/springboot-guide/tree/master/source-code/bean-validation-demo) 。 + +## 添加相关依赖 + +如果开发普通 Java 程序的的话,你需要可能需要像下面这样依赖: + +```xml + + org.hibernate.validator + hibernate-validator + 6.0.9.Final + + + javax.el + javax.el-api + 3.0.0 + + + org.glassfish.web + javax.el + 2.2.6 + +``` + +不过,相信大家都是使用的 Spring Boot 框架来做开发。 + +基于 Spring Boot 的话,就比较简单了,只需要给项目添加上 `spring-boot-starter-web` 依赖就够了,它的子依赖包含了我们所需要的东西。另外,我们的示例项目中还使用到了 Lombok。 + +![](https://img-blog.csdnimg.cn/20210421172058450.png) + +```xml + + + org.springframework.boot + spring-boot-starter-web + + + org.projectlombok + lombok + true + + + junit + junit + 4.13.1 + test + + + org.springframework.boot + spring-boot-starter-test + test + + +``` + +但是!!! Spring Boot 2.3 1 之后,`spring-boot-starter-validation` 已经不包括在了 `spring-boot-starter-web` 中,需要我们手动加上! + +![](https://img-blog.csdnimg.cn/20210421170846695.png) + +```xml + + org.springframework.boot + spring-boot-starter-validation + +``` + +## 验证 Controller 的输入 + +### 验证请求体 + +验证请求体即使验证被 `@RequestBody` 注解标记的方法参数。 + +**`PersonController`** + +我们在需要验证的参数上加上了`@Valid`注解,如果验证失败,它将抛出`MethodArgumentNotValidException`。默认情况下,Spring 会将此异常转换为 HTTP Status 400(错误请求)。 + +```java +@RestController +@RequestMapping("/api/person") +@Validated +public class PersonController { + + @PostMapping + public ResponseEntity save(@RequestBody @Valid PersonRequest personRequest) { + return ResponseEntity.ok().body(personRequest); + } +} +``` + +**`PersonRequest`** + +我们使用校验注解对请求的参数进行校验! + +```java +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class PersonRequest { + + @NotNull(message = "classId 不能为空") + private String classId; + + @Size(max = 33) + @NotNull(message = "name 不能为空") + private String name; + + @Pattern(regexp = "(^Man$|^Woman$|^UGM$)", message = "sex 值不在可选范围") + @NotNull(message = "sex 不能为空") + private String sex; + +} + +``` + +正则表达式说明: + +- `^string` : 匹配以 string 开头的字符串 +- `string$` :匹配以 string 结尾的字符串 +- `^string$` :精确匹配 string 字符串 +- `(^Man$|^Woman$|^UGM$)` : 值只能在 Man,Woman,UGM 这三个值中选择 + +**`GlobalExceptionHandler`** + +自定义异常处理器可以帮助我们捕获异常,并进行一些简单的处理。如果对于下面的处理异常的代码不太理解的话,可以查看这篇文章 [《SpringBoot 处理异常的几种常见姿势》](https://mp.weixin.qq.com/s?__biz=Mzg2OTA0Njk0OA==&mid=2247485568&idx=2&sn=c5ba880fd0c5d82e39531fa42cb036ac&chksm=cea2474bf9d5ce5dcbc6a5f6580198fdce4bc92ef577579183a729cb5d1430e4994720d59b34&token=1924773784&lang=zh_CN#rd)。 + +```java +@ControllerAdvice(assignableTypes = {PersonController.class}) +public class GlobalExceptionHandler { + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity> handleValidationExceptions( + MethodArgumentNotValidException ex) { + Map errors = new HashMap<>(); + ex.getBindingResult().getAllErrors().forEach((error) -> { + String fieldName = ((FieldError) error).getField(); + String errorMessage = error.getDefaultMessage(); + errors.put(fieldName, errorMessage); + }); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errors); + } +} +``` + +**通过测试验证** + +下面我通过 `MockMvc` 模拟请求 `Controller` 的方式来验证是否生效。当然了,你也可以通过 `Postman` 这种工具来验证。 + +```java +@SpringBootTest +@AutoConfigureMockMvc +public class PersonControllerTest { + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + /** + * 验证出现参数不合法的情况抛出异常并且可以正确被捕获 + */ + @Test + public void should_check_person_value() throws Exception { + PersonRequest personRequest = PersonRequest.builder().sex("Man22") + .classId("82938390").build(); + mockMvc.perform(post("/api/personRequest") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(personRequest))) + .andExpect(MockMvcResultMatchers.jsonPath("sex").value("sex 值不在可选范围")) + .andExpect(MockMvcResultMatchers.jsonPath("name").value("name 不能为空")); + } +} +``` + +**使用 `Postman` 验证** + +![](https://img-blog.csdnimg.cn/20210421175345253.png) + +### 验证请求参数 + +验证请求参数(Path Variables 和 Request Parameters)即是验证被 `@PathVariable` 以及 `@RequestParam` 标记的方法参数。 + +**`PersonController`** + +**一定一定不要忘记在类上加上 `Validated` 注解了,这个参数可以告诉 Spring 去校验方法参数。** + +```java +@RestController +@RequestMapping("/api/persons") +@Validated +public class PersonController { + + @GetMapping("/{id}") + public ResponseEntity getPersonByID(@Valid @PathVariable("id") @Max(value = 5, message = "超过 id 的范围了") Integer id) { + return ResponseEntity.ok().body(id); + } + + @PutMapping + public ResponseEntity getPersonByName(@Valid @RequestParam("name") @Size(max = 6, message = "超过 name 的范围了") String name) { + return ResponseEntity.ok().body(name); + } +} +``` + +**`ExceptionHandler`** + +```java + @ExceptionHandler(ConstraintViolationException.class) + ResponseEntity handleConstraintViolationException(ConstraintViolationException e) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage()); + } +``` + +**通过测试验证** + +```java +@Test +public void should_check_path_variable() throws Exception { + mockMvc.perform(get("/api/person/6") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isBadRequest()) + .andExpect(content().string("getPersonByID.id: 超过 id 的范围了")); +} + +@Test +public void should_check_request_param_value2() throws Exception { + mockMvc.perform(put("/api/person") + .param("name", "snailclimbsnailclimb") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isBadRequest()) + .andExpect(content().string("getPersonByName.name: 超过 name 的范围了")); +} +``` + +**使用 `Postman` 验证** + +![](https://img-blog.csdnimg.cn/20210421190508416.png) + +![](https://img-blog.csdnimg.cn/20210421190810975.png) + +## 验证 Service 中的方法 + +我们还可以验证任何 Spring Bean 的输入,而不仅仅是 `Controller` 级别的输入。通过使用`@Validated`和`@Valid`注释的组合即可实现这一需求! + +一般情况下,我们在项目中也更倾向于使用这种方案。 + +**一定一定不要忘记在类上加上 `Validated` 注解了,这个参数可以告诉 Spring 去校验方法参数。** + +```java +@Service +@Validated +public class PersonService { + + public void validatePersonRequest(@Valid PersonRequest personRequest) { + // do something + } + +} +``` + +**通过测试验证:** + +```java +@RunWith(SpringRunner.class) +@SpringBootTest +public class PersonServiceTest { + @Autowired + private PersonService service; + + @Test + public void should_throw_exception_when_person_request_is_not_valid() { + try { + PersonRequest personRequest = PersonRequest.builder().sex("Man22") + .classId("82938390").build(); + service.validatePersonRequest(personRequest); + } catch (ConstraintViolationException e) { + // 输出异常信息 + e.getConstraintViolations().forEach(constraintViolation -> System.out.println(constraintViolation.getMessage())); + } + } +} +``` + +输出结果如下: + +``` +name 不能为空 +sex 值不在可选范围 +``` + +## Validator 编程方式手动进行参数验证 + +某些场景下可能会需要我们手动校验并获得校验结果。 + +我们通过 `Validator` 工厂类获得的 `Validator` 示例。另外,如果是在 Spring Bean 中的话,还可以通过 `@Autowired` 直接注入的方式。 + +```java +@Autowired +Validator validate +``` + +具体使用情况如下: + +```java +/** + * 手动校验对象 + */ +@Test +public void check_person_manually() { + ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); + Validator validator = factory.getValidator(); + PersonRequest personRequest = PersonRequest.builder().sex("Man22") + .classId("82938390").build(); + Set> violations = validator.validate(personRequest); + violations.forEach(constraintViolation -> System.out.println(constraintViolation.getMessage())); +} +``` + +输出结果如下: + +``` +sex 值不在可选范围 +name 不能为空 +``` + +## 自定义 Validator(实用) + +如果自带的校验注解无法满足你的需求的话,你还可以自定义实现注解。 + +### 案例一:校验特定字段的值是否在可选范围 + +比如我们现在多了这样一个需求:`PersonRequest` 类多了一个 `Region` 字段,`Region` 字段只能是`China`、`China-Taiwan`、`China-HongKong`这三个中的一个。 + +**第一步,你需要创建一个注解 `Region`。** + +```java +@Target({FIELD}) +@Retention(RUNTIME) +@Constraint(validatedBy = RegionValidator.class) +@Documented +public @interface Region { + + String message() default "Region 值不在可选范围内"; + + Class[] groups() default {}; + + Class[] payload() default {}; +} +``` + +**第二步,你需要实现 `ConstraintValidator`接口,并重写`isValid` 方法。** + +```java +public class RegionValidator implements ConstraintValidator { + + @Override + public boolean isValid(String value, ConstraintValidatorContext context) { + HashSet regions = new HashSet<>(); + regions.add("China"); + regions.add("China-Taiwan"); + regions.add("China-HongKong"); + return regions.contains(value); + } +} + +``` + +现在你就可以使用这个注解: + +```java +@Region +private String region; +``` + +**通过测试验证** + +```java +PersonRequest personRequest = PersonRequest.builder() + .region("Shanghai").build(); +mockMvc.perform(post("/api/person") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(personRequest))) + .andExpect(MockMvcResultMatchers.jsonPath("region").value("Region 值不在可选范围内")); +``` + +**使用 `Postman` 验证** + +![](https://img-blog.csdnimg.cn/20210421203330978.png) + +### 案例二:校验电话号码 + +校验我们的电话号码是否合法,这个可以通过正则表达式来做,相关的正则表达式都可以在网上搜到,你甚至可以搜索到针对特定运营商电话号码段的正则表达式。 + +`PhoneNumber.java` + +```java +@Documented +@Constraint(validatedBy = PhoneNumberValidator.class) +@Target({FIELD, PARAMETER}) +@Retention(RUNTIME) +public @interface PhoneNumber { + String message() default "Invalid phone number"; + Class[] groups() default {}; + Class[] payload() default {}; +} +``` + +`PhoneNumberValidator.java` + +```java +public class PhoneNumberValidator implements ConstraintValidator { + + @Override + public boolean isValid(String phoneField, ConstraintValidatorContext context) { + if (phoneField == null) { + // can be null + return true; + } + // 大陆手机号码11位数,匹配格式:前三位固定格式+后8位任意数 + // ^ 匹配输入字符串开始的位置 + // \d 匹配一个或多个数字,其中 \ 要转义,所以是 \\d + // $ 匹配输入字符串结尾的位置 + String regExp = "^[1]((3[0-9])|(4[5-9])|(5[0-3,5-9])|([6][5,6])|(7[0-9])|(8[0-9])|(9[1,8,9]))\\d{8}$"; + return phoneField.matches(regExp); + } +} + +``` + +搞定,我们现在就可以使用这个注解了。 + +```java +@PhoneNumber(message = "phoneNumber 格式不正确") +@NotNull(message = "phoneNumber 不能为空") +private String phoneNumber; +``` + +**通过测试验证** + +```java +PersonRequest personRequest = PersonRequest.builder() + .phoneNumber("1816313815").build(); +mockMvc.perform(post("/api/person") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(personRequest))) + .andExpect(MockMvcResultMatchers.jsonPath("phoneNumber").value("phoneNumber 格式不正确")); +``` + +![](https://img-blog.csdnimg.cn/20210421204116640.png) + +## 使用验证组 + +验证组我们基本是不会用到的,也不太建议在项目中使用,理解起来比较麻烦,写起来也比较麻烦。简单了解即可! + +当我们对对象操作的不同方法有不同的验证规则的时候才会用到验证组。 + +我写一个简单的例子,你们就能看明白了! + +**1.先创建两个接口,代表不同的验证组** + +```java +public interface AddPersonGroup { +} +public interface DeletePersonGroup { +} +``` + +**2.使用验证组** + +```java +@Data +public class Person { + // 当验证组为 DeletePersonGroup 的时候 group 字段不能为空 + @NotNull(groups = DeletePersonGroup.class) + // 当验证组为 AddPersonGroup 的时候 group 字段需要为空 + @Null(groups = AddPersonGroup.class) + private String group; +} + +@Service +@Validated +public class PersonService { + + @Validated(AddPersonGroup.class) + public void validatePersonGroupForAdd(@Valid Person person) { + // do something + } + + @Validated(DeletePersonGroup.class) + public void validatePersonGroupForDelete(@Valid Person person) { + // do something + } + +} +``` + +通过测试验证: + +```java + @Test(expected = ConstraintViolationException.class) + public void should_check_person_with_groups() { + Person person = new Person(); + person.setGroup("group1"); + service.validatePersonGroupForAdd(person); + } + + @Test(expected = ConstraintViolationException.class) + public void should_check_person_with_groups2() { + Person person = new Person(); + service.validatePersonGroupForDelete(person); + } +``` + +验证组使用下来的体验就是有点反模式的感觉,让代码的可维护性变差了!尽量不要使用! + +## 常用校验注解总结 + +`JSR303` 定义了 `Bean Validation`(校验)的标准 `validation-api`,并没有提供实现。`Hibernate Validation`是对这个规范/规范的实现 `hibernate-validator`,并且增加了 `@Email`、`@Length`、`@Range` 等注解。`Spring Validation` 底层依赖的就是`Hibernate Validation`。 + +**JSR 提供的校验注解**: + +- `@Null` 被注释的元素必须为 null +- `@NotNull` 被注释的元素必须不为 null +- `@AssertTrue` 被注释的元素必须为 true +- `@AssertFalse` 被注释的元素必须为 false +- `@Min(value)` 被注释的元素必须是一个数字,其值必须大于等于指定的最小值 +- `@Max(value)` 被注释的元素必须是一个数字,其值必须小于等于指定的最大值 +- `@DecimalMin(value)` 被注释的元素必须是一个数字,其值必须大于等于指定的最小值 +- `@DecimalMax(value)` 被注释的元素必须是一个数字,其值必须小于等于指定的最大值 +- `@Size(max=, min=)` 被注释的元素的大小必须在指定的范围内 +- `@Digits (integer, fraction)` 被注释的元素必须是一个数字,其值必须在可接受的范围内 +- `@Past` 被注释的元素必须是一个过去的日期 +- `@Future` 被注释的元素必须是一个将来的日期 +- `@Pattern(regex=,flag=)` 被注释的元素必须符合指定的正则表达式 + +**Hibernate Validator 提供的校验注解**: + +- `@NotBlank(message =)` 验证字符串非 null,且长度必须大于 0 +- `@Email` 被注释的元素必须是电子邮箱地址 +- `@Length(min=,max=)` 被注释的字符串的大小必须在指定的范围内 +- `@NotEmpty` 被注释的字符串的必须非空 +- `@Range(min=,max=,message=)` 被注释的元素必须在合适的范围内 + +## 拓展 + +经常有小伙伴问到:“`@NotNull` 和 `@Column(nullable = false)` 两者有什么区别?” + +我这里简单回答一下: + +- `@NotNull`是 JSR 303 Bean 验证批注,它与数据库约束本身无关。 +- `@Column(nullable = false)` : 是 JPA 声明列为非空的方法。 + +总结来说就是即前者用于验证,而后者则用于指示数据库创建表的时候对表的约束。 diff --git a/docs/start/springboot-hello-world.md b/docs/start/springboot-hello-world.md index 78ae5cb..9d6d49a 100644 --- a/docs/start/springboot-hello-world.md +++ b/docs/start/springboot-hello-world.md @@ -1,22 +1,26 @@ -### 新建 Spring Boot 项目常用的两种方式 +示例项目源代码地址:[https://github.com/CodingDocs/springboot-guide/tree/master/source-code/hello-world](https://github.com/CodingDocs/springboot-guide/tree/master/source-code/hello-world) 。 -你可以通过 https://start.spring.io/ 这个网站来生成一个 Spring Boot 的项目。 +## 新建 Spring Boot 项目 -![start.spring.io](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-7/spring.start.io.png) +**1. 你可以通过 [https://start.spring.io/](https://start.spring.io/) 这个网站来生成一个 Spring Boot 的项目。** + +![start.spring.io](https://img-blog.csdnimg.cn/img_convert/69f88b648b5f94fe8fa509fc4d987057.png) 注意勾选上 Spring Web 这个模块,这是我们所必需的一个依赖。当所有选项都勾选完毕之后,点击下方的按钮 Generate 下载这个 Spring Boot 的项目。下载完成并解压之后,我们直接使用 IDEA 打开即可。 -当然你也可以直接通过 IDEA 来生成一个 Spring Boot 的项目,具体方法和上面类似:`File->New->Project->Spring Initializr`。 +另外,阿里也有一个类似的网站 [https://start.aliyun.com/bootstrap.html](https://start.aliyun.com/bootstrap.html) ,功能甚至还要更强大点,支持生成特定应用架构的项目模板! -### Spring Boot 项目结构分析 +![](https://img-blog.csdnimg.cn/20210421220259726.png) -成功打开项目之后,项目长下面这个样子: +**2.你也可以直接通过 IDEA 来生成一个 Spring Boot 的项目,具体方法和上面类似:`File->New->Project->Spring Initializr`。** - +## Spring Boot 项目结构分析 +成功打开项目之后,项目长下面这个样子: +![](https://img-blog.csdnimg.cn/img_convert/1f1a3ee40347e941891988cbb72ceee1.png#pic_center) -以 Application为后缀名的 Java 类一般就是 Spring Boot 的启动类,比如本项目的启动项目就是`HelloWorldApplication` 。我们直接像运行普通 Java 程序一样运行它,由于 Spring Boot 本身就嵌入servlet容器的缘故,我们的 web 项目就运行成功了, 非常方便。 +以 Application 为后缀名的 Java 类一般就是 Spring Boot 的启动类,比如本项目的启动项目就是`HelloWorldApplication` 。我们直接像运行普通 Java 程序一样运行它,由于 Spring Boot 本身就嵌入 servlet 容器的缘故,我们的 web 项目就运行成功了, 非常方便。 需要注意的一点是 **Spring Boot 的启动类是需要最外层的,不然可能导致一些类无法被正确扫描到,导致一些奇怪的问题。** 一般情况下 Spring Boot 项目结构类似下面这样 @@ -35,19 +39,19 @@ com | +- controller | +- CustomerController.java - | - | +- config + | + +- config | +- swagerConfig.java | ``` -1. ` Application.java`是项目的启动类 -2. domain目录主要用于实体(Entity)与数据访问层(Repository) +1. `Application.java`是项目的启动类 +2. domain 目录主要用于实体(Entity)与数据访问层(Repository) 3. service 层主要是业务类代码 4. controller 负责页面访问控制 5. config 目录主要放一些配置类 -### @SpringBootApplication 注解分析 +## @SpringBootApplication 注解分析 `HelloWorldApplication` @@ -91,21 +95,21 @@ public @interface SpringBootConfiguration { } ``` -可以看出大概可以把 `@SpringBootApplication `看作是 `@Configuration`、`@EnableAutoConfiguration`、`@ComponentScan ` 注解的集合。根据 SpringBoot官网,这三个注解的作用分别是: +可以看出大概可以把 `@SpringBootApplication`看作是 `@Configuration`、`@EnableAutoConfiguration`、`@ComponentScan` 注解的集合。根据 SpringBoot 官网,这三个注解的作用分别是: - `@EnableAutoConfiguration`:启用 SpringBoot 的自动配置机制 -- `@ComponentScan`: 扫描被`@Component` (`@Service`,`@Controller`)注解的bean,注解默认会扫描该类所在的包下所有的类。 -- `@Configuration`:允许在上下文中注册额外的bean或导入其他配置类。 +- `@ComponentScan`: 扫描被`@Component` (`@Service`,`@Controller`)注解的 bean,注解默认会扫描该类所在的包下所有的类。 +- `@Configuration`:允许在上下文中注册额外的 bean 或导入其他配置类。 -所以说 `@SpringBootApplication `就是几个重要的注解的组合,为什么要有它?当然是为了省事,避免了我们每次开发 Spring Boot 项目都要写一些必备的注解。这一点在我们平时开发中也经常用到,比如我们通常会提一个测试基类,这个基类包含了我们写测试所需要的一些基本的注解和一些依赖。 +所以说 `@SpringBootApplication`就是几个重要的注解的组合,为什么要有它?当然是为了省事,避免了我们每次开发 Spring Boot 项目都要写一些必备的注解。这一点在我们平时开发中也经常用到,比如我们通常会提一个测试基类,这个基类包含了我们写测试所需要的一些基本的注解和一些依赖。 -### 新建一个 Controller +## 新建一个 Controller 上面说了这么多,我们现在正式开始写 Spring Boot 版的 “Hello World” 吧。 -新建一个 controller 文件夹,并在这个文件夹下新建一个名字叫做 `HelloWorldController` 的类。 +新建一个 `controller` 文件夹,并在这个文件夹下新建一个名字叫做 `HelloWorldController` 的类。 -`@RestController`是Spring 4 之后新加的注解,如果在Spring4之前开发 RESTful Web服务的话,你需要使用`@Controller` 并结合`@ResponseBody`注解,也就是说`@Controller` +`@ResponseBody`= `@RestController`。对于这两个注解,我在基础篇单独抽了一篇文章来介绍。 +`@RestController`是 Spring 4 之后新加的注解,如果在 Spring4 之前开发 RESTful Web 服务的话,你需要使用`@Controller` 并结合`@ResponseBody`注解,也就是说`@Controller` +`@ResponseBody`= `@RestController`。对于这两个注解,我在基础篇单独抽了一篇文章来介绍。 `com.example.helloworld.controller` @@ -134,9 +138,9 @@ public class HelloWorldController { server.port=8333 ``` -### 大功告成,运行项目 +## 大功告成,运行项目 -运行 `HelloWorldApplication` ,运行成功控制台会打印出一些消息,不要忽略这些消息,它里面会有一些比较有用的信息。 +运行 `HelloWorldApplication` ,运行成功控制台会打印出一些消息,不要忽略这些消息,它里面会有一些比较有用的信息。 ``` 2019-10-03 09:24:47.757 INFO 26326 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8333 (http) with context path '' @@ -146,14 +150,6 @@ server.port=8333 浏览器 http://localhost:8333/test/hello 如果你可以在页面正确得到 "Hello World" 的话,说明你已经成功完成了这部分内容。 -### 总结 - -通过本文我们学到了如何新建 Spring Boot 项目、SpringBoot 项目常见的项目结构分析、`@SpringBootApplication` 注解分析,最后实现了 Spring Boot 版的 "Hello World"。 - -代码地址: https://github.com/Snailclimb/springboot-guide/tree/master/source-code/start/hello-world(建议自己手敲一遍!!!) - -### 代办 - -- [ ] Spring Boot 启动流程分析 +## 总结 - \ No newline at end of file +通过本文我们学到了如何新建 Spring Boot 项目、SpringBoot 项目常见的项目结构分析、`@SpringBootApplication` 注解分析,最后实现了 Spring Boot 版的 "Hello World"。 \ No newline at end of file diff --git a/docs/start/springboot-introduction.md b/docs/start/springboot-introduction.md index 8b1e792..a6c73f6 100644 --- a/docs/start/springboot-introduction.md +++ b/docs/start/springboot-introduction.md @@ -1,43 +1,69 @@ -# 一 SpringBoot介绍 +## 1.SpringBoot 介绍 -## 1.1 先从Spring谈起 -我们知道Spring是重量级企业开发框架 **Enterprise JavaBean(EJB)** 的替代品,Spring为企业级Java开发提供了一种相对简单的方法,通过 **依赖注入** 和 **面向切面编程** ,用简单的 **Java对象(Plain Old Java Object,POJO)** 实现了EJB的功能 +### 1.1 先从 Spring 谈起 -**虽然Spring的组件代码是轻量级的,但它的配置却是重量级的(需要大量XML配置)** 。Spring 2.5引入了基于注解的组件扫描,这消除了大量针对应用程序自身组件的显式XML配置。Spring 3.0引入了基于Java的配置,这是一种类型安全的可重构配置方式,可以代替XML。 +Spring 是重量级企业开发框架 **Enterprise JavaBean(EJB)** 的替代品,Spring 为企业级 Java 开发提供了一种相对简单的方法,通过 **依赖注入** 和 **面向切面编程** ,用简单的 **Java 对象(Plain Old Java Object,POJO)** 实现了 EJB 的功能 -尽管如此,我们依旧没能逃脱配置的魔爪。开启某些Spring特性时,比如事务管理和Spring MVC,还是需要用XML或Java进行显式配置。启用第三方库时也需要显式配置,比如基于Thymeleaf的Web视图。配置Servlet和过滤器(比如Spring的DispatcherServlet)同样需要在web.xml或Servlet初始化代码里进行显式配置。组件扫描减少了配置量,Java配置让它看上去简洁不少,但Spring还是需要不少配置。 +**虽然 Spring 的组件代码是轻量级的,但它的配置却是重量级的(需要大量 XML 配置)** 。 -光配置这些XML文件都够我们头疼的了,占用了我们大部分时间和精力。除此之外,相关库的依赖非常让人头疼,不同库之间的版本冲突也非常常见。 +为此,Spring 2.5 引入了基于注解的组件扫描,这消除了大量针对应用程序自身组件的显式 XML 配置。Spring 3.0 引入了基于 Java 的配置,这是一种类型安全的可重构配置方式,可以代替 XML。 -**不过,好消息是:Spring Boot让这一切成为了过去。** +尽管如此,我们依旧没能逃脱配置的魔爪。开启某些 Spring 特性时,比如事务管理和 Spring MVC,还是需要用 XML 或 Java 进行显式配置。启用第三方库时也需要显式配置,比如基于 Thymeleaf 的 Web 视图。配置 Servlet 和过滤器(比如 Spring 的`DispatcherServlet`)同样需要在 web.xml 或 Servlet 初始化代码里进行显式配置。组件扫描减少了配置量,Java 配置让它看上去简洁不少,但 Spring 还是需要不少配置。 -## 1.2 再来谈谈 Spring Boot +光配置这些 XML 文件都够我们头疼的了,占用了我们大部分时间和精力。除此之外,相关库的依赖非常让人头疼,不同库之间的版本冲突也非常常见。 +**不过,好消息是:Spring Boot 让这一切成为了过去。** + +### 1.2 再来谈谈 Spring Boot **最好直白的介绍莫过于官方的介绍:** -> Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run”...Most Spring Boot applications need very little Spring configuration.(Spring Boot可以轻松创建独立的生产级基于Spring的应用程序,只要通过 “just run”(可能是run ‘Application’或java -jar 或 tomcat 或 maven插件run 或 shell脚本)便可以运行项目。大部分Spring Boot项目只需要少量的配置即可) +> Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run”...Most Spring Boot applications need very little Spring configuration.(Spring Boot 可以轻松创建独立的生产级基于 Spring 的应用程序,只要通过 “just run”(可能是 run ‘Application’或 java -jar 或 tomcat 或 maven 插件 run 或 shell 脚本)便可以运行项目。大部分 Spring Boot 项目只需要少量的配置即可) -**简而言之,从本质上来说,Spring Boot就是Spring,它做了那些没有它你自己也会去做的Spring Bean配置。** +**简而言之,从本质上来说,Spring Boot 就是 Spring,它做了那些没有它你自己也会去做的 Spring Bean 配置。** -### 1.2.1 为什么需要 Spring Boot? +#### 1.2.1 为什么需要 Spring Boot? -Spring Framework旨在简化J2EE企业应用程序开发。Spring Boot Framework旨在简化Spring开发。 +Spring Framework 旨在简化 J2EE 企业应用程序开发。Spring Boot Framework 旨在简化 Spring 开发。 ![why-we-need-springboot](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-7/why-we-need-springboot.png) -### 1.2.2 Spring Boot的主要优点 +#### 1.2.2 Spring Boot 的主要优点 1. 开发基于 Spring 的应用程序很容易。 2. Spring Boot 项目所需的开发或工程时间明显减少,通常会提高整体生产力。 -3. Spring Boot不需要编写大量样板代码、XML配置和注释。 -4. Spring引导应用程序可以很容易地与Spring生态系统集成,如Spring JDBC、Spring ORM、Spring Data、Spring Security等。 -5. Spring Boot遵循“固执己见的默认配置”,以减少开发工作(默认配置可以修改)。 -6. Spring Boot 应用程序提供嵌入式HTTP服务器,如Tomcat和Jetty,可以轻松地开发和测试web应用程序。(这点很赞!普通运行Java程序的方式就能运行基于Spring Boot web 项目,省事很多) -7. Spring Boot提供命令行接口(CLI)工具,用于开发和测试Spring Boot应用程序,如Java或Groovy。 -8. Spring Boot提供了多种插件,可以使用内置工具(如Maven和Gradle)开发和测试Spring Boot应用程序。 +3. Spring Boot 不需要编写大量样板代码、XML 配置和注释。 +4. Spring 引导应用程序可以很容易地与 Spring 生态系统集成,如 Spring JDBC、Spring ORM、Spring Data、Spring Security 等。 +5. Spring Boot 遵循“固执己见的默认配置”,以减少开发工作(默认配置可以修改)。 +6. Spring Boot 应用程序提供嵌入式 HTTP 服务器,如 Tomcat 和 Jetty,可以轻松地开发和测试 web 应用程序。(这点很赞!普通运行 Java 程序的方式就能运行基于 Spring Boot web 项目,省事很多) +7. Spring Boot 提供命令行接口(CLI)工具,用于开发和测试 Spring Boot 应用程序,如 Java 或 Groovy。 +8. Spring Boot 提供了多种插件,可以使用内置工具(如 Maven 和 Gradle)开发和测试 Spring Boot 应用程序。 + +## 2.SpringBoot 开发环境要求 + +### 2.1 构建工具 + +构建工具(本项目涉及的代码大部分会采用 Maven 作为包管理工具): + +| **Build Tool** | **Version** | +| -------------- | ----------- | +| Maven | 3.3+ | +| Gradle | 4.4+ | + +### 2.2 开发工具推荐 + +推荐使用 IDEA 进行开发。最好的 Java 后台开发编辑器,没有之一! +### 2.3 Web 服务器 +Spring Boot 支持以下嵌入式 servlet 容器: +| **Name** | **Servlet Version** | +| ------------ | ------------------- | +| Tomcat 9.0 | 4.0 | +| Jetty 9.4 | 3.1 | +| Undertow 2.0 | 4.0 | +您还可以将 Spring 引导应用程序部署到任何 Servlet 3.1+兼容的 Web 容器中。 +这就是你为什么可以通过直接像运行 普通 Java 项目一样运行 SpringBoot 项目。这样的确省事了很多,方便了我们进行开发,降低了学习难度。 \ No newline at end of file diff --git a/docs/start/springboot-system-requirements.md b/docs/start/springboot-system-requirements.md deleted file mode 100644 index df55803..0000000 --- a/docs/start/springboot-system-requirements.md +++ /dev/null @@ -1,30 +0,0 @@ -### JDK - -截止到目前Spring Boot 的最新版本:2.1.8.RELEASE 要求 JDK 版本在 1.8 以上,所以确保你的电脑已经正确下载安装配置了 JDK(推荐 JDK 1.8 版本)。 - -### 构建工具 - -构建工具(本项目涉及的代码大部分会采用 Maven 作为包管理工具): - -| **Build Tool** | **Version** | -| -------------- | ----------- | -| Maven | 3.3+ | -| Gradle | 4.4+ | - -### 开发工具推荐 - -推荐使用 IDEA 进行开发。最好的 Java 后台开发编辑器,没有之一! - -### Web 服务器 - -Spring Boot支持以下嵌入式servlet容器: - -| **Name** | **Servlet Version** | -| ------------ | ------------------- | -| Tomcat 9.0 | 4.0 | -| Jetty 9.4 | 3.1 | -| Undertow 2.0 | 4.0 | - -您还可以将Spring引导应用程序部署到任何Servlet 3.1+兼容的 Web 容器中。 - -这就是你为什么可以通过直接像运行 普通 Java 项目一样运行 SpringBoot 项目。这样的确省事了很多,方便了我们进行开发,降低了学习难度。 \ No newline at end of file diff --git a/source-code/advanced/bean-validation-demo/pom.xml b/source-code/advanced/bean-validation-demo/pom.xml index d5779cb..c5a9e2f 100644 --- a/source-code/advanced/bean-validation-demo/pom.xml +++ b/source-code/advanced/bean-validation-demo/pom.xml @@ -5,7 +5,7 @@ org.springframework.boot spring-boot-starter-parent - 2.1.8.RELEASE + 2.4.5 com.example @@ -19,22 +19,25 @@ - org.springframework.boot spring-boot-starter-web org.springframework.boot - spring-boot-devtools - runtime - true + spring-boot-starter-validation org.projectlombok lombok true + + junit + junit + 4.13.1 + test + org.springframework.boot spring-boot-starter-test diff --git a/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/.DS_Store b/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/.DS_Store deleted file mode 100644 index feb1863..0000000 Binary files a/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/.DS_Store and /dev/null differ diff --git a/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/controller/PersonController.java b/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/controller/PersonController.java index 1b22d08..c0482b5 100644 --- a/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/controller/PersonController.java +++ b/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/controller/PersonController.java @@ -1,12 +1,9 @@ package com.example.beanvalidationdemo.controller; -import com.example.beanvalidationdemo.entity.Person; +import com.example.beanvalidationdemo.entity.PersonRequest; import org.springframework.http.ResponseEntity; -import org.springframework.validation.BindingResult; -import org.springframework.validation.Errors; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.Mapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; @@ -20,21 +17,21 @@ import javax.validation.constraints.Size; @RestController -@RequestMapping("/api") +@RequestMapping("/api/persons") @Validated public class PersonController { - @PostMapping("/person") - public ResponseEntity getPerson(@RequestBody @Valid Person person) { - return ResponseEntity.ok().body(person); + @PostMapping + public ResponseEntity save(@RequestBody @Valid PersonRequest personRequest) { + return ResponseEntity.ok().body(personRequest); } - @GetMapping("/person/{id}") + @GetMapping("/{id}") public ResponseEntity getPersonByID(@Valid @PathVariable("id") @Max(value = 5, message = "超过 id 的范围了") Integer id) { return ResponseEntity.ok().body(id); } - @PutMapping("/person") + @PutMapping public ResponseEntity getPersonByName(@Valid @RequestParam("name") @Size(max = 6, message = "超过 name 的范围了") String name) { return ResponseEntity.ok().body(name); } diff --git a/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/entity/Person.java b/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/entity/Person.java index d095320..80bb5e8 100644 --- a/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/entity/Person.java +++ b/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/entity/Person.java @@ -1,48 +1,18 @@ package com.example.beanvalidationdemo.entity; -import com.example.beanvalidationdemo.constants.Constants; import com.example.beanvalidationdemo.service.AddPersonGroup; import com.example.beanvalidationdemo.service.DeletePersonGroup; -import com.example.beanvalidationdemo.validation.PhoneNumber; -import com.example.beanvalidationdemo.validation.Region; -import lombok.AllArgsConstructor; import lombok.Data; -import lombok.NoArgsConstructor; -import javax.validation.constraints.Email; import javax.validation.constraints.NotNull; import javax.validation.constraints.Null; -import javax.validation.constraints.Pattern; -import javax.validation.constraints.Size; @Data -@AllArgsConstructor -@NoArgsConstructor public class Person { - @NotNull(message = "classId 不能为空") - private String classId; - - @Size(max = 33) - @NotNull(message = "name 不能为空") - private String name; - - @Pattern(regexp = Constants.sexs, message = "sex 值不在可选范围") - @NotNull(message = "sex 不能为空") - private String sex; - - @Email(message = "email 格式不正确") - @NotNull(message = "email 不能为空") - private String email; - - @PhoneNumber(message = "phoneNumber 格式不正确") - @NotNull(message = "phoneNumber 不能为空") - private String phoneNumber; - - @Region - private String region; - + // 当验证组为 DeletePersonGroup 的时候 group 字段不能为空 @NotNull(groups = DeletePersonGroup.class) + // 当验证组为 AddPersonGroup 的时候 group 字段需要为空 @Null(groups = AddPersonGroup.class) private String group; } diff --git a/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/entity/PersonRequest.java b/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/entity/PersonRequest.java new file mode 100644 index 0000000..9b2c789 --- /dev/null +++ b/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/entity/PersonRequest.java @@ -0,0 +1,44 @@ +package com.example.beanvalidationdemo.entity; + +import com.example.beanvalidationdemo.validation.PhoneNumber; +import com.example.beanvalidationdemo.validation.Region; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; +import javax.validation.constraints.Size; + +/** + * 微信搜 JavaGuide 回复"面试突击"即可免费领取个人原创的 Java 面试手册 + * + * @author Guide哥 + * @date 2021/04/21 20:48 + **/ +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class PersonRequest { + + @NotNull(message = "classId 不能为空") + private String classId; + + @Size(max = 33) + @NotNull(message = "name 不能为空") + private String name; + + @Pattern(regexp = "(^Man$|^Woman$|^UGM$)", message = "sex 值不在可选范围") + @NotNull(message = "sex 不能为空") + private String sex; + + @Region + private String region; + + @PhoneNumber(message = "phoneNumber 格式不正确") + @NotNull(message = "phoneNumber 不能为空") + private String phoneNumber; + +} diff --git a/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/service/PersonService.java b/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/service/PersonService.java index 99856bf..08e8e14 100644 --- a/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/service/PersonService.java +++ b/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/service/PersonService.java @@ -1,6 +1,7 @@ package com.example.beanvalidationdemo.service; import com.example.beanvalidationdemo.entity.Person; +import com.example.beanvalidationdemo.entity.PersonRequest; import org.springframework.stereotype.Service; import org.springframework.validation.annotation.Validated; @@ -10,7 +11,7 @@ @Validated public class PersonService { - public void validatePerson(@Valid Person person) { + public void validatePersonRequest(@Valid PersonRequest personRequest) { // do something } diff --git a/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/PhoneNumber.java b/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/PhoneNumber.java index 8226e99..afd5373 100644 --- a/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/PhoneNumber.java +++ b/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/PhoneNumber.java @@ -15,6 +15,8 @@ @Retention(RUNTIME) public @interface PhoneNumber { String message() default "Invalid phone number"; + Class[] groups() default {}; + Class[] payload() default {}; } diff --git a/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/PhoneNumberValidator.java b/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/PhoneNumberValidator.java index 4fc63c9..85acdcd 100644 --- a/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/PhoneNumberValidator.java +++ b/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/PhoneNumberValidator.java @@ -3,7 +3,7 @@ import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; -public class PhoneNumberValidator implements ConstraintValidator { +public class PhoneNumberValidator implements ConstraintValidator { @Override public boolean isValid(String phoneField, ConstraintValidatorContext context) { @@ -11,6 +11,11 @@ public boolean isValid(String phoneField, ConstraintValidatorContext context) { // can be null return true; } - return phoneField.matches("^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\\d{8}$") && phoneField.length() > 8 && phoneField.length() < 14; + // 大陆手机号码11位数,匹配格式:前三位固定格式+后8位任意数 + // ^ 匹配输入字符串开始的位置 + // \d 匹配一个或多个数字,其中 \ 要转义,所以是 \\d + // $ 匹配输入字符串结尾的位置 + String regExp = "^[1]((3[0-9])|(4[5-9])|(5[0-3,5-9])|([6][5,6])|(7[0-9])|(8[0-9])|(9[1,8,9]))\\d{8}$"; + return phoneField.matches(regExp); } } diff --git a/source-code/advanced/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/HelloWorldControllerTest.java b/source-code/advanced/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/HelloWorldControllerTest.java deleted file mode 100644 index ea998ca..0000000 --- a/source-code/advanced/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/HelloWorldControllerTest.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.example.beanvalidationdemo; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; - -/** - * 验证基本的项目基本环境是否有问题 - */ -@RunWith(SpringRunner.class) -@SpringBootTest -@AutoConfigureMockMvc -public class HelloWorldControllerTest { - @Autowired - private MockMvc mockMvc; - - @Test - public void should_get_hello() throws Exception { - mockMvc.perform(get("/api/hello")).andExpect(content().string("Hello")); - } -} diff --git a/source-code/advanced/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/PersonControllerTest.java b/source-code/advanced/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/PersonControllerTest.java index 0ff4eb4..f020f05 100644 --- a/source-code/advanced/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/PersonControllerTest.java +++ b/source-code/advanced/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/PersonControllerTest.java @@ -1,15 +1,13 @@ package com.example.beanvalidationdemo; -import com.example.beanvalidationdemo.entity.Person; +import com.example.beanvalidationdemo.entity.PersonRequest; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; @@ -25,7 +23,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -@RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class PersonControllerTest { @@ -35,85 +32,52 @@ public class PersonControllerTest { @Autowired private ObjectMapper objectMapper; - @Test - public void should_get_person() throws Exception { - Person person = new Person(); - person.setName("SnailClimb"); - person.setSex("Man"); - person.setClassId("82938390"); - person.setEmail("Snailclimb@qq.com"); - person.setRegion("China"); - person.setPhoneNumber("13615833391"); - - - mockMvc.perform(post("/api/person") - .contentType(MediaType.APPLICATION_JSON_UTF8) - .content(objectMapper.writeValueAsString(person))) - .andExpect(MockMvcResultMatchers.jsonPath("name").value("SnailClimb")) - .andExpect(MockMvcResultMatchers.jsonPath("classId").value("82938390")) - .andExpect(MockMvcResultMatchers.jsonPath("sex").value("Man")) - .andExpect(MockMvcResultMatchers.jsonPath("email").value("Snailclimb@qq.com")); - ; - } + /** + * 验证出现参数不合法的情况抛出异常并且可以正确被捕获 + */ @Test public void should_check_person_value() throws Exception { - Person person = new Person(); - person.setSex("Man22"); - person.setClassId("82938390"); - person.setEmail("SnailClimb"); - person.setRegion("BeiGuo"); - person.setPhoneNumber("1361583339"); - + PersonRequest personRequest = PersonRequest.builder().sex("Man22") + .classId("82938390") + .region("Shanghai") + .phoneNumber("1816313815").build(); mockMvc.perform(post("/api/person") - .contentType(MediaType.APPLICATION_JSON_UTF8) - .content(objectMapper.writeValueAsString(person))) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(personRequest))) .andExpect(MockMvcResultMatchers.jsonPath("sex").value("sex 值不在可选范围")) .andExpect(MockMvcResultMatchers.jsonPath("name").value("name 不能为空")) - .andExpect(MockMvcResultMatchers.jsonPath("email").value("email 格式不正确")) .andExpect(MockMvcResultMatchers.jsonPath("region").value("Region 值不在可选范围内")) .andExpect(MockMvcResultMatchers.jsonPath("phoneNumber").value("phoneNumber 格式不正确")); - } @Test - public void should_check_param_value() throws Exception { - + public void should_check_path_variable() throws Exception { mockMvc.perform(get("/api/person/6") - .contentType(MediaType.APPLICATION_JSON_UTF8)) + .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()) .andExpect(content().string("getPersonByID.id: 超过 id 的范围了")); } @Test - public void should_check_param_value2() throws Exception { - + public void should_check_request_param_value2() throws Exception { mockMvc.perform(put("/api/person") .param("name", "snailclimbsnailclimb") - .contentType(MediaType.APPLICATION_JSON_UTF8)) + .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()) .andExpect(content().string("getPersonByName.name: 超过 name 的范围了")); } /** - * 手动校验对象,很多场景下需要使用这种方式 + * 手动校验对象 */ @Test public void check_person_manually() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); - Person person = new Person(); - person.setSex("Man22"); - person.setClassId("82938390"); - person.setEmail("SnailClimb"); - Set> violations = validator.validate(person); - //output: - //email 格式不正确 - //name 不能为空 - //sex 值不在可选范围 - for (ConstraintViolation constraintViolation : violations) { - System.out.println(constraintViolation.getMessage()); - } + PersonRequest personRequest = PersonRequest.builder().sex("Man22") + .classId("82938390").build(); + Set> violations = validator.validate(personRequest); + violations.forEach(constraintViolation -> System.out.println(constraintViolation.getMessage())); } } diff --git a/source-code/advanced/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/PersonServiceTest.java b/source-code/advanced/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/PersonServiceTest.java index 377d7e1..88b5da3 100644 --- a/source-code/advanced/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/PersonServiceTest.java +++ b/source-code/advanced/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/PersonServiceTest.java @@ -1,6 +1,7 @@ package com.example.beanvalidationdemo; import com.example.beanvalidationdemo.entity.Person; +import com.example.beanvalidationdemo.entity.PersonRequest; import com.example.beanvalidationdemo.service.PersonService; import org.junit.Test; import org.junit.runner.RunWith; @@ -16,21 +17,20 @@ public class PersonServiceTest { @Autowired private PersonService service; - @Test(expected = ConstraintViolationException.class) - public void should_throw_exception_when_person_is_not_valid() { - Person person = new Person(); - person.setSex("Man22"); - person.setClassId("82938390"); - person.setEmail("SnailClimb"); - service.validatePerson(person); + @Test + public void should_throw_exception_when_person_request_is_not_valid() { + try { + PersonRequest personRequest = PersonRequest.builder().sex("Man22") + .classId("82938390").build(); + service.validatePersonRequest(personRequest); + } catch (ConstraintViolationException e) { + e.getConstraintViolations().forEach(constraintViolation -> System.out.println(constraintViolation.getMessage())); + } } @Test(expected = ConstraintViolationException.class) public void should_check_person_with_groups() { Person person = new Person(); - person.setSex("Man22"); - person.setClassId("82938390"); - person.setEmail("SnailClimb"); person.setGroup("group1"); service.validatePersonGroupForAdd(person); } @@ -38,9 +38,6 @@ public void should_check_person_with_groups() { @Test(expected = ConstraintViolationException.class) public void should_check_person_with_groups2() { Person person = new Person(); - person.setSex("Man22"); - person.setClassId("82938390"); - person.setEmail("SnailClimb"); service.validatePersonGroupForDelete(person); } diff --git a/source-code/advanced/springboot-oss/qrcode_for_gh_b109a4892225_258.jpg b/source-code/advanced/springboot-oss/qrcode_for_gh_b109a4892225_258.jpg deleted file mode 100644 index f03a22c..0000000 Binary files a/source-code/advanced/springboot-oss/qrcode_for_gh_b109a4892225_258.jpg and /dev/null differ diff --git a/source-code/advanced/springboot-oss/rawpixel-600782-unsplash.jpg b/source-code/advanced/springboot-oss/rawpixel-600782-unsplash.jpg deleted file mode 100644 index 241b6bc..0000000 Binary files a/source-code/advanced/springboot-oss/rawpixel-600782-unsplash.jpg and /dev/null differ diff --git a/source-code/advanced/springboot-oss/src/main/java/top/snailclimb/common/constants/AliyunOSSConfigConstant.java b/source-code/advanced/springboot-oss/src/main/java/top/snailclimb/common/constants/AliyunOSSConfigConstant.java deleted file mode 100644 index e8d842a..0000000 --- a/source-code/advanced/springboot-oss/src/main/java/top/snailclimb/common/constants/AliyunOSSConfigConstant.java +++ /dev/null @@ -1,24 +0,0 @@ -package top.snailclimb.common.constants; - -/** - * @Author: SnailClimb - * @Date: 2018/12/4 15:09 - * @Description: 阿里云OSS存储的相关常量配置.我这里通过常量类来配置的,当然你也可以通过.properties 配置文件来配置, - * 然后利用 SpringBoot 的@ConfigurationProperties 注解来注入 - */ -public class AliyunOSSConfigConstant { - //私有构造方法 禁止该类初始化 - private AliyunOSSConfigConstant() { - } - - //仓库名称 - public static final String BUCKE_NAME = "my-blog-to-use"; - //地域节点 - public static final String END_POINT = "oss-cn-beijing.aliyuncs.com"; - //AccessKey ID - public static final String AccessKey_ID = "你的AccessKeyID"; - //Access Key Secret - public static final String AccessKey_Secret = "你的AccessKeyIDAccessKey_Secret"; - //仓库中的某个文件夹 - public static final String FILE_HOST = "test"; -} diff --git a/source-code/advanced/springboot-oss/src/main/java/top/snailclimb/common/utils/AliyunOSSUtil.java b/source-code/advanced/springboot-oss/src/main/java/top/snailclimb/common/utils/AliyunOSSUtil.java deleted file mode 100644 index 29552b5..0000000 --- a/source-code/advanced/springboot-oss/src/main/java/top/snailclimb/common/utils/AliyunOSSUtil.java +++ /dev/null @@ -1,146 +0,0 @@ -package top.snailclimb.common.utils; - - -import com.aliyun.oss.ClientException; -import com.aliyun.oss.OSSClient; -import com.aliyun.oss.OSSException; -import com.aliyun.oss.model.*; -import org.slf4j.LoggerFactory; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.stereotype.Component; -import top.snailclimb.common.constants.AliyunOSSConfigConstant; -import top.snailclimb.config.AliyunOSSConfig; - -import javax.imageio.ImageIO; -import java.awt.*; -import java.io.File; -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.UUID; - -/** - * @Author: SnailClimb - * @Date: 2018/12/1 16:56 - * @Description: 阿里云OSS服务相关工具类. - * Java API文档地址:https://help.aliyun.com/document_detail/32008.html?spm=a2c4g.11186623.6.703.238374b4PsMzWf - */ -@Component -public class AliyunOSSUtil { - private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class); - private static String FILE_URL; - private static String bucketName = AliyunOSSConfigConstant.BUCKE_NAME; - private static String endpoint = AliyunOSSConfigConstant.END_POINT; - private static String accessKeyId = AliyunOSSConfigConstant.AccessKey_ID; - private static String accessKeySecret = AliyunOSSConfigConstant.AccessKey_Secret; - private static String fileHost = AliyunOSSConfigConstant.FILE_HOST; - - - /** - * 上传文件。 - * - * @param file 需要上传的文件路径 - * @return 如果上传的文件是图片的话,会返回图片的"URL",如果非图片的话会返回"非图片,不可预览。文件路径为:+文件路径" - */ - public static String upLoad(File file) { - // 默认值为:true - boolean isImage = true; - // 判断所要上传的图片是否是图片,图片可以预览,其他文件不提供通过URL预览 - try { - Image image = ImageIO.read(file); - isImage = image == null ? false : true; - } catch (IOException e) { - e.printStackTrace(); - } - - logger.info("------OSS文件上传开始--------" + file.getName()); - - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); - String dateStr = format.format(new Date()); - - // 判断文件 - if (file == null) { - return null; - } - // 创建OSSClient实例。 - OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); - try { - // 判断容器是否存在,不存在就创建 - if (!ossClient.doesBucketExist(bucketName)) { - ossClient.createBucket(bucketName); - CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName); - createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead); - ossClient.createBucket(createBucketRequest); - } - // 设置文件路径和名称 - String fileUrl = fileHost + "/" + (dateStr + "/" + UUID.randomUUID().toString().replace("-", "") + "-" + file.getName()); - if (isImage) {//如果是图片,则图片的URL为:.... - FILE_URL = "https://" + bucketName + "." + endpoint + "/" + fileUrl; - } else { - FILE_URL = "非图片,不可预览。文件路径为:" + fileUrl; - } - - // 上传文件 - PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, file)); - // 设置权限(公开读) - ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead); - if (result != null) { - logger.info("------OSS文件上传成功------" + fileUrl); - } - } catch (OSSException oe) { - logger.error(oe.getMessage()); - } catch (ClientException ce) { - logger.error(ce.getErrorMessage()); - } finally { - if (ossClient != null) { - ossClient.shutdown(); - } - } - return FILE_URL; - } - - - /** - * 通过文件名下载文件 - * - * @param objectName 要下载的文件名 - * @param localFileName 本地要创建的文件名 - */ - public static void downloadFile(String objectName, String localFileName) { - - // 创建OSSClient实例。 - OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); - // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖,不存在则新建。 - ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(localFileName)); - // 关闭OSSClient。 - ossClient.shutdown(); - } - - /** - * 列举 test 文件下所有的文件 - */ - public static void listFile() { - // 创建OSSClient实例。 - OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); - // 构造ListObjectsRequest请求。 - ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName); - - // 设置prefix参数来获取fun目录下的所有文件。 - listObjectsRequest.setPrefix("test/"); - // 列出文件。 - ObjectListing listing = ossClient.listObjects(listObjectsRequest); - // 遍历所有文件。 - System.out.println("Objects:"); - for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) { - System.out.println(objectSummary.getKey()); - } - // 遍历所有commonPrefix。 - System.out.println("CommonPrefixes:"); - for (String commonPrefix : listing.getCommonPrefixes()) { - System.out.println(commonPrefix); - } - // 关闭OSSClient。 - ossClient.shutdown(); - } -} - diff --git a/source-code/advanced/springboot-oss/src/main/java/top/snailclimb/config/AliyunOSSConfig.java b/source-code/advanced/springboot-oss/src/main/java/top/snailclimb/config/AliyunOSSConfig.java deleted file mode 100644 index b5df76b..0000000 --- a/source-code/advanced/springboot-oss/src/main/java/top/snailclimb/config/AliyunOSSConfig.java +++ /dev/null @@ -1,60 +0,0 @@ -package top.snailclimb.config; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.PropertySource; -import org.springframework.stereotype.Component; - - -@Component -@PropertySource(value = "classpath:application-oss.properties") -@ConfigurationProperties(prefix = "aliyun.oss") -/** - * 阿里云oss的配置类 - */ -public class AliyunOSSConfig { - private String bucketname; - private String endpoint; - private String keyid; - private String keysecret; - private String filehost; - - public String getBucketname() { - return bucketname; - } - - public void setBucketname(String bucketname) { - this.bucketname = bucketname; - } - - public String getEndpoint() { - return endpoint; - } - - public void setEndpoint(String endpoint) { - this.endpoint = endpoint; - } - - public String getKeyid() { - return keyid; - } - - public void setKeyid(String keyid) { - this.keyid = keyid; - } - - public String getKeysecret() { - return keysecret; - } - - public void setKeysecret(String keysecret) { - this.keysecret = keysecret; - } - - public String getFilehost() { - return filehost; - } - - public void setFilehost(String filehost) { - this.filehost = filehost; - } -} diff --git a/source-code/advanced/springboot-oss/src/main/java/top/snailclimb/controller/AliyunOSSController.java b/source-code/advanced/springboot-oss/src/main/java/top/snailclimb/controller/AliyunOSSController.java deleted file mode 100644 index e4e9f3e..0000000 --- a/source-code/advanced/springboot-oss/src/main/java/top/snailclimb/controller/AliyunOSSController.java +++ /dev/null @@ -1,96 +0,0 @@ -package top.snailclimb.controller; - -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.multipart.MultipartFile; -import top.snailclimb.config.AliyunOSSConfig; -import top.snailclimb.common.utils.AliyunOSSUtil; - -import java.io.File; -import java.io.FileOutputStream; - -/** - * @Author: SnailClimb - * @Date: 2018/12/2 16:56 - * @Description: 阿里云OSS服务Controller - */ -@Controller -@RequestMapping("/oss") -public class AliyunOSSController { - - private final org.slf4j.Logger logger = LoggerFactory.getLogger(getClass()); - @Autowired - private AliyunOSSUtil aliyunOSSUtil; - - /** - * 测试上传文件到阿里云OSS存储(不支持上传文件,推荐作为图床使用) - * - * @return - */ - @RequestMapping("/testUpload") - @ResponseBody - public String testUpload() { - File file = new File("E:/Picture/test.jpg"); - AliyunOSSUtil aliyunOSSUtil = new AliyunOSSUtil(); - String url = aliyunOSSUtil.upLoad(file); - System.out.println(url); - return "success"; - } - - /** - * 通过文件名下载文件 - */ - @RequestMapping("/testDownload") - @ResponseBody - public String testDownload() { - AliyunOSSUtil aliyunOSSUtil = new AliyunOSSUtil(); - aliyunOSSUtil.downloadFile( - "test/2018-12-04/e3f892c27f07462a864a43b8187d4562-rawpixel-600782-unsplash.jpg","E:/Picture/e3f892c27f07462a864a43b8187d4562-rawpixel-600782-unsplash.jpg"); - return "success"; - } - - /** - * 列出某个文件夹下的所有文件 - */ - @RequestMapping("/testListFile") - @ResponseBody - public String testListFile() { - AliyunOSSUtil aliyunOSSUtil = new AliyunOSSUtil(); - aliyunOSSUtil.listFile(); - return "success"; - } - - /** - * 文件上传 - */ - @RequestMapping(value = "/uploadFile") - public String uploadPicture(@RequestParam("file") MultipartFile file, Model model) { - logger.info("文件上传"); - String filename = file.getOriginalFilename(); - System.out.println(filename); - try { - - if (file != null) { - if (!"".equals(filename.trim())) { - File newFile = new File(filename); - FileOutputStream os = new FileOutputStream(newFile); - os.write(file.getBytes()); - os.close(); - file.transferTo(newFile); - // 上传到OSS - String uploadUrl = aliyunOSSUtil.upLoad(newFile); - model.addAttribute("url",uploadUrl); - } - - } - } catch (Exception ex) { - ex.printStackTrace(); - } - return "success"; - } -} diff --git a/source-code/advanced/springboot-oss/src/main/resources/application-oss.properties b/source-code/advanced/springboot-oss/src/main/resources/application-oss.properties deleted file mode 100644 index f78f09b..0000000 --- a/source-code/advanced/springboot-oss/src/main/resources/application-oss.properties +++ /dev/null @@ -1,7 +0,0 @@ -#OSS配置 -aliyun.oss.bucketname=my-blog-to-use -aliyun.oss.endpoint=oss-cn-beijing.aliyuncs.com -#阿里云主账号AccessKey拥有所有API的访问权限,风险很高。建议创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。 -aliyun.oss.keyid=你的AccessKeyID -aliyun.oss.keysecret=你的AccessKeySecret -aliyun.oss.filehost=test diff --git a/source-code/advanced/springboot-oss/src/main/resources/static/js/jquery-3.3.1.js b/source-code/advanced/springboot-oss/src/main/resources/static/js/jquery-3.3.1.js deleted file mode 100644 index 62dd5b1..0000000 --- a/source-code/advanced/springboot-oss/src/main/resources/static/js/jquery-3.3.1.js +++ /dev/null @@ -1,10364 +0,0 @@ -/*! - * jQuery JavaScript Library v3.3.1 - * https://jquery.com/ - * - * Includes Sizzle.js - * https://sizzlejs.com/ - * - * Copyright JS Foundation and other contributors - * Released under the MIT license - * https://jquery.org/license - * - * Date: 2018-01-20T17:24Z - */ -( function( global, factory ) { - - "use strict"; - - if ( typeof module === "object" && typeof module.exports === "object" ) { - - // For CommonJS and CommonJS-like environments where a proper `window` - // is present, execute the factory and get jQuery. - // For environments that do not have a `window` with a `document` - // (such as Node.js), expose a factory as module.exports. - // This accentuates the need for the creation of a real `window`. - // e.g. var jQuery = require("jquery")(window); - // See ticket #14549 for more info. - module.exports = global.document ? - factory( global, true ) : - function( w ) { - if ( !w.document ) { - throw new Error( "jQuery requires a window with a document" ); - } - return factory( w ); - }; - } else { - factory( global ); - } - -// Pass this if window is not defined yet -} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { - -// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 -// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode -// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common -// enough that all such attempts are guarded in a try block. - "use strict"; - - var arr = []; - - var document = window.document; - - var getProto = Object.getPrototypeOf; - - var slice = arr.slice; - - var concat = arr.concat; - - var push = arr.push; - - var indexOf = arr.indexOf; - - var class2type = {}; - - var toString = class2type.toString; - - var hasOwn = class2type.hasOwnProperty; - - var fnToString = hasOwn.toString; - - var ObjectFunctionString = fnToString.call( Object ); - - var support = {}; - - var isFunction = function isFunction( obj ) { - - // Support: Chrome <=57, Firefox <=52 - // In some browsers, typeof returns "function" for HTML elements - // (i.e., `typeof document.createElement( "object" ) === "function"`). - // We don't want to classify *any* DOM node as a function. - return typeof obj === "function" && typeof obj.nodeType !== "number"; - }; - - - var isWindow = function isWindow( obj ) { - return obj != null && obj === obj.window; - }; - - - - - var preservedScriptAttributes = { - type: true, - src: true, - noModule: true - }; - - function DOMEval( code, doc, node ) { - doc = doc || document; - - var i, - script = doc.createElement( "script" ); - - script.text = code; - if ( node ) { - for ( i in preservedScriptAttributes ) { - if ( node[ i ] ) { - script[ i ] = node[ i ]; - } - } - } - doc.head.appendChild( script ).parentNode.removeChild( script ); - } - - - function toType( obj ) { - if ( obj == null ) { - return obj + ""; - } - - // Support: Android <=2.3 only (functionish RegExp) - return typeof obj === "object" || typeof obj === "function" ? - class2type[ toString.call( obj ) ] || "object" : - typeof obj; - } - /* global Symbol */ -// Defining this global in .eslintrc.json would create a danger of using the global -// unguarded in another place, it seems safer to define global only for this module - - - - var - version = "3.3.1", - - // Define a local copy of jQuery - jQuery = function( selector, context ) { - - // The jQuery object is actually just the init constructor 'enhanced' - // Need init if jQuery is called (just allow error to be thrown if not included) - return new jQuery.fn.init( selector, context ); - }, - - // Support: Android <=4.0 only - // Make sure we trim BOM and NBSP - rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g; - - jQuery.fn = jQuery.prototype = { - - // The current version of jQuery being used - jquery: version, - - constructor: jQuery, - - // The default length of a jQuery object is 0 - length: 0, - - toArray: function() { - return slice.call( this ); - }, - - // Get the Nth element in the matched element set OR - // Get the whole matched element set as a clean array - get: function( num ) { - - // Return all the elements in a clean array - if ( num == null ) { - return slice.call( this ); - } - - // Return just the one element from the set - return num < 0 ? this[ num + this.length ] : this[ num ]; - }, - - // Take an array of elements and push it onto the stack - // (returning the new matched element set) - pushStack: function( elems ) { - - // Build a new jQuery matched element set - var ret = jQuery.merge( this.constructor(), elems ); - - // Add the old object onto the stack (as a reference) - ret.prevObject = this; - - // Return the newly-formed element set - return ret; - }, - - // Execute a callback for every element in the matched set. - each: function( callback ) { - return jQuery.each( this, callback ); - }, - - map: function( callback ) { - return this.pushStack( jQuery.map( this, function( elem, i ) { - return callback.call( elem, i, elem ); - } ) ); - }, - - slice: function() { - return this.pushStack( slice.apply( this, arguments ) ); - }, - - first: function() { - return this.eq( 0 ); - }, - - last: function() { - return this.eq( -1 ); - }, - - eq: function( i ) { - var len = this.length, - j = +i + ( i < 0 ? len : 0 ); - return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); - }, - - end: function() { - return this.prevObject || this.constructor(); - }, - - // For internal use only. - // Behaves like an Array's method, not like a jQuery method. - push: push, - sort: arr.sort, - splice: arr.splice - }; - - jQuery.extend = jQuery.fn.extend = function() { - var options, name, src, copy, copyIsArray, clone, - target = arguments[ 0 ] || {}, - i = 1, - length = arguments.length, - deep = false; - - // Handle a deep copy situation - if ( typeof target === "boolean" ) { - deep = target; - - // Skip the boolean and the target - target = arguments[ i ] || {}; - i++; - } - - // Handle case when target is a string or something (possible in deep copy) - if ( typeof target !== "object" && !isFunction( target ) ) { - target = {}; - } - - // Extend jQuery itself if only one argument is passed - if ( i === length ) { - target = this; - i--; - } - - for ( ; i < length; i++ ) { - - // Only deal with non-null/undefined values - if ( ( options = arguments[ i ] ) != null ) { - - // Extend the base object - for ( name in options ) { - src = target[ name ]; - copy = options[ name ]; - - // Prevent never-ending loop - if ( target === copy ) { - continue; - } - - // Recurse if we're merging plain objects or arrays - if ( deep && copy && ( jQuery.isPlainObject( copy ) || - ( copyIsArray = Array.isArray( copy ) ) ) ) { - - if ( copyIsArray ) { - copyIsArray = false; - clone = src && Array.isArray( src ) ? src : []; - - } else { - clone = src && jQuery.isPlainObject( src ) ? src : {}; - } - - // Never move original objects, clone them - target[ name ] = jQuery.extend( deep, clone, copy ); - - // Don't bring in undefined values - } else if ( copy !== undefined ) { - target[ name ] = copy; - } - } - } - } - - // Return the modified object - return target; - }; - - jQuery.extend( { - - // Unique for each copy of jQuery on the page - expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), - - // Assume jQuery is ready without the ready module - isReady: true, - - error: function( msg ) { - throw new Error( msg ); - }, - - noop: function() {}, - - isPlainObject: function( obj ) { - var proto, Ctor; - - // Detect obvious negatives - // Use toString instead of jQuery.type to catch host objects - if ( !obj || toString.call( obj ) !== "[object Object]" ) { - return false; - } - - proto = getProto( obj ); - - // Objects with no prototype (e.g., `Object.create( null )`) are plain - if ( !proto ) { - return true; - } - - // Objects with prototype are plain iff they were constructed by a global Object function - Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; - return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; - }, - - isEmptyObject: function( obj ) { - - /* eslint-disable no-unused-vars */ - // See https://github.com/eslint/eslint/issues/6125 - var name; - - for ( name in obj ) { - return false; - } - return true; - }, - - // Evaluates a script in a global context - globalEval: function( code ) { - DOMEval( code ); - }, - - each: function( obj, callback ) { - var length, i = 0; - - if ( isArrayLike( obj ) ) { - length = obj.length; - for ( ; i < length; i++ ) { - if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { - break; - } - } - } else { - for ( i in obj ) { - if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { - break; - } - } - } - - return obj; - }, - - // Support: Android <=4.0 only - trim: function( text ) { - return text == null ? - "" : - ( text + "" ).replace( rtrim, "" ); - }, - - // results is for internal usage only - makeArray: function( arr, results ) { - var ret = results || []; - - if ( arr != null ) { - if ( isArrayLike( Object( arr ) ) ) { - jQuery.merge( ret, - typeof arr === "string" ? - [ arr ] : arr - ); - } else { - push.call( ret, arr ); - } - } - - return ret; - }, - - inArray: function( elem, arr, i ) { - return arr == null ? -1 : indexOf.call( arr, elem, i ); - }, - - // Support: Android <=4.0 only, PhantomJS 1 only - // push.apply(_, arraylike) throws on ancient WebKit - merge: function( first, second ) { - var len = +second.length, - j = 0, - i = first.length; - - for ( ; j < len; j++ ) { - first[ i++ ] = second[ j ]; - } - - first.length = i; - - return first; - }, - - grep: function( elems, callback, invert ) { - var callbackInverse, - matches = [], - i = 0, - length = elems.length, - callbackExpect = !invert; - - // Go through the array, only saving the items - // that pass the validator function - for ( ; i < length; i++ ) { - callbackInverse = !callback( elems[ i ], i ); - if ( callbackInverse !== callbackExpect ) { - matches.push( elems[ i ] ); - } - } - - return matches; - }, - - // arg is for internal usage only - map: function( elems, callback, arg ) { - var length, value, - i = 0, - ret = []; - - // Go through the array, translating each of the items to their new values - if ( isArrayLike( elems ) ) { - length = elems.length; - for ( ; i < length; i++ ) { - value = callback( elems[ i ], i, arg ); - - if ( value != null ) { - ret.push( value ); - } - } - - // Go through every key on the object, - } else { - for ( i in elems ) { - value = callback( elems[ i ], i, arg ); - - if ( value != null ) { - ret.push( value ); - } - } - } - - // Flatten any nested arrays - return concat.apply( [], ret ); - }, - - // A global GUID counter for objects - guid: 1, - - // jQuery.support is not used in Core but other projects attach their - // properties to it so it needs to exist. - support: support - } ); - - if ( typeof Symbol === "function" ) { - jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; - } - -// Populate the class2type map - jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), - function( i, name ) { - class2type[ "[object " + name + "]" ] = name.toLowerCase(); - } ); - - function isArrayLike( obj ) { - - // Support: real iOS 8.2 only (not reproducible in simulator) - // `in` check used to prevent JIT error (gh-2145) - // hasOwn isn't used here due to false negatives - // regarding Nodelist length in IE - var length = !!obj && "length" in obj && obj.length, - type = toType( obj ); - - if ( isFunction( obj ) || isWindow( obj ) ) { - return false; - } - - return type === "array" || length === 0 || - typeof length === "number" && length > 0 && ( length - 1 ) in obj; - } - var Sizzle = - /*! - * Sizzle CSS Selector Engine v2.3.3 - * https://sizzlejs.com/ - * - * Copyright jQuery Foundation and other contributors - * Released under the MIT license - * http://jquery.org/license - * - * Date: 2016-08-08 - */ - (function( window ) { - - var i, - support, - Expr, - getText, - isXML, - tokenize, - compile, - select, - outermostContext, - sortInput, - hasDuplicate, - - // Local document vars - setDocument, - document, - docElem, - documentIsHTML, - rbuggyQSA, - rbuggyMatches, - matches, - contains, - - // Instance-specific data - expando = "sizzle" + 1 * new Date(), - preferredDoc = window.document, - dirruns = 0, - done = 0, - classCache = createCache(), - tokenCache = createCache(), - compilerCache = createCache(), - sortOrder = function( a, b ) { - if ( a === b ) { - hasDuplicate = true; - } - return 0; - }, - - // Instance methods - hasOwn = ({}).hasOwnProperty, - arr = [], - pop = arr.pop, - push_native = arr.push, - push = arr.push, - slice = arr.slice, - // Use a stripped-down indexOf as it's faster than native - // https://jsperf.com/thor-indexof-vs-for/5 - indexOf = function( list, elem ) { - var i = 0, - len = list.length; - for ( ; i < len; i++ ) { - if ( list[i] === elem ) { - return i; - } - } - return -1; - }, - - booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", - - // Regular expressions - - // http://www.w3.org/TR/css3-selectors/#whitespace - whitespace = "[\\x20\\t\\r\\n\\f]", - - // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier - identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+", - - // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors - attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + - // Operator (capture 2) - "*([*^$|!~]?=)" + whitespace + - // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" - "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + - "*\\]", - - pseudos = ":(" + identifier + ")(?:\\((" + - // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: - // 1. quoted (capture 3; capture 4 or capture 5) - "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + - // 2. simple (capture 6) - "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + - // 3. anything else (capture 2) - ".*" + - ")\\)|)", - - // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter - rwhitespace = new RegExp( whitespace + "+", "g" ), - rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), - - rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), - rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), - - rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), - - rpseudo = new RegExp( pseudos ), - ridentifier = new RegExp( "^" + identifier + "$" ), - - matchExpr = { - "ID": new RegExp( "^#(" + identifier + ")" ), - "CLASS": new RegExp( "^\\.(" + identifier + ")" ), - "TAG": new RegExp( "^(" + identifier + "|[*])" ), - "ATTR": new RegExp( "^" + attributes ), - "PSEUDO": new RegExp( "^" + pseudos ), - "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + - "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + - "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), - "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), - // For use in libraries implementing .is() - // We use this for POS matching in `select` - "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + - whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) - }, - - rinputs = /^(?:input|select|textarea|button)$/i, - rheader = /^h\d$/i, - - rnative = /^[^{]+\{\s*\[native \w/, - - // Easily-parseable/retrievable ID or TAG or CLASS selectors - rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, - - rsibling = /[+~]/, - - // CSS escapes - // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters - runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), - funescape = function( _, escaped, escapedWhitespace ) { - var high = "0x" + escaped - 0x10000; - // NaN means non-codepoint - // Support: Firefox<24 - // Workaround erroneous numeric interpretation of +"0x" - return high !== high || escapedWhitespace ? - escaped : - high < 0 ? - // BMP codepoint - String.fromCharCode( high + 0x10000 ) : - // Supplemental Plane codepoint (surrogate pair) - String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); - }, - - // CSS string/identifier serialization - // https://drafts.csswg.org/cssom/#common-serializing-idioms - rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, - fcssescape = function( ch, asCodePoint ) { - if ( asCodePoint ) { - - // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER - if ( ch === "\0" ) { - return "\uFFFD"; - } - - // Control characters and (dependent upon position) numbers get escaped as code points - return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; - } - - // Other potentially-special ASCII characters get backslash-escaped - return "\\" + ch; - }, - - // Used for iframes - // See setDocument() - // Removing the function wrapper causes a "Permission Denied" - // error in IE - unloadHandler = function() { - setDocument(); - }, - - disabledAncestor = addCombinator( - function( elem ) { - return elem.disabled === true && ("form" in elem || "label" in elem); - }, - { dir: "parentNode", next: "legend" } - ); - -// Optimize for push.apply( _, NodeList ) - try { - push.apply( - (arr = slice.call( preferredDoc.childNodes )), - preferredDoc.childNodes - ); - // Support: Android<4.0 - // Detect silently failing push.apply - arr[ preferredDoc.childNodes.length ].nodeType; - } catch ( e ) { - push = { apply: arr.length ? - - // Leverage slice if possible - function( target, els ) { - push_native.apply( target, slice.call(els) ); - } : - - // Support: IE<9 - // Otherwise append directly - function( target, els ) { - var j = target.length, - i = 0; - // Can't trust NodeList.length - while ( (target[j++] = els[i++]) ) {} - target.length = j - 1; - } - }; - } - - function Sizzle( selector, context, results, seed ) { - var m, i, elem, nid, match, groups, newSelector, - newContext = context && context.ownerDocument, - - // nodeType defaults to 9, since context defaults to document - nodeType = context ? context.nodeType : 9; - - results = results || []; - - // Return early from calls with invalid selector or context - if ( typeof selector !== "string" || !selector || - nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { - - return results; - } - - // Try to shortcut find operations (as opposed to filters) in HTML documents - if ( !seed ) { - - if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { - setDocument( context ); - } - context = context || document; - - if ( documentIsHTML ) { - - // If the selector is sufficiently simple, try using a "get*By*" DOM method - // (excepting DocumentFragment context, where the methods don't exist) - if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { - - // ID selector - if ( (m = match[1]) ) { - - // Document context - if ( nodeType === 9 ) { - if ( (elem = context.getElementById( m )) ) { - - // Support: IE, Opera, Webkit - // TODO: identify versions - // getElementById can match elements by name instead of ID - if ( elem.id === m ) { - results.push( elem ); - return results; - } - } else { - return results; - } - - // Element context - } else { - - // Support: IE, Opera, Webkit - // TODO: identify versions - // getElementById can match elements by name instead of ID - if ( newContext && (elem = newContext.getElementById( m )) && - contains( context, elem ) && - elem.id === m ) { - - results.push( elem ); - return results; - } - } - - // Type selector - } else if ( match[2] ) { - push.apply( results, context.getElementsByTagName( selector ) ); - return results; - - // Class selector - } else if ( (m = match[3]) && support.getElementsByClassName && - context.getElementsByClassName ) { - - push.apply( results, context.getElementsByClassName( m ) ); - return results; - } - } - - // Take advantage of querySelectorAll - if ( support.qsa && - !compilerCache[ selector + " " ] && - (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { - - if ( nodeType !== 1 ) { - newContext = context; - newSelector = selector; - - // qSA looks outside Element context, which is not what we want - // Thanks to Andrew Dupont for this workaround technique - // Support: IE <=8 - // Exclude object elements - } else if ( context.nodeName.toLowerCase() !== "object" ) { - - // Capture the context ID, setting it first if necessary - if ( (nid = context.getAttribute( "id" )) ) { - nid = nid.replace( rcssescape, fcssescape ); - } else { - context.setAttribute( "id", (nid = expando) ); - } - - // Prefix every selector in the list - groups = tokenize( selector ); - i = groups.length; - while ( i-- ) { - groups[i] = "#" + nid + " " + toSelector( groups[i] ); - } - newSelector = groups.join( "," ); - - // Expand context for sibling selectors - newContext = rsibling.test( selector ) && testContext( context.parentNode ) || - context; - } - - if ( newSelector ) { - try { - push.apply( results, - newContext.querySelectorAll( newSelector ) - ); - return results; - } catch ( qsaError ) { - } finally { - if ( nid === expando ) { - context.removeAttribute( "id" ); - } - } - } - } - } - } - - // All others - return select( selector.replace( rtrim, "$1" ), context, results, seed ); - } - - /** - * Create key-value caches of limited size - * @returns {function(string, object)} Returns the Object data after storing it on itself with - * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) - * deleting the oldest entry - */ - function createCache() { - var keys = []; - - function cache( key, value ) { - // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) - if ( keys.push( key + " " ) > Expr.cacheLength ) { - // Only keep the most recent entries - delete cache[ keys.shift() ]; - } - return (cache[ key + " " ] = value); - } - return cache; - } - - /** - * Mark a function for special use by Sizzle - * @param {Function} fn The function to mark - */ - function markFunction( fn ) { - fn[ expando ] = true; - return fn; - } - - /** - * Support testing using an element - * @param {Function} fn Passed the created element and returns a boolean result - */ - function assert( fn ) { - var el = document.createElement("fieldset"); - - try { - return !!fn( el ); - } catch (e) { - return false; - } finally { - // Remove from its parent by default - if ( el.parentNode ) { - el.parentNode.removeChild( el ); - } - // release memory in IE - el = null; - } - } - - /** - * Adds the same handler for all of the specified attrs - * @param {String} attrs Pipe-separated list of attributes - * @param {Function} handler The method that will be applied - */ - function addHandle( attrs, handler ) { - var arr = attrs.split("|"), - i = arr.length; - - while ( i-- ) { - Expr.attrHandle[ arr[i] ] = handler; - } - } - - /** - * Checks document order of two siblings - * @param {Element} a - * @param {Element} b - * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b - */ - function siblingCheck( a, b ) { - var cur = b && a, - diff = cur && a.nodeType === 1 && b.nodeType === 1 && - a.sourceIndex - b.sourceIndex; - - // Use IE sourceIndex if available on both nodes - if ( diff ) { - return diff; - } - - // Check if b follows a - if ( cur ) { - while ( (cur = cur.nextSibling) ) { - if ( cur === b ) { - return -1; - } - } - } - - return a ? 1 : -1; - } - - /** - * Returns a function to use in pseudos for input types - * @param {String} type - */ - function createInputPseudo( type ) { - return function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && elem.type === type; - }; - } - - /** - * Returns a function to use in pseudos for buttons - * @param {String} type - */ - function createButtonPseudo( type ) { - return function( elem ) { - var name = elem.nodeName.toLowerCase(); - return (name === "input" || name === "button") && elem.type === type; - }; - } - - /** - * Returns a function to use in pseudos for :enabled/:disabled - * @param {Boolean} disabled true for :disabled; false for :enabled - */ - function createDisabledPseudo( disabled ) { - - // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable - return function( elem ) { - - // Only certain elements can match :enabled or :disabled - // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled - // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled - if ( "form" in elem ) { - - // Check for inherited disabledness on relevant non-disabled elements: - // * listed form-associated elements in a disabled fieldset - // https://html.spec.whatwg.org/multipage/forms.html#category-listed - // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled - // * option elements in a disabled optgroup - // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled - // All such elements have a "form" property. - if ( elem.parentNode && elem.disabled === false ) { - - // Option elements defer to a parent optgroup if present - if ( "label" in elem ) { - if ( "label" in elem.parentNode ) { - return elem.parentNode.disabled === disabled; - } else { - return elem.disabled === disabled; - } - } - - // Support: IE 6 - 11 - // Use the isDisabled shortcut property to check for disabled fieldset ancestors - return elem.isDisabled === disabled || - - // Where there is no isDisabled, check manually - /* jshint -W018 */ - elem.isDisabled !== !disabled && - disabledAncestor( elem ) === disabled; - } - - return elem.disabled === disabled; - - // Try to winnow out elements that can't be disabled before trusting the disabled property. - // Some victims get caught in our net (label, legend, menu, track), but it shouldn't - // even exist on them, let alone have a boolean value. - } else if ( "label" in elem ) { - return elem.disabled === disabled; - } - - // Remaining elements are neither :enabled nor :disabled - return false; - }; - } - - /** - * Returns a function to use in pseudos for positionals - * @param {Function} fn - */ - function createPositionalPseudo( fn ) { - return markFunction(function( argument ) { - argument = +argument; - return markFunction(function( seed, matches ) { - var j, - matchIndexes = fn( [], seed.length, argument ), - i = matchIndexes.length; - - // Match elements found at the specified indexes - while ( i-- ) { - if ( seed[ (j = matchIndexes[i]) ] ) { - seed[j] = !(matches[j] = seed[j]); - } - } - }); - }); - } - - /** - * Checks a node for validity as a Sizzle context - * @param {Element|Object=} context - * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value - */ - function testContext( context ) { - return context && typeof context.getElementsByTagName !== "undefined" && context; - } - -// Expose support vars for convenience - support = Sizzle.support = {}; - - /** - * Detects XML nodes - * @param {Element|Object} elem An element or a document - * @returns {Boolean} True iff elem is a non-HTML XML node - */ - isXML = Sizzle.isXML = function( elem ) { - // documentElement is verified for cases where it doesn't yet exist - // (such as loading iframes in IE - #4833) - var documentElement = elem && (elem.ownerDocument || elem).documentElement; - return documentElement ? documentElement.nodeName !== "HTML" : false; - }; - - /** - * Sets document-related variables once based on the current document - * @param {Element|Object} [doc] An element or document object to use to set the document - * @returns {Object} Returns the current document - */ - setDocument = Sizzle.setDocument = function( node ) { - var hasCompare, subWindow, - doc = node ? node.ownerDocument || node : preferredDoc; - - // Return early if doc is invalid or already selected - if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { - return document; - } - - // Update global variables - document = doc; - docElem = document.documentElement; - documentIsHTML = !isXML( document ); - - // Support: IE 9-11, Edge - // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) - if ( preferredDoc !== document && - (subWindow = document.defaultView) && subWindow.top !== subWindow ) { - - // Support: IE 11, Edge - if ( subWindow.addEventListener ) { - subWindow.addEventListener( "unload", unloadHandler, false ); - - // Support: IE 9 - 10 only - } else if ( subWindow.attachEvent ) { - subWindow.attachEvent( "onunload", unloadHandler ); - } - } - - /* Attributes - ---------------------------------------------------------------------- */ - - // Support: IE<8 - // Verify that getAttribute really returns attributes and not properties - // (excepting IE8 booleans) - support.attributes = assert(function( el ) { - el.className = "i"; - return !el.getAttribute("className"); - }); - - /* getElement(s)By* - ---------------------------------------------------------------------- */ - - // Check if getElementsByTagName("*") returns only elements - support.getElementsByTagName = assert(function( el ) { - el.appendChild( document.createComment("") ); - return !el.getElementsByTagName("*").length; - }); - - // Support: IE<9 - support.getElementsByClassName = rnative.test( document.getElementsByClassName ); - - // Support: IE<10 - // Check if getElementById returns elements by name - // The broken getElementById methods don't pick up programmatically-set names, - // so use a roundabout getElementsByName test - support.getById = assert(function( el ) { - docElem.appendChild( el ).id = expando; - return !document.getElementsByName || !document.getElementsByName( expando ).length; - }); - - // ID filter and find - if ( support.getById ) { - Expr.filter["ID"] = function( id ) { - var attrId = id.replace( runescape, funescape ); - return function( elem ) { - return elem.getAttribute("id") === attrId; - }; - }; - Expr.find["ID"] = function( id, context ) { - if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { - var elem = context.getElementById( id ); - return elem ? [ elem ] : []; - } - }; - } else { - Expr.filter["ID"] = function( id ) { - var attrId = id.replace( runescape, funescape ); - return function( elem ) { - var node = typeof elem.getAttributeNode !== "undefined" && - elem.getAttributeNode("id"); - return node && node.value === attrId; - }; - }; - - // Support: IE 6 - 7 only - // getElementById is not reliable as a find shortcut - Expr.find["ID"] = function( id, context ) { - if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { - var node, i, elems, - elem = context.getElementById( id ); - - if ( elem ) { - - // Verify the id attribute - node = elem.getAttributeNode("id"); - if ( node && node.value === id ) { - return [ elem ]; - } - - // Fall back on getElementsByName - elems = context.getElementsByName( id ); - i = 0; - while ( (elem = elems[i++]) ) { - node = elem.getAttributeNode("id"); - if ( node && node.value === id ) { - return [ elem ]; - } - } - } - - return []; - } - }; - } - - // Tag - Expr.find["TAG"] = support.getElementsByTagName ? - function( tag, context ) { - if ( typeof context.getElementsByTagName !== "undefined" ) { - return context.getElementsByTagName( tag ); - - // DocumentFragment nodes don't have gEBTN - } else if ( support.qsa ) { - return context.querySelectorAll( tag ); - } - } : - - function( tag, context ) { - var elem, - tmp = [], - i = 0, - // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too - results = context.getElementsByTagName( tag ); - - // Filter out possible comments - if ( tag === "*" ) { - while ( (elem = results[i++]) ) { - if ( elem.nodeType === 1 ) { - tmp.push( elem ); - } - } - - return tmp; - } - return results; - }; - - // Class - Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { - if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { - return context.getElementsByClassName( className ); - } - }; - - /* QSA/matchesSelector - ---------------------------------------------------------------------- */ - - // QSA and matchesSelector support - - // matchesSelector(:active) reports false when true (IE9/Opera 11.5) - rbuggyMatches = []; - - // qSa(:focus) reports false when true (Chrome 21) - // We allow this because of a bug in IE8/9 that throws an error - // whenever `document.activeElement` is accessed on an iframe - // So, we allow :focus to pass through QSA all the time to avoid the IE error - // See https://bugs.jquery.com/ticket/13378 - rbuggyQSA = []; - - if ( (support.qsa = rnative.test( document.querySelectorAll )) ) { - // Build QSA regex - // Regex strategy adopted from Diego Perini - assert(function( el ) { - // Select is set to empty string on purpose - // This is to test IE's treatment of not explicitly - // setting a boolean content attribute, - // since its presence should be enough - // https://bugs.jquery.com/ticket/12359 - docElem.appendChild( el ).innerHTML = "" + - ""; - - // Support: IE8, Opera 11-12.16 - // Nothing should be selected when empty strings follow ^= or $= or *= - // The test attribute must be unknown in Opera but "safe" for WinRT - // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section - if ( el.querySelectorAll("[msallowcapture^='']").length ) { - rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); - } - - // Support: IE8 - // Boolean attributes and "value" are not treated correctly - if ( !el.querySelectorAll("[selected]").length ) { - rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); - } - - // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ - if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { - rbuggyQSA.push("~="); - } - - // Webkit/Opera - :checked should return selected option elements - // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked - // IE8 throws error here and will not see later tests - if ( !el.querySelectorAll(":checked").length ) { - rbuggyQSA.push(":checked"); - } - - // Support: Safari 8+, iOS 8+ - // https://bugs.webkit.org/show_bug.cgi?id=136851 - // In-page `selector#id sibling-combinator selector` fails - if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { - rbuggyQSA.push(".#.+[+~]"); - } - }); - - assert(function( el ) { - el.innerHTML = "" + - ""; - - // Support: Windows 8 Native Apps - // The type and name attributes are restricted during .innerHTML assignment - var input = document.createElement("input"); - input.setAttribute( "type", "hidden" ); - el.appendChild( input ).setAttribute( "name", "D" ); - - // Support: IE8 - // Enforce case-sensitivity of name attribute - if ( el.querySelectorAll("[name=d]").length ) { - rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); - } - - // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) - // IE8 throws error here and will not see later tests - if ( el.querySelectorAll(":enabled").length !== 2 ) { - rbuggyQSA.push( ":enabled", ":disabled" ); - } - - // Support: IE9-11+ - // IE's :disabled selector does not pick up the children of disabled fieldsets - docElem.appendChild( el ).disabled = true; - if ( el.querySelectorAll(":disabled").length !== 2 ) { - rbuggyQSA.push( ":enabled", ":disabled" ); - } - - // Opera 10-11 does not throw on post-comma invalid pseudos - el.querySelectorAll("*,:x"); - rbuggyQSA.push(",.*:"); - }); - } - - if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || - docElem.webkitMatchesSelector || - docElem.mozMatchesSelector || - docElem.oMatchesSelector || - docElem.msMatchesSelector) )) ) { - - assert(function( el ) { - // Check to see if it's possible to do matchesSelector - // on a disconnected node (IE 9) - support.disconnectedMatch = matches.call( el, "*" ); - - // This should fail with an exception - // Gecko does not error, returns false instead - matches.call( el, "[s!='']:x" ); - rbuggyMatches.push( "!=", pseudos ); - }); - } - - rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); - rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); - - /* Contains - ---------------------------------------------------------------------- */ - hasCompare = rnative.test( docElem.compareDocumentPosition ); - - // Element contains another - // Purposefully self-exclusive - // As in, an element does not contain itself - contains = hasCompare || rnative.test( docElem.contains ) ? - function( a, b ) { - var adown = a.nodeType === 9 ? a.documentElement : a, - bup = b && b.parentNode; - return a === bup || !!( bup && bup.nodeType === 1 && ( - adown.contains ? - adown.contains( bup ) : - a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 - )); - } : - function( a, b ) { - if ( b ) { - while ( (b = b.parentNode) ) { - if ( b === a ) { - return true; - } - } - } - return false; - }; - - /* Sorting - ---------------------------------------------------------------------- */ - - // Document order sorting - sortOrder = hasCompare ? - function( a, b ) { - - // Flag for duplicate removal - if ( a === b ) { - hasDuplicate = true; - return 0; - } - - // Sort on method existence if only one input has compareDocumentPosition - var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; - if ( compare ) { - return compare; - } - - // Calculate position if both inputs belong to the same document - compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? - a.compareDocumentPosition( b ) : - - // Otherwise we know they are disconnected - 1; - - // Disconnected nodes - if ( compare & 1 || - (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { - - // Choose the first element that is related to our preferred document - if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { - return -1; - } - if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { - return 1; - } - - // Maintain original order - return sortInput ? - ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : - 0; - } - - return compare & 4 ? -1 : 1; - } : - function( a, b ) { - // Exit early if the nodes are identical - if ( a === b ) { - hasDuplicate = true; - return 0; - } - - var cur, - i = 0, - aup = a.parentNode, - bup = b.parentNode, - ap = [ a ], - bp = [ b ]; - - // Parentless nodes are either documents or disconnected - if ( !aup || !bup ) { - return a === document ? -1 : - b === document ? 1 : - aup ? -1 : - bup ? 1 : - sortInput ? - ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : - 0; - - // If the nodes are siblings, we can do a quick check - } else if ( aup === bup ) { - return siblingCheck( a, b ); - } - - // Otherwise we need full lists of their ancestors for comparison - cur = a; - while ( (cur = cur.parentNode) ) { - ap.unshift( cur ); - } - cur = b; - while ( (cur = cur.parentNode) ) { - bp.unshift( cur ); - } - - // Walk down the tree looking for a discrepancy - while ( ap[i] === bp[i] ) { - i++; - } - - return i ? - // Do a sibling check if the nodes have a common ancestor - siblingCheck( ap[i], bp[i] ) : - - // Otherwise nodes in our document sort first - ap[i] === preferredDoc ? -1 : - bp[i] === preferredDoc ? 1 : - 0; - }; - - return document; - }; - - Sizzle.matches = function( expr, elements ) { - return Sizzle( expr, null, null, elements ); - }; - - Sizzle.matchesSelector = function( elem, expr ) { - // Set document vars if needed - if ( ( elem.ownerDocument || elem ) !== document ) { - setDocument( elem ); - } - - // Make sure that attribute selectors are quoted - expr = expr.replace( rattributeQuotes, "='$1']" ); - - if ( support.matchesSelector && documentIsHTML && - !compilerCache[ expr + " " ] && - ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && - ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { - - try { - var ret = matches.call( elem, expr ); - - // IE 9's matchesSelector returns false on disconnected nodes - if ( ret || support.disconnectedMatch || - // As well, disconnected nodes are said to be in a document - // fragment in IE 9 - elem.document && elem.document.nodeType !== 11 ) { - return ret; - } - } catch (e) {} - } - - return Sizzle( expr, document, null, [ elem ] ).length > 0; - }; - - Sizzle.contains = function( context, elem ) { - // Set document vars if needed - if ( ( context.ownerDocument || context ) !== document ) { - setDocument( context ); - } - return contains( context, elem ); - }; - - Sizzle.attr = function( elem, name ) { - // Set document vars if needed - if ( ( elem.ownerDocument || elem ) !== document ) { - setDocument( elem ); - } - - var fn = Expr.attrHandle[ name.toLowerCase() ], - // Don't get fooled by Object.prototype properties (jQuery #13807) - val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? - fn( elem, name, !documentIsHTML ) : - undefined; - - return val !== undefined ? - val : - support.attributes || !documentIsHTML ? - elem.getAttribute( name ) : - (val = elem.getAttributeNode(name)) && val.specified ? - val.value : - null; - }; - - Sizzle.escape = function( sel ) { - return (sel + "").replace( rcssescape, fcssescape ); - }; - - Sizzle.error = function( msg ) { - throw new Error( "Syntax error, unrecognized expression: " + msg ); - }; - - /** - * Document sorting and removing duplicates - * @param {ArrayLike} results - */ - Sizzle.uniqueSort = function( results ) { - var elem, - duplicates = [], - j = 0, - i = 0; - - // Unless we *know* we can detect duplicates, assume their presence - hasDuplicate = !support.detectDuplicates; - sortInput = !support.sortStable && results.slice( 0 ); - results.sort( sortOrder ); - - if ( hasDuplicate ) { - while ( (elem = results[i++]) ) { - if ( elem === results[ i ] ) { - j = duplicates.push( i ); - } - } - while ( j-- ) { - results.splice( duplicates[ j ], 1 ); - } - } - - // Clear input after sorting to release objects - // See https://github.com/jquery/sizzle/pull/225 - sortInput = null; - - return results; - }; - - /** - * Utility function for retrieving the text value of an array of DOM nodes - * @param {Array|Element} elem - */ - getText = Sizzle.getText = function( elem ) { - var node, - ret = "", - i = 0, - nodeType = elem.nodeType; - - if ( !nodeType ) { - // If no nodeType, this is expected to be an array - while ( (node = elem[i++]) ) { - // Do not traverse comment nodes - ret += getText( node ); - } - } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { - // Use textContent for elements - // innerText usage removed for consistency of new lines (jQuery #11153) - if ( typeof elem.textContent === "string" ) { - return elem.textContent; - } else { - // Traverse its children - for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { - ret += getText( elem ); - } - } - } else if ( nodeType === 3 || nodeType === 4 ) { - return elem.nodeValue; - } - // Do not include comment or processing instruction nodes - - return ret; - }; - - Expr = Sizzle.selectors = { - - // Can be adjusted by the user - cacheLength: 50, - - createPseudo: markFunction, - - match: matchExpr, - - attrHandle: {}, - - find: {}, - - relative: { - ">": { dir: "parentNode", first: true }, - " ": { dir: "parentNode" }, - "+": { dir: "previousSibling", first: true }, - "~": { dir: "previousSibling" } - }, - - preFilter: { - "ATTR": function( match ) { - match[1] = match[1].replace( runescape, funescape ); - - // Move the given value to match[3] whether quoted or unquoted - match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); - - if ( match[2] === "~=" ) { - match[3] = " " + match[3] + " "; - } - - return match.slice( 0, 4 ); - }, - - "CHILD": function( match ) { - /* matches from matchExpr["CHILD"] - 1 type (only|nth|...) - 2 what (child|of-type) - 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) - 4 xn-component of xn+y argument ([+-]?\d*n|) - 5 sign of xn-component - 6 x of xn-component - 7 sign of y-component - 8 y of y-component - */ - match[1] = match[1].toLowerCase(); - - if ( match[1].slice( 0, 3 ) === "nth" ) { - // nth-* requires argument - if ( !match[3] ) { - Sizzle.error( match[0] ); - } - - // numeric x and y parameters for Expr.filter.CHILD - // remember that false/true cast respectively to 0/1 - match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); - match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); - - // other types prohibit arguments - } else if ( match[3] ) { - Sizzle.error( match[0] ); - } - - return match; - }, - - "PSEUDO": function( match ) { - var excess, - unquoted = !match[6] && match[2]; - - if ( matchExpr["CHILD"].test( match[0] ) ) { - return null; - } - - // Accept quoted arguments as-is - if ( match[3] ) { - match[2] = match[4] || match[5] || ""; - - // Strip excess characters from unquoted arguments - } else if ( unquoted && rpseudo.test( unquoted ) && - // Get excess from tokenize (recursively) - (excess = tokenize( unquoted, true )) && - // advance to the next closing parenthesis - (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { - - // excess is a negative index - match[0] = match[0].slice( 0, excess ); - match[2] = unquoted.slice( 0, excess ); - } - - // Return only captures needed by the pseudo filter method (type and argument) - return match.slice( 0, 3 ); - } - }, - - filter: { - - "TAG": function( nodeNameSelector ) { - var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); - return nodeNameSelector === "*" ? - function() { return true; } : - function( elem ) { - return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; - }; - }, - - "CLASS": function( className ) { - var pattern = classCache[ className + " " ]; - - return pattern || - (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && - classCache( className, function( elem ) { - return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); - }); - }, - - "ATTR": function( name, operator, check ) { - return function( elem ) { - var result = Sizzle.attr( elem, name ); - - if ( result == null ) { - return operator === "!="; - } - if ( !operator ) { - return true; - } - - result += ""; - - return operator === "=" ? result === check : - operator === "!=" ? result !== check : - operator === "^=" ? check && result.indexOf( check ) === 0 : - operator === "*=" ? check && result.indexOf( check ) > -1 : - operator === "$=" ? check && result.slice( -check.length ) === check : - operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : - operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : - false; - }; - }, - - "CHILD": function( type, what, argument, first, last ) { - var simple = type.slice( 0, 3 ) !== "nth", - forward = type.slice( -4 ) !== "last", - ofType = what === "of-type"; - - return first === 1 && last === 0 ? - - // Shortcut for :nth-*(n) - function( elem ) { - return !!elem.parentNode; - } : - - function( elem, context, xml ) { - var cache, uniqueCache, outerCache, node, nodeIndex, start, - dir = simple !== forward ? "nextSibling" : "previousSibling", - parent = elem.parentNode, - name = ofType && elem.nodeName.toLowerCase(), - useCache = !xml && !ofType, - diff = false; - - if ( parent ) { - - // :(first|last|only)-(child|of-type) - if ( simple ) { - while ( dir ) { - node = elem; - while ( (node = node[ dir ]) ) { - if ( ofType ? - node.nodeName.toLowerCase() === name : - node.nodeType === 1 ) { - - return false; - } - } - // Reverse direction for :only-* (if we haven't yet done so) - start = dir = type === "only" && !start && "nextSibling"; - } - return true; - } - - start = [ forward ? parent.firstChild : parent.lastChild ]; - - // non-xml :nth-child(...) stores cache data on `parent` - if ( forward && useCache ) { - - // Seek `elem` from a previously-cached index - - // ...in a gzip-friendly way - node = parent; - outerCache = node[ expando ] || (node[ expando ] = {}); - - // Support: IE <9 only - // Defend against cloned attroperties (jQuery gh-1709) - uniqueCache = outerCache[ node.uniqueID ] || - (outerCache[ node.uniqueID ] = {}); - - cache = uniqueCache[ type ] || []; - nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; - diff = nodeIndex && cache[ 2 ]; - node = nodeIndex && parent.childNodes[ nodeIndex ]; - - while ( (node = ++nodeIndex && node && node[ dir ] || - - // Fallback to seeking `elem` from the start - (diff = nodeIndex = 0) || start.pop()) ) { - - // When found, cache indexes on `parent` and break - if ( node.nodeType === 1 && ++diff && node === elem ) { - uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; - break; - } - } - - } else { - // Use previously-cached element index if available - if ( useCache ) { - // ...in a gzip-friendly way - node = elem; - outerCache = node[ expando ] || (node[ expando ] = {}); - - // Support: IE <9 only - // Defend against cloned attroperties (jQuery gh-1709) - uniqueCache = outerCache[ node.uniqueID ] || - (outerCache[ node.uniqueID ] = {}); - - cache = uniqueCache[ type ] || []; - nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; - diff = nodeIndex; - } - - // xml :nth-child(...) - // or :nth-last-child(...) or :nth(-last)?-of-type(...) - if ( diff === false ) { - // Use the same loop as above to seek `elem` from the start - while ( (node = ++nodeIndex && node && node[ dir ] || - (diff = nodeIndex = 0) || start.pop()) ) { - - if ( ( ofType ? - node.nodeName.toLowerCase() === name : - node.nodeType === 1 ) && - ++diff ) { - - // Cache the index of each encountered element - if ( useCache ) { - outerCache = node[ expando ] || (node[ expando ] = {}); - - // Support: IE <9 only - // Defend against cloned attroperties (jQuery gh-1709) - uniqueCache = outerCache[ node.uniqueID ] || - (outerCache[ node.uniqueID ] = {}); - - uniqueCache[ type ] = [ dirruns, diff ]; - } - - if ( node === elem ) { - break; - } - } - } - } - } - - // Incorporate the offset, then check against cycle size - diff -= last; - return diff === first || ( diff % first === 0 && diff / first >= 0 ); - } - }; - }, - - "PSEUDO": function( pseudo, argument ) { - // pseudo-class names are case-insensitive - // http://www.w3.org/TR/selectors/#pseudo-classes - // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters - // Remember that setFilters inherits from pseudos - var args, - fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || - Sizzle.error( "unsupported pseudo: " + pseudo ); - - // The user may use createPseudo to indicate that - // arguments are needed to create the filter function - // just as Sizzle does - if ( fn[ expando ] ) { - return fn( argument ); - } - - // But maintain support for old signatures - if ( fn.length > 1 ) { - args = [ pseudo, pseudo, "", argument ]; - return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? - markFunction(function( seed, matches ) { - var idx, - matched = fn( seed, argument ), - i = matched.length; - while ( i-- ) { - idx = indexOf( seed, matched[i] ); - seed[ idx ] = !( matches[ idx ] = matched[i] ); - } - }) : - function( elem ) { - return fn( elem, 0, args ); - }; - } - - return fn; - } - }, - - pseudos: { - // Potentially complex pseudos - "not": markFunction(function( selector ) { - // Trim the selector passed to compile - // to avoid treating leading and trailing - // spaces as combinators - var input = [], - results = [], - matcher = compile( selector.replace( rtrim, "$1" ) ); - - return matcher[ expando ] ? - markFunction(function( seed, matches, context, xml ) { - var elem, - unmatched = matcher( seed, null, xml, [] ), - i = seed.length; - - // Match elements unmatched by `matcher` - while ( i-- ) { - if ( (elem = unmatched[i]) ) { - seed[i] = !(matches[i] = elem); - } - } - }) : - function( elem, context, xml ) { - input[0] = elem; - matcher( input, null, xml, results ); - // Don't keep the element (issue #299) - input[0] = null; - return !results.pop(); - }; - }), - - "has": markFunction(function( selector ) { - return function( elem ) { - return Sizzle( selector, elem ).length > 0; - }; - }), - - "contains": markFunction(function( text ) { - text = text.replace( runescape, funescape ); - return function( elem ) { - return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; - }; - }), - - // "Whether an element is represented by a :lang() selector - // is based solely on the element's language value - // being equal to the identifier C, - // or beginning with the identifier C immediately followed by "-". - // The matching of C against the element's language value is performed case-insensitively. - // The identifier C does not have to be a valid language name." - // http://www.w3.org/TR/selectors/#lang-pseudo - "lang": markFunction( function( lang ) { - // lang value must be a valid identifier - if ( !ridentifier.test(lang || "") ) { - Sizzle.error( "unsupported lang: " + lang ); - } - lang = lang.replace( runescape, funescape ).toLowerCase(); - return function( elem ) { - var elemLang; - do { - if ( (elemLang = documentIsHTML ? - elem.lang : - elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { - - elemLang = elemLang.toLowerCase(); - return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; - } - } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); - return false; - }; - }), - - // Miscellaneous - "target": function( elem ) { - var hash = window.location && window.location.hash; - return hash && hash.slice( 1 ) === elem.id; - }, - - "root": function( elem ) { - return elem === docElem; - }, - - "focus": function( elem ) { - return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); - }, - - // Boolean properties - "enabled": createDisabledPseudo( false ), - "disabled": createDisabledPseudo( true ), - - "checked": function( elem ) { - // In CSS3, :checked should return both checked and selected elements - // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked - var nodeName = elem.nodeName.toLowerCase(); - return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); - }, - - "selected": function( elem ) { - // Accessing this property makes selected-by-default - // options in Safari work properly - if ( elem.parentNode ) { - elem.parentNode.selectedIndex; - } - - return elem.selected === true; - }, - - // Contents - "empty": function( elem ) { - // http://www.w3.org/TR/selectors/#empty-pseudo - // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), - // but not by others (comment: 8; processing instruction: 7; etc.) - // nodeType < 6 works because attributes (2) do not appear as children - for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { - if ( elem.nodeType < 6 ) { - return false; - } - } - return true; - }, - - "parent": function( elem ) { - return !Expr.pseudos["empty"]( elem ); - }, - - // Element/input types - "header": function( elem ) { - return rheader.test( elem.nodeName ); - }, - - "input": function( elem ) { - return rinputs.test( elem.nodeName ); - }, - - "button": function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && elem.type === "button" || name === "button"; - }, - - "text": function( elem ) { - var attr; - return elem.nodeName.toLowerCase() === "input" && - elem.type === "text" && - - // Support: IE<8 - // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" - ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); - }, - - // Position-in-collection - "first": createPositionalPseudo(function() { - return [ 0 ]; - }), - - "last": createPositionalPseudo(function( matchIndexes, length ) { - return [ length - 1 ]; - }), - - "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { - return [ argument < 0 ? argument + length : argument ]; - }), - - "even": createPositionalPseudo(function( matchIndexes, length ) { - var i = 0; - for ( ; i < length; i += 2 ) { - matchIndexes.push( i ); - } - return matchIndexes; - }), - - "odd": createPositionalPseudo(function( matchIndexes, length ) { - var i = 1; - for ( ; i < length; i += 2 ) { - matchIndexes.push( i ); - } - return matchIndexes; - }), - - "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { - var i = argument < 0 ? argument + length : argument; - for ( ; --i >= 0; ) { - matchIndexes.push( i ); - } - return matchIndexes; - }), - - "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { - var i = argument < 0 ? argument + length : argument; - for ( ; ++i < length; ) { - matchIndexes.push( i ); - } - return matchIndexes; - }) - } - }; - - Expr.pseudos["nth"] = Expr.pseudos["eq"]; - -// Add button/input type pseudos - for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { - Expr.pseudos[ i ] = createInputPseudo( i ); - } - for ( i in { submit: true, reset: true } ) { - Expr.pseudos[ i ] = createButtonPseudo( i ); - } - -// Easy API for creating new setFilters - function setFilters() {} - setFilters.prototype = Expr.filters = Expr.pseudos; - Expr.setFilters = new setFilters(); - - tokenize = Sizzle.tokenize = function( selector, parseOnly ) { - var matched, match, tokens, type, - soFar, groups, preFilters, - cached = tokenCache[ selector + " " ]; - - if ( cached ) { - return parseOnly ? 0 : cached.slice( 0 ); - } - - soFar = selector; - groups = []; - preFilters = Expr.preFilter; - - while ( soFar ) { - - // Comma and first run - if ( !matched || (match = rcomma.exec( soFar )) ) { - if ( match ) { - // Don't consume trailing commas as valid - soFar = soFar.slice( match[0].length ) || soFar; - } - groups.push( (tokens = []) ); - } - - matched = false; - - // Combinators - if ( (match = rcombinators.exec( soFar )) ) { - matched = match.shift(); - tokens.push({ - value: matched, - // Cast descendant combinators to space - type: match[0].replace( rtrim, " " ) - }); - soFar = soFar.slice( matched.length ); - } - - // Filters - for ( type in Expr.filter ) { - if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || - (match = preFilters[ type ]( match ))) ) { - matched = match.shift(); - tokens.push({ - value: matched, - type: type, - matches: match - }); - soFar = soFar.slice( matched.length ); - } - } - - if ( !matched ) { - break; - } - } - - // Return the length of the invalid excess - // if we're just parsing - // Otherwise, throw an error or return tokens - return parseOnly ? - soFar.length : - soFar ? - Sizzle.error( selector ) : - // Cache the tokens - tokenCache( selector, groups ).slice( 0 ); - }; - - function toSelector( tokens ) { - var i = 0, - len = tokens.length, - selector = ""; - for ( ; i < len; i++ ) { - selector += tokens[i].value; - } - return selector; - } - - function addCombinator( matcher, combinator, base ) { - var dir = combinator.dir, - skip = combinator.next, - key = skip || dir, - checkNonElements = base && key === "parentNode", - doneName = done++; - - return combinator.first ? - // Check against closest ancestor/preceding element - function( elem, context, xml ) { - while ( (elem = elem[ dir ]) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - return matcher( elem, context, xml ); - } - } - return false; - } : - - // Check against all ancestor/preceding elements - function( elem, context, xml ) { - var oldCache, uniqueCache, outerCache, - newCache = [ dirruns, doneName ]; - - // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching - if ( xml ) { - while ( (elem = elem[ dir ]) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - if ( matcher( elem, context, xml ) ) { - return true; - } - } - } - } else { - while ( (elem = elem[ dir ]) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - outerCache = elem[ expando ] || (elem[ expando ] = {}); - - // Support: IE <9 only - // Defend against cloned attroperties (jQuery gh-1709) - uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {}); - - if ( skip && skip === elem.nodeName.toLowerCase() ) { - elem = elem[ dir ] || elem; - } else if ( (oldCache = uniqueCache[ key ]) && - oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { - - // Assign to newCache so results back-propagate to previous elements - return (newCache[ 2 ] = oldCache[ 2 ]); - } else { - // Reuse newcache so results back-propagate to previous elements - uniqueCache[ key ] = newCache; - - // A match means we're done; a fail means we have to keep checking - if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { - return true; - } - } - } - } - } - return false; - }; - } - - function elementMatcher( matchers ) { - return matchers.length > 1 ? - function( elem, context, xml ) { - var i = matchers.length; - while ( i-- ) { - if ( !matchers[i]( elem, context, xml ) ) { - return false; - } - } - return true; - } : - matchers[0]; - } - - function multipleContexts( selector, contexts, results ) { - var i = 0, - len = contexts.length; - for ( ; i < len; i++ ) { - Sizzle( selector, contexts[i], results ); - } - return results; - } - - function condense( unmatched, map, filter, context, xml ) { - var elem, - newUnmatched = [], - i = 0, - len = unmatched.length, - mapped = map != null; - - for ( ; i < len; i++ ) { - if ( (elem = unmatched[i]) ) { - if ( !filter || filter( elem, context, xml ) ) { - newUnmatched.push( elem ); - if ( mapped ) { - map.push( i ); - } - } - } - } - - return newUnmatched; - } - - function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { - if ( postFilter && !postFilter[ expando ] ) { - postFilter = setMatcher( postFilter ); - } - if ( postFinder && !postFinder[ expando ] ) { - postFinder = setMatcher( postFinder, postSelector ); - } - return markFunction(function( seed, results, context, xml ) { - var temp, i, elem, - preMap = [], - postMap = [], - preexisting = results.length, - - // Get initial elements from seed or context - elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), - - // Prefilter to get matcher input, preserving a map for seed-results synchronization - matcherIn = preFilter && ( seed || !selector ) ? - condense( elems, preMap, preFilter, context, xml ) : - elems, - - matcherOut = matcher ? - // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, - postFinder || ( seed ? preFilter : preexisting || postFilter ) ? - - // ...intermediate processing is necessary - [] : - - // ...otherwise use results directly - results : - matcherIn; - - // Find primary matches - if ( matcher ) { - matcher( matcherIn, matcherOut, context, xml ); - } - - // Apply postFilter - if ( postFilter ) { - temp = condense( matcherOut, postMap ); - postFilter( temp, [], context, xml ); - - // Un-match failing elements by moving them back to matcherIn - i = temp.length; - while ( i-- ) { - if ( (elem = temp[i]) ) { - matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); - } - } - } - - if ( seed ) { - if ( postFinder || preFilter ) { - if ( postFinder ) { - // Get the final matcherOut by condensing this intermediate into postFinder contexts - temp = []; - i = matcherOut.length; - while ( i-- ) { - if ( (elem = matcherOut[i]) ) { - // Restore matcherIn since elem is not yet a final match - temp.push( (matcherIn[i] = elem) ); - } - } - postFinder( null, (matcherOut = []), temp, xml ); - } - - // Move matched elements from seed to results to keep them synchronized - i = matcherOut.length; - while ( i-- ) { - if ( (elem = matcherOut[i]) && - (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) { - - seed[temp] = !(results[temp] = elem); - } - } - } - - // Add elements to results, through postFinder if defined - } else { - matcherOut = condense( - matcherOut === results ? - matcherOut.splice( preexisting, matcherOut.length ) : - matcherOut - ); - if ( postFinder ) { - postFinder( null, results, matcherOut, xml ); - } else { - push.apply( results, matcherOut ); - } - } - }); - } - - function matcherFromTokens( tokens ) { - var checkContext, matcher, j, - len = tokens.length, - leadingRelative = Expr.relative[ tokens[0].type ], - implicitRelative = leadingRelative || Expr.relative[" "], - i = leadingRelative ? 1 : 0, - - // The foundational matcher ensures that elements are reachable from top-level context(s) - matchContext = addCombinator( function( elem ) { - return elem === checkContext; - }, implicitRelative, true ), - matchAnyContext = addCombinator( function( elem ) { - return indexOf( checkContext, elem ) > -1; - }, implicitRelative, true ), - matchers = [ function( elem, context, xml ) { - var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( - (checkContext = context).nodeType ? - matchContext( elem, context, xml ) : - matchAnyContext( elem, context, xml ) ); - // Avoid hanging onto element (issue #299) - checkContext = null; - return ret; - } ]; - - for ( ; i < len; i++ ) { - if ( (matcher = Expr.relative[ tokens[i].type ]) ) { - matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; - } else { - matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); - - // Return special upon seeing a positional matcher - if ( matcher[ expando ] ) { - // Find the next relative operator (if any) for proper handling - j = ++i; - for ( ; j < len; j++ ) { - if ( Expr.relative[ tokens[j].type ] ) { - break; - } - } - return setMatcher( - i > 1 && elementMatcher( matchers ), - i > 1 && toSelector( - // If the preceding token was a descendant combinator, insert an implicit any-element `*` - tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) - ).replace( rtrim, "$1" ), - matcher, - i < j && matcherFromTokens( tokens.slice( i, j ) ), - j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), - j < len && toSelector( tokens ) - ); - } - matchers.push( matcher ); - } - } - - return elementMatcher( matchers ); - } - - function matcherFromGroupMatchers( elementMatchers, setMatchers ) { - var bySet = setMatchers.length > 0, - byElement = elementMatchers.length > 0, - superMatcher = function( seed, context, xml, results, outermost ) { - var elem, j, matcher, - matchedCount = 0, - i = "0", - unmatched = seed && [], - setMatched = [], - contextBackup = outermostContext, - // We must always have either seed elements or outermost context - elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), - // Use integer dirruns iff this is the outermost matcher - dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), - len = elems.length; - - if ( outermost ) { - outermostContext = context === document || context || outermost; - } - - // Add elements passing elementMatchers directly to results - // Support: IE<9, Safari - // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id - for ( ; i !== len && (elem = elems[i]) != null; i++ ) { - if ( byElement && elem ) { - j = 0; - if ( !context && elem.ownerDocument !== document ) { - setDocument( elem ); - xml = !documentIsHTML; - } - while ( (matcher = elementMatchers[j++]) ) { - if ( matcher( elem, context || document, xml) ) { - results.push( elem ); - break; - } - } - if ( outermost ) { - dirruns = dirrunsUnique; - } - } - - // Track unmatched elements for set filters - if ( bySet ) { - // They will have gone through all possible matchers - if ( (elem = !matcher && elem) ) { - matchedCount--; - } - - // Lengthen the array for every element, matched or not - if ( seed ) { - unmatched.push( elem ); - } - } - } - - // `i` is now the count of elements visited above, and adding it to `matchedCount` - // makes the latter nonnegative. - matchedCount += i; - - // Apply set filters to unmatched elements - // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` - // equals `i`), unless we didn't visit _any_ elements in the above loop because we have - // no element matchers and no seed. - // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that - // case, which will result in a "00" `matchedCount` that differs from `i` but is also - // numerically zero. - if ( bySet && i !== matchedCount ) { - j = 0; - while ( (matcher = setMatchers[j++]) ) { - matcher( unmatched, setMatched, context, xml ); - } - - if ( seed ) { - // Reintegrate element matches to eliminate the need for sorting - if ( matchedCount > 0 ) { - while ( i-- ) { - if ( !(unmatched[i] || setMatched[i]) ) { - setMatched[i] = pop.call( results ); - } - } - } - - // Discard index placeholder values to get only actual matches - setMatched = condense( setMatched ); - } - - // Add matches to results - push.apply( results, setMatched ); - - // Seedless set matches succeeding multiple successful matchers stipulate sorting - if ( outermost && !seed && setMatched.length > 0 && - ( matchedCount + setMatchers.length ) > 1 ) { - - Sizzle.uniqueSort( results ); - } - } - - // Override manipulation of globals by nested matchers - if ( outermost ) { - dirruns = dirrunsUnique; - outermostContext = contextBackup; - } - - return unmatched; - }; - - return bySet ? - markFunction( superMatcher ) : - superMatcher; - } - - compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { - var i, - setMatchers = [], - elementMatchers = [], - cached = compilerCache[ selector + " " ]; - - if ( !cached ) { - // Generate a function of recursive functions that can be used to check each element - if ( !match ) { - match = tokenize( selector ); - } - i = match.length; - while ( i-- ) { - cached = matcherFromTokens( match[i] ); - if ( cached[ expando ] ) { - setMatchers.push( cached ); - } else { - elementMatchers.push( cached ); - } - } - - // Cache the compiled function - cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); - - // Save selector and tokenization - cached.selector = selector; - } - return cached; - }; - - /** - * A low-level selection function that works with Sizzle's compiled - * selector functions - * @param {String|Function} selector A selector or a pre-compiled - * selector function built with Sizzle.compile - * @param {Element} context - * @param {Array} [results] - * @param {Array} [seed] A set of elements to match against - */ - select = Sizzle.select = function( selector, context, results, seed ) { - var i, tokens, token, type, find, - compiled = typeof selector === "function" && selector, - match = !seed && tokenize( (selector = compiled.selector || selector) ); - - results = results || []; - - // Try to minimize operations if there is only one selector in the list and no seed - // (the latter of which guarantees us context) - if ( match.length === 1 ) { - - // Reduce context if the leading compound selector is an ID - tokens = match[0] = match[0].slice( 0 ); - if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && - context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { - - context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; - if ( !context ) { - return results; - - // Precompiled matchers will still verify ancestry, so step up a level - } else if ( compiled ) { - context = context.parentNode; - } - - selector = selector.slice( tokens.shift().value.length ); - } - - // Fetch a seed set for right-to-left matching - i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; - while ( i-- ) { - token = tokens[i]; - - // Abort if we hit a combinator - if ( Expr.relative[ (type = token.type) ] ) { - break; - } - if ( (find = Expr.find[ type ]) ) { - // Search, expanding context for leading sibling combinators - if ( (seed = find( - token.matches[0].replace( runescape, funescape ), - rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context - )) ) { - - // If seed is empty or no tokens remain, we can return early - tokens.splice( i, 1 ); - selector = seed.length && toSelector( tokens ); - if ( !selector ) { - push.apply( results, seed ); - return results; - } - - break; - } - } - } - } - - // Compile and execute a filtering function if one is not provided - // Provide `match` to avoid retokenization if we modified the selector above - ( compiled || compile( selector, match ) )( - seed, - context, - !documentIsHTML, - results, - !context || rsibling.test( selector ) && testContext( context.parentNode ) || context - ); - return results; - }; - -// One-time assignments - -// Sort stability - support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; - -// Support: Chrome 14-35+ -// Always assume duplicates if they aren't passed to the comparison function - support.detectDuplicates = !!hasDuplicate; - -// Initialize against the default document - setDocument(); - -// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) -// Detached nodes confoundingly follow *each other* - support.sortDetached = assert(function( el ) { - // Should return 1, but returns 4 (following) - return el.compareDocumentPosition( document.createElement("fieldset") ) & 1; - }); - -// Support: IE<8 -// Prevent attribute/property "interpolation" -// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx - if ( !assert(function( el ) { - el.innerHTML = ""; - return el.firstChild.getAttribute("href") === "#" ; - }) ) { - addHandle( "type|href|height|width", function( elem, name, isXML ) { - if ( !isXML ) { - return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); - } - }); - } - -// Support: IE<9 -// Use defaultValue in place of getAttribute("value") - if ( !support.attributes || !assert(function( el ) { - el.innerHTML = ""; - el.firstChild.setAttribute( "value", "" ); - return el.firstChild.getAttribute( "value" ) === ""; - }) ) { - addHandle( "value", function( elem, name, isXML ) { - if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { - return elem.defaultValue; - } - }); - } - -// Support: IE<9 -// Use getAttributeNode to fetch booleans when getAttribute lies - if ( !assert(function( el ) { - return el.getAttribute("disabled") == null; - }) ) { - addHandle( booleans, function( elem, name, isXML ) { - var val; - if ( !isXML ) { - return elem[ name ] === true ? name.toLowerCase() : - (val = elem.getAttributeNode( name )) && val.specified ? - val.value : - null; - } - }); - } - - return Sizzle; - - })( window ); - - - - jQuery.find = Sizzle; - jQuery.expr = Sizzle.selectors; - -// Deprecated - jQuery.expr[ ":" ] = jQuery.expr.pseudos; - jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; - jQuery.text = Sizzle.getText; - jQuery.isXMLDoc = Sizzle.isXML; - jQuery.contains = Sizzle.contains; - jQuery.escapeSelector = Sizzle.escape; - - - - - var dir = function( elem, dir, until ) { - var matched = [], - truncate = until !== undefined; - - while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { - if ( elem.nodeType === 1 ) { - if ( truncate && jQuery( elem ).is( until ) ) { - break; - } - matched.push( elem ); - } - } - return matched; - }; - - - var siblings = function( n, elem ) { - var matched = []; - - for ( ; n; n = n.nextSibling ) { - if ( n.nodeType === 1 && n !== elem ) { - matched.push( n ); - } - } - - return matched; - }; - - - var rneedsContext = jQuery.expr.match.needsContext; - - - - function nodeName( elem, name ) { - - return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); - - }; - var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i ); - - - -// Implement the identical functionality for filter and not - function winnow( elements, qualifier, not ) { - if ( isFunction( qualifier ) ) { - return jQuery.grep( elements, function( elem, i ) { - return !!qualifier.call( elem, i, elem ) !== not; - } ); - } - - // Single element - if ( qualifier.nodeType ) { - return jQuery.grep( elements, function( elem ) { - return ( elem === qualifier ) !== not; - } ); - } - - // Arraylike of elements (jQuery, arguments, Array) - if ( typeof qualifier !== "string" ) { - return jQuery.grep( elements, function( elem ) { - return ( indexOf.call( qualifier, elem ) > -1 ) !== not; - } ); - } - - // Filtered directly for both simple and complex selectors - return jQuery.filter( qualifier, elements, not ); - } - - jQuery.filter = function( expr, elems, not ) { - var elem = elems[ 0 ]; - - if ( not ) { - expr = ":not(" + expr + ")"; - } - - if ( elems.length === 1 && elem.nodeType === 1 ) { - return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : []; - } - - return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { - return elem.nodeType === 1; - } ) ); - }; - - jQuery.fn.extend( { - find: function( selector ) { - var i, ret, - len = this.length, - self = this; - - if ( typeof selector !== "string" ) { - return this.pushStack( jQuery( selector ).filter( function() { - for ( i = 0; i < len; i++ ) { - if ( jQuery.contains( self[ i ], this ) ) { - return true; - } - } - } ) ); - } - - ret = this.pushStack( [] ); - - for ( i = 0; i < len; i++ ) { - jQuery.find( selector, self[ i ], ret ); - } - - return len > 1 ? jQuery.uniqueSort( ret ) : ret; - }, - filter: function( selector ) { - return this.pushStack( winnow( this, selector || [], false ) ); - }, - not: function( selector ) { - return this.pushStack( winnow( this, selector || [], true ) ); - }, - is: function( selector ) { - return !!winnow( - this, - - // If this is a positional/relative selector, check membership in the returned set - // so $("p:first").is("p:last") won't return true for a doc with two "p". - typeof selector === "string" && rneedsContext.test( selector ) ? - jQuery( selector ) : - selector || [], - false - ).length; - } - } ); - - -// Initialize a jQuery object - - -// A central reference to the root jQuery(document) - var rootjQuery, - - // A simple way to check for HTML strings - // Prioritize #id over to avoid XSS via location.hash (#9521) - // Strict HTML recognition (#11290: must start with <) - // Shortcut simple #id case for speed - rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, - - init = jQuery.fn.init = function( selector, context, root ) { - var match, elem; - - // HANDLE: $(""), $(null), $(undefined), $(false) - if ( !selector ) { - return this; - } - - // Method init() accepts an alternate rootjQuery - // so migrate can support jQuery.sub (gh-2101) - root = root || rootjQuery; - - // Handle HTML strings - if ( typeof selector === "string" ) { - if ( selector[ 0 ] === "<" && - selector[ selector.length - 1 ] === ">" && - selector.length >= 3 ) { - - // Assume that strings that start and end with <> are HTML and skip the regex check - match = [ null, selector, null ]; - - } else { - match = rquickExpr.exec( selector ); - } - - // Match html or make sure no context is specified for #id - if ( match && ( match[ 1 ] || !context ) ) { - - // HANDLE: $(html) -> $(array) - if ( match[ 1 ] ) { - context = context instanceof jQuery ? context[ 0 ] : context; - - // Option to run scripts is true for back-compat - // Intentionally let the error be thrown if parseHTML is not present - jQuery.merge( this, jQuery.parseHTML( - match[ 1 ], - context && context.nodeType ? context.ownerDocument || context : document, - true - ) ); - - // HANDLE: $(html, props) - if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { - for ( match in context ) { - - // Properties of context are called as methods if possible - if ( isFunction( this[ match ] ) ) { - this[ match ]( context[ match ] ); - - // ...and otherwise set as attributes - } else { - this.attr( match, context[ match ] ); - } - } - } - - return this; - - // HANDLE: $(#id) - } else { - elem = document.getElementById( match[ 2 ] ); - - if ( elem ) { - - // Inject the element directly into the jQuery object - this[ 0 ] = elem; - this.length = 1; - } - return this; - } - - // HANDLE: $(expr, $(...)) - } else if ( !context || context.jquery ) { - return ( context || root ).find( selector ); - - // HANDLE: $(expr, context) - // (which is just equivalent to: $(context).find(expr) - } else { - return this.constructor( context ).find( selector ); - } - - // HANDLE: $(DOMElement) - } else if ( selector.nodeType ) { - this[ 0 ] = selector; - this.length = 1; - return this; - - // HANDLE: $(function) - // Shortcut for document ready - } else if ( isFunction( selector ) ) { - return root.ready !== undefined ? - root.ready( selector ) : - - // Execute immediately if ready is not present - selector( jQuery ); - } - - return jQuery.makeArray( selector, this ); - }; - -// Give the init function the jQuery prototype for later instantiation - init.prototype = jQuery.fn; - -// Initialize central reference - rootjQuery = jQuery( document ); - - - var rparentsprev = /^(?:parents|prev(?:Until|All))/, - - // Methods guaranteed to produce a unique set when starting from a unique set - guaranteedUnique = { - children: true, - contents: true, - next: true, - prev: true - }; - - jQuery.fn.extend( { - has: function( target ) { - var targets = jQuery( target, this ), - l = targets.length; - - return this.filter( function() { - var i = 0; - for ( ; i < l; i++ ) { - if ( jQuery.contains( this, targets[ i ] ) ) { - return true; - } - } - } ); - }, - - closest: function( selectors, context ) { - var cur, - i = 0, - l = this.length, - matched = [], - targets = typeof selectors !== "string" && jQuery( selectors ); - - // Positional selectors never match, since there's no _selection_ context - if ( !rneedsContext.test( selectors ) ) { - for ( ; i < l; i++ ) { - for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { - - // Always skip document fragments - if ( cur.nodeType < 11 && ( targets ? - targets.index( cur ) > -1 : - - // Don't pass non-elements to Sizzle - cur.nodeType === 1 && - jQuery.find.matchesSelector( cur, selectors ) ) ) { - - matched.push( cur ); - break; - } - } - } - } - - return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); - }, - - // Determine the position of an element within the set - index: function( elem ) { - - // No argument, return index in parent - if ( !elem ) { - return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; - } - - // Index in selector - if ( typeof elem === "string" ) { - return indexOf.call( jQuery( elem ), this[ 0 ] ); - } - - // Locate the position of the desired element - return indexOf.call( this, - - // If it receives a jQuery object, the first element is used - elem.jquery ? elem[ 0 ] : elem - ); - }, - - add: function( selector, context ) { - return this.pushStack( - jQuery.uniqueSort( - jQuery.merge( this.get(), jQuery( selector, context ) ) - ) - ); - }, - - addBack: function( selector ) { - return this.add( selector == null ? - this.prevObject : this.prevObject.filter( selector ) - ); - } - } ); - - function sibling( cur, dir ) { - while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {} - return cur; - } - - jQuery.each( { - parent: function( elem ) { - var parent = elem.parentNode; - return parent && parent.nodeType !== 11 ? parent : null; - }, - parents: function( elem ) { - return dir( elem, "parentNode" ); - }, - parentsUntil: function( elem, i, until ) { - return dir( elem, "parentNode", until ); - }, - next: function( elem ) { - return sibling( elem, "nextSibling" ); - }, - prev: function( elem ) { - return sibling( elem, "previousSibling" ); - }, - nextAll: function( elem ) { - return dir( elem, "nextSibling" ); - }, - prevAll: function( elem ) { - return dir( elem, "previousSibling" ); - }, - nextUntil: function( elem, i, until ) { - return dir( elem, "nextSibling", until ); - }, - prevUntil: function( elem, i, until ) { - return dir( elem, "previousSibling", until ); - }, - siblings: function( elem ) { - return siblings( ( elem.parentNode || {} ).firstChild, elem ); - }, - children: function( elem ) { - return siblings( elem.firstChild ); - }, - contents: function( elem ) { - if ( nodeName( elem, "iframe" ) ) { - return elem.contentDocument; - } - - // Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only - // Treat the template element as a regular one in browsers that - // don't support it. - if ( nodeName( elem, "template" ) ) { - elem = elem.content || elem; - } - - return jQuery.merge( [], elem.childNodes ); - } - }, function( name, fn ) { - jQuery.fn[ name ] = function( until, selector ) { - var matched = jQuery.map( this, fn, until ); - - if ( name.slice( -5 ) !== "Until" ) { - selector = until; - } - - if ( selector && typeof selector === "string" ) { - matched = jQuery.filter( selector, matched ); - } - - if ( this.length > 1 ) { - - // Remove duplicates - if ( !guaranteedUnique[ name ] ) { - jQuery.uniqueSort( matched ); - } - - // Reverse order for parents* and prev-derivatives - if ( rparentsprev.test( name ) ) { - matched.reverse(); - } - } - - return this.pushStack( matched ); - }; - } ); - var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g ); - - - -// Convert String-formatted options into Object-formatted ones - function createOptions( options ) { - var object = {}; - jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) { - object[ flag ] = true; - } ); - return object; - } - - /* - * Create a callback list using the following parameters: - * - * options: an optional list of space-separated options that will change how - * the callback list behaves or a more traditional option object - * - * By default a callback list will act like an event callback list and can be - * "fired" multiple times. - * - * Possible options: - * - * once: will ensure the callback list can only be fired once (like a Deferred) - * - * memory: will keep track of previous values and will call any callback added - * after the list has been fired right away with the latest "memorized" - * values (like a Deferred) - * - * unique: will ensure a callback can only be added once (no duplicate in the list) - * - * stopOnFalse: interrupt callings when a callback returns false - * - */ - jQuery.Callbacks = function( options ) { - - // Convert options from String-formatted to Object-formatted if needed - // (we check in cache first) - options = typeof options === "string" ? - createOptions( options ) : - jQuery.extend( {}, options ); - - var // Flag to know if list is currently firing - firing, - - // Last fire value for non-forgettable lists - memory, - - // Flag to know if list was already fired - fired, - - // Flag to prevent firing - locked, - - // Actual callback list - list = [], - - // Queue of execution data for repeatable lists - queue = [], - - // Index of currently firing callback (modified by add/remove as needed) - firingIndex = -1, - - // Fire callbacks - fire = function() { - - // Enforce single-firing - locked = locked || options.once; - - // Execute callbacks for all pending executions, - // respecting firingIndex overrides and runtime changes - fired = firing = true; - for ( ; queue.length; firingIndex = -1 ) { - memory = queue.shift(); - while ( ++firingIndex < list.length ) { - - // Run callback and check for early termination - if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && - options.stopOnFalse ) { - - // Jump to end and forget the data so .add doesn't re-fire - firingIndex = list.length; - memory = false; - } - } - } - - // Forget the data if we're done with it - if ( !options.memory ) { - memory = false; - } - - firing = false; - - // Clean up if we're done firing for good - if ( locked ) { - - // Keep an empty list if we have data for future add calls - if ( memory ) { - list = []; - - // Otherwise, this object is spent - } else { - list = ""; - } - } - }, - - // Actual Callbacks object - self = { - - // Add a callback or a collection of callbacks to the list - add: function() { - if ( list ) { - - // If we have memory from a past run, we should fire after adding - if ( memory && !firing ) { - firingIndex = list.length - 1; - queue.push( memory ); - } - - ( function add( args ) { - jQuery.each( args, function( _, arg ) { - if ( isFunction( arg ) ) { - if ( !options.unique || !self.has( arg ) ) { - list.push( arg ); - } - } else if ( arg && arg.length && toType( arg ) !== "string" ) { - - // Inspect recursively - add( arg ); - } - } ); - } )( arguments ); - - if ( memory && !firing ) { - fire(); - } - } - return this; - }, - - // Remove a callback from the list - remove: function() { - jQuery.each( arguments, function( _, arg ) { - var index; - while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { - list.splice( index, 1 ); - - // Handle firing indexes - if ( index <= firingIndex ) { - firingIndex--; - } - } - } ); - return this; - }, - - // Check if a given callback is in the list. - // If no argument is given, return whether or not list has callbacks attached. - has: function( fn ) { - return fn ? - jQuery.inArray( fn, list ) > -1 : - list.length > 0; - }, - - // Remove all callbacks from the list - empty: function() { - if ( list ) { - list = []; - } - return this; - }, - - // Disable .fire and .add - // Abort any current/pending executions - // Clear all callbacks and values - disable: function() { - locked = queue = []; - list = memory = ""; - return this; - }, - disabled: function() { - return !list; - }, - - // Disable .fire - // Also disable .add unless we have memory (since it would have no effect) - // Abort any pending executions - lock: function() { - locked = queue = []; - if ( !memory && !firing ) { - list = memory = ""; - } - return this; - }, - locked: function() { - return !!locked; - }, - - // Call all callbacks with the given context and arguments - fireWith: function( context, args ) { - if ( !locked ) { - args = args || []; - args = [ context, args.slice ? args.slice() : args ]; - queue.push( args ); - if ( !firing ) { - fire(); - } - } - return this; - }, - - // Call all the callbacks with the given arguments - fire: function() { - self.fireWith( this, arguments ); - return this; - }, - - // To know if the callbacks have already been called at least once - fired: function() { - return !!fired; - } - }; - - return self; - }; - - - function Identity( v ) { - return v; - } - function Thrower( ex ) { - throw ex; - } - - function adoptValue( value, resolve, reject, noValue ) { - var method; - - try { - - // Check for promise aspect first to privilege synchronous behavior - if ( value && isFunction( ( method = value.promise ) ) ) { - method.call( value ).done( resolve ).fail( reject ); - - // Other thenables - } else if ( value && isFunction( ( method = value.then ) ) ) { - method.call( value, resolve, reject ); - - // Other non-thenables - } else { - - // Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer: - // * false: [ value ].slice( 0 ) => resolve( value ) - // * true: [ value ].slice( 1 ) => resolve() - resolve.apply( undefined, [ value ].slice( noValue ) ); - } - - // For Promises/A+, convert exceptions into rejections - // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in - // Deferred#then to conditionally suppress rejection. - } catch ( value ) { - - // Support: Android 4.0 only - // Strict mode functions invoked without .call/.apply get global-object context - reject.apply( undefined, [ value ] ); - } - } - - jQuery.extend( { - - Deferred: function( func ) { - var tuples = [ - - // action, add listener, callbacks, - // ... .then handlers, argument index, [final state] - [ "notify", "progress", jQuery.Callbacks( "memory" ), - jQuery.Callbacks( "memory" ), 2 ], - [ "resolve", "done", jQuery.Callbacks( "once memory" ), - jQuery.Callbacks( "once memory" ), 0, "resolved" ], - [ "reject", "fail", jQuery.Callbacks( "once memory" ), - jQuery.Callbacks( "once memory" ), 1, "rejected" ] - ], - state = "pending", - promise = { - state: function() { - return state; - }, - always: function() { - deferred.done( arguments ).fail( arguments ); - return this; - }, - "catch": function( fn ) { - return promise.then( null, fn ); - }, - - // Keep pipe for back-compat - pipe: function( /* fnDone, fnFail, fnProgress */ ) { - var fns = arguments; - - return jQuery.Deferred( function( newDefer ) { - jQuery.each( tuples, function( i, tuple ) { - - // Map tuples (progress, done, fail) to arguments (done, fail, progress) - var fn = isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ]; - - // deferred.progress(function() { bind to newDefer or newDefer.notify }) - // deferred.done(function() { bind to newDefer or newDefer.resolve }) - // deferred.fail(function() { bind to newDefer or newDefer.reject }) - deferred[ tuple[ 1 ] ]( function() { - var returned = fn && fn.apply( this, arguments ); - if ( returned && isFunction( returned.promise ) ) { - returned.promise() - .progress( newDefer.notify ) - .done( newDefer.resolve ) - .fail( newDefer.reject ); - } else { - newDefer[ tuple[ 0 ] + "With" ]( - this, - fn ? [ returned ] : arguments - ); - } - } ); - } ); - fns = null; - } ).promise(); - }, - then: function( onFulfilled, onRejected, onProgress ) { - var maxDepth = 0; - function resolve( depth, deferred, handler, special ) { - return function() { - var that = this, - args = arguments, - mightThrow = function() { - var returned, then; - - // Support: Promises/A+ section 2.3.3.3.3 - // https://promisesaplus.com/#point-59 - // Ignore double-resolution attempts - if ( depth < maxDepth ) { - return; - } - - returned = handler.apply( that, args ); - - // Support: Promises/A+ section 2.3.1 - // https://promisesaplus.com/#point-48 - if ( returned === deferred.promise() ) { - throw new TypeError( "Thenable self-resolution" ); - } - - // Support: Promises/A+ sections 2.3.3.1, 3.5 - // https://promisesaplus.com/#point-54 - // https://promisesaplus.com/#point-75 - // Retrieve `then` only once - then = returned && - - // Support: Promises/A+ section 2.3.4 - // https://promisesaplus.com/#point-64 - // Only check objects and functions for thenability - ( typeof returned === "object" || - typeof returned === "function" ) && - returned.then; - - // Handle a returned thenable - if ( isFunction( then ) ) { - - // Special processors (notify) just wait for resolution - if ( special ) { - then.call( - returned, - resolve( maxDepth, deferred, Identity, special ), - resolve( maxDepth, deferred, Thrower, special ) - ); - - // Normal processors (resolve) also hook into progress - } else { - - // ...and disregard older resolution values - maxDepth++; - - then.call( - returned, - resolve( maxDepth, deferred, Identity, special ), - resolve( maxDepth, deferred, Thrower, special ), - resolve( maxDepth, deferred, Identity, - deferred.notifyWith ) - ); - } - - // Handle all other returned values - } else { - - // Only substitute handlers pass on context - // and multiple values (non-spec behavior) - if ( handler !== Identity ) { - that = undefined; - args = [ returned ]; - } - - // Process the value(s) - // Default process is resolve - ( special || deferred.resolveWith )( that, args ); - } - }, - - // Only normal processors (resolve) catch and reject exceptions - process = special ? - mightThrow : - function() { - try { - mightThrow(); - } catch ( e ) { - - if ( jQuery.Deferred.exceptionHook ) { - jQuery.Deferred.exceptionHook( e, - process.stackTrace ); - } - - // Support: Promises/A+ section 2.3.3.3.4.1 - // https://promisesaplus.com/#point-61 - // Ignore post-resolution exceptions - if ( depth + 1 >= maxDepth ) { - - // Only substitute handlers pass on context - // and multiple values (non-spec behavior) - if ( handler !== Thrower ) { - that = undefined; - args = [ e ]; - } - - deferred.rejectWith( that, args ); - } - } - }; - - // Support: Promises/A+ section 2.3.3.3.1 - // https://promisesaplus.com/#point-57 - // Re-resolve promises immediately to dodge false rejection from - // subsequent errors - if ( depth ) { - process(); - } else { - - // Call an optional hook to record the stack, in case of exception - // since it's otherwise lost when execution goes async - if ( jQuery.Deferred.getStackHook ) { - process.stackTrace = jQuery.Deferred.getStackHook(); - } - window.setTimeout( process ); - } - }; - } - - return jQuery.Deferred( function( newDefer ) { - - // progress_handlers.add( ... ) - tuples[ 0 ][ 3 ].add( - resolve( - 0, - newDefer, - isFunction( onProgress ) ? - onProgress : - Identity, - newDefer.notifyWith - ) - ); - - // fulfilled_handlers.add( ... ) - tuples[ 1 ][ 3 ].add( - resolve( - 0, - newDefer, - isFunction( onFulfilled ) ? - onFulfilled : - Identity - ) - ); - - // rejected_handlers.add( ... ) - tuples[ 2 ][ 3 ].add( - resolve( - 0, - newDefer, - isFunction( onRejected ) ? - onRejected : - Thrower - ) - ); - } ).promise(); - }, - - // Get a promise for this deferred - // If obj is provided, the promise aspect is added to the object - promise: function( obj ) { - return obj != null ? jQuery.extend( obj, promise ) : promise; - } - }, - deferred = {}; - - // Add list-specific methods - jQuery.each( tuples, function( i, tuple ) { - var list = tuple[ 2 ], - stateString = tuple[ 5 ]; - - // promise.progress = list.add - // promise.done = list.add - // promise.fail = list.add - promise[ tuple[ 1 ] ] = list.add; - - // Handle state - if ( stateString ) { - list.add( - function() { - - // state = "resolved" (i.e., fulfilled) - // state = "rejected" - state = stateString; - }, - - // rejected_callbacks.disable - // fulfilled_callbacks.disable - tuples[ 3 - i ][ 2 ].disable, - - // rejected_handlers.disable - // fulfilled_handlers.disable - tuples[ 3 - i ][ 3 ].disable, - - // progress_callbacks.lock - tuples[ 0 ][ 2 ].lock, - - // progress_handlers.lock - tuples[ 0 ][ 3 ].lock - ); - } - - // progress_handlers.fire - // fulfilled_handlers.fire - // rejected_handlers.fire - list.add( tuple[ 3 ].fire ); - - // deferred.notify = function() { deferred.notifyWith(...) } - // deferred.resolve = function() { deferred.resolveWith(...) } - // deferred.reject = function() { deferred.rejectWith(...) } - deferred[ tuple[ 0 ] ] = function() { - deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments ); - return this; - }; - - // deferred.notifyWith = list.fireWith - // deferred.resolveWith = list.fireWith - // deferred.rejectWith = list.fireWith - deferred[ tuple[ 0 ] + "With" ] = list.fireWith; - } ); - - // Make the deferred a promise - promise.promise( deferred ); - - // Call given func if any - if ( func ) { - func.call( deferred, deferred ); - } - - // All done! - return deferred; - }, - - // Deferred helper - when: function( singleValue ) { - var - - // count of uncompleted subordinates - remaining = arguments.length, - - // count of unprocessed arguments - i = remaining, - - // subordinate fulfillment data - resolveContexts = Array( i ), - resolveValues = slice.call( arguments ), - - // the master Deferred - master = jQuery.Deferred(), - - // subordinate callback factory - updateFunc = function( i ) { - return function( value ) { - resolveContexts[ i ] = this; - resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; - if ( !( --remaining ) ) { - master.resolveWith( resolveContexts, resolveValues ); - } - }; - }; - - // Single- and empty arguments are adopted like Promise.resolve - if ( remaining <= 1 ) { - adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject, - !remaining ); - - // Use .then() to unwrap secondary thenables (cf. gh-3000) - if ( master.state() === "pending" || - isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) { - - return master.then(); - } - } - - // Multiple arguments are aggregated like Promise.all array elements - while ( i-- ) { - adoptValue( resolveValues[ i ], updateFunc( i ), master.reject ); - } - - return master.promise(); - } - } ); - - -// These usually indicate a programmer mistake during development, -// warn about them ASAP rather than swallowing them by default. - var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/; - - jQuery.Deferred.exceptionHook = function( error, stack ) { - - // Support: IE 8 - 9 only - // Console exists when dev tools are open, which can happen at any time - if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) { - window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack ); - } - }; - - - - - jQuery.readyException = function( error ) { - window.setTimeout( function() { - throw error; - } ); - }; - - - - -// The deferred used on DOM ready - var readyList = jQuery.Deferred(); - - jQuery.fn.ready = function( fn ) { - - readyList - .then( fn ) - - // Wrap jQuery.readyException in a function so that the lookup - // happens at the time of error handling instead of callback - // registration. - .catch( function( error ) { - jQuery.readyException( error ); - } ); - - return this; - }; - - jQuery.extend( { - - // Is the DOM ready to be used? Set to true once it occurs. - isReady: false, - - // A counter to track how many items to wait for before - // the ready event fires. See #6781 - readyWait: 1, - - // Handle when the DOM is ready - ready: function( wait ) { - - // Abort if there are pending holds or we're already ready - if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { - return; - } - - // Remember that the DOM is ready - jQuery.isReady = true; - - // If a normal DOM Ready event fired, decrement, and wait if need be - if ( wait !== true && --jQuery.readyWait > 0 ) { - return; - } - - // If there are functions bound, to execute - readyList.resolveWith( document, [ jQuery ] ); - } - } ); - - jQuery.ready.then = readyList.then; - -// The ready event handler and self cleanup method - function completed() { - document.removeEventListener( "DOMContentLoaded", completed ); - window.removeEventListener( "load", completed ); - jQuery.ready(); - } - -// Catch cases where $(document).ready() is called -// after the browser event has already occurred. -// Support: IE <=9 - 10 only -// Older IE sometimes signals "interactive" too soon - if ( document.readyState === "complete" || - ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { - - // Handle it asynchronously to allow scripts the opportunity to delay ready - window.setTimeout( jQuery.ready ); - - } else { - - // Use the handy event callback - document.addEventListener( "DOMContentLoaded", completed ); - - // A fallback to window.onload, that will always work - window.addEventListener( "load", completed ); - } - - - - -// Multifunctional method to get and set values of a collection -// The value/s can optionally be executed if it's a function - var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { - var i = 0, - len = elems.length, - bulk = key == null; - - // Sets many values - if ( toType( key ) === "object" ) { - chainable = true; - for ( i in key ) { - access( elems, fn, i, key[ i ], true, emptyGet, raw ); - } - - // Sets one value - } else if ( value !== undefined ) { - chainable = true; - - if ( !isFunction( value ) ) { - raw = true; - } - - if ( bulk ) { - - // Bulk operations run against the entire set - if ( raw ) { - fn.call( elems, value ); - fn = null; - - // ...except when executing function values - } else { - bulk = fn; - fn = function( elem, key, value ) { - return bulk.call( jQuery( elem ), value ); - }; - } - } - - if ( fn ) { - for ( ; i < len; i++ ) { - fn( - elems[ i ], key, raw ? - value : - value.call( elems[ i ], i, fn( elems[ i ], key ) ) - ); - } - } - } - - if ( chainable ) { - return elems; - } - - // Gets - if ( bulk ) { - return fn.call( elems ); - } - - return len ? fn( elems[ 0 ], key ) : emptyGet; - }; - - -// Matches dashed string for camelizing - var rmsPrefix = /^-ms-/, - rdashAlpha = /-([a-z])/g; - -// Used by camelCase as callback to replace() - function fcamelCase( all, letter ) { - return letter.toUpperCase(); - } - -// Convert dashed to camelCase; used by the css and data modules -// Support: IE <=9 - 11, Edge 12 - 15 -// Microsoft forgot to hump their vendor prefix (#9572) - function camelCase( string ) { - return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); - } - var acceptData = function( owner ) { - - // Accepts only: - // - Node - // - Node.ELEMENT_NODE - // - Node.DOCUMENT_NODE - // - Object - // - Any - return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); - }; - - - - - function Data() { - this.expando = jQuery.expando + Data.uid++; - } - - Data.uid = 1; - - Data.prototype = { - - cache: function( owner ) { - - // Check if the owner object already has a cache - var value = owner[ this.expando ]; - - // If not, create one - if ( !value ) { - value = {}; - - // We can accept data for non-element nodes in modern browsers, - // but we should not, see #8335. - // Always return an empty object. - if ( acceptData( owner ) ) { - - // If it is a node unlikely to be stringify-ed or looped over - // use plain assignment - if ( owner.nodeType ) { - owner[ this.expando ] = value; - - // Otherwise secure it in a non-enumerable property - // configurable must be true to allow the property to be - // deleted when data is removed - } else { - Object.defineProperty( owner, this.expando, { - value: value, - configurable: true - } ); - } - } - } - - return value; - }, - set: function( owner, data, value ) { - var prop, - cache = this.cache( owner ); - - // Handle: [ owner, key, value ] args - // Always use camelCase key (gh-2257) - if ( typeof data === "string" ) { - cache[ camelCase( data ) ] = value; - - // Handle: [ owner, { properties } ] args - } else { - - // Copy the properties one-by-one to the cache object - for ( prop in data ) { - cache[ camelCase( prop ) ] = data[ prop ]; - } - } - return cache; - }, - get: function( owner, key ) { - return key === undefined ? - this.cache( owner ) : - - // Always use camelCase key (gh-2257) - owner[ this.expando ] && owner[ this.expando ][ camelCase( key ) ]; - }, - access: function( owner, key, value ) { - - // In cases where either: - // - // 1. No key was specified - // 2. A string key was specified, but no value provided - // - // Take the "read" path and allow the get method to determine - // which value to return, respectively either: - // - // 1. The entire cache object - // 2. The data stored at the key - // - if ( key === undefined || - ( ( key && typeof key === "string" ) && value === undefined ) ) { - - return this.get( owner, key ); - } - - // When the key is not a string, or both a key and value - // are specified, set or extend (existing objects) with either: - // - // 1. An object of properties - // 2. A key and value - // - this.set( owner, key, value ); - - // Since the "set" path can have two possible entry points - // return the expected data based on which path was taken[*] - return value !== undefined ? value : key; - }, - remove: function( owner, key ) { - var i, - cache = owner[ this.expando ]; - - if ( cache === undefined ) { - return; - } - - if ( key !== undefined ) { - - // Support array or space separated string of keys - if ( Array.isArray( key ) ) { - - // If key is an array of keys... - // We always set camelCase keys, so remove that. - key = key.map( camelCase ); - } else { - key = camelCase( key ); - - // If a key with the spaces exists, use it. - // Otherwise, create an array by matching non-whitespace - key = key in cache ? - [ key ] : - ( key.match( rnothtmlwhite ) || [] ); - } - - i = key.length; - - while ( i-- ) { - delete cache[ key[ i ] ]; - } - } - - // Remove the expando if there's no more data - if ( key === undefined || jQuery.isEmptyObject( cache ) ) { - - // Support: Chrome <=35 - 45 - // Webkit & Blink performance suffers when deleting properties - // from DOM nodes, so set to undefined instead - // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted) - if ( owner.nodeType ) { - owner[ this.expando ] = undefined; - } else { - delete owner[ this.expando ]; - } - } - }, - hasData: function( owner ) { - var cache = owner[ this.expando ]; - return cache !== undefined && !jQuery.isEmptyObject( cache ); - } - }; - var dataPriv = new Data(); - - var dataUser = new Data(); - - - -// Implementation Summary -// -// 1. Enforce API surface and semantic compatibility with 1.9.x branch -// 2. Improve the module's maintainability by reducing the storage -// paths to a single mechanism. -// 3. Use the same single mechanism to support "private" and "user" data. -// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) -// 5. Avoid exposing implementation details on user objects (eg. expando properties) -// 6. Provide a clear path for implementation upgrade to WeakMap in 2014 - - var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, - rmultiDash = /[A-Z]/g; - - function getData( data ) { - if ( data === "true" ) { - return true; - } - - if ( data === "false" ) { - return false; - } - - if ( data === "null" ) { - return null; - } - - // Only convert to a number if it doesn't change the string - if ( data === +data + "" ) { - return +data; - } - - if ( rbrace.test( data ) ) { - return JSON.parse( data ); - } - - return data; - } - - function dataAttr( elem, key, data ) { - var name; - - // If nothing was found internally, try to fetch any - // data from the HTML5 data-* attribute - if ( data === undefined && elem.nodeType === 1 ) { - name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); - data = elem.getAttribute( name ); - - if ( typeof data === "string" ) { - try { - data = getData( data ); - } catch ( e ) {} - - // Make sure we set the data so it isn't changed later - dataUser.set( elem, key, data ); - } else { - data = undefined; - } - } - return data; - } - - jQuery.extend( { - hasData: function( elem ) { - return dataUser.hasData( elem ) || dataPriv.hasData( elem ); - }, - - data: function( elem, name, data ) { - return dataUser.access( elem, name, data ); - }, - - removeData: function( elem, name ) { - dataUser.remove( elem, name ); - }, - - // TODO: Now that all calls to _data and _removeData have been replaced - // with direct calls to dataPriv methods, these can be deprecated. - _data: function( elem, name, data ) { - return dataPriv.access( elem, name, data ); - }, - - _removeData: function( elem, name ) { - dataPriv.remove( elem, name ); - } - } ); - - jQuery.fn.extend( { - data: function( key, value ) { - var i, name, data, - elem = this[ 0 ], - attrs = elem && elem.attributes; - - // Gets all values - if ( key === undefined ) { - if ( this.length ) { - data = dataUser.get( elem ); - - if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { - i = attrs.length; - while ( i-- ) { - - // Support: IE 11 only - // The attrs elements can be null (#14894) - if ( attrs[ i ] ) { - name = attrs[ i ].name; - if ( name.indexOf( "data-" ) === 0 ) { - name = camelCase( name.slice( 5 ) ); - dataAttr( elem, name, data[ name ] ); - } - } - } - dataPriv.set( elem, "hasDataAttrs", true ); - } - } - - return data; - } - - // Sets multiple values - if ( typeof key === "object" ) { - return this.each( function() { - dataUser.set( this, key ); - } ); - } - - return access( this, function( value ) { - var data; - - // The calling jQuery object (element matches) is not empty - // (and therefore has an element appears at this[ 0 ]) and the - // `value` parameter was not undefined. An empty jQuery object - // will result in `undefined` for elem = this[ 0 ] which will - // throw an exception if an attempt to read a data cache is made. - if ( elem && value === undefined ) { - - // Attempt to get data from the cache - // The key will always be camelCased in Data - data = dataUser.get( elem, key ); - if ( data !== undefined ) { - return data; - } - - // Attempt to "discover" the data in - // HTML5 custom data-* attrs - data = dataAttr( elem, key ); - if ( data !== undefined ) { - return data; - } - - // We tried really hard, but the data doesn't exist. - return; - } - - // Set the data... - this.each( function() { - - // We always store the camelCased key - dataUser.set( this, key, value ); - } ); - }, null, value, arguments.length > 1, null, true ); - }, - - removeData: function( key ) { - return this.each( function() { - dataUser.remove( this, key ); - } ); - } - } ); - - - jQuery.extend( { - queue: function( elem, type, data ) { - var queue; - - if ( elem ) { - type = ( type || "fx" ) + "queue"; - queue = dataPriv.get( elem, type ); - - // Speed up dequeue by getting out quickly if this is just a lookup - if ( data ) { - if ( !queue || Array.isArray( data ) ) { - queue = dataPriv.access( elem, type, jQuery.makeArray( data ) ); - } else { - queue.push( data ); - } - } - return queue || []; - } - }, - - dequeue: function( elem, type ) { - type = type || "fx"; - - var queue = jQuery.queue( elem, type ), - startLength = queue.length, - fn = queue.shift(), - hooks = jQuery._queueHooks( elem, type ), - next = function() { - jQuery.dequeue( elem, type ); - }; - - // If the fx queue is dequeued, always remove the progress sentinel - if ( fn === "inprogress" ) { - fn = queue.shift(); - startLength--; - } - - if ( fn ) { - - // Add a progress sentinel to prevent the fx queue from being - // automatically dequeued - if ( type === "fx" ) { - queue.unshift( "inprogress" ); - } - - // Clear up the last queue stop function - delete hooks.stop; - fn.call( elem, next, hooks ); - } - - if ( !startLength && hooks ) { - hooks.empty.fire(); - } - }, - - // Not public - generate a queueHooks object, or return the current one - _queueHooks: function( elem, type ) { - var key = type + "queueHooks"; - return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { - empty: jQuery.Callbacks( "once memory" ).add( function() { - dataPriv.remove( elem, [ type + "queue", key ] ); - } ) - } ); - } - } ); - - jQuery.fn.extend( { - queue: function( type, data ) { - var setter = 2; - - if ( typeof type !== "string" ) { - data = type; - type = "fx"; - setter--; - } - - if ( arguments.length < setter ) { - return jQuery.queue( this[ 0 ], type ); - } - - return data === undefined ? - this : - this.each( function() { - var queue = jQuery.queue( this, type, data ); - - // Ensure a hooks for this queue - jQuery._queueHooks( this, type ); - - if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { - jQuery.dequeue( this, type ); - } - } ); - }, - dequeue: function( type ) { - return this.each( function() { - jQuery.dequeue( this, type ); - } ); - }, - clearQueue: function( type ) { - return this.queue( type || "fx", [] ); - }, - - // Get a promise resolved when queues of a certain type - // are emptied (fx is the type by default) - promise: function( type, obj ) { - var tmp, - count = 1, - defer = jQuery.Deferred(), - elements = this, - i = this.length, - resolve = function() { - if ( !( --count ) ) { - defer.resolveWith( elements, [ elements ] ); - } - }; - - if ( typeof type !== "string" ) { - obj = type; - type = undefined; - } - type = type || "fx"; - - while ( i-- ) { - tmp = dataPriv.get( elements[ i ], type + "queueHooks" ); - if ( tmp && tmp.empty ) { - count++; - tmp.empty.add( resolve ); - } - } - resolve(); - return defer.promise( obj ); - } - } ); - var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; - - var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); - - - var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; - - var isHiddenWithinTree = function( elem, el ) { - - // isHiddenWithinTree might be called from jQuery#filter function; - // in that case, element will be second argument - elem = el || elem; - - // Inline style trumps all - return elem.style.display === "none" || - elem.style.display === "" && - - // Otherwise, check computed style - // Support: Firefox <=43 - 45 - // Disconnected elements can have computed display: none, so first confirm that elem is - // in the document. - jQuery.contains( elem.ownerDocument, elem ) && - - jQuery.css( elem, "display" ) === "none"; - }; - - var swap = function( elem, options, callback, args ) { - var ret, name, - old = {}; - - // Remember the old values, and insert the new ones - for ( name in options ) { - old[ name ] = elem.style[ name ]; - elem.style[ name ] = options[ name ]; - } - - ret = callback.apply( elem, args || [] ); - - // Revert the old values - for ( name in options ) { - elem.style[ name ] = old[ name ]; - } - - return ret; - }; - - - - - function adjustCSS( elem, prop, valueParts, tween ) { - var adjusted, scale, - maxIterations = 20, - currentValue = tween ? - function() { - return tween.cur(); - } : - function() { - return jQuery.css( elem, prop, "" ); - }, - initial = currentValue(), - unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), - - // Starting value computation is required for potential unit mismatches - initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && - rcssNum.exec( jQuery.css( elem, prop ) ); - - if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { - - // Support: Firefox <=54 - // Halve the iteration target value to prevent interference from CSS upper bounds (gh-2144) - initial = initial / 2; - - // Trust units reported by jQuery.css - unit = unit || initialInUnit[ 3 ]; - - // Iteratively approximate from a nonzero starting point - initialInUnit = +initial || 1; - - while ( maxIterations-- ) { - - // Evaluate and update our best guess (doubling guesses that zero out). - // Finish if the scale equals or crosses 1 (making the old*new product non-positive). - jQuery.style( elem, prop, initialInUnit + unit ); - if ( ( 1 - scale ) * ( 1 - ( scale = currentValue() / initial || 0.5 ) ) <= 0 ) { - maxIterations = 0; - } - initialInUnit = initialInUnit / scale; - - } - - initialInUnit = initialInUnit * 2; - jQuery.style( elem, prop, initialInUnit + unit ); - - // Make sure we update the tween properties later on - valueParts = valueParts || []; - } - - if ( valueParts ) { - initialInUnit = +initialInUnit || +initial || 0; - - // Apply relative offset (+=/-=) if specified - adjusted = valueParts[ 1 ] ? - initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : - +valueParts[ 2 ]; - if ( tween ) { - tween.unit = unit; - tween.start = initialInUnit; - tween.end = adjusted; - } - } - return adjusted; - } - - - var defaultDisplayMap = {}; - - function getDefaultDisplay( elem ) { - var temp, - doc = elem.ownerDocument, - nodeName = elem.nodeName, - display = defaultDisplayMap[ nodeName ]; - - if ( display ) { - return display; - } - - temp = doc.body.appendChild( doc.createElement( nodeName ) ); - display = jQuery.css( temp, "display" ); - - temp.parentNode.removeChild( temp ); - - if ( display === "none" ) { - display = "block"; - } - defaultDisplayMap[ nodeName ] = display; - - return display; - } - - function showHide( elements, show ) { - var display, elem, - values = [], - index = 0, - length = elements.length; - - // Determine new display value for elements that need to change - for ( ; index < length; index++ ) { - elem = elements[ index ]; - if ( !elem.style ) { - continue; - } - - display = elem.style.display; - if ( show ) { - - // Since we force visibility upon cascade-hidden elements, an immediate (and slow) - // check is required in this first loop unless we have a nonempty display value (either - // inline or about-to-be-restored) - if ( display === "none" ) { - values[ index ] = dataPriv.get( elem, "display" ) || null; - if ( !values[ index ] ) { - elem.style.display = ""; - } - } - if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) { - values[ index ] = getDefaultDisplay( elem ); - } - } else { - if ( display !== "none" ) { - values[ index ] = "none"; - - // Remember what we're overwriting - dataPriv.set( elem, "display", display ); - } - } - } - - // Set the display of the elements in a second loop to avoid constant reflow - for ( index = 0; index < length; index++ ) { - if ( values[ index ] != null ) { - elements[ index ].style.display = values[ index ]; - } - } - - return elements; - } - - jQuery.fn.extend( { - show: function() { - return showHide( this, true ); - }, - hide: function() { - return showHide( this ); - }, - toggle: function( state ) { - if ( typeof state === "boolean" ) { - return state ? this.show() : this.hide(); - } - - return this.each( function() { - if ( isHiddenWithinTree( this ) ) { - jQuery( this ).show(); - } else { - jQuery( this ).hide(); - } - } ); - } - } ); - var rcheckableType = ( /^(?:checkbox|radio)$/i ); - - var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]+)/i ); - - var rscriptType = ( /^$|^module$|\/(?:java|ecma)script/i ); - - - -// We have to close these tags to support XHTML (#13200) - var wrapMap = { - - // Support: IE <=9 only - option: [ 1, "" ], - - // XHTML parsers do not magically insert elements in the - // same way that tag soup parsers do. So we cannot shorten - // this by omitting or other required elements. - thead: [ 1, "", "
" ], - col: [ 2, "", "
" ], - tr: [ 2, "", "
" ], - td: [ 3, "", "
" ], - - _default: [ 0, "", "" ] - }; - -// Support: IE <=9 only - wrapMap.optgroup = wrapMap.option; - - wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; - wrapMap.th = wrapMap.td; - - - function getAll( context, tag ) { - - // Support: IE <=9 - 11 only - // Use typeof to avoid zero-argument method invocation on host objects (#15151) - var ret; - - if ( typeof context.getElementsByTagName !== "undefined" ) { - ret = context.getElementsByTagName( tag || "*" ); - - } else if ( typeof context.querySelectorAll !== "undefined" ) { - ret = context.querySelectorAll( tag || "*" ); - - } else { - ret = []; - } - - if ( tag === undefined || tag && nodeName( context, tag ) ) { - return jQuery.merge( [ context ], ret ); - } - - return ret; - } - - -// Mark scripts as having already been evaluated - function setGlobalEval( elems, refElements ) { - var i = 0, - l = elems.length; - - for ( ; i < l; i++ ) { - dataPriv.set( - elems[ i ], - "globalEval", - !refElements || dataPriv.get( refElements[ i ], "globalEval" ) - ); - } - } - - - var rhtml = /<|&#?\w+;/; - - function buildFragment( elems, context, scripts, selection, ignored ) { - var elem, tmp, tag, wrap, contains, j, - fragment = context.createDocumentFragment(), - nodes = [], - i = 0, - l = elems.length; - - for ( ; i < l; i++ ) { - elem = elems[ i ]; - - if ( elem || elem === 0 ) { - - // Add nodes directly - if ( toType( elem ) === "object" ) { - - // Support: Android <=4.0 only, PhantomJS 1 only - // push.apply(_, arraylike) throws on ancient WebKit - jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); - - // Convert non-html into a text node - } else if ( !rhtml.test( elem ) ) { - nodes.push( context.createTextNode( elem ) ); - - // Convert html into DOM nodes - } else { - tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); - - // Deserialize a standard representation - tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); - wrap = wrapMap[ tag ] || wrapMap._default; - tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; - - // Descend through wrappers to the right content - j = wrap[ 0 ]; - while ( j-- ) { - tmp = tmp.lastChild; - } - - // Support: Android <=4.0 only, PhantomJS 1 only - // push.apply(_, arraylike) throws on ancient WebKit - jQuery.merge( nodes, tmp.childNodes ); - - // Remember the top-level container - tmp = fragment.firstChild; - - // Ensure the created nodes are orphaned (#12392) - tmp.textContent = ""; - } - } - } - - // Remove wrapper from fragment - fragment.textContent = ""; - - i = 0; - while ( ( elem = nodes[ i++ ] ) ) { - - // Skip elements already in the context collection (trac-4087) - if ( selection && jQuery.inArray( elem, selection ) > -1 ) { - if ( ignored ) { - ignored.push( elem ); - } - continue; - } - - contains = jQuery.contains( elem.ownerDocument, elem ); - - // Append to fragment - tmp = getAll( fragment.appendChild( elem ), "script" ); - - // Preserve script evaluation history - if ( contains ) { - setGlobalEval( tmp ); - } - - // Capture executables - if ( scripts ) { - j = 0; - while ( ( elem = tmp[ j++ ] ) ) { - if ( rscriptType.test( elem.type || "" ) ) { - scripts.push( elem ); - } - } - } - } - - return fragment; - } - - - ( function() { - var fragment = document.createDocumentFragment(), - div = fragment.appendChild( document.createElement( "div" ) ), - input = document.createElement( "input" ); - - // Support: Android 4.0 - 4.3 only - // Check state lost if the name is set (#11217) - // Support: Windows Web Apps (WWA) - // `name` and `type` must use .setAttribute for WWA (#14901) - input.setAttribute( "type", "radio" ); - input.setAttribute( "checked", "checked" ); - input.setAttribute( "name", "t" ); - - div.appendChild( input ); - - // Support: Android <=4.1 only - // Older WebKit doesn't clone checked state correctly in fragments - support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; - - // Support: IE <=11 only - // Make sure textarea (and checkbox) defaultValue is properly cloned - div.innerHTML = ""; - support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; - } )(); - var documentElement = document.documentElement; - - - - var - rkeyEvent = /^key/, - rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, - rtypenamespace = /^([^.]*)(?:\.(.+)|)/; - - function returnTrue() { - return true; - } - - function returnFalse() { - return false; - } - -// Support: IE <=9 only -// See #13393 for more info - function safeActiveElement() { - try { - return document.activeElement; - } catch ( err ) { } - } - - function on( elem, types, selector, data, fn, one ) { - var origFn, type; - - // Types can be a map of types/handlers - if ( typeof types === "object" ) { - - // ( types-Object, selector, data ) - if ( typeof selector !== "string" ) { - - // ( types-Object, data ) - data = data || selector; - selector = undefined; - } - for ( type in types ) { - on( elem, type, selector, data, types[ type ], one ); - } - return elem; - } - - if ( data == null && fn == null ) { - - // ( types, fn ) - fn = selector; - data = selector = undefined; - } else if ( fn == null ) { - if ( typeof selector === "string" ) { - - // ( types, selector, fn ) - fn = data; - data = undefined; - } else { - - // ( types, data, fn ) - fn = data; - data = selector; - selector = undefined; - } - } - if ( fn === false ) { - fn = returnFalse; - } else if ( !fn ) { - return elem; - } - - if ( one === 1 ) { - origFn = fn; - fn = function( event ) { - - // Can use an empty set, since event contains the info - jQuery().off( event ); - return origFn.apply( this, arguments ); - }; - - // Use same guid so caller can remove using origFn - fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); - } - return elem.each( function() { - jQuery.event.add( this, types, fn, data, selector ); - } ); - } - - /* - * Helper functions for managing events -- not part of the public interface. - * Props to Dean Edwards' addEvent library for many of the ideas. - */ - jQuery.event = { - - global: {}, - - add: function( elem, types, handler, data, selector ) { - - var handleObjIn, eventHandle, tmp, - events, t, handleObj, - special, handlers, type, namespaces, origType, - elemData = dataPriv.get( elem ); - - // Don't attach events to noData or text/comment nodes (but allow plain objects) - if ( !elemData ) { - return; - } - - // Caller can pass in an object of custom data in lieu of the handler - if ( handler.handler ) { - handleObjIn = handler; - handler = handleObjIn.handler; - selector = handleObjIn.selector; - } - - // Ensure that invalid selectors throw exceptions at attach time - // Evaluate against documentElement in case elem is a non-element node (e.g., document) - if ( selector ) { - jQuery.find.matchesSelector( documentElement, selector ); - } - - // Make sure that the handler has a unique ID, used to find/remove it later - if ( !handler.guid ) { - handler.guid = jQuery.guid++; - } - - // Init the element's event structure and main handler, if this is the first - if ( !( events = elemData.events ) ) { - events = elemData.events = {}; - } - if ( !( eventHandle = elemData.handle ) ) { - eventHandle = elemData.handle = function( e ) { - - // Discard the second event of a jQuery.event.trigger() and - // when an event is called after a page has unloaded - return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? - jQuery.event.dispatch.apply( elem, arguments ) : undefined; - }; - } - - // Handle multiple events separated by a space - types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; - t = types.length; - while ( t-- ) { - tmp = rtypenamespace.exec( types[ t ] ) || []; - type = origType = tmp[ 1 ]; - namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); - - // There *must* be a type, no attaching namespace-only handlers - if ( !type ) { - continue; - } - - // If event changes its type, use the special event handlers for the changed type - special = jQuery.event.special[ type ] || {}; - - // If selector defined, determine special event api type, otherwise given type - type = ( selector ? special.delegateType : special.bindType ) || type; - - // Update special based on newly reset type - special = jQuery.event.special[ type ] || {}; - - // handleObj is passed to all event handlers - handleObj = jQuery.extend( { - type: type, - origType: origType, - data: data, - handler: handler, - guid: handler.guid, - selector: selector, - needsContext: selector && jQuery.expr.match.needsContext.test( selector ), - namespace: namespaces.join( "." ) - }, handleObjIn ); - - // Init the event handler queue if we're the first - if ( !( handlers = events[ type ] ) ) { - handlers = events[ type ] = []; - handlers.delegateCount = 0; - - // Only use addEventListener if the special events handler returns false - if ( !special.setup || - special.setup.call( elem, data, namespaces, eventHandle ) === false ) { - - if ( elem.addEventListener ) { - elem.addEventListener( type, eventHandle ); - } - } - } - - if ( special.add ) { - special.add.call( elem, handleObj ); - - if ( !handleObj.handler.guid ) { - handleObj.handler.guid = handler.guid; - } - } - - // Add to the element's handler list, delegates in front - if ( selector ) { - handlers.splice( handlers.delegateCount++, 0, handleObj ); - } else { - handlers.push( handleObj ); - } - - // Keep track of which events have ever been used, for event optimization - jQuery.event.global[ type ] = true; - } - - }, - - // Detach an event or set of events from an element - remove: function( elem, types, handler, selector, mappedTypes ) { - - var j, origCount, tmp, - events, t, handleObj, - special, handlers, type, namespaces, origType, - elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); - - if ( !elemData || !( events = elemData.events ) ) { - return; - } - - // Once for each type.namespace in types; type may be omitted - types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; - t = types.length; - while ( t-- ) { - tmp = rtypenamespace.exec( types[ t ] ) || []; - type = origType = tmp[ 1 ]; - namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); - - // Unbind all events (on this namespace, if provided) for the element - if ( !type ) { - for ( type in events ) { - jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); - } - continue; - } - - special = jQuery.event.special[ type ] || {}; - type = ( selector ? special.delegateType : special.bindType ) || type; - handlers = events[ type ] || []; - tmp = tmp[ 2 ] && - new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); - - // Remove matching events - origCount = j = handlers.length; - while ( j-- ) { - handleObj = handlers[ j ]; - - if ( ( mappedTypes || origType === handleObj.origType ) && - ( !handler || handler.guid === handleObj.guid ) && - ( !tmp || tmp.test( handleObj.namespace ) ) && - ( !selector || selector === handleObj.selector || - selector === "**" && handleObj.selector ) ) { - handlers.splice( j, 1 ); - - if ( handleObj.selector ) { - handlers.delegateCount--; - } - if ( special.remove ) { - special.remove.call( elem, handleObj ); - } - } - } - - // Remove generic event handler if we removed something and no more handlers exist - // (avoids potential for endless recursion during removal of special event handlers) - if ( origCount && !handlers.length ) { - if ( !special.teardown || - special.teardown.call( elem, namespaces, elemData.handle ) === false ) { - - jQuery.removeEvent( elem, type, elemData.handle ); - } - - delete events[ type ]; - } - } - - // Remove data and the expando if it's no longer used - if ( jQuery.isEmptyObject( events ) ) { - dataPriv.remove( elem, "handle events" ); - } - }, - - dispatch: function( nativeEvent ) { - - // Make a writable jQuery.Event from the native event object - var event = jQuery.event.fix( nativeEvent ); - - var i, j, ret, matched, handleObj, handlerQueue, - args = new Array( arguments.length ), - handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [], - special = jQuery.event.special[ event.type ] || {}; - - // Use the fix-ed jQuery.Event rather than the (read-only) native event - args[ 0 ] = event; - - for ( i = 1; i < arguments.length; i++ ) { - args[ i ] = arguments[ i ]; - } - - event.delegateTarget = this; - - // Call the preDispatch hook for the mapped type, and let it bail if desired - if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { - return; - } - - // Determine handlers - handlerQueue = jQuery.event.handlers.call( this, event, handlers ); - - // Run delegates first; they may want to stop propagation beneath us - i = 0; - while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { - event.currentTarget = matched.elem; - - j = 0; - while ( ( handleObj = matched.handlers[ j++ ] ) && - !event.isImmediatePropagationStopped() ) { - - // Triggered event must either 1) have no namespace, or 2) have namespace(s) - // a subset or equal to those in the bound event (both can have no namespace). - if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) { - - event.handleObj = handleObj; - event.data = handleObj.data; - - ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || - handleObj.handler ).apply( matched.elem, args ); - - if ( ret !== undefined ) { - if ( ( event.result = ret ) === false ) { - event.preventDefault(); - event.stopPropagation(); - } - } - } - } - } - - // Call the postDispatch hook for the mapped type - if ( special.postDispatch ) { - special.postDispatch.call( this, event ); - } - - return event.result; - }, - - handlers: function( event, handlers ) { - var i, handleObj, sel, matchedHandlers, matchedSelectors, - handlerQueue = [], - delegateCount = handlers.delegateCount, - cur = event.target; - - // Find delegate handlers - if ( delegateCount && - - // Support: IE <=9 - // Black-hole SVG instance trees (trac-13180) - cur.nodeType && - - // Support: Firefox <=42 - // Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861) - // https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click - // Support: IE 11 only - // ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343) - !( event.type === "click" && event.button >= 1 ) ) { - - for ( ; cur !== this; cur = cur.parentNode || this ) { - - // Don't check non-elements (#13208) - // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) - if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) { - matchedHandlers = []; - matchedSelectors = {}; - for ( i = 0; i < delegateCount; i++ ) { - handleObj = handlers[ i ]; - - // Don't conflict with Object.prototype properties (#13203) - sel = handleObj.selector + " "; - - if ( matchedSelectors[ sel ] === undefined ) { - matchedSelectors[ sel ] = handleObj.needsContext ? - jQuery( sel, this ).index( cur ) > -1 : - jQuery.find( sel, this, null, [ cur ] ).length; - } - if ( matchedSelectors[ sel ] ) { - matchedHandlers.push( handleObj ); - } - } - if ( matchedHandlers.length ) { - handlerQueue.push( { elem: cur, handlers: matchedHandlers } ); - } - } - } - } - - // Add the remaining (directly-bound) handlers - cur = this; - if ( delegateCount < handlers.length ) { - handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } ); - } - - return handlerQueue; - }, - - addProp: function( name, hook ) { - Object.defineProperty( jQuery.Event.prototype, name, { - enumerable: true, - configurable: true, - - get: isFunction( hook ) ? - function() { - if ( this.originalEvent ) { - return hook( this.originalEvent ); - } - } : - function() { - if ( this.originalEvent ) { - return this.originalEvent[ name ]; - } - }, - - set: function( value ) { - Object.defineProperty( this, name, { - enumerable: true, - configurable: true, - writable: true, - value: value - } ); - } - } ); - }, - - fix: function( originalEvent ) { - return originalEvent[ jQuery.expando ] ? - originalEvent : - new jQuery.Event( originalEvent ); - }, - - special: { - load: { - - // Prevent triggered image.load events from bubbling to window.load - noBubble: true - }, - focus: { - - // Fire native event if possible so blur/focus sequence is correct - trigger: function() { - if ( this !== safeActiveElement() && this.focus ) { - this.focus(); - return false; - } - }, - delegateType: "focusin" - }, - blur: { - trigger: function() { - if ( this === safeActiveElement() && this.blur ) { - this.blur(); - return false; - } - }, - delegateType: "focusout" - }, - click: { - - // For checkbox, fire native event so checked state will be right - trigger: function() { - if ( this.type === "checkbox" && this.click && nodeName( this, "input" ) ) { - this.click(); - return false; - } - }, - - // For cross-browser consistency, don't fire native .click() on links - _default: function( event ) { - return nodeName( event.target, "a" ); - } - }, - - beforeunload: { - postDispatch: function( event ) { - - // Support: Firefox 20+ - // Firefox doesn't alert if the returnValue field is not set. - if ( event.result !== undefined && event.originalEvent ) { - event.originalEvent.returnValue = event.result; - } - } - } - } - }; - - jQuery.removeEvent = function( elem, type, handle ) { - - // This "if" is needed for plain objects - if ( elem.removeEventListener ) { - elem.removeEventListener( type, handle ); - } - }; - - jQuery.Event = function( src, props ) { - - // Allow instantiation without the 'new' keyword - if ( !( this instanceof jQuery.Event ) ) { - return new jQuery.Event( src, props ); - } - - // Event object - if ( src && src.type ) { - this.originalEvent = src; - this.type = src.type; - - // Events bubbling up the document may have been marked as prevented - // by a handler lower down the tree; reflect the correct value. - this.isDefaultPrevented = src.defaultPrevented || - src.defaultPrevented === undefined && - - // Support: Android <=2.3 only - src.returnValue === false ? - returnTrue : - returnFalse; - - // Create target properties - // Support: Safari <=6 - 7 only - // Target should not be a text node (#504, #13143) - this.target = ( src.target && src.target.nodeType === 3 ) ? - src.target.parentNode : - src.target; - - this.currentTarget = src.currentTarget; - this.relatedTarget = src.relatedTarget; - - // Event type - } else { - this.type = src; - } - - // Put explicitly provided properties onto the event object - if ( props ) { - jQuery.extend( this, props ); - } - - // Create a timestamp if incoming event doesn't have one - this.timeStamp = src && src.timeStamp || Date.now(); - - // Mark it as fixed - this[ jQuery.expando ] = true; - }; - -// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding -// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html - jQuery.Event.prototype = { - constructor: jQuery.Event, - isDefaultPrevented: returnFalse, - isPropagationStopped: returnFalse, - isImmediatePropagationStopped: returnFalse, - isSimulated: false, - - preventDefault: function() { - var e = this.originalEvent; - - this.isDefaultPrevented = returnTrue; - - if ( e && !this.isSimulated ) { - e.preventDefault(); - } - }, - stopPropagation: function() { - var e = this.originalEvent; - - this.isPropagationStopped = returnTrue; - - if ( e && !this.isSimulated ) { - e.stopPropagation(); - } - }, - stopImmediatePropagation: function() { - var e = this.originalEvent; - - this.isImmediatePropagationStopped = returnTrue; - - if ( e && !this.isSimulated ) { - e.stopImmediatePropagation(); - } - - this.stopPropagation(); - } - }; - -// Includes all common event props including KeyEvent and MouseEvent specific props - jQuery.each( { - altKey: true, - bubbles: true, - cancelable: true, - changedTouches: true, - ctrlKey: true, - detail: true, - eventPhase: true, - metaKey: true, - pageX: true, - pageY: true, - shiftKey: true, - view: true, - "char": true, - charCode: true, - key: true, - keyCode: true, - button: true, - buttons: true, - clientX: true, - clientY: true, - offsetX: true, - offsetY: true, - pointerId: true, - pointerType: true, - screenX: true, - screenY: true, - targetTouches: true, - toElement: true, - touches: true, - - which: function( event ) { - var button = event.button; - - // Add which for key events - if ( event.which == null && rkeyEvent.test( event.type ) ) { - return event.charCode != null ? event.charCode : event.keyCode; - } - - // Add which for click: 1 === left; 2 === middle; 3 === right - if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) { - if ( button & 1 ) { - return 1; - } - - if ( button & 2 ) { - return 3; - } - - if ( button & 4 ) { - return 2; - } - - return 0; - } - - return event.which; - } - }, jQuery.event.addProp ); - -// Create mouseenter/leave events using mouseover/out and event-time checks -// so that event delegation works in jQuery. -// Do the same for pointerenter/pointerleave and pointerover/pointerout -// -// Support: Safari 7 only -// Safari sends mouseenter too often; see: -// https://bugs.chromium.org/p/chromium/issues/detail?id=470258 -// for the description of the bug (it existed in older Chrome versions as well). - jQuery.each( { - mouseenter: "mouseover", - mouseleave: "mouseout", - pointerenter: "pointerover", - pointerleave: "pointerout" - }, function( orig, fix ) { - jQuery.event.special[ orig ] = { - delegateType: fix, - bindType: fix, - - handle: function( event ) { - var ret, - target = this, - related = event.relatedTarget, - handleObj = event.handleObj; - - // For mouseenter/leave call the handler if related is outside the target. - // NB: No relatedTarget if the mouse left/entered the browser window - if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { - event.type = handleObj.origType; - ret = handleObj.handler.apply( this, arguments ); - event.type = fix; - } - return ret; - } - }; - } ); - - jQuery.fn.extend( { - - on: function( types, selector, data, fn ) { - return on( this, types, selector, data, fn ); - }, - one: function( types, selector, data, fn ) { - return on( this, types, selector, data, fn, 1 ); - }, - off: function( types, selector, fn ) { - var handleObj, type; - if ( types && types.preventDefault && types.handleObj ) { - - // ( event ) dispatched jQuery.Event - handleObj = types.handleObj; - jQuery( types.delegateTarget ).off( - handleObj.namespace ? - handleObj.origType + "." + handleObj.namespace : - handleObj.origType, - handleObj.selector, - handleObj.handler - ); - return this; - } - if ( typeof types === "object" ) { - - // ( types-object [, selector] ) - for ( type in types ) { - this.off( type, selector, types[ type ] ); - } - return this; - } - if ( selector === false || typeof selector === "function" ) { - - // ( types [, fn] ) - fn = selector; - selector = undefined; - } - if ( fn === false ) { - fn = returnFalse; - } - return this.each( function() { - jQuery.event.remove( this, types, fn, selector ); - } ); - } - } ); - - - var - - /* eslint-disable max-len */ - - // See https://github.com/eslint/eslint/issues/3229 - rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi, - - /* eslint-enable */ - - // Support: IE <=10 - 11, Edge 12 - 13 only - // In IE/Edge using regex groups here causes severe slowdowns. - // See https://connect.microsoft.com/IE/feedback/details/1736512/ - rnoInnerhtml = /\s*$/g; - -// Prefer a tbody over its parent table for containing new rows - function manipulationTarget( elem, content ) { - if ( nodeName( elem, "table" ) && - nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { - - return jQuery( elem ).children( "tbody" )[ 0 ] || elem; - } - - return elem; - } - -// Replace/restore the type attribute of script elements for safe DOM manipulation - function disableScript( elem ) { - elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; - return elem; - } - function restoreScript( elem ) { - if ( ( elem.type || "" ).slice( 0, 5 ) === "true/" ) { - elem.type = elem.type.slice( 5 ); - } else { - elem.removeAttribute( "type" ); - } - - return elem; - } - - function cloneCopyEvent( src, dest ) { - var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; - - if ( dest.nodeType !== 1 ) { - return; - } - - // 1. Copy private data: events, handlers, etc. - if ( dataPriv.hasData( src ) ) { - pdataOld = dataPriv.access( src ); - pdataCur = dataPriv.set( dest, pdataOld ); - events = pdataOld.events; - - if ( events ) { - delete pdataCur.handle; - pdataCur.events = {}; - - for ( type in events ) { - for ( i = 0, l = events[ type ].length; i < l; i++ ) { - jQuery.event.add( dest, type, events[ type ][ i ] ); - } - } - } - } - - // 2. Copy user data - if ( dataUser.hasData( src ) ) { - udataOld = dataUser.access( src ); - udataCur = jQuery.extend( {}, udataOld ); - - dataUser.set( dest, udataCur ); - } - } - -// Fix IE bugs, see support tests - function fixInput( src, dest ) { - var nodeName = dest.nodeName.toLowerCase(); - - // Fails to persist the checked state of a cloned checkbox or radio button. - if ( nodeName === "input" && rcheckableType.test( src.type ) ) { - dest.checked = src.checked; - - // Fails to return the selected option to the default selected state when cloning options - } else if ( nodeName === "input" || nodeName === "textarea" ) { - dest.defaultValue = src.defaultValue; - } - } - - function domManip( collection, args, callback, ignored ) { - - // Flatten any nested arrays - args = concat.apply( [], args ); - - var fragment, first, scripts, hasScripts, node, doc, - i = 0, - l = collection.length, - iNoClone = l - 1, - value = args[ 0 ], - valueIsFunction = isFunction( value ); - - // We can't cloneNode fragments that contain checked, in WebKit - if ( valueIsFunction || - ( l > 1 && typeof value === "string" && - !support.checkClone && rchecked.test( value ) ) ) { - return collection.each( function( index ) { - var self = collection.eq( index ); - if ( valueIsFunction ) { - args[ 0 ] = value.call( this, index, self.html() ); - } - domManip( self, args, callback, ignored ); - } ); - } - - if ( l ) { - fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); - first = fragment.firstChild; - - if ( fragment.childNodes.length === 1 ) { - fragment = first; - } - - // Require either new content or an interest in ignored elements to invoke the callback - if ( first || ignored ) { - scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); - hasScripts = scripts.length; - - // Use the original fragment for the last item - // instead of the first because it can end up - // being emptied incorrectly in certain situations (#8070). - for ( ; i < l; i++ ) { - node = fragment; - - if ( i !== iNoClone ) { - node = jQuery.clone( node, true, true ); - - // Keep references to cloned scripts for later restoration - if ( hasScripts ) { - - // Support: Android <=4.0 only, PhantomJS 1 only - // push.apply(_, arraylike) throws on ancient WebKit - jQuery.merge( scripts, getAll( node, "script" ) ); - } - } - - callback.call( collection[ i ], node, i ); - } - - if ( hasScripts ) { - doc = scripts[ scripts.length - 1 ].ownerDocument; - - // Reenable scripts - jQuery.map( scripts, restoreScript ); - - // Evaluate executable scripts on first document insertion - for ( i = 0; i < hasScripts; i++ ) { - node = scripts[ i ]; - if ( rscriptType.test( node.type || "" ) && - !dataPriv.access( node, "globalEval" ) && - jQuery.contains( doc, node ) ) { - - if ( node.src && ( node.type || "" ).toLowerCase() !== "module" ) { - - // Optional AJAX dependency, but won't run scripts if not present - if ( jQuery._evalUrl ) { - jQuery._evalUrl( node.src ); - } - } else { - DOMEval( node.textContent.replace( rcleanScript, "" ), doc, node ); - } - } - } - } - } - } - - return collection; - } - - function remove( elem, selector, keepData ) { - var node, - nodes = selector ? jQuery.filter( selector, elem ) : elem, - i = 0; - - for ( ; ( node = nodes[ i ] ) != null; i++ ) { - if ( !keepData && node.nodeType === 1 ) { - jQuery.cleanData( getAll( node ) ); - } - - if ( node.parentNode ) { - if ( keepData && jQuery.contains( node.ownerDocument, node ) ) { - setGlobalEval( getAll( node, "script" ) ); - } - node.parentNode.removeChild( node ); - } - } - - return elem; - } - - jQuery.extend( { - htmlPrefilter: function( html ) { - return html.replace( rxhtmlTag, "<$1>" ); - }, - - clone: function( elem, dataAndEvents, deepDataAndEvents ) { - var i, l, srcElements, destElements, - clone = elem.cloneNode( true ), - inPage = jQuery.contains( elem.ownerDocument, elem ); - - // Fix IE cloning issues - if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && - !jQuery.isXMLDoc( elem ) ) { - - // We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2 - destElements = getAll( clone ); - srcElements = getAll( elem ); - - for ( i = 0, l = srcElements.length; i < l; i++ ) { - fixInput( srcElements[ i ], destElements[ i ] ); - } - } - - // Copy the events from the original to the clone - if ( dataAndEvents ) { - if ( deepDataAndEvents ) { - srcElements = srcElements || getAll( elem ); - destElements = destElements || getAll( clone ); - - for ( i = 0, l = srcElements.length; i < l; i++ ) { - cloneCopyEvent( srcElements[ i ], destElements[ i ] ); - } - } else { - cloneCopyEvent( elem, clone ); - } - } - - // Preserve script evaluation history - destElements = getAll( clone, "script" ); - if ( destElements.length > 0 ) { - setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); - } - - // Return the cloned set - return clone; - }, - - cleanData: function( elems ) { - var data, elem, type, - special = jQuery.event.special, - i = 0; - - for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { - if ( acceptData( elem ) ) { - if ( ( data = elem[ dataPriv.expando ] ) ) { - if ( data.events ) { - for ( type in data.events ) { - if ( special[ type ] ) { - jQuery.event.remove( elem, type ); - - // This is a shortcut to avoid jQuery.event.remove's overhead - } else { - jQuery.removeEvent( elem, type, data.handle ); - } - } - } - - // Support: Chrome <=35 - 45+ - // Assign undefined instead of using delete, see Data#remove - elem[ dataPriv.expando ] = undefined; - } - if ( elem[ dataUser.expando ] ) { - - // Support: Chrome <=35 - 45+ - // Assign undefined instead of using delete, see Data#remove - elem[ dataUser.expando ] = undefined; - } - } - } - } - } ); - - jQuery.fn.extend( { - detach: function( selector ) { - return remove( this, selector, true ); - }, - - remove: function( selector ) { - return remove( this, selector ); - }, - - text: function( value ) { - return access( this, function( value ) { - return value === undefined ? - jQuery.text( this ) : - this.empty().each( function() { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - this.textContent = value; - } - } ); - }, null, value, arguments.length ); - }, - - append: function() { - return domManip( this, arguments, function( elem ) { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - var target = manipulationTarget( this, elem ); - target.appendChild( elem ); - } - } ); - }, - - prepend: function() { - return domManip( this, arguments, function( elem ) { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - var target = manipulationTarget( this, elem ); - target.insertBefore( elem, target.firstChild ); - } - } ); - }, - - before: function() { - return domManip( this, arguments, function( elem ) { - if ( this.parentNode ) { - this.parentNode.insertBefore( elem, this ); - } - } ); - }, - - after: function() { - return domManip( this, arguments, function( elem ) { - if ( this.parentNode ) { - this.parentNode.insertBefore( elem, this.nextSibling ); - } - } ); - }, - - empty: function() { - var elem, - i = 0; - - for ( ; ( elem = this[ i ] ) != null; i++ ) { - if ( elem.nodeType === 1 ) { - - // Prevent memory leaks - jQuery.cleanData( getAll( elem, false ) ); - - // Remove any remaining nodes - elem.textContent = ""; - } - } - - return this; - }, - - clone: function( dataAndEvents, deepDataAndEvents ) { - dataAndEvents = dataAndEvents == null ? false : dataAndEvents; - deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; - - return this.map( function() { - return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); - } ); - }, - - html: function( value ) { - return access( this, function( value ) { - var elem = this[ 0 ] || {}, - i = 0, - l = this.length; - - if ( value === undefined && elem.nodeType === 1 ) { - return elem.innerHTML; - } - - // See if we can take a shortcut and just use innerHTML - if ( typeof value === "string" && !rnoInnerhtml.test( value ) && - !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { - - value = jQuery.htmlPrefilter( value ); - - try { - for ( ; i < l; i++ ) { - elem = this[ i ] || {}; - - // Remove element nodes and prevent memory leaks - if ( elem.nodeType === 1 ) { - jQuery.cleanData( getAll( elem, false ) ); - elem.innerHTML = value; - } - } - - elem = 0; - - // If using innerHTML throws an exception, use the fallback method - } catch ( e ) {} - } - - if ( elem ) { - this.empty().append( value ); - } - }, null, value, arguments.length ); - }, - - replaceWith: function() { - var ignored = []; - - // Make the changes, replacing each non-ignored context element with the new content - return domManip( this, arguments, function( elem ) { - var parent = this.parentNode; - - if ( jQuery.inArray( this, ignored ) < 0 ) { - jQuery.cleanData( getAll( this ) ); - if ( parent ) { - parent.replaceChild( elem, this ); - } - } - - // Force callback invocation - }, ignored ); - } - } ); - - jQuery.each( { - appendTo: "append", - prependTo: "prepend", - insertBefore: "before", - insertAfter: "after", - replaceAll: "replaceWith" - }, function( name, original ) { - jQuery.fn[ name ] = function( selector ) { - var elems, - ret = [], - insert = jQuery( selector ), - last = insert.length - 1, - i = 0; - - for ( ; i <= last; i++ ) { - elems = i === last ? this : this.clone( true ); - jQuery( insert[ i ] )[ original ]( elems ); - - // Support: Android <=4.0 only, PhantomJS 1 only - // .get() because push.apply(_, arraylike) throws on ancient WebKit - push.apply( ret, elems.get() ); - } - - return this.pushStack( ret ); - }; - } ); - var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); - - var getStyles = function( elem ) { - - // Support: IE <=11 only, Firefox <=30 (#15098, #14150) - // IE throws on elements created in popups - // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" - var view = elem.ownerDocument.defaultView; - - if ( !view || !view.opener ) { - view = window; - } - - return view.getComputedStyle( elem ); - }; - - var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" ); - - - - ( function() { - - // Executing both pixelPosition & boxSizingReliable tests require only one layout - // so they're executed at the same time to save the second computation. - function computeStyleTests() { - - // This is a singleton, we need to execute it only once - if ( !div ) { - return; - } - - container.style.cssText = "position:absolute;left:-11111px;width:60px;" + - "margin-top:1px;padding:0;border:0"; - div.style.cssText = - "position:relative;display:block;box-sizing:border-box;overflow:scroll;" + - "margin:auto;border:1px;padding:1px;" + - "width:60%;top:1%"; - documentElement.appendChild( container ).appendChild( div ); - - var divStyle = window.getComputedStyle( div ); - pixelPositionVal = divStyle.top !== "1%"; - - // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44 - reliableMarginLeftVal = roundPixelMeasures( divStyle.marginLeft ) === 12; - - // Support: Android 4.0 - 4.3 only, Safari <=9.1 - 10.1, iOS <=7.0 - 9.3 - // Some styles come back with percentage values, even though they shouldn't - div.style.right = "60%"; - pixelBoxStylesVal = roundPixelMeasures( divStyle.right ) === 36; - - // Support: IE 9 - 11 only - // Detect misreporting of content dimensions for box-sizing:border-box elements - boxSizingReliableVal = roundPixelMeasures( divStyle.width ) === 36; - - // Support: IE 9 only - // Detect overflow:scroll screwiness (gh-3699) - div.style.position = "absolute"; - scrollboxSizeVal = div.offsetWidth === 36 || "absolute"; - - documentElement.removeChild( container ); - - // Nullify the div so it wouldn't be stored in the memory and - // it will also be a sign that checks already performed - div = null; - } - - function roundPixelMeasures( measure ) { - return Math.round( parseFloat( measure ) ); - } - - var pixelPositionVal, boxSizingReliableVal, scrollboxSizeVal, pixelBoxStylesVal, - reliableMarginLeftVal, - container = document.createElement( "div" ), - div = document.createElement( "div" ); - - // Finish early in limited (non-browser) environments - if ( !div.style ) { - return; - } - - // Support: IE <=9 - 11 only - // Style of cloned element affects source element cloned (#8908) - div.style.backgroundClip = "content-box"; - div.cloneNode( true ).style.backgroundClip = ""; - support.clearCloneStyle = div.style.backgroundClip === "content-box"; - - jQuery.extend( support, { - boxSizingReliable: function() { - computeStyleTests(); - return boxSizingReliableVal; - }, - pixelBoxStyles: function() { - computeStyleTests(); - return pixelBoxStylesVal; - }, - pixelPosition: function() { - computeStyleTests(); - return pixelPositionVal; - }, - reliableMarginLeft: function() { - computeStyleTests(); - return reliableMarginLeftVal; - }, - scrollboxSize: function() { - computeStyleTests(); - return scrollboxSizeVal; - } - } ); - } )(); - - - function curCSS( elem, name, computed ) { - var width, minWidth, maxWidth, ret, - - // Support: Firefox 51+ - // Retrieving style before computed somehow - // fixes an issue with getting wrong values - // on detached elements - style = elem.style; - - computed = computed || getStyles( elem ); - - // getPropertyValue is needed for: - // .css('filter') (IE 9 only, #12537) - // .css('--customProperty) (#3144) - if ( computed ) { - ret = computed.getPropertyValue( name ) || computed[ name ]; - - if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { - ret = jQuery.style( elem, name ); - } - - // A tribute to the "awesome hack by Dean Edwards" - // Android Browser returns percentage for some values, - // but width seems to be reliably pixels. - // This is against the CSSOM draft spec: - // https://drafts.csswg.org/cssom/#resolved-values - if ( !support.pixelBoxStyles() && rnumnonpx.test( ret ) && rboxStyle.test( name ) ) { - - // Remember the original values - width = style.width; - minWidth = style.minWidth; - maxWidth = style.maxWidth; - - // Put in the new values to get a computed value out - style.minWidth = style.maxWidth = style.width = ret; - ret = computed.width; - - // Revert the changed values - style.width = width; - style.minWidth = minWidth; - style.maxWidth = maxWidth; - } - } - - return ret !== undefined ? - - // Support: IE <=9 - 11 only - // IE returns zIndex value as an integer. - ret + "" : - ret; - } - - - function addGetHookIf( conditionFn, hookFn ) { - - // Define the hook, we'll check on the first run if it's really needed. - return { - get: function() { - if ( conditionFn() ) { - - // Hook not needed (or it's not possible to use it due - // to missing dependency), remove it. - delete this.get; - return; - } - - // Hook needed; redefine it so that the support test is not executed again. - return ( this.get = hookFn ).apply( this, arguments ); - } - }; - } - - - var - - // Swappable if display is none or starts with table - // except "table", "table-cell", or "table-caption" - // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display - rdisplayswap = /^(none|table(?!-c[ea]).+)/, - rcustomProp = /^--/, - cssShow = { position: "absolute", visibility: "hidden", display: "block" }, - cssNormalTransform = { - letterSpacing: "0", - fontWeight: "400" - }, - - cssPrefixes = [ "Webkit", "Moz", "ms" ], - emptyStyle = document.createElement( "div" ).style; - -// Return a css property mapped to a potentially vendor prefixed property - function vendorPropName( name ) { - - // Shortcut for names that are not vendor prefixed - if ( name in emptyStyle ) { - return name; - } - - // Check for vendor prefixed names - var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), - i = cssPrefixes.length; - - while ( i-- ) { - name = cssPrefixes[ i ] + capName; - if ( name in emptyStyle ) { - return name; - } - } - } - -// Return a property mapped along what jQuery.cssProps suggests or to -// a vendor prefixed property. - function finalPropName( name ) { - var ret = jQuery.cssProps[ name ]; - if ( !ret ) { - ret = jQuery.cssProps[ name ] = vendorPropName( name ) || name; - } - return ret; - } - - function setPositiveNumber( elem, value, subtract ) { - - // Any relative (+/-) values have already been - // normalized at this point - var matches = rcssNum.exec( value ); - return matches ? - - // Guard against undefined "subtract", e.g., when used as in cssHooks - Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : - value; - } - - function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computedVal ) { - var i = dimension === "width" ? 1 : 0, - extra = 0, - delta = 0; - - // Adjustment may not be necessary - if ( box === ( isBorderBox ? "border" : "content" ) ) { - return 0; - } - - for ( ; i < 4; i += 2 ) { - - // Both box models exclude margin - if ( box === "margin" ) { - delta += jQuery.css( elem, box + cssExpand[ i ], true, styles ); - } - - // If we get here with a content-box, we're seeking "padding" or "border" or "margin" - if ( !isBorderBox ) { - - // Add padding - delta += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); - - // For "border" or "margin", add border - if ( box !== "padding" ) { - delta += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); - - // But still keep track of it otherwise - } else { - extra += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); - } - - // If we get here with a border-box (content + padding + border), we're seeking "content" or - // "padding" or "margin" - } else { - - // For "content", subtract padding - if ( box === "content" ) { - delta -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); - } - - // For "content" or "padding", subtract border - if ( box !== "margin" ) { - delta -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); - } - } - } - - // Account for positive content-box scroll gutter when requested by providing computedVal - if ( !isBorderBox && computedVal >= 0 ) { - - // offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border - // Assuming integer scroll gutter, subtract the rest and round down - delta += Math.max( 0, Math.ceil( - elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - - computedVal - - delta - - extra - - 0.5 - ) ); - } - - return delta; - } - - function getWidthOrHeight( elem, dimension, extra ) { - - // Start with computed style - var styles = getStyles( elem ), - val = curCSS( elem, dimension, styles ), - isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box", - valueIsBorderBox = isBorderBox; - - // Support: Firefox <=54 - // Return a confounding non-pixel value or feign ignorance, as appropriate. - if ( rnumnonpx.test( val ) ) { - if ( !extra ) { - return val; - } - val = "auto"; - } - - // Check for style in case a browser which returns unreliable values - // for getComputedStyle silently falls back to the reliable elem.style - valueIsBorderBox = valueIsBorderBox && - ( support.boxSizingReliable() || val === elem.style[ dimension ] ); - - // Fall back to offsetWidth/offsetHeight when value is "auto" - // This happens for inline elements with no explicit setting (gh-3571) - // Support: Android <=4.1 - 4.3 only - // Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602) - if ( val === "auto" || - !parseFloat( val ) && jQuery.css( elem, "display", false, styles ) === "inline" ) { - - val = elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ]; - - // offsetWidth/offsetHeight provide border-box values - valueIsBorderBox = true; - } - - // Normalize "" and auto - val = parseFloat( val ) || 0; - - // Adjust for the element's box model - return ( val + - boxModelAdjustment( - elem, - dimension, - extra || ( isBorderBox ? "border" : "content" ), - valueIsBorderBox, - styles, - - // Provide the current computed size to request scroll gutter calculation (gh-3589) - val - ) - ) + "px"; - } - - jQuery.extend( { - - // Add in style property hooks for overriding the default - // behavior of getting and setting a style property - cssHooks: { - opacity: { - get: function( elem, computed ) { - if ( computed ) { - - // We should always get a number back from opacity - var ret = curCSS( elem, "opacity" ); - return ret === "" ? "1" : ret; - } - } - } - }, - - // Don't automatically add "px" to these possibly-unitless properties - cssNumber: { - "animationIterationCount": true, - "columnCount": true, - "fillOpacity": true, - "flexGrow": true, - "flexShrink": true, - "fontWeight": true, - "lineHeight": true, - "opacity": true, - "order": true, - "orphans": true, - "widows": true, - "zIndex": true, - "zoom": true - }, - - // Add in properties whose names you wish to fix before - // setting or getting the value - cssProps: {}, - - // Get and set the style property on a DOM Node - style: function( elem, name, value, extra ) { - - // Don't set styles on text and comment nodes - if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { - return; - } - - // Make sure that we're working with the right name - var ret, type, hooks, - origName = camelCase( name ), - isCustomProp = rcustomProp.test( name ), - style = elem.style; - - // Make sure that we're working with the right name. We don't - // want to query the value if it is a CSS custom property - // since they are user-defined. - if ( !isCustomProp ) { - name = finalPropName( origName ); - } - - // Gets hook for the prefixed version, then unprefixed version - hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; - - // Check if we're setting a value - if ( value !== undefined ) { - type = typeof value; - - // Convert "+=" or "-=" to relative numbers (#7345) - if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { - value = adjustCSS( elem, name, ret ); - - // Fixes bug #9237 - type = "number"; - } - - // Make sure that null and NaN values aren't set (#7116) - if ( value == null || value !== value ) { - return; - } - - // If a number was passed in, add the unit (except for certain CSS properties) - if ( type === "number" ) { - value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" ); - } - - // background-* props affect original clone's values - if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { - style[ name ] = "inherit"; - } - - // If a hook was provided, use that value, otherwise just set the specified value - if ( !hooks || !( "set" in hooks ) || - ( value = hooks.set( elem, value, extra ) ) !== undefined ) { - - if ( isCustomProp ) { - style.setProperty( name, value ); - } else { - style[ name ] = value; - } - } - - } else { - - // If a hook was provided get the non-computed value from there - if ( hooks && "get" in hooks && - ( ret = hooks.get( elem, false, extra ) ) !== undefined ) { - - return ret; - } - - // Otherwise just get the value from the style object - return style[ name ]; - } - }, - - css: function( elem, name, extra, styles ) { - var val, num, hooks, - origName = camelCase( name ), - isCustomProp = rcustomProp.test( name ); - - // Make sure that we're working with the right name. We don't - // want to modify the value if it is a CSS custom property - // since they are user-defined. - if ( !isCustomProp ) { - name = finalPropName( origName ); - } - - // Try prefixed name followed by the unprefixed name - hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; - - // If a hook was provided get the computed value from there - if ( hooks && "get" in hooks ) { - val = hooks.get( elem, true, extra ); - } - - // Otherwise, if a way to get the computed value exists, use that - if ( val === undefined ) { - val = curCSS( elem, name, styles ); - } - - // Convert "normal" to computed value - if ( val === "normal" && name in cssNormalTransform ) { - val = cssNormalTransform[ name ]; - } - - // Make numeric if forced or a qualifier was provided and val looks numeric - if ( extra === "" || extra ) { - num = parseFloat( val ); - return extra === true || isFinite( num ) ? num || 0 : val; - } - - return val; - } - } ); - - jQuery.each( [ "height", "width" ], function( i, dimension ) { - jQuery.cssHooks[ dimension ] = { - get: function( elem, computed, extra ) { - if ( computed ) { - - // Certain elements can have dimension info if we invisibly show them - // but it must have a current display style that would benefit - return rdisplayswap.test( jQuery.css( elem, "display" ) ) && - - // Support: Safari 8+ - // Table columns in Safari have non-zero offsetWidth & zero - // getBoundingClientRect().width unless display is changed. - // Support: IE <=11 only - // Running getBoundingClientRect on a disconnected node - // in IE throws an error. - ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ? - swap( elem, cssShow, function() { - return getWidthOrHeight( elem, dimension, extra ); - } ) : - getWidthOrHeight( elem, dimension, extra ); - } - }, - - set: function( elem, value, extra ) { - var matches, - styles = getStyles( elem ), - isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box", - subtract = extra && boxModelAdjustment( - elem, - dimension, - extra, - isBorderBox, - styles - ); - - // Account for unreliable border-box dimensions by comparing offset* to computed and - // faking a content-box to get border and padding (gh-3699) - if ( isBorderBox && support.scrollboxSize() === styles.position ) { - subtract -= Math.ceil( - elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - - parseFloat( styles[ dimension ] ) - - boxModelAdjustment( elem, dimension, "border", false, styles ) - - 0.5 - ); - } - - // Convert to pixels if value adjustment is needed - if ( subtract && ( matches = rcssNum.exec( value ) ) && - ( matches[ 3 ] || "px" ) !== "px" ) { - - elem.style[ dimension ] = value; - value = jQuery.css( elem, dimension ); - } - - return setPositiveNumber( elem, value, subtract ); - } - }; - } ); - - jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, - function( elem, computed ) { - if ( computed ) { - return ( parseFloat( curCSS( elem, "marginLeft" ) ) || - elem.getBoundingClientRect().left - - swap( elem, { marginLeft: 0 }, function() { - return elem.getBoundingClientRect().left; - } ) - ) + "px"; - } - } - ); - -// These hooks are used by animate to expand properties - jQuery.each( { - margin: "", - padding: "", - border: "Width" - }, function( prefix, suffix ) { - jQuery.cssHooks[ prefix + suffix ] = { - expand: function( value ) { - var i = 0, - expanded = {}, - - // Assumes a single number if not a string - parts = typeof value === "string" ? value.split( " " ) : [ value ]; - - for ( ; i < 4; i++ ) { - expanded[ prefix + cssExpand[ i ] + suffix ] = - parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; - } - - return expanded; - } - }; - - if ( prefix !== "margin" ) { - jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; - } - } ); - - jQuery.fn.extend( { - css: function( name, value ) { - return access( this, function( elem, name, value ) { - var styles, len, - map = {}, - i = 0; - - if ( Array.isArray( name ) ) { - styles = getStyles( elem ); - len = name.length; - - for ( ; i < len; i++ ) { - map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); - } - - return map; - } - - return value !== undefined ? - jQuery.style( elem, name, value ) : - jQuery.css( elem, name ); - }, name, value, arguments.length > 1 ); - } - } ); - - - function Tween( elem, options, prop, end, easing ) { - return new Tween.prototype.init( elem, options, prop, end, easing ); - } - jQuery.Tween = Tween; - - Tween.prototype = { - constructor: Tween, - init: function( elem, options, prop, end, easing, unit ) { - this.elem = elem; - this.prop = prop; - this.easing = easing || jQuery.easing._default; - this.options = options; - this.start = this.now = this.cur(); - this.end = end; - this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); - }, - cur: function() { - var hooks = Tween.propHooks[ this.prop ]; - - return hooks && hooks.get ? - hooks.get( this ) : - Tween.propHooks._default.get( this ); - }, - run: function( percent ) { - var eased, - hooks = Tween.propHooks[ this.prop ]; - - if ( this.options.duration ) { - this.pos = eased = jQuery.easing[ this.easing ]( - percent, this.options.duration * percent, 0, 1, this.options.duration - ); - } else { - this.pos = eased = percent; - } - this.now = ( this.end - this.start ) * eased + this.start; - - if ( this.options.step ) { - this.options.step.call( this.elem, this.now, this ); - } - - if ( hooks && hooks.set ) { - hooks.set( this ); - } else { - Tween.propHooks._default.set( this ); - } - return this; - } - }; - - Tween.prototype.init.prototype = Tween.prototype; - - Tween.propHooks = { - _default: { - get: function( tween ) { - var result; - - // Use a property on the element directly when it is not a DOM element, - // or when there is no matching style property that exists. - if ( tween.elem.nodeType !== 1 || - tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) { - return tween.elem[ tween.prop ]; - } - - // Passing an empty string as a 3rd parameter to .css will automatically - // attempt a parseFloat and fallback to a string if the parse fails. - // Simple values such as "10px" are parsed to Float; - // complex values such as "rotate(1rad)" are returned as-is. - result = jQuery.css( tween.elem, tween.prop, "" ); - - // Empty strings, null, undefined and "auto" are converted to 0. - return !result || result === "auto" ? 0 : result; - }, - set: function( tween ) { - - // Use step hook for back compat. - // Use cssHook if its there. - // Use .style if available and use plain properties where available. - if ( jQuery.fx.step[ tween.prop ] ) { - jQuery.fx.step[ tween.prop ]( tween ); - } else if ( tween.elem.nodeType === 1 && - ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || - jQuery.cssHooks[ tween.prop ] ) ) { - jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); - } else { - tween.elem[ tween.prop ] = tween.now; - } - } - } - }; - -// Support: IE <=9 only -// Panic based approach to setting things on disconnected nodes - Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { - set: function( tween ) { - if ( tween.elem.nodeType && tween.elem.parentNode ) { - tween.elem[ tween.prop ] = tween.now; - } - } - }; - - jQuery.easing = { - linear: function( p ) { - return p; - }, - swing: function( p ) { - return 0.5 - Math.cos( p * Math.PI ) / 2; - }, - _default: "swing" - }; - - jQuery.fx = Tween.prototype.init; - -// Back compat <1.8 extension point - jQuery.fx.step = {}; - - - - - var - fxNow, inProgress, - rfxtypes = /^(?:toggle|show|hide)$/, - rrun = /queueHooks$/; - - function schedule() { - if ( inProgress ) { - if ( document.hidden === false && window.requestAnimationFrame ) { - window.requestAnimationFrame( schedule ); - } else { - window.setTimeout( schedule, jQuery.fx.interval ); - } - - jQuery.fx.tick(); - } - } - -// Animations created synchronously will run synchronously - function createFxNow() { - window.setTimeout( function() { - fxNow = undefined; - } ); - return ( fxNow = Date.now() ); - } - -// Generate parameters to create a standard animation - function genFx( type, includeWidth ) { - var which, - i = 0, - attrs = { height: type }; - - // If we include width, step value is 1 to do all cssExpand values, - // otherwise step value is 2 to skip over Left and Right - includeWidth = includeWidth ? 1 : 0; - for ( ; i < 4; i += 2 - includeWidth ) { - which = cssExpand[ i ]; - attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; - } - - if ( includeWidth ) { - attrs.opacity = attrs.width = type; - } - - return attrs; - } - - function createTween( value, prop, animation ) { - var tween, - collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ), - index = 0, - length = collection.length; - for ( ; index < length; index++ ) { - if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) { - - // We're done with this property - return tween; - } - } - } - - function defaultPrefilter( elem, props, opts ) { - var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display, - isBox = "width" in props || "height" in props, - anim = this, - orig = {}, - style = elem.style, - hidden = elem.nodeType && isHiddenWithinTree( elem ), - dataShow = dataPriv.get( elem, "fxshow" ); - - // Queue-skipping animations hijack the fx hooks - if ( !opts.queue ) { - hooks = jQuery._queueHooks( elem, "fx" ); - if ( hooks.unqueued == null ) { - hooks.unqueued = 0; - oldfire = hooks.empty.fire; - hooks.empty.fire = function() { - if ( !hooks.unqueued ) { - oldfire(); - } - }; - } - hooks.unqueued++; - - anim.always( function() { - - // Ensure the complete handler is called before this completes - anim.always( function() { - hooks.unqueued--; - if ( !jQuery.queue( elem, "fx" ).length ) { - hooks.empty.fire(); - } - } ); - } ); - } - - // Detect show/hide animations - for ( prop in props ) { - value = props[ prop ]; - if ( rfxtypes.test( value ) ) { - delete props[ prop ]; - toggle = toggle || value === "toggle"; - if ( value === ( hidden ? "hide" : "show" ) ) { - - // Pretend to be hidden if this is a "show" and - // there is still data from a stopped show/hide - if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { - hidden = true; - - // Ignore all other no-op show/hide data - } else { - continue; - } - } - orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); - } - } - - // Bail out if this is a no-op like .hide().hide() - propTween = !jQuery.isEmptyObject( props ); - if ( !propTween && jQuery.isEmptyObject( orig ) ) { - return; - } - - // Restrict "overflow" and "display" styles during box animations - if ( isBox && elem.nodeType === 1 ) { - - // Support: IE <=9 - 11, Edge 12 - 15 - // Record all 3 overflow attributes because IE does not infer the shorthand - // from identically-valued overflowX and overflowY and Edge just mirrors - // the overflowX value there. - opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; - - // Identify a display type, preferring old show/hide data over the CSS cascade - restoreDisplay = dataShow && dataShow.display; - if ( restoreDisplay == null ) { - restoreDisplay = dataPriv.get( elem, "display" ); - } - display = jQuery.css( elem, "display" ); - if ( display === "none" ) { - if ( restoreDisplay ) { - display = restoreDisplay; - } else { - - // Get nonempty value(s) by temporarily forcing visibility - showHide( [ elem ], true ); - restoreDisplay = elem.style.display || restoreDisplay; - display = jQuery.css( elem, "display" ); - showHide( [ elem ] ); - } - } - - // Animate inline elements as inline-block - if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) { - if ( jQuery.css( elem, "float" ) === "none" ) { - - // Restore the original display value at the end of pure show/hide animations - if ( !propTween ) { - anim.done( function() { - style.display = restoreDisplay; - } ); - if ( restoreDisplay == null ) { - display = style.display; - restoreDisplay = display === "none" ? "" : display; - } - } - style.display = "inline-block"; - } - } - } - - if ( opts.overflow ) { - style.overflow = "hidden"; - anim.always( function() { - style.overflow = opts.overflow[ 0 ]; - style.overflowX = opts.overflow[ 1 ]; - style.overflowY = opts.overflow[ 2 ]; - } ); - } - - // Implement show/hide animations - propTween = false; - for ( prop in orig ) { - - // General show/hide setup for this element animation - if ( !propTween ) { - if ( dataShow ) { - if ( "hidden" in dataShow ) { - hidden = dataShow.hidden; - } - } else { - dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } ); - } - - // Store hidden/visible for toggle so `.stop().toggle()` "reverses" - if ( toggle ) { - dataShow.hidden = !hidden; - } - - // Show elements before animating them - if ( hidden ) { - showHide( [ elem ], true ); - } - - /* eslint-disable no-loop-func */ - - anim.done( function() { - - /* eslint-enable no-loop-func */ - - // The final step of a "hide" animation is actually hiding the element - if ( !hidden ) { - showHide( [ elem ] ); - } - dataPriv.remove( elem, "fxshow" ); - for ( prop in orig ) { - jQuery.style( elem, prop, orig[ prop ] ); - } - } ); - } - - // Per-property setup - propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); - if ( !( prop in dataShow ) ) { - dataShow[ prop ] = propTween.start; - if ( hidden ) { - propTween.end = propTween.start; - propTween.start = 0; - } - } - } - } - - function propFilter( props, specialEasing ) { - var index, name, easing, value, hooks; - - // camelCase, specialEasing and expand cssHook pass - for ( index in props ) { - name = camelCase( index ); - easing = specialEasing[ name ]; - value = props[ index ]; - if ( Array.isArray( value ) ) { - easing = value[ 1 ]; - value = props[ index ] = value[ 0 ]; - } - - if ( index !== name ) { - props[ name ] = value; - delete props[ index ]; - } - - hooks = jQuery.cssHooks[ name ]; - if ( hooks && "expand" in hooks ) { - value = hooks.expand( value ); - delete props[ name ]; - - // Not quite $.extend, this won't overwrite existing keys. - // Reusing 'index' because we have the correct "name" - for ( index in value ) { - if ( !( index in props ) ) { - props[ index ] = value[ index ]; - specialEasing[ index ] = easing; - } - } - } else { - specialEasing[ name ] = easing; - } - } - } - - function Animation( elem, properties, options ) { - var result, - stopped, - index = 0, - length = Animation.prefilters.length, - deferred = jQuery.Deferred().always( function() { - - // Don't match elem in the :animated selector - delete tick.elem; - } ), - tick = function() { - if ( stopped ) { - return false; - } - var currentTime = fxNow || createFxNow(), - remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), - - // Support: Android 2.3 only - // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497) - temp = remaining / animation.duration || 0, - percent = 1 - temp, - index = 0, - length = animation.tweens.length; - - for ( ; index < length; index++ ) { - animation.tweens[ index ].run( percent ); - } - - deferred.notifyWith( elem, [ animation, percent, remaining ] ); - - // If there's more to do, yield - if ( percent < 1 && length ) { - return remaining; - } - - // If this was an empty animation, synthesize a final progress notification - if ( !length ) { - deferred.notifyWith( elem, [ animation, 1, 0 ] ); - } - - // Resolve the animation and report its conclusion - deferred.resolveWith( elem, [ animation ] ); - return false; - }, - animation = deferred.promise( { - elem: elem, - props: jQuery.extend( {}, properties ), - opts: jQuery.extend( true, { - specialEasing: {}, - easing: jQuery.easing._default - }, options ), - originalProperties: properties, - originalOptions: options, - startTime: fxNow || createFxNow(), - duration: options.duration, - tweens: [], - createTween: function( prop, end ) { - var tween = jQuery.Tween( elem, animation.opts, prop, end, - animation.opts.specialEasing[ prop ] || animation.opts.easing ); - animation.tweens.push( tween ); - return tween; - }, - stop: function( gotoEnd ) { - var index = 0, - - // If we are going to the end, we want to run all the tweens - // otherwise we skip this part - length = gotoEnd ? animation.tweens.length : 0; - if ( stopped ) { - return this; - } - stopped = true; - for ( ; index < length; index++ ) { - animation.tweens[ index ].run( 1 ); - } - - // Resolve when we played the last frame; otherwise, reject - if ( gotoEnd ) { - deferred.notifyWith( elem, [ animation, 1, 0 ] ); - deferred.resolveWith( elem, [ animation, gotoEnd ] ); - } else { - deferred.rejectWith( elem, [ animation, gotoEnd ] ); - } - return this; - } - } ), - props = animation.props; - - propFilter( props, animation.opts.specialEasing ); - - for ( ; index < length; index++ ) { - result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); - if ( result ) { - if ( isFunction( result.stop ) ) { - jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = - result.stop.bind( result ); - } - return result; - } - } - - jQuery.map( props, createTween, animation ); - - if ( isFunction( animation.opts.start ) ) { - animation.opts.start.call( elem, animation ); - } - - // Attach callbacks from options - animation - .progress( animation.opts.progress ) - .done( animation.opts.done, animation.opts.complete ) - .fail( animation.opts.fail ) - .always( animation.opts.always ); - - jQuery.fx.timer( - jQuery.extend( tick, { - elem: elem, - anim: animation, - queue: animation.opts.queue - } ) - ); - - return animation; - } - - jQuery.Animation = jQuery.extend( Animation, { - - tweeners: { - "*": [ function( prop, value ) { - var tween = this.createTween( prop, value ); - adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween ); - return tween; - } ] - }, - - tweener: function( props, callback ) { - if ( isFunction( props ) ) { - callback = props; - props = [ "*" ]; - } else { - props = props.match( rnothtmlwhite ); - } - - var prop, - index = 0, - length = props.length; - - for ( ; index < length; index++ ) { - prop = props[ index ]; - Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || []; - Animation.tweeners[ prop ].unshift( callback ); - } - }, - - prefilters: [ defaultPrefilter ], - - prefilter: function( callback, prepend ) { - if ( prepend ) { - Animation.prefilters.unshift( callback ); - } else { - Animation.prefilters.push( callback ); - } - } - } ); - - jQuery.speed = function( speed, easing, fn ) { - var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { - complete: fn || !fn && easing || - isFunction( speed ) && speed, - duration: speed, - easing: fn && easing || easing && !isFunction( easing ) && easing - }; - - // Go to the end state if fx are off - if ( jQuery.fx.off ) { - opt.duration = 0; - - } else { - if ( typeof opt.duration !== "number" ) { - if ( opt.duration in jQuery.fx.speeds ) { - opt.duration = jQuery.fx.speeds[ opt.duration ]; - - } else { - opt.duration = jQuery.fx.speeds._default; - } - } - } - - // Normalize opt.queue - true/undefined/null -> "fx" - if ( opt.queue == null || opt.queue === true ) { - opt.queue = "fx"; - } - - // Queueing - opt.old = opt.complete; - - opt.complete = function() { - if ( isFunction( opt.old ) ) { - opt.old.call( this ); - } - - if ( opt.queue ) { - jQuery.dequeue( this, opt.queue ); - } - }; - - return opt; - }; - - jQuery.fn.extend( { - fadeTo: function( speed, to, easing, callback ) { - - // Show any hidden elements after setting opacity to 0 - return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show() - - // Animate to the value specified - .end().animate( { opacity: to }, speed, easing, callback ); - }, - animate: function( prop, speed, easing, callback ) { - var empty = jQuery.isEmptyObject( prop ), - optall = jQuery.speed( speed, easing, callback ), - doAnimation = function() { - - // Operate on a copy of prop so per-property easing won't be lost - var anim = Animation( this, jQuery.extend( {}, prop ), optall ); - - // Empty animations, or finishing resolves immediately - if ( empty || dataPriv.get( this, "finish" ) ) { - anim.stop( true ); - } - }; - doAnimation.finish = doAnimation; - - return empty || optall.queue === false ? - this.each( doAnimation ) : - this.queue( optall.queue, doAnimation ); - }, - stop: function( type, clearQueue, gotoEnd ) { - var stopQueue = function( hooks ) { - var stop = hooks.stop; - delete hooks.stop; - stop( gotoEnd ); - }; - - if ( typeof type !== "string" ) { - gotoEnd = clearQueue; - clearQueue = type; - type = undefined; - } - if ( clearQueue && type !== false ) { - this.queue( type || "fx", [] ); - } - - return this.each( function() { - var dequeue = true, - index = type != null && type + "queueHooks", - timers = jQuery.timers, - data = dataPriv.get( this ); - - if ( index ) { - if ( data[ index ] && data[ index ].stop ) { - stopQueue( data[ index ] ); - } - } else { - for ( index in data ) { - if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { - stopQueue( data[ index ] ); - } - } - } - - for ( index = timers.length; index--; ) { - if ( timers[ index ].elem === this && - ( type == null || timers[ index ].queue === type ) ) { - - timers[ index ].anim.stop( gotoEnd ); - dequeue = false; - timers.splice( index, 1 ); - } - } - - // Start the next in the queue if the last step wasn't forced. - // Timers currently will call their complete callbacks, which - // will dequeue but only if they were gotoEnd. - if ( dequeue || !gotoEnd ) { - jQuery.dequeue( this, type ); - } - } ); - }, - finish: function( type ) { - if ( type !== false ) { - type = type || "fx"; - } - return this.each( function() { - var index, - data = dataPriv.get( this ), - queue = data[ type + "queue" ], - hooks = data[ type + "queueHooks" ], - timers = jQuery.timers, - length = queue ? queue.length : 0; - - // Enable finishing flag on private data - data.finish = true; - - // Empty the queue first - jQuery.queue( this, type, [] ); - - if ( hooks && hooks.stop ) { - hooks.stop.call( this, true ); - } - - // Look for any active animations, and finish them - for ( index = timers.length; index--; ) { - if ( timers[ index ].elem === this && timers[ index ].queue === type ) { - timers[ index ].anim.stop( true ); - timers.splice( index, 1 ); - } - } - - // Look for any animations in the old queue and finish them - for ( index = 0; index < length; index++ ) { - if ( queue[ index ] && queue[ index ].finish ) { - queue[ index ].finish.call( this ); - } - } - - // Turn off finishing flag - delete data.finish; - } ); - } - } ); - - jQuery.each( [ "toggle", "show", "hide" ], function( i, name ) { - var cssFn = jQuery.fn[ name ]; - jQuery.fn[ name ] = function( speed, easing, callback ) { - return speed == null || typeof speed === "boolean" ? - cssFn.apply( this, arguments ) : - this.animate( genFx( name, true ), speed, easing, callback ); - }; - } ); - -// Generate shortcuts for custom animations - jQuery.each( { - slideDown: genFx( "show" ), - slideUp: genFx( "hide" ), - slideToggle: genFx( "toggle" ), - fadeIn: { opacity: "show" }, - fadeOut: { opacity: "hide" }, - fadeToggle: { opacity: "toggle" } - }, function( name, props ) { - jQuery.fn[ name ] = function( speed, easing, callback ) { - return this.animate( props, speed, easing, callback ); - }; - } ); - - jQuery.timers = []; - jQuery.fx.tick = function() { - var timer, - i = 0, - timers = jQuery.timers; - - fxNow = Date.now(); - - for ( ; i < timers.length; i++ ) { - timer = timers[ i ]; - - // Run the timer and safely remove it when done (allowing for external removal) - if ( !timer() && timers[ i ] === timer ) { - timers.splice( i--, 1 ); - } - } - - if ( !timers.length ) { - jQuery.fx.stop(); - } - fxNow = undefined; - }; - - jQuery.fx.timer = function( timer ) { - jQuery.timers.push( timer ); - jQuery.fx.start(); - }; - - jQuery.fx.interval = 13; - jQuery.fx.start = function() { - if ( inProgress ) { - return; - } - - inProgress = true; - schedule(); - }; - - jQuery.fx.stop = function() { - inProgress = null; - }; - - jQuery.fx.speeds = { - slow: 600, - fast: 200, - - // Default speed - _default: 400 - }; - - -// Based off of the plugin by Clint Helfers, with permission. -// https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/ - jQuery.fn.delay = function( time, type ) { - time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; - type = type || "fx"; - - return this.queue( type, function( next, hooks ) { - var timeout = window.setTimeout( next, time ); - hooks.stop = function() { - window.clearTimeout( timeout ); - }; - } ); - }; - - - ( function() { - var input = document.createElement( "input" ), - select = document.createElement( "select" ), - opt = select.appendChild( document.createElement( "option" ) ); - - input.type = "checkbox"; - - // Support: Android <=4.3 only - // Default value for a checkbox should be "on" - support.checkOn = input.value !== ""; - - // Support: IE <=11 only - // Must access selectedIndex to make default options select - support.optSelected = opt.selected; - - // Support: IE <=11 only - // An input loses its value after becoming a radio - input = document.createElement( "input" ); - input.value = "t"; - input.type = "radio"; - support.radioValue = input.value === "t"; - } )(); - - - var boolHook, - attrHandle = jQuery.expr.attrHandle; - - jQuery.fn.extend( { - attr: function( name, value ) { - return access( this, jQuery.attr, name, value, arguments.length > 1 ); - }, - - removeAttr: function( name ) { - return this.each( function() { - jQuery.removeAttr( this, name ); - } ); - } - } ); - - jQuery.extend( { - attr: function( elem, name, value ) { - var ret, hooks, - nType = elem.nodeType; - - // Don't get/set attributes on text, comment and attribute nodes - if ( nType === 3 || nType === 8 || nType === 2 ) { - return; - } - - // Fallback to prop when attributes are not supported - if ( typeof elem.getAttribute === "undefined" ) { - return jQuery.prop( elem, name, value ); - } - - // Attribute hooks are determined by the lowercase version - // Grab necessary hook if one is defined - if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { - hooks = jQuery.attrHooks[ name.toLowerCase() ] || - ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); - } - - if ( value !== undefined ) { - if ( value === null ) { - jQuery.removeAttr( elem, name ); - return; - } - - if ( hooks && "set" in hooks && - ( ret = hooks.set( elem, value, name ) ) !== undefined ) { - return ret; - } - - elem.setAttribute( name, value + "" ); - return value; - } - - if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { - return ret; - } - - ret = jQuery.find.attr( elem, name ); - - // Non-existent attributes return null, we normalize to undefined - return ret == null ? undefined : ret; - }, - - attrHooks: { - type: { - set: function( elem, value ) { - if ( !support.radioValue && value === "radio" && - nodeName( elem, "input" ) ) { - var val = elem.value; - elem.setAttribute( "type", value ); - if ( val ) { - elem.value = val; - } - return value; - } - } - } - }, - - removeAttr: function( elem, value ) { - var name, - i = 0, - - // Attribute names can contain non-HTML whitespace characters - // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 - attrNames = value && value.match( rnothtmlwhite ); - - if ( attrNames && elem.nodeType === 1 ) { - while ( ( name = attrNames[ i++ ] ) ) { - elem.removeAttribute( name ); - } - } - } - } ); - -// Hooks for boolean attributes - boolHook = { - set: function( elem, value, name ) { - if ( value === false ) { - - // Remove boolean attributes when set to false - jQuery.removeAttr( elem, name ); - } else { - elem.setAttribute( name, name ); - } - return name; - } - }; - - jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { - var getter = attrHandle[ name ] || jQuery.find.attr; - - attrHandle[ name ] = function( elem, name, isXML ) { - var ret, handle, - lowercaseName = name.toLowerCase(); - - if ( !isXML ) { - - // Avoid an infinite loop by temporarily removing this function from the getter - handle = attrHandle[ lowercaseName ]; - attrHandle[ lowercaseName ] = ret; - ret = getter( elem, name, isXML ) != null ? - lowercaseName : - null; - attrHandle[ lowercaseName ] = handle; - } - return ret; - }; - } ); - - - - - var rfocusable = /^(?:input|select|textarea|button)$/i, - rclickable = /^(?:a|area)$/i; - - jQuery.fn.extend( { - prop: function( name, value ) { - return access( this, jQuery.prop, name, value, arguments.length > 1 ); - }, - - removeProp: function( name ) { - return this.each( function() { - delete this[ jQuery.propFix[ name ] || name ]; - } ); - } - } ); - - jQuery.extend( { - prop: function( elem, name, value ) { - var ret, hooks, - nType = elem.nodeType; - - // Don't get/set properties on text, comment and attribute nodes - if ( nType === 3 || nType === 8 || nType === 2 ) { - return; - } - - if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { - - // Fix name and attach hooks - name = jQuery.propFix[ name ] || name; - hooks = jQuery.propHooks[ name ]; - } - - if ( value !== undefined ) { - if ( hooks && "set" in hooks && - ( ret = hooks.set( elem, value, name ) ) !== undefined ) { - return ret; - } - - return ( elem[ name ] = value ); - } - - if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { - return ret; - } - - return elem[ name ]; - }, - - propHooks: { - tabIndex: { - get: function( elem ) { - - // Support: IE <=9 - 11 only - // elem.tabIndex doesn't always return the - // correct value when it hasn't been explicitly set - // https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ - // Use proper attribute retrieval(#12072) - var tabindex = jQuery.find.attr( elem, "tabindex" ); - - if ( tabindex ) { - return parseInt( tabindex, 10 ); - } - - if ( - rfocusable.test( elem.nodeName ) || - rclickable.test( elem.nodeName ) && - elem.href - ) { - return 0; - } - - return -1; - } - } - }, - - propFix: { - "for": "htmlFor", - "class": "className" - } - } ); - -// Support: IE <=11 only -// Accessing the selectedIndex property -// forces the browser to respect setting selected -// on the option -// The getter ensures a default option is selected -// when in an optgroup -// eslint rule "no-unused-expressions" is disabled for this code -// since it considers such accessions noop - if ( !support.optSelected ) { - jQuery.propHooks.selected = { - get: function( elem ) { - - /* eslint no-unused-expressions: "off" */ - - var parent = elem.parentNode; - if ( parent && parent.parentNode ) { - parent.parentNode.selectedIndex; - } - return null; - }, - set: function( elem ) { - - /* eslint no-unused-expressions: "off" */ - - var parent = elem.parentNode; - if ( parent ) { - parent.selectedIndex; - - if ( parent.parentNode ) { - parent.parentNode.selectedIndex; - } - } - } - }; - } - - jQuery.each( [ - "tabIndex", - "readOnly", - "maxLength", - "cellSpacing", - "cellPadding", - "rowSpan", - "colSpan", - "useMap", - "frameBorder", - "contentEditable" - ], function() { - jQuery.propFix[ this.toLowerCase() ] = this; - } ); - - - - - // Strip and collapse whitespace according to HTML spec - // https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace - function stripAndCollapse( value ) { - var tokens = value.match( rnothtmlwhite ) || []; - return tokens.join( " " ); - } - - - function getClass( elem ) { - return elem.getAttribute && elem.getAttribute( "class" ) || ""; - } - - function classesToArray( value ) { - if ( Array.isArray( value ) ) { - return value; - } - if ( typeof value === "string" ) { - return value.match( rnothtmlwhite ) || []; - } - return []; - } - - jQuery.fn.extend( { - addClass: function( value ) { - var classes, elem, cur, curValue, clazz, j, finalValue, - i = 0; - - if ( isFunction( value ) ) { - return this.each( function( j ) { - jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); - } ); - } - - classes = classesToArray( value ); - - if ( classes.length ) { - while ( ( elem = this[ i++ ] ) ) { - curValue = getClass( elem ); - cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); - - if ( cur ) { - j = 0; - while ( ( clazz = classes[ j++ ] ) ) { - if ( cur.indexOf( " " + clazz + " " ) < 0 ) { - cur += clazz + " "; - } - } - - // Only assign if different to avoid unneeded rendering. - finalValue = stripAndCollapse( cur ); - if ( curValue !== finalValue ) { - elem.setAttribute( "class", finalValue ); - } - } - } - } - - return this; - }, - - removeClass: function( value ) { - var classes, elem, cur, curValue, clazz, j, finalValue, - i = 0; - - if ( isFunction( value ) ) { - return this.each( function( j ) { - jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); - } ); - } - - if ( !arguments.length ) { - return this.attr( "class", "" ); - } - - classes = classesToArray( value ); - - if ( classes.length ) { - while ( ( elem = this[ i++ ] ) ) { - curValue = getClass( elem ); - - // This expression is here for better compressibility (see addClass) - cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); - - if ( cur ) { - j = 0; - while ( ( clazz = classes[ j++ ] ) ) { - - // Remove *all* instances - while ( cur.indexOf( " " + clazz + " " ) > -1 ) { - cur = cur.replace( " " + clazz + " ", " " ); - } - } - - // Only assign if different to avoid unneeded rendering. - finalValue = stripAndCollapse( cur ); - if ( curValue !== finalValue ) { - elem.setAttribute( "class", finalValue ); - } - } - } - } - - return this; - }, - - toggleClass: function( value, stateVal ) { - var type = typeof value, - isValidValue = type === "string" || Array.isArray( value ); - - if ( typeof stateVal === "boolean" && isValidValue ) { - return stateVal ? this.addClass( value ) : this.removeClass( value ); - } - - if ( isFunction( value ) ) { - return this.each( function( i ) { - jQuery( this ).toggleClass( - value.call( this, i, getClass( this ), stateVal ), - stateVal - ); - } ); - } - - return this.each( function() { - var className, i, self, classNames; - - if ( isValidValue ) { - - // Toggle individual class names - i = 0; - self = jQuery( this ); - classNames = classesToArray( value ); - - while ( ( className = classNames[ i++ ] ) ) { - - // Check each className given, space separated list - if ( self.hasClass( className ) ) { - self.removeClass( className ); - } else { - self.addClass( className ); - } - } - - // Toggle whole class name - } else if ( value === undefined || type === "boolean" ) { - className = getClass( this ); - if ( className ) { - - // Store className if set - dataPriv.set( this, "__className__", className ); - } - - // If the element has a class name or if we're passed `false`, - // then remove the whole classname (if there was one, the above saved it). - // Otherwise bring back whatever was previously saved (if anything), - // falling back to the empty string if nothing was stored. - if ( this.setAttribute ) { - this.setAttribute( "class", - className || value === false ? - "" : - dataPriv.get( this, "__className__" ) || "" - ); - } - } - } ); - }, - - hasClass: function( selector ) { - var className, elem, - i = 0; - - className = " " + selector + " "; - while ( ( elem = this[ i++ ] ) ) { - if ( elem.nodeType === 1 && - ( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) { - return true; - } - } - - return false; - } - } ); - - - - - var rreturn = /\r/g; - - jQuery.fn.extend( { - val: function( value ) { - var hooks, ret, valueIsFunction, - elem = this[ 0 ]; - - if ( !arguments.length ) { - if ( elem ) { - hooks = jQuery.valHooks[ elem.type ] || - jQuery.valHooks[ elem.nodeName.toLowerCase() ]; - - if ( hooks && - "get" in hooks && - ( ret = hooks.get( elem, "value" ) ) !== undefined - ) { - return ret; - } - - ret = elem.value; - - // Handle most common string cases - if ( typeof ret === "string" ) { - return ret.replace( rreturn, "" ); - } - - // Handle cases where value is null/undef or number - return ret == null ? "" : ret; - } - - return; - } - - valueIsFunction = isFunction( value ); - - return this.each( function( i ) { - var val; - - if ( this.nodeType !== 1 ) { - return; - } - - if ( valueIsFunction ) { - val = value.call( this, i, jQuery( this ).val() ); - } else { - val = value; - } - - // Treat null/undefined as ""; convert numbers to string - if ( val == null ) { - val = ""; - - } else if ( typeof val === "number" ) { - val += ""; - - } else if ( Array.isArray( val ) ) { - val = jQuery.map( val, function( value ) { - return value == null ? "" : value + ""; - } ); - } - - hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; - - // If set returns undefined, fall back to normal setting - if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) { - this.value = val; - } - } ); - } - } ); - - jQuery.extend( { - valHooks: { - option: { - get: function( elem ) { - - var val = jQuery.find.attr( elem, "value" ); - return val != null ? - val : - - // Support: IE <=10 - 11 only - // option.text throws exceptions (#14686, #14858) - // Strip and collapse whitespace - // https://html.spec.whatwg.org/#strip-and-collapse-whitespace - stripAndCollapse( jQuery.text( elem ) ); - } - }, - select: { - get: function( elem ) { - var value, option, i, - options = elem.options, - index = elem.selectedIndex, - one = elem.type === "select-one", - values = one ? null : [], - max = one ? index + 1 : options.length; - - if ( index < 0 ) { - i = max; - - } else { - i = one ? index : 0; - } - - // Loop through all the selected options - for ( ; i < max; i++ ) { - option = options[ i ]; - - // Support: IE <=9 only - // IE8-9 doesn't update selected after form reset (#2551) - if ( ( option.selected || i === index ) && - - // Don't return options that are disabled or in a disabled optgroup - !option.disabled && - ( !option.parentNode.disabled || - !nodeName( option.parentNode, "optgroup" ) ) ) { - - // Get the specific value for the option - value = jQuery( option ).val(); - - // We don't need an array for one selects - if ( one ) { - return value; - } - - // Multi-Selects return an array - values.push( value ); - } - } - - return values; - }, - - set: function( elem, value ) { - var optionSet, option, - options = elem.options, - values = jQuery.makeArray( value ), - i = options.length; - - while ( i-- ) { - option = options[ i ]; - - /* eslint-disable no-cond-assign */ - - if ( option.selected = - jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 - ) { - optionSet = true; - } - - /* eslint-enable no-cond-assign */ - } - - // Force browsers to behave consistently when non-matching value is set - if ( !optionSet ) { - elem.selectedIndex = -1; - } - return values; - } - } - } - } ); - -// Radios and checkboxes getter/setter - jQuery.each( [ "radio", "checkbox" ], function() { - jQuery.valHooks[ this ] = { - set: function( elem, value ) { - if ( Array.isArray( value ) ) { - return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); - } - } - }; - if ( !support.checkOn ) { - jQuery.valHooks[ this ].get = function( elem ) { - return elem.getAttribute( "value" ) === null ? "on" : elem.value; - }; - } - } ); - - - - -// Return jQuery for attributes-only inclusion - - - support.focusin = "onfocusin" in window; - - - var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, - stopPropagationCallback = function( e ) { - e.stopPropagation(); - }; - - jQuery.extend( jQuery.event, { - - trigger: function( event, data, elem, onlyHandlers ) { - - var i, cur, tmp, bubbleType, ontype, handle, special, lastElement, - eventPath = [ elem || document ], - type = hasOwn.call( event, "type" ) ? event.type : event, - namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; - - cur = lastElement = tmp = elem = elem || document; - - // Don't do events on text and comment nodes - if ( elem.nodeType === 3 || elem.nodeType === 8 ) { - return; - } - - // focus/blur morphs to focusin/out; ensure we're not firing them right now - if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { - return; - } - - if ( type.indexOf( "." ) > -1 ) { - - // Namespaced trigger; create a regexp to match event type in handle() - namespaces = type.split( "." ); - type = namespaces.shift(); - namespaces.sort(); - } - ontype = type.indexOf( ":" ) < 0 && "on" + type; - - // Caller can pass in a jQuery.Event object, Object, or just an event type string - event = event[ jQuery.expando ] ? - event : - new jQuery.Event( type, typeof event === "object" && event ); - - // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) - event.isTrigger = onlyHandlers ? 2 : 3; - event.namespace = namespaces.join( "." ); - event.rnamespace = event.namespace ? - new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : - null; - - // Clean up the event in case it is being reused - event.result = undefined; - if ( !event.target ) { - event.target = elem; - } - - // Clone any incoming data and prepend the event, creating the handler arg list - data = data == null ? - [ event ] : - jQuery.makeArray( data, [ event ] ); - - // Allow special events to draw outside the lines - special = jQuery.event.special[ type ] || {}; - if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { - return; - } - - // Determine event propagation path in advance, per W3C events spec (#9951) - // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) - if ( !onlyHandlers && !special.noBubble && !isWindow( elem ) ) { - - bubbleType = special.delegateType || type; - if ( !rfocusMorph.test( bubbleType + type ) ) { - cur = cur.parentNode; - } - for ( ; cur; cur = cur.parentNode ) { - eventPath.push( cur ); - tmp = cur; - } - - // Only add window if we got to document (e.g., not plain obj or detached DOM) - if ( tmp === ( elem.ownerDocument || document ) ) { - eventPath.push( tmp.defaultView || tmp.parentWindow || window ); - } - } - - // Fire handlers on the event path - i = 0; - while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { - lastElement = cur; - event.type = i > 1 ? - bubbleType : - special.bindType || type; - - // jQuery handler - handle = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] && - dataPriv.get( cur, "handle" ); - if ( handle ) { - handle.apply( cur, data ); - } - - // Native handler - handle = ontype && cur[ ontype ]; - if ( handle && handle.apply && acceptData( cur ) ) { - event.result = handle.apply( cur, data ); - if ( event.result === false ) { - event.preventDefault(); - } - } - } - event.type = type; - - // If nobody prevented the default action, do it now - if ( !onlyHandlers && !event.isDefaultPrevented() ) { - - if ( ( !special._default || - special._default.apply( eventPath.pop(), data ) === false ) && - acceptData( elem ) ) { - - // Call a native DOM method on the target with the same name as the event. - // Don't do default actions on window, that's where global variables be (#6170) - if ( ontype && isFunction( elem[ type ] ) && !isWindow( elem ) ) { - - // Don't re-trigger an onFOO event when we call its FOO() method - tmp = elem[ ontype ]; - - if ( tmp ) { - elem[ ontype ] = null; - } - - // Prevent re-triggering of the same event, since we already bubbled it above - jQuery.event.triggered = type; - - if ( event.isPropagationStopped() ) { - lastElement.addEventListener( type, stopPropagationCallback ); - } - - elem[ type ](); - - if ( event.isPropagationStopped() ) { - lastElement.removeEventListener( type, stopPropagationCallback ); - } - - jQuery.event.triggered = undefined; - - if ( tmp ) { - elem[ ontype ] = tmp; - } - } - } - } - - return event.result; - }, - - // Piggyback on a donor event to simulate a different one - // Used only for `focus(in | out)` events - simulate: function( type, elem, event ) { - var e = jQuery.extend( - new jQuery.Event(), - event, - { - type: type, - isSimulated: true - } - ); - - jQuery.event.trigger( e, null, elem ); - } - - } ); - - jQuery.fn.extend( { - - trigger: function( type, data ) { - return this.each( function() { - jQuery.event.trigger( type, data, this ); - } ); - }, - triggerHandler: function( type, data ) { - var elem = this[ 0 ]; - if ( elem ) { - return jQuery.event.trigger( type, data, elem, true ); - } - } - } ); - - -// Support: Firefox <=44 -// Firefox doesn't have focus(in | out) events -// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 -// -// Support: Chrome <=48 - 49, Safari <=9.0 - 9.1 -// focus(in | out) events fire after focus & blur events, -// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order -// Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857 - if ( !support.focusin ) { - jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) { - - // Attach a single capturing handler on the document while someone wants focusin/focusout - var handler = function( event ) { - jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) ); - }; - - jQuery.event.special[ fix ] = { - setup: function() { - var doc = this.ownerDocument || this, - attaches = dataPriv.access( doc, fix ); - - if ( !attaches ) { - doc.addEventListener( orig, handler, true ); - } - dataPriv.access( doc, fix, ( attaches || 0 ) + 1 ); - }, - teardown: function() { - var doc = this.ownerDocument || this, - attaches = dataPriv.access( doc, fix ) - 1; - - if ( !attaches ) { - doc.removeEventListener( orig, handler, true ); - dataPriv.remove( doc, fix ); - - } else { - dataPriv.access( doc, fix, attaches ); - } - } - }; - } ); - } - var location = window.location; - - var nonce = Date.now(); - - var rquery = ( /\?/ ); - - - -// Cross-browser xml parsing - jQuery.parseXML = function( data ) { - var xml; - if ( !data || typeof data !== "string" ) { - return null; - } - - // Support: IE 9 - 11 only - // IE throws on parseFromString with invalid input. - try { - xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); - } catch ( e ) { - xml = undefined; - } - - if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { - jQuery.error( "Invalid XML: " + data ); - } - return xml; - }; - - - var - rbracket = /\[\]$/, - rCRLF = /\r?\n/g, - rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, - rsubmittable = /^(?:input|select|textarea|keygen)/i; - - function buildParams( prefix, obj, traditional, add ) { - var name; - - if ( Array.isArray( obj ) ) { - - // Serialize array item. - jQuery.each( obj, function( i, v ) { - if ( traditional || rbracket.test( prefix ) ) { - - // Treat each array item as a scalar. - add( prefix, v ); - - } else { - - // Item is non-scalar (array or object), encode its numeric index. - buildParams( - prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]", - v, - traditional, - add - ); - } - } ); - - } else if ( !traditional && toType( obj ) === "object" ) { - - // Serialize object item. - for ( name in obj ) { - buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); - } - - } else { - - // Serialize scalar item. - add( prefix, obj ); - } - } - -// Serialize an array of form elements or a set of -// key/values into a query string - jQuery.param = function( a, traditional ) { - var prefix, - s = [], - add = function( key, valueOrFunction ) { - - // If value is a function, invoke it and use its return value - var value = isFunction( valueOrFunction ) ? - valueOrFunction() : - valueOrFunction; - - s[ s.length ] = encodeURIComponent( key ) + "=" + - encodeURIComponent( value == null ? "" : value ); - }; - - // If an array was passed in, assume that it is an array of form elements. - if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { - - // Serialize the form elements - jQuery.each( a, function() { - add( this.name, this.value ); - } ); - - } else { - - // If traditional, encode the "old" way (the way 1.3.2 or older - // did it), otherwise encode params recursively. - for ( prefix in a ) { - buildParams( prefix, a[ prefix ], traditional, add ); - } - } - - // Return the resulting serialization - return s.join( "&" ); - }; - - jQuery.fn.extend( { - serialize: function() { - return jQuery.param( this.serializeArray() ); - }, - serializeArray: function() { - return this.map( function() { - - // Can add propHook for "elements" to filter or add form elements - var elements = jQuery.prop( this, "elements" ); - return elements ? jQuery.makeArray( elements ) : this; - } ) - .filter( function() { - var type = this.type; - - // Use .is( ":disabled" ) so that fieldset[disabled] works - return this.name && !jQuery( this ).is( ":disabled" ) && - rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && - ( this.checked || !rcheckableType.test( type ) ); - } ) - .map( function( i, elem ) { - var val = jQuery( this ).val(); - - if ( val == null ) { - return null; - } - - if ( Array.isArray( val ) ) { - return jQuery.map( val, function( val ) { - return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; - } ); - } - - return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; - } ).get(); - } - } ); - - - var - r20 = /%20/g, - rhash = /#.*$/, - rantiCache = /([?&])_=[^&]*/, - rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, - - // #7653, #8125, #8152: local protocol detection - rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, - rnoContent = /^(?:GET|HEAD)$/, - rprotocol = /^\/\//, - - /* Prefilters - * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) - * 2) These are called: - * - BEFORE asking for a transport - * - AFTER param serialization (s.data is a string if s.processData is true) - * 3) key is the dataType - * 4) the catchall symbol "*" can be used - * 5) execution will start with transport dataType and THEN continue down to "*" if needed - */ - prefilters = {}, - - /* Transports bindings - * 1) key is the dataType - * 2) the catchall symbol "*" can be used - * 3) selection will start with transport dataType and THEN go to "*" if needed - */ - transports = {}, - - // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression - allTypes = "*/".concat( "*" ), - - // Anchor tag for parsing the document origin - originAnchor = document.createElement( "a" ); - originAnchor.href = location.href; - -// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport - function addToPrefiltersOrTransports( structure ) { - - // dataTypeExpression is optional and defaults to "*" - return function( dataTypeExpression, func ) { - - if ( typeof dataTypeExpression !== "string" ) { - func = dataTypeExpression; - dataTypeExpression = "*"; - } - - var dataType, - i = 0, - dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || []; - - if ( isFunction( func ) ) { - - // For each dataType in the dataTypeExpression - while ( ( dataType = dataTypes[ i++ ] ) ) { - - // Prepend if requested - if ( dataType[ 0 ] === "+" ) { - dataType = dataType.slice( 1 ) || "*"; - ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); - - // Otherwise append - } else { - ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); - } - } - } - }; - } - -// Base inspection function for prefilters and transports - function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { - - var inspected = {}, - seekingTransport = ( structure === transports ); - - function inspect( dataType ) { - var selected; - inspected[ dataType ] = true; - jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { - var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); - if ( typeof dataTypeOrTransport === "string" && - !seekingTransport && !inspected[ dataTypeOrTransport ] ) { - - options.dataTypes.unshift( dataTypeOrTransport ); - inspect( dataTypeOrTransport ); - return false; - } else if ( seekingTransport ) { - return !( selected = dataTypeOrTransport ); - } - } ); - return selected; - } - - return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); - } - -// A special extend for ajax options -// that takes "flat" options (not to be deep extended) -// Fixes #9887 - function ajaxExtend( target, src ) { - var key, deep, - flatOptions = jQuery.ajaxSettings.flatOptions || {}; - - for ( key in src ) { - if ( src[ key ] !== undefined ) { - ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; - } - } - if ( deep ) { - jQuery.extend( true, target, deep ); - } - - return target; - } - - /* Handles responses to an ajax request: - * - finds the right dataType (mediates between content-type and expected dataType) - * - returns the corresponding response - */ - function ajaxHandleResponses( s, jqXHR, responses ) { - - var ct, type, finalDataType, firstDataType, - contents = s.contents, - dataTypes = s.dataTypes; - - // Remove auto dataType and get content-type in the process - while ( dataTypes[ 0 ] === "*" ) { - dataTypes.shift(); - if ( ct === undefined ) { - ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" ); - } - } - - // Check if we're dealing with a known content-type - if ( ct ) { - for ( type in contents ) { - if ( contents[ type ] && contents[ type ].test( ct ) ) { - dataTypes.unshift( type ); - break; - } - } - } - - // Check to see if we have a response for the expected dataType - if ( dataTypes[ 0 ] in responses ) { - finalDataType = dataTypes[ 0 ]; - } else { - - // Try convertible dataTypes - for ( type in responses ) { - if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) { - finalDataType = type; - break; - } - if ( !firstDataType ) { - firstDataType = type; - } - } - - // Or just use first one - finalDataType = finalDataType || firstDataType; - } - - // If we found a dataType - // We add the dataType to the list if needed - // and return the corresponding response - if ( finalDataType ) { - if ( finalDataType !== dataTypes[ 0 ] ) { - dataTypes.unshift( finalDataType ); - } - return responses[ finalDataType ]; - } - } - - /* Chain conversions given the request and the original response - * Also sets the responseXXX fields on the jqXHR instance - */ - function ajaxConvert( s, response, jqXHR, isSuccess ) { - var conv2, current, conv, tmp, prev, - converters = {}, - - // Work with a copy of dataTypes in case we need to modify it for conversion - dataTypes = s.dataTypes.slice(); - - // Create converters map with lowercased keys - if ( dataTypes[ 1 ] ) { - for ( conv in s.converters ) { - converters[ conv.toLowerCase() ] = s.converters[ conv ]; - } - } - - current = dataTypes.shift(); - - // Convert to each sequential dataType - while ( current ) { - - if ( s.responseFields[ current ] ) { - jqXHR[ s.responseFields[ current ] ] = response; - } - - // Apply the dataFilter if provided - if ( !prev && isSuccess && s.dataFilter ) { - response = s.dataFilter( response, s.dataType ); - } - - prev = current; - current = dataTypes.shift(); - - if ( current ) { - - // There's only work to do if current dataType is non-auto - if ( current === "*" ) { - - current = prev; - - // Convert response if prev dataType is non-auto and differs from current - } else if ( prev !== "*" && prev !== current ) { - - // Seek a direct converter - conv = converters[ prev + " " + current ] || converters[ "* " + current ]; - - // If none found, seek a pair - if ( !conv ) { - for ( conv2 in converters ) { - - // If conv2 outputs current - tmp = conv2.split( " " ); - if ( tmp[ 1 ] === current ) { - - // If prev can be converted to accepted input - conv = converters[ prev + " " + tmp[ 0 ] ] || - converters[ "* " + tmp[ 0 ] ]; - if ( conv ) { - - // Condense equivalence converters - if ( conv === true ) { - conv = converters[ conv2 ]; - - // Otherwise, insert the intermediate dataType - } else if ( converters[ conv2 ] !== true ) { - current = tmp[ 0 ]; - dataTypes.unshift( tmp[ 1 ] ); - } - break; - } - } - } - } - - // Apply converter (if not an equivalence) - if ( conv !== true ) { - - // Unless errors are allowed to bubble, catch and return them - if ( conv && s.throws ) { - response = conv( response ); - } else { - try { - response = conv( response ); - } catch ( e ) { - return { - state: "parsererror", - error: conv ? e : "No conversion from " + prev + " to " + current - }; - } - } - } - } - } - } - - return { state: "success", data: response }; - } - - jQuery.extend( { - - // Counter for holding the number of active queries - active: 0, - - // Last-Modified header cache for next request - lastModified: {}, - etag: {}, - - ajaxSettings: { - url: location.href, - type: "GET", - isLocal: rlocalProtocol.test( location.protocol ), - global: true, - processData: true, - async: true, - contentType: "application/x-www-form-urlencoded; charset=UTF-8", - - /* - timeout: 0, - data: null, - dataType: null, - username: null, - password: null, - cache: null, - throws: false, - traditional: false, - headers: {}, - */ - - accepts: { - "*": allTypes, - text: "text/plain", - html: "text/html", - xml: "application/xml, text/xml", - json: "application/json, text/javascript" - }, - - contents: { - xml: /\bxml\b/, - html: /\bhtml/, - json: /\bjson\b/ - }, - - responseFields: { - xml: "responseXML", - text: "responseText", - json: "responseJSON" - }, - - // Data converters - // Keys separate source (or catchall "*") and destination types with a single space - converters: { - - // Convert anything to text - "* text": String, - - // Text to html (true = no transformation) - "text html": true, - - // Evaluate text as a json expression - "text json": JSON.parse, - - // Parse text as xml - "text xml": jQuery.parseXML - }, - - // For options that shouldn't be deep extended: - // you can add your own custom options here if - // and when you create one that shouldn't be - // deep extended (see ajaxExtend) - flatOptions: { - url: true, - context: true - } - }, - - // Creates a full fledged settings object into target - // with both ajaxSettings and settings fields. - // If target is omitted, writes into ajaxSettings. - ajaxSetup: function( target, settings ) { - return settings ? - - // Building a settings object - ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : - - // Extending ajaxSettings - ajaxExtend( jQuery.ajaxSettings, target ); - }, - - ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), - ajaxTransport: addToPrefiltersOrTransports( transports ), - - // Main method - ajax: function( url, options ) { - - // If url is an object, simulate pre-1.5 signature - if ( typeof url === "object" ) { - options = url; - url = undefined; - } - - // Force options to be an object - options = options || {}; - - var transport, - - // URL without anti-cache param - cacheURL, - - // Response headers - responseHeadersString, - responseHeaders, - - // timeout handle - timeoutTimer, - - // Url cleanup var - urlAnchor, - - // Request state (becomes false upon send and true upon completion) - completed, - - // To know if global events are to be dispatched - fireGlobals, - - // Loop variable - i, - - // uncached part of the url - uncached, - - // Create the final options object - s = jQuery.ajaxSetup( {}, options ), - - // Callbacks context - callbackContext = s.context || s, - - // Context for global events is callbackContext if it is a DOM node or jQuery collection - globalEventContext = s.context && - ( callbackContext.nodeType || callbackContext.jquery ) ? - jQuery( callbackContext ) : - jQuery.event, - - // Deferreds - deferred = jQuery.Deferred(), - completeDeferred = jQuery.Callbacks( "once memory" ), - - // Status-dependent callbacks - statusCode = s.statusCode || {}, - - // Headers (they are sent all at once) - requestHeaders = {}, - requestHeadersNames = {}, - - // Default abort message - strAbort = "canceled", - - // Fake xhr - jqXHR = { - readyState: 0, - - // Builds headers hashtable if needed - getResponseHeader: function( key ) { - var match; - if ( completed ) { - if ( !responseHeaders ) { - responseHeaders = {}; - while ( ( match = rheaders.exec( responseHeadersString ) ) ) { - responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ]; - } - } - match = responseHeaders[ key.toLowerCase() ]; - } - return match == null ? null : match; - }, - - // Raw string - getAllResponseHeaders: function() { - return completed ? responseHeadersString : null; - }, - - // Caches the header - setRequestHeader: function( name, value ) { - if ( completed == null ) { - name = requestHeadersNames[ name.toLowerCase() ] = - requestHeadersNames[ name.toLowerCase() ] || name; - requestHeaders[ name ] = value; - } - return this; - }, - - // Overrides response content-type header - overrideMimeType: function( type ) { - if ( completed == null ) { - s.mimeType = type; - } - return this; - }, - - // Status-dependent callbacks - statusCode: function( map ) { - var code; - if ( map ) { - if ( completed ) { - - // Execute the appropriate callbacks - jqXHR.always( map[ jqXHR.status ] ); - } else { - - // Lazy-add the new callbacks in a way that preserves old ones - for ( code in map ) { - statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; - } - } - } - return this; - }, - - // Cancel the request - abort: function( statusText ) { - var finalText = statusText || strAbort; - if ( transport ) { - transport.abort( finalText ); - } - done( 0, finalText ); - return this; - } - }; - - // Attach deferreds - deferred.promise( jqXHR ); - - // Add protocol if not provided (prefilters might expect it) - // Handle falsy url in the settings object (#10093: consistency with old signature) - // We also use the url parameter if available - s.url = ( ( url || s.url || location.href ) + "" ) - .replace( rprotocol, location.protocol + "//" ); - - // Alias method option to type as per ticket #12004 - s.type = options.method || options.type || s.method || s.type; - - // Extract dataTypes list - s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ]; - - // A cross-domain request is in order when the origin doesn't match the current origin. - if ( s.crossDomain == null ) { - urlAnchor = document.createElement( "a" ); - - // Support: IE <=8 - 11, Edge 12 - 15 - // IE throws exception on accessing the href property if url is malformed, - // e.g. http://example.com:80x/ - try { - urlAnchor.href = s.url; - - // Support: IE <=8 - 11 only - // Anchor's host property isn't correctly set when s.url is relative - urlAnchor.href = urlAnchor.href; - s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== - urlAnchor.protocol + "//" + urlAnchor.host; - } catch ( e ) { - - // If there is an error parsing the URL, assume it is crossDomain, - // it can be rejected by the transport if it is invalid - s.crossDomain = true; - } - } - - // Convert data if not already a string - if ( s.data && s.processData && typeof s.data !== "string" ) { - s.data = jQuery.param( s.data, s.traditional ); - } - - // Apply prefilters - inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); - - // If request was aborted inside a prefilter, stop there - if ( completed ) { - return jqXHR; - } - - // We can fire global events as of now if asked to - // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) - fireGlobals = jQuery.event && s.global; - - // Watch for a new set of requests - if ( fireGlobals && jQuery.active++ === 0 ) { - jQuery.event.trigger( "ajaxStart" ); - } - - // Uppercase the type - s.type = s.type.toUpperCase(); - - // Determine if request has content - s.hasContent = !rnoContent.test( s.type ); - - // Save the URL in case we're toying with the If-Modified-Since - // and/or If-None-Match header later on - // Remove hash to simplify url manipulation - cacheURL = s.url.replace( rhash, "" ); - - // More options handling for requests with no content - if ( !s.hasContent ) { - - // Remember the hash so we can put it back - uncached = s.url.slice( cacheURL.length ); - - // If data is available and should be processed, append data to url - if ( s.data && ( s.processData || typeof s.data === "string" ) ) { - cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data; - - // #9682: remove data so that it's not used in an eventual retry - delete s.data; - } - - // Add or update anti-cache param if needed - if ( s.cache === false ) { - cacheURL = cacheURL.replace( rantiCache, "$1" ); - uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce++ ) + uncached; - } - - // Put hash and anti-cache on the URL that will be requested (gh-1732) - s.url = cacheURL + uncached; - - // Change '%20' to '+' if this is encoded form body content (gh-2658) - } else if ( s.data && s.processData && - ( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) { - s.data = s.data.replace( r20, "+" ); - } - - // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. - if ( s.ifModified ) { - if ( jQuery.lastModified[ cacheURL ] ) { - jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); - } - if ( jQuery.etag[ cacheURL ] ) { - jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); - } - } - - // Set the correct header, if data is being sent - if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { - jqXHR.setRequestHeader( "Content-Type", s.contentType ); - } - - // Set the Accepts header for the server, depending on the dataType - jqXHR.setRequestHeader( - "Accept", - s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ? - s.accepts[ s.dataTypes[ 0 ] ] + - ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : - s.accepts[ "*" ] - ); - - // Check for headers option - for ( i in s.headers ) { - jqXHR.setRequestHeader( i, s.headers[ i ] ); - } - - // Allow custom headers/mimetypes and early abort - if ( s.beforeSend && - ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) { - - // Abort if not done already and return - return jqXHR.abort(); - } - - // Aborting is no longer a cancellation - strAbort = "abort"; - - // Install callbacks on deferreds - completeDeferred.add( s.complete ); - jqXHR.done( s.success ); - jqXHR.fail( s.error ); - - // Get transport - transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); - - // If no transport, we auto-abort - if ( !transport ) { - done( -1, "No Transport" ); - } else { - jqXHR.readyState = 1; - - // Send global event - if ( fireGlobals ) { - globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); - } - - // If request was aborted inside ajaxSend, stop there - if ( completed ) { - return jqXHR; - } - - // Timeout - if ( s.async && s.timeout > 0 ) { - timeoutTimer = window.setTimeout( function() { - jqXHR.abort( "timeout" ); - }, s.timeout ); - } - - try { - completed = false; - transport.send( requestHeaders, done ); - } catch ( e ) { - - // Rethrow post-completion exceptions - if ( completed ) { - throw e; - } - - // Propagate others as results - done( -1, e ); - } - } - - // Callback for when everything is done - function done( status, nativeStatusText, responses, headers ) { - var isSuccess, success, error, response, modified, - statusText = nativeStatusText; - - // Ignore repeat invocations - if ( completed ) { - return; - } - - completed = true; - - // Clear timeout if it exists - if ( timeoutTimer ) { - window.clearTimeout( timeoutTimer ); - } - - // Dereference transport for early garbage collection - // (no matter how long the jqXHR object will be used) - transport = undefined; - - // Cache response headers - responseHeadersString = headers || ""; - - // Set readyState - jqXHR.readyState = status > 0 ? 4 : 0; - - // Determine if successful - isSuccess = status >= 200 && status < 300 || status === 304; - - // Get response data - if ( responses ) { - response = ajaxHandleResponses( s, jqXHR, responses ); - } - - // Convert no matter what (that way responseXXX fields are always set) - response = ajaxConvert( s, response, jqXHR, isSuccess ); - - // If successful, handle type chaining - if ( isSuccess ) { - - // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. - if ( s.ifModified ) { - modified = jqXHR.getResponseHeader( "Last-Modified" ); - if ( modified ) { - jQuery.lastModified[ cacheURL ] = modified; - } - modified = jqXHR.getResponseHeader( "etag" ); - if ( modified ) { - jQuery.etag[ cacheURL ] = modified; - } - } - - // if no content - if ( status === 204 || s.type === "HEAD" ) { - statusText = "nocontent"; - - // if not modified - } else if ( status === 304 ) { - statusText = "notmodified"; - - // If we have data, let's convert it - } else { - statusText = response.state; - success = response.data; - error = response.error; - isSuccess = !error; - } - } else { - - // Extract error from statusText and normalize for non-aborts - error = statusText; - if ( status || !statusText ) { - statusText = "error"; - if ( status < 0 ) { - status = 0; - } - } - } - - // Set data for the fake xhr object - jqXHR.status = status; - jqXHR.statusText = ( nativeStatusText || statusText ) + ""; - - // Success/Error - if ( isSuccess ) { - deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); - } else { - deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); - } - - // Status-dependent callbacks - jqXHR.statusCode( statusCode ); - statusCode = undefined; - - if ( fireGlobals ) { - globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", - [ jqXHR, s, isSuccess ? success : error ] ); - } - - // Complete - completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); - - if ( fireGlobals ) { - globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); - - // Handle the global AJAX counter - if ( !( --jQuery.active ) ) { - jQuery.event.trigger( "ajaxStop" ); - } - } - } - - return jqXHR; - }, - - getJSON: function( url, data, callback ) { - return jQuery.get( url, data, callback, "json" ); - }, - - getScript: function( url, callback ) { - return jQuery.get( url, undefined, callback, "script" ); - } - } ); - - jQuery.each( [ "get", "post" ], function( i, method ) { - jQuery[ method ] = function( url, data, callback, type ) { - - // Shift arguments if data argument was omitted - if ( isFunction( data ) ) { - type = type || callback; - callback = data; - data = undefined; - } - - // The url can be an options object (which then must have .url) - return jQuery.ajax( jQuery.extend( { - url: url, - type: method, - dataType: type, - data: data, - success: callback - }, jQuery.isPlainObject( url ) && url ) ); - }; - } ); - - - jQuery._evalUrl = function( url ) { - return jQuery.ajax( { - url: url, - - // Make this explicit, since user can override this through ajaxSetup (#11264) - type: "GET", - dataType: "script", - cache: true, - async: false, - global: false, - "throws": true - } ); - }; - - - jQuery.fn.extend( { - wrapAll: function( html ) { - var wrap; - - if ( this[ 0 ] ) { - if ( isFunction( html ) ) { - html = html.call( this[ 0 ] ); - } - - // The elements to wrap the target around - wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); - - if ( this[ 0 ].parentNode ) { - wrap.insertBefore( this[ 0 ] ); - } - - wrap.map( function() { - var elem = this; - - while ( elem.firstElementChild ) { - elem = elem.firstElementChild; - } - - return elem; - } ).append( this ); - } - - return this; - }, - - wrapInner: function( html ) { - if ( isFunction( html ) ) { - return this.each( function( i ) { - jQuery( this ).wrapInner( html.call( this, i ) ); - } ); - } - - return this.each( function() { - var self = jQuery( this ), - contents = self.contents(); - - if ( contents.length ) { - contents.wrapAll( html ); - - } else { - self.append( html ); - } - } ); - }, - - wrap: function( html ) { - var htmlIsFunction = isFunction( html ); - - return this.each( function( i ) { - jQuery( this ).wrapAll( htmlIsFunction ? html.call( this, i ) : html ); - } ); - }, - - unwrap: function( selector ) { - this.parent( selector ).not( "body" ).each( function() { - jQuery( this ).replaceWith( this.childNodes ); - } ); - return this; - } - } ); - - - jQuery.expr.pseudos.hidden = function( elem ) { - return !jQuery.expr.pseudos.visible( elem ); - }; - jQuery.expr.pseudos.visible = function( elem ) { - return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); - }; - - - - - jQuery.ajaxSettings.xhr = function() { - try { - return new window.XMLHttpRequest(); - } catch ( e ) {} - }; - - var xhrSuccessStatus = { - - // File protocol always yields status code 0, assume 200 - 0: 200, - - // Support: IE <=9 only - // #1450: sometimes IE returns 1223 when it should be 204 - 1223: 204 - }, - xhrSupported = jQuery.ajaxSettings.xhr(); - - support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); - support.ajax = xhrSupported = !!xhrSupported; - - jQuery.ajaxTransport( function( options ) { - var callback, errorCallback; - - // Cross domain only allowed if supported through XMLHttpRequest - if ( support.cors || xhrSupported && !options.crossDomain ) { - return { - send: function( headers, complete ) { - var i, - xhr = options.xhr(); - - xhr.open( - options.type, - options.url, - options.async, - options.username, - options.password - ); - - // Apply custom fields if provided - if ( options.xhrFields ) { - for ( i in options.xhrFields ) { - xhr[ i ] = options.xhrFields[ i ]; - } - } - - // Override mime type if needed - if ( options.mimeType && xhr.overrideMimeType ) { - xhr.overrideMimeType( options.mimeType ); - } - - // X-Requested-With header - // For cross-domain requests, seeing as conditions for a preflight are - // akin to a jigsaw puzzle, we simply never set it to be sure. - // (it can always be set on a per-request basis or even using ajaxSetup) - // For same-domain requests, won't change header if already provided. - if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) { - headers[ "X-Requested-With" ] = "XMLHttpRequest"; - } - - // Set headers - for ( i in headers ) { - xhr.setRequestHeader( i, headers[ i ] ); - } - - // Callback - callback = function( type ) { - return function() { - if ( callback ) { - callback = errorCallback = xhr.onload = - xhr.onerror = xhr.onabort = xhr.ontimeout = - xhr.onreadystatechange = null; - - if ( type === "abort" ) { - xhr.abort(); - } else if ( type === "error" ) { - - // Support: IE <=9 only - // On a manual native abort, IE9 throws - // errors on any property access that is not readyState - if ( typeof xhr.status !== "number" ) { - complete( 0, "error" ); - } else { - complete( - - // File: protocol always yields status 0; see #8605, #14207 - xhr.status, - xhr.statusText - ); - } - } else { - complete( - xhrSuccessStatus[ xhr.status ] || xhr.status, - xhr.statusText, - - // Support: IE <=9 only - // IE9 has no XHR2 but throws on binary (trac-11426) - // For XHR2 non-text, let the caller handle it (gh-2498) - ( xhr.responseType || "text" ) !== "text" || - typeof xhr.responseText !== "string" ? - { binary: xhr.response } : - { text: xhr.responseText }, - xhr.getAllResponseHeaders() - ); - } - } - }; - }; - - // Listen to events - xhr.onload = callback(); - errorCallback = xhr.onerror = xhr.ontimeout = callback( "error" ); - - // Support: IE 9 only - // Use onreadystatechange to replace onabort - // to handle uncaught aborts - if ( xhr.onabort !== undefined ) { - xhr.onabort = errorCallback; - } else { - xhr.onreadystatechange = function() { - - // Check readyState before timeout as it changes - if ( xhr.readyState === 4 ) { - - // Allow onerror to be called first, - // but that will not handle a native abort - // Also, save errorCallback to a variable - // as xhr.onerror cannot be accessed - window.setTimeout( function() { - if ( callback ) { - errorCallback(); - } - } ); - } - }; - } - - // Create the abort callback - callback = callback( "abort" ); - - try { - - // Do send the request (this may raise an exception) - xhr.send( options.hasContent && options.data || null ); - } catch ( e ) { - - // #14683: Only rethrow if this hasn't been notified as an error yet - if ( callback ) { - throw e; - } - } - }, - - abort: function() { - if ( callback ) { - callback(); - } - } - }; - } - } ); - - - - -// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432) - jQuery.ajaxPrefilter( function( s ) { - if ( s.crossDomain ) { - s.contents.script = false; - } - } ); - -// Install script dataType - jQuery.ajaxSetup( { - accepts: { - script: "text/javascript, application/javascript, " + - "application/ecmascript, application/x-ecmascript" - }, - contents: { - script: /\b(?:java|ecma)script\b/ - }, - converters: { - "text script": function( text ) { - jQuery.globalEval( text ); - return text; - } - } - } ); - -// Handle cache's special case and crossDomain - jQuery.ajaxPrefilter( "script", function( s ) { - if ( s.cache === undefined ) { - s.cache = false; - } - if ( s.crossDomain ) { - s.type = "GET"; - } - } ); - -// Bind script tag hack transport - jQuery.ajaxTransport( "script", function( s ) { - - // This transport only deals with cross domain requests - if ( s.crossDomain ) { - var script, callback; - return { - send: function( _, complete ) { - script = jQuery( " - - - - -
-
- - -
- - -
-
- - - diff --git a/source-code/advanced/springboot-oss/src/main/resources/templates/success.html b/source-code/advanced/springboot-oss/src/main/resources/templates/success.html deleted file mode 100644 index dde1ca2..0000000 --- a/source-code/advanced/springboot-oss/src/main/resources/templates/success.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - 上传结果 - - -

上传成功!

-图片地址为: - - \ No newline at end of file diff --git a/source-code/advanced/springboot-oss/src/test/java/top/snailclimb/springbootoss/SpringbootOssApplicationTests.java b/source-code/advanced/springboot-oss/src/test/java/top/snailclimb/springbootoss/SpringbootOssApplicationTests.java deleted file mode 100644 index 0737dbe..0000000 --- a/source-code/advanced/springboot-oss/src/test/java/top/snailclimb/springbootoss/SpringbootOssApplicationTests.java +++ /dev/null @@ -1,17 +0,0 @@ -package top.snailclimb.springbootoss; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class SpringbootOssApplicationTests { - - - @Test - public void contextLoads() { - } - -} diff --git a/source-code/basis/jpa-demo/pom.xml b/source-code/basis/jpa-demo/pom.xml index 511ca9b..0bf0d4c 100644 --- a/source-code/basis/jpa-demo/pom.xml +++ b/source-code/basis/jpa-demo/pom.xml @@ -32,6 +32,11 @@ mysql-connector-java runtime + + com.h2database + h2 + runtime + org.projectlombok lombok diff --git a/source-code/basis/jpa-demo/src/main/resources/application.properties b/source-code/basis/jpa-demo/src/main/resources/application.properties index e7405ea..9d0470e 100644 --- a/source-code/basis/jpa-demo/src/main/resources/application.properties +++ b/source-code/basis/jpa-demo/src/main/resources/application.properties @@ -1,6 +1,11 @@ -spring.datasource.url=jdbc:mysql://localhost:3306/springboot_jpa?useSSL=false&serverTimezone=CTT +# 数据库url地址 +spring.datasource.url=jdbc:h2:mem:jpa-demo spring.datasource.username=root spring.datasource.password=123456 +spring.datasource.platform=h2 +spring.datasource.driverClassName =org.h2.Driver + +spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true # 打印出 sql 语句 spring.jpa.show-sql=true #常用的有四种: @@ -8,7 +13,8 @@ spring.jpa.show-sql=true # 2.create-drop:每次启动项目创建表结构,关闭项目删除表结构 # 3.update:每次启动项目会更新表结构 # 4. validate:验证表结构,不对数据库进行任何更改 -spring.jpa.hibernate.ddl-auto=create +spring.jpa.hibernate.ddl-auto=update spring.jpa.open-in-view=false -# 创建的表的 ENGINE 为 InnoDB -spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL55Dialect +server.port=8080 +#H2控制台 +spring.h2.console.enabled=true diff --git a/source-code/start/hello-world/.gitignore b/source-code/basis/life-cycle-annotation/.gitignore similarity index 100% rename from source-code/start/hello-world/.gitignore rename to source-code/basis/life-cycle-annotation/.gitignore diff --git a/source-code/basis/life-cycle-annotation/.mvn/wrapper/MavenWrapperDownloader.java b/source-code/basis/life-cycle-annotation/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..a45eb6b --- /dev/null +++ b/source-code/basis/life-cycle-annotation/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,118 @@ +/* + * Copyright 2007-present 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 + * + * https://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. + */ + +import java.net.*; +import java.io.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader { + + private static final String WRAPPER_VERSION = "0.5.6"; + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if (mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if (mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if (!outputFile.getParentFile().exists()) { + if (!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/source-code/basis/life-cycle-annotation/.mvn/wrapper/maven-wrapper.jar b/source-code/basis/life-cycle-annotation/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..2cc7d4a Binary files /dev/null and b/source-code/basis/life-cycle-annotation/.mvn/wrapper/maven-wrapper.jar differ diff --git a/source-code/basis/life-cycle-annotation/.mvn/wrapper/maven-wrapper.properties b/source-code/basis/life-cycle-annotation/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..642d572 --- /dev/null +++ b/source-code/basis/life-cycle-annotation/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/source-code/basis/life-cycle-annotation/mvnw b/source-code/basis/life-cycle-annotation/mvnw new file mode 100755 index 0000000..3c8a553 --- /dev/null +++ b/source-code/basis/life-cycle-annotation/mvnw @@ -0,0 +1,322 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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 +# +# https://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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ]; then + + if [ -f /etc/mavenrc ]; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ]; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false +darwin=false +mingw=false +case "$(uname)" in +CYGWIN*) cygwin=true ;; +MINGW*) mingw=true ;; +Darwin*) + darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="$(/usr/libexec/java_home)" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ]; then + if [ -r /etc/gentoo-release ]; then + JAVA_HOME=$(java-config --jre-home) + fi +fi + +if [ -z "$M2_HOME" ]; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ]; do + ls=$(ls -ld "$PRG") + link=$(expr "$ls" : '.*-> \(.*\)$') + if expr "$link" : '/.*' >/dev/null; then + PRG="$link" + else + PRG="$(dirname "$PRG")/$link" + fi + done + + saveddir=$(pwd) + + M2_HOME=$(dirname "$PRG")/.. + + # make it fully qualified + M2_HOME=$(cd "$M2_HOME" && pwd) + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=$(cygpath --unix "$M2_HOME") + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --unix "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --unix "$CLASSPATH") +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw; then + [ -n "$M2_HOME" ] && + M2_HOME="$( ( + cd "$M2_HOME" + pwd + ))" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="$( ( + cd "$JAVA_HOME" + pwd + ))" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="$(which javac)" + if [ -n "$javaExecutable" ] && ! [ "$(expr \"$javaExecutable\" : '\([^ ]*\)')" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=$(which readlink) + if [ ! $(expr "$readLink" : '\([^ ]*\)') = "no" ]; then + if $darwin; then + javaHome="$(dirname \"$javaExecutable\")" + javaExecutable="$(cd \"$javaHome\" && pwd -P)/javac" + else + javaExecutable="$(readlink -f \"$javaExecutable\")" + fi + javaHome="$(dirname \"$javaExecutable\")" + javaHome=$(expr "$javaHome" : '\(.*\)/bin') + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ]; then + if [ -n "$JAVA_HOME" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="$(which java)" + fi +fi + +if [ ! -x "$JAVACMD" ]; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ]; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ]; then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ]; do + if [ -d "$wdir"/.mvn ]; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=$( + cd "$wdir/.." + pwd + ) + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' <"$1")" + fi +} + +BASE_DIR=$(find_maven_basedir "$(pwd)") +if [ -z "$BASE_DIR" ]; then + exit 1 +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in wrapperUrl) + jarUrl="$value" + break + ;; + esac + done <"$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") + fi + + if command -v wget >/dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl >/dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=$(cygpath --path --windows "$javaClass") + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=$(cygpath --path --windows "$M2_HOME") + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --windows "$CLASSPATH") + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/source-code/basis/life-cycle-annotation/mvnw.cmd b/source-code/basis/life-cycle-annotation/mvnw.cmd new file mode 100644 index 0000000..c8d4337 --- /dev/null +++ b/source-code/basis/life-cycle-annotation/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/source-code/basis/life-cycle-annotation/pom.xml b/source-code/basis/life-cycle-annotation/pom.xml new file mode 100644 index 0000000..83a2b41 --- /dev/null +++ b/source-code/basis/life-cycle-annotation/pom.xml @@ -0,0 +1,49 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.4.RELEASE + + + cn.javaguide + life-cycle-annotation + 0.0.1-SNAPSHOT + life-cycle-annotation + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/source-code/basis/life-cycle-annotation/src/main/java/cn/javaguide/LifeCycleAnnotationApplication.java b/source-code/basis/life-cycle-annotation/src/main/java/cn/javaguide/LifeCycleAnnotationApplication.java new file mode 100644 index 0000000..6ee104b --- /dev/null +++ b/source-code/basis/life-cycle-annotation/src/main/java/cn/javaguide/LifeCycleAnnotationApplication.java @@ -0,0 +1,16 @@ +package cn.javaguide; + +import cn.javaguide.config.MyConfiguration; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class LifeCycleAnnotationApplication { + + public static void main(String[] args) { + MyConfiguration myConfiguration = new MyConfiguration(); + MyConfiguration myConfiguration2 = new MyConfiguration(); + SpringApplication.run(LifeCycleAnnotationApplication.class, args); + } + +} diff --git a/source-code/basis/life-cycle-annotation/src/main/java/cn/javaguide/config/MyConfiguration.java b/source-code/basis/life-cycle-annotation/src/main/java/cn/javaguide/config/MyConfiguration.java new file mode 100644 index 0000000..e577773 --- /dev/null +++ b/source-code/basis/life-cycle-annotation/src/main/java/cn/javaguide/config/MyConfiguration.java @@ -0,0 +1,24 @@ +package cn.javaguide.config; + +import org.springframework.context.annotation.Configuration; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; + +@Configuration +public class MyConfiguration { + public MyConfiguration() { + System.out.println("构造方法被调用"); + } + + @PostConstruct + private void init() { + System.out.println("PostConstruct注解方法被调用"); + } + + @PreDestroy + private void shutdown() { + System.out.println("PreDestroy注解方法被调用"); + } +} + diff --git a/source-code/basis/life-cycle-annotation/src/main/java/cn/javaguide/config/MyConfiguration2.java b/source-code/basis/life-cycle-annotation/src/main/java/cn/javaguide/config/MyConfiguration2.java new file mode 100644 index 0000000..15c1007 --- /dev/null +++ b/source-code/basis/life-cycle-annotation/src/main/java/cn/javaguide/config/MyConfiguration2.java @@ -0,0 +1,24 @@ +package cn.javaguide.config; + +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class MyConfiguration2 implements InitializingBean, DisposableBean { + public MyConfiguration2() { + System.out.println("构造方法被调用"); + } + + @Override + public void afterPropertiesSet() { + System.out.println("afterPropertiesSet方法被调用"); + } + + @Override + public void destroy() { + System.out.println("destroy方法被调用"); + } + +} + diff --git a/source-code/basis/life-cycle-annotation/src/main/resources/application.properties b/source-code/basis/life-cycle-annotation/src/main/resources/application.properties new file mode 100644 index 0000000..c4e658f --- /dev/null +++ b/source-code/basis/life-cycle-annotation/src/main/resources/application.properties @@ -0,0 +1 @@ +server.port=8888 diff --git a/source-code/basis/life-cycle-annotation/src/test/java/cn/javaguide/lifecycleannotation/LifeCycleAnnotationApplicationTests.java b/source-code/basis/life-cycle-annotation/src/test/java/cn/javaguide/lifecycleannotation/LifeCycleAnnotationApplicationTests.java new file mode 100644 index 0000000..1641311 --- /dev/null +++ b/source-code/basis/life-cycle-annotation/src/test/java/cn/javaguide/lifecycleannotation/LifeCycleAnnotationApplicationTests.java @@ -0,0 +1,13 @@ +package cn.javaguide.lifecycleannotation; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class LifeCycleAnnotationApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/source-code/advanced/springboot-oss/.gitignore b/source-code/basis/read-config-properties/.gitignore similarity index 71% rename from source-code/advanced/springboot-oss/.gitignore rename to source-code/basis/read-config-properties/.gitignore index 82eca33..a2a3040 100644 --- a/source-code/advanced/springboot-oss/.gitignore +++ b/source-code/basis/read-config-properties/.gitignore @@ -1,5 +1,8 @@ -/target/ +HELP.md +target/ !.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** ### STS ### .apt_generated @@ -18,8 +21,11 @@ ### NetBeans ### /nbproject/private/ -/build/ /nbbuild/ /dist/ /nbdist/ -/.nb-gradle/ \ No newline at end of file +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/source-code/basis/read-config-properties/.mvn/wrapper/MavenWrapperDownloader.java b/source-code/basis/read-config-properties/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..a45eb6b --- /dev/null +++ b/source-code/basis/read-config-properties/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,118 @@ +/* + * Copyright 2007-present 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 + * + * https://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. + */ + +import java.net.*; +import java.io.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader { + + private static final String WRAPPER_VERSION = "0.5.6"; + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if (mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if (mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if (!outputFile.getParentFile().exists()) { + if (!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/source-code/basis/read-config-properties/.mvn/wrapper/maven-wrapper.jar b/source-code/basis/read-config-properties/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..2cc7d4a Binary files /dev/null and b/source-code/basis/read-config-properties/.mvn/wrapper/maven-wrapper.jar differ diff --git a/source-code/basis/read-config-properties/.mvn/wrapper/maven-wrapper.properties b/source-code/basis/read-config-properties/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..642d572 --- /dev/null +++ b/source-code/basis/read-config-properties/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/source-code/basis/read-config-properties/config/application.yml b/source-code/basis/read-config-properties/config/application.yml new file mode 100644 index 0000000..d437e2b --- /dev/null +++ b/source-code/basis/read-config-properties/config/application.yml @@ -0,0 +1,18 @@ +server: + port: 8083 +# 优先级1 +wuhan2020: 【优先级1】2020年初武汉爆发了新型冠状病毒,疫情严重,但是,我相信一切都会过去!武汉加油!中国加油! + +my-profile: + name: Guide哥 + email: koushuangbwcx@163.com + +library: + location: 湖北武汉加油中国加油 + books: + - name: 天才基本法 + description: 二十二岁的林朝夕在父亲确诊阿尔茨海默病这天,得知自己暗恋多年的校园男神裴之即将出国深造的消息——对方考取的学校,恰是父亲当年为她放弃的那所。 + - name: 时间的秩序 + description: 为什么我们记得过去,而非未来?时间“流逝”意味着什么?是我们存在于时间之内,还是时间存在于我们之中?卡洛·罗韦利用诗意的文字,邀请我们思考这一亘古难题——时间的本质。 + - name: 了不起的我 + description: 如何养成一个新习惯?如何让心智变得更成熟?如何拥有高质量的关系? 如何走出人生的艰难时刻? diff --git a/source-code/basis/read-config-properties/mvnw b/source-code/basis/read-config-properties/mvnw new file mode 100755 index 0000000..3c8a553 --- /dev/null +++ b/source-code/basis/read-config-properties/mvnw @@ -0,0 +1,322 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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 +# +# https://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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ]; then + + if [ -f /etc/mavenrc ]; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ]; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false +darwin=false +mingw=false +case "$(uname)" in +CYGWIN*) cygwin=true ;; +MINGW*) mingw=true ;; +Darwin*) + darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="$(/usr/libexec/java_home)" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ]; then + if [ -r /etc/gentoo-release ]; then + JAVA_HOME=$(java-config --jre-home) + fi +fi + +if [ -z "$M2_HOME" ]; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ]; do + ls=$(ls -ld "$PRG") + link=$(expr "$ls" : '.*-> \(.*\)$') + if expr "$link" : '/.*' >/dev/null; then + PRG="$link" + else + PRG="$(dirname "$PRG")/$link" + fi + done + + saveddir=$(pwd) + + M2_HOME=$(dirname "$PRG")/.. + + # make it fully qualified + M2_HOME=$(cd "$M2_HOME" && pwd) + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=$(cygpath --unix "$M2_HOME") + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --unix "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --unix "$CLASSPATH") +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw; then + [ -n "$M2_HOME" ] && + M2_HOME="$( ( + cd "$M2_HOME" + pwd + ))" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="$( ( + cd "$JAVA_HOME" + pwd + ))" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="$(which javac)" + if [ -n "$javaExecutable" ] && ! [ "$(expr \"$javaExecutable\" : '\([^ ]*\)')" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=$(which readlink) + if [ ! $(expr "$readLink" : '\([^ ]*\)') = "no" ]; then + if $darwin; then + javaHome="$(dirname \"$javaExecutable\")" + javaExecutable="$(cd \"$javaHome\" && pwd -P)/javac" + else + javaExecutable="$(readlink -f \"$javaExecutable\")" + fi + javaHome="$(dirname \"$javaExecutable\")" + javaHome=$(expr "$javaHome" : '\(.*\)/bin') + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ]; then + if [ -n "$JAVA_HOME" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="$(which java)" + fi +fi + +if [ ! -x "$JAVACMD" ]; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ]; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ]; then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ]; do + if [ -d "$wdir"/.mvn ]; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=$( + cd "$wdir/.." + pwd + ) + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' <"$1")" + fi +} + +BASE_DIR=$(find_maven_basedir "$(pwd)") +if [ -z "$BASE_DIR" ]; then + exit 1 +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in wrapperUrl) + jarUrl="$value" + break + ;; + esac + done <"$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") + fi + + if command -v wget >/dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl >/dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=$(cygpath --path --windows "$javaClass") + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=$(cygpath --path --windows "$M2_HOME") + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --windows "$CLASSPATH") + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/source-code/basis/read-config-properties/mvnw.cmd b/source-code/basis/read-config-properties/mvnw.cmd new file mode 100644 index 0000000..c8d4337 --- /dev/null +++ b/source-code/basis/read-config-properties/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/source-code/basis/read-config-properties/pom.xml b/source-code/basis/read-config-properties/pom.xml new file mode 100644 index 0000000..c179c08 --- /dev/null +++ b/source-code/basis/read-config-properties/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.4.RELEASE + + + cn.javaguide + read-config-properties + 0.0.1-SNAPSHOT + read-config-properties + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.projectlombok + lombok + 1.18.10 + provided + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/source-code/basis/read-config-properties/src/main/java/cn/javaguide/readconfigproperties/LibraryProperties.java b/source-code/basis/read-config-properties/src/main/java/cn/javaguide/readconfigproperties/LibraryProperties.java new file mode 100644 index 0000000..64b79d8 --- /dev/null +++ b/source-code/basis/read-config-properties/src/main/java/cn/javaguide/readconfigproperties/LibraryProperties.java @@ -0,0 +1,29 @@ +package cn.javaguide.readconfigproperties; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Component +@ConfigurationProperties(prefix = "library") +@Setter +@Getter +@ToString +class LibraryProperties { + private String location; + private List books; + + @Setter + @Getter + @ToString + static class Book { + String name; + String description; + } +} diff --git a/source-code/basis/read-config-properties/src/main/java/cn/javaguide/readconfigproperties/ProfileProperties.java b/source-code/basis/read-config-properties/src/main/java/cn/javaguide/readconfigproperties/ProfileProperties.java new file mode 100644 index 0000000..cc0975d --- /dev/null +++ b/source-code/basis/read-config-properties/src/main/java/cn/javaguide/readconfigproperties/ProfileProperties.java @@ -0,0 +1,29 @@ +package cn.javaguide.readconfigproperties; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.validation.annotation.Validated; + +import javax.validation.constraints.Email; +import javax.validation.constraints.NotEmpty; + +/** + * @author shuang.kou + */ +@Getter +@Setter +@ToString +@ConfigurationProperties("my-profile") +@Validated +public class ProfileProperties { + @NotEmpty + private String name; + + @Email + @NotEmpty + private String email; + + private Boolean handsome = Boolean.TRUE; +} diff --git a/source-code/basis/read-config-properties/src/main/java/cn/javaguide/readconfigproperties/ReadConfigPropertiesApplication.java b/source-code/basis/read-config-properties/src/main/java/cn/javaguide/readconfigproperties/ReadConfigPropertiesApplication.java new file mode 100644 index 0000000..5bdc777 --- /dev/null +++ b/source-code/basis/read-config-properties/src/main/java/cn/javaguide/readconfigproperties/ReadConfigPropertiesApplication.java @@ -0,0 +1,39 @@ +package cn.javaguide.readconfigproperties; + +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.EnableConfigurationProperties; + +/** + * @author shuang.kou + */ +@SpringBootApplication +@EnableConfigurationProperties(ProfileProperties.class) +public class ReadConfigPropertiesApplication implements InitializingBean { + private final ProfileProperties profileProperties; + private final LibraryProperties libraryProperties; + private final WebSite webSite; + @Value("${wuhan2020}") + String wuhan2020; + + public ReadConfigPropertiesApplication(LibraryProperties library, ProfileProperties profileProperties, WebSite webSite) { + this.libraryProperties = library; + this.profileProperties = profileProperties; + this.webSite = webSite; + } + + public static void main(String[] args) { + SpringApplication.run(ReadConfigPropertiesApplication.class, args); + } + + @Override + public void afterPropertiesSet() { + System.out.println(wuhan2020); + System.out.println(webSite.getUrl()); + System.out.println(libraryProperties.getLocation()); + System.out.println(libraryProperties.getBooks()); + System.out.println(profileProperties.toString()); + } +} diff --git a/source-code/basis/read-config-properties/src/main/java/cn/javaguide/readconfigproperties/WebSite.java b/source-code/basis/read-config-properties/src/main/java/cn/javaguide/readconfigproperties/WebSite.java new file mode 100644 index 0000000..bc2e605 --- /dev/null +++ b/source-code/basis/read-config-properties/src/main/java/cn/javaguide/readconfigproperties/WebSite.java @@ -0,0 +1,16 @@ +package cn.javaguide.readconfigproperties; + +import lombok.Getter; +import lombok.Setter; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.PropertySource; +import org.springframework.stereotype.Component; + +@Component +@PropertySource("classpath:website.properties") +@Getter +@Setter +class WebSite { + @Value("${url}") + private String url; +} diff --git a/source-code/basis/read-config-properties/src/main/resources/application.yml b/source-code/basis/read-config-properties/src/main/resources/application.yml new file mode 100644 index 0000000..3e9938a --- /dev/null +++ b/source-code/basis/read-config-properties/src/main/resources/application.yml @@ -0,0 +1,17 @@ + +# 优先级3 +wuhan2020: 【优先级3】武汉加油!中国加油! + +my-profile: + name: Guide哥 + email: koushuangbwcx@163.com + +library: + location: 湖北武汉加油中国加油 + books: + - name: 天才基本法 + description: 二十二岁的林朝夕在父亲确诊阿尔茨海默病这天,得知自己暗恋多年的校园男神裴之即将出国深造的消息——对方考取的学校,恰是父亲当年为她放弃的那所。 + - name: 时间的秩序 + description: 为什么我们记得过去,而非未来?时间“流逝”意味着什么?是我们存在于时间之内,还是时间存在于我们之中?卡洛·罗韦利用诗意的文字,邀请我们思考这一亘古难题——时间的本质。 + - name: 了不起的我 + description: 如何养成一个新习惯?如何让心智变得更成熟?如何拥有高质量的关系? 如何走出人生的艰难时刻? diff --git a/source-code/basis/read-config-properties/src/main/resources/config/application.yml b/source-code/basis/read-config-properties/src/main/resources/config/application.yml new file mode 100644 index 0000000..aa25d20 --- /dev/null +++ b/source-code/basis/read-config-properties/src/main/resources/config/application.yml @@ -0,0 +1,16 @@ +# 优先级2 +wuhan2020: 【优先级2】2020年初武汉爆发了新型冠状病毒,疫情严重,但是,我相信一切都会过去!武汉加油!中国加油! + +my-profile: + name: Guide哥 + email: koushuangbwcx@163.com + +library: + location: 湖北武汉加油中国加油 + books: + - name: 天才基本法 + description: 二十二岁的林朝夕在父亲确诊阿尔茨海默病这天,得知自己暗恋多年的校园男神裴之即将出国深造的消息——对方考取的学校,恰是父亲当年为她放弃的那所。 + - name: 时间的秩序 + description: 为什么我们记得过去,而非未来?时间“流逝”意味着什么?是我们存在于时间之内,还是时间存在于我们之中?卡洛·罗韦利用诗意的文字,邀请我们思考这一亘古难题——时间的本质。 + - name: 了不起的我 + description: 如何养成一个新习惯?如何让心智变得更成熟?如何拥有高质量的关系? 如何走出人生的艰难时刻? diff --git a/source-code/basis/read-config-properties/src/main/resources/website.properties b/source-code/basis/read-config-properties/src/main/resources/website.properties new file mode 100644 index 0000000..a73df68 --- /dev/null +++ b/source-code/basis/read-config-properties/src/main/resources/website.properties @@ -0,0 +1,2 @@ +url=https://javaguide.cn/ + diff --git a/source-code/basis/read-config-properties/src/test/java/cn/javaguide/readconfigproperties/ReadConfigPropertiesApplicationTests.java b/source-code/basis/read-config-properties/src/test/java/cn/javaguide/readconfigproperties/ReadConfigPropertiesApplicationTests.java new file mode 100644 index 0000000..3a85834 --- /dev/null +++ b/source-code/basis/read-config-properties/src/test/java/cn/javaguide/readconfigproperties/ReadConfigPropertiesApplicationTests.java @@ -0,0 +1,13 @@ +package cn.javaguide.readconfigproperties; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ReadConfigPropertiesApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/source-code/basis/springboot-handle-exception-improved/.idea/modules/webApp.main.iml b/source-code/basis/springboot-handle-exception-improved/.idea/modules/webApp.main.iml new file mode 100644 index 0000000..4a4ce55 --- /dev/null +++ b/source-code/basis/springboot-handle-exception-improved/.idea/modules/webApp.main.iml @@ -0,0 +1,8 @@ + + + + + + \ No newline at end of file diff --git a/source-code/basis/springboot-handle-exception-improved/build.gradle b/source-code/basis/springboot-handle-exception-improved/build.gradle index 6496f28..1f7d3f3 100644 --- a/source-code/basis/springboot-handle-exception-improved/build.gradle +++ b/source-code/basis/springboot-handle-exception-improved/build.gradle @@ -1,5 +1,5 @@ plugins { - id 'org.springframework.boot' version '2.1.9.RELEASE' + id 'org.springframework.boot' version '2.1.8.RELEASE' id 'java' } diff --git a/source-code/bean-validation-demo/.gitignore b/source-code/bean-validation-demo/.gitignore new file mode 100644 index 0000000..a2a3040 --- /dev/null +++ b/source-code/bean-validation-demo/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/source-code/bean-validation-demo/.mvn/wrapper/MavenWrapperDownloader.java b/source-code/bean-validation-demo/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..7f91a56 --- /dev/null +++ b/source-code/bean-validation-demo/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,114 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you 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 + + https://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. +*/ + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.URL; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.util.Properties; + +public class MavenWrapperDownloader { + + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = + "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if (mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if (mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: : " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if (!outputFile.getParentFile().exists()) { + if (!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/source-code/advanced/springboot-oss/.mvn/wrapper/maven-wrapper.jar b/source-code/bean-validation-demo/.mvn/wrapper/maven-wrapper.jar similarity index 100% rename from source-code/advanced/springboot-oss/.mvn/wrapper/maven-wrapper.jar rename to source-code/bean-validation-demo/.mvn/wrapper/maven-wrapper.jar diff --git a/source-code/start/hello-world/.mvn/wrapper/maven-wrapper.properties b/source-code/bean-validation-demo/.mvn/wrapper/maven-wrapper.properties similarity index 100% rename from source-code/start/hello-world/.mvn/wrapper/maven-wrapper.properties rename to source-code/bean-validation-demo/.mvn/wrapper/maven-wrapper.properties diff --git a/source-code/advanced/springboot-oss/mvnw b/source-code/bean-validation-demo/mvnw old mode 100644 new mode 100755 similarity index 55% rename from source-code/advanced/springboot-oss/mvnw rename to source-code/bean-validation-demo/mvnw index 5551fde..c188654 --- a/source-code/advanced/springboot-oss/mvnw +++ b/source-code/bean-validation-demo/mvnw @@ -8,7 +8,7 @@ # "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 +# https://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 @@ -34,129 +34,136 @@ # MAVEN_SKIP_RC - flag to disable loading of mavenrc files # ---------------------------------------------------------------------------- -if [ -z "$MAVEN_SKIP_RC" ] ; then +if [ -z "$MAVEN_SKIP_RC" ]; then - if [ -f /etc/mavenrc ] ; then + if [ -f /etc/mavenrc ]; then . /etc/mavenrc fi - if [ -f "$HOME/.mavenrc" ] ; then + if [ -f "$HOME/.mavenrc" ]; then . "$HOME/.mavenrc" fi fi # OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; +cygwin=false +darwin=false mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home - # See https://developer.apple.com/library/mac/qa/qa1170/_index.html - if [ -z "$JAVA_HOME" ]; then - if [ -x "/usr/libexec/java_home" ]; then - export JAVA_HOME="`/usr/libexec/java_home`" - else - export JAVA_HOME="/Library/Java/Home" - fi +case "$(uname)" in +CYGWIN*) cygwin=true ;; +MINGW*) mingw=true ;; +Darwin*) + darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="$(/usr/libexec/java_home)" + else + export JAVA_HOME="/Library/Java/Home" fi - ;; + fi + ;; esac -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` +if [ -z "$JAVA_HOME" ]; then + if [ -r /etc/gentoo-release ]; then + JAVA_HOME=$(java-config --jre-home) fi fi -if [ -z "$M2_HOME" ] ; then +if [ -z "$M2_HOME" ]; then ## resolve links - $0 may be a link to maven's home PRG="$0" # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then + while [ -h "$PRG" ]; do + ls=$(ls -ld "$PRG") + link=$(expr "$ls" : '.*-> \(.*\)$') + if expr "$link" : '/.*' >/dev/null; then PRG="$link" else - PRG="`dirname "$PRG"`/$link" + PRG="$(dirname "$PRG")/$link" fi done - saveddir=`pwd` + saveddir=$(pwd) - M2_HOME=`dirname "$PRG"`/.. + M2_HOME=$(dirname "$PRG")/.. # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` + M2_HOME=$(cd "$M2_HOME" && pwd) cd "$saveddir" # echo Using m2 at $M2_HOME fi # For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then +if $cygwin; then [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` + M2_HOME=$(cygpath --unix "$M2_HOME") [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + JAVA_HOME=$(cygpath --unix "$JAVA_HOME") [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` + CLASSPATH=$(cygpath --path --unix "$CLASSPATH") fi # For Mingw, ensure paths are in UNIX format before anything is touched -if $mingw ; then +if $mingw; then [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" + M2_HOME="$( ( + cd "$M2_HOME" + pwd + ))" [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + JAVA_HOME="$( ( + cd "$JAVA_HOME" + pwd + ))" # TODO classpath? fi if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + javaExecutable="$(which javac)" + if [ -n "$javaExecutable" ] && ! [ "$(expr \"$javaExecutable\" : '\([^ ]*\)')" = "no" ]; then # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + readLink=$(which readlink) + if [ ! $(expr "$readLink" : '\([^ ]*\)') = "no" ]; then + if $darwin; then + javaHome="$(dirname \"$javaExecutable\")" + javaExecutable="$(cd \"$javaHome\" && pwd -P)/javac" else - javaExecutable="`readlink -f \"$javaExecutable\"`" + javaExecutable="$(readlink -f \"$javaExecutable\")" fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` + javaHome="$(dirname \"$javaExecutable\")" + javaHome=$(expr "$javaHome" : '\(.*\)/bin') JAVA_HOME="$javaHome" export JAVA_HOME fi fi fi -if [ -z "$JAVACMD" ] ; then - if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then +if [ -z "$JAVACMD" ]; then + if [ -n "$JAVA_HOME" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi else - JAVACMD="`which java`" + JAVACMD="$(which java)" fi fi -if [ ! -x "$JAVACMD" ] ; then +if [ ! -x "$JAVACMD" ]; then echo "Error: JAVA_HOME is not defined correctly." >&2 echo " We cannot execute $JAVACMD" >&2 exit 1 fi -if [ -z "$JAVA_HOME" ] ; then +if [ -z "$JAVA_HOME" ]; then echo "Warning: JAVA_HOME environment variable is not set." fi @@ -166,22 +173,24 @@ CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher # first directory with .mvn subdirectory is considered project base directory find_maven_basedir() { - if [ -z "$1" ] - then + if [ -z "$1" ]; then echo "Path not specified to find_maven_basedir" return 1 fi basedir="$1" wdir="$1" - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then + while [ "$wdir" != '/' ]; do + if [ -d "$wdir"/.mvn ]; then basedir=$wdir break fi # workaround for JBEAP-8937 (on Solaris 10/Sparc) if [ -d "${wdir}" ]; then - wdir=`cd "$wdir/.."; pwd` + wdir=$( + cd "$wdir/.." + pwd + ) fi # end of workaround done @@ -191,13 +200,13 @@ find_maven_basedir() { # concatenates all lines of a file concat_lines() { if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" + echo "$(tr -s '\n' ' ' <"$1")" fi } -BASE_DIR=`find_maven_basedir "$(pwd)"` +BASE_DIR=$(find_maven_basedir "$(pwd)") if [ -z "$BASE_DIR" ]; then - exit 1; + exit 1 fi ########################################################################################## @@ -205,55 +214,58 @@ fi # This allows using the maven wrapper in projects that prohibit checking in binary data. ########################################################################################## if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" + while IFS="=" read key value; do + case "$key" in wrapperUrl) + jarUrl="$value" + break + ;; + esac + done <"$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + + if command -v wget >/dev/null; then if [ "$MVNW_VERBOSE" = true ]; then - echo "Found .mvn/wrapper/maven-wrapper.jar" + echo "Found wget ... using wget" fi -else + wget "$jarUrl" -O "$wrapperJarPath" + elif command -v curl >/dev/null; then if [ "$MVNW_VERBOSE" = true ]; then - echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + echo "Found curl ... using curl" fi - jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" - while IFS="=" read key value; do - case "$key" in (wrapperUrl) jarUrl="$value"; break ;; - esac - done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + curl -o "$wrapperJarPath" "$jarUrl" + else if [ "$MVNW_VERBOSE" = true ]; then - echo "Downloading from: $jarUrl" + echo "Falling back to using Java to download" fi - wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" - - if command -v wget > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found wget ... using wget" - fi - wget "$jarUrl" -O "$wrapperJarPath" - elif command -v curl > /dev/null; then + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then if [ "$MVNW_VERBOSE" = true ]; then - echo "Found curl ... using curl" + echo " - Compiling MavenWrapperDownloader.java ..." fi - curl -o "$wrapperJarPath" "$jarUrl" - else + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader if [ "$MVNW_VERBOSE" = true ]; then - echo "Falling back to using Java to download" - fi - javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" - if [ -e "$javaClass" ]; then - if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Compiling MavenWrapperDownloader.java ..." - fi - # Compiling the Java class - ("$JAVA_HOME/bin/javac" "$javaClass") - fi - if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - # Running the downloader - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Running MavenWrapperDownloader.java ..." - fi - ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") - fi + echo " - Running MavenWrapperDownloader.java ..." fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi fi + fi fi ########################################################################################## # End of extension @@ -268,13 +280,13 @@ MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" # For Cygwin, switch paths to Windows format before running java if $cygwin; then [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` + M2_HOME=$(cygpath --path --windows "$M2_HOME") [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + CLASSPATH=$(cygpath --path --windows "$CLASSPATH") [ -n "$MAVEN_PROJECTBASEDIR" ] && - MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` + MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") fi WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain diff --git a/source-code/start/hello-world/mvnw.cmd b/source-code/bean-validation-demo/mvnw.cmd similarity index 100% rename from source-code/start/hello-world/mvnw.cmd rename to source-code/bean-validation-demo/mvnw.cmd diff --git a/source-code/advanced/springboot-oss/pom.xml b/source-code/bean-validation-demo/pom.xml similarity index 60% rename from source-code/advanced/springboot-oss/pom.xml rename to source-code/bean-validation-demo/pom.xml index ac0a2f8..c5a9e2f 100644 --- a/source-code/advanced/springboot-oss/pom.xml +++ b/source-code/bean-validation-demo/pom.xml @@ -1,26 +1,20 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - - top.snailclimb - springboot-oss - 0.0.1-SNAPSHOT - jar - - springboot-oss - Demo project for Spring Boot - org.springframework.boot spring-boot-starter-parent - 2.1.1.RELEASE + 2.4.5 + com.example + bean-validation-demo + 0.0.1-SNAPSHOT + bean-validation-demo + Demo project for Spring Boot - UTF-8 - UTF-8 1.8 @@ -31,29 +25,23 @@ org.springframework.boot - spring-boot-starter-test - test - - - - org.springframework.boot - spring-boot-starter-thymeleaf + spring-boot-starter-validation - - com.aliyun.oss - aliyun-sdk-oss - 2.4.0 + org.projectlombok + lombok + true - commons-fileupload - commons-fileupload - 1.3.3 + junit + junit + 4.13.1 + test org.springframework.boot - spring-boot-configuration-processor - true + spring-boot-starter-test + test @@ -66,5 +54,4 @@ - diff --git a/source-code/advanced/springboot-oss/src/main/java/top/snailclimb/SpringbootOssApplication.java b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/BeanValidationDemoApplication.java similarity index 55% rename from source-code/advanced/springboot-oss/src/main/java/top/snailclimb/SpringbootOssApplication.java rename to source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/BeanValidationDemoApplication.java index fb7baaa..3f934bc 100644 --- a/source-code/advanced/springboot-oss/src/main/java/top/snailclimb/SpringbootOssApplication.java +++ b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/BeanValidationDemoApplication.java @@ -1,12 +1,13 @@ -package top.snailclimb; +package com.example.beanvalidationdemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication -public class SpringbootOssApplication { +public class BeanValidationDemoApplication { public static void main(String[] args) { - SpringApplication.run(SpringbootOssApplication.class, args); + SpringApplication.run(BeanValidationDemoApplication.class, args); } + } diff --git a/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/constants/Constants.java b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/constants/Constants.java new file mode 100644 index 0000000..8c20af3 --- /dev/null +++ b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/constants/Constants.java @@ -0,0 +1,5 @@ +package com.example.beanvalidationdemo.constants; + +public final class Constants { + public static final String sexs = "((^Man$|^Woman$|^UGM$))"; +} diff --git a/source-code/start/hello-world/src/main/java/com/example/helloworld/controller/HelloWorldController.java b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/controller/HelloWorldController.java similarity index 52% rename from source-code/start/hello-world/src/main/java/com/example/helloworld/controller/HelloWorldController.java rename to source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/controller/HelloWorldController.java index 90780b1..8742cbf 100644 --- a/source-code/start/hello-world/src/main/java/com/example/helloworld/controller/HelloWorldController.java +++ b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/controller/HelloWorldController.java @@ -1,14 +1,19 @@ -package com.example.helloworld.controller; +package com.example.beanvalidationdemo.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +/** + * @author shuang.kou + * 验证基本环境搭建是否正确 + */ @RestController -@RequestMapping("test") +@RequestMapping("/api") public class HelloWorldController { - @GetMapping("hello") - public String sayHello() { - return "Hello World"; + + @GetMapping("/hello") + public String hello() { + return "Hello"; } } diff --git a/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/controller/PersonController.java b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/controller/PersonController.java new file mode 100644 index 0000000..c0482b5 --- /dev/null +++ b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/controller/PersonController.java @@ -0,0 +1,38 @@ +package com.example.beanvalidationdemo.controller; + +import com.example.beanvalidationdemo.entity.PersonRequest; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import javax.validation.Valid; +import javax.validation.constraints.Max; +import javax.validation.constraints.Size; + +@RestController +@RequestMapping("/api/persons") +@Validated +public class PersonController { + + @PostMapping + public ResponseEntity save(@RequestBody @Valid PersonRequest personRequest) { + return ResponseEntity.ok().body(personRequest); + } + + @GetMapping("/{id}") + public ResponseEntity getPersonByID(@Valid @PathVariable("id") @Max(value = 5, message = "超过 id 的范围了") Integer id) { + return ResponseEntity.ok().body(id); + } + + @PutMapping + public ResponseEntity getPersonByName(@Valid @RequestParam("name") @Size(max = 6, message = "超过 name 的范围了") String name) { + return ResponseEntity.ok().body(name); + } +} diff --git a/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/entity/Person.java b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/entity/Person.java new file mode 100644 index 0000000..80bb5e8 --- /dev/null +++ b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/entity/Person.java @@ -0,0 +1,18 @@ +package com.example.beanvalidationdemo.entity; + +import com.example.beanvalidationdemo.service.AddPersonGroup; +import com.example.beanvalidationdemo.service.DeletePersonGroup; +import lombok.Data; + +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Null; + +@Data +public class Person { + + // 当验证组为 DeletePersonGroup 的时候 group 字段不能为空 + @NotNull(groups = DeletePersonGroup.class) + // 当验证组为 AddPersonGroup 的时候 group 字段需要为空 + @Null(groups = AddPersonGroup.class) + private String group; +} diff --git a/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/entity/PersonRequest.java b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/entity/PersonRequest.java new file mode 100644 index 0000000..9b2c789 --- /dev/null +++ b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/entity/PersonRequest.java @@ -0,0 +1,44 @@ +package com.example.beanvalidationdemo.entity; + +import com.example.beanvalidationdemo.validation.PhoneNumber; +import com.example.beanvalidationdemo.validation.Region; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; +import javax.validation.constraints.Size; + +/** + * 微信搜 JavaGuide 回复"面试突击"即可免费领取个人原创的 Java 面试手册 + * + * @author Guide哥 + * @date 2021/04/21 20:48 + **/ +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class PersonRequest { + + @NotNull(message = "classId 不能为空") + private String classId; + + @Size(max = 33) + @NotNull(message = "name 不能为空") + private String name; + + @Pattern(regexp = "(^Man$|^Woman$|^UGM$)", message = "sex 值不在可选范围") + @NotNull(message = "sex 不能为空") + private String sex; + + @Region + private String region; + + @PhoneNumber(message = "phoneNumber 格式不正确") + @NotNull(message = "phoneNumber 不能为空") + private String phoneNumber; + +} diff --git a/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/exception/GlobalExceptionHandler.java b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..c4f4e0a --- /dev/null +++ b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/exception/GlobalExceptionHandler.java @@ -0,0 +1,33 @@ +package com.example.beanvalidationdemo.exception; + +import com.example.beanvalidationdemo.controller.PersonController; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; + +import javax.validation.ConstraintViolationException; +import java.util.HashMap; +import java.util.Map; + +@ControllerAdvice(assignableTypes = {PersonController.class}) +public class GlobalExceptionHandler { + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity> handleValidationExceptions( + MethodArgumentNotValidException ex) { + Map errors = new HashMap<>(); + ex.getBindingResult().getAllErrors().forEach((error) -> { + String fieldName = ((FieldError) error).getField(); + String errorMessage = error.getDefaultMessage(); + errors.put(fieldName, errorMessage); + }); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errors); + } + + @ExceptionHandler(ConstraintViolationException.class) + ResponseEntity handleConstraintViolationException(ConstraintViolationException e) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage()); + } +} diff --git a/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/service/AddPersonGroup.java b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/service/AddPersonGroup.java new file mode 100644 index 0000000..1f2950d --- /dev/null +++ b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/service/AddPersonGroup.java @@ -0,0 +1,4 @@ +package com.example.beanvalidationdemo.service; + +public interface AddPersonGroup { +} diff --git a/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/service/DeletePersonGroup.java b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/service/DeletePersonGroup.java new file mode 100644 index 0000000..92f6713 --- /dev/null +++ b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/service/DeletePersonGroup.java @@ -0,0 +1,4 @@ +package com.example.beanvalidationdemo.service; + +public interface DeletePersonGroup { +} diff --git a/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/service/PersonService.java b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/service/PersonService.java new file mode 100644 index 0000000..08e8e14 --- /dev/null +++ b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/service/PersonService.java @@ -0,0 +1,28 @@ +package com.example.beanvalidationdemo.service; + +import com.example.beanvalidationdemo.entity.Person; +import com.example.beanvalidationdemo.entity.PersonRequest; +import org.springframework.stereotype.Service; +import org.springframework.validation.annotation.Validated; + +import javax.validation.Valid; + +@Service +@Validated +public class PersonService { + + public void validatePersonRequest(@Valid PersonRequest personRequest) { + // do something + } + + @Validated(AddPersonGroup.class) + public void validatePersonGroupForAdd(@Valid Person person) { + // do something + } + + @Validated(DeletePersonGroup.class) + public void validatePersonGroupForDelete(@Valid Person person) { + // do something + } + +} diff --git a/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/PhoneNumber.java b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/PhoneNumber.java new file mode 100644 index 0000000..afd5373 --- /dev/null +++ b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/PhoneNumber.java @@ -0,0 +1,22 @@ +package com.example.beanvalidationdemo.validation; + +import javax.validation.Constraint; +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.PARAMETER; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +@Documented +@Constraint(validatedBy = PhoneNumberValidator.class) +@Target({FIELD, PARAMETER}) +@Retention(RUNTIME) +public @interface PhoneNumber { + String message() default "Invalid phone number"; + + Class[] groups() default {}; + + Class[] payload() default {}; +} diff --git a/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/PhoneNumberValidator.java b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/PhoneNumberValidator.java new file mode 100644 index 0000000..85acdcd --- /dev/null +++ b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/PhoneNumberValidator.java @@ -0,0 +1,21 @@ +package com.example.beanvalidationdemo.validation; + +import javax.validation.ConstraintValidator; +import javax.validation.ConstraintValidatorContext; + +public class PhoneNumberValidator implements ConstraintValidator { + + @Override + public boolean isValid(String phoneField, ConstraintValidatorContext context) { + if (phoneField == null) { + // can be null + return true; + } + // 大陆手机号码11位数,匹配格式:前三位固定格式+后8位任意数 + // ^ 匹配输入字符串开始的位置 + // \d 匹配一个或多个数字,其中 \ 要转义,所以是 \\d + // $ 匹配输入字符串结尾的位置 + String regExp = "^[1]((3[0-9])|(4[5-9])|(5[0-3,5-9])|([6][5,6])|(7[0-9])|(8[0-9])|(9[1,8,9]))\\d{8}$"; + return phoneField.matches(regExp); + } +} diff --git a/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/Region.java b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/Region.java new file mode 100644 index 0000000..8b0a204 --- /dev/null +++ b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/Region.java @@ -0,0 +1,26 @@ +package com.example.beanvalidationdemo.validation; + +import javax.validation.Constraint; +import javax.validation.Payload; +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + * @author shuang.kou + */ +@Target({FIELD}) +@Retention(RUNTIME) +@Constraint(validatedBy = RegionValidator.class) +@Documented +public @interface Region { + + String message() default "Region 值不在可选范围内"; + + Class[] groups() default {}; + + Class[] payload() default {}; +} diff --git a/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/RegionValidator.java b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/RegionValidator.java new file mode 100644 index 0000000..9490c5b --- /dev/null +++ b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/RegionValidator.java @@ -0,0 +1,17 @@ +package com.example.beanvalidationdemo.validation; + +import javax.validation.ConstraintValidator; +import javax.validation.ConstraintValidatorContext; +import java.util.HashSet; + +public class RegionValidator implements ConstraintValidator { + + @Override + public boolean isValid(String value, ConstraintValidatorContext context) { + HashSet regions = new HashSet<>(); + regions.add("China"); + regions.add("China-Taiwan"); + regions.add("China-HongKong"); + return regions.contains(value); + } +} diff --git a/source-code/bean-validation-demo/src/main/resources/application.properties b/source-code/bean-validation-demo/src/main/resources/application.properties new file mode 100644 index 0000000..e69de29 diff --git a/source-code/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/PersonControllerTest.java b/source-code/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/PersonControllerTest.java new file mode 100644 index 0000000..4f7e594 --- /dev/null +++ b/source-code/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/PersonControllerTest.java @@ -0,0 +1,83 @@ +package com.example.beanvalidationdemo; + + +import com.example.beanvalidationdemo.entity.PersonRequest; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; + +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; +import java.util.Set; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringBootTest +@AutoConfigureMockMvc +public class PersonControllerTest { + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + + /** + * 验证出现参数不合法的情况抛出异常并且可以正确被捕获 + */ + @Test + public void should_check_person_value() throws Exception { + PersonRequest personRequest = PersonRequest.builder().sex("Man22") + .classId("82938390") + .region("Shanghai") + .phoneNumber("1816313815").build(); + mockMvc.perform(post("/api/persons") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(personRequest))) + .andExpect(MockMvcResultMatchers.jsonPath("sex").value("sex 值不在可选范围")) + .andExpect(MockMvcResultMatchers.jsonPath("name").value("name 不能为空")) + .andExpect(MockMvcResultMatchers.jsonPath("region").value("Region 值不在可选范围内")) + .andExpect(MockMvcResultMatchers.jsonPath("phoneNumber").value("phoneNumber 格式不正确")); + } + + @Test + public void should_check_path_variable() throws Exception { + mockMvc.perform(get("/api/persons/6") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isBadRequest()) + .andExpect(content().string("getPersonByID.id: 超过 id 的范围了")); + } + + @Test + public void should_check_request_param_value2() throws Exception { + mockMvc.perform(put("/api/persons") + .param("name", "snailclimbsnailclimb") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isBadRequest()) + .andExpect(content().string("getPersonByName.name: 超过 name 的范围了")); + } + + /** + * 手动校验对象 + */ + @Test + public void check_person_manually() { + ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); + Validator validator = factory.getValidator(); + PersonRequest personRequest = PersonRequest.builder().sex("Man22") + .classId("82938390").build(); + Set> violations = validator.validate(personRequest); + violations.forEach(constraintViolation -> System.out.println(constraintViolation.getMessage())); + } +} diff --git a/source-code/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/PersonServiceTest.java b/source-code/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/PersonServiceTest.java new file mode 100644 index 0000000..88b5da3 --- /dev/null +++ b/source-code/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/PersonServiceTest.java @@ -0,0 +1,44 @@ +package com.example.beanvalidationdemo; + +import com.example.beanvalidationdemo.entity.Person; +import com.example.beanvalidationdemo.entity.PersonRequest; +import com.example.beanvalidationdemo.service.PersonService; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import javax.validation.ConstraintViolationException; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class PersonServiceTest { + @Autowired + private PersonService service; + + @Test + public void should_throw_exception_when_person_request_is_not_valid() { + try { + PersonRequest personRequest = PersonRequest.builder().sex("Man22") + .classId("82938390").build(); + service.validatePersonRequest(personRequest); + } catch (ConstraintViolationException e) { + e.getConstraintViolations().forEach(constraintViolation -> System.out.println(constraintViolation.getMessage())); + } + } + + @Test(expected = ConstraintViolationException.class) + public void should_check_person_with_groups() { + Person person = new Person(); + person.setGroup("group1"); + service.validatePersonGroupForAdd(person); + } + + @Test(expected = ConstraintViolationException.class) + public void should_check_person_with_groups2() { + Person person = new Person(); + service.validatePersonGroupForDelete(person); + } + +} diff --git a/source-code/hello-world/.gitignore b/source-code/hello-world/.gitignore new file mode 100644 index 0000000..a2a3040 --- /dev/null +++ b/source-code/hello-world/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/source-code/start/hello-world/.mvn/wrapper/MavenWrapperDownloader.java b/source-code/hello-world/.mvn/wrapper/MavenWrapperDownloader.java similarity index 100% rename from source-code/start/hello-world/.mvn/wrapper/MavenWrapperDownloader.java rename to source-code/hello-world/.mvn/wrapper/MavenWrapperDownloader.java diff --git a/source-code/start/hello-world/.mvn/wrapper/maven-wrapper.jar b/source-code/hello-world/.mvn/wrapper/maven-wrapper.jar similarity index 100% rename from source-code/start/hello-world/.mvn/wrapper/maven-wrapper.jar rename to source-code/hello-world/.mvn/wrapper/maven-wrapper.jar diff --git a/source-code/advanced/springboot-oss/.mvn/wrapper/maven-wrapper.properties b/source-code/hello-world/.mvn/wrapper/maven-wrapper.properties similarity index 55% rename from source-code/advanced/springboot-oss/.mvn/wrapper/maven-wrapper.properties rename to source-code/hello-world/.mvn/wrapper/maven-wrapper.properties index 7179346..cd0d451 100644 --- a/source-code/advanced/springboot-oss/.mvn/wrapper/maven-wrapper.properties +++ b/source-code/hello-world/.mvn/wrapper/maven-wrapper.properties @@ -1 +1 @@ -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip diff --git a/source-code/start/hello-world/mvnw b/source-code/hello-world/mvnw similarity index 100% rename from source-code/start/hello-world/mvnw rename to source-code/hello-world/mvnw diff --git a/source-code/advanced/springboot-oss/mvnw.cmd b/source-code/hello-world/mvnw.cmd similarity index 99% rename from source-code/advanced/springboot-oss/mvnw.cmd rename to source-code/hello-world/mvnw.cmd index e5cfb0a..fef5a8f 100644 --- a/source-code/advanced/springboot-oss/mvnw.cmd +++ b/source-code/hello-world/mvnw.cmd @@ -7,7 +7,7 @@ @REM "License"); you may not use this file except in compliance @REM with the License. You may obtain a copy of the License at @REM -@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM https://www.apache.org/licenses/LICENSE-2.0 @REM @REM Unless required by applicable law or agreed to in writing, @REM software distributed under the License is distributed on an diff --git a/source-code/start/hello-world/pom.xml b/source-code/hello-world/pom.xml similarity index 100% rename from source-code/start/hello-world/pom.xml rename to source-code/hello-world/pom.xml diff --git a/source-code/start/hello-world/src/main/java/com/example/helloworld/HelloWorldApplication.java b/source-code/hello-world/src/main/java/com/example/helloworld/HelloWorldApplication.java similarity index 100% rename from source-code/start/hello-world/src/main/java/com/example/helloworld/HelloWorldApplication.java rename to source-code/hello-world/src/main/java/com/example/helloworld/HelloWorldApplication.java diff --git a/source-code/hello-world/src/main/java/com/example/helloworld/controller/UserController.java b/source-code/hello-world/src/main/java/com/example/helloworld/controller/UserController.java new file mode 100644 index 0000000..7fc86a5 --- /dev/null +++ b/source-code/hello-world/src/main/java/com/example/helloworld/controller/UserController.java @@ -0,0 +1,29 @@ +package com.example.helloworld.controller; + +import com.example.helloworld.dto.UserDto; +import com.example.helloworld.entity.User; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.IntStream; + +@RestController +@RequestMapping("users") +public class UserController { + + ArrayList users = new ArrayList() {{ + add(new User(11111L, "Guide哥", "koushuangbwcx@163.com", "123456")); + add(new User(22222L, "李真", "koushuangbwcx@163.com", "123456")); + add(new User(33333L, "帅", "koushuangbwcx@163.com", "123456")); + }}; + + @GetMapping + public ResponseEntity> getUsers() { + + return null; + } +} diff --git a/source-code/hello-world/src/main/java/com/example/helloworld/dto/UserDto.java b/source-code/hello-world/src/main/java/com/example/helloworld/dto/UserDto.java new file mode 100644 index 0000000..2996e18 --- /dev/null +++ b/source-code/hello-world/src/main/java/com/example/helloworld/dto/UserDto.java @@ -0,0 +1,13 @@ +package com.example.helloworld.dto; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Getter +@Setter +@ToString +public class UserDto { + String name; + String email; +} diff --git a/source-code/hello-world/src/main/java/com/example/helloworld/entity/User.java b/source-code/hello-world/src/main/java/com/example/helloworld/entity/User.java new file mode 100644 index 0000000..f9ea15b --- /dev/null +++ b/source-code/hello-world/src/main/java/com/example/helloworld/entity/User.java @@ -0,0 +1,13 @@ +package com.example.helloworld.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class User { + Long id; + String name; + String email; + String password; +} diff --git a/source-code/start/hello-world/src/main/resources/application.properties b/source-code/hello-world/src/main/resources/application.properties similarity index 100% rename from source-code/start/hello-world/src/main/resources/application.properties rename to source-code/hello-world/src/main/resources/application.properties diff --git a/source-code/hello-world/src/test/java/com/example/dto2entity/BeanUtilsTest.java b/source-code/hello-world/src/test/java/com/example/dto2entity/BeanUtilsTest.java new file mode 100644 index 0000000..ef936c0 --- /dev/null +++ b/source-code/hello-world/src/test/java/com/example/dto2entity/BeanUtilsTest.java @@ -0,0 +1,30 @@ +package com.example.dto2entity; + +import com.example.helloworld.entity.User; +import com.example.helloworld.dto.UserDto; +import org.junit.Test; +import org.springframework.beans.BeanUtils; + +import static org.junit.Assert.assertFalse; +import static org.springframework.test.util.AssertionErrors.assertTrue; + +public class BeanUtilsTest { + + @Test + public void should_copy_user_properties_to_userDto() { + User user = new User(123213L, "Guide哥", "koushuangbwcx@163.com", "123456"); + UserDto userDto = new UserDto(); + BeanUtils.copyProperties(user, userDto); + assertTrue("name copied", userDto.getName().equals(user.getName())); + assertTrue("email copied", userDto.getEmail().equals(user.getEmail())); + } + + @Test + public void should_copy_user_properties_to_userDto_but_not_copy_email() { + User user = new User(123213L, "Guide哥", "koushuangbwcx@163.com", "123456"); + UserDto userDto = new UserDto(); + BeanUtils.copyProperties(user, userDto, "email"); + assertTrue("name copied", userDto.getName().equals(user.getName())); + assertTrue("email not copied", userDto.getEmail() == null); + } +} diff --git a/source-code/start/hello-world/src/test/java/com/example/helloworld/HelloWorldApplicationTests.java b/source-code/hello-world/src/test/java/com/example/helloworld/HelloWorldApplicationTests.java similarity index 100% rename from source-code/start/hello-world/src/test/java/com/example/helloworld/HelloWorldApplicationTests.java rename to source-code/hello-world/src/test/java/com/example/helloworld/HelloWorldApplicationTests.java diff --git a/source-code/springboot-data-desensitization/.gitignore b/source-code/springboot-data-desensitization/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/source-code/springboot-data-desensitization/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/source-code/springboot-data-desensitization/.mvn/wrapper/MavenWrapperDownloader.java b/source-code/springboot-data-desensitization/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..a45eb6b --- /dev/null +++ b/source-code/springboot-data-desensitization/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,118 @@ +/* + * Copyright 2007-present 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 + * + * https://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. + */ + +import java.net.*; +import java.io.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader { + + private static final String WRAPPER_VERSION = "0.5.6"; + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if (mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if (mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if (!outputFile.getParentFile().exists()) { + if (!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/source-code/springboot-data-desensitization/.mvn/wrapper/maven-wrapper.jar b/source-code/springboot-data-desensitization/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..2cc7d4a Binary files /dev/null and b/source-code/springboot-data-desensitization/.mvn/wrapper/maven-wrapper.jar differ diff --git a/source-code/springboot-data-desensitization/.mvn/wrapper/maven-wrapper.properties b/source-code/springboot-data-desensitization/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..ffdc10e --- /dev/null +++ b/source-code/springboot-data-desensitization/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.1/apache-maven-3.8.1-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/source-code/springboot-data-desensitization/mvnw b/source-code/springboot-data-desensitization/mvnw new file mode 100755 index 0000000..3c8a553 --- /dev/null +++ b/source-code/springboot-data-desensitization/mvnw @@ -0,0 +1,322 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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 +# +# https://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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ]; then + + if [ -f /etc/mavenrc ]; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ]; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false +darwin=false +mingw=false +case "$(uname)" in +CYGWIN*) cygwin=true ;; +MINGW*) mingw=true ;; +Darwin*) + darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="$(/usr/libexec/java_home)" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ]; then + if [ -r /etc/gentoo-release ]; then + JAVA_HOME=$(java-config --jre-home) + fi +fi + +if [ -z "$M2_HOME" ]; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ]; do + ls=$(ls -ld "$PRG") + link=$(expr "$ls" : '.*-> \(.*\)$') + if expr "$link" : '/.*' >/dev/null; then + PRG="$link" + else + PRG="$(dirname "$PRG")/$link" + fi + done + + saveddir=$(pwd) + + M2_HOME=$(dirname "$PRG")/.. + + # make it fully qualified + M2_HOME=$(cd "$M2_HOME" && pwd) + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=$(cygpath --unix "$M2_HOME") + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --unix "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --unix "$CLASSPATH") +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw; then + [ -n "$M2_HOME" ] && + M2_HOME="$( ( + cd "$M2_HOME" + pwd + ))" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="$( ( + cd "$JAVA_HOME" + pwd + ))" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="$(which javac)" + if [ -n "$javaExecutable" ] && ! [ "$(expr \"$javaExecutable\" : '\([^ ]*\)')" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=$(which readlink) + if [ ! $(expr "$readLink" : '\([^ ]*\)') = "no" ]; then + if $darwin; then + javaHome="$(dirname \"$javaExecutable\")" + javaExecutable="$(cd \"$javaHome\" && pwd -P)/javac" + else + javaExecutable="$(readlink -f \"$javaExecutable\")" + fi + javaHome="$(dirname \"$javaExecutable\")" + javaHome=$(expr "$javaHome" : '\(.*\)/bin') + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ]; then + if [ -n "$JAVA_HOME" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="$(which java)" + fi +fi + +if [ ! -x "$JAVACMD" ]; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ]; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ]; then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ]; do + if [ -d "$wdir"/.mvn ]; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=$( + cd "$wdir/.." + pwd + ) + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' <"$1")" + fi +} + +BASE_DIR=$(find_maven_basedir "$(pwd)") +if [ -z "$BASE_DIR" ]; then + exit 1 +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in wrapperUrl) + jarUrl="$value" + break + ;; + esac + done <"$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") + fi + + if command -v wget >/dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl >/dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=$(cygpath --path --windows "$javaClass") + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=$(cygpath --path --windows "$M2_HOME") + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --windows "$CLASSPATH") + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/source-code/springboot-data-desensitization/mvnw.cmd b/source-code/springboot-data-desensitization/mvnw.cmd new file mode 100644 index 0000000..c8d4337 --- /dev/null +++ b/source-code/springboot-data-desensitization/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/source-code/springboot-data-desensitization/pom.xml b/source-code/springboot-data-desensitization/pom.xml new file mode 100644 index 0000000..baa65b9 --- /dev/null +++ b/source-code/springboot-data-desensitization/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.4.5 + + + com.github.javaguide + springboot-data-desensitization + 0.0.1-SNAPSHOT + springboot-data-desensitization + Demo project for Spring Boot + + 1.8 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/SpringbootDataDesensitizationApplication.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/SpringbootDataDesensitizationApplication.java new file mode 100644 index 0000000..8fd6367 --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/SpringbootDataDesensitizationApplication.java @@ -0,0 +1,13 @@ +package com.github.springbootdatadesensitization; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringbootDataDesensitizationApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringbootDataDesensitizationApplication.class, args); + } + +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/JsonDesensitizationSerializer.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/JsonDesensitizationSerializer.java new file mode 100644 index 0000000..8ea4523 --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/JsonDesensitizationSerializer.java @@ -0,0 +1,59 @@ +package com.github.springbootdatadesensitization.desensitize; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.BeanProperty; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.ContextualSerializer; +import com.github.springbootdatadesensitization.desensitize.annotation.JsonDesensitization; +import com.github.springbootdatadesensitization.desensitize.desensitizer.Desensitizer; +import com.github.springbootdatadesensitization.desensitize.desensitizer.DesensitizerFactory; +import com.github.springbootdatadesensitization.desensitize.enums.DesensitizationType; + +import java.io.IOException; +import java.util.Objects; + +/** + * 微信搜 JavaGuide 回复"面试突击"即可免费领取个人原创的 Java 面试手册 + * + * @author Guide哥 + * @date 2021/05/10 20:26 + **/ +public class JsonDesensitizationSerializer extends JsonSerializer implements ContextualSerializer { + + + private DesensitizationType type; + + public JsonDesensitizationSerializer() { + } + + public JsonDesensitizationSerializer(DesensitizationType type) { + this.type = type; + } + + @Override + public JsonSerializer createContextual(SerializerProvider serializerProvider, BeanProperty property) throws JsonMappingException { + if (property != null) { + if (Objects.equals(property.getType().getRawClass(), String.class)) { + JsonDesensitization jsonDesensitization = property.getAnnotation(JsonDesensitization.class); + if (jsonDesensitization == null) { + jsonDesensitization = property.getContextAnnotation(JsonDesensitization.class); + } + if (jsonDesensitization != null) { + return new JsonDesensitizationSerializer(jsonDesensitization.value()); + } + } + return serializerProvider.findValueSerializer(property.getType(), property); + } else { + return serializerProvider.findNullValueSerializer(null); + } + } + + @Override + public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { + Desensitizer desensitizer = DesensitizerFactory.get(this.type); + System.out.println(s); + jsonGenerator.writeString(desensitizer.desensitize(s)); + } +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/annotation/JsonDesensitization.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/annotation/JsonDesensitization.java new file mode 100644 index 0000000..d7fbf5d --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/annotation/JsonDesensitization.java @@ -0,0 +1,25 @@ +package com.github.springbootdatadesensitization.desensitize.annotation; + +import com.fasterxml.jackson.annotation.JacksonAnnotationsInside; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.github.springbootdatadesensitization.desensitize.JsonDesensitizationSerializer; +import com.github.springbootdatadesensitization.desensitize.enums.DesensitizationType; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * 微信搜 JavaGuide 回复"面试突击"即可免费领取个人原创的 Java 面试手册 + * + * @author Guide哥 + * @date 2021/05/10 20:36 + **/ +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.FIELD}) +@JacksonAnnotationsInside +@JsonSerialize(using = JsonDesensitizationSerializer.class) +public @interface JsonDesensitization { + DesensitizationType value(); +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/AbstractDesensitizer.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/AbstractDesensitizer.java new file mode 100644 index 0000000..32bbcd1 --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/AbstractDesensitizer.java @@ -0,0 +1,71 @@ +package com.github.springbootdatadesensitization.desensitize.desensitizer; + +import com.github.springbootdatadesensitization.desensitize.exception.DesensitizationException; + +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * 微信搜 JavaGuide 回复"面试突击"即可免费领取个人原创的 Java 面试手册 + * 数据脱敏所使用的的策略 + * + * @author Guide哥 + * @date 2021/05/10 20:15 + **/ +public abstract class AbstractDesensitizer implements Desensitizer { + + /** + * 左边的明文长度 + */ + private final Integer leftPlainTextLen; + /** + * 右边的明文长度 + */ + private Integer rightPlainTextLen; + + public AbstractDesensitizer(Integer leftPlainTextLen) { + this.leftPlainTextLen = leftPlainTextLen; + } + + public AbstractDesensitizer(Integer leftPlainTextLen, Integer rightPlainTextLen) { + this.leftPlainTextLen = leftPlainTextLen; + this.rightPlainTextLen = rightPlainTextLen; + } + + @Override + public String desensitize(String origin) { + if (origin == null || origin.isEmpty()) { + return ""; + } + // 处理邮箱的特殊情况 + if (isEmail(origin)) { + int index = origin.indexOf("@"); + rightPlainTextLen = origin.length() - index; + } + if (leftPlainTextLen == 0 && rightPlainTextLen == 0) { + return getEncryptedStr(6); + } + if (leftPlainTextLen < 0 || rightPlainTextLen < 0) { + throw new DesensitizationException("leftPlainTextLen and rightPlainTextLen must > 0"); + } + if (leftPlainTextLen + rightPlainTextLen >= origin.length()) { + throw new DesensitizationException("leftPlainTextLen+rightPlainTextLen should <= the length of origin"); + } + StringBuilder result = new StringBuilder(); + result.append(origin, 0, leftPlainTextLen); + result.append(getEncryptedStr(origin.length() - leftPlainTextLen - rightPlainTextLen)); + result.append(origin, origin.length() - rightPlainTextLen, origin.length()); + return result.toString(); + } + + private Boolean isEmail(String s) { + String emailRegex = "^[\\w-.]+@([\\w-]+\\.)+[\\w-]{2,4}$"; + Pattern emailPattern = Pattern.compile(emailRegex); + return emailPattern.matcher(s).matches(); + } + + private String getEncryptedStr(int length) { + return Stream.generate(() -> "*").limit(length).collect(Collectors.joining()); + } +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/Desensitizer.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/Desensitizer.java new file mode 100644 index 0000000..721009f --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/Desensitizer.java @@ -0,0 +1,11 @@ +package com.github.springbootdatadesensitization.desensitize.desensitizer; + +/** + * 微信搜 JavaGuide 回复"面试突击"即可免费领取个人原创的 Java 面试手册 + * + * @author Guide哥 + * @date 2021/05/10 20:36 + **/ +public interface Desensitizer { + String desensitize(String origin); +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/DesensitizerFactory.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/DesensitizerFactory.java new file mode 100644 index 0000000..f7d6fb3 --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/DesensitizerFactory.java @@ -0,0 +1,45 @@ +package com.github.springbootdatadesensitization.desensitize.desensitizer; + +import com.github.springbootdatadesensitization.desensitize.desensitizer.impl.AddressDesensitizer; +import com.github.springbootdatadesensitization.desensitize.desensitizer.impl.BankCardDesensitizer; +import com.github.springbootdatadesensitization.desensitize.desensitizer.impl.BirthdayDesensitizer; +import com.github.springbootdatadesensitization.desensitize.desensitizer.impl.DefaultDesensitizer; +import com.github.springbootdatadesensitization.desensitize.desensitizer.impl.EmailDesensitizer; +import com.github.springbootdatadesensitization.desensitize.desensitizer.impl.IdCardDesensitizer; +import com.github.springbootdatadesensitization.desensitize.desensitizer.impl.LandlineDesensitizer; +import com.github.springbootdatadesensitization.desensitize.desensitizer.impl.MobileDesensitizer; +import com.github.springbootdatadesensitization.desensitize.desensitizer.impl.PasswordDesensitizer; +import com.github.springbootdatadesensitization.desensitize.enums.DesensitizationType; + +import java.util.HashMap; +import java.util.Map; + +/** + * 微信搜 JavaGuide 回复"面试突击"即可免费领取个人原创的 Java 面试手册 + * + * @author Guide哥 + * @date 2021/05/10 23:18 + **/ +public class DesensitizerFactory { + public static final Map desensitizers = new HashMap<>(); + + static { + desensitizers.put(DesensitizationType.ADDRESS, new AddressDesensitizer()); + desensitizers.put(DesensitizationType.BANK_CARD, new BankCardDesensitizer()); + desensitizers.put(DesensitizationType.EMAIL, new EmailDesensitizer()); + desensitizers.put(DesensitizationType.ID_CARD, new IdCardDesensitizer()); + desensitizers.put(DesensitizationType.LANDLINE, new LandlineDesensitizer()); + desensitizers.put(DesensitizationType.MOBILE, new MobileDesensitizer()); + desensitizers.put(DesensitizationType.PASSWORD, new PasswordDesensitizer()); + desensitizers.put(DesensitizationType.DEFAULT, new DefaultDesensitizer()); + desensitizers.put(DesensitizationType.BIRTHDAY, new BirthdayDesensitizer()); + } + + public static Desensitizer get(DesensitizationType desensitizationType) { + Desensitizer desensitizer = desensitizers.get(desensitizationType); + if (desensitizer == null) { + return desensitizers.get(DesensitizationType.DEFAULT); + } + return desensitizer; + } +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/AddressDesensitizer.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/AddressDesensitizer.java new file mode 100644 index 0000000..cf9e429 --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/AddressDesensitizer.java @@ -0,0 +1,15 @@ +package com.github.springbootdatadesensitization.desensitize.desensitizer.impl; + +import com.github.springbootdatadesensitization.desensitize.desensitizer.AbstractDesensitizer; + +/** + * 地址脱敏 + * + * @author Guide哥 + * @date 2021/05/10 20:15 + **/ +public class AddressDesensitizer extends AbstractDesensitizer { + public AddressDesensitizer() { + super(3, 3); + } +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/BankCardDesensitizer.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/BankCardDesensitizer.java new file mode 100644 index 0000000..b9620f9 --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/BankCardDesensitizer.java @@ -0,0 +1,15 @@ +package com.github.springbootdatadesensitization.desensitize.desensitizer.impl; + +import com.github.springbootdatadesensitization.desensitize.desensitizer.AbstractDesensitizer; + +/** + * 银行卡号脱敏 + * + * @author Guide哥 + * @date 2021/05/10 20:28 + **/ +public class BankCardDesensitizer extends AbstractDesensitizer { + public BankCardDesensitizer() { + super(3, 3); + } +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/BirthdayDesensitizer.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/BirthdayDesensitizer.java new file mode 100644 index 0000000..1f8d300 --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/BirthdayDesensitizer.java @@ -0,0 +1,15 @@ +package com.github.springbootdatadesensitization.desensitize.desensitizer.impl; + +import com.github.springbootdatadesensitization.desensitize.desensitizer.AbstractDesensitizer; + +/** + * 密码脱敏 + * + * @author Guide哥 + * @date 2021/05/10 20:28 + **/ +public class BirthdayDesensitizer extends AbstractDesensitizer { + public BirthdayDesensitizer() { + super(4, 0); + } +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/DefaultDesensitizer.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/DefaultDesensitizer.java new file mode 100644 index 0000000..9a833de --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/DefaultDesensitizer.java @@ -0,0 +1,15 @@ +package com.github.springbootdatadesensitization.desensitize.desensitizer.impl; + +import com.github.springbootdatadesensitization.desensitize.desensitizer.AbstractDesensitizer; + +/** + * 密码脱敏 + * + * @author Guide哥 + * @date 2021/05/10 20:28 + **/ +public class DefaultDesensitizer extends AbstractDesensitizer { + public DefaultDesensitizer() { + super(0, 0); + } +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/EmailDesensitizer.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/EmailDesensitizer.java new file mode 100644 index 0000000..3ea0fb4 --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/EmailDesensitizer.java @@ -0,0 +1,15 @@ +package com.github.springbootdatadesensitization.desensitize.desensitizer.impl; + +import com.github.springbootdatadesensitization.desensitize.desensitizer.AbstractDesensitizer; + +/** + * 邮箱脱敏 + * + * @author Guide哥 + * @date 2021/05/10 20:28 + **/ +public class EmailDesensitizer extends AbstractDesensitizer { + public EmailDesensitizer() { + super(0); + } +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/IdCardDesensitizer.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/IdCardDesensitizer.java new file mode 100644 index 0000000..d979913 --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/IdCardDesensitizer.java @@ -0,0 +1,15 @@ +package com.github.springbootdatadesensitization.desensitize.desensitizer.impl; + +import com.github.springbootdatadesensitization.desensitize.desensitizer.AbstractDesensitizer; + +/** + * 身份证号脱敏 + * + * @author Guide哥 + * @date 2021/05/10 20:28 + **/ +public class IdCardDesensitizer extends AbstractDesensitizer { + public IdCardDesensitizer() { + super(3, 4); + } +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/LandlineDesensitizer.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/LandlineDesensitizer.java new file mode 100644 index 0000000..5bec86e --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/LandlineDesensitizer.java @@ -0,0 +1,15 @@ +package com.github.springbootdatadesensitization.desensitize.desensitizer.impl; + +import com.github.springbootdatadesensitization.desensitize.desensitizer.AbstractDesensitizer; + +/** + * 座机号脱敏 + * + * @author Guide哥 + * @date 2021/05/10 20:28 + **/ +public class LandlineDesensitizer extends AbstractDesensitizer { + public LandlineDesensitizer() { + super(2, 2); + } +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/MobileDesensitizer.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/MobileDesensitizer.java new file mode 100644 index 0000000..2482a9c --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/MobileDesensitizer.java @@ -0,0 +1,15 @@ +package com.github.springbootdatadesensitization.desensitize.desensitizer.impl; + +import com.github.springbootdatadesensitization.desensitize.desensitizer.AbstractDesensitizer; + +/** + * 手机号脱敏 + * + * @author Guide哥 + * @date 2021/05/10 20:28 + **/ +public class MobileDesensitizer extends AbstractDesensitizer { + public MobileDesensitizer() { + super(3, 4); + } +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/PasswordDesensitizer.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/PasswordDesensitizer.java new file mode 100644 index 0000000..62639ff --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/PasswordDesensitizer.java @@ -0,0 +1,15 @@ +package com.github.springbootdatadesensitization.desensitize.desensitizer.impl; + +import com.github.springbootdatadesensitization.desensitize.desensitizer.AbstractDesensitizer; + +/** + * 密码脱敏 + * + * @author Guide哥 + * @date 2021/05/10 20:28 + **/ +public class PasswordDesensitizer extends AbstractDesensitizer { + public PasswordDesensitizer() { + super(0, 0); + } +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/enums/DesensitizationType.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/enums/DesensitizationType.java new file mode 100644 index 0000000..502cf70 --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/enums/DesensitizationType.java @@ -0,0 +1,46 @@ +package com.github.springbootdatadesensitization.desensitize.enums; + +/** + * 微信搜 JavaGuide 回复"面试突击"即可免费领取个人原创的 Java 面试手册 + * + * @author Guide哥 + * @date 2021/05/10 20:36 + **/ +public enum DesensitizationType { + + DEFAULT, + /** + * 座机号 + */ + LANDLINE, + /** + * 手机 + */ + MOBILE, + /** + * 邮箱 + */ + EMAIL, + + /** + * 生日🎂 + */ + BIRTHDAY, + /** + * 密码 + */ + PASSWORD, + /** + * 身份证 + */ + ID_CARD, + /** + * 银行卡 + */ + BANK_CARD, + /** + * 地址 + */ + ADDRESS, + +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/exception/DesensitizationException.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/exception/DesensitizationException.java new file mode 100644 index 0000000..50a70b4 --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/exception/DesensitizationException.java @@ -0,0 +1,14 @@ +package com.github.springbootdatadesensitization.desensitize.exception; + +import lombok.Getter; + +/** + * @author shuang.kou + * @date 2017/12/19 14:25 + */ +@Getter +public class DesensitizationException extends RuntimeException { + public DesensitizationException(String message) { + super(message); + } +} \ No newline at end of file diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/entity/User.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/entity/User.java new file mode 100644 index 0000000..6dcbda5 --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/entity/User.java @@ -0,0 +1,35 @@ +package com.github.springbootdatadesensitization.entity; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.github.springbootdatadesensitization.desensitize.annotation.JsonDesensitization; +import com.github.springbootdatadesensitization.desensitize.enums.DesensitizationType; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Date; + + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class User { + private Long id; + @JsonDesensitization(DesensitizationType.EMAIL) + private String email; + + @JsonDesensitization(DesensitizationType.ID_CARD) + private String idCard; + + @JsonDesensitization(DesensitizationType.PASSWORD) + private String password; + + @JsonDesensitization(DesensitizationType.MOBILE) + private String phone; + + @JsonFormat(pattern = "yyyy-MM-dd", locale = "zh", timezone = "GMT+8") + @JsonDesensitization(DesensitizationType.BIRTHDAY) + private Date birthday; +} diff --git a/source-code/advanced/springboot-oss/src/main/resources/application.properties b/source-code/springboot-data-desensitization/src/main/resources/application.properties similarity index 100% rename from source-code/advanced/springboot-oss/src/main/resources/application.properties rename to source-code/springboot-data-desensitization/src/main/resources/application.properties diff --git a/source-code/springboot-data-desensitization/src/test/java/com/github/springbootdatadesensitization/desensitize/JsonDesensitizationSerializerTest.java b/source-code/springboot-data-desensitization/src/test/java/com/github/springbootdatadesensitization/desensitize/JsonDesensitizationSerializerTest.java new file mode 100644 index 0000000..3debd98 --- /dev/null +++ b/source-code/springboot-data-desensitization/src/test/java/com/github/springbootdatadesensitization/desensitize/JsonDesensitizationSerializerTest.java @@ -0,0 +1,33 @@ +package com.github.springbootdatadesensitization.desensitize; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.springbootdatadesensitization.entity.User; +import org.junit.jupiter.api.Test; + +import java.util.Date; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class JsonDesensitizationSerializerTest { + + @Test + void should_desensitize_entity() throws JsonProcessingException { + ObjectMapper objectMapper = new ObjectMapper(); + User user = User.builder() + .birthday(new Date()) + .phone("1816313814") + .email("136148@qq.com") + .password("12dsfs@dfsdg431") + .idCard("463827319960397495") + .build(); + String s = objectMapper.writeValueAsString(user); + System.out.println(s); + User desensitizedUser = objectMapper.readValue(s, User.class); + assertEquals("******@qq.com", desensitizedUser.getEmail()); + assertEquals("463***********7495", desensitizedUser.getIdCard()); + assertEquals("******", desensitizedUser.getPassword()); + assertEquals("181***3814", desensitizedUser.getPhone()); + + } +} \ No newline at end of file diff --git a/source-code/start/hello-world/src/main/java/com/example/helloworld/controller/BookController.java b/source-code/start/hello-world/src/main/java/com/example/helloworld/controller/BookController.java deleted file mode 100644 index 63e1dfa..0000000 --- a/source-code/start/hello-world/src/main/java/com/example/helloworld/controller/BookController.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.example.helloworld.controller; - -import com.example.helloworld.entity.Book; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -@RestController -@RequestMapping(value = "/api") -public class BookController { - - private List books = new ArrayList<>(); - - @PostMapping(value = "/book") - public ResponseEntity> addBook(@RequestBody Book book) { - books.add(book); - return ResponseEntity.ok(books); - } - - @DeleteMapping("/book/{id}") - public ResponseEntity deleteBookById(@PathVariable("id") int id) { - books.remove(id); - return ResponseEntity.ok(books); - } - - @GetMapping("/book") - public ResponseEntity getBookByName(@RequestParam(value = "name") String name) { - List results = books.stream().filter(book -> book.getName().equals(name)).collect(Collectors.toList()); - return ResponseEntity.ok(results); - } - - @GetMapping("/books") - public ResponseEntity getAllBook() { - return ResponseEntity.ok(books); - } -} diff --git a/source-code/start/hello-world/src/main/java/com/example/helloworld/entity/Book.java b/source-code/start/hello-world/src/main/java/com/example/helloworld/entity/Book.java deleted file mode 100644 index f4676c2..0000000 --- a/source-code/start/hello-world/src/main/java/com/example/helloworld/entity/Book.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.example.helloworld.entity; - - -import lombok.Data; - -/** - * @author shuang.kou - */ -@Data -public class Book { - private String name; - private String description; -} diff --git a/springboot-schedule-task/.idea/workspace.xml b/springboot-schedule-task/.idea/workspace.xml deleted file mode 100644 index 7120d02..0000000 --- a/springboot-schedule-task/.idea/workspace.xml +++ /dev/null @@ -1,118 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1573625912874 - - - - - - - - - \ No newline at end of file