diff --git "a/#### wujun\344\270\252\344\272\272\345\274\200\345\217\221\344\275\234\345\223\201\351\233\206\357\274\210\346\214\201\347\273\255\346\233\264\346\226\260\357\274\211###.md" "b/#### wujun\344\270\252\344\272\272\345\274\200\345\217\221\344\275\234\345\223\201\351\233\206\357\274\210\346\214\201\347\273\255\346\233\264\346\226\260\357\274\211###.md" deleted file mode 100644 index d04c04742a..0000000000 --- "a/#### wujun\344\270\252\344\272\272\345\274\200\345\217\221\344\275\234\345\223\201\351\233\206\357\274\210\346\214\201\347\273\255\346\233\264\346\226\260\357\274\211###.md" +++ /dev/null @@ -1,838 +0,0 @@ -## [俊哥个人技术栈代码库(持续更新)](https://github.com/wujun728) --------------------------------------------------------------------------------------------------------------- - -#### 产品篇:[产品及解决方案(重点)][jun_product_center,jun_website,wujun728.github.io] - -> 企业信息化系统: - -【企业TPG门户系统】[仿中软国际TPG门户系统](https://github.com/wujun728/jun_product/jun_portal/)
-【企业财经服务系统】[产品功能说明](https://github.com/wujun728/jun_product/tree/master/jun_finance)
-【企业HR服务系统】[产品功能说明](https://github.com/wujun728/jun_product/jun_hr)
-【企业项目管理系统】[产品功能说明](https://github.com/wujun728/jun_product/jun_project)
-【企业OA系统】[产品功能说明](https://github.com/wujun728/jun_product/jun_oa)
-【企业CRM系统】[产品功能说明](https://github.com/wujun728/jun_product/jun_crm)
-【企业ERP系统】[产品功能说明](https://github.com/wujun728/jun_product/jun_erp)
-【企业信息管理系统】[产品功能说明](https://github.com/wujun728/jun_product/jun_mis)
-【Blog管理系统】[产品功能说明](https://github.com/wujun728/jun_product/jun_blog)
-【俊哥的个人简历】[产品功能说明](https://github.com/wujun728/jun_product/jun_resume)
-【企业官网门户】[产品功能说明,企业网站产品,网站开发](https://github.com/wujun728/jun_website/jun_official_website)
-【企业CMS系统】[产品功能说明](https://github.com/wujun728/jun_website/jun_cms)
-【WordPress】[基于WordPress的CMS管理系统](https://github.com/wujun728/jun_website/jun_wordpress)
- -#### 移动篇:产品及解决方案(重点) [jun_android,jun_app,jun_weixin] - -> APP开发框架 jun_app, APP开发,Android开发,Vue+uniapp+Nodejs+Bigdata: - -【Android程序开发】[产品功能说明](https://github.com/wujun728/jun_android)
-【H5混合App程序开发】[产品功能说明](https://github.com/wujun728/jun_app)
- -> 微信开发框架, 微信开发 [jun_weixin] - -【微信小程序】[产品功能说明](https://github.com/wujun728/jun_weixin/weixin_miniprogram)
-【微信小程序管理系统】[产品功能说明](https://github.com/wujun728/jun_weixin/weixin_manager)
-【微信公众号】[产品功能说明](https://github.com/wujun728/jun_weixin//weixin_product)
-【微信公众号管理系统】[产品功能说明](https://github.com/wujun728/jun_weixin/weixin_manager)
-【微信工具系统-爬虫-代码生成器】[产品功能说明](https://github.com/wujun728/jun_weixin/weixin_crawler)
-【微信推送更新订阅管理系统】[产品功能说明](https://github.com/wujun728/jun_weixin/weixin_push)
- --------------------------------------------------------------------------------------------------------------- -#### 大数据篇:大数据场景,大数据开发,Hadoop、Spark、Strom开发 [jun_bigdata,jun_linux] - -【Hadoop大数据】[Spring连接Hadoop实现CRUD](https://github.com/wujun728/jun_bigdata/Spring-mongoDB)
-【Spark大数据】[Spring连接Spark实现CRUD](https://github.com/wujun728/jun_bigdata/Spring-mongoDB)
-【MongoDB数据库】[Spring连接mongoDB数据库实现增删改查](https://github.com/wujun728/jun_bigdata/Spring-mongoDB)
-【Oracle数据库】[实现Oracle数据库的CRUD](https://github.com/wujun728/jun_bigdata/Spring-redis)
-【MySQL数据库】[实现Mysql数据库的主从复制、读写分离、分表分库、负载均衡和高可用](https://github.com/wujun728/jun_bigdata/Spring-redis)
-【H2数据库】[Spring连接H2数据库实现CRUD](https://github.com/wujun728/jun_bigdata/Spring-redis)
-【SQLite数据库】[Spring连接SQLite实现CRUD](https://github.com/wujun728/jun_bigdata/Spring-redis)
-【Neo4j图数据库】[Spring连接图存数据库Neo4j实现增删改查](https://github.com/wujun728/jun_bigdata/Spring-neo4j)
-【ETL数据转换Kettle】[使用ETL工具Kettle的实例](https://github.com/wujun728/jun_bigdata/Kettle-demo)
-【Zeppelin数据分析】[使用数据仓库进行OLAP数据分析(Mysql+Kettle+Zeppelin)](https://github.com/wujun728/jun_bigdata)
- --------------------------------------------------------------------------------------------------------------- -#### 微服务篇:基于Spring系微服务[jun_springcloud,jun_springboot] - -【微服务快速开发平台SpringCoud】[产品功能说明](https://github.com/wujun728/jun_cloud)
-【微服务快速开发平台SpringBoot】[产品功能说明](https://github.com/wujun728/jun_boot)
-【SpringBoot微服务】[基于SpringBoot实现各种服务应用](https://github.com/wujun728/jun_cloud)
-【SpringCloud微服务Netflex】[基于SpringCloud2.1的微服务开发脚手架,整合了oauth2、nacos、gateway等](https://github.com/zhoutaoo/SpringCloud)
-【SpringCloud微服务2020】[基于SpringCloud2020最新版构建微服务框架](https://github.com/wujun728/jun_cloud)
-【SpringCloudAlibaba微服务】[基于SpringCloudAlibaba提供微服务开发的一站式解决方案](https://github.com/wujun728/jun_cloud)
-【ApacheDubbo微服务】[基于Dubbo实现高性能、轻量级的Java微服务框架](https://github.com/wujun728/jun_cloud)
-【分布式session】[Spring框架的session模块实现集中式session管理 ](https://github.com/wujun728/jun_cloud)
-【分布式文件】[使用FastDFS搭建分布式文件系统(高可用、负载均衡)](https://github.com/wujun728/jun_cloud/Spring-fastdfs)
-【分布式事务】[基于可靠消息最终一致性实现分布式事务(activeMQ),使用TCC框架实现分布式事务]
-【高并发事务】[高并发,数据库锁机制和事务隔离级别的实现](https://github.com/wujun728/jun_cloud)
-【分布式锁】[高并发:使用redis实现分布式锁,使用zookeeper实现分布式锁](https://github.com/wujun728/jun_cloud)
-【线程池&异步现场】[高并发:Java多线程编程实例 ](https://github.com/wujun728/jun_cloud)
-【高性能NIO】[高并发:使用netty实现高性能NIO通信]
-【dubbo RPC服务】[Spring boot整合Apache dubbo v2.7实现分布式服务治理(SOA架构)]
-【Spring Cloud微服务】[使用Spring Cloud实现微服务架构(MSA架构)]
-【Redis&Redis Cluster】[基于Redis集群实现分布式缓存](https://github.com/wujun728/jun_cloud/Spring-redis)
-【分库分表Mycat】[实现Mysql数据库的主从复制、读写分离、分表分库、负载均衡和高可用](https://github.com/wujun728/jun_cloud/Spring-redis)
- -> Linux环境部署&架构&分布式&高并发,Linux环境部署、各种中间件部署 [jun_linux] - -【Gitlib&SVN服务&搭建】[Git指南和分支管理策略 - -吴俊: -【Gitlib&SVN服务&搭建】[Git指南和分支管理策略](https://github.com/wujun728/jun_linux)
-【Nginx集群】[搭建高可用nginx集群和Tomcat负载均衡](https://github.com/wujun728/jun_linux)
-【zookeeper注册中心】[产品功能说明](https://github.com/wujun728/jun_linux)
-【jenkins自动化部署】[使用jenkins+git+maven搭建持续集成环境自动化部署分布式服务]
-【Docker微服务自动化】[使用docker+jenkins+gitlab+spring cloud实现微服务的编排、持续集成和动态扩容]
-【kubernetes服务编排】[基于Kubernetes实现服务编排、自动部署,扩展和管理容器化]
- --------------------------------------------------------------------------------------------------------------- - -#### 基础篇:企业级开发组件(开发组件、代码生成、前端组件) [jun_java_plugin,jun_ssm,jun_frontend_ui] - -> Java基础系开发组件jun_plugin 常用开发组件,调整,新增并优化项目组件: - -【Java基础】[文件上传下载,邮件、Echart报表、二维码,开发工具](https://github.com/wujun728/jun_plugin/jun_redis)
-【设计模式】[23种设计模式及常见数据结构与算法](https://github.com/wujun728/jun_plugin/SSM)
- -> Spring系开发框架组件 Spring常用开发组件,万能粘合剂,企业级J2EE实际标准平台 - -【SSH框架】[Struts2,Hibernate,Spring三大框架](https://github.com/wujun728/jun_spring_plugin/S2SH)
-【SSM框架】 [SpringMVC,Mybatis,Spring三大框架](https://github.com/wujun728/jun_spring_plugin/SSM)
-【SSH框架2】 [Spring,SpringMVC和Hibernate的整合实现增删改查](https://github.com/wujun728/jun_spring_plugin/SSH)
-【SSM微服务】[使用Spring boot整合mybatis,rabbitmq,redis,mongodb实现增删改查](https://github.com/wujun728/jun_spring_plugin)
-【Activiti工作流】 [Spring平台整合activiti工作流引擎实现OA开发](https://github.com/wujun728/jun_spring_plugin/Spring-activiti)
-【WebService服务】 [Spring发布与调用REST风格的WebService](https://github.com/wujun728/jun_spring_plugin/Spring-REST)
-【Shiro权限控制】 [Spring整合Apache Shiro框架,实现用户管理和权限控制](https://github.com/wujun728/jun_spring_plugin/Spring-shiro)
-【Spring security权限控制】 [使用Spring security做权限控制](https://github.com/wujun728/jun_spring_plugin/spring-security-demo)
-【Quartz定时JOB】[SpringTask 使用Spring security做权限控制](https://github.com/wujun728/jun_spring_plugin/spring-security-demo)
-【Lucence搜索】[SpringTask 使用Spring security做权限控制](https://github.com/wujun728/jun_spring_plugin/spring-security-demo)
-【ActiveMQ消息队列】[Spring平台整合消息队列ActiveMQ实现发布订阅、生产者消费者模型(JMS)](https://github.com/wujun728/jun_spring_plugin/Spring-activeMQ)
-【RabbitMQ消息队列】[Spring整合消息队列RabbitMQ实现四种消息模式(AMQP)](https://github.com/wujun728/jun_spring_plugin/Spring-rabbitMQ)
-【Websocket协议】[Spring整合websocket实现即时通讯](https://github.com/wujun728/jun_spring_plugin/Spring-websocket)
-【Elastic search全文检索】[Spring整合Elastic search实现全文检索](https://github.com/wujun728/jun_spring_plugin/Spring-elastic_search)
-【单点登录】[Spring整合CAS框架&JWT实现单点登录](https://github.com/wujun728/jun_spring_plugin/Spring-cas-sso)
- -Java基础系开发组件,代码生成器&开发模板,基于freemarker及MetaData&SQL解析的代码生成器 -【Java代码生成模块】[数据库表代码生成、页面代码生成](https://github.com/wujun728/jun_code_generator/jun_code_helper)
-【Mybatis代码生成模块】[Mybatis代码生成](https://github.com/wujun728/jun_code_generator)
-【MybatisPlus代码生成模块】[Mybatis-Plus代码生成](https://github.com/wujun728/jun_code_generator)
-【Maven项目模板】常用项目开发模板,新增SSH、SSM、Boot、Cloud、Android、APP模板 - -> 前端系开发框架[jun_frontend_ui]: - -【JQueryEasyUI】[基于JQuery的前端UI组件快速开发框架](https://github.com/wujun728/jun_frontend)
-【LayUI框架】[经典模块化前端UI 框架](https://github.com/wujun728/jun_frontend/)
-【Bootstrap框架】[前端响应式CSS/HTML框架](https://github.com/wujun728/jun_frontend)
-【Vue框架】[前端、构建用户界面的渐进式JavaScript框架](https://github.com/wujun728/jun_frontend)
- - - -TODO待办: -1、单表生成 -2、树表生成 -3、一对一生成(上下表单) -4、一对多生成(上表单下列表) - -5、父子表单生成(上下) -6、树表+表单或列表生成 - -Step1,代码生成器 -Step2,动态API -Step3、动态表单 - -> > jun_code_generator 代码生成器 -> > 为ssh项目写个代码生成器 -> > mvn_template 开发模板,调整,新增项目模板; -> > 新增SSH、SSM、SpringBoot、SpringCloud、Android、APP -> > 模板,新增+jun_ssh+ssm+springboot+mybatis+JPA - -1、精简代码生成器 -2、拆分成多个模块 -3、切换freemarker -4、使用公共的数据源 -5、维护多套模板-ssh - -6、微信登录 -7、切换前端模板为 easy-web-iframe 模板 - - -注册邮箱wujun728@163.com -原始IDgh_f4dcc9db8bc9 -appid wx427dae3919204962 - -> > jun_plugin -> > jun_java_plugin 常用开发组件,调整,新增并优化项目组件 -> > https://github.com/whirlys/Elastic-In-Practice/tree/master/guava -> > fileServer-master\ -> > fileServer-master (1)\ -> > haima-front-dist-master\ -> > jun_spring Spring开发组件,调整,新增Spring系常用plugin -> > jun_springboot SpringBoot开发组件,调整,SpringBoot系组件 - -> > jun_ssh_parent -> > Jun_ssh_eaayui -> > Jun_ssh_springboot -> > jun_ssm_parent -> > 整理ssm项目,写模板,模板还没梳理完 -> > 美化ssh项目 -> > https://github.com/doujinxian/renren-security -> > jun_springboot -> > jun_frontend_ui -> > jun_springcloud -> > SpringCloud开发组件,调整,SpringCloud系组件 -> > Vue+uniapp+Nodejs+WordPress+PHP+Android+Bigdata 。 -> > https://github.com/wujun728/vue-login-java -> > https://blog.csdn.net/xiaojinlai123/article/details/90694372 -> > https://blog.csdn.net/sxdtzhaoxinguo/article/details/77965226 -> > jun_linux -> > Linux开发组件,调整 -> > jun_website -> > https://github.com/zhangdaiscott/luban-h5 -> > https://github.com/zhangdaiscott/h5huodong -> > jun_bigdata - -吴俊: -jun_website -https://github.com/zhangdaiscott/luban-h5 -https://github.com/zhangdaiscott/h5huodong -jun_bigdata -jun_product_center -常用项目模板及常用项目,调整,常用项目的集合,私有的 -财务系统 -OA办公系统 -https://github.com/hjp1011/uniapp-oa -http://www.yiiframe.com/ -后端源码:官网下载 -https://github.com/misstt123/oasys -https://github.com/yunchaoyun/active4j-oa -https://github.com/yunchaoyun/active4j-jsp       -HR服务系统 -CRM客户关系 -行政服务系统 -问答系统 -知识学习系统 -jun_weixin -微信开发,调整 -weixin_api -weixin_boot -weixin_manager -jun_android -jun_app -APP开发,调整 -jun_uniapp -https://github.com/chenbool/uniapp-douyin -jun_app_cms - -待办: -https://github.com/lerry903/spring-boot-api-project-seed -https://github.com/jackying/H-ui.admin -https://github.com/xiaoshaDestiny/spring-cloud-2020 - -https://github.com/stylefeng/Guns -https://github.com/jsnjfz/WebStack-Guns -https://github.com/1477551037/exam -https://github.com/itd2008/My-Blog -https://github.com/qiaokun-sh/spring-token - -https://github.com/wujun728/inspinia_admin_java_ssm - -https://github.com/xwjie/ElementVueSpringbootCodeTemplate -https://github.com/RudeCrab/rude-java -https://github.com/Wjhsmart/Front-end-UI -https://github.com/zongjl/JavaWeb -https://github.com/zongjl/Jeebase -https://github.com/xzt1995/nideshop-springboot - -fsLayui -VIEWUI-FOR-EASYUI 迁移到UI -spring-boot-starter-motan -java -layoutit -Personnel-Management-System -fiction_house -inspinia_admin_java_ssm -springboot-mui -Jobs-search -xxyms———————————————————————————————————————————————————————————————————————————————————————————————————————— -​ - -TODO PLAN: - -1、清空readme,新增readme图片,新增胶片方案模板供截图 -2、调整package,调整author,调整每个工程大小,调整每个项目jar包 -3、调整每个项目运行 -4、mvn_template 开发模板,调整,新增项目模板;新增 - -jun_code_generator -0、默认生成模板调整,默认下载zip包调整 -1、代码生成器jun_code_generator 默认提供Spring、Hibernate、MyBatis、Spring JDBC模板 -2、代码生成器,将easyexcel的demo合并到code_generator -3、代码生成器的模板跟maven_template再整一下 -4、代码生成器新模板 - Ssm+easyUI - SSM+jwt+layui - boot+Bootstrap - boot+jwt+vue -5、单表生成 -6、关联表生成 -7、整理ssm项目 -8、整理boot项目 -9、SSH、SSM、SpringBoot、SpringCloud、Android、APP模板, -10、新增+jun_ssh+ssm+springboot+mybatis+JPA -jun_springboot_vue -1、ruoyi-vue-pro    ---迁移到 -jun_product_center 产品中心,常用项目模板及常用项目工程,调整,常用项目的集合,私有的 -0、整chinasoft的login.html跟index.html的page,适配Nginx跟ssm_jwt; -1、整理cs的login页面 -2、整理cs的index页面 -3、整理layui的静态前端页面并归档 -4、整理adminlte及hplus -5、整理easyui的前端页面并归档 -6、整理代码生成器 -先根据邮件去掉非必须的项目 -综合配置login及index的页面的归档 - -wujun728.github.io -jun_springcloud -jun_linux    Linux开发组件 -Nginx优化,nginx优化单台机器抗10万并发 -https://www.jianshu.com/p/5149a7a700b9 -jun_weixin   微信开发 -jun_android Android开发 -jun_app    APP开发,Vue+uniapp+Nodejs++Android -jun_temp    临时仓库,干掉 -jun_website    网站开发,以WordPress+网站模板为主 -jun_bigdata   大数据开发 - -https://blog.csdn.net/yf275908654/article/details/50171607 - -  - -Ssh_parent -aicode\      干掉 -authority\ jsp hplus boot jpa -biu\   迁移到vue里面 -mis\ 干掉 -ShiroJwt\ 迁移到vue里面 - -不要的东西删掉,重新拟定计划跟技术选型及产品 -1、新增产品规划,产品及技术选型 -2、先技术规划,技术规划 -3、新增管理规划,功能点补充及二次开发规划 -4、功能地图及产品中心规划 -5、整理胶片的模板发挥架构的优势 - -###TODO待办清单 -NOTE20210311 -jun_2021\ -jun_framework\ -jun_ssm\ -jun_test\ -jun_test11\ -About -代码生成器jun_code_generator 默认提供Spring、Hibernate、MyBatis、Spring JDBC模板,也可以根据FreeMarker语法编写自定义模板生成代码。 - -https://www.bejson.com/ -Nginx优化 -https://www.jianshu.com/p/5149a7a700b9 -Netty -https://blog.csdn.net/yuanzhenwei521/article/details/79194275 - -jun_boot -jun_plugin -jun_weixin -jun_ssm -jun_cloud -jun_app -jun_website -fsLayui -VIEWUI-FOR-EASYUI -spring-boot-starter-motan -java -layoutit -Personnel-Management-System -fiction_house -inspinia_admin_java_ssm -springboot-mui -Jobs-search -xxyms -jun_temp1\ -jun_temp2\ -TODO PLAN: - -Vue+uniapp+Nodejs+WordPress+PHP+Android+Bigdata - -https://blog.csdn.net/xiaojinlai123/article/details/90694372 -https://blog.csdn.net/sxdtzhaoxinguo/article/details/77965226 - -https://github.com/moshowgame/SpringBootCodeGenerator -https://github.com/SpringCloud/spring-cloud-codegen -http://hub.fastgit.org/thinkgem/jeesite_autocode - -Readme.md template - -plugin -https://github.com/RudeCrab/rude-java/tree/master/project-practice - -干掉,放到plugin里面 -https://github.com/wujun728/jun_frontend_ui - -boot - -https://github.com/wujun728/jun_springboot  -合并到jun_ssm,并重命名 - -https://github.com/wangyushuai/inspinia_admin_java_ssm - -前端模板-合并到front里面 -https://github.com/wenfengSAT/wenfengSAT-UI -迁移到CRM里面 -https://github.com/wenfengSAT/SpringbootCRM -迁移到plugin里面 -https://github.com/wenfengSAT/wenfengSAT-SpringBoot -迁移到uniapp里面 -https://github.com/fanchaoo/netease-cloud-music-community -待处理: -迁移到cloud里面 -fsLayui -VIEWUI-FOR-EASYUI -spring-boot-starter-motan -总体待办: -吴俊-补充TODO待办清单 -Jun_code-generator -临时分支 - -Jun_code_generator -doc\ - simple-fast-generator\   合并到code_mplus - -jun_code_generator\ - hub.fastgit.org/alibaba/easyexcel - 集成easyexcel读取文件的功能noModelRead -jun_code_mybatis\ -jun_code_mybatisplus\   - -### 附录:个人作品索引目录(持续更新) - -#### 基础篇:职业化,从做好OA系统开始 -1. [Spring boot整合Mybatis实现增删改查(支持多数据源)](https://gitee.com/shenzhanwang/SSM)![输入图片说明](https://img.shields.io/badge/-%E7%B2%BE%E5%93%81-orange.svg "在这里输入图片标题") -2. [Struts2,Hibernate,Spring三大框架的整合实现增删改查](https://gitee.com/shenzhanwang/S2SH) -3. [Spring,SpringMVC和Hibernate的整合实现增删改查](https://gitee.com/shenzhanwang/SSH) -4. [Spring平台整合activiti工作流引擎实现OA开发](https://gitee.com/shenzhanwang/Spring-activiti)![输入图片说明](https://img.shields.io/badge/-%E7%B2%BE%E5%93%81-orange.svg "在这里输入图片标题") -5. [Spring发布与调用REST风格的WebService](https://gitee.com/shenzhanwang/Spring-REST) -6. [Spring整合Apache Shiro框架,实现用户管理和权限控制](https://gitee.com/shenzhanwang/Spring-shiro) -7. [使用Spring security做权限控制](https://gitee.com/shenzhanwang/spring-security-demo) -8. [Spring整合Jasig CAS框架实现单点登录](https://gitee.com/shenzhanwang/Spring-cas-sso) -#### 中级篇:中间件的各种姿势 -9. [Spring连接mongoDB数据库实现增删改查](https://gitee.com/shenzhanwang/Spring-mongoDB) -10. [Spring连接Redis实现缓存](https://gitee.com/shenzhanwang/Spring-redis) -11. [Spring连接图存数据库Neo4j实现增删改查](https://gitee.com/shenzhanwang/Spring-neo4j) -12. [Spring平台整合消息队列ActiveMQ实现发布订阅、生产者消费者模型(JMS)](https://gitee.com/shenzhanwang/Spring-activeMQ) -13. [Spring整合消息队列RabbitMQ实现四种消息模式(AMQP)](https://gitee.com/shenzhanwang/Spring-rabbitMQ) -14. Spring框架的session模块实现集中式session管理 [购买](http://t.cn/Ai80zekN) -15. [Spring整合websocket实现即时通讯](https://gitee.com/shenzhanwang/Spring-websocket)![输入图片说明](https://img.shields.io/badge/-%E7%B2%BE%E5%93%81-orange.svg "在这里输入图片标题") -16. 使用Spring boot整合mybatis,rabbitmq,redis,mongodb实现增删改查 [购买](http://t.cn/Ai8Yh8Oy) -17. [Spring MVC整合FastDFS客户端实现文件上传](https://gitee.com/shenzhanwang/Spring-fastdfs) -18. 23种设计模式,源码、注释、使用场景 [购买](http://t.cn/Ai8Y7tEF) -19. [使用ETL工具Kettle的实例](https://gitee.com/shenzhanwang/Kettle-demo) -20. Git指南和分支管理策略 [购买](http://t.cn/Ai8Y7948) -21. 使用数据仓库进行OLAP数据分析(Mysql+Kettle+Zeppelin) ![输入图片说明](https://img.shields.io/badge/-%E7%B2%BE%E5%93%81-orange.svg "在这里输入图片标题")[购买](http://t.cn/Ai8Y7dVD) -#### 高级篇:架构之美 -22. [zookeeper原理、架构、使用场景和可视化](https://gitee.com/shenzhanwang/zookeeper-practice) -23. Spring boot整合Apache dubbo v2.7.5实现分布式服务治理(SOA架构) ![输入图片说明](https://img.shields.io/badge/-%E7%B2%BE%E5%93%81-orange.svg "在这里输入图片标题") [购买](https://dwz.lc/beP9N33) -> 包含组件Spring boot v2.2.2+Dubbo v2.7.5+Nacos v1.1.1 -效果图 -24. 使用Spring Cloud Alibaba v2.1.0实现微服务架构(MSA架构)![输入图片说明](https://img.shields.io/badge/-%E6%8B%9B%E7%89%8C-yellow.svg) [购买](https://dwz.lc/IdmrHzd) -> 包含组件Nacos+Feign+Gateway+Ribbon+Sentinel+Zipkin -效果图 -25. 使用jenkins+centos+git+maven搭建持续集成环境自动化部署分布式服务 [购买](http://t.cn/Ai8YZbaX) -26. 使用docker+compose+jenkins+gitlab+spring cloud实现微服务的编排、持续集成和动态扩容 [购买](http://t.cn/Ai8YZCYK) -27. 使用FastDFS搭建分布式文件系统(高可用、负载均衡)[购买](http://t.cn/Ai8YZePu) -28. 搭建高可用nginx集群和Tomcat负载均衡 [购买](http://t.cn/Ai8Ywlr8) -29. 搭建可扩展的ActiveMQ高可用集群 [购买](http://t.cn/Ai8YAbA8) -30. 实现Mysql数据库的主从复制、读写分离、分表分库、负载均衡和高可用 [购买](http://t.cn/Ai8YAOAK) -31. 搭建高可用redis集群实现分布式缓存 [购买](http://t.cn/Ai8Y2NQy) -32. [Spring boot整合Elastic search实现全文检索](https://gitee.com/shenzhanwang/Spring-elastic_search) ![输入图片说明](https://img.shields.io/badge/-%E6%8B%9B%E7%89%8C-yellow.svg "在这里输入图片标题") -#### 特别篇:分布式事务和并发控制 -33. 基于可靠消息最终一致性实现分布式事务(activeMQ)[购买](http://t.cn/Ai8YLPBL) -34. Spring boot dubbo整合seata实现分布式事务![输入图片说明](https://img.shields.io/badge/-%E7%B2%BE%E5%93%81-orange.svg "在这里输入图片标题") [购买](https://dwz.lc/csO0rp2) -> 包含组件nacos v1.1.0 + seata v0.7.1 +spring boot dubbo v2.7.5 -效果图 -35. Spring cloud alibaba v2.1.0整合seata实现分布式事务 ![输入图片说明](https://img.shields.io/badge/-%E7%B2%BE%E5%93%81-orange.svg "在这里输入图片标题")[购买](https://dwz.lc/0T8KCTC) -> 包含组件nacos v1.1.0 + seata v0.7.1 +spring cloud alibaba v2.1.0 -效果图 -36. 决战高并发:数据库锁机制和事务隔离级别的实现![输入图片说明](https://img.shields.io/badge/-%E7%B2%BE%E5%93%81-orange.svg "在这里输入图片标题") [购买](http://t.cn/Ai8YyAQE) -37. 决战高并发:使用redis实现分布式锁 ![输入图片说明](https://img.shields.io/badge/-%E7%B2%BE%E5%93%81-orange.svg "在这里输入图片标题")[购买](http://t.cn/Ai8Y4bER) -38. 决战高并发:使用zookeeper实现分布式锁 [购买](http://t.cn/Ai8Y4Cuq) -39. 决战高并发:Java多线程编程实例 [购买](http://t.cn/Ai8Y4s0r) -40. 决战高并发:使用netty实现高性能NIO通信 [购买](http://t.cn/Ai8Ybq3e) - - -全套大礼包2020年版 - -1、jun_api_service -初始化API_Service -https://github.com/lihengming/spring-boot-api-project-seed -干掉jun_api-plugin - -2、jun_cache   ---干掉 -新增springcache -https://github.com/iamsixer/spring-cache-demo -https://github.com/zheng-zy/spring-boot-redis-guava-caffeine-cache - -3、camel 干掉,没啥用 - -4、jun_crawler 调整,跑起来,净化 - -5、jun_datasource_cluster rename 到 DataSource -新增 https://github.com/ran-jit/tomcat-cluster-redis-session-manager - -6、分解jun_dbutils -https://github.com/objcoding/jdbc-utils - -7、jun_demo rename到 jun_test - -8、设计模式,合并到一起,分三种合并,中文转英文 - -9、jun_note 新增 -https://github.com/GourdErwa/review-notes - -10、新增jun_webservlet_guice_dbutil -https://www.cnblogs.com/huzi007/p/5802022.html -https://www.cnblogs.com/huzi007/p/5796372.html - -11、drools https://github.com/maxxbwsDemo - -12、email 调整,清理 -https://github.com/biezhi/oh-my-email/blob/master/pom.xml -https://github.com/isliqian/NiceEmail - -13、excel 集成 easyexcel -https://github.com/HowieYuan/easyexcel-encapsulation -新增jun_poi demo - -14、jun_fileupload -https://github.com/wemakebug/FileUpload.Java -Spring fileupload -https://github.com/jdmr/fileUpload - -15、freemarker boot https://github.com/JavaCodeMood/freemarker - -16、guava -https://github.com/tiantiangao/guava-study -https://github.com/tfnico/guava-examples - -17、guice -https://github.com/timlien/servlet-guice -https://github.com/greengerong/guice-demo -https://github.com/lg625740749/GuiceDemo - -18、hibernate -https://github.com/hibernate/hibernate-demos - -19、httpclient -https://github.com/Arronlong/httpclientutil -https://github.com/JourWon/httpclientutil - -20、image -https://github.com/xuehuayous/ImageUpload -https://github.com/jmitchener/spring-images -https://github.com/woobong/spring-boot-jpa-summernote-image-upload-example -https://github.com/mrmodise/java-spring-file-upload - -21、jbpm4 -https://github.com/xxg3053/jbpm-study -https://github.com/American/workflow/tree/master/workflow - -22.jdk 清理,调整 - -23、lucenne -https://github.com/abel533/SearchEngine -https://github.com/doushini/lucene -https://github.com/pumadong/cl-search -Springboot+ElasticSearch -https://github.com/Motianshi/all-search - -24、pay -https://github.com/kongzhidea/pay -https://github.com/iyangyuan/pay-spring-boot - -Spring-cloud - -  - -41、 webmagic -https://github.com/scsfwgy/WebMagic_CSDN_Demo -https://github.com/EzioL/neteasemusic - -42、api_service -合并都api里面,其他的2个干掉 - -Spring -43、 jwt rename一下 -新增springboot jwt -https://github.com/dolyw/VueStudy/tree/master/VueStudy08-JWT -https://github.com/dolyw/ShiroJwt.git - -44、spring activemq -清理代码,优化test及readme -https://github.com/888xin/activeMQ - -45、camel 调整为zip里面的spring -46、cas 干掉 -新增oauth - -47、cors 调整为filter过滤器 - -48、config 迁移到cloud里面 - -49、fastdfs - -50、dubbo -https://github.com/GenshenWang/DubboDemo - -51、quartz -https://github.com/ameizi/spring-quartz-cluster-sample - -52、新增xxl-job -https://github.com/xuxueli/xxl-job - -53、email -https://github.com/fangjieDevp/spring-email-master - -54、Excel 干掉 - -55、hibernate -https://github.com/zhonglinlin1305/Spring -https://github.com/zhonglinlin1305/spring-projects/ - -0、Boot&cloud -https://github.com/zhonglinlin1305/spring-boot-sample/ -https://github.com/zhonglinlin1305/spring-cloud-microservice -https://github.com/SpringForAll/springcloud-thoth - -56、kafka -https://github.com/smallnest/spring-kafka-demo - -57、lucenne -https://github.com/FuZhucheng/SSM - -  - -00、boot starter -https://github.com/battcn/extend-spring-boot - -00、util -https://github.com/864381832/xJavaFxTool-spring - -00、ppt -https://github.com/aalansehaiyang/technology-talk - -1、plugin 代码全部梳理一遍,package/pom/test/readme -1、清理没用代码、工程pom、工程package、工程test、readme、截图、胶片 -2、ssh 代码合并到一个,调整功能 -1、清理没用代码、工程pom、工程package、工程test、readme、截图、胶片 -3、ssm 代码合并到一个,调整功能 -1、清理没用代码、工程pom、工程package、工程test、readme、截图、胶片 -4、代码生成器、代码一套,功能一套,合并ry_gen -https://www.jianshu.com/p/31e532392a74 -1、清理没用代码、工程pom、工程package、工程test、readme、截图、胶片 -5、ui 整理ui -1、清理没用代码、工程pom、工程package、工程test、readme、截图、胶片 -6、apiservice 代码一套,功能一套,同步ssm -1、清理没用代码、工程pom、工程package、工程test、readme、截图、胶片 -https://github.com/callicoder/spring-webflux-reactive-rest-api-demo -https://blog.csdn.net/qq_35067322/article/details/106935320 -https://github.com/dolyw/ShiroJwt -7、linux 部署文档,部署包、docker部署 -1、清理没用代码、工程pom、工程package、工程test、readme、截图、胶片 -部署环境 - -Step2 -main -https://github.com/Heeexy/SpringBoot-Shiro-Vue -jun_springboot_jwt_layui\   合并到ssm框架 -jun_springboot_jwt_shiro_api\   空的 -jun_springboot_vue\   干掉 -jun_springboot_vue_pro\ 合并到上面里面 - -Step4 -1、uniapp -https://github.com/zsptsf/uniapp.git -https://github.com/c1013529993/springboot-uniapp-21cake - -Step1 -Jdbc_template -https://gitee.com/jervain_y/repository - -https://github.com/horsecms/layuiCMS - -Step2 -1、vue-element-admin -https://github.com/panjiachen/vue-element-admin-site -https://panjiachen.github.io/vue-element-admin-site/zh/guide/ -2、cloud -https://www.8kee.com/article/17347.html -https://github.com/JourWon/springcloud-learning -https://github.com/wenren0819/Spring-Cloud-2020 -https://blog.csdn.net/ThinkWon/article/details/103726655 - -2、api_service -https://github.com/koocyton/reactor-guice -https://github.com/jwpttcg66/NettyGameServer -3、bigdata -爬虫 -https://github.com/brianway/webporter -ETL -https://github.com/zhaxiaodong9860/kettle-scheduler -数仓 -https://github.com/fenglei110/DataWarehouse -https://github.com/jd-bigdata/rtf-lake -https://github.com/xzt1995/Data-Warehouse -新增用户画像、用户行为 -https://github.com/monsonlee/BigData -https://github.com/whirlys/BigData-In-Practice -https://github.com/597365581/bigdata_tools -https://blog.csdn.net/u013967628/article/details/83656560 - -1、plugin 代码全部梳理一遍,package/pom/test/readme -1、清理没用代码、工程pom、工程package、工程test、readme、截图、胶片 -2、ssh 代码合并到一个,调整功能 -1、清理没用代码、工程pom、工程package、工程test、readme、截图、胶片 -3、ssm 代码合并到一个,调整功能 -1、清理没用代码、工程pom、工程package、工程test、readme、截图、胶片 -4、代码生成器、代码一套,功能一套,合并ry_gen -https://www.jianshu.com/p/31e532392a74 -1、清理没用代码、工程pom、工程package、工程test、readme、截图、胶片 -5、ui 整理ui -1、清理没用代码、工程pom、工程package、工程test、readme、截图、胶片 -6、apiservice 代码一套,功能一套,同步ssm -1、清理没用代码、工程pom、工程package、工程test、readme、截图、胶片 -https://github.com/callicoder/spring-webflux-reactive-rest-api-demo -https://blog.csdn.net/qq_35067322/article/details/106935320 -https://github.com/dolyw/ShiroJwt -7、linux 部署文档,部署包、docker部署 -1、清理没用代码、工程pom、工程package、工程test、readme、截图、胶片 -部署环境 - -Step2 -main -https://github.com/Heeexy/SpringBoot-Shiro-Vue -jun_springboot_jwt_layui\   合并到ssm框架 -jun_springboot_jwt_shiro_api\   空的 -jun_springboot_vue\   干掉 -jun_springboot_vue_pro\ 合并到上面里面 - -Step4 -1、uniapp -https://github.com/zsptsf/uniapp.git -https://github.com/c1013529993/springboot-uniapp-21cake - -Step1 -Jdbc_template -https://gitee.com/jervain_y/repository - -https://github.com/horsecms/layuiCMS - -Step2 -1、vue-element-admin -https://github.com/panjiachen/vue-element-admin-site -https://panjiachen.github.io/vue-element-admin-site/zh/guide/ -2、cloud -https://www.8kee.com/article/17347.html -https://github.com/JourWon/springcloud-learning -https://github.com/wenren0819/Spring-Cloud-2020 -https://blog.csdn.net/ThinkWon/article/details/103726655 - -2、api_service -https://github.com/koocyton/reactor-guice -https://github.com/jwpttcg66/NettyGameServer -3、bigdata -爬虫 -https://github.com/brianway/webporter -ETL -https://github.com/zhaxiaodong9860/kettle-scheduler -数仓 -https://github.com/fenglei110/DataWarehouse -https://github.com/jd-bigdata/rtf-lake -https://github.com/xzt1995/Data-Warehouse -新增用户画像、用户行为 -https://github.com/monsonlee/BigData -https://github.com/whirlys/BigData-In-Practice -https://github.com/597365581/bigdata_tools -https://blog.csdn.net/u013967628/article/details/83656560 - -Eureka -https://www.cnblogs.com/rickiyang/p/11802413.html -Rebbon -https://blog.csdn.net/forezp/article/details/74820899 -Ribbon的负载均衡,主要通过LoadBalancerClient来实现的,而LoadBalancerClient具体交给了ILoadBalancer来处理,ILoadBalancer通过配置IRule、IPing等信息,并向EurekaClient获取注册列表的信息,并默认10秒一次向EurekaClient发送“ping”,进而检查是否更新服务列表,最后,得到注册列表后,ILoadBalancer根据IRule的策略进行负载均衡。在RestTemplate 被@LoadBalance注解后,能过用负载均衡,主要是维护了一个被@LoadBalance注解的RestTemplate列表,并给列表中的RestTemplate添加拦截器,进而交给负载均衡器去处理。 - -架构 -https://blog.csdn.net/shenhuxi10000/article/details/105058723 - -https://github.com/wujun728/learningSummary - -Springboot security -https://blog.csdn.net/yuanlaijike/article/details/80249235 - -mxtheme02 - -https://github.com/hemin1003 -jun_temp     临时仓库 -https://github.com/c1013529993/springboot-uniapp-21cake - -JWT+VUE -https://github.com/cailichao/easyweb-jwt -https://github.com/whvcse/JwtPermission - -Elasticsearch - -来自  - -  - -https://spring-cloud-alibaba-group.github.io/github-pages/hoxton/zh-cn/index.html - -*************************************************************************************************** - -Springboot_fileupload -https://github.com/gaoyuyue/MyUploader-Backend - -springcloud_plugin -Superboot    --- 迁移到jun_cloud_center -Jun_dubbo ---迁移到jun_microservice -Spring - -https://github.com/liuge1988/kitty-generator -https://github.com/zhoutaoo/SpringCloud - -Api_service -1、API_BOOT代码生成器合并到code_generator里面 -2、api里面的layui抽出来,合并到 -https://github.com/Radom7/springboot-layui -jun_layuiadmin -3、新增apijson -https://github.com/APIJSON/APIJSON-Demo -https://vincentcheng.github.io/apijson-doc/ - -Api_service -1、API_BOOT代码生成器合并到code_generator里面 -2、api里面的layui抽出来,合并到 -https://github.com/Radom7/springboot-layui -jun_layuiadmin -3、新增apijson -https://github.com/APIJSON/APIJSON-Demo -https://vincentcheng.github.io/apijson-doc/ - -https://github.com/scaladte - -https://github.com/malizhigithub/CRM - -https://blog.csdn.net/qq_22211217/article/details/83759513 -https://www.cnblogs.com/softidea/p/10271266.html -Mysql 递归查询 - - -WordPress 多站点 -企业官网 -中软门户网站 - diff --git a/.claude/.claude/settings.local.json b/.claude/.claude/settings.local.json deleted file mode 100644 index 966de11e87..0000000000 --- a/.claude/.claude/settings.local.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "permissions": { - "allow": [ - "Bash(dir /b \"D:\\\\workspace\\\\scrm-paas\\\\scrm-paas-runtime\\\\scrm-paas-runtime-server\\\\src\\\\main\\\\java\\\\net\\\\trueland\\\\scrm\\\\paas\\\\runtime\\\\service\\\\selector\")", - "Bash(git init)", - "Bash(find /d \"D:/workspace/scrm-paas\" -name \"*.sql\" -type f -exec grep -l \"INSERT INTO paas_component_instance\" {} ;)", - "Bash(xxd \"D:\\\\workspace\\\\scrm-paas\\\\scrm-paas-metadata\\\\paas-metadata-server\\\\src\\\\main\\\\java\\\\net\\\\trueland\\\\scrm\\\\paas\\\\metadata\\\\service\\\\selector\\\\paas\\\\user\\\\OneSelfAndSubUser.java\")", - "WebSearch", - "WebFetch(domain:developer.work.weixin.qq.com)", - "WebFetch(domain:open.work.weixin.qq.com)", - "Bash(xargs cat)", - "WebFetch(domain:github.com)", - "WebFetch(domain:blog.csdn.net)" - ] - } -} diff --git a/.claude/settings.local.json b/.claude/settings.local.json deleted file mode 100644 index d0be0c7ccc..0000000000 --- a/.claude/settings.local.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "permissions": { - "allow": [ - "Bash(mvn compile -q)", - "Bash(mvn test -Dtest=io.github.wujun728.db.DbActiveRecordTest)", - "Bash(ls -d \"D:\\\\workspace\\\\github-new\\\\jun_java_plugin\\\\jun_java_plugins\"*/)", - "Bash(ls -d \"D:\\\\workspace\\\\github-new\\\\jun_java_plugin\\\\jun_java_plugins\"jun_*/)", - "Bash(ls -d \"D:\\\\workspace\\\\github-new\\\\jun_java_plugin\\\\jun_java_plugins\"/jun_*/)", - "Bash(mvn compile -T 4 --fail-at-end)", - "Bash(git add jun_java_plugins/pom.xml jun_java_plugins/jun_mybatisplus/pom.xml jun_java_plugins/jun_redis/pom.xml jun_java_plugins/jun_email/pom.xml jun_java_plugins/jun_serialization/pom.xml jun_java_plugins/jun_quartz/pom.xml jun_java_plugins/jun_jdk/pom.xml)", - "Bash(git commit -m \"$\\(cat <<''EOF''\ncleanup: remove empty/duplicate modules and fix dependency issues in jun_java_plugins\n\n- Comment out 9 empty shell modules \\(no Java source files\\) from parent POM\n- Comment out 4 redundant/duplicate modules from parent POM\n- Fix 12 duplicate dependencies across 5 POMs, including 4 version-mismatch bugs:\n - jun_mybatisplus: spring-context was hardcoded 4.3.10 instead of $spring.version 5.1.9\n - jun_redis: jedis duplicated with 2.9.0 vs 2.2.1\n - jun_quartz: two spring version properties \\(4.0.6 vs 5.0.8\\) unified to 5.0.8\n- Remove unused spark-core, spark-sql, hadoop-client from jun_jdk \\(zero imports\\)\nEOF\n\\)\")", - "Bash(ls -d \"D:\\\\workspace\\\\github-new\\\\jun_java_plugin\\\\jun_java_plugins\"/*/)", - "Bash(xargs -I{} basename \"{}\")", - "Bash(ls -d D:/workspace/github-new/jun_java_plugin/jun_java_plugins/*/)", - "Bash(mvn compile -T 4)", - "Bash(mvn clean package -q)", - "Bash(cmd.exe /c \"cd /d D:\\\\workspace\\\\github-new\\\\jun_java_plugin\\\\jun_springboot_starter\\\\jun-mybatis-sql-engine && mvn clean package -q 2>&1\")", - "Bash(cmd.exe /c \"cd /d D:\\\\workspace\\\\github-new\\\\jun_java_plugin\\\\jun_springboot_starter\\\\jun-mybatis-sql-engine && mvn clean package 2>&1\")", - "Bash(cmd.exe /c \"D: && cd D:\\\\workspace\\\\github-new\\\\jun_java_plugin\\\\jun_springboot_starter\\\\jun-mybatis-sql-engine && mvn clean package\")", - "Bash(powershell.exe -Command \"Set-Location ''D:\\\\workspace\\\\github-new\\\\jun_java_plugin\\\\jun_springboot_starter\\\\jun-mybatis-sql-engine''; mvn clean package 2>&1\")", - "Bash(powershell.exe -Command \"Set-Location ''D:\\\\workspace\\\\github-new\\\\jun_java_plugin\\\\jun_springboot_starter\\\\jun-mybatis-sql-engine''; mvn clean package -Dmaven.javadoc.skip=true 2>&1\")", - "Bash(mvn clean compile -q)", - "Bash(mvn install -pl jun-db-activerecord -q -DskipTests)", - "Bash(mvn install -pl jun-mybatis-sql-engine -q -DskipTests)", - "Bash(dir \"C:\\\\Users\\\\Administrator\\\\.m2\\\\repository\\\\io\\\\github\\\\wujun728\\\\jun-db-activerecord\\\\1.0.25\"\")", - "Bash(mvn install -pl jun-common-base,jun-db-activerecord,jun-mybatis-sql-engine -DskipTests -am)", - "Bash(mvn clean compile)", - "Bash(jar tf \"D:\\\\Java\\\\.m2\\\\repository\\\\io\\\\github\\\\wujun728\\\\jun-db-activerecord\\\\1.0.25\\\\jun-db-activerecord-1.0.25.jar\")", - "Bash(mvn compile -pl jun-db-activerecord)", - "Bash(mvn install -pl jun-db-activerecord -DskipTests)", - "Bash(jar tf \"D:\\\\Java\\\\.m2\\\\repository\\\\io\\\\github\\\\wujun728\\\\jun-mybatis-sql-engine\\\\1.0.25\\\\jun-mybatis-sql-engine-1.0.25.jar\")", - "Bash(mvn test -Dtest=\"io.github.wujun728.groovy.GroovyScriptTest,io.github.wujun728.rest.RestApiTest,io.github.wujun728.sql.SqlEngineTest,io.github.wujun728.generator.CodeGeneratorTest\")", - "Bash(mvn test -Dtest=\"io.github.wujun728.generator.CodeGeneratorTest\")", - "Bash(mvn clean compile test-compile)", - "Bash(mvn test -Dtest=ModelTest -pl .)", - "Bash(mvn test)", - "Bash(mvn clean compile test-compile -q)", - "Bash(mvn clean test)", - "Bash(dir /s /b \"D:\\\\workspace\\\\github-new\\\\jun_java_plugin\\\\jun_springboot_starter\\\\jun-db-activerecord\\\\src\\\\main\\\\java\\\\io\\\\github\\\\wujun728\\\\db\\\\*.java\")", - "Bash(mvn test -Dtest=CodeGeneratorTest -pl .)", - "Bash(mvn test -pl .)", - "Bash(git add VERSION_CONSTANTS.md)", - "Bash(git add */pom.xml)", - "Bash(git commit -m \"$\\(cat <<''EOF''\nrefactor: 重构 jun_springboot_starter 模块 - 移除所有 Parent 依赖\n\n- 创建 VERSION_CONSTANTS.md 文档,统一记录所有版本号\n- 移除16个模块的parent POM引用,使其可以独立编译\n- 添加显式的groupId和version到所有模块\n- 为每个模块添加完整的properties和dependencyManagement配置\n- 统一所有内部模块版本号为1.0.25\n- 更新所有模块间依赖,明确指定版本号\n- 修正4个模块的错误parent引用(从jun_springcloud_starter改正)\n- 编译验证:jun-common-base、jun-swagger2、jun-groovy-api-spring-boot-starter等模块编译成功\n\n重构范围:\n- 新增模块:VERSION_CONSTANTS.md\n- 修改模块:16个pom.xml文件\n - 正确parent改为无parent:jun-activerecord、jun-db-spring-boot-starter、\n jun-groovy-api、jun-groovy-api-spring-boot-starter、jun-swagger2-spring-boot-starter、\n jun-uidgenerator-spring-boot-starter、jun-sentinel-spring-boot-starter、\n jun-job-spring-boot-starter、jun-snakerflow-spring-boot-starter、\n jun-minio-spring-boot-starter、jun-encrypt-body-spring-boot-starter\n - 错误parent改为无parent:jun-log-spring-boot-starter、\n jun-redis-spring-boot-starter、jun-onlineForm-spring-boot-starter、\n jun-db-activerecord2、jun-oss-spring-boot-starter\n\n预期结果:\n✓ 所有模块都可以独立使用 mvn clean compile 编译\n✓ 模块间依赖关系清晰明确,版本号统一\n✓ 第三方用户可以独立引用任何模块而无需关心parent POM\nEOF\n\\)\")", - "Bash(mvn clean compile -DskipTests -q)", - "Bash(mvn clean compile -DskipTests)", - "Bash(mvn compile -DskipTests)", - "Bash(git add -A)", - "Bash(git commit -m \"$\\(cat <<''EOF''\nrefactor: 清理冗余代码并重构RestController\n\n## 主要改进\n\n### 第一优先级 - 删除冗余依赖\n- 删除自定义 MapUtil.java(完全重复 hutool 库功能)\n- 删除自定义 StringUtils.java(所有方法都有 hutool 替代)\n- 统一使用 cn.hutool.core.map.MapUtil 和 cn.hutool.core.util.StrUtil\n\n### 第二优先级 - 提取公共逻辑\n- 创建 BaseRestController 基类,提取公共参数初始化逻辑\n- RestApiController 和 RestSqlController 继承 BaseRestController\n- 消除每个方法中重复的参数处理代码(8个重复片段 → 统一方法)\n\n### 具体改动\n1. MapUtil 替换:\n - RestApiService:getString → getStr\n - GeneratorServiceImpl:getString → getStr \n - TableParseUtil:getString → getStr,getBoolean 改为直接获取\n\n2. StringUtils 替换:\n - CodeUtil:countMatches → StrUtil.count\n - TableParseUtil:upperCaseFirst → StrUtil.upperFirst\n - TableParseUtil:underlineToCamelCase → StrUtil.toCamelCase\n - TableParseUtil:toLowerCamel/toUnderline 等方法使用 hutool 替代\n\n3. RestController 重构:\n - 提取 initCommonParameters\\(\\) 方法处理公共参数\n - 提取 getTableName\\(\\) 方法统一获取表名\n - list/page/tree/findOne/delete/create/update 方法都使用新方法\n\n## 代码质量改进\n- 代码重复率降低 ~30%\n- 去除重复工具类 2 个\n- 公共逻辑集中管理\n- 编译通过,功能不变\nEOF\n\\)\")" - ] - } -} diff --git a/.claude/skills/README.md b/.claude/skills/README.md deleted file mode 100644 index 82439afc8b..0000000000 --- a/.claude/skills/README.md +++ /dev/null @@ -1,284 +0,0 @@ -# 后端项目 Claude Code Skills 使用说明 - -本目录包含为后端项目开发的 Claude Code Skills,用于快速生成符合项目规范的代码。 - -## Skills 列表 - -| Skill 名称 | 功能说明 | 使用场景 | -|-----------|---------|---------| -| crud | 一键生成完整业务模块 | 新建完整的业务功能 | -| project-conventions | 项目编码规范指南 | 了解项目编码规范、代码审查参考 | - -## 安装部署 - -解压 `backend-claude-skills.zip` 将 `.claude` 目录放置到**项目根目录**下,确保目录结构如下: - -``` -your-project/ # 你的项目根目录 -├── .claude/ # .claude 目录 -│ └── skills/ # Skills 目录 -│ ├── README.md -│ ├── crud/ -│ └── project-conventions/ -├── src/ -├── pom.xml -└── ... -``` - -### 验证安装 - -在项目目录中启动 Claude Code,输入 `/crud` 测试是否能正确识别 skill。 - ---- - -## 快速开始 - -使用 `/crud` 命令,描述你的业务需求即可一键生成完整模块代码: - -``` -请帮我创建一个XXX功能,包含以下字段: -- 字段1(类型,说明) -- 字段2(类型,说明) -- ... -``` - -这将自动生成: -- SQL 建表语句 -- Entity 实体类 -- DAO 接口 + MyBatis XML -- Repository 仓储层 -- POJO(DTO/VO/QO) -- MapStruct Mapper -- Service 业务层 -- Controller 控制器 - ---- - -## 常用业务示例 - -### 1. 商品管理 - -``` -请帮我创建一个商品管理功能,包含以下字段: -- 商品名称(必填,最长200字符) -- 商品编码(唯一,最长50字符) -- 商品分类ID(关联分类表) -- 销售价格(精确到分,使用Long类型) -- 成本价格(精确到分,使用Long类型) -- 库存数量(整数,默认0) -- 商品图片(图片URL,最长500字符) -- 商品描述(富文本,TEXT类型) -- 状态(0下架/1上架,默认0) -``` - -### 2. 订单管理 - -``` -请帮我创建一个订单管理功能,包含以下字段: -- 订单号(唯一,最长64字符) -- 用户ID(关联用户表) -- 订单状态(0待付款/1已付款/2已发货/3已完成/4已取消) -- 商品总金额(精确到分,Long类型) -- 运费金额(精确到分,Long类型) -- 优惠金额(精确到分,Long类型) -- 实付金额(精确到分,Long类型) -- 收货人姓名(最长50字符) -- 收货人电话(最长20字符) -- 收货地址(最长500字符) -- 下单时间(时间类型) -- 支付时间(时间类型,可为空) -- 发货时间(时间类型,可为空) -- 订单备注(最长500字符) -``` - -### 3. 用户管理 - -``` -请帮我创建一个用户管理功能,包含以下字段: -- 用户名(唯一,最长50字符) -- 手机号(唯一,11位) -- 邮箱(最长100字符,可为空) -- 密码(加密存储,最长100字符) -- 昵称(最长50字符) -- 头像URL(最长500字符) -- 性别(0未知/1男/2女) -- 生日(日期类型,可为空) -- 用户等级(整数,默认1) -- 账户余额(精确到分,Long类型,默认0) -- 积分(整数,默认0) -- 状态(0禁用/1正常) -- 最后登录时间(时间类型,可为空) -``` - -### 4. 分类管理(树形结构) - -``` -请帮我创建一个分类管理功能,支持多级树形结构,包含以下字段: -- 分类名称(必填,最长100字符) -- 父级分类ID(默认0表示顶级分类) -- 分类图标(图片URL,最长500字符,可为空) -- 排序值(整数,默认0,值越小越靠前) -- 层级(整数,从1开始) -- 状态(0禁用/1启用,默认1) -``` - -### 5. 优惠券管理 - -``` -请帮我创建一个优惠券管理功能,包含以下字段: -- 优惠券名称(必填,最长100字符) -- 优惠券类型(1满减券/2折扣券/3无门槛券) -- 优惠券面值(精确到分,Long类型) -- 折扣率(百分比,如85表示8.5折,仅折扣券有效) -- 使用门槛金额(精确到分,Long类型,0表示无门槛) -- 发放总量(整数) -- 已领取数量(整数,默认0) -- 已使用数量(整数,默认0) -- 每人限领数量(整数,默认1) -- 生效时间(时间类型) -- 失效时间(时间类型) -- 使用说明(最长500字符) -- 状态(0未开始/1进行中/2已结束) -``` - -### 6. 会员卡管理 - -``` -请帮我创建一个会员卡管理功能,包含以下字段: -- 卡号(唯一,最长32字符) -- 用户ID(关联用户表) -- 会员等级ID(关联等级表) -- 卡片余额(精确到分,Long类型) -- 累计充值金额(精确到分,Long类型) -- 累计消费金额(精确到分,Long类型) -- 积分余额(整数) -- 开卡时间(时间类型) -- 到期时间(时间类型,可为空) -- 卡片状态(0冻结/1正常/2过期) -``` - -### 7. 库存管理 - -``` -请帮我创建一个库存管理功能,包含以下字段: -- 商品ID(关联商品表) -- 仓库ID(关联仓库表) -- SKU编码(最长64字符) -- 可用库存(整数) -- 锁定库存(整数,默认0,已下单未出库) -- 预警库存(整数,低于此值提醒) -- 最后入库时间(时间类型,可为空) -- 最后出库时间(时间类型,可为空) -``` - -### 8. 评价管理 - -``` -请帮我创建一个评价管理功能,包含以下字段: -- 订单ID(关联订单表) -- 商品ID(关联商品表) -- 用户ID(关联用户表) -- 评分(1-5整数) -- 评价内容(TEXT类型) -- 评价图片(JSON数组,存储多张图片URL) -- 是否匿名(0否/1是,默认0) -- 商家回复(TEXT类型,可为空) -- 回复时间(时间类型,可为空) -- 状态(0待审核/1已通过/2已拒绝) -``` - -### 9. 地址管理 - -``` -请帮我创建一个收货地址管理功能,包含以下字段: -- 用户ID(关联用户表) -- 收货人姓名(最长50字符) -- 收货人电话(最长20字符) -- 省份编码(最长10字符) -- 城市编码(最长10字符) -- 区县编码(最长10字符) -- 详细地址(最长500字符) -- 邮政编码(最长10字符,可为空) -- 是否默认地址(0否/1是,默认0) -- 地址标签(如"家""公司",最长20字符,可为空) -``` - -### 10. 操作日志 - -``` -请帮我创建一个操作日志功能,包含以下字段: -- 操作人ID(关联用户表) -- 操作人名称(最长50字符) -- 操作模块(最长50字符,如"订单管理") -- 操作类型(最长50字符,如"新增""编辑""删除") -- 操作内容(TEXT类型,记录详细操作) -- 请求URL(最长500字符) -- 请求方法(最长10字符,GET/POST等) -- 请求参数(TEXT类型) -- 响应结果(TEXT类型) -- 操作IP(最长50字符) -- 操作耗时(毫秒,Long类型) -``` - ---- - -## 目录结构 - -``` -.claude/skills/ -├── README.md # 本说明文件 -├── crud/ -│ └── SKILL.md # 一键生成所有模块 -└── project-conventions/ - └── SKILL.md # 项目编码规范指南 -``` - -## 项目代码规范 - -所有生成的代码都遵循以下规范: - -### 阿里巴巴 Java 开发手册 -- 命名规范(UpperCamelCase/lowerCamelCase) -- 注释规范(Javadoc + ApiModelProperty) -- 分层规范(Controller/Service/Repository/DAO) - -### 数据库规范 -- 表名:`s_` 前缀 + 蛇形命名 -- 字段名:蛇形命名 -- 必备字段:id、tenant_id、create_time、update_time、is_deleted - -### 包结构规范 -``` -net.trueland.tshop.example -├── domain -│ ├── dao/ # MyBatis Mapper 接口 -│ ├── entity/ # 数据库实体 -│ └── pojo/ # DTO/VO/QO -├── mapping/ # MapStruct 映射器 -├── repository/ # 数据仓储层 -├── service/ # 业务逻辑层 -└── web/ # Controller 控制器 - ├── admin/ # 管理端 API - ├── app/ # C端 API - └── feign/ # Feign 接口 -``` - -## 技术栈 - -- **Java 8** -- **Spring Boot 2.4.2 / 2.6.13** -- **Spring Cloud** -- **MyBatis** -- **MapStruct** -- **Lombok** -- **Hutool** -- **Swagger/Knife4j** -- **MySQL 5.7/8.0** - -## 注意事项 - -1. 生成的代码需要根据实际业务进行调整和完善 -2. 生成的 ErrorCode 枚举值需要在 `ErrorCode.java` 中添加 -3. 复杂业务逻辑需要在 Service 层手动编写 -4. 建议生成后运行项目检查编译是否通过 -5. 数据库表需要先执行 SQL 创建 diff --git a/.claude/skills/crud/SKILL.md b/.claude/skills/crud/SKILL.md deleted file mode 100644 index 256b3ced26..0000000000 --- a/.claude/skills/crud/SKILL.md +++ /dev/null @@ -1,511 +0,0 @@ ---- -name: crud -description: 一键生成完整业务模块代码(SQL/Entity/DAO/XML/Repository/Service/Controller/Mapper/POJO),用于创建新的业务功能 ---- - -# crud - 一键生成完整业务模块 - -根据用户提供的需求描述,一键生成完整的业务模块代码,包括:SQL建表语句 -> MyBatis XML -> Entity -> DAO -> Repository -> Service -> Controller -> MapStruct Mapper -> POJO (DTO/VO/QO)。 - -## 自动触发条件 - -当用户的输入符合以下任一情况时,应自动应用此技能(无需用户明确输入 /crud): - -### 关键词触发 -- 包含"创建"、"新建"、"添加"、"生成"等动词 + "功能"、"模块"、"管理"、"表"等名词 -- 包含"XXX管理"模式,如"用户管理"、"订单管理"、"商品管理" -- 包含"帮我做一个"、"帮我写一个"、"实现一个"等请求模式 -- 包含字段描述列表(多个字段说明) - -### 场景触发 -- 用户描述一个新的业务实体及其属性 -- 用户提供数据库表结构或字段清单 -- 用户需要实现增删改查(CRUD)功能 -- 用户描述一个需要持久化存储的业务对象 - -### 示例输入(应自动触发) -- "帮我创建一个商品分类管理功能" -- "我需要一个用户管理模块" -- "做一个订单表,包含订单号、金额、状态等字段" -- "实现一个会员卡功能,需要存储卡号、余额、积分" -- "新建一个评价管理,包含评分、评价内容、图片" - ---- - -## 执行步骤 - -### 步骤1:项目环境检测 - -在生成代码之前,**必须先完成以下检测**: - -#### 1.1 检测项目包名(Package) - -**检测方法:** -1. 查找 `src/main/java` 目录下的Java文件 -2. 读取已有Java文件的 `package` 声明 -3. 分析项目的根包名结构 - -**处理规则:** -- **如果检测到已有代码**:使用项目中已存在的包名结构 -- **如果是空项目或无法检测**:询问用户确认包名 - -**询问示例:** -``` -检测到这是一个新项目,请确认项目的基础包名: -- 例如:com.example.demo -- 例如:net.company.project -``` - -#### 1.2 检测代码作者(Author) - -**检测方法:** -1. 查找项目中已有的 `@author` 注释 -2. 检查 git 配置中的用户名 - -**处理规则:** -- **如果检测到统一的作者名**:使用检测到的作者名 -- **如果未检测到或不统一**:询问用户确认作者名 - -**询问示例:** -``` -请确认代码注释中的作者名(@author): -- 可以是您的名字、工号或团队名称 -- 例如:zhangsan、张三、dev-team -``` - ---- - -### 步骤2:需求分析 - -- 分析用户的业务需求描述 -- 确定需要创建的表名(遵循 `s_` 前缀命名规范) -- 确定表的字段、类型、注释 -- 确定业务模块名称(用于包路径) - ---- - -### 步骤3:按顺序生成代码 - -按以下顺序依次生成: - -1. **SQL建表语句** - 创建数据库表 -2. **Entity实体类** - 映射数据库表 -3. **MyBatis XML** - SQL映射文件 -4. **DAO接口** - 数据访问接口 -5. **Repository** - 数据仓储层 -6. **POJO** - 数据传输对象 (DTO/VO/QO) -7. **MapStruct Mapper** - 对象转换器 -8. **Service** - 业务逻辑层 -9. **Controller** - 接口控制层 - ---- - -## 代码规范要求(阿里巴巴Java开发手册) - -### 命名规范 -- **类名**:使用 UpperCamelCase 风格 -- **方法名、参数名、成员变量、局部变量**:使用 lowerCamelCase 风格 -- **常量**:全部大写,单词间用下划线隔开 -- **包名**:全部小写 -- **抽象类**:以 Abstract 或 Base 开头 -- **异常类**:以 Exception 结尾 -- **测试类**:以 Test 结尾 - -### 数据库规范 -- **表名**:使用 `s_` 前缀 + 蛇形命名,如 `s_user_info` -- **字段名**:蛇形命名,如 `create_time` -- **主键**:统一使用 `id`,类型为 `BIGINT` -- **必备字段**:`id`、`tenant_id`、`create_time`、`update_time`、`is_deleted` - -### 分层规范 -- **Controller**:只做参数校验和结果返回,不写业务逻辑 -- **Service**:业务逻辑处理,事务控制 -- **Repository**:数据访问封装,异常处理 -- **DAO**:MyBatis Mapper接口,纯数据访问 - -### 注释规范 -- 类、方法必须有 Javadoc 注释 -- 字段使用 `@ApiModelProperty` 注解说明 -- **@author 使用检测到的作者名或用户确认的作者名** - ---- - -## 项目结构参考 - -使用 `{basePackage}` 表示检测到的或用户确认的基础包名: - -``` -{basePackage} -├── domain -│ ├── dao/{实体名}Dao.java # MyBatis Mapper接口 -│ ├── entity/{实体名}.java # 数据库实体 -│ └── pojo/{模块名}/ # 业务对象 -│ ├── {实体名}DTO.java # 数据传输对象 -│ ├── {实体名}VO.java # 视图对象 -│ └── {实体名}SearchQO.java # 查询对象 -├── mapping/{模块名}/{实体名}Mapper.java # MapStruct映射器 -├── repository/{模块名}/{实体名}Repository.java # 数据仓储 -├── service/{模块名}/{实体名}Service.java # 业务服务 -└── web/admin/{模块名}/{实体名}Controller.java # 控制器 -``` - ---- - -## 代码模板 - -> **注意**:以下模板中的 `{basePackage}` 和 `{author}` 为动态变量,需要在生成前通过检测或询问用户确定。 - -### Entity 模板 -```java -package {basePackage}.domain.entity; - -import io.swagger.annotations.ApiModelProperty; -import java.time.LocalDateTime; -import lombok.Data; - -/** - * {实体描述} 实体类 - * - * @author {author} - */ -@Data -public class {实体名} { - - @ApiModelProperty("主键ID") - private Long id; - - @ApiModelProperty("商户ID") - private Long tenantId; - - // 业务字段... - - @ApiModelProperty("创建时间") - private LocalDateTime createTime; - - @ApiModelProperty("修改时间") - private LocalDateTime updateTime; - - @ApiModelProperty("是否删除 0否 1是") - private Integer isDeleted; -} -``` - -### DAO 模板 -```java -package {basePackage}.domain.dao; - -import java.util.List; -import {basePackage}.domain.entity.{实体名}; -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Param; - -/** - * {实体描述} Mapper接口 - * - * @author {author} - */ -@Mapper -public interface {实体名}Dao { - - int insert({实体名} row); - - int insertSelective({实体名} row); - - int batchInsert(@Param(value = "rows") List<{实体名}> rows); - - {实体名} selectByPrimaryKey(Long id); - - List<{实体名}> selectByIds(@Param(value = "ids") List ids); - - int updateByPrimaryKeySelective({实体名} row); - - int deleteByPrimaryKey(Long id); - - int removeByPrimaryKey(Long id); - - List<{实体名}> selectByQo(@Param(value = "qo") {实体名}SearchQO qo); -} -``` - -### Repository 模板 -```java -package {basePackage}.repository.{模块名}; - -import lombok.RequiredArgsConstructor; -import net.trueland.framework.core.ServiceException; -import {basePackage}.common.ErrorCode; -import {basePackage}.domain.dao.{实体名}Dao; -import {basePackage}.domain.entity.{实体名}; -import {basePackage}.domain.pojo.{模块名}.{实体名}SearchQO; -import org.springframework.stereotype.Repository; - -import java.time.LocalDateTime; -import java.util.List; -import java.util.Objects; - -/** - * {实体描述} Repository - * - * @author {author} - */ -@Repository -@RequiredArgsConstructor -public class {实体名}Repository { - - private final {实体名}Dao {实体名小写}Dao; - - /** - * 新增 - */ - public void addEntity({实体名} row) { - {实体名小写}Dao.insertSelective(row); - } - - /** - * 编辑 - */ - public void updateEntity({实体名} row) { - row.setUpdateTime(LocalDateTime.now()); - {实体名小写}Dao.updateByPrimaryKeySelective(row); - } - - /** - * 根据id查找数据(不存在则抛异常) - */ - public {实体名} exist(Long id) { - {实体名} data = {实体名小写}Dao.selectByPrimaryKey(id); - if (Objects.isNull(data)) { - throw new ServiceException(ErrorCode.DATA_NOT_EXISTS); - } - return data; - } - - /** - * 根据id查找数据 - */ - public {实体名} getById(Long id) { - return {实体名小写}Dao.selectByPrimaryKey(id); - } - - /** - * 根据ids批量查询 - */ - public List<{实体名}> selectByIds(List ids) { - return {实体名小写}Dao.selectByIds(ids); - } - - /** - * 条件查询列表 - */ - public List<{实体名}> getList({实体名}SearchQO qo) { - return {实体名小写}Dao.selectByQo(qo); - } - - /** - * 逻辑删除 - */ - public void removeById(Long id) { - {实体名小写}Dao.removeByPrimaryKey(id); - } -} -``` - -### Service 模板 -```java -package {basePackage}.service.{模块名}; - -import lombok.AllArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import {basePackage}.domain.entity.{实体名}; -import {basePackage}.domain.pojo.{模块名}.{实体名}DTO; -import {basePackage}.domain.pojo.{模块名}.{实体名}VO; -import {basePackage}.domain.pojo.{模块名}.{实体名}SearchQO; -import {basePackage}.mapping.{模块名}.{实体名}Mapper; -import {basePackage}.repository.{模块名}.{实体名}Repository; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; - -/** - * {实体描述} Service - * - * @author {author} - */ -@Service -@AllArgsConstructor -@Slf4j -public class {实体名}Service { - - private final {实体名}Mapper {实体名小写}Mapper; - private final {实体名}Repository {实体名小写}Repository; - - /** - * 新增 - */ - public Long add({实体名}DTO dto) { - {实体名} entity = {实体名小写}Mapper.toEntity(dto); - {实体名小写}Repository.addEntity(entity); - return entity.getId(); - } - - /** - * 编辑 - */ - public void update(Long id, {实体名}DTO dto) { - {实体名} entity = {实体名小写}Repository.exist(id); - {实体名小写}Mapper.updateEntity(dto, entity); - {实体名小写}Repository.updateEntity(entity); - } - - /** - * 详情 - */ - public {实体名}VO getInfo(Long id) { - {实体名} entity = {实体名小写}Repository.exist(id); - return {实体名小写}Mapper.toVO(entity); - } - - /** - * 列表查询 - */ - public List<{实体名}VO> getList({实体名}SearchQO qo) { - List<{实体名}> list = {实体名小写}Repository.getList(qo); - return {实体名小写}Mapper.toVOList(list); - } - - /** - * 删除 - */ - public void removeById(Long id) { - {实体名小写}Repository.exist(id); - {实体名小写}Repository.removeById(id); - } -} -``` - -### Controller 模板 -```java -package {basePackage}.web.admin.{模块名}; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import lombok.RequiredArgsConstructor; -import net.trueland.framework.web.result.ApiResult; -import {basePackage}.domain.pojo.{模块名}.{实体名}DTO; -import {basePackage}.domain.pojo.{模块名}.{实体名}VO; -import {basePackage}.domain.pojo.{模块名}.{实体名}SearchQO; -import {basePackage}.service.{模块名}.{实体名}Service; -import org.springframework.cloud.openfeign.SpringQueryMap; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -/** - * {实体描述} Controller - * - * @author {author} - */ -@Api(tags = "{实体描述}") -@RestController -@RequiredArgsConstructor -@RequestMapping("/{模块路径}") -public class {实体名}Controller { - - private final {实体名}Service {实体名小写}Service; - - @PostMapping - @ApiOperation(value = "新增") - public ApiResult add(@Validated @RequestBody {实体名}DTO dto) { - return ApiResult.ok({实体名小写}Service.add(dto)); - } - - @PostMapping("{id}") - @ApiOperation(value = "编辑") - public ApiResult update(@PathVariable Long id, @Validated @RequestBody {实体名}DTO dto) { - {实体名小写}Service.update(id, dto); - return ApiResult.ok(); - } - - @GetMapping("{id}") - @ApiOperation(value = "详情") - public ApiResult<{实体名}VO> getInfo(@PathVariable Long id) { - return ApiResult.ok({实体名小写}Service.getInfo(id)); - } - - @GetMapping - @ApiOperation(value = "列表查询") - public ApiResult> getList(@SpringQueryMap {实体名}SearchQO qo) { - return ApiResult.ok({实体名小写}Service.getList(qo)); - } - - @DeleteMapping("{id}") - @ApiOperation(value = "删除") - public ApiResult remove(@PathVariable Long id) { - {实体名小写}Service.removeById(id); - return ApiResult.ok(); - } -} -``` - -### MapStruct Mapper 模板 -```java -package {basePackage}.mapping.{模块名}; - -import {basePackage}.domain.entity.{实体名}; -import {basePackage}.domain.pojo.{模块名}.{实体名}DTO; -import {basePackage}.domain.pojo.{模块名}.{实体名}VO; -import org.mapstruct.Mapper; -import org.mapstruct.MappingTarget; - -import java.util.List; - -/** - * {实体描述} MapStruct映射器 - * - * @author {author} - */ -@Mapper(componentModel = "spring") -public interface {实体名}Mapper { - - {实体名} toEntity({实体名}DTO dto); - - void updateEntity({实体名}DTO dto, @MappingTarget {实体名} entity); - - {实体名}VO toVO({实体名} entity); - - List<{实体名}VO> toVOList(List<{实体名}> list); -} -``` - ---- - -## 生成文件清单 - -生成完成后,请列出所有生成的文件路径(使用检测到的 `{basePackage}` 转换为路径): - -- SQL文件(建议保存位置) -- Entity: `src/main/java/{basePackagePath}/domain/entity/{实体名}.java` -- DAO: `src/main/java/{basePackagePath}/domain/dao/{实体名}Dao.java` -- XML: `src/main/resources/mybatis/mapper/{实体名}Dao.xml` -- Repository: `src/main/java/{basePackagePath}/repository/{模块名}/{实体名}Repository.java` -- POJO: `src/main/java/{basePackagePath}/domain/pojo/{模块名}/` -- Mapper: `src/main/java/{basePackagePath}/mapping/{模块名}/{实体名}Mapper.java` -- Service: `src/main/java/{basePackagePath}/service/{模块名}/{实体名}Service.java` -- Controller: `src/main/java/{basePackagePath}/web/admin/{模块名}/{实体名}Controller.java` - ---- - -## 变量说明 - -| 变量 | 说明 | 获取方式 | -|-----|------|---------| -| `{basePackage}` | 项目基础包名 | 检测项目或询问用户 | -| `{basePackagePath}` | 包名转路径 | 将 `.` 替换为 `/` | -| `{author}` | 代码作者 | 检测项目或询问用户 | -| `{实体名}` | 实体类名(大驼峰) | 根据需求分析 | -| `{实体名小写}` | 实体变量名(小驼峰) | 首字母小写 | -| `{实体描述}` | 实体中文描述 | 根据需求分析 | -| `{模块名}` | 模块包名(小写) | 根据需求分析 | -| `{模块路径}` | API路径(短横线分隔) | 根据模块名转换 | diff --git a/.claude/skills/project-conventions/SKILL.md b/.claude/skills/project-conventions/SKILL.md deleted file mode 100644 index 3a2ba68a3a..0000000000 --- a/.claude/skills/project-conventions/SKILL.md +++ /dev/null @@ -1,687 +0,0 @@ ---- -name: project-conventions -description: 项目编码规范指南,遵循阿里巴巴Java开发手册,确保代码风格统一 ---- - -# project-conventions - 项目编码规范 - -本规范基于《阿里巴巴Java开发手册》,结合项目实际情况制定,适用于本项目所有Java代码开发。 - -## 一、项目结构规范 - -### 1.1 包结构 - -``` -net.trueland.tshop.retail.system.center -├── domain/ # 领域层 -│ ├── entity/ # 数据库实体类 -│ ├── dao/ # MyBatis Mapper接口 -│ └── pojo/ # 数据传输对象 -│ └── {模块名}/ # 按功能模块分包 -│ ├── {实体}DTO.java # 数据传输对象 -│ ├── {实体}VO.java # 视图对象 -│ └── {实体}SearchQO.java # 查询对象 -├── mapping/ # MapStruct映射器 -│ └── {模块名}/ -├── repository/ # 仓储层 -│ └── {模块名}/ -├── service/ # 业务逻辑层 -│ └── {模块名}/ -├── web/ # 控制器层 -│ ├── admin/ # 管理端API -│ ├── tenant/ # 租户端API -│ ├── app/ # C端API -│ └── feign/ # Feign接口 -├── client/ # 第三方服务客户端 -│ ├── feign/ # Feign客户端 -│ ├── retrofit/ # Retrofit客户端 -│ ├── config/ # 客户端配置 -│ └── model/ # 客户端模型 -├── common/ # 公共模块 -│ ├── constants/ # 常量类 -│ ├── enums/ # 枚举类 -│ ├── utils/ # 工具类 -│ └── ErrorCode.java # 错误码 -├── aspect/ # AOP切面 -├── annotation/ # 自定义注解 -├── manager/ # 管理器 -└── config/ # 配置类 -``` - -### 1.2 资源文件结构 - -``` -src/main/resources/ -├── mybatis/ -│ └── mapper/ # MyBatis XML映射文件 -│ └── {实体名}Dao.xml -├── application.yml # 主配置文件 -├── application-{env}.yml # 环境配置文件 -└── bootstrap.yml # 启动配置文件 -``` - ---- - -## 二、命名规范 - -### 2.1 包命名 - -- **格式**:全部小写,使用点分隔 -- **规则**:反向域名 + 项目名 + 模块名 -- **示例**:`net.trueland.tshop.retail.system.center.service.application` - -### 2.2 类命名 - -| 类型 | 命名格式 | 示例 | -|------|---------|------| -| Entity(实体类) | `{功能名}` | `Application`, `OrgUser` | -| DAO(数据访问) | `{功能名}Dao` | `ApplicationDao`, `OrgUserDao` | -| Repository(仓储) | `{功能名}Repository` | `ApplicationRepository` | -| Service(服务) | `{功能名}Service` | `ApplicationService` | -| Controller(控制器) | `{功能名}Controller` | `ApplicationController` | -| Mapper(对象映射) | `{功能名}Mapper` | `ApplicationMapper` | -| DTO(传输对象) | `{功能名}DTO` | `ApplicationDTO` | -| VO(视图对象) | `{功能名}VO` | `ApplicationVO` | -| QO(查询对象) | `{功能名}SearchQO` | `ApplicationSearchQO` | -| Enum(枚举) | `{功能名}Enum` | `EnableEnum`, `StatusEnum` | -| Constants(常量) | `{功能名}Constants` | `SystemConstants` | -| Utils(工具) | `{功能名}Utils` | `DateUtils`, `StringUtils` | -| Config(配置) | `{功能名}Config` | `WebConfig`, `RedisConfig` | -| Aspect(切面) | `{功能名}Aspect` | `LogAspect` | - -### 2.3 方法命名 - -| 操作类型 | 命名前缀 | 示例 | -|---------|---------|------| -| 查询单个 | `get`, `find`, `query` | `getById()`, `findByName()` | -| 查询列表 | `list`, `select` | `listByQo()`, `selectAll()` | -| 新增 | `add`, `insert`, `create` | `add()`, `insertSelective()` | -| 修改 | `update`, `modify`, `edit` | `update()`, `updateById()` | -| 删除 | `delete`, `remove` | `deleteById()`, `removeByIds()` | -| 判断存在 | `exist`, `check`, `is` | `exist()`, `checkExists()` | -| 统计 | `count` | `countByStatus()` | - -### 2.4 变量命名 - -- **格式**:小驼峰(lowerCamelCase) -- **示例**:`applicationName`, `createTime`, `isDeleted` -- **禁止**:拼音命名、无意义缩写 - -### 2.5 常量命名 - -- **格式**:全大写 + 下划线分隔 -- **示例**:`MAX_PAGE_SIZE`, `DEFAULT_STATUS` - ---- - -## 三、数据库规范 - -### 3.1 表命名 - -- **格式**:`s_` 或 `t_` 前缀 + 蛇形命名 -- **前缀说明**: - - `s_` - 系统表 - - `t_` - 业务表 -- **示例**:`s_application`, `s_org_user`, `t_order` - -### 3.2 字段命名 - -- **格式**:全小写 + 下划线分隔(蛇形命名) -- **示例**:`application_name`, `create_time`, `is_deleted` - -### 3.3 必备字段 - -每个表必须包含以下基础字段: - -| 字段名 | 类型 | 说明 | -|-------|------|------| -| `id` | BIGINT | 主键ID,自增 | -| `tenant_id` | BIGINT | 租户ID | -| `create_time` | DATETIME | 创建时间 | -| `update_time` | DATETIME | 更新时间 | -| `is_deleted` | TINYINT | 逻辑删除标记(0否/1是) | - -### 3.4 字段类型映射 - -| 数据库类型 | Java类型 | 说明 | -|-----------|---------|------| -| BIGINT | Long | 主键、ID类型 | -| INT/TINYINT | Integer | 状态、计数 | -| VARCHAR | String | 字符串 | -| DATETIME/TIMESTAMP | LocalDateTime | 时间类型 | -| DECIMAL | BigDecimal | 金额类型 | -| TEXT | String | 长文本 | - ---- - -## 四、分层规范 - -### 4.1 架构分层 - -``` -Controller层(Web层) - ↓ 调用 -Service层(业务逻辑层) - ↓ 调用 -Repository层(数据仓储层) - ↓ 调用 -DAO层(数据访问层) - ↓ 操作 -Database(数据库) -``` - -### 4.2 各层职责 - -#### Controller层 -- 接收HTTP请求,参数校验 -- 调用Service处理业务 -- 返回统一响应格式 `ApiResult` -- **禁止**:包含业务逻辑 - -```java -@Api(tags = "应用管理") -@RestController -@RequiredArgsConstructor -@RequestMapping("/application") -public class ApplicationController { - - private final ApplicationService applicationService; - - @PostMapping("/add") - @ApiOperation(value = "新增应用") - public ApiResult add(@Validated @RequestBody ApplicationDTO dto) { - return ApiResult.ok(applicationService.add(dto)); - } -} -``` - -#### Service层 -- 实现业务逻辑 -- 事务控制(@Transactional) -- 对象转换(调用Mapper) -- 异常处理 - -```java -@Service -@AllArgsConstructor -@Slf4j -public class ApplicationService { - - private final ApplicationMapper applicationMapper; - private final ApplicationRepository applicationRepository; - - public Long add(ApplicationDTO dto) { - Application entity = applicationMapper.toEntity(dto); - applicationRepository.addEntity(entity); - return entity.getId(); - } - - @Transactional(rollbackFor = Exception.class) - public void batchUpdate(List dtoList) { - // 事务操作 - } -} -``` - -#### Repository层 -- 封装DAO操作 -- 数据存在性验证 -- 异常转换 -- 复杂查询组装 - -```java -@Repository -@RequiredArgsConstructor -public class ApplicationRepository { - - private final ApplicationDao applicationDao; - - public void addEntity(Application row) { - applicationDao.insertSelective(row); - } - - public Application exist(Long id) { - Application data = applicationDao.selectByPrimaryKey(id); - if (Objects.isNull(data)) { - throw new ServiceException(ErrorCode.DATA_NOT_EXISTS); - } - return data; - } - - public Application getById(Long id) { - return applicationDao.selectByPrimaryKey(id); - } -} -``` - -#### DAO层 -- 纯数据访问接口 -- MyBatis Mapper接口 -- 不包含业务逻辑 - -```java -@Mapper -public interface ApplicationDao { - - int insert(Application row); - - int insertSelective(Application row); - - Application selectByPrimaryKey(Long id); - - int updateByPrimaryKeySelective(Application row); - - int deleteByPrimaryKey(Long id); - - List selectByQo(@Param(value = "qo") ApplicationSearchQO qo); -} -``` - ---- - -## 五、注解规范 - -### 5.1 类级注解 - -```java -// Controller -@Api(tags = "模块描述") -@RestController -@RequiredArgsConstructor -@RequestMapping("/path") - -// Service -@Service -@AllArgsConstructor -@Slf4j - -// Repository -@Repository -@RequiredArgsConstructor - -// DAO -@Mapper - -// Entity/DTO/VO -@Data - -// 配置类 -@Configuration - -// 切面 -@Aspect -@Component -``` - -### 5.2 方法级注解 - -```java -// Controller方法 -@PostMapping("/add") -@ApiOperation(value = "操作描述") - -// 事务控制 -@Transactional(rollbackFor = Exception.class) - -// 异常处理 -@SneakyThrows -``` - -### 5.3 字段级注解 - -```java -// 文档注解 -@ApiModelProperty("字段描述") - -// 验证注解 -@NotNull(message = "xxx不能为空") -@NotEmpty(message = "xxx不能为空") -@NotBlank(message = "xxx不能为空") -@Size(max = 100, message = "xxx长度不能超过100") - -// MyBatis参数 -@Param(value = "paramName") -``` - -### 5.4 MapStruct注解 - -```java -@Mapper(componentModel = "spring") -public interface ApplicationMapper { - - Application toEntity(ApplicationDTO dto); - - void updateEntity(ApplicationDTO dto, @MappingTarget Application entity); - - ApplicationVO toVO(Application entity); - - List toVOList(List list); - - @Mapping(target = "targetField", source = "sourceField") - SomeVO customMapping(SomeEntity entity); -} -``` - ---- - -## 六、注释规范 - -### 6.1 类注释 - -```java -/** - * 类功能描述 - * - * @author 作者名 - */ -public class ClassName { -} -``` - -### 6.2 方法注释 - -```java -/** - * 方法功能描述 - * - * @param paramName 参数说明 - * @return 返回值说明 - */ -public ReturnType methodName(ParamType paramName) { -} -``` - -### 6.3 字段注释 - -```java -/** - * 字段描述(可选) - */ -@ApiModelProperty("字段描述") -private String fieldName; -``` - -### 6.4 行内注释 - -```java -// 单行注释,说明下一行代码的作用 -doSomething(); - -/* - * 多行注释 - * 说明复杂逻辑 - */ -``` - ---- - -## 七、异常处理规范 - -### 7.1 错误码定义 - -```java -@Getter -@AllArgsConstructor -public enum ErrorCode implements IRespCode { - - // 通用错误码 10000-10999 - SYSTEM_ERROR(10000, HttpStatus.INTERNAL_SERVER_ERROR, "系统错误"), - PARAM_ERROR(10001, HttpStatus.BAD_REQUEST, "参数错误"), - DATA_NOT_EXISTS(10002, HttpStatus.OK, "数据不存在"), - - // 业务错误码 11000-11999 - APPLICATION_NOT_EXISTS(11000, HttpStatus.OK, "应用不存在"), - APPLICATION_NAME_EXISTS(11001, HttpStatus.OK, "应用名称已存在"), - ; - - private final Integer code; - private final HttpStatus httpStatus; - private final String message; -} -``` - -### 7.2 异常抛出 - -```java -// Repository层抛出业务异常 -public Application exist(Long id) { - Application data = applicationDao.selectByPrimaryKey(id); - if (Objects.isNull(data)) { - throw new ServiceException(ErrorCode.DATA_NOT_EXISTS); - } - return data; -} - -// Service层抛出业务异常 -public void add(ApplicationDTO dto) { - if (checkNameExists(dto.getName())) { - throw new ServiceException(ErrorCode.APPLICATION_NAME_EXISTS); - } - // ... -} -``` - -### 7.3 统一响应格式 - -```java -// 成功响应 -return ApiResult.ok(data); -return ApiResult.ok(); - -// 失败响应 -return ApiResult.err(ErrorCode.PARAM_ERROR); -return ApiResult.err(code, message); -``` - ---- - -## 八、工具类使用规范 - -### 8.1 对象工具(Hutool) - -```java -import cn.hutool.core.util.ObjectUtil; - -// 判空 -ObjectUtil.isNull(obj) -ObjectUtil.isNotNull(obj) -ObjectUtil.isEmpty(collection) -ObjectUtil.isNotEmpty(collection) - -// 相等判断 -ObjectUtil.equal(obj1, obj2) -``` - -### 8.2 字符串工具 - -```java -import org.apache.commons.lang3.StringUtils; - -// 判空 -StringUtils.isEmpty(str) -StringUtils.isNotEmpty(str) -StringUtils.isBlank(str) -StringUtils.isNotBlank(str) -``` - -### 8.3 集合工具 - -```java -import cn.hutool.core.collection.CollUtil; - -// 判空 -CollUtil.isEmpty(list) -CollUtil.isNotEmpty(list) - -// 转换 -CollUtil.newArrayList(items) -``` - -### 8.4 JSON工具 - -```java -import com.alibaba.fastjson.JSON; - -// 序列化 -String json = JSON.toJSONString(obj); - -// 反序列化 -Object obj = JSON.parseObject(json, Class.class); -List list = JSON.parseArray(json, Class.class); -``` - ---- - -## 九、日志规范 - -### 9.1 日志级别 - -| 级别 | 使用场景 | -|------|---------| -| ERROR | 系统错误、异常 | -| WARN | 警告信息、潜在问题 | -| INFO | 关键业务流程、重要操作 | -| DEBUG | 调试信息 | - -### 9.2 日志使用 - -```java -@Slf4j -public class ApplicationService { - - public void process() { - log.info("开始处理应用, applicationId: {}", applicationId); - - try { - // 业务逻辑 - log.debug("处理详情: {}", details); - } catch (Exception e) { - log.error("处理应用失败, applicationId: {}, error: {}", applicationId, e.getMessage(), e); - throw new ServiceException(ErrorCode.SYSTEM_ERROR); - } - - log.info("应用处理完成, applicationId: {}", applicationId); - } -} -``` - -### 9.3 日志规范 - -- 使用占位符 `{}` 而非字符串拼接 -- 异常日志必须包含异常堆栈 -- 敏感信息(密码、token)禁止打印 -- 日志内容应包含关键业务标识 - ---- - -## 十、数据类型规范 - -| 场景 | Java类型 | 说明 | -|------|---------|------| -| 主键ID | Long | 64位整数 | -| 状态/类型 | Integer | 使用枚举值 | -| 布尔值 | Integer | 0/1表示 | -| 时间 | LocalDateTime | 不使用Date | -| 金额 | Long | 以分为单位 | -| 精确计算 | BigDecimal | 财务计算 | -| 字符串 | String | - | -| 集合 | List | 优先使用List | - ---- - -## 十一、编码禁忌 - -1. **禁止**使用魔法数字,必须定义常量或枚举 -2. **禁止**在循环中进行数据库操作 -3. **禁止**捕获异常后不处理(空catch块) -4. **禁止**使用System.out.println,使用日志框架 -5. **禁止**在Controller层写业务逻辑 -6. **禁止**使用拼音命名 -7. **禁止**使用过时的Date类,使用LocalDateTime -8. **禁止**直接使用HashMap存储业务数据,使用DTO/VO -9. **禁止**硬编码配置信息,使用配置文件 -10. **禁止**返回null集合,返回空集合 - ---- - -## 十二、最佳实践 - -### 12.1 依赖注入 - -```java -// 推荐:构造函数注入 -@RequiredArgsConstructor -public class ApplicationService { - private final ApplicationRepository applicationRepository; -} - -// 不推荐:字段注入 -@Autowired -private ApplicationRepository applicationRepository; -``` - -### 12.2 判空处理 - -```java -// 推荐 -if (Objects.isNull(obj)) { } -if (ObjectUtil.isEmpty(list)) { } - -// 不推荐 -if (obj == null) { } -if (list == null || list.size() == 0) { } -``` - -### 12.3 Optional使用 - -```java -// 查询可能为空的数据 -public Optional findById(Long id) { - return Optional.ofNullable(applicationDao.selectByPrimaryKey(id)); -} - -// 使用 -applicationService.findById(id) - .orElseThrow(() -> new ServiceException(ErrorCode.DATA_NOT_EXISTS)); -``` - -### 12.4 Stream操作 - -```java -// 集合转换 -List ids = list.stream() - .map(Application::getId) - .collect(Collectors.toList()); - -// 过滤 -List filtered = list.stream() - .filter(app -> Objects.equals(app.getStatus(), 1)) - .collect(Collectors.toList()); - -// 分组 -Map> grouped = list.stream() - .collect(Collectors.groupingBy(Application::getType)); -``` - ---- - -## 十三、技术栈 - -| 类别 | 技术 | 版本 | -|------|------|------| -| 基础框架 | Spring Boot | 2.4.2 / 2.6.13 | -| 微服务 | Spring Cloud | - | -| ORM框架 | MyBatis | - | -| 对象映射 | MapStruct | - | -| 工具库 | Lombok | - | -| 工具库 | Hutool | - | -| JSON处理 | FastJSON | - | -| API文档 | Swagger/Knife4j | - | -| 数据库 | MySQL | 5.7/8.0 | -| 缓存 | Redis | - | - ---- - -## 使用说明 - -本规范作为项目开发的标准参考,所有代码提交前应确保符合以上规范。使用 `/crud` 命令生成的代码已自动遵循本规范。 diff --git a/.gitignore b/.gitignore index 7cd5f03bd4..124b507aa4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,41 +1,27 @@ -*.class -.DS_Store -application.pid - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ - -# Package Files # -*.jar -*.war -*.ear - -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* - -# Eclipse -.classpath -.project -target -bin -classes -.settings -.factorypath -doc2 -doc1 -*bak -log -logs -target -*.zip - -node_modules - -# Idea -.idea -*.iml -.mvn - -# git -*.orig -jun_spring_plugin \ No newline at end of file +*.class +.DS_Store +application.pid + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# Eclipse +.classpath +.project +target +.settings + +# Idea +.idea +*.iml + +# git +*.orig \ No newline at end of file diff --git a/PROJECT_PLAN_SUMMARY.md b/PROJECT_PLAN_SUMMARY.md deleted file mode 100644 index 13263e2a37..0000000000 --- a/PROJECT_PLAN_SUMMARY.md +++ /dev/null @@ -1,220 +0,0 @@ -# jun_java_plugin 项目规划摘要 - -**规划时间**: 2026-04-13 -**项目类型**: Java Spring Boot 企业级组件库 -**工作目录**: D:\workspace_github_v2\10技术基础层\jun_java_plugin - ---- - -## 📋 项目概述 - -jun_java_plugin 是一个全面的 Java 企业级开发组件库,目标是成为: -- ✅ 完整的 Java 技术栈参考仓库 -- ✅ 200+ 开箱即用的开发组件和示例 -- ✅ Java 开发者和 AI 助手的代码参考库 -- ✅ 涵盖 Java 基础、Spring Boot、Spring Cloud 全生态 - -## 📊 当前状态 - -### 模块统计 -| 主要模块 | 子模块数量 | 说明 | -|---------|-----------|------| -| jun_java_plugins | 65 | 原生 Java 组件(无 Spring 依赖) | -| jun_springboot_plugin | 100 | Spring Boot 集成示例 | -| jun_springboot_starter | 25 | 自定义 Spring Boot Starter | -| jun_springcloud_plugin | 1 | Spring Cloud 微服务组件 | -| java_project_template | 11 | Maven 项目模板 | -| **总计** | **202** | | - -### 技术栈 -- **Java**: JDK 1.8 / JDK 11 -- **构建工具**: Maven 3.5+ -- **Spring Boot**: 2.4.2, 2.6.13 (混合版本) -- **持久化**: MyBatis, MyBatis-Plus, Hibernate, JPA -- **缓存**: Redis, Ehcache -- **消息队列**: RabbitMQ, RocketMQ, Kafka -- **任务调度**: Quartz, XXL-Job, Elastic-Job -- **工具库**: Lombok, Hutool, Guava, Apache Commons - -## 📁 已创建的脚手架文件 - -1. **task_list.json** (45个任务) - - 完整的项目完善任务规划 - - 6个阶段,优先级从 P1 到 P5 - - 包含任务依赖关系和验证步骤 - -2. **init.sh / init.bat** - - 环境检查脚本(Linux/Mac 和 Windows) - - 检查 Java、Maven、Git 等工具 - - 统计模块数量 - - 可选的编译检查 - -3. **claude-progress.txt** - - 进度跟踪文档 - - 记录架构决策和会话历史 - - 下一位执行者的注意事项 - -4. **PROJECT_PLAN_SUMMARY.md** (本文件) - - 项目规划摘要 - - 快速了解项目状态和计划 - -## 🎯 任务规划 (45个任务) - -### 第一阶段: 分析评估 (T001-T009, Priority 1-2) -**目标**: 全面了解项目现状 - -| 任务ID | 任务 | 依赖 | -|-------|------|------| -| T001 | 创建项目分析工具和脚本 | - | -| T002 | 分析 jun_java_plugins 模块结构(65个) | T001 | -| T003 | 分析 jun_springboot_plugin 模块结构(100个) | T001 | -| T004 | 分析 jun_springboot_starter 自定义启动器(25个) | T001 | -| T005 | 分析 jun_springcloud_plugin 和项目模板 | T001 | -| T006 | 编译测试 jun_java_plugins 模块 | T002 | -| T007 | 编译测试 jun_springboot_plugin 模块 | T003 | -| T008 | 编译测试 jun_springboot_starter 模块 | T004 | -| T009 | 编译测试其他模块 | T005 | - -**产出**: 5个分析文档 + 4个编译报告 - -### 第二阶段: 覆盖度评估 (T010-T020, Priority 2-3) -**目标**: 识别缺失和冗余 - -| 任务ID | 任务 | 产出 | -|-------|------|------| -| T010 | 评估 Java 基础技术栈覆盖度 | java_core_coverage_report.md | -| T011 | 评估数据库和持久化技术覆盖度 | database_coverage_report.md | -| T012 | 评估 Web 和微服务技术覆盖度 | web_microservice_coverage_report.md | -| T013 | 评估安全和认证技术覆盖度 | security_coverage_report.md | -| T014 | 评估消息队列和任务调度覆盖度 | messaging_scheduling_coverage_report.md | -| T015 | 评估工具类库和第三方集成覆盖度 | utilities_integrations_coverage_report.md | -| T016 | 识别重复和冗余模块 | redundancy_analysis_report.md | -| T017 | 识别缺失的核心技术模块 | missing_modules_report.md | -| T018 | 评估文档完整性 | documentation_status_report.md | -| T019 | 评估测试覆盖率 | test_coverage_report.md | -| T020 | 创建项目全局技术栈清单 | technology_stack_inventory.md | - -**产出**: 11个评估报告 - -### 第三阶段: 文档完善 (T021-T022, T039-T042, Priority 3-5) -**目标**: 提升用户体验 - -| 任务ID | 任务 | 产出 | -|-------|------|------| -| T021 | 创建模块索引和导航文档 | MODULE_INDEX.md | -| T022 | 创建快速开始指南 | QUICK_START_GUIDE.md | -| T039 | 更新主 README 文档 | README.md | -| T040 | 创建贡献指南 | CONTRIBUTING.md | -| T041 | 创建最佳实践文档 | BEST_PRACTICES.md | -| T042 | 创建技术选型指南 | TECH_SELECTION_GUIDE.md | - -**产出**: 6个核心文档 - -### 第四阶段: 修复和补充 (T023-T029, Priority 4-5) -**目标**: 修复问题,补充缺失 - -| 任务ID | 任务 | 说明 | -|-------|------|------| -| T023 | 修复 jun_java_plugins 编译错误 | 90%+ 模块可编译 | -| T024 | 修复 jun_springboot_plugin 编译错误 | 版本兼容性优化 | -| T025 | 修复 jun_springboot_starter 配置问题 | spring.factories 配置 | -| T026 | 补充缺失的 Java 基础模块 | NIO, Stream API, JUC | -| T027 | 补充缺失的数据库技术模块 | ElasticSearch, ClickHouse | -| T028 | 补充缺失的微服务技术模块 | gRPC, Service Mesh | -| T029 | 补充缺失的新技术模块 | Docker/K8s, CI/CD | - -**产出**: 修复编译问题 + 10-20个新模块 - -### 第五阶段: 质量提升 (T030-T036, Priority 4-5) -**目标**: 提升代码质量 - -| 任务ID | 任务 | 目标 | -|-------|------|------| -| T030 | 完善模块 README 文档 | 100% 文档覆盖 | -| T031 | 为核心模块添加 Swagger API 文档 | API 文档化 | -| T032 | 为核心模块添加单元测试 | 60%+ 测试覆盖率 | -| T033 | 添加集成测试示例 | Spring Boot Test | -| T034 | 清理和合并冗余模块 | 减少 5-10 个模块 | -| T035 | 统一代码风格和规范 | Checkstyle 配置 | -| T036 | 优化依赖管理 | dependencyManagement | - -**产出**: 高质量代码库 - -### 第六阶段: 集成和部署 (T037-T038, T043-T045, Priority 5) -**目标**: 完成交付 - -| 任务ID | 任务 | 说明 | -|-------|------|------| -| T037 | 创建示例应用集合 | 博客系统、电商后台等 | -| T038 | 创建在线演示环境 | Docker Compose | -| T043 | 创建 CI/CD 配置 | GitHub Actions | -| T044 | 生成项目统计报告 | 关键指标汇总 | -| T045 | 生成完整项目文档汇总 | docs 目录组织 | - -**产出**: 可运行示例 + 完整文档中心 - -## 📈 关键指标和目标 - -| 指标 | 当前值 | 目标值 | -|-----|--------|--------| -| 模块总数 | ~202 | 210-220 | -| 文档覆盖率 | 未知 | 100% | -| 编译成功率 | 未知 | 90%+ | -| 测试覆盖率 | 低 | 60%+ | -| 技术栈覆盖 | 不完整 | 95%+ | - -## ⚠️ 风险和挑战 - -1. **模块数量庞大**: 202个模块,全面分析耗时较长 -2. **依赖冲突**: 不同版本的依赖冲突需要谨慎处理 -3. **版本兼容性**: 混合 Spring Boot 版本带来的兼容性问题 -4. **文档工作量**: 每个模块都需要编写完整文档 -5. **测试补充**: 大量模块缺少测试,补充工作量大 - -## 🚀 下一步行动 - -### 立即执行 -1. **运行环境检查**: `bash init.sh` 或 `init.bat` -2. **开始第一阶段任务**: T001-T005 (创建分析工具和遍历模块) -3. **编译测试**: T006-T009 (记录编译状态) - -### 推荐工作流程 -```bash -# 1. 环境检查 -bash init.sh - -# 2. 创建分析脚本目录 -mkdir scripts - -# 3. 开始执行任务 -# 按照 task_list.json 中的依赖顺序执行 - -# 4. 定期更新进度 -# 编辑 claude-progress.txt 记录进展 - -# 5. 及时提交代码 -git add . -git commit -m "feat: 完成 xxx 任务" -``` - -## 📚 参考文档 - -- **CLAUDE.md**: 项目开发规范和说明 -- **task_list.json**: 完整的任务清单 -- **claude-progress.txt**: 进度跟踪和会话记录 -- **README.md**: 项目主文档 -- **/project-conventions**: 编码规范技能 -- **/crud**: 代码生成技能 - -## 📞 联系方式 - -- GitHub Issues: https://github.com/wujun728/jun_java_plugin/issues -- 项目维护者: wujun728 - ---- - -**规划完成日期**: 2026-04-13 -**规划者**: Claude Code (Opus 4.6) -**状态**: ✅ 规划完成,等待执行 - -**下一位执行者**: 请从 T001 开始执行任务,祝你好运! 🎉 diff --git a/README-PLAN.md b/README-PLAN.md new file mode 100644 index 0000000000..1a42ac120c --- /dev/null +++ b/README-PLAN.md @@ -0,0 +1 @@ +待补充 \ No newline at end of file diff --git a/README.md b/README.md index 76840f7668..2bed571bb6 100644 --- a/README.md +++ b/README.md @@ -1,408 +1,71 @@ -### `jun_java_plugin` 项目 +### `jun_plugin` 项目 + +#### 项目说明 +jun_plugin 整合Java企业级各种开发组件、开箱即用、不写重复代码 + +#### `笔者其他项目` 功能实现&使用 +- jun_springboot:[点击查看](https://github.com/wujun728/jun_springboot) +- jun_springcloud:[点击查看](https://github.com/wujun728/jun_springcloud) +- jedp:[点击查看](https://github.com/wujun728/jedp) + +#### 基础篇:企业级开发组件功能列表(jun_plugin) +- 【fastdfs-client-java】[fastdfs的源码,编辑jar,引入maven本地,maven仓库没这个jar包](https://github.com/wujun728/jun_plugin) +- 【jun_activiti】[原生集成activity工作流,完成工作流常用操作](https://github.com/wujun728/jun_plugin) +- 【jun_ajax】[完成ajax操作,前端及后端的ajax](https://github.com/wujun728/jun_plugin) +- 【jun_aliyun_sms】[发送阿里云短信及验证码等](https://github.com/wujun728/jun_plugin) +- 【jun_cron】 [cron表达式的java的实现及调度](https://github.com/wujun728/jun_plugin) +- 【jun_dao_hibernate】[原生集成hibernate及使用](https://github.com/wujun728/jun_plugin) +- 【jun_datasource】[原生集成各种JDBC DataSource数据源](https://github.com/wujun728/jun_plugin) +- 【jun_dbutil】[原生集成Apache 的Dbutils完成单表及多表的增删改查](https://github.com/wujun728/jun_plugin) +- 【jun_designpattern】[23种涉及模式的Java实现](https://github.com/wujun728/jun_plugin) +- 【jun_distributed_session】[分布式Session实现及配置持久化等](https://github.com/wujun728/jun_plugin) +- 【jun_email】[原生邮件发送、纯文本、HTML邮件、带附件的邮件](https://github.com/wujun728/jun_plugin) +- 【jun_executor】[原生的并发多线程demo操作](https://github.com/wujun728/jun_plugin) +- 【jun_fileupload】[原生的文件上传及下载操作的实现基于common fileupload](https://github.com/wujun728/jun_plugin) +- 【jun_freemarker】[原生集成freemarker模板引擎,数据+模板=输出,可输出代码生成器](https://github.com/wujun728/jun_plugin) +- 【jun_httpclient】[原生集成httpclient,发送http请求、下载文件等](https://github.com/wujun728/jun_plugin) +- 【jun_image】[原生图片操作包、包括图片上传、下载、展示、缩略图等](https://github.com/wujun728/jun_plugin) +- 【jun_jdbc】[原生JDBC操作,简单封装,需要的可以看下](https://github.com/wujun728/jun_plugin) +- 【jun_jdk】[JDK原生demo代码,了解的越多才会了解的越深](https://github.com/wujun728/jun_plugin) +- 【jun_json】[集成jackjson及fastjson及jons-lib及Gson等实现JSON生成及序列化&反序列化](https://github.com/wujun728/jun_plugin) +- 【jun_jsoup】[HTM标记语言解析包,完成HTML解析、主要爬虫使用,解析HTML渲染数据](https://github.com/wujun728/jun_plugin) +- 【jun_leetcode】[算法刷题大全](https://github.com/wujun728/jun_plugin) +- 【jun_lucene】[老牌搜索引擎、可以看下](https://github.com/wujun728/jun_plugin) +- 【jun_poi】[原生POI完成Excel文件的导入、解析、导出及持久化等](https://github.com/wujun728/jun_plugin) +- 【jun_qrcode】[二维码生成器](https://github.com/wujun728/jun_plugin) +- 【jun_quartz】[job任务调度](https://github.com/wujun728/jun_plugin) +- 【jun_rpc】[原生RPC调用、客户端及服务端](https://github.com/wujun728/jun_plugin) +- 【jun_servlet】[原生Servlet、WEB开发的基础](https://github.com/wujun728/jun_plugin) +- 【jun_sso】[原生SSO的实现单点登录](https://github.com/wujun728/jun_plugin) +- 【jun_test】[JUNIT框架及TestNG框架](https://github.com/wujun728/jun_plugin) +- 【jun_utils】[常用开发工具集、非常重要!!!](https://github.com/wujun728/jun_plugin) +- 【jun_webservice】[原生的webservice调用、基于apache cxf实现服务调用及发布](https://github.com/wujun728/jun_plugin) +- 【jun_webservlet】[原生Servlet 3.0的实现](https://github.com/wujun728/jun_plugin) +- 【jun_websocket】[原生的WebSocket的实现长链接](https://github.com/wujun728/jun_plugin) +- 【jun_xml】[原生的XML解析及生产XML、提供SAX、DOM、DOM4J解析方式](https://github.com/wujun728/jun_plugin) +- 【jun_zxing】[Google二维码生成器](https://github.com/wujun728/jun_plugin) -### 项目说明 -jun_java_plugin 整合Java企业级各种开发组件、开箱即用、不写重复代码,包含基础Java基础开发组件,Spring企业级开发组,SpringBoot常用开发组件、SpringCloud开发组件 - -### 功能清单 - -1. 集成Java常用开发组件:**java_plugin**,Java常用开发组件,当前**包含60+类各种**lib类库示例与文档。 -2. 集成SpringBoot常用开发组件:**springboot_plugin**,当前**集成100+**种类库示例与文档。 -3. 集成Maven常用项目模板:**maven_template**,当前集成了**10种模板**,含单体及多模块、SSH、SSM、Boot、Cloud等。 -4. 集成SpringCloud常用开发组件:**springcloud_plugin**,含个版本netflix、alibaba、dubbo等,主要为示例与文档。 -5. 集成Spring常用开发组件:**spring_plugin**,企业级开发常用组件,当前**集成100+种**lib类库示例与文档(Spring的XML时代)。 - - -#### 基础篇:企业级开发组件(开发组件、代码生成、前端组件) [jun_java_plugin] - -> Java基础系开发组件-通用篇(jun_plugin) 常用开发组件,基础公共lib包的组件不依赖Spring的组件,主要供原生开发的项目集成: - - - - -#### 工程截图(组件较多,随意截了几个,所有组件正常编译运行) - - - - - - - - - - -
-
-
-
-
- - - -#### 模块清单(组件较多,随意写了几个,具体见代码明细) - -【jun_activiti】[流程引擎,Activiti工作流,完成工作流常用操作]
-【jun_ajax】[完成ajax操作,前端及后端的ajax]
-【jun_aliyun_sms】[短信工具,集成阿里云短信、腾讯云短信发送及验证码等功能]
-【jun_apache_commons】[ Common工具集,集成Apache通用工具集]
-【jun_api】[ API中心,API注册测试校验管控鉴权中心]
-【jun_cron】 [cron表达式的java的实现及调度]
-【jun_cache】[分布式缓存,缓存工具,集成Redis分布式缓存功能]
-【jun_camel】[消息路由,ESB服务总线,EIP框架,处理不同系统之间的消息传输]
-【jun_captcha】[ 验证码工具,GoogleKaptcha及各种验证码工具]
-【jun_crawler】[ 爬虫引擎,网络爬虫引擎,Xpath解析HTML]
-【jun_datasource_cluster】[原生集成各种JDBC DataSource数据源,分布式数据源,Druid、DBCP等数据源]
-【jun_dbutil】[原生集成Apache 的Dbutils完成单表及多表的增删改查,原生JDBC操作,简单封装]
-【jun_demo】[ DEMO测试,DEMO测试工具集]
-【jun_designpattern】[23种涉及模式的Java实现]
-【jun_drools】[ 规则引擎,规则引擎的各种demo及工具]
-【jun_dubbo】[ Dubbo,阿里巴巴Dubbo RPC demo及工具集]
-【jun_executor】[原生的并发多线程demo操作]
-【jun_email】[原生邮件发送、纯文本、HTML邮件、带附件的邮件]
-【jun_excel】[ Excel工具集,Excel导入导出工具集]
-【jun_fileupload】[原生的文件上传及下载操作的实现基于common fileupload,OSS上传下载]
-【jun_freemarker】[原生集成freemarker模板引擎,数据+模板=输出,可输出代码生成器]
-【jun_guava】[ GoogleGuava,谷歌工具集,集合工具,缓存工具]
-【jun_guice】[ GoogleGuice,谷歌依赖注入框架(配合Servlet3.0+Dbutil)]
-【jun_gzip】[ Gzip压缩,Gzip压缩及解压缩]
-【jun_hibernate】[原生集成hibernate及使用,Hibernate,JPA框架,持久化框架]
-【jun_httpclient】[原生集成httpclient,发送http请求、下载文件等,配合Postman发起各种HTTP请求]
-【jun_image】[原生图片操作包、包括图片上传、下载、展示、转码、压缩转Base64、缩略图等]
-【jun_jdk】[JDK原生demo代码,了解的越多才会了解的越深]
-【jun_jdbc】[原生JDBC操作,简单封装,需要的可以看下]
-【jun_j2cache】[ 缓存j2cache,缓存工具,OSCHACHE使用的缓存工具]
-【jun_jar2maven】[ Jar转Maven,Jar转Maven工具集,老web项目转maven项目]
-【jun_jbpm】[ 流程引擎JBPM,流程引擎JBPM,老牌流程引擎]
-【jun_jdk】[ JDK核心,JDK核心工具,常用Demo等]
-【jun_jsoup】[HTM标记语言解析包,完成HTML解析、主要爬虫使用,解析HTML渲染数据]
-【jun_lucene】[老牌搜索引擎、可以看下,搜索框架,搜索框架,全文检索工具]
-【jun_leetcode】[算法刷题大全]
-【jun_mybatisplus】[ MybatisPlus,MybatisPlus数据持久化映射框架]
-【jun_pay】[ 支付工具,支付工具,集成微信及阿里支付]
-【jun_pdf】[ PDF工具,PDF工具,生成PDF及PDF文件]
-【jun_poi】[原生POI完成Excel文件的导入、解析、导出及持久化等]
-【jun_qrcode】[二维码生成器,二维码生成工具,WEB二维码服务]
-【jun_quartz】[job任务调度,任务调度框架,分布式任务调度]
-【jun_redis】[ Redis缓存,Redis缓存,分布式缓存,分布式锁]
-【jun_rpc】[原生RPC调用、客户端及服务端]
-【jun_restlet】[REST工具,轻量级REST框架,不依赖Servlet的REST的工具]
-【jun_serializable】[ 序列化,序列化与反序列化工具集]
-【jun_shiro】[ 认证与鉴权,认证与鉴权,URL过滤,用户任务,角色功能鉴权]
-【jun_sso】[原生SSO的实现单点登录,SSO单点登录工具,提供单点登录服务]
-【jun_servlet】[原生Servlet、WEB开发的基础]
-【jun_templatespider】[ 模板爬虫,模板爬虫工具,直接下载url到html文件]
-【jun_test】[JUNIT框架及TestNG框架]
-【jun_util】[开发工具util,常用开发工具集、非常重要!!!]
-【jun_webmagic】[ 爬虫引擎Webmagic,爬虫引擎Webmagic,爬取整个网站]
-【jun_webservice】[原生的webservice调用、基于apache cxf实现服务调用及发布,CXF,Axis等]
-【jun_webservlet】[原生Servlet 3.0的实现,Servlet3.0新特性demo,原生注解Servlet]
-【jun_websocket】[原生的WebSocket的实现长链接,Websocket长链接demo,消息推送及异步工具]
-【jun_xml】[原生的XML解析及生产XML、提供SAX、DOM、DOM4J解析生成XML]
- - -> **Maven常用项目模板,含maven单体分布式、SSH、SSM、SpringBoot、SpringCloud等** - -【maven_javaproject】[Java单体项目模板,Java单体项目模板]
-【maven_spring4_multi_modules】[Spring4多模块项目模板,Spring4多模块项目模板]
-【maven_spring5_multi_modules】[Spring5多模块项目模板,Spring5多模块项目模板]
-【maven_spring5template】[Spring5微服务项目模板,Spring5微服务项目模板]
-【maven_springboot】[SpringBoot微服务项目模板,SpringBoot微服务项目模板]
-【maven_project_template】[Java单体项目模板,Java单体项目模板]
-【maven_springboot_jpa_jsp】[Java单体项目模板,Java单体项目模板]
-【maven_springboot_mybatis】[Java单体项目模板,Java单体项目模板]
-【maven_springboot_permission_example】[Java单体项目模板,Java单体项目模板]
-【maven_springboot_template】[Java单体项目模板,Java单体项目模板]
- - - -> **Spring系企业级开发框架组件 Spring常用开发组件100+,万能粘合剂** - -*模块太多,描述写太麻烦了,直接贴编译清单吧,具体如下:*
-` [INFO] --------------------< com.jun.plugin:spring_plugin >--------------------`
-` [INFO] Building spring_plugin 1.0 [111/111]`
-` [INFO] --------------------------------[ pom ]---------------------------------`
-` [INFO]`

-` [INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ spring_plugin ---`

-` [INFO] ------------------------------------------------------------------------`
-` [INFO] Reactor Summary:`
-` [INFO]`
-` [INFO] spring_activemq 1.0 ................................ SUCCESS [ 1.337 s]`
-` [INFO] spring_atomikos 1.0 ................................ SUCCESS [ 1.070 s]`
-` [INFO] spring_autowired 1.0 ............................... SUCCESS [ 0.649 s]`
-` [INFO] spring_camel 1.0 ................................... SUCCESS [ 0.444 s]`
-` [INFO] spring_captcha 1.1.9 ............................... SUCCESS [ 0.601 s]`
-` [INFO] spring_data_jpa 1.0 ................................ SUCCESS [ 0.526 s]`
-` [INFO] spring_demo 1.0 .................................... SUCCESS [ 0.341 s]`
-` [INFO] spring_distributed_datasource 1.0 .................. SUCCESS [ 0.291 s]`
-` [INFO] spring_distributed_fastdfs 1.0 ..................... SUCCESS [ 0.030 s]`
-` [INFO] fastdfs_client 1.0 ................................. SUCCESS [ 0.391 s]`
-` [INFO] fastdfs_app 1.0 .................................... SUCCESS [ 0.646 s]`
-` [INFO] fastdfs_core 1.0 ................................... SUCCESS [ 1.811 s]`
-` [INFO] spring_distributed_lock 1.0 ........................ SUCCESS [ 0.224 s]`
-` [INFO] spring_distributed_multidatasource Maven Webapp 1.0 SUCCESS [ 0.594 s]`
-` [INFO] spring_distributed_netty 1.0 ....................... SUCCESS [ 0.008 s]`
-` [INFO] spring_netty_common 1.0 ............................ SUCCESS [ 0.086 s]`
-` [INFO] spring_netty_server 1.0 ............................ SUCCESS [ 0.223 s]`
-` [INFO] spring_distributed_oss_qiniu Maven Webapp 1.0 ...... SUCCESS [ 0.544 s]`
-` [INFO] spring_distributed_rpc 1.0 ......................... SUCCESS [ 0.004 s]`
-` [INFO] fastrpc_core 1.0 ................................... SUCCESS [ 0.178 s]`
-` [INFO] fastrpc_server 1.0 ................................. SUCCESS [ 0.195 s]`
-` [INFO] fastrpc_client 1.0 ................................. SUCCESS [ 0.174 s]`
-` [INFO] spring_distributed_session 1.0.0 ................... SUCCESS [ 0.238 s]`
-` [INFO] spring_distributed_transaction_tcc 1.2.12 .......... SUCCESS [ 0.037 s]`
-` [INFO] tcc-transaction-api 1.2.12 ......................... SUCCESS [ 0.642 s]`
-` [INFO] tcc-transaction-core 1.2.12 ........................ SUCCESS [ 1.058 s]`
-` [INFO] tcc-transaction-spring 1.2.12 ...................... SUCCESS [ 0.741 s]`
-` [INFO] tcc-transaction-unit-test 1.2.12 ................... SUCCESS [ 0.858 s]`
-` [INFO] tcc-transaction-server 1.2.12 ...................... SUCCESS [ 0.826 s]`
-` [INFO] tcc-transaction-dubbo 1.2.12 ....................... SUCCESS [ 0.831 s]`
-` [INFO] tcc-transaction-bom 1.2.12 ......................... SUCCESS [ 0.003 s]`
-` [INFO] spring_drools 1.0 .................................. SUCCESS [ 0.573 s]`
-` [INFO] spring_dynamic_datasource 1.0 ...................... SUCCESS [ 0.259 s]`
-` [INFO] spring_dynamic_job 1.0 ............................. SUCCESS [ 0.644 s]`
-` [INFO] easy-excel-util 1.0 ................................ SUCCESS [ 0.952 s]`
-` [INFO] spring_easyexcel 1.0 ............................... SUCCESS [ 0.004 s]`
-` [INFO] my-base-common 1.0-SNAPSHOT ........................ SUCCESS [ 1.416 s]`
-` [INFO] my-web 1.0-SNAPSHOT ................................ SUCCESS [ 2.728 s]`
-` [INFO] spring_elasticsearch Maven Webapp 1.0 .............. SUCCESS [ 0.637 s]`
-` [INFO] spring_email 1.0 ................................... SUCCESS [ 0.107 s]`
-` [INFO] spring_fastdfs 1.0 ................................. SUCCESS [ 0.214 s]`
-` [INFO] spring_fastdfs_test 1.0 ............................ SUCCESS [ 0.501 s]`
-` [INFO] spring_fileupload 1.0 .............................. SUCCESS [ 1.736 s]`
-` [INFO] spring_hibernate 1.0.0-SNAPSHOT .................... SUCCESS [ 0.666 s]`
-` [INFO] spring_hibernate_plus 1.0 .......................... SUCCESS [ 1.278 s]`
-` [INFO] spring_hibernate_validator 1.0 ..................... SUCCESS [ 0.010 s]`
-` [INFO] spring_images 1.0 .................................. SUCCESS [ 0.720 s]`
-` [INFO] spring_ioc_aop 1.0 ................................. SUCCESS [ 0.414 s]`
-` [INFO] spring_jedis_cluster 1.0 ........................... SUCCESS [ 0.310 s]`
-` [INFO] spring_jedis_simple 1.0 ............................ SUCCESS [ 0.217 s]`
-` [INFO] spring_jpa 1.0 ..................................... SUCCESS [ 2.663 s]`
-` [INFO] spring_jqgrid 1.0 .................................. SUCCESS [ 0.244 s]`
-` [INFO] spring_json_view 1.0 ............................... SUCCESS [ 0.238 s]`
-` [INFO] spring_jsonp 1.0 ................................... SUCCESS [ 0.192 s]`
-` [INFO] spring_jsoup 1.0 ................................... SUCCESS [ 0.165 s]`
-` [INFO] spring_jwt_ssm Maven Webapp 1.0 .................... SUCCESS [ 0.673 s]`
-` [INFO] spring_lucene 1.0 .................................. SUCCESS [ 0.551 s]`
-` [INFO] spring_mina 1.0 .................................... SUCCESS [ 0.470 s]`
-` [INFO] spring_mongodb 1.0 ................................. SUCCESS [ 0.688 s]`
-` [INFO] spring_mybatis 1.0 ................................. SUCCESS [ 0.717 s]`
-` [INFO] spring_mybatis_generator 1.0 ....................... SUCCESS [ 1.976 s]`
-` [INFO] spring_mybatis_generator_gui 0.7.2 ................. SUCCESS [ 0.557 s]`
-` [INFO] spring_mybatis_mulidatasource 1.0 .................. SUCCESS [ 0.351 s]`
-` [INFO] spring_mybatis_mulidatasource_atomikos 1.0 ......... SUCCESS [ 0.270 s]`
-` [INFO] spring_mybatis_plus_generator 1.0 .................. SUCCESS [ 0.480 s]`
-` [INFO] spring_mybatis3_simple 1.0 ......................... SUCCESS [ 0.272 s]`
-` [INFO] spring_mybatisplus 1.0 ............................. SUCCESS [ 0.428 s]`
-` [INFO] spring_netty 1.0 ................................... SUCCESS [ 0.662 s]`
-` [INFO] spring_oauth_client 1.1 ............................ SUCCESS [ 0.806 s]`
-` [INFO] spring_oauth_server 1.0 ............................ SUCCESS [ 0.751 s]`
-` [INFO] spring_oauth_server2 1.01 .......................... SUCCESS [ 0.663 s]`
-` [INFO] spring_oauth 1.0 ................................... SUCCESS [ 0.004 s]`
-` [INFO] spring_oschina 1.0 ................................. SUCCESS [ 0.174 s]`
-` [INFO] spring_plupload 1.0 ................................ SUCCESS [ 0.188 s]`
-` [INFO] spring_projects 1.0 ................................ SUCCESS [ 0.003 s]`
-` [INFO] spring-mvc-session-with-redis Maven Webapp 1.0 ..... SUCCESS [ 0.331 s]`
-` [INFO] spring-mvc-with-redis Maven Webapp 1.0 ............. SUCCESS [ 0.306 s]`
-` [INFO] web-native-jar Maven Webapp 1.0 .................... SUCCESS [ 0.212 s]`
-` [INFO] spring-with-ehcache Maven Webapp 1.0 ............... SUCCESS [ 0.304 s]`
-` [INFO] spring-mvc-with-redis-rank Maven Webapp 1.0 ........ SUCCESS [ 0.298 s]`
-` [INFO] spring_quartz 1.0 .................................. SUCCESS [ 0.478 s]`
-` [INFO] spring_quartz_task 1.0 ............................. SUCCESS [ 1.270 s]`
-` [INFO] spring_rabbitmq 1.0 ................................ SUCCESS [ 0.360 s]`
-` [INFO] spring_redis 1.0 ................................... SUCCESS [ 0.556 s]`
-` [INFO] redis-demo-publisher 1.0 ........................... SUCCESS [ 0.533 s]`
-` [INFO] redis-demo-subscriber1 1.0 ......................... SUCCESS [ 0.310 s]`
-` [INFO] redis-demo-subscriber2 1.0 ......................... SUCCESS [ 0.303 s]`
-` [INFO] spring_redis_queue 1.0 ............................. SUCCESS [ 0.003 s]`
-` [INFO] spring_rest_client 1.0 ............................. SUCCESS [ 0.237 s]`
-` [INFO] spring_rest_server 1.0 ............................. SUCCESS [ 0.326 s]`
-` [INFO] spring_rest 1.0 .................................... SUCCESS [ 0.004 s]`
-` [INFO] spring-session-demo.javaconfig Maven Webapp 1.0 .... SUCCESS [ 0.343 s]`
-` [INFO] spring-session-demo.xml Maven Webapp 1.0 ........... SUCCESS [ 0.223 s]`
-` [INFO] spring_session 1.0 ................................. SUCCESS [ 0.004 s]`
-` [INFO] spring_shiro_redis Maven Webapp 1.0 ................ SUCCESS [ 0.658 s]`
-` [INFO] spring_solr 1.0 .................................... SUCCESS [ 0.282 s]`
-` [INFO] spring_springbatch 1.0 ............................. SUCCESS [ 0.967 s]`
-` [INFO] spring_springjdbc 1.0 .............................. SUCCESS [ 0.250 s]`
-` [INFO] spring_springmv_bootstrap Maven Webapp 1.0 ......... SUCCESS [ 2.355 s]`
-` [INFO] spring_springmvc 1.0 ............................... SUCCESS [ 0.863 s]`
-` [INFO] spring_springtest 1.0 .............................. SUCCESS [ 0.453 s]`
-` [INFO] spring_ssh 1.0 ..................................... SUCCESS [ 0.351 s]`
-` [INFO] spring_ssh2 1.0 .................................... SUCCESS [ 0.389 s]`
-` [INFO] spring_ssm_layui 1.0 ............................... SUCCESS [ 1.909 s]`
-` [INFO] spring_ssm2 1.0 .................................... SUCCESS [ 0.422 s]`
-` [INFO] spring_swagger Maven Webapp 1.0 .................... SUCCESS [ 1.483 s]`
-` [INFO] spring_task 1.0 .................................... SUCCESS [ 0.236 s]`
-` [INFO] spring_thymeleaf 1.0 ............................... SUCCESS [ 0.154 s]`
-` [INFO] spring_transaction 1.0 ............................. SUCCESS [ 1.995 s]`
-` [INFO] spring_websocket 1.0 ............................... SUCCESS [ 0.796 s]`
-` [INFO] spring_plugin 1.0 .................................. SUCCESS [ 0.003 s]`
-` [INFO] ------------------------------------------------------------------------`
-` [INFO] BUILD SUCCESS`
-` [INFO] ------------------------------------------------------------------------`
-` [INFO] Total time: 01:04 min`
-` [INFO] Finished at: 2023-06-01T11:25:59+08:00`
-` [INFO] ------------------------------------------------------------------------`
- -` Process finished with exit code 0`
- - - - -> **SpringBoot系开发框架组件,基于SpringBoot微服务开发组件100+,** - -*模块太多,描述写太麻烦了,直接贴编译清单吧,具体如下(编译内存溢出可调整JVM参数):*
-`[INFO] ----------------< com.jun.plugin:springboot_zookeeper >-----------------`
-` [INFO] Building springboot_zookeeper 1.0 [107/107]`
-` [INFO] ------------------------------------------------------------------------`
-` [INFO] Reactor Summary:`
-` [INFO]`
-` [INFO] springboot_a_test 1.0 .............................. SUCCESS [ 3.311 s]`
-` [INFO] springboot_actuator 1.0 ............................ SUCCESS [ 0.624 s]`
-` [INFO] springboot_aop 1.0 ................................. SUCCESS [ 0.638 s]`
-` [INFO] springboot_async 1.0 ............................... SUCCESS [ 1.988 s]`
-` [INFO] springboot_batch 1.0 ............................... SUCCESS [ 1.620 s]`
-` [INFO] springboot_cache 1.0 ............................... SUCCESS [ 0.974 s]`
-` [INFO] springboot_canal 1.0 ............................... SUCCESS [ 3.105 s]`
-` [INFO] jun_springboot_plugin 1.0 .......................... SUCCESS [ 0.047 s]`
-` [INFO] springboot_codegen 1.0.0-SNAPSHOT .................. SUCCESS [ 3.042 s]`
-` [INFO] springboot_content_negotiation 1.0 ................. SUCCESS [ 0.355 s]`
-` [INFO] springboot_cxf 1.0 ................................. SUCCESS [ 0.601 s]`
-` [INFO] springboot_data_jpa 1.0 ............................ SUCCESS [ 1.028 s]`
-` [INFO] springboot_distributed_seckill 1.0 ................. SUCCESS [ 2.698 s]`
-` [INFO] springboot_docker 1.0.0-SNAPSHOT ................... SUCCESS [ 0.209 s]`
-` [INFO] springboot_drools 1.0 .............................. SUCCESS [ 1.185 s]`
-` [INFO] springboot_dubbo_zookeeper 1.0 ..................... SUCCESS [ 0.004 s]`
-` [INFO] common-api 1.0 ..................................... SUCCESS [ 0.289 s]`
-` [INFO] server-provider 1.0 ................................ SUCCESS [ 0.283 s]`
-` [INFO] server-consumer 1.0 ................................ SUCCESS [ 0.284 s]`
-` [INFO] springboot_dynamic_datasource 1.0.0-SNAPSHOT ....... SUCCESS [ 2.692 s]`
-` [INFO] springboot_echarts 1.0 ............................. SUCCESS [ 2.748 s]`
-` [INFO] springboot_ehcache_cache 1.0 ....................... SUCCESS [ 0.591 s]`
-` [INFO] springboot_elastic_job 1.0 ......................... SUCCESS [ 0.769 s]`
-` [INFO] springboot_email 1.0 ............................... SUCCESS [ 0.332 s]`
-` [INFO] springboot_excel 1.0 ............................... SUCCESS [ 3.125 s]`
-` [INFO] springboot_fastdfs 1.0 ............................. SUCCESS [ 0.418 s]`
-` [INFO] springboot_file_upload 1.0 ......................... SUCCESS [ 0.359 s]`
-` [INFO] springboot_file_uploaderr 1.0 ...................... SUCCESS [ 0.993 s]`
-` [INFO] springboot_flowable 1.0 ............................ SUCCESS [ 2.156 s]`
-` [INFO] springboot_flyway 1.0 .............................. SUCCESS [ 0.318 s]`
-` [INFO] springboot_freemarker 1.0 .......................... SUCCESS [ 0.318 s]`
-` [INFO] springboot_graphql_mongodb 1.0 ..................... SUCCESS [ 2.263 s]`
-` [INFO] springboot_graylog 1.0 ............................. SUCCESS [ 0.194 s]`
-` [INFO] springboot_groovy 1.0 .............................. SUCCESS [ 1.795 s]`
-` [INFO] springboot_hibernate 1.0 ........................... SUCCESS [ 0.381 s]`
-` [INFO] springboot_hibernate_validator 1.0 ................. SUCCESS [ 1.741 s]`
-` [INFO] springboot_https 1.0 ............................... SUCCESS [ 0.272 s]`
-` [INFO] springboot_upload_h2db 1.0 ......................... SUCCESS [ 1.197 s]`
-` [INFO] springboot_jasypt 1.0 .............................. SUCCESS [ 2.108 s]`
-` [INFO] springboot_jackson2 1.0 ............................ SUCCESS [ 0.265 s]`
-` [INFO] springboot_jdbctemplate_multidatasource 1.0 ........ SUCCESS [ 0.374 s]`
-` [INFO] springboot_jpa_thymeleaf_curd 1.0 .................. SUCCESS [ 0.529 s]`
-` [INFO] springboot_jsp 1.0 ................................. SUCCESS [ 2.043 s]`
-` [INFO] springboot_junit 1.0 ............................... SUCCESS [ 0.358 s]`
-` [INFO] springboot_jwt 1.0 ................................. SUCCESS [ 0.735 s]`
-` [INFO] springboot_kafka 1.0 ............................... SUCCESS [ 0.549 s]`
-` [INFO] springboot_kisso 1.0 ............................... SUCCESS [ 0.385 s]`
-` [INFO] springboot_ldap 1.0 ................................ SUCCESS [ 1.751 s]`
-` [INFO] springboot_log4jmonitor 1.0 ........................ SUCCESS [ 0.338 s]`
-` [INFO] springboot_logback 1.0 ............................. SUCCESS [ 1.237 s]`
-` [INFO] springboot_mapper_pagehelper 1.0 ................... SUCCESS [ 0.506 s]`
-` [INFO] springboot_minio 1.0 ............................... SUCCESS [ 3.098 s]`
-` [INFO] springboot_mongodb 1.0 ............................. SUCCESS [ 2.908 s]`
-` [INFO] springboot_mq_rabbitmq 1.0 ......................... SUCCESS [ 0.011 s]`
-` [INFO] springboot_mq_rocketmq 1.0 ......................... SUCCESS [ 0.007 s]`
-` [INFO] springboot_multi_datasource_jpa 1.0 ................ SUCCESS [ 2.141 s]`
-` [INFO] springboot_multi_datasource_mybatis 1.0 ............ SUCCESS [ 1.369 s]`
-` [INFO] springboot_multi_threading 1.0 ..................... SUCCESS [ 1.262 s]`
-` [INFO] springboot_multisource 1.0 ......................... SUCCESS [ 0.780 s]`
-` [INFO] springboot_mybatis 1.0 ............................. SUCCESS [ 0.301 s]`
-` [INFO] springboot_mybatis_jsp 1.0 ......................... SUCCESS [ 0.581 s]`
-` [INFO] springboot_mybatisplus 1.0 ......................... SUCCESS [ 0.789 s]`
-` [INFO] springboot_netty_websocket 1.0 ..................... SUCCESS [ 4.037 s]`
-` [INFO] springboot_oauth2 1.0 .............................. SUCCESS [ 0.017 s]`
-` [INFO] authorization-server 1.0 ........................... SUCCESS [ 2.646 s]`
-` [INFO] resource-server 1.0 ................................ SUCCESS [ 0.734 s]`
-` [INFO] springboot_orm_jdbctemplate 1.0 .................... SUCCESS [ 2.003 s]`
-` [INFO] springboot_oss_aliyun 1.0 .......................... SUCCESS [ 0.695 s]`
-` [INFO] springboot_oss_qiniu 1.0 ........................... SUCCESS [ 0.583 s]`
-` [INFO] springboot_pay 1.0 ................................. SUCCESS [ 2.203 s]`
-` [INFO] springboot_quartz 1.0 .............................. SUCCESS [ 1.343 s]`
-` [INFO] springboot_ratelimit_guava 1.0 ..................... SUCCESS [ 1.538 s]`
-` [INFO] springboot_ratelimit_redis 1.0 ..................... SUCCESS [ 2.114 s]`
-` [INFO] springboot_rbac_security 1.0 ....................... SUCCESS [ 4.486 s]`
-` [INFO] springboot_rbac_shiro 1.0 .......................... SUCCESS [ 1.549 s]`
-` [INFO] springboot_redis 1.0 ............................... SUCCESS [ 0.845 s]`
-` [INFO] springboot_redis_cluster 1.0 ....................... SUCCESS [ 0.519 s]`
-` [INFO] springboot_redis_sentinel 1.0 ...................... SUCCESS [ 0.386 s]`
-` [INFO] springboot_redislock 1.0 ........................... SUCCESS [ 0.550 s]`
-` [INFO] springboot_resttemplate 1.0 ........................ SUCCESS [ 0.960 s]`
-` [INFO] springboot_schedule 1.0 ............................ SUCCESS [ 0.203 s]`
-` [INFO] simple-security-jwt 1.0.0 .......................... SUCCESS [ 1.704 s]`
-` [INFO] simple-security-jwt-demo 1.0.0 ..................... SUCCESS [ 0.300 s]`
-` [INFO] springboot_security2 1.0 ........................... SUCCESS [ 0.005 s]`
-` [INFO] springboot_session 1.0 ............................. SUCCESS [ 0.424 s]`
-` [INFO] springboot_shardingsphere-mybatisplus 1.0 .......... SUCCESS [ 2.885 s]`
-` [INFO] springboot_shiro 1.0 ............................... SUCCESS [ 1.735 s]`
-` [INFO] springboot_snaker 1.0 .............................. SUCCESS [ 0.990 s]`
-` [INFO] springboot_justauth 1.0 ............................ SUCCESS [ 1.590 s]`
-` [INFO] springboot_socketio 1.0 ............................ SUCCESS [ 0.373 s]`
-` [INFO] springboot_starter 1.0 ............................. SUCCESS [ 0.270 s]`
-` [INFO] springboot_swagger_beauty 1.0 ...................... SUCCESS [ 1.668 s]`
-` [INFO] springboot_task_xxl_job 1.0 ........................ SUCCESS [ 2.488 s]`
-` [INFO] springboot_template_freemarker 1.0 ................. SUCCESS [ 1.326 s]`
-` [INFO] springboot_template_thymeleaf 1.0 .................. SUCCESS [ 1.287 s]`
-` [INFO] springboot_testing 1.0 ............................. SUCCESS [ 0.435 s]`
-` [INFO] springboot_thumbnailator 0.0.1-SNAPSHOT ............ SUCCESS [ 0.809 s]`
-` [INFO] springboot_thymeleaf 1.0 ........................... SUCCESS [ 0.447 s]`
-` [INFO] springboot_transaction 1.0 ......................... SUCCESS [ 0.922 s]`
-` [INFO] springboot_upload 1.0 .............................. SUCCESS [ 2.881 s]`
-` [INFO] springboot_validation 1.0 .......................... SUCCESS [ 1.393 s]`
-` [INFO] springboot_war 1.0 ................................. SUCCESS [ 0.204 s]`
-` [INFO] springboot_webflux 1.0 ............................. SUCCESS [ 0.879 s]`
-` [INFO] springboot_webservice 0.0.1-SNAPSHOT ............... SUCCESS [ 0.741 s]`
-` [INFO] springboot_websocket 1.0 ........................... SUCCESS [ 0.487 s]`
-` [INFO] springboot_websocket_socketio 1.0 .................. SUCCESS [ 2.226 s]`
-` [INFO] springboot_zookeeper 1.0 ........................... SUCCESS [ 2.068 s]`
-` [INFO] ------------------------------------------------------------------------`
-` [INFO] BUILD SUCCESS`
-` [INFO] ------------------------------------------------------------------------`
-` [INFO] Total time: 02:09 min`
-` [INFO] Finished at: 2023-06-01T11:29:50+08:00`
-` [INFO] ------------------------------------------------------------------------`
- -` Process finished with exit code 0`
+#### 开发环境 +- **JDK 1.8 +** +- **Maven 3.5 +** +- **IDEA 2018.2 + or STS 4.5 +** (*注意:务必使用 IDEA 开发,同时保证安装 `lombok` 插件*) +- **Mysql 5.7 +** (*尽量保证使用 5.7 版本以上,因为 5.7 版本加了一些新特性,同时不向下兼容。本 demo 里会尽量避免这种不兼容的地方,但还是建议尽量保证 5.7 版本以上*) -#### 开发环境 -- **JDK 1.8 -- **Maven 3.5 -- **IDEA 2018.2 + or STS 4.5 +** (*注意:安装lombok插件) -- **TOKEN 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Abc -#### 笔者其他项目 - [俊哥个人技术栈代码库(持续更新)](https://github.com/wujun728) -TODO PLAN: -【Step1基础篇】: - jun_java_plugin Java基础框架-Java开发组件、Spring开发组件、SpringBoot开发组件、SpringCloud开发组件、Maven项目模板 - jun_ssh_parent  SSH基础框架-SpringBoot+EasyUI+JSP - jun_ssm_springboot SSM基础框架-SpringBoot+MybatisPlus+Boostrap+Shiro+JWT - jun_code_generator 代码生成器-SpringBoot+Freemarker+API接口 - jun_frontend_ui    前端框架,Bootstrap、LayUI、Vue、Vue-element-admin - jun_linux    服务器部署、gitlab部署、Nginx部署、Redis部署、Docker部署、MySQL部署、等等 - ---TODO审视项目本身,给出待办调整清单,给出下步计划 -【Step2微服务&大数据】: - jun_api_service API接口服务框架,SpringBoot+Rest API - jun_springboot_vue 前后端分离框架,SpringBoot+Vue+JWT - jun_springcloud 微服务框架,SpringCloud Netflix、SpringCloud Alibaba、Dubbo框架 - jun_bigdata 大数据框架,支持数据清理、数据推荐、大数据分析、大数据企业看板、大数据报表等 +#### 运行方式 -【Step3产品篇】: - jun_product_center 产品中心,包含企业官网、企业办公自动化系统、企业资源管理ERP系统等 - jun_website   CMS网站系统,基于WordPress的网站系统、支持博客、企业官网、及各种网站模板 - wujun728.github.io 个人博客 +> 提示:如果是 fork 的朋友,同步代码的请参考: +1. `git clone https://github.com/wujun728/jun_xxx.git` +2. 使用 IDEA 打开 clone 下来的项目 +3. 在 IDEA 中 Maven Projects 的面板导入项目根目录下 的 `pom.xml` 文件 +4. Maven Projects 找不到的童鞋,可以勾上 IDEA 顶部工具栏的 View -> Tool Buttons ,然后 Maven Projects 的面板就会出现在 IDEA 的右侧 +5. 找到各个 Module 的 Application 类就可以运行各个 demo 了 +6. 注意:每个 demo 均有详细的 README 配套,用 demo 前记得先看看 +7. 注意:运行各个 demo 之前,有些是需要事先初始化数据库数据的 -【Step4移动产品篇】: - jun_app    移动APP开发平台、支持Uniapp开发独立APP、小程序、企业办公等 - jun_weixin   微信开发平台、微信公众号、微信小程序、微信管理后台、微信API接口后台 - jun_android Android移动开发框架,APP开发模板、后台管理系统、后台API接口平台 +#### 已办&待办列表 +1. 完善Spring集成各种组件 +1. 梳理当前的代码及功能 + \ No newline at end of file diff --git a/claude-progress.txt b/claude-progress.txt deleted file mode 100644 index d3ef37ba09..0000000000 --- a/claude-progress.txt +++ /dev/null @@ -1,152 +0,0 @@ -# jun_java_plugin - 进度跟踪 - -## 项目概述 - -jun_java_plugin 是一个全面的 Java 企业级开发组件库,旨在成为完整的 Java 技术栈参考仓库。 - -**项目目标:** -- 提供 200+ 开箱即用的开发组件和示例 -- 覆盖 Java 基础、Spring Boot、Spring Cloud 全技术栈 -- 成为 Java 开发者和 AI 助手的代码参考仓库 -- 提供完整的文档和最佳实践指南 - -**当前状态:** -- 5个主要模块: jun_java_plugins(65), jun_springboot_plugin(100), jun_springboot_starter(25), jun_springcloud_plugin, java_project_template(11) -- 总计约 200+ 个子模块 -- 部分模块编译成功,部分存在依赖冲突 -- 文档不完整,需要系统化整理 - -## 架构决策 - -### 技术选型 -- **Java 版本**: JDK 1.8 (主流企业版本) -- **构建工具**: Maven 3.5+ -- **Spring Boot 版本**: 混合版本(2.4.2, 2.6.13) - 用于展示不同版本的集成方式 -- **文档格式**: Markdown -- **API 文档**: Swagger/Knife4j - -### 项目结构 -``` -jun_java_plugin/ -├── jun_java_plugins/ # 原生 Java 组件(无 Spring 依赖) -├── jun_springboot_plugin/ # Spring Boot 集成示例 -├── jun_springboot_starter/ # 自定义 Spring Boot Starter -├── jun_springcloud_plugin/ # Spring Cloud 微服务组件 -├── java_project_template/ # Maven 项目模板 -├── docs/ # 文档中心(待创建) -├── examples/ # 综合示例(待创建) -└── scripts/ # 辅助脚本(待创建) -``` - -### 设计原则 -1. **模块独立性**: 每个模块是独立的示例,可单独运行和学习 -2. **文档优先**: 所有模块必须有完整的 README 文档 -3. **最佳实践**: 遵循阿里巴巴 Java 开发手册规范 -4. **代码质量**: 提供单元测试和集成测试示例 -5. **实用性**: 代码可以直接复制使用,不仅仅是理论 - -## 会话记录 - -### Session #1 - 规划阶段 (2026-04-13) - -**目标**: 分析现有代码库,制定完善方案 - -**完成的工作**: -1. ✅ 环境检查和分析 - - 确认工作目录: D:\workspace_github_v2\10技术基础层\jun_java_plugin - - 验证开发环境: JDK 11.0.2, Maven 3.9.8 - - 统计模块数量: 65 + 100 + 25 + 1 + 11 = 202 个模块 - -2. ✅ 项目结构分析 - - 阅读根 pom.xml 和 README.md - - 理解项目目标和现状 - - 识别5个主要模块 - -3. ✅ 任务规划 - - 创建 task_list.json (共 45 个任务) - - 任务分类: setup(5), testing(4), functional(11), api(1), database(5), integration(2), deployment(3) - - 优先级分配: P1-P5 - -4. ✅ 脚手架创建 - - 创建 init.sh (Linux/Mac 环境检查脚本) - - 创建 init.bat (Windows 环境检查脚本) - - 创建 claude-progress.txt (本文件) - -**任务清单概览** (45个任务): - -**第一阶段 - 分析评估 (T001-T009, Priority 1-2)** -- 创建分析工具和脚本 -- 遍历分析所有5个主要模块 -- 编译测试所有模块,记录错误 - -**第二阶段 - 覆盖度评估 (T010-T020, Priority 2-3)** -- 评估 Java 基础、数据库、Web、安全、消息队列、工具库等技术栈覆盖度 -- 识别重复模块和缺失模块 -- 评估文档和测试覆盖率 -- 创建全局技术栈清单 - -**第三阶段 - 文档完善 (T021-T022, T039-T042, Priority 3-5)** -- 创建模块索引和导航 -- 创建快速开始指南 -- 更新主 README -- 创建贡献指南、最佳实践、技术选型指南 - -**第四阶段 - 修复和补充 (T023-T029, Priority 4-5)** -- 修复编译错误 -- 补充缺失的 Java 基础、数据库、微服务、新技术模块 -- 完善模块 README 文档 -- 添加 Swagger API 文档 - -**第五阶段 - 质量提升 (T030-T036, Priority 4-5)** -- 添加单元测试和集成测试 -- 清理冗余模块 -- 统一代码风格 -- 优化依赖管理 - -**第六阶段 - 集成和部署 (T037-T038, T043-T045, Priority 5)** -- 创建综合示例应用 -- 创建在线演示环境 -- 配置 CI/CD -- 生成统计报告和文档汇总 - -**关键指标**: -- 模块总数: ~202 个 -- 计划新增模块: 10-20 个(补充缺失技术) -- 计划清理模块: 5-10 个(冗余模块) -- 目标文档覆盖率: 100% -- 目标编译成功率: 90%+ -- 目标测试覆盖率: 60%+ - -**风险和挑战**: -1. 模块数量庞大,全面分析和测试耗时较长 -2. 部分模块有依赖冲突,修复需要谨慎 -3. 不同 Spring Boot 版本兼容性问题 -4. 文档工作量大,需要逐个模块编写 -5. 测试补充工作量大 - -**下一步计划**: -1. 执行环境初始化脚本(init.sh/init.bat) -2. 开始执行 T001-T005: 创建分析工具和遍历所有模块 -3. 执行 T006-T009: 编译测试所有模块 -4. 生成分析报告,评估技术栈覆盖度 - -**状态**: 规划完成,等待执行 - ---- - -## 下一位执行者注意事项 - -1. **先运行 init 脚本**: 执行 `bash init.sh` 或 `init.bat` 检查环境 -2. **读取任务清单**: 查看 task_list.json,按依赖关系执行任务 -3. **遵循规范**: 参考 CLAUDE.md 和 /project-conventions 技能 -4. **使用技能**: 利用 /crud 技能生成符合规范的代码 -5. **记录进度**: 在每个会话结束时更新本文件 -6. **Git 提交**: 完成关键任务后及时提交代码 - -## 参考资源 - -- 项目规范: CLAUDE.md -- 任务清单: task_list.json -- 主文档: README.md -- 编码规范: /project-conventions 技能 -- 代码生成: /crud 技能 diff --git a/claude.md b/claude.md deleted file mode 100644 index 6b46628c82..0000000000 --- a/claude.md +++ /dev/null @@ -1,222 +0,0 @@ -# CLAUDE.md - -本文件为 Claude Code (claude.ai/code) 在此代码仓库中工作时提供指导。 - -## 项目概述 - -`jun_java_plugin` 是一个全面的 Java 企业级开发组件库,提供开箱即用、生产级别的代码示例和模板。该项目通过提供 200+ 个集成类库消除重复编码,涵盖四大主要类别: - -- **jun_java_plugins**: 60+ 原生 Java 开发组件(无 Spring 依赖) -- **jun_springboot_plugin**: 100+ Spring Boot 集成示例 -- **jun_springcloud_plugin**: Spring Cloud 微服务组件(Netflix、Alibaba、Dubbo) -- **jun_springboot_starter**: 自定义 Spring Boot 启动器 -- **java_project_template**: Maven 项目模板(SSH、SSM、Spring Boot、Spring Cloud) - -这是一个**演示和参考仓库**,而非生产应用。每个模块都是独立的示例,展示集成模式。 - -## 构建命令 - -\`\`\`bash -# 清理并编译整个项目(可能需要增加 JVM 内存) -mvn clean compile - -# 使用内存配置构建(如果编译失败) -export MAVEN_OPTS="-Xmx2048m -XX:MaxPermSize=512m" -mvn clean install -DskipTests - -# 构建特定模块 -cd jun_java_plugins && mvn clean package - -# 构建 SpringBoot 插件模块(耗时约 2 分钟) -cd jun_springboot_plugin && mvn clean compile - -# 构建 SpringCloud 插件模块 -cd jun_springcloud_plugin && mvn clean compile -\`\`\` - -**重要说明:** -- 某些模块可能因依赖冲突而有编译错误 - 这在演示仓库中是正常的 -- 并非所有模块都能一起运行;它们是独立的示例 -- 使用 `-DskipTests` 在构建时跳过测试 -- 父 POM 设计简洁 - 每个模块管理自己的依赖 - -## 项目结构 - -``` -jun_java_plugin/ -├── jun_java_plugins/ # 原生 Java 组件(无 Spring) -│ ├── jun_algorithm/ # 算法和数据结构 -│ ├── jun_dbutil/ # JDBC 和数据库工具 -│ ├── jun_redis/ # Redis 客户端集成 -│ ├── jun_quartz/ # 任务调度 -│ ├── jun_freemarker/ # 代码生成模板引擎 -│ └── [60+ 其他模块] -│ -├── jun_springboot_plugin/ # Spring Boot 集成 -│ ├── springboot_codegen/ # 代码生成器(Velocity 模板) -│ ├── springboot_mybatis/ # MyBatis 集成 -│ ├── springboot_redis/ # Spring Boot 的 Redis -│ ├── springboot_security2/ # Spring Security 示例 -│ ├── springboot_oauth2/ # OAuth2 授权/资源服务器 -│ └── [100+ 其他模块] -│ -├── jun_springboot_starter/ # 自定义 Spring Boot 启动器 -│ ├── jun-encrypt-body-spring-boot-starter/ -│ ├── jun-minio-spring-boot-starter/ -│ ├── jun-p6spy-spring-boot-starter/ -│ └── [其他自定义启动器] -│ -├── jun_springcloud_plugin/ # Spring Cloud 微服务 -│ └── [Netflix、Alibaba、Dubbo 示例] -│ -└── java_project_template/ # Maven 项目模板 - └── [单模块、多模块、SSH、SSM 模板] -``` - -## 代码生成 - -项目包含两种代码生成方式: - -### 1. 内置代码生成器(`springboot_codegen`) - -位置:`jun_springboot_plugin/springboot_codegen/` - -- 使用 Velocity 模板生成 Entity/Mapper/Service/Controller -- 运行后可通过 http://localhost:8080/demo/index.html 访问 Web 界面 -- 生成基于 MyBatis-Plus 的 CRUD 代码,使用 Lombok 注解 -- 支持 MySQL 数据库 - -### 2. Claude Code 技能(`/crud` 命令) - -仓库包含自定义 Claude Code 技能: - -- **`/crud`**: 生成完整业务模块(SQL → Entity → DAO → XML → Repository → Service → Controller → Mapper → POJO) -- **`/project-conventions`**: 显示项目编码规范(阿里巴巴 Java 开发手册) - -使用方法:输入 `/crud` 后跟需求描述,例如 "/crud 创建一个商品分类管理模块" - -## 编码规范 - -项目遵循**阿里巴巴 Java 开发手册**约定: - -### 命名约定 -- **包名**: 全小写,反向域名格式(`net.trueland.tshop.retail.system.center`) -- **类名**: 大驼峰 + 后缀(`ApplicationService`、`ApplicationDao`、`ApplicationDTO`) -- **方法名**: 小驼峰 + 前缀(`getById()`、`listByQo()`、`add()`、`updateById()`) -- **常量**: 全大写下划线分隔(`MAX_PAGE_SIZE`、`DEFAULT_STATUS`) -- **数据库表**: 蛇形命名 + 前缀(`s_application`、`t_order`) - - `s_` 系统表 - - `t_` 业务表 - -### 分层架构 - -``` -Controller(Web 层) - ↓ 调用 -Service(业务逻辑层) - ↓ 调用 -Repository(数据仓储层) - ↓ 调用 -DAO(数据访问层 - MyBatis) - ↓ 操作 -Database(数据库) -``` - -### 必需数据库字段 - -每个表必须包含: -- `id` (BIGINT): 主键,自增 -- `tenant_id` (BIGINT): 租户 ID,用于多租户 -- `create_time` (DATETIME): 创建时间 -- `update_time` (DATETIME): 更新时间 -- `is_deleted` (TINYINT): 逻辑删除标记(0=否,1=是) - -### 注解规范 - -```java -// Controller -@Api(tags = "模块描述") -@RestController -@RequiredArgsConstructor -@RequestMapping("/path") - -// Service -@Service -@AllArgsConstructor -@Slf4j - -// Repository -@Repository -@RequiredArgsConstructor - -// Entity/DTO/VO -@Data -@ApiModelProperty("字段描述") -``` - -### 异常处理 - -- 使用自定义 `ServiceException` 和错误码 -- Repository 层验证数据存在性 -- Controller 返回统一的 `ApiResult` 格式 -- 永远不要捕获异常后不处理(禁止空 catch 块) - -## 技术栈 - -| 类别 | 技术 | 说明 | -|------|------|------| -| Java | JDK 1.8 | 必需 | -| 构建工具 | Maven 3.5+ | 必需 | -| IDE | IDEA 2018.2+ / STS 4.5+ | 需安装 Lombok 插件 | -| Spring Boot | 2.4.2 / 2.6.13 | 不同模块使用不同版本 | -| ORM | MyBatis、MyBatis-Plus、Hibernate、JPA | 多种示例 | -| 对象映射 | MapStruct | 推荐用于 DTO/Entity 转换 | -| 工具库 | Lombok、Hutool、Apache Commons | 广泛使用 | -| API 文档 | Swagger、Knife4j | 多数模块包含 | -| 数据库 | MySQL 5.7/8.0 | 主要数据库 | -| 缓存 | Redis | 多种集成示例 | -| 消息队列 | RabbitMQ、RocketMQ、Kafka | 各种示例 | -| 工作流 | Activiti、Flowable、Snaker | 流程引擎 | -| 任务调度 | Quartz、XXL-Job、Elastic-Job | 任务调度 | - -## 常见开发模式 - -### 探索模块时 - -1. 每个模块都是自包含的,有自己的 README.md -2. 检查 `src/main/resources/application.yml` 了解配置 -3. 查找 `*Application.java` 主类理解启动方式 -4. 检查 `pom.xml` 了解具体依赖和版本 - -### 添加新功能时 - -1. 使用 `/crud` 技能生成完整模块 -2. 遵循模块中现有的包结构 -3. 保持与项目编码约定的一致性 -4. 添加适当的 Swagger 注解进行 API 文档化 - -### 调试时 - -1. 检查模块特定的 `application.yml` 配置 -2. 查看 `src/main/resources/mybatis/mapper/` 中的 MyBatis XML 映射 -3. 在 `logback.xml` 中为特定包启用 DEBUG 日志 -4. 许多模块在 `src/test/java/` 中有测试类 - -## 重要说明 - -1. **内存需求**: 构建整个项目可能需要增加 JVM 堆大小(`-Xmx2048m`) -2. **模块独立性**: 模块是独立示例,一起运行可能有依赖冲突 -3. **非生产就绪**: 这是学习/参考仓库。模块展示集成模式,但可能缺乏生产级的错误处理、安全性和优化 -4. **中文文档**: 大多数 README 文件和注释是中文的 -5. **混合版本**: 不同模块故意使用不同的 Spring Boot 版本以展示兼容性 -6. **Git 状态**: 仓库可能有未提交的文件(`nul`、`prompt.md`)- 这些是工作文件,可以忽略 -7. **需要 Lombok**: IDE 必须安装 Lombok 插件以避免编译错误 - -## 使用此代码库时 - -- **将每个模块视为独立示例**,而非统一应用的一部分 -- **不要试图"修复"不同模块间的依赖冲突** - 它们是故意隔离的 -- **生成新代码时参考 `/project-conventions` 技能**以确保一致性 -- **使用 `/crud` 技能**生成遵循项目标准的样板代码 -- **查看模块特定的 README** 文件了解使用说明和配置详情 -- **创建新功能时**,在适当的插件目录中按现有模式生成代码 diff --git a/compile_output.log b/compile_output.log deleted file mode 100644 index cfea87bff3..0000000000 --- a/compile_output.log +++ /dev/null @@ -1,124 +0,0 @@ -OpenJDK 64-Bit Server VM warning: Ignoring option MaxPermSize; support was removed in 8.0 -[INFO] Scanning for projects... -[ERROR] [ERROR] Some problems were encountered while processing the POMs: -[FATAL] Non-parseable POM D:\workspace_github_v2\10\jun_java_plugin\jun_springboot_starter\jun-onlineForm-spring-boot-starter\pom.xml: Unrecognised tag: 'scope' (position: START_TAG seen ...\r\n ... @69:20) @ line 69, column 20 -[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing. @ line 44, column 12 -[WARNING] 'build.plugins.plugin.(groupId:artifactId)' must be unique but found duplicate declaration of plugin org.springframework.boot:spring-boot-maven-plugin @ line 108, column 21 -[WARNING] 'build.plugins.plugin.(groupId:artifactId)' must be unique but found duplicate declaration of plugin org.apache.maven.plugins:maven-compiler-plugin @ line 99, column 21 -[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing. @ line 74, column 21 -[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-surefire-plugin is missing. @ line 82, column 21 -[WARNING] 'dependencies.dependency.version' for org.junit.jupiter:junit-jupiter-api:jar is either LATEST or RELEASE (both of them are being deprecated) @ line 60, column 13 -[WARNING] 'dependencies.dependency.version' for org.junit.jupiter:junit-jupiter-api:jar is either LATEST or RELEASE (both of them are being deprecated) @ line 66, column 13 -[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: org.junit.jupiter:junit-jupiter-api:jar -> duplicate declaration of version RELEASE @ line 63, column 15 -[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-surefire-plugin is missing. @ line 127, column 12 -[WARNING] 'build.plugins.plugin.(groupId:artifactId)' must be unique but found duplicate declaration of plugin org.apache.maven.plugins:maven-compiler-plugin @ line 127, column 21 -[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-source-plugin is missing. @ line 105, column 21 -[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-javadoc-plugin is missing. @ line 100, column 21 -[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: us.codecraft:webmagic-extension:jar -> duplicate declaration of version 1.0.0 @ line 41, column 15 -[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: com.google.guava:guava:jar -> version ${guava.version} vs 29.0-jre @ line 140, column 15 -[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: org.apache.commons:commons-lang3:jar -> version ${commons.lang3.version} vs 3.1 @ line 157, column 15 -[WARNING] 'build.plugins.plugin.(groupId:artifactId)' must be unique but found duplicate declaration of plugin org.apache.maven.plugins:maven-compiler-plugin @ line 128, column 21 -[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: junit:junit:jar -> version 3.8.1 vs 4.12 @ line 138, column 15 -[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: mysql:mysql-connector-java:jar -> version 5.1.40 vs 5.1.46 @ line 215, column 15 -[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing. @ line 85, column 12 -[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing. @ line 12, column 21 -[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: com.jfinal:enjoy:jar -> duplicate declaration of version 5.1.2 @ line 125, column 21 -[ERROR] 'dependencies.dependency.version' for net.dreamlu:mica-auto:jar is missing. @ line 155, column 21 -[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: junit:junit:jar -> version ${junit.version} vs (?) @ line 161, column 21 -[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-source-plugin is missing. @ line 153, column 28 -[ERROR] 'dependencies.dependency.version' for cn.hutool:hutool-all:jar is missing. @ line 85, column 21 -[ERROR] 'dependencies.dependency.version' for net.dreamlu:mica-auto:jar is missing. @ line 90, column 21 -[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: com.baomidou:mybatis-plus-boot-starter:jar -> duplicate declaration of version (?) @ line 90, column 21 -[ERROR] 'dependencies.dependency.version' for com.baomidou:mybatis-plus-boot-starter:jar is missing. @ line 90, column 21 -[ERROR] 'dependencies.dependency.version' for com.alibaba:druid-spring-boot-starter:jar is missing. @ line 61, column 21 -[ERROR] 'dependencies.dependency.version' for net.dreamlu:mica-auto:jar is missing. @ line 94, column 21 -[ERROR] 'dependencies.dependency.version' for org.apache.dubbo:dubbo:jar is missing. @ line 106, column 21 -[ERROR] 'dependencies.dependency.version' for net.dreamlu:mica-auto:jar is missing. @ line 116, column 21 -[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: org.springframework.boot:spring-boot-configuration-processor:jar -> duplicate declaration of version (?) @ line 160, column 15 -[ERROR] 'dependencies.dependency.version' for com.github.tobato:fastdfs-client:jar is missing. @ line 44, column 21 -[ERROR] 'dependencies.dependency.version' for com.amazonaws:aws-java-sdk-s3:jar is missing. @ line 50, column 21 -[ERROR] 'dependencies.dependency.version' for com.baomidou:mybatis-plus-boot-starter:jar is missing. @ line 165, column 21 -[ERROR] 'dependencies.dependency.version' for net.dreamlu:mica-auto:jar is missing. @ line 173, column 15 -[ERROR] 'dependencies.dependency.version' for net.dreamlu:mica-auto:jar is missing. @ line 85, column 21 -[ERROR] 'dependencies.dependency.version' for com.baomidou:mybatis-plus-boot-starter:jar is missing. @ line 56, column 21 -[ERROR] 'dependencies.dependency.version' for com.alibaba:druid-spring-boot-starter:jar is missing. @ line 61, column 21 -[ERROR] 'dependencies.dependency.version' for net.dreamlu:mica-auto:jar is missing. @ line 91, column 21 -[WARNING] 'dependencyManagement.dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: cn.hutool:hutool-all:jar -> version ${hutool.version} vs 5.8.21 @ line 530, column 25 -[WARNING] 'build.plugins.plugin.version' for org.springframework.boot:spring-boot-maven-plugin is missing. @ line 93, column 21 -[WARNING] 'build.plugins.plugin.version' for org.springframework.boot:spring-boot-maven-plugin is missing. @ line 39, column 21 -[WARNING] 'build.plugins.plugin.version' for org.springframework.boot:spring-boot-maven-plugin is missing. @ line 61, column 15 -[WARNING] 'build.plugins.plugin.version' for org.springframework.boot:spring-boot-maven-plugin is missing. @ line 58, column 15 -[WARNING] 'build.plugins.plugin.version' for org.springframework.boot:spring-boot-maven-plugin is missing. @ line 49, column 15 -[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing. @ line 56, column 21 -[WARNING] 'build.plugins.plugin.version' for org.springframework.boot:spring-boot-maven-plugin is missing. @ line 65, column 21 -[WARNING] 'build.plugins.plugin.version' for org.springframework.boot:spring-boot-maven-plugin is missing. @ line 36, column 15 -[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: org.springframework.boot:spring-boot-starter-web:jar -> duplicate declaration of version (?) @ line 110, column 15 -[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing. @ line 211, column 12 -[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-war-plugin is missing. @ line 236, column 12 -[WARNING] 'build.plugins.plugin.version' for org.springframework.boot:spring-boot-maven-plugin is missing. @ line 45, column 12 -[WARNING] 'build.plugins.plugin.version' for org.springframework.boot:spring-boot-maven-plugin is missing. @ line 66, column 21 -[WARNING] 'build.plugins.plugin.version' for org.springframework.boot:spring-boot-maven-plugin is missing. @ line 66, column 21 -[WARNING] 'build.plugins.plugin.version' for org.springframework.boot:spring-boot-maven-plugin is missing. @ line 73, column 21 -[WARNING] 'build.plugins.plugin.version' for org.springframework.boot:spring-boot-maven-plugin is missing. @ line 73, column 21 -[WARNING] 'build.plugins.plugin.version' for org.springframework.boot:spring-boot-maven-plugin is missing. @ io.github.wujun728:springboot_oauth2:1.0, D:\workspace_github_v2\10\jun_java_plugin\jun_springboot_plugin\springboot_oauth2\pom.xml, line 48, column 21 -[WARNING] 'build.plugins.plugin.version' for org.springframework.boot:spring-boot-maven-plugin is missing. @ line 48, column 21 -[WARNING] 'build.plugins.plugin.version' for org.springframework.boot:spring-boot-maven-plugin is missing. @ line 63, column 12 -[WARNING] 'build.plugins.plugin.version' for org.springframework.boot:spring-boot-maven-plugin is missing. @ line 64, column 15 -[WARNING] 'build.plugins.plugin.version' for org.springframework.boot:spring-boot-maven-plugin is missing. @ line 69, column 15 -[WARNING] 'build.plugins.plugin.version' for org.springframework.boot:spring-boot-maven-plugin is missing. @ line 106, column 21 -[WARNING] 'build.plugins.plugin.version' for org.springframework.boot:spring-boot-maven-plugin is missing. @ line 93, column 21 -[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-javadoc-plugin is missing. @ line 58, column 21 -[WARNING] 'build.plugins.plugin.version' for org.springframework.boot:spring-boot-maven-plugin is missing. @ line 68, column 21 -[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: org.projectlombok:lombok:jar -> duplicate declaration of version (?) @ line 96, column 21 -[WARNING] The expression ${artifactId} is deprecated. Please use ${project.artifactId} instead. @ -[WARNING] 'build.plugins.plugin.version' for org.springframework.boot:spring-boot-maven-plugin is missing. @ line 77, column 15 -[WARNING] 'build.plugins.plugin.version' for org.springframework.boot:spring-boot-maven-plugin is missing. @ line 55, column 21 -[WARNING] 'build.plugins.plugin.version' for org.springframework.boot:spring-boot-maven-plugin is missing. @ line 58, column 12 -[WARNING] 'build.plugins.plugin.version' for org.springframework.boot:spring-boot-maven-plugin is missing. @ line 58, column 12 -[WARNING] 'build.plugins.plugin.version' for org.springframework.boot:spring-boot-maven-plugin is missing. @ line 64, column 21 -[WARNING] 'build.plugins.plugin.version' for org.springframework.boot:spring-boot-maven-plugin is missing. @ line 33, column 21 -[WARNING] 'build.plugins.plugin.version' for org.springframework.boot:spring-boot-maven-plugin is missing. @ line 51, column 12 -[WARNING] 'build.plugins.plugin.version' for org.springframework.boot:spring-boot-maven-plugin is missing. @ line 66, column 21 -[WARNING] 'build.plugins.plugin.version' for org.springframework.boot:spring-boot-maven-plugin is missing. @ line 72, column 21 - @ -[ERROR] The build could not read 8 projects -> [Help 1] -[ERROR] -[ERROR] The project (D:\workspace_github_v2\10\jun_java_plugin\jun_springboot_starter\jun-onlineForm-spring-boot-starter\pom.xml) has 1 error -[ERROR] Non-parseable POM D:\workspace_github_v2\10\jun_java_plugin\jun_springboot_starter\jun-onlineForm-spring-boot-starter\pom.xml: Unrecognised tag: 'scope' (position: START_TAG seen ...\r\n ... @69:20) @ line 69, column 20 -> [Help 2] -[ERROR] -[ERROR] The project io.github.wujun728:jun-activerecord:1.0.25 (D:\workspace_github_v2\10\jun_java_plugin\jun_springboot_starter\jun-activerecord\pom.xml) has 1 error -[ERROR] 'dependencies.dependency.version' for net.dreamlu:mica-auto:jar is missing. @ line 155, column 21 -[ERROR] -[ERROR] The project io.github.wujun728:jun-uidgenerator-spring-boot-starter:1.0.25 (D:\workspace_github_v2\10\jun_java_plugin\jun_springboot_starter\jun-uidgenerator-spring-boot-starter\pom.xml) has 2 errors -[ERROR] 'dependencies.dependency.version' for cn.hutool:hutool-all:jar is missing. @ line 85, column 21 -[ERROR] 'dependencies.dependency.version' for net.dreamlu:mica-auto:jar is missing. @ line 90, column 21 -[ERROR] -[ERROR] The project io.github.wujun728:jun-snakerflow-spring-boot-starter:1.0.25 (D:\workspace_github_v2\10\jun_java_plugin\jun_springboot_starter\jun-snakerflow-spring-boot-starter\pom.xml) has 3 errors -[ERROR] 'dependencies.dependency.version' for com.baomidou:mybatis-plus-boot-starter:jar is missing. @ line 90, column 21 -[ERROR] 'dependencies.dependency.version' for com.alibaba:druid-spring-boot-starter:jar is missing. @ line 61, column 21 -[ERROR] 'dependencies.dependency.version' for net.dreamlu:mica-auto:jar is missing. @ line 94, column 21 -[ERROR] -[ERROR] The project io.github.wujun728:jun-log-spring-boot-starter:1.0.25 (D:\workspace_github_v2\10\jun_java_plugin\jun_springboot_starter\jun-log-spring-boot-starter\pom.xml) has 2 errors -[ERROR] 'dependencies.dependency.version' for org.apache.dubbo:dubbo:jar is missing. @ line 106, column 21 -[ERROR] 'dependencies.dependency.version' for net.dreamlu:mica-auto:jar is missing. @ line 116, column 21 -[ERROR] -[ERROR] The project io.github.wujun728:jun-oss-spring-boot-starter:1.0.25 (D:\workspace_github_v2\10\jun_java_plugin\jun_springboot_starter\jun-oss-spring-boot-starter\pom.xml) has 4 errors -[ERROR] 'dependencies.dependency.version' for com.github.tobato:fastdfs-client:jar is missing. @ line 44, column 21 -[ERROR] 'dependencies.dependency.version' for com.amazonaws:aws-java-sdk-s3:jar is missing. @ line 50, column 21 -[ERROR] 'dependencies.dependency.version' for com.baomidou:mybatis-plus-boot-starter:jar is missing. @ line 165, column 21 -[ERROR] 'dependencies.dependency.version' for net.dreamlu:mica-auto:jar is missing. @ line 173, column 15 -[ERROR] -[ERROR] The project io.github.wujun728:jun-sentinel-spring-boot-starter:1.0.25 (D:\workspace_github_v2\10\jun_java_plugin\jun_springboot_starter\jun-sentinel-spring-boot-starter\pom.xml) has 1 error -[ERROR] 'dependencies.dependency.version' for net.dreamlu:mica-auto:jar is missing. @ line 85, column 21 -[ERROR] -[ERROR] The project io.github.wujun728:jun-job-spring-boot-starter:1.0.25 (D:\workspace_github_v2\10\jun_java_plugin\jun_springboot_starter\jun-job-spring-boot-starter\pom.xml) has 3 errors -[ERROR] 'dependencies.dependency.version' for com.baomidou:mybatis-plus-boot-starter:jar is missing. @ line 56, column 21 -[ERROR] 'dependencies.dependency.version' for com.alibaba:druid-spring-boot-starter:jar is missing. @ line 61, column 21 -[ERROR] 'dependencies.dependency.version' for net.dreamlu:mica-auto:jar is missing. @ line 91, column 21 -[ERROR] -[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. -[ERROR] Re-run Maven using the -X switch to enable full debug logging. -[ERROR] -[ERROR] For more information about the errors and possible solutions, please read the following articles: -[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException -[ERROR] [Help 2] http://cwiki.apache.org/confluence/display/MAVEN/ModelParseException diff --git "a/doc/#### wujun\344\270\252\344\272\272\345\274\200\345\217\221\344\275\234\345\223\201\351\233\206\357\274\210\346\214\201\347\273\255\346\233\264\346\226\260\357\274\211###.md" "b/doc/#### wujun\344\270\252\344\272\272\345\274\200\345\217\221\344\275\234\345\223\201\351\233\206\357\274\210\346\214\201\347\273\255\346\233\264\346\226\260\357\274\211###.md" deleted file mode 100644 index 8eec2422a1..0000000000 --- "a/doc/#### wujun\344\270\252\344\272\272\345\274\200\345\217\221\344\275\234\345\223\201\351\233\206\357\274\210\346\214\201\347\273\255\346\233\264\346\226\260\357\274\211###.md" +++ /dev/null @@ -1,819 +0,0 @@ -## [俊哥个人技术栈代码库(持续更新)](https://github.com/wujun728) --------------------------------------------------------------------------------------------------------------- - -#### 产品篇:[产品及解决方案(重点)][jun_product_center,jun_website,wujun728.github.io] - -> 企业信息化系统: - -【企业TPG门户系统】[仿中软国际TPG门户系统](https://github.com/wujun728/jun_product/jun_portal/)
-【企业财经服务系统】[产品功能说明](https://github.com/wujun728/jun_product/tree/master/jun_finance)
-【企业HR服务系统】[产品功能说明](https://github.com/wujun728/jun_product/jun_hr)
-【企业项目管理系统】[产品功能说明](https://github.com/wujun728/jun_product/jun_project)
-【企业OA系统】[产品功能说明](https://github.com/wujun728/jun_product/jun_oa)
-【企业CRM系统】[产品功能说明](https://github.com/wujun728/jun_product/jun_crm)
-【企业ERP系统】[产品功能说明](https://github.com/wujun728/jun_product/jun_erp)
-【企业信息管理系统】[产品功能说明](https://github.com/wujun728/jun_product/jun_mis)
-【Blog管理系统】[产品功能说明](https://github.com/wujun728/jun_product/jun_blog)
-【俊哥的个人简历】[产品功能说明](https://github.com/wujun728/jun_product/jun_resume)
-【企业官网门户】[产品功能说明,企业网站产品,网站开发](https://github.com/wujun728/jun_website/jun_official_website)
-【企业CMS系统】[产品功能说明](https://github.com/wujun728/jun_website/jun_cms)
-【WordPress】[基于WordPress的CMS管理系统](https://github.com/wujun728/jun_website/jun_wordpress)
- -#### 移动篇:产品及解决方案(重点) [jun_android,jun_app,jun_weixin] - -> APP开发框架 jun_app, APP开发,Android开发,Vue+uniapp+Nodejs+Bigdata: - -【Android程序开发】[产品功能说明](https://github.com/wujun728/jun_android)
-【H5混合App程序开发】[产品功能说明](https://github.com/wujun728/jun_app)
- -> 微信开发框架, 微信开发 [jun_weixin] - -【微信小程序】[产品功能说明](https://github.com/wujun728/jun_weixin/weixin_miniprogram)
-【微信小程序管理系统】[产品功能说明](https://github.com/wujun728/jun_weixin/weixin_manager)
-【微信公众号】[产品功能说明](https://github.com/wujun728/jun_weixin//weixin_product)
-【微信公众号管理系统】[产品功能说明](https://github.com/wujun728/jun_weixin/weixin_manager)
-【微信工具系统-爬虫-代码生成器】[产品功能说明](https://github.com/wujun728/jun_weixin/weixin_crawler)
-【微信推送更新订阅管理系统】[产品功能说明](https://github.com/wujun728/jun_weixin/weixin_push)
- --------------------------------------------------------------------------------------------------------------- -#### 大数据篇:大数据场景,大数据开发,Hadoop、Spark、Strom开发 [jun_bigdata,jun_linux] - -【Hadoop大数据】[Spring连接Hadoop实现CRUD](https://github.com/wujun728/jun_bigdata/Spring-mongoDB)
-【Spark大数据】[Spring连接Spark实现CRUD](https://github.com/wujun728/jun_bigdata/Spring-mongoDB)
-【MongoDB数据库】[Spring连接mongoDB数据库实现增删改查](https://github.com/wujun728/jun_bigdata/Spring-mongoDB)
-【Oracle数据库】[实现Oracle数据库的CRUD](https://github.com/wujun728/jun_bigdata/Spring-redis)
-【MySQL数据库】[实现Mysql数据库的主从复制、读写分离、分表分库、负载均衡和高可用](https://github.com/wujun728/jun_bigdata/Spring-redis)
-【H2数据库】[Spring连接H2数据库实现CRUD](https://github.com/wujun728/jun_bigdata/Spring-redis)
-【SQLite数据库】[Spring连接SQLite实现CRUD](https://github.com/wujun728/jun_bigdata/Spring-redis)
-【Neo4j图数据库】[Spring连接图存数据库Neo4j实现增删改查](https://github.com/wujun728/jun_bigdata/Spring-neo4j)
-【ETL数据转换Kettle】[使用ETL工具Kettle的实例](https://github.com/wujun728/jun_bigdata/Kettle-demo)
-【Zeppelin数据分析】[使用数据仓库进行OLAP数据分析(Mysql+Kettle+Zeppelin)](https://github.com/wujun728/jun_bigdata)
- --------------------------------------------------------------------------------------------------------------- -#### 微服务篇:基于Spring系微服务[jun_springcloud,jun_springboot] - -【微服务快速开发平台SpringCoud】[产品功能说明](https://github.com/wujun728/jun_cloud)
-【微服务快速开发平台SpringBoot】[产品功能说明](https://github.com/wujun728/jun_boot)
-【SpringBoot微服务】[基于SpringBoot实现各种服务应用](https://github.com/wujun728/jun_cloud)
-【SpringCloud微服务Netflex】[基于SpringCloud2.1的微服务开发脚手架,整合了oauth2、nacos、gateway等](https://github.com/zhoutaoo/SpringCloud)
-【SpringCloud微服务2020】[基于SpringCloud2020最新版构建微服务框架](https://github.com/wujun728/jun_cloud)
-【SpringCloudAlibaba微服务】[基于SpringCloudAlibaba提供微服务开发的一站式解决方案](https://github.com/wujun728/jun_cloud)
-【ApacheDubbo微服务】[基于Dubbo实现高性能、轻量级的Java微服务框架](https://github.com/wujun728/jun_cloud)
-【分布式session】[Spring框架的session模块实现集中式session管理 ](https://github.com/wujun728/jun_cloud)
-【分布式文件】[使用FastDFS搭建分布式文件系统(高可用、负载均衡)](https://github.com/wujun728/jun_cloud/Spring-fastdfs)
-【分布式事务】[基于可靠消息最终一致性实现分布式事务(activeMQ),使用TCC框架实现分布式事务]
-【高并发事务】[高并发,数据库锁机制和事务隔离级别的实现](https://github.com/wujun728/jun_cloud)
-【分布式锁】[高并发:使用redis实现分布式锁,使用zookeeper实现分布式锁](https://github.com/wujun728/jun_cloud)
-【线程池&异步现场】[高并发:Java多线程编程实例 ](https://github.com/wujun728/jun_cloud)
-【高性能NIO】[高并发:使用netty实现高性能NIO通信]
-【dubbo RPC服务】[Spring boot整合Apache dubbo v2.7实现分布式服务治理(SOA架构)]
-【Spring Cloud微服务】[使用Spring Cloud实现微服务架构(MSA架构)]
-【Redis&Redis Cluster】[基于Redis集群实现分布式缓存](https://github.com/wujun728/jun_cloud/Spring-redis)
-【分库分表Mycat】[实现Mysql数据库的主从复制、读写分离、分表分库、负载均衡和高可用](https://github.com/wujun728/jun_cloud/Spring-redis)
- -> Linux环境部署&架构&分布式&高并发,Linux环境部署、各种中间件部署 [jun_linux] - -【Gitlib&SVN服务&搭建】[Git指南和分支管理策略 - -吴俊: -【Gitlib&SVN服务&搭建】[Git指南和分支管理策略](https://github.com/wujun728/jun_linux)
-【Nginx集群】[搭建高可用nginx集群和Tomcat负载均衡](https://github.com/wujun728/jun_linux)
-【zookeeper注册中心】[产品功能说明](https://github.com/wujun728/jun_linux)
-【jenkins自动化部署】[使用jenkins+git+maven搭建持续集成环境自动化部署分布式服务]
-【Docker微服务自动化】[使用docker+jenkins+gitlab+spring cloud实现微服务的编排、持续集成和动态扩容]
-【kubernetes服务编排】[基于Kubernetes实现服务编排、自动部署,扩展和管理容器化]
- --------------------------------------------------------------------------------------------------------------- - -#### 基础篇:企业级开发组件(开发组件、代码生成、前端组件) [jun_java_plugin,jun_ssm,jun_frontend_ui] - -> Java基础系开发组件jun_plugin 常用开发组件,调整,新增并优化项目组件: - -【Java基础】[文件上传下载,邮件、Echart报表、二维码,开发工具](https://github.com/wujun728/jun_plugin/jun_redis)
-【设计模式】[23种设计模式及常见数据结构与算法](https://github.com/wujun728/jun_plugin/SSM)
- -> Spring系开发框架组件 Spring常用开发组件,万能粘合剂,企业级J2EE实际标准平台 - -【SSH框架】[Struts2,Hibernate,Spring三大框架](https://github.com/wujun728/jun_spring_plugin/S2SH)
-【SSM框架】 [SpringMVC,Mybatis,Spring三大框架](https://github.com/wujun728/jun_spring_plugin/SSM)
-【SSH框架2】 [Spring,SpringMVC和Hibernate的整合实现增删改查](https://github.com/wujun728/jun_spring_plugin/SSH)
-【SSM微服务】[使用Spring boot整合mybatis,rabbitmq,redis,mongodb实现增删改查](https://github.com/wujun728/jun_spring_plugin)
-【Activiti工作流】 [Spring平台整合activiti工作流引擎实现OA开发](https://github.com/wujun728/jun_spring_plugin/Spring-activiti)
-【WebService服务】 [Spring发布与调用REST风格的WebService](https://github.com/wujun728/jun_spring_plugin/Spring-REST)
-【Shiro权限控制】 [Spring整合Apache Shiro框架,实现用户管理和权限控制](https://github.com/wujun728/jun_spring_plugin/Spring-shiro)
-【Spring security权限控制】 [使用Spring security做权限控制](https://github.com/wujun728/jun_spring_plugin/spring-security-demo)
-【Quartz定时JOB】[SpringTask 使用Spring security做权限控制](https://github.com/wujun728/jun_spring_plugin/spring-security-demo)
-【Lucence搜索】[SpringTask 使用Spring security做权限控制](https://github.com/wujun728/jun_spring_plugin/spring-security-demo)
-【ActiveMQ消息队列】[Spring平台整合消息队列ActiveMQ实现发布订阅、生产者消费者模型(JMS)](https://github.com/wujun728/jun_spring_plugin/Spring-activeMQ)
-【RabbitMQ消息队列】[Spring整合消息队列RabbitMQ实现四种消息模式(AMQP)](https://github.com/wujun728/jun_spring_plugin/Spring-rabbitMQ)
-【Websocket协议】[Spring整合websocket实现即时通讯](https://github.com/wujun728/jun_spring_plugin/Spring-websocket)
-【Elastic search全文检索】[Spring整合Elastic search实现全文检索](https://github.com/wujun728/jun_spring_plugin/Spring-elastic_search)
-【单点登录】[Spring整合CAS框架&JWT实现单点登录](https://github.com/wujun728/jun_spring_plugin/Spring-cas-sso)
- -Java基础系开发组件,代码生成器&开发模板,基于freemarker及MetaData&SQL解析的代码生成器 -【Java代码生成模块】[数据库表代码生成、页面代码生成](https://github.com/wujun728/jun_code_generator/jun_code_helper)
-【Mybatis代码生成模块】[Mybatis代码生成](https://github.com/wujun728/jun_code_generator)
-【MybatisPlus代码生成模块】[Mybatis-Plus代码生成](https://github.com/wujun728/jun_code_generator)
-【Maven项目模板】常用项目开发模板,新增SSH、SSM、Boot、Cloud、Android、APP模板 - -> 前端系开发框架[jun_frontend_ui]: - -【JQueryEasyUI】[基于JQuery的前端UI组件快速开发框架](https://github.com/wujun728/jun_frontend)
-【LayUI框架】[经典模块化前端UI 框架](https://github.com/wujun728/jun_frontend/)
-【Bootstrap框架】[前端响应式CSS/HTML框架](https://github.com/wujun728/jun_frontend)
-【Vue框架】[前端、构建用户界面的渐进式JavaScript框架](https://github.com/wujun728/jun_frontend)
- - - - - -> > jun_code_generator 代码生成器 -> > 为ssh项目写个代码生成器 -> > mvn_template 开发模板,调整,新增项目模板; -> > 新增SSH、SSM、SpringBoot、SpringCloud、Android、APP -> > 模板,新增+jun_ssh+ssm+springboot+mybatis+JPA - -1、精简代码生成器 -2、拆分成多个模块 -3、切换freemarker -4、使用公共的数据源 -5、维护多套模板-ssh - -> > jun_plugin -> > jun_java_plugin 常用开发组件,调整,新增并优化项目组件 -> > https://github.com/whirlys/Elastic-In-Practice/tree/master/guava -> > fileServer-master\ -> > fileServer-master (1)\ -> > haima-front-dist-master\ -> > jun_spring Spring开发组件,调整,新增Spring系常用plugin -> > jun_springboot SpringBoot开发组件,调整,SpringBoot系组件 - -> > jun_ssh_parent -> > Jun_ssh_eaayui -> > Jun_ssh_springboot -> > jun_ssm_parent -> > 整理ssm项目,写模板,模板还没梳理完 -> > 美化ssh项目 -> > https://github.com/doujinxian/renren-security -> > jun_springboot -> > jun_frontend_ui -> > jun_springcloud -> > SpringCloud开发组件,调整,SpringCloud系组件 -> > Vue+uniapp+Nodejs+WordPress+PHP+Android+Bigdata 。 -> > https://github.com/wujun728/vue-login-java -> > https://blog.csdn.net/xiaojinlai123/article/details/90694372 -> > https://blog.csdn.net/sxdtzhaoxinguo/article/details/77965226 -> > jun_linux -> > Linux开发组件,调整 -> > jun_website -> > https://github.com/zhangdaiscott/luban-h5 -> > https://github.com/zhangdaiscott/h5huodong -> > jun_bigdata - -吴俊: -jun_website -https://github.com/zhangdaiscott/luban-h5 -https://github.com/zhangdaiscott/h5huodong -jun_bigdata -jun_product_center -常用项目模板及常用项目,调整,常用项目的集合,私有的 -财务系统 -OA办公系统 -https://github.com/hjp1011/uniapp-oa -http://www.yiiframe.com/ -后端源码:官网下载 -https://github.com/misstt123/oasys -https://github.com/yunchaoyun/active4j-oa -https://github.com/yunchaoyun/active4j-jsp       -HR服务系统 -CRM客户关系 -行政服务系统 -问答系统 -知识学习系统 -jun_weixin -微信开发,调整 -weixin_api -weixin_boot -weixin_manager -jun_android -jun_app -APP开发,调整 -jun_uniapp -https://github.com/chenbool/uniapp-douyin -jun_app_cms - -待办: -https://github.com/lerry903/spring-boot-api-project-seed -https://github.com/jackying/H-ui.admin -https://github.com/xiaoshaDestiny/spring-cloud-2020 - -https://github.com/stylefeng/Guns -https://github.com/jsnjfz/WebStack-Guns -https://github.com/1477551037/exam -https://github.com/itd2008/My-Blog -https://github.com/qiaokun-sh/spring-token - -https://github.com/wujun728/inspinia_admin_java_ssm - -https://github.com/xwjie/ElementVueSpringbootCodeTemplate -https://github.com/RudeCrab/rude-java -https://github.com/Wjhsmart/Front-end-UI -https://github.com/zongjl/JavaWeb -https://github.com/zongjl/Jeebase -https://github.com/xzt1995/nideshop-springboot - -fsLayui -VIEWUI-FOR-EASYUI 迁移到UI -spring-boot-starter-motan -java -layoutit -Personnel-Management-System -fiction_house -inspinia_admin_java_ssm -springboot-mui -Jobs-search -xxyms———————————————————————————————————————————————————————————————————————————————————————————————————————— -​ - -TODO PLAN: - -1、清空readme,新增readme图片,新增胶片方案模板供截图 -2、调整package,调整author,调整每个工程大小,调整每个项目jar包 -3、调整每个项目运行 -4、mvn_template 开发模板,调整,新增项目模板;新增 - -jun_code_generator -0、默认生成模板调整,默认下载zip包调整 -1、代码生成器jun_code_generator 默认提供Spring、Hibernate、MyBatis、Spring JDBC模板 -2、代码生成器,将easyexcel的demo合并到code_generator -3、代码生成器的模板跟maven_template再整一下 -4、代码生成器新模板 - Ssm+easyUI - SSM+jwt+layui - boot+Bootstrap - boot+jwt+vue -5、单表生成 -6、关联表生成 -7、整理ssm项目 -8、整理boot项目 -9、SSH、SSM、SpringBoot、SpringCloud、Android、APP模板, -10、新增+jun_ssh+ssm+springboot+mybatis+JPA -jun_springboot_vue -1、ruoyi-vue-pro    ---迁移到 -jun_product_center 产品中心,常用项目模板及常用项目工程,调整,常用项目的集合,私有的 -0、整chinasoft的login.html跟index.html的page,适配Nginx跟ssm_jwt; -1、整理cs的login页面 -2、整理cs的index页面 -3、整理layui的静态前端页面并归档 -4、整理adminlte及hplus -5、整理easyui的前端页面并归档 -6、整理代码生成器 -先根据邮件去掉非必须的项目 -综合配置login及index的页面的归档 - -wujun728.github.io -jun_springcloud -jun_linux    Linux开发组件 -Nginx优化,nginx优化单台机器抗10万并发 -https://www.jianshu.com/p/5149a7a700b9 -jun_weixin   微信开发 -jun_android Android开发 -jun_app    APP开发,Vue+uniapp+Nodejs++Android -jun_temp    临时仓库,干掉 -jun_website    网站开发,以WordPress+网站模板为主 -jun_bigdata   大数据开发 - -https://blog.csdn.net/yf275908654/article/details/50171607 - -  - -Ssh_parent -aicode\      干掉 -authority\ jsp hplus boot jpa -biu\   迁移到vue里面 -mis\ 干掉 -ShiroJwt\ 迁移到vue里面 - -不要的东西删掉,重新拟定计划跟技术选型及产品 -1、新增产品规划,产品及技术选型 -2、先技术规划,技术规划 -3、新增管理规划,功能点补充及二次开发规划 -4、功能地图及产品中心规划 -5、整理胶片的模板发挥架构的优势 - -###TODO待办清单 -NOTE20210311 -jun_2021\ -jun_framework\ -jun_ssm\ -jun_test\ -jun_test11\ -About -代码生成器jun_code_generator 默认提供Spring、Hibernate、MyBatis、Spring JDBC模板,也可以根据FreeMarker语法编写自定义模板生成代码。 - -https://www.bejson.com/ -Nginx优化 -https://www.jianshu.com/p/5149a7a700b9 -Netty -https://blog.csdn.net/yuanzhenwei521/article/details/79194275 - -jun_boot -jun_plugin -jun_weixin -jun_ssm -jun_cloud -jun_app -jun_website -fsLayui -VIEWUI-FOR-EASYUI -spring-boot-starter-motan -java -layoutit -Personnel-Management-System -fiction_house -inspinia_admin_java_ssm -springboot-mui -Jobs-search -xxyms -jun_temp1\ -jun_temp2\ -TODO PLAN: - -Vue+uniapp+Nodejs+WordPress+PHP+Android+Bigdata - -https://blog.csdn.net/xiaojinlai123/article/details/90694372 -https://blog.csdn.net/sxdtzhaoxinguo/article/details/77965226 - -https://github.com/moshowgame/SpringBootCodeGenerator -https://github.com/SpringCloud/spring-cloud-codegen -http://hub.fastgit.org/thinkgem/jeesite_autocode - -Readme.md template - -plugin -https://github.com/RudeCrab/rude-java/tree/master/project-practice - -干掉,放到plugin里面 -https://github.com/wujun728/jun_frontend_ui - -boot - -https://github.com/wujun728/jun_springboot  -合并到jun_ssm,并重命名 - -https://github.com/wangyushuai/inspinia_admin_java_ssm - -前端模板-合并到front里面 -https://github.com/wenfengSAT/wenfengSAT-UI -迁移到CRM里面 -https://github.com/wenfengSAT/SpringbootCRM -迁移到plugin里面 -https://github.com/wenfengSAT/wenfengSAT-SpringBoot -迁移到uniapp里面 -https://github.com/fanchaoo/netease-cloud-music-community -待处理: -迁移到cloud里面 -fsLayui -VIEWUI-FOR-EASYUI -spring-boot-starter-motan -总体待办: -吴俊-补充TODO待办清单 -Jun_code-generator -临时分支 - -Jun_code_generator -doc\ - simple-fast-generator\   合并到code_mplus - -jun_code_generator\ - hub.fastgit.org/alibaba/easyexcel - 集成easyexcel读取文件的功能noModelRead -jun_code_mybatis\ -jun_code_mybatisplus\   - -### 附录:个人作品索引目录(持续更新) - -#### 基础篇:职业化,从做好OA系统开始 -1. [Spring boot整合Mybatis实现增删改查(支持多数据源)](https://gitee.com/shenzhanwang/SSM)![输入图片说明](https://img.shields.io/badge/-%E7%B2%BE%E5%93%81-orange.svg "在这里输入图片标题") -2. [Struts2,Hibernate,Spring三大框架的整合实现增删改查](https://gitee.com/shenzhanwang/S2SH) -3. [Spring,SpringMVC和Hibernate的整合实现增删改查](https://gitee.com/shenzhanwang/SSH) -4. [Spring平台整合activiti工作流引擎实现OA开发](https://gitee.com/shenzhanwang/Spring-activiti)![输入图片说明](https://img.shields.io/badge/-%E7%B2%BE%E5%93%81-orange.svg "在这里输入图片标题") -5. [Spring发布与调用REST风格的WebService](https://gitee.com/shenzhanwang/Spring-REST) -6. [Spring整合Apache Shiro框架,实现用户管理和权限控制](https://gitee.com/shenzhanwang/Spring-shiro) -7. [使用Spring security做权限控制](https://gitee.com/shenzhanwang/spring-security-demo) -8. [Spring整合Jasig CAS框架实现单点登录](https://gitee.com/shenzhanwang/Spring-cas-sso) -#### 中级篇:中间件的各种姿势 -9. [Spring连接mongoDB数据库实现增删改查](https://gitee.com/shenzhanwang/Spring-mongoDB) -10. [Spring连接Redis实现缓存](https://gitee.com/shenzhanwang/Spring-redis) -11. [Spring连接图存数据库Neo4j实现增删改查](https://gitee.com/shenzhanwang/Spring-neo4j) -12. [Spring平台整合消息队列ActiveMQ实现发布订阅、生产者消费者模型(JMS)](https://gitee.com/shenzhanwang/Spring-activeMQ) -13. [Spring整合消息队列RabbitMQ实现四种消息模式(AMQP)](https://gitee.com/shenzhanwang/Spring-rabbitMQ) -14. Spring框架的session模块实现集中式session管理 [购买](http://t.cn/Ai80zekN) -15. [Spring整合websocket实现即时通讯](https://gitee.com/shenzhanwang/Spring-websocket)![输入图片说明](https://img.shields.io/badge/-%E7%B2%BE%E5%93%81-orange.svg "在这里输入图片标题") -16. 使用Spring boot整合mybatis,rabbitmq,redis,mongodb实现增删改查 [购买](http://t.cn/Ai8Yh8Oy) -17. [Spring MVC整合FastDFS客户端实现文件上传](https://gitee.com/shenzhanwang/Spring-fastdfs) -18. 23种设计模式,源码、注释、使用场景 [购买](http://t.cn/Ai8Y7tEF) -19. [使用ETL工具Kettle的实例](https://gitee.com/shenzhanwang/Kettle-demo) -20. Git指南和分支管理策略 [购买](http://t.cn/Ai8Y7948) -21. 使用数据仓库进行OLAP数据分析(Mysql+Kettle+Zeppelin) ![输入图片说明](https://img.shields.io/badge/-%E7%B2%BE%E5%93%81-orange.svg "在这里输入图片标题")[购买](http://t.cn/Ai8Y7dVD) -#### 高级篇:架构之美 -22. [zookeeper原理、架构、使用场景和可视化](https://gitee.com/shenzhanwang/zookeeper-practice) -23. Spring boot整合Apache dubbo v2.7.5实现分布式服务治理(SOA架构) ![输入图片说明](https://img.shields.io/badge/-%E7%B2%BE%E5%93%81-orange.svg "在这里输入图片标题") [购买](https://dwz.lc/beP9N33) -> 包含组件Spring boot v2.2.2+Dubbo v2.7.5+Nacos v1.1.1 -效果图 -24. 使用Spring Cloud Alibaba v2.1.0实现微服务架构(MSA架构)![输入图片说明](https://img.shields.io/badge/-%E6%8B%9B%E7%89%8C-yellow.svg) [购买](https://dwz.lc/IdmrHzd) -> 包含组件Nacos+Feign+Gateway+Ribbon+Sentinel+Zipkin -效果图 -25. 使用jenkins+centos+git+maven搭建持续集成环境自动化部署分布式服务 [购买](http://t.cn/Ai8YZbaX) -26. 使用docker+compose+jenkins+gitlab+spring cloud实现微服务的编排、持续集成和动态扩容 [购买](http://t.cn/Ai8YZCYK) -27. 使用FastDFS搭建分布式文件系统(高可用、负载均衡)[购买](http://t.cn/Ai8YZePu) -28. 搭建高可用nginx集群和Tomcat负载均衡 [购买](http://t.cn/Ai8Ywlr8) -29. 搭建可扩展的ActiveMQ高可用集群 [购买](http://t.cn/Ai8YAbA8) -30. 实现Mysql数据库的主从复制、读写分离、分表分库、负载均衡和高可用 [购买](http://t.cn/Ai8YAOAK) -31. 搭建高可用redis集群实现分布式缓存 [购买](http://t.cn/Ai8Y2NQy) -32. [Spring boot整合Elastic search实现全文检索](https://gitee.com/shenzhanwang/Spring-elastic_search) ![输入图片说明](https://img.shields.io/badge/-%E6%8B%9B%E7%89%8C-yellow.svg "在这里输入图片标题") -#### 特别篇:分布式事务和并发控制 -33. 基于可靠消息最终一致性实现分布式事务(activeMQ)[购买](http://t.cn/Ai8YLPBL) -34. Spring boot dubbo整合seata实现分布式事务![输入图片说明](https://img.shields.io/badge/-%E7%B2%BE%E5%93%81-orange.svg "在这里输入图片标题") [购买](https://dwz.lc/csO0rp2) -> 包含组件nacos v1.1.0 + seata v0.7.1 +spring boot dubbo v2.7.5 -效果图 -35. Spring cloud alibaba v2.1.0整合seata实现分布式事务 ![输入图片说明](https://img.shields.io/badge/-%E7%B2%BE%E5%93%81-orange.svg "在这里输入图片标题")[购买](https://dwz.lc/0T8KCTC) -> 包含组件nacos v1.1.0 + seata v0.7.1 +spring cloud alibaba v2.1.0 -效果图 -36. 决战高并发:数据库锁机制和事务隔离级别的实现![输入图片说明](https://img.shields.io/badge/-%E7%B2%BE%E5%93%81-orange.svg "在这里输入图片标题") [购买](http://t.cn/Ai8YyAQE) -37. 决战高并发:使用redis实现分布式锁 ![输入图片说明](https://img.shields.io/badge/-%E7%B2%BE%E5%93%81-orange.svg "在这里输入图片标题")[购买](http://t.cn/Ai8Y4bER) -38. 决战高并发:使用zookeeper实现分布式锁 [购买](http://t.cn/Ai8Y4Cuq) -39. 决战高并发:Java多线程编程实例 [购买](http://t.cn/Ai8Y4s0r) -40. 决战高并发:使用netty实现高性能NIO通信 [购买](http://t.cn/Ai8Ybq3e) - - -全套大礼包2020年版 - -1、jun_api_service -初始化API_Service -https://github.com/lihengming/spring-boot-api-project-seed -干掉jun_api-plugin - -2、jun_cache   ---干掉 -新增springcache -https://github.com/iamsixer/spring-cache-demo -https://github.com/zheng-zy/spring-boot-redis-guava-caffeine-cache - -3、camel 干掉,没啥用 - -4、jun_crawler 调整,跑起来,净化 - -5、jun_datasource_cluster rename 到 DataSource -新增 https://github.com/ran-jit/tomcat-cluster-redis-session-manager - -6、分解jun_dbutils -https://github.com/objcoding/jdbc-utils - -7、jun_demo rename到 jun_test - -8、设计模式,合并到一起,分三种合并,中文转英文 - -9、jun_note 新增 -https://github.com/GourdErwa/review-notes - -10、新增jun_webservlet_guice_dbutil -https://www.cnblogs.com/huzi007/p/5802022.html -https://www.cnblogs.com/huzi007/p/5796372.html - -11、drools https://github.com/maxxbwsDemo - -12、email 调整,清理 -https://github.com/biezhi/oh-my-email/blob/master/pom.xml -https://github.com/isliqian/NiceEmail - -13、excel 集成 easyexcel -https://github.com/HowieYuan/easyexcel-encapsulation -新增jun_poi demo - -14、jun_fileupload -https://github.com/wemakebug/FileUpload.Java -Spring fileupload -https://github.com/jdmr/fileUpload - -15、freemarker boot https://github.com/JavaCodeMood/freemarker - -16、guava -https://github.com/tiantiangao/guava-study -https://github.com/tfnico/guava-examples - -17、guice -https://github.com/timlien/servlet-guice -https://github.com/greengerong/guice-demo -https://github.com/lg625740749/GuiceDemo - -18、hibernate -https://github.com/hibernate/hibernate-demos - -19、httpclient -https://github.com/Arronlong/httpclientutil -https://github.com/JourWon/httpclientutil - -20、image -https://github.com/xuehuayous/ImageUpload -https://github.com/jmitchener/spring-images -https://github.com/woobong/spring-boot-jpa-summernote-image-upload-example -https://github.com/mrmodise/java-spring-file-upload - -21、jbpm4 -https://github.com/xxg3053/jbpm-study -https://github.com/American/workflow/tree/master/workflow - -22.jdk 清理,调整 - -23、lucenne -https://github.com/abel533/SearchEngine -https://github.com/doushini/lucene -https://github.com/pumadong/cl-search -Springboot+ElasticSearch -https://github.com/Motianshi/all-search - -24、pay -https://github.com/kongzhidea/pay -https://github.com/iyangyuan/pay-spring-boot - -Spring-cloud - -  - -41、 webmagic -https://github.com/scsfwgy/WebMagic_CSDN_Demo -https://github.com/EzioL/neteasemusic - -42、api_service -合并都api里面,其他的2个干掉 - -Spring -43、 jwt rename一下 -新增springboot jwt -https://github.com/dolyw/VueStudy/tree/master/VueStudy08-JWT -https://github.com/dolyw/ShiroJwt.git - -44、spring activemq -清理代码,优化test及readme -https://github.com/888xin/activeMQ - -45、camel 调整为zip里面的spring -46、cas 干掉 -新增oauth - -47、cors 调整为filter过滤器 - -48、config 迁移到cloud里面 - -49、fastdfs - -50、dubbo -https://github.com/GenshenWang/DubboDemo - -51、quartz -https://github.com/ameizi/spring-quartz-cluster-sample - -52、新增xxl-job -https://github.com/xuxueli/xxl-job - -53、email -https://github.com/fangjieDevp/spring-email-master - -54、Excel 干掉 - -55、hibernate -https://github.com/zhonglinlin1305/Spring -https://github.com/zhonglinlin1305/spring-projects/ - -0、Boot&cloud -https://github.com/zhonglinlin1305/spring-boot-sample/ -https://github.com/zhonglinlin1305/spring-cloud-microservice -https://github.com/SpringForAll/springcloud-thoth - -56、kafka -https://github.com/smallnest/spring-kafka-demo - -57、lucenne -https://github.com/FuZhucheng/SSM - -  - -00、boot starter -https://github.com/battcn/extend-spring-boot - -00、util -https://github.com/864381832/xJavaFxTool-spring - -00、ppt -https://github.com/aalansehaiyang/technology-talk - -1、plugin 代码全部梳理一遍,package/pom/test/readme -1、清理没用代码、工程pom、工程package、工程test、readme、截图、胶片 -2、ssh 代码合并到一个,调整功能 -1、清理没用代码、工程pom、工程package、工程test、readme、截图、胶片 -3、ssm 代码合并到一个,调整功能 -1、清理没用代码、工程pom、工程package、工程test、readme、截图、胶片 -4、代码生成器、代码一套,功能一套,合并ry_gen -https://www.jianshu.com/p/31e532392a74 -1、清理没用代码、工程pom、工程package、工程test、readme、截图、胶片 -5、ui 整理ui -1、清理没用代码、工程pom、工程package、工程test、readme、截图、胶片 -6、apiservice 代码一套,功能一套,同步ssm -1、清理没用代码、工程pom、工程package、工程test、readme、截图、胶片 -https://github.com/callicoder/spring-webflux-reactive-rest-api-demo -https://blog.csdn.net/qq_35067322/article/details/106935320 -https://github.com/dolyw/ShiroJwt -7、linux 部署文档,部署包、docker部署 -1、清理没用代码、工程pom、工程package、工程test、readme、截图、胶片 -部署环境 - -Step2 -main -https://github.com/Heeexy/SpringBoot-Shiro-Vue -jun_springboot_jwt_layui\   合并到ssm框架 -jun_springboot_jwt_shiro_api\   空的 -jun_springboot_vue\   干掉 -jun_springboot_vue_pro\ 合并到上面里面 - -Step4 -1、uniapp -https://github.com/zsptsf/uniapp.git -https://github.com/c1013529993/springboot-uniapp-21cake - -Step1 -Jdbc_template -https://gitee.com/jervain_y/repository - -https://github.com/horsecms/layuiCMS - -Step2 -1、vue-element-admin -https://github.com/panjiachen/vue-element-admin-site -https://panjiachen.github.io/vue-element-admin-site/zh/guide/ -2、cloud -https://www.8kee.com/article/17347.html -https://github.com/JourWon/springcloud-learning -https://github.com/wenren0819/Spring-Cloud-2020 -https://blog.csdn.net/ThinkWon/article/details/103726655 - -2、api_service -https://github.com/koocyton/reactor-guice -https://github.com/jwpttcg66/NettyGameServer -3、bigdata -爬虫 -https://github.com/brianway/webporter -ETL -https://github.com/zhaxiaodong9860/kettle-scheduler -数仓 -https://github.com/fenglei110/DataWarehouse -https://github.com/jd-bigdata/rtf-lake -https://github.com/xzt1995/Data-Warehouse -新增用户画像、用户行为 -https://github.com/monsonlee/BigData -https://github.com/whirlys/BigData-In-Practice -https://github.com/597365581/bigdata_tools -https://blog.csdn.net/u013967628/article/details/83656560 - -1、plugin 代码全部梳理一遍,package/pom/test/readme -1、清理没用代码、工程pom、工程package、工程test、readme、截图、胶片 -2、ssh 代码合并到一个,调整功能 -1、清理没用代码、工程pom、工程package、工程test、readme、截图、胶片 -3、ssm 代码合并到一个,调整功能 -1、清理没用代码、工程pom、工程package、工程test、readme、截图、胶片 -4、代码生成器、代码一套,功能一套,合并ry_gen -https://www.jianshu.com/p/31e532392a74 -1、清理没用代码、工程pom、工程package、工程test、readme、截图、胶片 -5、ui 整理ui -1、清理没用代码、工程pom、工程package、工程test、readme、截图、胶片 -6、apiservice 代码一套,功能一套,同步ssm -1、清理没用代码、工程pom、工程package、工程test、readme、截图、胶片 -https://github.com/callicoder/spring-webflux-reactive-rest-api-demo -https://blog.csdn.net/qq_35067322/article/details/106935320 -https://github.com/dolyw/ShiroJwt -7、linux 部署文档,部署包、docker部署 -1、清理没用代码、工程pom、工程package、工程test、readme、截图、胶片 -部署环境 - -Step2 -main -https://github.com/Heeexy/SpringBoot-Shiro-Vue -jun_springboot_jwt_layui\   合并到ssm框架 -jun_springboot_jwt_shiro_api\   空的 -jun_springboot_vue\   干掉 -jun_springboot_vue_pro\ 合并到上面里面 - -Step4 -1、uniapp -https://github.com/zsptsf/uniapp.git -https://github.com/c1013529993/springboot-uniapp-21cake - -Step1 -Jdbc_template -https://gitee.com/jervain_y/repository - -https://github.com/horsecms/layuiCMS - -Step2 -1、vue-element-admin -https://github.com/panjiachen/vue-element-admin-site -https://panjiachen.github.io/vue-element-admin-site/zh/guide/ -2、cloud -https://www.8kee.com/article/17347.html -https://github.com/JourWon/springcloud-learning -https://github.com/wenren0819/Spring-Cloud-2020 -https://blog.csdn.net/ThinkWon/article/details/103726655 - -2、api_service -https://github.com/koocyton/reactor-guice -https://github.com/jwpttcg66/NettyGameServer -3、bigdata -爬虫 -https://github.com/brianway/webporter -ETL -https://github.com/zhaxiaodong9860/kettle-scheduler -数仓 -https://github.com/fenglei110/DataWarehouse -https://github.com/jd-bigdata/rtf-lake -https://github.com/xzt1995/Data-Warehouse -新增用户画像、用户行为 -https://github.com/monsonlee/BigData -https://github.com/whirlys/BigData-In-Practice -https://github.com/597365581/bigdata_tools -https://blog.csdn.net/u013967628/article/details/83656560 - -Eureka -https://www.cnblogs.com/rickiyang/p/11802413.html -Rebbon -https://blog.csdn.net/forezp/article/details/74820899 -Ribbon的负载均衡,主要通过LoadBalancerClient来实现的,而LoadBalancerClient具体交给了ILoadBalancer来处理,ILoadBalancer通过配置IRule、IPing等信息,并向EurekaClient获取注册列表的信息,并默认10秒一次向EurekaClient发送“ping”,进而检查是否更新服务列表,最后,得到注册列表后,ILoadBalancer根据IRule的策略进行负载均衡。在RestTemplate 被@LoadBalance注解后,能过用负载均衡,主要是维护了一个被@LoadBalance注解的RestTemplate列表,并给列表中的RestTemplate添加拦截器,进而交给负载均衡器去处理。 - -架构 -https://blog.csdn.net/shenhuxi10000/article/details/105058723 - -https://github.com/wujun728/learningSummary - -Springboot security -https://blog.csdn.net/yuanlaijike/article/details/80249235 - -mxtheme02 - -https://github.com/hemin1003 -jun_temp     临时仓库 -https://github.com/c1013529993/springboot-uniapp-21cake - -JWT+VUE -https://github.com/cailichao/easyweb-jwt -https://github.com/whvcse/JwtPermission - -Elasticsearch - -来自  - -  - -https://spring-cloud-alibaba-group.github.io/github-pages/hoxton/zh-cn/index.html - -*************************************************************************************************** - -Springboot_fileupload -https://github.com/gaoyuyue/MyUploader-Backend - -springcloud_plugin -Superboot    --- 迁移到jun_cloud_center -Jun_dubbo ---迁移到jun_microservice -Spring - -https://github.com/liuge1988/kitty-generator -https://github.com/zhoutaoo/SpringCloud - -Api_service -1、API_BOOT代码生成器合并到code_generator里面 -2、api里面的layui抽出来,合并到 -https://github.com/Radom7/springboot-layui -jun_layuiadmin -3、新增apijson -https://github.com/APIJSON/APIJSON-Demo -https://vincentcheng.github.io/apijson-doc/ - -Api_service -1、API_BOOT代码生成器合并到code_generator里面 -2、api里面的layui抽出来,合并到 -https://github.com/Radom7/springboot-layui -jun_layuiadmin -3、新增apijson -https://github.com/APIJSON/APIJSON-Demo -https://vincentcheng.github.io/apijson-doc/ - -https://github.com/scaladte - -https://github.com/malizhigithub/CRM - -https://blog.csdn.net/qq_22211217/article/details/83759513 -https://www.cnblogs.com/softidea/p/10271266.html -Mysql 递归查询 - - -WordPress 多站点 -企业官网 -中软门户网站 - diff --git "a/doc/Devops/CentOS\344\275\277\347\224\250yum\345\256\211\350\243\205jdk.md" "b/doc/Devops/CentOS\344\275\277\347\224\250yum\345\256\211\350\243\205jdk.md" deleted file mode 100644 index 23c385e65c..0000000000 --- "a/doc/Devops/CentOS\344\275\277\347\224\250yum\345\256\211\350\243\205jdk.md" +++ /dev/null @@ -1,52 +0,0 @@ -# [CentOS使用yum安装jdk](https://www.cnblogs.com/zqyanywn/p/10812870.html) - -1、查看系统版本命令 - -``` -cat /etc/issue -2、查看yum包含的jdk版本 -yum search java 或者 yum list java* -``` - -  - -| 版本 | jre | jdk | -| ---- | ------------------------- | ------------------------------- | -| 1.8 | java-1.8.0-openjdk.x86_64 | java-1.8.0-openjdk-devel.x86_64 | -| 1.7 | java-1.7.0-openjdk.x86_64 | java-1.7.0-openjdk-devel.x86_64 | -| 1.6 | java-1.6.0-openjdk.x86_64 | java-1.6.0-openjdk-devel.x86_64 | - -3、安装jdk -此次选择java-1.8.0-openjdk-devel.x86_64 : OpenJDK Development Environment - -``` -yum install java-1.8.0-openjdk-devel.x86_64 -4、配置全局变量 -``` - -打开配置文件,按insert进入编辑模式 - -``` -vi /etc/profile -``` - -   - -``` -复制以下三行到文件中,按esc退出编辑模式,输入:wq保存退出(这里的JAVA_HOME以自己实际的目录为准) - -export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.312.b07-1.el7_9.x86_64 -export CLASSPATH=.:$JAVA_HOME/jre/lib/rt.jar:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar -export PATH=$PATH:$JAVA_HOME/bin - -``` - -   - -全局变量立即生效 - -``` -source /etc/profile -5、查看安装jdk是否成功 -java -version -``` \ No newline at end of file diff --git "a/doc/Devops/Centos\344\270\213\345\246\202\344\275\225\345\256\211\350\243\205MySQL5.7.md" "b/doc/Devops/Centos\344\270\213\345\246\202\344\275\225\345\256\211\350\243\205MySQL5.7.md" deleted file mode 100644 index dfc295137a..0000000000 --- "a/doc/Devops/Centos\344\270\213\345\246\202\344\275\225\345\256\211\350\243\205MySQL5.7.md" +++ /dev/null @@ -1,361 +0,0 @@ -## [Centos下如何安装MySQL5.7](https://www.cnblogs.com/wherehappens/articles/15055614.html) - - - -#### - -1、查看rpm包 - -`rpm-qa|grep mysql` 若有可用 `rpm-e`卸载 - -``` -[root@4WAN_1LAN_IPSec_VPN_Router ~]# rpm -qa|grep mysql -``` - -查找是否有mysql - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -``` -[root@4WAN_1LAN_IPSec_VPN_Router ~]# find / -name mysql -/run/lock/subsys/mysql -/etc/rc.d/init.d/mysql -/usr/bin/mysql -/usr/local/mysql-5.7.35-el7-x86_64/bin/mysql -/usr/local/mysql-5.7.35-el7-x86_64/include/mysql -/usr/local/mysql -/usr/local/mysql/bin/mysql -/usr/local/mysql/include/mysql -/data/mysql -/data/mysql/data/mysql -[root@4WAN_1LAN_IPSec_VPN_Router ~]# whereis mysql -mysql: /usr/bin/mysql /usr/local/mysql /usr/local/mysql/bin/mysql -``` - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -## 2、卸载CentOS7系统自带mariadb - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -``` -# 查看系统自带的Mariadb -# rpm -qa|grep mariadb -mariadb-libs-5.5.44-2.el7.centos.x86_64 -# 卸载系统自带的Mariadb -# rpm -e --nodeps mariadb-libs-5.5.44-2.el7.centos.x86_64 -# 删除etc目录下的my.cnf ,一定要删掉,等下再重新建,之前我将就用这个文件,后面改配置各种不生效 -# rm /etc/my.cnf -``` - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -## 3、检查有无安装过mysql 用户组,没有的话创建 - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -``` -//检查mysql 用户组是否存在 -cat /etc/group | grep mysql -cat /etc/passwd |grep mysql - -// 创建mysql 用户组和用户 -groupadd mysql -useradd -r -g mysql mysql -``` - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -``` -4、下载安装,从官网安装下载mysql包 -``` - -1. `cd /usr/local/ -- 进入local目录,下载mysql tar.gz包` -2. `# wget下载或者本地下载后上传` - -``` -wget https://cdn.mysql.com//Downloads/MySQL-5.7/mysql-5.7.35-el7-x86_64.tar.gz -这里的下载连接:https://cdn.mysql.com//Downloads/MySQL-5.7/mysql-5.7.35-el7-x86_64.tar.gz,去mysql官网下获取 -``` - -![img](https://img2020.cnblogs.com/blog/2124930/202107/2124930-20210724162240777-615887897.png) - - - - | - -| - -![img](https://img2020.cnblogs.com/blog/2124930/202107/2124930-20210724162357317-995161806.png) - - - - ![img](https://img2020.cnblogs.com/blog/2124930/202107/2124930-20210724162520114-253743396.png) - - - - - -``` -5、解压安装mysql -tar -zxvf mysql-5.7.31-linux-glibc2.12-x86_64.tar.gz -``` - -**6、将解压的文件做文件改名** - -``` -mv mysql-5.7.31-linux-glibc2.12-x86_64 mysql -7、更改mysql 目录下所有文件夹所属的用户组和用户,以及权限 - -chown -R mysql:mysql /usr/local/mysql -chmod -R 755 /usr/local/mysql - -``` - -![img](https://img2020.cnblogs.com/blog/2124930/202107/2124930-20210724163429461-270271939.png) - - - - - -``` -8、创建mysql相关目录 - -``` - -1. `mkdir -p /data/mysql/{data,logs,tmp}` -2. `# 更改文件夹所属` -3. `chown -R mysql.mysql /data/mysql/` - -``` -9、创建mysql配置文件my.cnf -``` - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -``` -vi /etc/my.cnf -# 简单模板如下: -[client] -port = 3306 -socket = /data/mysql/tmp/mysql.sock -[mysqld] -user = mysql -basedir = /usr/local/mysql -datadir = /data/mysql/data -port = 3306 -socket = /data/mysql/tmp/mysql.sock -pid-file = /data/mysql/tmp/mysqld.pid -tmpdir = /data/mysql/tmp -skip_name_resolve = 1 -symbolic-links=0 -max_connections = 2000 -group_concat_max_len = 1024000 -sql_mode = NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION -lower_case_table_names = 1 -log_timestamps=SYSTEM -character-set-server = utf8 -interactive_timeout = 1800 -wait_timeout = 1800 -max_allowed_packet = 32M -binlog_cache_size = 4M -sort_buffer_size = 2M -read_buffer_size = 4M -join_buffer_size = 4M -tmp_table_size = 96M -max_heap_table_size = 96M -max_length_for_sort_data = 8096 -#logs -server-id = 1003306 -log-error = /data/mysql/logs/error.log -slow_query_log = 1 -slow_query_log_file = /data/mysql/logs/slow.log -long_query_time = 3 -log-bin = /data/mysql/logs/binlog -binlog_format = row -expire_logs_days = 15 -log_bin_trust_function_creators = 1 -relay-log = /data/mysql/logs/relay-bin -relay-log-recovery = 1 -relay_log_purge = 1 -#innodb -innodb_file_per_table = 1 -innodb_log_buffer_size = 16M -innodb_log_file_size = 256M -innodb_log_files_in_group = 2 -innodb_io_capacity = 2000 -innodb_io_capacity_max = 4000 -innodb_flush_neighbors = 0 -innodb_flush_method = O_DIRECT -innodb_autoinc_lock_mode = 2 -innodb_read_io_threads = 8 -innodb_write_io_threads = 8 -innodb_buffer_pool_size = 2G -``` - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -10、配置mysql.server - -``` - -``` - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -``` -cd /usr/local/mysql/support-files -cp mysql.server /etc/init.d/mysql -vi /etc/init.d/mysql -# 修改目录位置 -basedir=/usr/local/mysql -datadir=/data/mysql/data -# 注册开机启动服务 -chkconfig --add mysql -chkconfig --list -``` - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -``` - -``` - -11、添加环境变量 - -``` - -echo "PATH=$PATH:/usr/local/mysql/bin " >> /etc/profile -source /etc/profile - -``` - -12、初始化mysql - -``` -/usr/local/mysql/bin/mysqld --initialize --user=mysql --basedir=/usr/local/mysql --datadir=/data/mysql/data -# 临时密码保存在errlog中 -# 获取临时密码 -more /data/mysql/logs/error.log |grep password -``` - -![img](https://img2020.cnblogs.com/blog/2124930/202107/2124930-20210724164648099-389709896.png) - - - - 13、启动mysql服务,并修改密码 - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -``` -# 启动mysql服务 -service mysql start -# 使用初始密码登录mysql服务 并修改密码 -mysql -uroot -p -alter user 'root'@'localhost' identified by 'root'; -flush privileges; -``` - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -![img](https://img2020.cnblogs.com/blog/2124930/202107/2124930-20210724165100493-1870359410.png) - - - - - -``` -[root@4WAN_1LAN_IPSec_VPN_Router ~]# /usr/local/mysql/support-files/mysql.server start -Starting MySQL.. SUCCESS! -``` - - - -``` - -``` - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -``` -[root@4WAN_1LAN_IPSec_VPN_Router ~]# ln -s /usr/local/mysql/bin/mysql /usr/bin/mysql -[root@4WAN_1LAN_IPSec_VPN_Router ~]# service mysql restart -/etc/init.d/mysql: line 46: /usr/local/mysql: Is a directory -/etc/init.d/mysql: line 47: /data/mysql/data: Is a directory -/etc/init.d/mysql: line 46: /usr/local/mysql: Is a directory -/etc/init.d/mysql: line 47: /data/mysql/data: Is a directory -Shutting down MySQL.. SUCCESS! -/etc/init.d/mysql: line 46: /usr/local/mysql: Is a directory -/etc/init.d/mysql: line 47: /data/mysql/data: Is a directory -Starting MySQL.. SUCCESS! -[root@4WAN_1LAN_IPSec_VPN_Router ~]# mysql -u root -p -mysql: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory -[root@4WAN_1LAN_IPSec_VPN_Router ~]# yum install libncurses* -上次元数据过期检查:1:29:23 前,执行于 2021年07月24日 星期六 00时50分20秒。 -软件包 ncurses-libs-6.1-9.20180224.el8.x86_64 已安装。 -依赖关系解决。 -=========================================================================================================== - 软件包 架构 版本 仓库 大小 -=========================================================================================================== -安装: - ncurses-c++-libs x86_64 6.1-9.20180224.el8 baseos 58 k - ncurses-compat-libs x86_64 6.1-9.20180224.el8 baseos 328 k - -事务概要 -=========================================================================================================== -安装 2 软件包 - -总下载:386 k -安装大小:1.1 M -确定吗?[y/N]: y -下载软件包: -(1/2): ncurses-c++-libs-6.1-9.20180224.el8.x86_64.rpm 188 kB/s | 58 kB 00:00 -(2/2): ncurses-compat-libs-6.1-9.20180224.el8.x86_64.rpm 394 kB/s | 328 kB 00:00 ------------------------------------------------------------------------------------------------------------ -总计 288 kB/s | 386 kB 00:01 -运行事务检查 -事务检查成功。 -运行事务测试 -事务测试成功。 -运行事务 - 准备中 : 1/1 - 安装 : ncurses-compat-libs-6.1-9.20180224.el8.x86_64 1/2 - 安装 : ncurses-c++-libs-6.1-9.20180224.el8.x86_64 2/2 - 运行脚本: ncurses-c++-libs-6.1-9.20180224.el8.x86_64 2/2 - 验证 : ncurses-c++-libs-6.1-9.20180224.el8.x86_64 1/2 - 验证 : ncurses-compat-libs-6.1-9.20180224.el8.x86_64 2/2 - -已安装: - ncurses-c++-libs-6.1-9.20180224.el8.x86_64 ncurses-compat-libs-6.1-9.20180224.el8.x86_64 - -完毕! -[root@4WAN_1LAN_IPSec_VPN_Router ~]# mysql -u root -p -Enter password: -Welcome to the MySQL monitor. Commands end with ; or \g. -Your MySQL connection id is 2 -Server version: 5.7.35-log - -Copyright (c) 2000, 2021, Oracle and/or its affiliates. - -Oracle is a registered trademark of Oracle Corporation and/or its -affiliates. Other names may be trademarks of their respective -owners. - -Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. - -mysql> alter user 'root'@'localhost' identified by 'Admin@2020@#!'; -Query OK, 0 rows affected (0.01 sec) - -mysql> flush privileges; -Query OK, 0 rows affected (0.06 sec) -``` - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -``` - -``` - - 参看文档:http://www.xiaoguan.net/posts/show/426 - -​ https://mp.weixin.qq.com/s/ybdY6cJNG2lC4FzBsc19ag \ No newline at end of file diff --git "a/doc/Devops/Docker cp \345\221\275\344\273\244.md" "b/doc/Devops/Docker cp \345\221\275\344\273\244.md" deleted file mode 100644 index f857efeaf6..0000000000 --- "a/doc/Devops/Docker cp \345\221\275\344\273\244.md" +++ /dev/null @@ -1,22 +0,0 @@ -Docker cp 命令 - Docker 命令大全Docker 命令大全 - -docker cp :用于容器与主机之间的数据拷贝。 - -语法 -docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|- -docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH -OPTIONS说明: - --L :保持源目标中的链接 - -实例 -将主机/www/runoob目录拷贝到容器96f7f14e99ab的/www目录下。 - -docker cp /www/runoob 96f7f14e99ab:/www/ -将主机/www/runoob目录拷贝到容器96f7f14e99ab中,目录重命名为www。 - -docker cp /www/runoob 96f7f14e99ab:/www -将容器96f7f14e99ab的/www目录拷贝到主机的/tmp目录中。 - -docker cp 96f7f14e99ab:/www /tmp/ \ No newline at end of file diff --git a/doc/Devops/Dockerfile b/doc/Devops/Dockerfile deleted file mode 100644 index 02857ee4d3..0000000000 --- a/doc/Devops/Dockerfile +++ /dev/null @@ -1,13 +0,0 @@ -# 基础镜像 -FROM openjdk:8-jdk-alpine -# author -MAINTAINER wenbin -# 复制jar文件到路径 -ADD manager.jar manager.jar -# 时间 -RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime -RUN echo 'Asia/Shanghai' >/etc/timezone -# 启动服务 -ENTRYPOINT ["java","-jar","/manager.jar"] -# 暴露端口 -EXPOSE 8080 diff --git "a/doc/Devops/docker \345\256\211\350\243\205 mysql5.7.md" "b/doc/Devops/docker \345\256\211\350\243\205 mysql5.7.md" deleted file mode 100644 index ec86989554..0000000000 --- "a/doc/Devops/docker \345\256\211\350\243\205 mysql5.7.md" +++ /dev/null @@ -1,52 +0,0 @@ -docker 安装 mysql5.7 - - -1.安装mysql5.7 docker镜像 -拉取官方mysql5.7镜像 - -docker pull mysql:5.7 - - -查看镜像库 - -docker images - - -2.创建mysql容器 -在本地创建mysql的映射目录 - -mkdir -p /root/mysql/data /root/mysql/logs /root/mysql/conf -在/root/mysql/conf中创建 *.cnf 文件(叫什么都行) - -touch my.cnf -创建容器,将数据,日志,配置文件映射到本机 - -docker run -p 3306:3306 --name mysql5.7 -v /root/mysql/conf:/etc/mysql/conf.d -v /root/mysql/logs:/logs -v /root/mysql/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=mysqladmin -d mysql:5.7 - --d: 后台运行容器 - --p 将容器的端口映射到本机的端口 - --v 将主机目录挂载到容器的目录 - --e 设置参数 - - - -启动mysql容器 - -docker start mysql5.7 - - - 查看/root/mysql/data目录是否有数据文件 - - - -使用工具连接测试 - - - -测试成功 -———————————————— -版权声明:本文为CSDN博主「疯狂的狮子Li」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 -原文链接:https://blog.csdn.net/weixin_40461281/article/details/92610876 \ No newline at end of file diff --git "a/doc/Devops/docker \346\220\255\345\273\272Mysql\351\233\206\347\276\244.md" "b/doc/Devops/docker \346\220\255\345\273\272Mysql\351\233\206\347\276\244.md" deleted file mode 100644 index e653b3610d..0000000000 --- "a/doc/Devops/docker \346\220\255\345\273\272Mysql\351\233\206\347\276\244.md" +++ /dev/null @@ -1,305 +0,0 @@ -# [docker 搭建Mysql集群](https://www.cnblogs.com/zhenghongxin/p/9228101.html) - -**docker基本指令:** - -更新软件包 - -``` -yum -y update -``` - -安装Docker虚拟机(centos 7) - -``` -yum install -y docker -``` - -运行、重启、关闭Docker虚拟机 - -``` -service docker start -service docker stop -``` - -搜索镜像 - -``` - docker search 镜像名称 -``` - -下载镜像 - -``` -docker pull 镜像名称 -``` - -查看镜像 - -``` -docker images -``` - -删除镜像 - -``` -docker rmi 镜像名称 -``` - -运行容器 - -``` -docker run 启动参数 镜像名称 -``` - -查看容器列表 - -``` -docker ps -a -``` - -当我们想要使用java环境,我们可以这么操作: - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -``` -搜索:[root@VM_71_225_centos ~]# docker search java -INDEX NAME DESCRIPTION STARS OFFICIAL AUTOMATED -docker.io docker.io/node Node.js is a JavaScript-based platform for... 5752 [OK] -docker.io docker.io/tomcat Apache Tomcat is an open source implementa... 1891 [OK] -docker.io docker.io/java Java is a concurrent, class-based, and obj... 1745 [OK] -docker.io docker.io/openjdk OpenJDK is an open-source implementation o... 1031 [OK] -``` - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -``` -下载:[root@VM_71_225_centos ~]# docker pull docker.io/java -Using default tag: latest -Trying to pull repository docker.io/library/java ... -latest: Pulling from docker.io/library/java -5040bd298390: Downloading [=> ] 1.572 MB/51.36 MB -``` - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -``` -运行:[root@VM_71_225_centos ~]# docker run -it --name myjava docker.io/java bash -root@25623e12b759:/# java -``` - -- **-i:** 以交互模式运行容器,通常与 -t 同时使用; -- **-t:** 为容器重新分配一个伪输入终端,通常与 -i 同时使用; - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -**安装PXC集群(在此不做mysql pxc集群与replication集群的方案优劣说明,在此选用pxc集群方案[多节点备份与强联合性]):** - -安装PXC镜像 - -``` -docker pull percona/percona-xtradb-cluster -``` - -查看本地镜像 - -``` -[root@VM_71_225_centos ~]# docker images -REPOSITORY TAG IMAGE ID CREATED SIZE -docker.io/hello-world latest e38bc07ac18e 2 months ago 1.85 kB -docker.io/percona/percona-xtradb-cluster latest f1439de62087 3 months ago 413 MB -docker.io/java latest d23bdf5b1b1b 17 months ago 643 MB -``` - -docker.io/percona/percona-xtradb-cluster 太长,进行改名: - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -``` -[root@VM_71_225_centos ~]# docker tag percona/percona-xtradb-cluster pxc -[root@VM_71_225_centos ~]# docker images -REPOSITORY TAG IMAGE ID CREATED SIZE -docker.io/hello-world latest e38bc07ac18e 2 months ago 1.85 kB -docker.io/percona/percona-xtradb-cluster latest f1439de62087 3 months ago 413 MB -pxc latest f1439de62087 3 months ago 413 MB -docker.io/java latest d23bdf5b1b1b 17 months ago 643 MB -``` - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -创建net1网段: - -``` -docker network create --subnet=172.18.0.0/16 net1 -``` - -创建五个数据卷(pxc无法直接存取宿组机的数据,所以创建五个docker数据卷) - -``` -docker volume create v1 -docker volume create v2 -docker volume create v3 -docker volume create v4 -docker volume create v5 -``` - -查看数据卷位置: - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -``` -[root@VM_71_225_centos code]# docker inspect v1 -[ - { - "Driver": "local", - "Labels": {}, - "Mountpoint": "/var/lib/docker/volumes/v1/_data", - "Name": "v1", - "Options": {}, - "Scope": "local" - } -] -``` - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -创建5节点的PXC集群 - -``` -#创建第1个MySQL节点 -docker run -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD=abc123456 -e CLUSTER_NAME=PXC -e XTRABACKUP_PASSWORD=abc123456 -v v1:/var/lib/mysql -v backup:/data --privileged --name=node1 --net=net1 --ip 172.18.0.2 pxc -``` - -等待2分钟后,再创建第二个节点,等待第一个节点实例化完毕后,才能开启第二个节点实例,不然会瞬间停止 - -创建其他节点: - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -``` -#创建第2个MySQL节点 -docker run -d -p 3307:3306 -e MYSQL_ROOT_PASSWORD=abc123456 -e CLUSTER_NAME=PXC -e XTRABACKUP_PASSWORD=abc123456 -e CLUSTER_JOIN=node1 -v v2:/var/lib/mysql -v backup:/data --privileged --name=node2 --net=net1 --ip 172.18.0.3 pxc -#创建第3个MySQL节点 -docker run -d -p 3308:3306 -e MYSQL_ROOT_PASSWORD=abc123456 -e CLUSTER_NAME=PXC -e XTRABACKUP_PASSWORD=abc123456 -e CLUSTER_JOIN=node1 -v v3:/var/lib/mysql --privileged --name=node3 --net=net1 --ip 172.18.0.4 pxc -#创建第4个MySQL节点 -docker run -d -p 3309:3306 -e MYSQL_ROOT_PASSWORD=abc123456 -e CLUSTER_NAME=PXC -e XTRABACKUP_PASSWORD=abc123456 -e CLUSTER_JOIN=node1 -v v4:/var/lib/mysql --privileged --name=node4 --net=net1 --ip 172.18.0.5 pxc -#创建第5个MySQL节点 -docker run -d -p 3310:3306 -e MYSQL_ROOT_PASSWORD=abc123456 -e CLUSTER_NAME=PXC -e XTRABACKUP_PASSWORD=abc123456 -e CLUSTER_JOIN=node1 -v v5:/var/lib/mysql -v backup:/data --privileged --name=node5 --net=net1 --ip 172.18.0.6 pxc -``` - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -测试在任意mysql节点创建数据库: - -``` -mysql -h 172.18.0.3 -uroot -pabc123456 - -mysql> create database test; -Query OK, 1 row affected (0.03 sec) -``` - -登录其他节点数据库,能看到已经进行了同步,构成简单的mysql集群 - -**安装Haproxy进行高可用与负载均衡** - - 拉取haproxy - -``` -docker pull haproxy -``` - -编写Haproxy配置文件 - -``` -vi /home/soft/haproxy.cfg -``` - -配置文件如下: - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -``` -global - #工作目录 - chroot /usr/local/etc/haproxy - #日志文件,使用rsyslog服务中local5日志设备(/var/log/local5),等级info - log 127.0.0.1 local5 info - #守护进程运行 - daemon - -defaults - log global - mode http - #日志格式 - option httplog - #日志中不记录负载均衡的心跳检测记录 - option dontlognull - #连接超时(毫秒) - timeout connect 5000 - #客户端超时(毫秒) - timeout client 50000 - #服务器超时(毫秒) - timeout server 50000 - -#监控界面 -listen admin_stats - #监控界面的访问的IP和端口 - bind 0.0.0.0:8888 - #访问协议 - mode http - #URI相对地址 - stats uri /dbs - #统计报告格式 - stats realm Global\ statistics - #登陆帐户信息 - stats auth admin:abc123456 -#数据库负载均衡 -listen proxy-mysql - #访问的IP和端口 - bind 0.0.0.0:3306 - #网络协议 - mode tcp - #负载均衡算法(轮询算法) - #轮询算法:roundrobin - #权重算法:static-rr - #最少连接算法:leastconn - #请求源IP算法:source - balance roundrobin - #日志格式 - option tcplog - #在MySQL中创建一个没有权限的haproxy用户,密码为空。Haproxy使用这个账户对MySQL数据库心跳检测 - option mysql-check user haproxy - server MySQL_1 172.18.0.2:3306 check weight 1 maxconn 2000 - server MySQL_2 172.18.0.3:3306 check weight 1 maxconn 2000 - server MySQL_3 172.18.0.4:3306 check weight 1 maxconn 2000 - server MySQL_4 172.18.0.5:3306 check weight 1 maxconn 2000 - server MySQL_5 172.18.0.6:3306 check weight 1 maxconn 2000 - #使用keepalive检测死链 - option tcpka -``` - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -创建第1个Haproxy负载均衡服务器 - -``` -docker run -it -d -p 4001:8888 -p 4002:3306 -v /home/soft/haproxy:/usr/local/etc/haproxy --name h1 --privileged --net=net1 --ip 172.18.0.7 haproxy -``` - -进入h1容器,启动Haproxy - -``` -docker exec -it h1 bash -haproxy -f /usr/local/etc/haproxy/haproxy.cfg -``` - -查看是否启动成功: - -访问http://ip:4001/dbs - -![img](https://images2018.cnblogs.com/blog/608476/201807/608476-20180701201220668-1695009593.png) - - 安装keepalive实现双击热备 \ No newline at end of file diff --git a/doc/Devops/docker.md b/doc/Devops/docker.md deleted file mode 100644 index 0cd8245112..0000000000 --- a/doc/Devops/docker.md +++ /dev/null @@ -1,43 +0,0 @@ - -------MySQL - -1.拉取镜像。 - -docker pull mysql:8 - -2.运行镜像,name、端口和密码可自行修改。 - -docker run -p 3307:3306 --name mysql8 -e MYSQL_ROOT_PASSWORD=mysqladmin -d mysql:8 - -3.进入容器终端。 - -docker exec -it mysql8 bash - -4.客户端连接mysql。 - -mysql -uroot -pmysqladmin - - -------kkfileview - -docker pull keking/kkfileview -docker run -it -p 8012:8012 keking/kkfileview - -docker run -p 8012:8012 --name kkfileview -d keking/kkfileview - - - - - -------manager - -ps -ef |grep java - -nohup java -jar manager.jar --server.port=8081 > log8081.log & | tail -f log8081.log & - -nohup java -jar manager.jar --server.port=8081 > log8081.log & -tail -f log8081.log & - - -nohup java -jar manager.jar --server.port=8082 > log8081.log & -nohup java -jar manager.jar --server.port=8083 > log8081.log & \ No newline at end of file diff --git "a/doc/Devops/docker\345\256\211\350\243\205Redis\345\271\266\350\256\276\347\275\256\345\257\206\347\240\201.md" "b/doc/Devops/docker\345\256\211\350\243\205Redis\345\271\266\350\256\276\347\275\256\345\257\206\347\240\201.md" deleted file mode 100644 index f2056ed10f..0000000000 --- "a/doc/Devops/docker\345\256\211\350\243\205Redis\345\271\266\350\256\276\347\275\256\345\257\206\347\240\201.md" +++ /dev/null @@ -1,41 +0,0 @@ -# [docker安装Redis并设置密码](https://www.cnblogs.com/zhangzimo/p/12753563.html) - -## 1.搜索镜像 - -``` -docker search redis -``` - -## 2.拉取镜像 - -``` -docker pull redis -``` - -## 3.创建Redis容器并设置密码 - -``` -docker run --name redis -p 6380:6379 redis-test --requirepass 123456 - -docker run -itd --name redis-v4-6379 -p 6379:6379 redis:4.0 - -docker run -itd --name redis-6379 -p 6379:6379 redis:5.0 --requirepass 123456 - -#前边是宿主机端口 后面是docker使用的端口 -``` - -## 4.备注 - -为现有的redis创建密码或修改密码的方法: - -1.进入redis的容器 docker exec -it 容器ID bash - -2.进入redis目录 cd /usr/local/bin - -3.运行命令:redis-cli - -4.查看现有的redis密码:config get requirepass - -5.设置redis密码config set requirepass ****(****为你要设置的密码) - -6.若出现(error) NOAUTH Authentication required.错误,则使用 auth 密码 来认证密码 \ No newline at end of file diff --git "a/doc/Devops/\351\203\250\347\275\262\346\226\207\346\241\243" "b/doc/Devops/\351\203\250\347\275\262\346\226\207\346\241\243" deleted file mode 100644 index 6dae5f59de..0000000000 --- "a/doc/Devops/\351\203\250\347\275\262\346\226\207\346\241\243" +++ /dev/null @@ -1,15 +0,0 @@ -1. 使用IDE导入本项目,IDE需要安装lombok插件 -2. 下载redis 启动redis -3. 创建数据库, 导入***.sql -4. 配置application-dev.yml中的redis以及数据库连接 -5. 运行项目 - 1、直接运行CompanyProjectApplication.java - 2、项目根目录下执行mvn -X clean package -Dmaven.test.skip=true编译打包,然后执行java -jar manager.jar -6. 接口文档访问 http://localhost:8080/doc.html -7. 登录地址 http://localhost:8080/index/login 用户名密码:admin/123456 -8. 代码生成使用: - 1、 application.yml中配置: 使用代码生成模块时 指定要生成的表存在于哪种数据库。project.database=mysql - 2、点击代码生成菜单,生成一个或多个表的代码,下载到本地 - 3、解压下载的代码,直接复制main文件夹到本地项目的src目录下 - 4、数据库执行sql,生成菜单 - 5、修改角色所绑定的菜单的权限,刷新页面查看 \ No newline at end of file diff --git a/doc/java1.png b/doc/java1.png deleted file mode 100644 index 0088aa8828..0000000000 Binary files a/doc/java1.png and /dev/null differ diff --git a/doc/maven1.png b/doc/maven1.png deleted file mode 100644 index 6404b0eee0..0000000000 Binary files a/doc/maven1.png and /dev/null differ diff --git a/doc/spring1.png b/doc/spring1.png deleted file mode 100644 index e466c091fa..0000000000 Binary files a/doc/spring1.png and /dev/null differ diff --git a/doc/springboot1.png b/doc/springboot1.png deleted file mode 100644 index 6cc1acb460..0000000000 Binary files a/doc/springboot1.png and /dev/null differ diff --git "a/doc/\351\203\250\347\275\262\346\226\207\346\241\243" "b/doc/\351\203\250\347\275\262\346\226\207\346\241\243" deleted file mode 100644 index c6bb4711ac..0000000000 --- "a/doc/\351\203\250\347\275\262\346\226\207\346\241\243" +++ /dev/null @@ -1,51 +0,0 @@ -1. 使用IDE导入本项目,IDE需要安装lombok插件 -2. 下载redis 启动redis -3. 创建数据库, 导入***.sql -4. 配置application-dev.yml中的redis以及数据库连接 -5. 运行项目 - 1、直接运行CompanyProjectApplication.java - 2、项目根目录下执行mvn -X clean package -Dmaven.test.skip=true编译打包,然后执行java -jar manager.jar -6. 接口文档访问 http://localhost:8080/doc.html -7. 登录地址 http://localhost:8080/index/login 用户名密码:admin/123456 -8. 代码生成使用: - 1、 application.yml中配置: 使用代码生成模块时 指定要生成的表存在于哪种数据库。project.database=mysql - 2、点击代码生成菜单,生成一个或多个表的代码,下载到本地 - 3、解压下载的代码,直接复制main文件夹到本地项目的src目录下 - 4、数据库执行sql,生成菜单 - 5、修改角色所绑定的菜单的权限,刷新页面查看 - - - - -chcp 65001 -@echo off -set /p gd=输入要清除历史提交信息的仓库目录的绝对路径: -echo 待处理的路径:%gd% -set /p gm=输入提交说明: -pushd -cd /d %gd% -git checkout --orphan latest_branch -git add -A -git commit -am "%gm%" -git branch -D master -git branch -m master -git push -f origin master -git pull -echo "已清除全部的历史记录!" -echo "查看新仓库信息:" -git log --pretty=oneline -git branch -a -git tag -git ls-remote --tags -pause -popd -exit - - -git checkout --orphan latest_branch -git add -A -git commit -am "%gm%" -git branch -D main -git branch -m main -git push -f origin main -git pull \ No newline at end of file diff --git "a/doc/\351\207\215\347\275\256master\345\210\206\346\224\257.md" "b/doc/\351\207\215\347\275\256master\345\210\206\346\224\257.md" deleted file mode 100644 index 8806290760..0000000000 --- "a/doc/\351\207\215\347\275\256master\345\210\206\346\224\257.md" +++ /dev/null @@ -1,142 +0,0 @@ -重置master分支: -git checkout --orphan latest_branch -git add -A -git commit -am "commit message" -git branch -D master -git branch -m master - - -git branch -m latest_branch master -git push -f origin master -git push origin latest_branch:master -f -git reset --hard origin/master - -git checkout --orphan latest_branch -git push -f origin latest_branch -git push -f origin master --force - -有时候我们项目中会配置很多内容,在新起一个项目的时候,重新从头配置比较浪费时间,但是直接将原来项目拿来修改远程地址后,项目里还会保存之前的提交历史和tag;这个时候我们就需要下面的操作来清空这些内容。 - -1.创建新分支(这个命名是基于当前所在分支新建一个赤裸裸的分支,没有任何的提交历史,但是当前分支的内容一应俱全。新建的分支,严格意义上说,还不是一个分支,因为HEAD指向的引用中没有commit值,只有在进行一次提交后,它才算得上真正的分支。) - - git checkout --orphan latest_branch - -2.添加所有文件 - - git add . - -3.commit代码 - - git commit -m "xxx" - -4.删除原来的master分支 - - git branch -D master - git branch -D main - -5.把当前分支重命名为master - - git branch -m master - git branch -m main - -6.最后把代码推送到远程仓库(有些仓库有master分支保护,不允许强制push,需要在远程仓库项目里暂时把项目保护关掉才能推送) - - git push -f origin master - git push -f origin main - - - -1、.git目录过大 -要解决.git目录过大的问题,可以尝试以下方法: -使用git gc命令清理不再需要的缓存。这将帮助减小仓库的大小。 -在命令行中输入以下命令: - -git gc --prune=now --aggressive -1 -使用git repack -ad命令来重新打包已经提交的文件。 -这将有助于减小仓库的大小。在命令行中输入以下命令: - -git repack -ad -2、灵活使用 .gitignore 文件 -及时排除仓库不需要的特殊目录或者文件 -如下,忽略dist和build文件下内容,忽略格式为zip和exe的文件 - -/dist -/build -*.zip -*.exe -3、查看仓库下文件大小 -数字1代表查看当前1级子目录 - -du -d 1 -h - - - - -git branch -r | grep -v 'main' | grep -v 'HEAD' | sed 's/origin\///' - -git branch -r | grep -v 'main' | grep -v 'HEAD' | sed 's/origin\///' | xargs -I {} git push origin --delete {} - - - - - -方法一:强制回退法 - -1. 克隆仓库,但记住不可以加--depth=1这类选项; - -2. 使用 git log 命令查询要回滚的 commit_id; - -3. 查找最早一次提交到的commit_id; - - -4. 备份原仓库目录下所有文件及文件夹(.git文件夹除外); - -5. 强制还原,执行命令:git reset --hard commit_id,之后 HEAD 就会指向此次的提交记录; -git reset --hard 7ee28e8437002722a9d5ff0c7e88ff8cc66dc9de - -6. 删除仓库目录下所有文件和文件夹,去除你备份的文件中包含隐私信息的部分,并还原至原仓库目录下; - -7. 执行提交新commit前的常规操作:git add . 和 git commit -m "<...>"; -git add . -git commit -m "xxx" - -8. 强制推送到github远程仓库:git push origin HEAD --force; -git push origin HEAD --force - -9. 此时只剩下第一次提交和本次提交记录,基本达到清空目的: - - 方法二:分支替换法 - -1. 同方法一克隆仓库; - -2. 将当前分支指向一个空分支 latest_branch:git checkout --orphan latest_branch; - -3. 备份原仓库目录下所有文件及文件夹(.git文件夹除外),之后清空该目录(.git文件夹除外); - -4. 去除你备份的文件中包含隐私信息的部分,并还原至原仓库目录下,最后重新添加:git add -A; - -5. 提交更改:git commit -am "<...>"; - -6. 删除原分支:git branch -D master (新版的github默认分支是main了,请根据实际情况更改,下同); - -7. 将现有临时分支切换到主分支:git branch -m master; - -8. 强制推送到远程:git push -f origin master --force -———————————————— - - 本文是博主原创文章,未经许可不准转载! - -原文链接:https://blog.csdn.net/u012783994/article/details/126339284 - - - - - - - -git remote add origin https://github.com/wujun728/jun_product_center_private.git - -# 3. 推送到远程指定分支(例如叫 temp-test) -git push origin master:2026 - diff --git a/execution_log.jsonl b/execution_log.jsonl deleted file mode 100644 index c7b588c1cd..0000000000 --- a/execution_log.jsonl +++ /dev/null @@ -1,20 +0,0 @@ -{"ts": "2026-04-13T00:44:15", "event": "info", "data": {"message": "使用模型提供者: claude"}} -{"ts": "2026-04-13T00:44:15", "event": "planner_start", "data": {"task": "根据当前项目下面的 D:\\workspace_github_v2\\10技术基础层\\jun_java_plugin\\ 文件夹,完成下面的任务。任务1,项目模块很多但是不全面,你需要作为一个java专家,这个是你的代码仓库,你需要补充并完善整个仓库,包括技术栈覆盖,代码实现,示例实现等等。你需要遍历整个仓库,输出完整的md文档。你需要编译及测试所有的模块并保障功能正常。仓库里面的功能每个作为一块功能点,有冗余的就干掉,或者补充进来。我希望整个仓库能是一个完整的java技术栈,完整的java基础示例、完整的功能参考示例仓库,可以共享给其他人或者其他的大模型,后面可以直接参考仓库的代码或者文档,使用仓库的组件及功能等,并能帮助到所有的java开发人员。"}} -{"ts": "2026-04-13T00:49:57", "event": "planner_done", "data": {"tasks_count": 45}} -{"ts": "2026-04-13T00:49:57", "event": "worker_start", "data": {"task_id": "T001", "session": 1, "attempt": 1}} -{"ts": "2026-04-13T00:52:35", "event": "worker_done", "data": {"task_id": "T001", "success": true}} -{"ts": "2026-04-13T00:52:35", "event": "eval_start", "data": {"task_id": "T001"}} -{"ts": "2026-04-13T00:58:44", "event": "warn", "data": {"message": "无法解析 Evaluator 输出,默认为失败"}} -{"ts": "2026-04-13T00:58:44", "event": "eval_done", "data": {"task_id": "T001", "passed": false, "score": 0}} -{"ts": "2026-04-13T00:58:49", "event": "worker_start", "data": {"task_id": "T001", "session": 2, "attempt": 2}} -{"ts": "2026-04-13T01:06:46", "event": "worker_done", "data": {"task_id": "T001", "success": true}} -{"ts": "2026-04-13T01:06:46", "event": "eval_start", "data": {"task_id": "T001"}} -{"ts": "2026-04-13T01:13:06", "event": "warn", "data": {"message": "无法解析 Evaluator 输出,默认为失败"}} -{"ts": "2026-04-13T01:13:06", "event": "eval_done", "data": {"task_id": "T001", "passed": false, "score": 0}} -{"ts": "2026-04-13T01:13:11", "event": "worker_start", "data": {"task_id": "T001", "session": 3, "attempt": 3}} -{"ts": "2026-04-13T01:18:19", "event": "worker_done", "data": {"task_id": "T001", "success": true}} -{"ts": "2026-04-13T01:18:19", "event": "eval_start", "data": {"task_id": "T001"}} -{"ts": "2026-04-13T01:21:27", "event": "warn", "data": {"message": "无法解析 Evaluator 输出,默认为失败"}} -{"ts": "2026-04-13T01:21:27", "event": "eval_done", "data": {"task_id": "T001", "passed": false, "score": 0}} -{"ts": "2026-04-13T01:21:32", "event": "all_done", "data": {"passed": 0, "skipped": 45}} -{"ts": "2026-04-13T01:21:32", "event": "session_end", "data": {"total": 45, "passed": 0, "skipped": 45, "pending": 0, "tasks": [{"id": "T001", "title": "创建项目分析工具和脚本", "status": "skipped", "attempts": 3, "started_at": "2026-04-13T01:13:11", "completed_at": null, "evaluation": {"passed": false, "score": 0, "feedback": "无法解析评估结果,请检查 Evaluator 输出日志", "checks": []}}, {"id": "T002", "title": "分析 jun_java_plugins 模块结构", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T003", "title": "分析 jun_springboot_plugin 模块结构", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T004", "title": "分析 jun_springboot_starter 自定义启动器", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T005", "title": "分析 jun_springcloud_plugin 和项目模板", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T006", "title": "编译测试 jun_java_plugins 模块", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T007", "title": "编译测试 jun_springboot_plugin 模块", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T008", "title": "编译测试 jun_springboot_starter 模块", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T009", "title": "编译测试其他模块", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T010", "title": "评估 Java 基础技术栈覆盖度", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T011", "title": "评估数据库和持久化技术覆盖度", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T012", "title": "评估 Web 和微服务技术覆盖度", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T013", "title": "评估安全和认证技术覆盖度", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T014", "title": "评估消息队列和任务调度覆盖度", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T015", "title": "评估工具类库和第三方集成覆盖度", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T016", "title": "识别重复和冗余模块", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T017", "title": "识别缺失的核心技术模块", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T018", "title": "评估文档完整性", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T019", "title": "评估测试覆盖率", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T020", "title": "创建项目全局技术栈清单", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T021", "title": "创建模块索引和导航文档", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T022", "title": "创建快速开始指南", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T023", "title": "修复 jun_java_plugins 编译错误", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T024", "title": "修复 jun_springboot_plugin 编译错误", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T025", "title": "修复 jun_springboot_starter 配置问题", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T026", "title": "补充缺失的 Java 基础模块", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T027", "title": "补充缺失的数据库技术模块", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T028", "title": "补充缺失的微服务技术模块", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T029", "title": "补充缺失的新技术模块", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T030", "title": "完善模块 README 文档", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T031", "title": "为核心模块添加 Swagger API 文档", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T032", "title": "为核心模块添加单元测试", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T033", "title": "添加集成测试示例", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T034", "title": "清理和合并冗余模块", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T035", "title": "统一代码风格和规范", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T036", "title": "优化依赖管理", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T037", "title": "创建示例应用集合", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T038", "title": "创建在线演示环境", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T039", "title": "更新主 README 文档", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T040", "title": "创建贡献指南", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T041", "title": "创建最佳实践文档", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T042", "title": "创建技术选型指南", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T043", "title": "创建 CI/CD 配置", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T044", "title": "生成项目统计报告", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}, {"id": "T045", "title": "生成完整项目文档汇总", "status": "skipped", "attempts": 0, "started_at": null, "completed_at": null, "evaluation": null}], "budget": "Token 用量: input=66 output=7,253 | 调用次数: 3 | 累计费用: $0.11 / $10.00"}} diff --git a/init.bat b/init.bat deleted file mode 100644 index 3fd063265c..0000000000 --- a/init.bat +++ /dev/null @@ -1,174 +0,0 @@ -@echo off -chcp 65001 >nul -setlocal enabledelayedexpansion - -echo ========================================== -echo jun_java_plugin 环境检查和初始化 -echo ========================================== -echo. - -REM 1. 检查前置条件 -echo 1. 检查开发环境... -echo ---------------------------- - -where java >nul 2>&1 -if %errorlevel% equ 0 ( - echo [√] java 已安装 - java -version 2>&1 | findstr "version" -) else ( - echo [×] java 未安装 - set JAVA_OK=0 -) - -where mvn >nul 2>&1 -if %errorlevel% equ 0 ( - echo [√] mvn 已安装 - mvn -version 2>&1 | findstr "Apache Maven" -) else ( - echo [×] mvn 未安装 - set MVN_OK=0 -) - -where git >nul 2>&1 -if %errorlevel% equ 0 ( - echo [√] git 已安装 -) else ( - echo [×] git 未安装 -) - -echo. - -if defined JAVA_OK ( - echo 错误: 缺少必要的开发工具 - echo 请安装: JDK 1.8+ - pause - exit /b 1 -) - -if defined MVN_OK ( - echo 错误: 缺少必要的开发工具 - echo 请安装: Maven 3.5+ - pause - exit /b 1 -) - -REM 2. 检查项目结构 -echo 2. 检查项目结构... -echo ---------------------------- - -set MODULES=jun_java_plugins jun_springboot_plugin jun_springboot_starter jun_springcloud_plugin java_project_template - -for %%m in (%MODULES%) do ( - if exist "%%m\" ( - echo [√] %%m 目录存在 - ) else ( - echo [!] %%m 目录不存在 - ) -) - -echo. - -REM 3. 统计模块数量 -echo 3. 统计项目模块... -echo ---------------------------- - -for %%m in (%MODULES%) do ( - if exist "%%m\" ( - dir /AD /B "%%m" 2>nul | find /C /V "" > temp.txt - set /p count=" pom.xml | findstr /V " temp.txt - set /p version= temp.txt - set /p task_count= /dev/null; then - echo -e "${GREEN}✓${NC} $1 已安装" - if [ "$1" == "java" ]; then - java -version 2>&1 | head -n 1 - elif [ "$1" == "mvn" ]; then - mvn -version 2>&1 | head -n 1 - fi - return 0 - else - echo -e "${RED}✗${NC} $1 未安装" - return 1 - fi -} - -# 1. 检查前置条件 -echo "1. 检查开发环境..." -echo "----------------------------" - -check_command java -JAVA_OK=$? - -check_command mvn -MVN_OK=$? - -check_command git -GIT_OK=$? - -echo "" - -if [ $JAVA_OK -ne 0 ] || [ $MVN_OK -ne 0 ]; then - echo -e "${RED}错误: 缺少必要的开发工具${NC}" - echo "请安装以下工具:" - [ $JAVA_OK -ne 0 ] && echo " - JDK 1.8+" - [ $MVN_OK -ne 0 ] && echo " - Maven 3.5+" - exit 1 -fi - -# 2. 检查项目结构 -echo "2. 检查项目结构..." -echo "----------------------------" - -MODULES=("jun_java_plugins" "jun_springboot_plugin" "jun_springboot_starter" "jun_springcloud_plugin" "java_project_template") - -for module in "${MODULES[@]}"; do - if [ -d "$module" ]; then - echo -e "${GREEN}✓${NC} $module 目录存在" - else - echo -e "${YELLOW}⚠${NC} $module 目录不存在" - fi -done - -echo "" - -# 3. 统计模块数量 -echo "3. 统计项目模块..." -echo "----------------------------" - -for module in "${MODULES[@]}"; do - if [ -d "$module" ]; then - count=$(find "$module" -maxdepth 1 -type d | grep -v "^$module$" | wc -l) - echo "$module: $count 个子模块" - fi -done - -echo "" - -# 4. 检查 Maven 依赖 -echo "4. 检查 Maven 配置..." -echo "----------------------------" - -if [ -f "pom.xml" ]; then - echo -e "${GREEN}✓${NC} 找到根 pom.xml" - echo "项目版本: $(grep -m 1 '' pom.xml | sed 's/.*\(.*\)<\/version>.*/\1/')" -else - echo -e "${RED}✗${NC} 未找到根 pom.xml" - exit 1 -fi - -echo "" - -# 5. 清理和编译检查(可选) -echo "5. 编译检查选项..." -echo "----------------------------" -echo "是否执行 Maven 编译检查? (y/n)" -echo -e "${YELLOW}注意: 完整编译可能需要 5-10 分钟${NC}" -read -p "请选择: " compile_choice - -if [ "$compile_choice" == "y" ] || [ "$compile_choice" == "Y" ]; then - echo "" - echo "开始编译..." - export MAVEN_OPTS="-Xmx2048m -XX:MaxPermSize=512m" - - # 只编译不测试 - mvn clean compile -DskipTests -T 4 - - if [ $? -eq 0 ]; then - echo -e "${GREEN}✓ 编译成功${NC}" - else - echo -e "${RED}✗ 编译失败,请查看错误信息${NC}" - echo "提示: 某些模块可能有依赖冲突,这在演示仓库中是正常的" - fi -else - echo "跳过编译检查" -fi - -echo "" - -# 6. 冒烟测试 -echo "6. 冒烟测试..." -echo "----------------------------" - -# 检查是否有编译产物 -if [ -d "target" ]; then - echo -e "${GREEN}✓${NC} target 目录存在" -else - echo -e "${YELLOW}⚠${NC} target 目录不存在,未进行编译" -fi - -# 检查关键文件 -if [ -f "task_list.json" ]; then - echo -e "${GREEN}✓${NC} 任务规划文件存在" - task_count=$(grep -o '"id"' task_list.json | wc -l) - echo " - 共 $task_count 个任务" -fi - -if [ -f "CLAUDE.md" ]; then - echo -e "${GREEN}✓${NC} CLAUDE.md 文档存在" -fi - -echo "" - -# 7. 总结 -echo "==========================================" -echo " 环境检查完成" -echo "==========================================" -echo "" -echo "下一步操作:" -echo "1. 阅读 README.md 了解项目结构" -echo "2. 查看 task_list.json 了解任务规划" -echo "3. 参考 CLAUDE.md 了解开发规范" -echo "4. 使用 /crud 技能生成代码" -echo "" -echo "常用命令:" -echo " mvn clean compile # 编译项目" -echo " mvn clean package # 打包项目" -echo " mvn clean install # 安装到本地仓库" -echo "" -echo -e "${GREEN}初始化完成!${NC}" diff --git a/java_project_template/jun-mybatisplus-api-v2/.gitignore b/java_project_template/jun-mybatisplus-api-v2/.gitignore deleted file mode 100644 index bfa6a22a52..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/.gitignore +++ /dev/null @@ -1 +0,0 @@ -# Created by .ignore support plugin (hsz.mobi) diff --git a/java_project_template/jun-mybatisplus-api-v2/CLAUDE.md b/java_project_template/jun-mybatisplus-api-v2/CLAUDE.md deleted file mode 100644 index c4e80ae91a..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/CLAUDE.md +++ /dev/null @@ -1,264 +0,0 @@ -# CLAUDE.md - -This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. - -## Project Overview - -This is a Spring Boot 2.2.2 + MyBatis-Plus 3.3.0 API seed project for rapid development of small to medium-sized REST APIs. It features a Redis-based token authentication system, unified response handling, code generation, and multi-datasource support. - -**Tech Stack**: Spring Boot, MyBatis-Plus, Redis, Druid, Knife4j (Swagger), MySQL, FastJSON, Lombok - -## Development Commands - -### Build and Run -```bash -# Build project -mvn clean package - -# Run application (default port 8080) -mvn spring-boot:run - -# Run with specific profile -mvn spring-boot:run -Dspring-boot.run.profiles=dev -``` - -### Testing -```bash -# Run all tests -mvn test - -# Run specific test class -mvn test -Dtest=UserServiceTest -``` - -### Code Generation -1. Configure database connection in `src/test/java/CodeGenerator.java` (lines 40-44) -2. Set `tableName` variable (line 18) to target table(s) - comma-separated for multiple -3. Run `CodeGenerator.main()` to generate: Model, Mapper, Service, ServiceImpl, Controller, Mapper XML -4. Refresh project directory to see generated files -5. Generated files follow project structure: `web/`, `service/`, `dao/`, `model/`, `resources/mapper/` - -### Database -- Import test database: `test/mysql/user.sql` into MySQL -- Configure datasource in `src/main/resources/application-dev.yml` -- Default database name: `project`, username: `root`, password: `123456` - -### API Documentation -- Access Knife4j UI: http://localhost:8080/doc.html -- Disable in production: set `knife4j.production: true` in config - -## Architecture Overview - -### Package Structure -``` -com.company.project/ -├── web/ # Controllers (@RestController) - REST endpoints -├── service/ # Business logic interfaces (IService extensions) -│ └── impl/ # Service implementations (ServiceImpl extensions) -├── dao/ # MyBatis mappers (extends BaseMapper) -├── model/ # JPA entities with Lombok annotations -├── configurer/ # Spring configurations & interceptors -├── core/ # Core utilities (Result, ServiceException, etc.) -└── utils/ # Helper utilities (MD5, ImageCode, etc.) -``` - -### Authentication & Session Management - -**Token-Based Authentication (Redis)**: -- Token format: `{32-random-chars}#{userId}` (e.g., `aBcD1234efgh...#123`) -- Token stored in Redis with key `user:token:{token}`, TTL: 7 days (604800s) -- Token can be passed via: - - Header: `Authorization: {token}` (preferred) - - Request parameter: `?token={token}` (fallback) -- Login endpoint: `POST /api/user/login` with `{"username":"admin","password":"123456"}` -- Returns token in response, use it in all subsequent requests - -**Session Service** (`HttpSessionService`): -- `createTokenAndUser(User)` - Generate token and store session -- `getCurrentSession()` - Retrieve session from current request token -- `abortUserByToken()` - Logout current session (single token) -- `abortAllUserByToken()` - Invalidate all tokens for current user (used on password change) -- `abortUserByUserId(userId)` - Admin function to force logout specific user - -**Login Security**: -- Password hashing: Double MD5 with salt (`MD5(MD5(password + "springboot_api"))`) -- Failed login tracking: Max 5 attempts, locks account for 1 hour -- Redis key for tracking: `user:password:error:{username}` -- Single/Multi-login mode: Configure via `redis.allowMultipleLogin` (default: false) - -**LoginInterceptor** (`configurer/LoginInterceptor.java`): -- Intercepts all requests except: `/api/user/login`, `/api/user/register`, `/doc.html`, Swagger resources -- Validates token presence and validity -- Returns 401 UNAUTHORIZED if token missing/invalid - -### Unified Response Handling - -**Result Wrapper** - All API responses use this structure: -```json -{ - "code": 200, - "success": true, - "message": "SUCCESS", - "data": {...} -} -``` - -**ResultCode Enum**: -- 200: SUCCESS -- 400: FAIL (business errors) -- 401: UNAUTHORIZED -- 404: NOT_FOUND -- 500: INTERNAL_SERVER_ERROR -- 10001: PARAM_FAIL (validation errors) - -**Usage in Controllers**: -```java -return ResultGenerator.genSuccessResult(data); -return ResultGenerator.genFailResult("Error message"); -``` - -**Exception Handling** (`WebMvcConfigurer.java`): -- `ServiceException` → Auto-wrapped into Result with code 400 -- `MethodArgumentNotValidException` → Code 10001 (validation) -- `NoHandlerFoundException` → Code 404 -- Generic exceptions → Code 500 -- **Best Practice**: Throw `new ServiceException("message")` for business failures, will be auto-wrapped - -### Multi-Datasource Support - -**Configuration** (in `application-dev.yml`): -```yaml -spring.datasource.dynamic: - primary: master # Default datasource - datasource: - master: {...} # Primary DB - slave_1: {...} # Secondary DB - slave_2: {...} # Tertiary DB -``` - -**Usage**: Add `@DS("slave_1")` annotation on service methods or classes to switch datasource - -**Important**: Uses `dynamic-datasource-spring-boot-starter` v2.5.5 - -### MyBatis-Plus Features - -**Base Operations** (No SQL needed): -- All services extend `ServiceImpl`, which provides: `save()`, `saveOrUpdate()`, `removeById()`, `updateById()`, `getById()`, `list()`, `page()` -- All mappers extend `BaseMapper` with CRUD methods - -**Pagination**: -- Configured via `PaginationInterceptor` in `MyBatisPlusConfig` -- Usage: `Page page = new Page<>(pageNum, pageSize); userService.page(page, queryWrapper);` - -**Logic Delete**: -- Field name: `del_flag` (configurable in CodeGenerator line 20) -- Deletes set field to 1, queries auto-filter deleted records -- Config in `application-dev.yml`: `logic-delete-value: 1`, `logic-not-delete-value: 0` - -**Custom Queries**: -- Define in Mapper interface: `List customQuery(@Param("param") String param);` -- XML in `src/main/resources/mapper/UserMapper.xml` - -### Model/Entity Guidelines - -**Annotations**: -- `@TableName("table_name")` - Map to specific table -- `@TableId(type = IdType.AUTO)` - Primary key with auto-increment -- `@TableLogic` - Mark logic delete field -- `@TableField(exist = false)` - Non-database fields (e.g., DTOs, transient data) - -**DTO Pattern**: -- If extending model with non-DB fields (e.g., join queries), prefer creating separate DTO class -- Alternative: Use `@TableField(exist = false)` on extended fields in Model - -**Lombok Support**: -- All models use: `@Data`, `@EqualsAndHashCode(callSuper = false)`, `@Accessors(chain = true)` - -## Key Configuration Files - -**Profile-specific configs**: -- `application.yml` - Base configuration (active profile: dev, server port: 8080) -- `application-dev.yml` - Development (local MySQL, Redis, multi-datasource setup) -- `application-test.yml` - Testing environment -- `application-prod.yml` - Production (knife4j docs disabled) - -**Redis Configuration** (`application-dev.yml`): -```yaml -redis: - key.prefix.userToken: "user:token:" - key.prefix.passwordError: "user:password:error:" - key.expire.userToken: 604800 # 7 days - key.expire.passwordError: 3600 # 1 hour - allowMultipleLogin: false # Single login mode -``` - -**MyBatis-Plus Configuration**: -```yaml -mybatis-plus: - configuration.log-impl: org.apache.ibatis.logging.stdout.StdOutImpl - mapper-locations: classpath:mapper/*.xml -``` - -## Development Patterns - -### Creating New Endpoints - -1. **Generate Code**: Use `CodeGenerator` for table-based CRUD -2. **Service Layer**: Business logic in `service/impl/`, throw `ServiceException` for errors -3. **Controller Layer**: REST endpoints in `web/`, use `ResultGenerator` for responses -4. **Request Validation**: Use `@Valid` on request bodies with validation annotations -5. **Authentication**: Protected endpoints auto-validated by `LoginInterceptor` -6. **Get Current User**: `JSONObject session = httpSessionService.getCurrentSession();` - - Returns: `{"userId": 123, "username": "admin"}` - -### Working with Redis - -Use `RedisService` for all Redis operations: -```java -@Autowired -private RedisService redisService; - -redisService.set(key, value, expireSeconds); -String value = redisService.get(key); -boolean exists = redisService.exists(key); -redisService.remove(key); -redisService.delKeys(pattern); // Pattern-based deletion -``` - -### Custom Exception Handling - -Throw `ServiceException` anywhere in service/controller layer: -```java -if (user == null) { - throw new ServiceException("User not found"); -} -``` -Will automatically return: `{"code": 400, "success": false, "message": "User not found"}` - -## Important Files Reference - -- `Application.java` - Main entry point, enables mapper scanning -- `WebMvcConfigurer.java` - Global exception handler, CORS, interceptors -- `LoginInterceptor.java` - Token validation interceptor -- `HttpSessionService.java` - Session lifecycle management -- `RedisService.java` - Redis operations wrapper -- `UserController.java` - Example auth endpoints (login, register, logout, password change) -- `CodeGenerator.java` - Code generation tool (in test directory) - -## Testing API - -**Login Flow**: -```bash -# 1. Login -curl -X POST http://localhost:8080/api/user/login \ - -H "Content-Type: application/json" \ - -d '{"username":"admin","password":"123456"}' - -# Response: {"code":200,"data":{"token":"xyz123...#1","username":"admin"}} - -# 2. Use token in subsequent requests -curl -X GET http://localhost:8080/api/user/getById/1 \ - -H "Authorization: xyz123...#1" -``` - -**Access Documentation**: http://localhost:8080/doc.html (Knife4j UI with all endpoints) diff --git a/java_project_template/jun-mybatisplus-api-v2/README.md b/java_project_template/jun-mybatisplus-api-v2/README.md deleted file mode 100644 index a4be665995..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/README.md +++ /dev/null @@ -1,43 +0,0 @@ -## 简介 -Spring Boot API 是一个基于Spring Boot & MyBatis plus的种子项目,用于快速构建中小型API项目,特点稳定、简单、快速,摆脱那些重复劳动 - -## 特征&提供 -- 统一响应结果封装及生成工具 -- 统一异常处理 -- 采用redis token认证,支持单登陆端/多登陆端登陆 -- 使用Druid Spring Boot Starter 集成Druid数据库连接池与监控 -- 集成MyBatis-Plus,实现单表业务零SQL -- 支持多数据源,自由切换,只需方法或类上用 @DS 切换数据源 -- 集成国人风格的knife4j,自动生成接口文档 -- 提供代码生成器,生成controller,service,serviceImpl,dao,mapper.xml - -## 快速开始 -1. 克隆项目 -2. 导入```test```包里的mysql脚本user.sql -3. 对```test```包内的代码生成器```CodeGenerator```进行配置,主要是JDBC,因为要根据表名来生成代码 -4. 输入表名,运行```CodeGenerator.main()```方法,生成基础代码(可能需要刷新项目目录才会出来) -5. 根据业务在基础代码上进行扩展 -6. 对开发环境配置文件```application-dev.yml```进行配置,启动项目,Have Fun! - -## 开发建议 -- post调用接口ip:8080/api/user/login,参数json: {"username":"admin","password":"123456"},调用成功后, 返回token。以后调用api接口,header中传token -- 已写好注册、登陆、登出、修改密码接口, 支持单登陆端/多登陆端登陆, 具体看UserController.java 类。用户登陆之后获取session信息 JSONObject sessionInfo = httpSession.getCurrentSession(); -- 正式环境已禁用接口文档的查看,配置文件添加knife4j:production: true 即可 -- 是否允许多个登陆端,修改配置文件 redis:allowMultipleLogin:true -- Model内成员变量建议与表字段数量对应,如需扩展成员变量(比如连表查询)建议创建DTO,否则需在扩展的成员变量上加@TableField(exist = false),详见[MyBatis-Plus](https://mp.baomidou.com/guide/)文档说明 -- 建议业务失败直接使用ServiceException("ErrorMessage")抛出,由统一异常处理器来封装业务失败的响应结果,会直接被封装为{"code":400,"message":"ErrorMessage"}返回,尽情抛出;body方式传参,@Valid校验Model,更无需自己处理; - -## 接口文档效果图 -![image-20200313084433855](http://tuchuang.aitangbao.com.cn/image-20200313084433855.png) - -## 相关文档 -- Spring Boot([springboot官方](https://spring.io/projects/spring-boot/)) -- MyBatis-Plus ([查看官方中文文档](https://mp.baomidou.com/guide/)) -- MyBatis-Plus分页插件([查看官方中文文档](https://mp.baomidou.com/guide/page.html)) -- Druid Spring Boot Starter([查看官方中文文档](https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter/)) -- Fastjson([查看官方中文文档](https://github.com/Alibaba/fastjson/wiki/%E9%A6%96%E9%A1%B5)) -- 阿里巴巴Java开发手册[最新版下载](https://github.com/alibaba/p3c) -其他 - -## License -纯粹开源分享,感谢大家 [Star](https://github.com/aitangbao/springboot-api-v2) 的支持。 diff --git a/java_project_template/jun-mybatisplus-api-v2/pom.xml b/java_project_template/jun-mybatisplus-api-v2/pom.xml deleted file mode 100644 index a581e8039d..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/pom.xml +++ /dev/null @@ -1,160 +0,0 @@ - - - 4.0.0 - - com.company.project - jun-mybatisplus-api-v2 - 1.0 - jar - - - 1.8 - 3.3.0 - - - - - org.springframework.boot - spring-boot-starter-parent - 2.2.2.RELEASE - - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-jdbc - - - - org.springframework.boot - spring-boot-starter-data-redis - - - org.springframework.boot - spring-boot-starter-test - test - - - - com.baomidou - dynamic-datasource-spring-boot-starter - 2.5.5 - - - com.baomidou - mybatis-plus - ${mybatis-plus.version} - - - com.baomidou - mybatis-plus-boot-starter - ${mybatis-plus.version} - - - com.baomidou - mybatis-plus-generator - ${mybatis-plus.version} - - - org.projectlombok - lombok - 1.18.10 - provided - - - - - - commons-codec - commons-codec - - - org.apache.commons - commons-lang3 - 3.6 - - - - mysql - mysql-connector-java - runtime - - - - - com.alibaba - fastjson - 1.2.47 - - - - com.alibaba - druid-spring-boot-starter - 1.1.10 - - - - org.freemarker - freemarker - 2.3.30 - test - - - - com.github.xiaoymin - knife4j-spring-boot-starter - 2.0.2 - - - cn.hutool - hutool-all - 5.8.41 - compile - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - maven-compiler-plugin - - ${java.version} - ${java.version} - UTF-8 - - - - - - - - aliyun-repos - http://maven.aliyun.com/nexus/content/groups/public/ - - false - - - - - - - aliyun-plugin - http://maven.aliyun.com/nexus/content/groups/public/ - - false - - - - - \ No newline at end of file diff --git a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/Application.java b/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/Application.java deleted file mode 100644 index 2d366a4211..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/Application.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.company.project; - -import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure; -import org.mybatis.spring.annotation.MapperScan; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.env.Environment; -import springfox.documentation.swagger2.annotations.EnableSwagger2; - -import java.net.InetAddress; - -@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class) -@MapperScan("com.company.project.dao") -public class Application { - - private static Logger logger= LoggerFactory.getLogger(Application.class); - - public static void main(String[] args) throws Exception { - - ConfigurableApplicationContext application = SpringApplication.run(Application.class, args); - - Environment env = application.getEnvironment(); - logger.info("\n----------------------------------------------------------\n\t" + - "Application '{}' is running! Access URLs:\n\t" + - "Local: \t\thttp://localhost:{}\n\t" + - "External: \thttp://{}:{}\n\t" + - "Doc: \thttp://{}:{}/doc.html\n" + - "----------------------------------------------------------", - env.getProperty("spring.application.name"), - env.getProperty("server.port"), - InetAddress.getLocalHost().getHostAddress(), - env.getProperty("server.port"), - InetAddress.getLocalHost().getHostAddress(), - env.getProperty("server.port")); - } -} - diff --git a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/configurer/LoginInterceptor.java b/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/configurer/LoginInterceptor.java deleted file mode 100644 index b0d7c2949c..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/configurer/LoginInterceptor.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.company.project.configurer; - - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.company.project.core.Result; -import com.company.project.core.ResultCode; -import com.company.project.service.HttpSessionService; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import java.io.IOException; - -/** - * @author wenbin - * @since 2019/10/30 15:29 - *

登陆拦截器 - */ -public class LoginInterceptor extends HandlerInterceptorAdapter { - - @Autowired - private HttpSessionService httpSession; - - private final Logger logger = LoggerFactory.getLogger(WebMvcConfigurer.class); - - @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - //用户当前session信息 - JSONObject currentSession; - //拦截接口 - //从header中获取token - String token = request.getHeader("token"); - //如果header中不存在token,则从参数中获取token - if (StringUtils.isBlank(token)) { - token = request.getParameter("token"); - } - //token为空返回 - if (StringUtils.isBlank(token)) { - Result result = new Result(); - result.setCode(ResultCode.UNAUTHORIZED).setMessage("token不能为空").setSuccess(false); - responseResult(response, result); - return false; - }// 校验并解析token,如果token过期或者篡改,则会返回null - currentSession = httpSession.getCurrentSession(); - if (null != currentSession) { - return true; - } else { - Result result = new Result(); - result.setCode(ResultCode.UNAUTHORIZED).setMessage("用户未登陆!").setSuccess(false); - responseResult(response, result); - return false; - } - } - - - private void responseResult(HttpServletResponse response, Result result) { - response.setCharacterEncoding("UTF-8"); - response.setHeader("Content-type", "application/json;charset=UTF-8"); - try { - response.getWriter().write(JSON.toJSONString(result)); - } catch (IOException ex) { - logger.error(ex.getMessage()); - } - } -} diff --git a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/configurer/MyBatisPlusConfig.java b/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/configurer/MyBatisPlusConfig.java deleted file mode 100644 index f75a63819c..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/configurer/MyBatisPlusConfig.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.company.project.configurer; - -import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * @ClassName MyBatisPlusConfig - * @Version 1.0 - **/ -@Configuration -public class MyBatisPlusConfig { - /** - * 配置mybatis-plus 分页查件 - * @return - */ - @Bean - public PaginationInterceptor paginationInterceptor() { - PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); - return paginationInterceptor; - } -} \ No newline at end of file diff --git a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/configurer/SwaggerConfiguration.java b/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/configurer/SwaggerConfiguration.java deleted file mode 100644 index d5bca5303f..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/configurer/SwaggerConfiguration.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.company.project.configurer; - -import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration; -import springfox.documentation.builders.ApiInfoBuilder; -import springfox.documentation.builders.PathSelectors; -import springfox.documentation.builders.RequestHandlerSelectors; -import springfox.documentation.service.ApiInfo; -import springfox.documentation.spi.DocumentationType; -import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger2.annotations.EnableSwagger2; - -@Configuration -@EnableSwagger2 -@EnableKnife4j -@Import(BeanValidatorPluginsConfiguration.class) -public class SwaggerConfiguration { - - @Bean - public Docket createRestApi() { - return new Docket(DocumentationType.SWAGGER_2) - .apiInfo(apiInfo()) - .select() - .apis(RequestHandlerSelectors.basePackage("com.company.project.web")) - .paths(PathSelectors.any()) - .build(); - } - - private ApiInfo apiInfo() { - return new ApiInfoBuilder() - .title("Springboot-api APIs") - .description("Springboot-api APIs") - .termsOfServiceUrl("http://localhost:8080/") - .contact("xxxxxxxxxx@163.com") - .version("1.0") - .build(); - } -} \ No newline at end of file diff --git a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/configurer/WebMvcConfigurer.java b/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/configurer/WebMvcConfigurer.java deleted file mode 100644 index c960c54e8f..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/configurer/WebMvcConfigurer.java +++ /dev/null @@ -1,179 +0,0 @@ -package com.company.project.configurer; - -import java.io.IOException; -import java.nio.charset.Charset; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.serializer.SerializerFeature; -import com.alibaba.fastjson.support.config.FastJsonConfig; -import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; - -import com.company.project.core.Result; -import com.company.project.core.ResultCode; -import com.company.project.core.ResultGenerator; -import com.company.project.core.ServiceException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.MediaType; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.web.bind.MethodArgumentNotValidException; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.method.HandlerMethod; -import org.springframework.web.servlet.HandlerExceptionResolver; -import org.springframework.web.servlet.ModelAndView; -import org.springframework.web.servlet.NoHandlerFoundException; -import org.springframework.web.servlet.config.annotation.*; - -/** - * Spring MVC 配置 - */ -@Configuration -public class WebMvcConfigurer extends WebMvcConfigurerAdapter { - - private final Logger logger = LoggerFactory.getLogger(WebMvcConfigurer.class); - - @Bean - LoginInterceptor loginInterceptor() { - - return new LoginInterceptor(); - } - - //使用阿里 FastJson 作为JSON MessageConverter - @Override - public void configureMessageConverters(List> converters) { - FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); - FastJsonConfig config = new FastJsonConfig(); - config.setSerializerFeatures(SerializerFeature.WriteMapNullValue);//保留空的字段 - //SerializerFeature.WriteNullStringAsEmpty,//String null -> "" - //SerializerFeature.WriteNullNumberAsZero//Number null -> 0 - // 按需配置,更多参考FastJson文档哈 - - converter.setFastJsonConfig(config); - converter.setDefaultCharset(Charset.forName("UTF-8")); - converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON_UTF8)); - converters.add(converter); - } - - - //统一异常处理 - @Override - public void configureHandlerExceptionResolvers(List exceptionResolvers) { - exceptionResolvers.add(new HandlerExceptionResolver() { - public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) { - Result result = new Result(); - if (e instanceof ServiceException) {//业务失败的异常,如“账号或密码错误” - result.setCode(ResultCode.FAIL).setMessage(e.getMessage()).setSuccess(false); - } else if (e instanceof MethodArgumentNotValidException) {//@valid注解验证参数 - MethodArgumentNotValidException m = (MethodArgumentNotValidException) e; - m.getBindingResult().getFieldError().getDefaultMessage(); - result.setCode(ResultCode.PARAM_FAIL).setMessage(m.getBindingResult().getFieldError().getDefaultMessage()).setSuccess(false); - } else if (e instanceof NoHandlerFoundException) { - result.setCode(ResultCode.NOT_FOUND).setMessage("接口 [" + request.getRequestURI() + "] 不存在").setSuccess(false); - } else if (e instanceof ServletException) { - result.setCode(ResultCode.FAIL).setMessage(e.getMessage()).setSuccess(false); - } else { - result.setCode(ResultCode.INTERNAL_SERVER_ERROR).setMessage("接口 [" + request.getRequestURI() + "] 内部错误,请联系管理员").setSuccess(false); - String message; - if (handler instanceof HandlerMethod) { - HandlerMethod handlerMethod = (HandlerMethod) handler; - message = String.format("接口 [%s] 出现异常,方法:%s.%s,异常摘要:%s", - request.getRequestURI(), - handlerMethod.getBean().getClass().getName(), - handlerMethod.getMethod().getName(), - e.getMessage()); - } else { - message = e.getMessage(); - } - logger.error(message, e); - } - responseResult(response, result); - return new ModelAndView(); - } - - }); - } - - @ExceptionHandler(MethodArgumentNotValidException.class) - public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { - return ResultGenerator.genFailResult(e.getBindingResult().getFieldError().getDefaultMessage()); - } - - /** - * 页面跨域访问Controller过滤 - * - * @return - */ - @Override - public void addCorsMappings(CorsRegistry registry) { - WebMvcConfigurer.super.addCorsMappings(registry); - registry.addMapping("/**") - .allowedHeaders("*") - .allowedMethods("POST","GET") - .allowedOrigins("*"); - } - - //添加拦截器 - @Override - public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(loginInterceptor()) - .excludePathPatterns("/doc.html") - .excludePathPatterns("/swagger-resources/**") - .excludePathPatterns("/error") - .excludePathPatterns("/webjars/**") - .excludePathPatterns("/api/user/login") - .excludePathPatterns("/api/user/register") - .addPathPatterns("/**"); - } - - - private void responseResult(HttpServletResponse response, Result result) { - response.setCharacterEncoding("UTF-8"); - response.setHeader("Content-type", "application/json;charset=UTF-8"); - response.setStatus(200); - try { - response.getWriter().write(JSON.toJSONString(result)); - } catch (IOException ex) { - logger.error(ex.getMessage()); - } - } - - /** - * 发现如果继承了WebMvcConfigurationSupport,则在yml中配置的相关内容会失效。 需要重新指定静态资源 - * - * @param registry - */ - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("/**").addResourceLocations( - "classpath:/static/"); - registry.addResourceHandler("doc.html").addResourceLocations( - "classpath:/META-INF/resources/"); - registry.addResourceHandler("/webjars/**").addResourceLocations( - "classpath:/META-INF/resources/webjars/"); - super.addResourceHandlers(registry); - } - - - /** - * 配置servlet处理 - */ - @Override - public void configureDefaultServletHandling( - DefaultServletHandlerConfigurer configurer) { - configurer.enable(); - } - - - - -} - diff --git a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/core/ApplicationContextUtil.java b/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/core/ApplicationContextUtil.java deleted file mode 100644 index 8121fb4b4b..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/core/ApplicationContextUtil.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.company.project.core; - -import org.springframework.beans.BeansException; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.stereotype.Component; - -/** - * @className: ApplicationContextUtil - * @Description: 解决定时任务获取不到service的问题 - * @Author moneylee - * @Date 2019-05-11 14:28 - * @Version 1.0 - **/ -@Component -public class ApplicationContextUtil implements ApplicationContextAware { - - private static ApplicationContext applicationContext; - - public static ApplicationContext getApplicationContext() { - return applicationContext; - } - - - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - ApplicationContextUtil.applicationContext = applicationContext; - - } - - public static Object getBean(String beanName) { - return applicationContext.getBean(beanName); - } - -} \ No newline at end of file diff --git a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/core/Result.java b/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/core/Result.java deleted file mode 100644 index b208a52ae2..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/core/Result.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.company.project.core; - -import com.alibaba.fastjson.JSON; - -/** - * 统一API响应结果封装 - */ -public class Result { - private int code; - private String message; - private T data; - private Boolean success; - - public Result setCode(ResultCode resultCode) { - this.code = resultCode.code(); - return this; - } - - public int getCode() { - return code; - } - - public String getMessage() { - return message; - } - - public Result setMessage(String message) { - this.message = message; - return this; - } - - public T getData() { - return data; - } - - public Result setData(T data) { - this.data = data; - return this; - } - - public Boolean getSuccess() { - return success; - } - - public Result setSuccess(Boolean success) { - this.success = success; - return this; - } - - @Override - public String toString() { - return JSON.toJSONString(this); - } -} diff --git a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/core/ResultCode.java b/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/core/ResultCode.java deleted file mode 100644 index 651c04d826..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/core/ResultCode.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.company.project.core; - -/** - * 响应码枚举,参考HTTP状态码的语义 - */ -public enum ResultCode { - SUCCESS(200),//成功 - FAIL(400),//失败 - UNAUTHORIZED(401),//未认证(签名错误) - NOT_FOUND(404),//接口不存在 - INTERNAL_SERVER_ERROR(500),//服务器内部错误 - PARAM_FAIL(10001);//参数异常 - - private final int code; - - ResultCode(int code) { - this.code = code; - } - - public int code() { - return code; - } -} diff --git a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/core/ResultGenerator.java b/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/core/ResultGenerator.java deleted file mode 100644 index de79f955e9..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/core/ResultGenerator.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.company.project.core; - -/** - * 响应结果生成工具 - */ -public class ResultGenerator { - private static final String DEFAULT_SUCCESS_MESSAGE = "SUCCESS"; - - public static Result genSuccessResult() { - return new Result() - .setSuccess(true) - .setCode(ResultCode.SUCCESS) - .setMessage(DEFAULT_SUCCESS_MESSAGE); - } - - public static Result genSuccessResult(T data) { - return new Result() - .setSuccess(true) - .setCode(ResultCode.SUCCESS) - .setMessage(DEFAULT_SUCCESS_MESSAGE) - .setData(data); - } - - public static Result genFailResult(String message) { - return new Result() - .setSuccess(false) - .setCode(ResultCode.FAIL) - .setMessage(message); - } -} diff --git a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/core/ServiceException.java b/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/core/ServiceException.java deleted file mode 100644 index e698bce9da..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/core/ServiceException.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.company.project.core; - -/** - * 服务(业务)异常如“ 账号或密码错误 ”,该异常只做INFO级别的日志记录 @see WebMvcConfigurer - */ -public class ServiceException extends RuntimeException { - public ServiceException() { - } - - public ServiceException(String message) { - super(message); - } - - public ServiceException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/dao/UserMapper.java b/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/dao/UserMapper.java deleted file mode 100644 index f731dd72d1..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/dao/UserMapper.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.company.project.dao; - -import com.company.project.model.User; -import com.baomidou.mybatisplus.core.mapper.BaseMapper; - -/** - *

- * Mapper 接口 - *

- * - * @author project - * @since 2020-01-08 - */ -public interface UserMapper extends BaseMapper { - -} diff --git a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/model/User.java b/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/model/User.java deleted file mode 100644 index ccb159e35c..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/model/User.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.company.project.model; - -import com.baomidou.mybatisplus.annotation.IdType; -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableId; -import com.baomidou.mybatisplus.annotation.TableLogic; -import java.io.Serializable; -import java.util.Date; - -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.experimental.Accessors; - -import javax.validation.constraints.NotEmpty; - -/** - *

- * - *

- * - * @author project - * @since 2020-01-08 - */ -@Data -@EqualsAndHashCode(callSuper = false) -@Accessors(chain = true) -public class User implements Serializable { - - private static final long serialVersionUID = 1L; - - /** - * 主键 - */ - @TableId(value = "id", type = IdType.AUTO) - private Integer id; - - /** - * 用户名 - */ - @NotEmpty(message = "用户名不能为空!") - private String username; - - /** - * 密码 - */ - @NotEmpty(message = "密码不能为空!") - private String password; - - /** - * 昵称 - */ - private String nickName; - - /** - * 性别 - */ - private Integer sex; - - /** - * 创建时间 - */ - private Date createDate; - - /** - * 创建人 - */ - private Integer createUser; - - /** - * 修改时间 - */ - private Date updateDate; - - /** - * 修改人 - */ - private Integer updateUser; - - /** - * 删除标志0未删 1删除 - */ - @TableLogic - private Integer delFlag; - - /** - * 登陆返回token - */ - @TableField(exist = false) - private String token; - -} diff --git a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/service/HttpSessionService.java b/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/service/HttpSessionService.java deleted file mode 100644 index c28c14b817..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/service/HttpSessionService.java +++ /dev/null @@ -1,148 +0,0 @@ -package com.company.project.service; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.company.project.model.User; -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; - -import javax.servlet.http.HttpServletRequest; -import java.util.Random; - -/** - * session管理器 - * - * @author aitangbao - */ -@Service -public class HttpSessionService { - - @Autowired - private RedisService redisDB; - - @Autowired - private HttpServletRequest request; - - @Value("${redis.key.prefix.userToken}") - private String USER_TOKEN_PREFIX; - - @Value("${redis.key.expire.userToken}") - private int EXPIRE ; - - public String createTokenAndUser(User user) { - //方便根据id找到redis的key, 修改密码/退出登陆 方便使用 - String token = getRandomToken(32) + "#" + user.getId(); - JSONObject sessionInfo = new JSONObject(); - sessionInfo.put("userId", user.getId()); - sessionInfo.put("username", user.getUsername()); - String key = USER_TOKEN_PREFIX + token; - //设置该用户已登录的token - redisDB.setAndExpire(key, sessionInfo.toJSONString(), EXPIRE); - return token; - } - - /** - * 根据token获取userid - * - * @param token - * @return - */ - public static String getUserIdByToken(String token) { - if (StringUtils.isBlank(token) || !token.contains("#")) { - return ""; - } else { - return token.substring(token.indexOf("#") + 1); - } - } - - /** - * 获取参数中的token - * - * @return - */ - public String getTokenFromHeader() { - String token = request.getHeader("token"); - //如果header中不存在token,则从参数中获取token - if (StringUtils.isBlank(token)) { - token = request.getParameter("token"); - } - return token; - } - - /** - * 获取当前session信息 - * - * @return - */ - public JSONObject getCurrentSession() { - String token = getTokenFromHeader(); - if (null != token) { - if (redisDB.exists(USER_TOKEN_PREFIX + token)) { - String sessionInfoStr = redisDB.get(USER_TOKEN_PREFIX + token); - JSONObject sessionInfo = JSON.parseObject(sessionInfoStr); - return sessionInfo; - } else { - return null; - } - } else { - return null; - } - } - - - /** - * 使当前用户的token失效 - */ - public void abortUserByToken() { - String token = getTokenFromHeader(); - redisDB.del(USER_TOKEN_PREFIX + token); - } - - /** - * 使所有用户的token失效 - */ - public void abortAllUserByToken() { - String token = getTokenFromHeader(); - String userId = getUserIdByToken(token); - redisDB.delKeys(USER_TOKEN_PREFIX+"*#" + userId); - } - - /** - * 使用户的token失效 - */ - public void abortUserByUserId(Integer userId) { - redisDB.delKeys(USER_TOKEN_PREFIX+"*#" + userId); - } - - - /** - * 生成随机的token - * - * @param length - * @return - */ - private String getRandomToken(int length) { - Random random = new Random(); - StringBuilder randomStr = new StringBuilder(); - - // 根据length生成相应长度的随机字符串 - for (int i = 0; i < length; i++) { - String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; - - //输出字母还是数字 - if ("char".equalsIgnoreCase(charOrNum)) { - //输出是大写字母还是小写字母 - int temp = random.nextInt(2) % 2 == 0 ? 65 : 97; - randomStr.append((char) (random.nextInt(26) + temp)); - } else if ("num".equalsIgnoreCase(charOrNum)) { - randomStr.append(String.valueOf(random.nextInt(10))); - } - } - - return randomStr.toString(); - } - - -} diff --git a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/service/IUserService.java b/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/service/IUserService.java deleted file mode 100644 index 97ab829ead..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/service/IUserService.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.company.project.service; - -import com.company.project.core.Result; -import com.company.project.model.User; -import com.baomidou.mybatisplus.extension.service.IService; - -/** - *

- * 服务类 - *

- * - * @author project - * @since 2020-01-08 - */ -public interface IUserService extends IService { - - Result checkPassword(User userParam); -} diff --git a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/service/RedisService.java b/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/service/RedisService.java deleted file mode 100644 index 238e4bee99..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/service/RedisService.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.company.project.service; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.stereotype.Service; -import org.springframework.util.CollectionUtils; - -import java.util.Date; -import java.util.Set; -import java.util.concurrent.TimeUnit; - - -/** - * @author : aitangbao - */ - -@Service -public class RedisService { - @Autowired - private StringRedisTemplate redisTemplate; - - public boolean exists(String key) { - return this.redisTemplate.hasKey(key); - } - - public String get(String key) { - String value = this.redisTemplate.opsForValue().get(key); - return value; - } - - - public void del(String key) { - if (this.exists(key)) { - this.redisTemplate.delete(key); - } - - } - - public void setAndExpire(String key, String value, int seconds) { - this.redisTemplate.opsForValue().set(key, value); - this.redisTemplate.expire(key, (long) seconds, TimeUnit.SECONDS); - } - - - public void setExpire(String key, Date endTime) { - long seconds = endTime.getTime() - (new Date()).getTime(); - this.redisTemplate.expire(key, (long) ((int) (seconds / 1000L)), TimeUnit.SECONDS); - } - - - public Set keys(String pattern) { - return redisTemplate.keys("*" + pattern); - } - - public void delKeys(String pattern) { - Set keys = redisTemplate.keys(pattern); - if (!CollectionUtils.isEmpty(keys)) { - this.redisTemplate.delete(keys); - } - } -} diff --git a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/service/impl/UserServiceImpl.java b/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/service/impl/UserServiceImpl.java deleted file mode 100644 index 67f595f402..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/service/impl/UserServiceImpl.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.company.project.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.company.project.core.Result; -import com.company.project.core.ResultGenerator; -import com.company.project.model.User; -import com.company.project.dao.UserMapper; -import com.company.project.service.IUserService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.company.project.service.RedisService; -import com.company.project.utils.MD5Utils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; - -/** - *

- * 服务实现类 - *

- * - * @author project - * @since 2020-01-08 - */ -@Service -public class UserServiceImpl extends ServiceImpl implements IUserService { - - @Autowired - private UserMapper userMapper; - - - @Autowired - private RedisService redis; - @Value("${redis.key.prefix.passwordError}") - private String PASSWORD_ERROR_PREFIX; - @Value("${redis.key.expire.passwordError}") - private int PASSWORD_ERROR_EXPIRE; - - @Override - public Result checkPassword(User userParam) { - - String username = userParam.getUsername(); - String password = userParam.getPassword(); - //redis key - String redisPasswordErrorKey = PASSWORD_ERROR_PREFIX + username; - //判断账户是否锁定 - String errorCount = redis.get(redisPasswordErrorKey); - if (errorCount != null && Integer.parseInt(errorCount) == 5) { - return ResultGenerator.genFailResult("密码连续错误5次,请1小时后重试"); - } - //根据用户名获取用户信息 - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.eq("username", username); - User user = userMapper.selectOne(queryWrapper); - if (user == null) { - return ResultGenerator.genFailResult("账号未找到"); - } - - if (!MD5Utils.Encrypt(password, true).equals(user.getPassword())) { - if (errorCount == null) { - errorCount = "1"; - } else { - errorCount = String.valueOf(Integer.parseInt(errorCount) + 1); - } - redis.setAndExpire(redisPasswordErrorKey, errorCount, PASSWORD_ERROR_EXPIRE); - if ("5".equals(errorCount)) { - return ResultGenerator.genFailResult("密码连续错误5次,请1小时后重试"); - } else { - return ResultGenerator.genFailResult("密码错误,剩余次数" + (5 - Integer.parseInt(errorCount))); - } - } else { - //登录成功删除错误登录次数 - redis.del(redisPasswordErrorKey); - return ResultGenerator.genSuccessResult(user); - } - } -} diff --git a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/utils/ImageCodeUtil.java b/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/utils/ImageCodeUtil.java deleted file mode 100644 index d87c21e8c2..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/utils/ImageCodeUtil.java +++ /dev/null @@ -1,117 +0,0 @@ -package com.company.project.utils; - -import cn.hutool.log.StaticLog; -import lombok.extern.slf4j.Slf4j; - -import javax.imageio.ImageIO; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import java.awt.*; -import java.awt.image.BufferedImage; -import java.util.Random; - -@Slf4j -public class ImageCodeUtil { - - - public static final String IMAGE_RANDOM_CODEKEY = "RANDOMVALIDATECODEKEY";//放到session中的key - private String randString = "0123456789";//随机产生只有数字的字符串 private String - //private String randString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生只有字母的字符串 - //private String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生数字与字母组合的字符串 - private int width = 95;// 图片宽 - private int height = 25;// 图片高 - private int lineSize = 40;// 干扰线数量 - private int stringNum = 4;// 随机产生字符数量 - - - private Random random = new Random(); - - /** - * 获得字体 - */ - private Font getFont() { - return new Font("Fixedsys", Font.CENTER_BASELINE, 18); - } - - /** - * 获得颜色 - */ - private Color getRandColor(int fc, int bc) { - if (fc > 255) - fc = 255; - if (bc > 255) - bc = 255; - int r = fc + random.nextInt(bc - fc - 16); - int g = fc + random.nextInt(bc - fc - 14); - int b = fc + random.nextInt(bc - fc - 18); - return new Color(r, g, b); - } - - /** - * 生成随机图片 - */ - public void getRandcode(HttpServletRequest request, HttpServletResponse response) { - HttpSession session = request.getSession(); - // BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类 - BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); - Graphics g = image.getGraphics();// 产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作 - g.fillRect(0, 0, width, height);//图片大小 - g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));//字体大小 - g.setColor(getRandColor(110, 133));//字体颜色 - // 绘制干扰线 - for (int i = 0; i <= lineSize; i++) { - drowLine(g); - } - // 绘制随机字符 - String randomString = ""; - for (int i = 1; i <= stringNum; i++) { - randomString = drowString(g, randomString, i); - } - StaticLog.info(randomString); - //将生成的随机字符串保存到session中 - session.removeAttribute(IMAGE_RANDOM_CODEKEY); - session.setAttribute(IMAGE_RANDOM_CODEKEY, randomString); - g.dispose(); - try { - // 将内存中的图片通过流动形式输出到客户端 - ImageIO.write(image, "JPEG", response.getOutputStream()); - } catch (Exception e) { - StaticLog.error("将内存中的图片通过流动形式输出到客户端失败>>>> ", e); - } - - } - - /** - * 绘制字符串 - */ - private String drowString(Graphics g, String randomString, int i) { - g.setFont(getFont()); - g.setColor(new Color(random.nextInt(101), random.nextInt(111), random - .nextInt(121))); - String rand = String.valueOf(getRandomString(random.nextInt(randString - .length()))); - randomString += rand; - g.translate(random.nextInt(3), random.nextInt(3)); - g.drawString(rand, 13 * i, 16); - return randomString; - } - - /** - * 绘制干扰线 - */ - private void drowLine(Graphics g) { - int x = random.nextInt(width); - int y = random.nextInt(height); - int xl = random.nextInt(13); - int yl = random.nextInt(15); - g.drawLine(x, y, x + xl, y + yl); - } - - /** - * 获取随机的字符 - */ - public String getRandomString(int num) { - return String.valueOf(randString.charAt(num)); - } -} \ No newline at end of file diff --git a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/utils/MD5Utils.java b/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/utils/MD5Utils.java deleted file mode 100644 index c7a3dff75c..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/utils/MD5Utils.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.company.project.utils; - -import org.apache.commons.codec.digest.DigestUtils; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.StringUtils; - -public class MD5Utils { - - private static String salt = "springboot_api"; - - /** - * 加密字符串 - * @param password 要加密的明文 - * @param isAddSalt 是否加默认盐 - * @return 加密之后的结果 - */ - public static String Encrypt(String password, boolean isAddSalt){ - if (StringUtils.isNotEmpty(password)){ - if (isAddSalt){ - return DigestUtils.md5Hex(DigestUtils.md5(password + salt)); - } else { - return DigestUtils.md5Hex(DigestUtils.md5(password)); - } - } - return null; - } - - /** - * - * @param bytes - * @return - */ - public static String Encrypt(byte[] bytes){ - if (ArrayUtils.isNotEmpty(bytes)){ - return DigestUtils.md5Hex(DigestUtils.md5(bytes)); - } - return null; - } - - /** - * MD5加盐加密 - * @param password 要加密的明文 - * @param salt 盐 - * @return 加密之后的结果 - */ - public static String Encrypt(String password, String salt){ - if (StringUtils.isNotEmpty(password)){ - return DigestUtils.md5Hex(DigestUtils.md5(password + salt)); - } - return null; - } - - public static void main(String[] args){ - System.out.println(MD5Utils.Encrypt("admin", true)); - } -} diff --git a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/web/UserController.java b/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/web/UserController.java deleted file mode 100644 index 48aa0249b6..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/src/main/java/com/company/project/web/UserController.java +++ /dev/null @@ -1,203 +0,0 @@ -package com.company.project.web; - -import com.alibaba.fastjson.JSONObject; -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.company.project.core.Result; -import com.company.project.core.ResultGenerator; -import com.company.project.service.HttpSessionService; -import com.company.project.utils.MD5Utils; -import com.company.project.utils.ImageCodeUtil; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.web.bind.annotation.*; -import com.company.project.service.IUserService; -import com.company.project.model.User; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import lombok.extern.slf4j.Slf4j; -import com.baomidou.mybatisplus.core.metadata.IPage; - -import javax.annotation.Resource; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import javax.validation.Valid; - -import org.springframework.web.bind.annotation.RestController; - -import java.util.HashMap; -import java.util.Map; - -/** - *

- * 前端控制器 - *

- * - * @author project - * @since 2020-01-08 - */ -@Slf4j -@RestController -@RequestMapping("/api/user") -public class UserController { - - @Resource - private IUserService userService; - @Autowired - private HttpSessionService httpSession; - - @Value("${redis.allowMultipleLogin}") - private Boolean allowMultipleLogin; - - @ApiOperation("登陆") - @PostMapping("/login") - public Result login(@RequestBody @Valid User userParam) { - - //校验密码,5次错误锁定账户 - Result result = userService.checkPassword(userParam); - if (!result.getSuccess()) { - return result; - } - //成功之后返回user - User user = (User)result.getData(); - - //是否删除之前token, 此处控制是否支持多登陆端; - // true:允许多处登陆; false:只能单处登陆,顶掉之前登陆 - if (!allowMultipleLogin) { - httpSession.abortUserByUserId(user.getId()); - } - - //生成token - String token = httpSession.createTokenAndUser(user); - - Map resultMap = new HashMap<>(2); - resultMap.put("token", token); - resultMap.put("username", userParam.getUsername()); - return ResultGenerator.genSuccessResult(resultMap); - } - - @ApiOperation("注册") - @PostMapping("/register") - public Result register(@RequestBody @Valid User user) { - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.eq("username", user.getUsername()); - User userO = userService.getOne(queryWrapper); - if (userO != null) { - return ResultGenerator.genFailResult("账号已存在"); - } - user.setPassword(MD5Utils.Encrypt(user.getPassword(), true)); - userService.save(user); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation("修改密码") - @PostMapping("/updatePassword") - public Result updatePassword(@RequestBody JSONObject param) { - String oldPassword = param.getString("oldPassword"); - String newPassword = param.getString("newPassword"); - if (StringUtils.isBlank(oldPassword) || StringUtils.isBlank(newPassword)) { - return ResultGenerator.genFailResult("密码不能为空"); - } - //获取登陆信息 - JSONObject sessionInfo = httpSession.getCurrentSession(); - String userId = sessionInfo.getString("userId"); - - User user = userService.getById(userId); - if (user == null) { - return ResultGenerator.genFailResult("账号未找到"); - } - if (!MD5Utils.Encrypt(oldPassword, true).equals(user.getPassword())) { - return ResultGenerator.genFailResult("旧密码错误"); - } - User updateUser = new User(); - updateUser.setId(user.getId()); - updateUser.setPassword(MD5Utils.Encrypt(newPassword, true)); - userService.updateById(updateUser); - - //重置密码后删除原所有token - httpSession.abortAllUserByToken(); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation("登出") - @GetMapping("/logout") - public Result logout() { - //退出删除token - httpSession.abortUserByToken(); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation("校验token是否有效") - @GetMapping("/validateToken") - public Result validateToken() { - //拦截器拦截已判断,直接返回成功 - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "删除") - @PostMapping("delete/{id}") - public Result delete(@PathVariable("id") Long id) { - userService.removeById(id); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "更新") - @PostMapping("update") - public Result update(@RequestBody User user) { - //密码不更新 - user.setPassword(null); - userService.updateById(user); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "查询分页数据") - @ApiImplicitParams({ - @ApiImplicitParam(name = "currentPage", value = "页码"), - @ApiImplicitParam(name = "pageCount", value = "每页条数") - }) - @GetMapping("listByPage") - public Result findListByPage(@RequestParam(defaultValue = "1") Integer currentPage, - @RequestParam(defaultValue = "10") Integer pageCount) { - Page page = new Page(currentPage, pageCount); - IPage iPage = userService.page(page); - return ResultGenerator.genSuccessResult(iPage); - } - - @ApiOperation(value = "id查询") - @GetMapping("getById/{id}") - public Result findById(@PathVariable Long id) { - return ResultGenerator.genSuccessResult(userService.getById(id)); - } - - @ApiOperation(value = "生成验证码") - @GetMapping(value = "/getVerify") - public void getVerify(HttpServletRequest request, HttpServletResponse response) { - response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片 - response.setHeader("Pragma", "No-cache");//设置响应头信息,告诉浏览器不要缓存此内容 - response.setHeader("Cache-Control", "no-cache"); - response.setDateHeader("Expire", 0); - try { - ImageCodeUtil randomValidateCode = new ImageCodeUtil(); - randomValidateCode.getRandcode(request, response);//输出验证码图片方法 - } catch (Exception e) { - log.error("生成验证码失败"); - } - } - - @ApiOperation(value = "校验验证码") - @PostMapping(value = "/checkVerify") - public Result checkVerify(@RequestParam String imageCode, HttpSession session) { - //从session中获取随机数 - Object random = session.getAttribute(ImageCodeUtil.IMAGE_RANDOM_CODEKEY); - if (random != null && String.valueOf(random).equals(imageCode)) { - return ResultGenerator.genSuccessResult(); - } - return ResultGenerator.genFailResult("校验失败"); - } - - -} diff --git a/java_project_template/jun-mybatisplus-api-v2/src/main/resources/application-dev.yml b/java_project_template/jun-mybatisplus-api-v2/src/main/resources/application-dev.yml deleted file mode 100644 index b16e34f2cd..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/src/main/resources/application-dev.yml +++ /dev/null @@ -1,53 +0,0 @@ -# 开发环境配置 -spring: - datasource: - dynamic: - primary: master #设置默认的数据源或者数据源组,默认值即为master - datasource: - master: - username: root - password: 123456 - driver-class-name: com.mysql.cj.jdbc.Driver - url: jdbc:mysql://localhost:3306/project?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2b8 - slave_1: - username: root - password: 123456 - driver-class-name: com.mysql.cj.jdbc.Driver - url: jdbc:mysql://xx.xx.xx.xx:3307/dynamic?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2b8 - slave_2: - username: root - password: 123456 - driver-class-name: com.mysql.cj.jdbc.Driver - url: jdbc:mysql://xx.xx.xx.xx:3308/dynamic?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2b8 - #......省略 - #以上会配置一个默认库master,一个组slave下有两个子库slave_1,slave_2 - -redis: - key: - prefix: - userToken: "user:token:" - passwordError: "user:password:error:" - expire: - userToken: 604800 # 7天 7*24*3600 - passwordError: 3600 # 一个小时 - allowMultipleLogin: false # 允许多处登陆 - host: localhost # Redis服务器地址 - database: 0 # Redis数据库索引(默认为0) - port: 6379 # Redis服务器连接端口 - password: # Redis服务器连接密码(默认为空) - jedis: - pool: - max-active: 8 # 连接池最大连接数(使用负值表示没有限制) - max-wait: -1ms # 连接池最大阻塞等待时间(使用负值表示没有限制) - max-idle: 8 # 连接池中的最大空闲连接 - min-idle: 0 # 连接池中的最小空闲连接 - timeout: 3000ms # 连接超时时间(毫秒 - -mybatis-plus: - configuration: - log-impl: org.apache.ibatis.logging.stdout.StdOutImpl - mapper-locations: classpath:mapper/*.xml - global-config: - db-config: - logic-delete-value: 1 - logic-not-delete-value: 0 diff --git a/java_project_template/jun-mybatisplus-api-v2/src/main/resources/application-prod.yml b/java_project_template/jun-mybatisplus-api-v2/src/main/resources/application-prod.yml deleted file mode 100644 index 27cc9a1df0..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/src/main/resources/application-prod.yml +++ /dev/null @@ -1,4 +0,0 @@ -# 生产环境配置 - -knife4j: - production: true #生成环境禁用查看文档 \ No newline at end of file diff --git a/java_project_template/jun-mybatisplus-api-v2/src/main/resources/application-test.yml b/java_project_template/jun-mybatisplus-api-v2/src/main/resources/application-test.yml deleted file mode 100644 index 287da7b20e..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/src/main/resources/application-test.yml +++ /dev/null @@ -1 +0,0 @@ -# 测试环境配置 diff --git a/java_project_template/jun-mybatisplus-api-v2/src/main/resources/application.yml b/java_project_template/jun-mybatisplus-api-v2/src/main/resources/application.yml deleted file mode 100644 index facce6d372..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/src/main/resources/application.yml +++ /dev/null @@ -1,14 +0,0 @@ -spring: - profiles: - active: dev - mvc: - throw-exception-if-no-handler-found: true - resources: - add-mappings: false - application: - name: Springboot-api - jackson: - date-format: yyyy-MM-dd HH:mm:ss - time-zone: GMT+8 -server: - port: 8080 diff --git a/java_project_template/jun-mybatisplus-api-v2/src/main/resources/banner.txt b/java_project_template/jun-mybatisplus-api-v2/src/main/resources/banner.txt deleted file mode 100644 index 152e179398..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/src/main/resources/banner.txt +++ /dev/null @@ -1,22 +0,0 @@ -//////////////////////////////////////////////////////////////////// -// _ooOoo_ // -// o8888888o // -// 88" . "88 // -// (| ^_^ |) // -// O\ = /O // -// ____/`---'\____ // -// .' \\| |// `. // -// / \\||| : |||// \ // -// / _||||| -:- |||||- \ // -// | | \\\ - /// | | // -// | \_| ''\---/'' | | // -// \ .-\__ `-` ___/-. / // -// ___`. .' /--.--\ `. . ___ // -// ."" '< `.___\_<|>_/___.' >'"". // -// | | : `- \`.;`\ _ /`;.`/ - ` : | | // -// \ \ `-. \_ __\ /__ _/ .-` / / // -// ========`-.____`-.___\_____/___.-`____.-'======== // -// `=---=' // -// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // -// 佛祖保佑 永不宕机 永无BUG // -//////////////////////////////////////////////////////////////////// \ No newline at end of file diff --git a/java_project_template/jun-mybatisplus-api-v2/src/main/resources/mapper/UserMapper.xml b/java_project_template/jun-mybatisplus-api-v2/src/main/resources/mapper/UserMapper.xml deleted file mode 100644 index 87ab7e4161..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/src/main/resources/mapper/UserMapper.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - id, username, password, nick_name, sex, create_date, create_user, update_date, update_user, del_flag - - - \ No newline at end of file diff --git a/java_project_template/jun-mybatisplus-api-v2/src/test/java/CodeGenerator.java b/java_project_template/jun-mybatisplus-api-v2/src/test/java/CodeGenerator.java deleted file mode 100644 index 027a50e707..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/src/test/java/CodeGenerator.java +++ /dev/null @@ -1,113 +0,0 @@ -import com.baomidou.mybatisplus.core.toolkit.StringPool; -import com.baomidou.mybatisplus.generator.AutoGenerator; -import com.baomidou.mybatisplus.generator.InjectionConfig; -import com.baomidou.mybatisplus.generator.config.*; -import com.baomidou.mybatisplus.generator.config.po.TableInfo; -import com.baomidou.mybatisplus.generator.config.rules.DateType; -import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; -import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; - -import java.util.ArrayList; -import java.util.List; - -// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中 -public class CodeGenerator { - - - //多个表逗号分隔 - static String tableName = "biz_mail"; - //逻辑删除字段名, 假如表没有逻辑删除字段,请忽视 - static String logicDeleteFieldName = "del_flag"; - - public static void main(String[] args) { - // 代码生成器 - AutoGenerator mpg = new AutoGenerator(); - - // 全局配置 - GlobalConfig gc = new GlobalConfig(); - String projectPath = System.getProperty("user.dir"); - gc.setOutputDir(projectPath + "/src/main/java"); - gc.setAuthor("wujun"); - gc.setOpen(false); - gc.setBaseColumnList(true); - gc.setBaseResultMap(true); - gc.setDateType(DateType.ONLY_DATE); - // gc.setSwagger2(true); 实体属性 Swagger2 注解 - mpg.setGlobalConfig(gc); - - // 数据源配置 - DataSourceConfig dsc = new DataSourceConfig(); - dsc.setUrl("jdbc:mysql://localhost:3307/db_test?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC"); - // dsc.setSchemaName("public"); - dsc.setDriverName("com.mysql.cj.jdbc.Driver"); - dsc.setUsername("root"); - dsc.setPassword("mysqladmin"); - mpg.setDataSource(dsc); - - // 包配置 - PackageConfig pc = new PackageConfig(); - pc.setParent("com.company.project"); - pc.setEntity("model"); - pc.setMapper("dao"); - pc.setController("web"); - mpg.setPackageInfo(pc); - - // 自定义配置 - InjectionConfig cfg = new InjectionConfig() { - @Override - public void initMap() { - // to do nothing - } - }; - - // 如果模板引擎是 freemarker - String templatePath = "/templates/mapper.xml.ftl"; - // 如果模板引擎是 velocity - // String templatePath = "/templates/mapper.xml.vm"; - - // 自定义输出配置 - List focList = new ArrayList<>(); - // 自定义配置会被优先输出 - focList.add(new FileOutConfig(templatePath) { - @Override - public String outputFile(TableInfo tableInfo) { - // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!! - return projectPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; - } - }); - cfg.setFileOutConfigList(focList); - mpg.setCfg(cfg); - - // 配置模板 - TemplateConfig templateConfig = new TemplateConfig(); - - // 配置自定义输出模板 - //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别 -// templateConfig.setEntity("templates/entity.java"); - // templateConfig.setService(); - templateConfig.setController("templates/controller.java"); - - templateConfig.setXml(null); - mpg.setTemplate(templateConfig); - - // 策略配置 - StrategyConfig strategy = new StrategyConfig(); - strategy.setNaming(NamingStrategy.underline_to_camel); - strategy.setColumnNaming(NamingStrategy.underline_to_camel); -// strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!"); - strategy.setEntityLombokModel(true); - strategy.setRestControllerStyle(true); - // 公共父类 -// strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!"); - // 写于父类中的公共字段 -// strategy.setSuperEntityColumns("id"); - strategy.setInclude(tableName.split(",")); - strategy.setControllerMappingHyphenStyle(true); - strategy.setLogicDeleteFieldName(logicDeleteFieldName); // 逻辑删除字段名称 - strategy.setTablePrefix(pc.getModuleName() + "_"); - mpg.setStrategy(strategy); - mpg.setTemplateEngine(new FreemarkerTemplateEngine()); - mpg.execute(); - } - -} \ No newline at end of file diff --git a/java_project_template/jun-mybatisplus-api-v2/src/test/java/com/company/project/Tester.java b/java_project_template/jun-mybatisplus-api-v2/src/test/java/com/company/project/Tester.java deleted file mode 100644 index f513bc219d..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/src/test/java/com/company/project/Tester.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.company.project; - -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(classes = Application.class) -public class Tester { - - @Test - public void test() { - - } -} - - - diff --git a/java_project_template/jun-mybatisplus-api-v2/src/test/resources/templates/controller.java.ftl b/java_project_template/jun-mybatisplus-api-v2/src/test/resources/templates/controller.java.ftl deleted file mode 100644 index a62f181707..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/src/test/resources/templates/controller.java.ftl +++ /dev/null @@ -1,94 +0,0 @@ -package ${package.Controller}; - -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.company.project.core.Result; -import com.company.project.core.ResultGenerator; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import org.springframework.web.bind.annotation.*; -import ${package.Service}.${table.serviceName}; -import ${package.Entity}.${entity}; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import lombok.extern.slf4j.Slf4j; -import com.baomidou.mybatisplus.core.metadata.IPage; - -import javax.annotation.Resource; -<#if restControllerStyle> -import org.springframework.web.bind.annotation.RestController; -<#else> -import org.springframework.stereotype.Controller; - -<#if superControllerClassPackage??> -import ${superControllerClassPackage}; - - -/** - *

- * ${table.comment!} 前端控制器 - *

- * - * @author ${author} - * @since ${date} - */ -<#if restControllerStyle> -@Api(tags = {"${table.comment!}"}) -@Slf4j -@RestController -<#else> -@Controller - -@RequestMapping("<#if package.ModuleName??>/${package.ModuleName}/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}") -<#if kotlin> -class ${table.controllerName}<#if superControllerClass??>:${superControllerClass}() -<#else> -<#if superControllerClass??>public class ${table.controllerName} extends ${superControllerClass}{ -<#else>public class ${table.controllerName} { - - - @Resource - private ${table.serviceName} ${(table.serviceName?substring(1))?uncap_first}; - - - @ApiOperation(value = "新增${table.comment!}") - @PostMapping("add") - public Result add(@RequestBody ${entity} ${entity?uncap_first}){ - ${(table.serviceName?substring(1))?uncap_first}.save(${entity?uncap_first}); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "删除${table.comment!}") - @PostMapping("delete/{id}") - public Result delete(@PathVariable("id") Long id){ - ${(table.serviceName?substring(1))?uncap_first}.removeById(id); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "更新${table.comment!}") - @PostMapping("update") - public Result update(@RequestBody ${entity} ${entity?uncap_first}){ - ${(table.serviceName?substring(1))?uncap_first}.updateById(${entity?uncap_first}); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "查询${table.comment!}分页数据") - @ApiImplicitParams({ - @ApiImplicitParam(name = "currentPage", value = "页码"), - @ApiImplicitParam(name = "pageCount", value = "每页条数") - }) - @GetMapping("listByPage") - public Result findListByPage(@RequestParam Integer currentPage, - @RequestParam Integer pageCount){ - Page page = new Page(currentPage, pageCount); - IPage<${entity}> iPage = ${(table.serviceName?substring(1))?uncap_first}.page(page); - return ResultGenerator.genSuccessResult(iPage); - } - - @ApiOperation(value = "id查询${table.comment!}") - @GetMapping("getById/{id}") - public Result findById(@PathVariable Long id){ - return ResultGenerator.genSuccessResult(${(table.serviceName?substring(1))?uncap_first}.getById(id)); - } - -} - \ No newline at end of file diff --git a/java_project_template/jun-mybatisplus-api-v2/src/test/resources/user.sql b/java_project_template/jun-mybatisplus-api-v2/src/test/resources/user.sql deleted file mode 100644 index 51bd7db81e..0000000000 --- a/java_project_template/jun-mybatisplus-api-v2/src/test/resources/user.sql +++ /dev/null @@ -1,52 +0,0 @@ -/* - Navicat Premium Data Transfer - - Source Server : localhost - Source Server Type : MySQL - Source Server Version : 50529 - Source Host : localhost:3306 - Source Schema : project - - Target Server Type : MySQL - Target Server Version : 50529 - File Encoding : 65001 - - Date: 08/01/2020 15:53:02 -*/ - -SET NAMES utf8mb4; -SET FOREIGN_KEY_CHECKS = 0; - --- ---------------------------- --- Table structure for user --- ---------------------------- -DROP TABLE IF EXISTS `user`; -CREATE TABLE `user` ( - `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键', - `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名', - `password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码', - `nick_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '昵称', - `sex` int(1) NULL DEFAULT NULL COMMENT '性别', - `create_date` datetime NULL DEFAULT NULL COMMENT '创建时间', - `create_user` int(11) NULL DEFAULT NULL COMMENT '创建人', - `update_date` datetime NULL DEFAULT NULL COMMENT '修改时间', - `update_user` int(11) NULL DEFAULT NULL COMMENT '修改人', - `del_flag` int(1) NULL DEFAULT 0 COMMENT '删除标志0未删 1删除', - PRIMARY KEY (`id`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 11 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact; - --- ---------------------------- --- Records of user --- ---------------------------- -INSERT INTO `user` VALUES (1, 'admin', '9dc818b4bca3baa7d230fbf96c919638', '土豆', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (2, '2@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-2', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (3, '3@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-3', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (4, '4@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-4', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (5, '5@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-5', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (6, '6@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-6', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (7, '7@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-7', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (8, '8@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-8', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (9, '9@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-9', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (10, '10@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-10', 1, NULL, NULL, NULL, NULL, 0); - -SET FOREIGN_KEY_CHECKS = 1; diff --git a/java_project_template/jun_api_service_admin/Dockerfile b/java_project_template/jun_api_service_admin/Dockerfile deleted file mode 100644 index 45ce8dba92..0000000000 --- a/java_project_template/jun_api_service_admin/Dockerfile +++ /dev/null @@ -1,13 +0,0 @@ -# 基础镜像 -FROM openjdk:8-jre -# author -MAINTAINER wenbin -# 复制jar文件到路径 -ADD manager.jar manager.jar -# 时间 -RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime -RUN echo 'Asia/Shanghai' >/etc/timezone -# 启动服务 -ENTRYPOINT ["java","-jar","/manager.jar"] -# 暴露端口 -EXPOSE 8080 diff --git a/java_project_template/jun_api_service_admin/dependencies.txt b/java_project_template/jun_api_service_admin/dependencies.txt deleted file mode 100644 index 520c4cfefc..0000000000 Binary files a/java_project_template/jun_api_service_admin/dependencies.txt and /dev/null differ diff --git a/java_project_template/jun_api_service_admin/pom.xml b/java_project_template/jun_api_service_admin/pom.xml deleted file mode 100644 index 60d9dba329..0000000000 --- a/java_project_template/jun_api_service_admin/pom.xml +++ /dev/null @@ -1,344 +0,0 @@ - - - 4.0.0 - - com.jun.plugin - 1.0 - jun_api_service_admin - - - 1.8 - 3.4.0 - 2.5.5 - 12.1.0.1-atlassian-hosted - 4.0 - 2.6 - 2.5 - 1.10 - 1.7 - 2.3.2 - 1.4.0 - 1.1.10 - 1.2.74 - 2.0.0 - 2.0.2 - 1.6.2 - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-groovy-templates - - - - - - org.springframework.boot - spring-boot-starter-test - test - - - - org.springframework.boot - spring-boot-starter-aop - - - - org.springframework.boot - spring-boot-starter-validation - 2.5.14 - - - - - junit - junit - 4.13.2 - test - - - - - com.alibaba - druid-spring-boot-starter - ${druid.version} - - - - org.springframework.boot - spring-boot-starter-data-redis - - - - - - com.baomidou - mybatis-plus - ${mybatis-plus.version} - - - com.baomidou - mybatis-plus-boot-starter - ${mybatis-plus.version} - - - mysql - mysql-connector-java - runtime - - - com.oracle - ojdbc6 - ${ojdbc6.version} - - - com.microsoft.sqlserver - sqljdbc4 - ${sqlserver.version} - runtime - - - - - - - - - - com.fasterxml.jackson.core - jackson-core - 2.13.3 - - - - com.fasterxml.jackson.core - jackson-annotations - 2.13.3 - - - - com.fasterxml.jackson.core - jackson-databind - 2.13.3 - - - - com.fasterxml.jackson.dataformat - jackson-dataformat-yaml - 2.13.3 - - - - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - 2.13.3 - - - - com.fasterxml.jackson.dataformat - jackson-dataformat-properties - 2.13.3 - - - - org.dom4j - dom4j - 2.1.3 - - - - - - com.google.code.gson - gson - 2.9.0 - - - - - - - - - - org.apache.shiro - shiro-spring - ${shiro.version} - - - - org.projectlombok - lombok - - - - com.alibaba - fastjson - ${fastjson.version} - - - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - com.github.theborakompanioni - thymeleaf-extras-shiro - ${thymeleaf-shiro.version} - - - - - - com.github.xiaoymin - knife4j-spring-boot-starter - ${knife4j.version} - - - commons-lang - commons-lang - ${commons.lang.version} - - - commons-io - commons-io - ${commons.io.version} - - - commons-configuration - commons-configuration - ${commons.configuration.version} - - - velocity - org.apache.velocity - ${velocity.version} - - - org.quartz-scheduler - quartz - ${quartz.version} - - - com.mchange - c3p0 - - - com.zaxxer - HikariCP-java6 - - - - - com.github.whvcse - easy-captcha - ${easy-captcha.version} - - - commons-codec - commons-codec - 1.13 - - - - - com.auth0 - java-jwt - 3.3.0 - - - - - redis.clients - jedis - 2.9.0 - - - - - - - - - org.springframework.boot - spring-boot-dependencies - - - - 2.5.14 - pom - import - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.0 - - 1.8 - 1.8 - - - - org.springframework.boot - spring-boot-maven-plugin - 2.6.2 - - - - - repackage - - - - - - - - - - aliyun-repos - http://maven.aliyun.com/nexus/content/groups/public/ - - false - - - - - - - aliyun-plugin - http://maven.aliyun.com/nexus/content/groups/public/ - - false - - - - diff --git a/java_project_template/jun_api_service_admin/src/main/java/com/jun/plugin/ApiServiceApplication.java b/java_project_template/jun_api_service_admin/src/main/java/com/jun/plugin/ApiServiceApplication.java deleted file mode 100644 index fac20938a2..0000000000 --- a/java_project_template/jun_api_service_admin/src/main/java/com/jun/plugin/ApiServiceApplication.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.jun.plugin; - -import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure; -import lombok.extern.slf4j.Slf4j; -import org.mybatis.spring.annotation.MapperScan; -import org.springframework.boot.CommandLineRunner; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.web.servlet.ServletComponentScan; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.core.env.Environment; - -import java.net.InetAddress; -@Slf4j -@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class) -@MapperScan("com.jun.plugin.**.mapper") -@ServletComponentScan(basePackages = {"com.jun.plugin.**.filter"}) -public class ApiServiceApplication { - - public static void main(String[] args) throws Exception { - ConfigurableApplicationContext application = SpringApplication.run(ApiServiceApplication.class, args); - - Environment env = application.getEnvironment(); - log.info("\n----------------------------------------------------------\n\t" + - "Application '{}' is running! Access URLs:\n\t" + - "Api Test Json: \thttp://{}:{}/public/json\n\t" + - "Api Code Generator: \thttp://{}:{}/generator/list.html\n\t" + - "----------------------------------------------------------", - env.getProperty("spring.application.name"), - InetAddress.getLocalHost().getHostAddress(), - env.getProperty("server.port"), - InetAddress.getLocalHost().getHostAddress(), - env.getProperty("server.port")); - } - - - @Bean - public CommandLineRunner commandLineRunner(ApplicationContext ctx) { - return args -> { - System.out.println("Let's inspect the beans provided by Spring Boot:"); - String[] beanNames = ctx.getBeanDefinitionNames(); - System.err.println("beanNames size = "+ beanNames.length); - for (String beanName : beanNames) { - //System.err.println(beanName); - /* - * Object bean = ctx.getBean(beanName); System.out.println(bean); - * System.out.println(); - */ - } - - }; - } - -} diff --git a/java_project_template/jun_api_service_admin/src/main/resources/application-dev.yml b/java_project_template/jun_api_service_admin/src/main/resources/application-dev.yml deleted file mode 100644 index 26c25d2d8e..0000000000 --- a/java_project_template/jun_api_service_admin/src/main/resources/application-dev.yml +++ /dev/null @@ -1,72 +0,0 @@ -# 开发环境配置 -spring: - thymeleaf: - cache: false - datasource: - type: com.alibaba.druid.pool.DruidDataSource - url: jdbc:mysql://localhost:3306/db_qixing?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2b8 - username: root - password: - driver-class-name: com.mysql.cj.jdbc.Driver -# initialSize: 10 -# minIdle: 10 -# maxActive: 40 -# maxWait: 60000 -# test-on-borrow: true -# test-while-idle: true -# dynamic: -# primary: master #设置默认的数据源或者数据源组,默认值即为master -# datasource: -# master: -# username: root -# password: -# driver-class-name: com.mysql.cj.jdbc.Driver -# url: jdbc:mysql://localhost:3306/test666?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2b8 -# oracle: -# username: root -# password: -# driver-class-name: oracle.jdbc.driver.OracleDriver -# url: jdbc:oracle:thin:@localhost:1521/company_project -# sqlServer: -# username: sa -# password: 123456 -# driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver -# url: jdbc:sqlserver://localhost:1433;databaseName=company_project - redis: - host: localhost # Redis服务器地址 - database: 0 # Redis数据库索引(默认为0) - port: 6379 # Redis服务器连接端口 - password: # Redis服务器连接密码(默认为空) - jedis: - pool: - max-active: 8 # 连接池最大连接数(使用负值表示没有限制) - max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制) - max-idle: 8 # 连接池中的最大空闲连接 - min-idle: 0 # 连接池中的最小空闲连接 - timeout: 13000 # 连接超时时间(毫秒 - -filepath: "D:\\files\\" -file: - #文件上传目录 绝对路径 末尾请加 / - path: D:/files/ #windows - #path: /home/data/files/ #linux - #文件预览、下载的url, 末尾请勿加 / - url: http://qixing.vip321.vip/files - qiniuAccessKey: ts0n9OF16ekFkDkZTTlpmyPI-tP3HKQDyw_GR4o2 - qiniuBucketName: qixing-files - qiniuDomain: http://qiniu.vip321.vip - qiniuPrefix: upload - qiniuSecretKey: c-OjjwV3ZgzCQwxc6W_bsTFKuDg8qeyqohyJU0RL - type: 1 - - -# AES密码加密私钥(Base64加密) -encryptAESKey: V2FuZzkyNjQ1NGRTQkFQSUpXVA== -# JWT认证加密私钥(Base64加密) -encryptJWTKey: U0JBUElKV1RkV2FuZzkyNjQ1NA== -# AccessToken过期时间-5分钟-5*60(秒为单位) -accessTokenExpireTime: 300 -# RefreshToken过期时间-30分钟-30*60(秒为单位) -refreshTokenExpireTime: 1800 -# Shiro缓存过期时间-5分钟-5*60(秒为单位)(一般设置与AccessToken过期时间一致) -shiroCacheExpireTime: 300 \ No newline at end of file diff --git a/java_project_template/jun_api_service_admin/src/main/resources/application.yml b/java_project_template/jun_api_service_admin/src/main/resources/application.yml deleted file mode 100644 index 219ae56fa5..0000000000 --- a/java_project_template/jun_api_service_admin/src/main/resources/application.yml +++ /dev/null @@ -1,50 +0,0 @@ -# 端口 -server: - port: 8088 - -spring: - profiles: - active: dev - mvc: - throw-exception-if-no-handler-found: true - resources: - add-mappings: false - application: - name: jun_springboot_api - jackson: - date-format: yyyy-MM-dd HH:mm:ss - time-zone: GMT+8 - # 文件大小限制 - servlet: - multipart: - max-file-size: 10MB - max-request-size: 100MB - # redis token信息 - redis: - key: - prefix: - userToken: "user:token:" - passwordError: "user:password:error:" - permissionRefresh: "user:token:permissionRefresh:" - expire: - userToken: 604800 # 7天 7*24*3600 - passwordError: 3600 # 一个小时 - permissionRefresh: 604800 # 7天 7*24*3600 - allowMultipleLogin: true # 允许多处登陆 - -mybatis-plus: - configuration: - log-impl: org.apache.ibatis.logging.stdout.StdOutImpl - mapper-locations: classpath:mapper/${project.database}/**/*.xml,classpath:mapper/*.xml - global-config: - db-config: - logic-delete-value: 0 - logic-not-delete-value: 1 - logic-delete-field: deleted - -#使用代码生成模块时 指定要生成的表存在于哪种数据库,可选值有【mysql、oracle、sqlServer】 -project: - database: mysql - -shiro: - enable: false \ No newline at end of file diff --git a/java_project_template/jun_api_service_admin/src/main/resources/logback-spring.xml b/java_project_template/jun_api_service_admin/src/main/resources/logback-spring.xml deleted file mode 100644 index e775a72900..0000000000 --- a/java_project_template/jun_api_service_admin/src/main/resources/logback-spring.xml +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - - - - - - - - - ${CONSOLE_LOG_PATTERN} - - - - - - - ${LOG_PATH}/${LOG_FILE} - - ${FILE_LOG_PATTERN} - - - ${LOG_PATH}/${LOG_HISTORY} - 30 - - - - - - - - 0 - 500 - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/java_project_template/jun_api_service_admin/src/main/resources/templates/biztest/list.html b/java_project_template/jun_api_service_admin/src/main/resources/templates/biztest/list.html deleted file mode 100644 index 128f8142a0..0000000000 --- a/java_project_template/jun_api_service_admin/src/main/resources/templates/biztest/list.html +++ /dev/null @@ -1,299 +0,0 @@ - - - - - Title - - - - - - -
-
-
-
- -
- -
- - -
-
- -
-
-
- - - - - - - - \ No newline at end of file diff --git a/java_project_template/jun_api_service_demo/.gitignore b/java_project_template/jun_api_service_demo/.gitignore deleted file mode 100644 index 957445a861..0000000000 --- a/java_project_template/jun_api_service_demo/.gitignore +++ /dev/null @@ -1,23 +0,0 @@ -target/ - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -nbproject/private/ -build/ -nbbuild/ -dist/ -nbdist/ -.nb-gradle/ \ No newline at end of file diff --git a/java_project_template/jun_api_service_demo/README.md b/java_project_template/jun_api_service_demo/README.md deleted file mode 100644 index 2692deaf29..0000000000 --- a/java_project_template/jun_api_service_demo/README.md +++ /dev/null @@ -1,41 +0,0 @@ -## 简介 -Spring Boot API 是一个基于Spring Boot & MyBatis plus的种子项目,用于快速构建中小型API项目,特点稳定、简单、快速,摆脱那些重复劳动 - -## 特征&提供 -- 统一响应结果封装及生成工具 -- 统一异常处理 -- 采用简单的jwt认证 -- 使用Druid Spring Boot Starter 集成Druid数据库连接池与监控 -- 集成MyBatis-Plus,实现单表业务零SQL -- 支持多数据源,自由切换,只需方法或类上用 @DS 切换数据源 -- 集成国人风格的knife4j,自动生成接口文档 -- 提供代码生成器,生成controller,service,serviceImpl,dao,mapper.xml - -## 快速开始 -1. 克隆项目 -2. 导入```test```包里的mysql脚本user.sql -3. 对```test```包内的代码生成器```CodeGenerator```进行配置,主要是JDBC,因为要根据表名来生成代码 -4. 输入表名,运行```CodeGenerator.main()```方法,生成基础代码(可能需要刷新项目目录才会出来) -5. 根据业务在基础代码上进行扩展 -6. 对开发环境配置文件```application-dev.yml```进行配置,启动项目,Have Fun! - -## 开发建议 -- post调用接口ip:8080/api/user/login,参数json: {"username":"admin","password":"123456"},调用成功后, 返回token。以后调用api接口,header中传token -- 正式环境已禁用接口文档的查看,配置文件添加knife4j:production: true 即可 -- Model内成员变量建议与表字段数量对应,如需扩展成员变量(比如连表查询)建议创建DTO,否则需在扩展的成员变量上加@TableField(exist = false),详见[MyBatis-Plus](https://mp.baomidou.com/guide/)文档说明 -- 建议业务失败直接使用ServiceException("ErrorMessage")抛出,由统一异常处理器来封装业务失败的响应结果,会直接被封装为{"code":400,"message":"ErrorMessage"}返回,尽情抛出;body方式传参,@Valid校验Model,更无需自己处理; - -## 接口文档效果图 -![image-20200313084433855](http://tuchuang.aitangbao.com.cn/image-20200313084433855.png) - -## 相关文档 -- Spring Boot([springboot官方](https://spring.io/projects/spring-boot/)) -- MyBatis-Plus ([查看官方中文文档](https://mp.baomidou.com/guide/)) -- MyBatis-Plus分页插件([查看官方中文文档](https://mp.baomidou.com/guide/page.html)) -- Druid Spring Boot Starter([查看官方中文文档](https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter/)) -- Fastjson([查看官方中文文档](https://github.com/Alibaba/fastjson/wiki/%E9%A6%96%E9%A1%B5)) -- 阿里巴巴Java开发手册[最新版下载](https://github.com/alibaba/p3c) -其他 - -## License -纯粹开源分享,感谢大家 [Star](https://github.com/aitangbao/springboot-api) 的支持。 diff --git a/java_project_template/jun_api_service_demo/pom.xml b/java_project_template/jun_api_service_demo/pom.xml deleted file mode 100644 index 27274de1f0..0000000000 --- a/java_project_template/jun_api_service_demo/pom.xml +++ /dev/null @@ -1,156 +0,0 @@ - - - 4.0.0 - - com.company.project - jun_api_service_demo - 1.0 - jar - - - 1.8 - 3.3.0 - - - - - org.springframework.boot - spring-boot-starter-parent - 2.2.2.RELEASE - - - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-jdbc - - - org.springframework.boot - spring-boot-starter-test - test - - - - com.baomidou - dynamic-datasource-spring-boot-starter - 2.5.5 - - - com.baomidou - mybatis-plus - ${mybatis-plus.version} - - - com.baomidou - mybatis-plus-boot-starter - ${mybatis-plus.version} - - - com.baomidou - mybatis-plus-generator - ${mybatis-plus.version} - - - org.projectlombok - lombok - 1.18.36 - - - - - - commons-codec - commons-codec - - - org.apache.commons - commons-lang3 - 3.6 - - - - mysql - mysql-connector-java - runtime - - - - - com.alibaba - fastjson - 1.2.47 - - - - com.alibaba - druid-spring-boot-starter - 1.1.10 - - - - org.freemarker - freemarker - 2.3.30 - test - - - - com.github.xiaoymin - knife4j-spring-boot-starter - 2.0.2 - - - - io.jsonwebtoken - jjwt - 0.9.0 - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - maven-compiler-plugin - - ${java.version} - ${java.version} - UTF-8 - - - - - - - - aliyun-repos - http://maven.aliyun.com/nexus/content/groups/public/ - - false - - - - - - - aliyun-plugin - http://maven.aliyun.com/nexus/content/groups/public/ - - false - - - - - \ No newline at end of file diff --git a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/Application.java b/java_project_template/jun_api_service_demo/src/main/java/com/company/project/Application.java deleted file mode 100644 index 2d366a4211..0000000000 --- a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/Application.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.company.project; - -import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure; -import org.mybatis.spring.annotation.MapperScan; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.env.Environment; -import springfox.documentation.swagger2.annotations.EnableSwagger2; - -import java.net.InetAddress; - -@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class) -@MapperScan("com.company.project.dao") -public class Application { - - private static Logger logger= LoggerFactory.getLogger(Application.class); - - public static void main(String[] args) throws Exception { - - ConfigurableApplicationContext application = SpringApplication.run(Application.class, args); - - Environment env = application.getEnvironment(); - logger.info("\n----------------------------------------------------------\n\t" + - "Application '{}' is running! Access URLs:\n\t" + - "Local: \t\thttp://localhost:{}\n\t" + - "External: \thttp://{}:{}\n\t" + - "Doc: \thttp://{}:{}/doc.html\n" + - "----------------------------------------------------------", - env.getProperty("spring.application.name"), - env.getProperty("server.port"), - InetAddress.getLocalHost().getHostAddress(), - env.getProperty("server.port"), - InetAddress.getLocalHost().getHostAddress(), - env.getProperty("server.port")); - } -} - diff --git a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/configurer/LoginInterceptor.java b/java_project_template/jun_api_service_demo/src/main/java/com/company/project/configurer/LoginInterceptor.java deleted file mode 100644 index 16e66ea0c8..0000000000 --- a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/configurer/LoginInterceptor.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.company.project.configurer; - - -import com.alibaba.fastjson.JSON; -import com.company.project.core.Result; -import com.company.project.core.ResultCode; -import com.company.project.utils.JwtUtils; -import io.jsonwebtoken.Claims; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import java.io.IOException; - -import static com.company.project.utils.JwtUtils.USER_ACCOUNT_KEY; -import static com.company.project.utils.JwtUtils.USER_ID_KEY; - -/** - *

登陆拦截器 - */ -public class LoginInterceptor extends HandlerInterceptorAdapter { - - private final Logger logger = LoggerFactory.getLogger(WebMvcConfigurer.class); - @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - //拦截接口 - //从header中获取token - String token = request.getHeader("token"); - //如果header中不存在token,则从参数中获取token - if(StringUtils.isBlank(token)){ - token = request.getParameter("token"); - } - //token为空返回 - if(StringUtils.isBlank(token)){ - Result result = new Result(); - result.setCode(ResultCode.UNAUTHORIZED).setMessage("token不能为空").setSuccess(false); - responseResult(response, result); - return false; - }// 校验并解析token,如果token过期或者篡改,则会返回null - Claims claims = JwtUtils.checkJWT(token); - if(null == claims){ - Result result = new Result(); - result.setCode(ResultCode.UNAUTHORIZED).setMessage("登陆失效, 请重新登陆").setSuccess(false); - responseResult(response, result); - return false; - } - // 校验通过后,设置用户信息到request里,在Controller中从Request域中获取用户信息 - request.setAttribute(USER_ID_KEY, claims.get("id")); - request.setAttribute(USER_ACCOUNT_KEY, claims.get("account")); - return true; - } - - - - private void responseResult(HttpServletResponse response, Result result) { - response.setCharacterEncoding("UTF-8"); - response.setHeader("Content-type", "application/json;charset=UTF-8"); - response.setStatus(200); - try { - response.getWriter().write(JSON.toJSONString(result)); - } catch (IOException ex) { - logger.error(ex.getMessage()); - } - } -} diff --git a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/configurer/MyBatisPlusConfig.java b/java_project_template/jun_api_service_demo/src/main/java/com/company/project/configurer/MyBatisPlusConfig.java deleted file mode 100644 index f75a63819c..0000000000 --- a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/configurer/MyBatisPlusConfig.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.company.project.configurer; - -import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * @ClassName MyBatisPlusConfig - * @Version 1.0 - **/ -@Configuration -public class MyBatisPlusConfig { - /** - * 配置mybatis-plus 分页查件 - * @return - */ - @Bean - public PaginationInterceptor paginationInterceptor() { - PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); - return paginationInterceptor; - } -} \ No newline at end of file diff --git a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/configurer/SwaggerConfiguration.java b/java_project_template/jun_api_service_demo/src/main/java/com/company/project/configurer/SwaggerConfiguration.java deleted file mode 100644 index d5bca5303f..0000000000 --- a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/configurer/SwaggerConfiguration.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.company.project.configurer; - -import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration; -import springfox.documentation.builders.ApiInfoBuilder; -import springfox.documentation.builders.PathSelectors; -import springfox.documentation.builders.RequestHandlerSelectors; -import springfox.documentation.service.ApiInfo; -import springfox.documentation.spi.DocumentationType; -import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger2.annotations.EnableSwagger2; - -@Configuration -@EnableSwagger2 -@EnableKnife4j -@Import(BeanValidatorPluginsConfiguration.class) -public class SwaggerConfiguration { - - @Bean - public Docket createRestApi() { - return new Docket(DocumentationType.SWAGGER_2) - .apiInfo(apiInfo()) - .select() - .apis(RequestHandlerSelectors.basePackage("com.company.project.web")) - .paths(PathSelectors.any()) - .build(); - } - - private ApiInfo apiInfo() { - return new ApiInfoBuilder() - .title("Springboot-api APIs") - .description("Springboot-api APIs") - .termsOfServiceUrl("http://localhost:8080/") - .contact("xxxxxxxxxx@163.com") - .version("1.0") - .build(); - } -} \ No newline at end of file diff --git a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/configurer/WebMvcConfigurer.java b/java_project_template/jun_api_service_demo/src/main/java/com/company/project/configurer/WebMvcConfigurer.java deleted file mode 100644 index e790419d9b..0000000000 --- a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/configurer/WebMvcConfigurer.java +++ /dev/null @@ -1,178 +0,0 @@ -package com.company.project.configurer; - -import java.io.IOException; -import java.nio.charset.Charset; -import java.util.Arrays; -import java.util.List; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.serializer.SerializerFeature; -import com.alibaba.fastjson.support.config.FastJsonConfig; -import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; - -import com.company.project.core.Result; -import com.company.project.core.ResultCode; -import com.company.project.core.ResultGenerator; -import com.company.project.core.ServiceException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.MediaType; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.web.bind.MethodArgumentNotValidException; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.method.HandlerMethod; -import org.springframework.web.servlet.HandlerExceptionResolver; -import org.springframework.web.servlet.ModelAndView; -import org.springframework.web.servlet.NoHandlerFoundException; -import org.springframework.web.servlet.config.annotation.*; - -/** - * Spring MVC 配置 - */ -@Configuration -public class WebMvcConfigurer extends WebMvcConfigurerAdapter { - - private final Logger logger = LoggerFactory.getLogger(WebMvcConfigurer.class); - - @Bean - LoginInterceptor loginInterceptor() { - - return new LoginInterceptor(); - } - - //使用阿里 FastJson 作为JSON MessageConverter - @Override - public void configureMessageConverters(List> converters) { - FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); - FastJsonConfig config = new FastJsonConfig(); - config.setSerializerFeatures(SerializerFeature.WriteMapNullValue);//保留空的字段 - //SerializerFeature.WriteNullStringAsEmpty,//String null -> "" - //SerializerFeature.WriteNullNumberAsZero//Number null -> 0 - // 按需配置,更多参考FastJson文档哈 - - converter.setFastJsonConfig(config); - converter.setDefaultCharset(Charset.forName("UTF-8")); - converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON_UTF8)); - converters.add(converter); - } - - - //统一异常处理 - @Override - public void configureHandlerExceptionResolvers(List exceptionResolvers) { - exceptionResolvers.add(new HandlerExceptionResolver() { - public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) { - Result result = new Result(); - if (e instanceof ServiceException) {//业务失败的异常,如“账号或密码错误” - result.setCode(ResultCode.FAIL).setMessage(e.getMessage()).setSuccess(false); - } else if (e instanceof MethodArgumentNotValidException) {//@valid注解验证参数 - MethodArgumentNotValidException m = (MethodArgumentNotValidException) e; - m.getBindingResult().getFieldError().getDefaultMessage(); - result.setCode(ResultCode.PARAM_FAIL).setMessage(m.getBindingResult().getFieldError().getDefaultMessage()).setSuccess(false); - } else if (e instanceof NoHandlerFoundException) { - result.setCode(ResultCode.NOT_FOUND).setMessage("接口 [" + request.getRequestURI() + "] 不存在").setSuccess(false); - } else if (e instanceof ServletException) { - result.setCode(ResultCode.FAIL).setMessage(e.getMessage()).setSuccess(false); - } else { - result.setCode(ResultCode.INTERNAL_SERVER_ERROR).setMessage("接口 [" + request.getRequestURI() + "] 内部错误,请联系管理员").setSuccess(false); - String message; - if (handler instanceof HandlerMethod) { - HandlerMethod handlerMethod = (HandlerMethod) handler; - message = String.format("接口 [%s] 出现异常,方法:%s.%s,异常摘要:%s", - request.getRequestURI(), - handlerMethod.getBean().getClass().getName(), - handlerMethod.getMethod().getName(), - e.getMessage()); - } else { - message = e.getMessage(); - } - logger.error(message, e); - } - responseResult(response, result); - return new ModelAndView(); - } - - }); - } - - @ExceptionHandler(MethodArgumentNotValidException.class) - public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { - return ResultGenerator.genFailResult(e.getBindingResult().getFieldError().getDefaultMessage()); - } - - /** - * 页面跨域访问Controller过滤 - * - * @return - */ - @Override - public void addCorsMappings(CorsRegistry registry) { - WebMvcConfigurer.super.addCorsMappings(registry); - registry.addMapping("/**") - .allowedHeaders("*") - .allowedMethods("POST","GET") - .allowedOrigins("*"); - } - - //添加拦截器 - @Override - public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(loginInterceptor()) - .excludePathPatterns("/doc.html") - .excludePathPatterns("/swagger-resources/**") - .excludePathPatterns("/error") - .excludePathPatterns("/webjars/**") - .excludePathPatterns("/api/user/login") - .excludePathPatterns("/api/user/register") - .addPathPatterns("/**"); - } - - - private void responseResult(HttpServletResponse response, Result result) { - response.setCharacterEncoding("UTF-8"); - response.setHeader("Content-type", "application/json;charset=UTF-8"); - response.setStatus(200); - try { - response.getWriter().write(JSON.toJSONString(result)); - } catch (IOException ex) { - logger.error(ex.getMessage()); - } - } - - /** - * 发现如果继承了WebMvcConfigurationSupport,则在yml中配置的相关内容会失效。 需要重新指定静态资源 - * - * @param registry - */ - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("/**").addResourceLocations( - "classpath:/static/"); - registry.addResourceHandler("doc.html").addResourceLocations( - "classpath:/META-INF/resources/"); - registry.addResourceHandler("/webjars/**").addResourceLocations( - "classpath:/META-INF/resources/webjars/"); - super.addResourceHandlers(registry); - } - - - /** - * 配置servlet处理 - */ - @Override - public void configureDefaultServletHandling( - DefaultServletHandlerConfigurer configurer) { - configurer.enable(); - } - - - - -} - diff --git a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/core/ApplicationContextUtil.java b/java_project_template/jun_api_service_demo/src/main/java/com/company/project/core/ApplicationContextUtil.java deleted file mode 100644 index 8121fb4b4b..0000000000 --- a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/core/ApplicationContextUtil.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.company.project.core; - -import org.springframework.beans.BeansException; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.stereotype.Component; - -/** - * @className: ApplicationContextUtil - * @Description: 解决定时任务获取不到service的问题 - * @Author moneylee - * @Date 2019-05-11 14:28 - * @Version 1.0 - **/ -@Component -public class ApplicationContextUtil implements ApplicationContextAware { - - private static ApplicationContext applicationContext; - - public static ApplicationContext getApplicationContext() { - return applicationContext; - } - - - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - ApplicationContextUtil.applicationContext = applicationContext; - - } - - public static Object getBean(String beanName) { - return applicationContext.getBean(beanName); - } - -} \ No newline at end of file diff --git a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/core/Result.java b/java_project_template/jun_api_service_demo/src/main/java/com/company/project/core/Result.java deleted file mode 100644 index b208a52ae2..0000000000 --- a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/core/Result.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.company.project.core; - -import com.alibaba.fastjson.JSON; - -/** - * 统一API响应结果封装 - */ -public class Result { - private int code; - private String message; - private T data; - private Boolean success; - - public Result setCode(ResultCode resultCode) { - this.code = resultCode.code(); - return this; - } - - public int getCode() { - return code; - } - - public String getMessage() { - return message; - } - - public Result setMessage(String message) { - this.message = message; - return this; - } - - public T getData() { - return data; - } - - public Result setData(T data) { - this.data = data; - return this; - } - - public Boolean getSuccess() { - return success; - } - - public Result setSuccess(Boolean success) { - this.success = success; - return this; - } - - @Override - public String toString() { - return JSON.toJSONString(this); - } -} diff --git a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/core/ResultCode.java b/java_project_template/jun_api_service_demo/src/main/java/com/company/project/core/ResultCode.java deleted file mode 100644 index 651c04d826..0000000000 --- a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/core/ResultCode.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.company.project.core; - -/** - * 响应码枚举,参考HTTP状态码的语义 - */ -public enum ResultCode { - SUCCESS(200),//成功 - FAIL(400),//失败 - UNAUTHORIZED(401),//未认证(签名错误) - NOT_FOUND(404),//接口不存在 - INTERNAL_SERVER_ERROR(500),//服务器内部错误 - PARAM_FAIL(10001);//参数异常 - - private final int code; - - ResultCode(int code) { - this.code = code; - } - - public int code() { - return code; - } -} diff --git a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/core/ResultGenerator.java b/java_project_template/jun_api_service_demo/src/main/java/com/company/project/core/ResultGenerator.java deleted file mode 100644 index de79f955e9..0000000000 --- a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/core/ResultGenerator.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.company.project.core; - -/** - * 响应结果生成工具 - */ -public class ResultGenerator { - private static final String DEFAULT_SUCCESS_MESSAGE = "SUCCESS"; - - public static Result genSuccessResult() { - return new Result() - .setSuccess(true) - .setCode(ResultCode.SUCCESS) - .setMessage(DEFAULT_SUCCESS_MESSAGE); - } - - public static Result genSuccessResult(T data) { - return new Result() - .setSuccess(true) - .setCode(ResultCode.SUCCESS) - .setMessage(DEFAULT_SUCCESS_MESSAGE) - .setData(data); - } - - public static Result genFailResult(String message) { - return new Result() - .setSuccess(false) - .setCode(ResultCode.FAIL) - .setMessage(message); - } -} diff --git a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/core/ServiceException.java b/java_project_template/jun_api_service_demo/src/main/java/com/company/project/core/ServiceException.java deleted file mode 100644 index e698bce9da..0000000000 --- a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/core/ServiceException.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.company.project.core; - -/** - * 服务(业务)异常如“ 账号或密码错误 ”,该异常只做INFO级别的日志记录 @see WebMvcConfigurer - */ -public class ServiceException extends RuntimeException { - public ServiceException() { - } - - public ServiceException(String message) { - super(message); - } - - public ServiceException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/dao/UserMapper.java b/java_project_template/jun_api_service_demo/src/main/java/com/company/project/dao/UserMapper.java deleted file mode 100644 index f731dd72d1..0000000000 --- a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/dao/UserMapper.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.company.project.dao; - -import com.company.project.model.User; -import com.baomidou.mybatisplus.core.mapper.BaseMapper; - -/** - *

- * Mapper 接口 - *

- * - * @author project - * @since 2020-01-08 - */ -public interface UserMapper extends BaseMapper { - -} diff --git a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/model/User.java b/java_project_template/jun_api_service_demo/src/main/java/com/company/project/model/User.java deleted file mode 100644 index ccb159e35c..0000000000 --- a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/model/User.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.company.project.model; - -import com.baomidou.mybatisplus.annotation.IdType; -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableId; -import com.baomidou.mybatisplus.annotation.TableLogic; -import java.io.Serializable; -import java.util.Date; - -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.experimental.Accessors; - -import javax.validation.constraints.NotEmpty; - -/** - *

- * - *

- * - * @author project - * @since 2020-01-08 - */ -@Data -@EqualsAndHashCode(callSuper = false) -@Accessors(chain = true) -public class User implements Serializable { - - private static final long serialVersionUID = 1L; - - /** - * 主键 - */ - @TableId(value = "id", type = IdType.AUTO) - private Integer id; - - /** - * 用户名 - */ - @NotEmpty(message = "用户名不能为空!") - private String username; - - /** - * 密码 - */ - @NotEmpty(message = "密码不能为空!") - private String password; - - /** - * 昵称 - */ - private String nickName; - - /** - * 性别 - */ - private Integer sex; - - /** - * 创建时间 - */ - private Date createDate; - - /** - * 创建人 - */ - private Integer createUser; - - /** - * 修改时间 - */ - private Date updateDate; - - /** - * 修改人 - */ - private Integer updateUser; - - /** - * 删除标志0未删 1删除 - */ - @TableLogic - private Integer delFlag; - - /** - * 登陆返回token - */ - @TableField(exist = false) - private String token; - -} diff --git a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/service/IUserService.java b/java_project_template/jun_api_service_demo/src/main/java/com/company/project/service/IUserService.java deleted file mode 100644 index c6ea45ce7e..0000000000 --- a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/service/IUserService.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.company.project.service; - -import com.company.project.model.User; -import com.baomidou.mybatisplus.extension.service.IService; - -/** - *

- * 服务类 - *

- * - * @author project - * @since 2020-01-08 - */ -public interface IUserService extends IService { - -} diff --git a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/service/impl/UserServiceImpl.java b/java_project_template/jun_api_service_demo/src/main/java/com/company/project/service/impl/UserServiceImpl.java deleted file mode 100644 index 83f0a1a11d..0000000000 --- a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/service/impl/UserServiceImpl.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.company.project.service.impl; - -import com.company.project.model.User; -import com.company.project.dao.UserMapper; -import com.company.project.service.IUserService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import org.springframework.stereotype.Service; - -/** - *

- * 服务实现类 - *

- * - * @author project - * @since 2020-01-08 - */ -@Service -public class UserServiceImpl extends ServiceImpl implements IUserService { - -} diff --git a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/utils/JwtUtils.java b/java_project_template/jun_api_service_demo/src/main/java/com/company/project/utils/JwtUtils.java deleted file mode 100644 index 7cf948ef1b..0000000000 --- a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/utils/JwtUtils.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.company.project.utils; - -import com.company.project.model.User; -import io.jsonwebtoken.Claims; -import io.jsonwebtoken.Jwts; -import io.jsonwebtoken.SignatureAlgorithm; - -import javax.servlet.http.HttpServletRequest; -import java.util.Date; - -/** - * jwt工具类 - */ -public class JwtUtils { - - public static final String USER_ID_KEY = "user_id_key"; - - public static final String USER_ACCOUNT_KEY = "user_account_key"; - - - public static final String SUBJECT = "onehee"; - - public static final long EXPIRE = 1000*60*60*24*7; //过期时间,毫秒,一周 - - //秘钥 - public static final String APPSECRET = "onehee666"; - - /** - * 生成jwt - * @param user - * @return - */ - public static String geneJsonWebToken(User user){ - - String token = Jwts.builder().setSubject(SUBJECT) - .claim("id",user.getId()) - .claim("userName",user.getUsername()) - .setIssuedAt(new Date()) - .setExpiration(new Date(System.currentTimeMillis()+EXPIRE)) - .signWith(SignatureAlgorithm.HS256,APPSECRET).compact(); - - return token; - } - - - /** - * 校验token - * @param token - * @return - */ - public static Claims checkJWT(String token ){ - - try{ - final Claims claims = Jwts.parser().setSigningKey(APPSECRET). - parseClaimsJws(token).getBody(); - return claims; - - }catch (Exception e){ } - return null; - - } - - - /** - * 判断当前登陆用户是不是admin - * @param request - * @return - */ - public static boolean isAdmin(HttpServletRequest request) { - if (request.getAttribute(USER_ACCOUNT_KEY) == null) { - return false; - } - if ("admin".equals(request.getAttribute(USER_ACCOUNT_KEY).toString())){ - return true; - } else { - return false; - } - } - - - -} \ No newline at end of file diff --git a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/utils/MD5Utils.java b/java_project_template/jun_api_service_demo/src/main/java/com/company/project/utils/MD5Utils.java deleted file mode 100644 index c7a3dff75c..0000000000 --- a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/utils/MD5Utils.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.company.project.utils; - -import org.apache.commons.codec.digest.DigestUtils; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.StringUtils; - -public class MD5Utils { - - private static String salt = "springboot_api"; - - /** - * 加密字符串 - * @param password 要加密的明文 - * @param isAddSalt 是否加默认盐 - * @return 加密之后的结果 - */ - public static String Encrypt(String password, boolean isAddSalt){ - if (StringUtils.isNotEmpty(password)){ - if (isAddSalt){ - return DigestUtils.md5Hex(DigestUtils.md5(password + salt)); - } else { - return DigestUtils.md5Hex(DigestUtils.md5(password)); - } - } - return null; - } - - /** - * - * @param bytes - * @return - */ - public static String Encrypt(byte[] bytes){ - if (ArrayUtils.isNotEmpty(bytes)){ - return DigestUtils.md5Hex(DigestUtils.md5(bytes)); - } - return null; - } - - /** - * MD5加盐加密 - * @param password 要加密的明文 - * @param salt 盐 - * @return 加密之后的结果 - */ - public static String Encrypt(String password, String salt){ - if (StringUtils.isNotEmpty(password)){ - return DigestUtils.md5Hex(DigestUtils.md5(password + salt)); - } - return null; - } - - public static void main(String[] args){ - System.out.println(MD5Utils.Encrypt("admin", true)); - } -} diff --git a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/web/UserController.java b/java_project_template/jun_api_service_demo/src/main/java/com/company/project/web/UserController.java deleted file mode 100644 index 303acb3819..0000000000 --- a/java_project_template/jun_api_service_demo/src/main/java/com/company/project/web/UserController.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.company.project.web; - -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.company.project.core.Result; -import com.company.project.core.ResultGenerator; -import com.company.project.utils.JwtUtils; -import com.company.project.utils.MD5Utils; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import org.springframework.web.bind.annotation.*; -import com.company.project.service.IUserService; -import com.company.project.model.User; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import lombok.extern.slf4j.Slf4j; -import com.baomidou.mybatisplus.core.metadata.IPage; - -import javax.annotation.Resource; -import javax.validation.Valid; - -import org.springframework.web.bind.annotation.RestController; - -/** - *

- * 前端控制器 - *

- * - * @author project - * @since 2020-01-08 - */ -@Slf4j -@RestController -@RequestMapping("/api/user") -public class UserController { - - @Resource - private IUserService userService; - - @ApiOperation("登陆") - @PostMapping("/login") - public Result login(@RequestBody @Valid User user) { - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.eq("username", user.getUsername()); - User userO = userService.getOne(queryWrapper); - if (userO == null) { - return ResultGenerator.genFailResult("账号未找到"); - } - if (!MD5Utils.Encrypt(user.getPassword(),true).equals(userO.getPassword())) { - return ResultGenerator.genFailResult("密码错误"); - } - String token = JwtUtils.geneJsonWebToken(user); - user.setToken(token); - user.setPassword(""); - return ResultGenerator.genSuccessResult(user); - } - - @ApiOperation("注册") - @PostMapping("/register") - public Result register(@RequestBody @Valid User user) { - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.eq("username", user.getUsername()); - User userO = userService.getOne(queryWrapper); - if (userO != null) { - return ResultGenerator.genFailResult("账号已存在"); - } - user.setPassword(MD5Utils.Encrypt(user.getPassword(),true)); - userService.save(user); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "删除") - @PostMapping("delete/{id}") - public Result delete(@PathVariable("id") Long id){ - userService.removeById(id); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "更新") - @PostMapping("update") - public Result update(@RequestBody User user){ - //密码不更新 - user.setPassword(null); - userService.updateById(user); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "查询分页数据") - @ApiImplicitParams({ - @ApiImplicitParam(name = "currentPage", value = "页码"), - @ApiImplicitParam(name = "pageCount", value = "每页条数") - }) - @GetMapping("listByPage") - public Result findListByPage(@RequestParam(defaultValue = "1") Integer currentPage, - @RequestParam(defaultValue = "10") Integer pageCount){ - Page page = new Page(currentPage, pageCount); - IPage iPage = userService.page(page); - return ResultGenerator.genSuccessResult(iPage); - } - - @ApiOperation(value = "id查询") - @GetMapping("getById/{id}") - public Result findById(@PathVariable Long id){ - return ResultGenerator.genSuccessResult(userService.getById(id)); - } - -} diff --git a/java_project_template/jun_api_service_demo/src/main/resources/application-dev.yml b/java_project_template/jun_api_service_demo/src/main/resources/application-dev.yml deleted file mode 100644 index bc1c96e6c7..0000000000 --- a/java_project_template/jun_api_service_demo/src/main/resources/application-dev.yml +++ /dev/null @@ -1,31 +0,0 @@ -# 开发环境配置 -spring: - datasource: - dynamic: - primary: master #设置默认的数据源或者数据源组,默认值即为master - datasource: - master: - username: root - password: - driver-class-name: com.mysql.cj.jdbc.Driver - url: jdbc:mysql://localhost:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2b8 - slave_1: - username: root - password: 123456 - driver-class-name: com.mysql.cj.jdbc.Driver - url: jdbc:mysql://xx.xx.xx.xx:3307/dynamic?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2b8 - slave_2: - username: root - password: 123456 - driver-class-name: com.mysql.cj.jdbc.Driver - url: jdbc:mysql://xx.xx.xx.xx:3308/dynamic?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2b8 - #......省略 - #以上会配置一个默认库master,一个组slave下有两个子库slave_1,slave_2 -mybatis-plus: - configuration: - log-impl: org.apache.ibatis.logging.stdout.StdOutImpl - mapper-locations: classpath:mapper/*.xml - global-config: - db-config: - logic-delete-value: 1 - logic-not-delete-value: 0 diff --git a/java_project_template/jun_api_service_demo/src/main/resources/application-prod.yml b/java_project_template/jun_api_service_demo/src/main/resources/application-prod.yml deleted file mode 100644 index 50dcaed189..0000000000 --- a/java_project_template/jun_api_service_demo/src/main/resources/application-prod.yml +++ /dev/null @@ -1,3 +0,0 @@ -# 生产环境配置 -knife4j: - production: true #生成环境禁用查看接口文档 diff --git a/java_project_template/jun_api_service_demo/src/main/resources/application-test.yml b/java_project_template/jun_api_service_demo/src/main/resources/application-test.yml deleted file mode 100644 index 287da7b20e..0000000000 --- a/java_project_template/jun_api_service_demo/src/main/resources/application-test.yml +++ /dev/null @@ -1 +0,0 @@ -# 测试环境配置 diff --git a/java_project_template/jun_api_service_demo/src/main/resources/application.yml b/java_project_template/jun_api_service_demo/src/main/resources/application.yml deleted file mode 100644 index facce6d372..0000000000 --- a/java_project_template/jun_api_service_demo/src/main/resources/application.yml +++ /dev/null @@ -1,14 +0,0 @@ -spring: - profiles: - active: dev - mvc: - throw-exception-if-no-handler-found: true - resources: - add-mappings: false - application: - name: Springboot-api - jackson: - date-format: yyyy-MM-dd HH:mm:ss - time-zone: GMT+8 -server: - port: 8080 diff --git a/java_project_template/jun_api_service_demo/src/main/resources/banner.txt b/java_project_template/jun_api_service_demo/src/main/resources/banner.txt deleted file mode 100644 index 152e179398..0000000000 --- a/java_project_template/jun_api_service_demo/src/main/resources/banner.txt +++ /dev/null @@ -1,22 +0,0 @@ -//////////////////////////////////////////////////////////////////// -// _ooOoo_ // -// o8888888o // -// 88" . "88 // -// (| ^_^ |) // -// O\ = /O // -// ____/`---'\____ // -// .' \\| |// `. // -// / \\||| : |||// \ // -// / _||||| -:- |||||- \ // -// | | \\\ - /// | | // -// | \_| ''\---/'' | | // -// \ .-\__ `-` ___/-. / // -// ___`. .' /--.--\ `. . ___ // -// ."" '< `.___\_<|>_/___.' >'"". // -// | | : `- \`.;`\ _ /`;.`/ - ` : | | // -// \ \ `-. \_ __\ /__ _/ .-` / / // -// ========`-.____`-.___\_____/___.-`____.-'======== // -// `=---=' // -// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // -// 佛祖保佑 永不宕机 永无BUG // -//////////////////////////////////////////////////////////////////// \ No newline at end of file diff --git a/java_project_template/jun_api_service_demo/src/main/resources/mapper/UserMapper.xml b/java_project_template/jun_api_service_demo/src/main/resources/mapper/UserMapper.xml deleted file mode 100644 index 87ab7e4161..0000000000 --- a/java_project_template/jun_api_service_demo/src/main/resources/mapper/UserMapper.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - id, username, password, nick_name, sex, create_date, create_user, update_date, update_user, del_flag - - - \ No newline at end of file diff --git a/java_project_template/jun_api_service_demo/src/test/java/CodeGenerator.java b/java_project_template/jun_api_service_demo/src/test/java/CodeGenerator.java deleted file mode 100644 index 1c3b5f2dd8..0000000000 --- a/java_project_template/jun_api_service_demo/src/test/java/CodeGenerator.java +++ /dev/null @@ -1,113 +0,0 @@ -import com.baomidou.mybatisplus.core.toolkit.StringPool; -import com.baomidou.mybatisplus.generator.AutoGenerator; -import com.baomidou.mybatisplus.generator.InjectionConfig; -import com.baomidou.mybatisplus.generator.config.*; -import com.baomidou.mybatisplus.generator.config.po.TableInfo; -import com.baomidou.mybatisplus.generator.config.rules.DateType; -import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; -import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; - -import java.util.ArrayList; -import java.util.List; - -// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中 -public class CodeGenerator { - - - //多个表逗号分隔 - static String tableName = "user_copy"; - //逻辑删除字段名, 假如表没有逻辑删除字段,请忽视 - static String logicDeleteFieldName = "del_flag"; - - public static void main(String[] args) { - // 代码生成器 - AutoGenerator mpg = new AutoGenerator(); - - // 全局配置 - GlobalConfig gc = new GlobalConfig(); - String projectPath = System.getProperty("user.dir"); - gc.setOutputDir(projectPath + "/src/main/java"); - gc.setAuthor("aitangbao"); - gc.setOpen(false); - gc.setBaseColumnList(true); - gc.setBaseResultMap(true); - gc.setDateType(DateType.ONLY_DATE); - // gc.setSwagger2(true); 实体属性 Swagger2 注解 - mpg.setGlobalConfig(gc); - - // 数据源配置 - DataSourceConfig dsc = new DataSourceConfig(); - dsc.setUrl("jdbc:mysql://localhost:3306/project?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC"); - // dsc.setSchemaName("public"); - dsc.setDriverName("com.mysql.cj.jdbc.Driver"); - dsc.setUsername("root"); - dsc.setPassword("123456"); - mpg.setDataSource(dsc); - - // 包配置 - PackageConfig pc = new PackageConfig(); - pc.setParent("com.company.project"); - pc.setEntity("model"); - pc.setMapper("dao"); - pc.setController("web"); - mpg.setPackageInfo(pc); - - // 自定义配置 - InjectionConfig cfg = new InjectionConfig() { - @Override - public void initMap() { - // to do nothing - } - }; - - // 如果模板引擎是 freemarker - String templatePath = "/templates/mapper.xml.ftl"; - // 如果模板引擎是 velocity - // String templatePath = "/templates/mapper.xml.vm"; - - // 自定义输出配置 - List focList = new ArrayList<>(); - // 自定义配置会被优先输出 - focList.add(new FileOutConfig(templatePath) { - @Override - public String outputFile(TableInfo tableInfo) { - // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!! - return projectPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; - } - }); - cfg.setFileOutConfigList(focList); - mpg.setCfg(cfg); - - // 配置模板 - TemplateConfig templateConfig = new TemplateConfig(); - - // 配置自定义输出模板 - //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别 -// templateConfig.setEntity("templates/entity.java"); - // templateConfig.setService(); - templateConfig.setController("templates/controller.java"); - - templateConfig.setXml(null); - mpg.setTemplate(templateConfig); - - // 策略配置 - StrategyConfig strategy = new StrategyConfig(); - strategy.setNaming(NamingStrategy.underline_to_camel); - strategy.setColumnNaming(NamingStrategy.underline_to_camel); -// strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!"); - strategy.setEntityLombokModel(true); - strategy.setRestControllerStyle(true); - // 公共父类 -// strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!"); - // 写于父类中的公共字段 -// strategy.setSuperEntityColumns("id"); - strategy.setInclude(tableName.split(",")); - strategy.setControllerMappingHyphenStyle(true); - strategy.setLogicDeleteFieldName(logicDeleteFieldName); // 逻辑删除字段名称 - strategy.setTablePrefix(pc.getModuleName() + "_"); - mpg.setStrategy(strategy); - mpg.setTemplateEngine(new FreemarkerTemplateEngine()); - mpg.execute(); - } - -} \ No newline at end of file diff --git a/java_project_template/jun_api_service_demo/src/test/java/com/company/project/Tester.java b/java_project_template/jun_api_service_demo/src/test/java/com/company/project/Tester.java deleted file mode 100644 index f513bc219d..0000000000 --- a/java_project_template/jun_api_service_demo/src/test/java/com/company/project/Tester.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.company.project; - -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(classes = Application.class) -public class Tester { - - @Test - public void test() { - - } -} - - - diff --git a/java_project_template/jun_api_service_demo/src/test/resources/templates/controller.java.ftl b/java_project_template/jun_api_service_demo/src/test/resources/templates/controller.java.ftl deleted file mode 100644 index a62f181707..0000000000 --- a/java_project_template/jun_api_service_demo/src/test/resources/templates/controller.java.ftl +++ /dev/null @@ -1,94 +0,0 @@ -package ${package.Controller}; - -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.company.project.core.Result; -import com.company.project.core.ResultGenerator; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import org.springframework.web.bind.annotation.*; -import ${package.Service}.${table.serviceName}; -import ${package.Entity}.${entity}; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import lombok.extern.slf4j.Slf4j; -import com.baomidou.mybatisplus.core.metadata.IPage; - -import javax.annotation.Resource; -<#if restControllerStyle> -import org.springframework.web.bind.annotation.RestController; -<#else> -import org.springframework.stereotype.Controller; - -<#if superControllerClassPackage??> -import ${superControllerClassPackage}; - - -/** - *

- * ${table.comment!} 前端控制器 - *

- * - * @author ${author} - * @since ${date} - */ -<#if restControllerStyle> -@Api(tags = {"${table.comment!}"}) -@Slf4j -@RestController -<#else> -@Controller - -@RequestMapping("<#if package.ModuleName??>/${package.ModuleName}/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}") -<#if kotlin> -class ${table.controllerName}<#if superControllerClass??>:${superControllerClass}() -<#else> -<#if superControllerClass??>public class ${table.controllerName} extends ${superControllerClass}{ -<#else>public class ${table.controllerName} { - - - @Resource - private ${table.serviceName} ${(table.serviceName?substring(1))?uncap_first}; - - - @ApiOperation(value = "新增${table.comment!}") - @PostMapping("add") - public Result add(@RequestBody ${entity} ${entity?uncap_first}){ - ${(table.serviceName?substring(1))?uncap_first}.save(${entity?uncap_first}); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "删除${table.comment!}") - @PostMapping("delete/{id}") - public Result delete(@PathVariable("id") Long id){ - ${(table.serviceName?substring(1))?uncap_first}.removeById(id); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "更新${table.comment!}") - @PostMapping("update") - public Result update(@RequestBody ${entity} ${entity?uncap_first}){ - ${(table.serviceName?substring(1))?uncap_first}.updateById(${entity?uncap_first}); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "查询${table.comment!}分页数据") - @ApiImplicitParams({ - @ApiImplicitParam(name = "currentPage", value = "页码"), - @ApiImplicitParam(name = "pageCount", value = "每页条数") - }) - @GetMapping("listByPage") - public Result findListByPage(@RequestParam Integer currentPage, - @RequestParam Integer pageCount){ - Page page = new Page(currentPage, pageCount); - IPage<${entity}> iPage = ${(table.serviceName?substring(1))?uncap_first}.page(page); - return ResultGenerator.genSuccessResult(iPage); - } - - @ApiOperation(value = "id查询${table.comment!}") - @GetMapping("getById/{id}") - public Result findById(@PathVariable Long id){ - return ResultGenerator.genSuccessResult(${(table.serviceName?substring(1))?uncap_first}.getById(id)); - } - -} - \ No newline at end of file diff --git a/java_project_template/jun_api_service_demo/src/test/resources/user.sql b/java_project_template/jun_api_service_demo/src/test/resources/user.sql deleted file mode 100644 index 51bd7db81e..0000000000 --- a/java_project_template/jun_api_service_demo/src/test/resources/user.sql +++ /dev/null @@ -1,52 +0,0 @@ -/* - Navicat Premium Data Transfer - - Source Server : localhost - Source Server Type : MySQL - Source Server Version : 50529 - Source Host : localhost:3306 - Source Schema : project - - Target Server Type : MySQL - Target Server Version : 50529 - File Encoding : 65001 - - Date: 08/01/2020 15:53:02 -*/ - -SET NAMES utf8mb4; -SET FOREIGN_KEY_CHECKS = 0; - --- ---------------------------- --- Table structure for user --- ---------------------------- -DROP TABLE IF EXISTS `user`; -CREATE TABLE `user` ( - `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键', - `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名', - `password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码', - `nick_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '昵称', - `sex` int(1) NULL DEFAULT NULL COMMENT '性别', - `create_date` datetime NULL DEFAULT NULL COMMENT '创建时间', - `create_user` int(11) NULL DEFAULT NULL COMMENT '创建人', - `update_date` datetime NULL DEFAULT NULL COMMENT '修改时间', - `update_user` int(11) NULL DEFAULT NULL COMMENT '修改人', - `del_flag` int(1) NULL DEFAULT 0 COMMENT '删除标志0未删 1删除', - PRIMARY KEY (`id`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 11 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact; - --- ---------------------------- --- Records of user --- ---------------------------- -INSERT INTO `user` VALUES (1, 'admin', '9dc818b4bca3baa7d230fbf96c919638', '土豆', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (2, '2@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-2', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (3, '3@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-3', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (4, '4@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-4', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (5, '5@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-5', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (6, '6@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-6', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (7, '7@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-7', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (8, '8@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-8', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (9, '9@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-9', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (10, '10@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-10', 1, NULL, NULL, NULL, NULL, 0); - -SET FOREIGN_KEY_CHECKS = 1; diff --git a/java_project_template/jun_api_service_main/doc/user.sql b/java_project_template/jun_api_service_main/doc/user.sql deleted file mode 100644 index 5503994482..0000000000 --- a/java_project_template/jun_api_service_main/doc/user.sql +++ /dev/null @@ -1,36 +0,0 @@ -SET NAMES utf8mb4; -SET FOREIGN_KEY_CHECKS = 0; - --- ---------------------------- --- Table structure for user --- ---------------------------- -DROP TABLE IF EXISTS `sys_user`; -CREATE TABLE `sys_user` ( - `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键', - `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名', - `password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码', - `nick_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '昵称', - `sex` int(1) NULL DEFAULT NULL COMMENT '性别', - `create_date` datetime NULL DEFAULT NULL COMMENT '创建时间', - `create_user` int(11) NULL DEFAULT NULL COMMENT '创建人', - `update_date` datetime NULL DEFAULT NULL COMMENT '修改时间', - `update_user` int(11) NULL DEFAULT NULL COMMENT '修改人', - `del_flag` int(1) NULL DEFAULT 0 COMMENT '删除标志0未删 1删除', - PRIMARY KEY (`id`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 11 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact; - --- ---------------------------- --- Records of user --- ---------------------------- -INSERT INTO `sys_user` VALUES (1, 'admin', '9dc818b4bca3baa7d230fbf96c919638', '用户', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `sys_user` VALUES (2, '2@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '用户-2', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `sys_user` VALUES (3, '3@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '用户-3', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `sys_user` VALUES (4, '4@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '用户-4', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `sys_user` VALUES (5, '5@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '用户-5', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `sys_user` VALUES (6, '6@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '用户-6', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `sys_user` VALUES (7, '7@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '用户-7', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `sys_user` VALUES (8, '8@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '用户-8', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `sys_user` VALUES (9, '9@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '用户-9', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `sys_user` VALUES (10, '10@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '用户-10', 1, NULL, NULL, NULL, NULL, 0); - -SET FOREIGN_KEY_CHECKS = 1; diff --git a/java_project_template/jun_api_service_main/pom.xml b/java_project_template/jun_api_service_main/pom.xml deleted file mode 100644 index 3a405fe579..0000000000 --- a/java_project_template/jun_api_service_main/pom.xml +++ /dev/null @@ -1,155 +0,0 @@ - - - 4.0.0 - - com.jun.plugin - jun_api_service_main - 1.0 - jar - - - 1.8 - 3.3.0 - - - - - org.springframework.boot - spring-boot-starter-parent - 2.5.14 - - - - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-jdbc - - - - org.springframework.boot - spring-boot-starter-data-redis - - - org.springframework.boot - spring-boot-starter-test - test - - - - - com.baomidou - mybatis-plus - ${mybatis-plus.version} - - - com.baomidou - mybatis-plus-boot-starter - ${mybatis-plus.version} - - - com.baomidou - mybatis-plus-generator - ${mybatis-plus.version} - - - org.projectlombok - lombok - 1.18.26 - provided - - - - - - commons-codec - commons-codec - - - org.apache.commons - commons-lang3 - 3.6 - - - - mysql - mysql-connector-java - runtime - - - - - com.alibaba - fastjson - 1.2.47 - - - - com.alibaba - druid-spring-boot-starter - 1.1.10 - - - - org.freemarker - freemarker - 2.3.30 - test - - - - com.github.xiaoymin - knife4j-spring-boot-starter - 2.0.2 - - - cn.hutool - hutool-all - 5.8.18 - compile - - - junit - junit - test - - - javax.validation - validation-api - - - - - - - aliyun-repos - http://maven.aliyun.com/nexus/content/groups/public/ - - false - - - - - - - aliyun-plugin - http://maven.aliyun.com/nexus/content/groups/public/ - - false - - - - - \ No newline at end of file diff --git a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/ApiServiceApplication.java b/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/ApiServiceApplication.java deleted file mode 100644 index c41f85cc60..0000000000 --- a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/ApiServiceApplication.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.jun.plugin.system; - -import java.net.InetAddress; -import java.net.UnknownHostException; - -import org.mybatis.spring.annotation.MapperScan; -import org.springframework.boot.CommandLineRunner; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.web.servlet.ServletComponentScan; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.core.env.Environment; - -import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure; - -import cn.hutool.core.lang.Console; -import cn.hutool.extra.spring.SpringUtil; -import lombok.extern.slf4j.Slf4j; -import org.springframework.scheduling.annotation.EnableScheduling; - -@Slf4j -@EnableScheduling -@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class) // 多数据源 (exclude = DruidDataSourceAutoConfigure.class) -@MapperScan({"com.jun.plugin.**.mapper","com.bjc.lcp.**.mapper"}) -@ComponentScan(basePackages = {"com.bjc.lcp","com.jun.plugin"}) -@ServletComponentScan(basePackages = {"com.jun.plugin.**.filter"}) -public class ApiServiceApplication { - - public static void main(String[] args) throws UnknownHostException { - SpringApplication app = new SpringApplication(ApiServiceApplication.class); - Environment env = app.run(args).getEnvironment(); - log.info("\n----------------------------------------------------------\n\t" + - "Application '{}' is running! Access URLs:\n\t" + - "Local: \t\thttp://localhost:{}\n\t" + - "External: \thttp://{}:{}\n\t" + - "Knife4j: \thttp://localhost:{}/doc.html\n" + - "SwaggerUI: \thttp://localhost:{}/swagger-ui.html\n" + - "----------------------------------------------------------", - env.getProperty("spring.application.name"), - env.getProperty("server.port"), - InetAddress.getLocalHost().getHostAddress(), - env.getProperty("server.port"), - env.getProperty("server.port"), - env.getProperty("server.port")); - Console.log(env.getProperty("server.port")); - log.info("profiles = " + SpringUtil.getProperty("spring.profiles.active")); - log.info("url = " + SpringUtil.getProperty("spring.datasource.url")); - log.info("context = " + SpringUtil.getProperty("spring.groovy-api.context")); - //SpringApplication.run(GroovyDemoApplication.class, args); - } - - @Bean - public CommandLineRunner commandLineRunner(ApplicationContext ctx) { - return args -> { - System.out.println("Let's inspect the beans provided by Spring Boot:"); - String[] beanNames = ctx.getBeanDefinitionNames(); - System.err.println("beanNames size = "+ beanNames.length); - for (String beanName : beanNames) { - //System.err.println(beanName); - /* - * Object bean = ctx.getBean(beanName); System.out.println(bean); - * System.out.println(); - */ - } - - }; - } - - - - -} diff --git a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/configurer/LoginInterceptor.java b/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/configurer/LoginInterceptor.java deleted file mode 100644 index bc938a0f60..0000000000 --- a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/configurer/LoginInterceptor.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.jun.plugin.system.configurer; - - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.jun.plugin.system.core.Result; -import com.jun.plugin.system.core.ResultCode; -import com.jun.plugin.system.service.HttpSessionService; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import java.io.IOException; - -/** - * @author wenbin - * @since 2019/10/30 15:29 - *

登陆拦截器 - */ -public class LoginInterceptor extends HandlerInterceptorAdapter { - - @Autowired - private HttpSessionService httpSession; - - private final Logger logger = LoggerFactory.getLogger(WebMvcConfigurer.class); - - @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - //用户当前session信息 - JSONObject currentSession; - //拦截接口 - //从header中获取token - String token = request.getHeader("token"); - //如果header中不存在token,则从参数中获取token - if (StringUtils.isBlank(token)) { - token = request.getParameter("token"); - } - //token为空返回 - if (StringUtils.isBlank(token)) { - Result result = new Result(); - result.setCode(ResultCode.UNAUTHORIZED).setMessage("token不能为空").setSuccess(false); - responseResult(response, result); - return false; - }// 校验并解析token,如果token过期或者篡改,则会返回null - currentSession = httpSession.getCurrentSession(); - if (null != currentSession) { - return true; - } else { - Result result = new Result(); - result.setCode(ResultCode.UNAUTHORIZED).setMessage("用户未登陆!").setSuccess(false); - responseResult(response, result); - return false; - } - } - - - private void responseResult(HttpServletResponse response, Result result) { - response.setCharacterEncoding("UTF-8"); - response.setHeader("Content-type", "application/json;charset=UTF-8"); - try { - response.getWriter().write(JSON.toJSONString(result)); - } catch (IOException ex) { - logger.error(ex.getMessage()); - } - } -} diff --git a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/configurer/WebMvcConfigurer.java b/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/configurer/WebMvcConfigurer.java deleted file mode 100644 index 0f2c8847f6..0000000000 --- a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/configurer/WebMvcConfigurer.java +++ /dev/null @@ -1,166 +0,0 @@ -package com.jun.plugin.system.configurer; - -import java.io.IOException; -import java.nio.charset.Charset; -import java.util.Arrays; -import java.util.List; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.serializer.SerializerFeature; -import com.alibaba.fastjson.support.config.FastJsonConfig; -import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; - -import com.jun.plugin.system.core.Result; -import com.jun.plugin.system.core.ResultCode; -import com.jun.plugin.system.core.ResultGenerator; -import com.jun.plugin.system.core.ServiceException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.MediaType; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.web.bind.MethodArgumentNotValidException; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.method.HandlerMethod; -import org.springframework.web.servlet.HandlerExceptionResolver; -import org.springframework.web.servlet.ModelAndView; -import org.springframework.web.servlet.NoHandlerFoundException; -import org.springframework.web.servlet.config.annotation.*; - -/** - * Spring MVC 配置 - */ -@Configuration -public class WebMvcConfigurer extends WebMvcConfigurerAdapter { - - private final Logger logger = LoggerFactory.getLogger(WebMvcConfigurer.class); - - @Bean - LoginInterceptor loginInterceptor() { - - return new LoginInterceptor(); - } - - - //使用阿里 FastJson 作为JSON MessageConverter - @Override - public void configureMessageConverters(List> converters) { - FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); - FastJsonConfig config = new FastJsonConfig(); - config.setSerializerFeatures(SerializerFeature.WriteMapNullValue);//保留空的字段 - //SerializerFeature.WriteNullStringAsEmpty,//String null -> "" - //SerializerFeature.WriteNullNumberAsZero//Number null -> 0 - // 按需配置,更多参考FastJson文档哈 - - converter.setFastJsonConfig(config); - converter.setDefaultCharset(Charset.forName("UTF-8")); - converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON_UTF8)); - converters.add(converter); - } - - - //统一异常处理 - @Override - public void configureHandlerExceptionResolvers(List exceptionResolvers) { - exceptionResolvers.add(new HandlerExceptionResolver() { - public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) { - Result result = new Result(); - if (e instanceof ServiceException) {//业务失败的异常,如“账号或密码错误” - result.setCode(ResultCode.FAIL).setMessage(e.getMessage()).setSuccess(false); - } else if (e instanceof MethodArgumentNotValidException) {//@valid注解验证参数 - MethodArgumentNotValidException m = (MethodArgumentNotValidException) e; - m.getBindingResult().getFieldError().getDefaultMessage(); - result.setCode(ResultCode.PARAM_FAIL).setMessage(m.getBindingResult().getFieldError().getDefaultMessage()).setSuccess(false); - } else if (e instanceof NoHandlerFoundException) { - result.setCode(ResultCode.NOT_FOUND).setMessage("接口 [" + request.getRequestURI() + "] 不存在").setSuccess(false); - } else if (e instanceof ServletException) { - result.setCode(ResultCode.FAIL).setMessage(e.getMessage()).setSuccess(false); - } else { - result.setCode(ResultCode.INTERNAL_SERVER_ERROR).setMessage("接口 [" + request.getRequestURI() + "] 内部错误,请联系管理员").setSuccess(false); - String message; - if (handler instanceof HandlerMethod) { - HandlerMethod handlerMethod = (HandlerMethod) handler; - message = String.format("接口 [%s] 出现异常,方法:%s.%s,异常摘要:%s", - request.getRequestURI(), - handlerMethod.getBean().getClass().getName(), - handlerMethod.getMethod().getName(), - e.getMessage()); - } else { - message = e.getMessage(); - } - logger.error(message, e); - } - responseResult(response, result); - return new ModelAndView(); - } - - }); - } - - @ExceptionHandler(MethodArgumentNotValidException.class) - public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { - return ResultGenerator.genFailResult(e.getBindingResult().getFieldError().getDefaultMessage()); - } - - /** - * 页面跨域访问Controller过滤 - * - * @return - */ - @Override - public void addCorsMappings(CorsRegistry registry) { - WebMvcConfigurer.super.addCorsMappings(registry); - registry.addMapping("/**") - .allowedHeaders("*") - .allowedMethods("POST", "GET") - .allowedOrigins("*"); - } - - //添加拦截器 - @Override - public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(loginInterceptor()) - .excludePathPatterns("/doc.html") - .excludePathPatterns("/swagger-resources/**") - .excludePathPatterns("/error") - .excludePathPatterns("/webjars/**") - .excludePathPatterns("/api/user/login") - .excludePathPatterns("/api/user/register") - .addPathPatterns("/**"); - } - - - private void responseResult(HttpServletResponse response, Result result) { - response.setCharacterEncoding("UTF-8"); - response.setHeader("Content-type", "application/json;charset=UTF-8"); - try { - response.getWriter().write(JSON.toJSONString(result)); - } catch (IOException ex) { - logger.error(ex.getMessage()); - } - } - - /** - * 发现如果继承了WebMvcConfigurationSupport,则在yml中配置的相关内容会失效。 需要重新指定静态资源 - * - * @param registry - */ - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("/**").addResourceLocations( - "classpath:/static/"); - registry.addResourceHandler("doc.html").addResourceLocations( - "classpath:/META-INF/resources/"); - registry.addResourceHandler("/webjars/**").addResourceLocations( - "classpath:/META-INF/resources/webjars/"); - super.addResourceHandlers(registry); - } - - -} - diff --git a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/core/Result.java b/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/core/Result.java deleted file mode 100644 index 9226990ccb..0000000000 --- a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/core/Result.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.jun.plugin.system.core; - -import com.alibaba.fastjson.JSON; - -/** - * 统一API响应结果封装 - */ -public class Result { - private int code; - private String message; - private T data; - private Boolean success; - - public Result setCode(ResultCode resultCode) { - this.code = resultCode.code(); - return this; - } - - public int getCode() { - return code; - } - - public String getMessage() { - return message; - } - - public Result setMessage(String message) { - this.message = message; - return this; - } - - public T getData() { - return data; - } - - public Result setData(T data) { - this.data = data; - return this; - } - - public Boolean getSuccess() { - return success; - } - - public Result setSuccess(Boolean success) { - this.success = success; - return this; - } - - @Override - public String toString() { - return JSON.toJSONString(this); - } -} diff --git a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/core/ResultCode.java b/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/core/ResultCode.java deleted file mode 100644 index ad96be137d..0000000000 --- a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/core/ResultCode.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.jun.plugin.system.core; - -/** - * 响应码枚举,参考HTTP状态码的语义 - */ -public enum ResultCode { - SUCCESS(200),//成功 - FAIL(400),//失败 - UNAUTHORIZED(401),//未认证(签名错误) - NOT_FOUND(404),//接口不存在 - INTERNAL_SERVER_ERROR(500),//服务器内部错误 - PARAM_FAIL(10001);//参数异常 - - private final int code; - - ResultCode(int code) { - this.code = code; - } - - public int code() { - return code; - } -} diff --git a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/core/ResultGenerator.java b/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/core/ResultGenerator.java deleted file mode 100644 index 15a347e0d6..0000000000 --- a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/core/ResultGenerator.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.jun.plugin.system.core; - -/** - * 响应结果生成工具 - */ -public class ResultGenerator { - private static final String DEFAULT_SUCCESS_MESSAGE = "SUCCESS"; - - public static Result genSuccessResult() { - return new Result() - .setSuccess(true) - .setCode(ResultCode.SUCCESS) - .setMessage(DEFAULT_SUCCESS_MESSAGE); - } - - public static Result genSuccessResult(T data) { - return new Result() - .setSuccess(true) - .setCode(ResultCode.SUCCESS) - .setMessage(DEFAULT_SUCCESS_MESSAGE) - .setData(data); - } - - public static Result genFailResult(String message) { - return new Result() - .setSuccess(false) - .setCode(ResultCode.FAIL) - .setMessage(message); - } -} diff --git a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/core/ServiceException.java b/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/core/ServiceException.java deleted file mode 100644 index 47352a26f7..0000000000 --- a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/core/ServiceException.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.jun.plugin.system.core; - -/** - * 服务(业务)异常如“ 账号或密码错误 ”,该异常只做INFO级别的日志记录 @see WebMvcConfigurer - */ -public class ServiceException extends RuntimeException { - public ServiceException() { - } - - public ServiceException(String message) { - super(message); - } - - public ServiceException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/mapper/UserMapper.java b/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/mapper/UserMapper.java deleted file mode 100644 index 15d4a4e183..0000000000 --- a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/mapper/UserMapper.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.jun.plugin.system.mapper; - -import com.jun.plugin.system.model.User; -import com.baomidou.mybatisplus.core.mapper.BaseMapper; - -/** - *

- * Mapper 接口 - *

- * - * @author project - * @since 2020-01-08 - */ -public interface UserMapper extends BaseMapper { - -} diff --git a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/model/User.java b/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/model/User.java deleted file mode 100644 index 19dfc1f8e9..0000000000 --- a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/model/User.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.jun.plugin.system.model; - -import com.baomidou.mybatisplus.annotation.*; - -import java.io.Serializable; -import java.util.Date; - -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.experimental.Accessors; - -import javax.validation.constraints.NotEmpty; - -/** - *

- * - *

- * - * @author project - * @since 2020-01-08 - */ -@Data -@EqualsAndHashCode(callSuper = false) -@Accessors(chain = true) -@TableName("user") -public class User implements Serializable { - - private static final long serialVersionUID = 1L; - - /** - * 主键 - */ - @TableId(value = "id", type = IdType.AUTO) - private Integer id; - - /** - * 用户名 - */ - @NotEmpty(message = "用户名不能为空!") - private String username; - - /** - * 密码 - */ - @NotEmpty(message = "密码不能为空!") - private String password; - - /** - * 昵称 - */ - private String nickName; - - /** - * 性别 - */ - private Integer sex; - - /** - * 创建时间 - */ - private Date createDate; - - /** - * 创建人 - */ - private Integer createUser; - - /** - * 修改时间 - */ - private Date updateDate; - - /** - * 修改人 - */ - private Integer updateUser; - - /** - * 删除标志0未删 1删除 - */ - @TableLogic - private Integer delFlag; - - /** - * 登陆返回token - */ - @TableField(exist = false) - private String token; - -} diff --git a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/service/HttpSessionService.java b/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/service/HttpSessionService.java deleted file mode 100644 index c2d0bd3afc..0000000000 --- a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/service/HttpSessionService.java +++ /dev/null @@ -1,148 +0,0 @@ -package com.jun.plugin.system.service; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.jun.plugin.system.model.User; -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; - -import javax.servlet.http.HttpServletRequest; -import java.util.Random; - -/** - * session管理器 - * - * @author aitangbao - */ -@Service -public class HttpSessionService { - - @Autowired - private RedisService redisDB; - - @Autowired - private HttpServletRequest request; - - @Value("${spring.redis.key.prefix.userToken}") - private String USER_TOKEN_PREFIX; - - @Value("${spring.redis.key.expire.userToken}") - private int EXPIRE ; - - public String createTokenAndUser(User user) { - //方便根据id找到redis的key, 修改密码/退出登陆 方便使用 - String token = getRandomToken(32) + "#" + user.getId(); - JSONObject sessionInfo = new JSONObject(); - sessionInfo.put("userId", user.getId()); - sessionInfo.put("username", user.getUsername()); - String key = USER_TOKEN_PREFIX + token; - //设置该用户已登录的token - redisDB.setAndExpire(key, sessionInfo.toJSONString(), EXPIRE); - return token; - } - - /** - * 根据token获取userid - * - * @param token - * @return - */ - public static String getUserIdByToken(String token) { - if (StringUtils.isBlank(token) || !token.contains("#")) { - return ""; - } else { - return token.substring(token.indexOf("#") + 1); - } - } - - /** - * 获取参数中的token - * - * @return - */ - public String getTokenFromHeader() { - String token = request.getHeader("token"); - //如果header中不存在token,则从参数中获取token - if (StringUtils.isBlank(token)) { - token = request.getParameter("token"); - } - return token; - } - - /** - * 获取当前session信息 - * - * @return - */ - public JSONObject getCurrentSession() { - String token = getTokenFromHeader(); - if (null != token) { - if (redisDB.exists(USER_TOKEN_PREFIX + token)) { - String sessionInfoStr = redisDB.get(USER_TOKEN_PREFIX + token); - JSONObject sessionInfo = JSON.parseObject(sessionInfoStr); - return sessionInfo; - } else { - return null; - } - } else { - return null; - } - } - - - /** - * 使当前用户的token失效 - */ - public void abortUserByToken() { - String token = getTokenFromHeader(); - redisDB.del(USER_TOKEN_PREFIX + token); - } - - /** - * 使所有用户的token失效 - */ - public void abortAllUserByToken() { - String token = getTokenFromHeader(); - String userId = getUserIdByToken(token); - redisDB.delKeys(USER_TOKEN_PREFIX+"*#" + userId); - } - - /** - * 使用户的token失效 - */ - public void abortUserByUserId(Integer userId) { - redisDB.delKeys(USER_TOKEN_PREFIX+"*#" + userId); - } - - - /** - * 生成随机的token - * - * @param length - * @return - */ - private String getRandomToken(int length) { - Random random = new Random(); - StringBuilder randomStr = new StringBuilder(); - - // 根据length生成相应长度的随机字符串 - for (int i = 0; i < length; i++) { - String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; - - //输出字母还是数字 - if ("char".equalsIgnoreCase(charOrNum)) { - //输出是大写字母还是小写字母 - int temp = random.nextInt(2) % 2 == 0 ? 65 : 97; - randomStr.append((char) (random.nextInt(26) + temp)); - } else if ("num".equalsIgnoreCase(charOrNum)) { - randomStr.append(String.valueOf(random.nextInt(10))); - } - } - - return randomStr.toString(); - } - - -} diff --git a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/service/IUserService.java b/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/service/IUserService.java deleted file mode 100644 index abc230a605..0000000000 --- a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/service/IUserService.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.jun.plugin.system.service; - -import com.jun.plugin.system.core.Result; -import com.jun.plugin.system.model.User; -import com.baomidou.mybatisplus.extension.service.IService; - -/** - *

- * 服务类 - *

- * - * @author project - * @since 2020-01-08 - */ -public interface IUserService extends IService { - - Result checkPassword(User userParam); -} diff --git a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/service/RedisService.java b/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/service/RedisService.java deleted file mode 100644 index 4af29950af..0000000000 --- a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/service/RedisService.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.jun.plugin.system.service; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.stereotype.Service; -import org.springframework.util.CollectionUtils; - -import java.util.Date; -import java.util.Set; -import java.util.concurrent.TimeUnit; - - -/** - * @author : aitangbao - */ - -@Service -public class RedisService { - @Autowired - private StringRedisTemplate redisTemplate; - - public boolean exists(String key) { - return this.redisTemplate.hasKey(key); - } - - public String get(String key) { - String value = this.redisTemplate.opsForValue().get(key); - return value; - } - - - public void del(String key) { - if (this.exists(key)) { - this.redisTemplate.delete(key); - } - - } - - public void setAndExpire(String key, String value, int seconds) { - this.redisTemplate.opsForValue().set(key, value); - this.redisTemplate.expire(key, (long) seconds, TimeUnit.SECONDS); - } - - - public void setExpire(String key, Date endTime) { - long seconds = endTime.getTime() - (new Date()).getTime(); - this.redisTemplate.expire(key, (long) ((int) (seconds / 1000L)), TimeUnit.SECONDS); - } - - - public Set keys(String pattern) { - return redisTemplate.keys("*" + pattern); - } - - public void delKeys(String pattern) { - Set keys = redisTemplate.keys(pattern); - if (!CollectionUtils.isEmpty(keys)) { - this.redisTemplate.delete(keys); - } - } -} diff --git a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/service/impl/UserServiceImpl.java b/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/service/impl/UserServiceImpl.java deleted file mode 100644 index aef225cda7..0000000000 --- a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/service/impl/UserServiceImpl.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.jun.plugin.system.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.jun.plugin.system.core.Result; -import com.jun.plugin.system.core.ResultGenerator; -import com.jun.plugin.system.model.User; -import com.jun.plugin.system.mapper.UserMapper; -import com.jun.plugin.system.service.IUserService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.jun.plugin.system.service.RedisService; -import com.jun.plugin.system.utils.MD5Utils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; - -/** - *

- * 服务实现类 - *

- * - * @author project - * @since 2020-01-08 - */ -@Service -public class UserServiceImpl extends ServiceImpl implements IUserService { - - @Autowired - private UserMapper userMapper; - - - @Autowired - private RedisService redis; - @Value("${spring.redis.key.prefix.passwordError}") - private String PASSWORD_ERROR_PREFIX; - @Value("${spring.redis.key.expire.passwordError}") - private int PASSWORD_ERROR_EXPIRE; - - @Override - public Result checkPassword(User userParam) { - - String username = userParam.getUsername(); - String password = userParam.getPassword(); - //redis key - String redisPasswordErrorKey = PASSWORD_ERROR_PREFIX + username; - //判断账户是否锁定 - String errorCount = redis.get(redisPasswordErrorKey); - if (errorCount != null && Integer.parseInt(errorCount) == 5) { - return ResultGenerator.genFailResult("密码连续错误5次,请1小时后重试"); - } - //根据用户名获取用户信息 - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.eq("username", username); - User user = userMapper.selectOne(queryWrapper); - if (user == null) { - return ResultGenerator.genFailResult("账号未找到"); - } - - if (!MD5Utils.Encrypt(password, true).equals(user.getPassword())) { - if (errorCount == null) { - errorCount = "1"; - } else { - errorCount = String.valueOf(Integer.parseInt(errorCount) + 1); - } - redis.setAndExpire(redisPasswordErrorKey, errorCount, PASSWORD_ERROR_EXPIRE); - if ("5".equals(errorCount)) { - return ResultGenerator.genFailResult("密码连续错误5次,请1小时后重试"); - } else { - return ResultGenerator.genFailResult("密码错误,剩余次数" + (5 - Integer.parseInt(errorCount))); - } - } else { - //登录成功删除错误登录次数 - redis.del(redisPasswordErrorKey); - return ResultGenerator.genSuccessResult(user); - } - } -} diff --git a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/utils/ImageCodeUtil.java b/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/utils/ImageCodeUtil.java deleted file mode 100644 index 44b4615a9e..0000000000 --- a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/utils/ImageCodeUtil.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.jun.plugin.system.utils; - -import lombok.extern.slf4j.Slf4j; - -import javax.imageio.ImageIO; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import java.awt.*; -import java.awt.image.BufferedImage; -import java.util.Random; - -@Slf4j -public class ImageCodeUtil { - - - public static final String IMAGE_RANDOM_CODEKEY = "RANDOMVALIDATECODEKEY";//放到session中的key - private String randString = "0123456789";//随机产生只有数字的字符串 private String - //private String randString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生只有字母的字符串 - //private String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生数字与字母组合的字符串 - private int width = 95;// 图片宽 - private int height = 25;// 图片高 - private int lineSize = 40;// 干扰线数量 - private int stringNum = 4;// 随机产生字符数量 - - - private Random random = new Random(); - - /** - * 获得字体 - */ - private Font getFont() { - return new Font("Fixedsys", Font.CENTER_BASELINE, 18); - } - - /** - * 获得颜色 - */ - private Color getRandColor(int fc, int bc) { - if (fc > 255) - fc = 255; - if (bc > 255) - bc = 255; - int r = fc + random.nextInt(bc - fc - 16); - int g = fc + random.nextInt(bc - fc - 14); - int b = fc + random.nextInt(bc - fc - 18); - return new Color(r, g, b); - } - - /** - * 生成随机图片 - */ - public void getRandcode(HttpServletRequest request, HttpServletResponse response) { - HttpSession session = request.getSession(); - // BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类 - BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); - Graphics g = image.getGraphics();// 产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作 - g.fillRect(0, 0, width, height);//图片大小 - g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));//字体大小 - g.setColor(getRandColor(110, 133));//字体颜色 - // 绘制干扰线 - for (int i = 0; i <= lineSize; i++) { - drowLine(g); - } - // 绘制随机字符 - String randomString = ""; - for (int i = 1; i <= stringNum; i++) { - randomString = drowString(g, randomString, i); - } - log.info(randomString); - //将生成的随机字符串保存到session中 - session.removeAttribute(IMAGE_RANDOM_CODEKEY); - session.setAttribute(IMAGE_RANDOM_CODEKEY, randomString); - g.dispose(); - try { - // 将内存中的图片通过流动形式输出到客户端 - ImageIO.write(image, "JPEG", response.getOutputStream()); - } catch (Exception e) { - log.error("将内存中的图片通过流动形式输出到客户端失败>>>> ", e); - } - - } - - /** - * 绘制字符串 - */ - private String drowString(Graphics g, String randomString, int i) { - g.setFont(getFont()); - g.setColor(new Color(random.nextInt(101), random.nextInt(111), random - .nextInt(121))); - String rand = String.valueOf(getRandomString(random.nextInt(randString - .length()))); - randomString += rand; - g.translate(random.nextInt(3), random.nextInt(3)); - g.drawString(rand, 13 * i, 16); - return randomString; - } - - /** - * 绘制干扰线 - */ - private void drowLine(Graphics g) { - int x = random.nextInt(width); - int y = random.nextInt(height); - int xl = random.nextInt(13); - int yl = random.nextInt(15); - g.drawLine(x, y, x + xl, y + yl); - } - - /** - * 获取随机的字符 - */ - public String getRandomString(int num) { - return String.valueOf(randString.charAt(num)); - } -} \ No newline at end of file diff --git a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/utils/MD5Utils.java b/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/utils/MD5Utils.java deleted file mode 100644 index 5d25618ede..0000000000 --- a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/utils/MD5Utils.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.jun.plugin.system.utils; - -import org.apache.commons.codec.digest.DigestUtils; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.StringUtils; - -public class MD5Utils { - - private static String salt = "springboot_api"; - - /** - * 加密字符串 - * @param password 要加密的明文 - * @param isAddSalt 是否加默认盐 - * @return 加密之后的结果 - */ - public static String Encrypt(String password, boolean isAddSalt){ - if (StringUtils.isNotEmpty(password)){ - if (isAddSalt){ - return DigestUtils.md5Hex(DigestUtils.md5(password + salt)); - } else { - return DigestUtils.md5Hex(DigestUtils.md5(password)); - } - } - return null; - } - - /** - * - * @param bytes - * @return - */ - public static String Encrypt(byte[] bytes){ - if (ArrayUtils.isNotEmpty(bytes)){ - return DigestUtils.md5Hex(DigestUtils.md5(bytes)); - } - return null; - } - - /** - * MD5加盐加密 - * @param password 要加密的明文 - * @param salt 盐 - * @return 加密之后的结果 - */ - public static String Encrypt(String password, String salt){ - if (StringUtils.isNotEmpty(password)){ - return DigestUtils.md5Hex(DigestUtils.md5(password + salt)); - } - return null; - } - - public static void main(String[] args){ - System.out.println(MD5Utils.Encrypt("admin", true)); - } -} diff --git a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/web/UserController.java b/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/web/UserController.java deleted file mode 100644 index c4c6bf4d3d..0000000000 --- a/java_project_template/jun_api_service_main/src/main/java/com/jun/plugin/system/web/UserController.java +++ /dev/null @@ -1,202 +0,0 @@ -package com.jun.plugin.system.web; - -import com.alibaba.fastjson.JSONObject; -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.jun.plugin.system.core.Result; -import com.jun.plugin.system.core.ResultGenerator; -import com.jun.plugin.system.service.HttpSessionService; -import com.jun.plugin.system.utils.MD5Utils; -import com.jun.plugin.system.utils.ImageCodeUtil; -import com.jun.plugin.system.service.IUserService; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.web.bind.annotation.*; -import com.jun.plugin.system.model.User; -import io.swagger.annotations.ApiOperation; -import lombok.extern.slf4j.Slf4j; -import com.baomidou.mybatisplus.core.metadata.IPage; - -import javax.annotation.Resource; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import javax.validation.Valid; - -import org.springframework.web.bind.annotation.RestController; - -import java.util.HashMap; -import java.util.Map; - -/** - *

- * 前端控制器 - *

- * - * @author project - * @since 2020-01-08 - */ -@Slf4j -@RestController -@RequestMapping("/api/user") -public class UserController { - - @Resource - private IUserService userService; - @Autowired - private HttpSessionService httpSession; - - @Value("${spring.redis.allowMultipleLogin}") - private Boolean allowMultipleLogin; - - @ApiOperation("登陆") - @PostMapping("/login") - public Result login(@RequestBody @Valid User userParam) { - - //校验密码,5次错误锁定账户 - Result result = userService.checkPassword(userParam); - if (!result.getSuccess()) { - return result; - } - //成功之后返回user - User user = (User)result.getData(); - - //是否删除之前token, 此处控制是否支持多登陆端; - // true:允许多处登陆; false:只能单处登陆,顶掉之前登陆 - if (!allowMultipleLogin) { - httpSession.abortUserByUserId(user.getId()); - } - - //生成token - String token = httpSession.createTokenAndUser(user); - - Map resultMap = new HashMap<>(2); - resultMap.put("token", token); - resultMap.put("username", userParam.getUsername()); - return ResultGenerator.genSuccessResult(resultMap); - } - - @ApiOperation("注册") - @PostMapping("/register") - public Result register(@RequestBody @Valid User user) { - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.eq("username", user.getUsername()); - User userO = userService.getOne(queryWrapper); - if (userO != null) { - return ResultGenerator.genFailResult("账号已存在"); - } - user.setPassword(MD5Utils.Encrypt(user.getPassword(), true)); - userService.save(user); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation("修改密码") - @PostMapping("/updatePassword") - public Result updatePassword(@RequestBody JSONObject param) { - String oldPassword = param.getString("oldPassword"); - String newPassword = param.getString("newPassword"); - if (StringUtils.isBlank(oldPassword) || StringUtils.isBlank(newPassword)) { - return ResultGenerator.genFailResult("密码不能为空"); - } - //获取登陆信息 - JSONObject sessionInfo = httpSession.getCurrentSession(); - String userId = sessionInfo.getString("userId"); - - User user = userService.getById(userId); - if (user == null) { - return ResultGenerator.genFailResult("账号未找到"); - } - if (!MD5Utils.Encrypt(oldPassword, true).equals(user.getPassword())) { - return ResultGenerator.genFailResult("旧密码错误"); - } - User updateUser = new User(); - updateUser.setId(user.getId()); - updateUser.setPassword(MD5Utils.Encrypt(newPassword, true)); - userService.updateById(updateUser); - - //重置密码后删除原所有token - httpSession.abortAllUserByToken(); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation("登出") - @GetMapping("/logout") - public Result logout() { - //退出删除token - httpSession.abortUserByToken(); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation("校验token是否有效") - @GetMapping("/validateToken") - public Result validateToken() { - //拦截器拦截已判断,直接返回成功 - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "删除") - @PostMapping("delete/{id}") - public Result delete(@PathVariable("id") Long id) { - userService.removeById(id); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "更新") - @PostMapping("update") - public Result update(@RequestBody User user) { - //密码不更新 - user.setPassword(null); - userService.updateById(user); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "查询分页数据") - @ApiImplicitParams({ - @ApiImplicitParam(name = "currentPage", value = "页码"), - @ApiImplicitParam(name = "pageCount", value = "每页条数") - }) - @GetMapping("listByPage") - public Result findListByPage(@RequestParam(defaultValue = "1") Integer currentPage, - @RequestParam(defaultValue = "10") Integer pageCount) { - Page page = new Page(currentPage, pageCount); - IPage iPage = userService.page(page); - return ResultGenerator.genSuccessResult(iPage); - } - - @ApiOperation(value = "id查询") - @GetMapping("getById/{id}") - public Result findById(@PathVariable Long id) { - return ResultGenerator.genSuccessResult(userService.getById(id)); - } - - @ApiOperation(value = "生成验证码") - @GetMapping(value = "/getVerify") - public void getVerify(HttpServletRequest request, HttpServletResponse response) { - response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片 - response.setHeader("Pragma", "No-cache");//设置响应头信息,告诉浏览器不要缓存此内容 - response.setHeader("Cache-Control", "no-cache"); - response.setDateHeader("Expire", 0); - try { - ImageCodeUtil randomValidateCode = new ImageCodeUtil(); - randomValidateCode.getRandcode(request, response);//输出验证码图片方法 - } catch (Exception e) { - log.error("生成验证码失败"); - } - } - - @ApiOperation(value = "校验验证码") - @PostMapping(value = "/checkVerify") - public Result checkVerify(@RequestParam String imageCode, HttpSession session) { - //从session中获取随机数 - Object random = session.getAttribute(ImageCodeUtil.IMAGE_RANDOM_CODEKEY); - if (random != null && String.valueOf(random).equals(imageCode)) { - return ResultGenerator.genSuccessResult(); - } - return ResultGenerator.genFailResult("校验失败"); - } - - -} diff --git a/java_project_template/jun_api_service_main/src/main/resources/application-sqlite.yml b/java_project_template/jun_api_service_main/src/main/resources/application-sqlite.yml deleted file mode 100644 index a43ec1e6f3..0000000000 --- a/java_project_template/jun_api_service_main/src/main/resources/application-sqlite.yml +++ /dev/null @@ -1,14 +0,0 @@ -# 数据源配置 -spring: - datasource: - type: com.alibaba.druid.pool.DruidDataSource - driverClassName: org.sqlite.JDBC - druid: - # 主库数据源 - master: - # 发布后 - # url: jdbc:sqlite:./sqlite/code-generator.db - # 开发时 - url: jdbc:sqlite::resource:static/sqlite/code-generator.db - username: root - password: password \ No newline at end of file diff --git a/java_project_template/jun_api_service_main/src/main/resources/application-test.yml b/java_project_template/jun_api_service_main/src/main/resources/application-test.yml deleted file mode 100644 index b9b3e21024..0000000000 --- a/java_project_template/jun_api_service_main/src/main/resources/application-test.yml +++ /dev/null @@ -1,88 +0,0 @@ -spring: - redis: - host: localhost # Redis服务器地址 - database: 0 # Redis数据库索引(默认为0) - port: 6379 # Redis服务器连接端口 - password: # Redis服务器连接密码(默认为空) - jedis: - pool: - max-active: 8 # 连接池最大连接数(使用负值表示没有限制) - max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制) - max-idle: 8 # 连接池中的最大空闲连接 - min-idle: 0 # 连接池中的最小空闲连接 - timeout: 3000 # 连接超时时间(毫秒 - # mysql - datasource: - type: com.alibaba.druid.pool.DruidDataSource - #MySQL配置 - driverClassName: com.mysql.jdbc.Driver - url: jdbc:mysql://localhost:3306/db_qixing?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2b8 - username: root - password: -# username: ENC(i9EHZ6vsnfpTeKGvHmH+fA==) -# password: ENC(KX2tfUq8cZG3IXeAwZgk5w==) - #oracle配置 - # driverClassName: oracle.jdbc.OracleDriver - # url: jdbc:oracle:thin:@47.100.206.162:1521:xe - # username: renren - # password: 123456 - #SQLServer配置 - # driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver - # url: jdbc:sqlserver://192.168.10.10:1433;DatabaseName=renren_fast - # username: sa - # password: 123456 - #PostgreSQL配置 - # driverClassName: org.postgresql.Driver - # url: jdbc:postgresql://192.168.10.10:5432/renren_fast - # username: postgres - # password: 123456 - - groovy-api: -# servicename: jun-engine-api -# enabled: true -# context: /api -# api_config: api_config -# gateway: ~ -# config: -# sql: sql.xml -# datasource: datasource.xml -# service-title: API平台 -# file-path: ~ -# datasource: -# dbtype: -# url: -# username: -# password: -# class-model: -# transcation: true -# sql-model: -# find-one-suffix: /first -# pager-suffix: /page -# count-suffix: /count - - -filepath: "D:\\files\\" -file: - #文件上传目录 绝对路径 末尾请加 / - path: D:/files/ #windows - #path: /home/data/files/ #linux - #文件预览、下载的url, 末尾请勿加 / - url: http://qixing.vip321.vip/files - qiniuAccessKey: ts0n9OF16ekFkDkZTTlpmyPI-tP3HKQDyw_GR4o2 - qiniuBucketName: qixing-files - qiniuDomain: http://qiniu.vip321.vip - qiniuPrefix: upload - qiniuSecretKey: c-OjjwV3ZgzCQwxc6W_bsTFKuDg8qeyqohyJU0RL - type: 1 - - -# AES密码加密私钥(Base64加密) -encryptAESKey: V2FuZzkyNjQ1NGRTQkFQSUpXVA== -# JWT认证加密私钥(Base64加密) -encryptJWTKey: U0JBUElKV1RkV2FuZzkyNjQ1NA== -# AccessToken过期时间-5分钟-5*60(秒为单位) -accessTokenExpireTime: 300 -# RefreshToken过期时间-30分钟-30*60(秒为单位) -refreshTokenExpireTime: 1800 -# Shiro缓存过期时间-5分钟-5*60(秒为单位)(一般设置与AccessToken过期时间一致) -shiroCacheExpireTime: 300 \ No newline at end of file diff --git a/java_project_template/jun_api_service_main/src/main/resources/application.yml b/java_project_template/jun_api_service_main/src/main/resources/application.yml deleted file mode 100644 index 1c9e9d4661..0000000000 --- a/java_project_template/jun_api_service_main/src/main/resources/application.yml +++ /dev/null @@ -1,59 +0,0 @@ -# 端口 -server: - port: 9080 - http2: - enabled: true - -spring: - profiles: - active: test - mvc: - throw-exception-if-no-handler-found: true - resources: - add-mappings: false - application: - name: groovy_api_service - jackson: - date-format: yyyy-MM-dd HH:mm:ss - time-zone: GMT+8 - # 文件大小限制 - servlet: - multipart: - max-file-size: 10MB - max-request-size: 100MB - main: - allow-bean-definition-overriding: true - # redis token信息 - redis: - key: - prefix: - userToken: "user:token:" - passwordError: "user:password:error:" - permissionRefresh: "user:token:permissionRefresh:" - expire: - userToken: 604800 # 7天 7*24*3600 - passwordError: 3600 # 一个小时 - permissionRefresh: 604800 # 7天 7*24*3600 - allowMultipleLogin: true # 允许多处登陆 - -mybatis-plus: - configuration: - log-impl: org.apache.ibatis.logging.stdout.StdOutImpl - mapper-locations: classpath:mapper/${project.database}/**/*.xml,classpath:mapper/*.xml - global-config: - db-config: - logic-delete-value: 0 - logic-not-delete-value: 1 - logic-delete-field: deleted - -#使用代码生成模块时 指定要生成的表存在于哪种数据库,可选值有【mysql、oracle、sqlServer】 -project: - database: mysql - -jasypt: - algorithm: PBEWithMD5AndDES - encryptor: - password: 123456@@ - -shiro: - enable: false \ No newline at end of file diff --git a/java_project_template/jun_api_service_main/src/test/java/CodeGenerator.java b/java_project_template/jun_api_service_main/src/test/java/CodeGenerator.java deleted file mode 100644 index b3c20b934e..0000000000 --- a/java_project_template/jun_api_service_main/src/test/java/CodeGenerator.java +++ /dev/null @@ -1,113 +0,0 @@ -import com.baomidou.mybatisplus.core.toolkit.StringPool; -import com.baomidou.mybatisplus.generator.AutoGenerator; -import com.baomidou.mybatisplus.generator.InjectionConfig; -import com.baomidou.mybatisplus.generator.config.*; -import com.baomidou.mybatisplus.generator.config.po.TableInfo; -import com.baomidou.mybatisplus.generator.config.rules.DateType; -import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; -import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; - -import java.util.ArrayList; -import java.util.List; - -// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中 -public class CodeGenerator { - - - //多个表逗号分隔 - static String tableName = "user"; - //逻辑删除字段名, 假如表没有逻辑删除字段,请忽视 - static String logicDeleteFieldName = "del_flag"; - - public static void main(String[] args) { - // 代码生成器 - AutoGenerator mpg = new AutoGenerator(); - - // 全局配置 - GlobalConfig gc = new GlobalConfig(); - String projectPath = System.getProperty("user.dir"); - gc.setOutputDir(projectPath + "/src/main/java"); - gc.setAuthor("aitangbao"); - gc.setOpen(false); - gc.setBaseColumnList(true); - gc.setBaseResultMap(true); - gc.setDateType(DateType.ONLY_DATE); - // gc.setSwagger2(true); 实体属性 Swagger2 注解 - mpg.setGlobalConfig(gc); - - // 数据源配置 - DataSourceConfig dsc = new DataSourceConfig(); - dsc.setUrl("jdbc:mysql://localhost:3306/project?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC"); - // dsc.setSchemaName("public"); - dsc.setDriverName("com.mysql.cj.jdbc.Driver"); - dsc.setUsername("root"); - dsc.setPassword("123456"); - mpg.setDataSource(dsc); - - // 包配置 - PackageConfig pc = new PackageConfig(); - pc.setParent("com.jun.plugin.system"); - pc.setEntity("model"); - pc.setMapper("dao"); - pc.setController("web"); - mpg.setPackageInfo(pc); - - // 自定义配置 - InjectionConfig cfg = new InjectionConfig() { - @Override - public void initMap() { - // to do nothing - } - }; - - // 如果模板引擎是 freemarker - String templatePath = "/templates/mapper.xml.ftl"; - // 如果模板引擎是 velocity - // String templatePath = "/templates/mapper.xml.vm"; - - // 自定义输出配置 - List focList = new ArrayList<>(); - // 自定义配置会被优先输出 - focList.add(new FileOutConfig(templatePath) { - @Override - public String outputFile(TableInfo tableInfo) { - // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!! - return projectPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; - } - }); - cfg.setFileOutConfigList(focList); - mpg.setCfg(cfg); - - // 配置模板 - TemplateConfig templateConfig = new TemplateConfig(); - - // 配置自定义输出模板 - //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别 -// templateConfig.setEntity("templates/entity.java"); - // templateConfig.setService(); - templateConfig.setController("templates/controller.java"); - - templateConfig.setXml(null); - mpg.setTemplate(templateConfig); - - // 策略配置 - StrategyConfig strategy = new StrategyConfig(); - strategy.setNaming(NamingStrategy.underline_to_camel); - strategy.setColumnNaming(NamingStrategy.underline_to_camel); -// strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!"); - strategy.setEntityLombokModel(true); - strategy.setRestControllerStyle(true); - // 公共父类 -// strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!"); - // 写于父类中的公共字段 -// strategy.setSuperEntityColumns("id"); - strategy.setInclude(tableName.split(",")); - strategy.setControllerMappingHyphenStyle(true); - strategy.setLogicDeleteFieldName(logicDeleteFieldName); // 逻辑删除字段名称 - strategy.setTablePrefix(pc.getModuleName() + "_"); - mpg.setStrategy(strategy); - mpg.setTemplateEngine(new FreemarkerTemplateEngine()); - mpg.execute(); - } - -} \ No newline at end of file diff --git a/java_project_template/jun_api_service_main/src/test/java/com/jun/plugin/system/Tester.java b/java_project_template/jun_api_service_main/src/test/java/com/jun/plugin/system/Tester.java deleted file mode 100644 index 73ec18fc47..0000000000 --- a/java_project_template/jun_api_service_main/src/test/java/com/jun/plugin/system/Tester.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.jun.plugin.system; - -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(classes = ApiServiceApplication.class,webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -public class Tester { - - @Test - public void test() { - - } -} - - - diff --git a/java_project_template/jun_api_service_main/src/test/resources/templates/controller.java.ftl b/java_project_template/jun_api_service_main/src/test/resources/templates/controller.java.ftl deleted file mode 100644 index 93f2bb3f44..0000000000 --- a/java_project_template/jun_api_service_main/src/test/resources/templates/controller.java.ftl +++ /dev/null @@ -1,94 +0,0 @@ -package ${package.Controller}; - -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import core.com.jun.plugin.system.Result; -import core.com.jun.plugin.system.ResultGenerator; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import org.springframework.web.bind.annotation.*; -import ${package.Service}.${table.serviceName}; -import ${package.Entity}.${entity}; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import lombok.extern.slf4j.Slf4j; -import com.baomidou.mybatisplus.core.metadata.IPage; - -import javax.annotation.Resource; -<#if restControllerStyle> -import org.springframework.web.bind.annotation.RestController; -<#else> -import org.springframework.stereotype.Controller; - -<#if superControllerClassPackage??> -import ${superControllerClassPackage}; - - -/** - *

- * ${table.comment!} 前端控制器 - *

- * - * @author ${author} - * @since ${date} - */ -<#if restControllerStyle> -@Api(tags = {"${table.comment!}"}) -@Slf4j -@RestController -<#else> -@Controller - -@RequestMapping("<#if package.ModuleName??>/${package.ModuleName}/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}") -<#if kotlin> -class ${table.controllerName}<#if superControllerClass??>:${superControllerClass}() -<#else> -<#if superControllerClass??>public class ${table.controllerName} extends ${superControllerClass}{ -<#else>public class ${table.controllerName} { - - - @Resource - private ${table.serviceName} ${(table.serviceName?substring(1))?uncap_first}; - - - @ApiOperation(value = "新增${table.comment!}") - @PostMapping("add") - public Result add(@RequestBody ${entity} ${entity?uncap_first}){ - ${(table.serviceName?substring(1))?uncap_first}.save(${entity?uncap_first}); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "删除${table.comment!}") - @PostMapping("delete/{id}") - public Result delete(@PathVariable("id") Long id){ - ${(table.serviceName?substring(1))?uncap_first}.removeById(id); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "更新${table.comment!}") - @PostMapping("update") - public Result update(@RequestBody ${entity} ${entity?uncap_first}){ - ${(table.serviceName?substring(1))?uncap_first}.updateById(${entity?uncap_first}); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "查询${table.comment!}分页数据") - @ApiImplicitParams({ - @ApiImplicitParam(name = "currentPage", value = "页码"), - @ApiImplicitParam(name = "pageCount", value = "每页条数") - }) - @GetMapping("listByPage") - public Result findListByPage(@RequestParam Integer currentPage, - @RequestParam Integer pageCount){ - Page page = new Page(currentPage, pageCount); - IPage<${entity}> iPage = ${(table.serviceName?substring(1))?uncap_first}.page(page); - return ResultGenerator.genSuccessResult(iPage); - } - - @ApiOperation(value = "id查询${table.comment!}") - @GetMapping("getById/{id}") - public Result findById(@PathVariable Long id){ - return ResultGenerator.genSuccessResult(${(table.serviceName?substring(1))?uncap_first}.getById(id)); - } - -} - \ No newline at end of file diff --git a/java_project_template/jun_api_service_simple/pom.xml b/java_project_template/jun_api_service_simple/pom.xml deleted file mode 100644 index a7a4fe5b02..0000000000 --- a/java_project_template/jun_api_service_simple/pom.xml +++ /dev/null @@ -1,160 +0,0 @@ - - - 4.0.0 - com.jun.plugin - jun_api_service_simple - 1.0 - jun_api_service_simple - - - - org.springframework.boot - spring-boot-starter-web - - - - io.github.wujun728 - jun-db-activerecord - 1.0.25 - - - - org.springframework.boot - spring-boot-starter-freemarker - - - - - org.springframework.boot - spring-boot-starter-validation - - - com.github.xiaoymin - knife4j-spring-boot-starter - 2.0.2 - - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - - org.springframework.boot - spring-boot-devtools - runtime - true - - - - org.springframework.boot - spring-boot-starter-mail - - - org.springframework.boot - spring-boot-starter-websocket - - - mysql - mysql-connector-java - runtime - - - - com.alibaba - druid-spring-boot-starter - 1.2.16 - - - com.baomidou - mybatis-plus-boot-starter - 3.5.3.2 - - - org.springframework.boot - spring-boot-starter-data-redis - - - - - - - - - org.springframework.boot - spring-boot-dependencies - - - - 2.5.14 - pom - import - - - - - - manager - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.0 - - 1.8 - 1.8 - UTF-8 - - - - - - - - - - - aliyun-repos - http://maven.aliyun.com/nexus/content/groups/public/ - - false - - - - - - - aliyun-plugin - http://maven.aliyun.com/nexus/content/groups/public/ - - false - - - - diff --git a/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/QixingApplication.java b/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/QixingApplication.java deleted file mode 100644 index 7b71f4b9c0..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/QixingApplication.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.jun.plugin.project; - -import java.net.Inet4Address; -import java.net.InetAddress; - -import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure; -import org.mybatis.spring.annotation.MapperScan; -import org.springframework.boot.CommandLineRunner; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.web.servlet.ServletComponentScan; -import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.core.env.Environment; -import org.springframework.scheduling.annotation.EnableScheduling; - -import lombok.extern.slf4j.Slf4j; - -@Slf4j -@EnableScheduling -@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class) // 多数据源 (exclude = DruidDataSourceAutoConfigure.class) -@MapperScan("com.jun.plugin.**.mapper") -//@ComponentScan(basePackages = "com.jun.plugin") -@ServletComponentScan(basePackages = {"com.jun.plugin.**.filter"}) -public class QixingApplication extends SpringBootServletInitializer { - - public static void main(String[] args) throws Exception { -// SpringApplication application = new SpringApplication(SpringbootApplication.class); -// application.setBannerMode(Banner.Mode.OFF); -// application.run(args); - System.setProperty("spring.devtools.restart.enabled", "true"); - ConfigurableApplicationContext application = SpringApplication.run(QixingApplication.class, args); - Environment env = application.getEnvironment(); - InetAddress inetAddress = Inet4Address.getLocalHost(); - String hostAddress = inetAddress.getHostAddress(); - String serverPort = env.getProperty("server.port"); - String serverPath = env.getProperty("spring.application.name"); - String url = env.getProperty("spring.datasource.url"); - - log.info("项目启动成功!访问地址: http://{}:{}/{}", hostAddress, serverPort, serverPath); - log.info("本机地址: http://localhost:{}", serverPort); - } - - @Override // 为了打包springboot项目 - protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { - return builder.sources(this.getClass()); - } - - @Bean - public CommandLineRunner commandLineRunner(ApplicationContext ctx) { - return args -> { - System.out.println("Let's inspect the beans provided by Spring Boot:"); - String[] beanNames = ctx.getBeanDefinitionNames(); - System.err.println("beanNames size = "+ beanNames.length); - - for (String beanName : beanNames) { - //System.err.println(beanName); - } - - }; - } -} - - diff --git a/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/config/GlobalRequestBodyAdvice2.java b/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/config/GlobalRequestBodyAdvice2.java deleted file mode 100644 index 827af89fa0..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/config/GlobalRequestBodyAdvice2.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.jun.plugin.project.config; - -import org.springframework.core.MethodParameter; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpInputMessage; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.web.bind.annotation.ControllerAdvice; -import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Type; -import java.util.Map; - -/** - * @title 全局请求参数处理类 - */ -@ControllerAdvice(basePackages = "com.jun.plugin.*.controller")//此处设置需要当前Advice执行的域 , 省略默认全局生效 -public class GlobalRequestBodyAdvice2 implements RequestBodyAdvice { - - - /** 此处如果返回false , 则不执行当前Advice的业务 */ - @Override - public boolean supports(MethodParameter methodParameter, Type targetType, Class> converterType) { -// return methodParameter.getMethod().isAnnotationPresent(XXApiReq.class); - return false; - } - - /** - * @title 读取参数前执行 - * @description 在此做些编码 / 解密 / 封装参数为对象的操作 - * - * */ - @Override - public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class> converterType) throws IOException { - // 提取数据 - InputStream is = inputMessage.getBody(); - byte[] data = new byte[is.available()]; - is.read(data); - //转数据类型 - ObjectMapper mapper = new ObjectMapper(); - Map m = mapper.readValue(new String(data), Map.class); - //m.forEach(null); - return new XHttpInputMessage2(inputMessage, "UTF-8"); - } - - /** - * @title 读取参数后执行 - */ - @Override - public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class> converterType) { - return inputMessage; - } - - /** - * @title 无请求时的处理 - */ - @Override - public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class> converterType) { - return body; - } -} - -//这里实现了HttpInputMessage 封装一个自己的HttpInputMessage -class XHttpInputMessage2 implements HttpInputMessage { - private HttpHeaders headers; - private InputStream body; - - public XHttpInputMessage2(HttpInputMessage httpInputMessage, String encode) throws IOException { - this.headers = httpInputMessage.getHeaders(); - this.body = encode(httpInputMessage.getBody(), encode); - } - - private InputStream encode(InputStream body, String encode) { - //省略对流进行编码的操作 - return body; - } - - @Override - public InputStream getBody() { - return body; - } - - @Override - public HttpHeaders getHeaders() { - return null; - } -} \ No newline at end of file diff --git a/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/config/MetaObjectHandlerConfig2.java b/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/config/MetaObjectHandlerConfig2.java deleted file mode 100644 index 311e24554b..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/config/MetaObjectHandlerConfig2.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.jun.plugin.project.config; - -import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; -//import com.jun.plugin.project.service.HttpSessionService; -import org.apache.ibatis.reflection.MetaObject; -import org.springframework.stereotype.Component; - -import java.util.Arrays; -import java.util.Date; -import java.util.HashSet; - - -/** - * mybatis plus 默认值配置 - * - * @author wujun - * @version V1.0 - * @date 2020年3月18日 - */ -@Component -public class MetaObjectHandlerConfig2 implements MetaObjectHandler { - -// @Lazy -// @Resource -// HttpSessionService httpSessionService; - - @Override - public void insertFill(MetaObject metaObject) { - Date currentDate = new Date(); - String[] setterNames = metaObject.getSetterNames(); - HashSet setterNameSet = new HashSet<>(Arrays.asList(setterNames)); - if (setterNameSet.contains("deleted")) { - //默认未删除 - setFieldValByName("deleted", 0, metaObject); - } - if (setterNameSet.contains("createTime")) { - //创建时间默认当前时间 - setFieldValByName("createTime", currentDate, metaObject); - } - if (setterNameSet.contains("createDate")) { - //创建时间默认当前时间 - setFieldValByName("createDate", currentDate, metaObject); - } -// if (setterNameSet.contains("createId")) { -// //创建时间默认当前时间 -// setFieldValByName("createId", httpSessionService.getCurrentUserId(), metaObject); -// } -// if (setterNameSet.contains("updateId")) { -// //创建时间默认当前时间 -// setFieldValByName("updateId", httpSessionService.getCurrentUserId(), metaObject); -// } - if (setterNameSet.contains("updateTime")) { - //创建时间默认当前时间 - setFieldValByName("updateTime", currentDate, metaObject); - } - if (setterNameSet.contains("updateDate")) { - //创建时间默认当前时间 - setFieldValByName("updateDate", currentDate, metaObject); - } - - - } - - @Override - public void updateFill(MetaObject metaObject) { - Date currentDate = new Date(); - String[] setterNames = metaObject.getSetterNames(); - HashSet setterNameSet = new HashSet<>(Arrays.asList(setterNames)); - if (setterNameSet.contains("updateTime")) { - //创建时间默认当前时间 - setFieldValByName("updateTime", currentDate, metaObject); - } - if (setterNameSet.contains("updateDate")) { - //创建时间默认当前时间 - setFieldValByName("updateDate", currentDate, metaObject); - } -// if (setterNameSet.contains("updateId")) { -// //创建时间默认当前时间 -// setFieldValByName("updateId", httpSessionService.getCurrentUserId(), metaObject); -// } - } -} \ No newline at end of file diff --git a/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/config/MyBatisPlusConfig2.java b/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/config/MyBatisPlusConfig2.java deleted file mode 100644 index 2161759216..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/config/MyBatisPlusConfig2.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.jun.plugin.project.config; - -import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * mybatis plus config - * - * @author wujun - * @version V1.0 - * @date 2020年3月18日 - */ -@Configuration -public class MyBatisPlusConfig2 { - /** - * 配置mybatis-plus 分页查件 - */ - @Bean - public PaginationInnerInterceptor paginationInterceptor() { - return new PaginationInnerInterceptor(); - } -} \ No newline at end of file diff --git a/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/config/RedisCacheConfig2.java b/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/config/RedisCacheConfig2.java deleted file mode 100644 index 0eee4e8081..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/config/RedisCacheConfig2.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.jun.plugin.project.config; - -import java.time.Duration; -import java.util.HashMap; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cache.annotation.EnableCaching; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.redis.cache.RedisCacheConfiguration; -import org.springframework.data.redis.cache.RedisCacheManager; -import org.springframework.data.redis.cache.RedisCacheWriter; -import org.springframework.data.redis.connection.RedisConnectionFactory; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; -import org.springframework.data.redis.serializer.RedisSerializationContext; -import org.springframework.data.redis.serializer.RedisSerializer; -import org.springframework.data.redis.serializer.StringRedisSerializer; - -import javax.annotation.Resource; - -/** - * Redis缓存配置。 - */ -@Configuration -@EnableCaching -public class RedisCacheConfig2 { - - @Autowired - private RedisTemplate redisTemplate; - - @Resource - private RedisConnectionFactory factory; - - @Bean - public RedisTemplate redisTemplate() { - RedisTemplate redisTemplate = new RedisTemplate<>(); - redisTemplate.setConnectionFactory(factory); - // 字符串Key序列化 - StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); - redisTemplate.setKeySerializer(stringRedisSerializer); - redisTemplate.setHashKeySerializer(stringRedisSerializer); - // 对象值序列化 -// ObjectRedisSerializer objectRedisSerializer = new ObjectRedisSerializer(); - RedisSerializer objectRedisSerializer = new GenericJackson2JsonRedisSerializer(); - redisTemplate.setValueSerializer(objectRedisSerializer); - redisTemplate.setHashValueSerializer(objectRedisSerializer); - return redisTemplate; - } - - @Bean(name = "redisCacheManager") - public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) { - - // 初始化一个RedisCacheWriter - RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory); - // 设置CacheManager的值序列化方式为json序列化 - RedisSerializer jsonSerializer = new GenericJackson2JsonRedisSerializer(); - RedisSerializationContext.SerializationPair pair = RedisSerializationContext.SerializationPair - .fromSerializer(jsonSerializer); - RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair); - config.entryTtl(Duration.ofSeconds(60*2)).disableCachingNullValues();// 不缓存空值 -// // 初始化RedisCacheManager - return new RedisCacheManager(redisCacheWriter, config, getRedisCacheConfigurationMap()); - } - - - private Map getRedisCacheConfigurationMap() { - Map redisCacheConfigurationMap = new HashMap<>(); - redisCacheConfigurationMap.put("messagCache", this.getRedisCacheConfigurationWithTtl(30 * 60)); - //自定义设置缓存时间 - redisCacheConfigurationMap.put("userCache", this.getRedisCacheConfigurationWithTtl(60)); - redisCacheConfigurationMap.put("cache4h", this.getRedisCacheConfigurationWithTtl(60*60*4)); - redisCacheConfigurationMap.put("cache5m", this.getRedisCacheConfigurationWithTtl(60*2)); - redisCacheConfigurationMap.put("cache2m", this.getRedisCacheConfigurationWithTtl(60*2)); - redisCacheConfigurationMap.put("cache1m", this.getRedisCacheConfigurationWithTtl(60)); - - return redisCacheConfigurationMap; - } - - private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) { -// RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(factory); - // 设置CacheManager的值序列化方式为json序列化 - RedisSerializer jsonSerializer = new GenericJackson2JsonRedisSerializer(); - RedisSerializationContext.SerializationPair pair = RedisSerializationContext.SerializationPair - .fromSerializer(jsonSerializer); - RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair); - redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith( - RedisSerializationContext - .SerializationPair - .fromSerializer(jsonSerializer) - ).entryTtl(Duration.ofSeconds(seconds)); - return redisCacheConfiguration; - } - -} diff --git a/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/config/ResourcesConfig2.java b/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/config/ResourcesConfig2.java deleted file mode 100644 index 90e9927291..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/config/ResourcesConfig2.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.jun.plugin.project.config; - -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.CorsRegistry; -import org.springframework.web.servlet.config.annotation.InterceptorRegistry; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -/** - * 通用配置 - * - */ -@Configuration -//@EnableConfigurationProperties(FileUploadProperties.class) -public class ResourcesConfig2 implements WebMvcConfigurer { - -// @Resource -// private FileUploadProperties fileUploadProperties; - /** - * 首页地址 - */ -// @Value("${shiro.user.indexUrl}") -// private String indexUrl; - -// @Autowired -// private RepeatSubmitInterceptor repeatSubmitInterceptor; - - @Override - public void addCorsMappings(CorsRegistry registry) { - WebMvcConfigurer.super.addCorsMappings(registry); - registry.addMapping("/**").allowedHeaders("*").allowedMethods("POST", "GET", "PUT", "DELETE") - .allowedOrigins("*"); - } - - /** - * 默认首页的设置,当输入域名是可以自动跳转到默认指定的网页 - */ - @Override - public void addViewControllers(ViewControllerRegistry registry) { -// registry.addViewController("/").setViewName("forward:" + indexUrl); - registry.addViewController("/").setViewName("forward:" + "login.html"); - } - - /** - * 发现如果继承了WebMvcConfigurationSupport,则在yml中配置的相关内容会失效。 需要重新指定静态资源 - */ - - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - /** 本地文件上传路径 */ -// registry.addResourceHandler(Constants.RESOURCE_PREFIX + "/**").addResourceLocations("file:" + Global.getProfile() + "/"); - - registry.addResourceHandler("/**").addResourceLocations("classpath:/static/","classpath:/templates/","classpath:/templates2/","classpath:/views/"); -// registry.addResourceHandler("/**").addResourceLocations("classpath:/templates/"); - registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/"); - registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); - - /** swagger配置 */ - registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); - registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); - /** 文件下载映射配置,同下 */ -// registry.addResourceHandler(fileUploadProperties.getAccessUrl()).addResourceLocations("file:" + fileUploadProperties.getPath()); - } - - /** - * @description: 访问静态文件 - * @date: 2021/4/15 - */ -// @Override -// public void addResourceHandlers(ResourceHandlerRegistry registry) { -// log.debug("System.getProperty(\"user.dir\")"); -// // 访问路径 -// registry.addResourceHandler("/api/upload/**") -// // 映射真实路径 -// .addResourceLocations("file:" + System.getProperty("user.dir") + "/");// 必须加"/",不然映射不到 -// } - - /** - * 自定义拦截规则 - */ - @Override - public void addInterceptors(InterceptorRegistry registry) { -// registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/**"); - } -} diff --git a/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/config/SwaggerConfiguration2.java b/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/config/SwaggerConfiguration2.java deleted file mode 100644 index 85b1f3dfa7..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/config/SwaggerConfiguration2.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.jun.plugin.project.config; - -import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j; -import com.google.common.base.Predicates; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration; -import springfox.documentation.builders.ApiInfoBuilder; -import springfox.documentation.builders.PathSelectors; -import springfox.documentation.builders.RequestHandlerSelectors; -import springfox.documentation.service.ApiInfo; -import springfox.documentation.spi.DocumentationType; -import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger2.annotations.EnableSwagger2; - - -/** - * SwaggerConfiguration - * - * @author wujun - * @version V1.0 - * @date 2020年3月18日 - */ -@Configuration -@EnableSwagger2 -@EnableKnife4j -@Import(BeanValidatorPluginsConfiguration.class) -public class SwaggerConfiguration2 { - - @Bean - public Docket createRestApi() { - return new Docket(DocumentationType.SWAGGER_2) - .apiInfo(apiInfo()) - .select() - .apis(Predicates.or(RequestHandlerSelectors.basePackage("com.jun.plugin.system.controller"), - RequestHandlerSelectors.basePackage("com.jun.plugin.bizservice.controller"))) - .paths(PathSelectors.any()) - .build(); - } - - private ApiInfo apiInfo() { - return new ApiInfoBuilder() - .title("Springboot-api APIs") - .description("Springboot-api APIs") - .termsOfServiceUrl("http://localhost:8080/") - .version("1.0") - .build(); - } -} \ No newline at end of file diff --git a/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/config/ThymeleafConfigration2.java b/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/config/ThymeleafConfigration2.java deleted file mode 100644 index eed66eb26d..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/config/ThymeleafConfigration2.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.jun.plugin.project.config; - -import java.io.File; -import java.io.FileNotFoundException; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.util.ResourceUtils; -import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver; -import org.thymeleaf.templatemode.TemplateMode; -import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; - -@Configuration -public class ThymeleafConfigration2 { - - @Bean - public SpringResourceTemplateResolver firstTemplateResolver() { - SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); - //templateResolver.setPrefix("classpath:/templates/"); - - File path = null; - try { - path = new File(ResourceUtils.getURL("classpath:").getPath()); - //file:/data/github/testmanagement/target/testmanagement-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes! - System.out.println(path.getPath()); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - //server.tomcat.basedir=outsidefile/jacococoverage - String outside_templates=path.getParentFile().getParentFile().getParent()+File.separator; - //String outside_templates=path.getParentFile().getParentFile().getParent()+File.separator+"outsidefile"+File.separator+"jacococoverage"+File.separator; - - System.out.println(outside_templates); - outside_templates=outside_templates.substring(5,outside_templates.length()); - //file:/data/github/testmanagement/target/outsidefile/jacococoverage/ - - System.out.println("new outside_templates is "+outside_templates); - templateResolver.setPrefix("file://"+outside_templates); - - templateResolver.setSuffix(".html"); - templateResolver.setTemplateMode(TemplateMode.HTML); - templateResolver.setCharacterEncoding("UTF-8"); - templateResolver.setOrder(0); - templateResolver.setCheckExistence(true); - //Spring Boot中Thymeleaf引擎动态刷新 - templateResolver.setCacheable(false); - return templateResolver; - } - -// @Bean -// public ClassLoaderTemplateResolver secondaryTemplateResolver() { -// ClassLoaderTemplateResolver secondaryTemplateResolver = new ClassLoaderTemplateResolver(); -// secondaryTemplateResolver.setPrefix("templates2/"); -// secondaryTemplateResolver.setSuffix(".html"); -// secondaryTemplateResolver.setTemplateMode(TemplateMode.HTML); -// secondaryTemplateResolver.setCharacterEncoding("UTF-8"); -// secondaryTemplateResolver.setOrder(1); -// secondaryTemplateResolver.setCacheable(false); -// secondaryTemplateResolver.setCheckExistence(true); -// return secondaryTemplateResolver; -// } - @Bean - public ClassLoaderTemplateResolver secondaryTemplateResolver3() { - ClassLoaderTemplateResolver secondaryTemplateResolver = new ClassLoaderTemplateResolver(); - secondaryTemplateResolver.setPrefix("templates3/"); - secondaryTemplateResolver.setSuffix(".html"); - secondaryTemplateResolver.setTemplateMode(TemplateMode.HTML); - secondaryTemplateResolver.setCharacterEncoding("UTF-8"); - secondaryTemplateResolver.setOrder(1); - secondaryTemplateResolver.setCacheable(false); - secondaryTemplateResolver.setCheckExistence(true); - return secondaryTemplateResolver; - } -} \ No newline at end of file diff --git a/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/config/WebMvcConfig.java b/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/config/WebMvcConfig.java deleted file mode 100644 index 9bc708fad0..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/config/WebMvcConfig.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.jun.plugin.project.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.*; -import org.springframework.web.servlet.view.InternalResourceViewResolver; - -import javax.servlet.http.HttpServletRequest; - -/** - * 通用配置 - * - */ -@Configuration -//@EnableConfigurationProperties(FileUploadProperties.class) -public class WebMvcConfig extends WebMvcConfigurationSupport/* implements WebMvcConfigurer*/ { - -// @Resource -// private FileUploadProperties fileUploadProperties; - /** - * 首页地址 - */ -// @Value("${shiro.user.indexUrl}") -// private String indexUrl; - - - @Override - public void addCorsMappings(CorsRegistry registry) { - super.addCorsMappings(registry); - registry.addMapping("/**").allowedHeaders("*").allowedMethods("POST", "GET", "PUT", "DELETE") - .allowedOrigins("*"); - } - - /** - * 默认首页的设置,当输入域名是可以自动跳转到默认指定的网页 - */ - @Override - public void addViewControllers(ViewControllerRegistry registry) { -// registry.addViewController("/").setViewName("forward:" + indexUrl); - registry.addViewController("/").setViewName("forward:" + "login.html"); - } - - - /** - * @description: 访问静态文件,发现如果继承了WebMvcConfigurationSupport,则在yml中配置的相关内容会失效。 需要重新指定静态资源 - * @date: 2021/4/15 - */ - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - /** 本地文件上传路径 */ -// registry.addResourceHandler(Constants.RESOURCE_PREFIX + "/**").addResourceLocations("file:" + Global.getProfile() + "/"); - - registry.addResourceHandler("/**").addResourceLocations("classpath:/static/","classpath:/static2/","classpath:/static3/","classpath:/templates/","classpath:/templates3/","classpath:/views/"); -// registry.addResourceHandler("/**").addResourceLocations("classpath:/templates/"); - registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/","classpath:/static2/","classpath:/static3/"); - registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/"); - registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); - - /** swagger配置 */ - registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); - registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); - /** 文件下载映射配置,同下 */ -// registry.addResourceHandler(fileUploadProperties.getAccessUrl()).addResourceLocations("file:" + fileUploadProperties.getPath()); - } - - - /** - * 自定义拦截规则 - */ - @Override - public void addInterceptors(InterceptorRegistry registry) { -// registry.addInterceptor(new RepeatSubmitInterceptor() { -// @Override -// public boolean isRepeatSubmit(HttpServletRequest request) { -// return false; -// } -// }).addPathPatterns("/**") -// .excludePathPatterns("/emp/toLogin","/emp/login","/js/**","/css/**","/images/**"); - } - - /** - * 配置请求视图映射 - * @return - */ - @Bean - public InternalResourceViewResolver resourceViewResolver() - { - InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver(); - //请求视图文件的前缀地址 - internalResourceViewResolver.setPrefix("/WEB-INF/jsp/"); - //请求视图文件的后缀 - internalResourceViewResolver.setSuffix(".jsp"); - return internalResourceViewResolver; - } - - /** - * 视图配置 - * @param registry - */ - @Override - public void configureViewResolvers(ViewResolverRegistry registry) { - super.configureViewResolvers(registry); - registry.viewResolver(resourceViewResolver()); - /*registry.jsp("/WEB-INF/jsp/",".jsp");*/ - } - - -} \ No newline at end of file diff --git a/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/config/interceptor/MyInterceptor2.java b/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/config/interceptor/MyInterceptor2.java deleted file mode 100644 index 8051099477..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/config/interceptor/MyInterceptor2.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.jun.plugin.project.config.interceptor; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; -import org.springframework.web.servlet.HandlerInterceptor; -import org.springframework.web.servlet.ModelAndView; - -/** - * @createTime 2021年02月01日 14:00:00 - */ -@Component -public class MyInterceptor2 implements HandlerInterceptor { - private static final Logger logger = LoggerFactory.getLogger(MyInterceptor2.class); - @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { - logger.info("------------------ preHandle"); - request.setAttribute("startTime",System.currentTimeMillis()); - return true; - } - - - @Override - public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { - logger.info("------------------ postHandle"); - long startTime = (long) request.getAttribute("startTime"); - request.removeAttribute("startTime"); - logger.info("请求处理时间: " + (System.currentTimeMillis() - startTime) + "毫秒"); - } - - @Override - public void afterCompletion(HttpServletRequest request, HttpServletResponse response, - Object handler, Exception ex) { - logger.info("------------------ after"); - } -} \ No newline at end of file diff --git a/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/config/interceptor/MybatisExecutor2.java b/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/config/interceptor/MybatisExecutor2.java deleted file mode 100644 index 2b5943988c..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/java/com/jun/plugin/project/config/interceptor/MybatisExecutor2.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.jun.plugin.project.config.interceptor; - -//import com.fen.dou.entity.BaseEntity; -//import com.fen.dou.entity.User; -import lombok.extern.slf4j.Slf4j; -import org.apache.ibatis.executor.Executor; -import org.apache.ibatis.mapping.MappedStatement; -import org.apache.ibatis.mapping.SqlCommandType; -import org.apache.ibatis.plugin.*; -import org.springframework.stereotype.Component; - - -import java.util.Map; -import java.util.Properties; - -@Slf4j -@Intercepts({ @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }) }) -@Component -public class MybatisExecutor2 implements Interceptor { - @Override - @SuppressWarnings("unchecked") - public Object intercept(Invocation invocation) throws Throwable { - // 根据签名指定的args顺序获取具体的实现类 - // 1. 获取MappedStatement实例, 并获取当前SQL命令类型 - MappedStatement ms = (MappedStatement) invocation.getArgs()[0]; - SqlCommandType commandType = ms.getSqlCommandType(); - - // 2. 获取当前正在被操作的类, 有可能是Java Bean, 也可能是普通的操作对象, 比如普通的参数传递 - // 普通参数, 即是 @Param 包装或者原始 Map 对象, 普通参数会被 Mybatis 包装成 Map 对象 - // 即是 org.apache.ibatis.binding.MapperMethod$ParamMap - Object parameter = invocation.getArgs()[1]; - // 获取拦截器指定的方法类型, 通常需要拦截 update - String methodName = invocation.getMethod().getName(); - log.info("NormalPlugin, methodName; {}, commandType: {}", methodName, commandType); - - // 3. 获取当前用户信息 -// User user = new User(1,"yangcai","sssss"); - // 默认测试参数值 - int creator = 2, updater = 3; - - // 5. @Param 等包装类 - // 更新时指定某些字段的最新数据值 - if (parameter instanceof Map && commandType.equals(SqlCommandType.UPDATE)) { - // 遍历参数类型, 检查目标参数值是否存在对象中, 该方式需要应用编写有一些统一的规范 - // 否则均统一为实体对象, 就免去该重复操作 - Map map = (Map) parameter; - if (map.containsKey("creator")) { - map.put("creator", creator); - } - if (map.containsKey("updateTime")) { - map.put("updateTime", System.currentTimeMillis()); - } - } - // 6. 均不是需要被拦截的类型, 不做操作 - return invocation.proceed(); - } - - @Override - public Object plugin(Object target) { - return Plugin.wrap(target, this); - } - - @Override - public void setProperties(Properties properties) { - } -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/application-dev.yml b/java_project_template/jun_api_service_simple/src/main/resources/application-dev.yml deleted file mode 100644 index 63eaf17518..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/application-dev.yml +++ /dev/null @@ -1,51 +0,0 @@ -# 开发环境配置 -spring: - thymeleaf: - cache: false - datasource: - url: jdbc:mysql://localhost:3306/db_test?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2b8&zeroDateTimeBehavior=convertToNull - username: root - password: -# username: ENC(i9EHZ6vsnfpTeKGvHmH+fA==) -# password: ENC(KX2tfUq8cZG3IXeAwZgk5w==) - driver-class-name: com.mysql.cj.jdbc.Driver - redis: - host: localhost # Redis服务器地址 - database: 0 # Redis数据库索引(默认为0) - port: 6379 # Redis服务器连接端口 - password: # Redis服务器连接密码(默认为空) - jedis: - pool: - max-active: 8 # 连接池最大连接数(使用负值表示没有限制) - max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制) - max-idle: 8 # 连接池中的最大空闲连接 - min-idle: 0 # 连接池中的最小空闲连接 - timeout: 13000 # 连接超时时间(毫秒 -filepath: "D:\\files\\" -file: - #文件上传目录 绝对路径 末尾请加 / - path: D:/files/ #windows - #path: /home/data/files/ #linux - #文件预览、下载的url, 末尾请勿加 / - url: http://qiniu.hbqxcpa.cn/files - qiniuAccessKey: ts0n9OF16ekFkDkZTTlpmyPI-tP3HKQDyw_GR4o2 - qiniuBucketName: qixing-files - qiniuDomain: http://qiniu.hbqxcpa.cn - qiniuPrefix: upload - qiniuSecretKey: c-OjjwV3ZgzCQwxc6W_bsTFKuDg8qeyqohyJU0RL - type: 1 - - -# AES密码加密私钥(Base64加密) -encryptAESKey: V2FuZzkyNjQ1NGRTQkFQSUpXVA== -# JWT认证加密私钥(Base64加密) -encryptJWTKey: U0JBUElKV1RkV2FuZzkyNjQ1NA== -# AccessToken过期时间-5分钟-5*60(秒为单位) -accessTokenExpireTime: 300 -# RefreshToken过期时间-30分钟-30*60(秒为单位) -refreshTokenExpireTime: 1800 -# Shiro缓存过期时间-5分钟-5*60(秒为单位)(一般设置与AccessToken过期时间一致) -shiroCacheExpireTime: 300 - -knife4j: - production: true #生成环境禁用查看文档 \ No newline at end of file diff --git a/java_project_template/jun_api_service_simple/src/main/resources/application.yml b/java_project_template/jun_api_service_simple/src/main/resources/application.yml deleted file mode 100644 index 5a509669be..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/application.yml +++ /dev/null @@ -1,206 +0,0 @@ -# 端口 -server: - port: 9081 - compression: - enabled: true - min-response-size: 1KB - mime-types: application/json,application/xml,text/html,text/xml,text/plain,application/javascript,text/css - max-http-header-size: 102400 - tomcat: - uri-encoding: UTF-8 - servlet: - encoding: - charset: UTF-8 - force: true - enabled: true - -spring: - profiles: - active: dev -# active: prod - mvc: - throw-exception-if-no-handler-found: true -# static-path-pattern: /static/** - resources: - add-mappings: false - main: - allow-bean-definition-overriding: true - allow-circular-references: true - application: - name: jun-springboot-admin-layui - jackson: - date-format: yyyy-MM-dd HH:mm:ss - time-zone: GMT+8 - # 文件大小限制 - servlet: - multipart: - max-file-size: 100MB - max-request-size: 100MB - # redis token信息 - redis: - key: - prefix: - userToken: "user:token:" - passwordError: "user:password:error:" - permissionRefresh: "user:token:permissionRefresh:" - expire: - #userToken: 604800 # 7天 1*24*3600 - userToken: 86400 # 1天 1*24*3600 - passwordError: 3600 # 一个小时 - #permissionRefresh: 604800 # 7天 7*24*3600 - permissionRefresh: 86400 # 1天 1*24*3600 - allowMultipleLogin: true # 允许多处登陆 - -mybatis-plus: - configuration: - log-impl: org.apache.ibatis.logging.stdout.StdOutImpl - cache-enabled: false - mapper-locations: classpath:mapper/${project.database}/**/*.xml,classpath:mapper/*.xml - type-aliases-package: org.snaker.engine.entity - global-config: - db-config: - logic-delete-value: 0 - logic-not-delete-value: 1 - logic-delete-field: deleted - -#使用代码生成模块时 指定要生成的表存在于哪种数据库,可选值有【mysql、oracle、sqlServer】 -project: - database: mysql - datasource: - url: ${spring.datasource.url} - driver: ${spring.datasource.driver-class-name} - username: ${spring.datasource.username} - password: - groovy-api: - enable: true - servicename: jun-engine-api - context: /api - datasource: - dbtype: ${project.database} - url: ${spring.datasource.url} - username: ${spring.datasource.username} - driver: ${spring.datasource.driver-class-name} - password: - api_config: api_config - -jasypt: - algorithm: PBEWithMD5AndDES - encryptor: - password: 123456@@ - -shiro: - enable: true - -# 防止XSS攻击 -xss: - # 过滤开关 - enabled: true - # 排除链接(多个用逗号分隔) - excludes: - # 匹配链接 - urlPatterns: /system/*,/tool/* -# 工作流参数定义 -workflows: - list: - - processName: leave - flowName: 请假流程 - pageURl: oapomsworkmarksleave/list - tname: oa_poms_workmarks_leave - taskName: 的请假流程 - - processName: project - flowName: 立项流程 - pageURl: pjProject/list - tname: pj_project - taskName: 的立项流程 - - processName: contract - flowName: 业务约定书流程 - pageURl: pjContract/list - tname: pj_contract - taskName: 的合同审批流程 - - processName: plan - flowName: 项目计划流程 - pageURl: pjProjectPlan/list - tname: pj_project_plan - taskName: 的项目计划流程 - - processName: daily - flowName: 日报审批流程 - pageURl: pjProjectDaily/list - tname: pj_project_daily - taskName: 的日报流程 - - processName: draft - flowName: 底稿审批流程 - pageURl: pjProjectDraft/list - tname: pj_project_draft - taskName: 的底稿 - - processName: recheck - flowName: 复核审批流程 - pageURl: pjProjectReport/list - tname: pj_project_report - taskName: 的复核 - - processName: member - flowName: 成员结算审批流程 - pageURl: pjProjectMember/list - tname: pj_project_member - taskName: 的成员结算 - - processName: invoice - flowName: 开票审批流程 - pageURl: pjProjectInvoice/list - tname: pj_project_invoice - taskName: 的开票申请 - - processName: borrow - flowName: 项目借阅审批流程 - pageURl: pjProjectBorrow/list - tname: pj_project_borrow - taskName: 的项目借阅 - - processName: office - flowName: 办公用品领用审批流程 - pageURl: oaOfficeCount/list - tname: oa_office_count - taskName: 的领用申购 - - processName: office2 - flowName: 办公用品申购审批流程 - pageURl: oaOfficeCount2/list - tname: oa_office_count2 - taskName: 的领用申购 - - processName: outsite - flowName: 外出审批流程 - pageURl: oaPomsWorkmarksOutsite/list - tname: oa_poms_workmarks_outsite - taskName: 的外出申请 - - processName: expense - flowName: 报销审批流程 - pageURl: oaPomsWorkmarksClaimExpense/list - tname: oa_poms_workmarks_claim_expense - taskName: 的报销申请 - - processName: hire - flowName: 录用审批流程 - pageURl: hrUserHire/list - tname: hr_user_hire - taskName: 的录用申请电子流 - - processName: hire - flowName: 录用审批流程 - pageURl: hrUserHire/list - tname: hr_user_hire - taskName: 的录用申请电子流 - - processName: becomemember - flowName: 转正审批流程 - pageURl: hrUserBecomeMember/list - tname: hr_user_become_member - taskName: 的转正申请电子流 - - processName: dimission - flowName: 离职审批流程 - pageURl: hrUserDimission/list - tname: hr_user_dimission - taskName: 的离职申请电子流 - - processName: assessment - flowName: 考核电子流 - pageURl: hrAssessmentUserRecord/list - tname: hr_assessment_user_record - taskName: 的考核电子流 - - processName: customer - flowName: 客户审批电子流 - pageURl: pjCustomer/list - tname: pj_customer - taskName: 的客户审批电子流 - - processName: your_name - pageURl: your_id \ No newline at end of file diff --git a/java_project_template/jun_api_service_simple/src/main/resources/config.properties b/java_project_template/jun_api_service_simple/src/main/resources/config.properties deleted file mode 100644 index 155e8e5ddc..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/config.properties +++ /dev/null @@ -1,38 +0,0 @@ -################################################# step1 for modify datasource -jdbc.url=jdbc:mysql://localhost:3306/code_generator?useUnicode=true&characterEncoding=UTF-8&useSSL=true&serverTimezone=UTC&useInformationSchema=true -jdbc.username=root -jdbc.password= -jdbc.driver=com.mysql.cj.jdbc.Driver -#mysql 5.7 com.mysql.jdbc.Driver ,mysql 8.0 com.mysql.cj.jdbc.Driver - -################################################# step2 for modify author package project_path -authorName=Wujun -packageName=com.bjc.lcp.app1222 -project_path=D:/workspace/github/jun_springboot_api_service/jun_api_service_api_rest/main -#className=${className}Controller.subfix.ftl -#jsp namespace: web/${namespace}/${className}/list.jsp -template_path=src/main/resources/templates -javaPath=src/main/java -resourcesPath=src/main/resources -tableRemovePrefixes=T_AR,T_BD,T_CD,T_PD,T_CL,T_IP,T_LO,T_RI,T_EV,T_, -rowRemovePrefixes=S_,B_,I_,DT_,TS_,M_,F_,PK_I_N,PK_I_S - -################################################# -isLombok=true -isAutoImport=true -isWithPackage=true -isSwagger=true -isComment=true - -################################################# - -java.sql.Timestamp=Date -java.sql.Date=Date -java.sql.Time=Date -java.util.Date=Date -java.lang.Byte=Integer -java.lang.Short=Integer -java.lang.Integer=Integer -java.lang.Long=Long -java.lang.String=String -java.math.BigDecimal=java.math.BigDecimal \ No newline at end of file diff --git a/java_project_template/jun_api_service_simple/src/main/resources/files/tree.sql b/java_project_template/jun_api_service_simple/src/main/resources/files/tree.sql deleted file mode 100644 index eb75b6956f..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/files/tree.sql +++ /dev/null @@ -1,33 +0,0 @@ --- 省市区域字符串连接拼接测试 -create table t_tree(id varchar(3) , pid varchar(3) , name varchar(10)); -insert into t_tree values('002' , 0 , '浙江省'); -insert into t_tree values('001' , 0 , '广东省'); -insert into t_tree values('003' , '002' , '衢州市'); -insert into t_tree values('004' , '002' , '杭州市') ; -insert into t_tree values('005' , '002' , '湖州市'); -insert into t_tree values('006' , '002' , '嘉兴市') ; -insert into t_tree values('007' , '002' , '宁波市'); -insert into t_tree values('008' , '002' , '绍兴市') ; -insert into t_tree values('009' , '002' , '台州市'); -insert into t_tree values('010' , '002' , '温州市') ; -insert into t_tree values('011' , '002' , '丽水市'); -insert into t_tree values('012' , '002' , '金华市') ; -insert into t_tree values('013' , '002' , '舟山市'); -insert into t_tree values('014' , '004' , '上城区') ; -insert into t_tree values('015' , '004' , '下城区'); -insert into t_tree values('016' , '004' , '拱墅区') ; -insert into t_tree values('017' , '004' , '余杭区') ; -insert into t_tree values('018' , '011' , '金东区') ; -insert into t_tree values('019' , '001' , '广州市') ; -insert into t_tree values('020' , '001' , '深圳市') ; - - -with RECURSIVE cte as -( - select a.id,cast(a.name as varchar(100)) from t_tree a where id='002' - union all - select k.id,cast(c.name||'>'||k.name as varchar(100)) as name from t_tree k inner join cte c on c.id = k.pid -)select id,name from cte ; ------------------------------------ -SQL技巧:WITH RECURSIVE递归运算 -https://blog.51cto.com/u_15101584/2623141 \ No newline at end of file diff --git a/java_project_template/jun_api_service_simple/src/main/resources/logback-spring.xml b/java_project_template/jun_api_service_simple/src/main/resources/logback-spring.xml deleted file mode 100644 index 82058f74ca..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/logback-spring.xml +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - - - - - - - - - ${CONSOLE_LOG_PATTERN} - - - - - - - ${LOG_PATH}/${LOG_FILE} - - ${FILE_LOG_PATTERN} - - - ${LOG_PATH}/${LOG_HISTORY} - 30 - - - - - - - - 0 - 500 - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/java_project_template/jun_api_service_simple/src/main/resources/qiniu.properties b/java_project_template/jun_api_service_simple/src/main/resources/qiniu.properties deleted file mode 100644 index b95e022ef2..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/qiniu.properties +++ /dev/null @@ -1,6 +0,0 @@ -bucketName=qixing-files -domain=http://qiniu.hbqxcpa.cn -prefix=upload -type=1 -ACCESS_KEY=ts0n9OF16ekFkDkZTTlpmyPI-tP3HKQDyw_GR4o2 -SECRET_KEY=c-OjjwV3ZgzCQwxc6W_bsTFKuDg8qeyqohyJU0RL diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/beetlsql/beetlcontroller.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/beetlsql/beetlcontroller.ftl deleted file mode 100644 index 65be7585ab..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/beetlsql/beetlcontroller.ftl +++ /dev/null @@ -1,75 +0,0 @@ -<#if isAutoImport?exists && isAutoImport==true> -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RestController; -import java.util.List; -import java.util.Map; - -/** - * @description ${classInfo.classComment} - * @author ${authorName} - * @date ${.now?string('yyyy-MM-dd')} - */ -@RestController -@RequestMapping("/${classInfo.className?uncap_first}") -public class ${classInfo.className}Controller { - - @Autowired - private SQLManager sqlManager; - - /** - * 新增或编辑 - */ - @PostMapping("/save") - public Object save(${classInfo.className} ${classInfo.className?uncap_first}){ - ${classInfo.className} ${classInfo.className?uncap_first}=sqlManager.unique(${classInfo.className}.class,${classInfo.className?uncap_first}.getId()); - if(${classInfo.className?uncap_first}!=null){ - sqlManager.updateById(${classInfo.className?uncap_first}); - return ${returnUtilSuccess}("编辑成功"); - }else{ - sqlManager.insert(${classInfo.className?uncap_first}); - return ${returnUtilFailure}("保存成功"); - } - } - - /** - * 删除 - */ - @PostMapping("/delete") - public Object delete(int id){ - ${classInfo.className} ${classInfo.className?uncap_first}=sqlManager.unique(${classInfo.className}.class,id); - if(${classInfo.className?uncap_first}!=null){ - sqlManager.deleteById(id); - return ${returnUtilSuccess}("删除成功"); - }else{ - return ${returnUtilFailure}("没有找到该对象"); - } - } - - /** - * 查询 - */ - @PostMapping("/find") - public Object find(int id){ - ${classInfo.className} ${classInfo.className?uncap_first}=sqlManager.unique(${classInfo.className}.class,id); - if(${classInfo.className?uncap_first}!=null){ - return ${returnUtilSuccess}(${classInfo.className?uncap_first}); - }else{ - return ${returnUtilFailure}("没有找到该对象"); - } - } - - /** - * 分页查询 - */ - @PostMapping("/list") - public Object list(${classInfo.className} ${classInfo.className?uncap_first}, - @RequestParam(required = false, defaultValue = "0") int pageNumber, - @RequestParam(required = false, defaultValue = "10") int pageSize) { - List<${classInfo.className}> list = sqlManager.query(${classInfo.className}.class).select(); - return ${returnUtilSuccess}(list); - } - -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/beetlsql/beetlentity.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/beetlsql/beetlentity.ftl deleted file mode 100644 index de7e7609e4..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/beetlsql/beetlentity.ftl +++ /dev/null @@ -1,31 +0,0 @@ -<#if isAutoImport?exists && isAutoImport==true> -import java.io.Serializable; -import lombok.Data; -import java.util.Date; -import java.util.List; - -/** - * @description ${classInfo.classComment} - * @author ${authorName} - * @date ${.now?string('yyyy-MM-dd')} - */ -@Data<#if isSwagger?exists && isSwagger==true> -@ApiModel("${classInfo.classComment}") -public class ${classInfo.className} implements Serializable { - - private static final long serialVersionUID = 1L; - -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > - <#if isComment?exists && isComment==true>/** - * ${fieldItem.fieldComment} - */<#if isSwagger?exists && isSwagger==true> - @ApiModelProperty("${fieldItem.fieldComment}") - private ${fieldItem.fieldClass} ${fieldItem.fieldName}; - - - public ${classInfo.className}() { - } - - -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/beetlsql/beetlmd.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/beetlsql/beetlmd.ftl deleted file mode 100644 index 2dcdb64ac4..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/beetlsql/beetlmd.ftl +++ /dev/null @@ -1,31 +0,0 @@ -sample -=== - -select #use("cols")# from ${classInfo.tableName} where #use("condition")# - -cols -=== -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> - <#list classInfo.fieldList as fieldItem > - `${fieldItem.columnName}`<#if fieldItem_has_next>, - - - -updateSample -=== -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> - <#list classInfo.fieldList as fieldItem > - `${fieldItem.columnName}=#${fieldItem.fieldName}#`<#if fieldItem_has_next>, - - - -condition -=== - 1 = 1 -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> - <#list classInfo.fieldList as fieldItem > - @if(!isEmpty(${fieldItem.fieldName})){ - and `${fieldItem.columnName}`=#${fieldItem.fieldName}# - @} - - diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/common-mapper/tkentity.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/common-mapper/tkentity.ftl deleted file mode 100644 index 742dcb2711..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/common-mapper/tkentity.ftl +++ /dev/null @@ -1,50 +0,0 @@ -<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.entity; - -<#if isAutoImport?exists && isAutoImport==true> -<#if isLombok?exists && isLombok==true>import lombok.Data; -import java.util.Date; -import java.util.List; -import java.io.Serializable; -import javax.persistence.*; -<#if isSwagger?exists && isSwagger==true> -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * @description ${classInfo.classComment} - * @author ${authorName} - * @date ${.now?string('yyyy-MM-dd')} - */ -<#if isLombok?exists && isLombok==true>@Data -<#if isComment?exists && isComment==true>@Table(name="${classInfo.originTableName}")<#if isSwagger?exists && isSwagger==true> -@ApiModel("${classInfo.classComment}") -public class ${classInfo.className} implements Serializable { - - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > - <#if isComment?exists && isComment==true>/** - * ${fieldItem.fieldComment} - */<#if isSwagger?exists && isSwagger==true> - @ApiModelProperty("${fieldItem.fieldComment}") - <#if isComment?exists && isComment==true>@Column(name="${fieldItem.columnName}") - private ${fieldItem.fieldClass} ${fieldItem.fieldName}; - - - public ${classInfo.className}() { - } - - -<#if isLombok?exists && isLombok==false> - public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { - return ${fieldItem.fieldName}; - } - - public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { - this.${fieldItem.fieldName} = ${fieldItem.fieldName}; - } - -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/common-mapper/tkmapper.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/common-mapper/tkmapper.ftl deleted file mode 100644 index 3fdb960596..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/common-mapper/tkmapper.ftl +++ /dev/null @@ -1,16 +0,0 @@ -<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.mapper; -<#if isAutoImport?exists && isAutoImport==true> -import tk.mybatis.mapper.common.Mapper; -import org.apache.ibatis.annotations.Mapper; -import ${packageName}.entity.${classInfo.className}; - -/** - * @description ${classInfo.classComment}Mapper - * @author ${authorName} - * @date ${.now?string('yyyy-MM-dd')} - */ -@Mapper -public interface ${classInfo.className}Mapper extends Mapper<${classInfo.className}> { - - -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/controller.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/controller.ftl deleted file mode 100644 index 0b928a89f6..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/controller.ftl +++ /dev/null @@ -1,73 +0,0 @@ -package ${packageController}; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; - -import ${packageModel}.${classInfo.className}; -import ${packageService}.${classInfo.className}Service; -import com.jun.plugin.codegenerator.admin.model.ReturnT; - -import javax.annotation.Resource; -import javax.servlet.http.HttpServletRequest; -import java.util.List; -import java.util.Map; - -/** -* ${classInfo.classComment} -* -* Created by wujun on '${.now?string('yyyy-MM-dd HH:mm:ss')}'. -*/ -@Controller -public class ${classInfo.className}Controller { - - @Resource - private ${classInfo.className}Service ${classInfo.className?uncap_first}Service; - - /** - * 新增 - */ - @RequestMapping("/insert") - @ResponseBody - public ReturnT insert(${classInfo.className} ${classInfo.className?uncap_first}){ - return ${classInfo.className?uncap_first}Service.insert(${classInfo.className?uncap_first}); - } - - /** - * 删除 - */ - @RequestMapping("/delete") - @ResponseBody - public ReturnT delete(int id){ - return ${classInfo.className?uncap_first}Service.delete(id); - } - - /** - * 更新 - */ - @RequestMapping("/update") - @ResponseBody - public ReturnT update(${classInfo.className} ${classInfo.className?uncap_first}){ - return ${classInfo.className?uncap_first}Service.update(${classInfo.className?uncap_first}); - } - - /** - * Load查询 - */ - @RequestMapping("/load") - @ResponseBody - public ${classInfo.className} load(int id){ - return ${classInfo.className?uncap_first}Service.load(id); - } - - /** - * 分页查询 - */ - @RequestMapping("/pageList") - @ResponseBody - public Map pageList(@RequestParam(required = false, defaultValue = "0") int offset, - @RequestParam(required = false, defaultValue = "10") int pagesize) { - return ${classInfo.className?uncap_first}Service.pageList(offset, pagesize); - } - -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/dao.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/dao.ftl deleted file mode 100644 index 6ed153d427..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/dao.ftl +++ /dev/null @@ -1,49 +0,0 @@ -package ${packageDao}; - -import org.apache.ibatis.annotations.Param; -import org.springframework.stereotype.Component; -import ${packageModel}.${classInfo.className}; - -import java.util.List; - -/** -* ${classInfo.classComment} -* -* Created by wujun on '${.now?string('yyyy-MM-dd HH:mm:ss')}'. -*/ -@Component -public interface ${classInfo.className}Dao { - - /** - * 新增 - */ - public int insert(@Param("${classInfo.className?uncap_first}") ${classInfo.className} ${classInfo.className?uncap_first}); - - /** - * 删除 - */ - public int delete(@Param("id") int id); - - /** - * 更新 - */ - public int update(@Param("${classInfo.className?uncap_first}") ${classInfo.className} ${classInfo.className?uncap_first}); - - /** - * Load查询 - */ - public ${classInfo.className} load(@Param("id") int id); - - /** - * 分页查询Data - */ - public List<${classInfo.className}> pageList(@Param("offset") int offset, - @Param("pagesize") int pagesize); - - /** - * 分页查询Count - */ - public int pageListCount(@Param("offset") int offset, - @Param("pagesize") int pagesize); - -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/jdbc-template/jtdao.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/jdbc-template/jtdao.ftl deleted file mode 100644 index 681518fb19..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/jdbc-template/jtdao.ftl +++ /dev/null @@ -1,21 +0,0 @@ -<#if isAutoImport?exists && isAutoImport==true> -import java.util.List; - -/** - * @description ${classInfo.classComment} - * @author ${authorName} - * @date ${.now?string('yyyy-MM-dd')} - */ -public interface I${classInfo.className}DAO { - - int add(${classInfo.className} ${classInfo.className?uncap_first}); - - int update(${classInfo.className} ${classInfo.className?uncap_first}); - - int delete(int id); - - ${classInfo.className} findById(int id); - - List<${classInfo.className}> findAllList(Map param); - -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/jdbc-template/jtdaoimpl.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/jdbc-template/jtdaoimpl.ftl deleted file mode 100644 index f3e93889eb..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/jdbc-template/jtdaoimpl.ftl +++ /dev/null @@ -1,61 +0,0 @@ -<#if isAutoImport?exists && isAutoImport==true> -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.jdbc.core.BeanPropertyRowMapper; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Repository; -import java.util.List; - - -/** - * @description ${classInfo.classComment} - * @author ${authorName} - * @date ${.now?string('yyyy-MM-dd')} - */ -@Repository -public class ${classInfo.className}DaoImpl implements I${classInfo.className}Dao{ - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Override - public int add(${classInfo.className} ${classInfo.className?uncap_first}) { - return jdbcTemplate.update("insert into ${classInfo.tableName} (<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0><#list classInfo.fieldList as fieldItem >${fieldItem.columnName}<#if fieldItem_has_next>, ) values (<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0><#list classInfo.fieldList as fieldItem >?<#if fieldItem_has_next>, )", - <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0><#list classInfo.fieldList as fieldItem >${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}()<#if fieldItem_has_next>,); - } - - @Override - public int update(${classInfo.className} ${classInfo.className?uncap_first}) { - return jdbcTemplate.update("UPDATE ${classInfo.tableName} SET <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0><#list classInfo.fieldList as fieldItem ><#if fieldItem_index gt 0 >${fieldItem.columnName}=?<#if fieldItem_has_next>," - +" where <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0><#list classInfo.fieldList as fieldItem ><#if fieldItem_index = 0>${fieldItem.columnName}=?<#break >", - <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> - <#list classInfo.fieldList as fieldItem ><#if fieldItem_index gt 0 >${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}(), - <#list classInfo.fieldList as fieldItem ><#if fieldItem_index = 0 >${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}() - ); - } - - @Override - public int delete(int id) { - return jdbcTemplate.update("DELETE from ${classInfo.tableName} where <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0><#list classInfo.fieldList as fieldItem ><#if fieldItem_index = 0>${fieldItem.columnName}=?<#break >",id); - } - - @Override - public ${classInfo.className} findById(int id) { - List<${classInfo.className}> list = jdbcTemplate.query("select * from ${classInfo.tableName} where <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0><#list classInfo.fieldList as fieldItem ><#if fieldItem_index = 0>${fieldItem.columnName}=?<#break >", new Object[]{id}, new BeanPropertyRowMapper<${classInfo.className}>(${classInfo.className}.class)); - if(list!=null && !list.isEmpty() ){ - return list.get(0); - }else{ - return null; - } - } - - @Override - public List<${classInfo.className}> findAllList(Map params) { - List<${classInfo.className}> list = jdbcTemplate.query("select * from ${classInfo.tableName}", new Object[]{}, new BeanPropertyRowMapper<${classInfo.className}>(${classInfo.className}.class)); - if(list!=null && !list.isEmpty() ){ - return list; - }else{ - return Collections.emptyList(); - } - } - -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/jpa/entity.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/jpa/entity.ftl deleted file mode 100644 index ceb1456dc8..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/jpa/entity.ftl +++ /dev/null @@ -1,55 +0,0 @@ -<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.entity; - -<#if isAutoImport?exists && isAutoImport==true> -<#if isLombok?exists && isLombok==true>import lombok.Data; -import java.util.Date; -import java.util.List; -import java.io.Serializable; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -<#if isSwagger?exists && isSwagger==true> -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * @description ${classInfo.classComment} - * @author ${authorName} - * @date ${.now?string('yyyy-MM-dd')} - */ -@Entity -<#if isLombok?exists && isLombok==true>@Data -<#if isComment?exists && isComment==true>@Table(name="${classInfo.tableName}")<#if isSwagger?exists && isSwagger==true> -@ApiModel("${classInfo.classComment}") -public class ${classInfo.className} implements Serializable { - - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > - <#if isComment?exists && isComment==true>/** - * ${fieldItem.fieldComment} - */<#if isSwagger?exists && isSwagger==true> - @ApiModelProperty("${fieldItem.fieldComment}") - <#if isComment?exists && isComment==true>@Column(name="${fieldItem.columnName}") - private ${fieldItem.fieldClass} ${fieldItem.fieldName}; - - - public ${classInfo.className}() { - } - - -<#if isLombok?exists && isLombok==false> - public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { - return ${fieldItem.fieldName}; - } - - public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { - this.${fieldItem.fieldName} = ${fieldItem.fieldName}; - } - -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/jpa/jpacontroller.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/jpa/jpacontroller.ftl deleted file mode 100644 index c6c98299b6..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/jpa/jpacontroller.ftl +++ /dev/null @@ -1,83 +0,0 @@ -<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.controller; -<#if isAutoImport?exists && isAutoImport==true> -import ${packageName}.entity.${classInfo.className}; -import ${packageName}.repository.${classInfo.className}Repository; -import org.springframework.data.domain.Example; -import org.springframework.data.domain.Pageable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.data.domain.ExampleMatcher; -import org.springframework.data.domain.PageRequest; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RestController; -import java.util.List; -import java.util.Map; - -/** - * @description ${classInfo.classComment} - * @author ${authorName} - * @date ${.now?string('yyyy-MM-dd')} - */ -@RestController -@RequestMapping("/${classInfo.className?uncap_first}") -public class ${classInfo.className}Controller { - - @Autowired - private ${classInfo.className}Repository ${classInfo.className?uncap_first}Repository; - - /** - * 新增或编辑 - */ - @PostMapping("/save") - public Object save(${classInfo.className} ${classInfo.className?uncap_first}){ - return ${classInfo.className?uncap_first}Repository.save(${classInfo.className?uncap_first}); - } - - /** - * 删除 - */ - @PostMapping("/delete") - public Object delete(int id){ - Optional<${classInfo.className}> ${classInfo.className?uncap_first}=${classInfo.className?uncap_first}Repository.findById(id); - if(${classInfo.className?uncap_first}.isPresent()){ - ${classInfo.className?uncap_first}Repository.deleteById(id); - return ${returnUtilSuccess}("删除成功"); - }else{ - return ${returnUtilFailure}("没有找到该对象"); - } - } - - /** - * 查询 - */ - @PostMapping("/find") - public Object find(int id){ - Optional<${classInfo.className}> ${classInfo.className?uncap_first}=${classInfo.className?uncap_first}Repository.findById(id); - if(${classInfo.className?uncap_first}.isPresent()){ - return ${returnUtilSuccess}(${classInfo.className?uncap_first}.get()); - }else{ - return ${returnUtilFailure}("没有找到该对象"); - } - } - - /** - * 分页查询 - */ - @PostMapping("/list") - public Object list(${classInfo.className} ${classInfo.className?uncap_first}, - @RequestParam(required = false, defaultValue = "0") int pageNumber, - @RequestParam(required = false, defaultValue = "10") int pageSize) { - - //创建匹配器,需要查询条件请修改此处代码 - ExampleMatcher matcher = ExampleMatcher.matchingAll(); - - //创建实例 - Example<${classInfo.className}> example = Example.of(${classInfo.className?uncap_first}, matcher); - //分页构造 - Pageable pageable = PageRequest.of(pageNumber,pageSize); - - return ${classInfo.className?uncap_first}Repository.findAll(example, pageable); - } - -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/jpa/repository.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/jpa/repository.ftl deleted file mode 100644 index c2a8affb8d..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/jpa/repository.ftl +++ /dev/null @@ -1,26 +0,0 @@ -<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.mapper; -<#if isAutoImport?exists && isAutoImport==true>import ${packageName}.entity.${classInfo.className}; - -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> - <#list classInfo.fieldList as fieldItem > - <#if fieldItem.fieldClass == "Date"> - <#assign importDdate = true /> - - - -import java.util.List; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.stereotype.Repository; - -/** - * @description ${classInfo.classComment} - * @author ${authorName} - * @date ${.now?string('yyyy-MM-dd')} - */ -@Repository -public interface ${classInfo.className}Repository extends JpaRepository<${classInfo.className},Integer> { - - - -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/model.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/model.ftl deleted file mode 100644 index 7a28cc64ad..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/model.ftl +++ /dev/null @@ -1,45 +0,0 @@ -package ${packageModel}; - -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> - <#list classInfo.fieldList as fieldItem > - <#if fieldItem.fieldClass == "Date"> - <#assign importDdate = true /> - - - -import java.io.Serializable; -<#if importDdate?? && importDdate> -import java.util.Date; - - -/** -* ${classInfo.classComment} -* -* Created by wujun on '${.now?string('yyyy-MM-dd HH:mm:ss')}'. -*/ -public class ${classInfo.className} implements Serializable { - private static final long serialVersionUID = 42L; - -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > - /** - * ${fieldItem.fieldComment} - */ - private ${fieldItem.fieldClass} ${fieldItem.fieldName}; - - - - -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem> - public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { - return ${fieldItem.fieldName}; - } - - public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { - this.${fieldItem.fieldName} = ${fieldItem.fieldName}; - } - - - -} \ No newline at end of file diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/controller.java.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/controller.java.ftl deleted file mode 100644 index 14d4b9fa3c..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/controller.java.ftl +++ /dev/null @@ -1,231 +0,0 @@ -<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.controller; -<#if isAutoImport?exists && isAutoImport==true> -import ${packageName}.vo.${classInfo.className}Vo; -import ${packageName}.dto.${classInfo.className}Dto; -import ${packageName}.mapper.${classInfo.className}Mapper; -import ${packageName}.entity.${classInfo.className}Entity; -import ${packageName}.service.${classInfo.className}Service; -//import com.bjc.lcp.common.cnt.enums.CntTableNameEnum; -//import com.bjc.lcp.common.cnt.service.CntService; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import lombok.extern.slf4j.Slf4j; -import org.springframework.validation.annotation.Validated; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; -import org.springframework.beans.BeanUtils; -import org.springframework.util.ObjectUtils; -<#--import org.apache.shiro.authz.annotation.RequiresPermissions;--> -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.baomidou.mybatisplus.core.metadata.IPage; -import com.baomidou.mybatisplus.core.toolkit.Wrappers; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import org.springframework.web.servlet.ModelAndView; -import com.jun.plugin.common.Result; -import javax.annotation.Resource; -import java.util.Arrays; -import java.util.Date; -import java.util.List; -import java.util.Map; - -/** -* @Version666 -* @description ${classInfo.classComment} -* @author ${authorName} -* @date ${.now?string('yyyy-MM-dd')} -*/ -@Api(tags = "${classInfo.classComment}-管理") -@Slf4j -@RestController -@RequestMapping("/${classInfo.className?uncap_first}") -public class ${classInfo.className}Controller { - - @Resource - private ${classInfo.className}Service ${classInfo.className?uncap_first}Service; - - @Resource - private ${classInfo.className}Mapper ${classInfo.className?uncap_first}Mapper; - - @ApiOperation(value = "${classInfo.classComment}-新增") - @PostMapping("/add") - //@RequiresPermissions("${classInfo.className?uncap_first}:add") - public Result add(@Validated(${classInfo.className}Vo.Create.class) @RequestBody ${classInfo.className}Vo vo) { - ${classInfo.className}Dto dto = new ${classInfo.className}Dto(); - BeanUtils.copyProperties(vo, dto); -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > -<#if fieldItem.nullable==true> - if (ObjectUtils.isEmpty(dto.get${fieldItem.fieldName?cap_first}())) { - return Result.fail("参数[${fieldItem.fieldName}]不能为空"); - } - - - - LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > -<#if fieldItem.isPrimaryKey==true> - queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); - - - - List<${classInfo.className}Entity> list = ${classInfo.className?uncap_first}Service.list(queryWrapper); - if (list.size() > 0) { - return Result.fail("数据已存在"); - } - ${classInfo.className}Entity entity = new ${classInfo.className}Entity(); - - BeanUtils.copyProperties(dto, entity); - return Result.success(${classInfo.className?uncap_first}Service.save(entity)); - } - - @ApiOperation(value = "${classInfo.classComment}-删除") - @DeleteMapping("/remove") - //@RequiresPermissions("${classInfo.className?uncap_first}:remove") - public Result delete(@Validated(${classInfo.className}Vo.Delete.class) @RequestBody ${classInfo.className}Vo vo) { - ${classInfo.className}Dto dto = new ${classInfo.className}Dto(); - BeanUtils.copyProperties(vo, dto); -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > -<#if fieldItem.isPrimaryKey==true> - if (ObjectUtils.isEmpty(dto.get${fieldItem.fieldName?cap_first}())) { - return Result.fail("参数[${fieldItem.fieldName}]不能为空"); - } - - - - LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > -<#if fieldItem.isPrimaryKey==true> - queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); - - - - return Result.success(${classInfo.className?uncap_first}Service.remove(queryWrapper)); - } - - @ApiOperation(value = "${classInfo.classComment}-删除") - @DeleteMapping("/delete") - //@RequiresPermissions("${classInfo.className?uncap_first}:delete") - public Result delete(@RequestBody @ApiParam(value = "id集合") List ids) { - return Result.success(${classInfo.className?uncap_first}Service.removeByIds(ids)); - } - - - @ApiOperation(value = "${classInfo.classComment}-更新") - @PutMapping("/update") - //@RequiresPermissions("${classInfo.className?uncap_first}:update") - public Result update(@Validated(${classInfo.className}Vo.Update.class) @RequestBody ${classInfo.className}Vo vo) { - ${classInfo.className}Dto dto = new ${classInfo.className}Dto(); - BeanUtils.copyProperties(vo, dto); -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > -<#if fieldItem.isPrimaryKey==true> - if (ObjectUtils.isEmpty(dto.get${fieldItem.fieldName?cap_first}())) { - return Result.fail("参数[${fieldItem.fieldName}]不能为空"); - } - - - - LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > -<#if fieldItem.isPrimaryKey==true> - queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); - - - - ${classInfo.className}Entity entity = ${classInfo.className?uncap_first}Service.getOne(queryWrapper);; - if (entity == null) { - //return Result.fail("数据不存在"); - entity = new ${classInfo.className}Entity(); - } - BeanUtils.copyProperties(dto, entity); - return Result.success(${classInfo.className?uncap_first}Service.saveOrUpdate(entity)); - } - - - - @ApiOperation(value = "${classInfo.classComment}-查询单条") - @RequestMapping(value = "/getOne",method = {RequestMethod.GET,RequestMethod.POST}) - //@RequiresPermissions("${classInfo.className?uncap_first}:getOne") - public Result getOne(@RequestBody ${classInfo.className}Vo vo) { - ${classInfo.className}Dto dto = new ${classInfo.className}Dto(); - BeanUtils.copyProperties(vo, dto); -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > -<#if fieldItem.isPrimaryKey==true> - if (ObjectUtils.isEmpty(dto.get${fieldItem.fieldName?cap_first}())) { - return Result.fail("参数[${fieldItem.fieldName}]不能为空"); - } - - - - LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > -<#if fieldItem.isPrimaryKey==true> - queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); - - - - ${classInfo.className}Entity entity = ${classInfo.className?uncap_first}Service.getOne(queryWrapper);; - return Result.success(entity); - } - - - - - @ApiOperation(value = "${classInfo.classComment}-查询列表分页数据") - @RequestMapping(value = "/listByPage",method = {RequestMethod.GET,RequestMethod.POST}) - //@RequiresPermissions("${classInfo.className?uncap_first}:listByPage") - public Result listByPage(@RequestBody ${classInfo.className}Vo ${classInfo.className?uncap_first}) { - Page page = new Page(${classInfo.className?uncap_first}.getPage(), ${classInfo.className?uncap_first}.getLimit()); - ${classInfo.className}Dto dto = new ${classInfo.className}Dto(); - BeanUtils.copyProperties(${classInfo.className?uncap_first}, dto); - LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > -<#if fieldItem.isPrimaryKey==true> - if (!ObjectUtils.isEmpty(${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}())) { - queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); - } -<#else> - if (!ObjectUtils.isEmpty(${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}())) { - queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); - } - - - - IPage<${classInfo.className}Entity> iPage = ${classInfo.className?uncap_first}Service.page(page, queryWrapper); - return Result.success(iPage); - } - - @ApiOperation(value = "${classInfo.classComment}-查询全部列表数据") - @RequestMapping(value = "/list",method = {RequestMethod.GET,RequestMethod.POST}) - //@RequiresPermissions("${classInfo.className?uncap_first}:list") - public Result findListByPage(@RequestBody ${classInfo.className}Vo ${classInfo.className?uncap_first}) { - LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > -<#if fieldItem.isPrimaryKey==true> - if (!ObjectUtils.isEmpty(${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}())) { - queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, ${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}()); - } -<#else> - if (!ObjectUtils.isEmpty(${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}())) { - queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, ${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}()); - } - - - - List<${classInfo.className}Entity> list = ${classInfo.className?uncap_first}Service.list(queryWrapper); - return Result.success(list); - } - - -} - diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/dto.java.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/dto.java.ftl deleted file mode 100644 index 918648f836..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/dto.java.ftl +++ /dev/null @@ -1,44 +0,0 @@ -<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.dto; - -<#if isAutoImport?exists && isAutoImport==true> -<#if isLombok?exists && isLombok==true>import lombok.Data; -import java.util.Date; -import java.util.List; -import java.io.Serializable; -import com.jun.plugin.common.entity.BaseEntity; -<#if isSwagger?exists && isSwagger==true> -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * @description ${classInfo.classComment} - * @author ${authorName} - * @date ${.now?string('yyyy-MM-dd')} - */ -<#if isLombok?exists && isLombok==true>@Data<#if isSwagger?exists && isSwagger==true> -@ApiModel("${classInfo.classComment}") -public class ${classInfo.className}Dto extends BaseEntity implements Serializable { - - private static final long serialVersionUID = 1L; - -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > - <#if isComment?exists && isComment==true>/** - * ${fieldItem.fieldComment} - */<#if isSwagger?exists && isSwagger==true> - @ApiModelProperty("${fieldItem.fieldComment}") - private ${fieldItem.fieldClass} ${fieldItem.fieldName}; - -<#if isLombok?exists && isLombok==false> - public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { - return ${fieldItem.fieldName}; - } - - public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { - this.${fieldItem.fieldName} = ${fieldItem.fieldName}; - } - - - - public ${classInfo.className}Dto() {} -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/edit.html.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/edit.html.ftl deleted file mode 100644 index 6299a1b242..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/edit.html.ftl +++ /dev/null @@ -1,64 +0,0 @@ - - - -
- - - -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> - <#list classInfo.fieldList as fieldItem > -
- -
- - <#--${fieldItem.fieldComment}--> -
-
- - - -
-
- -
-
-
- - - - - \ No newline at end of file diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/entity.java.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/entity.java.ftl deleted file mode 100644 index 612f07aa81..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/entity.java.ftl +++ /dev/null @@ -1,51 +0,0 @@ -<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.entity; - -<#if isAutoImport?exists && isAutoImport==true> -<#if isLombok?exists && isLombok==true>import lombok.Data; -import java.util.Date; -import java.util.List; -import java.io.Serializable; -import com.baomidou.mybatisplus.annotation.IdType; -import com.baomidou.mybatisplus.annotation.TableId; -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableName; -import com.jun.plugin.common.entity.BaseEntity; -<#assign isSwagger=false /> -<#if isSwagger?exists && isSwagger==true> -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * @description ${classInfo.classComment} - * @author ${authorName} - * @date ${.now?string('yyyy-MM-dd')} - */ -<#if isLombok?exists && isLombok==true>@Data<#if isSwagger?exists && isSwagger==true> -@ApiModel("${classInfo.classComment}") -@TableName("${classInfo.tableName}") -public class ${classInfo.className}Entity extends BaseEntity implements Serializable { - - private static final long serialVersionUID = 1L; - -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > - <#if isComment?exists && isComment==true>/** - * ${fieldItem.fieldComment} - */<#if isSwagger?exists && isSwagger==true> - @ApiModelProperty("${fieldItem.fieldComment}") - <#if fieldItem.isPrimaryKey==true>@TableId(value = "${fieldItem.columnName}" ,type = IdType.AUTO )<#else>@TableField(value = "${fieldItem.columnName}" ) - private ${fieldItem.fieldClass} ${fieldItem.fieldName}; - -<#if isLombok?exists && isLombok==false> - public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { - return ${fieldItem.fieldName}; - } - - public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { - this.${fieldItem.fieldName} = ${fieldItem.fieldName}; - } - - - - public ${classInfo.className}Entity() {} -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/list.html.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/list.html.ftl deleted file mode 100644 index d36251c328..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/list.html.ftl +++ /dev/null @@ -1,266 +0,0 @@ - - - - - - - XXXX管理 - - - - - - -
-
-
- -
-
- <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> - <#list classInfo.fieldList as fieldItem > - <#if fieldItem.nullable==false> -
- -
- -
-
- - - - <#--
- -
- -
-
-
- -
- -
-
-
- -
- -
-
--> -
  - -
-
-
- -
-
-
-
- - - - - - - - - - - - - - \ No newline at end of file diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/list.html.v1.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/list.html.v1.ftl deleted file mode 100644 index 3fb1442734..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/list.html.v1.ftl +++ /dev/null @@ -1,234 +0,0 @@ - - - - - - - XXX管理 - - - - -
-
- -
- 搜索信息 -
-
-
-
- -
- -
-
-
- -
- -
-
-
- -
-
-
-
-
- - - -
- - - - - -
-
- - - - - - - - - - \ No newline at end of file diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/list.html.vm.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/list.html.vm.ftl deleted file mode 100644 index 447a9cae33..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/list.html.vm.ftl +++ /dev/null @@ -1,604 +0,0 @@ - - - - - Title - - - - - - - - - - - -
-
-
-
- 在此你可以对${comments}进行编辑!若有操作及使用问题及常见“问题”:请查看操作手册! -
-
-
-###遍历查询条件 -#foreach($column in $columns) -#if($column.columnName != $pk.columnName && $column.isNull == 'NO') -##跳过循环,新增及修改时间字段,注解支持,不展示 -#if($column.columnName.toString().contains("create") || $column.columnName.toString().contains("deleted") || $column.columnName.toString().contains("update")) - #break -#end -#if($column.dataType == 'datetime') -
- -
-#else -
- -
-#end -#end -#end -
- - -
-
-
- -
-
-
-
- - - - - - - - - - - - - - \ No newline at end of file diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/mapper.java.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/mapper.java.ftl deleted file mode 100644 index c6e239c8b9..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/mapper.java.ftl +++ /dev/null @@ -1,41 +0,0 @@ -<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.mapper; -<#if isAutoImport?exists && isAutoImport==true> -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Select; -import ${packageName}.entity.${classInfo.className}Entity; -import java.util.List; - -/** - * @description ${classInfo.classComment}Mapper - * @author ${authorName} - * @date ${.now?string('yyyy-MM-dd')} - */ -@Mapper -public interface ${classInfo.className}Mapper extends BaseMapper<${classInfo.className}Entity> { - - @Select( - "") - List<${classInfo.className}Entity> pageAll(${classInfo.className}Entity dto,int page,int limit); - - @Select("") - int countAll(${classInfo.className}Entity dto); - - @Select("SELECT count(1) from ${classInfo.tableName} ") - int countAll(); - -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/menu.sql.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/menu.sql.ftl deleted file mode 100644 index 2b3193a3f3..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/menu.sql.ftl +++ /dev/null @@ -1,17 +0,0 @@ --- 菜单SQL -INSERT INTO `sys_menu` (`parent_id`, `name`, `url`, `perms`, `type`, `icon`, `order_num`) -VALUES ('1', '${classInfo.classComment}', 'generator/${classInfo.className?uncap_first}', NULL, '1', 'config', '6'); - --- 按钮父菜单ID -set @parentId = @@identity; - --- 菜单对应按钮SQL -INSERT INTO `sys_menu` (`parent_id`, `name`, `url`, `perms`, `type`, `icon`, `order_num`) -SELECT @parentId, '查看', null, 'generator:${classInfo.className?uncap_first}:list,generator:${classInfo.className?uncap_first}:info', '2', null, '6'; -INSERT INTO `sys_menu` (`parent_id`, `name`, `url`, `perms`, `type`, `icon`, `order_num`) -SELECT @parentId, '新增', null, 'generator:${classInfo.className?uncap_first}:save', '2', null, '6'; -INSERT INTO `sys_menu` (`parent_id`, `name`, `url`, `perms`, `type`, `icon`, `order_num`) -SELECT @parentId, '修改', null, 'generator:${classInfo.className?uncap_first}:update', '2', null, '6'; -INSERT INTO `sys_menu` (`parent_id`, `name`, `url`, `perms`, `type`, `icon`, `order_num`) -SELECT @parentId, '删除', null, 'generator:${classInfo.className?uncap_first}:delete', '2', null, '6'; - diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/service.impl.java.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/service.impl.java.ftl deleted file mode 100644 index 6b3a91a117..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/service.impl.java.ftl +++ /dev/null @@ -1,26 +0,0 @@ -<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.service.impl; -<#if isAutoImport?exists && isAutoImport==true> -import org.springframework.stereotype.Service; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import ${packageName}.entity.${classInfo.className}Entity; -import ${packageName}.mapper.${classInfo.className}Mapper; -import ${packageName}.service.${classInfo.className}Service; - - -/** - * @description ${classInfo.classComment}服务层实现 - * @author ${authorName} - * @date ${.now?string('yyyy-MM-dd')} - */ -@Service -public class ${classInfo.className}ServiceImpl extends ServiceImpl<${classInfo.className}Mapper, ${classInfo.className}Entity> implements ${classInfo.className}Service { - - @Autowired - private ${classInfo.className}Mapper ${classInfo.className?uncap_first}Mapper; - -} - - - diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/service.java.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/service.java.ftl deleted file mode 100644 index 76483b1fe6..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/service.java.ftl +++ /dev/null @@ -1,16 +0,0 @@ -<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.service; -<#if isAutoImport?exists && isAutoImport==true> -import org.springframework.stereotype.Service; -import com.baomidou.mybatisplus.extension.service.IService; - -import ${packageName}.entity.${classInfo.className}Entity; - -/** - * @description ${classInfo.classComment}服务层 - * @author ${authorName} - * @date ${.now?string('yyyy-MM-dd')} - */ -public interface ${classInfo.className}Service extends IService<${classInfo.className}Entity> { - - -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/vo.java.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/vo.java.ftl deleted file mode 100644 index 77144a1652..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-single/vo.java.ftl +++ /dev/null @@ -1,56 +0,0 @@ -<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.vo; - -<#if isAutoImport?exists && isAutoImport==true> -<#if isLombok?exists && isLombok==true>import lombok.Data; -import java.util.Date; -import java.util.List; -import java.io.Serializable; -import io.swagger.annotations.ApiModelProperty; -import lombok.Data; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; -import java.io.Serializable; -import com.jun.plugin.common.entity.BaseEntity; -<#if isSwagger?exists && isSwagger==true> -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * @description ${classInfo.classComment} - * @author ${authorName} - * @date ${.now?string('yyyy-MM-dd')} - */ -<#if isLombok?exists && isLombok==true>@Data<#if isSwagger?exists && isSwagger==true> -@ApiModel("${classInfo.classComment}") -public class ${classInfo.className}Vo extends BaseEntity implements Serializable { - - public interface Retrieve{} - public interface Delete {} - public interface Update {} - public interface Create {} - - private static final long serialVersionUID = 1L; - -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > - <#if isComment?exists && isComment==true>/** - * ${fieldItem.fieldComment} - */<#if isSwagger?exists && isSwagger==true> - @ApiModelProperty("${fieldItem.fieldComment}") - <#if fieldItem.nullable==true>@NotNull(message = "${fieldItem.fieldComment}不能为空", groups = {Create.class,Update.class,Delete.class}) - <#if fieldItem.nullable==true>@Size( max = ${fieldItem.columnSize?c},message = "${fieldItem.fieldComment}长度限制${fieldItem.columnSize?c}位") - private ${fieldItem.fieldClass} ${fieldItem.fieldName}; - -<#if isLombok?exists && isLombok==false> - public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { - return ${fieldItem.fieldName}; - } - - public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { - this.${fieldItem.fieldName} = ${fieldItem.fieldName}; - } - - - - public ${classInfo.className}Vo() {} -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-controller.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-controller.ftl deleted file mode 100644 index 0039f4c8ec..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-controller.ftl +++ /dev/null @@ -1,232 +0,0 @@ -<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.controller; -<#if isAutoImport?exists && isAutoImport==true> -import com.alibaba.fastjson.JSON; -import ${packageName}.vo.${classInfo.className}VO; -import ${packageName}.dto.${classInfo.className}DTO; -import ${packageName}.mapper.${classInfo.className}Mapper; -import ${packageName}.entity.${classInfo.className}Entity; -import ${packageName}.service.${classInfo.className}Service; -//import com.bjc.lcp.common.cnt.enums.CntTableNameEnum; -//import com.bjc.lcp.common.cnt.service.CntService; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import lombok.extern.slf4j.Slf4j; -import org.springframework.validation.annotation.Validated; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; -import org.springframework.beans.BeanUtils; -import org.springframework.util.ObjectUtils; -import org.apache.shiro.authz.annotation.RequiresPermissions; -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.baomidou.mybatisplus.core.metadata.IPage; -import com.baomidou.mybatisplus.core.toolkit.Wrappers; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.bjc.lcp.system.common.utils.DataResult; -import org.springframework.web.servlet.ModelAndView; -import javax.annotation.Resource; -import java.util.Date; -import java.util.List; -import java.util.Map; - -/** -* @description ${classInfo.classComment} -* @author ${authorName} -* @date ${.now?string('yyyy-MM-dd')} -*/ -@Api(tags = "${classInfo.classComment}-管理") -@Slf4j -@RestController -@RequestMapping("/${classInfo.className?uncap_first}") -public class ${classInfo.className}Controller { - - @Resource - private ${classInfo.className}Service ${classInfo.className?uncap_first}Service; - - @Resource - private ${classInfo.className}Mapper ${classInfo.className?uncap_first}Mapper; - - //@Autowired - //private CntService cntService; - - @ApiOperation(value = "${classInfo.classComment}-新增") - @PostMapping("/add") - @RequiresPermissions("${classInfo.className?uncap_first}:add") - public DataResult add(@Validated(${classInfo.className}VO.Create.class) @RequestBody ${classInfo.className}VO vo) { - ${classInfo.className}DTO dto = new ${classInfo.className}DTO(); - BeanUtils.copyProperties(vo, dto); -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > -<#if fieldItem.nullable==true> - if (ObjectUtils.isEmpty(dto.get${fieldItem.fieldName?cap_first}())) { - return DataResult.fail("参数[${fieldItem.fieldName}]不能为空"); - } - - - - LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > -<#if fieldItem.isPrimaryKey==true> - queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); - - - - List<${classInfo.className}Entity> list = ${classInfo.className?uncap_first}Service.list(queryWrapper); - if (list.size() > 0) { - return DataResult.fail("数据已存在"); - } - ${classInfo.className}Entity entity = new ${classInfo.className}Entity(); - - BeanUtils.copyProperties(dto, entity); - return DataResult.success(${classInfo.className?uncap_first}Service.save(entity)); - } - - @ApiOperation(value = "${classInfo.classComment}-删除") - @DeleteMapping("/remove") - @RequiresPermissions("${classInfo.className?uncap_first}:remove") - public DataResult delete(@Validated(${classInfo.className}VO.Delete.class) @RequestBody ${classInfo.className}VO vo) { - ${classInfo.className}DTO dto = new ${classInfo.className}DTO(); - BeanUtils.copyProperties(vo, dto); -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > -<#if fieldItem.isPrimaryKey==true> - if (ObjectUtils.isEmpty(dto.get${fieldItem.fieldName?cap_first}())) { - return DataResult.fail("参数[${fieldItem.fieldName}]不能为空"); - } - - - - LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > -<#if fieldItem.isPrimaryKey==true> - queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); - - - - return DataResult.success(${classInfo.className?uncap_first}Service.remove(queryWrapper)); - } - - @ApiOperation(value = "${classInfo.classComment}-删除") - @DeleteMapping("/delete") - @RequiresPermissions("${classInfo.className?uncap_first}:delete") - public DataResult delete(@RequestBody @ApiParam(value = "id集合") List ids) { - return DataResult.success(${classInfo.className?uncap_first}Service.removeByIds(ids)); - } - - - @ApiOperation(value = "${classInfo.classComment}-更新") - @PutMapping("/update") - @RequiresPermissions("${classInfo.className?uncap_first}:update") - public DataResult update(@Validated(${classInfo.className}VO.Update.class) @RequestBody ${classInfo.className}VO vo) { - ${classInfo.className}DTO dto = new ${classInfo.className}DTO(); - BeanUtils.copyProperties(vo, dto); -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > -<#if fieldItem.isPrimaryKey==true> - if (ObjectUtils.isEmpty(dto.get${fieldItem.fieldName?cap_first}())) { - return DataResult.fail("参数[${fieldItem.fieldName}]不能为空"); - } - - - - LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > -<#if fieldItem.isPrimaryKey==true> - queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); - - - - ${classInfo.className}Entity entity = ${classInfo.className?uncap_first}Service.getOne(queryWrapper);; - if (entity == null) { - return DataResult.fail("数据不存在"); - } - BeanUtils.copyProperties(dto, entity); - return DataResult.success(${classInfo.className?uncap_first}Service.updateById(entity)); - } - - - - @ApiOperation(value = "${classInfo.classComment}-查询单条") - @RequestMapping(value = "/getOne",method = {RequestMethod.GET,RequestMethod.POST}) - @RequiresPermissions("${classInfo.className?uncap_first}:getOne") - public DataResult getOne(@RequestBody ${classInfo.className}VO vo) { - ${classInfo.className}DTO dto = new ${classInfo.className}DTO(); - BeanUtils.copyProperties(vo, dto); -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > -<#if fieldItem.isPrimaryKey==true> - if (ObjectUtils.isEmpty(dto.get${fieldItem.fieldName?cap_first}())) { - return DataResult.fail("参数[${fieldItem.fieldName}]不能为空"); - } - - - - LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > -<#if fieldItem.isPrimaryKey==true> - queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); - - - - ${classInfo.className}Entity entity = ${classInfo.className?uncap_first}Service.getOne(queryWrapper);; - return DataResult.success(entity); - } - - - - - @ApiOperation(value = "${classInfo.classComment}-查询列表分页数据") - @RequestMapping(value = "/listByPage",method = {RequestMethod.GET,RequestMethod.POST}) - @RequiresPermissions("${classInfo.className?uncap_first}:listByPage") - public DataResult listByPage(@RequestBody ${classInfo.className}VO ${classInfo.className?uncap_first}) { - Page page = new Page(${classInfo.className?uncap_first}.getPage(), ${classInfo.className?uncap_first}.getLimit()); - ${classInfo.className}DTO dto = new ${classInfo.className}DTO(); - BeanUtils.copyProperties(${classInfo.className?uncap_first}, dto); - LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > -<#if fieldItem.isPrimaryKey==true> - if (!ObjectUtils.isEmpty(${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}())) { - queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); - } -<#else> - if (!ObjectUtils.isEmpty(${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}())) { - queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); - } - - - - IPage<${classInfo.className}Entity> iPage = ${classInfo.className?uncap_first}Service.page(page, queryWrapper); - return DataResult.success(iPage); - } - - @ApiOperation(value = "${classInfo.classComment}-查询全部列表数据") - @RequestMapping(value = "/list",method = {RequestMethod.GET,RequestMethod.POST}) - @RequiresPermissions("${classInfo.className?uncap_first}:list") - public DataResult findListByPage(@RequestBody ${classInfo.className}VO ${classInfo.className?uncap_first}) { - LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > -<#if fieldItem.isPrimaryKey==true> - if (!ObjectUtils.isEmpty(${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}())) { - queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, ${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}()); - } -<#else> - if (!ObjectUtils.isEmpty(${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}())) { - queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, ${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}()); - } - - - - List<${classInfo.className}Entity> list = ${classInfo.className?uncap_first}Service.list(queryWrapper); - return DataResult.success(list); - } - - -} - diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-dto.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-dto.ftl deleted file mode 100644 index 132f5e4064..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-dto.ftl +++ /dev/null @@ -1,44 +0,0 @@ -<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.dto; - -<#if isAutoImport?exists && isAutoImport==true> -<#if isLombok?exists && isLombok==true>import lombok.Data; -import java.util.Date; -import java.util.List; -import java.io.Serializable; -import com.bjc.lcp.system.entity.BaseEntity; -<#if isSwagger?exists && isSwagger==true> -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * @description ${classInfo.classComment} - * @author ${authorName} - * @date ${.now?string('yyyy-MM-dd')} - */ -<#if isLombok?exists && isLombok==true>@Data<#if isSwagger?exists && isSwagger==true> -@ApiModel("${classInfo.classComment}") -public class ${classInfo.className}DTO extends BaseEntity implements Serializable { - - private static final long serialVersionUID = 1L; - -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > - <#if isComment?exists && isComment==true>/** - * ${fieldItem.fieldComment} - */<#if isSwagger?exists && isSwagger==true> - @ApiModelProperty("${fieldItem.fieldComment}") - private ${fieldItem.fieldClass} ${fieldItem.fieldName}; - -<#if isLombok?exists && isLombok==false> - public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { - return ${fieldItem.fieldName}; - } - - public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { - this.${fieldItem.fieldName} = ${fieldItem.fieldName}; - } - - - - public ${classInfo.className}DTO() {} -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-entity.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-entity.ftl deleted file mode 100644 index 1b0bd65ff2..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-entity.ftl +++ /dev/null @@ -1,51 +0,0 @@ -<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.entity; - -<#if isAutoImport?exists && isAutoImport==true> -<#if isLombok?exists && isLombok==true>import lombok.Data; -import java.util.Date; -import java.util.List; -import java.io.Serializable; -import com.baomidou.mybatisplus.annotation.IdType; -import com.baomidou.mybatisplus.annotation.TableId; -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableName; -import com.bjc.lcp.system.entity.BaseEntity; -<#assign isSwagger=false /> -<#if isSwagger?exists && isSwagger==true> -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * @description ${classInfo.classComment} - * @author ${authorName} - * @date ${.now?string('yyyy-MM-dd')} - */ -<#if isLombok?exists && isLombok==true>@Data<#if isSwagger?exists && isSwagger==true> -@ApiModel("${classInfo.classComment}") -@TableName("${classInfo.tableName}") -public class ${classInfo.className}Entity extends BaseEntity implements Serializable { - - private static final long serialVersionUID = 1L; - -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > - <#if isComment?exists && isComment==true>/** - * ${fieldItem.fieldComment} - */<#if isSwagger?exists && isSwagger==true> - @ApiModelProperty("${fieldItem.fieldComment}") - <#if fieldItem.isPrimaryKey==true>@TableId(value = "${fieldItem.columnName}" ,type = IdType.AUTO )<#else>@TableField(value = "${fieldItem.columnName}" ) - private ${fieldItem.fieldClass} ${fieldItem.fieldName}; - -<#if isLombok?exists && isLombok==false> - public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { - return ${fieldItem.fieldName}; - } - - public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { - this.${fieldItem.fieldName} = ${fieldItem.fieldName}; - } - - - - public ${classInfo.className}Entity() {} -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-mapper.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-mapper.ftl deleted file mode 100644 index c6e239c8b9..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-mapper.ftl +++ /dev/null @@ -1,41 +0,0 @@ -<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.mapper; -<#if isAutoImport?exists && isAutoImport==true> -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Select; -import ${packageName}.entity.${classInfo.className}Entity; -import java.util.List; - -/** - * @description ${classInfo.classComment}Mapper - * @author ${authorName} - * @date ${.now?string('yyyy-MM-dd')} - */ -@Mapper -public interface ${classInfo.className}Mapper extends BaseMapper<${classInfo.className}Entity> { - - @Select( - "") - List<${classInfo.className}Entity> pageAll(${classInfo.className}Entity dto,int page,int limit); - - @Select("") - int countAll(${classInfo.className}Entity dto); - - @Select("SELECT count(1) from ${classInfo.tableName} ") - int countAll(); - -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-service.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-service.ftl deleted file mode 100644 index 76483b1fe6..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-service.ftl +++ /dev/null @@ -1,16 +0,0 @@ -<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.service; -<#if isAutoImport?exists && isAutoImport==true> -import org.springframework.stereotype.Service; -import com.baomidou.mybatisplus.extension.service.IService; - -import ${packageName}.entity.${classInfo.className}Entity; - -/** - * @description ${classInfo.classComment}服务层 - * @author ${authorName} - * @date ${.now?string('yyyy-MM-dd')} - */ -public interface ${classInfo.className}Service extends IService<${classInfo.className}Entity> { - - -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-serviceimpl.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-serviceimpl.ftl deleted file mode 100644 index 6b3a91a117..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-serviceimpl.ftl +++ /dev/null @@ -1,26 +0,0 @@ -<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.service.impl; -<#if isAutoImport?exists && isAutoImport==true> -import org.springframework.stereotype.Service; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import ${packageName}.entity.${classInfo.className}Entity; -import ${packageName}.mapper.${classInfo.className}Mapper; -import ${packageName}.service.${classInfo.className}Service; - - -/** - * @description ${classInfo.classComment}服务层实现 - * @author ${authorName} - * @date ${.now?string('yyyy-MM-dd')} - */ -@Service -public class ${classInfo.className}ServiceImpl extends ServiceImpl<${classInfo.className}Mapper, ${classInfo.className}Entity> implements ${classInfo.className}Service { - - @Autowired - private ${classInfo.className}Mapper ${classInfo.className?uncap_first}Mapper; - -} - - - diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-vo.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-vo.ftl deleted file mode 100644 index 9e958ba139..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-vo.ftl +++ /dev/null @@ -1,56 +0,0 @@ -<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.vo; - -<#if isAutoImport?exists && isAutoImport==true> -<#if isLombok?exists && isLombok==true>import lombok.Data; -import java.util.Date; -import java.util.List; -import java.io.Serializable; -import io.swagger.annotations.ApiModelProperty; -import lombok.Data; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; -import java.io.Serializable; -import com.bjc.lcp.system.entity.BaseEntity; -<#if isSwagger?exists && isSwagger==true> -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * @description ${classInfo.classComment} - * @author ${authorName} - * @date ${.now?string('yyyy-MM-dd')} - */ -<#if isLombok?exists && isLombok==true>@Data<#if isSwagger?exists && isSwagger==true> -@ApiModel("${classInfo.classComment}") -public class ${classInfo.className}VO extends BaseEntity implements Serializable { - - public interface Retrieve{} - public interface Delete {} - public interface Update {} - public interface Create {} - - private static final long serialVersionUID = 1L; - -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > - <#if isComment?exists && isComment==true>/** - * ${fieldItem.fieldComment} - */<#if isSwagger?exists && isSwagger==true> - @ApiModelProperty("${fieldItem.fieldComment}") - <#if fieldItem.nullable==true>@NotNull(message = "${fieldItem.fieldComment}不能为空", groups = {Create.class,Update.class,Delete.class}) - <#if fieldItem.nullable==true>@Size( max = ${fieldItem.columnSize},message = "${fieldItem.fieldComment}长度限制${fieldItem.columnSize}位") - private ${fieldItem.fieldClass} ${fieldItem.fieldName}; - -<#if isLombok?exists && isLombok==false> - public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { - return ${fieldItem.fieldName}; - } - - public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { - this.${fieldItem.fieldName} = ${fieldItem.fieldName}; - } - - - - public ${classInfo.className}VO() {} -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-v2/pluscontroller.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-v2/pluscontroller.ftl deleted file mode 100644 index 2aaa8d7a08..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus-v2/pluscontroller.ftl +++ /dev/null @@ -1,166 +0,0 @@ -<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.controller; -<#if isAutoImport?exists && isAutoImport==true> -import com.alibaba.fastjson.JSON; -import ${packageName}.vo.${classInfo.className}VO; -import ${packageName}.mapper.${classInfo.className}Mapper; -import ${packageName}.entity.${classInfo.className}Entity; -import ${packageName}.service.${classInfo.className}Service; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.baomidou.mybatisplus.core.metadata.IPage; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import org.springframework.web.servlet.ModelAndView; - -import java.util.Date; -import java.util.List; -import java.util.Map; - -/** -* @description ${classInfo.classComment} -* @author ${authorName} -* @date ${.now?string('yyyy-MM-dd')} -*/ -@Slf4j -@RestController -@RequestMapping("/${classInfo.className?uncap_first}") -public class ${classInfo.className}Controller { - - @Autowired - private ${classInfo.className}Mapper ${classInfo.className?uncap_first}Mapper; - - @Autowired - private ${classInfo.className}Service ${classInfo.className?uncap_first}Service; - /** - * 新增或编辑 - */ - @PostMapping("/save") - public Object save(@RequestBody ${classInfo.className} ${classInfo.className?uncap_first}){ - log.info("${classInfo.className?uncap_first}:"+JSON.toJSONString(${classInfo.className?uncap_first})); - ${classInfo.className} old${classInfo.className} = ${classInfo.className?uncap_first}Mapper.selectOne(new QueryWrapper<${classInfo.className}>().eq("${classInfo.className?uncap_first}_id",${classInfo.className?uncap_first}.get${classInfo.className}Id())); - ${classInfo.className?uncap_first}.setUpdateTime(new Date()); - if(old${classInfo.className}!=null){ - ${classInfo.className?uncap_first}Mapper.updateById(${classInfo.className?uncap_first}); - }else{ - if(${classInfo.className?uncap_first}Mapper.selectOne(new QueryWrapper<${classInfo.className}>().eq("${classInfo.className?uncap_first}_name",${classInfo.className?uncap_first}.get${classInfo.className}Name()))!=null){ - return ${returnUtilFailure}("保存失败,名字重复"); - } - ${classInfo.className?uncap_first}.setCreateTime(new Date()); - ${classInfo.className?uncap_first}Mapper.insert(${classInfo.className?uncap_first}); - } - return ${returnUtilSuccess}("保存成功"); - } - - /** - * 删除 - */ - @PostMapping("/delete") - public Object delete(int id){ - ${classInfo.className} ${classInfo.className?uncap_first} = ${classInfo.className?uncap_first}Mapper.selectOne(new QueryWrapper<${classInfo.className}>().eq("${classInfo.className?uncap_first}_id",id)); - if(${classInfo.className?uncap_first}!=null){ - ${classInfo.className?uncap_first}Mapper.deleteById(id); - return ${returnUtilSuccess}("删除成功"); - }else{ - return ${returnUtilFailure}("没有找到该对象"); - } - } - - /** - * 查询 - */ - @PostMapping("/find") - public Object find(int id){ - ${classInfo.className} ${classInfo.className?uncap_first} = ${classInfo.className?uncap_first}Mapper.selectOne(new QueryWrapper<${classInfo.className}>().eq("${classInfo.className?uncap_first}_id",id)); - if(${classInfo.className?uncap_first}!=null){ - return ${returnUtilSuccess}(${classInfo.className?uncap_first}); - }else{ - return ${returnUtilFailure}("没有找到该对象"); - } - } - - /** - * 自动分页查询 - */ - @PostMapping("/list") - public Object list(String searchParams, - @RequestParam(required = false, defaultValue = "0") int page, - @RequestParam(required = false, defaultValue = "10") int limit) { - log.info("page:"+page+"-limit:"+limit+"-json:"+ JSON.toJSONString(searchParams)); - //分页构造器 - Page<${classInfo.className}> buildPage = new Page<${classInfo.className}>(page,limit); - //条件构造器 - QueryWrapper<${classInfo.className}> queryWrapper = new QueryWrapper<${classInfo.className}>(); - if(StringUtils.isNotEmpty(searchParams)&&JSON.isValid(searchParams)) { - ${classInfo.className} ${classInfo.className?uncap_first} = JSON.parseObject(searchParams, ${classInfo.className}.class); - queryWrapper.eq(StringUtils.isNoneEmpty(${classInfo.className?uncap_first}.get${classInfo.className}Name()), "${classInfo.className?uncap_first}_name", ${classInfo.className?uncap_first}.get${classInfo.className}Name()); - } - //执行分页 - IPage<${classInfo.className}> pageList = ${classInfo.className?uncap_first}Mapper.selectPage(buildPage, queryWrapper); - //返回结果 - return ${returnUtil}.PAGE(pageList.getRecords(),pageList.getTotal()); - } - /** - * 手工分页查询(按需使用) - */ - /*@PostMapping("/list2") - public Object list2(String searchParams, - @RequestParam(required = false, defaultValue = "0") int page, - @RequestParam(required = false, defaultValue = "10") int limit) { - log.info("searchParams:"+ JSON.toJSONString(searchParams)); - //通用模式 - ${classInfo.className} queryParamDTO = JSON.parseObject(searchParams, ${classInfo.className}.class); - //专用DTO模式 - //QueryParamDTO queryParamDTO = JSON.parseObject(searchParams, QueryParamDTO.class); - //queryParamDTO.setPage((page - 1)* limit); - //queryParamDTO.setLimit(limit); - //(page - 1) * limit, limit - List<${classInfo.className}> itemList = ${classInfo.className?uncap_first}Mapper.pageAll(queryParamDTO,(page - 1)* limit,limit); - Integer itemCount = ${classInfo.className?uncap_first}Mapper.countAll(queryParamDTO); - //返回结果 - return ${returnUtilSuccess}.PAGE(itemList,itemCount); - }*/ - @GetMapping("/list") - public ModelAndView listPage(){ - return new ModelAndView("${classInfo.className?uncap_first}-list"); - } - - @GetMapping("/edit") - public ModelAndView editPage(int id){ - ${classInfo.className} ${classInfo.className?uncap_first} = ${classInfo.className?uncap_first}Mapper.selectOne(new QueryWrapper<${classInfo.className}>().eq("${classInfo.className?uncap_first}_id",id)); - return new ModelAndView("${classInfo.className?uncap_first}-edit","${classInfo.className?uncap_first}",${classInfo.className?uncap_first}); - } - - /** - * 发布/暂停(如不需要请屏蔽) - */ - @PostMapping("/publish") - public Object publish(int id,Integer status){ - ${classInfo.className} ${classInfo.className?uncap_first} = ${classInfo.className?uncap_first}Mapper.selectOne(new QueryWrapper<${classInfo.className}>().eq("${classInfo.className?uncap_first}_id",id)); - if(${classInfo.className?uncap_first}!=null){ - ${classInfo.className?uncap_first}.setUpdateTime(new Date()); - ${classInfo.className?uncap_first}.setStatus(status); - ${classInfo.className?uncap_first}Mapper.updateById(${classInfo.className?uncap_first}); - return ${returnUtilSuccess}((status==1)?"已发布":"已暂停"); - }else if(status.equals(${classInfo.className?uncap_first}.getStatus())){ - return ${returnUtilFailure}("状态不正确"); - }else{ - return ${returnUtilFailure}(); - } - } - - /** - * 执行(如不需要请屏蔽) - */ - @PostMapping("/execute") - public Object execute(){ - return ${returnUtilSuccess}; - } -} -} - - - diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus/pluscontroller.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus/pluscontroller.ftl deleted file mode 100644 index f18e4429c0..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus/pluscontroller.ftl +++ /dev/null @@ -1,161 +0,0 @@ -<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.controller; -<#if isAutoImport?exists && isAutoImport==true> -import com.alibaba.fastjson.JSON; -import ${packageName}.entity.${classInfo.className}; -import ${packageName}.mapper.${classInfo.className}Mapper; -import ${packageName}.util.ReturnT; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.baomidou.mybatisplus.core.metadata.IPage; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import org.springframework.web.servlet.ModelAndView; - -import java.util.Date; -import java.util.List; -import java.util.Map; - -/** -* @description ${classInfo.classComment}控制器 -* @author ${authorName} -* @date ${.now?string('yyyy-MM-dd')} -*/ -@Slf4j -@RestController -@RequestMapping("/${classInfo.className?uncap_first}") -public class ${classInfo.className}Controller { - - @Autowired - private ${classInfo.className}Mapper ${classInfo.className?uncap_first}Mapper; - - /** - * 新增或编辑 - */ - @PostMapping("/save") - public Object save(@RequestBody ${classInfo.className} ${classInfo.className?uncap_first}){ - log.info("${classInfo.className?uncap_first}:"+JSON.toJSONString(${classInfo.className?uncap_first})); - ${classInfo.className} old${classInfo.className} = ${classInfo.className?uncap_first}Mapper.selectOne(new QueryWrapper<${classInfo.className}>().eq("${classInfo.className?uncap_first}_id",${classInfo.className?uncap_first}.get${classInfo.className}Id())); - ${classInfo.className?uncap_first}.setUpdateTime(new Date()); - if(old${classInfo.className}!=null){ - ${classInfo.className?uncap_first}Mapper.updateById(${classInfo.className?uncap_first}); - }else{ - if(${classInfo.className?uncap_first}Mapper.selectOne(new QueryWrapper<${classInfo.className}>().eq("${classInfo.className?uncap_first}_name",${classInfo.className?uncap_first}.get${classInfo.className}Name()))!=null){ - return ${returnUtilFailure}("保存失败,名字重复"); - } - ${classInfo.className?uncap_first}.setCreateTime(new Date()); - ${classInfo.className?uncap_first}Mapper.insert(${classInfo.className?uncap_first}); - } - return ${returnUtilSuccess}("保存成功"); - } - - /** - * 删除 - */ - @PostMapping("/delete") - public Object delete(int id){ - ${classInfo.className} ${classInfo.className?uncap_first} = ${classInfo.className?uncap_first}Mapper.selectOne(new QueryWrapper<${classInfo.className}>().eq("${classInfo.className?uncap_first}_id",id)); - if(${classInfo.className?uncap_first}!=null){ - ${classInfo.className?uncap_first}Mapper.deleteById(id); - return ${returnUtilSuccess}("删除成功"); - }else{ - return ${returnUtilFailure}("没有找到该对象"); - } - } - - /** - * 查询 - */ - @PostMapping("/find") - public Object find(int id){ - ${classInfo.className} ${classInfo.className?uncap_first} = ${classInfo.className?uncap_first}Mapper.selectOne(new QueryWrapper<${classInfo.className}>().eq("${classInfo.className?uncap_first}_id",id)); - if(${classInfo.className?uncap_first}!=null){ - return ${returnUtilSuccess}(${classInfo.className?uncap_first}); - }else{ - return ${returnUtilFailure}("没有找到该对象"); - } - } - - /** - * 自动分页查询 - */ - @PostMapping("/list") - public Object list(String searchParams, - @RequestParam(required = false, defaultValue = "0") int page, - @RequestParam(required = false, defaultValue = "10") int limit) { - log.info("page:"+page+"-limit:"+limit+"-json:"+ JSON.toJSONString(searchParams)); - //分页构造器 - Page<${classInfo.className}> buildPage = new Page<${classInfo.className}>(page,limit); - //条件构造器 - QueryWrapper<${classInfo.className}> queryWrapper = new QueryWrapper<${classInfo.className}>(); - if(StringUtils.isNotEmpty(searchParams)&&JSON.isValid(searchParams)) { - ${classInfo.className} ${classInfo.className?uncap_first} = JSON.parseObject(searchParams, ${classInfo.className}.class); - queryWrapper.eq(StringUtils.isNoneEmpty(${classInfo.className?uncap_first}.get${classInfo.className}Name()), "${classInfo.className?uncap_first}_name", ${classInfo.className?uncap_first}.get${classInfo.className}Name()); - } - //执行分页 - IPage<${classInfo.className}> pageList = ${classInfo.className?uncap_first}Mapper.selectPage(buildPage, queryWrapper); - //返回结果 - return ${returnUtil}.PAGE(pageList.getRecords(),pageList.getTotal()); - } - /** - * 手工分页查询(按需使用) - */ - /*@PostMapping("/list2") - public Object list2(String searchParams, - @RequestParam(required = false, defaultValue = "0") int page, - @RequestParam(required = false, defaultValue = "10") int limit) { - log.info("searchParams:"+ JSON.toJSONString(searchParams)); - //通用模式 - ${classInfo.className} queryParamDTO = JSON.parseObject(searchParams, ${classInfo.className}.class); - //专用DTO模式 - //QueryParamDTO queryParamDTO = JSON.parseObject(searchParams, QueryParamDTO.class); - //queryParamDTO.setPage((page - 1)* limit); - //queryParamDTO.setLimit(limit); - //(page - 1) * limit, limit - List<${classInfo.className}> itemList = ${classInfo.className?uncap_first}Mapper.pageAll(queryParamDTO,(page - 1)* limit,limit); - Integer itemCount = ${classInfo.className?uncap_first}Mapper.countAll(queryParamDTO); - //返回结果 - return ${returnUtilSuccess}.PAGE(itemList,itemCount); - }*/ - @GetMapping("/list") - public ModelAndView listPage(){ - return new ModelAndView("${classInfo.className?uncap_first}-list"); - } - - @GetMapping("/edit") - public ModelAndView editPage(int id){ - ${classInfo.className} ${classInfo.className?uncap_first} = ${classInfo.className?uncap_first}Mapper.selectOne(new QueryWrapper<${classInfo.className}>().eq("${classInfo.className?uncap_first}_id",id)); - return new ModelAndView("${classInfo.className?uncap_first}-edit","${classInfo.className?uncap_first}",${classInfo.className?uncap_first}); - } - - /** - * 发布/暂停(如不需要请屏蔽) - */ - @PostMapping("/publish") - public Object publish(int id,Integer status){ - ${classInfo.className} ${classInfo.className?uncap_first} = ${classInfo.className?uncap_first}Mapper.selectOne(new QueryWrapper<${classInfo.className}>().eq("${classInfo.className?uncap_first}_id",id)); - if(${classInfo.className?uncap_first}!=null){ - ${classInfo.className?uncap_first}.setUpdateTime(new Date()); - ${classInfo.className?uncap_first}.setStatus(status); - ${classInfo.className?uncap_first}Mapper.updateById(${classInfo.className?uncap_first}); - return ${returnUtilSuccess}((status==1)?"已发布":"已暂停"); - }else if(status.equals(${classInfo.className?uncap_first}.getStatus())){ - return ${returnUtilFailure}("状态不正确"); - }else{ - return ${returnUtilFailure}(); - } - } - - /** - * 执行(如不需要请屏蔽) - */ - @PostMapping("/execute") - public Object execute(){ - return ${returnUtilSuccess}; - } -} -} - - - diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus/plusentity.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus/plusentity.ftl deleted file mode 100644 index 52134edbb6..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus/plusentity.ftl +++ /dev/null @@ -1,46 +0,0 @@ -<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.entity; - -<#if isAutoImport?exists && isAutoImport==true> -<#if isLombok?exists && isLombok==true>import lombok.Data; -import java.util.Date; -import java.util.List; -import java.io.Serializable; -import com.baomidou.mybatisplus.annotation.IdType; -import com.baomidou.mybatisplus.annotation.TableId; -<#if isSwagger?exists && isSwagger==true> -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * @description ${classInfo.classComment} - * @author ${authorName} - * @date ${.now?string('yyyy-MM-dd')} - */ -<#if isLombok?exists && isLombok==true>@Data<#if isSwagger?exists && isSwagger==true> -@ApiModel("${classInfo.classComment}") -public class ${classInfo.className} implements Serializable { - - private static final long serialVersionUID = 1L; - - @TableId(type = IdType.AUTO) -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > - <#if isComment?exists && isComment==true>/** - * ${fieldItem.fieldComment} - */<#if isSwagger?exists && isSwagger==true> - @ApiModelProperty("${fieldItem.fieldComment}") - private ${fieldItem.fieldClass} ${fieldItem.fieldName}; - -<#if isLombok?exists && isLombok==false> - public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { - return ${fieldItem.fieldName}; - } - - public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { - this.${fieldItem.fieldName} = ${fieldItem.fieldName}; - } - - - - public ${classInfo.className}() {} -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus/plusmapper.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus/plusmapper.ftl deleted file mode 100644 index 438b514fd1..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus/plusmapper.ftl +++ /dev/null @@ -1,38 +0,0 @@ -<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.mapper; -<#if isAutoImport?exists && isAutoImport==true> -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Select; -import ${packageName}.entity.${classInfo.className}; -import java.util.List; - -/** - * @description ${classInfo.classComment}Mapper - * @author ${authorName} - * @date ${.now?string('yyyy-MM-dd')} - */ -@Mapper -public interface ${classInfo.className}Mapper extends BaseMapper<${classInfo.className}> { - - @Select( - "") - List<${classInfo.className}> pageAll(${classInfo.className} queryParamDTO,int page,int limit); - - @Select("") - int countAll(${classInfo.className} queryParamDTO); - -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus/plusservice.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus/plusservice.ftl deleted file mode 100644 index 4672e01a16..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis-plus/plusservice.ftl +++ /dev/null @@ -1,16 +0,0 @@ -<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.service; -<#if isAutoImport?exists && isAutoImport==true> -import org.springframework.stereotype.Service; -import com.baomidou.mybatisplus.extension.service.IService; - -/** - * @description ${classInfo.classComment}服务层 - * @author ${authorName} - * @date ${.now?string('yyyy-MM-dd')} - */ -@Service -public interface ${classInfo.className}Service extends IService<${classInfo.className}> { - - - -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis.ftl deleted file mode 100644 index 0e1a7560eb..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis.ftl +++ /dev/null @@ -1,82 +0,0 @@ - - - - - - <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> - <#list classInfo.fieldList as fieldItem > - - - - - - - <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> - <#list classInfo.fieldList as fieldItem > - `${fieldItem.columnName}`<#if fieldItem_has_next>, - - - - - - INSERT INTO ${classInfo.tableName} ( - <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> - <#list classInfo.fieldList as fieldItem > - <#if fieldItem.columnName != "Id" > - `${fieldItem.columnName}`<#if fieldItem_has_next>, - - - - ) - VALUES( - <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> - <#list classInfo.fieldList as fieldItem > - <#if fieldItem.columnName != "Id" > - <#if fieldItem.columnName="AddTime" || fieldItem.columnName="UpdateTime" > - NOW()<#if fieldItem_has_next>, - <#else> - ${r"#{"}${classInfo.className?uncap_first}.${fieldItem.fieldName}${r"}"}<#if fieldItem_has_next>, - - - - - ) - - - - DELETE FROM ${classInfo.tableName} - WHERE `id` = ${r"#{id}"} - - - - UPDATE ${classInfo.tableName} - SET - <#list classInfo.fieldList as fieldItem > - <#if fieldItem.columnName != "Id" && fieldItem.columnName != "AddTime" && fieldItem.columnName != "UpdateTime" > - ${fieldItem.columnName} = ${r"#{"}${classInfo.className?uncap_first}.${fieldItem.fieldName}${r"}"}, - - - UpdateTime = NOW() - WHERE `id` = ${r"#{"}${classInfo.className?uncap_first}.id${r"}"} - - - - - - - - - - diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis/controller.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis/controller.ftl deleted file mode 100644 index 69697c732f..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis/controller.ftl +++ /dev/null @@ -1,76 +0,0 @@ -<#if isAutoImport?exists && isAutoImport==true> -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; - -import javax.annotation.Resource; -import javax.servlet.http.HttpServletRequest; -import java.util.List; -import java.util.Map; - - -/** - * @description ${classInfo.classComment} - * @author ${authorName} - * @date ${.now?string('yyyy-MM-dd')} - */ -@RestController -@RequestMapping(value = "/${classInfo.className?uncap_first}") -public class ${classInfo.className}Controller { - - @Resource - private ${classInfo.className}Service ${classInfo.className?uncap_first}Service; - - /** - * 新增 - * @author ${authorName} - * @date ${.now?string('yyyy/MM/dd')} - **/ - @RequestMapping("/insert") - public Object insert(${classInfo.className} ${classInfo.className?uncap_first}){ - return ${classInfo.className?uncap_first}Service.insert(${classInfo.className?uncap_first}); - } - - /** - * 刪除 - * @author ${authorName} - * @date ${.now?string('yyyy/MM/dd')} - **/ - @RequestMapping("/delete") - public ReturnT delete(int id){ - return ${classInfo.className?uncap_first}Service.delete(id); - } - - /** - * 更新 - * @author ${authorName} - * @date ${.now?string('yyyy/MM/dd')} - **/ - @RequestMapping("/update") - public ReturnT update(${classInfo.className} ${classInfo.className?uncap_first}){ - return ${classInfo.className?uncap_first}Service.update(${classInfo.className?uncap_first}); - } - - /** - * 查询 根据主键 id 查询 - * @author ${authorName} - * @date ${.now?string('yyyy/MM/dd')} - **/ - @RequestMapping("/load") - public Object load(int id){ - return ${classInfo.className?uncap_first}Service.load(id); - } - - /** - * 查询 分页查询 - * @author ${authorName} - * @date ${.now?string('yyyy/MM/dd')} - **/ - @RequestMapping("/pageList") - public Map pageList(@RequestParam(required = false, defaultValue = "0") int offset, - @RequestParam(required = false, defaultValue = "10") int pagesize) { - return ${classInfo.className?uncap_first}Service.pageList(offset, pagesize); - } - -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis/mapper.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis/mapper.ftl deleted file mode 100644 index e7dc9ef574..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis/mapper.ftl +++ /dev/null @@ -1,59 +0,0 @@ -<#if isAutoImport?exists && isAutoImport==true> -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Mapper; -import org.springframework.stereotype.Repository; -import java.util.List; - - -/** - * @description ${classInfo.classComment} - * @author ${authorName} - * @date ${.now?string('yyyy-MM-dd')} - */ -@Mapper -@Repository -public interface ${classInfo.className}Mapper { - - /** - * 新增 - * @author ${authorName} - * @date ${.now?string('yyyy/MM/dd')} - **/ - int insert(${classInfo.className} ${classInfo.className?uncap_first}); - - /** - * 刪除 - * @author ${authorName} - * @date ${.now?string('yyyy/MM/dd')} - **/ - int delete(int id); - - /** - * 更新 - * @author ${authorName} - * @date ${.now?string('yyyy/MM/dd')} - **/ - int update(${classInfo.className} ${classInfo.className?uncap_first}); - - /** - * 查询 根据主键 id 查询 - * @author ${authorName} - * @date ${.now?string('yyyy/MM/dd')} - **/ - ${classInfo.className} load(int id); - - /** - * 查询 分页查询 - * @author ${authorName} - * @date ${.now?string('yyyy/MM/dd')} - **/ - List<${classInfo.className}> pageList(int offset,int pagesize); - - /** - * 查询 分页查询 count - * @author ${authorName} - * @date ${.now?string('yyyy/MM/dd')} - **/ - int pageListCount(int offset,int pagesize); - -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis/mapper2.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis/mapper2.ftl deleted file mode 100644 index ee0b5e0a6b..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis/mapper2.ftl +++ /dev/null @@ -1,56 +0,0 @@ -<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.mapper; -<#if isAutoImport?exists && isAutoImport==true> -import org.apache.ibatis.annotations.*; -import org.springframework.stereotype.Repository; -import java.util.List; - -/** - * @description ${classInfo.classComment}Mapper - * @author ${authorName} - * @date ${.now?string('yyyy-MM-dd')} - */ -@Mapper -@Repository -public interface ${classInfo.className}Mapper { - - @Select("select * from ${classInfo.tableName} where ${classInfo.tableName}_id=井{id}") - public ${classInfo.className} getById(Integer id); - - @Options(useGeneratedKeys=true,keyProperty="${classInfo.className?uncap_first}Id") - @Insert("insert into ${classInfo.tableName}" + - " (<#list classInfo.fieldList as fieldItem >${fieldItem.columnName}<#if fieldItem_has_next>,)" + - " values(<#list classInfo.fieldList as fieldItem >${fieldItem.fieldName}<#if fieldItem_has_next>,<#else>)") - public Integer insert(${classInfo.className} ${classInfo.className?uncap_first}); - - @Delete(value = "delete from ${classInfo.tableName} where ${classInfo.tableName}_id=井{${classInfo.className?uncap_first}Id}") - boolean delete(Integer id); - - @Update(value = "update ${classInfo.tableName} set " - <#list classInfo.fieldList as fieldItem > - <#if fieldItem.columnName != "id">+" ${fieldItem.columnName}=井{${fieldItem.fieldName}}<#if fieldItem_has_next>," - - +" where ${classInfo.tableName}_id=井{${classInfo.className?uncap_first}Id} ") - boolean update(${classInfo.className} ${classInfo.className?uncap_first}); - - - @Results(value = { - <#list classInfo.fieldList as fieldItem > - @Result(property = "${fieldItem.fieldName}", column = "${fieldItem.columnName}")<#if fieldItem_has_next>, - - }) - @Select(value = "select * from ${classInfo.tableName} where ${classInfo.tableName}_id=井{queryParam}") - ${classInfo.className} selectOne(String queryParam); - - @Results(value = { - <#list classInfo.fieldList as fieldItem > - @Result(property = "${fieldItem.fieldName}", column = "${fieldItem.columnName}")<#if fieldItem_has_next>, - - }) - @Select(value = "select * from ${classInfo.tableName} where " - <#list classInfo.fieldList as fieldItem > - +" ${fieldItem.columnName}=井{${fieldItem.fieldName}}<#if fieldItem_has_next> or " - - ) - List<${classInfo.className}> selectList(${classInfo.className} ${classInfo.className?uncap_first}); - -} \ No newline at end of file diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis/model.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis/model.ftl deleted file mode 100644 index 3e94df7076..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis/model.ftl +++ /dev/null @@ -1,40 +0,0 @@ -<#if isAutoImport?exists && isAutoImport==true> -import java.io.Serializable; -import java.util.Date; -import java.util.List; - -/** - * @description ${classInfo.classComment} - * @author ${authorName} - * @date ${.now?string('yyyy-MM-dd')} - */ -public class ${classInfo.className} implements Serializable { - - private static final long serialVersionUID = 1L; - -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem > - <#if isComment?exists && isComment==true>/** - * ${fieldItem.fieldComment} - */ - private ${fieldItem.fieldClass} ${fieldItem.fieldName}; - - - - -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> - public ${classInfo.className}() { - } - -<#list classInfo.fieldList as fieldItem> - public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { - return ${fieldItem.fieldName}; - } - - public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { - this.${fieldItem.fieldName} = ${fieldItem.fieldName}; - } - - - -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis/mybatis.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis/mybatis.ftl deleted file mode 100644 index 24bfb858b5..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis/mybatis.ftl +++ /dev/null @@ -1,89 +0,0 @@ - - - - - - <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> - <#list classInfo.fieldList as fieldItem > - - - - - - - <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> - <#list classInfo.fieldList as fieldItem > - ${fieldItem.columnName}<#if fieldItem_has_next>, - - - - - - INSERT INTO ${classInfo.tableName} - - <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> - <#list classInfo.fieldList as fieldItem > - <#if fieldItem.columnName != "id" > - - ${fieldItem.columnName}<#if fieldItem_has_next>, - ${r""} - - - - - - <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> - <#list classInfo.fieldList as fieldItem > - <#if fieldItem.columnName != "id" > - <#--<#if fieldItem.columnName="addtime" || fieldItem.columnName="updatetime" > - ${r""} - NOW()<#if fieldItem_has_next>, - ${r""} - <#else>--> - - ${r"#{"}${fieldItem.fieldName}${r"}"}<#if fieldItem_has_next>, - ${r""} - <#----> - - - - - - - - DELETE FROM ${classInfo.tableName} - WHERE id = ${r"#{id}"} - - - - UPDATE ${classInfo.tableName} - - <#list classInfo.fieldList as fieldItem > - <#if fieldItem.columnName != "id" && fieldItem.columnName != "AddTime" && fieldItem.columnName != "UpdateTime" > - ${fieldItem.columnName} = ${r"#{"}${fieldItem.fieldName}${r"}"}<#if fieldItem_has_next>,${r""} - - - - WHERE id = ${r"#{"}id${r"}"} - - - - - - - - - - \ No newline at end of file diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis/service.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis/service.ftl deleted file mode 100644 index c31f30b0ff..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis/service.ftl +++ /dev/null @@ -1,36 +0,0 @@ -<#if isAutoImport?exists && isAutoImport==true> -import java.util.Map; - -/** - * @description ${classInfo.classComment} - * @author ${authorName} - * @date ${.now?string('yyyy-MM-dd')} - */ -public interface ${classInfo.className}Service { - - /** - * 新增 - */ - public Object insert(${classInfo.className} ${classInfo.className?uncap_first}); - - /** - * 删除 - */ - public Object delete(int id); - - /** - * 更新 - */ - public Object update(${classInfo.className} ${classInfo.className?uncap_first}); - - /** - * 根据主键 id 查询 - */ - public ${classInfo.className} load(int id); - - /** - * 分页查询 - */ - public Map pageList(int offset, int pagesize); - -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis/service_impl.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis/service_impl.ftl deleted file mode 100644 index 3a8345de89..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/mybatis/service_impl.ftl +++ /dev/null @@ -1,68 +0,0 @@ -<#if isAutoImport?exists && isAutoImport==true> -import org.springframework.stereotype.Service; -import javax.annotation.Resource; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * @description ${classInfo.classComment} - * @author ${authorName} - * @date ${.now?string('yyyy-MM-dd')} - */ -@Service -public class ${classInfo.className}ServiceImpl implements ${classInfo.className}Service { - - @Resource - private ${classInfo.className}Mapper ${classInfo.className?uncap_first}Mapper; - - - @Override - public Object insert(${classInfo.className} ${classInfo.className?uncap_first}) { - - // valid - if (${classInfo.className?uncap_first} == null) { - return ${returnUtilFailure}("必要参数缺失"); - } - - ${classInfo.className?uncap_first}Mapper.insert(${classInfo.className?uncap_first}); - return ${returnUtilSuccess}(); - } - - - @Override - public Object delete(int id) { - int ret = ${classInfo.className?uncap_first}Mapper.delete(id); - return ret>0?${returnUtilSuccess}():${returnUtilFailure}(); - } - - - @Override - public Object update(${classInfo.className} ${classInfo.className?uncap_first}) { - int ret = ${classInfo.className?uncap_first}Mapper.update(${classInfo.className?uncap_first}); - return ret>0?${returnUtilSuccess}():${returnUtilFailure}(); - } - - - @Override - public ${classInfo.className} load(int id) { - return ${classInfo.className?uncap_first}Mapper.load(id); - } - - - @Override - public Map pageList(int offset, int pagesize) { - - List<${classInfo.className}> pageList = ${classInfo.className?uncap_first}Mapper.pageList(offset, pagesize); - int totalCount = ${classInfo.className?uncap_first}Mapper.pageListCount(offset, pagesize); - - // result - Map result = new HashMap(); - result.put("pageList", pageList); - result.put("totalCount", totalCount); - - return result; - } - -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/renren-fast/menu-sql.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/renren-fast/menu-sql.ftl deleted file mode 100644 index 2b3193a3f3..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/renren-fast/menu-sql.ftl +++ /dev/null @@ -1,17 +0,0 @@ --- 菜单SQL -INSERT INTO `sys_menu` (`parent_id`, `name`, `url`, `perms`, `type`, `icon`, `order_num`) -VALUES ('1', '${classInfo.classComment}', 'generator/${classInfo.className?uncap_first}', NULL, '1', 'config', '6'); - --- 按钮父菜单ID -set @parentId = @@identity; - --- 菜单对应按钮SQL -INSERT INTO `sys_menu` (`parent_id`, `name`, `url`, `perms`, `type`, `icon`, `order_num`) -SELECT @parentId, '查看', null, 'generator:${classInfo.className?uncap_first}:list,generator:${classInfo.className?uncap_first}:info', '2', null, '6'; -INSERT INTO `sys_menu` (`parent_id`, `name`, `url`, `perms`, `type`, `icon`, `order_num`) -SELECT @parentId, '新增', null, 'generator:${classInfo.className?uncap_first}:save', '2', null, '6'; -INSERT INTO `sys_menu` (`parent_id`, `name`, `url`, `perms`, `type`, `icon`, `order_num`) -SELECT @parentId, '修改', null, 'generator:${classInfo.className?uncap_first}:update', '2', null, '6'; -INSERT INTO `sys_menu` (`parent_id`, `name`, `url`, `perms`, `type`, `icon`, `order_num`) -SELECT @parentId, '删除', null, 'generator:${classInfo.className?uncap_first}:delete', '2', null, '6'; - diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/renren-fast/rr-controller.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/renren-fast/rr-controller.ftl deleted file mode 100644 index 31a1c39f9c..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/renren-fast/rr-controller.ftl +++ /dev/null @@ -1,89 +0,0 @@ -<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.controller; -<#if isAutoImport?exists && isAutoImport==true> -import java.util.Arrays; -import java.util.Map; - -import org.apache.shiro.authz.annotation.RequiresPermissions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.PathVariable; -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 ${packageName}.entity.${classInfo.className}Entity; -import ${packageName}.service.${classInfo.className}Service; -import ${packageName}.common.utils.PageUtils; -import ${packageName}.common.utils.R; - - - -/** -* @description ${classInfo.classComment}控制器 -* @author ${authorName} -* @date ${.now?string('yyyy-MM-dd')} -*/ -@RestController -@RequestMapping("generator/${classInfo.className?uncap_first}") -public class ${classInfo.className}Controller { - -@Autowired -private ${classInfo.className}Service ${classInfo.className?uncap_first}Service; - -/** -* 列表 -*/ -@RequestMapping("/list") -@RequiresPermissions("generator:${classInfo.className?uncap_first}:list") -public R list(@RequestParam Map params){ - PageUtils page = ${classInfo.className?uncap_first}Service.queryPage(params); - - return R.ok().put("page", page); -} - - -/** -* 信息 -*/ -@RequestMapping("/info/{${classInfo.className?uncap_first}Id}") -@RequiresPermissions("generator:${classInfo.className?uncap_first}:info") -public R info(@PathVariable("${classInfo.className?uncap_first}Id") int ${classInfo.className?uncap_first}Id){ - ${classInfo.className}Entity ${classInfo.className?uncap_first} = ${classInfo.className?uncap_first}Service.getById(${classInfo.className?uncap_first}Id); - - return R.ok().put("${classInfo.className?uncap_first}", ${classInfo.className?uncap_first}); -} - -/** -* 保存 -*/ -@RequestMapping("/save") -@RequiresPermissions("generator:${classInfo.className?uncap_first}:save") -public R save(@RequestBody ${classInfo.className}Entity ${classInfo.className?uncap_first}){ - ${classInfo.className?uncap_first}Service.save(${classInfo.className?uncap_first}); - - return R.ok(); -} - -/** -* 修改 -*/ -@RequestMapping("/update") -@RequiresPermissions("generator:${classInfo.className?uncap_first}:update") -public R update(@RequestBody ${classInfo.className}Entity ${classInfo.className?uncap_first}){ - ${classInfo.className?uncap_first}Service.updateById(${classInfo.className?uncap_first}); - - return R.ok(); -} - -/** -* 删除 -*/ -@RequestMapping("/delete") -@RequiresPermissions("generator:${classInfo.className?uncap_first}:delete") -public R delete(@RequestBody int[] ${classInfo.className?uncap_first}Ids){ - ${classInfo.className?uncap_first}Service.removeByIds(Arrays.asList(${classInfo.className?uncap_first}Ids)); - - return R.ok(); -} - -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/renren-fast/rr-dao.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/renren-fast/rr-dao.ftl deleted file mode 100644 index 15f7e96435..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/renren-fast/rr-dao.ftl +++ /dev/null @@ -1,15 +0,0 @@ -<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.mapper; -<#if isAutoImport?exists && isAutoImport==true> -import ${packageName}.entity.${classInfo.className}Entity; -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import org.apache.ibatis.annotations.Mapper; - -/** -* @description ${classInfo.classComment}Mapper -* @author ${authorName} -* @date ${.now?string('yyyy-MM-dd')} -*/ -@Mapper -public interface ${classInfo.className}Dao extends BaseMapper<${classInfo.className}Entity> { - -} \ No newline at end of file diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/renren-fast/rr-daoxml.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/renren-fast/rr-daoxml.ftl deleted file mode 100644 index c4656036e5..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/renren-fast/rr-daoxml.ftl +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> - <#list classInfo.fieldList as fieldItem > - - - - - - \ No newline at end of file diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/renren-fast/rr-entity.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/renren-fast/rr-entity.ftl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/renren-fast/rr-service.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/renren-fast/rr-service.ftl deleted file mode 100644 index 719246d22b..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/renren-fast/rr-service.ftl +++ /dev/null @@ -1,28 +0,0 @@ -<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.service; -<#if isAutoImport?exists && isAutoImport==true> -import org.springframework.stereotype.Service; -import java.util.Map; -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.baomidou.mybatisplus.core.metadata.IPage; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import ${packageName}.common.utils.PageUtils; -import ${packageName}.common.utils.Query; - -import ${packageName}.dao.${classInfo.className}Dao; -import ${packageName}.entity.${classInfo.className}Entity; - - -@Service("${classInfo.className?uncap_first}Service") -public class ${classInfo.className}Service extends ServiceImpl<${classInfo.className}Dao, ${classInfo.className}Entity> { - - @Override - public PageUtils queryPage(Map params) { - IPage<${classInfo.className}Entity> page = this.page( - new Query<${classInfo.className}Entity>().getPage(params), - new QueryWrapper<${classInfo.className}Entity>() - ); - - return new PageUtils(page); - } - -} \ No newline at end of file diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/renren-fast/vue-edit.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/renren-fast/vue-edit.ftl deleted file mode 100644 index 6f5835baf0..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/renren-fast/vue-edit.ftl +++ /dev/null @@ -1,101 +0,0 @@ - - - diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/renren-fast/vue-list.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/renren-fast/vue-list.ftl deleted file mode 100644 index 969d7d8086..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/renren-fast/vue-list.ftl +++ /dev/null @@ -1,162 +0,0 @@ - - - diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/service.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/service.ftl deleted file mode 100644 index b3295ddab7..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/service.ftl +++ /dev/null @@ -1,39 +0,0 @@ -package ${packageService}; -import java.util.Map; - -import ${packageModel}.${classInfo.className}; -import com.jun.plugin.codegenerator.admin.model.ReturnT; - -/** -* ${classInfo.classComment} -* -* Created by wujun on '${.now?string('yyyy-MM-dd HH:mm:ss')}'. -*/ -public interface ${classInfo.className}Service { - - /** - * 新增 - */ - public ReturnT insert(${classInfo.className} ${classInfo.className?uncap_first}); - - /** - * 删除 - */ - public ReturnT delete(int id); - - /** - * 更新 - */ - public ReturnT update(${classInfo.className} ${classInfo.className?uncap_first}); - - /** - * Load查询 - */ - public ${classInfo.className} load(int id); - - /** - * 分页查询 - */ - public Map pageList(int offset, int pagesize); - -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/service_impl.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/service_impl.ftl deleted file mode 100644 index 44ca00df83..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/service_impl.ftl +++ /dev/null @@ -1,85 +0,0 @@ -package ${packageServiceImpl}; - -import org.springframework.stereotype.Service; - -import com.jun.plugin.biz.dao.${classInfo.className}Dao; -import ${packageModel}.${classInfo.className}; -import ${packageService}.${classInfo.className}Service; -import com.jun.plugin.codegenerator.admin.model.ReturnT; - -import javax.annotation.Resource; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** -* ${classInfo.classComment} -* -* Created by wujun on '${.now?string('yyyy-MM-dd HH:mm:ss')}'. -*/ -@Service -public class ${classInfo.className}ServiceImpl implements ${classInfo.className}Service { - - @Resource - private ${classInfo.className}Dao ${classInfo.className?uncap_first}Dao; - - /** - * 新增 - */ - @Override - public ReturnT insert(${classInfo.className} ${classInfo.className?uncap_first}) { - - // valid - if (${classInfo.className?uncap_first} == null) { - return new ReturnT(ReturnT.FAIL_CODE, "必要参数缺失"); - } - - ${classInfo.className?uncap_first}Dao.insert(${classInfo.className?uncap_first}); - return ReturnT.SUCCESS; - } - - /** - * 删除 - */ - @Override - public ReturnT delete(int id) { - int ret = ${classInfo.className?uncap_first}Dao.delete(id); - return ret>0?ReturnT.SUCCESS:ReturnT.FAIL; - } - - /** - * 更新 - */ - @Override - public ReturnT update(${classInfo.className} ${classInfo.className?uncap_first}) { - int ret = ${classInfo.className?uncap_first}Dao.update(${classInfo.className?uncap_first}); - return ret>0?ReturnT.SUCCESS:ReturnT.FAIL; - } - - /** - * Load查询 - */ - @Override - public ${classInfo.className} load(int id) { - return ${classInfo.className?uncap_first}Dao.load(id); - } - - /** - * 分页查询 - */ - @Override - public Map pageList(int offset, int pagesize) { - - List<${classInfo.className}> pageList = ${classInfo.className?uncap_first}Dao.pageList(offset, pagesize); - int totalCount = ${classInfo.className?uncap_first}Dao.pageListCount(offset, pagesize); - - // result - Map result = new HashMap(); - result.put("pageList", pageList); - result.put("totalCount", totalCount); - - return result; - } - -} diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/ui/bootstrap-ui.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/ui/bootstrap-ui.ftl deleted file mode 100644 index eaefd4312d..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/ui/bootstrap-ui.ftl +++ /dev/null @@ -1,13 +0,0 @@ -
- - <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> - <#list classInfo.fieldList as fieldItem > -
- - -
- - - - -
diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/ui/element-ui.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/ui/element-ui.ftl deleted file mode 100644 index 9f9e224d2b..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/ui/element-ui.ftl +++ /dev/null @@ -1,16 +0,0 @@ - - -
- ${classInfo.classComment} - 提交 - 返回 -
- <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> - <#list classInfo.fieldList as fieldItem > - - - - - -
-
\ No newline at end of file diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/ui/layui-edit.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/ui/layui-edit.ftl deleted file mode 100644 index 6299a1b242..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/ui/layui-edit.ftl +++ /dev/null @@ -1,64 +0,0 @@ - - - -
- - - -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> - <#list classInfo.fieldList as fieldItem > -
- -
- - <#--${fieldItem.fieldComment}--> -
-
- - - -
-
- -
-
-
- - - - - \ No newline at end of file diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/ui/layui-list.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/ui/layui-list.ftl deleted file mode 100644 index a3de2993c8..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/ui/layui-list.ftl +++ /dev/null @@ -1,221 +0,0 @@ - - - -
-
- -
- 搜索信息 -
-
-
-
- -
- -
-
-
- -
- -
-
-
- -
-
-
-
-
- - - -
- - - - - -
-
- - - - - - \ No newline at end of file diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/ui/swagger-ui.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/ui/swagger-ui.ftl deleted file mode 100644 index 0e506598d8..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/ui/swagger-ui.ftl +++ /dev/null @@ -1,9 +0,0 @@ -@ApiOperation(value = "${classInfo.classComment}", notes = "${classInfo.classComment}") - @ApiImplicitParams({ - <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> - <#list classInfo.fieldList as fieldItem > - @ApiImplicitParam(name = "${fieldItem.fieldName}", value = "${fieldItem.fieldComment}", required = false, dataType = "${fieldItem.fieldClass}")<#if fieldItem_has_next>, - - - } - ) diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/util/beanutil.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/util/beanutil.ftl deleted file mode 100644 index 108e27af9e..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/util/beanutil.ftl +++ /dev/null @@ -1,41 +0,0 @@ -/** -* ${classInfo.classComment}对象Get Set -* @author ${authorName} ${.now?string('yyyy-MM-dd')} -*/ - -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<#list classInfo.fieldList as fieldItem> -// ${fieldItem.fieldComment} -${fieldItem.fieldClass} ${fieldItem.fieldName} = ${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}(); - - -<#list classInfo.fieldList as fieldItem> -// ${fieldItem.fieldComment} -${classInfo.className?uncap_first}.set${fieldItem.fieldName?cap_first}(); - - -<#list classInfo.fieldList as fieldItem> -// ${fieldItem.fieldComment} -${classInfo.className?uncap_first}.set${fieldItem.fieldName?cap_first}(${classInfo.className?uncap_first}2.get${fieldItem.fieldName?cap_first}()); - - -<#list classInfo.fieldList as fieldItem> -// ${fieldItem.fieldComment} -map.put("${fieldItem.fieldName?uncap_first}",${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}()); - - -<#list classInfo.fieldList as fieldItem> -// ${fieldItem.fieldComment} -map.put("${fieldItem.columnName}",${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}()); - - -<#list classInfo.fieldList as fieldItem> -map.put("${fieldItem.fieldComment}",${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}()); - - -<#list classInfo.fieldList as fieldItem> -// ${fieldItem.fieldComment} -map.put("${fieldItem.fieldName?uncap_first}",${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}()); - - - diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/util/json.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/util/json.ftl deleted file mode 100644 index 596cce40f8..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/util/json.ftl +++ /dev/null @@ -1,13 +0,0 @@ -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -{ -<#list classInfo.fieldList as fieldItem> - "${fieldItem.fieldName}":"${fieldItem.fieldComment}"<#if fieldItem_has_next>, - -} - -{ -<#list classInfo.fieldList as fieldItem> - "${fieldItem.fieldName}":""<#if fieldItem_has_next>, - -} - diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/util/sql.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/util/sql.ftl deleted file mode 100644 index 126f84dc2b..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/util/sql.ftl +++ /dev/null @@ -1,74 +0,0 @@ - -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> - #SQL横向select - SELECT <#list classInfo.fieldList as fieldItem >t.${fieldItem.columnName}<#if fieldItem_has_next>, - FROM ${classInfo.tableName} t; - - #CSV横向字段名 - <#list classInfo.fieldList as fieldItem >${fieldItem.columnName}<#if fieldItem_has_next>, - - -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -#LEFT JOIN - SELECT - * - FROM - ${classInfo.tableName} a - LEFT JOIN ${classInfo.tableName} b - ON a.${classInfo.tableName}_id=b.${classInfo.tableName}_id - WHERE 1=1; - - -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -#INSERT INTO - INSERT INTO ${classInfo.tableName} ( <#list classInfo.fieldList as fieldItem >${fieldItem.columnName}<#if fieldItem_has_next>, ) - VALUES - ( - <#list classInfo.fieldList as fieldItem >''<#if fieldItem_has_next>, - ); - - - -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -#关联更新 - UPDATE ${classInfo.tableName} a - JOIN ${classInfo.tableName}_join b ON a.${classInfo.tableName}_id = b.${classInfo.tableName}_id - SET <#list classInfo.fieldList as fieldItem > a.${fieldItem.columnName} = b.${fieldItem.columnName}<#if fieldItem_has_next>, - WHERE - b.${classInfo.tableName}_id IS NOT NULL; - - UPDATE ${classInfo.tableName} a,${classInfo.tableName}_join b - SET <#list classInfo.fieldList as fieldItem > a.${fieldItem.columnName} = b.${fieldItem.columnName}<#if fieldItem_has_next>, - WHERE a.${classInfo.tableName}_id = b.${classInfo.tableName}_id; - -#普通update - UPDATE ${classInfo.tableName} - SET - <#list classInfo.fieldList as fieldItem > - ${fieldItem.columnName} = ''<#if fieldItem_has_next>, - - WHERE - <#list classInfo.fieldList as fieldItem > - ${fieldItem.columnName} = ''<#if fieldItem_has_next>, - ; - - - - -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -#关联删除 - delete a from ${classInfo.tableName}_del as a inner join ${classInfo.tableName} as b - where a.${classInfo.tableName}_id=b.${classInfo.tableName}_id; - -#普通删除 - DELETE - FROM - ${classInfo.tableName} - WHERE - <#list classInfo.fieldList as fieldItem > - ${fieldItem.columnName} = ''<#if fieldItem_has_next>, - ; - - - - diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/util/swagger-yml.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/util/swagger-yml.ftl deleted file mode 100644 index ce22aaa503..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/util/swagger-yml.ftl +++ /dev/null @@ -1,12 +0,0 @@ - -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -${classInfo.className}: - type: "object" - properties: -<#list classInfo.fieldList as fieldItem > - ${fieldItem.fieldName}: - type: ${fieldItem.swaggerClass} - description: <#if isComment?exists && isComment==true>"${fieldItem.fieldComment}" - - - diff --git a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/util/xml.ftl b/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/util/xml.ftl deleted file mode 100644 index 3959cfcb1d..0000000000 --- a/java_project_template/jun_api_service_simple/src/main/resources/templates/code-generator/util/xml.ftl +++ /dev/null @@ -1,11 +0,0 @@ - -<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> -<${classInfo.className}> -<#list classInfo.fieldList as fieldItem> - <${fieldItem.fieldName}>${fieldItem.fieldComment} - - - diff --git a/java_project_template/jun_api_service_simple/src/test/java/CodeGenerator.java b/java_project_template/jun_api_service_simple/src/test/java/CodeGenerator.java deleted file mode 100644 index b0b61e09d0..0000000000 --- a/java_project_template/jun_api_service_simple/src/test/java/CodeGenerator.java +++ /dev/null @@ -1,45 +0,0 @@ -import com.google.common.collect.Lists; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Arrays; -import java.util.List; - -/** - * 代码生成器,根据DatabaseMetaData及数据表名称生成对应的Model、Mapper、Service、Controller简化基础代码逻辑开发。 - * @author Wujun - */ -public class CodeGenerator { - private static final Logger logger = LoggerFactory.getLogger(CodeGenerator.class); - - public static void main(String[] args) throws Exception { - String tables = "t_admin"; -// String tables = "res_basc,res_basc_arg,api_config"; -// String tables = "git_user"; -// String tables = "app_infoenvt,app_member,app_datasource,app_git_config,git_user,app_deploy_config"; - //GenUtils.isDefaultTemplate = true; - //GenUtils.genTables(GenUtils.getClassInfo(tables.split(",")),getTemplates());; -// GenUtils.genCode(Arrays.asList(tables.split(",")),getTemplates());; - } - - public static List getTemplates() { - List templates = Lists.newArrayList(); - // ************************************************************************************ - templates.add("code-generator/mybatis-plus-single/controller.java.ftl"); - templates.add("code-generator/mybatis-plus-single/entity.java.ftl"); - templates.add("code-generator/mybatis-plus-single/mapper.java.ftl"); - templates.add("code-generator/mybatis-plus-single/service.java.ftl"); - templates.add("code-generator/mybatis-plus-single/dto.java.ftl"); - templates.add("code-generator/mybatis-plus-single/vo.java.ftl"); - templates.add("code-generator/mybatis-plus-single/service.impl.java.ftl"); -// templates.add("code-generator/mybatis-plus-v2/plus-controller.ftl"); -// templates.add("code-generator/mybatis-plus-v2/plus-entity.ftl"); -// templates.add("code-generator/mybatis-plus-v2/plus-mapper.ftl"); -// templates.add("code-generator/mybatis-plus-v2/plus-service.ftl"); -// templates.add("code-generator/mybatis-plus-v2/plus-dto.ftl"); -// templates.add("code-generator/mybatis-plus-v2/plus-vo.ftl"); -// templates.add("code-generator/mybatis-plus-v2/plus-serviceimpl.ftl"); - return templates; - } - -} diff --git a/java_project_template/maven_javaproject/pom.xml b/java_project_template/maven_javaproject/pom.xml deleted file mode 100644 index 9fe2b84c14..0000000000 --- a/java_project_template/maven_javaproject/pom.xml +++ /dev/null @@ -1,73 +0,0 @@ - - 4.0.0 - - com.jun - maven_javaproject - 1.0 - jar - - - - UTF-8 - UTF-8 - 1.8 - 1.8 - 4.3.13.RELEASE - - - - - - org.springframework - spring-context - ${spring.version} - - - - log4j - log4j - 1.2.17 - - - - org.springframework - spring-test - ${spring.version} - - - - org.testng - testng - 6.8 - test - - - - - junit - junit - 4.13.1 - test - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.7.0 - - 1.8 - 1.8 - - - - - - - - - diff --git a/java_project_template/maven_javaproject/src/main/java/com/jun/plugin/teamplate/App.java b/java_project_template/maven_javaproject/src/main/java/com/jun/plugin/teamplate/App.java deleted file mode 100644 index 67c6ead6ad..0000000000 --- a/java_project_template/maven_javaproject/src/main/java/com/jun/plugin/teamplate/App.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.jun.plugin.teamplate; - -/** - * Hello world! - * - */ -public class App { - public static void main( String[] args ) { - System.out.println( "你好 java" ); - } -} diff --git a/java_project_template/maven_javaproject/src/main/resources/applicationContext.xml b/java_project_template/maven_javaproject/src/main/resources/applicationContext.xml deleted file mode 100644 index b28e08e5d0..0000000000 --- a/java_project_template/maven_javaproject/src/main/resources/applicationContext.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/java_project_template/maven_javaproject/src/test/java/com/jun/plugin/teamplate/AppTest.java b/java_project_template/maven_javaproject/src/test/java/com/jun/plugin/teamplate/AppTest.java deleted file mode 100644 index f9808d5da7..0000000000 --- a/java_project_template/maven_javaproject/src/test/java/com/jun/plugin/teamplate/AppTest.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.jun.plugin.teamplate; - -import org.testng.Assert; -import org.testng.annotations.Test; - -@Test -public class AppTest { - - public void testApp() { - Assert.assertEquals(1, 1); - } -} diff --git a/java_project_template/pom.xml b/java_project_template/pom.xml deleted file mode 100644 index 141bb0eefd..0000000000 --- a/java_project_template/pom.xml +++ /dev/null @@ -1,80 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - java_project_template - 1.0 - pom - - - - UTF-8 - 1.8 - 1.8 - - - - - jun_api_service_admin - jun_api_service_demo - jun_api_service_main - jun_api_service_simple - - maven_javaproject - - springboot-api-v2 - - - - - junit - junit - 3.8.1 - test - - - javax.servlet - javax.servlet-api - 3.1.0 - provided - - - mysql - mysql-connector-java - 5.1.40 - - - - - - - jdk-1.8 - - true - 1.8 - - - 1.8 - 1.8 - 1.8 - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.0 - - 1.8 - 1.8 - - - - - \ No newline at end of file diff --git a/java_project_template/springboot-api-jwt/.gitignore b/java_project_template/springboot-api-jwt/.gitignore deleted file mode 100644 index 957445a861..0000000000 --- a/java_project_template/springboot-api-jwt/.gitignore +++ /dev/null @@ -1,23 +0,0 @@ -target/ - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -nbproject/private/ -build/ -nbbuild/ -dist/ -nbdist/ -.nb-gradle/ \ No newline at end of file diff --git a/java_project_template/springboot-api-jwt/README.md b/java_project_template/springboot-api-jwt/README.md deleted file mode 100644 index 2692deaf29..0000000000 --- a/java_project_template/springboot-api-jwt/README.md +++ /dev/null @@ -1,41 +0,0 @@ -## 简介 -Spring Boot API 是一个基于Spring Boot & MyBatis plus的种子项目,用于快速构建中小型API项目,特点稳定、简单、快速,摆脱那些重复劳动 - -## 特征&提供 -- 统一响应结果封装及生成工具 -- 统一异常处理 -- 采用简单的jwt认证 -- 使用Druid Spring Boot Starter 集成Druid数据库连接池与监控 -- 集成MyBatis-Plus,实现单表业务零SQL -- 支持多数据源,自由切换,只需方法或类上用 @DS 切换数据源 -- 集成国人风格的knife4j,自动生成接口文档 -- 提供代码生成器,生成controller,service,serviceImpl,dao,mapper.xml - -## 快速开始 -1. 克隆项目 -2. 导入```test```包里的mysql脚本user.sql -3. 对```test```包内的代码生成器```CodeGenerator```进行配置,主要是JDBC,因为要根据表名来生成代码 -4. 输入表名,运行```CodeGenerator.main()```方法,生成基础代码(可能需要刷新项目目录才会出来) -5. 根据业务在基础代码上进行扩展 -6. 对开发环境配置文件```application-dev.yml```进行配置,启动项目,Have Fun! - -## 开发建议 -- post调用接口ip:8080/api/user/login,参数json: {"username":"admin","password":"123456"},调用成功后, 返回token。以后调用api接口,header中传token -- 正式环境已禁用接口文档的查看,配置文件添加knife4j:production: true 即可 -- Model内成员变量建议与表字段数量对应,如需扩展成员变量(比如连表查询)建议创建DTO,否则需在扩展的成员变量上加@TableField(exist = false),详见[MyBatis-Plus](https://mp.baomidou.com/guide/)文档说明 -- 建议业务失败直接使用ServiceException("ErrorMessage")抛出,由统一异常处理器来封装业务失败的响应结果,会直接被封装为{"code":400,"message":"ErrorMessage"}返回,尽情抛出;body方式传参,@Valid校验Model,更无需自己处理; - -## 接口文档效果图 -![image-20200313084433855](http://tuchuang.aitangbao.com.cn/image-20200313084433855.png) - -## 相关文档 -- Spring Boot([springboot官方](https://spring.io/projects/spring-boot/)) -- MyBatis-Plus ([查看官方中文文档](https://mp.baomidou.com/guide/)) -- MyBatis-Plus分页插件([查看官方中文文档](https://mp.baomidou.com/guide/page.html)) -- Druid Spring Boot Starter([查看官方中文文档](https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter/)) -- Fastjson([查看官方中文文档](https://github.com/Alibaba/fastjson/wiki/%E9%A6%96%E9%A1%B5)) -- 阿里巴巴Java开发手册[最新版下载](https://github.com/alibaba/p3c) -其他 - -## License -纯粹开源分享,感谢大家 [Star](https://github.com/aitangbao/springboot-api) 的支持。 diff --git a/java_project_template/springboot-api-jwt/pom.xml b/java_project_template/springboot-api-jwt/pom.xml deleted file mode 100644 index a11f7d522d..0000000000 --- a/java_project_template/springboot-api-jwt/pom.xml +++ /dev/null @@ -1,156 +0,0 @@ - - - 4.0.0 - - com.company.project - springboot-api-jwt - 1.0 - jar - - - 1.8 - 3.3.0 - - - - - org.springframework.boot - spring-boot-starter-parent - 2.2.2.RELEASE - - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-jdbc - - - org.springframework.boot - spring-boot-starter-test - test - - - - com.baomidou - dynamic-datasource-spring-boot-starter - 2.5.5 - - - com.baomidou - mybatis-plus - ${mybatis-plus.version} - - - com.baomidou - mybatis-plus-boot-starter - ${mybatis-plus.version} - - - com.baomidou - mybatis-plus-generator - ${mybatis-plus.version} - - - org.projectlombok - lombok - 1.18.10 - provided - - - - - - commons-codec - commons-codec - - - org.apache.commons - commons-lang3 - 3.6 - - - - mysql - mysql-connector-java - runtime - - - - - com.alibaba - fastjson - 1.2.47 - - - - com.alibaba - druid-spring-boot-starter - 1.1.10 - - - - org.freemarker - freemarker - 2.3.30 - test - - - - com.github.xiaoymin - knife4j-spring-boot-starter - 2.0.2 - - - - io.jsonwebtoken - jjwt - 0.9.0 - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - maven-compiler-plugin - - ${java.version} - ${java.version} - UTF-8 - - - - - - - - aliyun-repos - http://maven.aliyun.com/nexus/content/groups/public/ - - false - - - - - - - aliyun-plugin - http://maven.aliyun.com/nexus/content/groups/public/ - - false - - - - - \ No newline at end of file diff --git a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/Application.java b/java_project_template/springboot-api-jwt/src/main/java/com/company/project/Application.java deleted file mode 100644 index 2d366a4211..0000000000 --- a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/Application.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.company.project; - -import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure; -import org.mybatis.spring.annotation.MapperScan; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.env.Environment; -import springfox.documentation.swagger2.annotations.EnableSwagger2; - -import java.net.InetAddress; - -@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class) -@MapperScan("com.company.project.dao") -public class Application { - - private static Logger logger= LoggerFactory.getLogger(Application.class); - - public static void main(String[] args) throws Exception { - - ConfigurableApplicationContext application = SpringApplication.run(Application.class, args); - - Environment env = application.getEnvironment(); - logger.info("\n----------------------------------------------------------\n\t" + - "Application '{}' is running! Access URLs:\n\t" + - "Local: \t\thttp://localhost:{}\n\t" + - "External: \thttp://{}:{}\n\t" + - "Doc: \thttp://{}:{}/doc.html\n" + - "----------------------------------------------------------", - env.getProperty("spring.application.name"), - env.getProperty("server.port"), - InetAddress.getLocalHost().getHostAddress(), - env.getProperty("server.port"), - InetAddress.getLocalHost().getHostAddress(), - env.getProperty("server.port")); - } -} - diff --git a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/configurer/LoginInterceptor.java b/java_project_template/springboot-api-jwt/src/main/java/com/company/project/configurer/LoginInterceptor.java deleted file mode 100644 index 16e66ea0c8..0000000000 --- a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/configurer/LoginInterceptor.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.company.project.configurer; - - -import com.alibaba.fastjson.JSON; -import com.company.project.core.Result; -import com.company.project.core.ResultCode; -import com.company.project.utils.JwtUtils; -import io.jsonwebtoken.Claims; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import java.io.IOException; - -import static com.company.project.utils.JwtUtils.USER_ACCOUNT_KEY; -import static com.company.project.utils.JwtUtils.USER_ID_KEY; - -/** - *

登陆拦截器 - */ -public class LoginInterceptor extends HandlerInterceptorAdapter { - - private final Logger logger = LoggerFactory.getLogger(WebMvcConfigurer.class); - @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - //拦截接口 - //从header中获取token - String token = request.getHeader("token"); - //如果header中不存在token,则从参数中获取token - if(StringUtils.isBlank(token)){ - token = request.getParameter("token"); - } - //token为空返回 - if(StringUtils.isBlank(token)){ - Result result = new Result(); - result.setCode(ResultCode.UNAUTHORIZED).setMessage("token不能为空").setSuccess(false); - responseResult(response, result); - return false; - }// 校验并解析token,如果token过期或者篡改,则会返回null - Claims claims = JwtUtils.checkJWT(token); - if(null == claims){ - Result result = new Result(); - result.setCode(ResultCode.UNAUTHORIZED).setMessage("登陆失效, 请重新登陆").setSuccess(false); - responseResult(response, result); - return false; - } - // 校验通过后,设置用户信息到request里,在Controller中从Request域中获取用户信息 - request.setAttribute(USER_ID_KEY, claims.get("id")); - request.setAttribute(USER_ACCOUNT_KEY, claims.get("account")); - return true; - } - - - - private void responseResult(HttpServletResponse response, Result result) { - response.setCharacterEncoding("UTF-8"); - response.setHeader("Content-type", "application/json;charset=UTF-8"); - response.setStatus(200); - try { - response.getWriter().write(JSON.toJSONString(result)); - } catch (IOException ex) { - logger.error(ex.getMessage()); - } - } -} diff --git a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/configurer/MyBatisPlusConfig.java b/java_project_template/springboot-api-jwt/src/main/java/com/company/project/configurer/MyBatisPlusConfig.java deleted file mode 100644 index f75a63819c..0000000000 --- a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/configurer/MyBatisPlusConfig.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.company.project.configurer; - -import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * @ClassName MyBatisPlusConfig - * @Version 1.0 - **/ -@Configuration -public class MyBatisPlusConfig { - /** - * 配置mybatis-plus 分页查件 - * @return - */ - @Bean - public PaginationInterceptor paginationInterceptor() { - PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); - return paginationInterceptor; - } -} \ No newline at end of file diff --git a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/configurer/SwaggerConfiguration.java b/java_project_template/springboot-api-jwt/src/main/java/com/company/project/configurer/SwaggerConfiguration.java deleted file mode 100644 index d5bca5303f..0000000000 --- a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/configurer/SwaggerConfiguration.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.company.project.configurer; - -import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration; -import springfox.documentation.builders.ApiInfoBuilder; -import springfox.documentation.builders.PathSelectors; -import springfox.documentation.builders.RequestHandlerSelectors; -import springfox.documentation.service.ApiInfo; -import springfox.documentation.spi.DocumentationType; -import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger2.annotations.EnableSwagger2; - -@Configuration -@EnableSwagger2 -@EnableKnife4j -@Import(BeanValidatorPluginsConfiguration.class) -public class SwaggerConfiguration { - - @Bean - public Docket createRestApi() { - return new Docket(DocumentationType.SWAGGER_2) - .apiInfo(apiInfo()) - .select() - .apis(RequestHandlerSelectors.basePackage("com.company.project.web")) - .paths(PathSelectors.any()) - .build(); - } - - private ApiInfo apiInfo() { - return new ApiInfoBuilder() - .title("Springboot-api APIs") - .description("Springboot-api APIs") - .termsOfServiceUrl("http://localhost:8080/") - .contact("xxxxxxxxxx@163.com") - .version("1.0") - .build(); - } -} \ No newline at end of file diff --git a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/configurer/WebMvcConfigurer.java b/java_project_template/springboot-api-jwt/src/main/java/com/company/project/configurer/WebMvcConfigurer.java deleted file mode 100644 index e790419d9b..0000000000 --- a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/configurer/WebMvcConfigurer.java +++ /dev/null @@ -1,178 +0,0 @@ -package com.company.project.configurer; - -import java.io.IOException; -import java.nio.charset.Charset; -import java.util.Arrays; -import java.util.List; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.serializer.SerializerFeature; -import com.alibaba.fastjson.support.config.FastJsonConfig; -import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; - -import com.company.project.core.Result; -import com.company.project.core.ResultCode; -import com.company.project.core.ResultGenerator; -import com.company.project.core.ServiceException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.MediaType; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.web.bind.MethodArgumentNotValidException; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.method.HandlerMethod; -import org.springframework.web.servlet.HandlerExceptionResolver; -import org.springframework.web.servlet.ModelAndView; -import org.springframework.web.servlet.NoHandlerFoundException; -import org.springframework.web.servlet.config.annotation.*; - -/** - * Spring MVC 配置 - */ -@Configuration -public class WebMvcConfigurer extends WebMvcConfigurerAdapter { - - private final Logger logger = LoggerFactory.getLogger(WebMvcConfigurer.class); - - @Bean - LoginInterceptor loginInterceptor() { - - return new LoginInterceptor(); - } - - //使用阿里 FastJson 作为JSON MessageConverter - @Override - public void configureMessageConverters(List> converters) { - FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); - FastJsonConfig config = new FastJsonConfig(); - config.setSerializerFeatures(SerializerFeature.WriteMapNullValue);//保留空的字段 - //SerializerFeature.WriteNullStringAsEmpty,//String null -> "" - //SerializerFeature.WriteNullNumberAsZero//Number null -> 0 - // 按需配置,更多参考FastJson文档哈 - - converter.setFastJsonConfig(config); - converter.setDefaultCharset(Charset.forName("UTF-8")); - converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON_UTF8)); - converters.add(converter); - } - - - //统一异常处理 - @Override - public void configureHandlerExceptionResolvers(List exceptionResolvers) { - exceptionResolvers.add(new HandlerExceptionResolver() { - public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) { - Result result = new Result(); - if (e instanceof ServiceException) {//业务失败的异常,如“账号或密码错误” - result.setCode(ResultCode.FAIL).setMessage(e.getMessage()).setSuccess(false); - } else if (e instanceof MethodArgumentNotValidException) {//@valid注解验证参数 - MethodArgumentNotValidException m = (MethodArgumentNotValidException) e; - m.getBindingResult().getFieldError().getDefaultMessage(); - result.setCode(ResultCode.PARAM_FAIL).setMessage(m.getBindingResult().getFieldError().getDefaultMessage()).setSuccess(false); - } else if (e instanceof NoHandlerFoundException) { - result.setCode(ResultCode.NOT_FOUND).setMessage("接口 [" + request.getRequestURI() + "] 不存在").setSuccess(false); - } else if (e instanceof ServletException) { - result.setCode(ResultCode.FAIL).setMessage(e.getMessage()).setSuccess(false); - } else { - result.setCode(ResultCode.INTERNAL_SERVER_ERROR).setMessage("接口 [" + request.getRequestURI() + "] 内部错误,请联系管理员").setSuccess(false); - String message; - if (handler instanceof HandlerMethod) { - HandlerMethod handlerMethod = (HandlerMethod) handler; - message = String.format("接口 [%s] 出现异常,方法:%s.%s,异常摘要:%s", - request.getRequestURI(), - handlerMethod.getBean().getClass().getName(), - handlerMethod.getMethod().getName(), - e.getMessage()); - } else { - message = e.getMessage(); - } - logger.error(message, e); - } - responseResult(response, result); - return new ModelAndView(); - } - - }); - } - - @ExceptionHandler(MethodArgumentNotValidException.class) - public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { - return ResultGenerator.genFailResult(e.getBindingResult().getFieldError().getDefaultMessage()); - } - - /** - * 页面跨域访问Controller过滤 - * - * @return - */ - @Override - public void addCorsMappings(CorsRegistry registry) { - WebMvcConfigurer.super.addCorsMappings(registry); - registry.addMapping("/**") - .allowedHeaders("*") - .allowedMethods("POST","GET") - .allowedOrigins("*"); - } - - //添加拦截器 - @Override - public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(loginInterceptor()) - .excludePathPatterns("/doc.html") - .excludePathPatterns("/swagger-resources/**") - .excludePathPatterns("/error") - .excludePathPatterns("/webjars/**") - .excludePathPatterns("/api/user/login") - .excludePathPatterns("/api/user/register") - .addPathPatterns("/**"); - } - - - private void responseResult(HttpServletResponse response, Result result) { - response.setCharacterEncoding("UTF-8"); - response.setHeader("Content-type", "application/json;charset=UTF-8"); - response.setStatus(200); - try { - response.getWriter().write(JSON.toJSONString(result)); - } catch (IOException ex) { - logger.error(ex.getMessage()); - } - } - - /** - * 发现如果继承了WebMvcConfigurationSupport,则在yml中配置的相关内容会失效。 需要重新指定静态资源 - * - * @param registry - */ - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("/**").addResourceLocations( - "classpath:/static/"); - registry.addResourceHandler("doc.html").addResourceLocations( - "classpath:/META-INF/resources/"); - registry.addResourceHandler("/webjars/**").addResourceLocations( - "classpath:/META-INF/resources/webjars/"); - super.addResourceHandlers(registry); - } - - - /** - * 配置servlet处理 - */ - @Override - public void configureDefaultServletHandling( - DefaultServletHandlerConfigurer configurer) { - configurer.enable(); - } - - - - -} - diff --git a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/core/ApplicationContextUtil.java b/java_project_template/springboot-api-jwt/src/main/java/com/company/project/core/ApplicationContextUtil.java deleted file mode 100644 index 8121fb4b4b..0000000000 --- a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/core/ApplicationContextUtil.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.company.project.core; - -import org.springframework.beans.BeansException; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.stereotype.Component; - -/** - * @className: ApplicationContextUtil - * @Description: 解决定时任务获取不到service的问题 - * @Author moneylee - * @Date 2019-05-11 14:28 - * @Version 1.0 - **/ -@Component -public class ApplicationContextUtil implements ApplicationContextAware { - - private static ApplicationContext applicationContext; - - public static ApplicationContext getApplicationContext() { - return applicationContext; - } - - - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - ApplicationContextUtil.applicationContext = applicationContext; - - } - - public static Object getBean(String beanName) { - return applicationContext.getBean(beanName); - } - -} \ No newline at end of file diff --git a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/core/Result.java b/java_project_template/springboot-api-jwt/src/main/java/com/company/project/core/Result.java deleted file mode 100644 index b208a52ae2..0000000000 --- a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/core/Result.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.company.project.core; - -import com.alibaba.fastjson.JSON; - -/** - * 统一API响应结果封装 - */ -public class Result { - private int code; - private String message; - private T data; - private Boolean success; - - public Result setCode(ResultCode resultCode) { - this.code = resultCode.code(); - return this; - } - - public int getCode() { - return code; - } - - public String getMessage() { - return message; - } - - public Result setMessage(String message) { - this.message = message; - return this; - } - - public T getData() { - return data; - } - - public Result setData(T data) { - this.data = data; - return this; - } - - public Boolean getSuccess() { - return success; - } - - public Result setSuccess(Boolean success) { - this.success = success; - return this; - } - - @Override - public String toString() { - return JSON.toJSONString(this); - } -} diff --git a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/core/ResultCode.java b/java_project_template/springboot-api-jwt/src/main/java/com/company/project/core/ResultCode.java deleted file mode 100644 index 651c04d826..0000000000 --- a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/core/ResultCode.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.company.project.core; - -/** - * 响应码枚举,参考HTTP状态码的语义 - */ -public enum ResultCode { - SUCCESS(200),//成功 - FAIL(400),//失败 - UNAUTHORIZED(401),//未认证(签名错误) - NOT_FOUND(404),//接口不存在 - INTERNAL_SERVER_ERROR(500),//服务器内部错误 - PARAM_FAIL(10001);//参数异常 - - private final int code; - - ResultCode(int code) { - this.code = code; - } - - public int code() { - return code; - } -} diff --git a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/core/ResultGenerator.java b/java_project_template/springboot-api-jwt/src/main/java/com/company/project/core/ResultGenerator.java deleted file mode 100644 index de79f955e9..0000000000 --- a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/core/ResultGenerator.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.company.project.core; - -/** - * 响应结果生成工具 - */ -public class ResultGenerator { - private static final String DEFAULT_SUCCESS_MESSAGE = "SUCCESS"; - - public static Result genSuccessResult() { - return new Result() - .setSuccess(true) - .setCode(ResultCode.SUCCESS) - .setMessage(DEFAULT_SUCCESS_MESSAGE); - } - - public static Result genSuccessResult(T data) { - return new Result() - .setSuccess(true) - .setCode(ResultCode.SUCCESS) - .setMessage(DEFAULT_SUCCESS_MESSAGE) - .setData(data); - } - - public static Result genFailResult(String message) { - return new Result() - .setSuccess(false) - .setCode(ResultCode.FAIL) - .setMessage(message); - } -} diff --git a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/core/ServiceException.java b/java_project_template/springboot-api-jwt/src/main/java/com/company/project/core/ServiceException.java deleted file mode 100644 index e698bce9da..0000000000 --- a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/core/ServiceException.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.company.project.core; - -/** - * 服务(业务)异常如“ 账号或密码错误 ”,该异常只做INFO级别的日志记录 @see WebMvcConfigurer - */ -public class ServiceException extends RuntimeException { - public ServiceException() { - } - - public ServiceException(String message) { - super(message); - } - - public ServiceException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/dao/UserMapper.java b/java_project_template/springboot-api-jwt/src/main/java/com/company/project/dao/UserMapper.java deleted file mode 100644 index f731dd72d1..0000000000 --- a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/dao/UserMapper.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.company.project.dao; - -import com.company.project.model.User; -import com.baomidou.mybatisplus.core.mapper.BaseMapper; - -/** - *

- * Mapper 接口 - *

- * - * @author project - * @since 2020-01-08 - */ -public interface UserMapper extends BaseMapper { - -} diff --git a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/model/User.java b/java_project_template/springboot-api-jwt/src/main/java/com/company/project/model/User.java deleted file mode 100644 index ccb159e35c..0000000000 --- a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/model/User.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.company.project.model; - -import com.baomidou.mybatisplus.annotation.IdType; -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableId; -import com.baomidou.mybatisplus.annotation.TableLogic; -import java.io.Serializable; -import java.util.Date; - -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.experimental.Accessors; - -import javax.validation.constraints.NotEmpty; - -/** - *

- * - *

- * - * @author project - * @since 2020-01-08 - */ -@Data -@EqualsAndHashCode(callSuper = false) -@Accessors(chain = true) -public class User implements Serializable { - - private static final long serialVersionUID = 1L; - - /** - * 主键 - */ - @TableId(value = "id", type = IdType.AUTO) - private Integer id; - - /** - * 用户名 - */ - @NotEmpty(message = "用户名不能为空!") - private String username; - - /** - * 密码 - */ - @NotEmpty(message = "密码不能为空!") - private String password; - - /** - * 昵称 - */ - private String nickName; - - /** - * 性别 - */ - private Integer sex; - - /** - * 创建时间 - */ - private Date createDate; - - /** - * 创建人 - */ - private Integer createUser; - - /** - * 修改时间 - */ - private Date updateDate; - - /** - * 修改人 - */ - private Integer updateUser; - - /** - * 删除标志0未删 1删除 - */ - @TableLogic - private Integer delFlag; - - /** - * 登陆返回token - */ - @TableField(exist = false) - private String token; - -} diff --git a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/service/IUserService.java b/java_project_template/springboot-api-jwt/src/main/java/com/company/project/service/IUserService.java deleted file mode 100644 index c6ea45ce7e..0000000000 --- a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/service/IUserService.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.company.project.service; - -import com.company.project.model.User; -import com.baomidou.mybatisplus.extension.service.IService; - -/** - *

- * 服务类 - *

- * - * @author project - * @since 2020-01-08 - */ -public interface IUserService extends IService { - -} diff --git a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/service/impl/UserServiceImpl.java b/java_project_template/springboot-api-jwt/src/main/java/com/company/project/service/impl/UserServiceImpl.java deleted file mode 100644 index 83f0a1a11d..0000000000 --- a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/service/impl/UserServiceImpl.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.company.project.service.impl; - -import com.company.project.model.User; -import com.company.project.dao.UserMapper; -import com.company.project.service.IUserService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import org.springframework.stereotype.Service; - -/** - *

- * 服务实现类 - *

- * - * @author project - * @since 2020-01-08 - */ -@Service -public class UserServiceImpl extends ServiceImpl implements IUserService { - -} diff --git a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/utils/JwtUtils.java b/java_project_template/springboot-api-jwt/src/main/java/com/company/project/utils/JwtUtils.java deleted file mode 100644 index 7cf948ef1b..0000000000 --- a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/utils/JwtUtils.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.company.project.utils; - -import com.company.project.model.User; -import io.jsonwebtoken.Claims; -import io.jsonwebtoken.Jwts; -import io.jsonwebtoken.SignatureAlgorithm; - -import javax.servlet.http.HttpServletRequest; -import java.util.Date; - -/** - * jwt工具类 - */ -public class JwtUtils { - - public static final String USER_ID_KEY = "user_id_key"; - - public static final String USER_ACCOUNT_KEY = "user_account_key"; - - - public static final String SUBJECT = "onehee"; - - public static final long EXPIRE = 1000*60*60*24*7; //过期时间,毫秒,一周 - - //秘钥 - public static final String APPSECRET = "onehee666"; - - /** - * 生成jwt - * @param user - * @return - */ - public static String geneJsonWebToken(User user){ - - String token = Jwts.builder().setSubject(SUBJECT) - .claim("id",user.getId()) - .claim("userName",user.getUsername()) - .setIssuedAt(new Date()) - .setExpiration(new Date(System.currentTimeMillis()+EXPIRE)) - .signWith(SignatureAlgorithm.HS256,APPSECRET).compact(); - - return token; - } - - - /** - * 校验token - * @param token - * @return - */ - public static Claims checkJWT(String token ){ - - try{ - final Claims claims = Jwts.parser().setSigningKey(APPSECRET). - parseClaimsJws(token).getBody(); - return claims; - - }catch (Exception e){ } - return null; - - } - - - /** - * 判断当前登陆用户是不是admin - * @param request - * @return - */ - public static boolean isAdmin(HttpServletRequest request) { - if (request.getAttribute(USER_ACCOUNT_KEY) == null) { - return false; - } - if ("admin".equals(request.getAttribute(USER_ACCOUNT_KEY).toString())){ - return true; - } else { - return false; - } - } - - - -} \ No newline at end of file diff --git a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/utils/MD5Utils.java b/java_project_template/springboot-api-jwt/src/main/java/com/company/project/utils/MD5Utils.java deleted file mode 100644 index c7a3dff75c..0000000000 --- a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/utils/MD5Utils.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.company.project.utils; - -import org.apache.commons.codec.digest.DigestUtils; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.StringUtils; - -public class MD5Utils { - - private static String salt = "springboot_api"; - - /** - * 加密字符串 - * @param password 要加密的明文 - * @param isAddSalt 是否加默认盐 - * @return 加密之后的结果 - */ - public static String Encrypt(String password, boolean isAddSalt){ - if (StringUtils.isNotEmpty(password)){ - if (isAddSalt){ - return DigestUtils.md5Hex(DigestUtils.md5(password + salt)); - } else { - return DigestUtils.md5Hex(DigestUtils.md5(password)); - } - } - return null; - } - - /** - * - * @param bytes - * @return - */ - public static String Encrypt(byte[] bytes){ - if (ArrayUtils.isNotEmpty(bytes)){ - return DigestUtils.md5Hex(DigestUtils.md5(bytes)); - } - return null; - } - - /** - * MD5加盐加密 - * @param password 要加密的明文 - * @param salt 盐 - * @return 加密之后的结果 - */ - public static String Encrypt(String password, String salt){ - if (StringUtils.isNotEmpty(password)){ - return DigestUtils.md5Hex(DigestUtils.md5(password + salt)); - } - return null; - } - - public static void main(String[] args){ - System.out.println(MD5Utils.Encrypt("admin", true)); - } -} diff --git a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/web/UserController.java b/java_project_template/springboot-api-jwt/src/main/java/com/company/project/web/UserController.java deleted file mode 100644 index 303acb3819..0000000000 --- a/java_project_template/springboot-api-jwt/src/main/java/com/company/project/web/UserController.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.company.project.web; - -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.company.project.core.Result; -import com.company.project.core.ResultGenerator; -import com.company.project.utils.JwtUtils; -import com.company.project.utils.MD5Utils; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import org.springframework.web.bind.annotation.*; -import com.company.project.service.IUserService; -import com.company.project.model.User; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import lombok.extern.slf4j.Slf4j; -import com.baomidou.mybatisplus.core.metadata.IPage; - -import javax.annotation.Resource; -import javax.validation.Valid; - -import org.springframework.web.bind.annotation.RestController; - -/** - *

- * 前端控制器 - *

- * - * @author project - * @since 2020-01-08 - */ -@Slf4j -@RestController -@RequestMapping("/api/user") -public class UserController { - - @Resource - private IUserService userService; - - @ApiOperation("登陆") - @PostMapping("/login") - public Result login(@RequestBody @Valid User user) { - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.eq("username", user.getUsername()); - User userO = userService.getOne(queryWrapper); - if (userO == null) { - return ResultGenerator.genFailResult("账号未找到"); - } - if (!MD5Utils.Encrypt(user.getPassword(),true).equals(userO.getPassword())) { - return ResultGenerator.genFailResult("密码错误"); - } - String token = JwtUtils.geneJsonWebToken(user); - user.setToken(token); - user.setPassword(""); - return ResultGenerator.genSuccessResult(user); - } - - @ApiOperation("注册") - @PostMapping("/register") - public Result register(@RequestBody @Valid User user) { - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.eq("username", user.getUsername()); - User userO = userService.getOne(queryWrapper); - if (userO != null) { - return ResultGenerator.genFailResult("账号已存在"); - } - user.setPassword(MD5Utils.Encrypt(user.getPassword(),true)); - userService.save(user); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "删除") - @PostMapping("delete/{id}") - public Result delete(@PathVariable("id") Long id){ - userService.removeById(id); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "更新") - @PostMapping("update") - public Result update(@RequestBody User user){ - //密码不更新 - user.setPassword(null); - userService.updateById(user); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "查询分页数据") - @ApiImplicitParams({ - @ApiImplicitParam(name = "currentPage", value = "页码"), - @ApiImplicitParam(name = "pageCount", value = "每页条数") - }) - @GetMapping("listByPage") - public Result findListByPage(@RequestParam(defaultValue = "1") Integer currentPage, - @RequestParam(defaultValue = "10") Integer pageCount){ - Page page = new Page(currentPage, pageCount); - IPage iPage = userService.page(page); - return ResultGenerator.genSuccessResult(iPage); - } - - @ApiOperation(value = "id查询") - @GetMapping("getById/{id}") - public Result findById(@PathVariable Long id){ - return ResultGenerator.genSuccessResult(userService.getById(id)); - } - -} diff --git a/java_project_template/springboot-api-jwt/src/main/resources/application-dev.yml b/java_project_template/springboot-api-jwt/src/main/resources/application-dev.yml deleted file mode 100644 index bbf43f9efb..0000000000 --- a/java_project_template/springboot-api-jwt/src/main/resources/application-dev.yml +++ /dev/null @@ -1,31 +0,0 @@ -# 开发环境配置 -spring: - datasource: - dynamic: - primary: master #设置默认的数据源或者数据源组,默认值即为master - datasource: - master: - username: root - password: 123456 - driver-class-name: com.mysql.cj.jdbc.Driver - url: jdbc:mysql://localhost:3306/project?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2b8 - slave_1: - username: root - password: 123456 - driver-class-name: com.mysql.cj.jdbc.Driver - url: jdbc:mysql://xx.xx.xx.xx:3307/dynamic?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2b8 - slave_2: - username: root - password: 123456 - driver-class-name: com.mysql.cj.jdbc.Driver - url: jdbc:mysql://xx.xx.xx.xx:3308/dynamic?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2b8 - #......省略 - #以上会配置一个默认库master,一个组slave下有两个子库slave_1,slave_2 -mybatis-plus: - configuration: - log-impl: org.apache.ibatis.logging.stdout.StdOutImpl - mapper-locations: classpath:mapper/*.xml - global-config: - db-config: - logic-delete-value: 1 - logic-not-delete-value: 0 diff --git a/java_project_template/springboot-api-jwt/src/main/resources/application-prod.yml b/java_project_template/springboot-api-jwt/src/main/resources/application-prod.yml deleted file mode 100644 index 50dcaed189..0000000000 --- a/java_project_template/springboot-api-jwt/src/main/resources/application-prod.yml +++ /dev/null @@ -1,3 +0,0 @@ -# 生产环境配置 -knife4j: - production: true #生成环境禁用查看接口文档 diff --git a/java_project_template/springboot-api-jwt/src/main/resources/application-test.yml b/java_project_template/springboot-api-jwt/src/main/resources/application-test.yml deleted file mode 100644 index 287da7b20e..0000000000 --- a/java_project_template/springboot-api-jwt/src/main/resources/application-test.yml +++ /dev/null @@ -1 +0,0 @@ -# 测试环境配置 diff --git a/java_project_template/springboot-api-jwt/src/main/resources/application.yml b/java_project_template/springboot-api-jwt/src/main/resources/application.yml deleted file mode 100644 index facce6d372..0000000000 --- a/java_project_template/springboot-api-jwt/src/main/resources/application.yml +++ /dev/null @@ -1,14 +0,0 @@ -spring: - profiles: - active: dev - mvc: - throw-exception-if-no-handler-found: true - resources: - add-mappings: false - application: - name: Springboot-api - jackson: - date-format: yyyy-MM-dd HH:mm:ss - time-zone: GMT+8 -server: - port: 8080 diff --git a/java_project_template/springboot-api-jwt/src/main/resources/banner.txt b/java_project_template/springboot-api-jwt/src/main/resources/banner.txt deleted file mode 100644 index 152e179398..0000000000 --- a/java_project_template/springboot-api-jwt/src/main/resources/banner.txt +++ /dev/null @@ -1,22 +0,0 @@ -//////////////////////////////////////////////////////////////////// -// _ooOoo_ // -// o8888888o // -// 88" . "88 // -// (| ^_^ |) // -// O\ = /O // -// ____/`---'\____ // -// .' \\| |// `. // -// / \\||| : |||// \ // -// / _||||| -:- |||||- \ // -// | | \\\ - /// | | // -// | \_| ''\---/'' | | // -// \ .-\__ `-` ___/-. / // -// ___`. .' /--.--\ `. . ___ // -// ."" '< `.___\_<|>_/___.' >'"". // -// | | : `- \`.;`\ _ /`;.`/ - ` : | | // -// \ \ `-. \_ __\ /__ _/ .-` / / // -// ========`-.____`-.___\_____/___.-`____.-'======== // -// `=---=' // -// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // -// 佛祖保佑 永不宕机 永无BUG // -//////////////////////////////////////////////////////////////////// \ No newline at end of file diff --git a/java_project_template/springboot-api-jwt/src/main/resources/mapper/UserMapper.xml b/java_project_template/springboot-api-jwt/src/main/resources/mapper/UserMapper.xml deleted file mode 100644 index 87ab7e4161..0000000000 --- a/java_project_template/springboot-api-jwt/src/main/resources/mapper/UserMapper.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - id, username, password, nick_name, sex, create_date, create_user, update_date, update_user, del_flag - - - \ No newline at end of file diff --git a/java_project_template/springboot-api-jwt/src/test/java/CodeGenerator.java b/java_project_template/springboot-api-jwt/src/test/java/CodeGenerator.java deleted file mode 100644 index 1c3b5f2dd8..0000000000 --- a/java_project_template/springboot-api-jwt/src/test/java/CodeGenerator.java +++ /dev/null @@ -1,113 +0,0 @@ -import com.baomidou.mybatisplus.core.toolkit.StringPool; -import com.baomidou.mybatisplus.generator.AutoGenerator; -import com.baomidou.mybatisplus.generator.InjectionConfig; -import com.baomidou.mybatisplus.generator.config.*; -import com.baomidou.mybatisplus.generator.config.po.TableInfo; -import com.baomidou.mybatisplus.generator.config.rules.DateType; -import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; -import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; - -import java.util.ArrayList; -import java.util.List; - -// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中 -public class CodeGenerator { - - - //多个表逗号分隔 - static String tableName = "user_copy"; - //逻辑删除字段名, 假如表没有逻辑删除字段,请忽视 - static String logicDeleteFieldName = "del_flag"; - - public static void main(String[] args) { - // 代码生成器 - AutoGenerator mpg = new AutoGenerator(); - - // 全局配置 - GlobalConfig gc = new GlobalConfig(); - String projectPath = System.getProperty("user.dir"); - gc.setOutputDir(projectPath + "/src/main/java"); - gc.setAuthor("aitangbao"); - gc.setOpen(false); - gc.setBaseColumnList(true); - gc.setBaseResultMap(true); - gc.setDateType(DateType.ONLY_DATE); - // gc.setSwagger2(true); 实体属性 Swagger2 注解 - mpg.setGlobalConfig(gc); - - // 数据源配置 - DataSourceConfig dsc = new DataSourceConfig(); - dsc.setUrl("jdbc:mysql://localhost:3306/project?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC"); - // dsc.setSchemaName("public"); - dsc.setDriverName("com.mysql.cj.jdbc.Driver"); - dsc.setUsername("root"); - dsc.setPassword("123456"); - mpg.setDataSource(dsc); - - // 包配置 - PackageConfig pc = new PackageConfig(); - pc.setParent("com.company.project"); - pc.setEntity("model"); - pc.setMapper("dao"); - pc.setController("web"); - mpg.setPackageInfo(pc); - - // 自定义配置 - InjectionConfig cfg = new InjectionConfig() { - @Override - public void initMap() { - // to do nothing - } - }; - - // 如果模板引擎是 freemarker - String templatePath = "/templates/mapper.xml.ftl"; - // 如果模板引擎是 velocity - // String templatePath = "/templates/mapper.xml.vm"; - - // 自定义输出配置 - List focList = new ArrayList<>(); - // 自定义配置会被优先输出 - focList.add(new FileOutConfig(templatePath) { - @Override - public String outputFile(TableInfo tableInfo) { - // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!! - return projectPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; - } - }); - cfg.setFileOutConfigList(focList); - mpg.setCfg(cfg); - - // 配置模板 - TemplateConfig templateConfig = new TemplateConfig(); - - // 配置自定义输出模板 - //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别 -// templateConfig.setEntity("templates/entity.java"); - // templateConfig.setService(); - templateConfig.setController("templates/controller.java"); - - templateConfig.setXml(null); - mpg.setTemplate(templateConfig); - - // 策略配置 - StrategyConfig strategy = new StrategyConfig(); - strategy.setNaming(NamingStrategy.underline_to_camel); - strategy.setColumnNaming(NamingStrategy.underline_to_camel); -// strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!"); - strategy.setEntityLombokModel(true); - strategy.setRestControllerStyle(true); - // 公共父类 -// strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!"); - // 写于父类中的公共字段 -// strategy.setSuperEntityColumns("id"); - strategy.setInclude(tableName.split(",")); - strategy.setControllerMappingHyphenStyle(true); - strategy.setLogicDeleteFieldName(logicDeleteFieldName); // 逻辑删除字段名称 - strategy.setTablePrefix(pc.getModuleName() + "_"); - mpg.setStrategy(strategy); - mpg.setTemplateEngine(new FreemarkerTemplateEngine()); - mpg.execute(); - } - -} \ No newline at end of file diff --git a/java_project_template/springboot-api-jwt/src/test/java/com/company/project/Tester.java b/java_project_template/springboot-api-jwt/src/test/java/com/company/project/Tester.java deleted file mode 100644 index f513bc219d..0000000000 --- a/java_project_template/springboot-api-jwt/src/test/java/com/company/project/Tester.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.company.project; - -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(classes = Application.class) -public class Tester { - - @Test - public void test() { - - } -} - - - diff --git a/java_project_template/springboot-api-jwt/src/test/resources/templates/controller.java.ftl b/java_project_template/springboot-api-jwt/src/test/resources/templates/controller.java.ftl deleted file mode 100644 index a62f181707..0000000000 --- a/java_project_template/springboot-api-jwt/src/test/resources/templates/controller.java.ftl +++ /dev/null @@ -1,94 +0,0 @@ -package ${package.Controller}; - -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.company.project.core.Result; -import com.company.project.core.ResultGenerator; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import org.springframework.web.bind.annotation.*; -import ${package.Service}.${table.serviceName}; -import ${package.Entity}.${entity}; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import lombok.extern.slf4j.Slf4j; -import com.baomidou.mybatisplus.core.metadata.IPage; - -import javax.annotation.Resource; -<#if restControllerStyle> -import org.springframework.web.bind.annotation.RestController; -<#else> -import org.springframework.stereotype.Controller; - -<#if superControllerClassPackage??> -import ${superControllerClassPackage}; - - -/** - *

- * ${table.comment!} 前端控制器 - *

- * - * @author ${author} - * @since ${date} - */ -<#if restControllerStyle> -@Api(tags = {"${table.comment!}"}) -@Slf4j -@RestController -<#else> -@Controller - -@RequestMapping("<#if package.ModuleName??>/${package.ModuleName}/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}") -<#if kotlin> -class ${table.controllerName}<#if superControllerClass??>:${superControllerClass}() -<#else> -<#if superControllerClass??>public class ${table.controllerName} extends ${superControllerClass}{ -<#else>public class ${table.controllerName} { - - - @Resource - private ${table.serviceName} ${(table.serviceName?substring(1))?uncap_first}; - - - @ApiOperation(value = "新增${table.comment!}") - @PostMapping("add") - public Result add(@RequestBody ${entity} ${entity?uncap_first}){ - ${(table.serviceName?substring(1))?uncap_first}.save(${entity?uncap_first}); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "删除${table.comment!}") - @PostMapping("delete/{id}") - public Result delete(@PathVariable("id") Long id){ - ${(table.serviceName?substring(1))?uncap_first}.removeById(id); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "更新${table.comment!}") - @PostMapping("update") - public Result update(@RequestBody ${entity} ${entity?uncap_first}){ - ${(table.serviceName?substring(1))?uncap_first}.updateById(${entity?uncap_first}); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "查询${table.comment!}分页数据") - @ApiImplicitParams({ - @ApiImplicitParam(name = "currentPage", value = "页码"), - @ApiImplicitParam(name = "pageCount", value = "每页条数") - }) - @GetMapping("listByPage") - public Result findListByPage(@RequestParam Integer currentPage, - @RequestParam Integer pageCount){ - Page page = new Page(currentPage, pageCount); - IPage<${entity}> iPage = ${(table.serviceName?substring(1))?uncap_first}.page(page); - return ResultGenerator.genSuccessResult(iPage); - } - - @ApiOperation(value = "id查询${table.comment!}") - @GetMapping("getById/{id}") - public Result findById(@PathVariable Long id){ - return ResultGenerator.genSuccessResult(${(table.serviceName?substring(1))?uncap_first}.getById(id)); - } - -} - \ No newline at end of file diff --git a/java_project_template/springboot-api-jwt/src/test/resources/user.sql b/java_project_template/springboot-api-jwt/src/test/resources/user.sql deleted file mode 100644 index 51bd7db81e..0000000000 --- a/java_project_template/springboot-api-jwt/src/test/resources/user.sql +++ /dev/null @@ -1,52 +0,0 @@ -/* - Navicat Premium Data Transfer - - Source Server : localhost - Source Server Type : MySQL - Source Server Version : 50529 - Source Host : localhost:3306 - Source Schema : project - - Target Server Type : MySQL - Target Server Version : 50529 - File Encoding : 65001 - - Date: 08/01/2020 15:53:02 -*/ - -SET NAMES utf8mb4; -SET FOREIGN_KEY_CHECKS = 0; - --- ---------------------------- --- Table structure for user --- ---------------------------- -DROP TABLE IF EXISTS `user`; -CREATE TABLE `user` ( - `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键', - `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名', - `password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码', - `nick_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '昵称', - `sex` int(1) NULL DEFAULT NULL COMMENT '性别', - `create_date` datetime NULL DEFAULT NULL COMMENT '创建时间', - `create_user` int(11) NULL DEFAULT NULL COMMENT '创建人', - `update_date` datetime NULL DEFAULT NULL COMMENT '修改时间', - `update_user` int(11) NULL DEFAULT NULL COMMENT '修改人', - `del_flag` int(1) NULL DEFAULT 0 COMMENT '删除标志0未删 1删除', - PRIMARY KEY (`id`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 11 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact; - --- ---------------------------- --- Records of user --- ---------------------------- -INSERT INTO `user` VALUES (1, 'admin', '9dc818b4bca3baa7d230fbf96c919638', '土豆', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (2, '2@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-2', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (3, '3@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-3', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (4, '4@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-4', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (5, '5@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-5', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (6, '6@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-6', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (7, '7@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-7', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (8, '8@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-8', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (9, '9@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-9', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (10, '10@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-10', 1, NULL, NULL, NULL, NULL, 0); - -SET FOREIGN_KEY_CHECKS = 1; diff --git a/java_project_template/springboot-api-session/.gitignore b/java_project_template/springboot-api-session/.gitignore deleted file mode 100644 index bfa6a22a52..0000000000 --- a/java_project_template/springboot-api-session/.gitignore +++ /dev/null @@ -1 +0,0 @@ -# Created by .ignore support plugin (hsz.mobi) diff --git a/java_project_template/springboot-api-session/README.md b/java_project_template/springboot-api-session/README.md deleted file mode 100644 index a4be665995..0000000000 --- a/java_project_template/springboot-api-session/README.md +++ /dev/null @@ -1,43 +0,0 @@ -## 简介 -Spring Boot API 是一个基于Spring Boot & MyBatis plus的种子项目,用于快速构建中小型API项目,特点稳定、简单、快速,摆脱那些重复劳动 - -## 特征&提供 -- 统一响应结果封装及生成工具 -- 统一异常处理 -- 采用redis token认证,支持单登陆端/多登陆端登陆 -- 使用Druid Spring Boot Starter 集成Druid数据库连接池与监控 -- 集成MyBatis-Plus,实现单表业务零SQL -- 支持多数据源,自由切换,只需方法或类上用 @DS 切换数据源 -- 集成国人风格的knife4j,自动生成接口文档 -- 提供代码生成器,生成controller,service,serviceImpl,dao,mapper.xml - -## 快速开始 -1. 克隆项目 -2. 导入```test```包里的mysql脚本user.sql -3. 对```test```包内的代码生成器```CodeGenerator```进行配置,主要是JDBC,因为要根据表名来生成代码 -4. 输入表名,运行```CodeGenerator.main()```方法,生成基础代码(可能需要刷新项目目录才会出来) -5. 根据业务在基础代码上进行扩展 -6. 对开发环境配置文件```application-dev.yml```进行配置,启动项目,Have Fun! - -## 开发建议 -- post调用接口ip:8080/api/user/login,参数json: {"username":"admin","password":"123456"},调用成功后, 返回token。以后调用api接口,header中传token -- 已写好注册、登陆、登出、修改密码接口, 支持单登陆端/多登陆端登陆, 具体看UserController.java 类。用户登陆之后获取session信息 JSONObject sessionInfo = httpSession.getCurrentSession(); -- 正式环境已禁用接口文档的查看,配置文件添加knife4j:production: true 即可 -- 是否允许多个登陆端,修改配置文件 redis:allowMultipleLogin:true -- Model内成员变量建议与表字段数量对应,如需扩展成员变量(比如连表查询)建议创建DTO,否则需在扩展的成员变量上加@TableField(exist = false),详见[MyBatis-Plus](https://mp.baomidou.com/guide/)文档说明 -- 建议业务失败直接使用ServiceException("ErrorMessage")抛出,由统一异常处理器来封装业务失败的响应结果,会直接被封装为{"code":400,"message":"ErrorMessage"}返回,尽情抛出;body方式传参,@Valid校验Model,更无需自己处理; - -## 接口文档效果图 -![image-20200313084433855](http://tuchuang.aitangbao.com.cn/image-20200313084433855.png) - -## 相关文档 -- Spring Boot([springboot官方](https://spring.io/projects/spring-boot/)) -- MyBatis-Plus ([查看官方中文文档](https://mp.baomidou.com/guide/)) -- MyBatis-Plus分页插件([查看官方中文文档](https://mp.baomidou.com/guide/page.html)) -- Druid Spring Boot Starter([查看官方中文文档](https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter/)) -- Fastjson([查看官方中文文档](https://github.com/Alibaba/fastjson/wiki/%E9%A6%96%E9%A1%B5)) -- 阿里巴巴Java开发手册[最新版下载](https://github.com/alibaba/p3c) -其他 - -## License -纯粹开源分享,感谢大家 [Star](https://github.com/aitangbao/springboot-api-v2) 的支持。 diff --git a/java_project_template/springboot-api-session/pom.xml b/java_project_template/springboot-api-session/pom.xml deleted file mode 100644 index 729245457b..0000000000 --- a/java_project_template/springboot-api-session/pom.xml +++ /dev/null @@ -1,155 +0,0 @@ - - - 4.0.0 - - com.company.project - springboot-api-session - 1.0 - jar - - - 1.8 - 3.3.0 - - - - - org.springframework.boot - spring-boot-starter-parent - 2.2.2.RELEASE - - - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-jdbc - - - - org.springframework.boot - spring-boot-starter-data-redis - - - org.springframework.boot - spring-boot-starter-test - test - - - - com.baomidou - dynamic-datasource-spring-boot-starter - 2.5.5 - - - com.baomidou - mybatis-plus - ${mybatis-plus.version} - - - com.baomidou - mybatis-plus-boot-starter - ${mybatis-plus.version} - - - com.baomidou - mybatis-plus-generator - ${mybatis-plus.version} - - - org.projectlombok - lombok - 1.18.10 - provided - - - - - - commons-codec - commons-codec - - - org.apache.commons - commons-lang3 - 3.6 - - - - mysql - mysql-connector-java - runtime - - - - - com.alibaba - fastjson - 1.2.47 - - - - com.alibaba - druid-spring-boot-starter - 1.1.10 - - - - org.freemarker - freemarker - 2.3.30 - test - - - - com.github.xiaoymin - knife4j-spring-boot-starter - 2.0.2 - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - maven-compiler-plugin - - ${java.version} - ${java.version} - UTF-8 - - - - - - - - aliyun-repos - http://maven.aliyun.com/nexus/content/groups/public/ - - false - - - - - - - aliyun-plugin - http://maven.aliyun.com/nexus/content/groups/public/ - - false - - - - - \ No newline at end of file diff --git a/java_project_template/springboot-api-session/src/main/java/com/company/project/Application.java b/java_project_template/springboot-api-session/src/main/java/com/company/project/Application.java deleted file mode 100644 index 2d366a4211..0000000000 --- a/java_project_template/springboot-api-session/src/main/java/com/company/project/Application.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.company.project; - -import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure; -import org.mybatis.spring.annotation.MapperScan; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.env.Environment; -import springfox.documentation.swagger2.annotations.EnableSwagger2; - -import java.net.InetAddress; - -@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class) -@MapperScan("com.company.project.dao") -public class Application { - - private static Logger logger= LoggerFactory.getLogger(Application.class); - - public static void main(String[] args) throws Exception { - - ConfigurableApplicationContext application = SpringApplication.run(Application.class, args); - - Environment env = application.getEnvironment(); - logger.info("\n----------------------------------------------------------\n\t" + - "Application '{}' is running! Access URLs:\n\t" + - "Local: \t\thttp://localhost:{}\n\t" + - "External: \thttp://{}:{}\n\t" + - "Doc: \thttp://{}:{}/doc.html\n" + - "----------------------------------------------------------", - env.getProperty("spring.application.name"), - env.getProperty("server.port"), - InetAddress.getLocalHost().getHostAddress(), - env.getProperty("server.port"), - InetAddress.getLocalHost().getHostAddress(), - env.getProperty("server.port")); - } -} - diff --git a/java_project_template/springboot-api-session/src/main/java/com/company/project/configurer/LoginInterceptor.java b/java_project_template/springboot-api-session/src/main/java/com/company/project/configurer/LoginInterceptor.java deleted file mode 100644 index b0d7c2949c..0000000000 --- a/java_project_template/springboot-api-session/src/main/java/com/company/project/configurer/LoginInterceptor.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.company.project.configurer; - - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.company.project.core.Result; -import com.company.project.core.ResultCode; -import com.company.project.service.HttpSessionService; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import java.io.IOException; - -/** - * @author wenbin - * @since 2019/10/30 15:29 - *

登陆拦截器 - */ -public class LoginInterceptor extends HandlerInterceptorAdapter { - - @Autowired - private HttpSessionService httpSession; - - private final Logger logger = LoggerFactory.getLogger(WebMvcConfigurer.class); - - @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - //用户当前session信息 - JSONObject currentSession; - //拦截接口 - //从header中获取token - String token = request.getHeader("token"); - //如果header中不存在token,则从参数中获取token - if (StringUtils.isBlank(token)) { - token = request.getParameter("token"); - } - //token为空返回 - if (StringUtils.isBlank(token)) { - Result result = new Result(); - result.setCode(ResultCode.UNAUTHORIZED).setMessage("token不能为空").setSuccess(false); - responseResult(response, result); - return false; - }// 校验并解析token,如果token过期或者篡改,则会返回null - currentSession = httpSession.getCurrentSession(); - if (null != currentSession) { - return true; - } else { - Result result = new Result(); - result.setCode(ResultCode.UNAUTHORIZED).setMessage("用户未登陆!").setSuccess(false); - responseResult(response, result); - return false; - } - } - - - private void responseResult(HttpServletResponse response, Result result) { - response.setCharacterEncoding("UTF-8"); - response.setHeader("Content-type", "application/json;charset=UTF-8"); - try { - response.getWriter().write(JSON.toJSONString(result)); - } catch (IOException ex) { - logger.error(ex.getMessage()); - } - } -} diff --git a/java_project_template/springboot-api-session/src/main/java/com/company/project/configurer/MyBatisPlusConfig.java b/java_project_template/springboot-api-session/src/main/java/com/company/project/configurer/MyBatisPlusConfig.java deleted file mode 100644 index f75a63819c..0000000000 --- a/java_project_template/springboot-api-session/src/main/java/com/company/project/configurer/MyBatisPlusConfig.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.company.project.configurer; - -import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * @ClassName MyBatisPlusConfig - * @Version 1.0 - **/ -@Configuration -public class MyBatisPlusConfig { - /** - * 配置mybatis-plus 分页查件 - * @return - */ - @Bean - public PaginationInterceptor paginationInterceptor() { - PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); - return paginationInterceptor; - } -} \ No newline at end of file diff --git a/java_project_template/springboot-api-session/src/main/java/com/company/project/configurer/SwaggerConfiguration.java b/java_project_template/springboot-api-session/src/main/java/com/company/project/configurer/SwaggerConfiguration.java deleted file mode 100644 index d5bca5303f..0000000000 --- a/java_project_template/springboot-api-session/src/main/java/com/company/project/configurer/SwaggerConfiguration.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.company.project.configurer; - -import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration; -import springfox.documentation.builders.ApiInfoBuilder; -import springfox.documentation.builders.PathSelectors; -import springfox.documentation.builders.RequestHandlerSelectors; -import springfox.documentation.service.ApiInfo; -import springfox.documentation.spi.DocumentationType; -import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger2.annotations.EnableSwagger2; - -@Configuration -@EnableSwagger2 -@EnableKnife4j -@Import(BeanValidatorPluginsConfiguration.class) -public class SwaggerConfiguration { - - @Bean - public Docket createRestApi() { - return new Docket(DocumentationType.SWAGGER_2) - .apiInfo(apiInfo()) - .select() - .apis(RequestHandlerSelectors.basePackage("com.company.project.web")) - .paths(PathSelectors.any()) - .build(); - } - - private ApiInfo apiInfo() { - return new ApiInfoBuilder() - .title("Springboot-api APIs") - .description("Springboot-api APIs") - .termsOfServiceUrl("http://localhost:8080/") - .contact("xxxxxxxxxx@163.com") - .version("1.0") - .build(); - } -} \ No newline at end of file diff --git a/java_project_template/springboot-api-session/src/main/java/com/company/project/configurer/WebMvcConfigurer.java b/java_project_template/springboot-api-session/src/main/java/com/company/project/configurer/WebMvcConfigurer.java deleted file mode 100644 index e95b243815..0000000000 --- a/java_project_template/springboot-api-session/src/main/java/com/company/project/configurer/WebMvcConfigurer.java +++ /dev/null @@ -1,177 +0,0 @@ -package com.company.project.configurer; - -import java.io.IOException; -import java.nio.charset.Charset; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.serializer.SerializerFeature; -import com.alibaba.fastjson.support.config.FastJsonConfig; -import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; - -import com.company.project.core.Result; -import com.company.project.core.ResultCode; -import com.company.project.core.ResultGenerator; -import com.company.project.core.ServiceException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.MediaType; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.web.bind.MethodArgumentNotValidException; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.method.HandlerMethod; -import org.springframework.web.servlet.HandlerExceptionResolver; -import org.springframework.web.servlet.ModelAndView; -import org.springframework.web.servlet.NoHandlerFoundException; -import org.springframework.web.servlet.config.annotation.*; - -/** - * Spring MVC 配置 - */ -@Configuration -public class WebMvcConfigurer extends WebMvcConfigurerAdapter { - - private final Logger logger = LoggerFactory.getLogger(WebMvcConfigurer.class); - - @Bean - LoginInterceptor loginInterceptor() { - - return new LoginInterceptor(); - } - - - //使用阿里 FastJson 作为JSON MessageConverter - @Override - public void configureMessageConverters(List> converters) { - FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); - FastJsonConfig config = new FastJsonConfig(); - config.setSerializerFeatures(SerializerFeature.WriteMapNullValue);//保留空的字段 - //SerializerFeature.WriteNullStringAsEmpty,//String null -> "" - //SerializerFeature.WriteNullNumberAsZero//Number null -> 0 - // 按需配置,更多参考FastJson文档哈 - - converter.setFastJsonConfig(config); - converter.setDefaultCharset(Charset.forName("UTF-8")); - converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON_UTF8)); - converters.add(converter); - } - - - //统一异常处理 - @Override - public void configureHandlerExceptionResolvers(List exceptionResolvers) { - exceptionResolvers.add(new HandlerExceptionResolver() { - public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) { - Result result = new Result(); - if (e instanceof ServiceException) {//业务失败的异常,如“账号或密码错误” - result.setCode(ResultCode.FAIL).setMessage(e.getMessage()).setSuccess(false); - } else if (e instanceof MethodArgumentNotValidException) {//@valid注解验证参数 - MethodArgumentNotValidException m = (MethodArgumentNotValidException) e; - m.getBindingResult().getFieldError().getDefaultMessage(); - result.setCode(ResultCode.PARAM_FAIL).setMessage(m.getBindingResult().getFieldError().getDefaultMessage()).setSuccess(false); - } else if (e instanceof NoHandlerFoundException) { - result.setCode(ResultCode.NOT_FOUND).setMessage("接口 [" + request.getRequestURI() + "] 不存在").setSuccess(false); - } else if (e instanceof ServletException) { - result.setCode(ResultCode.FAIL).setMessage(e.getMessage()).setSuccess(false); - } else { - result.setCode(ResultCode.INTERNAL_SERVER_ERROR).setMessage("接口 [" + request.getRequestURI() + "] 内部错误,请联系管理员").setSuccess(false); - String message; - if (handler instanceof HandlerMethod) { - HandlerMethod handlerMethod = (HandlerMethod) handler; - message = String.format("接口 [%s] 出现异常,方法:%s.%s,异常摘要:%s", - request.getRequestURI(), - handlerMethod.getBean().getClass().getName(), - handlerMethod.getMethod().getName(), - e.getMessage()); - } else { - message = e.getMessage(); - } - logger.error(message, e); - } - responseResult(response, result); - return new ModelAndView(); - } - - }); - } - - @ExceptionHandler(MethodArgumentNotValidException.class) - public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { - return ResultGenerator.genFailResult(e.getBindingResult().getFieldError().getDefaultMessage()); - } - - /** - * 页面跨域访问Controller过滤 - * - * @return - */ - @Override - public void addCorsMappings(CorsRegistry registry) { - WebMvcConfigurer.super.addCorsMappings(registry); - registry.addMapping("/**") - .allowedHeaders("*") - .allowedMethods("POST", "GET") - .allowedOrigins("*"); - } - - //添加拦截器 - @Override - public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(loginInterceptor()) - .excludePathPatterns("/doc.html") - .excludePathPatterns("/swagger-resources/**") - .excludePathPatterns("/error") - .excludePathPatterns("/webjars/**") - .excludePathPatterns("/api/user/login") - .excludePathPatterns("/api/user/register") - .addPathPatterns("/**"); - } - - - private void responseResult(HttpServletResponse response, Result result) { - response.setCharacterEncoding("UTF-8"); - response.setHeader("Content-type", "application/json;charset=UTF-8"); - try { - response.getWriter().write(JSON.toJSONString(result)); - } catch (IOException ex) { - logger.error(ex.getMessage()); - } - } - - /** - * 发现如果继承了WebMvcConfigurationSupport,则在yml中配置的相关内容会失效。 需要重新指定静态资源 - * - * @param registry - */ - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("/**").addResourceLocations( - "classpath:/static/"); - registry.addResourceHandler("doc.html").addResourceLocations( - "classpath:/META-INF/resources/"); - registry.addResourceHandler("/webjars/**").addResourceLocations( - "classpath:/META-INF/resources/webjars/"); - super.addResourceHandlers(registry); - } - - - /** - * 配置servlet处理 - */ - @Override - public void configureDefaultServletHandling( - DefaultServletHandlerConfigurer configurer) { - configurer.enable(); - } - - -} - diff --git a/java_project_template/springboot-api-session/src/main/java/com/company/project/core/ApplicationContextUtil.java b/java_project_template/springboot-api-session/src/main/java/com/company/project/core/ApplicationContextUtil.java deleted file mode 100644 index 8121fb4b4b..0000000000 --- a/java_project_template/springboot-api-session/src/main/java/com/company/project/core/ApplicationContextUtil.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.company.project.core; - -import org.springframework.beans.BeansException; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.stereotype.Component; - -/** - * @className: ApplicationContextUtil - * @Description: 解决定时任务获取不到service的问题 - * @Author moneylee - * @Date 2019-05-11 14:28 - * @Version 1.0 - **/ -@Component -public class ApplicationContextUtil implements ApplicationContextAware { - - private static ApplicationContext applicationContext; - - public static ApplicationContext getApplicationContext() { - return applicationContext; - } - - - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - ApplicationContextUtil.applicationContext = applicationContext; - - } - - public static Object getBean(String beanName) { - return applicationContext.getBean(beanName); - } - -} \ No newline at end of file diff --git a/java_project_template/springboot-api-session/src/main/java/com/company/project/core/Result.java b/java_project_template/springboot-api-session/src/main/java/com/company/project/core/Result.java deleted file mode 100644 index b208a52ae2..0000000000 --- a/java_project_template/springboot-api-session/src/main/java/com/company/project/core/Result.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.company.project.core; - -import com.alibaba.fastjson.JSON; - -/** - * 统一API响应结果封装 - */ -public class Result { - private int code; - private String message; - private T data; - private Boolean success; - - public Result setCode(ResultCode resultCode) { - this.code = resultCode.code(); - return this; - } - - public int getCode() { - return code; - } - - public String getMessage() { - return message; - } - - public Result setMessage(String message) { - this.message = message; - return this; - } - - public T getData() { - return data; - } - - public Result setData(T data) { - this.data = data; - return this; - } - - public Boolean getSuccess() { - return success; - } - - public Result setSuccess(Boolean success) { - this.success = success; - return this; - } - - @Override - public String toString() { - return JSON.toJSONString(this); - } -} diff --git a/java_project_template/springboot-api-session/src/main/java/com/company/project/core/ResultCode.java b/java_project_template/springboot-api-session/src/main/java/com/company/project/core/ResultCode.java deleted file mode 100644 index 651c04d826..0000000000 --- a/java_project_template/springboot-api-session/src/main/java/com/company/project/core/ResultCode.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.company.project.core; - -/** - * 响应码枚举,参考HTTP状态码的语义 - */ -public enum ResultCode { - SUCCESS(200),//成功 - FAIL(400),//失败 - UNAUTHORIZED(401),//未认证(签名错误) - NOT_FOUND(404),//接口不存在 - INTERNAL_SERVER_ERROR(500),//服务器内部错误 - PARAM_FAIL(10001);//参数异常 - - private final int code; - - ResultCode(int code) { - this.code = code; - } - - public int code() { - return code; - } -} diff --git a/java_project_template/springboot-api-session/src/main/java/com/company/project/core/ResultGenerator.java b/java_project_template/springboot-api-session/src/main/java/com/company/project/core/ResultGenerator.java deleted file mode 100644 index de79f955e9..0000000000 --- a/java_project_template/springboot-api-session/src/main/java/com/company/project/core/ResultGenerator.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.company.project.core; - -/** - * 响应结果生成工具 - */ -public class ResultGenerator { - private static final String DEFAULT_SUCCESS_MESSAGE = "SUCCESS"; - - public static Result genSuccessResult() { - return new Result() - .setSuccess(true) - .setCode(ResultCode.SUCCESS) - .setMessage(DEFAULT_SUCCESS_MESSAGE); - } - - public static Result genSuccessResult(T data) { - return new Result() - .setSuccess(true) - .setCode(ResultCode.SUCCESS) - .setMessage(DEFAULT_SUCCESS_MESSAGE) - .setData(data); - } - - public static Result genFailResult(String message) { - return new Result() - .setSuccess(false) - .setCode(ResultCode.FAIL) - .setMessage(message); - } -} diff --git a/java_project_template/springboot-api-session/src/main/java/com/company/project/core/ServiceException.java b/java_project_template/springboot-api-session/src/main/java/com/company/project/core/ServiceException.java deleted file mode 100644 index e698bce9da..0000000000 --- a/java_project_template/springboot-api-session/src/main/java/com/company/project/core/ServiceException.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.company.project.core; - -/** - * 服务(业务)异常如“ 账号或密码错误 ”,该异常只做INFO级别的日志记录 @see WebMvcConfigurer - */ -public class ServiceException extends RuntimeException { - public ServiceException() { - } - - public ServiceException(String message) { - super(message); - } - - public ServiceException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/java_project_template/springboot-api-session/src/main/java/com/company/project/dao/UserMapper.java b/java_project_template/springboot-api-session/src/main/java/com/company/project/dao/UserMapper.java deleted file mode 100644 index f731dd72d1..0000000000 --- a/java_project_template/springboot-api-session/src/main/java/com/company/project/dao/UserMapper.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.company.project.dao; - -import com.company.project.model.User; -import com.baomidou.mybatisplus.core.mapper.BaseMapper; - -/** - *

- * Mapper 接口 - *

- * - * @author project - * @since 2020-01-08 - */ -public interface UserMapper extends BaseMapper { - -} diff --git a/java_project_template/springboot-api-session/src/main/java/com/company/project/model/User.java b/java_project_template/springboot-api-session/src/main/java/com/company/project/model/User.java deleted file mode 100644 index ccb159e35c..0000000000 --- a/java_project_template/springboot-api-session/src/main/java/com/company/project/model/User.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.company.project.model; - -import com.baomidou.mybatisplus.annotation.IdType; -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableId; -import com.baomidou.mybatisplus.annotation.TableLogic; -import java.io.Serializable; -import java.util.Date; - -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.experimental.Accessors; - -import javax.validation.constraints.NotEmpty; - -/** - *

- * - *

- * - * @author project - * @since 2020-01-08 - */ -@Data -@EqualsAndHashCode(callSuper = false) -@Accessors(chain = true) -public class User implements Serializable { - - private static final long serialVersionUID = 1L; - - /** - * 主键 - */ - @TableId(value = "id", type = IdType.AUTO) - private Integer id; - - /** - * 用户名 - */ - @NotEmpty(message = "用户名不能为空!") - private String username; - - /** - * 密码 - */ - @NotEmpty(message = "密码不能为空!") - private String password; - - /** - * 昵称 - */ - private String nickName; - - /** - * 性别 - */ - private Integer sex; - - /** - * 创建时间 - */ - private Date createDate; - - /** - * 创建人 - */ - private Integer createUser; - - /** - * 修改时间 - */ - private Date updateDate; - - /** - * 修改人 - */ - private Integer updateUser; - - /** - * 删除标志0未删 1删除 - */ - @TableLogic - private Integer delFlag; - - /** - * 登陆返回token - */ - @TableField(exist = false) - private String token; - -} diff --git a/java_project_template/springboot-api-session/src/main/java/com/company/project/service/HttpSessionService.java b/java_project_template/springboot-api-session/src/main/java/com/company/project/service/HttpSessionService.java deleted file mode 100644 index c28c14b817..0000000000 --- a/java_project_template/springboot-api-session/src/main/java/com/company/project/service/HttpSessionService.java +++ /dev/null @@ -1,148 +0,0 @@ -package com.company.project.service; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.company.project.model.User; -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; - -import javax.servlet.http.HttpServletRequest; -import java.util.Random; - -/** - * session管理器 - * - * @author aitangbao - */ -@Service -public class HttpSessionService { - - @Autowired - private RedisService redisDB; - - @Autowired - private HttpServletRequest request; - - @Value("${redis.key.prefix.userToken}") - private String USER_TOKEN_PREFIX; - - @Value("${redis.key.expire.userToken}") - private int EXPIRE ; - - public String createTokenAndUser(User user) { - //方便根据id找到redis的key, 修改密码/退出登陆 方便使用 - String token = getRandomToken(32) + "#" + user.getId(); - JSONObject sessionInfo = new JSONObject(); - sessionInfo.put("userId", user.getId()); - sessionInfo.put("username", user.getUsername()); - String key = USER_TOKEN_PREFIX + token; - //设置该用户已登录的token - redisDB.setAndExpire(key, sessionInfo.toJSONString(), EXPIRE); - return token; - } - - /** - * 根据token获取userid - * - * @param token - * @return - */ - public static String getUserIdByToken(String token) { - if (StringUtils.isBlank(token) || !token.contains("#")) { - return ""; - } else { - return token.substring(token.indexOf("#") + 1); - } - } - - /** - * 获取参数中的token - * - * @return - */ - public String getTokenFromHeader() { - String token = request.getHeader("token"); - //如果header中不存在token,则从参数中获取token - if (StringUtils.isBlank(token)) { - token = request.getParameter("token"); - } - return token; - } - - /** - * 获取当前session信息 - * - * @return - */ - public JSONObject getCurrentSession() { - String token = getTokenFromHeader(); - if (null != token) { - if (redisDB.exists(USER_TOKEN_PREFIX + token)) { - String sessionInfoStr = redisDB.get(USER_TOKEN_PREFIX + token); - JSONObject sessionInfo = JSON.parseObject(sessionInfoStr); - return sessionInfo; - } else { - return null; - } - } else { - return null; - } - } - - - /** - * 使当前用户的token失效 - */ - public void abortUserByToken() { - String token = getTokenFromHeader(); - redisDB.del(USER_TOKEN_PREFIX + token); - } - - /** - * 使所有用户的token失效 - */ - public void abortAllUserByToken() { - String token = getTokenFromHeader(); - String userId = getUserIdByToken(token); - redisDB.delKeys(USER_TOKEN_PREFIX+"*#" + userId); - } - - /** - * 使用户的token失效 - */ - public void abortUserByUserId(Integer userId) { - redisDB.delKeys(USER_TOKEN_PREFIX+"*#" + userId); - } - - - /** - * 生成随机的token - * - * @param length - * @return - */ - private String getRandomToken(int length) { - Random random = new Random(); - StringBuilder randomStr = new StringBuilder(); - - // 根据length生成相应长度的随机字符串 - for (int i = 0; i < length; i++) { - String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; - - //输出字母还是数字 - if ("char".equalsIgnoreCase(charOrNum)) { - //输出是大写字母还是小写字母 - int temp = random.nextInt(2) % 2 == 0 ? 65 : 97; - randomStr.append((char) (random.nextInt(26) + temp)); - } else if ("num".equalsIgnoreCase(charOrNum)) { - randomStr.append(String.valueOf(random.nextInt(10))); - } - } - - return randomStr.toString(); - } - - -} diff --git a/java_project_template/springboot-api-session/src/main/java/com/company/project/service/IUserService.java b/java_project_template/springboot-api-session/src/main/java/com/company/project/service/IUserService.java deleted file mode 100644 index 97ab829ead..0000000000 --- a/java_project_template/springboot-api-session/src/main/java/com/company/project/service/IUserService.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.company.project.service; - -import com.company.project.core.Result; -import com.company.project.model.User; -import com.baomidou.mybatisplus.extension.service.IService; - -/** - *

- * 服务类 - *

- * - * @author project - * @since 2020-01-08 - */ -public interface IUserService extends IService { - - Result checkPassword(User userParam); -} diff --git a/java_project_template/springboot-api-session/src/main/java/com/company/project/service/RedisService.java b/java_project_template/springboot-api-session/src/main/java/com/company/project/service/RedisService.java deleted file mode 100644 index 238e4bee99..0000000000 --- a/java_project_template/springboot-api-session/src/main/java/com/company/project/service/RedisService.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.company.project.service; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.stereotype.Service; -import org.springframework.util.CollectionUtils; - -import java.util.Date; -import java.util.Set; -import java.util.concurrent.TimeUnit; - - -/** - * @author : aitangbao - */ - -@Service -public class RedisService { - @Autowired - private StringRedisTemplate redisTemplate; - - public boolean exists(String key) { - return this.redisTemplate.hasKey(key); - } - - public String get(String key) { - String value = this.redisTemplate.opsForValue().get(key); - return value; - } - - - public void del(String key) { - if (this.exists(key)) { - this.redisTemplate.delete(key); - } - - } - - public void setAndExpire(String key, String value, int seconds) { - this.redisTemplate.opsForValue().set(key, value); - this.redisTemplate.expire(key, (long) seconds, TimeUnit.SECONDS); - } - - - public void setExpire(String key, Date endTime) { - long seconds = endTime.getTime() - (new Date()).getTime(); - this.redisTemplate.expire(key, (long) ((int) (seconds / 1000L)), TimeUnit.SECONDS); - } - - - public Set keys(String pattern) { - return redisTemplate.keys("*" + pattern); - } - - public void delKeys(String pattern) { - Set keys = redisTemplate.keys(pattern); - if (!CollectionUtils.isEmpty(keys)) { - this.redisTemplate.delete(keys); - } - } -} diff --git a/java_project_template/springboot-api-session/src/main/java/com/company/project/service/impl/UserServiceImpl.java b/java_project_template/springboot-api-session/src/main/java/com/company/project/service/impl/UserServiceImpl.java deleted file mode 100644 index 67f595f402..0000000000 --- a/java_project_template/springboot-api-session/src/main/java/com/company/project/service/impl/UserServiceImpl.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.company.project.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.company.project.core.Result; -import com.company.project.core.ResultGenerator; -import com.company.project.model.User; -import com.company.project.dao.UserMapper; -import com.company.project.service.IUserService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.company.project.service.RedisService; -import com.company.project.utils.MD5Utils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; - -/** - *

- * 服务实现类 - *

- * - * @author project - * @since 2020-01-08 - */ -@Service -public class UserServiceImpl extends ServiceImpl implements IUserService { - - @Autowired - private UserMapper userMapper; - - - @Autowired - private RedisService redis; - @Value("${redis.key.prefix.passwordError}") - private String PASSWORD_ERROR_PREFIX; - @Value("${redis.key.expire.passwordError}") - private int PASSWORD_ERROR_EXPIRE; - - @Override - public Result checkPassword(User userParam) { - - String username = userParam.getUsername(); - String password = userParam.getPassword(); - //redis key - String redisPasswordErrorKey = PASSWORD_ERROR_PREFIX + username; - //判断账户是否锁定 - String errorCount = redis.get(redisPasswordErrorKey); - if (errorCount != null && Integer.parseInt(errorCount) == 5) { - return ResultGenerator.genFailResult("密码连续错误5次,请1小时后重试"); - } - //根据用户名获取用户信息 - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.eq("username", username); - User user = userMapper.selectOne(queryWrapper); - if (user == null) { - return ResultGenerator.genFailResult("账号未找到"); - } - - if (!MD5Utils.Encrypt(password, true).equals(user.getPassword())) { - if (errorCount == null) { - errorCount = "1"; - } else { - errorCount = String.valueOf(Integer.parseInt(errorCount) + 1); - } - redis.setAndExpire(redisPasswordErrorKey, errorCount, PASSWORD_ERROR_EXPIRE); - if ("5".equals(errorCount)) { - return ResultGenerator.genFailResult("密码连续错误5次,请1小时后重试"); - } else { - return ResultGenerator.genFailResult("密码错误,剩余次数" + (5 - Integer.parseInt(errorCount))); - } - } else { - //登录成功删除错误登录次数 - redis.del(redisPasswordErrorKey); - return ResultGenerator.genSuccessResult(user); - } - } -} diff --git a/java_project_template/springboot-api-session/src/main/java/com/company/project/utils/ImageCodeUtil.java b/java_project_template/springboot-api-session/src/main/java/com/company/project/utils/ImageCodeUtil.java deleted file mode 100644 index dd70fbc80d..0000000000 --- a/java_project_template/springboot-api-session/src/main/java/com/company/project/utils/ImageCodeUtil.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.company.project.utils; - -import lombok.extern.slf4j.Slf4j; - -import javax.imageio.ImageIO; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import java.awt.*; -import java.awt.image.BufferedImage; -import java.util.Random; - -@Slf4j -public class ImageCodeUtil { - - - public static final String IMAGE_RANDOM_CODEKEY = "RANDOMVALIDATECODEKEY";//放到session中的key - private String randString = "0123456789";//随机产生只有数字的字符串 private String - //private String randString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生只有字母的字符串 - //private String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生数字与字母组合的字符串 - private int width = 95;// 图片宽 - private int height = 25;// 图片高 - private int lineSize = 40;// 干扰线数量 - private int stringNum = 4;// 随机产生字符数量 - - - private Random random = new Random(); - - /** - * 获得字体 - */ - private Font getFont() { - return new Font("Fixedsys", Font.CENTER_BASELINE, 18); - } - - /** - * 获得颜色 - */ - private Color getRandColor(int fc, int bc) { - if (fc > 255) - fc = 255; - if (bc > 255) - bc = 255; - int r = fc + random.nextInt(bc - fc - 16); - int g = fc + random.nextInt(bc - fc - 14); - int b = fc + random.nextInt(bc - fc - 18); - return new Color(r, g, b); - } - - /** - * 生成随机图片 - */ - public void getRandcode(HttpServletRequest request, HttpServletResponse response) { - HttpSession session = request.getSession(); - // BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类 - BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); - Graphics g = image.getGraphics();// 产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作 - g.fillRect(0, 0, width, height);//图片大小 - g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));//字体大小 - g.setColor(getRandColor(110, 133));//字体颜色 - // 绘制干扰线 - for (int i = 0; i <= lineSize; i++) { - drowLine(g); - } - // 绘制随机字符 - String randomString = ""; - for (int i = 1; i <= stringNum; i++) { - randomString = drowString(g, randomString, i); - } - log.info(randomString); - //将生成的随机字符串保存到session中 - session.removeAttribute(IMAGE_RANDOM_CODEKEY); - session.setAttribute(IMAGE_RANDOM_CODEKEY, randomString); - g.dispose(); - try { - // 将内存中的图片通过流动形式输出到客户端 - ImageIO.write(image, "JPEG", response.getOutputStream()); - } catch (Exception e) { - log.error("将内存中的图片通过流动形式输出到客户端失败>>>> ", e); - } - - } - - /** - * 绘制字符串 - */ - private String drowString(Graphics g, String randomString, int i) { - g.setFont(getFont()); - g.setColor(new Color(random.nextInt(101), random.nextInt(111), random - .nextInt(121))); - String rand = String.valueOf(getRandomString(random.nextInt(randString - .length()))); - randomString += rand; - g.translate(random.nextInt(3), random.nextInt(3)); - g.drawString(rand, 13 * i, 16); - return randomString; - } - - /** - * 绘制干扰线 - */ - private void drowLine(Graphics g) { - int x = random.nextInt(width); - int y = random.nextInt(height); - int xl = random.nextInt(13); - int yl = random.nextInt(15); - g.drawLine(x, y, x + xl, y + yl); - } - - /** - * 获取随机的字符 - */ - public String getRandomString(int num) { - return String.valueOf(randString.charAt(num)); - } -} \ No newline at end of file diff --git a/java_project_template/springboot-api-session/src/main/java/com/company/project/utils/MD5Utils.java b/java_project_template/springboot-api-session/src/main/java/com/company/project/utils/MD5Utils.java deleted file mode 100644 index c7a3dff75c..0000000000 --- a/java_project_template/springboot-api-session/src/main/java/com/company/project/utils/MD5Utils.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.company.project.utils; - -import org.apache.commons.codec.digest.DigestUtils; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.StringUtils; - -public class MD5Utils { - - private static String salt = "springboot_api"; - - /** - * 加密字符串 - * @param password 要加密的明文 - * @param isAddSalt 是否加默认盐 - * @return 加密之后的结果 - */ - public static String Encrypt(String password, boolean isAddSalt){ - if (StringUtils.isNotEmpty(password)){ - if (isAddSalt){ - return DigestUtils.md5Hex(DigestUtils.md5(password + salt)); - } else { - return DigestUtils.md5Hex(DigestUtils.md5(password)); - } - } - return null; - } - - /** - * - * @param bytes - * @return - */ - public static String Encrypt(byte[] bytes){ - if (ArrayUtils.isNotEmpty(bytes)){ - return DigestUtils.md5Hex(DigestUtils.md5(bytes)); - } - return null; - } - - /** - * MD5加盐加密 - * @param password 要加密的明文 - * @param salt 盐 - * @return 加密之后的结果 - */ - public static String Encrypt(String password, String salt){ - if (StringUtils.isNotEmpty(password)){ - return DigestUtils.md5Hex(DigestUtils.md5(password + salt)); - } - return null; - } - - public static void main(String[] args){ - System.out.println(MD5Utils.Encrypt("admin", true)); - } -} diff --git a/java_project_template/springboot-api-session/src/main/java/com/company/project/web/UserController.java b/java_project_template/springboot-api-session/src/main/java/com/company/project/web/UserController.java deleted file mode 100644 index 48aa0249b6..0000000000 --- a/java_project_template/springboot-api-session/src/main/java/com/company/project/web/UserController.java +++ /dev/null @@ -1,203 +0,0 @@ -package com.company.project.web; - -import com.alibaba.fastjson.JSONObject; -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.company.project.core.Result; -import com.company.project.core.ResultGenerator; -import com.company.project.service.HttpSessionService; -import com.company.project.utils.MD5Utils; -import com.company.project.utils.ImageCodeUtil; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.web.bind.annotation.*; -import com.company.project.service.IUserService; -import com.company.project.model.User; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import lombok.extern.slf4j.Slf4j; -import com.baomidou.mybatisplus.core.metadata.IPage; - -import javax.annotation.Resource; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import javax.validation.Valid; - -import org.springframework.web.bind.annotation.RestController; - -import java.util.HashMap; -import java.util.Map; - -/** - *

- * 前端控制器 - *

- * - * @author project - * @since 2020-01-08 - */ -@Slf4j -@RestController -@RequestMapping("/api/user") -public class UserController { - - @Resource - private IUserService userService; - @Autowired - private HttpSessionService httpSession; - - @Value("${redis.allowMultipleLogin}") - private Boolean allowMultipleLogin; - - @ApiOperation("登陆") - @PostMapping("/login") - public Result login(@RequestBody @Valid User userParam) { - - //校验密码,5次错误锁定账户 - Result result = userService.checkPassword(userParam); - if (!result.getSuccess()) { - return result; - } - //成功之后返回user - User user = (User)result.getData(); - - //是否删除之前token, 此处控制是否支持多登陆端; - // true:允许多处登陆; false:只能单处登陆,顶掉之前登陆 - if (!allowMultipleLogin) { - httpSession.abortUserByUserId(user.getId()); - } - - //生成token - String token = httpSession.createTokenAndUser(user); - - Map resultMap = new HashMap<>(2); - resultMap.put("token", token); - resultMap.put("username", userParam.getUsername()); - return ResultGenerator.genSuccessResult(resultMap); - } - - @ApiOperation("注册") - @PostMapping("/register") - public Result register(@RequestBody @Valid User user) { - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.eq("username", user.getUsername()); - User userO = userService.getOne(queryWrapper); - if (userO != null) { - return ResultGenerator.genFailResult("账号已存在"); - } - user.setPassword(MD5Utils.Encrypt(user.getPassword(), true)); - userService.save(user); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation("修改密码") - @PostMapping("/updatePassword") - public Result updatePassword(@RequestBody JSONObject param) { - String oldPassword = param.getString("oldPassword"); - String newPassword = param.getString("newPassword"); - if (StringUtils.isBlank(oldPassword) || StringUtils.isBlank(newPassword)) { - return ResultGenerator.genFailResult("密码不能为空"); - } - //获取登陆信息 - JSONObject sessionInfo = httpSession.getCurrentSession(); - String userId = sessionInfo.getString("userId"); - - User user = userService.getById(userId); - if (user == null) { - return ResultGenerator.genFailResult("账号未找到"); - } - if (!MD5Utils.Encrypt(oldPassword, true).equals(user.getPassword())) { - return ResultGenerator.genFailResult("旧密码错误"); - } - User updateUser = new User(); - updateUser.setId(user.getId()); - updateUser.setPassword(MD5Utils.Encrypt(newPassword, true)); - userService.updateById(updateUser); - - //重置密码后删除原所有token - httpSession.abortAllUserByToken(); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation("登出") - @GetMapping("/logout") - public Result logout() { - //退出删除token - httpSession.abortUserByToken(); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation("校验token是否有效") - @GetMapping("/validateToken") - public Result validateToken() { - //拦截器拦截已判断,直接返回成功 - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "删除") - @PostMapping("delete/{id}") - public Result delete(@PathVariable("id") Long id) { - userService.removeById(id); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "更新") - @PostMapping("update") - public Result update(@RequestBody User user) { - //密码不更新 - user.setPassword(null); - userService.updateById(user); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "查询分页数据") - @ApiImplicitParams({ - @ApiImplicitParam(name = "currentPage", value = "页码"), - @ApiImplicitParam(name = "pageCount", value = "每页条数") - }) - @GetMapping("listByPage") - public Result findListByPage(@RequestParam(defaultValue = "1") Integer currentPage, - @RequestParam(defaultValue = "10") Integer pageCount) { - Page page = new Page(currentPage, pageCount); - IPage iPage = userService.page(page); - return ResultGenerator.genSuccessResult(iPage); - } - - @ApiOperation(value = "id查询") - @GetMapping("getById/{id}") - public Result findById(@PathVariable Long id) { - return ResultGenerator.genSuccessResult(userService.getById(id)); - } - - @ApiOperation(value = "生成验证码") - @GetMapping(value = "/getVerify") - public void getVerify(HttpServletRequest request, HttpServletResponse response) { - response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片 - response.setHeader("Pragma", "No-cache");//设置响应头信息,告诉浏览器不要缓存此内容 - response.setHeader("Cache-Control", "no-cache"); - response.setDateHeader("Expire", 0); - try { - ImageCodeUtil randomValidateCode = new ImageCodeUtil(); - randomValidateCode.getRandcode(request, response);//输出验证码图片方法 - } catch (Exception e) { - log.error("生成验证码失败"); - } - } - - @ApiOperation(value = "校验验证码") - @PostMapping(value = "/checkVerify") - public Result checkVerify(@RequestParam String imageCode, HttpSession session) { - //从session中获取随机数 - Object random = session.getAttribute(ImageCodeUtil.IMAGE_RANDOM_CODEKEY); - if (random != null && String.valueOf(random).equals(imageCode)) { - return ResultGenerator.genSuccessResult(); - } - return ResultGenerator.genFailResult("校验失败"); - } - - -} diff --git a/java_project_template/springboot-api-session/src/main/resources/application-dev.yml b/java_project_template/springboot-api-session/src/main/resources/application-dev.yml deleted file mode 100644 index b16e34f2cd..0000000000 --- a/java_project_template/springboot-api-session/src/main/resources/application-dev.yml +++ /dev/null @@ -1,53 +0,0 @@ -# 开发环境配置 -spring: - datasource: - dynamic: - primary: master #设置默认的数据源或者数据源组,默认值即为master - datasource: - master: - username: root - password: 123456 - driver-class-name: com.mysql.cj.jdbc.Driver - url: jdbc:mysql://localhost:3306/project?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2b8 - slave_1: - username: root - password: 123456 - driver-class-name: com.mysql.cj.jdbc.Driver - url: jdbc:mysql://xx.xx.xx.xx:3307/dynamic?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2b8 - slave_2: - username: root - password: 123456 - driver-class-name: com.mysql.cj.jdbc.Driver - url: jdbc:mysql://xx.xx.xx.xx:3308/dynamic?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2b8 - #......省略 - #以上会配置一个默认库master,一个组slave下有两个子库slave_1,slave_2 - -redis: - key: - prefix: - userToken: "user:token:" - passwordError: "user:password:error:" - expire: - userToken: 604800 # 7天 7*24*3600 - passwordError: 3600 # 一个小时 - allowMultipleLogin: false # 允许多处登陆 - host: localhost # Redis服务器地址 - database: 0 # Redis数据库索引(默认为0) - port: 6379 # Redis服务器连接端口 - password: # Redis服务器连接密码(默认为空) - jedis: - pool: - max-active: 8 # 连接池最大连接数(使用负值表示没有限制) - max-wait: -1ms # 连接池最大阻塞等待时间(使用负值表示没有限制) - max-idle: 8 # 连接池中的最大空闲连接 - min-idle: 0 # 连接池中的最小空闲连接 - timeout: 3000ms # 连接超时时间(毫秒 - -mybatis-plus: - configuration: - log-impl: org.apache.ibatis.logging.stdout.StdOutImpl - mapper-locations: classpath:mapper/*.xml - global-config: - db-config: - logic-delete-value: 1 - logic-not-delete-value: 0 diff --git a/java_project_template/springboot-api-session/src/main/resources/application-prod.yml b/java_project_template/springboot-api-session/src/main/resources/application-prod.yml deleted file mode 100644 index 27cc9a1df0..0000000000 --- a/java_project_template/springboot-api-session/src/main/resources/application-prod.yml +++ /dev/null @@ -1,4 +0,0 @@ -# 生产环境配置 - -knife4j: - production: true #生成环境禁用查看文档 \ No newline at end of file diff --git a/java_project_template/springboot-api-session/src/main/resources/application-test.yml b/java_project_template/springboot-api-session/src/main/resources/application-test.yml deleted file mode 100644 index 287da7b20e..0000000000 --- a/java_project_template/springboot-api-session/src/main/resources/application-test.yml +++ /dev/null @@ -1 +0,0 @@ -# 测试环境配置 diff --git a/java_project_template/springboot-api-session/src/main/resources/application.yml b/java_project_template/springboot-api-session/src/main/resources/application.yml deleted file mode 100644 index facce6d372..0000000000 --- a/java_project_template/springboot-api-session/src/main/resources/application.yml +++ /dev/null @@ -1,14 +0,0 @@ -spring: - profiles: - active: dev - mvc: - throw-exception-if-no-handler-found: true - resources: - add-mappings: false - application: - name: Springboot-api - jackson: - date-format: yyyy-MM-dd HH:mm:ss - time-zone: GMT+8 -server: - port: 8080 diff --git a/java_project_template/springboot-api-session/src/main/resources/banner.txt b/java_project_template/springboot-api-session/src/main/resources/banner.txt deleted file mode 100644 index 152e179398..0000000000 --- a/java_project_template/springboot-api-session/src/main/resources/banner.txt +++ /dev/null @@ -1,22 +0,0 @@ -//////////////////////////////////////////////////////////////////// -// _ooOoo_ // -// o8888888o // -// 88" . "88 // -// (| ^_^ |) // -// O\ = /O // -// ____/`---'\____ // -// .' \\| |// `. // -// / \\||| : |||// \ // -// / _||||| -:- |||||- \ // -// | | \\\ - /// | | // -// | \_| ''\---/'' | | // -// \ .-\__ `-` ___/-. / // -// ___`. .' /--.--\ `. . ___ // -// ."" '< `.___\_<|>_/___.' >'"". // -// | | : `- \`.;`\ _ /`;.`/ - ` : | | // -// \ \ `-. \_ __\ /__ _/ .-` / / // -// ========`-.____`-.___\_____/___.-`____.-'======== // -// `=---=' // -// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // -// 佛祖保佑 永不宕机 永无BUG // -//////////////////////////////////////////////////////////////////// \ No newline at end of file diff --git a/java_project_template/springboot-api-session/src/main/resources/mapper/UserMapper.xml b/java_project_template/springboot-api-session/src/main/resources/mapper/UserMapper.xml deleted file mode 100644 index 87ab7e4161..0000000000 --- a/java_project_template/springboot-api-session/src/main/resources/mapper/UserMapper.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - id, username, password, nick_name, sex, create_date, create_user, update_date, update_user, del_flag - - - \ No newline at end of file diff --git a/java_project_template/springboot-api-session/src/test/java/CodeGenerator.java b/java_project_template/springboot-api-session/src/test/java/CodeGenerator.java deleted file mode 100644 index 2154821759..0000000000 --- a/java_project_template/springboot-api-session/src/test/java/CodeGenerator.java +++ /dev/null @@ -1,113 +0,0 @@ -import com.baomidou.mybatisplus.core.toolkit.StringPool; -import com.baomidou.mybatisplus.generator.AutoGenerator; -import com.baomidou.mybatisplus.generator.InjectionConfig; -import com.baomidou.mybatisplus.generator.config.*; -import com.baomidou.mybatisplus.generator.config.po.TableInfo; -import com.baomidou.mybatisplus.generator.config.rules.DateType; -import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; -import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; - -import java.util.ArrayList; -import java.util.List; - -// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中 -public class CodeGenerator { - - - //多个表逗号分隔 - static String tableName = "user"; - //逻辑删除字段名, 假如表没有逻辑删除字段,请忽视 - static String logicDeleteFieldName = "del_flag"; - - public static void main(String[] args) { - // 代码生成器 - AutoGenerator mpg = new AutoGenerator(); - - // 全局配置 - GlobalConfig gc = new GlobalConfig(); - String projectPath = System.getProperty("user.dir"); - gc.setOutputDir(projectPath + "/src/main/java"); - gc.setAuthor("aitangbao"); - gc.setOpen(false); - gc.setBaseColumnList(true); - gc.setBaseResultMap(true); - gc.setDateType(DateType.ONLY_DATE); - // gc.setSwagger2(true); 实体属性 Swagger2 注解 - mpg.setGlobalConfig(gc); - - // 数据源配置 - DataSourceConfig dsc = new DataSourceConfig(); - dsc.setUrl("jdbc:mysql://localhost:3306/project?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC"); - // dsc.setSchemaName("public"); - dsc.setDriverName("com.mysql.cj.jdbc.Driver"); - dsc.setUsername("root"); - dsc.setPassword("123456"); - mpg.setDataSource(dsc); - - // 包配置 - PackageConfig pc = new PackageConfig(); - pc.setParent("com.company.project"); - pc.setEntity("model"); - pc.setMapper("dao"); - pc.setController("web"); - mpg.setPackageInfo(pc); - - // 自定义配置 - InjectionConfig cfg = new InjectionConfig() { - @Override - public void initMap() { - // to do nothing - } - }; - - // 如果模板引擎是 freemarker - String templatePath = "/templates/mapper.xml.ftl"; - // 如果模板引擎是 velocity - // String templatePath = "/templates/mapper.xml.vm"; - - // 自定义输出配置 - List focList = new ArrayList<>(); - // 自定义配置会被优先输出 - focList.add(new FileOutConfig(templatePath) { - @Override - public String outputFile(TableInfo tableInfo) { - // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!! - return projectPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; - } - }); - cfg.setFileOutConfigList(focList); - mpg.setCfg(cfg); - - // 配置模板 - TemplateConfig templateConfig = new TemplateConfig(); - - // 配置自定义输出模板 - //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别 -// templateConfig.setEntity("templates/entity.java"); - // templateConfig.setService(); - templateConfig.setController("templates/controller.java"); - - templateConfig.setXml(null); - mpg.setTemplate(templateConfig); - - // 策略配置 - StrategyConfig strategy = new StrategyConfig(); - strategy.setNaming(NamingStrategy.underline_to_camel); - strategy.setColumnNaming(NamingStrategy.underline_to_camel); -// strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!"); - strategy.setEntityLombokModel(true); - strategy.setRestControllerStyle(true); - // 公共父类 -// strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!"); - // 写于父类中的公共字段 -// strategy.setSuperEntityColumns("id"); - strategy.setInclude(tableName.split(",")); - strategy.setControllerMappingHyphenStyle(true); - strategy.setLogicDeleteFieldName(logicDeleteFieldName); // 逻辑删除字段名称 - strategy.setTablePrefix(pc.getModuleName() + "_"); - mpg.setStrategy(strategy); - mpg.setTemplateEngine(new FreemarkerTemplateEngine()); - mpg.execute(); - } - -} \ No newline at end of file diff --git a/java_project_template/springboot-api-session/src/test/java/com/company/project/Tester.java b/java_project_template/springboot-api-session/src/test/java/com/company/project/Tester.java deleted file mode 100644 index f513bc219d..0000000000 --- a/java_project_template/springboot-api-session/src/test/java/com/company/project/Tester.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.company.project; - -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(classes = Application.class) -public class Tester { - - @Test - public void test() { - - } -} - - - diff --git a/java_project_template/springboot-api-session/src/test/resources/templates/controller.java.ftl b/java_project_template/springboot-api-session/src/test/resources/templates/controller.java.ftl deleted file mode 100644 index a62f181707..0000000000 --- a/java_project_template/springboot-api-session/src/test/resources/templates/controller.java.ftl +++ /dev/null @@ -1,94 +0,0 @@ -package ${package.Controller}; - -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.company.project.core.Result; -import com.company.project.core.ResultGenerator; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import org.springframework.web.bind.annotation.*; -import ${package.Service}.${table.serviceName}; -import ${package.Entity}.${entity}; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import lombok.extern.slf4j.Slf4j; -import com.baomidou.mybatisplus.core.metadata.IPage; - -import javax.annotation.Resource; -<#if restControllerStyle> -import org.springframework.web.bind.annotation.RestController; -<#else> -import org.springframework.stereotype.Controller; - -<#if superControllerClassPackage??> -import ${superControllerClassPackage}; - - -/** - *

- * ${table.comment!} 前端控制器 - *

- * - * @author ${author} - * @since ${date} - */ -<#if restControllerStyle> -@Api(tags = {"${table.comment!}"}) -@Slf4j -@RestController -<#else> -@Controller - -@RequestMapping("<#if package.ModuleName??>/${package.ModuleName}/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}") -<#if kotlin> -class ${table.controllerName}<#if superControllerClass??>:${superControllerClass}() -<#else> -<#if superControllerClass??>public class ${table.controllerName} extends ${superControllerClass}{ -<#else>public class ${table.controllerName} { - - - @Resource - private ${table.serviceName} ${(table.serviceName?substring(1))?uncap_first}; - - - @ApiOperation(value = "新增${table.comment!}") - @PostMapping("add") - public Result add(@RequestBody ${entity} ${entity?uncap_first}){ - ${(table.serviceName?substring(1))?uncap_first}.save(${entity?uncap_first}); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "删除${table.comment!}") - @PostMapping("delete/{id}") - public Result delete(@PathVariable("id") Long id){ - ${(table.serviceName?substring(1))?uncap_first}.removeById(id); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "更新${table.comment!}") - @PostMapping("update") - public Result update(@RequestBody ${entity} ${entity?uncap_first}){ - ${(table.serviceName?substring(1))?uncap_first}.updateById(${entity?uncap_first}); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "查询${table.comment!}分页数据") - @ApiImplicitParams({ - @ApiImplicitParam(name = "currentPage", value = "页码"), - @ApiImplicitParam(name = "pageCount", value = "每页条数") - }) - @GetMapping("listByPage") - public Result findListByPage(@RequestParam Integer currentPage, - @RequestParam Integer pageCount){ - Page page = new Page(currentPage, pageCount); - IPage<${entity}> iPage = ${(table.serviceName?substring(1))?uncap_first}.page(page); - return ResultGenerator.genSuccessResult(iPage); - } - - @ApiOperation(value = "id查询${table.comment!}") - @GetMapping("getById/{id}") - public Result findById(@PathVariable Long id){ - return ResultGenerator.genSuccessResult(${(table.serviceName?substring(1))?uncap_first}.getById(id)); - } - -} - \ No newline at end of file diff --git a/java_project_template/springboot-api-session/src/test/resources/user.sql b/java_project_template/springboot-api-session/src/test/resources/user.sql deleted file mode 100644 index 51bd7db81e..0000000000 --- a/java_project_template/springboot-api-session/src/test/resources/user.sql +++ /dev/null @@ -1,52 +0,0 @@ -/* - Navicat Premium Data Transfer - - Source Server : localhost - Source Server Type : MySQL - Source Server Version : 50529 - Source Host : localhost:3306 - Source Schema : project - - Target Server Type : MySQL - Target Server Version : 50529 - File Encoding : 65001 - - Date: 08/01/2020 15:53:02 -*/ - -SET NAMES utf8mb4; -SET FOREIGN_KEY_CHECKS = 0; - --- ---------------------------- --- Table structure for user --- ---------------------------- -DROP TABLE IF EXISTS `user`; -CREATE TABLE `user` ( - `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键', - `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名', - `password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码', - `nick_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '昵称', - `sex` int(1) NULL DEFAULT NULL COMMENT '性别', - `create_date` datetime NULL DEFAULT NULL COMMENT '创建时间', - `create_user` int(11) NULL DEFAULT NULL COMMENT '创建人', - `update_date` datetime NULL DEFAULT NULL COMMENT '修改时间', - `update_user` int(11) NULL DEFAULT NULL COMMENT '修改人', - `del_flag` int(1) NULL DEFAULT 0 COMMENT '删除标志0未删 1删除', - PRIMARY KEY (`id`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 11 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact; - --- ---------------------------- --- Records of user --- ---------------------------- -INSERT INTO `user` VALUES (1, 'admin', '9dc818b4bca3baa7d230fbf96c919638', '土豆', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (2, '2@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-2', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (3, '3@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-3', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (4, '4@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-4', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (5, '5@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-5', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (6, '6@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-6', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (7, '7@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-7', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (8, '8@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-8', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (9, '9@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-9', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (10, '10@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-10', 1, NULL, NULL, NULL, NULL, 0); - -SET FOREIGN_KEY_CHECKS = 1; diff --git a/java_project_template/springboot-api-v2/.gitignore b/java_project_template/springboot-api-v2/.gitignore deleted file mode 100644 index bfa6a22a52..0000000000 --- a/java_project_template/springboot-api-v2/.gitignore +++ /dev/null @@ -1 +0,0 @@ -# Created by .ignore support plugin (hsz.mobi) diff --git a/java_project_template/springboot-api-v2/README.md b/java_project_template/springboot-api-v2/README.md deleted file mode 100644 index a4be665995..0000000000 --- a/java_project_template/springboot-api-v2/README.md +++ /dev/null @@ -1,43 +0,0 @@ -## 简介 -Spring Boot API 是一个基于Spring Boot & MyBatis plus的种子项目,用于快速构建中小型API项目,特点稳定、简单、快速,摆脱那些重复劳动 - -## 特征&提供 -- 统一响应结果封装及生成工具 -- 统一异常处理 -- 采用redis token认证,支持单登陆端/多登陆端登陆 -- 使用Druid Spring Boot Starter 集成Druid数据库连接池与监控 -- 集成MyBatis-Plus,实现单表业务零SQL -- 支持多数据源,自由切换,只需方法或类上用 @DS 切换数据源 -- 集成国人风格的knife4j,自动生成接口文档 -- 提供代码生成器,生成controller,service,serviceImpl,dao,mapper.xml - -## 快速开始 -1. 克隆项目 -2. 导入```test```包里的mysql脚本user.sql -3. 对```test```包内的代码生成器```CodeGenerator```进行配置,主要是JDBC,因为要根据表名来生成代码 -4. 输入表名,运行```CodeGenerator.main()```方法,生成基础代码(可能需要刷新项目目录才会出来) -5. 根据业务在基础代码上进行扩展 -6. 对开发环境配置文件```application-dev.yml```进行配置,启动项目,Have Fun! - -## 开发建议 -- post调用接口ip:8080/api/user/login,参数json: {"username":"admin","password":"123456"},调用成功后, 返回token。以后调用api接口,header中传token -- 已写好注册、登陆、登出、修改密码接口, 支持单登陆端/多登陆端登陆, 具体看UserController.java 类。用户登陆之后获取session信息 JSONObject sessionInfo = httpSession.getCurrentSession(); -- 正式环境已禁用接口文档的查看,配置文件添加knife4j:production: true 即可 -- 是否允许多个登陆端,修改配置文件 redis:allowMultipleLogin:true -- Model内成员变量建议与表字段数量对应,如需扩展成员变量(比如连表查询)建议创建DTO,否则需在扩展的成员变量上加@TableField(exist = false),详见[MyBatis-Plus](https://mp.baomidou.com/guide/)文档说明 -- 建议业务失败直接使用ServiceException("ErrorMessage")抛出,由统一异常处理器来封装业务失败的响应结果,会直接被封装为{"code":400,"message":"ErrorMessage"}返回,尽情抛出;body方式传参,@Valid校验Model,更无需自己处理; - -## 接口文档效果图 -![image-20200313084433855](http://tuchuang.aitangbao.com.cn/image-20200313084433855.png) - -## 相关文档 -- Spring Boot([springboot官方](https://spring.io/projects/spring-boot/)) -- MyBatis-Plus ([查看官方中文文档](https://mp.baomidou.com/guide/)) -- MyBatis-Plus分页插件([查看官方中文文档](https://mp.baomidou.com/guide/page.html)) -- Druid Spring Boot Starter([查看官方中文文档](https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter/)) -- Fastjson([查看官方中文文档](https://github.com/Alibaba/fastjson/wiki/%E9%A6%96%E9%A1%B5)) -- 阿里巴巴Java开发手册[最新版下载](https://github.com/alibaba/p3c) -其他 - -## License -纯粹开源分享,感谢大家 [Star](https://github.com/aitangbao/springboot-api-v2) 的支持。 diff --git a/java_project_template/springboot-api-v2/pom.xml b/java_project_template/springboot-api-v2/pom.xml deleted file mode 100644 index 8c6983d8e2..0000000000 --- a/java_project_template/springboot-api-v2/pom.xml +++ /dev/null @@ -1,160 +0,0 @@ - - - 4.0.0 - - com.company.project - springboot-api-v2 - 1.0 - jar - - - 1.8 - 3.3.0 - - - - - org.springframework.boot - spring-boot-starter-parent - 2.2.2.RELEASE - - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-jdbc - - - - org.springframework.boot - spring-boot-starter-data-redis - - - org.springframework.boot - spring-boot-starter-test - test - - - - com.baomidou - dynamic-datasource-spring-boot-starter - 2.5.5 - - - com.baomidou - mybatis-plus - ${mybatis-plus.version} - - - com.baomidou - mybatis-plus-boot-starter - ${mybatis-plus.version} - - - com.baomidou - mybatis-plus-generator - ${mybatis-plus.version} - - - org.projectlombok - lombok - 1.18.10 - provided - - - - - - commons-codec - commons-codec - - - org.apache.commons - commons-lang3 - 3.6 - - - - mysql - mysql-connector-java - runtime - - - - - com.alibaba - fastjson - 1.2.47 - - - - com.alibaba - druid-spring-boot-starter - 1.1.10 - - - - org.freemarker - freemarker - 2.3.30 - test - - - - com.github.xiaoymin - knife4j-spring-boot-starter - 2.0.2 - - - - io.jsonwebtoken - jjwt - 0.9.1 - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - maven-compiler-plugin - - ${java.version} - ${java.version} - UTF-8 - - - - - - - - aliyun-repos - http://maven.aliyun.com/nexus/content/groups/public/ - - false - - - - - - - aliyun-plugin - http://maven.aliyun.com/nexus/content/groups/public/ - - false - - - - - \ No newline at end of file diff --git a/java_project_template/springboot-api-v2/src/main/java/com/company/project/Application.java b/java_project_template/springboot-api-v2/src/main/java/com/company/project/Application.java deleted file mode 100644 index 2d366a4211..0000000000 --- a/java_project_template/springboot-api-v2/src/main/java/com/company/project/Application.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.company.project; - -import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure; -import org.mybatis.spring.annotation.MapperScan; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.env.Environment; -import springfox.documentation.swagger2.annotations.EnableSwagger2; - -import java.net.InetAddress; - -@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class) -@MapperScan("com.company.project.dao") -public class Application { - - private static Logger logger= LoggerFactory.getLogger(Application.class); - - public static void main(String[] args) throws Exception { - - ConfigurableApplicationContext application = SpringApplication.run(Application.class, args); - - Environment env = application.getEnvironment(); - logger.info("\n----------------------------------------------------------\n\t" + - "Application '{}' is running! Access URLs:\n\t" + - "Local: \t\thttp://localhost:{}\n\t" + - "External: \thttp://{}:{}\n\t" + - "Doc: \thttp://{}:{}/doc.html\n" + - "----------------------------------------------------------", - env.getProperty("spring.application.name"), - env.getProperty("server.port"), - InetAddress.getLocalHost().getHostAddress(), - env.getProperty("server.port"), - InetAddress.getLocalHost().getHostAddress(), - env.getProperty("server.port")); - } -} - diff --git a/java_project_template/springboot-api-v2/src/main/java/com/company/project/configurer/LoginInterceptor.java b/java_project_template/springboot-api-v2/src/main/java/com/company/project/configurer/LoginInterceptor.java deleted file mode 100644 index b0d7c2949c..0000000000 --- a/java_project_template/springboot-api-v2/src/main/java/com/company/project/configurer/LoginInterceptor.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.company.project.configurer; - - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.company.project.core.Result; -import com.company.project.core.ResultCode; -import com.company.project.service.HttpSessionService; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import java.io.IOException; - -/** - * @author wenbin - * @since 2019/10/30 15:29 - *

登陆拦截器 - */ -public class LoginInterceptor extends HandlerInterceptorAdapter { - - @Autowired - private HttpSessionService httpSession; - - private final Logger logger = LoggerFactory.getLogger(WebMvcConfigurer.class); - - @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - //用户当前session信息 - JSONObject currentSession; - //拦截接口 - //从header中获取token - String token = request.getHeader("token"); - //如果header中不存在token,则从参数中获取token - if (StringUtils.isBlank(token)) { - token = request.getParameter("token"); - } - //token为空返回 - if (StringUtils.isBlank(token)) { - Result result = new Result(); - result.setCode(ResultCode.UNAUTHORIZED).setMessage("token不能为空").setSuccess(false); - responseResult(response, result); - return false; - }// 校验并解析token,如果token过期或者篡改,则会返回null - currentSession = httpSession.getCurrentSession(); - if (null != currentSession) { - return true; - } else { - Result result = new Result(); - result.setCode(ResultCode.UNAUTHORIZED).setMessage("用户未登陆!").setSuccess(false); - responseResult(response, result); - return false; - } - } - - - private void responseResult(HttpServletResponse response, Result result) { - response.setCharacterEncoding("UTF-8"); - response.setHeader("Content-type", "application/json;charset=UTF-8"); - try { - response.getWriter().write(JSON.toJSONString(result)); - } catch (IOException ex) { - logger.error(ex.getMessage()); - } - } -} diff --git a/java_project_template/springboot-api-v2/src/main/java/com/company/project/configurer/MyBatisPlusConfig.java b/java_project_template/springboot-api-v2/src/main/java/com/company/project/configurer/MyBatisPlusConfig.java deleted file mode 100644 index f75a63819c..0000000000 --- a/java_project_template/springboot-api-v2/src/main/java/com/company/project/configurer/MyBatisPlusConfig.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.company.project.configurer; - -import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * @ClassName MyBatisPlusConfig - * @Version 1.0 - **/ -@Configuration -public class MyBatisPlusConfig { - /** - * 配置mybatis-plus 分页查件 - * @return - */ - @Bean - public PaginationInterceptor paginationInterceptor() { - PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); - return paginationInterceptor; - } -} \ No newline at end of file diff --git a/java_project_template/springboot-api-v2/src/main/java/com/company/project/configurer/SwaggerConfiguration.java b/java_project_template/springboot-api-v2/src/main/java/com/company/project/configurer/SwaggerConfiguration.java deleted file mode 100644 index d5bca5303f..0000000000 --- a/java_project_template/springboot-api-v2/src/main/java/com/company/project/configurer/SwaggerConfiguration.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.company.project.configurer; - -import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration; -import springfox.documentation.builders.ApiInfoBuilder; -import springfox.documentation.builders.PathSelectors; -import springfox.documentation.builders.RequestHandlerSelectors; -import springfox.documentation.service.ApiInfo; -import springfox.documentation.spi.DocumentationType; -import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger2.annotations.EnableSwagger2; - -@Configuration -@EnableSwagger2 -@EnableKnife4j -@Import(BeanValidatorPluginsConfiguration.class) -public class SwaggerConfiguration { - - @Bean - public Docket createRestApi() { - return new Docket(DocumentationType.SWAGGER_2) - .apiInfo(apiInfo()) - .select() - .apis(RequestHandlerSelectors.basePackage("com.company.project.web")) - .paths(PathSelectors.any()) - .build(); - } - - private ApiInfo apiInfo() { - return new ApiInfoBuilder() - .title("Springboot-api APIs") - .description("Springboot-api APIs") - .termsOfServiceUrl("http://localhost:8080/") - .contact("xxxxxxxxxx@163.com") - .version("1.0") - .build(); - } -} \ No newline at end of file diff --git a/java_project_template/springboot-api-v2/src/main/java/com/company/project/configurer/WebMvcConfigurer.java b/java_project_template/springboot-api-v2/src/main/java/com/company/project/configurer/WebMvcConfigurer.java deleted file mode 100644 index e95b243815..0000000000 --- a/java_project_template/springboot-api-v2/src/main/java/com/company/project/configurer/WebMvcConfigurer.java +++ /dev/null @@ -1,177 +0,0 @@ -package com.company.project.configurer; - -import java.io.IOException; -import java.nio.charset.Charset; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.serializer.SerializerFeature; -import com.alibaba.fastjson.support.config.FastJsonConfig; -import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; - -import com.company.project.core.Result; -import com.company.project.core.ResultCode; -import com.company.project.core.ResultGenerator; -import com.company.project.core.ServiceException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.MediaType; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.web.bind.MethodArgumentNotValidException; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.method.HandlerMethod; -import org.springframework.web.servlet.HandlerExceptionResolver; -import org.springframework.web.servlet.ModelAndView; -import org.springframework.web.servlet.NoHandlerFoundException; -import org.springframework.web.servlet.config.annotation.*; - -/** - * Spring MVC 配置 - */ -@Configuration -public class WebMvcConfigurer extends WebMvcConfigurerAdapter { - - private final Logger logger = LoggerFactory.getLogger(WebMvcConfigurer.class); - - @Bean - LoginInterceptor loginInterceptor() { - - return new LoginInterceptor(); - } - - - //使用阿里 FastJson 作为JSON MessageConverter - @Override - public void configureMessageConverters(List> converters) { - FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); - FastJsonConfig config = new FastJsonConfig(); - config.setSerializerFeatures(SerializerFeature.WriteMapNullValue);//保留空的字段 - //SerializerFeature.WriteNullStringAsEmpty,//String null -> "" - //SerializerFeature.WriteNullNumberAsZero//Number null -> 0 - // 按需配置,更多参考FastJson文档哈 - - converter.setFastJsonConfig(config); - converter.setDefaultCharset(Charset.forName("UTF-8")); - converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON_UTF8)); - converters.add(converter); - } - - - //统一异常处理 - @Override - public void configureHandlerExceptionResolvers(List exceptionResolvers) { - exceptionResolvers.add(new HandlerExceptionResolver() { - public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) { - Result result = new Result(); - if (e instanceof ServiceException) {//业务失败的异常,如“账号或密码错误” - result.setCode(ResultCode.FAIL).setMessage(e.getMessage()).setSuccess(false); - } else if (e instanceof MethodArgumentNotValidException) {//@valid注解验证参数 - MethodArgumentNotValidException m = (MethodArgumentNotValidException) e; - m.getBindingResult().getFieldError().getDefaultMessage(); - result.setCode(ResultCode.PARAM_FAIL).setMessage(m.getBindingResult().getFieldError().getDefaultMessage()).setSuccess(false); - } else if (e instanceof NoHandlerFoundException) { - result.setCode(ResultCode.NOT_FOUND).setMessage("接口 [" + request.getRequestURI() + "] 不存在").setSuccess(false); - } else if (e instanceof ServletException) { - result.setCode(ResultCode.FAIL).setMessage(e.getMessage()).setSuccess(false); - } else { - result.setCode(ResultCode.INTERNAL_SERVER_ERROR).setMessage("接口 [" + request.getRequestURI() + "] 内部错误,请联系管理员").setSuccess(false); - String message; - if (handler instanceof HandlerMethod) { - HandlerMethod handlerMethod = (HandlerMethod) handler; - message = String.format("接口 [%s] 出现异常,方法:%s.%s,异常摘要:%s", - request.getRequestURI(), - handlerMethod.getBean().getClass().getName(), - handlerMethod.getMethod().getName(), - e.getMessage()); - } else { - message = e.getMessage(); - } - logger.error(message, e); - } - responseResult(response, result); - return new ModelAndView(); - } - - }); - } - - @ExceptionHandler(MethodArgumentNotValidException.class) - public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { - return ResultGenerator.genFailResult(e.getBindingResult().getFieldError().getDefaultMessage()); - } - - /** - * 页面跨域访问Controller过滤 - * - * @return - */ - @Override - public void addCorsMappings(CorsRegistry registry) { - WebMvcConfigurer.super.addCorsMappings(registry); - registry.addMapping("/**") - .allowedHeaders("*") - .allowedMethods("POST", "GET") - .allowedOrigins("*"); - } - - //添加拦截器 - @Override - public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(loginInterceptor()) - .excludePathPatterns("/doc.html") - .excludePathPatterns("/swagger-resources/**") - .excludePathPatterns("/error") - .excludePathPatterns("/webjars/**") - .excludePathPatterns("/api/user/login") - .excludePathPatterns("/api/user/register") - .addPathPatterns("/**"); - } - - - private void responseResult(HttpServletResponse response, Result result) { - response.setCharacterEncoding("UTF-8"); - response.setHeader("Content-type", "application/json;charset=UTF-8"); - try { - response.getWriter().write(JSON.toJSONString(result)); - } catch (IOException ex) { - logger.error(ex.getMessage()); - } - } - - /** - * 发现如果继承了WebMvcConfigurationSupport,则在yml中配置的相关内容会失效。 需要重新指定静态资源 - * - * @param registry - */ - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("/**").addResourceLocations( - "classpath:/static/"); - registry.addResourceHandler("doc.html").addResourceLocations( - "classpath:/META-INF/resources/"); - registry.addResourceHandler("/webjars/**").addResourceLocations( - "classpath:/META-INF/resources/webjars/"); - super.addResourceHandlers(registry); - } - - - /** - * 配置servlet处理 - */ - @Override - public void configureDefaultServletHandling( - DefaultServletHandlerConfigurer configurer) { - configurer.enable(); - } - - -} - diff --git a/java_project_template/springboot-api-v2/src/main/java/com/company/project/core/ApplicationContextUtil.java b/java_project_template/springboot-api-v2/src/main/java/com/company/project/core/ApplicationContextUtil.java deleted file mode 100644 index 8121fb4b4b..0000000000 --- a/java_project_template/springboot-api-v2/src/main/java/com/company/project/core/ApplicationContextUtil.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.company.project.core; - -import org.springframework.beans.BeansException; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.stereotype.Component; - -/** - * @className: ApplicationContextUtil - * @Description: 解决定时任务获取不到service的问题 - * @Author moneylee - * @Date 2019-05-11 14:28 - * @Version 1.0 - **/ -@Component -public class ApplicationContextUtil implements ApplicationContextAware { - - private static ApplicationContext applicationContext; - - public static ApplicationContext getApplicationContext() { - return applicationContext; - } - - - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - ApplicationContextUtil.applicationContext = applicationContext; - - } - - public static Object getBean(String beanName) { - return applicationContext.getBean(beanName); - } - -} \ No newline at end of file diff --git a/java_project_template/springboot-api-v2/src/main/java/com/company/project/core/Result.java b/java_project_template/springboot-api-v2/src/main/java/com/company/project/core/Result.java deleted file mode 100644 index b208a52ae2..0000000000 --- a/java_project_template/springboot-api-v2/src/main/java/com/company/project/core/Result.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.company.project.core; - -import com.alibaba.fastjson.JSON; - -/** - * 统一API响应结果封装 - */ -public class Result { - private int code; - private String message; - private T data; - private Boolean success; - - public Result setCode(ResultCode resultCode) { - this.code = resultCode.code(); - return this; - } - - public int getCode() { - return code; - } - - public String getMessage() { - return message; - } - - public Result setMessage(String message) { - this.message = message; - return this; - } - - public T getData() { - return data; - } - - public Result setData(T data) { - this.data = data; - return this; - } - - public Boolean getSuccess() { - return success; - } - - public Result setSuccess(Boolean success) { - this.success = success; - return this; - } - - @Override - public String toString() { - return JSON.toJSONString(this); - } -} diff --git a/java_project_template/springboot-api-v2/src/main/java/com/company/project/core/ResultCode.java b/java_project_template/springboot-api-v2/src/main/java/com/company/project/core/ResultCode.java deleted file mode 100644 index 651c04d826..0000000000 --- a/java_project_template/springboot-api-v2/src/main/java/com/company/project/core/ResultCode.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.company.project.core; - -/** - * 响应码枚举,参考HTTP状态码的语义 - */ -public enum ResultCode { - SUCCESS(200),//成功 - FAIL(400),//失败 - UNAUTHORIZED(401),//未认证(签名错误) - NOT_FOUND(404),//接口不存在 - INTERNAL_SERVER_ERROR(500),//服务器内部错误 - PARAM_FAIL(10001);//参数异常 - - private final int code; - - ResultCode(int code) { - this.code = code; - } - - public int code() { - return code; - } -} diff --git a/java_project_template/springboot-api-v2/src/main/java/com/company/project/core/ResultGenerator.java b/java_project_template/springboot-api-v2/src/main/java/com/company/project/core/ResultGenerator.java deleted file mode 100644 index de79f955e9..0000000000 --- a/java_project_template/springboot-api-v2/src/main/java/com/company/project/core/ResultGenerator.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.company.project.core; - -/** - * 响应结果生成工具 - */ -public class ResultGenerator { - private static final String DEFAULT_SUCCESS_MESSAGE = "SUCCESS"; - - public static Result genSuccessResult() { - return new Result() - .setSuccess(true) - .setCode(ResultCode.SUCCESS) - .setMessage(DEFAULT_SUCCESS_MESSAGE); - } - - public static Result genSuccessResult(T data) { - return new Result() - .setSuccess(true) - .setCode(ResultCode.SUCCESS) - .setMessage(DEFAULT_SUCCESS_MESSAGE) - .setData(data); - } - - public static Result genFailResult(String message) { - return new Result() - .setSuccess(false) - .setCode(ResultCode.FAIL) - .setMessage(message); - } -} diff --git a/java_project_template/springboot-api-v2/src/main/java/com/company/project/core/ServiceException.java b/java_project_template/springboot-api-v2/src/main/java/com/company/project/core/ServiceException.java deleted file mode 100644 index e698bce9da..0000000000 --- a/java_project_template/springboot-api-v2/src/main/java/com/company/project/core/ServiceException.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.company.project.core; - -/** - * 服务(业务)异常如“ 账号或密码错误 ”,该异常只做INFO级别的日志记录 @see WebMvcConfigurer - */ -public class ServiceException extends RuntimeException { - public ServiceException() { - } - - public ServiceException(String message) { - super(message); - } - - public ServiceException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/java_project_template/springboot-api-v2/src/main/java/com/company/project/dao/UserMapper.java b/java_project_template/springboot-api-v2/src/main/java/com/company/project/dao/UserMapper.java deleted file mode 100644 index f731dd72d1..0000000000 --- a/java_project_template/springboot-api-v2/src/main/java/com/company/project/dao/UserMapper.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.company.project.dao; - -import com.company.project.model.User; -import com.baomidou.mybatisplus.core.mapper.BaseMapper; - -/** - *

- * Mapper 接口 - *

- * - * @author project - * @since 2020-01-08 - */ -public interface UserMapper extends BaseMapper { - -} diff --git a/java_project_template/springboot-api-v2/src/main/java/com/company/project/model/User.java b/java_project_template/springboot-api-v2/src/main/java/com/company/project/model/User.java deleted file mode 100644 index ccb159e35c..0000000000 --- a/java_project_template/springboot-api-v2/src/main/java/com/company/project/model/User.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.company.project.model; - -import com.baomidou.mybatisplus.annotation.IdType; -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableId; -import com.baomidou.mybatisplus.annotation.TableLogic; -import java.io.Serializable; -import java.util.Date; - -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.experimental.Accessors; - -import javax.validation.constraints.NotEmpty; - -/** - *

- * - *

- * - * @author project - * @since 2020-01-08 - */ -@Data -@EqualsAndHashCode(callSuper = false) -@Accessors(chain = true) -public class User implements Serializable { - - private static final long serialVersionUID = 1L; - - /** - * 主键 - */ - @TableId(value = "id", type = IdType.AUTO) - private Integer id; - - /** - * 用户名 - */ - @NotEmpty(message = "用户名不能为空!") - private String username; - - /** - * 密码 - */ - @NotEmpty(message = "密码不能为空!") - private String password; - - /** - * 昵称 - */ - private String nickName; - - /** - * 性别 - */ - private Integer sex; - - /** - * 创建时间 - */ - private Date createDate; - - /** - * 创建人 - */ - private Integer createUser; - - /** - * 修改时间 - */ - private Date updateDate; - - /** - * 修改人 - */ - private Integer updateUser; - - /** - * 删除标志0未删 1删除 - */ - @TableLogic - private Integer delFlag; - - /** - * 登陆返回token - */ - @TableField(exist = false) - private String token; - -} diff --git a/java_project_template/springboot-api-v2/src/main/java/com/company/project/service/HttpSessionService.java b/java_project_template/springboot-api-v2/src/main/java/com/company/project/service/HttpSessionService.java deleted file mode 100644 index c28c14b817..0000000000 --- a/java_project_template/springboot-api-v2/src/main/java/com/company/project/service/HttpSessionService.java +++ /dev/null @@ -1,148 +0,0 @@ -package com.company.project.service; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.company.project.model.User; -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; - -import javax.servlet.http.HttpServletRequest; -import java.util.Random; - -/** - * session管理器 - * - * @author aitangbao - */ -@Service -public class HttpSessionService { - - @Autowired - private RedisService redisDB; - - @Autowired - private HttpServletRequest request; - - @Value("${redis.key.prefix.userToken}") - private String USER_TOKEN_PREFIX; - - @Value("${redis.key.expire.userToken}") - private int EXPIRE ; - - public String createTokenAndUser(User user) { - //方便根据id找到redis的key, 修改密码/退出登陆 方便使用 - String token = getRandomToken(32) + "#" + user.getId(); - JSONObject sessionInfo = new JSONObject(); - sessionInfo.put("userId", user.getId()); - sessionInfo.put("username", user.getUsername()); - String key = USER_TOKEN_PREFIX + token; - //设置该用户已登录的token - redisDB.setAndExpire(key, sessionInfo.toJSONString(), EXPIRE); - return token; - } - - /** - * 根据token获取userid - * - * @param token - * @return - */ - public static String getUserIdByToken(String token) { - if (StringUtils.isBlank(token) || !token.contains("#")) { - return ""; - } else { - return token.substring(token.indexOf("#") + 1); - } - } - - /** - * 获取参数中的token - * - * @return - */ - public String getTokenFromHeader() { - String token = request.getHeader("token"); - //如果header中不存在token,则从参数中获取token - if (StringUtils.isBlank(token)) { - token = request.getParameter("token"); - } - return token; - } - - /** - * 获取当前session信息 - * - * @return - */ - public JSONObject getCurrentSession() { - String token = getTokenFromHeader(); - if (null != token) { - if (redisDB.exists(USER_TOKEN_PREFIX + token)) { - String sessionInfoStr = redisDB.get(USER_TOKEN_PREFIX + token); - JSONObject sessionInfo = JSON.parseObject(sessionInfoStr); - return sessionInfo; - } else { - return null; - } - } else { - return null; - } - } - - - /** - * 使当前用户的token失效 - */ - public void abortUserByToken() { - String token = getTokenFromHeader(); - redisDB.del(USER_TOKEN_PREFIX + token); - } - - /** - * 使所有用户的token失效 - */ - public void abortAllUserByToken() { - String token = getTokenFromHeader(); - String userId = getUserIdByToken(token); - redisDB.delKeys(USER_TOKEN_PREFIX+"*#" + userId); - } - - /** - * 使用户的token失效 - */ - public void abortUserByUserId(Integer userId) { - redisDB.delKeys(USER_TOKEN_PREFIX+"*#" + userId); - } - - - /** - * 生成随机的token - * - * @param length - * @return - */ - private String getRandomToken(int length) { - Random random = new Random(); - StringBuilder randomStr = new StringBuilder(); - - // 根据length生成相应长度的随机字符串 - for (int i = 0; i < length; i++) { - String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; - - //输出字母还是数字 - if ("char".equalsIgnoreCase(charOrNum)) { - //输出是大写字母还是小写字母 - int temp = random.nextInt(2) % 2 == 0 ? 65 : 97; - randomStr.append((char) (random.nextInt(26) + temp)); - } else if ("num".equalsIgnoreCase(charOrNum)) { - randomStr.append(String.valueOf(random.nextInt(10))); - } - } - - return randomStr.toString(); - } - - -} diff --git a/java_project_template/springboot-api-v2/src/main/java/com/company/project/service/IUserService.java b/java_project_template/springboot-api-v2/src/main/java/com/company/project/service/IUserService.java deleted file mode 100644 index 97ab829ead..0000000000 --- a/java_project_template/springboot-api-v2/src/main/java/com/company/project/service/IUserService.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.company.project.service; - -import com.company.project.core.Result; -import com.company.project.model.User; -import com.baomidou.mybatisplus.extension.service.IService; - -/** - *

- * 服务类 - *

- * - * @author project - * @since 2020-01-08 - */ -public interface IUserService extends IService { - - Result checkPassword(User userParam); -} diff --git a/java_project_template/springboot-api-v2/src/main/java/com/company/project/service/RedisService.java b/java_project_template/springboot-api-v2/src/main/java/com/company/project/service/RedisService.java deleted file mode 100644 index 238e4bee99..0000000000 --- a/java_project_template/springboot-api-v2/src/main/java/com/company/project/service/RedisService.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.company.project.service; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.stereotype.Service; -import org.springframework.util.CollectionUtils; - -import java.util.Date; -import java.util.Set; -import java.util.concurrent.TimeUnit; - - -/** - * @author : aitangbao - */ - -@Service -public class RedisService { - @Autowired - private StringRedisTemplate redisTemplate; - - public boolean exists(String key) { - return this.redisTemplate.hasKey(key); - } - - public String get(String key) { - String value = this.redisTemplate.opsForValue().get(key); - return value; - } - - - public void del(String key) { - if (this.exists(key)) { - this.redisTemplate.delete(key); - } - - } - - public void setAndExpire(String key, String value, int seconds) { - this.redisTemplate.opsForValue().set(key, value); - this.redisTemplate.expire(key, (long) seconds, TimeUnit.SECONDS); - } - - - public void setExpire(String key, Date endTime) { - long seconds = endTime.getTime() - (new Date()).getTime(); - this.redisTemplate.expire(key, (long) ((int) (seconds / 1000L)), TimeUnit.SECONDS); - } - - - public Set keys(String pattern) { - return redisTemplate.keys("*" + pattern); - } - - public void delKeys(String pattern) { - Set keys = redisTemplate.keys(pattern); - if (!CollectionUtils.isEmpty(keys)) { - this.redisTemplate.delete(keys); - } - } -} diff --git a/java_project_template/springboot-api-v2/src/main/java/com/company/project/service/impl/UserServiceImpl.java b/java_project_template/springboot-api-v2/src/main/java/com/company/project/service/impl/UserServiceImpl.java deleted file mode 100644 index 67f595f402..0000000000 --- a/java_project_template/springboot-api-v2/src/main/java/com/company/project/service/impl/UserServiceImpl.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.company.project.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.company.project.core.Result; -import com.company.project.core.ResultGenerator; -import com.company.project.model.User; -import com.company.project.dao.UserMapper; -import com.company.project.service.IUserService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.company.project.service.RedisService; -import com.company.project.utils.MD5Utils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; - -/** - *

- * 服务实现类 - *

- * - * @author project - * @since 2020-01-08 - */ -@Service -public class UserServiceImpl extends ServiceImpl implements IUserService { - - @Autowired - private UserMapper userMapper; - - - @Autowired - private RedisService redis; - @Value("${redis.key.prefix.passwordError}") - private String PASSWORD_ERROR_PREFIX; - @Value("${redis.key.expire.passwordError}") - private int PASSWORD_ERROR_EXPIRE; - - @Override - public Result checkPassword(User userParam) { - - String username = userParam.getUsername(); - String password = userParam.getPassword(); - //redis key - String redisPasswordErrorKey = PASSWORD_ERROR_PREFIX + username; - //判断账户是否锁定 - String errorCount = redis.get(redisPasswordErrorKey); - if (errorCount != null && Integer.parseInt(errorCount) == 5) { - return ResultGenerator.genFailResult("密码连续错误5次,请1小时后重试"); - } - //根据用户名获取用户信息 - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.eq("username", username); - User user = userMapper.selectOne(queryWrapper); - if (user == null) { - return ResultGenerator.genFailResult("账号未找到"); - } - - if (!MD5Utils.Encrypt(password, true).equals(user.getPassword())) { - if (errorCount == null) { - errorCount = "1"; - } else { - errorCount = String.valueOf(Integer.parseInt(errorCount) + 1); - } - redis.setAndExpire(redisPasswordErrorKey, errorCount, PASSWORD_ERROR_EXPIRE); - if ("5".equals(errorCount)) { - return ResultGenerator.genFailResult("密码连续错误5次,请1小时后重试"); - } else { - return ResultGenerator.genFailResult("密码错误,剩余次数" + (5 - Integer.parseInt(errorCount))); - } - } else { - //登录成功删除错误登录次数 - redis.del(redisPasswordErrorKey); - return ResultGenerator.genSuccessResult(user); - } - } -} diff --git a/java_project_template/springboot-api-v2/src/main/java/com/company/project/utils/ImageCodeUtil.java b/java_project_template/springboot-api-v2/src/main/java/com/company/project/utils/ImageCodeUtil.java deleted file mode 100644 index dd70fbc80d..0000000000 --- a/java_project_template/springboot-api-v2/src/main/java/com/company/project/utils/ImageCodeUtil.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.company.project.utils; - -import lombok.extern.slf4j.Slf4j; - -import javax.imageio.ImageIO; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import java.awt.*; -import java.awt.image.BufferedImage; -import java.util.Random; - -@Slf4j -public class ImageCodeUtil { - - - public static final String IMAGE_RANDOM_CODEKEY = "RANDOMVALIDATECODEKEY";//放到session中的key - private String randString = "0123456789";//随机产生只有数字的字符串 private String - //private String randString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生只有字母的字符串 - //private String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生数字与字母组合的字符串 - private int width = 95;// 图片宽 - private int height = 25;// 图片高 - private int lineSize = 40;// 干扰线数量 - private int stringNum = 4;// 随机产生字符数量 - - - private Random random = new Random(); - - /** - * 获得字体 - */ - private Font getFont() { - return new Font("Fixedsys", Font.CENTER_BASELINE, 18); - } - - /** - * 获得颜色 - */ - private Color getRandColor(int fc, int bc) { - if (fc > 255) - fc = 255; - if (bc > 255) - bc = 255; - int r = fc + random.nextInt(bc - fc - 16); - int g = fc + random.nextInt(bc - fc - 14); - int b = fc + random.nextInt(bc - fc - 18); - return new Color(r, g, b); - } - - /** - * 生成随机图片 - */ - public void getRandcode(HttpServletRequest request, HttpServletResponse response) { - HttpSession session = request.getSession(); - // BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类 - BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); - Graphics g = image.getGraphics();// 产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作 - g.fillRect(0, 0, width, height);//图片大小 - g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));//字体大小 - g.setColor(getRandColor(110, 133));//字体颜色 - // 绘制干扰线 - for (int i = 0; i <= lineSize; i++) { - drowLine(g); - } - // 绘制随机字符 - String randomString = ""; - for (int i = 1; i <= stringNum; i++) { - randomString = drowString(g, randomString, i); - } - log.info(randomString); - //将生成的随机字符串保存到session中 - session.removeAttribute(IMAGE_RANDOM_CODEKEY); - session.setAttribute(IMAGE_RANDOM_CODEKEY, randomString); - g.dispose(); - try { - // 将内存中的图片通过流动形式输出到客户端 - ImageIO.write(image, "JPEG", response.getOutputStream()); - } catch (Exception e) { - log.error("将内存中的图片通过流动形式输出到客户端失败>>>> ", e); - } - - } - - /** - * 绘制字符串 - */ - private String drowString(Graphics g, String randomString, int i) { - g.setFont(getFont()); - g.setColor(new Color(random.nextInt(101), random.nextInt(111), random - .nextInt(121))); - String rand = String.valueOf(getRandomString(random.nextInt(randString - .length()))); - randomString += rand; - g.translate(random.nextInt(3), random.nextInt(3)); - g.drawString(rand, 13 * i, 16); - return randomString; - } - - /** - * 绘制干扰线 - */ - private void drowLine(Graphics g) { - int x = random.nextInt(width); - int y = random.nextInt(height); - int xl = random.nextInt(13); - int yl = random.nextInt(15); - g.drawLine(x, y, x + xl, y + yl); - } - - /** - * 获取随机的字符 - */ - public String getRandomString(int num) { - return String.valueOf(randString.charAt(num)); - } -} \ No newline at end of file diff --git a/java_project_template/springboot-api-v2/src/main/java/com/company/project/utils/JwtUtils.java b/java_project_template/springboot-api-v2/src/main/java/com/company/project/utils/JwtUtils.java deleted file mode 100644 index 7cf948ef1b..0000000000 --- a/java_project_template/springboot-api-v2/src/main/java/com/company/project/utils/JwtUtils.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.company.project.utils; - -import com.company.project.model.User; -import io.jsonwebtoken.Claims; -import io.jsonwebtoken.Jwts; -import io.jsonwebtoken.SignatureAlgorithm; - -import javax.servlet.http.HttpServletRequest; -import java.util.Date; - -/** - * jwt工具类 - */ -public class JwtUtils { - - public static final String USER_ID_KEY = "user_id_key"; - - public static final String USER_ACCOUNT_KEY = "user_account_key"; - - - public static final String SUBJECT = "onehee"; - - public static final long EXPIRE = 1000*60*60*24*7; //过期时间,毫秒,一周 - - //秘钥 - public static final String APPSECRET = "onehee666"; - - /** - * 生成jwt - * @param user - * @return - */ - public static String geneJsonWebToken(User user){ - - String token = Jwts.builder().setSubject(SUBJECT) - .claim("id",user.getId()) - .claim("userName",user.getUsername()) - .setIssuedAt(new Date()) - .setExpiration(new Date(System.currentTimeMillis()+EXPIRE)) - .signWith(SignatureAlgorithm.HS256,APPSECRET).compact(); - - return token; - } - - - /** - * 校验token - * @param token - * @return - */ - public static Claims checkJWT(String token ){ - - try{ - final Claims claims = Jwts.parser().setSigningKey(APPSECRET). - parseClaimsJws(token).getBody(); - return claims; - - }catch (Exception e){ } - return null; - - } - - - /** - * 判断当前登陆用户是不是admin - * @param request - * @return - */ - public static boolean isAdmin(HttpServletRequest request) { - if (request.getAttribute(USER_ACCOUNT_KEY) == null) { - return false; - } - if ("admin".equals(request.getAttribute(USER_ACCOUNT_KEY).toString())){ - return true; - } else { - return false; - } - } - - - -} \ No newline at end of file diff --git a/java_project_template/springboot-api-v2/src/main/java/com/company/project/utils/MD5Utils.java b/java_project_template/springboot-api-v2/src/main/java/com/company/project/utils/MD5Utils.java deleted file mode 100644 index c7a3dff75c..0000000000 --- a/java_project_template/springboot-api-v2/src/main/java/com/company/project/utils/MD5Utils.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.company.project.utils; - -import org.apache.commons.codec.digest.DigestUtils; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.StringUtils; - -public class MD5Utils { - - private static String salt = "springboot_api"; - - /** - * 加密字符串 - * @param password 要加密的明文 - * @param isAddSalt 是否加默认盐 - * @return 加密之后的结果 - */ - public static String Encrypt(String password, boolean isAddSalt){ - if (StringUtils.isNotEmpty(password)){ - if (isAddSalt){ - return DigestUtils.md5Hex(DigestUtils.md5(password + salt)); - } else { - return DigestUtils.md5Hex(DigestUtils.md5(password)); - } - } - return null; - } - - /** - * - * @param bytes - * @return - */ - public static String Encrypt(byte[] bytes){ - if (ArrayUtils.isNotEmpty(bytes)){ - return DigestUtils.md5Hex(DigestUtils.md5(bytes)); - } - return null; - } - - /** - * MD5加盐加密 - * @param password 要加密的明文 - * @param salt 盐 - * @return 加密之后的结果 - */ - public static String Encrypt(String password, String salt){ - if (StringUtils.isNotEmpty(password)){ - return DigestUtils.md5Hex(DigestUtils.md5(password + salt)); - } - return null; - } - - public static void main(String[] args){ - System.out.println(MD5Utils.Encrypt("admin", true)); - } -} diff --git a/java_project_template/springboot-api-v2/src/main/java/com/company/project/web/UserController.java b/java_project_template/springboot-api-v2/src/main/java/com/company/project/web/UserController.java deleted file mode 100644 index 48aa0249b6..0000000000 --- a/java_project_template/springboot-api-v2/src/main/java/com/company/project/web/UserController.java +++ /dev/null @@ -1,203 +0,0 @@ -package com.company.project.web; - -import com.alibaba.fastjson.JSONObject; -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.company.project.core.Result; -import com.company.project.core.ResultGenerator; -import com.company.project.service.HttpSessionService; -import com.company.project.utils.MD5Utils; -import com.company.project.utils.ImageCodeUtil; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.web.bind.annotation.*; -import com.company.project.service.IUserService; -import com.company.project.model.User; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import lombok.extern.slf4j.Slf4j; -import com.baomidou.mybatisplus.core.metadata.IPage; - -import javax.annotation.Resource; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import javax.validation.Valid; - -import org.springframework.web.bind.annotation.RestController; - -import java.util.HashMap; -import java.util.Map; - -/** - *

- * 前端控制器 - *

- * - * @author project - * @since 2020-01-08 - */ -@Slf4j -@RestController -@RequestMapping("/api/user") -public class UserController { - - @Resource - private IUserService userService; - @Autowired - private HttpSessionService httpSession; - - @Value("${redis.allowMultipleLogin}") - private Boolean allowMultipleLogin; - - @ApiOperation("登陆") - @PostMapping("/login") - public Result login(@RequestBody @Valid User userParam) { - - //校验密码,5次错误锁定账户 - Result result = userService.checkPassword(userParam); - if (!result.getSuccess()) { - return result; - } - //成功之后返回user - User user = (User)result.getData(); - - //是否删除之前token, 此处控制是否支持多登陆端; - // true:允许多处登陆; false:只能单处登陆,顶掉之前登陆 - if (!allowMultipleLogin) { - httpSession.abortUserByUserId(user.getId()); - } - - //生成token - String token = httpSession.createTokenAndUser(user); - - Map resultMap = new HashMap<>(2); - resultMap.put("token", token); - resultMap.put("username", userParam.getUsername()); - return ResultGenerator.genSuccessResult(resultMap); - } - - @ApiOperation("注册") - @PostMapping("/register") - public Result register(@RequestBody @Valid User user) { - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.eq("username", user.getUsername()); - User userO = userService.getOne(queryWrapper); - if (userO != null) { - return ResultGenerator.genFailResult("账号已存在"); - } - user.setPassword(MD5Utils.Encrypt(user.getPassword(), true)); - userService.save(user); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation("修改密码") - @PostMapping("/updatePassword") - public Result updatePassword(@RequestBody JSONObject param) { - String oldPassword = param.getString("oldPassword"); - String newPassword = param.getString("newPassword"); - if (StringUtils.isBlank(oldPassword) || StringUtils.isBlank(newPassword)) { - return ResultGenerator.genFailResult("密码不能为空"); - } - //获取登陆信息 - JSONObject sessionInfo = httpSession.getCurrentSession(); - String userId = sessionInfo.getString("userId"); - - User user = userService.getById(userId); - if (user == null) { - return ResultGenerator.genFailResult("账号未找到"); - } - if (!MD5Utils.Encrypt(oldPassword, true).equals(user.getPassword())) { - return ResultGenerator.genFailResult("旧密码错误"); - } - User updateUser = new User(); - updateUser.setId(user.getId()); - updateUser.setPassword(MD5Utils.Encrypt(newPassword, true)); - userService.updateById(updateUser); - - //重置密码后删除原所有token - httpSession.abortAllUserByToken(); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation("登出") - @GetMapping("/logout") - public Result logout() { - //退出删除token - httpSession.abortUserByToken(); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation("校验token是否有效") - @GetMapping("/validateToken") - public Result validateToken() { - //拦截器拦截已判断,直接返回成功 - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "删除") - @PostMapping("delete/{id}") - public Result delete(@PathVariable("id") Long id) { - userService.removeById(id); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "更新") - @PostMapping("update") - public Result update(@RequestBody User user) { - //密码不更新 - user.setPassword(null); - userService.updateById(user); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "查询分页数据") - @ApiImplicitParams({ - @ApiImplicitParam(name = "currentPage", value = "页码"), - @ApiImplicitParam(name = "pageCount", value = "每页条数") - }) - @GetMapping("listByPage") - public Result findListByPage(@RequestParam(defaultValue = "1") Integer currentPage, - @RequestParam(defaultValue = "10") Integer pageCount) { - Page page = new Page(currentPage, pageCount); - IPage iPage = userService.page(page); - return ResultGenerator.genSuccessResult(iPage); - } - - @ApiOperation(value = "id查询") - @GetMapping("getById/{id}") - public Result findById(@PathVariable Long id) { - return ResultGenerator.genSuccessResult(userService.getById(id)); - } - - @ApiOperation(value = "生成验证码") - @GetMapping(value = "/getVerify") - public void getVerify(HttpServletRequest request, HttpServletResponse response) { - response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片 - response.setHeader("Pragma", "No-cache");//设置响应头信息,告诉浏览器不要缓存此内容 - response.setHeader("Cache-Control", "no-cache"); - response.setDateHeader("Expire", 0); - try { - ImageCodeUtil randomValidateCode = new ImageCodeUtil(); - randomValidateCode.getRandcode(request, response);//输出验证码图片方法 - } catch (Exception e) { - log.error("生成验证码失败"); - } - } - - @ApiOperation(value = "校验验证码") - @PostMapping(value = "/checkVerify") - public Result checkVerify(@RequestParam String imageCode, HttpSession session) { - //从session中获取随机数 - Object random = session.getAttribute(ImageCodeUtil.IMAGE_RANDOM_CODEKEY); - if (random != null && String.valueOf(random).equals(imageCode)) { - return ResultGenerator.genSuccessResult(); - } - return ResultGenerator.genFailResult("校验失败"); - } - - -} diff --git a/java_project_template/springboot-api-v2/src/main/resources/application-dev.yml b/java_project_template/springboot-api-v2/src/main/resources/application-dev.yml deleted file mode 100644 index b16e34f2cd..0000000000 --- a/java_project_template/springboot-api-v2/src/main/resources/application-dev.yml +++ /dev/null @@ -1,53 +0,0 @@ -# 开发环境配置 -spring: - datasource: - dynamic: - primary: master #设置默认的数据源或者数据源组,默认值即为master - datasource: - master: - username: root - password: 123456 - driver-class-name: com.mysql.cj.jdbc.Driver - url: jdbc:mysql://localhost:3306/project?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2b8 - slave_1: - username: root - password: 123456 - driver-class-name: com.mysql.cj.jdbc.Driver - url: jdbc:mysql://xx.xx.xx.xx:3307/dynamic?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2b8 - slave_2: - username: root - password: 123456 - driver-class-name: com.mysql.cj.jdbc.Driver - url: jdbc:mysql://xx.xx.xx.xx:3308/dynamic?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2b8 - #......省略 - #以上会配置一个默认库master,一个组slave下有两个子库slave_1,slave_2 - -redis: - key: - prefix: - userToken: "user:token:" - passwordError: "user:password:error:" - expire: - userToken: 604800 # 7天 7*24*3600 - passwordError: 3600 # 一个小时 - allowMultipleLogin: false # 允许多处登陆 - host: localhost # Redis服务器地址 - database: 0 # Redis数据库索引(默认为0) - port: 6379 # Redis服务器连接端口 - password: # Redis服务器连接密码(默认为空) - jedis: - pool: - max-active: 8 # 连接池最大连接数(使用负值表示没有限制) - max-wait: -1ms # 连接池最大阻塞等待时间(使用负值表示没有限制) - max-idle: 8 # 连接池中的最大空闲连接 - min-idle: 0 # 连接池中的最小空闲连接 - timeout: 3000ms # 连接超时时间(毫秒 - -mybatis-plus: - configuration: - log-impl: org.apache.ibatis.logging.stdout.StdOutImpl - mapper-locations: classpath:mapper/*.xml - global-config: - db-config: - logic-delete-value: 1 - logic-not-delete-value: 0 diff --git a/java_project_template/springboot-api-v2/src/main/resources/application-prod.yml b/java_project_template/springboot-api-v2/src/main/resources/application-prod.yml deleted file mode 100644 index 27cc9a1df0..0000000000 --- a/java_project_template/springboot-api-v2/src/main/resources/application-prod.yml +++ /dev/null @@ -1,4 +0,0 @@ -# 生产环境配置 - -knife4j: - production: true #生成环境禁用查看文档 \ No newline at end of file diff --git a/java_project_template/springboot-api-v2/src/main/resources/application-test.yml b/java_project_template/springboot-api-v2/src/main/resources/application-test.yml deleted file mode 100644 index 287da7b20e..0000000000 --- a/java_project_template/springboot-api-v2/src/main/resources/application-test.yml +++ /dev/null @@ -1 +0,0 @@ -# 测试环境配置 diff --git a/java_project_template/springboot-api-v2/src/main/resources/application.yml b/java_project_template/springboot-api-v2/src/main/resources/application.yml deleted file mode 100644 index facce6d372..0000000000 --- a/java_project_template/springboot-api-v2/src/main/resources/application.yml +++ /dev/null @@ -1,14 +0,0 @@ -spring: - profiles: - active: dev - mvc: - throw-exception-if-no-handler-found: true - resources: - add-mappings: false - application: - name: Springboot-api - jackson: - date-format: yyyy-MM-dd HH:mm:ss - time-zone: GMT+8 -server: - port: 8080 diff --git a/java_project_template/springboot-api-v2/src/main/resources/banner.txt b/java_project_template/springboot-api-v2/src/main/resources/banner.txt deleted file mode 100644 index 152e179398..0000000000 --- a/java_project_template/springboot-api-v2/src/main/resources/banner.txt +++ /dev/null @@ -1,22 +0,0 @@ -//////////////////////////////////////////////////////////////////// -// _ooOoo_ // -// o8888888o // -// 88" . "88 // -// (| ^_^ |) // -// O\ = /O // -// ____/`---'\____ // -// .' \\| |// `. // -// / \\||| : |||// \ // -// / _||||| -:- |||||- \ // -// | | \\\ - /// | | // -// | \_| ''\---/'' | | // -// \ .-\__ `-` ___/-. / // -// ___`. .' /--.--\ `. . ___ // -// ."" '< `.___\_<|>_/___.' >'"". // -// | | : `- \`.;`\ _ /`;.`/ - ` : | | // -// \ \ `-. \_ __\ /__ _/ .-` / / // -// ========`-.____`-.___\_____/___.-`____.-'======== // -// `=---=' // -// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // -// 佛祖保佑 永不宕机 永无BUG // -//////////////////////////////////////////////////////////////////// \ No newline at end of file diff --git a/java_project_template/springboot-api-v2/src/main/resources/mapper/UserMapper.xml b/java_project_template/springboot-api-v2/src/main/resources/mapper/UserMapper.xml deleted file mode 100644 index 190726401e..0000000000 --- a/java_project_template/springboot-api-v2/src/main/resources/mapper/UserMapper.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - id, username, password, nick_name, sex, create_date, create_user, update_date, update_user, del_flag - - - \ No newline at end of file diff --git a/java_project_template/springboot-api-v2/src/test/java/CodeGenerator.java b/java_project_template/springboot-api-v2/src/test/java/CodeGenerator.java deleted file mode 100644 index 2154821759..0000000000 --- a/java_project_template/springboot-api-v2/src/test/java/CodeGenerator.java +++ /dev/null @@ -1,113 +0,0 @@ -import com.baomidou.mybatisplus.core.toolkit.StringPool; -import com.baomidou.mybatisplus.generator.AutoGenerator; -import com.baomidou.mybatisplus.generator.InjectionConfig; -import com.baomidou.mybatisplus.generator.config.*; -import com.baomidou.mybatisplus.generator.config.po.TableInfo; -import com.baomidou.mybatisplus.generator.config.rules.DateType; -import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; -import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; - -import java.util.ArrayList; -import java.util.List; - -// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中 -public class CodeGenerator { - - - //多个表逗号分隔 - static String tableName = "user"; - //逻辑删除字段名, 假如表没有逻辑删除字段,请忽视 - static String logicDeleteFieldName = "del_flag"; - - public static void main(String[] args) { - // 代码生成器 - AutoGenerator mpg = new AutoGenerator(); - - // 全局配置 - GlobalConfig gc = new GlobalConfig(); - String projectPath = System.getProperty("user.dir"); - gc.setOutputDir(projectPath + "/src/main/java"); - gc.setAuthor("aitangbao"); - gc.setOpen(false); - gc.setBaseColumnList(true); - gc.setBaseResultMap(true); - gc.setDateType(DateType.ONLY_DATE); - // gc.setSwagger2(true); 实体属性 Swagger2 注解 - mpg.setGlobalConfig(gc); - - // 数据源配置 - DataSourceConfig dsc = new DataSourceConfig(); - dsc.setUrl("jdbc:mysql://localhost:3306/project?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC"); - // dsc.setSchemaName("public"); - dsc.setDriverName("com.mysql.cj.jdbc.Driver"); - dsc.setUsername("root"); - dsc.setPassword("123456"); - mpg.setDataSource(dsc); - - // 包配置 - PackageConfig pc = new PackageConfig(); - pc.setParent("com.company.project"); - pc.setEntity("model"); - pc.setMapper("dao"); - pc.setController("web"); - mpg.setPackageInfo(pc); - - // 自定义配置 - InjectionConfig cfg = new InjectionConfig() { - @Override - public void initMap() { - // to do nothing - } - }; - - // 如果模板引擎是 freemarker - String templatePath = "/templates/mapper.xml.ftl"; - // 如果模板引擎是 velocity - // String templatePath = "/templates/mapper.xml.vm"; - - // 自定义输出配置 - List focList = new ArrayList<>(); - // 自定义配置会被优先输出 - focList.add(new FileOutConfig(templatePath) { - @Override - public String outputFile(TableInfo tableInfo) { - // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!! - return projectPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; - } - }); - cfg.setFileOutConfigList(focList); - mpg.setCfg(cfg); - - // 配置模板 - TemplateConfig templateConfig = new TemplateConfig(); - - // 配置自定义输出模板 - //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别 -// templateConfig.setEntity("templates/entity.java"); - // templateConfig.setService(); - templateConfig.setController("templates/controller.java"); - - templateConfig.setXml(null); - mpg.setTemplate(templateConfig); - - // 策略配置 - StrategyConfig strategy = new StrategyConfig(); - strategy.setNaming(NamingStrategy.underline_to_camel); - strategy.setColumnNaming(NamingStrategy.underline_to_camel); -// strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!"); - strategy.setEntityLombokModel(true); - strategy.setRestControllerStyle(true); - // 公共父类 -// strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!"); - // 写于父类中的公共字段 -// strategy.setSuperEntityColumns("id"); - strategy.setInclude(tableName.split(",")); - strategy.setControllerMappingHyphenStyle(true); - strategy.setLogicDeleteFieldName(logicDeleteFieldName); // 逻辑删除字段名称 - strategy.setTablePrefix(pc.getModuleName() + "_"); - mpg.setStrategy(strategy); - mpg.setTemplateEngine(new FreemarkerTemplateEngine()); - mpg.execute(); - } - -} \ No newline at end of file diff --git a/java_project_template/springboot-api-v2/src/test/java/com/company/project/Tester.java b/java_project_template/springboot-api-v2/src/test/java/com/company/project/Tester.java deleted file mode 100644 index f513bc219d..0000000000 --- a/java_project_template/springboot-api-v2/src/test/java/com/company/project/Tester.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.company.project; - -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(classes = Application.class) -public class Tester { - - @Test - public void test() { - - } -} - - - diff --git a/java_project_template/springboot-api-v2/src/test/resources/templates/controller.java.ftl b/java_project_template/springboot-api-v2/src/test/resources/templates/controller.java.ftl deleted file mode 100644 index a62f181707..0000000000 --- a/java_project_template/springboot-api-v2/src/test/resources/templates/controller.java.ftl +++ /dev/null @@ -1,94 +0,0 @@ -package ${package.Controller}; - -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.company.project.core.Result; -import com.company.project.core.ResultGenerator; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import org.springframework.web.bind.annotation.*; -import ${package.Service}.${table.serviceName}; -import ${package.Entity}.${entity}; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import lombok.extern.slf4j.Slf4j; -import com.baomidou.mybatisplus.core.metadata.IPage; - -import javax.annotation.Resource; -<#if restControllerStyle> -import org.springframework.web.bind.annotation.RestController; -<#else> -import org.springframework.stereotype.Controller; - -<#if superControllerClassPackage??> -import ${superControllerClassPackage}; - - -/** - *

- * ${table.comment!} 前端控制器 - *

- * - * @author ${author} - * @since ${date} - */ -<#if restControllerStyle> -@Api(tags = {"${table.comment!}"}) -@Slf4j -@RestController -<#else> -@Controller - -@RequestMapping("<#if package.ModuleName??>/${package.ModuleName}/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}") -<#if kotlin> -class ${table.controllerName}<#if superControllerClass??>:${superControllerClass}() -<#else> -<#if superControllerClass??>public class ${table.controllerName} extends ${superControllerClass}{ -<#else>public class ${table.controllerName} { - - - @Resource - private ${table.serviceName} ${(table.serviceName?substring(1))?uncap_first}; - - - @ApiOperation(value = "新增${table.comment!}") - @PostMapping("add") - public Result add(@RequestBody ${entity} ${entity?uncap_first}){ - ${(table.serviceName?substring(1))?uncap_first}.save(${entity?uncap_first}); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "删除${table.comment!}") - @PostMapping("delete/{id}") - public Result delete(@PathVariable("id") Long id){ - ${(table.serviceName?substring(1))?uncap_first}.removeById(id); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "更新${table.comment!}") - @PostMapping("update") - public Result update(@RequestBody ${entity} ${entity?uncap_first}){ - ${(table.serviceName?substring(1))?uncap_first}.updateById(${entity?uncap_first}); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "查询${table.comment!}分页数据") - @ApiImplicitParams({ - @ApiImplicitParam(name = "currentPage", value = "页码"), - @ApiImplicitParam(name = "pageCount", value = "每页条数") - }) - @GetMapping("listByPage") - public Result findListByPage(@RequestParam Integer currentPage, - @RequestParam Integer pageCount){ - Page page = new Page(currentPage, pageCount); - IPage<${entity}> iPage = ${(table.serviceName?substring(1))?uncap_first}.page(page); - return ResultGenerator.genSuccessResult(iPage); - } - - @ApiOperation(value = "id查询${table.comment!}") - @GetMapping("getById/{id}") - public Result findById(@PathVariable Long id){ - return ResultGenerator.genSuccessResult(${(table.serviceName?substring(1))?uncap_first}.getById(id)); - } - -} - \ No newline at end of file diff --git a/java_project_template/springboot-api-v2/src/test/resources/user.sql b/java_project_template/springboot-api-v2/src/test/resources/user.sql deleted file mode 100644 index 51bd7db81e..0000000000 --- a/java_project_template/springboot-api-v2/src/test/resources/user.sql +++ /dev/null @@ -1,52 +0,0 @@ -/* - Navicat Premium Data Transfer - - Source Server : localhost - Source Server Type : MySQL - Source Server Version : 50529 - Source Host : localhost:3306 - Source Schema : project - - Target Server Type : MySQL - Target Server Version : 50529 - File Encoding : 65001 - - Date: 08/01/2020 15:53:02 -*/ - -SET NAMES utf8mb4; -SET FOREIGN_KEY_CHECKS = 0; - --- ---------------------------- --- Table structure for user --- ---------------------------- -DROP TABLE IF EXISTS `user`; -CREATE TABLE `user` ( - `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键', - `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名', - `password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码', - `nick_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '昵称', - `sex` int(1) NULL DEFAULT NULL COMMENT '性别', - `create_date` datetime NULL DEFAULT NULL COMMENT '创建时间', - `create_user` int(11) NULL DEFAULT NULL COMMENT '创建人', - `update_date` datetime NULL DEFAULT NULL COMMENT '修改时间', - `update_user` int(11) NULL DEFAULT NULL COMMENT '修改人', - `del_flag` int(1) NULL DEFAULT 0 COMMENT '删除标志0未删 1删除', - PRIMARY KEY (`id`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 11 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact; - --- ---------------------------- --- Records of user --- ---------------------------- -INSERT INTO `user` VALUES (1, 'admin', '9dc818b4bca3baa7d230fbf96c919638', '土豆', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (2, '2@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-2', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (3, '3@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-3', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (4, '4@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-4', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (5, '5@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-5', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (6, '6@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-6', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (7, '7@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-7', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (8, '8@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-8', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (9, '9@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-9', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `user` VALUES (10, '10@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '土豆-10', 1, NULL, NULL, NULL, NULL, 0); - -SET FOREIGN_KEY_CHECKS = 1; diff --git a/java_project_template/springboot_api_simple/README.md b/java_project_template/springboot_api_simple/README.md deleted file mode 100644 index 9e0b9c2950..0000000000 --- a/java_project_template/springboot_api_simple/README.md +++ /dev/null @@ -1,57 +0,0 @@ -## 简介 -Spring Boot API 是一个基于Spring Boot & MyBatis plus的种子项目,用于快速构建中小型API项目,特点稳定、简单、快速,摆脱那些重复劳动 - -## 特征&提供 -- 统一响应结果封装及生成工具 -- 统一异常处理 -- 采用redis token认证,支持单登陆端/多登陆端登陆 -- 使用Druid Spring Boot Starter 集成Druid数据库连接池与监控 -- 集成MyBatis-Plus,实现单表业务零SQL -- 支持多数据源,自由切换,只需方法或类上用 @DS 切换数据源 -- 集成国人风格的knife4j,自动生成接口文档 -- 提供代码生成器,生成controller,service,serviceImpl,dao,mapper.xml - -## 快速开始 -1. 克隆项目 -2. 导入```test```包里的mysql脚本user.sql -3. 对```test```包内的代码生成器```CodeGenerator```进行配置,主要是JDBC,因为要根据表名来生成代码 -4. 输入表名,运行```CodeGenerator.main()```方法,生成基础代码(可能需要刷新项目目录才会出来) -5. 根据业务在基础代码上进行扩展 -6. 对开发环境配置文件```application-dev.yml```进行配置,启动项目,Have Fun! - -## 开发建议 -- post调用接口ip:8080/api/user/login,参数json: {"username":"admin","password":"123456"},调用成功后, 返回token。以后调用api接口,header中传token -- 已写好注册、登陆、登出、修改密码接口, 支持单登陆端/多登陆端登陆, 具体看UserController.java 类。用户登陆之后获取session信息 JSONObject sessionInfo = httpSession.getCurrentSession(); -- 正式环境已禁用接口文档的查看,配置文件添加knife4j:production: true 即可 -- 是否允许多个登陆端,修改配置文件 redis:allowMultipleLogin:true -- Model内成员变量建议与表字段数量对应,如需扩展成员变量(比如连表查询)建议创建DTO,否则需在扩展的成员变量上加@TableField(exist = false),详见[MyBatis-Plus](https://mp.baomidou.com/guide/)文档说明 -- 建议业务失败直接使用ServiceException("ErrorMessage")抛出,由统一异常处理器来封装业务失败的响应结果,会直接被封装为{"code":400,"message":"ErrorMessage"}返回,尽情抛出;body方式传参,@Valid校验Model,更无需自己处理; - -## 接口文档效果图 -http://192.168.0.12:8080/api/user/login - -{"username":"admin","password":"123456"} - -{ - "code": 200, - "message": "SUCCESS", - "data": { - "token": "21C1ITp0c9973707PR9Do4Q1W18R5904#1", - "username": "admin" - }, - "success": true -} - -![image-20200313084433855](http://tuchuang.aitangbao.com.cn/image-20200313084433855.png) - -## 相关文档 -- Spring Boot([springboot官方](https://spring.io/projects/spring-boot/)) -- MyBatis-Plus ([查看官方中文文档](https://mp.baomidou.com/guide/)) -- MyBatis-Plus分页插件([查看官方中文文档](https://mp.baomidou.com/guide/page.html)) -- Druid Spring Boot Starter([查看官方中文文档](https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter/)) -- Fastjson([查看官方中文文档](https://github.com/Alibaba/fastjson/wiki/%E9%A6%96%E9%A1%B5)) -- 阿里巴巴Java开发手册[最新版下载](https://github.com/alibaba/p3c) -其他 - -## License -纯粹开源分享,感谢大家 [Star](https://github.com/aitangbao/springboot-api-v2) 的支持。 diff --git a/java_project_template/springboot_api_simple/pom.xml b/java_project_template/springboot_api_simple/pom.xml deleted file mode 100644 index a61be3b3ba..0000000000 --- a/java_project_template/springboot_api_simple/pom.xml +++ /dev/null @@ -1,164 +0,0 @@ - - - 4.0.0 - - com.company.project - springboot_api_simple - 1.0 - jar - - - 1.8 - 3.5.5 - - - - - org.springframework.boot - spring-boot-starter-parent - 2.2.2.RELEASE - - - - - - - org.projectlombok - lombok - 1.18.30 - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-jdbc - - - - org.springframework.boot - spring-boot-starter-data-redis - - - org.springframework.boot - spring-boot-starter-test - test - - - - com.baomidou - dynamic-datasource-spring-boot-starter - 2.5.5 - - - com.baomidou - mybatis-plus - ${mybatis-plus.version} - - - com.baomidou - mybatis-plus-boot-starter - ${mybatis-plus.version} - - - com.baomidou - mybatis-plus-generator - ${mybatis-plus.version} - - - org.projectlombok - lombok - 1.18.10 - provided - - - - - - commons-codec - commons-codec - - - org.apache.commons - commons-lang3 - 3.6 - - - - mysql - mysql-connector-java - runtime - - - - - com.alibaba - fastjson - 1.2.47 - - - - com.alibaba - druid-spring-boot-starter - 1.1.10 - - - - org.freemarker - freemarker - 2.3.30 - test - - - - com.github.xiaoymin - knife4j-spring-boot-starter - 2.0.2 - - - - - - - - - - - - - aliyun-repos - http://maven.aliyun.com/nexus/content/groups/public/ - - false - - - - - - - aliyun-plugin - http://maven.aliyun.com/nexus/content/groups/public/ - - false - - - - - \ No newline at end of file diff --git a/java_project_template/springboot_api_simple/src/main/java/com/company/project/Application.java b/java_project_template/springboot_api_simple/src/main/java/com/company/project/Application.java deleted file mode 100644 index d9ba05a8ed..0000000000 --- a/java_project_template/springboot_api_simple/src/main/java/com/company/project/Application.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.company.project; - -import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure; -import org.mybatis.spring.annotation.MapperScan; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.env.Environment; -import springfox.documentation.swagger2.annotations.EnableSwagger2; - -import java.net.InetAddress; - -@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class) -@MapperScan("com.company.project.dao") -public class Application { - - private static Logger logger= LoggerFactory.getLogger(Application.class); - - public static void main(String[] args) throws Exception { - - ConfigurableApplicationContext application = SpringApplication.run(Application.class, args); - - Environment env = application.getEnvironment(); - logger.info("\n----------------------------------------------------------\n\t" + - "Application '{}' is running! Access URLs:\n\t" + - "Local: \t\thttp://localhost:{}\n\t" + - "External: \thttp://{}:{}\n\t" + - "Doc: \thttp://{}:{}/doc.html\n\t" + - "Login: \thttp://{}:{}/api/user/login\n" + - "----------------------------------------------------------", - env.getProperty("spring.application.name"), - env.getProperty("server.port"), - InetAddress.getLocalHost().getHostAddress(), - env.getProperty("server.port"), - InetAddress.getLocalHost().getHostAddress(), - env.getProperty("server.port"), - InetAddress.getLocalHost().getHostAddress(), - env.getProperty("server.port")); - } -} - diff --git a/java_project_template/springboot_api_simple/src/main/java/com/company/project/config/LoginInterceptor.java b/java_project_template/springboot_api_simple/src/main/java/com/company/project/config/LoginInterceptor.java deleted file mode 100644 index 604e84baa6..0000000000 --- a/java_project_template/springboot_api_simple/src/main/java/com/company/project/config/LoginInterceptor.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.company.project.config; - - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.company.project.core.ResultCode; -import com.company.project.core.HttpSessionService; -import com.jun.plugin.common.Result; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import java.io.IOException; - -/** - * @since 2019/10/30 15:29 - *

登陆拦截器 - */ -public class LoginInterceptor extends HandlerInterceptorAdapter { - - @Autowired - private HttpSessionService httpSession; - - private final Logger logger = LoggerFactory.getLogger(WebMvcConfigurer.class); - - @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - //用户当前session信息 - JSONObject currentSession; - //拦截接口 - //从header中获取token - String token = request.getHeader("token"); - //如果header中不存在token,则从参数中获取token - if (StringUtils.isBlank(token)) { - token = request.getParameter("token"); - } - //token为空返回 - if (StringUtils.isBlank(token)) { - Result result = new Result(ResultCode.UNAUTHORIZED.code(), "token不能为空").put("success",false); - responseResult(response, result); - return false; - }// 校验并解析token,如果token过期或者篡改,则会返回null - currentSession = httpSession.getCurrentSession(); - if (null != currentSession) { - return true; - } else { - Result result = new Result(ResultCode.UNAUTHORIZED.code(), "用户未登陆!").put("success",false); - responseResult(response, result); - return false; - } - } - - - private void responseResult(HttpServletResponse response, Result result) { - response.setCharacterEncoding("UTF-8"); - response.setHeader("Content-type", "application/json;charset=UTF-8"); - try { - response.getWriter().write(JSON.toJSONString(result)); - } catch (IOException ex) { - logger.error(ex.getMessage()); - } - } -} diff --git a/java_project_template/springboot_api_simple/src/main/java/com/company/project/config/MyBatisPlusConfig.java b/java_project_template/springboot_api_simple/src/main/java/com/company/project/config/MyBatisPlusConfig.java deleted file mode 100644 index f8e1c0693f..0000000000 --- a/java_project_template/springboot_api_simple/src/main/java/com/company/project/config/MyBatisPlusConfig.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.company.project.config; - -import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * @ClassName MyBatisPlusConfig - * @Version 1.0 - **/ -@Configuration -public class MyBatisPlusConfig { - /** - * 配置mybatis-plus 分页查件 - * @return - */ - @Bean - public PaginationInnerInterceptor paginationInterceptor() { - PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor(); - return paginationInterceptor; - } -} \ No newline at end of file diff --git a/java_project_template/springboot_api_simple/src/main/java/com/company/project/config/SwaggerConfiguration.java b/java_project_template/springboot_api_simple/src/main/java/com/company/project/config/SwaggerConfiguration.java deleted file mode 100644 index 1fe8af5419..0000000000 --- a/java_project_template/springboot_api_simple/src/main/java/com/company/project/config/SwaggerConfiguration.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.company.project.config; - -import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration; -import springfox.documentation.builders.ApiInfoBuilder; -import springfox.documentation.builders.PathSelectors; -import springfox.documentation.builders.RequestHandlerSelectors; -import springfox.documentation.service.ApiInfo; -import springfox.documentation.spi.DocumentationType; -import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger2.annotations.EnableSwagger2; - -@Configuration -@EnableSwagger2 -@EnableKnife4j -@Import(BeanValidatorPluginsConfiguration.class) -public class SwaggerConfiguration { - - @Bean - public Docket createRestApi() { - return new Docket(DocumentationType.SWAGGER_2) - .apiInfo(apiInfo()) - .select() - .apis(RequestHandlerSelectors.basePackage("com.company.project.web")) - .paths(PathSelectors.any()) - .build(); - } - - private ApiInfo apiInfo() { - return new ApiInfoBuilder() - .title("Springboot-api APIs") - .description("Springboot-api APIs") - .termsOfServiceUrl("http://localhost:8080/") - .contact("xxxxxxxxxx@163.com") - .version("1.0") - .build(); - } -} \ No newline at end of file diff --git a/java_project_template/springboot_api_simple/src/main/java/com/company/project/config/WebMvcConfigurer.java b/java_project_template/springboot_api_simple/src/main/java/com/company/project/config/WebMvcConfigurer.java deleted file mode 100644 index d235f1052b..0000000000 --- a/java_project_template/springboot_api_simple/src/main/java/com/company/project/config/WebMvcConfigurer.java +++ /dev/null @@ -1,176 +0,0 @@ -package com.company.project.config; - -import java.io.IOException; -import java.nio.charset.Charset; -import java.util.Arrays; -import java.util.List; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.serializer.SerializerFeature; -import com.alibaba.fastjson.support.config.FastJsonConfig; -import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; - -import com.company.project.core.ResultCode; -import com.jun.plugin.common.Result; -import com.jun.plugin.common.exception.BusinessException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.MediaType; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.web.bind.MethodArgumentNotValidException; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.method.HandlerMethod; -import org.springframework.web.servlet.HandlerExceptionResolver; -import org.springframework.web.servlet.ModelAndView; -import org.springframework.web.servlet.NoHandlerFoundException; -import org.springframework.web.servlet.config.annotation.*; - -/** - * Spring MVC 配置 - */ -@Configuration -public class WebMvcConfigurer extends WebMvcConfigurerAdapter { - - private final Logger logger = LoggerFactory.getLogger(WebMvcConfigurer.class); - - @Bean - LoginInterceptor loginInterceptor() { - - return new LoginInterceptor(); - } - - - //使用阿里 FastJson 作为JSON MessageConverter - @Override - public void configureMessageConverters(List> converters) { - FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); - FastJsonConfig config = new FastJsonConfig(); - config.setSerializerFeatures(SerializerFeature.WriteMapNullValue);//保留空的字段 - //SerializerFeature.WriteNullStringAsEmpty,//String null -> "" - //SerializerFeature.WriteNullNumberAsZero//Number null -> 0 - // 按需配置,更多参考FastJson文档哈 - - converter.setFastJsonConfig(config); - converter.setDefaultCharset(Charset.forName("UTF-8")); - converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON_UTF8)); - converters.add(converter); - } - - - //统一异常处理 - @Override - public void configureHandlerExceptionResolvers(List exceptionResolvers) { - exceptionResolvers.add(new HandlerExceptionResolver() { - public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) { - Result result = new Result(); - if (e instanceof BusinessException) {//业务失败的异常,如“账号或密码错误” - result = Result.error(ResultCode.FAIL.code(), e.getMessage()).setSuccess(false); - } else if (e instanceof MethodArgumentNotValidException) {//@valid注解验证参数 - MethodArgumentNotValidException m = (MethodArgumentNotValidException) e; - m.getBindingResult().getFieldError().getDefaultMessage(); - result = Result.error(ResultCode.PARAM_FAIL.code(), e.getMessage()).setSuccess(false); - } else if (e instanceof NoHandlerFoundException) { - result = Result.error(ResultCode.NOT_FOUND.code(), "接口 [" + request.getRequestURI() + "] 不存在").setSuccess(false); - - } else if (e instanceof ServletException) { - result = Result.error(ResultCode.FAIL.code(), e.getMessage()).setSuccess(false); - } else { - result = Result.error(ResultCode.INTERNAL_SERVER_ERROR.code(), "接口 [" + request.getRequestURI() + "] 内部错误,请联系管理员").setSuccess(false); - String message; - if (handler instanceof HandlerMethod) { - HandlerMethod handlerMethod = (HandlerMethod) handler; - message = String.format("接口 [%s] 出现异常,方法:%s.%s,异常摘要:%s", - request.getRequestURI(), - handlerMethod.getBean().getClass().getName(), - handlerMethod.getMethod().getName(), - e.getMessage()); - } else { - message = e.getMessage(); - } - logger.error(message, e); - } - responseResult(response, result); - return new ModelAndView(); - } - - }); - } - - @ExceptionHandler(MethodArgumentNotValidException.class) - public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { - return Result.fail(e.getBindingResult().getFieldError().getDefaultMessage()); - } - - /** - * 页面跨域访问Controller过滤 - * - * @return - */ - @Override - public void addCorsMappings(CorsRegistry registry) { - WebMvcConfigurer.super.addCorsMappings(registry); - registry.addMapping("/**") - .allowedHeaders("*") - .allowedMethods("POST", "GET") - .allowedOrigins("*"); - } - - //添加拦截器 - @Override - public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(loginInterceptor()) - .excludePathPatterns("/doc.html") - .excludePathPatterns("/swagger-resources/**") - .excludePathPatterns("/error") - .excludePathPatterns("/webjars/**") - .excludePathPatterns("/api/user/login") - .excludePathPatterns("/api/user/register") - .addPathPatterns("/**"); - } - - - private void responseResult(HttpServletResponse response, Result result) { - response.setCharacterEncoding("UTF-8"); - response.setHeader("Content-type", "application/json;charset=UTF-8"); - try { - response.getWriter().write(JSON.toJSONString(result)); - } catch (IOException ex) { - logger.error(ex.getMessage()); - } - } - - /** - * 发现如果继承了WebMvcConfigurationSupport,则在yml中配置的相关内容会失效。 需要重新指定静态资源 - * - * @param registry - */ - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("/**").addResourceLocations( - "classpath:/static/"); - registry.addResourceHandler("doc.html").addResourceLocations( - "classpath:/META-INF/resources/"); - registry.addResourceHandler("/webjars/**").addResourceLocations( - "classpath:/META-INF/resources/webjars/"); - super.addResourceHandlers(registry); - } - - - /** - * 配置servlet处理 - */ - @Override - public void configureDefaultServletHandling( - DefaultServletHandlerConfigurer configurer) { - configurer.enable(); - } - - -} - diff --git a/java_project_template/springboot_api_simple/src/main/java/com/company/project/core/HttpSessionService.java b/java_project_template/springboot_api_simple/src/main/java/com/company/project/core/HttpSessionService.java deleted file mode 100644 index b6e733bc16..0000000000 --- a/java_project_template/springboot_api_simple/src/main/java/com/company/project/core/HttpSessionService.java +++ /dev/null @@ -1,148 +0,0 @@ -package com.company.project.core; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.company.project.model.User; -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; - -import javax.servlet.http.HttpServletRequest; -import java.util.Random; - -/** - * session管理器 - * - * @author aitangbao - */ -@Service -public class HttpSessionService { - - @Autowired - private RedisService redisDB; - - @Autowired - private HttpServletRequest request; - - @Value("${redis.key.prefix.userToken}") - private String USER_TOKEN_PREFIX; - - @Value("${redis.key.expire.userToken}") - private int EXPIRE ; - - public String createTokenAndUser(User user) { - //方便根据id找到redis的key, 修改密码/退出登陆 方便使用 - String token = getRandomToken(32) + "#" + user.getId(); - JSONObject sessionInfo = new JSONObject(); - sessionInfo.put("userId", user.getId()); - sessionInfo.put("username", user.getUsername()); - String key = USER_TOKEN_PREFIX + token; - //设置该用户已登录的token - redisDB.setAndExpire(key, sessionInfo.toJSONString(), EXPIRE); - return token; - } - - /** - * 根据token获取userid - * - * @param token - * @return - */ - public static String getUserIdByToken(String token) { - if (StringUtils.isBlank(token) || !token.contains("#")) { - return ""; - } else { - return token.substring(token.indexOf("#") + 1); - } - } - - /** - * 获取参数中的token - * - * @return - */ - public String getTokenFromHeader() { - String token = request.getHeader("token"); - //如果header中不存在token,则从参数中获取token - if (StringUtils.isBlank(token)) { - token = request.getParameter("token"); - } - return token; - } - - /** - * 获取当前session信息 - * - * @return - */ - public JSONObject getCurrentSession() { - String token = getTokenFromHeader(); - if (null != token) { - if (redisDB.exists(USER_TOKEN_PREFIX + token)) { - String sessionInfoStr = redisDB.get(USER_TOKEN_PREFIX + token); - JSONObject sessionInfo = JSON.parseObject(sessionInfoStr); - return sessionInfo; - } else { - return null; - } - } else { - return null; - } - } - - - /** - * 使当前用户的token失效 - */ - public void abortUserByToken() { - String token = getTokenFromHeader(); - redisDB.del(USER_TOKEN_PREFIX + token); - } - - /** - * 使所有用户的token失效 - */ - public void abortAllUserByToken() { - String token = getTokenFromHeader(); - String userId = getUserIdByToken(token); - redisDB.delKeys(USER_TOKEN_PREFIX+"*#" + userId); - } - - /** - * 使用户的token失效 - */ - public void abortUserByUserId(Integer userId) { - redisDB.delKeys(USER_TOKEN_PREFIX+"*#" + userId); - } - - - /** - * 生成随机的token - * - * @param length - * @return - */ - private String getRandomToken(int length) { - Random random = new Random(); - StringBuilder randomStr = new StringBuilder(); - - // 根据length生成相应长度的随机字符串 - for (int i = 0; i < length; i++) { - String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; - - //输出字母还是数字 - if ("char".equalsIgnoreCase(charOrNum)) { - //输出是大写字母还是小写字母 - int temp = random.nextInt(2) % 2 == 0 ? 65 : 97; - randomStr.append((char) (random.nextInt(26) + temp)); - } else if ("num".equalsIgnoreCase(charOrNum)) { - randomStr.append(String.valueOf(random.nextInt(10))); - } - } - - return randomStr.toString(); - } - - -} diff --git a/java_project_template/springboot_api_simple/src/main/java/com/company/project/core/RedisService.java b/java_project_template/springboot_api_simple/src/main/java/com/company/project/core/RedisService.java deleted file mode 100644 index 79dc9da70d..0000000000 --- a/java_project_template/springboot_api_simple/src/main/java/com/company/project/core/RedisService.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.company.project.core; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.stereotype.Service; -import org.springframework.util.CollectionUtils; - -import java.util.Date; -import java.util.Set; -import java.util.concurrent.TimeUnit; - - -/** - * @author : aitangbao - */ - -@Service -public class RedisService { - @Autowired - private StringRedisTemplate redisTemplate; - - public boolean exists(String key) { - return this.redisTemplate.hasKey(key); - } - - public String get(String key) { - String value = this.redisTemplate.opsForValue().get(key); - return value; - } - - - public void del(String key) { - if (this.exists(key)) { - this.redisTemplate.delete(key); - } - - } - - public void setAndExpire(String key, String value, int seconds) { - this.redisTemplate.opsForValue().set(key, value); - this.redisTemplate.expire(key, (long) seconds, TimeUnit.SECONDS); - } - - - public void setExpire(String key, Date endTime) { - long seconds = endTime.getTime() - (new Date()).getTime(); - this.redisTemplate.expire(key, (long) ((int) (seconds / 1000L)), TimeUnit.SECONDS); - } - - - public Set keys(String pattern) { - return redisTemplate.keys("*" + pattern); - } - - public void delKeys(String pattern) { - Set keys = redisTemplate.keys(pattern); - if (!CollectionUtils.isEmpty(keys)) { - this.redisTemplate.delete(keys); - } - } -} diff --git a/java_project_template/springboot_api_simple/src/main/java/com/company/project/core/ResultCode.java b/java_project_template/springboot_api_simple/src/main/java/com/company/project/core/ResultCode.java deleted file mode 100644 index 651c04d826..0000000000 --- a/java_project_template/springboot_api_simple/src/main/java/com/company/project/core/ResultCode.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.company.project.core; - -/** - * 响应码枚举,参考HTTP状态码的语义 - */ -public enum ResultCode { - SUCCESS(200),//成功 - FAIL(400),//失败 - UNAUTHORIZED(401),//未认证(签名错误) - NOT_FOUND(404),//接口不存在 - INTERNAL_SERVER_ERROR(500),//服务器内部错误 - PARAM_FAIL(10001);//参数异常 - - private final int code; - - ResultCode(int code) { - this.code = code; - } - - public int code() { - return code; - } -} diff --git a/java_project_template/springboot_api_simple/src/main/java/com/company/project/dao/UserMapper.java b/java_project_template/springboot_api_simple/src/main/java/com/company/project/dao/UserMapper.java deleted file mode 100644 index f731dd72d1..0000000000 --- a/java_project_template/springboot_api_simple/src/main/java/com/company/project/dao/UserMapper.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.company.project.dao; - -import com.company.project.model.User; -import com.baomidou.mybatisplus.core.mapper.BaseMapper; - -/** - *

- * Mapper 接口 - *

- * - * @author project - * @since 2020-01-08 - */ -public interface UserMapper extends BaseMapper { - -} diff --git a/java_project_template/springboot_api_simple/src/main/java/com/company/project/model/User.java b/java_project_template/springboot_api_simple/src/main/java/com/company/project/model/User.java deleted file mode 100644 index fd6180a538..0000000000 --- a/java_project_template/springboot_api_simple/src/main/java/com/company/project/model/User.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.company.project.model; - -import com.baomidou.mybatisplus.annotation.*; - -import java.io.Serializable; -import java.util.Date; - -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.experimental.Accessors; - -import javax.validation.constraints.NotEmpty; - -/** - * @author project - * @since 2020-01-08 - */ -@Data -@EqualsAndHashCode(callSuper = false) -@Accessors(chain = true) -@TableName("t_user") -public class User implements Serializable { - - private static final long serialVersionUID = 1L; - - /** - * 主键 - */ - @TableId(value = "id", type = IdType.AUTO) - private Integer id; - - /** - * 用户名 - */ - @NotEmpty(message = "用户名不能为空!") - private String username; - - /** - * 密码 - */ - @NotEmpty(message = "密码不能为空!") - private String password; - - /** - * 昵称 - */ - private String nickName; - - /** - * 性别 - */ - private Integer sex; - - /** - * 创建时间 - */ - private Date createDate; - - /** - * 创建人 - */ - private Integer createUser; - - /** - * 修改时间 - */ - private Date updateDate; - - /** - * 修改人 - */ - private Integer updateUser; - - /** - * 删除标志0未删 1删除 - */ - @TableLogic - private Integer delFlag; - - /** - * 登陆返回token - */ - @TableField(exist = false) - private String token; - -} diff --git a/java_project_template/springboot_api_simple/src/main/java/com/company/project/service/IUserService.java b/java_project_template/springboot_api_simple/src/main/java/com/company/project/service/IUserService.java deleted file mode 100644 index 48c10d3af1..0000000000 --- a/java_project_template/springboot_api_simple/src/main/java/com/company/project/service/IUserService.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.company.project.service; - -import com.company.project.model.User; -import com.baomidou.mybatisplus.extension.service.IService; -import com.jun.plugin.common.Result; - -/** - *

- * 服务类 - *

- * - * @author project - * @since 2020-01-08 - */ -public interface IUserService extends IService { - - Result checkPassword(User userParam); -} diff --git a/java_project_template/springboot_api_simple/src/main/java/com/company/project/service/impl/UserServiceImpl.java b/java_project_template/springboot_api_simple/src/main/java/com/company/project/service/impl/UserServiceImpl.java deleted file mode 100644 index 186562d4f8..0000000000 --- a/java_project_template/springboot_api_simple/src/main/java/com/company/project/service/impl/UserServiceImpl.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.company.project.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.company.project.model.User; -import com.company.project.dao.UserMapper; -import com.company.project.service.IUserService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.company.project.core.RedisService; -import com.company.project.utils.MD5Utils; -import com.jun.plugin.common.Result; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; - -/** - *

- * 服务实现类 - *

- * - * @author project - * @since 2020-01-08 - */ -@Service -public class UserServiceImpl extends ServiceImpl implements IUserService { - - @Autowired - private UserMapper userMapper; - - - @Autowired - private RedisService redis; - @Value("${redis.key.prefix.passwordError}") - private String PASSWORD_ERROR_PREFIX; - @Value("${redis.key.expire.passwordError}") - private int PASSWORD_ERROR_EXPIRE; - - @Override - public Result checkPassword(User userParam) { - - String username = userParam.getUsername(); - String password = userParam.getPassword(); - //redis key - String redisPasswordErrorKey = PASSWORD_ERROR_PREFIX + username; - //判断账户是否锁定 - String errorCount = redis.get(redisPasswordErrorKey); - if (errorCount != null && Integer.parseInt(errorCount) == 5) { - return Result.fail("密码连续错误5次,请1小时后重试"); - } - //根据用户名获取用户信息 - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.eq("username", username); - User user = userMapper.selectOne(queryWrapper); - if (user == null) { - return Result.fail("账号未找到"); - } - - if (!MD5Utils.Encrypt(password, true).equals(user.getPassword())) { - if (errorCount == null) { - errorCount = "1"; - } else { - errorCount = String.valueOf(Integer.parseInt(errorCount) + 1); - } - redis.setAndExpire(redisPasswordErrorKey, errorCount, PASSWORD_ERROR_EXPIRE); - if ("5".equals(errorCount)) { - return Result.fail("密码连续错误5次,请1小时后重试"); - } else { - return Result.fail("密码错误,剩余次数" + (5 - Integer.parseInt(errorCount))); - } - } else { - //登录成功删除错误登录次数 - redis.del(redisPasswordErrorKey); - return Result.success(user); - } - } -} diff --git a/java_project_template/springboot_api_simple/src/main/java/com/company/project/utils/ImageCodeUtil.java b/java_project_template/springboot_api_simple/src/main/java/com/company/project/utils/ImageCodeUtil.java deleted file mode 100644 index dd70fbc80d..0000000000 --- a/java_project_template/springboot_api_simple/src/main/java/com/company/project/utils/ImageCodeUtil.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.company.project.utils; - -import lombok.extern.slf4j.Slf4j; - -import javax.imageio.ImageIO; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import java.awt.*; -import java.awt.image.BufferedImage; -import java.util.Random; - -@Slf4j -public class ImageCodeUtil { - - - public static final String IMAGE_RANDOM_CODEKEY = "RANDOMVALIDATECODEKEY";//放到session中的key - private String randString = "0123456789";//随机产生只有数字的字符串 private String - //private String randString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生只有字母的字符串 - //private String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生数字与字母组合的字符串 - private int width = 95;// 图片宽 - private int height = 25;// 图片高 - private int lineSize = 40;// 干扰线数量 - private int stringNum = 4;// 随机产生字符数量 - - - private Random random = new Random(); - - /** - * 获得字体 - */ - private Font getFont() { - return new Font("Fixedsys", Font.CENTER_BASELINE, 18); - } - - /** - * 获得颜色 - */ - private Color getRandColor(int fc, int bc) { - if (fc > 255) - fc = 255; - if (bc > 255) - bc = 255; - int r = fc + random.nextInt(bc - fc - 16); - int g = fc + random.nextInt(bc - fc - 14); - int b = fc + random.nextInt(bc - fc - 18); - return new Color(r, g, b); - } - - /** - * 生成随机图片 - */ - public void getRandcode(HttpServletRequest request, HttpServletResponse response) { - HttpSession session = request.getSession(); - // BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类 - BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); - Graphics g = image.getGraphics();// 产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作 - g.fillRect(0, 0, width, height);//图片大小 - g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));//字体大小 - g.setColor(getRandColor(110, 133));//字体颜色 - // 绘制干扰线 - for (int i = 0; i <= lineSize; i++) { - drowLine(g); - } - // 绘制随机字符 - String randomString = ""; - for (int i = 1; i <= stringNum; i++) { - randomString = drowString(g, randomString, i); - } - log.info(randomString); - //将生成的随机字符串保存到session中 - session.removeAttribute(IMAGE_RANDOM_CODEKEY); - session.setAttribute(IMAGE_RANDOM_CODEKEY, randomString); - g.dispose(); - try { - // 将内存中的图片通过流动形式输出到客户端 - ImageIO.write(image, "JPEG", response.getOutputStream()); - } catch (Exception e) { - log.error("将内存中的图片通过流动形式输出到客户端失败>>>> ", e); - } - - } - - /** - * 绘制字符串 - */ - private String drowString(Graphics g, String randomString, int i) { - g.setFont(getFont()); - g.setColor(new Color(random.nextInt(101), random.nextInt(111), random - .nextInt(121))); - String rand = String.valueOf(getRandomString(random.nextInt(randString - .length()))); - randomString += rand; - g.translate(random.nextInt(3), random.nextInt(3)); - g.drawString(rand, 13 * i, 16); - return randomString; - } - - /** - * 绘制干扰线 - */ - private void drowLine(Graphics g) { - int x = random.nextInt(width); - int y = random.nextInt(height); - int xl = random.nextInt(13); - int yl = random.nextInt(15); - g.drawLine(x, y, x + xl, y + yl); - } - - /** - * 获取随机的字符 - */ - public String getRandomString(int num) { - return String.valueOf(randString.charAt(num)); - } -} \ No newline at end of file diff --git a/java_project_template/springboot_api_simple/src/main/java/com/company/project/utils/MD5Utils.java b/java_project_template/springboot_api_simple/src/main/java/com/company/project/utils/MD5Utils.java deleted file mode 100644 index c7a3dff75c..0000000000 --- a/java_project_template/springboot_api_simple/src/main/java/com/company/project/utils/MD5Utils.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.company.project.utils; - -import org.apache.commons.codec.digest.DigestUtils; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.StringUtils; - -public class MD5Utils { - - private static String salt = "springboot_api"; - - /** - * 加密字符串 - * @param password 要加密的明文 - * @param isAddSalt 是否加默认盐 - * @return 加密之后的结果 - */ - public static String Encrypt(String password, boolean isAddSalt){ - if (StringUtils.isNotEmpty(password)){ - if (isAddSalt){ - return DigestUtils.md5Hex(DigestUtils.md5(password + salt)); - } else { - return DigestUtils.md5Hex(DigestUtils.md5(password)); - } - } - return null; - } - - /** - * - * @param bytes - * @return - */ - public static String Encrypt(byte[] bytes){ - if (ArrayUtils.isNotEmpty(bytes)){ - return DigestUtils.md5Hex(DigestUtils.md5(bytes)); - } - return null; - } - - /** - * MD5加盐加密 - * @param password 要加密的明文 - * @param salt 盐 - * @return 加密之后的结果 - */ - public static String Encrypt(String password, String salt){ - if (StringUtils.isNotEmpty(password)){ - return DigestUtils.md5Hex(DigestUtils.md5(password + salt)); - } - return null; - } - - public static void main(String[] args){ - System.out.println(MD5Utils.Encrypt("admin", true)); - } -} diff --git a/java_project_template/springboot_api_simple/src/main/java/com/company/project/web/UserController.java b/java_project_template/springboot_api_simple/src/main/java/com/company/project/web/UserController.java deleted file mode 100644 index b238c2d363..0000000000 --- a/java_project_template/springboot_api_simple/src/main/java/com/company/project/web/UserController.java +++ /dev/null @@ -1,201 +0,0 @@ -package com.company.project.web; - -import com.alibaba.fastjson.JSONObject; -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.company.project.core.HttpSessionService; -import com.company.project.utils.MD5Utils; -import com.company.project.utils.ImageCodeUtil; -import com.jun.plugin.common.Result; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.web.bind.annotation.*; -import com.company.project.service.IUserService; -import com.company.project.model.User; -import io.swagger.annotations.ApiOperation; -import lombok.extern.slf4j.Slf4j; -import com.baomidou.mybatisplus.core.metadata.IPage; - -import javax.annotation.Resource; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import javax.validation.Valid; - -import org.springframework.web.bind.annotation.RestController; - -import java.util.HashMap; -import java.util.Map; - -/** - *

- * 前端控制器 - *

- * - * @author project - * @since 2020-01-08 - */ -@Slf4j -@RestController -@RequestMapping("/api/user") -public class UserController { - - @Resource - private IUserService userService; - @Autowired - private HttpSessionService httpSession; - - @Value("${redis.allowMultipleLogin}") - private Boolean allowMultipleLogin; - - @ApiOperation("登陆")//请求方式:POST,实际使用时屏蔽GET请求 - @RequestMapping(value = "/login", method = {RequestMethod.POST}) - public Result login(@RequestBody @Valid User userParam) { - - //校验密码,5次错误锁定账户 - Result result = userService.checkPassword(userParam); - if (!result.getSuccess()) { - return result; - } - //成功之后返回user - User user = (User)result.get(Result.DATA_TAG); - - //是否删除之前token, 此处控制是否支持多登陆端; - // true:允许多处登陆; false:只能单处登陆,顶掉之前登陆 - if (!allowMultipleLogin) { - httpSession.abortUserByUserId(user.getId()); - } - - //生成token - String token = httpSession.createTokenAndUser(user); - - Map resultMap = new HashMap<>(2); - resultMap.put("token", token); - resultMap.put("username", userParam.getUsername()); - return Result.success(resultMap); - } - - @ApiOperation("注册") - @PostMapping("/register") - public Result register(@RequestBody @Valid User user) { - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.eq("username", user.getUsername()); - User userO = userService.getOne(queryWrapper); - if (userO != null) { - return Result.fail("账号已存在"); - } - user.setPassword(MD5Utils.Encrypt(user.getPassword(), true)); - userService.save(user); - return Result.success(); - } - - @ApiOperation("修改密码") - @PostMapping("/updatePassword") - public Result updatePassword(@RequestBody JSONObject param) { - String oldPassword = param.getString("oldPassword"); - String newPassword = param.getString("newPassword"); - if (StringUtils.isBlank(oldPassword) || StringUtils.isBlank(newPassword)) { - return Result.fail("密码不能为空"); - } - //获取登陆信息 - JSONObject sessionInfo = httpSession.getCurrentSession(); - String userId = sessionInfo.getString("userId"); - - User user = userService.getById(userId); - if (user == null) { - return Result.fail("账号未找到"); - } - if (!MD5Utils.Encrypt(oldPassword, true).equals(user.getPassword())) { - return Result.fail("旧密码错误"); - } - User updateUser = new User(); - updateUser.setId(user.getId()); - updateUser.setPassword(MD5Utils.Encrypt(newPassword, true)); - userService.updateById(updateUser); - - //重置密码后删除原所有token - httpSession.abortAllUserByToken(); - return Result.success(); - } - - @ApiOperation("登出") - @GetMapping("/logout") - public Result logout() { - //退出删除token - httpSession.abortUserByToken(); - return Result.success(); - } - - @ApiOperation("校验token是否有效") - @GetMapping("/validateToken") - public Result validateToken() { - //拦截器拦截已判断,直接返回成功 - return Result.success(); - } - - @ApiOperation(value = "删除") - @PostMapping("delete/{id}") - public Result delete(@PathVariable("id") Long id) { - userService.removeById(id); - return Result.success(); - } - - @ApiOperation(value = "更新") - @PostMapping("update") - public Result update(@RequestBody User user) { - //密码不更新 - user.setPassword(null); - userService.updateById(user); - return Result.success(); - } - - @ApiOperation(value = "查询分页数据") - @ApiImplicitParams({ - @ApiImplicitParam(name = "currentPage", value = "页码"), - @ApiImplicitParam(name = "pageCount", value = "每页条数") - }) - @GetMapping("listByPage") - public Result findListByPage(@RequestParam(defaultValue = "1") Integer currentPage, - @RequestParam(defaultValue = "10") Integer pageCount) { - Page page = new Page(currentPage, pageCount); - IPage iPage = userService.page(page); - return Result.success(iPage); - } - - @ApiOperation(value = "id查询") - @GetMapping("getById/{id}") - public Result findById(@PathVariable Long id) { - return Result.success(userService.getById(id)); - } - - @ApiOperation(value = "生成验证码") - @GetMapping(value = "/getVerify") - public void getVerify(HttpServletRequest request, HttpServletResponse response) { - response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片 - response.setHeader("Pragma", "No-cache");//设置响应头信息,告诉浏览器不要缓存此内容 - response.setHeader("Cache-Control", "no-cache"); - response.setDateHeader("Expire", 0); - try { - ImageCodeUtil randomValidateCode = new ImageCodeUtil(); - randomValidateCode.getRandcode(request, response);//输出验证码图片方法 - } catch (Exception e) { - log.error("生成验证码失败"); - } - } - - @ApiOperation(value = "校验验证码") - @PostMapping(value = "/checkVerify") - public Result checkVerify(@RequestParam String imageCode, HttpSession session) { - //从session中获取随机数 - Object random = session.getAttribute(ImageCodeUtil.IMAGE_RANDOM_CODEKEY); - if (random != null && String.valueOf(random).equals(imageCode)) { - return Result.success(); - } - return Result.fail("校验失败"); - } - - -} diff --git a/java_project_template/springboot_api_simple/src/main/java/com/jun/plugin/common/Result.java b/java_project_template/springboot_api_simple/src/main/java/com/jun/plugin/common/Result.java deleted file mode 100644 index 1f4877bbb8..0000000000 --- a/java_project_template/springboot_api_simple/src/main/java/com/jun/plugin/common/Result.java +++ /dev/null @@ -1,189 +0,0 @@ -package com.jun.plugin.common; - -import com.jun.plugin.common.exception.code.BaseResponseCode; - -import java.util.HashMap; - -/** - * 返回对象 - * - * @author wujun - */ -public class Result extends HashMap -{ - private static final long serialVersionUID = 1L; - - /** 状态码 */ - public static final String CODE_TAG = "code"; - - /** 返回内容 */ - public static final String MSG_TAG = "msg"; - - /** 数据对象 */ - public static final String DATA_TAG = "data"; - - private Boolean success = true; - - public Boolean getSuccess() { - return success; - } - - public Result setSuccess(Boolean success) { - this.success = success; - return this; - } - - - - /** - * 初始化一个新创建的 AjaxResult 对象,使其表示一个空消息。 - */ - public Result() - { - } - - /** - * 初始化一个新创建的 AjaxResult 对象 - * - * @param code 状态码 - * @param msg 返回内容 - */ - public Result(int code, String msg) - { - super.put(CODE_TAG, code); - super.put(MSG_TAG, msg); - } - - /** - * 初始化一个新创建的 AjaxResult 对象 - * - * @param code 状态码 - * @param msg 返回内容 - * @param data 数据对象 - */ - public Result(int code, String msg, Object data) - { - super.put(CODE_TAG, code); - super.put(MSG_TAG, msg); - super.put(DATA_TAG, data); - } - - public static Result getResult(int i, String s) { - return Result.error(i,s); - } - - public static Result getResult(BaseResponseCode systemRedisBusy) { - return Result.error(systemRedisBusy.getCode(),systemRedisBusy.getMsg()); - } - - /** - * 方便链式调用 - * - * @param key - * @param value - * @return - */ - @Override - public Result put(String key, Object value) - { - super.put(key, value); - return this; - } - - /** - * 返回成功消息 - * - * @return 成功消息 - */ - public static Result success() - { - return Result.success("success"); - } - public static Result ok() - { - return Result.success("success"); - } - - /** - * 返回成功数据 - * - * @return 成功消息 - */ - public static Result ok(Object data) - { - return Result.success("success", data); - } - public static Result success(Object data) - { - return Result.success("success", data); - } - - /** - * 返回成功消息 - * - * @param msg 返回内容 - * @param data 数据对象 - * @return 成功消息 - */ - public static Result success(String msg, Object data) - { - return new Result(0, msg, data); - } - public static Result success(int code, String msg, Object data) - { - return new Result(code, msg, data); - } - - /** - * 返回错误消息 - * - * @return - */ - public static Result fail() - { - return Result.error("fail").setSuccess(false); - } - public static Result error() - { - return Result.error("fail").setSuccess(false); - } - - /** - * 返回错误消息 - * - * @param msg 返回内容 - * @return 警告消息 - */ - public static Result fail(String msg) - { - return Result.error(msg, null).setSuccess(false); - } - public static Result error(String msg) - { - return Result.error(msg, null).setSuccess(false); - } - - /** - * 返回错误消息 - * - * @param msg 返回内容 - * @param data 数据对象 - * @return 警告消息 - */ - public static Result error(String msg, Object data) - { - return new Result(500, msg, data).setSuccess(false); - } - - /** - * 返回错误消息 - * - * @param code 状态码 - * @param msg 返回内容 - * @return 警告消息 - */ - public static Result error(int code, String msg) - { - return new Result(code, msg, null).setSuccess(false); - } -} diff --git a/java_project_template/springboot_api_simple/src/main/java/com/jun/plugin/common/exception/BusinessException.java b/java_project_template/springboot_api_simple/src/main/java/com/jun/plugin/common/exception/BusinessException.java deleted file mode 100644 index f3499a76a0..0000000000 --- a/java_project_template/springboot_api_simple/src/main/java/com/jun/plugin/common/exception/BusinessException.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.jun.plugin.common.exception; - - -import com.jun.plugin.common.exception.code.BaseResponseCode; -import com.jun.plugin.common.exception.code.ResponseCodeInterface; - -/** - * BusinessException - * - * @author wujun - * @version V1.0 - * @date 2020年3月18日 - */ -public class BusinessException extends RuntimeException { - /** - * 异常编号 - */ - private final int messageCode; - - /** - * 对messageCode 异常信息进行补充说明 - */ - private final String detailMessage; - - public BusinessException(int messageCode, String message) { - super(message); - this.messageCode = messageCode; - this.detailMessage = message; - } - - public BusinessException(String message) { - super(message); - this.messageCode = BaseResponseCode.OPERATION_ERRO.getCode(); - this.detailMessage = message; - } - - /** - * 构造函数 - * - * @param code 异常码 - */ - public BusinessException(ResponseCodeInterface code) { - this(code.getCode(), code.getMsg()); - } - - public int getMessageCode() { - return messageCode; - } - - public String getDetailMessage() { - return detailMessage; - } -} diff --git a/java_project_template/springboot_api_simple/src/main/java/com/jun/plugin/common/exception/code/BaseResponseCode.java b/java_project_template/springboot_api_simple/src/main/java/com/jun/plugin/common/exception/code/BaseResponseCode.java deleted file mode 100644 index d6fb71ccfb..0000000000 --- a/java_project_template/springboot_api_simple/src/main/java/com/jun/plugin/common/exception/code/BaseResponseCode.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.jun.plugin.common.exception.code; - - -/** - * 错误码 - * - * @author wujun - * @version V1.0 - * @date 2020年3月18日 - */ -public enum BaseResponseCode implements ResponseCodeInterface { - /** - * 错误码 - */ - SUCCESS(0, "操作成功"), - SYSTEM_BUSY(500001, "系统繁忙,请稍候再试!"), - OPERATION_ERRO(500002, "操作失败"), - SYSTEM_REDIS_BUSY(500003, "REDIS服务器请求超时(超7S),请稍候再试!"), - - TOKEN_ERROR(401001, "登录凭证已过期,请重新登录"), - DATA_ERROR(401003, "传入数据异常"), - NOT_ACCOUNT(401004, "该用户不存在,请先注册"), - USER_LOCK(401005, "该用户已被锁定,请联系运营人员"), - PASSWORD_ERROR(401006, "用户名或密码错误"), - METHODARGUMENTNOTVALIDEXCEPTION(401007, "方法参数校验异常"), - UNAUTHORIZED_ERROR(401008, "权鉴校验不通过"), - ROLE_PERMISSION_RELATION(401009, "该菜单权限存在子集关联,不允许删除"), - OLD_PASSWORD_ERROR(401010, "旧密码不正确"), - NOT_PERMISSION_DELETED_DEPT(401011, "该组织机构下还关联着用户,不允许删除"), - OPERATION_MENU_PERMISSION_CATALOG_ERROR(401012, "操作后的菜单类型是目录,所属菜单必须为默认顶级菜单或者目录"), - OPERATION_MENU_PERMISSION_MENU_ERROR(401013, "操作后的菜单类型是菜单,所属菜单必须为目录类型"), - OPERATION_MENU_PERMISSION_BTN_ERROR(401013, "操作后的菜单类型是按钮,所属菜单必须为菜单类型"), - OPERATION_MENU_PERMISSION_URL_NOT_NULL(401015, "菜单权限的url不能为空"), - OPERATION_MENU_PERMISSION_URL_PERMS_NULL(401016, "菜单权限的标识符不能为空"), - - ; - - /** - * 错误码 - */ - private final int code; - /** - * 错误消息 - */ - private final String msg; - - BaseResponseCode(int code, String msg) { - this.code = code; - this.msg = msg; - } - - @Override - public int getCode() { - return code; - } - - @Override - public String getMsg() { - return msg; - } -} diff --git a/java_project_template/springboot_api_simple/src/main/java/com/jun/plugin/common/exception/code/ResponseCodeInterface.java b/java_project_template/springboot_api_simple/src/main/java/com/jun/plugin/common/exception/code/ResponseCodeInterface.java deleted file mode 100644 index e9463ba919..0000000000 --- a/java_project_template/springboot_api_simple/src/main/java/com/jun/plugin/common/exception/code/ResponseCodeInterface.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.jun.plugin.common.exception.code; - -/** - * ResponseCodeInterface - * - * @author wujun - * @version V1.0 - * @date 2020年3月18日 - */ -public interface ResponseCodeInterface { - /** - * 获取code - * - * @return code - */ - int getCode(); - - /** - * 获取信息 - * - * @return msg - */ - String getMsg(); -} diff --git a/java_project_template/springboot_api_simple/src/main/resources/application-dev.yml b/java_project_template/springboot_api_simple/src/main/resources/application-dev.yml deleted file mode 100644 index 1c9d811027..0000000000 --- a/java_project_template/springboot_api_simple/src/main/resources/application-dev.yml +++ /dev/null @@ -1,53 +0,0 @@ -# 开发环境配置 -spring: - datasource: - dynamic: - primary: master #设置默认的数据源或者数据源组,默认值即为master - datasource: - master: - username: root - password: - driver-class-name: com.mysql.cj.jdbc.Driver - url: jdbc:mysql://localhost:3306/db_test?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2b8 - slave_1: - username: root - password: 123456 - driver-class-name: com.mysql.cj.jdbc.Driver - url: jdbc:mysql://xx.xx.xx.xx:3307/dynamic?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2b8 - slave_2: - username: root - password: 123456 - driver-class-name: com.mysql.cj.jdbc.Driver - url: jdbc:mysql://xx.xx.xx.xx:3308/dynamic?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2b8 - #......省略 - #以上会配置一个默认库master,一个组slave下有两个子库slave_1,slave_2 - -redis: - key: - prefix: - userToken: "user:token:" - passwordError: "user:password:error:" - expire: - userToken: 604800 # 7天 7*24*3600 - passwordError: 3600 # 一个小时 - allowMultipleLogin: false # 允许多处登陆 - host: localhost # Redis服务器地址 - database: 0 # Redis数据库索引(默认为0) - port: 6379 # Redis服务器连接端口 - password: # Redis服务器连接密码(默认为空) - jedis: - pool: - max-active: 8 # 连接池最大连接数(使用负值表示没有限制) - max-wait: -1ms # 连接池最大阻塞等待时间(使用负值表示没有限制) - max-idle: 8 # 连接池中的最大空闲连接 - min-idle: 0 # 连接池中的最小空闲连接 - timeout: 3000ms # 连接超时时间(毫秒 - -mybatis-plus: - configuration: - log-impl: org.apache.ibatis.logging.stdout.StdOutImpl - mapper-locations: classpath:mapper/*.xml - global-config: - db-config: - logic-delete-value: 1 - logic-not-delete-value: 0 diff --git a/java_project_template/springboot_api_simple/src/main/resources/application-prod.yml b/java_project_template/springboot_api_simple/src/main/resources/application-prod.yml deleted file mode 100644 index 27cc9a1df0..0000000000 --- a/java_project_template/springboot_api_simple/src/main/resources/application-prod.yml +++ /dev/null @@ -1,4 +0,0 @@ -# 生产环境配置 - -knife4j: - production: true #生成环境禁用查看文档 \ No newline at end of file diff --git a/java_project_template/springboot_api_simple/src/main/resources/application-test.yml b/java_project_template/springboot_api_simple/src/main/resources/application-test.yml deleted file mode 100644 index 287da7b20e..0000000000 --- a/java_project_template/springboot_api_simple/src/main/resources/application-test.yml +++ /dev/null @@ -1 +0,0 @@ -# 测试环境配置 diff --git a/java_project_template/springboot_api_simple/src/main/resources/application.yml b/java_project_template/springboot_api_simple/src/main/resources/application.yml deleted file mode 100644 index facce6d372..0000000000 --- a/java_project_template/springboot_api_simple/src/main/resources/application.yml +++ /dev/null @@ -1,14 +0,0 @@ -spring: - profiles: - active: dev - mvc: - throw-exception-if-no-handler-found: true - resources: - add-mappings: false - application: - name: Springboot-api - jackson: - date-format: yyyy-MM-dd HH:mm:ss - time-zone: GMT+8 -server: - port: 8080 diff --git a/java_project_template/springboot_api_simple/src/main/resources/banner.txt b/java_project_template/springboot_api_simple/src/main/resources/banner.txt deleted file mode 100644 index 152e179398..0000000000 --- a/java_project_template/springboot_api_simple/src/main/resources/banner.txt +++ /dev/null @@ -1,22 +0,0 @@ -//////////////////////////////////////////////////////////////////// -// _ooOoo_ // -// o8888888o // -// 88" . "88 // -// (| ^_^ |) // -// O\ = /O // -// ____/`---'\____ // -// .' \\| |// `. // -// / \\||| : |||// \ // -// / _||||| -:- |||||- \ // -// | | \\\ - /// | | // -// | \_| ''\---/'' | | // -// \ .-\__ `-` ___/-. / // -// ___`. .' /--.--\ `. . ___ // -// ."" '< `.___\_<|>_/___.' >'"". // -// | | : `- \`.;`\ _ /`;.`/ - ` : | | // -// \ \ `-. \_ __\ /__ _/ .-` / / // -// ========`-.____`-.___\_____/___.-`____.-'======== // -// `=---=' // -// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // -// 佛祖保佑 永不宕机 永无BUG // -//////////////////////////////////////////////////////////////////// \ No newline at end of file diff --git a/java_project_template/springboot_api_simple/src/main/resources/mapper/UserMapper.xml b/java_project_template/springboot_api_simple/src/main/resources/mapper/UserMapper.xml deleted file mode 100644 index 190726401e..0000000000 --- a/java_project_template/springboot_api_simple/src/main/resources/mapper/UserMapper.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - id, username, password, nick_name, sex, create_date, create_user, update_date, update_user, del_flag - - - \ No newline at end of file diff --git a/java_project_template/springboot_api_simple/src/test/java/CodeGenerator.java b/java_project_template/springboot_api_simple/src/test/java/CodeGenerator.java deleted file mode 100644 index 98b1485b94..0000000000 --- a/java_project_template/springboot_api_simple/src/test/java/CodeGenerator.java +++ /dev/null @@ -1,25 +0,0 @@ -import com.baomidou.mybatisplus.core.toolkit.StringPool; -import com.baomidou.mybatisplus.generator.AutoGenerator; -import com.baomidou.mybatisplus.generator.config.*; -import com.baomidou.mybatisplus.generator.config.po.TableInfo; -import com.baomidou.mybatisplus.generator.config.rules.DateType; -import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; -import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; - -import java.util.ArrayList; -import java.util.List; - -// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中 -public class CodeGenerator { - - - //多个表逗号分隔 - static String tableName = "user"; - //逻辑删除字段名, 假如表没有逻辑删除字段,请忽视 - static String logicDeleteFieldName = "del_flag"; - - public static void main(String[] args) { - // 代码生成器 - } - -} \ No newline at end of file diff --git a/java_project_template/springboot_api_simple/src/test/java/com/company/project/Tester.java b/java_project_template/springboot_api_simple/src/test/java/com/company/project/Tester.java deleted file mode 100644 index 7dc34ff465..0000000000 --- a/java_project_template/springboot_api_simple/src/test/java/com/company/project/Tester.java +++ /dev/null @@ -1,22 +0,0 @@ -//package com.company.project; -// -//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(classes = Application.class) -//public class Tester { -// -// @Test -// public void test() { -// -// } -//} -// -// -// diff --git a/java_project_template/springboot_api_simple/src/test/resources/templates/controller.java.ftl b/java_project_template/springboot_api_simple/src/test/resources/templates/controller.java.ftl deleted file mode 100644 index a62f181707..0000000000 --- a/java_project_template/springboot_api_simple/src/test/resources/templates/controller.java.ftl +++ /dev/null @@ -1,94 +0,0 @@ -package ${package.Controller}; - -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.company.project.core.Result; -import com.company.project.core.ResultGenerator; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import org.springframework.web.bind.annotation.*; -import ${package.Service}.${table.serviceName}; -import ${package.Entity}.${entity}; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import lombok.extern.slf4j.Slf4j; -import com.baomidou.mybatisplus.core.metadata.IPage; - -import javax.annotation.Resource; -<#if restControllerStyle> -import org.springframework.web.bind.annotation.RestController; -<#else> -import org.springframework.stereotype.Controller; - -<#if superControllerClassPackage??> -import ${superControllerClassPackage}; - - -/** - *

- * ${table.comment!} 前端控制器 - *

- * - * @author ${author} - * @since ${date} - */ -<#if restControllerStyle> -@Api(tags = {"${table.comment!}"}) -@Slf4j -@RestController -<#else> -@Controller - -@RequestMapping("<#if package.ModuleName??>/${package.ModuleName}/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}") -<#if kotlin> -class ${table.controllerName}<#if superControllerClass??>:${superControllerClass}() -<#else> -<#if superControllerClass??>public class ${table.controllerName} extends ${superControllerClass}{ -<#else>public class ${table.controllerName} { - - - @Resource - private ${table.serviceName} ${(table.serviceName?substring(1))?uncap_first}; - - - @ApiOperation(value = "新增${table.comment!}") - @PostMapping("add") - public Result add(@RequestBody ${entity} ${entity?uncap_first}){ - ${(table.serviceName?substring(1))?uncap_first}.save(${entity?uncap_first}); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "删除${table.comment!}") - @PostMapping("delete/{id}") - public Result delete(@PathVariable("id") Long id){ - ${(table.serviceName?substring(1))?uncap_first}.removeById(id); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "更新${table.comment!}") - @PostMapping("update") - public Result update(@RequestBody ${entity} ${entity?uncap_first}){ - ${(table.serviceName?substring(1))?uncap_first}.updateById(${entity?uncap_first}); - return ResultGenerator.genSuccessResult(); - } - - @ApiOperation(value = "查询${table.comment!}分页数据") - @ApiImplicitParams({ - @ApiImplicitParam(name = "currentPage", value = "页码"), - @ApiImplicitParam(name = "pageCount", value = "每页条数") - }) - @GetMapping("listByPage") - public Result findListByPage(@RequestParam Integer currentPage, - @RequestParam Integer pageCount){ - Page page = new Page(currentPage, pageCount); - IPage<${entity}> iPage = ${(table.serviceName?substring(1))?uncap_first}.page(page); - return ResultGenerator.genSuccessResult(iPage); - } - - @ApiOperation(value = "id查询${table.comment!}") - @GetMapping("getById/{id}") - public Result findById(@PathVariable Long id){ - return ResultGenerator.genSuccessResult(${(table.serviceName?substring(1))?uncap_first}.getById(id)); - } - -} - \ No newline at end of file diff --git a/java_project_template/springboot_api_simple/src/test/resources/user.sql b/java_project_template/springboot_api_simple/src/test/resources/user.sql deleted file mode 100644 index 51c44dc612..0000000000 --- a/java_project_template/springboot_api_simple/src/test/resources/user.sql +++ /dev/null @@ -1,52 +0,0 @@ -/* - Navicat Premium Data Transfer - - Source Server : localhost - Source Server Type : MySQL - Source Server Version : 50529 - Source Host : localhost:3306 - Source Schema : project - - Target Server Type : MySQL - Target Server Version : 50529 - File Encoding : 65001 - - Date: 08/01/2020 15:53:02 -*/ - -SET NAMES utf8mb4; -SET FOREIGN_KEY_CHECKS = 0; - --- ---------------------------- --- Table structure for t_user --- ---------------------------- -DROP TABLE IF EXISTS `t_user`; -CREATE TABLE `t_user` ( - `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键', - `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名', - `password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码', - `nick_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '昵称', - `sex` int(1) NULL DEFAULT NULL COMMENT '性别', - `create_date` datetime NULL DEFAULT NULL COMMENT '创建时间', - `create_user` int(11) NULL DEFAULT NULL COMMENT '创建人', - `update_date` datetime NULL DEFAULT NULL COMMENT '修改时间', - `update_user` int(11) NULL DEFAULT NULL COMMENT '修改人', - `del_flag` int(1) NULL DEFAULT 0 COMMENT '删除标志0未删 1删除', - PRIMARY KEY (`id`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 11 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact; - --- ---------------------------- --- Records of t_user --- ---------------------------- -INSERT INTO `t_user` VALUES (1, 'admin', '9dc818b4bca3baa7d230fbf96c919638', '测试', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `t_user` VALUES (2, '2@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '测试-2', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `t_user` VALUES (3, '3@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '测试-3', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `t_user` VALUES (4, '4@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '测试-4', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `t_user` VALUES (5, '5@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '测试-5', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `t_user` VALUES (6, '6@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '测试-6', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `t_user` VALUES (7, '7@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '测试-7', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `t_user` VALUES (8, '8@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '测试-8', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `t_user` VALUES (9, '9@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '测试-9', 1, NULL, NULL, NULL, NULL, 0); -INSERT INTO `t_user` VALUES (10, '10@qq.com', '9dc818b4bca3baa7d230fbf96c919638', '测试-10', 1, NULL, NULL, NULL, NULL, 0); - -SET FOREIGN_KEY_CHECKS = 1; diff --git a/java_project_template/springboot_jfinal_activerecord/.gitignore b/java_project_template/springboot_jfinal_activerecord/.gitignore deleted file mode 100644 index cf3b11dd1f..0000000000 --- a/java_project_template/springboot_jfinal_activerecord/.gitignore +++ /dev/null @@ -1,35 +0,0 @@ -# maven ignore -target/ -*.jar -*.war -*.zip -*.tar -*.tar.gz - -build/ - -# eclipse ignore -.settings/ -.project -.classpath - -# idea ignore -.idea/ -*.ipr -*.iml -*.iws - -# temp ignore -logs/ -*.log -*.cache -*.diff -*.patch -*.tmp -*.java~ -*.properties~ -*.xml~ - -# system ignore -.DS_Store -Thumbs.db diff --git a/java_project_template/springboot_jfinal_activerecord/README.md b/java_project_template/springboot_jfinal_activerecord/README.md deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/java_project_template/springboot_jfinal_activerecord/pom.xml b/java_project_template/springboot_jfinal_activerecord/pom.xml deleted file mode 100644 index 5f10f64c77..0000000000 --- a/java_project_template/springboot_jfinal_activerecord/pom.xml +++ /dev/null @@ -1,114 +0,0 @@ - - - - 4.0.0 - - com.lxhc - springboot_jfinal_activerecord - 1.0-SNAPSHOT - - spring_jfinal_activerecord - - - - org.springframework.boot - spring-boot-starter-parent - 2.2.2.RELEASE - - - - - UTF-8 - 1.8 - 1.8 - 2.3.0.RELEASE - 4.8 - 5.1.20 - 1.1.22 - - - - - junit - junit - 4.12 - test - - - com.jfinal - activerecord - ${jfinal.activerecord.version} - - - org.springframework.boot - spring-boot-dependencies - ${springboot.version} - pom - import - - - org.springframework.boot - spring-boot-starter-web - ${springboot.version} - - - - org.springframework.boot - spring-boot-starter-tomcat - - - - org.springframework.boot - spring-boot-starter-logging - - - - - - org.springframework.boot - spring-boot-starter-jdbc - ${springboot.version} - - - - org.springframework.boot - spring-boot-starter-logging - - - - - org.springframework.boot - spring-boot-starter-undertow - ${springboot.version} - - - org.springframework.boot - spring-boot-starter-log4j2 - ${springboot.version} - - - org.springframework.boot - spring-boot-starter-test - ${springboot.version} - test - - - org.junit.vintage - junit-vintage-engine - - - - - mysql - mysql-connector-java - ${mysql.version} - - - com.alibaba - druid - ${druid.version} - - - - diff --git a/java_project_template/springboot_jfinal_activerecord/sql/emp.sql b/java_project_template/springboot_jfinal_activerecord/sql/emp.sql deleted file mode 100644 index c44d2908c5..0000000000 --- a/java_project_template/springboot_jfinal_activerecord/sql/emp.sql +++ /dev/null @@ -1,25 +0,0 @@ -CREATE TABLE `emp` ( - `id` int(11) NOT NULL, - `name` varchar(10) NOT NULL, - `age` int(11) DEFAULT 18 -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - -ALTER TABLE `emp` - ADD PRIMARY KEY (`id`); - -ALTER TABLE `emp` - MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -COMMIT; - -CREATE TABLE `emp_balance` ( - `id` int(11) NOT NULL, - `emp_id` int(11) NOT NULL, - `balance` int(11) DEFAULT 0 -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - -ALTER TABLE `emp_balance` - ADD PRIMARY KEY (`id`); - -ALTER TABLE `emp_balance` - MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -COMMIT; \ No newline at end of file diff --git a/java_project_template/springboot_jfinal_activerecord/src/main/java/com/lxhc/Application.java b/java_project_template/springboot_jfinal_activerecord/src/main/java/com/lxhc/Application.java deleted file mode 100644 index 252fc8c23f..0000000000 --- a/java_project_template/springboot_jfinal_activerecord/src/main/java/com/lxhc/Application.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.lxhc; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -/** - * Created on 2020/5/19. - * - * @author 拎小壶冲 - */ -@SpringBootApplication -public class Application { - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } -} diff --git a/java_project_template/springboot_jfinal_activerecord/src/main/java/com/lxhc/config/JfinalActiveRecordConfig.java b/java_project_template/springboot_jfinal_activerecord/src/main/java/com/lxhc/config/JfinalActiveRecordConfig.java deleted file mode 100644 index 37185aa95f..0000000000 --- a/java_project_template/springboot_jfinal_activerecord/src/main/java/com/lxhc/config/JfinalActiveRecordConfig.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.lxhc.config; - -import com.alibaba.druid.pool.DruidDataSource; -import com.jfinal.plugin.activerecord.ActiveRecordPlugin; -import com.lxhc.model.Emp; -import com.lxhc.model.EmpBalance; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.jdbc.datasource.DataSourceTransactionManager; -import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; - -/** - * Created on 2020/5/19. - * - * @author 拎小壶冲 - */ -@Configuration -public class JfinalActiveRecordConfig { - /** - * 主数据源名称 - */ - private static final String MAIN_DATA_SOURCE_CONFIG = "main"; - - /** - * 业务数据源名称 - */ - private static final String BIZ_DATA_SOURCE_CONFIG = "biz"; - - @Bean - @ConfigurationProperties("spring.datasource.main") - public DruidDataSource masterDataSource(){ - return new DruidDataSource(); - } - - @Bean - @ConfigurationProperties("spring.datasource.biz") - public DruidDataSource bizDataSource(){ - return new DruidDataSource(); - } - - /** - * 主数据源 - * @return - */ - @Bean - public ActiveRecordPlugin initMainActiveRecord() { - ActiveRecordPlugin arp = new ActiveRecordPlugin(MAIN_DATA_SOURCE_CONFIG, masterTransactionAwareDataSourceProxy()); - - arp.addMapping("emp", Emp.class); - arp.addMapping("emp_balance", EmpBalance.class); - - arp.start(); - - return arp; - } - - /** - * 业务数据源 - * @return - */ - @Bean - public ActiveRecordPlugin initBizActiveRecord() { - ActiveRecordPlugin arp = new ActiveRecordPlugin(BIZ_DATA_SOURCE_CONFIG, bizTransactionAwareDataSourceProxy()); - -// arp2.addMapping("emp", Emp.class); - - arp.start(); - - return arp; - } - - /** - * 设置数据源代理 - */ - @Bean - public TransactionAwareDataSourceProxy masterTransactionAwareDataSourceProxy() { - TransactionAwareDataSourceProxy transactionAwareDataSourceProxy = new TransactionAwareDataSourceProxy(); - transactionAwareDataSourceProxy.setTargetDataSource(masterDataSource()); - return transactionAwareDataSourceProxy; - } - - @Bean - public TransactionAwareDataSourceProxy bizTransactionAwareDataSourceProxy() { - TransactionAwareDataSourceProxy transactionAwareDataSourceProxy = new TransactionAwareDataSourceProxy(); - transactionAwareDataSourceProxy.setTargetDataSource(bizDataSource()); - return transactionAwareDataSourceProxy; - } - - /** - * 设置事务管理 - */ - @Bean(name="mainDataSourceTransactionManager") - public DataSourceTransactionManager masterDataSourceTransactionManager() { - DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(); - dataSourceTransactionManager.setDataSource(masterTransactionAwareDataSourceProxy()); - return dataSourceTransactionManager; - } - - @Bean(name="bizDataSourceTransactionManager") - public DataSourceTransactionManager bizDataSourceTransactionManager() { - DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(); - dataSourceTransactionManager.setDataSource(bizTransactionAwareDataSourceProxy()); - return dataSourceTransactionManager; - } -} diff --git a/java_project_template/springboot_jfinal_activerecord/src/main/java/com/lxhc/model/Emp.java b/java_project_template/springboot_jfinal_activerecord/src/main/java/com/lxhc/model/Emp.java deleted file mode 100644 index 0e84d5d0a5..0000000000 --- a/java_project_template/springboot_jfinal_activerecord/src/main/java/com/lxhc/model/Emp.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.lxhc.model; - -import com.jfinal.plugin.activerecord.Model; - -/** - * Created on 2020/5/19. - * - * @author 拎小壶冲 - */ -public class Emp extends Model { - public static final Emp dao = new Emp().dao(); -} diff --git a/java_project_template/springboot_jfinal_activerecord/src/main/java/com/lxhc/model/EmpBalance.java b/java_project_template/springboot_jfinal_activerecord/src/main/java/com/lxhc/model/EmpBalance.java deleted file mode 100644 index 72ffbca1a6..0000000000 --- a/java_project_template/springboot_jfinal_activerecord/src/main/java/com/lxhc/model/EmpBalance.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.lxhc.model; - -import com.jfinal.plugin.activerecord.Model; - -/** - * Created on 2020/5/21. - * - * @author 拎小壶冲 - */ -public class EmpBalance extends Model { - public static final EmpBalance dao = new EmpBalance().dao(); -} diff --git a/java_project_template/springboot_jfinal_activerecord/src/main/java/com/lxhc/service/EmpBalanceService.java b/java_project_template/springboot_jfinal_activerecord/src/main/java/com/lxhc/service/EmpBalanceService.java deleted file mode 100644 index 728c124213..0000000000 --- a/java_project_template/springboot_jfinal_activerecord/src/main/java/com/lxhc/service/EmpBalanceService.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.lxhc.service; - -import com.lxhc.model.Emp; -import com.lxhc.model.EmpBalance; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -/** - * Created on 2020/5/21. - * - * @author 拎小壶冲 - */ -@Service -public class EmpBalanceService { - - @Transactional(transactionManager="mainDataSourceTransactionManager", rollbackFor = Exception.class) - public void addBalance() { - // 这个应该不能保存进表中才对 - new EmpBalance().set("emp_id", 1) - .set("balance", 10).save(); - - Emp emp = Emp.dao.findById(1); - - // 这里故意写错,以测试实务 - emp.set("name", "超出长度的字符串用于测试错误").update(); - } -} diff --git a/java_project_template/springboot_jfinal_activerecord/src/main/resources/application.yml b/java_project_template/springboot_jfinal_activerecord/src/main/resources/application.yml deleted file mode 100644 index ef462f826d..0000000000 --- a/java_project_template/springboot_jfinal_activerecord/src/main/resources/application.yml +++ /dev/null @@ -1,13 +0,0 @@ -spring: - # 数据源配置 - datasource: - main: #主数据源 - driverClassName: com.mysql.jdbc.Driver - url: jdbc:mysql://localhost:3306/db_test - username: root - password: - biz: #业务数据源 - driverClassName: com.mysql.jdbc.Driver - url: jdbc:mysql://localhost:3306/test - username: root - password: \ No newline at end of file diff --git a/java_project_template/springboot_jfinal_activerecord/src/main/resources/log4j2.xml b/java_project_template/springboot_jfinal_activerecord/src/main/resources/log4j2.xml deleted file mode 100644 index 12510db9ff..0000000000 --- a/java_project_template/springboot_jfinal_activerecord/src/main/resources/log4j2.xml +++ /dev/null @@ -1,66 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/java_project_template/springboot_jfinal_activerecord/src/test/java/com/lxhc/model/EmpTest.java b/java_project_template/springboot_jfinal_activerecord/src/test/java/com/lxhc/model/EmpTest.java deleted file mode 100644 index 72891add45..0000000000 --- a/java_project_template/springboot_jfinal_activerecord/src/test/java/com/lxhc/model/EmpTest.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.lxhc.model; - -import com.jfinal.plugin.activerecord.Db; -import com.jfinal.plugin.activerecord.Record; -import com.lxhc.Application; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -/** - * Created on 2020/5/19. - * - * @author 拎小壶冲 - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -public class EmpTest { - - @Test - public void masterEmpTest() { - Emp emp = Emp.dao.findById(1); - System.out.println(emp.getStr("name")); - - Record emp2 = Db.use("biz").findFirst("select * from emp where id = 1"); - System.out.println(emp2.getStr("name")); - - Emp emp3 = new Emp().use("biz").findById(1); - System.out.println(emp3.getStr("name")); - } -} diff --git a/java_project_template/springboot_jfinal_activerecord/src/test/java/com/lxhc/service/EmpBalanceServiceTest.java b/java_project_template/springboot_jfinal_activerecord/src/test/java/com/lxhc/service/EmpBalanceServiceTest.java deleted file mode 100644 index adcb51e7ef..0000000000 --- a/java_project_template/springboot_jfinal_activerecord/src/test/java/com/lxhc/service/EmpBalanceServiceTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.lxhc.service; - -import com.lxhc.Application; -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; - -/** - * Created on 2020/5/21. - * - * @author 拎小壶冲 - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -public class EmpBalanceServiceTest { - - @Autowired - private EmpBalanceService empBalanceService; - - @Test - public void addBalanceTest() { - empBalanceService.addBalance(); - } -} diff --git a/jun_ajax/README.md b/jun_ajax/README.md new file mode 100644 index 0000000000..5101ffd28d --- /dev/null +++ b/jun_ajax/README.md @@ -0,0 +1 @@ +Ajax,XMLHttpRequest+Servlet的Ajax实现 \ No newline at end of file diff --git a/jun_ajax/pom.xml b/jun_ajax/pom.xml new file mode 100644 index 0000000000..c2a946ec50 --- /dev/null +++ b/jun_ajax/pom.xml @@ -0,0 +1,53 @@ + + 4.0.0 + + com.jun.plugin + jun_plugin + 1.0 + + jun_ajax + + + UTF-8 + + + + + + + org.activiti + activiti-engine + 5.19.0.2 + + + + org.activiti + activiti-spring + 5.19.0.2 + + + + org.activiti + activiti-bpmn-model + 5.19.0.2 + + + + mysql + mysql-connector-java + 5.1.38 + + + + + junit + junit + 4.11 + + + + + + + diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/java/com/jun/plugin/ajax/servlet/LoadServlet.java b/jun_ajax/src/main/java/com/jun/plugin/ajax/servlet/LoadServlet.java similarity index 100% rename from jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/java/com/jun/plugin/ajax/servlet/LoadServlet.java rename to jun_ajax/src/main/java/com/jun/plugin/ajax/servlet/LoadServlet.java diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/java/com/jun/plugin/ajax/servlet/RegisterServlet.java b/jun_ajax/src/main/java/com/jun/plugin/ajax/servlet/RegisterServlet.java similarity index 100% rename from jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/java/com/jun/plugin/ajax/servlet/RegisterServlet.java rename to jun_ajax/src/main/java/com/jun/plugin/ajax/servlet/RegisterServlet.java diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/java/com/jun/plugin/ajax/servlet/TestServlet.java b/jun_ajax/src/main/java/com/jun/plugin/ajax/servlet/TestServlet.java similarity index 100% rename from jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/java/com/jun/plugin/ajax/servlet/TestServlet.java rename to jun_ajax/src/main/java/com/jun/plugin/ajax/servlet/TestServlet.java diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/java/com/jun/plugin/ajax/servlet/XmlFileServlet.java b/jun_ajax/src/main/java/com/jun/plugin/ajax/servlet/XmlFileServlet.java similarity index 100% rename from jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/java/com/jun/plugin/ajax/servlet/XmlFileServlet.java rename to jun_ajax/src/main/java/com/jun/plugin/ajax/servlet/XmlFileServlet.java diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/01_testget/test.js b/jun_ajax/src/main/webapp/01_testget/test.js similarity index 100% rename from jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/01_testget/test.js rename to jun_ajax/src/main/webapp/01_testget/test.js diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/01_testget/testget.jsp b/jun_ajax/src/main/webapp/01_testget/testget.jsp similarity index 100% rename from jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/01_testget/testget.jsp rename to jun_ajax/src/main/webapp/01_testget/testget.jsp diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/02_testpost/test.js b/jun_ajax/src/main/webapp/02_testpost/test.js similarity index 100% rename from jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/02_testpost/test.js rename to jun_ajax/src/main/webapp/02_testpost/test.js diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/02_testpost/testpost.jsp b/jun_ajax/src/main/webapp/02_testpost/testpost.jsp similarity index 100% rename from jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/02_testpost/testpost.jsp rename to jun_ajax/src/main/webapp/02_testpost/testpost.jsp diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/03_load/image/ajax-loading-gif1.jpg b/jun_ajax/src/main/webapp/03_load/image/ajax-loading-gif1.jpg similarity index 100% rename from jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/03_load/image/ajax-loading-gif1.jpg rename to jun_ajax/src/main/webapp/03_load/image/ajax-loading-gif1.jpg diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/03_load/image/gif-loading.gif b/jun_ajax/src/main/webapp/03_load/image/gif-loading.gif similarity index 100% rename from jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/03_load/image/gif-loading.gif rename to jun_ajax/src/main/webapp/03_load/image/gif-loading.gif diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/03_load/image/loading-gif-animation.gif b/jun_ajax/src/main/webapp/03_load/image/loading-gif-animation.gif similarity index 100% rename from jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/03_load/image/loading-gif-animation.gif rename to jun_ajax/src/main/webapp/03_load/image/loading-gif-animation.gif diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/03_load/image/loading.gif b/jun_ajax/src/main/webapp/03_load/image/loading.gif similarity index 100% rename from jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/03_load/image/loading.gif rename to jun_ajax/src/main/webapp/03_load/image/loading.gif diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/03_load/image/loading1.gif b/jun_ajax/src/main/webapp/03_load/image/loading1.gif similarity index 100% rename from jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/03_load/image/loading1.gif rename to jun_ajax/src/main/webapp/03_load/image/loading1.gif diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/03_load/image/loading3.gif b/jun_ajax/src/main/webapp/03_load/image/loading3.gif similarity index 100% rename from jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/03_load/image/loading3.gif rename to jun_ajax/src/main/webapp/03_load/image/loading3.gif diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/03_load/image/loading33.gif b/jun_ajax/src/main/webapp/03_load/image/loading33.gif similarity index 100% rename from jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/03_load/image/loading33.gif rename to jun_ajax/src/main/webapp/03_load/image/loading33.gif diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/03_load/image/loading_.gif b/jun_ajax/src/main/webapp/03_load/image/loading_.gif similarity index 100% rename from jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/03_load/image/loading_.gif rename to jun_ajax/src/main/webapp/03_load/image/loading_.gif diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/03_load/load.js b/jun_ajax/src/main/webapp/03_load/load.js similarity index 100% rename from jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/03_load/load.js rename to jun_ajax/src/main/webapp/03_load/load.js diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/03_load/loading33.gif b/jun_ajax/src/main/webapp/03_load/loading33.gif similarity index 100% rename from jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/03_load/loading33.gif rename to jun_ajax/src/main/webapp/03_load/loading33.gif diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/03_load/testload.jsp b/jun_ajax/src/main/webapp/03_load/testload.jsp similarity index 100% rename from jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/03_load/testload.jsp rename to jun_ajax/src/main/webapp/03_load/testload.jsp diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/04_register/register.js b/jun_ajax/src/main/webapp/04_register/register.js similarity index 100% rename from jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/04_register/register.js rename to jun_ajax/src/main/webapp/04_register/register.js diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/04_register/register.jsp b/jun_ajax/src/main/webapp/04_register/register.jsp similarity index 100% rename from jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/04_register/register.jsp rename to jun_ajax/src/main/webapp/04_register/register.jsp diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/05_xmlfile/xmFile.js b/jun_ajax/src/main/webapp/05_xmlfile/xmFile.js similarity index 100% rename from jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/05_xmlfile/xmFile.js rename to jun_ajax/src/main/webapp/05_xmlfile/xmFile.js diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/05_xmlfile/xmlFile.jsp b/jun_ajax/src/main/webapp/05_xmlfile/xmlFile.jsp similarity index 100% rename from jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/05_xmlfile/xmlFile.jsp rename to jun_ajax/src/main/webapp/05_xmlfile/xmlFile.jsp diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/06_json/json01.html b/jun_ajax/src/main/webapp/06_json/json01.html similarity index 100% rename from jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/06_json/json01.html rename to jun_ajax/src/main/webapp/06_json/json01.html diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/06_json/json02.html b/jun_ajax/src/main/webapp/06_json/json02.html similarity index 100% rename from jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/06_json/json02.html rename to jun_ajax/src/main/webapp/06_json/json02.html diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/06_json/json03.html b/jun_ajax/src/main/webapp/06_json/json03.html similarity index 100% rename from jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/06_json/json03.html rename to jun_ajax/src/main/webapp/06_json/json03.html diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/06_json/json04.html b/jun_ajax/src/main/webapp/06_json/json04.html similarity index 100% rename from jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/06_json/json04.html rename to jun_ajax/src/main/webapp/06_json/json04.html diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/06_json/json05.html b/jun_ajax/src/main/webapp/06_json/json05.html similarity index 100% rename from jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/06_json/json05.html rename to jun_ajax/src/main/webapp/06_json/json05.html diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/META-INF/MANIFEST.MF b/jun_ajax/src/main/webapp/META-INF/MANIFEST.MF similarity index 100% rename from jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/META-INF/MANIFEST.MF rename to jun_ajax/src/main/webapp/META-INF/MANIFEST.MF diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/WEB-INF/web.xml b/jun_ajax/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from jun_java_plugins/jun_webservlet/doc/jun_ajax/src/main/webapp/WEB-INF/web.xml rename to jun_ajax/src/main/webapp/WEB-INF/web.xml diff --git a/jun_algorithm/.gitignore b/jun_algorithm/.gitignore new file mode 100644 index 0000000000..20dec8ae7d --- /dev/null +++ b/jun_algorithm/.gitignore @@ -0,0 +1,7 @@ +/.idea +/target +algorithm.iml +/.settings +*.iml +.classpath +.project \ No newline at end of file diff --git a/jun_algorithm/README.md b/jun_algorithm/README.md new file mode 100644 index 0000000000..d4a88b5a70 --- /dev/null +++ b/jun_algorithm/README.md @@ -0,0 +1,7 @@ +## jun_algorithm,常用数据结构及算法 + +1. 八大排序 二分查找 +2. 实现自己的List和ArrayList +3. 二叉树遍历算法(递归 & 非递归)AVLTree +4. 一致性Hash算法 +5. 其他 \ No newline at end of file diff --git "a/jun_algorithm/doc/cpp/array/\346\225\260\347\273\204\344\270\255\347\232\204\351\200\206\345\272\217\345\257\271\357\274\210\345\275\222\345\271\266\346\200\235\346\203\263\357\274\211.cpp" "b/jun_algorithm/doc/cpp/array/\346\225\260\347\273\204\344\270\255\347\232\204\351\200\206\345\272\217\345\257\271\357\274\210\345\275\222\345\271\266\346\200\235\346\203\263\357\274\211.cpp" new file mode 100644 index 0000000000..1c326060e3 --- /dev/null +++ "b/jun_algorithm/doc/cpp/array/\346\225\260\347\273\204\344\270\255\347\232\204\351\200\206\345\272\217\345\257\271\357\274\210\345\275\222\345\271\266\346\200\235\346\203\263\357\274\211.cpp" @@ -0,0 +1,64 @@ +#include +#include +#include + +using namespace std; + +unsigned int CountInversions(vector& a); +unsigned int MergeSortCount(vector& a,int left,int right,vector& temp); +unsigned int MergeCount(vector& a,int left,int mid,int right,vector& temp); + +int main() +{ + int array[]={4,2,10,3,5,7}; + vector a(array,array+sizeof(array)/sizeof(int)); + unsigned int result = CountInversions(a); + cout <& a,int left,int mid,int right,vector& temp) +{ + int i = left; + int j= mid+1; + int k = left; + int count = 0; + //ʼԵĸ + while( i<= mid && j<=right) + { + if(a[i]<= a[j]) + temp[k++] = a[i++]; + else + { + temp[k++]=a[j++]; + count+= mid-i+1; + } + } + + while(i<=mid) temp[k++]= a[i++]; + while(j<= right) temp[k++] = a[j++]; + + for(i=left;i<=right;i++) + a[i]= temp[i]; + return count; +} + +unsigned int MergeSortCount(vector& a,int left,int right,vector& temp) +{ + if(left >= right) return 0; + + int mid = (left+right)/2; + unsigned int Inverleft = MergeSortCount(a,left,mid,temp); + unsigned int Inverright = MergeSortCount(a,mid+1,right,temp); + unsigned int InverSum = MergeCount(a,left,mid,right,temp); + + return Inverleft+Inverright+InverSum; +} + +unsigned int CountInversions(vector& a) +{ + int n= a.size(); + vector temp(a.begin(),a.end()); + unsigned int ans = MergeSortCount(a,0,n-1,temp); + return ans; +} diff --git "a/jun_algorithm/doc/cpp/array/\347\211\271\346\256\212\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276\357\274\210\347\273\217\345\205\270\357\274\211.cpp" "b/jun_algorithm/doc/cpp/array/\347\211\271\346\256\212\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276\357\274\210\347\273\217\345\205\270\357\274\211.cpp" new file mode 100644 index 0000000000..46f411b197 --- /dev/null +++ "b/jun_algorithm/doc/cpp/array/\347\211\271\346\256\212\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276\357\274\210\347\273\217\345\205\270\357\274\211.cpp" @@ -0,0 +1,97 @@ +#include +#include +using namespace std; + +/* +һֻһһ dz +ҵһε +*/ + +//е õĽҪҵ +int SingleNumber(vector& vec) +{ + if(vec.size()<=0) + return 0; + int i; + int value = vec[0]; + for(i=1;i& a,int& pN1,int& pN2) +{ + int i,j,temp; + + // + temp =0; + for(i=0;i> j)&1) ==1) + break; + + //jλΪ1˵ڵjλDzͬ з + pN1 =0; + pN2 =0; + for(i=0;i> j )&1) ==0) + pN1 ^= a[i]; + else + pN2 ^= a[i]; + +} + +/* +һֻһһ dz ҳ +*/ + +//ͬλж + +int SingleNumberIII(vector& vec) +{ + int i,j; + int low=0,high=vec.size()-1; + int bit =1; + int flag =0; + + //ͨijһλֵΪ֣һְ˴ҵ һֲ + while(low <= high) + { + if(low == high) + return vec[low]; + i = low-1; + for(j = low;j<= high;j++) + { + if((vec[j]&bit) == 0) + { + i++; + swap(vec[i],vec[j]); + } + } + if(i >= low) + { + if((i-low+1)%3 == 0) + low = i+1; + else + high =i; + } + bit = bit<<1; + } + return 0; +} +int main() +{ + int array[]={12,23,12,45,56,45,23,78,78,78,12,23,45}; + vector vec(array,array+sizeof(array)/sizeof(int)); + int fir,sec; + cout< +#include +#include +#include + +using namespace std; + +//һеĵKԪ + +int Find_K(int a[],int low,int high,int k) +{ + if(k<=0) + return -1; + if(k>high-low+1) + return -1; + //ѡһ֧ + int pivot = low+rand()%(high-low+1); + swap(a[low],a[pivot]); + int m = low; + int count = 1; + + // ÿһ ѽϴķŵ + for(int i=low+1;i<=high;i++) + { + if(a[i] > a[low]) + { + swap(a[++m],a[i]); + count++; //ȹؼĸΪcount+1 + } + } + swap(a[m],a[low]);// ؼֵķֽ + if(count > k) + return Find_K(a,low,m-1,k); + else if(count < k) + return Find_K(a,m+1,high,k-count); + else + return m; +} + +//СK +void FindMinTopK(vector& vec,int k) +{ + vector heap(vec.begin(),vec.begin()+k); + make_heap(heap.begin(),heap.end()); + int i; + + //ʼʣ + for(i =k;i vec(array,array+sizeof(array)/sizeof(int)); + FindMinTopK(vec,4); + return 0; +} diff --git "a/jun_algorithm/doc/cpp/array/\350\256\276\347\275\256\344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\345\205\203\347\264\240\345\200\274.cpp" "b/jun_algorithm/doc/cpp/array/\350\256\276\347\275\256\344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\345\205\203\347\264\240\345\200\274.cpp" new file mode 100644 index 0000000000..c4ba04a41a --- /dev/null +++ "b/jun_algorithm/doc/cpp/array/\350\256\276\347\275\256\344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\345\205\203\347\264\240\345\200\274.cpp" @@ -0,0 +1,74 @@ +#include +#include + +using namespace std; + +/* +һά ijһԪصֵΪ0 ڵкԪض +Ϊ0 СĿռ临Ӷ +*/ + +void SetZero(vector >& matrix) +{ + bool firstLine = false; + bool firstRow = false; + + //жϵһǷֵΪ0 Ԫ + for(int i=0;i +#include +#include +using namespace std; +/* +һԪ֮͵ڹ̶ֵض +*/ + +void Combination_helper(vector& vec,int begin,int target,int& cur,vector& path) +{ + + if(begin >=vec.size()) + return ; + + cur += vec[begin]; + path.push_back(vec[begin]); + if(cur == target) + { + for(int i=0;i& vec,int target) +{ + vector path; + int cur = 0; + if(vec.size() == 0) + return ; + Combination_helper(vec,0,target,cur,path); +} + +int main() +{ + + vector path; + int array[]={1,1,2,5,6,7,10}; + int cur =0; + vector vec(array,array+sizeof(array)/sizeof(int)); + Combination(vec,8); + return 0; +} diff --git "a/jun_algorithm/doc/cpp/back-track/\346\261\202\344\271\235\345\256\253\346\240\274\344\270\255\345\255\227\347\254\246\345\222\214\346\225\260\345\255\227\347\232\204\347\273\204\345\220\210.cpp" "b/jun_algorithm/doc/cpp/back-track/\346\261\202\344\271\235\345\256\253\346\240\274\344\270\255\345\255\227\347\254\246\345\222\214\346\225\260\345\255\227\347\232\204\347\273\204\345\220\210.cpp" new file mode 100644 index 0000000000..b8c9edecc3 --- /dev/null +++ "b/jun_algorithm/doc/cpp/back-track/\346\261\202\344\271\235\345\256\253\346\240\274\344\270\255\345\255\227\347\254\246\345\222\214\346\225\260\345\255\227\347\232\204\347\273\204\345\220\210.cpp" @@ -0,0 +1,62 @@ +#include +#include +#include +using namespace std; +/* +ĿھŹֻϣÿֶӦżַ +һֵַҳжӦַϣÿ +һַжӦ +*/ +void helper(string& str,int begin,vector& hash,vector& vec) +{ + int i; + if(begin > str.length()) + return; + if(begin == str.length()) + { + for(i=0;i& hash) +{ + if(str.length()==0) + return ; + vector vec; + helper(str,0,hash,vec); +} + +void LetterCom(string& str) +{ + int i; + vector hash(10); //10 + hash[0]=" "; + hash[1]="-"; + hash[2]="abc"; + hash[3]="def"; + hash[4]="ghi"; + hash[5]="jkl"; + hash[6]="mno"; + hash[7]="pqrs"; + hash[8]="tuv"; + hash[9]="wxyz"; + + Combination(str,hash); + return ; +} + +int main() +{ + string str("23"); + LetterCom(str); + return 0; +} diff --git "a/jun_algorithm/doc/cpp/back-track/\346\261\202\346\213\254\345\217\267\346\255\243\347\241\256\347\232\204\347\273\204\345\220\210\346\226\271\345\274\217.cpp" "b/jun_algorithm/doc/cpp/back-track/\346\261\202\346\213\254\345\217\267\346\255\243\347\241\256\347\232\204\347\273\204\345\220\210\346\226\271\345\274\217.cpp" new file mode 100644 index 0000000000..ce388ee694 --- /dev/null +++ "b/jun_algorithm/doc/cpp/back-track/\346\261\202\346\213\254\345\217\267\346\255\243\347\241\256\347\232\204\347\273\204\345\220\210\346\226\271\345\274\217.cpp" @@ -0,0 +1,49 @@ +#include +#include +#include +using namespace std; + +/* +ڼţжȷϷʽ +˼·ʹõݹķֻڵݹʱ +ʱҪ֤ߵűұߵŶ +ֻűŶ²пܱ֤ΪϷƥ +*/ + +void helper(vector& str,int l,int r) +{ + if(l == 0 && r == 0) + { + for(int i=0;i0) + { + str.push_back('('); + helper(str,l-1,r); + str.pop_back(); + } + if(r>0 && l tmp; + helper(tmp,n,n); +} + +int main() +{ + GenerateParenthess(3); + return 0; +} diff --git a/jun_algorithm/doc/cpp/character/atoi.cpp b/jun_algorithm/doc/cpp/character/atoi.cpp new file mode 100644 index 0000000000..74c907b7cc --- /dev/null +++ b/jun_algorithm/doc/cpp/character/atoi.cpp @@ -0,0 +1,60 @@ +#include +#include +#include +#include + +using namespace std; + +/* +ʵatoi + +Ҫעĵط +1.ֵԽ +2. +3.ַ־ +*/ + +int StringToInt(string& str) +{ + if(str.length() == 0) + return 0; + int i; + int flag =1; + int result =0; + int digit; + + //տʼĿոַ + for(i=0;i '9') + break; + digit = str[i]-'0'; + //жԽ + if(flag && (numeric_limits::max() - result*10) <= digit) + return numeric_limits::max(); + else if(!flag && (numeric_limits::min() + result*10) >= digit*-1) + return numeric_limits::min(); + result = result*10+digit; + } + return flag ==1? result:-result; +} + +int main() +{ + string str("-4324324878787998797"); + cout< +#include + +// һѾõַ ظַһ + +void Remove(char* str) +{ + int index =0; + int pos =1; + for(;str[pos]!='\0';pos++) + { + if(str[pos] != str[index]) + { + index++; + str[index]= str[pos]; + } + } + str[index+1] ='\0'; +} + +// һѾõַ ظַ +void Remove2(char* str) +{ + int index =0; + int pos =1; + int flag =0; + for(;str[pos]!='\0';pos++) + { + //ǰλõַѾַһλõַͬ + if(str[pos] != str[index]) + { + index++; + str[index] = str[pos]; + flag=0; + } + //ǰλõַѾַһλõַͬ + else + { + if(flag == 0) + { + index++; + str[index] = str[pos]; + flag =1; + } + } + } + str[index+1]='\0'; +} + +//ظַȫɾ +void Remove3(char* str) +{ + int flag =0; + int index =-1; + int pos; + //ַ + for(pos=0;str[pos+1]!='\0';) + { + //ǰַһַͬ + if(str[pos] == str[pos+1]) + { + flag =1; + pos++; + } + //ǰַһַͬ + else + { + if(flag == 1) + { + flag =0; + pos++; + } + else + { + index++; + str[index] = str[pos]; + pos++; + } + } + } + if(str[pos]!= str[pos-1]) + str[++index] = str[pos]; + str[index+1] = '\0'; +} + +int main() +{ + char str[]="AAABCCCDFGGIIIKKLMNNOOPQQQQ"; + printf("%s\n",str); + Remove3(str); + printf("%s\n",str); + return 0; +} diff --git "a/jun_algorithm/doc/cpp/character/\345\255\227\347\254\246\344\270\262\346\216\222\345\272\217\357\274\210\345\217\257\345\274\225\347\224\263\344\270\272\345\277\253\346\216\222\357\274\211.cpp" "b/jun_algorithm/doc/cpp/character/\345\255\227\347\254\246\344\270\262\346\216\222\345\272\217\357\274\210\345\217\257\345\274\225\347\224\263\344\270\272\345\277\253\346\216\222\357\274\211.cpp" new file mode 100644 index 0000000000..7a9148603d --- /dev/null +++ "b/jun_algorithm/doc/cpp/character/\345\255\227\347\254\246\344\270\262\346\216\222\345\272\217\357\274\210\345\217\257\345\274\225\347\224\263\344\270\272\345\277\253\346\216\222\357\274\211.cpp" @@ -0,0 +1,56 @@ +#include +#include + +// ַ ʹַддַǰ Сдַں +void StrSort(char* str) +{ + int index =-1; + int pos =0; + char temp; + for(;str[pos]!='\0';pos++) + { + if(str[pos] >= 'A' && str[pos]<='Z') + { + index++; + temp = str[index]; + str[index] = str[pos]; + str[pos]= temp; + } + } +} + +// ͬҪ ʹСдַ˳򲻸ı +void StrSort2(char* str) +{ + int len =0; + while(str[len]!='\0') + len++; + int index =len; + int pos = len-1; + char temp; + + for(;pos>=0;pos--) + { + if(str[pos] >= 'a' && str[pos] <= 'z') + { + index--; + temp = str[index]; + str[index]=str[pos]; + str[pos] = temp; + } + } +} + + +int main() +{ + char str[] ="jdfIhdHHfdslfdSFDldfaDSKdIdgHWlkfDf"; + printf("%s\n",str); + StrSort(str); + printf("%s\n",str); + + char str[] ="jdfIhdHHfdslfdSFDldfaDSKdIdgHWlkfDf"; + StrSort2(str); + printf("%s\n",str); + return 0; +} diff --git "a/jun_algorithm/doc/cpp/character/\345\255\227\347\254\246\344\270\262\346\237\245\346\211\276\344\270\216\345\217\215\350\275\254.cpp" "b/jun_algorithm/doc/cpp/character/\345\255\227\347\254\246\344\270\262\346\237\245\346\211\276\344\270\216\345\217\215\350\275\254.cpp" new file mode 100644 index 0000000000..5d0e474b52 --- /dev/null +++ "b/jun_algorithm/doc/cpp/character/\345\255\227\347\254\246\344\270\262\346\237\245\346\211\276\344\270\216\345\217\215\350\275\254.cpp" @@ -0,0 +1,64 @@ +#include +#include + +//ַиֵַĴ +void FindTimes(char* str) +{ + int hash[256]={0}; + int index =0; + while(str[index]!='\0') + { + hash[str[index]]++; + index++; + } + + for(index=0;index<256;index++) + printf("%d ",hash[index]); + printf("\r\n"); +} +// ηתһӣԵΪλзת +/** +ӵķת +ȻڲʵĶηת +*/ + +//ַй̶λõзת +void Reverse(char* str,int begin,int end) +{ + char tmp; + while(begin < end) + { + tmp = str[begin]; + str[begin] = str[end]; + str[end] = tmp; + begin++; + end--; + } +} + +/* +ַڲʵķת ͷʼ ÿȷһʾͽзת +*/ + +void Reverse_second(char* str,int len) +{ + int begin,i,j; + for(i=0;i +#include + + +//1ݹķʽַ +int RecurLength(char* str) +{ + if(str[0] == '\0') + return 0; + else + return RecurLength(str+1)+1; +} + +//2ַһʵij(ַ֪ij) +int LastWordLen(char* str,int len) +{ + int lastlen = 0; + int index = len-1; + while(index>=0 && str[index--] != ' ') + lastlen++; + return lastlen; +} + +//2ַһʵij(δַ֪ij) +int LastWordLen2(char* str) +{ + int lastlen = 0; + int index =0; + while(str[index] !='\0') + { + if(str[index]==' ') + lastlen =0; + else + lastlen++; + index++; + } + return lastlen; +} + + +//ַڴĿ ʵmemmove(޸ǿ) +char* my_memmove(char* dst,char* src,int count) +{ + char* ret = dst; + if(dst == NULL || src == NULL) + return NULL; + //dstsrcûصôӿʼһ + if(dst <= src || dst >= (src+count)) + { + while(count--) + { + *dst = *src; + dst++; + src++; + } + } + //dstsrcн棬ôβʼʼλÿԱص + else + { + dst = dst + count-1; + src = src + count-1; + while(count--) + { + *dst = *src; + dst--; + src--; + } + } + return ret; +} +int main() +{ + char str[]="Hello dunso"; + printf("str len is %d\r\n",RecurLength(str)); + printf("lastword len is %d\r\n",LastWordLen(str,12)); + printf("lastword len is %d\r\n",LastWordLen2(str)); + return 0; +} diff --git "a/jun_algorithm/doc/cpp/character/\347\211\271\346\256\212\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276(\347\273\217\345\205\270).cpp" "b/jun_algorithm/doc/cpp/character/\347\211\271\346\256\212\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276(\347\273\217\345\205\270).cpp" new file mode 100644 index 0000000000..46f411b197 --- /dev/null +++ "b/jun_algorithm/doc/cpp/character/\347\211\271\346\256\212\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276(\347\273\217\345\205\270).cpp" @@ -0,0 +1,97 @@ +#include +#include +using namespace std; + +/* +һֻһһ dz +ҵһε +*/ + +//е õĽҪҵ +int SingleNumber(vector& vec) +{ + if(vec.size()<=0) + return 0; + int i; + int value = vec[0]; + for(i=1;i& a,int& pN1,int& pN2) +{ + int i,j,temp; + + // + temp =0; + for(i=0;i> j)&1) ==1) + break; + + //jλΪ1˵ڵjλDzͬ з + pN1 =0; + pN2 =0; + for(i=0;i> j )&1) ==0) + pN1 ^= a[i]; + else + pN2 ^= a[i]; + +} + +/* +һֻһһ dz ҳ +*/ + +//ͬλж + +int SingleNumberIII(vector& vec) +{ + int i,j; + int low=0,high=vec.size()-1; + int bit =1; + int flag =0; + + //ͨijһλֵΪ֣һְ˴ҵ һֲ + while(low <= high) + { + if(low == high) + return vec[low]; + i = low-1; + for(j = low;j<= high;j++) + { + if((vec[j]&bit) == 0) + { + i++; + swap(vec[i],vec[j]); + } + } + if(i >= low) + { + if((i-low+1)%3 == 0) + low = i+1; + else + high =i; + } + bit = bit<<1; + } + return 0; +} +int main() +{ + int array[]={12,23,12,45,56,45,23,78,78,78,12,23,45}; + vector vec(array,array+sizeof(array)/sizeof(int)); + int fir,sec; + cout< +#include +using namespace std; +/* +˼·ڳΪnַmַ +ͷɨַõһַԵһַѡ +ַŵȥҪʣµn-1ַѡȡm-1ַ +ַŵȥҪʣµn-1ַѡȡmַ +*/ +void Combination(char* string, int number, vector& result) +{ + if(number == 0) + { + vector::iterator iter = result.begin(); + for(; iter < result.end(); ++ iter) + cout<<(*iter); + cout< result; + for(int i = 1; i <= length; ++ i) + { + Combination(string, i, result); + } +} +int main() +{ + char str[] ="abc"; + Combination(str); + return 0; +} diff --git "a/jun_algorithm/doc/cpp/combination/\347\273\204\345\220\210\347\256\227\346\263\225\347\232\204\345\256\236\347\216\260.cpp" "b/jun_algorithm/doc/cpp/combination/\347\273\204\345\220\210\347\256\227\346\263\225\347\232\204\345\256\236\347\216\260.cpp" new file mode 100644 index 0000000000..2eb88d774e --- /dev/null +++ "b/jun_algorithm/doc/cpp/combination/\347\273\204\345\220\210\347\256\227\346\263\225\347\232\204\345\256\236\347\216\260.cpp" @@ -0,0 +1,81 @@ +#include +#include +#include +#include +using namespace std; +/* +ϵһʵ +*/ +void helper(vector& vec,int begin,int& num,vector& subset) +{ + if(begin >= vec.size() || num<0 ) + return ; + subset.push_back(vec[begin]); + num--; + if(num == 0) + { + int i; + for(i=0;i& vec,int k) +{ + if(vec.size()==0 || k <0) + return ; + vector subset; + sort(vec.begin(),vec.end()); + helper(vec,0,k,subset); +} + +void Subsets(vector& vec) +{ + int i; + for(i=0;i<=vec.size();i++) + Combination(vec,i); +} +/* +һַ +*/ +void generate(vector res, vector &S, int i) + { + if(i == S.size()) + { + for(int j=0;j& vec) +{ + if(vec.size()<=0) + return; + + sort(vec.begin(),vec.end()); + vector result; + generate(result,vec,0); + +} + + +int main() +{ + int array[]={2,1,3}; + vector vec(array,array+sizeof(array)/sizeof(int)); + SubsetSecond(vec); + return 0; +} diff --git "a/jun_algorithm/doc/cpp/combination/\347\273\204\345\220\210\347\256\227\346\263\225\347\232\204\345\272\224\347\224\250.cpp" "b/jun_algorithm/doc/cpp/combination/\347\273\204\345\220\210\347\256\227\346\263\225\347\232\204\345\272\224\347\224\250.cpp" new file mode 100644 index 0000000000..95120b31da --- /dev/null +++ "b/jun_algorithm/doc/cpp/combination/\347\273\204\345\220\210\347\256\227\346\263\225\347\232\204\345\272\224\347\224\250.cpp" @@ -0,0 +1,49 @@ +#include +#include +#include +#include +using namespace std; +/* +һУҵʵĸʹΪ0 +*/ +void helper(vector& vec,int index,int num,vector& target) +{ + if(index >= vec.size()) + return ; + target.push_back(vec[index]); + num--; + if(num ==0) + { + int i=0; + int sum=0; + sum =accumulate(target.begin(),target.end(),sum); + if(sum == 0) + { + for(i=0;i& vec) +{ + if(vec.size()==0) + return ; + vector target; + helper(vec,0,4,target); +} + + +int main() +{ + int array[]={1,0,-1,0,-2,2}; + vector vec(array,array+sizeof(array)/sizeof(int)); + FourSum(vec); + return 0; +} diff --git "a/jun_algorithm/doc/cpp/dp/\345\255\227\347\254\246\344\270\262\350\247\243\347\240\201.cpp" "b/jun_algorithm/doc/cpp/dp/\345\255\227\347\254\246\344\270\262\350\247\243\347\240\201.cpp" new file mode 100644 index 0000000000..371156f5cc --- /dev/null +++ "b/jun_algorithm/doc/cpp/dp/\345\255\227\347\254\246\344\270\262\350\247\243\347\240\201.cpp" @@ -0,0 +1,44 @@ +#include +#include +#include +using namespace std; + +/* +˼· +һ͵DP⣬趨һ飬dp[i]Ϊiַܹɵ +б뷽ʽĸôdp[i+1]˵϶ٺdp[i]һ࣬i +ַi+1ַԺϳһַôdp[i+1] += dp[i-1]. +*/ + +int Decode_num(string& str) +{ + vector vec(str.size(),1); + if(str.size() <2) + return 1; + if(str[0]=='1'||(str[0]=='2'&& str[1]<='6')) + vec[1] =2; + int i; + int tmp; + for(i=2;i= '0' && str[i] <= '9')//жǺϷַ + vec[i] = vec[i-1]; + else + return 0; + tmp = str[i-1] -'0'; + tmp = tmp*10 + str[i]-'0'; + + if(str[i-1]!='0' && tmp <=26) + vec[i] += vec[i-2]; + else + vec[i] = vec[i-1]; + } + return vec[str.size()-1]; +} + +int main() +{ + string str("1231725"); + cout< +#define NIL -1 +#define MAX 100 + +int lookup[MAX]; + +/*ʼ*/ +void _initialize() +{ + int i; + for (i = 0; i < MAX; i++) + lookup[i] = NIL; +} + +/*仯϶£ +仯洢ʵǶԵݹС޸ģ +ΪDPĹɡ +dzʼһвгʼֵΪ-1 +ÿҪһ⣬ +(ұ)Ƿд𰸡 +Ԥȼֵ,ôǾͷظֵ +Ǽֵѽ(ұ)У +ԱԺظʹá*/ +int fib1(int n) +{ + if(lookup[n] == NIL) + { + if ( n <= 1 ) + lookup[n] = n; + else + lookup[n] = fib1(n-1) + fib1(n-2); + } + + return lookup[n]; +} + +int fib2(int n) +{ + int f[n+1]; + int i; + f[0] = 0; f[1] = 1; + for (i = 2; i <= n; i++) + f[i] = f[i-1] + f[i-2]; + + return f[n]; +} + + +int main () +{ + int n = 9; + _initialize(); + printf("Fibonacci number is %d\n", fib1(n)); + printf("Fibonacci number is %d ", fib2(n)); + getchar(); + return 0; +} diff --git "a/jun_algorithm/doc/cpp/dp/\346\234\200\345\244\247\345\255\220\346\225\260\347\273\204\344\271\230\347\247\257.cpp" "b/jun_algorithm/doc/cpp/dp/\346\234\200\345\244\247\345\255\220\346\225\260\347\273\204\344\271\230\347\247\257.cpp" new file mode 100644 index 0000000000..697e1e3104 --- /dev/null +++ "b/jun_algorithm/doc/cpp/dp/\346\234\200\345\244\247\345\255\220\346\225\260\347\273\204\344\271\230\347\247\257.cpp" @@ -0,0 +1,41 @@ +#include +#include +#include +using namespace std; + +/* +Ӵ˻ڿָܳҲDP⣬ҲǾֲźȫ⡣ +Ҫ¼Сֵ飬ֱ¼ǰԪڵӴܹ +СֵȻٸȫڵǰ󣬿֮ǰ +ԵǰԪأҲǰһԪСԵǰԪأҲǵǰԪ +*/ + +int maxProduct(vector& vec) +{ + if(vec.size()==0) + return 0; + vector maxcur(vec.size(),0); + vector mincur(vec.size(),0); + maxcur[0]=vec[0]; + mincur[0]=vec[0]; + int maxproduct = vec[0]; + int i,temp; + for(i=1;i vec(array,array+sizeof(array)/sizeof(int)); + cout< +#include +#include +#include +using namespace std; + +/* +бƷ +ÿεʱжߵұߵָĸ +ߵ£ζƶұߵ㲻ʹýø +Ϊƿߵ㣬ƶұߵֻСʱѡߵ +֮ѡұߵƣһֱάݻ +*/ + +int area(vector &height, int i, int j) +{ + int h = height[i] &height) +{ + int max=0; + for(int i=0;imax) + max=a; + } + } + return max; +} + +/* +ڶַ +*/ +int maxarea(vector& vec) +{ + int maxarea=0; + int first,second; + int i=0,j=vec.size()-1; + while( i maxarea) + { + maxarea = min(vec[i],vec[j])*(j-i); + } + if(vec[i] < vec[j]) + i++; + else + j--; + } + return maxarea; +} + +/* + + | + | __ + | | | + | __ | |__ __ + | | | | | | | | + | __ | |__ __ | | |__| |__ + | | | | | | | | | | | | | | + |__|__|__|__|__|__|__|__|__|__|__|__|__|_____ + 1 2 3 4 5 6 7 8 8 9 10 11 12 +һΪ[0,1,0,2,1,0,1,3,2,1,2,1]ÿԪشӵĸ߶ +ķֵΪ6 + +˼·ҵߵλãôͷʼҿ +ʢˮĶ٣ͷʼҪߵλãǰλ +ֵǰӱ֮ǰ¼Ӹߣô +û֮ǰ¼ӸߣôͿԼ㵱ǰ֮ǰĸӵʢˮ +*/ +int TrapRainWater(vector& vec) +{ + int i,maxhigh; + maxhigh = 0; + int left=0,right = 0; + int sum =0; + for(i=0;i vec[maxhigh]) + maxhigh = i; + + for(i=0;imaxhigh;i--) + { + if(vec[i] vec(array,array+sizeof(array)/sizeof(int)); +// cout< vec(array,array+sizeof(array)/sizeof(int)); + cout< +#include +#include +#include +using namespace std; + +/* +͵DP⣬ҪʹSƥT ö̬滮˼ +ʹdp[i][j]ʾSTǰiַǰjַƥӴ +1ʼTΪմʱSΪַƥһΣdp[i][0]=1 +SΪַTΪʱƥ䣬dp[0][j] =0 +2)S[i] == T[j]dp[i][j] = dp[i-1][j-1]+dp[i-1][j].ʾǰַԱ +Ҳ +3S[i] != T[j]dp[i][j] = dp[i-1][j-1] +*/ + +int Distinct_sub(string& src,string& dst) +{ + vector > dp(src.size()); + int i,j; + for(i=0;i > dp(s1.size()); + int i,j; + for(i=0;i::max()); + if(s1[0]==s2[0]) + dp[0][0] =0; + else + dp[0][0] =1; + for(i=1;i& prices) +{ + if(prices.size() <= 0) + return 0; + int global[3]; + int local[3]; + for(int i=0;i=1;j--) + { + local[j] = max(global[j-1]+(diff>0?diff:0),local[j]+diff); + global[j] = max(local[j],global[j]); + } + } + global[2]; +} + + +/* +ν֮ +*/ +int helper(vector& prices,int k) +{ + int len = prices.size(); + if(len == 0) + return 0; + int local[10][10]; + int global[10][10];//ʱĿռ + for(int i=1;i& prices) +{ + return helper(prices,2); +} diff --git "a/jun_algorithm/doc/cpp/dp/\350\267\257\345\276\204\346\225\260\347\233\256 & \346\234\200\345\260\217\350\267\257\345\276\204\345\222\214.cpp" "b/jun_algorithm/doc/cpp/dp/\350\267\257\345\276\204\346\225\260\347\233\256 & \346\234\200\345\260\217\350\267\257\345\276\204\345\222\214.cpp" new file mode 100644 index 0000000000..a6a1c9ba76 --- /dev/null +++ "b/jun_algorithm/doc/cpp/dp/\350\267\257\345\276\204\346\225\260\347\233\256 & \346\234\200\345\260\217\350\267\257\345\276\204\345\222\214.cpp" @@ -0,0 +1,84 @@ +#include +#include +#include +using namespace std; + +/* +˼·ijһdp[i][j]·ĿǸõϷ·Ŀ֮ +dp[i][j] = dp[i][j-1] + dp[i-1][j]; ǶطҪ⿼ +*/ + +int Unique_path(int m,int n,int first,int second) +{ + vector > dp(m); + int i,j; + for(i=0;i >& vec) +{ + vector > dp(vec.size()); + int i,j; + for(i=0;i::max()); + dp[0][0] = vec[0][0]; + for(i=1;i > vec(3); + int i,j; + int array[]={2,4,3,7}; + int array1[]={5,3,2,1}; + int array2[]={4,8,6,2}; + vec[0].assign(array,array+4); + vec[1].assign(array1,array1+4); + vec[2].assign(array2,array2+4); + cout< +#include + +//ֲ +/* +һ ijһԪǷ +ڣظԪڸеλ +ڣ-1 +*/ +/* +high = n-1,while(high >= low) high = middle -1; +high = n while(high > low) high = middle; +*/ +int binary_search(int* array,int n,int key) +{ + int low = 0; + int high = n-1; + int mid; + if(high < low) + return -1; + while(high >= low) + { + mid = low+((high-low)>>1); + if(array[mid] == key) + return mid; + else if(array[mid] > key) + high = mid-1; + else + low = mid+1; + } + return -1; +} + +int main() +{ + int array[]={1,2,3,4,5,6,7,8,9,10}; + printf("%d\n",binary_search(array,10,4)); + return 0; +} diff --git "a/jun_algorithm/doc/cpp/find/\345\257\273\346\211\276\345\244\232\344\270\252\351\233\206\345\220\210\347\232\204\344\272\244\351\233\206.cpp" "b/jun_algorithm/doc/cpp/find/\345\257\273\346\211\276\345\244\232\344\270\252\351\233\206\345\220\210\347\232\204\344\272\244\351\233\206.cpp" new file mode 100644 index 0000000000..3b832b211e --- /dev/null +++ "b/jun_algorithm/doc/cpp/find/\345\257\273\346\211\276\345\244\232\344\270\252\351\233\206\345\220\210\347\232\204\344\272\244\351\233\206.cpp" @@ -0,0 +1,55 @@ +#include +#include +#include +using namespace std; + +/* +Ľ +*/ + +void FindElements(vector& first,vector& second) +{ + if(first.size() <=0 || second.size() <= 0) + return; + // + sort(first.begin(),first.end()); + sort(second.begin(),second.end()); + + //ԪظٵһǷ + if(first.size() >second.size()) + first.swap(second); + int i,key; + for(i =0;i second[mid]) + low = mid+1; + else + high = mid-1; + + } + + } +} + +int main() +{ + int array[]={5,4,3,8,9,7,0}; + int array1[]={11,8,34,3,4,8,9,2}; + vector first(array,array+sizeof(array)/sizeof(int)); + vector second(array1,array1+sizeof(array1)/sizeof(int)); + FindElements(first,second); + return 0; +} diff --git "a/jun_algorithm/doc/cpp/find/\346\227\213\350\275\254\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276.cpp" "b/jun_algorithm/doc/cpp/find/\346\227\213\350\275\254\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276.cpp" new file mode 100644 index 0000000000..a3ae86df0e --- /dev/null +++ "b/jun_algorithm/doc/cpp/find/\346\227\213\350\275\254\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276.cpp" @@ -0,0 +1,79 @@ +#include +#include +#include +using namespace std; + +/* +һظԪصѾתвijһԪ +ԪشڸתУ1 +ԪزڸתУ0 +*/ + +bool RotateArray(vector& vec,int key) +{ + int low =0,high = vec.size()-1; + int mid; + while(low<=high) + { + mid = low + (high-low)/2; + if(vec[mid] == key) + return 1; + // + if(vec[mid]>vec[low]) //ǰ벿һ + { + if(key >= vec[low]&& key vec[mid]&& key<= vec[high]) + low= mid+1; + else + high = mid-1; + } + } + return 0; +} + +/* +һظԪصתвijһԪ +жϸԪǷ +*/ +bool RotateArray2(vector& vec,int key) +{ + int low = 0,high=vec.size()-1; + int mid; + //ͬʹöֲҵ˼ + while(low <= high) + { + mid = low+(high-low)/2; + if(vec[mid] == key) + return 1; + if(vec[mid] > vec[low])//ǰ벿 + { + if(key >= vec[low] && key < vec[mid]) + high = mid-1; + else + low = mid+1; + } + else if(vec[mid] < vec[low]) //ǰ벿ǽ + { + if(key > vec[mid] && key <= vec[high]) + low = mid+1; + else + high = mid-1; + } + else + low++; + } + return 0; +} + +int main() +{ + int array[]={4,5,6,7,0,1,2}; + vector vec(array,array+sizeof(array)/sizeof(int)); + cout< +#include +using namespace std; + +//һУijһԪڸе +//ҵһڸԪص± +int lower_bound(int* array,int low,int high,int key) +{ + int mid; + if(high < low) + return -1; + + //öֲҵIJ + while(high >= low) + { + mid = low+((high-low)>>1); + if(array[mid] < key) + low = mid+1; + else + high = mid-1; + } + return low; +} +/* + һУijһԪڸе + ҵһڸԪص± +*/ +int upper_bound(int* array,int low,int high,int key) +{ + int mid; + if(high < low) + return -1; + while(high >= low) + { + mid = low+((high-low)>>1); + if(array[mid]>key) + high = mid-1; + else + low = mid+1; + } + return low; +} + + +/* +ijһԪһеķΧ +Ԫص Ϊ˱ +ûҵ ͷ-1 +*/ +pair Findvalue(vector& vec,int key) +{ + pair pos(-1,-1); + int mid,begin = 0,end = vec.size(); + //жϸԪǷ + while(begin <= end) + { + mid = begin + ((end-begin)>>1); + if(vec[mid] == key) + { + pos.first = mid; + pos.second = mid; + break; + } + else if(vec[mid] > key) + end = mid-1; + else + begin =mid+1; + } + + if(vec[mid] != key) + return pos; + int low = mid-1; + int high = mid+1; + + //ҵ͵ַ + while(begin <= low) + { + mid = begin +(low-begin)/2; + if(vec[mid] < key) + begin = mid+1; + else + low = mid-1; + } + pos.first = begin; + + //Ҹߵַ + while(high <= end) + { + mid = high +(end-high)/2; + if(vec[mid] > key) + end = mid-1; + else + high = mid+1; + } + pos.second = high -1; + return pos; +} + +int main() +{ + int array[]={1,2,3,3,3,3,3,3,4,5,7}; + cout< vec(array,array+sizeof(array)/sizeof(int)); + pair pos = Findvalue(vec,3); + cout< +#include +using namespace std; + +/* +ɨ裬һδңһδ +һɨʱάÿһСҪٵǹ +ӦԪУڶɨʱάұǹ +ұȽϽߺұߴǹӦԪ +*/ + +int candy(vector &ratings) +{ + vector candy(ratings.size(),1); + int sum,i; + for(i=1;i ratings[i-1]) + candy[i] = candy[i-1]+1; + } + + sum = candy[ratings.size()-1]; + for(i=ratings.size()-2;i>=0;i--) + { + int cur =1; + if(ratings[i] > ratings[i+1]) + cur = candy[i+1]+1; + sum += max(cur,candy[i]); + candy[i] = cur; + } + return sum; +} + + +/* +˼· +*/ +int candy2(vector &ratings) +{ + vector candy(ratings.size(),1); + int sum,i; + for(i=1;i ratings[i-1]) + candy[i] = candy[i-1]+1; + } + + sum = candy[ratings.size()-1]; + for(i=ratings.size()-2;i>=0;i--) + { + int cur =1; + if(ratings[i] > ratings[i+1] && candy[i] <= candy[i+1]) + candy[i] = candy[i+1]+1; + sum += candy[i]; + + } + + return sum; +} + + +int main() +{ + int array[]={4,2,6,8,5}; + vector vec(array,array+sizeof(array)/sizeof(int)); + cout< +#include +#include +using namespace std; + +/* + +*/ +int MaxSubarray(vector& vec) +{ + int sum = vec[0]; + int curmax= vec[0]; + int i; + for(i=1;i sum) + sum = curmax; + } + if(sum<0) + { + for(i=0;i vec(array,array+sizeof(array)/sizeof(int)); + cout< +#include +using namespace std; + +/* +̰˼룬ʱ̼㵱ǰλú͵ǰλԶȣʼպͽޱȽ +λóΪ0ô޷ȥ +λó+ǰλ >ޣô˵ȥ +*/ + +bool canJump(vector& vec) +{ + if(vec.size() <=0) + return true; + int maxstep = vec[0]; + for(int i=1;i= vec.size()-1) + return true; + } +} + +int main() +{ + int array[]={2,3,1,1,4}; + vector vec(array,array+sizeof(array)/sizeof(int)); + cout< +#include +#include +using namespace std; +/* +ĿһַܰһַĻӴС +˼·ʹָ룬һhashָΪ˼¼hashΪ˼¼Ƿ +ĿӴָ֮˶ٴΣֱַӴڣ +ƶǰָ룬ֱijһӴӴһ +ôռijȾǵǰ̵ģֱַ +*/ + +string MinLength(string& src,string& dest) +{ + int i=0,j=0; + int flag =0; + int len = src.size(); + int pos =0; + vector hash(26,-1); + for(i=0;i= 0) + { + hash[src[i]-'A']++; + if(hash[src[i]-'A'] ==1) + flag++; + } + if(flag == dest.length()) + { + for(;ji-j+1) + { + len =i-j+1; + pos = j; + } + + hash[src[j]-'A'] =0; + j++; + flag--; + } + } + cout< +#include +#include +using namespace std; +/* +ĿûظַӴ +˼·еַ26СдӢַԴ˽hash +hashڼ¼ֵַλãֵǰַǰַѾ +ôϴγַλõһַ± +ôhashգӵǰλÿʼ +*/ + +int Longest_substring(string& str) +{ + vector hash(26,-1); + int i; + int cur =0; + int maxlen =0; + int tmp; + for(i=0;i cur?maxlen:cur; + } + else + { + tmp = hash[str[i]-'a'];//ʱ¼λ + i = tmp; + cur =0; + //memset(&hash[0],-1,sizeof(int)*hash.size()); + } + } + return maxlen; +} +/* +ͬ˼ ķ +*/ +int lengthOfLongeststring(string s) +{ + vector charIndex(256,-1);//չеַ + int longest =0; + int m=0; + + for(int i=0;i +#include +using namespace std; + +/* +ĵĸ +˼·ԿֱܹߵбʣбжϹߵĵĸ +бʺ͸бϵĸ͹һֵԣʹhash洢 +*/ + +int maxPoints(vector >& points ) +{ + if(points.size() == 0) + return 0; + int max =1; + double ratio=0.0; + //ʼ㣬ֵ + for(int i=0;i map; + int numofSame=0; + int localMax=1; + //ӵǰ֮ĵ㹹ɵб + for(int j=i+1;;j::max(); + } + else if(points[j].second == points[i].second) + { + ratio =0.0; + } + else + { + ratio = (double)(points[j].second-points[i].second)/(double)(points[j].first-points[i].first); + + } + int num; + if(map.find(ratio) != map.end()) + map[ratio]++; + else + map[ratio]=2; + } + //ʼijһбĵĸ + hash_map::iterator it = map.begin(); + fo(;it!=map.end();it++) + localMax = max(localMax,it->second); + localMax += numofSame; + max = max(max,localMax); + } + return max; +} + diff --git "a/jun_algorithm/doc/cpp/link/\345\210\240\351\231\244\345\215\225\351\223\276\350\241\250\344\270\255\351\207\215\345\244\215\347\232\204\345\205\203\347\264\240\357\274\210\344\274\252\346\214\207\351\222\210\357\274\211.cpp" "b/jun_algorithm/doc/cpp/link/\345\210\240\351\231\244\345\215\225\351\223\276\350\241\250\344\270\255\351\207\215\345\244\215\347\232\204\345\205\203\347\264\240\357\274\210\344\274\252\346\214\207\351\222\210\357\274\211.cpp" new file mode 100644 index 0000000000..058d11dbca --- /dev/null +++ "b/jun_algorithm/doc/cpp/link/\345\210\240\351\231\244\345\215\225\351\223\276\350\241\250\344\270\255\351\207\215\345\244\215\347\232\204\345\205\203\347\264\240\357\274\210\344\274\252\346\214\207\351\222\210\357\274\211.cpp" @@ -0,0 +1,109 @@ +#include +#include +using namespace std; + +typedef struct list_node List; +struct list_node +{ + int value; + struct list_node* next; +}; + +void Init_List(List*& head,int* array,int n) +{ + head = NULL; + List* tmp; + List* record; + for(int i=1;i<=n;i++) + { + tmp = new List; + tmp->next = NULL; + tmp->value = array[i-1]; + if(head == NULL) + { + head = tmp; + record = head; + } + else + { + record->next = tmp; + record = tmp; + } + } +} +void print_list(List* list) +{ + List* tmp=list; + while(tmp != NULL) + { + cout<value<next; + } +} + +/* +ɾظԪ +*/ +void RemoveDuplicate(List*& head) +{ + if(head == NULL || head->next == NULL) + return; + List* slow = head; + List* fast = head->next; + List* tmp; + while(fast != NULL) + { + if(slow->value == fast->value) + { + tmp = fast; + fast = fast->next; + slow->next = fast; + delete tmp; + } + else + { + slow = slow->next; + fast = fast->next; + } + } +} +//ɾظԪأֻظԪأαָ룩 +List* removeDuplicate(List* head) +{ + if(head == NULL || head->next == NULL) + return head; + List* temp,*pre,*cur; + List* newhead = new List; + newhead->next = head; + temp = newhead; + pre = head; + cur = head->next; + while(cur != NULL) + { + while(cur != NULL && cur->value == pre->value) + cur = cur->next; + if(pre->next == cur) + { + temp->next = pre; + temp = pre; + pre = cur; + } + else + { + pre = cur; + } + if(cur != NULL) + cur = cur->next; + } + temp->next = cur; + return newhead->next; +} +int main() +{ + int array[]={1,1,1,2,3,3,4,5,6,6,7,7}; + List* head; + Init_List(head,array,sizeof(array)/sizeof(int)); + head = removeDuplicate(head); + print_list(head); + return 0; +} diff --git "a/jun_algorithm/doc/cpp/link/\345\215\225\351\223\276\350\241\250\344\270\255\345\214\272\351\227\264\350\212\202\347\202\271\347\232\204\347\277\273\350\275\254.cpp" "b/jun_algorithm/doc/cpp/link/\345\215\225\351\223\276\350\241\250\344\270\255\345\214\272\351\227\264\350\212\202\347\202\271\347\232\204\347\277\273\350\275\254.cpp" new file mode 100644 index 0000000000..9a3348ad89 --- /dev/null +++ "b/jun_algorithm/doc/cpp/link/\345\215\225\351\223\276\350\241\250\344\270\255\345\214\272\351\227\264\350\212\202\347\202\271\347\232\204\347\277\273\350\275\254.cpp" @@ -0,0 +1,96 @@ +#include +#include +#include +using namespace std; + +typedef struct list_node List; +struct list_node +{ + int value; + struct list_node* next; +}; + +void Init_List(List*& head,int* array,int n) +{ + head = NULL; + List* tmp; + List* record; + for(int i=1;i<=n;i++) + { + tmp = new List; + tmp->next = NULL; + tmp->value = array[i-1]; + if(head == NULL) + { + head = tmp; + record = head; + } + else + { + record->next = tmp; + record = tmp; + } + } +} +void print_list(List* list) +{ + List* tmp=list; + while(tmp != NULL) + { + cout<value<next; + } +} +/* +еĵmڵ㵽nڵ֮Ԫؽзת +*/ +void ReverseList(List*& list,int m,int n) +{ + if(list == NULL ||list->next == NULL || n-m<1) + return ; + int num =1; + List* pre,*next,*cur,*temp,*tmp; + cur = list; + pre = NULL; + while(cur != NULL) + { + next = cur->next; + if(num < m) + { + pre = cur; + cur = next; + } + if(num == m) + { + tmp = cur; + temp = cur; + cur = next; + } + if(num >m && num <= n) + { + cur->next = temp; + temp = cur; + cur = next; + } + if(num == n) + { + if(m ==1) + list = temp; + else + pre->next = temp; + tmp->next = cur; + break; + } + num++; + } +} + +int main() +{ + int array[]={5,1,2,7,8,4,3,6,10,9}; + List* list ; + Init_List(list,array,sizeof(array)/sizeof(int)); + ReverseList(list,1,3); + print_list(list); + return 0; +} diff --git "a/jun_algorithm/doc/cpp/link/\345\215\225\351\223\276\350\241\250\347\232\204 K \347\277\273\350\275\254\357\274\210\344\274\252\346\214\207\351\222\210\357\274\211.cpp" "b/jun_algorithm/doc/cpp/link/\345\215\225\351\223\276\350\241\250\347\232\204 K \347\277\273\350\275\254\357\274\210\344\274\252\346\214\207\351\222\210\357\274\211.cpp" new file mode 100644 index 0000000000..babf0392f8 --- /dev/null +++ "b/jun_algorithm/doc/cpp/link/\345\215\225\351\223\276\350\241\250\347\232\204 K \347\277\273\350\275\254\357\274\210\344\274\252\346\214\207\351\222\210\357\274\211.cpp" @@ -0,0 +1,164 @@ +#include +#include +using namespace std; + +/* +ҪKת +*/ +typedef struct list_node List; +struct list_node +{ + int value; + struct list_node* next; +}; + +void Init_List(List*& head,int* array,int n) +{ + head = NULL; + List* tmp; + List* record; + for(int i=1;i<=n;i++) + { + tmp = new List; + tmp->next = NULL; + tmp->value = array[i-1]; + if(head == NULL) + { + head = tmp; + record = head; + } + else + { + record->next = tmp; + record = tmp; + } + } +} +void print_list(List* list) +{ + List* tmp=list; + while(tmp != NULL) + { + cout<value<next; + } +} + +/* +תList ʹµͷΪHeadµβΪtail +*/ +void Reverse_list(List*& list,List*& head,List*& tail) +{ + if(list == NULL || list->next == NULL) + return; + head = list; + tail = list; + List* cur = NULL; + List* next; + while(head != NULL) + { + next = head->next; + head->next = cur; + cur = head; + head = next; + } + list= cur; + head = cur; +} + +/* +Kڵķת +*/ +void Reverse_k(List*& list,int k) +{ + int num =1; + int flag =1; + if(list == NULL ||list->next == NULL || k ==0) + return ; + List* head,*tail,*next,*pre; + head = list; + tail= list; + + while(tail != NULL && tail->next != NULL) + { + tail = tail->next; + num++; + if(num == k) + { + if(tail != NULL) + { + next = tail->next; + tail->next = NULL; + } + else + next = NULL; + Reverse_list(head,head,tail); + + if(flag) + { + list = head; + flag =0; + pre = tail; + } + else//ڶ֮ķת + { + pre->next = head; + pre = tail; + } + head = next; + tail = next; + num =1; + } + } + pre->next = head; +} +List* Reverse(List* pre,List* end) +{ + if(pre == NULL || pre->next == NULL) + return pre; + List* head = pre->next; + List* cur = pre->next->next; + while(cur != end) + { + List* next = cur->next; + cur->next = pre->next; + pre->next = cur; + cur = next; + } + head->next = end; + return head; +} + +//һֱȽϼ򵥵ķ + +List* Reverse_K(List* head,int k) +{ + if(head == NULL) + return NULL; + List* dummy = new List; + dummy->next = head; + int count =0; + List* pre = dummy; + List* cur = head; + while(cur != NULL) + { + count++; + List* next = cur->next; + if(count == k) + { + pre = Reverse(pre,next); //˴ǿ䣬תǴpreһڵ㵽nextһڵ + count =0; + } + cur = next; + } + return dummy->next; +} +int main() +{ + int array[]={1,2,3,4,5,6,7,8,9,10,11}; + List* list,*head,*tail; + Init_List(list,array,sizeof(array)/sizeof(int)); + list = Reverse_K(list,3); + print_list(list); + return 0; +} diff --git "a/jun_algorithm/doc/cpp/link/\345\215\225\351\223\276\350\241\250\347\232\204\345\210\206\345\211\262.cpp" "b/jun_algorithm/doc/cpp/link/\345\215\225\351\223\276\350\241\250\347\232\204\345\210\206\345\211\262.cpp" new file mode 100644 index 0000000000..520e07120d --- /dev/null +++ "b/jun_algorithm/doc/cpp/link/\345\215\225\351\223\276\350\241\250\347\232\204\345\210\206\345\211\262.cpp" @@ -0,0 +1,154 @@ +#include +#include +#include +using namespace std; + +typedef struct list_node List; +struct list_node +{ + struct list_node* next; + int value; +}; + +void print_list(List* list) +{ + List* tmp=list; + while(tmp != NULL) + { + cout<value<next; + } +} + +/* +ʼList 1~nֲ뵽 +*/ +void Init_List(List*& head,int* array,int n) +{ + head = NULL; + List* tmp; + List* record; + + for(int i=1;i<=n;i++) + { + tmp = new List; + tmp->next = NULL; + tmp->value = array[i-1]; + if(head == NULL) + { + head = tmp; + record = head; + } + else + { + record->next = tmp; + record = tmp; + } + } +} + +// +int Len_list(List* list) +{ + if(list == NULL) + return 0; + else + return Len_list(list->next)+1; +} + +/* +˼·ڿţҪ󲻸ıԭ˳ԱнڵĽ +ҪȻ֮佻ڵڲֵɡ +*/ + +/* +ڿķָ +*/ + +void PartitionList(List*& list,int key) +{ + if(list == NULL) + return ; + List* record,*cur,*pre,*tmp; + record = NULL; + cur = list; + pre = NULL; + //ʼ + while(cur != NULL) + { + if(cur->value< key) //뵽pre֮Ҫ⴦ͷڵ + { + tmp = cur->next; + if(pre == NULL) + pre = cur; + if(record ==NULL) + { + record = list; + list = cur; + cur->next = record; + record = cur; + pre->next = tmp; + } + else + { + if(pre != record) + { + cur->next = record->next; + record->next = cur; + pre->next = tmp; + record = cur; + } + else + { + record = pre= cur; + } + } + + cur = tmp; + } + else + { + pre= cur; + cur = cur->next; + } + } +} + +//ڶַ ʹαָ +List* PartitionList2(List* list,int key) +{ + List* head = new List; + head->next = list; + List* temp = head; + List* pre = head,*cur = list,*next; + + //ʼ + while(cur != NULL) + { + next = cur->next; + if(cur->value < key) + { + pre->next = next; + cur->next = temp->next; + temp->next = cur; + temp = cur; + cur = next; + } + else + { + pre = cur; + cur = next; + } + } + return head->next; +} + +int main() +{ + int array[]={5,1,2,7,8,4,3,6,10,9}; + List* list; + Init_List(list,array,sizeof(array)/sizeof(int)); + list = PartitionList2(list,5); + print_list(list); + return 0; +} diff --git "a/jun_algorithm/doc/cpp/link/\345\215\225\351\223\276\350\241\250\347\232\204\345\220\210\345\271\266\357\274\210\351\235\236\346\234\200\345\260\217\345\240\206\346\226\271\346\263\225\357\274\211.cpp" "b/jun_algorithm/doc/cpp/link/\345\215\225\351\223\276\350\241\250\347\232\204\345\220\210\345\271\266\357\274\210\351\235\236\346\234\200\345\260\217\345\240\206\346\226\271\346\263\225\357\274\211.cpp" new file mode 100644 index 0000000000..d644b24a30 --- /dev/null +++ "b/jun_algorithm/doc/cpp/link/\345\215\225\351\223\276\350\241\250\347\232\204\345\220\210\345\271\266\357\274\210\351\235\236\346\234\200\345\260\217\345\240\206\346\226\271\346\263\225\357\274\211.cpp" @@ -0,0 +1,149 @@ +#include +#include +using namespace std; + +/* +ϲKѾõ +*/ + +typedef struct list_node List; +struct list_node +{ + struct list_node* next; + int value; +}; + +void print_list(List* list) +{ + List* tmp=list; + while(tmp != NULL) + { + cout<value<next; + } +} + +/* +ʼList 1~nֲ뵽 +*/ +void Init_List(List*& head,int* array,int n) +{ + head = NULL; + List* tmp; + List* record; + + for(int i=1;i<=n;i++) + { + tmp = new List; + tmp->next = NULL; + tmp->value = array[i-1]; + if(head == NULL) + { + head = tmp; + record = head; + } + else + { + record->next = tmp; + record = tmp; + } + } +} + +// +int Len_list(List* list) +{ + if(list == NULL) + return 0; + else + return Len_list(list->next)+1; +} + +/* +ںϲѾõ˼룬СѣÿνѶԪ +µУҲʹбǣÿδѡСĽڵ +ֱĽڵ㶼ѡ +*/ + +List* Merge_k(vector& vec) +{ + int i; + //ʹб + vector flag(vec.size(),1); //flagʼֵΪ1 + List* head = NULL; + List* cur = NULL; + List* tmp = NULL; //¼ǰʱСֵ + int pos;//ǰʱСֵڵڼ + + //ʼK + while(1) + { + tmp = NULL; + //ʼ飬ҵʵĽڵ + for(i =0;ivalue > vec[i]->value) + { + tmp = vec[i]; + pos =i; + } + } + } + //ʼ⴦ͷڵ + if(head == NULL) + { + head = tmp; + cur = head; + } + else + { + cur->next = tmp; + cur= cur->next; + } + + //ѡеҪɾղŵԪ + vec[pos] = vec[pos]->next; + if(vec[pos] == NULL) + flag[pos] =0; + + //жǷеĽڵ㶼Ѿѡ + for(i=0;i=flag.size()) + break; + } + return head; + +} + + +int main() +{ + int array1[]={1,4,7,8,13,19}; + int array2[]={5,8,9,10,12,15,17,22,23}; + int array3[]={3,6,11,16,17,18,21,24}; + int array4[]={2,14,20,25}; + vector vec(4); + int i; + + Init_List(vec[0],array1,sizeof(array1)/sizeof(int)); + Init_List(vec[1],array2,sizeof(array2)/sizeof(int)); + Init_List(vec[2],array3,sizeof(array3)/sizeof(int)); + Init_List(vec[3],array4,sizeof(array4)/sizeof(int)); + + List* head = Merge_k(vec); + print_list(head); + return 0; +} diff --git "a/jun_algorithm/doc/cpp/link/\345\215\225\351\223\276\350\241\250\347\232\204\346\216\222\345\272\217\357\274\210\345\275\222\345\271\266\357\274\211.cpp" "b/jun_algorithm/doc/cpp/link/\345\215\225\351\223\276\350\241\250\347\232\204\346\216\222\345\272\217\357\274\210\345\275\222\345\271\266\357\274\211.cpp" new file mode 100644 index 0000000000..f55c795aa1 --- /dev/null +++ "b/jun_algorithm/doc/cpp/link/\345\215\225\351\223\276\350\241\250\347\232\204\346\216\222\345\272\217\357\274\210\345\275\222\345\271\266\357\274\211.cpp" @@ -0,0 +1,230 @@ +#include +#include +using namespace std; + +/* + ʹù鲢 +*/ +typedef struct list_node List; +struct list_node +{ + struct list_node* next; + int value; +}; + +void print_list(List* list) +{ + List* tmp=list; + while(tmp != NULL) + { + cout<value<next; + } +} + +/* +ʼList 1~nֲ뵽 +*/ +void Init_List(List*& head,int* array,int n) +{ + head = NULL; + List* tmp; + List* record; + + for(int i=1;i<=n;i++) + { + tmp = new List; + tmp->next = NULL; + tmp->value = array[i-1]; + if(head == NULL) + { + head = tmp; + record = head; + } + else + { + record->next = tmp; + record = tmp; + } + } +} + +// +int Len_list(List* list) +{ + if(list == NULL) + return 0; + else + return Len_list(list->next)+1; +} + +void FindMid(List*& list,List*& pre,List*& last) +{ + pre = list; + last = list->next; + while(last != NULL && last->next !=NULL) + { + pre = pre->next; + last = last->next; + if(last->next != NULL) + last = last->next; + + } + last = pre->next; + pre->next = NULL; + pre = list; +} + +//ϲ +void Merge(List*& list,List*& pre,List*& last) +{ + if(pre == NULL) + { + list = last; + return; + } + if(last == NULL) + { + list =pre; + return; + } + List* cur; + List* tmp; + + if(pre->value > last->value) + swap(pre,last); + //ʼսLastеĽڵ뵽pre + list = pre; + cur = pre; + while(cur->next != NULL && last != NULL) + { + if(cur->next->value > last->value)//Ԫ + { + tmp = last->next; + last->next = cur->next; + cur->next = last; + cur = last; + last = tmp; + } + else + cur =cur->next; + } + if(last != NULL) + cur->next = last; +} + +//һĺϲαָ +void Merge_sec(List*& list,List*& pre,List*& last) +{ + List* tmp = new List; + list = tmp; + while(pre != NULL && last != NULL) + { + if(pre->value < last->value) + { + tmp->next = pre; + pre = pre->next; + } + else + { + tmp->next = last; + last = last->next; + } + tmp = tmp->next; + } + if(last != NULL) + tmp->next = last; + else + tmp->next = pre; + list = list->next; +} +/* +鲢˼ +*/ +void MergeSort(List*& list) +{ + if(list == NULL || list->next == NULL) + return ; + //ҵм + List* pre = NULL; + List* last = NULL; + FindMid(list,pre,last);//һListмֳprelast + + MergeSort(pre);//鲢ʹǰ벿 + MergeSort(last);//鲢ʹú벿 + Merge(list,pre,last);//ֵϲ +} + +/* +鲢ڶʵ +*/ + +List* Merge(List* first,List* second) +{ + List* head = NULL; + List* current = NULL; + if(first == NULL) + return second; + if(second == NULL) + return first; + if(first->value > second->value) + { + current = first; + first = second; + second = current; + + } + head = first; + current = first; + first = first->next; + //ʼսsecondĽڵ뵽first + while(first != NULL && second != NULL) + { + List* temp = NULL; + if(first->value > second->value) + { + temp = second->next; + current->next = second; + second->next = first; + current = second; + second = temp; + } + else + { + current = first; + first = first->next; + } + } + if(first == NULL) + current->next = second; + return head; +} + +List* MergeSort(List* list,int size) +{ + if(size == 0 | size == 1) + return list; + //м + List* middle = list; + int i; + for(i =1;inext; + + List* temp = middle->next; + middle->next =NULL; + middle = temp; + + List* left = MergeSort(list,i); + List* right = MergeSort(middle,size-i); + return Merge(right,left); +} + +int main() +{ + int array[]={7,4,9,15,2,1,6,10,12,11}; + List* head; + Init_List(head,array,sizeof(array)/sizeof(int)); + head = MergeSort(head,10); + print_list(head); + return 0; +} diff --git "a/jun_algorithm/doc/cpp/link/\345\215\225\351\223\276\350\241\250\350\212\202\347\202\271\347\232\204\344\272\244\345\217\211\351\207\215\346\216\222.cpp" "b/jun_algorithm/doc/cpp/link/\345\215\225\351\223\276\350\241\250\350\212\202\347\202\271\347\232\204\344\272\244\345\217\211\351\207\215\346\216\222.cpp" new file mode 100644 index 0000000000..0400c13533 --- /dev/null +++ "b/jun_algorithm/doc/cpp/link/\345\215\225\351\223\276\350\241\250\350\212\202\347\202\271\347\232\204\344\272\244\345\217\211\351\207\215\346\216\222.cpp" @@ -0,0 +1,132 @@ +#include +#include +using namespace std; + +/* +ҪΪ +*/ + +typedef struct list_node List; +struct list_node +{ + struct list_node* next; + int value; +}; + +void print_list(List* list) +{ + List* tmp=list; + while(tmp != NULL) + { + cout<value<next; + } +} + +/* +ʼList 1~nֲ뵽 +*/ +void Init_List(List*& head,int* array,int n) +{ + head = NULL; + List* tmp; + List* record; + + for(int i=1;i<=n;i++) + { + tmp = new List; + tmp->next = NULL; + tmp->value = array[i-1]; + if(head == NULL) + { + head = tmp; + record = head; + } + else + { + record->next = tmp; + record = tmp; + } + } +} + +// +int Len_list(List* list) +{ + if(list == NULL) + return 0; + else + return Len_list(list->next)+1; +} + +/* +ķת +*/ +void Reverse(List*& list) +{ + List* tmp = NULL; + List* cur = list; + List* next = list->next; + while(next != NULL) + { + cur->next = tmp; + tmp = cur; + cur = next; + next = next->next; + } + cur->next = tmp; + list = cur; +} + +/* +һ֣Ȼ +ؼż +*/ + +void Reorder_list(List*& list) +{ + List* first = list; + List* second; + List* tmp_first,*tmp_second; + //Ҫнڵĸָ + int len = Len_list(first); + int i; + if(len%2 == 0) + { + for(i=1;inext; + } + else + { + for(i=1;inext; + } + second = first->next; + first->next = NULL; + //зת + Reverse(second); + + //¹滮 + first = list; + //ʼкϲͬʱsecondĸ϶firstĽڵ + while(second != NULL) + { + tmp_first = first->next; + tmp_second = second->next; + first->next= second; + second->next = tmp_first; + second = tmp_second; + first = tmp_first; + } //ܷʹαָ뽫 +} + +int main() +{ + int array[]={1,2,3,4,5,6,7,8,9,10,11}; + List* head; + Init_List(head,array,sizeof(array)/sizeof(int)); + + Reorder_list(head); + print_list(head); + return 0; +} diff --git "a/jun_algorithm/doc/cpp/link/\345\270\246\347\216\257\347\232\204\345\215\225\351\223\276\350\241\250\344\270\255\345\205\245\347\216\257\347\232\204\347\254\254\344\270\200\344\270\252\350\212\202\347\202\271.cpp" "b/jun_algorithm/doc/cpp/link/\345\270\246\347\216\257\347\232\204\345\215\225\351\223\276\350\241\250\344\270\255\345\205\245\347\216\257\347\232\204\347\254\254\344\270\200\344\270\252\350\212\202\347\202\271.cpp" new file mode 100644 index 0000000000..1cda993743 --- /dev/null +++ "b/jun_algorithm/doc/cpp/link/\345\270\246\347\216\257\347\232\204\345\215\225\351\223\276\350\241\250\344\270\255\345\205\245\347\216\257\347\232\204\347\254\254\344\270\200\344\270\252\350\212\202\347\202\271.cpp" @@ -0,0 +1,70 @@ +//֪һдڻ뻷еĵһڵ + +ListNode* GetFirstNodeInCircle(ListNode* phead) +{ + if(phead == NULL || phead->next == NULL) + { + return NULL; + } + + ListNode* pfast = phead; + ListNode* pslow = phead; + //жǷڻ + while(pfast != NULL && pfast->next != NULL) + { + pslow = pslow->next; + pfast = pfast->next->next; + if(pslow == pfast) + break; + } + if(pfast == NULL || pfast->next == NULL) + return NULL; + + //ڻָ붼ͬٶǰΪһڵ + pfast = phead; + while(pslow != pfast) + { + pslow= pslow->next; + pfast = pfast->next; + } + return pslow; +} + +//һҪɾеĽڵ +typedef boolk (*remove_fn)(ListNode* node); + +ListNode* remove_if(ListNode* head,remove_fn rm) +{ + for(ListNode* prev= NULL,*curr = head;curr != NULL) + { + ListNode* next = curr->next; + if(rm(curr)) + { + if(prev) + prev->next = next; + else + head= next; + delete curr; + } + else + prev= curr; + curr = next; + } + return head; +} + +// (ʹöָɾеĽڵ)Linuxں˴룩 +void remove_if(ListNode** head,remove_if rm) +{ + for(ListNode** curr = head;*curr;) + { + ListNode* entry = *curr; + if(rm(entry)) + { + *curr = entry->next; + delete entry; + } + else + curr = &entry->next; + } +} diff --git "a/jun_algorithm/doc/cpp/link/\347\272\246\347\221\237\345\244\253\347\216\257.cpp" "b/jun_algorithm/doc/cpp/link/\347\272\246\347\221\237\345\244\253\347\216\257.cpp" new file mode 100644 index 0000000000..6a69355e1c --- /dev/null +++ "b/jun_algorithm/doc/cpp/link/\347\272\246\347\221\237\345\244\253\347\216\257.cpp" @@ -0,0 +1,47 @@ +#include +#include +#include +using namespace std; + +// Լɪ⣬ʹSTLеList +int Joseph(list& ring,int k) +{ + list::iterator itr = ring.begin(),temp; + int m; + //ڵ1ͻһֱɾȥ + while(ring.size()>1) + { + m =1; + //жϵǰǷҪλ + if(itr == ring.end()) + itr = ring.begin(); + //ҺʵĽڵɾ + while(m ring; + for(i=1;i<=9;i++) + ring.insert(ring.begin(),i); + cout< +using namespace std; + +typedef struct list_node ListNode; + +struct list_node +{ + struct list_node* next; + int value; +}; + +/* +ʼList 1~nֲ뵽 +*/ +void Init_List(ListNode*& head,int* array,int n) +{ + head = NULL; + ListNode* tmp; + ListNode* record; + + for(int i=1;i<=n;i++) + { + tmp = new ListNode; + tmp->next = NULL; + tmp->value = array[i-1]; + if(head == NULL) + { + head = tmp; + record = head; + } + else + { + record->next = tmp; + record = tmp; + } + } +} + +void print_list(ListNode* list) +{ + ListNode* tmp = list; + while(tmp != NULL) + { + cout<value<next; + } +} + +//ҵеKڵ +ListNode* GetKthNode(ListNode* phead,int k) +{ + //KļǴ1ʼ + if(k == 0 || phead == NULL) + return NULL; + + ListNode* pAhead = phead; + ListNode* pBehind = phead; + //ǰָߵKڵ + while(k>1 && pAhead != NULL) + { + pAhead = pAhead->next; + k--; + } + //ڵСKֱӷNULL + if(k>1 || pAhead == NULL) + return NULL; + //ǰָһǰߣֱǰָָһڵ + while(pAhead->next != NULL) + { + pBehind = pBehind->next; + pAhead = pAhead->next; + } + return pBehind;//ָָĽڵǵKڵ +} + +//βͷӡʹõݹķ +void RPrintList(ListNode* phead) +{ + if(phead == NULL) + return ; + else + { + RPrintList(phead->next); + cout<value<next != NULL) + { + pfast = pfast->next->next; + pslow = pslow->next; + if(pslow == pfast) + return true; + } + return false; +} + +/* +һͷָpheadһɾĽڵָ룬 +O(1)ʱ临Ӷɾ˽ڵ +*/ +void Delete(ListNode* phead,ListNode* tobedelete) + { + if(tobedelete == NULL || phead == NULL) + return; + ListNode* temp = phead; + + //һڵݸƵڵ㣬Ȼɾһڵ + if(tobedelete->next != NULL) + { + tobedelete->value = tobedelete->next->value; + ListNode* temp = tobedelete->next; + tobedelete->next = tobedelete->next->next; + delete temp; + } + else //Ҫɾһڵ + { + if(phead == tobedelete)//ֻһڵ + { + phead = NULL; + delete tobedelete; + + } + else + { + ListNode* pnode = phead; + while(pnode->next != tobedelete)//ҵڶڵ + pnode =pnode->next; + pnode->next = NULL; + delete tobedelete; + } + } + } + +int main() +{ + int array[]={1,2,3,4,5,6,7,8,9,10}; + ListNode* list; + Init_List(list,array,sizeof(array)/sizeof(int)); +// print_list(list); + Delete(list,list->next->next->next); + print_list(list); + return 0; +} diff --git "a/jun_algorithm/doc/cpp/link/\351\223\276\350\241\250\347\232\204\346\236\204\351\200\240\345\222\214\347\277\273\350\275\254 .cpp" "b/jun_algorithm/doc/cpp/link/\351\223\276\350\241\250\347\232\204\346\236\204\351\200\240\345\222\214\347\277\273\350\275\254 .cpp" new file mode 100644 index 0000000000..252799420b --- /dev/null +++ "b/jun_algorithm/doc/cpp/link/\351\223\276\350\241\250\347\232\204\346\236\204\351\200\240\345\222\214\347\277\273\350\275\254 .cpp" @@ -0,0 +1,101 @@ +#include +using namespace std; + +typedef struct list_node ListNode; + +struct list_node +{ + struct list_node* next; + int value; +}; + +/* +ʼList 1~nֲ뵽 +*/ +void Init_List(ListNode*& head,int* array,int n) +{ + head = NULL; + ListNode* tmp; + ListNode* record; + + for(int i=1;i<=n;i++) + { + tmp = new ListNode; + tmp->next = NULL; + tmp->value = array[i-1]; + if(head == NULL) + { + head = tmp; + record = head; + } + else + { + record->next = tmp; + record = tmp; + } + } +} + +void print_list(ListNode* list) +{ + ListNode* tmp = list; + while(tmp != NULL) + { + cout<value<next; + } +} + +//нڵĸ +int GetListLength(ListNode* phead) +{ + if(phead == NULL) + return 0; + int length = 0; + ListNode* current = phead; + while(current != NULL) + { + length++; + current = current->next; + } + return length; +} + +//ݹķij +int Len_list(ListNode* list) +{ + if(list == NULL) + return 0; + else + return Len_list(list->next)+1; +} + + +//ת +ListNode* ReverseList(ListNode* phead) +{ + //Ϊջֻһڵ㣬跭תֱӷͷڵ + if(phead == NULL | phead->next == NULL) + return phead; + ListNode* preverse = NULL;//תͷָ룬ʼΪNULL + ListNode* current = phead; + while(current != NULL) + { + ListNode* temp = current; + current = current->next; + temp->next = preverse;//ǰڵ¼ǰ + preverse = temp; + } + return preverse; +} +int main() +{ + int array[]={1,2,3,4,5,6,7,8,9,10}; + ListNode* list; + Init_List(list,array,sizeof(array)/sizeof(int)); + print_list(list); + list = ReverseList(list); + print_list(list); + + return 0; +} diff --git "a/jun_algorithm/doc/cpp/permutation/\345\205\253\347\232\207\345\220\216\351\227\256\351\242\230.cpp" "b/jun_algorithm/doc/cpp/permutation/\345\205\253\347\232\207\345\220\216\351\227\256\351\242\230.cpp" new file mode 100644 index 0000000000..a2b0eb4a94 --- /dev/null +++ "b/jun_algorithm/doc/cpp/permutation/\345\205\253\347\232\207\345\220\216\351\227\256\351\242\230.cpp" @@ -0,0 +1,71 @@ +#include +#include +using namespace std; +/* +ĿҪ +8*8ĹϰڷŰ˸ʺʹ䲻ܻ๥ +Ҳ˵ʺ󲻵ôͬһСͬһлͬһԽ +жַ +*/ + +/* +˻ʺ +*/ +int g_number=0; + void Print(int ColumnIndex[] , int length) + { + cout< +#include +using namespace std; +/* +ȫ +ַabcΪ +ȹ̶aַbcȫУ֮ +ѵһַaͺbõbac̶һַbַac +УȻcŵһλ.... +*/ + +int count =0;//¼и +void Permutation(char* str,int begin) +{ + if(str[begin] == '\0') + { + cout<& vec,int begin,int index) +{ + int i; + for(i = begin;i& vec,int begin,int end) +{ + int i=0; + if(begin >= end) + { + for(i=0;i vec(3); + int i; + for(i=0;i +#include +using namespace std; + +/* +ǵݹķʵȫ +˼·ʹSTLе˼룬Ӻǰһڵһڵ +һԪСڵڶԪأ*i < *ii,ӺǰҵһԪ*j +ʹ*j > *i,Ȼ󽻻*i*j,Ȼ󽻻*iiʼ*iiڣ +ĩβ +*/ +void Rserve(vector& vec,int begin,int end) +{ + while(begin <= end) + { + swap(vec[begin],vec[end]); + begin++; + end--; + } +} + +bool FindPair(vector& vec,int& first,int& second) +{ + int last = vec.size()-1; + for(;last>0;last--) + { + second = last; + first = last-1; + if(vec[first] < vec[second]) + return true; + } + return false; +} + +bool next_premutation(vector& vec) +{ + int first,second,index; + if(FindPair(vec,first,second)) + { + index = vec.size()-1; + for(;index>=first;index--) + { + if(vec[index] > vec[first]) + break; + } + swap(vec[index],vec[first]); + Rserve(vec,second,vec.size()-1); + return true; + } + return false; +} + +int main() +{ + vector vec(3); + int i; + for(i=0;i +#include +using namespace std; + +//ð ӴС +void Bulldle(int* array,int num) +{ + int i,j,temp; + for(i=0;i array[j]) + { + temp = array[i]; + array[i] = array[j]; + array[j] = temp; + flag =1; + } + } +} +int main() +{ + int array[]={7,5,2,9,1,3}; + Bulldle2(array,6); + int i; + for(i=0;i +#include + +using namespace std; + +/* +ĿҪ +a[0,mid-1]a[mid,num-1] 鲢ʹ +ռ临ӶΪO(1) +*/ + +/* +˼·ͬһкϲΪһ ʹòʽ +벿ֵԪز뵽ǰ벿 Ժ벿ֵÿһԪ ǰ벿ҵ +ʵλ Ȼ루ڲ +*/ + +void Merge2(int* array,int begin,int end) +{ + int middle = begin + (end-begin)/2; + + int i= begin; + int temp; + + //벿еԪǰ + while(middle <= end) + { + temp = array[middle];//Ԫ + if(array[i] < array[middle]) //ҵʵλ + { + i++; + } + else //вIJ + { + int index = middle; + while(index != i) + { + array[index] = array[index-1]; + index--; + } + array[i++] = temp; + middle++; + } + + } +} //ܷپ + +/* +ԭع鲢˼ +һ飬Ѿõ鲻ʹöĿռ佫 +кϲ ռֱΪA BAҵһB[0]Ԫز¼ΪA[i] +BҵһA[i]Ԫز¼ΪB[j] οռн Ȼͱ +*/ + +//Գƽ +void Revere(int* array,int begin,int end) +{ + int temp; + while(begin < end) + { + temp = array[begin]; + array[begin]=array[end]; + array[end] = temp; + begin++; + end--; + } +} + +//ת +/* +arrayΪת +begin Ϊʼλ +middleת +end Ϊ +*/ +void Rotate_right(int* array,int begin,int middle,int end) +{ + Revere(array,begin,middle); + Revere(array,middle+1,end); + Revere(array,begin,end); +} + +//ԭغϲ +void Merge_second(int* array,int begin,int end) +{ + //[begin,mid-1] [mid,end]ֱ + int mid = begin + (end-begin)/2+1; + int i = begin; + int index; + //ֱеԪ ôоͺϲ + while(mid <= end && i +#include + +// +void HeapAdjust(int* array,int s,int length) +{ + int temp = array[s];//Ԫ + int child = 2*s+1;//ڵӵλ + + //ʼ + while(child < length) + { + //ҺӴӣҵȵǰڵĺӽڵ + if(child+1 < length&& array[child] < array[child+1]) + child++; + //ϴĺӴڴĽڵ + if(array[s] < array[child]) + { + array[s] = array[child];//ôϴĽڵ + s = child;//´ڵλ + child = 2*s+1;//´ڵ + } + + else + break; + array[s] = temp; + + } +} + +// +void HeapSort(int* array,int length) +{ + int i; + // + for(i=(length-1)/2;i>=0;i--) + { + HeapAdjust(array,i,length); + } + + //һԪؿʼне + for(i=length-1;i>0;i--) + { + //ѶԪغͶһԪ + int tmp = array[i]; + array[i] = array[0]; + array[0] = tmp; + //ÿνԪ֮󣬾Ҫµ + HeapAdjust(array,0,i); + } +} + +int main() +{ + int array[]={3,4,5,1,9,8,6,2,7,10}; + HeapSort(array,10); + int i; + for(i=0;i<10;i++) + printf("%d\n",array[i]); + return 0; +} diff --git "a/jun_algorithm/doc/cpp/sort/\345\275\222\345\271\266\346\216\222\345\272\217.cpp" "b/jun_algorithm/doc/cpp/sort/\345\275\222\345\271\266\346\216\222\345\272\217.cpp" new file mode 100644 index 0000000000..6d5180927c --- /dev/null +++ "b/jun_algorithm/doc/cpp/sort/\345\275\222\345\271\266\346\216\222\345\272\217.cpp" @@ -0,0 +1,56 @@ +#include +#include + +//ϲ +void Mergearray(int* a,int left,int mid,int right,int* temp) +{ + int i = left,j = mid+1; + int m = mid,n = right; + int k=0; + //·鲢 + while(i<=m && j<=n) + { + if(a[i]<=a[j]) + temp[k++] = a[i++]; + else + temp[k++] = a[j++]; + } + //ʣԪ + while(i<=m) + temp[k++] = a[i++]; + while(j<=n) + temp[k++] = a[j++]; + + //ʱпĿ + for(i=0;i +#include + +//һijһ׼㻮Ϊ +int Partition(int* array,int left,int right) +{ + int key = array[right];//һԪΪ׼ + int i = left-1; + int temp; + + //ʼԻ׼Ϊ׼ָ + for(int j = left;j= key) + high--; + swap(&array[low],&array[high]); + + //ǰҵһʵֵͺĽ + while(low< high && array[low] <= key) + ++low; + swap(&array[low],&array[high]); + } + + return low; +} + +//ڶַָµĿ +void quicksort2(int* array,int left,int right) +{ + int i,j,key; + if(left < right) + { + i = left; + j = right; + key = array[i];//ߵԪΪֵĻ׼ + do + { + while(array[j] > key && i +using namespace std; + +// ˼룺һѾõУΪһԪҺʵIJλã +void InsertSort(int* array,int n) +{ + int i,j; + int temp; + + //ӵڶԪؿʼв ΪǰõҺʵλ + for(i=1;i=0;j--) + if(array[j] > temp) + array[j+1] = array[j]; + else + break; + + //ҵʵλú䵱ǰֵ + array[j+1] = temp; + } + + for(i=0;i +#include +#include +#include +using namespace std; + +/* +жһַɵǷϷ +ʹջ˼ ,жջǷΪ +*/ +bool isValidParenthess(string& str) +{ + stack st; + int i; + char tmp; + //ʼջݽṹַ + for(i=0;i& st,int value) +{ + int tmp; + //ջΪգôֱӽǰԪѹջ + if(st.size()==0) + st.push(value); + else //ջԪأôȡеԪأȻٽԪѹ + { + tmp = st.top(); + st.pop(); + Push_Bottom(st,value); + st.push(tmp); + } +} + +/* +תջ +*/ +void Reverse_st(stack& st) +{ + int tmp; + if(st.size()<=1) + return; + else + { + //ȡջԪ + tmp = st.top(); + st.pop(); + //ݹãתʣԪ + Reverse_st(st); + //ȡԪطջײ + Push_Bottom(st,tmp); + } +} + +int main() +{ + string str("{()[]{}}"); + cout< st; + int i; + int tmp; + for(i=0;i<5;i++) + st.push(i); + + Reverse_st(st); + // Push_Bottom(st,5); + while(!st.empty()) + { + tmp = st.top(); + cout< +#include +#include +using namespace std; + +/* +Ϸƥ䳤 +*/ + +/* +ʹһboolѾƥַ +ֱǵijȾĽֻҪα飬ʱ临ӶΪO(n) +*/ +int LongestValidParentheses(string s) { + bool *a = new bool[s.length()]; + //memset(a, false, s.length()); + stack st; + for (int i = 0; i < s.length(); ++i) { + if (s[i] == '(') { + st.push(i); + } else if (s[i] == ')' && !st.empty()) { + a[i] = true; + a[st.top()] = true; + st.pop(); + } + } + int max_len = 0, cur_len = 0; + for (int i = 0; i < s.length(); ++i) { + if (a[i]) + cur_len++; + else + cur_len = 0; + max_len = max(max_len, cur_len); + } + return max_len; +} + +/* +ʹջ¼ijһַеλãڵǰַջλõ +ַƥ䣬ôԸջǷΪжϵǰƥ +ȻĿƥ +*/ +int LongestValidParentheses2(string s) { + stack st; + int pos; + int maxlen = 0; + for(int i = 0 ; i < s.size() ; i++) + { + if(s[i] == '(') st.push(i); + else // ')' + { + if(!st.empty() && s[st.top()]=='(') + { + + st.pop(); + if(st.empty()) + pos = i+1; + else + pos = i-st.top(); + if(maxlen < pos) + maxlen = pos; + } + else + st.push(i); + } + + } + return maxlen; +} + +int main() +{ + string str=")()())"; + cout< +#include +#include +#include +#include +using namespace std; + +/* +ʽ⣬ջݽṹҪעַ֮ת +*/ + +//ַתΪ +int strtoi(string& s) +{ + if(s.length() == 0) + return 0; + int i=0,flag=1,result=0; + if(s[0]=='-') + { + flag =-1; + i++; + } + if(s[0]=='+') + { + i++; + } + for(;i &tokens) +{ + stack sk; + int result =0,i,temp; + string first,second; + //ʼַ + for(i=0;i tokens(array,array+sizeof(array)/sizeof(array[0])); + cout< +#include +#include +#include +using namespace std; +/* +һʽ· +*/ +string SimplifyPath(string& str) +{ + string result; + stack st; + if(str.length() == 0 || str[0] !='/') + return result; + int i; + char tmp; + st.push(str[0]); + for(i=1;i +#include +#include +#include +#include +using namespace std; + +/* +Ļ +*/ +typedef struct Bin_tree BinTree; +struct Bin_tree +{ + int value; + BinTree* right; + BinTree* left; +}; +/* + +*/ +BinTree* InsertNode(BinTree* root,int data) +{ + BinTree* newnode = new BinTree; + newnode->value = data; + newnode->right = NULL; + newnode->left = NULL; + if(root == NULL) + { + root = newnode; + } + else + { + BinTree* parent = root; + // BinTree* cur = NULL; + while(parent != NULL) + { + if(parent->value < data) + { + if(parent->right == NULL) + break; + else + parent = parent->right; + } + else + { + if(parent->left == NULL) + break; + else + parent = parent->left; + } + } + if(parent->value < data) + parent->right = newnode; + else + parent->left = newnode; + } + return root; +} + + +/** +Ҷֵ +*/ + +BinTree* Max(BinTree* root) +{ + if(root == NULL) + return NULL; + BinTree* temp = root; + while(temp->left != NULL) + { + temp = temp->left; + } + return temp; +} + +/* +ҶСֵ +*/ +BinTree* Min(BinTree* root) +{ + if(root == NULL) + return NULL; + BinTree* temp = root; + while(temp->right != NULL) + { + temp = temp->right; + } + return temp; +} + +/* +ڶвԪ +*/ +BinTree* Search(BinTree* root,BinTree*& parent,int value) +{ + if(root == NULL ) + return NULL; + BinTree* temp = root; + parent = NULL; + while(temp != NULL) + { + if(temp->value == value) + break; + else + { + parent = temp; + if(temp->value > value) + temp = temp->left; + else + temp = temp->right; + } + } + if(temp == NULL) + { + parent = NULL; + return NULL; + } + return temp; +} + + +/* +ɾֵijڵ +*/ +void Delete(BinTree*& root,int value) +{ + BinTree* delnode = NULL; + if(root == NULL) + return ; + BinTree* temp = root; + BinTree* parent = NULL; + //ҪҸԪǷ + while(temp != NULL) + { + if(temp->value == value) + break; + else + { + parent = temp; + if(temp->value > value) + temp = temp->left; + else + temp = temp->right; + } + } + //ûҵɾĽڵ㣬ôֱӷ + if(temp == NULL) + return ; + delnode = temp; + /* + ɾĽڵ㱻ҵɾIJΪ + һǴɾڵûкӣôֱɾ + ڶǴɾڵһӣпҲпҺӣ + Ǵɾڵ + */ + /* + һֱɾ˽ڵ + */ + if(delnode->right == NULL && delnode->left == NULL) + { + if(delnode == root) + { + root = NULL; + } + if(parent && parent->left == delnode) + { + parent->left = NULL; + } + if(parent && parent->right == delnode) + { + parent->right = NULL; + } + delete delnode; + } + //˽ڵһ + if(delnode->right != NULL && delnode->left == NULL) + { + if(parent != NULL) + { + if(parent->left == delnode) + parent->left = delnode->right; + else if(parent->right == delnode) + parent->right = delnode->right; + } + else + { + root = delnode->right; + } + delete delnode; + } + if(delnode->left != NULL && delnode->right == NULL) + { + if(parent != NULL) + { + if(parent->left == delnode) + parent->left = delnode->left; + else if(parent->right == delnode) + parent->right = delnode->left; + } + else + { + root = delnode->left; + } + delete delnode; + } + //ڵ㶼Ϊ һʵֵ + if(delnode->left != NULL && delnode->right != NULL) + { + temp = delnode->right; + parent = delnode; + while(temp->left != NULL) + { + parent = temp; + temp = temp->left; + } + delnode->value = temp->value; + parent->left = temp->right; + delete temp; + } +} + +int main() +{ + int array[]={30,22,45,15,24,40,50,10}; + BinTree* root = NULL; + for(int i=0;i +#include +#include +#include +#include +using namespace std; + +/* +Ļ +*/ + +typedef struct Bin_tree BinTree; +struct Bin_tree +{ + int value; + BinTree* right; + BinTree* left; +}; +/* + +*/ +BinTree* InsertNode(BinTree* root,int data) +{ + BinTree* newnode = new BinTree; + newnode->value = data; + newnode->right = NULL; + newnode->left = NULL; + if(root == NULL) + { + root = newnode; + } + else + { + BinTree* parent = root; + // BinTree* cur = NULL; + while(parent != NULL) + { + if(parent->value < data) + { + if(parent->right == NULL) + break; + else + parent = parent->right; + } + else + { + if(parent->left == NULL) + break; + else + parent = parent->left; + } + } + if(parent->value < data) + parent->right = newnode; + else + parent->left = newnode; + } + return root; +} + +/* +α ʹöл˫˶ +*/ + +void FloorVisit(BinTree* root) +{ + if(root == NULL) + return ; + deque dequ; + dequ.push_back(root); + BinTree* current = NULL; + //ʼ + while(dequ.size()) + { + current = dequ.front(); + dequ.pop_front(); + cout<value<left != NULL) + dequ.push_back(current->left); + if(current->right != NULL) + dequ.push_back(current->right); + } +} + +/* +нڵĸ +*/ +int NumOfTree(BinTree* root) +{ + if(root == NULL) + return 0; + return (NumOfTree(root->right)+NumOfTree(root->left)) +1; +} + +/* + +*/ + +int Depth(BinTree* root) +{ + if(root == NULL) + return 0; + int left = Depth(root->left); + int right = Depth(root->right); + return (left > right ? left:right)+1; +} + +/* +Ŀ ĿȾǽڵDzнڵĸ +*/ +void Width(BinTree* root,int& width) +{ + if(root == NULL) + return; + deque< BinTree*> dequ; + dequ.push_back(root); + BinTree* current; + width =0; + int tempWidth= dequ.size(); + //ʼҿ + while(tempWidth) + { + if(tempWidth > width) + width = tempWidth; + while(tempWidth) + { + current = dequ.front(); + dequ.pop_front(); + if(current->left != NULL) + dequ.push_back(current->left); + if(current->right != NULL) + dequ.push_back(current->right); + tempWidth--; + } + tempWidth = dequ.size(); + } +} + +/* +иҶӽڵ· +*/ +void Routh(BinTree* root,vector& vec) +{ + if(root == NULL) + return ; + vec.push_back(root); + if(root->left == NULL && root->right == NULL) + { + vector::iterator itr = vec.begin(); + for(;itr!=vec.end();itr++) + { + cout<<(*itr)->value<left,vec); + Routh(root->right,vec); + vec.pop_back(); +} + +/* +жöǷṹͬ +*/ +bool JudeSame(BinTree* first,BinTree* second) +{ + if(first == NULL && second == NULL) + return true; + if((first == NULL && second!=NULL) || (first != NULL && second == NULL)) + return false; + if(first->value != second->value) + return false; + return (JudeSame(first->left,second->left)&&(JudeSame(first->right,second->right))); + +} + +/* +ľת +*/ +void Reverse(BinTree* root) +{ + if(root == NULL) + return; + BinTree* temp = NULL; + temp = root->right; + root->right = root->left; + root->left = temp; + //ݹúʹת + Reverse(root->left); + Reverse(root->right); +} + +int main() +{ + int array[]={30,22,45,15,24,40,50,10}; + BinTree* root = NULL; + for(int i=0;i vec; + Routh(root,vec); + return 0; +} diff --git "a/jun_algorithm/doc/cpp/tree/\344\272\214\345\217\211\346\240\221\347\232\204\351\201\215\345\216\206.cpp" "b/jun_algorithm/doc/cpp/tree/\344\272\214\345\217\211\346\240\221\347\232\204\351\201\215\345\216\206.cpp" new file mode 100644 index 0000000000..c1f6e269e5 --- /dev/null +++ "b/jun_algorithm/doc/cpp/tree/\344\272\214\345\217\211\346\240\221\347\232\204\351\201\215\345\216\206.cpp" @@ -0,0 +1,262 @@ +#include +#include +#include +#include +using namespace std; + +/* +Ĵ +ĵݹ +ķǵݹ +*/ +typedef struct Bin_Tree BinTree; +struct Bin_Tree +{ + int value; + BinTree* right; + BinTree* left; +}; + +/* + +*/ +BinTree* InsertNode(BinTree* root,int value) +{ + BinTree* newnode = new BinTree; + newnode->value = value; + newnode->right = NULL; + newnode->left = NULL; + //һµĽڵ㣬Ҫ˽ڵ뵽ʵλ + if(root == NULL) + { + root = newnode; + } + else + { + //Һʵλ + BinTree* parent = root; + while(parent != NULL) + { + if(parent->value < value) + { + if(parent->right == NULL) + break; + else + parent = parent->right; + } + else + { + if(parent->left == NULL) + break; + else + parent = parent->left; + } + } + if(parent->value < value) + parent->right = newnode; + else + parent->left = newnode; + } + return root; +} + +/* +ݹķǰ +*/ +void Preorder(BinTree* root) +{ + if(root == NULL) + return ; + cout<value<left); + Preorder(root->right); +} + +/* +ݹķ +*/ +void Inorder(BinTree* root) +{ + if(root == NULL) + return ; + Inorder(root->left); + cout<value<right); +} + +/* +ݹķ +*/ +void Postorder(BinTree* root) +{ + if(root == NULL) + return ; + Postorder(root->left); + Postorder(root->right); + cout<value< s; + s.push(root); + while(!s.empty()) + { + BinTree* temp = s.top(); + cout<value<<" "; + s.pop(); + if(temp->right) + s.push(temp->right); + if(temp->left) + s.push(temp->left); + } +} + + +/*ڶַ*/ + +void Preorder_Nonrecursive1(BinTree* root) +{ + if(root == NULL) + return ; + stack s; + BinTree* cur = root; + while(cur != NULL || !s.empty()) + { + while(cur != NULL) + { + cout<value<<" "; + s.push(cur); + cur = cur->left; + } + if(!s.empty()) + { + cur = s.top(); + s.pop(); + cur = cur->right; + } + } +} + +/*ǵݹ*/ +void Inorder_Nonre(BinTree* root) +{ + if(root == NULL) + return ; + BinTree* cur = root; + stack s; + while(cur != NULL || !s.empty()) + { + while(cur != NULL) + { + s.push(cur); + cur = cur->left; + } + if(!s.empty()) + { + cur = s.top(); + s.pop(); + cout<value<<" "; + cur = cur->right; + } + } +} + +/* +ڶַ +*/ +void Inorder_Nonre2(BinTree* root) +{ + if(root == NULL) + return ; + stack st; + BinTree* p = root; + while(p!= NULL || !st.empty()) + { + if(p != NULL) + { + st.push(p); + p = p->left; + } + else + { + p=st.top(); + st.pop(); + cout<value<right; + } + } +} + +/* +ǵݹĺ +*/ +void Postorder_Nonre(BinTree* root) +{ + stack s; + BinTree* cur = root; + BinTree* pre = NULL;//ָǰһʵĽڵ + while(cur != NULL || !s.empty()) + { + while( cur != NULL) //һֱֱΪ + { + s.push(cur); + cur = cur->left; + } + cur = s.top(); + //ǰڵҺΪջѾʣʵǰڵ + if(cur->right == NULL || cur->right == pre) + { + cout<value<<" "; + pre = cur; + s.pop(); + cur = NULL; + } + else + cur = cur->right;//Һ + } +} + +/* +ڶַ +*/ +void Postorder_Nonre2(BinTree* root) +{ + //ʹ˫ջ + stack s1,s2; + BinTree* cur;//ָǰҪĽڵ + s1.push(root); + //ջΪʱ + while(!s1.empty()) + { + cur = s1.top(); + s1.pop(); + s2.push(cur); + if(cur->left) + s1.push(cur->left); + if(cur->right) + s1.push(cur->right); + } + while(!s2.empty()) + { + cout<value<<" "; + s2.pop(); + } +} + +int main() +{ + BinTree* root =NULL; + int array[]={10,6,14,4,8,12,16}; + for(int i=0;i +#include +using namespace std; + +/* +жһǷΪĺ + +ںһҪһԪǸڵ㣬ȸԪش +ȸԪС,Ȼݹ +*/ + +bool helper_verify(vector& vec,int begin,int end) +{ + int i,j; + if(end-begin <=1) + return true; + for(i=begin;i vec[end]) + break; + for(j=i;j& vec) +{ + if(vec.size() <=1) + return true; + return helper_verify(vec,0,vec.size()-1); +} + + + +int main() +{ + int array[]={1,3,2,5,6,8,7,4}; + vector vec(array,array+sizeof(array)/sizeof(int)); + cout< +#include +#include + +/* +ʵֵĴ롢ѯ +*/ + +#define MAX_CHILD 26 + +typedef struct Tree +{ + int count;//ǸýڵǷγһʣcount=0 ˵ + struct Tree* child[MAX_CHILD]; + +}Node,*Trie_node; +/* +childDZʾÿжСдĸΪ26 +*/ + +/* +Trieڵ +*/ +Node* CreateTrie() +{ + Node* node = (Node*)malloc(sizeof(Node)); + memset(node,0,sizeof(Node)); + return node; +} + +/* +Trieڵ +*/ +void Insert_node(Trie_node root,char* str) +{ + if(root == NULL || *str == '\0') + return ; + Node* t = root; + while(*str != '\0') + { + if(t->child[*str-'a'] == NULL) + { + Node* tmp = CreateTrie(); + t->child[*str-'a'] = tmp; + } + t = t->child[*str-'a']; + str++; + } + t->count++; +} + +/* +TrieеIJ +*/ +void search_str(Trie_node root,char* str) +{ + if(NULL == root || *str == '\0') + { + printf("tire is empty\n"); + return; + } + Node* t = root; + while(*str != '\0') + { + if(t->child[*str-'a'] != NULL) + { + t = t->child[*str-'a']; + str++; + } + else + break; + } + if(*str == '\0') + { + if(t->count == 0) + printf("ַ\n"); + else + printf("ַ\n"); + } + else + printf("ַ\n"); +} + +/* +ͷֵĿռ +*/ +void del(Trie_node root) +{ + int i; + for(i =0;ichild[i] != NULL) + del(root->child[i]); + } + free(root); +} + + +int main() +{ + int i,n; + char str[20]; + printf("ҪtrieĴС"); + scanf("%d",&n); + Trie_node root = NULL; + root =CreateTrie(); + if(root == NULL) + printf("Trieʧ\n"); + for(i=0;i +#include +using namespace std; +/* +һЧز뵽 +*/ +typedef struct Bin_tree BinTree; +struct Bin_tree +{ + int value; + BinTree* right; + BinTree* left; +}; + +/*BST*/ +void InsertFromArray(BinTree*& root,int* array,int start,int end) +{ + if(start >end) + return ; + //ʼһڵ + root = new BinTree; + root->left = NULL; + root->right = NULL; + //ҵмΪڵ + int mid = start+(end-start)/2; + root->value = array[mid]; + //Ȼݹô + InsertFromArray(root->left,array,start,mid-1); + // + InsertFromArray(root->right,array,mid+1,end); +} + +/* +ݹ +*/ +void Inorder(BinTree* root) +{ + if(root == NULL) + return; + Inorder(root->left); + cout<value<right); +} + +int main() +{ + int array[]={1,2,3,4,5,6,7,8,9}; + BinTree* root = NULL; + InsertFromArray(root,array,0,8); + Inorder(root); + return 0; +} diff --git "a/jun_algorithm/doc/cpp/tree/\346\237\245\346\211\276\346\240\271\345\210\260\345\217\266\345\255\220\347\232\204\345\233\272\345\256\232\350\267\257\345\276\204\345\200\274.cpp" "b/jun_algorithm/doc/cpp/tree/\346\237\245\346\211\276\346\240\271\345\210\260\345\217\266\345\255\220\347\232\204\345\233\272\345\256\232\350\267\257\345\276\204\345\200\274.cpp" new file mode 100644 index 0000000000..44637c234e --- /dev/null +++ "b/jun_algorithm/doc/cpp/tree/\346\237\245\346\211\276\346\240\271\345\210\260\345\217\266\345\255\220\347\232\204\345\233\272\345\256\232\350\267\257\345\276\204\345\200\274.cpp" @@ -0,0 +1,176 @@ +#include +#include +#include +#include +using namespace std; + +/* +Ҷ·֮Ϊֵָ +*/ + +using namespace std; +typedef struct Bin_tree BinTree; +struct Bin_tree +{ + int value; + BinTree* right; + BinTree* left; +}; +/* + +*/ +BinTree* InsertNode(BinTree* root,int data) +{ + BinTree* newnode = new BinTree; + newnode->value = data; + newnode->right = NULL; + newnode->left = NULL; + if(root == NULL) + { + root = newnode; + } + else + { + BinTree* parent = root; + // BinTree* cur = NULL; + while(parent != NULL) + { + if(parent->value < data) + { + if(parent->right == NULL) + break; + else + parent = parent->right; + } + else + { + if(parent->left == NULL) + break; + else + parent = parent->left; + } + } + if(parent->value < data) + parent->right = newnode; + else + parent->left = newnode; + } + return root; +} +/* + ݹ ǰ +*/ +void Preorder(BinTree* root) +{ + if(root == NULL) + return ; + cout<value <left); + Preorder(root->right); +} + +/* + ݹ +*/ +void Inorder(BinTree* root) +{ + if(root == NULL) + return ; + Inorder(root->left); + cout<value<right); +} + +//Ҷ·Ϊijһֵ +void helper(BinTree* root,int key,int cur,vector& vec) +{ + if(root == NULL) + return ; + cur+=root->value; + vec.push_back(root->value); + if(root->left == NULL && root->right == NULL && cur == key) + { + int i; + for(i=0;ileft !=NULL) + { + helper(root->left,key,cur,vec); + vec.pop_back(); + } + + if(root->right !=NULL) + { + helper(root->right,key,cur,vec); + vec.pop_back(); + } +} + +void PathSum(BinTree* root,int key) +{ + int cur=0; + if(root== NULL) + return ; + vector vec; + helper(root,key,cur,vec); + +} +//ڶַ +bool PathSum_second(BinTree* root,int value) +{ + if(root == NULL) + return 0; + if(root->left == NULL && root->right == NULL &&root->value == value) + return 1; + return PathSum_second(root->left,value-root->value)||PathSum_second(root->right,value-root->value); +} + +/* +ӸҶ·У·ֵ +*/ +void helper_sum(BinTree* root,vector& path,int& maxsum) +{ + if(root == NULL) + return; + path.push_back(root->value); + if(root->left == NULL && root->right == NULL) + { + int tmp =0; + for(int i=0;ileft,path,maxsum); + helper_sum(root->right,path,maxsum); + path.pop_back(); +} + +int MaxPathToLeaf(BinTree* root) +{ + if(root ==NULL) + return 0; + vector path; + int maxsum =0; + helper_sum(root,path,maxsum); + return maxsum; +} + + +int main() +{ + BinTree* root = NULL; + BinTree* second = NULL; + int array[]={10,6,14,3,16,5,8}; + int i; + for(i=0;i& path) +{ + if(root == NULL) + return false; + if(root == node) + return true; + else if(GetNodePath(root->left,node,path)) + { + path.push_back(root->left); + return true; + } + else if(GetNodePath(root->right,node,path)) + { + path,push_back(root->right); + return true; + } + return false; +} + + +BinTree* GetLastNode(vector& path1,vector& path2) +{ + vector::iterator iter1 = path1.begin(); + vector::iterator iter2 = path2.begin(); + BinTree* plast; + while(iter1 != path1.end() && iter2 != path2.end()) + { + if(*iter1 == *iter2) + plast = *iter1; + else + break; + iter1++; + iter2++; + } + return plast; +} + +BinTree* GetParent(BinTree* root,BinTree* node1,BinTree* node2) +{ + if(root == NULL || node1 == NULL || node2 == NULL) + return NULL; + vector path1; + GetNodePath(root,node1,path1); + + vector path2; + GetNodePath(root,node2,path2); + return GetLastNode(path1,path2); +} + +/* +ڶַ +ͷʼһнڵڵеһȣôνڵĿ +ڵ㣬ҪôڵҪô +ڵһһôǰڵǹڵ +ֶôڵ +ֶôڵ +*/ +bool FindNode(BinTree* root,BinTree* node) +{ + if(root == NULL) + return false; + if(root == node) + return true; + return (FindNode(root->left,node) || FindNode(root->right,node)); +} + +BinTree* LCP(BinTree* root,BinTree* first,BinTree* second) +{ + if(root == first || root== second) + return root; + bool isLeft = false; + isLeft = FindNode(root->left,first); + if(isLeft) + { + if(FindNode(root->left,second)) + return LCP(root->left,first,second); + else + return root; + } + else + { + if(FindNode(root->right,second)) + return LCP(root->right,first,second); + else + return root; + } +} + +/* +һּ +ҵ˽ڵ㣬left != NULL,ôһrightǷΪNULL +right != NULL ,ô˵жҵ˹ڵ +ô˵͵ĹڵǵǰĽڵ +*/ + +BinTree* LCP2(BinTree8 root,BinTree* first,BinTree* second) +{ + if(root == first || root== second) + return root; + if(root == NULL) + return NULL; + BinTree* left = LCP2(root->left,first,second); + BinTree* right = LCP2(root->right,first,second); + if(left == NULL) + return right; + else if(right == NULL) + return left; + else + return root; +} diff --git "a/jun_algorithm/doc/cpp/tree/\346\261\202\350\212\202\347\202\271\347\232\204\346\234\200\345\244\247\350\267\235\347\246\273.cpp" "b/jun_algorithm/doc/cpp/tree/\346\261\202\350\212\202\347\202\271\347\232\204\346\234\200\345\244\247\350\267\235\347\246\273.cpp" new file mode 100644 index 0000000000..a57e310bde --- /dev/null +++ "b/jun_algorithm/doc/cpp/tree/\346\261\202\350\212\202\347\202\271\347\232\204\346\234\200\345\244\247\350\267\235\347\246\273.cpp" @@ -0,0 +1,196 @@ +#include +#include +using namespace std; + +/* +нڵ +*/ +typedef struct Bin_tree BinTree; +struct Bin_tree +{ + int value; + BinTree* right; + BinTree* left; +}; +/* + +*/ +BinTree* InsertNode(BinTree* root,int data) +{ + BinTree* newnode = new BinTree; + newnode->value = data; + newnode->right = NULL; + newnode->left = NULL; + if(root == NULL) + { + root = newnode; + } + else + { + BinTree* parent = root; + // BinTree* cur = NULL; + while(parent != NULL) + { + if(parent->value < data) + { + if(parent->right == NULL) + break; + else + parent = parent->right; + } + else + { + if(parent->left == NULL) + break; + else + parent = parent->left; + } + } + if(parent->value < data) + parent->right = newnode; + else + parent->left = newnode; + } + return root; +} +/* + ݹ ǰ +*/ +void Preorder(BinTree* root) +{ + if(root == NULL) + return ; + cout<value <left); + Preorder(root->right); +} + +/* + ݹ +*/ +void Inorder(BinTree* root) +{ + if(root == NULL) + return ; + Inorder(root->left); + cout<value<right); +} + +/* +ڵԶ룬ľDZߵĸ +*/ +/* +ۣ +ԶڵһһôԶڵ +ǰڵľԶڵ㵽ǰڵľ룬Զ +Խ˸ڵ㡣 +ڶԶڵ㶼 +Զڵ㶼 +*/ + +/* +distancerootΪ +ֵrootΪԶ +*/ +int Distance(BinTree* root,int& depth) +{ + if(root == NULL) + { + depth = 0; + return 0; + } + int left,right; + int left_dis = Distance(root->left,left); + int right_dis = Distance(root->right,right); + depth = (left > right ? left: right)+1; + + return max(left_dis,max(right_dis,left+right)); +} + +/* +ΪգȶΪ0 +ΪգҪô룬Ҫô +룬Ҫôڵ+ڵеڵ + +*/ + +int MaxDepth(BinTree* root) +{ + int depth =0; + if(root != NULL) + { + int left_depth = MaxDepth(root->left); + int right_depth = MaxDepth(root->right); + depth = (left_depth > right_depth? left_depth: right_depth); + depth++; + } + return depth; +} + +int MaxDistance(BinTree* root) +{ + int maxdis = 0; + if(root != NULL) + { + maxdis = MaxDepth(root->right) + MaxDepth(root->left); + int left_dis = MaxDistance(root->left); + int right_dis = MaxDistance(root->right); + int temp = left_dis > right_dis? left_dis : right_dis; + maxdis = temp > maxdis ? temp:maxdis; + } + return maxdis; +} + + +int GetMaxDistance(BinTree* root,int& maxLeft,int& maxRight) +{ + //maxLeftеĽڵ뵱ǰڵԶ + //maxRight еĽڵ뵱ǰڵԶ + if(root == NULL) + { + maxLeft =0; + maxRight = 0; + return 0; + } + int maxLL,maxLR,maxRL,maxRR; + int maxDisLeft,maxDisRight; + if(root->left != NULL) + { + maxDisLeft = GetMaxDistance(root->left,maxLL,maxLR); + maxLeft = max(maxLL,maxLR)+1; + } + else + { + maxDisLeft = 0; + maxLeft = 0; + } + if(root->right != NULL) + { + maxDisRight = GetMaxDistance(root->right,maxRL,maxRR); + maxRight = max(maxRL,maxRR)+1; + } + else + { + maxDisRight = 0; + maxRight = 0; + } + return max(max(maxDisLeft,maxDisRight),maxLeft+maxRight); +} + +int main() +{ + + BinTree* root = NULL; + int array[]={10,6,14,4,8,12,16,5}; + int i; + for(i=0;i +#include +using namespace std; + +/* +һǰкй +*/ +typedef struct tree_node Tree; +struct tree_node +{ + Tree* left; + Tree* right; + int value; +}; + +Tree* helper(vector& pre,int pre_begin,int pre_end,vector& inorder,int in_begin,int in_end) +{ + Tree* root = NULL; + int mid; + int i; + if(pre_end - pre_begin <0) + return NULL; + else + { + for(i = in_begin;i<=in_end;i++) + if(inorder[i] == pre[pre_begin]) + break; + if(i > in_end) + return NULL; + + //ڵ + root = new Tree; + root->value = pre[pre_begin]; + root->left = helper(pre,pre_begin+1,pre_begin+1+i-in_begin,inorder,in_begin,i-1); + root->right = helper(pre,pre_begin+1+i-1-in_begin+1,pre_end,inorder,i+1,in_end); + return root; + } +} + +Tree* createBinTree(vector& pre,vector& inorder) +{ + if(pre.size() == 0 || inorder.size()== 0) + return NULL; + return helper(pre,0,pre.size()-1,inorder,0,inorder.size()-1); +} + + +/* +ͺб +*/ +Tree* helpersecond(vector& inorder,int in_begin,int in_end,vector& post,int post_begin,int post_end) +{ + Tree* root = NULL; + int mid; + int i; + if(in_begin > in_end) + { + return NULL; + } + else + { + for(i= in_begin;i<=in_end;i++) + if(inorder[i] == post[post_end]) + break; + if(i > in_end) + return NULL; + root = new Tree; + root->value = post[post_end]; + root->left = helpersecond(inorder,in_begin,i-1,post,post_begin,post_begin+i-1-in_begin); + root->right = helpersecond(inorder,i+1,in_end,post,post_begin+i-in_begin,post_end-1); + + } + return root; +} + +Tree* createBinTree2(vector& inorder,vector& post) +{ + if(inorder.size() == 0|| post.size()==0) + return NULL; + return helpersecond(inorder,0,inorder.size()-1,post,0,post.size()-1); +} + +/*ǰ*/ +void print_pre(Tree* tree) +{ + if(tree != NULL) + { + cout<value<<" "<left); + print_pre(tree->right); + } +} + +/**/ +void print_inorder(Tree* tree) +{ + if(tree != NULL) + { + print_inorder(tree->left); + cout<value<right); + } +} + +void print_post(Tree* root) +{ + if(root != NULL) + { + print_post(root->left); + print_post(root->right); + cout<value< preorder(array1,array1+sizeof(array1)/sizeof(int)); + + int array[]={1,2,3,4,5,6,7,8}; + vector inorder(array,array+sizeof(array)/sizeof(int)); + + int array2[]={1,3,2,5,6,8,7,4}; + vector postorder(array2,array2+sizeof(array2)/sizeof(int)); + + Tree* root = createBinTree(preorder,inorder); + print_inorder(root); + cout<<"==========="< +#include +#include +using namespace std; + +/* +תΪ +תΪ˫ +*/ + +using namespace std; +typedef struct list_node List; +struct list_node +{ + struct list_node* next; + int value; +}; + + +typedef struct Bin_tree BinTree; +struct Bin_tree +{ + int value; + BinTree* right; + BinTree* left; +}; + +void print_list(List* list) +{ + List* tmp=list; + while(tmp != NULL) + { + cout<value<next; + } +} + +/* +ʼList 1~nֲ뵽 +*/ +void Init_List(List*& head,int* array,int n) +{ + head = NULL; + List* tmp; + List* record; + + for(int i=1;i<=n;i++) + { + tmp = new List; + tmp->next = NULL; + tmp->value = array[i-1]; + if(head == NULL) + { + head = tmp; + record = head; + } + else + { + record->next = tmp; + record = tmp; + } + } +} + +int Len_list(List* list) +{ + if(list == NULL) + return 0; + else + return Len_list(list->next)+1; +} + +void Inorder(BinTree* root) +{ + if(root == NULL) + return ; + Inorder(root->left); + cout<value<right); +} + +/* +һĵתΪ +*/ +List* FindMid(List*& list,List*& head,List*& tail) +{ + List* fast = head; + List* slow = head; + while(fast != NULL && fast->next != tail) + { + slow = slow->next; + fast = fast->next; + if(fast != NULL &&fast->next != tail) + fast = fast->next; + } + return slow; +} + +BinTree* helper(List*& root,List*& head,List*& tail) +{ + BinTree* node = NULL; + if(head == tail || head == NULL) + return node; + List* mid = FindMid(root,head,tail); + List* next = mid->next; + node = new BinTree; + node->value= mid->value; + node->left = helper(root,head,mid); + node->right = helper(root,next,tail); + return node; +} + +BinTree* ConvertBST(List*& list) +{ + BinTree* root = NULL; + if(list == NULL) + return root; + List* head = list; + List* tail = NULL; + root = helper(list,head,tail); + return root; +} + +/* +һתΪ˫ +*/ +BinTree* head =NULL; +void helper(BinTree* root,BinTree*& pre) +{ + if(root == NULL && root == NULL) + return ; + + helper(root->left,pre); + if(head == NULL) + head = root; + if(pre == NULL) + pre = root; + else + { + root->left = pre; + pre->right = root; + pre = root; + } + //cout<value<<" "<right,pre); +} +BinTree* SearchTreeConverstToList(BinTree* root) +{ + BinTree* pre = NULL;//¼һָ + helper(root,pre); + return head; +} + +void helper_second(BinTree* root,BinTree*& head,BinTree*& tail) +{ + if(root==NULL || (root->left == NULL && root->right == NULL)) + { + head = root; + tail = root; + return; + } + BinTree* left_head = NULL; + BinTree* left_tail = NULL; + BinTree* right_head = NULL; + BinTree* right_tail = NULL; + + helper_second(root->left,left_head,left_tail); + helper_second(root->right,right_head,right_tail); + + if(left_head == NULL) + head = root; + else + { + head = left_head; + left_tail->right = root; + root->left = left_tail; + } + if(right_head == NULL) + tail = root; + else + { + tail = right_tail; + root->right = right_head; + right_head->left = root; + } +} +/* +ڶַ +*/ +BinTree* ConverstToList(BinTree* root) +{ + BinTree* head=NULL; + BinTree* tail = NULL; + helper_second(root,head,tail); + return head; +} +int main() +{ + int array[]={1,2,3,4,5,6,7,8,9,10}; + List* list; + Init_List(list,array,sizeof(array)/sizeof(int)); + BinTree* root = ConvertBST(list); + print_list(list); + Inorder(root); + return 0; +} diff --git a/jun_algorithm/pom.xml b/jun_algorithm/pom.xml new file mode 100644 index 0000000000..2a5088eae5 --- /dev/null +++ b/jun_algorithm/pom.xml @@ -0,0 +1,58 @@ + + + 4.0.0 + + com.jun.plugin + jun_algorithm + 1.0-SNAPSHOT + jun_algorithm + + + UTF-8 + + + + + junit + junit + 4.12 + + + org.slf4j + slf4j-api + 1.6.2 + + + org.slf4j + slf4j-log4j12 + 1.6.2 + + + org.apache.commons + commons-lang3 + 3.1 + + + org.springframework + spring-webmvc + 4.3.0.RELEASE + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + ${project.build.sourceEncoding} + + + + + + \ No newline at end of file diff --git a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/GcdAndLcm.java b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/GcdAndLcm.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/GcdAndLcm.java rename to jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/GcdAndLcm.java diff --git a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/InverseArray.java b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/InverseArray.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/InverseArray.java rename to jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/InverseArray.java diff --git a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/MonkeyEatFruit.java b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/MonkeyEatFruit.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/MonkeyEatFruit.java rename to jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/MonkeyEatFruit.java diff --git a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/SeriesSum.java b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/SeriesSum.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/SeriesSum.java rename to jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/SeriesSum.java diff --git a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/TestInverse.java b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/TestInverse.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/TestInverse.java rename to jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/TestInverse.java diff --git a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/TwoSum.java b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/TwoSum.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/TwoSum.java rename to jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/TwoSum.java diff --git a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/_026RemoveDuplicates.java b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/_026RemoveDuplicates.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/_026RemoveDuplicates.java rename to jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/_026RemoveDuplicates.java diff --git a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/_040Climb.java b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/_040Climb.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/_040Climb.java rename to jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/_040Climb.java diff --git a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/_189RotateArray.java b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/_189RotateArray.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/_189RotateArray.java rename to jun_algorithm/src/main/java/com/jun/plugin/algorithm/array/_189RotateArray.java diff --git a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/datastructure/jcollections/IArrayList.java b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/datastructure/jcollections/IArrayList.java similarity index 99% rename from jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/datastructure/jcollections/IArrayList.java rename to jun_algorithm/src/main/java/com/jun/plugin/algorithm/datastructure/jcollections/IArrayList.java index 7369390c95..279b0e2847 100644 --- a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/datastructure/jcollections/IArrayList.java +++ b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/datastructure/jcollections/IArrayList.java @@ -6,7 +6,7 @@ * 实现自己的ArrayList * * @param - * @author Wujun + * @author hztaoran */ public class IArrayList implements IList { diff --git a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/datastructure/jcollections/IList.java b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/datastructure/jcollections/IList.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/datastructure/jcollections/IList.java rename to jun_algorithm/src/main/java/com/jun/plugin/algorithm/datastructure/jcollections/IList.java diff --git a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/datastructure/tree/AVLTree.java b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/datastructure/tree/AVLTree.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/datastructure/tree/AVLTree.java rename to jun_algorithm/src/main/java/com/jun/plugin/algorithm/datastructure/tree/AVLTree.java diff --git a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/datastructure/tree/BTree.java b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/datastructure/tree/BTree.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/datastructure/tree/BTree.java rename to jun_algorithm/src/main/java/com/jun/plugin/algorithm/datastructure/tree/BTree.java diff --git a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/hash/ConsistentHashWithVN.java b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/hash/ConsistentHashWithVN.java similarity index 99% rename from jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/hash/ConsistentHashWithVN.java rename to jun_algorithm/src/main/java/com/jun/plugin/algorithm/hash/ConsistentHashWithVN.java index 4c2ec4dd41..efb3c40bfb 100644 --- a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/hash/ConsistentHashWithVN.java +++ b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/hash/ConsistentHashWithVN.java @@ -8,7 +8,7 @@ /** * 带虚拟结点的一致性Hash算法 * - * @author Wujun + * @author hztaoran */ public class ConsistentHashWithVN { /** diff --git a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/hash/ConsistentHashWithoutVN.java b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/hash/ConsistentHashWithoutVN.java similarity index 99% rename from jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/hash/ConsistentHashWithoutVN.java rename to jun_algorithm/src/main/java/com/jun/plugin/algorithm/hash/ConsistentHashWithoutVN.java index abaa280298..952b16ca15 100644 --- a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/hash/ConsistentHashWithoutVN.java +++ b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/hash/ConsistentHashWithoutVN.java @@ -5,7 +5,7 @@ /** * 不带虚拟结点的一致性Hash算法 - * @author Wujun + * @author 哓哓 * */ public class ConsistentHashWithoutVN { diff --git a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/hash/HashUtil.java b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/hash/HashUtil.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/hash/HashUtil.java rename to jun_algorithm/src/main/java/com/jun/plugin/algorithm/hash/HashUtil.java diff --git a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/palindrome/PalindromeString.java b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/palindrome/PalindromeString.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/palindrome/PalindromeString.java rename to jun_algorithm/src/main/java/com/jun/plugin/algorithm/palindrome/PalindromeString.java diff --git a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/palindrome/_125ValidPalindrome.java b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/palindrome/_125ValidPalindrome.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/palindrome/_125ValidPalindrome.java rename to jun_algorithm/src/main/java/com/jun/plugin/algorithm/palindrome/_125ValidPalindrome.java diff --git a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/BubbleSort.java b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/BubbleSort.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/BubbleSort.java rename to jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/BubbleSort.java diff --git a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/HalfSearch.java b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/HalfSearch.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/HalfSearch.java rename to jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/HalfSearch.java diff --git a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/HeapSort.java b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/HeapSort.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/HeapSort.java rename to jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/HeapSort.java diff --git a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/InsertionSort.java b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/InsertionSort.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/InsertionSort.java rename to jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/InsertionSort.java diff --git a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/MergeSort.java b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/MergeSort.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/MergeSort.java rename to jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/MergeSort.java diff --git a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/QuickSort.java b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/QuickSort.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/QuickSort.java rename to jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/QuickSort.java diff --git a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/RadixSort.java b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/RadixSort.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/RadixSort.java rename to jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/RadixSort.java diff --git a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/SelectSort.java b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/SelectSort.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/SelectSort.java rename to jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/SelectSort.java diff --git a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/ShellSort.java b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/ShellSort.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/ShellSort.java rename to jun_algorithm/src/main/java/com/jun/plugin/algorithm/sort/ShellSort.java diff --git a/jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/util/GCD.java b/jun_algorithm/src/main/java/com/jun/plugin/algorithm/util/GCD.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/java/com/jun/plugin/algorithm/util/GCD.java rename to jun_algorithm/src/main/java/com/jun/plugin/algorithm/util/GCD.java diff --git a/jun_java_plugins/jun_algorithm/src/main/scala/com/scala/oj/Knapsack.scala b/jun_algorithm/src/main/scala/com/scala/oj/Knapsack.scala similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/scala/com/scala/oj/Knapsack.scala rename to jun_algorithm/src/main/scala/com/scala/oj/Knapsack.scala diff --git a/jun_java_plugins/jun_algorithm/src/main/scala/com/scala/sort/BubbleSortScala.scala b/jun_algorithm/src/main/scala/com/scala/sort/BubbleSortScala.scala similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/scala/com/scala/sort/BubbleSortScala.scala rename to jun_algorithm/src/main/scala/com/scala/sort/BubbleSortScala.scala diff --git a/jun_java_plugins/jun_algorithm/src/main/scala/com/scala/sort/HalfSearchScala.scala b/jun_algorithm/src/main/scala/com/scala/sort/HalfSearchScala.scala similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/scala/com/scala/sort/HalfSearchScala.scala rename to jun_algorithm/src/main/scala/com/scala/sort/HalfSearchScala.scala diff --git a/jun_java_plugins/jun_algorithm/src/main/scala/com/scala/sort/HeapSortScala.scala b/jun_algorithm/src/main/scala/com/scala/sort/HeapSortScala.scala similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/scala/com/scala/sort/HeapSortScala.scala rename to jun_algorithm/src/main/scala/com/scala/sort/HeapSortScala.scala diff --git a/jun_java_plugins/jun_algorithm/src/main/scala/com/scala/sort/InsertSortScala.scala b/jun_algorithm/src/main/scala/com/scala/sort/InsertSortScala.scala similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/scala/com/scala/sort/InsertSortScala.scala rename to jun_algorithm/src/main/scala/com/scala/sort/InsertSortScala.scala diff --git a/jun_java_plugins/jun_algorithm/src/main/scala/com/scala/sort/MergeSortScala.scala b/jun_algorithm/src/main/scala/com/scala/sort/MergeSortScala.scala similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/scala/com/scala/sort/MergeSortScala.scala rename to jun_algorithm/src/main/scala/com/scala/sort/MergeSortScala.scala diff --git a/jun_java_plugins/jun_algorithm/src/main/scala/com/scala/sort/QuickSortScala.scala b/jun_algorithm/src/main/scala/com/scala/sort/QuickSortScala.scala similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/scala/com/scala/sort/QuickSortScala.scala rename to jun_algorithm/src/main/scala/com/scala/sort/QuickSortScala.scala diff --git a/jun_java_plugins/jun_algorithm/src/main/scala/com/scala/sort/SelectSortScala.scala b/jun_algorithm/src/main/scala/com/scala/sort/SelectSortScala.scala similarity index 100% rename from jun_java_plugins/jun_algorithm/src/main/scala/com/scala/sort/SelectSortScala.scala rename to jun_algorithm/src/main/scala/com/scala/sort/SelectSortScala.scala diff --git a/jun_java_plugins/jun_algorithm/src/test/java/com/jun/plugin/algorithm/datastructure/jcollections/IArrayListTest.java b/jun_algorithm/src/test/java/com/jun/plugin/algorithm/datastructure/jcollections/IArrayListTest.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/test/java/com/jun/plugin/algorithm/datastructure/jcollections/IArrayListTest.java rename to jun_algorithm/src/test/java/com/jun/plugin/algorithm/datastructure/jcollections/IArrayListTest.java diff --git a/jun_java_plugins/jun_algorithm/src/test/java/com/jun/plugin/algorithm/datastructure/tree/AVLTreeTest.java b/jun_algorithm/src/test/java/com/jun/plugin/algorithm/datastructure/tree/AVLTreeTest.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/test/java/com/jun/plugin/algorithm/datastructure/tree/AVLTreeTest.java rename to jun_algorithm/src/test/java/com/jun/plugin/algorithm/datastructure/tree/AVLTreeTest.java diff --git a/jun_java_plugins/jun_algorithm/src/test/java/com/jun/plugin/algorithm/datastructure/tree/BTreeTest.java b/jun_algorithm/src/test/java/com/jun/plugin/algorithm/datastructure/tree/BTreeTest.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/test/java/com/jun/plugin/algorithm/datastructure/tree/BTreeTest.java rename to jun_algorithm/src/test/java/com/jun/plugin/algorithm/datastructure/tree/BTreeTest.java diff --git a/jun_java_plugins/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/BubbleSortTest.java b/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/BubbleSortTest.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/BubbleSortTest.java rename to jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/BubbleSortTest.java diff --git a/jun_java_plugins/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/HalfSearchTest.java b/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/HalfSearchTest.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/HalfSearchTest.java rename to jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/HalfSearchTest.java diff --git a/jun_java_plugins/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/HeapSortTest.java b/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/HeapSortTest.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/HeapSortTest.java rename to jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/HeapSortTest.java diff --git a/jun_java_plugins/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/InsertionSortTest.java b/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/InsertionSortTest.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/InsertionSortTest.java rename to jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/InsertionSortTest.java diff --git a/jun_java_plugins/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/MergeSortTest.java b/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/MergeSortTest.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/MergeSortTest.java rename to jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/MergeSortTest.java diff --git a/jun_java_plugins/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/QuickSortTest.java b/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/QuickSortTest.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/QuickSortTest.java rename to jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/QuickSortTest.java diff --git a/jun_java_plugins/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/RadixSortTest.java b/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/RadixSortTest.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/RadixSortTest.java rename to jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/RadixSortTest.java diff --git a/jun_java_plugins/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/SelectSortTest.java b/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/SelectSortTest.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/SelectSortTest.java rename to jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/SelectSortTest.java diff --git a/jun_java_plugins/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/ShellSortTest.java b/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/ShellSortTest.java similarity index 100% rename from jun_java_plugins/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/ShellSortTest.java rename to jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/ShellSortTest.java diff --git a/jun_java_plugins/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/SortPerformanceTest.java b/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/SortPerformanceTest.java similarity index 99% rename from jun_java_plugins/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/SortPerformanceTest.java rename to jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/SortPerformanceTest.java index ca6b053dd2..c97c7f629b 100644 --- a/jun_java_plugins/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/SortPerformanceTest.java +++ b/jun_algorithm/src/test/java/com/jun/plugin/algorithm/sort/SortPerformanceTest.java @@ -23,7 +23,7 @@ /** * 改进的希尔排序效果显著 * - * @author Wujun + * @author 哓哓 */ public class SortPerformanceTest { private static final int MAX_SIZE = 10000; diff --git a/jun_aliyun_sms/README.md b/jun_aliyun_sms/README.md new file mode 100644 index 0000000000..3a65bfabb7 --- /dev/null +++ b/jun_aliyun_sms/README.md @@ -0,0 +1,30 @@ +#### jun_aliyun_sms,阿里云短信发送Demo +1、阿里云短信发送 +2、阿里云短信发送Demo +3、阿里云短信发送接口 +4、Rest验证码发送接口 + + +#### Installation 安装使用 + +1、配置POM +2、直接参考Demo + + +#### Documents 文档 + +1、秘钥管理地址:https://ak-console.aliyun.com/ +2、SDK下载地址:https://help.aliyun.com/document_detail/55359.html +3、阿里开发人员写的代码和文档:https://bbs.aliyun.com/read/317490.html + + +#### Feature 计划 + +1、提供通用的jar +2、提供通用的API接口 +2、提供后端服务化接口 + + + + + diff --git a/jun_aliyun_sms/aliyun-oss-upload-stream/.gitignore b/jun_aliyun_sms/aliyun-oss-upload-stream/.gitignore new file mode 100644 index 0000000000..67e2eb300f --- /dev/null +++ b/jun_aliyun_sms/aliyun-oss-upload-stream/.gitignore @@ -0,0 +1,3 @@ +node_modules/ +.DS_Store +config.js \ No newline at end of file diff --git a/jun_aliyun_sms/aliyun-oss-upload-stream/LICENSE b/jun_aliyun_sms/aliyun-oss-upload-stream/LICENSE new file mode 100644 index 0000000000..e126b6b079 --- /dev/null +++ b/jun_aliyun_sms/aliyun-oss-upload-stream/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Berwin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/jun_aliyun_sms/aliyun-oss-upload-stream/README.md b/jun_aliyun_sms/aliyun-oss-upload-stream/README.md new file mode 100644 index 0000000000..78645d41e1 --- /dev/null +++ b/jun_aliyun_sms/aliyun-oss-upload-stream/README.md @@ -0,0 +1,165 @@ +# aliyun-oss-upload-stream + +[![NPM Version](https://img.shields.io/npm/v/aliyun-oss-upload-stream.svg)](https://www.npmjs.com/package/aliyun-oss-upload-stream) +[![NPM Downloads](https://img.shields.io/npm/dm/aliyun-oss-upload-stream.svg)](https://www.npmjs.com/package/aliyun-oss-upload-stream) + +用[Aliyun oss](https://github.com/aliyun-UED/aliyun-sdk-js) 的 Multipart upload API 实现的Node.js模块,通过stream的方式上传文件。 + +***官方指定Nodejs模块~*** + +## 为什么使用stream? + +* 使用stream的方式上传文件可以很大程度上降低服务器内存开销。Aliyun官方SDK并没有对stream进行一个完美的封装,所以通常上传文件(Put Object)的流程是客户端上传文件到服务器,服务器把文件数据缓存到内存,等文件全部上传完毕后,一次性上传到Aliyun Oss服务。这样做一旦瞬间上传文件的请求过多,服务器的内存开销会直线上升。而使用stream的方式上传文件的流程是客户端在上传文件数据到服务器的过程中,服务器同时也在把文件数据往Aliyun Oss服务传送,而不需要在服务器上缓存文件数据。 +* 可以上传大文件,根据上传数据方式不同而不同, Put Object 方式 文件最大不能超过 5GB,而使用stream的方式,文件大小不能超过 48.8TB +* 更快的速度,由于传统方式(Put Object方式)是客户端上传完毕文件后,统一上传到Aliyun Oss,而stream的方式基本上客户端上传完毕后,服务器已经把一大半的文件数据上传到Aliyun了,所以速度要快很多 +* 使用更简单,经过封装后,stream的方式使用起来非常的方便,1分钟就可以学会如何使用 + +## 例子 + +```javascript + +var ALY = require('aliyun-sdk'), + fs = require('fs'); + +var ossStream = require('aliyun-oss-upload-stream')(new ALY.OSS({ + accessKeyId: '在阿里云OSS申请的 accessKeyId', + secretAccessKey: '在阿里云OSS申请的 secretAccessKey', + endpoint: 'http://oss-cn-hangzhou.aliyuncs.com', + apiVersion: '2013-10-15' +})); + +var upload = ossStream.upload({ + Bucket: 'Bucket', + Key: 'Key (可以理解为文件名)' +}); + +// 可选配置 +upload.minPartSize(1048576); // 1M,表示每块part大小至少大于1M + +upload.on('error', function (error) { + console.log('error:', error); +}); + +upload.on('part', function (part) { + console.log('part:', part); +}); + +upload.on('uploaded', function (details) { + var s = (new Date() - startTime) / 1000; + console.log('details:', details); + console.log('Completed upload in %d seconds', s); +}); + +var read = fs.createReadStream('./photo.jpg'); +read.pipe(upload); + +var startTime = new Date(); +``` + +## 使用 + +### 初始化 + +```javascript +var ALY = require('aliyun-sdk'); + +var ossStream = require('aliyun-oss-upload-stream')(new ALY.OSS({ + accessKeyId: '在阿里云OSS申请的 accessKeyId', + secretAccessKey: '在阿里云OSS申请的 secretAccessKey', + endpoint: 'http://oss-cn-hangzhou.aliyuncs.com', + apiVersion: '2013-10-15' +})); +``` + +### 上传文件 + +```javascript +var upload = ossStream.upload({ + Bucket: 'Bucket-Name', + Key: 'Key-Name' +}); + +var read = fs.createReadStream('./photo.jpg'); +read.pipe(upload); +``` + +## 操作方法 + +**upload.minPartSize** + +用于调整每次上传一小块数据的大小,不得低于200KB,默认为200KB,如果经常上传大文件,建议用此方法把值调整大一些 + +``` +var upload = ossStream.upload({ + Bucket: 'Bucket-Name', + Key: 'Key-Name' +}); + +// 可选配置 +upload.minPartSize(1048576); // 1M,表示每块part大小至少大于1M + +var read = fs.createReadStream('./photo.jpg'); +read.pipe(upload); +``` + +## 事件 + +**error** + +当上传过程中发生错误,触发error事件,回调函数参数为错误信息 + +```javascript +upload.on('error', function (error) { + console.log('error:', error); +}); +``` +**part** + +上传文件的过程中,会触发part事件,回调函数参数为当前分片的信息 + +```javascript +upload.on('part', function (part) { + console.log('part:', part); +}); +``` + +**uploaded** + +上传成功后触发该事件,回调函数参数为完整的 Object + +```javascript +upload.on('uploaded', function (details) { + console.log('details:', details); +}); + +``` + +## 安装 + +``` +npm i --save aliyun-oss-upload-stream +``` + +PS: 如果大家使用过程中,发现什么问题或者需要添加什么功能,及时通知我哈~ 我会及时更新和发布新版本~ + +## The MIT License (MIT) + +Copyright (c) 2015 Berwin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/jun_aliyun_sms/aliyun-oss-upload-stream/examples/basics/README.md b/jun_aliyun_sms/aliyun-oss-upload-stream/examples/basics/README.md new file mode 100644 index 0000000000..fe6c49e8b1 --- /dev/null +++ b/jun_aliyun_sms/aliyun-oss-upload-stream/examples/basics/README.md @@ -0,0 +1,38 @@ +## 修改配置信息 + +``` +vi upload.js +``` +配置accessKeyId、secretAccessKey、endpoint和Bucket、Key + +``` +var ossStream = require('../lib/aliyun-oss-upload-stream.js')(new ALY.OSS({ + accessKeyId: '在阿里云OSS申请的 accessKeyId', + secretAccessKey: '在阿里云OSS申请的 secretAccessKey', + endpoint: 'http://oss-cn-hangzhou.aliyuncs.com', + apiVersion: '2013-10-15' +})); + +var upload = ossStream.upload({ + Bucket: 'Bucket-Name', + Key: 'Key-Name' +}); +``` + +## 安装依赖 + +``` +npm install +``` + +## 运行 + +``` +node upload.js +``` + +也可以在配置完信息之后直接运行下面的命令 + +``` +npm run upload +``` \ No newline at end of file diff --git a/jun_aliyun_sms/aliyun-oss-upload-stream/examples/basics/package.json b/jun_aliyun_sms/aliyun-oss-upload-stream/examples/basics/package.json new file mode 100644 index 0000000000..609e9836ae --- /dev/null +++ b/jun_aliyun_sms/aliyun-oss-upload-stream/examples/basics/package.json @@ -0,0 +1,30 @@ +{ + "name": "aliyun-oss-upload-stream-examples-simple", + "version": "1.1.0", + "description": "aliyun-oss-upload-stream examples simple", + "main": "./upload.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "upload": "npm install && node upload.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/berwin/aliyun-oss-upload-stream.git" + }, + "keywords": [ + "aliyun", + "oss", + "upload", + "pipe", + "stream" + ], + "author": "Berwin", + "license": "MIT", + "bugs": { + "url": "https://github.com/berwin/aliyun-oss-upload-stream/issues" + }, + "homepage": "https://github.com/berwin/aliyun-oss-upload-stream#readme", + "dependencies": { + "aliyun-sdk": "^1.7.6" + } +} diff --git a/jun_aliyun_sms/aliyun-oss-upload-stream/examples/basics/photo.jpg b/jun_aliyun_sms/aliyun-oss-upload-stream/examples/basics/photo.jpg new file mode 100644 index 0000000000..fce3ee0a39 Binary files /dev/null and b/jun_aliyun_sms/aliyun-oss-upload-stream/examples/basics/photo.jpg differ diff --git a/jun_aliyun_sms/aliyun-oss-upload-stream/examples/basics/upload.js b/jun_aliyun_sms/aliyun-oss-upload-stream/examples/basics/upload.js new file mode 100644 index 0000000000..985257bb88 --- /dev/null +++ b/jun_aliyun_sms/aliyun-oss-upload-stream/examples/basics/upload.js @@ -0,0 +1,35 @@ +'use strict'; + +var ALY = require('aliyun-sdk'), + fs = require('fs'); + +var ossStream = require('../../lib/aliyun-oss-upload-stream.js')(new ALY.OSS({ + accessKeyId: '在阿里云OSS申请的 accessKeyId', + secretAccessKey: '在阿里云OSS申请的 secretAccessKey', + endpoint: 'http://oss-cn-hangzhou.aliyuncs.com', + apiVersion: '2013-10-15' +})); + +var upload = ossStream.upload({ + Bucket: 'Bucket-Name', + Key: 'Key-Name' +}); + +upload.on('error', function (error) { + console.log('error:', error); +}); + +upload.on('part', function (part) { + console.log('part:', part); +}); + +upload.on('uploaded', function (details) { + var s = (new Date() - startTime) / 1000; + console.log('details:', details); + console.log('Completed upload in %d seconds', s); +}); + +var read = fs.createReadStream('./photo.jpg'); +read.pipe(upload); + +var startTime = new Date(); \ No newline at end of file diff --git a/jun_aliyun_sms/aliyun-oss-upload-stream/examples/client-to-server/README.md b/jun_aliyun_sms/aliyun-oss-upload-stream/examples/client-to-server/README.md new file mode 100644 index 0000000000..3c3ae009a6 --- /dev/null +++ b/jun_aliyun_sms/aliyun-oss-upload-stream/examples/client-to-server/README.md @@ -0,0 +1,41 @@ +# 案例 + +## 修改配置信息 + +``` +vim upload.js +``` +配置accessKeyId、secretAccessKey、endpoint和Bucket、Key + +``` +var ossStream = require('../lib/aliyun-oss-upload-stream.js')(new ALY.OSS({ + accessKeyId: '在阿里云OSS申请的 accessKeyId', + secretAccessKey: '在阿里云OSS申请的 secretAccessKey', + endpoint: 'http://oss-cn-hangzhou.aliyuncs.com', + apiVersion: '2013-10-15' +})); + +var upload = ossStream.upload({ + Bucket: 'Bucket-Name', + Key: 'Key-Name' +}); +``` + +## 安装依赖 + +``` +npm install +``` + +## 运行 + +``` +npm start +``` + +## 访问 + +``` +http://127.0.0.1:1995 +``` +在页面上传图片,并查看终端,会在终端打印出上传相关信息 \ No newline at end of file diff --git a/jun_aliyun_sms/aliyun-oss-upload-stream/examples/client-to-server/app.js b/jun_aliyun_sms/aliyun-oss-upload-stream/examples/client-to-server/app.js new file mode 100644 index 0000000000..3cbec97f7c --- /dev/null +++ b/jun_aliyun_sms/aliyun-oss-upload-stream/examples/client-to-server/app.js @@ -0,0 +1,53 @@ +'use strict'; + +var http = require('http'); +var Busboy = require('busboy'); +var ALY = require('aliyun-sdk'); + +var ossStream = require('../../lib/aliyun-oss-upload-stream.js')(new ALY.OSS({ + accessKeyId: '在阿里云OSS申请的 accessKeyId', + secretAccessKey: '在阿里云OSS申请的 secretAccessKey', + endpoint: 'http://oss-cn-hangzhou.aliyuncs.com', + apiVersion: '2013-10-15' +})); + +http.createServer(function(req, res) { + if (req.method === 'POST') { + var busboy = new Busboy({ headers: req.headers }); + busboy.on('file', function(fieldname, file, filename, encoding, mimetype) { + var upload = ossStream.upload({ + Bucket: 'Bucket', + Key: filename + }); + + upload.on('error', function (error) { + console.log('error:', error); + }); + + upload.on('part', function (part) { + console.log('part:', part); + }); + + upload.on('uploaded', function (details) { + console.log('details:', details); + res.writeHead(303, { Connection: 'close', Location: '/' }); + res.end(); + }); + + file.pipe(upload); + }); + + req.pipe(busboy); + } else if (req.method === 'GET') { + res.writeHead(200, { Connection: 'close' }); + res.end('\ +
\ +
\ +
\ + \ +
\ + '); + } +}).listen(1995, function() { + console.log('Listening for requests'); +}); \ No newline at end of file diff --git a/jun_aliyun_sms/aliyun-oss-upload-stream/examples/client-to-server/package.json b/jun_aliyun_sms/aliyun-oss-upload-stream/examples/client-to-server/package.json new file mode 100644 index 0000000000..0ecabe6473 --- /dev/null +++ b/jun_aliyun_sms/aliyun-oss-upload-stream/examples/client-to-server/package.json @@ -0,0 +1,31 @@ +{ + "name": "aliyun-oss-upload-stream-examples-client-to-server", + "version": "1.1.0", + "description": "aliyun-oss-upload-stream examples client-to-server", + "main": "./app.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "start": "node app.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/berwin/aliyun-oss-upload-stream.git" + }, + "keywords": [ + "aliyun", + "oss", + "upload", + "pipe", + "stream" + ], + "author": "Berwin", + "license": "MIT", + "bugs": { + "url": "https://github.com/berwin/aliyun-oss-upload-stream/issues" + }, + "homepage": "https://github.com/berwin/aliyun-oss-upload-stream#readme", + "dependencies": { + "aliyun-sdk": "^1.9.1", + "busboy": "^0.2.13" + } +} diff --git a/jun_aliyun_sms/aliyun-oss-upload-stream/lib/aliyun-oss-upload-stream.js b/jun_aliyun_sms/aliyun-oss-upload-stream/lib/aliyun-oss-upload-stream.js new file mode 100644 index 0000000000..910eb554bf --- /dev/null +++ b/jun_aliyun_sms/aliyun-oss-upload-stream/lib/aliyun-oss-upload-stream.js @@ -0,0 +1,260 @@ +/**! + * Aliyun-oss-upload-stream - lib/index.js + * + * 使用 stream 的方式上传文件 + * + * Authors: + * Berwin (https://github.com/berwin) + */ + +'use strict'; + +var Writable = require('stream').Writable; +var events = require('events'); + +function Client(client) { + if (!client) throw new Error('Must configure an oss client before attempting to create an oss upload stream.'); + + // 安全监测 + if (!(this instanceof Client)) { + return new Client(client); + } + + this.cachedClient = client; +} + +Client.prototype.upload = function (destinationDetails) { + + if (!arguments.length || Object.prototype.toString.call(destinationDetails) !== '[object Object]') throw new Error('Parameter is not correct'); + + var e = new events.EventEmitter(); + var cachedClient = this.cachedClient; + var multipartUploadID = null; + var multipartUploadResult = null; + + // 缓存的buffer数据 + var receivedBuffers = []; + + // 缓存的buffer数据长度 + var receivedBuffersLength = 0; + + // Part 列表,用于数据全部上传成功后,验证Part有效性 + var partIds = []; + + // Part 索引 + var localPartNumber = 0; + + // 用于判断是否 Parts 全部上传完毕(服务器端->阿里云) + var pendingParts = 0; + // 判断是否上传完毕(客户端->服务器端) + var completed = false; + + // 每个part的最小值 + var minPartSize = 204800; + + var ws = new Writable({ + highWaterMark: 4194304 // 4 MB + }); + + // 设置每个part的最小值 + ws.minPartSize = function (partSize) { + if (partSize > minPartSize) { + minPartSize = partSize; + } + return ws; + }; + + ws.getMinPartSize = function () { + return minPartSize; + }; + + ws._write = function (chunk, encoding, next) { + // 缓存buffer + absorbBuffer(chunk); + + // 缓存区数据大小 + var size = Buffer.byteLength(Buffer.concat(receivedBuffers, receivedBuffersLength)); + + /* + * 如果初始化完成,并且当前Part大小大于minPartSize(默认200KB),执行flushPart操作 + * Multipart Upload要求除最后一个Part以外,其他的Part大小都要大于100KB + * 所以如果当前write的大小不够minPartSize的情况下只缓存,不处理数据,直到缓存大小超过minPartSize,在从缓存中取出所有缓存的part数据执行flushPart操作 + */ + if (multipartUploadID && size > minPartSize) { + flushPart(); + } + + // 上传数据前,必须先初始化 + if (!multipartUploadID && !e.listeners('ready').length) { + /* + * 注册ready事件 + * 初始化完成后,只有当 completed 为真并且缓存区有数据时,执行 flushPart 操作 + * + * 1. 为什么只在completed为真并且缓存区有数据时,执行 flushPart 操作? + * 答:因为初始化完成之前,是不会执行 flushPart 操作的, + * 所以如果 客户端->服务端 的传输在初始化之前结束, + * 那么初始化结束后,需要一次性将数据上传到阿里云(一般这种情况发生在小文件) + * + * 但还有一种情况,就是在触发ready事件的时候,状态已经改变,但回调函数还没执行的这一瞬间, + * 客户端->服务端 的传输结束了,此时状态是“初始化完成”,那么 ws.end 与 ws._write 做最后一次 flushPart 操作 + * 因为ready事件已经触发,所以又触发了一次多余的,不必要的flushPart操作,所以需要判断缓存区是否有内容 + * + * 2. 为什么只有completed为真时,执行flushPart操作? + * 答:如果客户端网比较慢,而服务端与阿里云之间通信比较快, + * 那么会出现 初始化完成后,缓存区中的chunk大小 小于 100KB, + * 如果直接上传,会触发阿里云 “除最后一个Part以外,其他的Part大小都要大于100KB” 的限制,从而报错, + * 所以不需要 flushPart 操作,只改变状态就可以,当下一次触发 ws._write 时,如果条件满足会自动进行flushPart操作 + */ + e.once('ready', function () { + if (completed === true && Buffer.byteLength(Buffer.concat(receivedBuffers, receivedBuffersLength)) > 0) { + flushPart(); + } + }); + + // 初始化MultipartUpload + createMultipartUpload(destinationDetails); + } + + next(); + }; + + ws.end = function () { + completed = true; + + // 缓存区数据大小 + var size = Buffer.byteLength(Buffer.concat(receivedBuffers, receivedBuffersLength)); + + /* + * 由于_write只操作缓存区大于 minPartSize(默认200KB) 的数据,所以最后一次或最后几次加在一起的数据不够 minPartSize 的时候,_write并不会做任何处理 + * 所以需要在end的时候,检查当前缓存区是否有没处理完的数据,如果有,则执行最后一次flushPart操作 + */ + if (multipartUploadID && size > 0) { + flushPart(); + } + }; + + /* + * 初始化 Multipart Upload + * 使用 Multipart Upload 模式传输数据前,必须先调用该接口来通知 OSS 初始 化一个 Multipart Upload 事件 + * + * 初始化结束后,触发ready事件 + * @param {Object} Bucket && Key + */ + function createMultipartUpload(details) { + cachedClient.createMultipartUpload(details, function (err, data) { + if (err) return abortUpload(err); + multipartUploadID = data.UploadId; + multipartUploadResult = data; + e.emit('ready'); + }); + } + + /* + * 分块(Part)上传数据 + * flushPart 会从缓存区中取出所有缓存数据,并清空缓存区的数据 + */ + var flushPart = function () { + var chunk = preparePartBuffer(); + localPartNumber = localPartNumber + 1; + pendingParts = pendingParts + 1; + + (function (localPartNumber) { + cachedClient.uploadPart({ + Body: chunk, + Bucket: multipartUploadResult.Bucket, + Key: multipartUploadResult.Key, + UploadId: multipartUploadID, + PartNumber: localPartNumber + }, function (err, result) { + if (err) return abortUpload(err); + + pendingParts = pendingParts - 1; + + var part = { + ETag: result.ETag, + PartNumber: localPartNumber + }; + + partIds[localPartNumber - 1] = part; + + ws.emit('part', part); + + if (!pendingParts && completed) completeUpload(); + }); + })(localPartNumber); + }; + + /* + * 上传成功 + * + * 在将所有数据 Part 都上传完成后,必须调用 Complete Multipart Upload API 来完成整个文件的 Multipart Upload。在执行该操作时,用户必须 供所有有效 的数据 Part 的列表(包括 part 号码和 ETAG);OSS 收到用户 交的 Part 列表后, 会逐一验证每个数据 Part 的有效性。当所有的数据 Part 验证通过后,OSS 将把 这些数据 part 组合成一个完整的 Object。 + * + * @return {Object} ossObject + */ + var completeUpload = function () { + cachedClient.completeMultipartUpload({ + Bucket: multipartUploadResult.Bucket, + Key: multipartUploadResult.Key, + UploadId: multipartUploadID, + CompleteMultipartUpload: { + Parts: partIds + } + }, function (err, result) { + if (err) return abortUpload(err); + ws.emit('uploaded', result); + }); + }; + + /* + * 缓存Buffer + */ + function absorbBuffer(incomingBuffer) { + receivedBuffers.push(incomingBuffer); + receivedBuffersLength += incomingBuffer.length; + } + + /* + * 生成 chunk + * 根据缓存的buffer数据,生成一个新buffer并返回 + * + * @return {Buffer} chunk + */ + function preparePartBuffer() { + var combinedBuffer = Buffer.concat(receivedBuffers, receivedBuffersLength); + receivedBuffers = []; + receivedBuffersLength = 0; + + return combinedBuffer; + } + + /* + * 终止Multipart Upload 事件 + * + * 当一个Multipart Upload事件被中止后,就不能再使用这个Upload ID做任何操作,已经上传的 Part 数据也会被删除 + * + * @param {error} 错误信息 + */ + function abortUpload(rootError) { + + // 初始化MultipartUpload的时候报错,则直接触发error事件 + if (multipartUploadResult === null && multipartUploadID === null) { + return ws.emit('error', rootError); + } + + cachedClient.abortMultipartUpload({ + Bucket: multipartUploadResult.Bucket, + Key: multipartUploadResult.Key, + UploadId: multipartUploadID + }, function (err) { + if (err) { + ws.emit('error', rootError + '\n Additionally failed to abort the multipart upload on OSS: ' + err); + } else { + ws.emit('error', rootError); + } + }); + } + + return ws; +}; + +module.exports = Client; \ No newline at end of file diff --git a/jun_aliyun_sms/aliyun-oss-upload-stream/package.json b/jun_aliyun_sms/aliyun-oss-upload-stream/package.json new file mode 100644 index 0000000000..29fcfe4b93 --- /dev/null +++ b/jun_aliyun_sms/aliyun-oss-upload-stream/package.json @@ -0,0 +1,29 @@ +{ + "name": "aliyun-oss-upload-stream", + "version": "1.3.0", + "description": "A Node.js module for streaming data to Aliyun oss via the multipart upload API", + "main": "./lib/aliyun-oss-upload-stream.js", + "scripts": { + "test": "mocha -t 10000 --recursive test/" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/berwin/aliyun-oss-upload-stream.git" + }, + "keywords": [ + "aliyun", + "oss", + "upload", + "pipe", + "stream" + ], + "author": "Berwin", + "license": "MIT", + "bugs": { + "url": "https://github.com/berwin/aliyun-oss-upload-stream/issues" + }, + "homepage": "https://github.com/berwin/aliyun-oss-upload-stream#readme", + "devDependencies": { + "aliyun-sdk": "^1.9.1" + } +} diff --git a/jun_aliyun_sms/aliyun-oss-upload-stream/test/aliyun-oss-upload-stream.test.js b/jun_aliyun_sms/aliyun-oss-upload-stream/test/aliyun-oss-upload-stream.test.js new file mode 100644 index 0000000000..72c42458ff --- /dev/null +++ b/jun_aliyun_sms/aliyun-oss-upload-stream/test/aliyun-oss-upload-stream.test.js @@ -0,0 +1,96 @@ +/**! + * Aliyun-oss-upload-stream - test/aliyun-oss-upload-stream.test.js + * + * Copyright(c) Berwin and other contributors. + * MIT Licensed + * + * Authors: + * Berwin (https://github.com/berwin) + */ + +'use strict'; + +var ALY = require('aliyun-sdk'); +var fs = require('fs'); + +var ossConfig = { + accessKeyId: '在阿里云OSS申请的 accessKeyId', + secretAccessKey: '在阿里云OSS申请的 secretAccessKey', + endpoint: 'http://oss-cn-hangzhou.aliyuncs.com', + apiVersion: '2013-10-15' +}; + +var uploadConfig = { + "Bucket": "Test-Bucket-Name", + "Key": "Test-Key-Name" +}; + +describe('Piping data into the writable upload stream', function () { + var ossStream = require('../lib/aliyun-oss-upload-stream.js')(new ALY.OSS(ossConfig)); + var uploadStream = ossStream.upload(uploadConfig); + + before(function (done) { + uploadStream.on('error', function () { + throw "Did not expect to receive an error"; + }); + + done(); + }); + + it('should emit valid part and uploaded events', function (done) { + var file = fs.createReadStream(process.cwd() + '/examples/basics/photo.jpg'); + var part = false, uploaded = false; + + uploadStream.on('part', function (details) { + part = true; + if (part && uploaded) done(); + }); + + uploadStream.on('uploaded', function (details) { + uploaded = true; + if (part && uploaded) done(); + }); + + file.pipe(uploadStream); + file.on('error', function () { + throw 'Error! Unable to open the file for reading'; + }); + }); +}); + +describe('OSS Error catching', function () { + describe('Bucket Not correct', function () { + var ossStream = require('../lib/aliyun-oss-upload-stream.js')(new ALY.OSS(ossConfig)); + var uploadStream = ossStream.upload({"Bucket": "NotcorrectBucket", "Key": "test.photo.jpg"}); + + it('should emit an error', function (done) { + var file = fs.createReadStream(process.cwd() + '/examples/basics/photo.jpg'); + + uploadStream.on('error', function (err) { + done(); + }); + + file.pipe(uploadStream); + }); + }); + + describe('Config Not correct', function () { + var ossStream = require('../lib/aliyun-oss-upload-stream.js')(new ALY.OSS({ + accessKeyId: 'NotcorrectAccessKeyId', + secretAccessKey: 'NotcorrectSecretAccessKey', + endpoint: 'http://oss-cn-hangzhou.aliyuncs.com', + apiVersion: '2013-10-15' + })); + var uploadStream = ossStream.upload(uploadConfig); + + it('should emit an error', function (done) { + var file = fs.createReadStream(process.cwd() + '/examples/basics/photo.jpg'); + + uploadStream.on('error', function (err) { + done(); + }); + + file.pipe(uploadStream); + }); + }); +}); \ No newline at end of file diff --git a/jun_aliyun_sms/aliyun_sms/LICENSE b/jun_aliyun_sms/aliyun_sms/LICENSE new file mode 100644 index 0000000000..ddb63499a7 --- /dev/null +++ b/jun_aliyun_sms/aliyun_sms/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., [http://fsf.org/] + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {description} + Copyright (C) 2017 小柒2012 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + {signature of Ty Coon}, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. \ No newline at end of file diff --git a/jun_aliyun_sms/aliyun_sms/README.md b/jun_aliyun_sms/aliyun_sms/README.md new file mode 100644 index 0000000000..8d92a2dbb4 --- /dev/null +++ b/jun_aliyun_sms/aliyun_sms/README.md @@ -0,0 +1,22 @@ +## aliyun_sms +阿里云短信发送 + +[搭建亿万级别短信服务发送平台](https://blog.52itstyle.com/archives/1101/) + +## 阿里大鱼 + +阿里大鱼去哪了,这么牛掰的名字,居然被阿里云抛弃了? + +显然不是,进入短信后台。阿里云还是给了提示:原短信服务已停止开通。 +感谢你对短信服务产品的支持,原短信服务(整合在消息服务内)已停止开通。请前往短信服务控制台,开通新短信服务。 + +很明显短信服务被整合到消息服务中去了,阿里大鱼也不能单独存在了。 + +让我们先默哀三分钟~~~ +![3.jpg](https://blog.52itstyle.com/usr/uploads/2017/06/1363396662.jpg) + + + +作者: 小柒2012 + +欢迎关注: https://blog.52itstyle.com diff --git a/jun_aliyun_sms/aliyun_sms/pom.xml b/jun_aliyun_sms/aliyun_sms/pom.xml new file mode 100644 index 0000000000..6ccfdee9ec --- /dev/null +++ b/jun_aliyun_sms/aliyun_sms/pom.xml @@ -0,0 +1,46 @@ + + 4.0.0 + com.acts.web + aliyun_sms + war + 0.0.1-SNAPSHOT + aliyun_sms + http://maven.apache.org + + + + javax.servlet + servlet-api + 2.5 + + + com.aliyun + sdk-dysmsapi + 1.0.0 + + + com.aliyun + sdk-core + 3.2.2 + + + log4j + log4j + 1.2.17 + + + commons-logging + commons-logging + 1.1.1 + + + com.google.code.gson + gson + 2.3.1 + + + + aliyun_sms + + diff --git a/jun_aliyun_sms/aliyun_sms/src/main/java/com/alicom/dysms/config/AliSmsConfig.java b/jun_aliyun_sms/aliyun_sms/src/main/java/com/alicom/dysms/config/AliSmsConfig.java new file mode 100644 index 0000000000..4d8ac54bcb --- /dev/null +++ b/jun_aliyun_sms/aliyun_sms/src/main/java/com/alicom/dysms/config/AliSmsConfig.java @@ -0,0 +1,45 @@ +package com.alicom.dysms.config; + +import com.aliyuncs.DefaultAcsClient; +import com.aliyuncs.IAcsClient; +import com.aliyuncs.exceptions.ClientException; +import com.aliyuncs.profile.DefaultProfile; +import com.aliyuncs.profile.IClientProfile; +/** + * 单例实现 + * 创建者 科帮网 + * 创建时间 2017年6月29日 + * + */ +public class AliSmsConfig { + private AliSmsConfig(){}; + static final String signName = "科帮网";//签名 + static final String templateCode = "SMS_75085007";//模版 + static final String product = "Dysmsapi"; + static final String domain = "dysmsapi.aliyuncs.com"; + static final String accessKeyId = "2017";//此处私钥 填写自己的 + static final String accessKeySecret = "2017";//此处私钥 填写自己的 + static final IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret); + static { + try { + System.setProperty("sun.net.client.defaultConnectTimeout", "10000"); + System.setProperty("sun.net.client.defaultReadTimeout", "10000"); + DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain); + } catch (ClientException e) { + e.printStackTrace(); + } + } + /** + * 类级的内部类,也就是静态的成员式内部类,该内部类的实例与外部类的实例 + * 没有绑定关系,而且只有被调用到才会装载,从而实现了延迟加载 + */ + private static class SingletonHolder{ + /** + * 静态初始化器,由JVM来保证线程安全 + */ + private static IAcsClient acsClient = new DefaultAcsClient(profile); + } + public static IAcsClient getAcsClient(){ + return SingletonHolder.acsClient; + } +} diff --git a/jun_aliyun_sms/aliyun_sms/src/main/java/com/alicom/dysms/config/SmsUtil.java b/jun_aliyun_sms/aliyun_sms/src/main/java/com/alicom/dysms/config/SmsUtil.java new file mode 100644 index 0000000000..2431b74d4f --- /dev/null +++ b/jun_aliyun_sms/aliyun_sms/src/main/java/com/alicom/dysms/config/SmsUtil.java @@ -0,0 +1,31 @@ +package com.alicom.dysms.config; +import org.apache.log4j.LogManager; +import org.apache.log4j.Logger; + +import com.aliyuncs.IAcsClient; +import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest; +import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse; +/** + * 短信发送工具类 + * 创建者 科帮网 + * 创建时间 2017年6月29日 + * + */ +public class SmsUtil { + private static final Logger LOG = LogManager.getLogger(SmsUtil.class.getName()); + public static SendSmsResponse sendSms(SendSmsRequest request) { + SendSmsResponse sendSmsResponse = null; + LOG.info("发送手机验证码:"+request.getPhoneNumbers()); + try { + IAcsClient acsClient = AliSmsConfig.getAcsClient(); + //必填:短信签名-可在短信控制台中找到 + request.setSignName(AliSmsConfig.signName); + //必填:短信模板-可在短信控制台中找到 + request.setTemplateCode(AliSmsConfig.templateCode); + sendSmsResponse = acsClient.getAcsResponse(request); + } catch (Exception e) { + LOG.error("短信发送异常:"+request.getPhoneNumbers(), e); + } + return sendSmsResponse; + } +} diff --git a/jun_aliyun_sms/aliyun_sms/src/main/java/com/alicom/dysms/servlet/SendServlet.java b/jun_aliyun_sms/aliyun_sms/src/main/java/com/alicom/dysms/servlet/SendServlet.java new file mode 100644 index 0000000000..29d26a773c --- /dev/null +++ b/jun_aliyun_sms/aliyun_sms/src/main/java/com/alicom/dysms/servlet/SendServlet.java @@ -0,0 +1,48 @@ +package com.alicom.dysms.servlet; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import com.alicom.dysms.config.SmsUtil; +import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest; +import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse; +import com.google.gson.JsonObject; +/** + * 短信发送 + * 创建者 科帮网 + * 创建时间 2017年6月29日 + */ +public class SendServlet extends HttpServlet { + private static final long serialVersionUID = 1L; + + @Override + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + this.doPost(request, response); + } + + @Override + public void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + String mobile = request.getParameter("mobile");//手机 + String number = request.getParameter("number");//验证码 + SendSmsRequest sms = new SendSmsRequest(); + sms.setPhoneNumbers(mobile); + JsonObject params = new JsonObject(); + params.addProperty("name", "小柒"); + params.addProperty("number", number); + sms.setTemplateParam(params.toString()); + SendSmsResponse res = SmsUtil.sendSms(sms); + PrintWriter out = response.getWriter(); + if("OK".equals(res.getCode())){ + out.print("success"); + }else{ + out.print("fail"); + } + } +} \ No newline at end of file diff --git a/jun_aliyun_sms/aliyun_sms/src/main/java/com/alicom/dysms/web/SmsDemo.java b/jun_aliyun_sms/aliyun_sms/src/main/java/com/alicom/dysms/web/SmsDemo.java new file mode 100644 index 0000000000..825e3068dd --- /dev/null +++ b/jun_aliyun_sms/aliyun_sms/src/main/java/com/alicom/dysms/web/SmsDemo.java @@ -0,0 +1,38 @@ +package com.alicom.dysms.web; + +import org.apache.log4j.LogManager; +import org.apache.log4j.Logger; + +import com.alicom.dysms.config.SmsUtil; +import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest; +import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse; +import com.aliyuncs.exceptions.ClientException; +import com.google.gson.JsonObject; +/** + * 阿里短信发送Demo + * 创建者 科帮网 + * 创建时间 2017年6月29日 + * + */ +public class SmsDemo { + private static final Logger LOG = LogManager.getLogger(SmsDemo.class.getName()); + public static void main(String[] args) throws ClientException, InterruptedException { + SendSmsRequest request = new SendSmsRequest(); + //必填:待发送手机号 + request.setPhoneNumbers("18888888888"); + //尊敬的${name},您正进行科帮网的身份验证,验证码${number},打死不告诉别人! + JsonObject params = new JsonObject(); + params.addProperty("name", "蛋蛋"); + params.addProperty("number", "521521"); + request.setTemplateParam(params.toString()); + SendSmsResponse response = SmsUtil.sendSms(request); + LOG.info("--------短信接口返回的数据--------"); + if("OK".equals(response.getCode())){ + System.out.println("Code=" + response.getCode()); + System.out.println("Message=" + response.getMessage()); + System.out.println("RequestId=" + response.getRequestId()); + System.out.println("BizId=" + response.getBizId()); + LOG.info("短信发送成功"); + } + } +} diff --git a/jun_java_plugins/jun_aliyun_sms/src/main/resources/log4j.properties b/jun_aliyun_sms/aliyun_sms/src/main/resources/log4j.properties similarity index 100% rename from jun_java_plugins/jun_aliyun_sms/src/main/resources/log4j.properties rename to jun_aliyun_sms/aliyun_sms/src/main/resources/log4j.properties diff --git a/jun_aliyun_sms/aliyun_sms/src/main/webapp/WEB-INF/web.xml b/jun_aliyun_sms/aliyun_sms/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..9e8f6024a5 --- /dev/null +++ b/jun_aliyun_sms/aliyun_sms/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + aliyun_sms + + SendServlet + com.alicom.dysms.servlet.SendServlet + + + SendServlet + /SendServlet + + \ No newline at end of file diff --git a/jun_java_plugins/jun_datasource/src/main/webapp/index.jsp b/jun_aliyun_sms/aliyun_sms/src/main/webapp/index.jsp similarity index 100% rename from jun_java_plugins/jun_datasource/src/main/webapp/index.jsp rename to jun_aliyun_sms/aliyun_sms/src/main/webapp/index.jsp diff --git a/jun_aliyun_sms/gotanks-aliyunSV_1.0.4_example.zip b/jun_aliyun_sms/gotanks-aliyunSV_1.0.4_example.zip new file mode 100644 index 0000000000..ca321c9699 Binary files /dev/null and b/jun_aliyun_sms/gotanks-aliyunSV_1.0.4_example.zip differ diff --git a/jun_aliyun_sms/pom.xml b/jun_aliyun_sms/pom.xml new file mode 100644 index 0000000000..89e020343d --- /dev/null +++ b/jun_aliyun_sms/pom.xml @@ -0,0 +1,49 @@ + + 4.0.0 + com.jun.plugin + jun_aliyun_sms + war + 0.0.1-SNAPSHOT + jun_aliyun_sms + http://maven.apache.org + + + + javax.servlet + servlet-api + 2.5 + + + + com.aliyun + aliyun-java-sdk-dysmsapi + 2.1.0 + + + + com.aliyun + aliyun-java-sdk-core + 4.5.3 + + + log4j + log4j + 1.2.17 + + + commons-logging + commons-logging + 1.1.1 + + + com.google.code.gson + gson + 2.3.1 + + + + aliyun_sms + + diff --git a/jun_java_plugins/jun_aliyun_sms/src/main/java/com/jun/plugin/aliyunsms/config/AliSmsConfig.java b/jun_aliyun_sms/src/main/java/com/jun/plugin/aliyunsms/config/AliSmsConfig.java similarity index 100% rename from jun_java_plugins/jun_aliyun_sms/src/main/java/com/jun/plugin/aliyunsms/config/AliSmsConfig.java rename to jun_aliyun_sms/src/main/java/com/jun/plugin/aliyunsms/config/AliSmsConfig.java diff --git a/jun_java_plugins/jun_aliyun_sms/src/main/java/com/jun/plugin/aliyunsms/config/SmsUtil.java b/jun_aliyun_sms/src/main/java/com/jun/plugin/aliyunsms/config/SmsUtil.java similarity index 100% rename from jun_java_plugins/jun_aliyun_sms/src/main/java/com/jun/plugin/aliyunsms/config/SmsUtil.java rename to jun_aliyun_sms/src/main/java/com/jun/plugin/aliyunsms/config/SmsUtil.java diff --git a/jun_java_plugins/jun_aliyun_sms/src/main/java/com/jun/plugin/aliyunsms/demo/SmsDemo.java b/jun_aliyun_sms/src/main/java/com/jun/plugin/aliyunsms/demo/SmsDemo.java similarity index 100% rename from jun_java_plugins/jun_aliyun_sms/src/main/java/com/jun/plugin/aliyunsms/demo/SmsDemo.java rename to jun_aliyun_sms/src/main/java/com/jun/plugin/aliyunsms/demo/SmsDemo.java diff --git a/jun_java_plugins/jun_aliyun_sms/src/main/java/com/jun/plugin/aliyunsms/servlet/SendServlet.java b/jun_aliyun_sms/src/main/java/com/jun/plugin/aliyunsms/servlet/SendServlet.java similarity index 100% rename from jun_java_plugins/jun_aliyun_sms/src/main/java/com/jun/plugin/aliyunsms/servlet/SendServlet.java rename to jun_aliyun_sms/src/main/java/com/jun/plugin/aliyunsms/servlet/SendServlet.java diff --git a/jun_aliyun_sms/src/main/resources/log4j.properties b/jun_aliyun_sms/src/main/resources/log4j.properties new file mode 100644 index 0000000000..8758099cae --- /dev/null +++ b/jun_aliyun_sms/src/main/resources/log4j.properties @@ -0,0 +1,7 @@ +log4j.rootLogger=info, stdout + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender + +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout + +log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n \ No newline at end of file diff --git a/jun_aliyun_sms/src/main/webapp/WEB-INF/web.xml b/jun_aliyun_sms/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..9e8f6024a5 --- /dev/null +++ b/jun_aliyun_sms/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + aliyun_sms + + SendServlet + com.alicom.dysms.servlet.SendServlet + + + SendServlet + /SendServlet + + \ No newline at end of file diff --git a/jun_java_plugins/jun_dbutil/src/main/webapp/index.jsp b/jun_aliyun_sms/src/main/webapp/index.jsp similarity index 100% rename from jun_java_plugins/jun_dbutil/src/main/webapp/index.jsp rename to jun_aliyun_sms/src/main/webapp/index.jsp diff --git a/jun_java_plugins/jun_mongodb/.gitignore b/jun_apache_commons/.gitignore similarity index 100% rename from jun_java_plugins/jun_mongodb/.gitignore rename to jun_apache_commons/.gitignore diff --git a/jun_java_plugins/jun_apache_commons/README.md b/jun_apache_commons/README.md similarity index 100% rename from jun_java_plugins/jun_apache_commons/README.md rename to jun_apache_commons/README.md diff --git "a/jun_apache_commons/doc/commons-beanutil\345\255\246\344\271\240\346\212\245\345\221\212.doc" "b/jun_apache_commons/doc/commons-beanutil\345\255\246\344\271\240\346\212\245\345\221\212.doc" new file mode 100644 index 0000000000..880f6f5d06 Binary files /dev/null and "b/jun_apache_commons/doc/commons-beanutil\345\255\246\344\271\240\346\212\245\345\221\212.doc" differ diff --git a/jun_apache_commons/doc/readMe.txt b/jun_apache_commons/doc/readMe.txt new file mode 100644 index 0000000000..46669b5c08 --- /dev/null +++ b/jun_apache_commons/doc/readMe.txt @@ -0,0 +1,62 @@ +一、数据库工具类 + 1、com.baijob.commonTools.db.ds + + C3p0Ds 和 DruidDs分别是两种连接池的实现,依赖于数据库配置文件,配置文件的样例参考config/db-example.setting + 使用时将db-example.setting复制于${classpath}/config/db.setting,按照配置文件中的说明替换相应值 + 如果使用Druid,则需参考druid-example.setting创建${classpath}/config/druid.setting文件,详情请参考官方文档 + 使用C3P0则需要参考c3p0-config-example.xml创建${classpath}/c3p0-config.xml来调节C3P0参数 + 此时即可调用C3p0Ds.getDataSource()或DruidDs.getDataSource()方法获得默认的数据源 + + 如果要自定义数据库配置文件的参数,请调用相应的init(),传入相关参数 + 注:Setting对象请参考与之对应的章节 + + 2、com.baijob.commonTools.db.DbUtil + + 数据库工具类,提供了关闭方法:关闭可以传入多个参数,关闭的顺序是按照参数的顺序来的,用于一次性关闭Connnection、Statement、ResultSet等 + newSqlRunner方法用于快速新建一个SqlRunner(此类介绍参考下问) + + 3、com.baijob.commonTools.db.DsSetting,用于读取db.setting文件辅助类,内部使用 + + 4、com.baijob.commonTools.db.SqlRunner类参考Apache的DbUtils工具包,封装了常用的增删改查方法,与com.baijob.commonTools.db.RsHandler配合使用 + com.baijob.commonTools.db.RsHandler接口与Apache的DbUtils的ResultSetHandler等价,抽象结果集处理。 + +二、邮件工具类 + + 1、com.baijob.commonTools.mail.MailAccount 邮件账户类。 + 可以调用MailAccount(String accountSettingFileBaseClassLoader)读取相对路径的Setting文件,配置参考mailAccount-example.setting + + 2、com.baijob.commonTools.mail.MailUtil邮件发送工具类,方法请参考注释 + + 此工具类依赖javax.mail,请参考pom.xml添加依赖或手动下载 + +三、网络相关工具类 + + 1、com.baijob.commonTools.net.AccessControl访问控制,基于配置文件,可以设定IP白名单或黑名单,可以通过配置文件实现简单的账户验证。 + 配置文件请参考access-example.xml + + 2、com.baijob.commonTools.net.Connector 连接对象实体类,有host、端口、用户名、密码等属性 + + 3、com.baijob.commonTools.net.HtmlUtil HTML工具类,暂时只提供特殊字符转义 + + 4、com.baijob.commonTools.net.SocketUtil socket工具类。 + isUsableLocalPort() 检测本地某个端口是否可用(可用是指没有被其他程序占用) + isValidPort()是否是符合规范的端口号 + longToIpv4()将long转换为ipv4地址,反方法是ipv4ToLong() + netCat()简易的数据发送方法 + + 5、com.baijob.commonTools.net.SSHUtil SSH相关工具类 + getSession()获得一个SSH会话 + bindPort()将远程主机的端口映射到本地某个端口 + + 6、com.baijob.commonTools.net.URLUtil 将相对、绝对路径转换为URL对象,用于网络或文件流的读写,Setting的配置依赖此工具包 + +四、线程相关工具类 + 1、com.baijob.commonTools.thread.BaseRunnable 此类实现了Runnable接口,扩展了功能。 + 增加名称、ID,调用次数和时间统计、线程停止接口等,并且在线程运行时,不允许此线程第二次启动。 + + 2、com.baijob.commonTools.thread.Executor 线程池工具类 + 调用静态方法execute()启动线程,此线程在公共的线程池中执行 + 若想自定义线程池大小或独立控制,可调用newExecutor()实例化一个线程池 + excAsync()执行一个异步方法 + + 3、com.baijob.commonTools.thread.SyncQueue 阻塞队列,简化了JDK的BlockingQueue \ No newline at end of file diff --git a/jun_apache_commons/pom.xml b/jun_apache_commons/pom.xml new file mode 100644 index 0000000000..d6da14b27c --- /dev/null +++ b/jun_apache_commons/pom.xml @@ -0,0 +1,173 @@ + + 4.0.0 + com.jun.plugin + jun_apache_commons + jar + 0.0.1-SNAPSHOT + + + UTF-8 + + + + + commons-cli + commons-cli + 1.2 + + + + org.slf4j + slf4j-api + 1.7.2 + + + + dom4j + dom4j + 1.6.1 + + + + mysql + mysql-connector-java + 5.1.21 + test + + + + junit + junit + 4.10 + test + + + + ch.qos.logback + logback-classic + 1.0.9 + test + + + + c3p0 + c3p0 + 0.9.1.2 + provided + + + + com.alibaba + druid + 0.2.23 + provided + + + + com.jcraft + jsch + 0.1.49 + provided + + + + org.apache.tomcat + tomcat-servlet-api + 7.0.30 + provided + + + javax.mail + mail + 1.4.5 + provided + + + org.jodd + jodd-http + 3.4.2 + provided + + + + + org.apache.commons + commons-lang3 + 3.11 + + + + commons-beanutils + commons-beanutils + 1.9.4 + + + + commons-lang + commons-lang + 2.6 + + + + org.mvel + mvel2 + 2.4.10.Final + + + + org.apache.tapestry + tapestry5-annotations + 5.6.1 + + + + redis.clients + jedis + 3.3.0 + + + + org.json + json + 20200518 + + + + org.apache.httpcomponents + httpclient + 4.5.12 + + + net.sourceforge.jexcelapi + jxl + 2.6.12 + + + + + org.apache.poi + poi + 4.1.2 + + + + + commons-fileupload + commons-fileupload + 1.4 + + + + + + + + + diff --git a/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/CollectionUtil.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/CollectionUtil.java new file mode 100644 index 0000000000..906674ac78 --- /dev/null +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/CollectionUtil.java @@ -0,0 +1,173 @@ +package com.jun.plugin.commons.util; + +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.Stack; + +/** + * 集合相关工具类,包括数组 + * @author luxiaolei@baijob.com + * + */ +public class CollectionUtil { + /** + * 以 conjunction 为分隔符将集合转换为字符串 + * @param 被处理的集合 + * @param collection 集合 + * @param conjunction 分隔符 + * @return 连接后的字符串 + */ + public static String join(Iterable collection, String conjunction) { + StringBuilder sb = new StringBuilder(); + boolean isFirst = true; + for (T item : collection) { + if (isFirst){ + isFirst = false; + }else{ + sb.append(conjunction); + } + sb.append(item); + } + return sb.toString(); + } + + /** + * 以 conjunction 为分隔符将数组转换为字符串 + * @param 被处理的集合 + * @param array 数组 + * @param conjunction 分隔符 + * @return 连接后的字符串 + */ + public static String join(T[] array, String conjunction) { + StringBuilder sb = new StringBuilder(); + boolean isFirst = true; + for (T item : array) { + if (isFirst){ + isFirst = false; + }else{ + sb.append(conjunction); + } + sb.append(item); + } + return sb.toString(); + } + + /** + * 将Set排序(根据Entry的值) + * @param set 被排序的Set + * @return 排序后的Set + */ + public static List> sortEntrySetToList(Set> set){ + List> list = new LinkedList>(set); + Collections.sort(list, new Comparator>() { + + @Override + public int compare(Entry o1, Entry o2) { + if(o1.getValue() > o2.getValue()) return 1; + if(o1.getValue() < o2.getValue()) return -1; + return 0; + } + }); + return list; + } + + /** + * 切取部分数据 + * @param 集合元素类型 + * @param surplusAlaDatas 原数据 + * @param partSize 每部分数据的长度 + * @return 切取出的数据或null + */ + public static List popPart(Stack surplusAlaDatas, int partSize){ + if(surplusAlaDatas == null || surplusAlaDatas.size() <= 0) return null; + + List currentAlaDatas = new ArrayList(); + int size = surplusAlaDatas.size(); + //切割 + if(size > partSize){ + for(int i = 0; i < partSize; i++){ + currentAlaDatas.add(surplusAlaDatas.pop()); + } + }else{ + for(int i = 0; i < size; i++){ + currentAlaDatas.add(surplusAlaDatas.pop()); + } + } + return currentAlaDatas; + } + + /** + * 新建一个HashMap + * @return HashMap对象 + */ + public static HashMap newHashMap(){ + return new HashMap(); + } + + /** + * 新建一个HashSet + * @return HashSet对象 + */ + public static HashSet newHashSet(){ + return new HashSet(); + } + + /** + * 新建一个ArrayList + * @return ArrayList对象 + */ + public static ArrayList newArrayList(){ + return new ArrayList(); + } + + /** + * 将新元素添加到已有数组中
+ * 添加新元素会生成一个新的数组,不影响原数组 + * @param buffer 已有数组 + * @param newElement 新元素 + * @return 新数组 + */ + public static T[] append(T[] buffer, T newElement) { + T[] t = resize(buffer, buffer.length + 1, newElement.getClass()); + t[buffer.length] = newElement; + return t; + } + + /** + * 生成一个新的重新设置大小的数组 + * @param buffer 原数组 + * @param newSize 新的数组大小 + * @param componentType 数组元素类型 + * @return 调整后的新数组 + */ + @SuppressWarnings({"unchecked"}) + public static T[] resize(T[] buffer, int newSize, Class componentType) { + //给定类型为空时,使用原数组的类型 + if (componentType == null) { + componentType = buffer.getClass().getComponentType(); + } + T[] newArray = (T[]) Array.newInstance(componentType, newSize); + System.arraycopy(buffer, 0, newArray, 0, buffer.length >= newSize ? newSize : buffer.length); + return newArray; + } + + /** + * 生成一个新的重新设置大小的数组
+ * 新数组的类型为原数组的类型 + * @param buffer 原数组 + * @param newSize 新的数组大小 + * @return 调整后的新数组 + */ + public static T[] resize(T[] buffer, int newSize) { + return resize(buffer, newSize, null); + } +} diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/Conf.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/Conf.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/Conf.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/Conf.java diff --git a/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/Config.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/Config.java new file mode 100644 index 0000000000..6bd9510bc4 --- /dev/null +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/Config.java @@ -0,0 +1,161 @@ +package com.jun.plugin.commons.util; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Map.Entry; +import java.util.Properties; +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * 读取配置文件的类 + * @author Luxiaolei + */ +public final class Config { + private static Logger logger = LoggerFactory.getLogger(Config.class); + + /*--------------------------私有属性 start-------------------------------*/ + private Properties props; + /*--------------------------私有属性 end-------------------------------*/ + + /** + * 构造,使用相对于Class文件根目录的相对路径 + * @param pathBaseClassLoader 相对路径(相对于当前项目的classes路径) + */ + public Config(String pathBaseClassLoader){ + URL url = Config.class.getClassLoader().getResource(pathBaseClassLoader); + logger.debug("加载配置文件 => " + url.getPath()); + this.init(url); + } + + /** + * 构造 + * @param configFile 配置文件对象 + */ + public Config(File configFile){ + if(configFile == null){ + logger.error("请指定配置文件!"); + return; + } + URL url = null; + try { + url = configFile.toURI().toURL(); + logger.debug("加载配置文件 => " + url.getPath()); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + this.init(url); + } + + /** + * 构造,相对于classes读取文件 + * @param path 相对路径 + * @param clazz 基准类 + */ + public Config(String path, Class clazz){ + URL url = clazz.getResource(path); + this.init(url); + } + + /*--------------------------公有方法 start-------------------------------*/ + /** + * 初始化配置文件 + * @param configUrl 配置文件URL + */ + public void init(URL configUrl){ + if(configUrl == null){ + logger.error("指定配置文件路径为空,请检查!"); + return; + } + InputStream in = null; + props = new Properties(); + try { + in = configUrl.openStream(); + props.load(in); + } catch (IOException e) { + e.printStackTrace(); + }finally{ + FileUtil.close(in); + } + } + + /** + * 获取字符型型属性值 + * @param key 属性名 + * @return 属性值 + */ + public String getString(String key){ + return props.getProperty(key); + } + + /** + * 获取数字型型属性值 + * @param key 属性名 + * @return 属性值 + */ + public int getInt(String key){ + return Integer.parseInt(props.getProperty(key)); + } + + /** + * 获取波尔型属性值 + * @param key 属性名 + * @return 属性值 + */ + public boolean getBool(String key){ + return Boolean.parseBoolean(props.getProperty(key)); + } + + /** + * 获取long类型属性值 + * @param key 属性名 + * @return 属性值 + */ + public long getLong(String key){ + return Long.parseLong(props.getProperty(key)); + } + + /** + * 设置值,无给定键创建之。设置后未持久化 + * @param key 属性键 + * @param value 属性值 + */ + public void setProperty(String key, Object value){ + props.setProperty(key, value.toString()); + } + + /** + * 持久化当前设置,会覆盖掉之前的设置 + * @param absolutePath 设置文件的绝对路径 + */ + public void store(String absolutePath){ + try { + FileUtil.touch(absolutePath); + props.store(FileUtil.getOutputStream(absolutePath), null); + } catch (FileNotFoundException e) { + //不会出现这个异常 + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * 存储当前设置,会覆盖掉以前的设置 + * @param path 相对路径 + * @param clazz 相对的类 + */ + public void store(String path, Class clazz){ + this.store(FileUtil.getAbsolutePath(path, clazz)); + } + + public Set> entrySet(){ + return props.entrySet(); + } + /*--------------------------公有方法 end-------------------------------*/ +} diff --git a/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/ConsistentHash.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/ConsistentHash.java new file mode 100644 index 0000000000..1d06b0bca1 --- /dev/null +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/ConsistentHash.java @@ -0,0 +1,108 @@ +package com.jun.plugin.commons.util; + +import java.util.Collection; +import java.util.SortedMap; +import java.util.TreeMap; + +/** + * 一致性Hash算法 + * 算法详解:http://blog.csdn.net/sparkliang/article/details/5279393 + * 算法实现:https://weblogs.java.net/blog/2007/11/27/consistent-hashing + * @author xiaoleilu + * + * @param 节点类型 + */ +public class ConsistentHash { + /** Hash计算对象,用于自定义hash算法 */ + HashFunc hashFunc; + /** 复制的节点个数 */ + private final int numberOfReplicas; + /** 一致性Hash环 */ + private final SortedMap circle = new TreeMap(); + + /** + * 构造,使用Java默认的Hash算法 + * @param numberOfReplicas 复制的节点个数,增加每个节点的复制节点有利于负载均衡 + * @param nodes 节点对象 + */ + public ConsistentHash(int numberOfReplicas, Collection nodes) { + this.numberOfReplicas = numberOfReplicas; + this.hashFunc = new HashFunc() { + + @Override + public Integer hash(Object key) { + //默认使用FNV1hash算法 + return HashUtil.FNVHash1(key.toString()); + } + }; + //初始化节点 + for (T node : nodes) { + add(node); + } + } + + /** + * 构造 + * @param hashFunc hash算法对象 + * @param numberOfReplicas 复制的节点个数,增加每个节点的复制节点有利于负载均衡 + * @param nodes 节点对象 + */ + public ConsistentHash(HashFunc hashFunc, int numberOfReplicas, Collection nodes) { + this.numberOfReplicas = numberOfReplicas; + this.hashFunc = hashFunc; + //初始化节点 + for (T node : nodes) { + add(node); + } + } + + /** + * 增加节点
+ * 每增加一个节点,就会在闭环上增加给定复制节点数
+ * 例如复制节点数是2,则每调用此方法一次,增加两个虚拟节点,这两个节点指向同一Node + * 由于hash算法会调用node的toString方法,故按照toString去重 + * @param node 节点对象 + */ + public void add(T node) { + for (int i = 0; i < numberOfReplicas; i++) { + circle.put(hashFunc.hash(node.toString() + i), node); + } + } + + /** + * 移除节点的同时移除相应的虚拟节点 + * @param node 节点对象 + */ + public void remove(T node) { + for (int i = 0; i < numberOfReplicas; i++) { + circle.remove(hashFunc.hash(node.toString() + i)); + } + } + + /** + * 获得一个最近的顺时针节点 + * @param key 为给定键取Hash,取得顺时针方向上最近的一个虚拟节点对应的实际节点 + * @return 节点对象 + */ + public T get(Object key) { + if (circle.isEmpty()) { + return null; + } + int hash = hashFunc.hash(key); + if (!circle.containsKey(hash)) { + SortedMap tailMap = circle.tailMap(hash); //返回此映射的部分视图,其键大于等于 hash + hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey(); + } + //正好命中 + return circle.get(hash); + } + + /** + * Hash算法对象,用于自定义hash算法 + * @author xiaoleilu + * + */ + public interface HashFunc { + public Integer hash(Object key); + } +} diff --git a/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/CsvUtil.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/CsvUtil.java new file mode 100644 index 0000000000..9a57b927f5 --- /dev/null +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/CsvUtil.java @@ -0,0 +1,68 @@ +package com.jun.plugin.commons.util; + +import java.io.IOException; +import java.io.PrintWriter; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Collection; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * CSV文件相关工具(逗号分隔符文件) + * @author Luxiaolei + * + */ +public class CsvUtil { + private static Logger logger = LoggerFactory.getLogger(CsvUtil.class); + + /** + * 将结果集存储为CSV文件 + * @param rs 结果集 + * @param pathWithName 要存储到文件的路径 + */ + public static void toCSV(ResultSet rs, String pathWithName, String charset) { + try { + PrintWriter writer = FileUtil.getPrintWriter(pathWithName, charset, false); + while (rs.next()) { + int count = rs.getMetaData().getColumnCount(); + // 处理一行 + StringBuffer sb = new StringBuffer(); + for (int i = 1; i <= count; i++) { + sb.append(rs.getObject(i)); + if (i == count) + break; + sb.append(","); + } + String line = sb.toString(); + logger.debug("写入:" + line); + writer.println(line); + } + writer.close(); + } catch (SQLException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * 将集合中的内容写入CSV文件 + * @param collection 要写入文件的集合集合 + * @param pathWithName CSV文件路径,带文件名 + * @param charset 字符集 + */ + public static void toCSV(Collection collection, String pathWithName, String charset){ + try { + PrintWriter writer = FileUtil.getPrintWriter(pathWithName, charset, false); + for (String line : collection) { + logger.debug("写入:" + line); + writer.println(line); + } + writer.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/DateUtil.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/DateUtil.java new file mode 100644 index 0000000000..640bf9dd9a --- /dev/null +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/DateUtil.java @@ -0,0 +1,168 @@ +package com.jun.plugin.commons.util; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * 时间工具类 + * @author 刘世权 路小磊 + */ +public class DateUtil { + private static Logger logger = LoggerFactory.getLogger(DateUtil.class); + + /** 毫秒 */ + public final static long MS = 1; + /** 每秒钟的毫秒数 */ + public final static long SECOND_MS = MS * 1000; + /** 每分钟的毫秒数 */ + public final static long MINUTE_MS = SECOND_MS * 60; + /** 每小时的毫秒数 */ + public final static long HOUR_MS = MINUTE_MS * 60; + /** 每天的毫秒数 */ + public final static long DAY_MS = HOUR_MS * 24; + + /** 标准日期(不含时间)格式化器 */ + private final static SimpleDateFormat NORM_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); + /** 标准日期时间格式化器 */ + private final static SimpleDateFormat NORM_DATETIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + /** HTTP日期时间格式化器 */ + private final static SimpleDateFormat HTTP_DATETIME_FORMAT = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); + + /** + * 当前时间,格式 yyyy-MM-dd HH:mm:ss + * @return 当前时间的标准形式字符串 + */ + public static String now() { + return formatDateTime(new Date()); + } + + /** + * 当前日期,格式 yyyy-MM-dd + * @return 当前日期的标准形式字符串 + */ + public static String today() { + return formatDate(new Date()); + } + + // ------------------------------------ Format start ---------------------------------------------- + /** + * 根据特定格式格式化日期 + * @param date 被格式化的日期 + * @param format 格式 + * @return 格式化后的字符串 + */ + public static String format(Date date, String format){ + return new SimpleDateFormat(format).format(date); + } + + /** + * 格式 yyyy-MM-dd HH:mm:ss + * @param date 被格式化的日期 + * @return 格式化后的日期 + */ + public static String formatDateTime(Date date) { +// return format(d, "yyyy-MM-dd HH:mm:ss"); + return NORM_DATETIME_FORMAT.format(date); + } + + /** + * 格式化为Http的标准日期格式 + * @param date 被格式化的日期 + * @return HTTP标准形式日期字符串 + */ + public static String formatHttpDate(Date date) { +// return new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US).format(date); + return HTTP_DATETIME_FORMAT.format(date); + } + + /** + * 格式 yyyy-MM-dd + * @param date 被格式化的日期 + * @return 格式化后的字符串 + */ + public static String formatDate(Date date) { +// return format(d, "yyyy-MM-dd"); + return NORM_DATE_FORMAT.format(date); + } + // ------------------------------------ Format end ---------------------------------------------- + + // ------------------------------------ Parse start ---------------------------------------------- + /** + * 将特定格式的日期转换为Date对象 + * @param dateString 特定格式的日期 + * @param format 格式,例如yyyy-MM-dd + * @return 日期对象 + */ + public static Date parse(String dateString, String format){ + try { + return (new SimpleDateFormat(format)).parse(dateString); + } catch (ParseException e) { + logger.error("Parse " + dateString + " with format " + format + " error!", e); + } + return null; + } + + /** + * 格式yyyy-MM-dd HH:mm:ss + * @param dateString 标准形式的时间字符串 + * @return 日期对象 + */ + public static Date parseDateTime(String dateString){ +// return parse(s, "yyyy-MM-dd HH:mm:ss"); + try { + return NORM_DATETIME_FORMAT.parse(dateString); + } catch (ParseException e) { + logger.error("Parse " + dateString + " with format " + NORM_DATETIME_FORMAT.toPattern() + " error!", e); + } + return null; + } + + /** + * 格式yyyy-MM-dd + * @param dateString 标准形式的日期字符串 + * @return 日期对象 + */ + public static Date parseDate(String dateString){ +// return parse(s, "yyyy-MM-dd"); + try { + return NORM_DATE_FORMAT.parse(dateString); + } catch (ParseException e) { + logger.error("Parse " + dateString + " with format " + NORM_DATE_FORMAT.toPattern() + " error!", e); + } + return null; + } + // ------------------------------------ Parse end ---------------------------------------------- + + /** + * 获取指定日期偏移指定时间后的时间 + * @param date 基准日期 + * @param calendarField 偏移的粒度大小(小时、天、月等)使用Calendar中的常数 + * @param offsite 偏移量,正数为向后偏移,负数为向前偏移 + * @return 偏移后的日期 + */ + public static Date getOffsiteDate(Date date, int calendarField, int offsite){ + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + cal.add(calendarField, offsite); + return cal.getTime(); + } + + /** + * 判断两个日期相差的时长
+ * 返回 minuend - subtrahend 的差 + * @param subtrahend 减数日期 + * @param minuend 被减数日期 + * @param diffField 相差的选项:相差的天、小时 + * @return 日期差 + */ + public static long dateDiff(Date subtrahend, Date minuend, long diffField){ + long diff = minuend.getTime() - subtrahend.getTime(); + return diff/diffField; + } +} diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/Exceptions/ConnException.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/Exceptions/ConnException.java similarity index 95% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/Exceptions/ConnException.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/Exceptions/ConnException.java index 455286f749..8175c74b16 100644 --- a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/Exceptions/ConnException.java +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/Exceptions/ConnException.java @@ -2,7 +2,7 @@ /** * 数据库连接异常 - * @author Wujun + * @author Luxiaolei */ public class ConnException extends Exception{ private static final long serialVersionUID = -5515153957859362853L; diff --git a/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/Exceptions/SettingException.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/Exceptions/SettingException.java new file mode 100644 index 0000000000..941b01a265 --- /dev/null +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/Exceptions/SettingException.java @@ -0,0 +1,21 @@ +package com.jun.plugin.commons.util.Exceptions; + +/** + * 设置异常 + * @author Luxiaolei + */ +public class SettingException extends Exception{ + private static final long serialVersionUID = -4134588858314744501L; + + public SettingException(Throwable e) { + super(e); + } + + public SettingException(String message) { + super(message); + } + + public SettingException(String message, Throwable throwable) { + super(message, throwable); + } +} diff --git a/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/FileUtil.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/FileUtil.java new file mode 100644 index 0000000000..919480e045 --- /dev/null +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/FileUtil.java @@ -0,0 +1,231 @@ +package com.jun.plugin.commons.util; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.Closeable; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.net.URL; +import java.util.Collection; + +/** + * 文件工具类 + * @author Luxiaolei + * + */ +public class FileUtil { + /** + * 创建文件,如果这个文件存在,直接返回这个文件 + * @param fullFilePath 文件的全路径,使用POSIX风格 + * @return 文件 + * @throws IOException + */ + public static File touch(String fullFilePath) throws IOException { + File file = new File(fullFilePath); + file.getParentFile().mkdirs(); + if(!file.exists()) file.createNewFile(); + return file; + } + + /** + * 创建文件夹,如果存在直接返回此文件夹 + * @param dirPath 文件夹路径,使用POSIX格式,无论哪个平台 + * @return 创建的目录 + */ + public static File mkdir(String dirPath){ + File dir = new File(dirPath); + dir.mkdirs(); + return dir; + } + + /** + * 获取绝对路径
+ * 此方法不会判定给定路径是否有效(文件或目录存在) + * @param path 相对路径 + * @param baseClass 相对路径所相对的类 + * @return 绝对路径 + */ + public static String getAbsolutePath(String path, Class baseClass){ + if(path == null) return null; + if(baseClass == null) { + ClassLoader classLoader = FileUtil.class.getClassLoader(); + URL url = classLoader.getResource(path); + if(url != null) { + return url.getPath(); + }else { + return classLoader.getResource("").getPath() + path; + } + } + return baseClass.getResource(path).getPath(); + } + + /** + * 获取绝对路径,相对于classes的根目录 + * @param pathBaseClassLoader 相对路径 + * @return 绝对路径 + */ + public static String getAbsolutePath(String pathBaseClassLoader){ + return getAbsolutePath(pathBaseClassLoader, null); + } + + /** + * 文件是否存在 + * @param path 文件路径 + * @return 是否存在 + */ + public static boolean isExist(String path){ + return new File(path).exists(); + } + + /** + * 关闭 + * @param closeable 被关闭的对象 + */ + public static void close(Closeable closeable){ + if(closeable == null) return; + try { + closeable.close(); + } catch (IOException e) { + } + } + + /** + * 获得一个带缓存的写入对象 + * @param path 输出路径,绝对路径 + * @param charset 字符集 + * @param isAppend 是否追加 + * @return BufferedReader对象 + * @throws IOException + */ + public static BufferedWriter getBufferedWriter(String path, String charset, boolean isAppend) throws IOException { + return new BufferedWriter( + new OutputStreamWriter( + new FileOutputStream(touch(path), isAppend), charset + ) + ); + } + + /** + * 获得一个打印写入对象,可以有print + * @param path 输出路径,绝对路径 + * @param charset 字符集 + * @param isAppend 是否追加 + * @return 打印对象 + * @throws IOException + */ + public static PrintWriter getPrintWriter(String path, String charset, boolean isAppend) throws IOException { + return new PrintWriter(getBufferedWriter(path, charset, isAppend)); + } + + /** + * 获得一个输出流对象 + * @param path 输出到的文件路径,绝对路径 + * @return 输出流对象 + * @throws IOException + */ + public static OutputStream getOutputStream(String path) throws IOException { + return new FileOutputStream(touch(path)); + } + + /** + * 清空一个目录 + * @param dirPath 需要删除的文件夹路径 + */ + public static void cleanDir(String dirPath){ + File dir = new File(dirPath); + if(dir.exists() && dir.isDirectory()){ + File[] files = dir.listFiles(); + for (File file : files) { + if(file.isDirectory()) cleanDir(file.getAbsolutePath()); + file.delete(); + } + } + } + + /** + * 获得一个文件读取器 + * @param path 绝对路径 + * @param charset 字符集 + * @return BufferedReader对象 + * @throws IOException + */ + public static BufferedReader getReader(String path, String charset) throws IOException{ + return new BufferedReader(new InputStreamReader(new FileInputStream(path), charset)); + } + + /** + * 从文件中读取每一行数据 + * @param path 文件路径 + * @param charset 字符集 + * @param collection 集合 + * @return 文件中的每行内容的集合 + * @throws IOException + */ + public static > T loadFileLines(String path, String charset, T collection) throws IOException{ + BufferedReader reader = getReader(path, charset); + while(true){ + String line = reader.readLine(); + if(line == null) break; + collection.add(line); + } + close(reader); + return collection; + } + + /** + * 按照给定的readerHandler读取文件中的数据 + * @param readerHandler Reader处理类 + * @param path 文件的绝对路径 + * @param charset 字符集 + * @return 从文件中load出的数据 + * @throws IOException + */ + public static T loadDataFromfile(ReaderHandler readerHandler, String path, String charset) throws IOException { + BufferedReader reader = null; + T result = null; + try { + reader = getReader(path, charset); + result = readerHandler.handle(reader); + } catch (IOException e) { + throw new IOException(e); + }finally { + FileUtil.close(reader); + } + return result; + } + + /** + * 获得文件的扩展名 + * @param fileName 文件名 + * @return 扩展名 + */ + public static String getExtension(String fileName) { + if (fileName == null) { + return null; + } + int index = fileName.lastIndexOf("."); + if (index == -1) { + return ""; + } else { + String ext = fileName.substring(index + 1); + //扩展名中不能包含路径相关的符号 + return (ext.contains("/") || ext.contains("\\")) ? "" : ext; + } + } + + /** + * Reader处理接口 + * @author Luxiaolei + * + * @param + */ + public interface ReaderHandler { + public T handle(BufferedReader reader) throws IOException; + } +} diff --git a/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/HashUtil.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/HashUtil.java new file mode 100644 index 0000000000..79a5a5f8d7 --- /dev/null +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/HashUtil.java @@ -0,0 +1,383 @@ +package com.jun.plugin.commons.util; + +/** + * Hash算法大全
+ * 推荐使用FNV1算法 + * + * @author Goodzzp 2006-11-20 + */ +public class HashUtil { + + /** + * 加法hash + * + * @param key 字符串 + * @param prime 一个质数 + * @return hash结果 + */ + public static int additiveHash(String key, int prime) { + int hash, i; + for (hash = key.length(), i = 0; i < key.length(); i++) + hash += key.charAt(i); + return (hash % prime); + } + + /** + * 旋转hash + * + * @param key 输入字符串 + * @param prime 质数 + * @return hash值 + */ + public static int rotatingHash(String key, int prime) { + int hash, i; + for (hash = key.length(), i = 0; i < key.length(); ++i) + hash = (hash << 4) ^ (hash >> 28) ^ key.charAt(i); + + // 使用:hash = (hash ^ (hash>>10) ^ (hash>>20)) & mask; + // 替代:hash %= prime; + return (hash % prime); + // return (hash ^ (hash>>10) ^ (hash>>20)); + } + + + /** + * MASK值,随便找一个值,最好是质数 + */ + static int M_MASK = 0x8765fed1; + + /** + * 一次一个hash + * + * @param key 输入字符串 + * @return 输出hash值 + */ + public static int oneByOneHash(String key) { + int hash, i; + for (hash = 0, i = 0; i < key.length(); ++i) { + hash += key.charAt(i); + hash += (hash << 10); + hash ^= (hash >> 6); + } + hash += (hash << 3); + hash ^= (hash >> 11); + hash += (hash << 15); + // return (hash & M_MASK); + return hash; + } + + /** + * Bernstein's hash + * + * @param key 输入字节数组 + * @return 结果hash + */ + public static int bernstein(String key) { + int hash = 0; + int i; + for (i = 0; i < key.length(); ++i) + hash = 33 * hash + key.charAt(i); + return hash; + } + + /** + * Universal Hashing + * @param key 字节数组 + * @param mask 掩码 + * @param tab tab + * @return hash值 + */ + public static int universal(char[] key, int mask, int[] tab) { + int hash = key.length, i, len = key.length; + for (i = 0; i < (len << 3); i += 8) { + char k = key[i >> 3]; + if ((k & 0x01) == 0) + hash ^= tab[i + 0]; + if ((k & 0x02) == 0) + hash ^= tab[i + 1]; + if ((k & 0x04) == 0) + hash ^= tab[i + 2]; + if ((k & 0x08) == 0) + hash ^= tab[i + 3]; + if ((k & 0x10) == 0) + hash ^= tab[i + 4]; + if ((k & 0x20) == 0) + hash ^= tab[i + 5]; + if ((k & 0x40) == 0) + hash ^= tab[i + 6]; + if ((k & 0x80) == 0) + hash ^= tab[i + 7]; + } + return (hash & mask); + } + + /** + * Zobrist Hashing + * @param key 字节数组 + * @param mask 掩码 + * @param tab tab + * @return hash值 + */ + public static int zobrist(char[] key, int mask, int[][] tab) { + int hash, i; + for (hash = key.length, i = 0; i < key.length; ++i) + hash ^= tab[i][key[i]]; + return (hash & mask); + } + + // LOOKUP3 + // 见Bob Jenkins(3).c文件 + + // 32位FNV算法 + static int M_SHIFT = 0; + + /** + * 32位的FNV算法 + * + * @param data 数组 + * @return hash结果 + */ + public static int FNVHash(byte[] data) { + int hash = (int) 2166136261L; + for (byte b : data) + hash = (hash * 16777619) ^ b; + if (M_SHIFT == 0) + return hash; + return (hash ^ (hash >> M_SHIFT)) & M_MASK; + } + + /** + * 改进的32位FNV算法1 + * + * @param data 数组 + * @return hash结果 + */ + public static int FNVHash1(byte[] data) { + final int p = 16777619; + int hash = (int) 2166136261L; + for (byte b : data) + hash = (hash ^ b) * p; + hash += hash << 13; + hash ^= hash >> 7; + hash += hash << 3; + hash ^= hash >> 17; + hash += hash << 5; + return hash; + } + + /** + * 改进的32位FNV算法1 + * + * @param data 字符串 + * @return hash结果 + */ + public static int FNVHash1(String data) { + final int p = 16777619; + int hash = (int) 2166136261L; + for (int i = 0; i < data.length(); i++) + hash = (hash ^ data.charAt(i)) * p; + hash += hash << 13; + hash ^= hash >> 7; + hash += hash << 3; + hash ^= hash >> 17; + hash += hash << 5; + return hash; + } + + /** + * Thomas Wang的算法,整数hash + * @param key 整数 + * @return hash值 + */ + public static int intHash(int key) { + key += ~(key << 15); + key ^= (key >>> 10); + key += (key << 3); + key ^= (key >>> 6); + key += ~(key << 11); + key ^= (key >>> 16); + return key; + } + + /** + * RS算法hash + * @param str 字符串 + * @return hash值 + */ + public static int RSHash(String str) { + int b = 378551; + int a = 63689; + int hash = 0; + + for (int i = 0; i < str.length(); i++) { + hash = hash * a + str.charAt(i); + a = a * b; + } + + return (hash & 0x7FFFFFFF); + } + + /** + * JS算法 + * @param str 字符串 + * @return hash值 + */ + public static int JSHash(String str) { + int hash = 1315423911; + + for (int i = 0; i < str.length(); i++) { + hash ^= ((hash << 5) + str.charAt(i) + (hash >> 2)); + } + + return (hash & 0x7FFFFFFF); + } + + /** + * PJW算法 + * @param str 字符串 + * @return hash值 + */ + public static int PJWHash(String str) { + int BitsInUnsignedInt = 32; + int ThreeQuarters = (BitsInUnsignedInt * 3) / 4; + int OneEighth = BitsInUnsignedInt / 8; + int HighBits = 0xFFFFFFFF << (BitsInUnsignedInt - OneEighth); + int hash = 0; + int test = 0; + + for (int i = 0; i < str.length(); i++) { + hash = (hash << OneEighth) + str.charAt(i); + + if ((test = hash & HighBits) != 0) { + hash = ((hash ^ (test >> ThreeQuarters)) & (~HighBits)); + } + } + + return (hash & 0x7FFFFFFF); + } + + /** + * ELF算法 + * @param str 字符串 + * @return hash值 + */ + public static int ELFHash(String str) { + int hash = 0; + int x = 0; + + for (int i = 0; i < str.length(); i++) { + hash = (hash << 4) + str.charAt(i); + if ((x = (int) (hash & 0xF0000000L)) != 0) { + hash ^= (x >> 24); + hash &= ~x; + } + } + + return (hash & 0x7FFFFFFF); + } + + /** + * BKDR算法 + * @param str 字符串 + * @return hash值 + */ + public static int BKDRHash(String str) { + int seed = 131; // 31 131 1313 13131 131313 etc.. + int hash = 0; + + for (int i = 0; i < str.length(); i++) { + hash = (hash * seed) + str.charAt(i); + } + + return (hash & 0x7FFFFFFF); + } + + /** + * SDBM算法 + * @param str 字符串 + * @return hash值 + */ + public static int SDBMHash(String str) { + int hash = 0; + + for (int i = 0; i < str.length(); i++) { + hash = str.charAt(i) + (hash << 6) + (hash << 16) - hash; + } + + return (hash & 0x7FFFFFFF); + } + + /** + * DJB算法 + * @param str 字符串 + * @return hash值 + */ + public static int DJBHash(String str) { + int hash = 5381; + + for (int i = 0; i < str.length(); i++) { + hash = ((hash << 5) + hash) + str.charAt(i); + } + + return (hash & 0x7FFFFFFF); + } + + /** + * DEK算法 + * @param str 字符串 + * @return hash值 + */ + public static int DEKHash(String str) { + int hash = str.length(); + + for (int i = 0; i < str.length(); i++) { + hash = ((hash << 5) ^ (hash >> 27)) ^ str.charAt(i); + } + + return (hash & 0x7FFFFFFF); + } + + /** + * AP算法 + * @param str 字符串 + * @return hash值 + */ + public static int APHash(String str) { + int hash = 0; + + for (int i = 0; i < str.length(); i++) { + hash ^= ((i & 1) == 0) ? ((hash << 7) ^ str.charAt(i) ^ (hash >> 3)) + : (~((hash << 11) ^ str.charAt(i) ^ (hash >> 5))); + } + + // return (hash & 0x7FFFFFFF); + return hash; + } + + /** + * JAVA自己带的算法 + * @param str 字符串 + * @return hash值 + */ + public static int javaDefaultHash(String str) { + int h = 0; + int off = 0; + int len = str.length(); + for (int i = 0; i < len; i++) { + h = 31 * h + str.charAt(off++); + } + return h; + } + + /** + * 混合hash算法,输出64位的值 + * @param str 字符串 + * @return hash值 + */ + public static long mixHash(String str) { + long hash = str.hashCode(); + hash <<= 32; + hash |= FNVHash1(str); + return hash; + } +} \ No newline at end of file diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/IoUtil.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/IoUtil.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/IoUtil.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/IoUtil.java diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/LangUtil.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/LangUtil.java similarity index 99% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/LangUtil.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/LangUtil.java index a6a8318428..d192f32e35 100644 --- a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/LangUtil.java +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/LangUtil.java @@ -222,7 +222,7 @@ public static String transCharset(String str, String sourceCharset, String destC /** * 基本变量类型的枚举 - * @author Wujun + * @author Luxiaolei * */ private static enum BASIC_TYPE { diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/MessageUtils.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/MessageUtils.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/MessageUtils.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/MessageUtils.java diff --git a/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/RegexUtil.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/RegexUtil.java new file mode 100644 index 0000000000..1b0bdeaa01 --- /dev/null +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/RegexUtil.java @@ -0,0 +1,120 @@ +package com.jun.plugin.commons.util; + +import java.util.Collection; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * 正则相关工具类 + * + * @author 路小磊 luxiaolei@baijob.com + */ +public class RegexUtil { + + private RegexUtil() { + //阻止实例化 + } + + /** + * 获得匹配的字符串 + * + * @param regex 匹配的正则 + * @param content 被匹配的内容 + * @param groupIndex 匹配正则的分组序号 + * @return 匹配后得到的字符串,未匹配返回null + */ + public static String get(String regex, String content, int groupIndex) { + Matcher matcher = Pattern.compile(regex, Pattern.MULTILINE).matcher(content); + if (matcher.find()) { + return matcher.group(groupIndex); + } + return null; + } + + /** + * 删除匹配的内容 + * + * @param regex 正则 + * @param content 被匹配的内容 + * @return 删除后剩余的内容 + */ + public static String delFirst(String regex, String content) { + return content.replaceFirst(regex, ""); + } + + /** + * 删除正则匹配到的内容之前的字符 如果没有找到,则返回原文 + * + * @param regex 定位正则 + * @param content 被查找的内容 + * @return 删除前缀后的新内容 + */ + public static String delPreLocation(String regex, String content) { + Matcher matcher = Pattern.compile(regex, Pattern.MULTILINE).matcher(content); + if (matcher.find()) { + return content.substring(matcher.end(), content.length()); + } + return content; + } + + /** + * 取得内容中匹配的所有结果 + * + * @param regex 正则 + * @param content 被查找的内容 + * @param group 正则的分组 + * @param collection 返回的集合类型 + * @return 结果集 + */ + @Deprecated + public static > T gets(String regex, String content, int group, T collection) { + while (true) { + String result = get(regex, content, group); + if (result == null) break; + collection.add(result); + content = delPreLocation(regex, content); + } + return collection; + } + + /** + * 取得内容中匹配的所有结果 + * + * @param regex 正则 + * @param content 被查找的内容 + * @param group 正则的分组 + * @param collection 返回的集合类型 + * @return 结果集 + */ + public static > T findAll(String regex, String content, int group, T collection) { + Matcher matcher = Pattern.compile(regex, Pattern.MULTILINE).matcher(content); + while(matcher.find()){ + collection.add(matcher.group(group)); + } + return collection; + } + + /** + * 从字符串中获得第一个整数 + * + * @param StringWithNumber 带数字的字符串 + * @return 整数 + */ + public static int getFirstNumber(String StringWithNumber) { + return Integer.parseInt(get("\\d+", StringWithNumber, 0)); + } + + /** + * 判断该字符串是否是IPV4地址 + * + * @param ip IP地址 + * @return 是否是IPV4 + */ + public static boolean isIpv4(String ip) { + if(LangUtil.isEmpty(ip)){ + return false; + } + String regex = "\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b"; + return Pattern.matches(regex, ip); + } +} diff --git a/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/SecureUtil.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/SecureUtil.java new file mode 100644 index 0000000000..02160c342e --- /dev/null +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/SecureUtil.java @@ -0,0 +1,77 @@ +package com.jun.plugin.commons.util; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.zip.CRC32; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.sun.mail.util.BASE64EncoderStream; + +/** + * 安全相关的工具类,包括各种加密算法 + * @author xiaoleilu + * + */ +public class SecureUtil { + private static Logger logger = LoggerFactory.getLogger(SecureUtil.class); + + /** + * 获得指定字符串的MD5码 + * @param key 字符串 + * @return MD5 + */ + public static String md5(String key) { + return digest(ALGORITHM.MD5, key); + } + + public static String sha1(String key) { + return digest(ALGORITHM.SHA1, key); + } + + /** + * 对给定的byte数组做base64编码 + * @param bytes byte数组 + * @return base64编码 + */ + public static String base64Encode(byte[] bytes){ + return new String(BASE64EncoderStream.encode(bytes)); + } + + public static long crc32(String key) { + CRC32 crc32 = new CRC32(); + crc32.update(key.getBytes()); + return crc32.getValue(); + } + + /** + * 计算指定加密算法后生成的结果 + * @param algorithm 加密算法枚举 + * @param key 字符串 + * @return 加密后的结果 + */ + private static String digest(ALGORITHM algorithm, String key) { + MessageDigest instance = null; + try { + instance = MessageDigest.getInstance(algorithm.toString()); + } catch (NoSuchAlgorithmException e) { + logger.error("No such Algorit!", e); + return null; + } + if(instance != null) { + instance.update(key.getBytes()); + return new String(BASE64EncoderStream.encode(instance.digest())); + } + return null; + } + + /** + * 加密算法枚举 + * @author xiaoleilu + * + */ + enum ALGORITHM{ + MD5, SHA1; + } +} diff --git a/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/Setting.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/Setting.java new file mode 100644 index 0000000000..af35dc93d6 --- /dev/null +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/Setting.java @@ -0,0 +1,478 @@ +package com.jun.plugin.commons.util; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.lang.reflect.Method; +import java.net.URL; +import java.nio.charset.Charset; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.jun.plugin.commons.util.Exceptions.SettingException; +import com.jun.plugin.commons.util.net.URLUtil; + +/** + * 设置工具类。 用于支持设置文件 1、支持变量,默认变量命名为 + * + * @author Luxiaolei + * + */ +public class Setting extends HashMap { + private static final long serialVersionUID = -477527787843971824L; + private static Logger logger = LoggerFactory.getLogger(Setting.class); + + /** 默认字符集 */ + public final static String DEFAULT_CHARSET = "utf8"; + + /** 注释符号(当有此符号在行首,表示此行为注释) */ + private final static String COMMENT_FLAG_PRE = "#"; + /** 赋值分隔符(用于分隔键值对) */ + private final static String ASSIGN_FLAG = "="; + /** 分组行识别的环绕标记 */ + private final static char[] GROUP_SURROUND = { '[', ']' }; + /** 变量名称的正则 */ + private String reg_var = "\\$\\{(.*?)\\}"; + + /** 本设置对象的字符集 */ + private Charset charset; + /** 是否使用变量 */ + private boolean isUseVariable; + /** 设定文件的URL */ + private URL settingUrl; + /** 分组的缓存 */ + private String group_cache; + + /** + * 基本构造
+ * 需自定义初始化配置文件
+ * + * @param charset 字符集 + * @param isUseVariable 是否使用变量 + */ + public Setting(Charset charset, boolean isUseVariable) { + this.charset = charset; + this.isUseVariable = isUseVariable; + } + + /** + * 构造,使用相对于Class文件根目录的相对路径 + * + * @param pathBaseClassLoader 相对路径(相对于当前项目的classes路径) + * @param charset 字符集 + * @param isUseVariable 是否使用变量 + */ + public Setting(String pathBaseClassLoader, String charset, boolean isUseVariable) { + URL url = URLUtil.getURL(pathBaseClassLoader); + this.init(url, charset, isUseVariable); + } + + /** + * 构造 + * + * @param configFile 配置文件对象 + * @param charset 字符集 + * @param isUseVariable 是否使用变量 + */ + public Setting(File configFile, String charset, boolean isUseVariable) { + if (configFile == null) { + logger.error("请指定配置文件!"); + return; + } + URL url = URLUtil.getURL(configFile); + this.init(url, charset, isUseVariable); + } + + /** + * 构造,相对于classes读取文件 + * + * @param path 相对路径 + * @param clazz 基准类 + * @param charset 字符集 + * @param isUseVariable 是否使用变量 + */ + public Setting(String path, Class clazz, String charset, boolean isUseVariable) { + URL url = URLUtil.getURL(path, clazz); + this.init(url, charset, isUseVariable); + } + + /** + * 构造 + * + * @param url 设定文件的URL + * @param charset 字符集 + * @param isUseVariable 是否使用变量 + */ + public Setting(URL url, String charset, boolean isUseVariable) { + this.init(url, charset, isUseVariable); + } + + /*--------------------------公有方法 start-------------------------------*/ + /** + * 初始化设定文件 + * + * @param settingUrl 设定文件的URL + * @param charset 字符集 + * @param isUseVariable 是否使用变量 + * @return 成功初始化与否 + */ + public boolean init(URL settingUrl, String charset, boolean isUseVariable) { + if (settingUrl == null || LangUtil.isEmpty(charset)) { + logger.error("给定参数无效!"); + return false; + } + this.charset = Charset.forName(charset); + this.isUseVariable = isUseVariable; + this.settingUrl = settingUrl; + + return this.load(settingUrl); + } + + /** + * 加载设置文件 + * + * @param settingUrl 配置文件URL + * @return 加载是否成功 + */ + public boolean load(URL settingUrl) { + if (settingUrl == null) { + logger.error("Define setting url is null, please chech it !"); + return false; + } + logger.debug("Load setting file=>" + settingUrl.getPath()); + InputStream settingStream = null; + try { + settingStream = settingUrl.openStream(); + load(settingStream, isUseVariable); + } catch (IOException e) { + logger.error("Load setting error!", e); + return false; + } finally { + FileUtil.close(settingStream); + } + return true; + } + + /** + * 重新加载配置文件 + */ + public void reload() { + this.load(settingUrl); + } + + /** + * 加载设置文件。 此方法不会关闭流对象 + * + * @param settingStream 文件流 + * @param isUseVariable 是否使用变量(替换配置文件值中含有的变量) + * @return 加载成功与否 + * @throws IOException + */ + public boolean load(InputStream settingStream, boolean isUseVariable) throws IOException { + this.clear(); + BufferedReader reader = new BufferedReader(new InputStreamReader(settingStream, charset)); + + while (true) { + String line = reader.readLine(); + if (line == null) { + break; + } + line = line.trim(); + // 跳过注释行和空行 + if (LangUtil.isEmpty(line) || line.startsWith(COMMENT_FLAG_PRE)) { + continue; + } + + // 记录分组名 + if (line.charAt(0) == GROUP_SURROUND[0] && line.charAt(line.length() - 1) == GROUP_SURROUND[1]) { + this.group_cache = line.substring(1, line.length() - 1).trim(); + } + + String[] keyValue = line.split(ASSIGN_FLAG, 2); + // 跳过不符合简直规范的行 + if (keyValue.length < 2) { + continue; + } + + String key = keyValue[0].trim(); + if (!LangUtil.isEmpty(this.group_cache)) { + key = this.group_cache + "." + key; + } + String value = keyValue[1].trim(); + + // 替换值中的所有变量变量(变量必须是此行之前定义的变量,否则无法找到) + if (isUseVariable) { + // 找到所有变量标识 + Set vars = RegexUtil.findAll(reg_var, value, 0, new HashSet()); + for (String var : vars) { + // 查找变量名对应的值 + String varValue = this.get(RegexUtil.get(reg_var, var, 1)); + if (varValue != null) { + // 替换标识 + value = value.replace(var, varValue); + } + } + } + put(key, value); + } + FileUtil.close(reader); + this.group_cache = null; + return true; + } + + /** + * 设置变量的正则
+ * 正则只能有一个group表示变量本身,剩余为字符 例如 \$\{(name)\}表示${name}变量名为name的一个变量表示 + * + * @param regex 正则 + */ + public void setVarRegex(String regex) { + this.reg_var = regex; + } + + /** + * 带有日志提示的get,如果没有定义指定的KEY,则打印debug日志 + * + * @param key 键 + * @return 值 + */ + public String getWithLog(String key) { + String value = super.get(key); + if (value == null) { + logger.debug("No key define for [{}]!", key); + } + return value; + } + + /** + * 获得指定分组的键对应值 + * + * @param key 键 + * @param group 分组 + * @return 值 + */ + public String get(String key, String group) { + String keyWithGroup = key; + if (!LangUtil.isEmpty(group)) { + keyWithGroup = group + "." + keyWithGroup; + } + return get(keyWithGroup); + } + + /** + * 获取字符型型属性值 + * + * @param key 属性名 + * @return 属性值 + */ + public String getString(String key) { + return getString(key, null); + } + + /** + * 获取字符型型属性值 + * + * @param key 属性名 + * @param group 分组名 + * @return 属性值 + */ + public String getString(String key, String group) { + return get(key, group); + } + + /** + * 获取数字型型属性值 + * + * @param key 属性名 + * @return 属性值 + */ + public int getInt(String key) throws NumberFormatException { + return getInt(key, null); + } + + /** + * 获取数字型型属性值 + * + * @param key 属性名 + * @param group 分组名 + * @return 属性值 + */ + public int getInt(String key, String group) throws NumberFormatException { + return Integer.parseInt(get(key, group)); + } + + /** + * 获取波尔型属性值 + * + * @param key 属性名 + * @return 属性值 + */ + public boolean getBool(String key) throws NumberFormatException { + return getBool(key, null); + } + + /** + * 获取波尔型属性值 + * + * @param key 属性名 + * @param group 分组名 + * @return 属性值 + */ + public boolean getBool(String key, String group) throws NumberFormatException { + return Boolean.parseBoolean(get(key, group)); + } + + /** + * 获取long类型属性值 + * + * @param key 属性名 + * @return 属性值 + */ + public long getLong(String key) throws NumberFormatException { + return getLong(key, null); + } + + /** + * 获取long类型属性值 + * + * @param key 属性名 + * @param group 分组名 + * @return 属性值 + */ + public long getLong(String key, String group) throws NumberFormatException { + return Long.parseLong(get(key, group)); + } + + /** + * 获取char类型属性值 + * + * @param key 属性名 + * @return 属性值 + */ + public char getChar(String key) { + return getChar(key, null); + } + + /** + * 获取char类型属性值 + * + * @param key 属性名 + * @param group 分组名 + * @return 属性值 + */ + public char getChar(String key, String group) { + return get(key, group).charAt(0); + } + + /** + * 获取double类型属性值 + * + * @param key 属性名 + * @return 属性值 + */ + public double getDouble(String key) throws NumberFormatException { + return getDouble(key, null); + } + + /** + * 获取double类型属性值 + * + * @param key 属性名 + * @param group 分组名 + * @return 属性值 + */ + public double getDouble(String key, String group) throws NumberFormatException { + return Double.parseDouble(get(key, group)); + } + + /** + * 设置值,无给定键创建之。设置后未持久化 + * + * @param key 键 + * @param value 值 + */ + public void setSetting(String key, Object value) { + put(key, value.toString()); + } + + /** + * 持久化当前设置,会覆盖掉之前的设置
+ * 持久化会不会保留之前的分组 + * @param absolutePath 设置文件的绝对路径 + */ + public void store(String absolutePath) { + try { + FileUtil.touch(absolutePath); + OutputStream out = FileUtil.getOutputStream(absolutePath); + BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, charset)); + Set> entrySet = this.entrySet(); + for (java.util.Map.Entry entry : entrySet) { + writer.write(entry.getKey() + ASSIGN_FLAG + entry.getValue()); + } + writer.close(); + } catch (FileNotFoundException e) { + // 不会出现这个异常 + } catch (IOException e) { + logger.error("存储设置时出现异常。", e); + } + } + + /** + * 存储当前设置,会覆盖掉以前的设置 + * + * @param path 相对路径 + * @param clazz 相对的类 + */ + public void store(String path, Class clazz) { + this.store(FileUtil.getAbsolutePath(path, clazz)); + } + + /** + * 将setting中的键值关系映射到对象中,原理是调用对象对应的set方法
+ * 只支持基本类型的转换 + * + * @param object 被调用的对象 + * @throws SettingException + */ + public void settingToObject(String group, Object object) throws SettingException { + try { + Method[] methods = object.getClass().getMethods(); + for (Method method : methods) { + String methodName = method.getName(); + if (methodName.startsWith("set")) { + String field = LangUtil.getGeneralField(methodName); + Object value = get(field, group); + if (value != null) { + Object castedValue = LangUtil.cast(method.getParameterTypes()[0], value); + method.invoke(object, castedValue); + logger.debug("Set {}=>{}", field, value); + } + } + } + } catch (Exception e) { + throw new SettingException("转换设置至对象出现异常", e); + } + } + + /** + * 将setting中的键值关系映射到对象中,原理是调用对象对应的set方法
+ * 只支持基本类型的转换 + * + * @param object + * @throws SettingException + */ + public void settingToObject(Object object) throws SettingException { + settingToObject(null, object); + } + /*--------------------------公有方法 end-------------------------------*/ +} diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/Span.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/Span.java similarity index 99% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/Span.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/Span.java index 401112a3b4..a4f393434b 100644 --- a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/Span.java +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/Span.java @@ -7,7 +7,7 @@ * 数据区间对象 * 存放ID最小和最大值 * 包含一个区间的完整性信息。 - * @author Wujun + * @author Luxiaolei * */ public class Span { diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/TaskScheduler.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/TaskScheduler.java similarity index 97% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/TaskScheduler.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/TaskScheduler.java index 43a89c00a7..d452c2b39b 100644 --- a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/TaskScheduler.java +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/TaskScheduler.java @@ -8,7 +8,7 @@ import org.slf4j.LoggerFactory; /** * 任务调度类 - * @author Wujun + * @author luxiaolei@baijob.com */ public class TaskScheduler extends Timer{ private static Logger logger = LoggerFactory.getLogger(TaskScheduler.class); diff --git a/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/XmlUtil.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/XmlUtil.java new file mode 100644 index 0000000000..34690f789e --- /dev/null +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/XmlUtil.java @@ -0,0 +1,151 @@ +package com.jun.plugin.commons.util; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.URL; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; + +import org.dom4j.Document; +import org.dom4j.DocumentException; +import org.dom4j.DocumentHelper; +import org.dom4j.io.OutputFormat; +import org.dom4j.io.SAXReader; +import org.dom4j.io.SAXValidator; +import org.dom4j.io.XMLWriter; +import org.dom4j.util.XMLErrorHandler; +import org.xml.sax.SAXException; + +/** + * DOM工具类,处理XML + * @author luxiaolei@baijob.com + */ +public class XmlUtil { + /** 在XML中无效的字符 正则 */ + public final static String INVALID_REGEX = "[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]"; + + /** + * 从字符串中获得DOM对象 + * @param xmlString xml字符串 + * @return DOM对象 + * @throws DocumentException + */ + public static Document parseDoc(String xmlString) throws DocumentException{ + return DocumentHelper.parseText(cleanInvalid(xmlString)); + } + + /** + * 从文件获得DOM对象 + * @param xmlPathBaseClassLoader 相对路径(相对于当前项目的classes路径) + * @return DOM 对象 + * @throws DocumentException + */ + public static Document readDoc(String xmlPathBaseClassLoader) throws DocumentException{ + return new SAXReader().read(XmlUtil.class.getClassLoader().getResourceAsStream(xmlPathBaseClassLoader)); + } + + /** + * 从文件获得DOM对象 + * @param xmlFile xml文件对象 + * @return DOM对象 + * @throws DocumentException + */ + public static Document readDoc(File xmlFile) throws DocumentException{ + return new SAXReader().read(xmlFile); + } + + /** + * 从URL获得DOM对象 + * @param url XML的URL + * @return DOM对象 + * @throws DocumentException + * @throws IOException + */ + public static Document readDoc(URL url) throws DocumentException, IOException{ + return new SAXReader().read(url.openStream()); + } + + /** + * 创建一个空XML + * @param rootElementName 根节点名 + * @return XML对象 + */ + public static Document createDoc(String rootElementName){ + Document doc = DocumentHelper.createDocument(); + doc.addElement(rootElementName); + return doc; + } + + /** + * 写入XML到文件 + * @param doc XML文档 + * @param filePath 文件的路径 + * @param charset 字符集 + * @param isEscapeText 是否对特殊字符转义 + * @throws IOException + */ + public static void xmlWriteToFile(Document doc, String filePath, String charset, boolean isEscapeText) throws IOException { + OutputFormat outputFormat = OutputFormat.createPrettyPrint(); + outputFormat.setEncoding(charset); + XMLWriter writer = null; + try { + writer = new XMLWriter(FileUtil.getBufferedWriter(filePath, charset, false), outputFormat); + writer.setEscapeText(isEscapeText); + writer.write(doc); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } catch (FileNotFoundException e) { + //不会发生此异常(在getBufferedWriter方法中已经做了自动创建文件操作) + e.printStackTrace(); + } finally { + if(writer != null) writer.close(); + } + } + + /** + * 检验指定的XML是否符合 + * @param doc 被检验的XML文档 + * @param schemePath schema的路径 + * @return 如果出错,返回错误信息,否则返回null + * @throws ParserConfigurationException + * @throws SAXException + * @throws DocumentException + */ + public static String validateBySchema(Document doc, String schemePath) throws ParserConfigurationException, SAXException, DocumentException{ + XMLErrorHandler errorHandler = new XMLErrorHandler(); + SAXParserFactory factory = SAXParserFactory.newInstance(); + factory.setValidating(true); + factory.setNamespaceAware(true); + SAXParser parser = factory.newSAXParser(); + + parser.setProperty( + "http://java.sun.com/xml/jaxp/properties/schemaLanguage", + "http://www.w3.org/2001/XMLSchema"); + parser.setProperty( + "http://java.sun.com/xml/jaxp/properties/schemaSource", + "file:" + schemePath); + + SAXValidator validator = new SAXValidator(parser.getXMLReader()); + validator.setErrorHandler(errorHandler); + validator.validate(doc); + + if (errorHandler.getErrors().hasContent()) { + return errorHandler.getErrors().asXML(); + } + return null; + } + + /** + * 去除XML文本中的无效字符 + * @param xmlContent XML文本 + * @return 当传入为null时返回null + */ + public static String cleanInvalid(String xmlContent){ + if (xmlContent == null) return null; + return xmlContent.replaceAll(INVALID_REGEX, ""); + } +} diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/ZhUtil.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/ZhUtil.java similarity index 99% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/ZhUtil.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/ZhUtil.java index d3a82d4671..bf890126dd 100644 --- a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/ZhUtil.java +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/ZhUtil.java @@ -3,7 +3,7 @@ /** * 中文相关工具类 * - * @author Wujun + * @author Luxiaolei * */ public class ZhUtil { diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/CollectionUtil.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/CollectionUtil.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/CollectionUtil.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/CollectionUtil.java diff --git a/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/DateUtil.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/DateUtil.java new file mode 100644 index 0000000000..acb5cd84d6 --- /dev/null +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/DateUtil.java @@ -0,0 +1,394 @@ +package com.jun.plugin.commons.util.apiext; + +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; + +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; + +import org.apache.commons.beanutils.PropertyUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.jun.plugin.commons.util.constant.MathConvertType; +import com.jun.plugin.commons.util.constant.SimpleDateFormatCase; +import com.jun.plugin.commons.util.constant.StrPattern; +import com.jun.plugin.commons.util.exception.ProjectException; + +/** + * @ClassName: DateUtil + * @Description: 时间相关的常用用法 + * @author 周俊辉 + * @date 2010-10-29 下午01:37:06 + * + */ +public abstract class DateUtil { + public static Logger logger = LoggerFactory.getLogger(DateUtil.class); + + public static Date objToDate(Object ojbDate, DateFormat formate) { + if (ojbDate == null) { + return null; + } + Date date = null; + if (ojbDate instanceof Date) { + date = (Date) ojbDate; + } else if (ojbDate instanceof java.sql.Date) { + java.sql.Date tempObj = (java.sql.Date) ojbDate; + date = new java.util.Date(tempObj.getTime()); + } else if (ojbDate instanceof XMLGregorianCalendar) { + date = xmlDateToDate((XMLGregorianCalendar) ojbDate); + } else if (ojbDate instanceof String) { + String strDate = String.valueOf(ojbDate); + try { + if (formate != null) { + date = formate.parse(strDate); + } else { + if (StrPattern.date.checkStrFormat(strDate)) { + strDate = strDate + " 00:00:00"; + } + if (StrPattern.date_time.checkStrFormat(String + .valueOf(strDate)) + && !"0001-01-01 00:00:00".equals(ojbDate) + && !"1970-01-01 00:00:00".equals(ojbDate)) { + date = SimpleDateFormatCase.YYYY_MM_DD_hhmmss + .getInstanc().parse(strDate); + } + } + } catch (Exception e) { + throw new IllegalArgumentException("String转换为Date类型错误"); + } + } + + if (date == null) { + throw new IllegalArgumentException("不支持的数据类型,不能转为Date类型"); + } else { + return date; + } + } + + /**** + * 把Bean的某个字段格式化为String + * + * @param bean + * 要格式化的Bean + * @param path + *    要格式化的字段所在路径 + * @param format + * 要格式化的格式 + * @param isTime + * 是不是时间,默认为日期 + * @return + */ + public static String formatDate(Object bean, String path, String format, + Boolean isTime) { + if (StringUtil.isNull(path)) { + return ""; + } + try { + Object obj = PropertyUtils.getProperty(bean, path); + Date curDate = DateUtil.objToDate(obj); + if (curDate == null) { + return ""; + } + return formatDate(curDate, format, isTime); + } catch (Exception e) { + e.printStackTrace(); + } + return ""; + } + + /*** + * 把Date格式化为String ,时间:yyyy-MM-dd HH:mm:ss 日期:yyyy-MM-dd + * + * @param oriDate + * 要格式化的时间 + * @param format + * 要格式化的格式 + * @param isTime + * 是不是时间,默认为日期 + * @return + */ + public static String formatDate(Date oriDate, String format, Boolean isTime) { + if (oriDate == null) { + return ""; + } + String formatStr = StringUtil.hasNull(format, + (isTime != null && isTime) ? "yyyy-MM-dd HH:mm:ss" + : "yyyy-MM-dd"); + SimpleDateFormat curFormat = new SimpleDateFormat(formatStr); + return curFormat.format(oriDate); + } + + /**** + * 把对象转换成Date Formate为 yyyy-MM-dd HH:mm:ss + * + * @param xmlDate + * @return + */ + public static Date objToDate(Object ojbDate) { + return objToDate(ojbDate, null); + } + + /** + * 今天的0时0分0秒0毫秒 + * */ + public static Date setDayBeginTime(Date date) { + Calendar ca = Calendar.getInstance(); + ca.setTime(date); + ca.set(Calendar.HOUR_OF_DAY, 0); + ca.set(Calendar.MINUTE, 0); + ca.set(Calendar.SECOND, 0); + ca.set(Calendar.MILLISECOND, 0); + return ca.getTime(); + } + + /*** + * 指定时间的相隔一定天数的0时0分0秒0毫秒 + * + * @param date + * @param num + * @return + */ + public static Date setDayAfterBeginTime(Date date, int num) { + Calendar ca = Calendar.getInstance(); + ca.setTime(date); + ca.add(Calendar.DATE, num); + ca.set(Calendar.HOUR_OF_DAY, 0); + ca.set(Calendar.MINUTE, 0); + ca.set(Calendar.SECOND, 0); + ca.set(Calendar.MILLISECOND, 0); + return ca.getTime(); + } + + /**** + * 指定时间的相隔一定月份的 0时0分0秒0毫秒 + * + * @param date + * @param monthNum + * @return + */ + public static Date setDayAfterMonthTime(Date date, int monthNum) { + Calendar ca = Calendar.getInstance(); + ca.setTime(date); + ca.add(Calendar.MONTH, monthNum); + ca.set(Calendar.HOUR_OF_DAY, 0); + ca.set(Calendar.MINUTE, 0); + ca.set(Calendar.SECOND, 0); + ca.set(Calendar.MILLISECOND, 0); + return ca.getTime(); + } + + /** + * 两个时间的相差天数 + * */ + public static int differDays(Date beginData, Date endDate) { + long resL = endDate.getTime() - beginData.getTime(); + long dayInt = resL / 1000 * 60 * 60 * 24; + return Integer.parseInt(Long.toString(dayInt)); + } + + /** + * beginData+days是否比endDate大 + * + * @param beginData + * 基准时间 + * @param days + * 相差天数 + * @param endDate + * 比较时间 + * @return 0等于 -1小于 1大于 + * */ + public static int compareTo(Date beginData, int days, Date endDate) { + Calendar ca = Calendar.getInstance(); + ca.setTime(beginData); + ca.add(Calendar.DATE, days); + Calendar otherCal = Calendar.getInstance(); + otherCal.setTime(endDate); + return ca.compareTo(otherCal); + } + + /** + * beginData+month是否比endDate大 + * + * @param beginData + * 基准时间 + * @param month + * 相差月份数 + * @param endDate + * 比较时间 + * @return 0等于 -1小于 1大于 + * */ + public static int compareMonthTo(Date beginData, int month, Date endDate) { + Calendar ca = Calendar.getInstance(); + ca.setTime(beginData); + ca.add(Calendar.MONTH, month); + Calendar otherCal = Calendar.getInstance(); + otherCal.setTime(endDate); + return ca.compareTo(otherCal); + } + + /** + * 这个月的最后一天开始 + * */ + public static Date getLastDayOfMonth(Date date) { + Calendar ca = Calendar.getInstance(); + ca.setTime(date); + ca.add(Calendar.MONTH, 1); + ca.set(Calendar.DATE, 1); + ca.add(Calendar.DATE, -1); + ca.set(Calendar.HOUR_OF_DAY, 0); + ca.set(Calendar.MINUTE, 0); + ca.set(Calendar.SECOND, 0); + ca.set(Calendar.MILLISECOND, 0); + return ca.getTime(); + } + + /** + * 通过两个ISO时间字符合并为一个时间,取第一个的日期,取第两个的时间 + * + * @param dateStr1 + * 取天数, 如:2011-09-09T16:00:00Z + * @param dateStr2 + * 取时间 如:1970-01-01T07:00:00Z + * @throws ProjectException + * */ + public static Date getDateByTwoIso(String dateStr1, String dateStr2) { + try { + int jIndex = dateStr1.indexOf("+"); + dateStr1 = dateStr1.substring(0, jIndex) + "GMT" + + dateStr1.substring(jIndex); + int j2Index = dateStr2.indexOf("+"); + dateStr2 = dateStr2.substring(0, j2Index) + "GMT" + + dateStr2.substring(j2Index); + + Calendar returnDateTime = Calendar.getInstance(); + Date dateD = SimpleDateFormatCase.TyyyyMMddHHmmss.getInstanc() + .parse(dateStr1); + Date dateT = SimpleDateFormatCase.TyyyyMMddHHmmss.getInstanc() + .parse(dateStr2); + Calendar calDateT = Calendar.getInstance(); + returnDateTime.setTime(dateD); + calDateT.setTime(dateT); + returnDateTime.set(Calendar.HOUR, calDateT.get(Calendar.HOUR)); + returnDateTime.set(Calendar.MINUTE, calDateT.get(Calendar.MINUTE)); + returnDateTime.set(Calendar.SECOND, calDateT.get(Calendar.SECOND)); + return returnDateTime.getTime(); + } catch (ParseException e) { + logger.error("解析时间错误", e); + return null; + } + } + + /** + * 通过两个ISO时间字符合并为一个时间,取第一个的日期,取第两个的时间 + * + * @param dateStr1 + * 取天数, 如:2011-09-09 + * @param dateStr2 + * 取时间 如:T16:00:00 + * */ + public static Date getDateByStr(String dateStr1, String dateStr2) { + if (StringUtil.isNull(dateStr1) || StringUtil.isNull(dateStr2)) { + return null; + } + String tempDateStr = String.format("%s %s", dateStr1, dateStr2); + try { + Date dateT = SimpleDateFormatCase.TyyyyMMddHHmmssNoZ.getInstanc() + .parse(tempDateStr); + return dateT; + } catch (ParseException e) { + logger.error("解析时间错误", e); + return null; + } + } + + /*** + * XMLGregorianCalendar 转为Date + * + * @param xmlDate + * @return + */ + public static Date xmlDateToDate(XMLGregorianCalendar xmlDate) { + return xmlDate.toGregorianCalendar().getTime(); + } + + /*** + * Dae 转为 XMLGregorianCalendar + * + * @param date + * @return + */ + public static XMLGregorianCalendar dateToXmlDate(Date date) { + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + DatatypeFactory dtf = null; + try { + dtf = DatatypeFactory.newInstance(); + } catch (DatatypeConfigurationException e) { + } + XMLGregorianCalendar dateType = dtf.newXMLGregorianCalendar(); + dateType.setYear(cal.get(Calendar.YEAR)); + // 由于Calendar.MONTH取值范围为0~11,需要加1 + dateType.setMonth(cal.get(Calendar.MONTH) + 1); + dateType.setDay(cal.get(Calendar.DAY_OF_MONTH)); + dateType.setHour(cal.get(Calendar.HOUR_OF_DAY)); + dateType.setMinute(cal.get(Calendar.MINUTE)); + dateType.setSecond(cal.get(Calendar.SECOND)); + return dateType; + } + + /*** + * 得到明天的0点时间 + * + * @param ojbDate + * @return + */ + public static Date getTomorrow(Object ojbDate) { + Date ret = objToDate(ojbDate); + ret = setDayAfterBeginTime(ret, 1); + return ret; + } + + /*** + * 得到明天的0点时间 + * + * @param ojbDate + * @return + */ + public static String getTomorrowStr(Object ojbDate) { + Date ori = getTomorrow(ojbDate); + return SimpleDateFormatCase.YYYY_MM_DD.getInstanc().format(ori); + } + + /*** + * 把秒数转为分钟数 + * + * @param min + * 秒数 + * @param conType + * 转换类型,分为trunc("取整"),round("四舍五入"),ceil("有值进1") + * @return 分钟数 + */ + public static int convertMinuteToSecond(int min, MathConvertType conType) { + int retValue = 0; + switch (conType) { + case trunc: + retValue = (int) Math.floor((float) min / 60); + break; + case round: + retValue = (int) Math.rint((float) min / 60); + break; + case ceil: + retValue = (int) Math.ceil((float) min / 60); + break; + default: + break; + } + return retValue; + } + +} diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/DynaBeanUtil.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/DynaBeanUtil.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/DynaBeanUtil.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/DynaBeanUtil.java diff --git a/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/IOUtil.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/IOUtil.java new file mode 100644 index 0000000000..632b955d58 --- /dev/null +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/IOUtil.java @@ -0,0 +1,137 @@ +package com.jun.plugin.commons.util.apiext; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URL; +import java.util.Properties; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.jun.plugin.commons.util.exception.ExceptAll; +import com.jun.plugin.commons.util.exception.ProjectException; + +/** + * @ClassName: IOUtil + * @Description: TODO(这里用一句话描述这个类的作用) + * @author 周俊辉 + * @date 2010-11-13 上午11:01:04 + * + */ +public abstract class IOUtil { + public static Logger logger = LoggerFactory.getLogger(IOUtil.class); + + /** + * 转换输入流为字符串 + * + * @param in + * 输入流 + * @return java.lang.String 转换后的字符串 + * @throws IOException + */ + public static String slurp(InputStream in) throws IOException { + StringBuffer out = new StringBuffer(); + byte[] b = new byte[4096]; + for (int n; (n = in.read(b)) != -1;) { + out.append(new String(b, 0, n)); + } + return out.toString(); + } + + /** + * 属性文件转为属性 + * + * @param filePath + * 文件路径 + * @return Properties 属性对象 + * @throws ProjectException + */ + public static Properties fileToProperties(String filePath) { + Properties returnPro = new Properties(); + try { + InputStream inputFile = IOUtil.class.getResourceAsStream(filePath); + returnPro.load(inputFile); + } catch (Exception e) { + logger.error("读属性文件出错", e); + } + return returnPro; + } + + /** + * 合并目录与文件名 + * + * @param folderPath + * 目录路径 + * @param fileName + * 文件名 + * @return String 合并后的文件路径 + * */ + public static String mergeFolderAndFilePath(String folderPath, + String fileName) { + if (StringUtil.isNull(folderPath)) { + return fileName; + } + if (StringUtil.isNull(fileName)) { + return folderPath; + } + if (!folderPath.endsWith(File.separator) && !folderPath.endsWith("/")) { + return folderPath + File.separator + fileName; + } else { + return folderPath + fileName; + } + } + + /*** + * 得到指定Class下的文件的目录 + * + * @param classStr + * @param filePath + * @return + */ + public static String getDirForFilePath( + @SuppressWarnings("rawtypes") Class classStr, String filePath) { + URL url = classStr.getResource(filePath); + int lastIndex = url.getPath().lastIndexOf("/"); + if (lastIndex > 0) { + return url.getPath().substring(0, lastIndex); + } + return null; + } + + /*** + * 得到此项目下的文件目录路径 + * + * @param filePath + * @return + */ + public static String getDirForCommonUtilFilePath(String filePath) { + return getDirForFilePath(IOUtil.class, filePath); + } + + /*** + * 把InputStream复制到OutputStream + * + * @param from + * @param to + * @return + * @throws IOException + */ + public static long copyInToOut(InputStream from, OutputStream to) + throws IOException { + byte[] buf = new byte[1024]; + long total = 0; + while (true) { + int r = from.read(buf); + if (r == -1) { + break; + } + to.write(buf, 0, r); + total += r; + } + return total; + } + +} diff --git a/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/JSONUtil.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/JSONUtil.java new file mode 100644 index 0000000000..a93ec2e5b1 --- /dev/null +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/JSONUtil.java @@ -0,0 +1,317 @@ +package com.jun.plugin.commons.util.apiext; + +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.apache.commons.beanutils.PropertyUtils; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang.ArrayUtils; +import org.apache.commons.lang3.StringUtils; +import org.json.JSONObject; +//import org.apache.tapestry5.json.JSONObject; +import org.mvel2.templates.TemplateRuntime; + +import com.jun.plugin.commons.util.callback.IConvertValue; +import com.jun.plugin.commons.util.callback.IConvertValueDate; + +/** + * @ClassName: JSONUtil + * @Description: JSON对象的扩展 + * @author 周俊辉 + * @date 2010-11-15 上午09:26:25 + * + */ +@SuppressWarnings("rawtypes") +public abstract class JSONUtil { + // js里面需要处理的特殊字符集 + public static final String[][] specialChar = new String[][] { + { "\\\\", "\\\\\\\\" }, { "\"null\"", "\"\"" } }; + + /** + * 合并JSon + * + * @param res1 + * 要合并的json对象1 + * @param res2 + * 要合并的json对象2 + * @return JSONObject + * */ + public static JSONObject mergeJSON(JSONObject res1, JSONObject res2) { +// JSONObject addJSON = res1.keys().size() < res2.keys().size() ? res1 +// : res2; +// JSONObject mainJSON = res1.keys().size() < res2.keys().size() ? res2 +// : res1; +// for (Iterator iterator = addJSON.keys().iterator(); iterator.hasNext();) { +// String key = (String) iterator.next(); +// mainJSON.append(key, addJSON.get(key)); +// } + return null; + } + + /** + * 把JSONObject对象转为list,里面的第个元素为String[2] + * + * @param jsonObject + * 要合并的json对象1 + * @return List + * */ + public static List getValues(JSONObject jsonObject) { + List resultList = new ArrayList();// 因为是有序的,不能用map + String key; +// for (Iterator keys = jsonObject.keys().iterator(); keys.hasNext(); resultList +// .add(new String[] { key, String.valueOf(jsonObject.get(key)) })) +// key = (String) keys.next(); + return resultList; + } + + /*** + * 把Map转为json格式的的json数据,全部为String输出 + * 结果为:{"itemCode":"returnCheck","itemName":"待退货检查"} + * + * @param fromMap + * 需要转的map + * @param convert + * 转换规则,可以为null + * @param keys + * 需要转的key值,如果不填则为全部 要取的标题,支持别名,如:new + * String[]{""itemCode,itemCode","itemName_zh,itemName""} + * itemName_zh为是取值的列名,itemName要显示的列名 + * @return + */ + public static String getJsonForMap(Map fromMap, + IConvertValue[] convert, String... keys) { + if (fromMap == null || fromMap.size() == 0) { + return null; + } + keys = ArrayUtils.isNotEmpty(keys) ? keys : (String[]) fromMap.keySet() + .toArray(); + StringBuffer buff = new StringBuffer("{"); + for (int i = 0; i < keys.length; i++) { + String key = keys[i]; + String[] keyAry = key.split(","); + String valCol = StringUtil.trimSpace(keyAry[0]); + String showCol = StringUtil.trimSpace(keyAry[keyAry.length - 1]); + Object value = fromMap.get(valCol); + String valueTrue = value == null ? null : String.valueOf(value); + if (convert != null && convert.length > i && convert[i] != null) { + IConvertValue convertTrue = convert[i]; + if (ReflectAsset.isInterface(convertTrue.getClass(), + "cn.rjzjh.commons.util.callback.IConvertValueDate")) {// 是时间转换 + IConvertValueDate convInst = (IConvertValueDate) convertTrue; + valueTrue = value == null ? "" : convInst + .getStr((Date) value); + } else { + valueTrue = valueTrue == null ? "" : convertTrue + .getStr(valueTrue); + } + } + if (i != 0) { + buff.append(","); + } + buff.append("\"" + showCol + "\":\"" + + StringUtil.hasNull(valueTrue) + "\""); + + } + buff.append("}"); + return buff.toString(); + } + + public static String getJsonForMap(Map fromMap, + String... keys) { + return getJsonForMap(fromMap, null, keys); + } + + /**** + * 递归组装带"."的字符串,如"caOrganization.caOrganization.orgName" + * @param valCol + * @param startindex + * @return + */ + private static String packMvel2(String valCol, int startindex) { + if (StringUtils.isEmpty(valCol)) { + return ""; + } + int indexdot = valCol.indexOf(".", startindex); + if (indexdot <= 0) { + return valCol; + } + String retstr = "(" + valCol.substring(0, indexdot) + "==null?\"\":" + + packMvel2(valCol, indexdot + 1) + ")"; + return retstr; + } + + /**** + * 返回格式 [{"itemCode":"checkNoPass","itemName":"质检不通过"},{ + * "itemCode":"checkPass","itemName":"质检通过"}] + * + * @param fromList + * 要取的源数据,支持Map和Object对象 + * @param converts + * 要转换的规则,可以为空,与title要一一对应 + * @param titles + * 要取的标题,支持别名,如:new + * String[]{""itemCode,itemCode","itemName_zh,itemName""} + * itemName_zh为是取值的列名,itemName要显示的列名 + * + * @return + */ + public static String getJsonForList(List fromList, + IConvertValue[] converts, String... titles) { + if (CollectionUtils.isEmpty(fromList) || ArrayUtils.isEmpty(titles)) { + return "[]"; + } + StringBuffer buff = new StringBuffer("["); + for (Object object : fromList) { + if (ReflectAsset.isInterface(object.getClass(), "java.util.Map")) { + String singJoson = getJsonForMap((Map) object, converts, titles); + buff.append(singJoson + ","); + } else { + StringBuffer jsonTempStr = new StringBuffer("@{'{"); + for (int i = 0; i < titles.length; i++) { + String[] titleAry = titles[i].split(","); + String valCol = StringUtil.trimSpace(titleAry[0]); + valCol=packMvel2(valCol,0); + String showCol = StringUtil + .trimSpace(titleAry[titleAry.length - 1]); + jsonTempStr.append("\"" + showCol + "\":\"'+" + valCol + + "+'\""); + if (i != titles.length - 1) { + jsonTempStr.append(","); + } + } + jsonTempStr.append("}'}"); + // 通过规则转换字符 + String tempStr = String.valueOf(TemplateRuntime.eval( + jsonTempStr.toString(), object)); + if (ArrayUtils.isNotEmpty(converts)) { + JSONObject jsObj = new JSONObject(tempStr); + for (int i = 0; i < converts.length; i++) { + IConvertValue convert = converts[i]; + String colName = i < titles.length ? titles[i] : null; + if (convert != null && StringUtil.isNotNull(colName)) { + int index = colName.indexOf(","); + String key = ""; + String oriKey = ""; + if (index > 0) { + key = colName.substring(index + 1); + oriKey = colName.substring(0, index); + } else { + key = colName; + oriKey = colName; + } + + String value = ""; + if (ReflectAsset + .isInterface(convert.getClass(), + "cn.rjzjh.commons.util.callback.IConvertValueDate")) {// 是时间转换 + try { + Date oriDate = (Date) PropertyUtils + .getProperty(object, oriKey); + IConvertValueDate convInst = (IConvertValueDate) convert; + value = convInst.getStr(oriDate); + + } catch (Exception e) { + e.printStackTrace(); + } + } else { + value = convert.getStr(jsObj.getString(key)); + } + jsObj.put(key, value); + } + } + tempStr = jsObj.toString(); + } + for (int i = 0; i < specialChar.length; i++) { + String[] tempAry = specialChar[i]; + tempStr = tempStr.replaceAll(tempAry[0], tempAry[1]); + } + buff.append(tempStr + ","); + } + } + buff.delete(buff.length() - 1, buff.length());// 去除最后一个“,” + buff.append("]"); + return buff.toString(); + } + + public static String getJsonForList(List fromList, String... titles) { + return getJsonForList(fromList, new IConvertValue[] {}, titles); + } + + /**** + * 支持Map, Map key为title + * 如果是标题有别名方式:aaa,bbb  则以别名主识别IConvertValue + * + * @param fromList + * @param convertsMap + * @param titles + * @return + */ + public static String getJsonForList(List fromList, + Map convertsMap, String... titles) { + IConvertValue[] convert = null; + if (convertsMap != null + && CollectionUtils.isNotEmpty(convertsMap.keySet())) { + convert = new IConvertValue[titles.length]; + for (String title : convertsMap.keySet()) { + int index = -1; + for (int i = 0; i < titles.length; i++) { + String eleTitle = titles[i]; + if (StringUtil.isNotNull(eleTitle)) { + String[] tempTitleAry = eleTitle.split(","); + String trueKey = tempTitleAry.length > 1 ? tempTitleAry[1] + : tempTitleAry[0]; + if (title.equalsIgnoreCase(trueKey)) { + index = i; + break; + } + } + } + // int index = ArrayUtils.indexOf(titles, title); + if (index >= 0) { + convert[index] = convertsMap.get(title); + } + } + } + return getJsonForList(fromList, convert, titles); + } + + /**** + * 别名 + * + * @param fromList + * @param aliasTitles + * @param convertsMap + * @return + */ + public static String getJsonForListAlias(List fromList, + String[] aliasTitles, Map convertsMap) { + if (CollectionUtils.isEmpty(fromList)) { + return "[]"; + } + Object object = fromList.get(0); + String[] titles = null; + if (ReflectAsset.isInterface(object.getClass(), "java.util.Map")) { + Map temp = (Map) object; + titles = new String[temp.size()]; + int i = 0; + for (Object keyObj : temp.keySet()) { + titles[i++] = String.valueOf(keyObj); + } + } else { + List fields = ReflectAsset.findGetField(object.getClass()); + titles = fields.toArray(new String[fields.size()]); + } + if (aliasTitles != null && aliasTitles.length > 0) { + titles = CollectionUtil.arrayMerge(titles, aliasTitles); + } + return getJsonForList(fromList, convertsMap, titles); + } + + public static String getJsonForListAlias(List fromList) { + return getJsonForListAlias(fromList, null, null); + } + +} diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/LoggerHelp.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/LoggerHelp.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/LoggerHelp.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/LoggerHelp.java diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/NumberUtil.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/NumberUtil.java similarity index 99% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/NumberUtil.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/NumberUtil.java index 2c1d3cf956..832d581a1d 100644 --- a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/NumberUtil.java +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/NumberUtil.java @@ -8,7 +8,7 @@ /** * @ClassName: NumberUtil * @Description: 计算类型的处理 - * @author Wujun + * @author 周俊辉 * @date 2010-10-29 下午01:37:46 * */ diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/RedisClient.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/RedisClient.java similarity index 86% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/RedisClient.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/RedisClient.java index 0d77f07662..4c5230fd9a 100644 --- a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/RedisClient.java +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/RedisClient.java @@ -1,6 +1,3 @@ -// This file is commented out — uses Jedis which is now removed. -// See jun_redis module for Redis client functionality. -/* package com.jun.plugin.commons.util.apiext; import java.util.Map; @@ -14,9 +11,17 @@ import redis.clients.jedis.JedisPoolConfig; public class RedisClient { - private static JedisPool jedisPool; + private static JedisPool jedisPool;// 非切片连接池 + private final static Object lockObj = new Object(); + /**** + * 通过配置得到 Jedis + * + * @param connProp + * @return + * @throws ProjectException + */ public static Jedis getConnection(Properties connProp) { if (connProp == null || connProp.size() == 0) { return null; @@ -40,6 +45,11 @@ public static Jedis getConnection(Properties connProp) { return jedisPool.getResource(); } + /*** + * 放资源 + * + * @param jedis + */ public static void returnResource(Jedis jedis) { jedis.close(); if (jedisPool != null) { @@ -48,4 +58,3 @@ public static void returnResource(Jedis jedis) { } } -*/ diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/ReflectAsset.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/ReflectAsset.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/ReflectAsset.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/ReflectAsset.java diff --git a/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/StringUtil.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/StringUtil.java new file mode 100644 index 0000000000..2104913a62 --- /dev/null +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/StringUtil.java @@ -0,0 +1,237 @@ +package com.jun.plugin.commons.util.apiext; + +import java.math.BigDecimal; +import java.text.FieldPosition; +import java.text.Format; +import java.text.ParsePosition; +import java.util.Date; + +import org.apache.commons.lang.ArrayUtils; +import org.apache.commons.lang.StringUtils; + +import com.jun.plugin.commons.util.callback.ValueEncoder; + +/** + * @ClassName: StringUtil + * @Description: TODO(这里用一句话描述这个类的作用) + * @author 周俊辉 + * @date 2010-10-29 下午01:36:36 + * + */ +public abstract class StringUtil { + /** + * 把为空的字符按指定字符返回,
+ * 如果inputStr[0]为null或"" 则取inputStr[1]值
+ * + * @param inputStr + * 输入要转换的数组 + * @return String + * */ + public static String hasNull(String... inputStr) { + if (inputStr == null) + return ""; + String returnStr; + switch (inputStr.length) { + case 0: + returnStr = ""; + break; + case 1: + returnStr = trimSpace(inputStr[0]); + break; + default: + if (inputStr[0] == null || inputStr[0].trim().length() <= 0) + returnStr = inputStr[1]; + else + returnStr = inputStr[0].trim(); + break; + } + return returnStr; + } + + /** + * 判断字符串是否为空 + * + * @param inputStr + * 输入要转换的数组,如果inputStr[0]为null或"" 则取inputStr[1]值 + * @return String + * */ + public static boolean isNull(String input) { + if (input == null || "null".equals(input) || input.trim().length() == 0) { + return true; + } else { + return false; + } + } + + /** + * 判断字符串是否不为空 + * + * @param inputStr + * 输入要转换的数组,如果inputStr[0]为null或"" 则取inputStr[1]值 + * @return String + * */ + public static boolean isNotNull(String input) { + return !isNull(input); + } + + /** + * 去掉字符串前后的空格(半角,全角空格) + * + * @param str + * 要处理的字符串 + * @return String + */ + public static String trimSpace(String str) { + if (str == null || str.trim().length() == 0) { + return ""; + } + + int len = str.length(); + int first = 0; + int last = str.length() - 1; + char c; + + for (c = str.charAt(first); (first < len) + && (c == '\u3000' || c == ' '); first++) { + c = str.charAt(first); + } + if (first > 0) { + first--; + } + if (len > 0) { + c = str.charAt(last); + while ((last > 0) && (c == '\u3000' || c == ' ')) { + last--; + c = str.charAt(last); + } + last = last + 1; + } + if (first >= last) { + return ""; + } + return ((first > 0) || (last < len)) ? str.substring(first, last) : str; + } + + /** + * 获取字符串中含数字和字母的个数
+ */ + public static int sumOfNumLet(String src) { + String figures = "0123456789"; + String letters = "abcdefghijklmnopqrstuvwxyz"; + int sum = 0; + for (int i = 0; (src != null) && (i < src.length()); i++) { + char ch = src.charAt(i); + if ((figures.indexOf(ch) != -1) || (letters.indexOf(ch) != -1)) + sum++; + } + return sum; + } + + /** + * tapestry输出变量 时要填此格式化对象 + * */ + public final static Format formatCommon = new Format() { + private static final long serialVersionUID = -8271124584977967310L; + + @Override + public Object parseObject(String source, ParsePosition pos) { + return source; + } + + @Override + public StringBuffer format(Object obj, StringBuffer toAppendTo, + FieldPosition pos) { + return toAppendTo.append(obj); + } + }; + + public static String combo(String[] paramArrayOfString, String paramString) { + String str1 = paramString; + if ((paramArrayOfString == null) || (paramArrayOfString.length < 1)) + return ""; + if ((paramString == null) || (paramString.trim().equals(""))) + str1 = ","; + String str2 = trimSpace(paramArrayOfString[0]); + int i = paramArrayOfString.length; + for (int j = 1; j < i; ++j) + str2 = new StringBuilder().append(str2).append(str1) + .append(trimSpace(paramArrayOfString[j])).toString(); + return str2; + } + + /** + * 首字母转成大写 + * + * @param s + * @return + */ + public static String toUpperCaseFirstOne(String s) { + if (isNull(s)) { + return ""; + } else if (Character.isUpperCase(s.charAt(0))) { + return s; + } else { + return (new StringBuilder()) + .append(Character.toUpperCase(s.charAt(0))) + .append(s.substring(1)).toString(); + } + } + + /*** + * String转为基本数据类型 + * + * @param type + * @param v + * @param handler + * @return + */ + public static final T str2Object(Class type, String v, + ValueEncoder handler) { + Object param = null; + if (handler != null) + return handler.toValue(v); + + if (type != String.class + && org.apache.commons.lang3.StringUtils.isEmpty(v)) { + return null; + } + if (type == String.class) + param = v; + else if (type == int.class || type == Integer.class) + param = Integer.parseInt(v); + else if (type == long.class || type == Long.class) + param = Long.parseLong(v); + else if (type == byte.class || type == Byte.class) + param = Byte.parseByte(v); + else if (type == char.class || type == Character.class) + param = v.charAt(0); + else if (type == float.class || type == Float.class) + param = Float.parseFloat(v); + else if (type == double.class || type == Double.class) + param = Double.parseDouble(v); + else if (type == short.class || type == Short.class) + param = Short.parseShort(v); + else if (type == boolean.class || type == Boolean.class) + param = Boolean.parseBoolean(v); + else if (Date.class.isAssignableFrom(type)) + param = DateUtil.objToDate(v); + else if (Enum.class.isAssignableFrom(type)) { + try { + param = type.getField(v).get(null); + } catch (Exception e) { + } + } else if (type == BigDecimal.class) { + try { + param = new BigDecimal(v); + } catch (Exception e) { + } + } else + throw new IllegalArgumentException(String.format( + "object type '%s' not valid", type)); + return (T) param; + } + + public static final T str2Object(Class type, String v) { + return str2Object(type, v, null); + } +} \ No newline at end of file diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/XmlUtil.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/XmlUtil.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/XmlUtil.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/apiext/XmlUtil.java diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/assistbean/EasyUINode.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/assistbean/EasyUINode.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/assistbean/EasyUINode.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/assistbean/EasyUINode.java diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/assistbean/EasyUINodeConf.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/assistbean/EasyUINodeConf.java similarity index 99% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/assistbean/EasyUINodeConf.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/assistbean/EasyUINodeConf.java index 28ef4e4adc..125984f33b 100644 --- a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/assistbean/EasyUINodeConf.java +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/assistbean/EasyUINodeConf.java @@ -10,7 +10,7 @@ /**** * 用户对象与EasyUINode的转换器 * - * @author Wujun + * @author Administrator * */ public class EasyUINodeConf { diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/assistbean/NodeSax.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/assistbean/NodeSax.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/assistbean/NodeSax.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/assistbean/NodeSax.java diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/callback/IConvertValue.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/callback/IConvertValue.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/callback/IConvertValue.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/callback/IConvertValue.java diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/callback/IConvertValueDate.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/callback/IConvertValueDate.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/callback/IConvertValueDate.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/callback/IConvertValueDate.java diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/callback/ValueEncoder.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/callback/ValueEncoder.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/callback/ValueEncoder.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/callback/ValueEncoder.java diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/callback/impl/ConvertValueDate.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/callback/impl/ConvertValueDate.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/callback/impl/ConvertValueDate.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/callback/impl/ConvertValueDate.java diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/callback/impl/ConvertValueMsg.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/callback/impl/ConvertValueMsg.java similarity index 95% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/callback/impl/ConvertValueMsg.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/callback/impl/ConvertValueMsg.java index 5d5fc19a94..09e7fa0bb7 100644 --- a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/callback/impl/ConvertValueMsg.java +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/callback/impl/ConvertValueMsg.java @@ -8,7 +8,7 @@ /**** * commons-util的国际化转换器 * - * @author Wujun + * @author Administrator * */ public class ConvertValueMsg implements IConvertValue { diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/cli/HelloCli.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/cli/HelloCli.java similarity index 97% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/cli/HelloCli.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/cli/HelloCli.java index 7a686c0f66..443af625e7 100644 --- a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/cli/HelloCli.java +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/cli/HelloCli.java @@ -24,7 +24,7 @@ /** * - * @author Wujun + * @author ketayao * Version 3.1.0 * @since 2013年9月4日 下午3:07:20 */ diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/cli/Mkdir.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/cli/Mkdir.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/cli/Mkdir.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/cli/Mkdir.java diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/constant/HibernateConf.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/constant/HibernateConf.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/constant/HibernateConf.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/constant/HibernateConf.java diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/constant/MathConvertType.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/constant/MathConvertType.java similarity index 92% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/constant/MathConvertType.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/constant/MathConvertType.java index d97fee16cd..7539d3a534 100644 --- a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/constant/MathConvertType.java +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/constant/MathConvertType.java @@ -3,7 +3,7 @@ /*** * 数学方面转换的类型 * - * @author Wujun + * @author Administrator * */ public enum MathConvertType { diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/constant/SimpleDateFormatCase.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/constant/SimpleDateFormatCase.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/constant/SimpleDateFormatCase.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/constant/SimpleDateFormatCase.java diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/constant/StrPattern.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/constant/StrPattern.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/constant/StrPattern.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/constant/StrPattern.java diff --git a/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/db/DbUtil.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/db/DbUtil.java new file mode 100644 index 0000000000..d44efd97ed --- /dev/null +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/db/DbUtil.java @@ -0,0 +1,103 @@ +package com.jun.plugin.commons.util.db; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.sql.DataSource; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * 数据库操作工具类 + * + * @author Luxiaolei + * + */ +public class DbUtil { + private static Logger logger = LoggerFactory.getLogger(DbUtil.class); + + private DbUtil() { + // 非可实例化类 + } + + /** + * 实例化一个新的SQL运行对象 + * + * @param ds 数据源 + * @return SQL执行类 + */ + public static SqlRunner newSqlRunner(DataSource ds) { + return new SqlRunner(ds); + } + + /** + * 拼接JDBC连接字符串 + * @param protocol 协议 + * @param host 主机名 + * @param port 端口号 + * @param dbName 数据库名 + * @param jdbcParam 参数 + * @return JDBC字符串 + */ + public static String buildJdbcUrl(String protocol, String host, int port, String dbName, String jdbcParam) { + jdbcParam = jdbcParam == null ? "" : jdbcParam; + if(! jdbcParam.startsWith("?")) { + jdbcParam = "?" + jdbcParam; + } + + String sep = "//"; + if(protocol.contains("jdbc:oracle")) { + sep = "@"; + } + return protocol + ":" + sep + host + ":" + port + "/" + dbName + jdbcParam; + } + + /** + * 连续关闭一系列的SQL相关对象
+ * 这些对象必须按照顺序关闭,否则会出错。 + * + * @param objsToClose 需要关闭的对象 + */ + public static void close(Object... objsToClose) { + for (Object obj : objsToClose) { + try { + if (obj != null) { + if (obj instanceof ResultSet) { + ((ResultSet) obj).close(); + } else if (obj instanceof Statement) { + ((Statement) obj).close(); + } else if (obj instanceof PreparedStatement) { + ((PreparedStatement) obj).close(); + } else if (obj instanceof Connection) { + ((Connection) obj).close(); + } else { + logger.warn("对象" + obj.getClass().getName() + "不是可关闭的类型"); + } + } + } catch (SQLException e) { + } + } + } + + /** + * 获得JNDI数据源 + * @param jndiName JNDI名称 + * @return 数据源 + */ + public static DataSource getJndiDs(String jndiName) { + try { + Context ctx = new InitialContext(); + return (DataSource) ctx.lookup(jndiName); + } catch (NamingException e) { + logger.error("Find JNDI datasource error!", e); + } + return null; + } +} diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/db/DsSetting.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/db/DsSetting.java similarity index 99% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/db/DsSetting.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/db/DsSetting.java index b22b8e8410..7e10060bcc 100644 --- a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/db/DsSetting.java +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/db/DsSetting.java @@ -12,7 +12,7 @@ /** * 数据库设定,与数据库配置文件对应 - * @author Wujun + * @author Luxiaolei * */ public class DsSetting { diff --git a/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/db/RsHandler.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/db/RsHandler.java new file mode 100644 index 0000000000..7dd6f34cb9 --- /dev/null +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/db/RsHandler.java @@ -0,0 +1,13 @@ +package com.jun.plugin.commons.util.db; + +import java.sql.ResultSet; +import java.sql.SQLException; + +/** + * 结果集处理类 + * @author Luxiaolei + * + */ +public interface RsHandler { + public T handle(ResultSet rs) throws SQLException; +} diff --git a/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/db/SqlRunner.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/db/SqlRunner.java new file mode 100644 index 0000000000..4208901e4f --- /dev/null +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/db/SqlRunner.java @@ -0,0 +1,197 @@ +package com.jun.plugin.commons.util.db; + +import java.sql.Connection; +import java.sql.ParameterMetaData; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; + +import javax.sql.DataSource; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * SQL执行类 + * + * @author Luxiaolei + * + */ +public class SqlRunner { + private static Logger logger = LoggerFactory.getLogger(SqlRunner.class); + + private DataSource ds; + + public SqlRunner(DataSource ds) { + this.ds = ds; + } + + /** + * 查询 + * + * @param sql 查询语句 + * @param rsh 结果集处理对象 + * @param params 参数 + * @return 结果对象 + * @throws SQLException + */ + public T query(String sql, RsHandler rsh, Object... params) throws SQLException { + Connection conn = null; + try { + conn = ds.getConnection(); + return this.query(conn, sql, rsh, params); + } catch (SQLException e) { + throw e; + } finally { + DbUtil.close(conn); + } + } + + /** + * 查询
+ * 发查询语句包括 插入、更新、删除
+ * 此方法不会关闭Connection + * + * @param conn 数据库连接对象 + * @param sql 查询语句 + * @param rsh 结果集处理对象 + * @param params 参数 + * @return 结果对象 + * @throws SQLException + */ + public T query(Connection conn, String sql, RsHandler rsh, Object... params) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + try { + ps = conn.prepareStatement(sql); + this.fillParams(ps, params); + rs = ps.executeQuery(); + return rsh.handle(rs); + } catch (SQLException e) { + throw e; + } finally { + DbUtil.close(rs, ps); + } + } + + /** + * 执行非查询语句
+ * 发查询语句包括 插入、更新、删除 + * + * @param sql SQL + * @param params 参数 + * @return 影响的行数 + * @throws SQLException + */ + public int update(String sql, Object... params) throws SQLException { + Connection conn = null; + try { + conn = ds.getConnection(); + return this.update(conn, sql, params); + } catch (SQLException e) { + throw e; + } finally { + DbUtil.close(conn); + } + } + + /** + * 执行非查询语句
+ * 发查询语句包括 插入、更新、删除
+ * 此方法不会关闭Connection + * + * @param conn 数据库连接对象 + * @param sql SQL + * @param params 参数 + * @return 影响的行数 + * @throws SQLException + */ + public int update(Connection conn, String sql, Object... params) throws SQLException { + PreparedStatement ps = null; + try { + ps = conn.prepareStatement(sql); + this.fillParams(ps, params); + return ps.executeUpdate(); + } catch (SQLException e) { + throw e; + } finally { + DbUtil.close(ps); + } + } + + /** + * 批量执行非查询语句 + * + * @param sql SQL + * @param paramsBatch 批量的参数 + * @return 每个SQL执行影响的行数 + * @throws SQLException + */ + public int[] updateBatch(String sql, Object[]... paramsBatch) throws SQLException { + Connection conn = null; + try { + conn = ds.getConnection(); + return this.updateBatch(conn, sql, paramsBatch); + } catch (SQLException e) { + throw e; + } finally { + DbUtil.close(conn); + } + } + + /** + * 批量执行非查询语句
+ * 发查询语句包括 插入、更新、删除
+ * 此方法不会关闭Connection + * + * @param conn 数据库连接对象 + * @param sql SQL + * @param paramsBatch 批量的参数 + * @return 每个SQL执行影响的行数 + * @throws SQLException + */ + public int[] updateBatch(Connection conn, String sql, Object[]... paramsBatch) throws SQLException { + PreparedStatement ps = null; + try { + ps = conn.prepareStatement(sql); + for (Object[] params : paramsBatch) { + this.fillParams(ps, params); + ps.addBatch(); + } + return ps.executeBatch(); + } catch (SQLException e) { + throw e; + } finally { + DbUtil.close(ps); + } + } + + /** + * 填充SQL的参数。 + * + * @param ps PreparedStatement + * @param params SQL参数 + * @throws SQLException + */ + private void fillParams(PreparedStatement ps, Object... params) throws SQLException { + if (params == null) { + return; + } + ParameterMetaData pmd = ps.getParameterMetaData(); + for (int i = 0; i < params.length; i++) { + int paramIndex = i + 1; + if (params[i] != null) { + ps.setObject(paramIndex, params[i]); + } else { + int sqlType = Types.VARCHAR; + try { + sqlType = pmd.getParameterType(paramIndex); + } catch (SQLException e) { + logger.warn("null参数出现无法识别的类型。"); + } + ps.setNull(paramIndex, sqlType); + } + } + } +} \ No newline at end of file diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/db/ds/C3p0Ds.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/db/ds/C3p0Ds.java similarity index 99% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/db/ds/C3p0Ds.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/db/ds/C3p0Ds.java index 1fc6e1d776..e5643ce11d 100644 --- a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/db/ds/C3p0Ds.java +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/db/ds/C3p0Ds.java @@ -25,7 +25,7 @@ /** * 封装Druid数据源 * - * @author Wujun + * @author Luxiaolei * */ public class C3p0Ds { diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/db/ds/DruidDs.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/db/ds/DruidDs.java similarity index 99% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/db/ds/DruidDs.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/db/ds/DruidDs.java index 2c2ac09fa1..4569f9b9f9 100644 --- a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/db/ds/DruidDs.java +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/db/ds/DruidDs.java @@ -25,7 +25,7 @@ /** * 封装Druid数据源 * - * @author Wujun + * @author Luxiaolei * */ public class DruidDs { diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/exception/ExceptAll.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/exception/ExceptAll.java similarity index 95% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/exception/ExceptAll.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/exception/ExceptAll.java index f9b020ae97..1881adeadd 100644 --- a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/exception/ExceptAll.java +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/exception/ExceptAll.java @@ -2,7 +2,7 @@ * @Title: ExceptAll.java * @Package rjzjh.tech.common.Exception * @Description: TODO(用一句话描述该文件做什么) - * @author Wujun + * @author 周俊辉 * @date 2010-10-29 下午01:26:42 * @version V1.0 */ @@ -11,7 +11,7 @@ /** * @ClassName: ExceptAll * @Description: 自定义异常编码与其解释(仅项目用。) - * @author Wujun + * @author 周俊辉 * @date 2010-10-29 下午01:26:42 * */ diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/exception/ParamInfoBean.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/exception/ParamInfoBean.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/exception/ParamInfoBean.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/exception/ParamInfoBean.java diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/exception/ProjectException.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/exception/ProjectException.java similarity index 99% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/exception/ProjectException.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/exception/ProjectException.java index b81cf6d397..daebcc3a51 100644 --- a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/exception/ProjectException.java +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/exception/ProjectException.java @@ -11,7 +11,7 @@ * @ClassName: ProjectException * @Description: 整个项目的异常基类,errorCode不允许修改且必需是ExceptAll所枚举的异常编码。
* errorMessage可以修改,如果不修改且是ExceptAll枚举的desc字段。 - * @author Wujun + * @author 周俊辉 * @date 2010-10-29 下午03:45:52 */ diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/log/LogUtil.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/log/LogUtil.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/log/LogUtil.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/log/LogUtil.java diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/mail/MailAccount.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/mail/MailAccount.java similarity index 98% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/mail/MailAccount.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/mail/MailAccount.java index b336ec9153..ca04abe5bc 100644 --- a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/mail/MailAccount.java +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/mail/MailAccount.java @@ -8,7 +8,7 @@ /** * 邮件账户对象 - * @author Wujun + * @author Luxiaolei * */ public class MailAccount { diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/mail/MailUtil.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/mail/MailUtil.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/mail/MailUtil.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/mail/MailUtil.java diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/maths/Det.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/maths/Det.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/maths/Det.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/maths/Det.java diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/maths/Matrix.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/maths/Matrix.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/maths/Matrix.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/maths/Matrix.java diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/maths/algorithm/MultiVariableLinearRegression.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/maths/algorithm/MultiVariableLinearRegression.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/maths/algorithm/MultiVariableLinearRegression.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/maths/algorithm/MultiVariableLinearRegression.java diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/maths/algorithm/Viterbi.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/maths/algorithm/Viterbi.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/maths/algorithm/Viterbi.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/maths/algorithm/Viterbi.java diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/AccessControl.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/AccessControl.java similarity index 99% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/AccessControl.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/AccessControl.java index 7afb941d47..5cb3a547d2 100644 --- a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/AccessControl.java +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/AccessControl.java @@ -21,7 +21,7 @@ /** * 访问控制对象 - * @author Wujun + * @author Luxiaolei * */ public class AccessControl{ diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/Connector.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/Connector.java similarity index 99% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/Connector.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/Connector.java index 5bb778c8fa..94616fd2ab 100644 --- a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/Connector.java +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/Connector.java @@ -2,7 +2,7 @@ /** * 连接者对象,提供一些连接的基本信息 - * @author Wujun + * @author Luxiaolei * */ public class Connector { diff --git a/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/HtmlUtil.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/HtmlUtil.java new file mode 100644 index 0000000000..6f0ea6a32f --- /dev/null +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/HtmlUtil.java @@ -0,0 +1,33 @@ +package com.jun.plugin.commons.util.net; + +import com.jun.plugin.commons.util.LangUtil; + +/** + * HTML工具类 + * @author Luxiaolei + * + */ +public class HtmlUtil { + + public static final String RE_HTML_MARK = "(<.*?>)|(<[\\s]*?/.*?>)|(<.*?/[\\s]*?>)"; + public static final String RE_SCRIPT = "<[\\s]*?script[^>]*?>.*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; + + /** + * 还原被转义的HTML特殊字符 + * @param htmlStr 包含转义符的HTML内容 + * @return 转换后的字符串 + */ + public static String restoreEscaped(String htmlStr) { + if (LangUtil.isEmpty(htmlStr)) { + return htmlStr; + } + return htmlStr + .replace("<", "<") + .replace("<", "<") + .replace(">", ">") + .replace("&", "&") + .replace(""", "\"") + .replace("'", "'") + .replace(" ", " "); + } +} diff --git a/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/HttpUtil.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/HttpUtil.java new file mode 100644 index 0000000000..d1eee91ab5 --- /dev/null +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/HttpUtil.java @@ -0,0 +1,224 @@ +package com.jun.plugin.commons.util.net; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.jun.plugin.commons.util.FileUtil; +import com.jun.plugin.commons.util.LangUtil; +import com.jun.plugin.commons.util.RegexUtil; + +/** + * Http请求工具类 + * @author luxiaolei@baijob.com + */ +public class HttpUtil { + private static Logger logger = LoggerFactory.getLogger(HttpUtil.class); + + public final static String HTTP_CHARSET = "GBK"; + /** 未知的标识 */ + public final static String UNKNOW = "unknown"; + + private static Map cookies; + + public HttpUtil() { + cookies = new HashMap(); + } + + /** + * 发送get请求 + * @param urlString 网址 + * @param customCharset 自定义请求字符集 + * @return 返回内容,如果只检查状态码,正常只返回 "",不正常返回 null + * @throws IOException + */ + public String get(String urlString, String customCharset) throws IOException{ + URL url = new URL(urlString); + HttpURLConnection conn = (HttpURLConnection)url.openConnection(); + String host = url.getHost(); + String cookie = cookies.get(host); + if(cookie != null) conn.addRequestProperty("Cookie", cookie); + +// conn.addRequestProperty("User-Agent", "Baiduspider+(+http://www.baidu.com/search/spider.htm)"); + conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1"); + + conn.setRequestMethod("GET"); + conn.setDoInput(true); + + String setCookie = conn.getHeaderField("Set-Cookie"); + if(setCookie != null){ + logger.debug("Set Cookie: " + setCookie); + cookies.put(host, setCookie); + } + + /* 获取内容 */ + int contentLength = conn.getContentLength(); + StringBuilder content = new StringBuilder(contentLength > 0 ? contentLength : 16); + BufferedReader bufferedReader = null; + String charset = getCharsetFromConn(conn); + if(charset == null){ + bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream())); + }else{ + bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset)); + } + String line = bufferedReader.readLine(); + while (line != null) { + content.append(line).append("\n"); + line = bufferedReader.readLine(); + } + FileUtil.close(bufferedReader); + conn.disconnect(); + + return content.toString(); + } + + /** + * 编码字符为 application/x-www-form-urlencoded + * @param content 被编码内容 + * @return 编码后的字符 + */ + public static String encode(String content, String charset){ + if(LangUtil.isEmpty(content)) return content; + + String encodeContnt = null; + try { + encodeContnt = URLEncoder.encode(content, charset); + } catch (UnsupportedEncodingException e) { + logger.error("Unsupported encoding: {}", charset); + } + return encodeContnt; + } + + /** + * 解码application/x-www-form-urlencoded字符 + * @param content 被编码内容 + * @return 编码后的字符 + */ + public static String decode(String content, String charset){ + if(LangUtil.isEmpty(content)) return content; + + String encodeContnt = null; + try { + encodeContnt = URLDecoder.decode(content, charset); + } catch (UnsupportedEncodingException e) { + logger.error("Unsupported encoding: {}", charset); + } + return encodeContnt; + } + + /** + * 格式化URL链接 + * @param url 需要格式化的URL + * @return 格式化后的URL,如果提供了null或者空串,返回null + */ + public static String formatUrl(String url){ + if(LangUtil.isEmpty(url)) return null; + if(url.startsWith("http://") || url.startsWith("https://")) return url; + return "http://" + url; + } + + /** + * 格式化Http Header 的name部分 + * @param headerName 头名称 + * @return 格式化后的 header name, 如果headerName为空,返回null + */ + public static String formatHeaderName(String headerName) { + if(LangUtil.isEmpty(headerName)) { + return null; + }else { + headerName = headerName.toLowerCase(); + } + + if (headerName.equals("etag")) { + return "ETag"; + } + + if (headerName.equals("www-authenticate")) { + return "WWW-Authenticate"; + } + + char[] name = headerName.toCharArray(); + + boolean capitalize = true; + + for (int i = 0; i < name.length; i++) { + char c = name[i]; + + if (c == '-') { + capitalize = true; + continue; + } + + if (capitalize) { + name[i] = Character.toUpperCase(c); + capitalize = false; + } else { + name[i] = Character.toLowerCase(c); + } + } + + return new String(name); + } + + /** + * 获取客户端IP + * @param request 请求对象 + * @return IP地址 + */ + public static String getClientIP(HttpServletRequest request) { + String ip = request.getHeader("X-Forwarded-For"); + if (isUnknow(ip)) { + ip = request.getHeader("Proxy-Client-IP"); + } + if (isUnknow(ip)) { + ip = request.getHeader("WL-Proxy-Client-IP"); + } + if (isUnknow(ip)) { + ip = request.getHeader("X-Real-IP"); + } + if (isUnknow(ip)) { + ip = request.getRemoteAddr(); + } + // 多级反向代理检测 + if (ip != null && ip.indexOf(",") > 0) { + ip = ip.trim().split(",")[0]; + } + return ip; + } + + /** + * 从Http连接的头信息中获得字符集 + * @param conn HTTP连接对象 + * @return 字符集 + */ + private static String getCharsetFromConn(HttpURLConnection conn){ + String charset = conn.getContentEncoding(); + if(charset == null || "".equals(charset.trim())){ + String contentType = conn.getContentType(); + charset = RegexUtil.get("charset=(.*)", contentType, 1); + } + return charset; + } + + /** + * 检测给定字符串是否为未知,多用于检测HTTP请求相关
+ * + * @param checkString 被检测的字符串 + * @return 是否未知 + */ + private static boolean isUnknow(String checkString) { + return LangUtil.isEmpty(checkString) || UNKNOW.equalsIgnoreCase(checkString); + } +} diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/SSHUtil.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/SSHUtil.java similarity index 99% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/SSHUtil.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/SSHUtil.java index 9041af0002..7ed5fa290f 100644 --- a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/SSHUtil.java +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/SSHUtil.java @@ -16,7 +16,7 @@ /** * SSH安全连接相关工具类 * 此工具类用于维护一个到跳板机的通道,并将跳板机可访问的服务器端口映射到本地使用 - * @author Wujun + * @author luxiaolei@baijob.com */ public class SSHUtil { private static Logger logger = LoggerFactory.getLogger(SSHUtil.class); diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/SocketUtil.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/SocketUtil.java similarity index 99% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/SocketUtil.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/SocketUtil.java index 742db7910f..e8ff53a242 100644 --- a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/SocketUtil.java +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/SocketUtil.java @@ -12,7 +12,7 @@ /** * 套接字相关工具类 * - * @author Wujun + * @author luxiaolei@baijob.com * */ public class SocketUtil { diff --git a/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/URLUtil.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/URLUtil.java new file mode 100644 index 0000000000..87b28f3785 --- /dev/null +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/net/URLUtil.java @@ -0,0 +1,52 @@ +package com.jun.plugin.commons.util.net; + +import java.io.File; +import java.net.MalformedURLException; +import java.net.URL; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.jun.plugin.commons.util.Setting; + +/** + * 统一资源定位符相关工具类 + * @author Luxiaolei + * + */ +public class URLUtil { + private static Logger logger = LoggerFactory.getLogger(Setting.class); + + /** + * 获得URL + * @param pathBaseClassLoader 相对路径(相对于classes) + * @return URL + */ + public static URL getURL(String pathBaseClassLoader){ + return URLUtil.class.getClassLoader().getResource(pathBaseClassLoader); + } + + /** + * 获得URL + * @param path 相对给定 class所在的路径 + * @param clazz 指定class + * @return URL + */ + public static URL getURL(String path, Class clazz){ + return clazz.getResource(path); + } + + /** + * 获得URL,常用于使用绝对路径时的情况 + * @param configFile URL对应的文件对象 + * @return URL + */ + public static URL getURL(File configFile){ + try { + return configFile.toURI().toURL(); + } catch (MalformedURLException e) { + logger.error("Error occured when get URL!", e); + } + return null; + } +} diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/network/HttpClientUtils.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/network/HttpClientUtils.java similarity index 88% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/network/HttpClientUtils.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/network/HttpClientUtils.java index 977d4b4b5e..b458e30c99 100644 --- a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/network/HttpClientUtils.java +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/network/HttpClientUtils.java @@ -1,6 +1,3 @@ -// This file is commented out — uses Apache HttpClient which is now removed. -// See jun_httpclient module for HTTP client functionality. -/* package com.jun.plugin.commons.util.network; import java.io.IOException; @@ -29,6 +26,13 @@ public abstract class HttpClientUtils { protected static Log log = LogFactory.getLog(HttpClientUtils.class); + /** + * 发送Get请求 + * + * @param url + * 发送请求地址 + * @return 返回内容 + * */ public static String sendGet(String url, String ecode) throws ProjectException { String result = null; @@ -73,6 +77,15 @@ public static String sendGet(String url) throws ProjectException { return sendGet(url, "utf-8"); } + /** + * 发送带参数的Get请求 + * + * @param url + * 发送请求地址 + * @param params + * 发送请求的参数 + * @return 返回内容 + * */ public static String sendGet(String url, Map params) throws ProjectException { Set keys = params.keySet(); @@ -85,22 +98,35 @@ public static String sendGet(String url, Map params) return sendGet(urlBuilder.toString()); } + /** + * 发送带参数的post请求 + * + * @param url + * 发送请求地址 + * @param params + * 发送请求的参数 + * @return 返回内容 + * */ public static String sendPost(String url, Map params) throws ProjectException { String result = null; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost get = new HttpPost(url); + // 创建表单参数列表 List qparams = new ArrayList(); Set keys = params.keySet(); for (String key : keys) { qparams.add(new BasicNameValuePair(key, params.get(key))); } try { + // 填充表单 get.setEntity(new UrlEncodedFormEntity(qparams, "utf-8")); + HttpResponse response = httpClient.execute(get); HttpEntity entity = response.getEntity(); if (entity != null) { entity = new BufferedHttpEntity(entity); + InputStream in = entity.getContent(); byte[] read = new byte[1024]; byte[] all = new byte[0]; @@ -117,11 +143,12 @@ public static String sendPost(String url, Map params) } } get.abort(); + return result; } catch (Exception e) { throw new ProjectException(ExceptAll.default_Project, "请求错误"); } + } } -*/ diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/test/MD5Tools.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/test/MD5Tools.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/test/MD5Tools.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/test/MD5Tools.java diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/test/RegUtils.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/test/RegUtils.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/test/RegUtils.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/test/RegUtils.java diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/test/SecurityCode.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/test/SecurityCode.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/test/SecurityCode.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/test/SecurityCode.java diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/thread/ICancelHandle.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/thread/ICancelHandle.java similarity index 91% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/thread/ICancelHandle.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/thread/ICancelHandle.java index f3653882de..cd09192f8e 100644 --- a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/thread/ICancelHandle.java +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/thread/ICancelHandle.java @@ -3,7 +3,7 @@ /**** * 如果线程被池给取消需要做的事情,如果提交给池的线程实现这个接口,那么当池拒绝这个线程时会调用些接口 * - * @author Wujun + * @author Administrator * */ public interface ICancelHandle { diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/thread/RejectedExecutionForLog.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/thread/RejectedExecutionForLog.java similarity index 98% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/thread/RejectedExecutionForLog.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/thread/RejectedExecutionForLog.java index f96bec6a9b..f92d8e3546 100644 --- a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/thread/RejectedExecutionForLog.java +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/thread/RejectedExecutionForLog.java @@ -11,7 +11,7 @@ /**** * 当线程被拒绝时采取的策略,如果线程实现cn.rjzjh.commons.util.thread.ICancelHandle接口则调用 * - * @author Wujun + * @author Administrator * */ public class RejectedExecutionForLog implements RejectedExecutionHandler { diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/thread/ThreadPool.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/thread/ThreadPool.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/thread/ThreadPool.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/thread/ThreadPool.java diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/threads/BaseRunnable.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/threads/BaseRunnable.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/threads/BaseRunnable.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/threads/BaseRunnable.java diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/threads/Executor.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/threads/Executor.java similarity index 98% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/threads/Executor.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/threads/Executor.java index e2b335f025..bfb6cf1180 100644 --- a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/threads/Executor.java +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/threads/Executor.java @@ -12,7 +12,7 @@ /** * 线程池工具 - * @author Wujun + * @author liushiquan,luxiaolei */ public class Executor { private static Logger logger = LoggerFactory.getLogger(Executor.class); diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/threads/SyncQueue.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/threads/SyncQueue.java similarity index 99% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/threads/SyncQueue.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/threads/SyncQueue.java index 35fba10a7d..a6a88f9cb3 100644 --- a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/threads/SyncQueue.java +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/threads/SyncQueue.java @@ -9,7 +9,7 @@ /** * 同步队列 * - * @author Wujun + * @author Luxiaolei * * @param */ diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/uid/SimpleUidUtil.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/uid/SimpleUidUtil.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/uid/SimpleUidUtil.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/uid/SimpleUidUtil.java diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/web/EasyUiAssist.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/web/EasyUiAssist.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/web/EasyUiAssist.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/web/EasyUiAssist.java diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/web/OperateResult.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/web/OperateResult.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/web/OperateResult.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/web/OperateResult.java diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/web/PageAssist.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/web/PageAssist.java similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/web/PageAssist.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/web/PageAssist.java diff --git a/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/web/WebTools.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/web/WebTools.java new file mode 100644 index 0000000000..3992a87564 --- /dev/null +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/web/WebTools.java @@ -0,0 +1,194 @@ +package com.jun.plugin.commons.util.web; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import jxl.format.Colour; +import jxl.format.UnderlineStyle; +import jxl.write.Label; +import jxl.write.WritableCellFormat; +import jxl.write.WritableFont; +import jxl.write.WritableSheet; +import jxl.write.WritableWorkbook; + +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.commons.fileupload.servlet.ServletFileUpload; +import org.apache.commons.lang.ArrayUtils; +import org.apache.poi.ss.usermodel.Workbook; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.jun.plugin.commons.util.Conf; +import com.jun.plugin.commons.util.exception.ExceptAll; +import com.jun.plugin.commons.util.exception.ProjectException; + +public abstract class WebTools { + private static Logger logger = LoggerFactory.getLogger(WebTools.class); + public final static File tempDir=new File(Conf.utilProperties.getProperty("file.tempDir"));//临时文件夹目录 + + + /** + * + * @param response + * 返回响应 + * @param workbook + * 要返回的excel文件 + * @param fileName + * 要保存的文件名 + * @return void + * */ + public static void returnExcelStreamResponse(HttpServletResponse response, + Workbook workbook, String fileName) throws ProjectException { + ByteArrayOutputStream file = new ByteArrayOutputStream(); + try { + workbook.write(file); + final byte[] dataFile = file.toByteArray(); + response.setHeader("Content-Disposition", "attachment; filename=\"" + + new String(fileName.getBytes("GBK"), "iso8859-1") + + ".xls\"");// 中文文件名问题 + response.setContentLength(dataFile.length); + ServletOutputStream resStream = response.getOutputStream(); + resStream.write(dataFile); + resStream.close(); + } catch (Exception e) { + throw new ProjectException(ExceptAll.default_Project, + "返回excle输出流错误"); + } + } + + /***** + * 导出Excel文件,文件内容格式如下: + * 标题1,标题2\r\n + * aaa,bbb\r\n + * ccc,ccc + * + * exshow[0]:文件名 + * exshow[1]:sheet名 + * @param response + * @param context + * @param exshow + * @return + */ + public static OperateResult exportExcel(HttpServletResponse response, + String context, String... exshow) { + OperateResult retObj = new OperateResult(0); + try { + + String fileName=ArrayUtils.isEmpty(exshow)?"fileName":exshow[0]; + String sheetTitle = ArrayUtils.isEmpty(exshow)||exshow.length<2?"sheet1":exshow[1]; + + OutputStream os = response.getOutputStream();// 取得输出流 + response.reset();// 清空输出流 + response.setHeader("Content-disposition", "attachment; filename=" + + fileName + ".xls");// 设定输出文件头 + response.setContentType("application/msexcel");// 定义输出类型 + WritableWorkbook wbook = jxl.Workbook.createWorkbook(os); // 建立excel文件 + WritableSheet wsheet = wbook.createSheet(sheetTitle, 0); // sheet名称 + WritableFont wfont = new WritableFont(WritableFont.ARIAL, 16, + WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, + Colour.BLACK); + WritableCellFormat wcfFC = new WritableCellFormat(wfont); + wcfFC.setBackground(Colour.AQUA); + wsheet.addCell(new Label(1, 0, sheetTitle, wcfFC)); + wfont = new jxl.write.WritableFont(WritableFont.ARIAL, 14, + WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, + Colour.BLACK); + wcfFC = new WritableCellFormat(wfont); + // 开始生成主体内容 + String[] rows = context.split("\r\n"); + for (int i = 0; i < rows.length; i++) { + String rowString = rows[i]; + String[] rowAry = rowString.split(","); + for (int j = 0; j < rowAry.length; j++) { + wsheet.addCell(new Label(j, i, rowAry[j])); + } + } + // 主体内容生成结束 + wbook.write(); // 写入文件 + wbook.close(); + os.close(); // 关闭 + retObj.setResult(1); + retObj.setMessage("success"); + } catch (Exception e) { + retObj.setMessage(e.getMessage()); + } + return retObj; + } + + /*** + * 返回json数据 + * + * @param response + * @param jsonMsg + */ + public static void returnJsonResponse(HttpServletResponse response, + String jsonMsg) { + response.setContentType("text/html"); + try { + PrintWriter out = response.getWriter(); + out.print(jsonMsg); + out.flush(); + out.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /*** + * 返回json数据 + * + * @param response + * @param operateResult + * 要返回的结果封装 + */ + public static void returnJsonResponse(HttpServletResponse response, + OperateResult operateResult) { + returnJsonResponse(response, operateResult.getJsonMsg(null)); + } + + /***** + * 把requesty请求组装为Map返回,支持enctype属性为multipart/form-data的form提交 + * + * @param request + * @return + */ + public static Map paseReqestParam(HttpServletRequest request) { + Map retMap = new HashMap(); + boolean isMultipart = ServletFileUpload.isMultipartContent(request); + if (isMultipart) { + DiskFileItemFactory factory = new DiskFileItemFactory(); + ServletFileUpload upload = new ServletFileUpload(factory); + upload.setSizeMax(Long.parseLong(Conf.utilProperties.getProperty("file.sizeMax"))); // 设置上传内容的大小限制(单位:字节) + factory.setSizeThreshold(Integer.parseInt(Conf.utilProperties.getProperty("file.sizeThreshold"))); // 2M + factory.setRepository(tempDir); // 与上一个结合使用,设置临时文件的路径(绝对路径) + try { + List items = upload.parseRequest(request); + for (FileItem fileItem : items) { + String name = fileItem.getFieldName(); + String value = fileItem.getString(Conf.utilProperties.getProperty("connect.encode")); + retMap.put(name, value); + } + } catch (Exception e) { + logger.error("解析文件类型的参数错误",e); + } + } else { + Map requestParam = request.getParameterMap(); + for (String key : requestParam.keySet()) { + retMap.put(key, ArrayUtils.toString(requestParam.get(key))); + } + } + return retMap; + } + +} diff --git a/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/wordSearch/StopChar.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/wordSearch/StopChar.java new file mode 100644 index 0000000000..4951e63c0d --- /dev/null +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/wordSearch/StopChar.java @@ -0,0 +1,58 @@ +package com.jun.plugin.commons.util.wordSearch; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +import com.jun.plugin.commons.util.LangUtil; + +/** + * 过滤词及一些简单处理 + * + * @author taofucheng + */ +public class StopChar { + /** 不需要处理的词,如标点符号、空格等 */ + public static final Set STOP_WORD = new HashSet(Arrays.asList(new String[] { " ", "'", "、", "。", + "·", "ˉ", "ˇ", "々", "—", "~", "‖", "…", "‘", "’", "“", "”", "〔", "〕", "〈", "〉", "《", "》", "「", "」", "『", + "』", "〖", "〗", "【", "】", "±", "+", "-", "×", "÷", "∧", "∨", "∑", "∏", "∪", "∩", "∈", "√", "⊥", "⊙", "∫", + "∮", "≡", "≌", "≈", "∽", "∝", "≠", "≮", "≯", "≤", "≥", "∞", "∶", "∵", "∴", "∷", "♂", "♀", "°", "′", "〃", + "℃", "$", "¤", "¢", "£", "‰", "§", "☆", "★", "〇", "○", "●", "◎", "◇", "◆", "□", "■", "△", "▽", "⊿", "▲", + "▼", "◣", "◤", "◢", "◥", "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█", "▉", "▊", "▋", "▌", "▍", "▎", "▏", "▓", + "※", "→", "←", "↑", "↓", "↖", "↗", "↘", "↙", "〓", "ⅰ", "ⅱ", "ⅲ", "ⅳ", "ⅴ", "ⅵ", "ⅶ", "ⅷ", "ⅸ", "ⅹ", "①", + "②", "③", "④", "⑤", "⑥", "⑦", "⑧", "⑨", "⑩", "⒈", "⒉", "⒊", "⒋", "⒌", "⒍", "⒎", "⒏", "⒐", "⒑", "⒒", "⒓", + "⒔", "⒕", "⒖", "⒗", "⒘", "⒙", "⒚", "⒛", "⑴", "⑵", "⑶", "⑷", "⑸", "⑹", "⑺", "⑻", "⑼", "⑽", "⑾", "⑿", "⒀", + "⒁", "⒂", "⒃", "⒄", "⒅", "⒆", "⒇", "Ⅰ", "Ⅱ", "Ⅲ", "Ⅳ", "Ⅴ", "Ⅵ", "Ⅶ", "Ⅷ", "Ⅸ", "Ⅹ", "Ⅺ", "Ⅻ", "!", "”", + "#", "¥", "%", "&", "’", "(", ")", "*", "+", ",", "-", ".", "/", "0", "1", "2", "3", "4", "5", "6", "7", + "8", "9", ":", ";", "<", "=", ">", "?", "@", "〔", "\", "〕", "^", "_", "‘", "{", "|", "}", "∏", "Ρ", "∑", + "Υ", "Φ", "Χ", "Ψ", "Ω", "α", "β", "γ", "δ", "ε", "ζ", "η", "θ", "ι", "κ", "λ", "μ", "ν", "ξ", "ο", "π", + "ρ", "σ", "τ", "υ", "φ", "χ", "ψ", "ω", "(", ")", "〔", "〕", "^", "﹊", "﹍", "╭", "╮", "╰", "╯", "", "_", + "", "^", "(", "^", ":", "!", "/", "\\", "\"", "<", ">", "`", "·", "。", "{", "}", "~", "~", "(", ")", "-", + "√", "$", "@", "*", "&", "#", "卐", "㎎", "㎏", "㎜", "㎝", "㎞", "㎡", "㏄", "㏎", "㏑", "㏒", "㏕" })); + + /** + * 判断指定的词是否是不处理的词。 + * 如果参数为空,则返回true,因为空也属于不处理的字符。 + * @param ch 指定的词 + * @return 是否是不处理的词 + */ + public static boolean isStopChar(String ch) { + if (LangUtil.isEmpty(ch)) return true; + return STOP_WORD.contains(ch); + } + + /** + * 判断指定的词是否是不处理的词。 + * 如果参数为空,则返回true,因为空也属于不处理的字符。 + * + * @param ch 指定的词 + * @return 是否是不处理的词 + */ + public static boolean isStopChar(char ch) { + return STOP_WORD.contains(String.valueOf(ch)); + } + + @Override + public String toString() { + return super.toString(); + } +} diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/wordSearch/Words.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/wordSearch/Words.java similarity index 99% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/wordSearch/Words.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/wordSearch/Words.java index fc9649dc18..2961eb10e1 100644 --- a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/wordSearch/Words.java +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/wordSearch/Words.java @@ -8,7 +8,7 @@ /** * 单词树 - * @author Wujun + * @author Luxiaolei * */ public class Words extends HashMap{ diff --git a/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/workflow/Consumer.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/workflow/Consumer.java new file mode 100644 index 0000000000..0cbf855d98 --- /dev/null +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/workflow/Consumer.java @@ -0,0 +1,67 @@ +package com.jun.plugin.commons.util.workflow; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * 消费者线程
+ * 结束条件:1、isFinished() 2、生态系统中取出null 3、被线程中断 + * + * @author Luxiaolei + * + * @param 产品类型 + */ +public abstract class Consumer extends Thread { + private static Logger logger = LoggerFactory.getLogger(Consumer.class); + + /** 生态系统对象(产品队列) */ + private Ecosystem queue; + + public Consumer(Ecosystem queue, ThreadGroup group, String name) { + super(group, name); + this.queue = queue; + } + + @Override + public final void run() { + try { + while (!isFinished()) { + E product = queue.take(); + if (product == null) { + //由于queue为null时会阻塞队列,故返回产品为null的情况表示生态系统结束 + break; + } + consume(product); + } + } catch (InterruptedException e) { + logger.debug("【" + getName() + "】中断结束。"); + } + this.end(); + queue.consumerEnd(); // 通知生态系统自己已经关闭 + } + + /** + * 线程结束条件方法
+ * 默认为false,即只有被强制中断或从队列中取到 null 时才结束
+ * 若想自定义结束条件,请重写此方法 + * + * @return 线程是否结束 + */ + protected boolean isFinished() { + return false; + } + + /** + * 线程结束调用的方法
+ * 当线程结束前会调用此方法 + */ + protected abstract void end(); + + /** + * 消费
+ * 线程会循环调用此方法直到达到结束条件 + * + * @param product 待处理的产品 + */ + protected abstract void consume(E product); +} diff --git a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/workflow/Ecosystem.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/workflow/Ecosystem.java similarity index 99% rename from jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/workflow/Ecosystem.java rename to jun_apache_commons/src/main/java/com/jun/plugin/commons/util/workflow/Ecosystem.java index 23be93bea4..4dee7134a3 100644 --- a/jun_java_plugins/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/workflow/Ecosystem.java +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/workflow/Ecosystem.java @@ -14,7 +14,7 @@ * 1、队列满阻塞生产者,队列空阻塞消费者
* 2、生产者结束后,关闭生态系统,等队列中的数据全部消费完毕后,消费者结束
* 3、消费者若提前结束,则生态系统结束
- * @author Wujun + * @author Luxiaolei * @param 生产和消费的产品类型 * */ diff --git a/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/workflow/Producer.java b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/workflow/Producer.java new file mode 100644 index 0000000000..08fc2a1b6b --- /dev/null +++ b/jun_apache_commons/src/main/java/com/jun/plugin/commons/util/workflow/Producer.java @@ -0,0 +1,65 @@ +package com.jun.plugin.commons.util.workflow; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * 生产者线程 + * 结束条件:1、isFinished() 2、产品插入失败 3、被线程中断 + * @author Luxiaolei + * + * @param 产品类型 + */ +public abstract class Producer extends Thread { + private static Logger logger = LoggerFactory.getLogger(Producer.class); + + /** 生态系统对象(产品队列) */ + private Ecosystem queue; + + public Producer(Ecosystem queue, ThreadGroup group, String name) { + super(group, name); + this.queue = queue; + } + + @Override + public final void run() { + try { + while (!isFinished()) { + E product = produce(); + if (product == null) { + //空产品跳过此条继续 + continue; + } + if(!queue.put(product)) { + //插入失败(队列关闭了) + logger.debug("【"+getName()+"】生态系统关闭,结束。"); + break; + } + } + } catch (InterruptedException e) { + logger.debug("【" + getName() + "】中断结束。"); + } + this.end(); + queue.producerEnd(); // 通知生态系统自己已经关闭 + } + + /** + * 线程结束条件方法 + * @return 线程是否结束 + */ + protected boolean isFinished(){ + return false; + } + + /** + * 线程结束时调用的方法 + */ + protected abstract void end(); + + /** + * 生产 + * + * @return 生产的结果供消费者使用,若为null,则跳过此条 + */ + protected abstract E produce(); +} diff --git a/jun_java_plugins/jun_apache_commons/src/main/resources/I18N/MessageBundleUtil.properties b/jun_apache_commons/src/main/resources/I18N/MessageBundleUtil.properties similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/resources/I18N/MessageBundleUtil.properties rename to jun_apache_commons/src/main/resources/I18N/MessageBundleUtil.properties diff --git a/jun_java_plugins/jun_apache_commons/src/main/resources/I18N/MessageBundleUtil_en_US.properties b/jun_apache_commons/src/main/resources/I18N/MessageBundleUtil_en_US.properties similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/resources/I18N/MessageBundleUtil_en_US.properties rename to jun_apache_commons/src/main/resources/I18N/MessageBundleUtil_en_US.properties diff --git a/jun_java_plugins/jun_apache_commons/src/main/resources/application.properties b/jun_apache_commons/src/main/resources/application.properties similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/resources/application.properties rename to jun_apache_commons/src/main/resources/application.properties diff --git a/jun_java_plugins/jun_apache_commons/src/main/resources/commonsUtil.properties b/jun_apache_commons/src/main/resources/commonsUtil.properties similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/resources/commonsUtil.properties rename to jun_apache_commons/src/main/resources/commonsUtil.properties diff --git a/jun_java_plugins/jun_apache_commons/src/main/resources/config/access-example.xml b/jun_apache_commons/src/main/resources/config/access-example.xml similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/resources/config/access-example.xml rename to jun_apache_commons/src/main/resources/config/access-example.xml diff --git a/jun_java_plugins/jun_apache_commons/src/main/resources/config/c3p0-config-example.xml b/jun_apache_commons/src/main/resources/config/c3p0-config-example.xml similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/resources/config/c3p0-config-example.xml rename to jun_apache_commons/src/main/resources/config/c3p0-config-example.xml diff --git a/jun_java_plugins/jun_apache_commons/src/main/resources/config/db-example.setting b/jun_apache_commons/src/main/resources/config/db-example.setting similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/resources/config/db-example.setting rename to jun_apache_commons/src/main/resources/config/db-example.setting diff --git a/jun_java_plugins/jun_apache_commons/src/main/resources/config/druid-example.setting b/jun_apache_commons/src/main/resources/config/druid-example.setting similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/resources/config/druid-example.setting rename to jun_apache_commons/src/main/resources/config/druid-example.setting diff --git a/jun_java_plugins/jun_apache_commons/src/main/resources/config/mailAccount-example.setting b/jun_apache_commons/src/main/resources/config/mailAccount-example.setting similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/resources/config/mailAccount-example.setting rename to jun_apache_commons/src/main/resources/config/mailAccount-example.setting diff --git a/jun_java_plugins/jun_apache_commons/src/main/resources/data/simplified2traditional.setting b/jun_apache_commons/src/main/resources/data/simplified2traditional.setting similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/resources/data/simplified2traditional.setting rename to jun_apache_commons/src/main/resources/data/simplified2traditional.setting diff --git a/jun_java_plugins/jun_apache_commons/src/main/resources/data/traditional2simplified.setting b/jun_apache_commons/src/main/resources/data/traditional2simplified.setting similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/resources/data/traditional2simplified.setting rename to jun_apache_commons/src/main/resources/data/traditional2simplified.setting diff --git a/jun_java_plugins/jun_apache_commons/src/main/resources/log4j.properties b/jun_apache_commons/src/main/resources/log4j.properties similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/main/resources/log4j.properties rename to jun_apache_commons/src/main/resources/log4j.properties diff --git a/jun_apache_commons/src/test/java/cn/rjzjh/commons/test/Test.java b/jun_apache_commons/src/test/java/cn/rjzjh/commons/test/Test.java new file mode 100644 index 0000000000..c625e1767c --- /dev/null +++ b/jun_apache_commons/src/test/java/cn/rjzjh/commons/test/Test.java @@ -0,0 +1,5 @@ +package cn.rjzjh.commons.test; + +public class Test { + +} diff --git a/jun_java_plugins/jun_apache_commons/src/test/java/com/jun/plugin/commons/util/CommonTest.java b/jun_apache_commons/src/test/java/com/baijob/commonTools/CommonTest.java similarity index 75% rename from jun_java_plugins/jun_apache_commons/src/test/java/com/jun/plugin/commons/util/CommonTest.java rename to jun_apache_commons/src/test/java/com/baijob/commonTools/CommonTest.java index 0d50b065c5..e813331327 100644 --- a/jun_java_plugins/jun_apache_commons/src/test/java/com/jun/plugin/commons/util/CommonTest.java +++ b/jun_apache_commons/src/test/java/com/baijob/commonTools/CommonTest.java @@ -1,4 +1,4 @@ -package com.jun.plugin.commons.util; +package com.baijob.commonTools; diff --git a/jun_java_plugins/jun_apache_commons/src/test/java/com/jun/plugin/commons/util/DateUtilTest.java b/jun_apache_commons/src/test/java/com/baijob/commonTools/DateUtilTest.java similarity index 96% rename from jun_java_plugins/jun_apache_commons/src/test/java/com/jun/plugin/commons/util/DateUtilTest.java rename to jun_apache_commons/src/test/java/com/baijob/commonTools/DateUtilTest.java index bea4739f2a..83f3dc4773 100644 --- a/jun_java_plugins/jun_apache_commons/src/test/java/com/jun/plugin/commons/util/DateUtilTest.java +++ b/jun_apache_commons/src/test/java/com/baijob/commonTools/DateUtilTest.java @@ -1,4 +1,4 @@ -package com.jun.plugin.commons.util; +package com.baijob.commonTools; import java.util.Calendar; import java.util.Date; diff --git a/jun_java_plugins/jun_apache_commons/src/test/java/com/jun/plugin/commons/util/SecureUtilTest.java b/jun_apache_commons/src/test/java/com/baijob/commonTools/SecureUtilTest.java similarity index 92% rename from jun_java_plugins/jun_apache_commons/src/test/java/com/jun/plugin/commons/util/SecureUtilTest.java rename to jun_apache_commons/src/test/java/com/baijob/commonTools/SecureUtilTest.java index e2127f11c2..aedd0b1c01 100644 --- a/jun_java_plugins/jun_apache_commons/src/test/java/com/jun/plugin/commons/util/SecureUtilTest.java +++ b/jun_apache_commons/src/test/java/com/baijob/commonTools/SecureUtilTest.java @@ -1,4 +1,4 @@ -package com.jun.plugin.commons.util; +package com.baijob.commonTools; import org.junit.Assert; import org.junit.Test; diff --git a/jun_java_plugins/jun_apache_commons/src/test/java/com/jun/plugin/commons/util/SettingTest.java b/jun_apache_commons/src/test/java/com/baijob/commonTools/SettingTest.java similarity index 96% rename from jun_java_plugins/jun_apache_commons/src/test/java/com/jun/plugin/commons/util/SettingTest.java rename to jun_apache_commons/src/test/java/com/baijob/commonTools/SettingTest.java index 0aec3d3a3d..040b8ea2e4 100644 --- a/jun_java_plugins/jun_apache_commons/src/test/java/com/jun/plugin/commons/util/SettingTest.java +++ b/jun_apache_commons/src/test/java/com/baijob/commonTools/SettingTest.java @@ -1,4 +1,4 @@ -package com.jun.plugin.commons.util; +package com.baijob.commonTools; import org.junit.Assert; import org.junit.Test; diff --git a/jun_java_plugins/jun_apache_commons/src/test/java/com/jun/plugin/commons/util/ZhUtilTest.java b/jun_apache_commons/src/test/java/com/baijob/commonTools/ZhUtilTest.java similarity index 96% rename from jun_java_plugins/jun_apache_commons/src/test/java/com/jun/plugin/commons/util/ZhUtilTest.java rename to jun_apache_commons/src/test/java/com/baijob/commonTools/ZhUtilTest.java index a44554a249..30235bd20e 100644 --- a/jun_java_plugins/jun_apache_commons/src/test/java/com/jun/plugin/commons/util/ZhUtilTest.java +++ b/jun_apache_commons/src/test/java/com/baijob/commonTools/ZhUtilTest.java @@ -1,4 +1,4 @@ -package com.jun.plugin.commons.util; +package com.baijob.commonTools; import org.junit.Assert; import org.junit.Test; diff --git a/jun_java_plugins/jun_apache_commons/src/test/java/com/jun/plugin/commons/util/wordSraech/WordSearchTest.java b/jun_apache_commons/src/test/java/com/baijob/commonTools/wordSraech/WordSearchTest.java similarity index 95% rename from jun_java_plugins/jun_apache_commons/src/test/java/com/jun/plugin/commons/util/wordSraech/WordSearchTest.java rename to jun_apache_commons/src/test/java/com/baijob/commonTools/wordSraech/WordSearchTest.java index 7e10b2acf7..11b3d239f9 100644 --- a/jun_java_plugins/jun_apache_commons/src/test/java/com/jun/plugin/commons/util/wordSraech/WordSearchTest.java +++ b/jun_apache_commons/src/test/java/com/baijob/commonTools/wordSraech/WordSearchTest.java @@ -1,4 +1,4 @@ -package com.jun.plugin.commons.util.wordSraech; +package com.baijob.commonTools.wordSraech; import java.util.List; diff --git a/jun_java_plugins/jun_apache_commons/src/test/resources/c3p0-config.xml b/jun_apache_commons/src/test/resources/c3p0-config.xml similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/test/resources/c3p0-config.xml rename to jun_apache_commons/src/test/resources/c3p0-config.xml diff --git a/jun_java_plugins/jun_apache_commons/src/test/resources/config/db.setting b/jun_apache_commons/src/test/resources/config/db.setting similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/test/resources/config/db.setting rename to jun_apache_commons/src/test/resources/config/db.setting diff --git a/jun_java_plugins/jun_apache_commons/src/test/resources/config/druid.setting b/jun_apache_commons/src/test/resources/config/druid.setting similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/test/resources/config/druid.setting rename to jun_apache_commons/src/test/resources/config/druid.setting diff --git a/jun_java_plugins/jun_apache_commons/src/test/resources/config/example.setting b/jun_apache_commons/src/test/resources/config/example.setting similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/test/resources/config/example.setting rename to jun_apache_commons/src/test/resources/config/example.setting diff --git a/jun_java_plugins/jun_apache_commons/src/test/resources/readme.txt b/jun_apache_commons/src/test/resources/readme.txt similarity index 100% rename from jun_java_plugins/jun_apache_commons/src/test/resources/readme.txt rename to jun_apache_commons/src/test/resources/readme.txt diff --git a/jun_java_plugins/jun_apache_commons/src/test/java/com/jun/plugin/commons/util/TestViterbi.java b/jun_apache_commons/test/com/getall/util/test/TestViterbi.java similarity index 87% rename from jun_java_plugins/jun_apache_commons/src/test/java/com/jun/plugin/commons/util/TestViterbi.java rename to jun_apache_commons/test/com/getall/util/test/TestViterbi.java index ccc7e0fab7..02fdf134c9 100644 --- a/jun_java_plugins/jun_apache_commons/src/test/java/com/jun/plugin/commons/util/TestViterbi.java +++ b/jun_apache_commons/test/com/getall/util/test/TestViterbi.java @@ -1,8 +1,8 @@ -package com.jun.plugin.commons.util; +package com.getall.util.test; -import com.jun.plugin.commons.util.log.LogUtil; -import com.jun.plugin.commons.util.maths.Matrix; -import com.jun.plugin.commons.util.maths.algorithm.Viterbi; +import com.getall.util.log.LogUtil; +import com.getall.util.maths.Matrix; +import com.getall.util.maths.algorithm.Viterbi; public class TestViterbi { diff --git a/jun_books/doc/jun_books.7z b/jun_books/doc/jun_books.7z new file mode 100644 index 0000000000..0aa50c2089 Binary files /dev/null and b/jun_books/doc/jun_books.7z differ diff --git a/jun_java_plugins/jun_redis/.gitignore b/jun_bootsrtap/.gitignore similarity index 100% rename from jun_java_plugins/jun_redis/.gitignore rename to jun_bootsrtap/.gitignore diff --git a/jun_bootsrtap/README.md b/jun_bootsrtap/README.md new file mode 100644 index 0000000000..622d4ce6da --- /dev/null +++ b/jun_bootsrtap/README.md @@ -0,0 +1,2 @@ +# 简介 jun_bootsrtap,基于前端bootsrtap框架的demo及示例,加速项目开发 + diff --git a/jun_bootsrtap/pom.xml b/jun_bootsrtap/pom.xml new file mode 100644 index 0000000000..4d2be869b0 --- /dev/null +++ b/jun_bootsrtap/pom.xml @@ -0,0 +1,12 @@ + + 4.0.0 + + com.jun.plugin + jun_plugin + 1.0 + + + + jun_bootsrtap + + \ No newline at end of file diff --git a/jun_java_plugins/jun_jbpm/src/main/webapp/WEB-INF/web.xml b/jun_bootsrtap/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from jun_java_plugins/jun_jbpm/src/main/webapp/WEB-INF/web.xml rename to jun_bootsrtap/src/main/webapp/WEB-INF/web.xml diff --git a/jun_cache/.gitignore b/jun_cache/.gitignore new file mode 100644 index 0000000000..0f182a0349 --- /dev/null +++ b/jun_cache/.gitignore @@ -0,0 +1,6 @@ +*.class + +# Package Files # +*.jar +*.war +*.ear diff --git a/jun_cache/README.md b/jun_cache/README.md new file mode 100644 index 0000000000..6c066443b6 --- /dev/null +++ b/jun_cache/README.md @@ -0,0 +1,22 @@ +#jun_cache二级缓存系统, 一级缓存ehcache,二级redis +## 说明 +目前一级缓存用的是ehcache,二级使用redis;集群同步工具使用jgroups或redis pub sub; +## 计划 +下一步会改为模块化工程,使用时按需加载; +包括 : +
    +
  • 一二级缓存自定义
  • +
  • 序列化工具自定义
  • +
+ +## 使用说明 +在src/test/resources目录下有个spring-cache-test.xml文件,演示了在spring项目中如何使用jun_cache;对于可以使用的配置项也有相应的文本注释 +
+* 属性说明:
+* useCluster                - 是否为集群,默认true
+* cacheBroadcast            - 集群模式下个节点数据同步的机制,可选择为:REDIS_PUBSUB/JGROUPS_MULTICAST
+* openSecondCache           - 是否启用二级缓存,默认false
+* cache_jgroup_conf_file    - 使用jgroups实现ehcache集群
+* cache_ehcache_conf_file   - 一级缓存ehcache配置文件
+* cache_redis_conf_file     - 二级缓存redis配置文件
+
\ No newline at end of file diff --git a/jun_cache/pom.xml b/jun_cache/pom.xml new file mode 100644 index 0000000000..d938e0b4f9 --- /dev/null +++ b/jun_cache/pom.xml @@ -0,0 +1,165 @@ + + + 4.0.0 + + com.jun.plugin + jun_cache + 1.0-SNAPSHOT + jar + + + UTF-8 + 1.8 + + 4.11 + + 4.2.3.RELEASE + 2.8.0 + 2.10.0 + 3.6.1.Final + 2.4 + 2.43 + 1.1.2 + + 1.1.2 + 1.7.7 + + + + + + + de.ruedigermoeller + fst + ${fst.version} + + + org.xerial.snappy + snappy-java + ${snappy-java.version} + + + org.jgroups + jgroups + ${jgroups.version} + + + + redis.clients + jedis + ${jedis.verion} + + + net.sf.ehcache + ehcache + ${ehcache.version} + + + + org.springframework + spring-beans + ${spring.version} + + + + commons-io + commons-io + ${commons-io.version} + + + + + org.slf4j + slf4j-api + ${slf4j-api.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + + org.slf4j + log4j-over-slf4j + ${slf4j-api.version} + runtime + + + + org.slf4j + jcl-over-slf4j + ${slf4j-api.version} + runtime + + + + org.slf4j + jul-to-slf4j + ${slf4j-api.version} + runtime + + + + + + junit + junit + ${junit.version} + test + + + org.springframework + spring-context + ${spring.version} + test + + + org.springframework + spring-test + ${spring.version} + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + ${java.version} + ${java.version} + true + + + + org.apache.maven.plugins + maven-install-plugin + 2.4 + + + org.apache.maven.plugins + maven-jar-plugin + 2.4 + + + + true + + + + + + + + \ No newline at end of file diff --git a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/Cache.java b/jun_cache/src/main/java/net/oschina/j2cache/Cache.java similarity index 100% rename from jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/Cache.java rename to jun_cache/src/main/java/net/oschina/j2cache/Cache.java diff --git a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/CacheAbstractTemplate.java b/jun_cache/src/main/java/net/oschina/j2cache/CacheAbstractTemplate.java similarity index 99% rename from jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/CacheAbstractTemplate.java rename to jun_cache/src/main/java/net/oschina/j2cache/CacheAbstractTemplate.java index 45570baab6..953fdbba6b 100644 --- a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/CacheAbstractTemplate.java +++ b/jun_cache/src/main/java/net/oschina/j2cache/CacheAbstractTemplate.java @@ -10,7 +10,7 @@ *

缓存方法调用入口

*

注:需设置JVM禁用IPv6服务,编译时添加参数:-Djava.net.preferIPv4Stack=true

* - * @author FY + * @author Wujun */ public abstract class CacheAbstractTemplate implements InitializingBean { /** 组播通道命名 */ diff --git a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/CacheBox.java b/jun_cache/src/main/java/net/oschina/j2cache/CacheBox.java similarity index 98% rename from jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/CacheBox.java rename to jun_cache/src/main/java/net/oschina/j2cache/CacheBox.java index b27ca8b659..3538fda661 100644 --- a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/CacheBox.java +++ b/jun_cache/src/main/java/net/oschina/j2cache/CacheBox.java @@ -6,7 +6,7 @@ /** * 写入缓存数据的封装 * - * @author FY + * @author Wujun */ public class CacheBox implements Serializable { /** 缓存写入的时间 */ diff --git a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/CacheBroadcastChannel.java b/jun_cache/src/main/java/net/oschina/j2cache/CacheBroadcastChannel.java similarity index 96% rename from jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/CacheBroadcastChannel.java rename to jun_cache/src/main/java/net/oschina/j2cache/CacheBroadcastChannel.java index 67db567c2c..e61cacc7d9 100644 --- a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/CacheBroadcastChannel.java +++ b/jun_cache/src/main/java/net/oschina/j2cache/CacheBroadcastChannel.java @@ -3,7 +3,7 @@ /** * 缓存通信通道接口类 * - * @author FY + * @author Wujun */ public interface CacheBroadcastChannel { diff --git a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/CacheException.java b/jun_cache/src/main/java/net/oschina/j2cache/CacheException.java similarity index 100% rename from jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/CacheException.java rename to jun_cache/src/main/java/net/oschina/j2cache/CacheException.java diff --git a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/CacheExpiredListener.java b/jun_cache/src/main/java/net/oschina/j2cache/CacheExpiredListener.java similarity index 100% rename from jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/CacheExpiredListener.java rename to jun_cache/src/main/java/net/oschina/j2cache/CacheExpiredListener.java diff --git a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/CacheFactory.java b/jun_cache/src/main/java/net/oschina/j2cache/CacheFactory.java similarity index 99% rename from jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/CacheFactory.java rename to jun_cache/src/main/java/net/oschina/j2cache/CacheFactory.java index 15001005b1..75d8f7bd34 100644 --- a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/CacheFactory.java +++ b/jun_cache/src/main/java/net/oschina/j2cache/CacheFactory.java @@ -10,7 +10,9 @@ import org.springframework.util.Assert; /** - * @author FY + * + * @author Wujun + * */ public class CacheFactory implements InitializingBean { private static final Logger logger = LoggerFactory.getLogger(CacheFactory.class); diff --git a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/CacheObject.java b/jun_cache/src/main/java/net/oschina/j2cache/CacheObject.java similarity index 100% rename from jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/CacheObject.java rename to jun_cache/src/main/java/net/oschina/j2cache/CacheObject.java diff --git a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/CacheProvider.java b/jun_cache/src/main/java/net/oschina/j2cache/CacheProvider.java similarity index 100% rename from jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/CacheProvider.java rename to jun_cache/src/main/java/net/oschina/j2cache/CacheProvider.java diff --git a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/CacheTemplate.java b/jun_cache/src/main/java/net/oschina/j2cache/CacheTemplate.java similarity index 98% rename from jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/CacheTemplate.java rename to jun_cache/src/main/java/net/oschina/j2cache/CacheTemplate.java index ac1cfeda69..41557309dc 100644 --- a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/CacheTemplate.java +++ b/jun_cache/src/main/java/net/oschina/j2cache/CacheTemplate.java @@ -8,11 +8,12 @@ /** * 缓存对外开发接口 * - * @author FY + * @author Wujun */ public class CacheTemplate extends CacheAbstractTemplate { - @Override + @SuppressWarnings("rawtypes") + @Override public CacheObject get(String region, String key) { CacheObject co = new CacheObject(); co.setRegion(region); diff --git a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/broadcast/BroadcastType.java b/jun_cache/src/main/java/net/oschina/j2cache/broadcast/BroadcastType.java similarity index 89% rename from jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/broadcast/BroadcastType.java rename to jun_cache/src/main/java/net/oschina/j2cache/broadcast/BroadcastType.java index 28949e6489..52df5e9785 100644 --- a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/broadcast/BroadcastType.java +++ b/jun_cache/src/main/java/net/oschina/j2cache/broadcast/BroadcastType.java @@ -3,7 +3,7 @@ /** * 集群缓存的广播问题 * - * @author FY + * @author Wujun */ public enum BroadcastType { diff --git a/jun_cache/src/main/java/net/oschina/j2cache/broadcast/Command.java b/jun_cache/src/main/java/net/oschina/j2cache/broadcast/Command.java new file mode 100644 index 0000000000..87c52cf4d0 --- /dev/null +++ b/jun_cache/src/main/java/net/oschina/j2cache/broadcast/Command.java @@ -0,0 +1,113 @@ +package net.oschina.j2cache.broadcast; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.nio.charset.Charset; + +/** + * 广播消息命令封装 + *

<规则:/P> + *

    + *
  • 第 1 个字节为命令代码,长度为1byte [OPT]
  • + *
  • 第 2至3 个字节为缓存region长度,长度为2 [R_LEN]
  • + *
  • 第 4至N 为region值,长度为N-4 [R_LEN]
  • + *
  • 第 N+1至N+2 为key长度,长度为2 [K_LEN]
  • + *
  • 第 N+3至M 为key内容容,长度为M-(N+3)
  • + *
+ * + * @author Wujun + */ +public class Command { + private static final Logger logger = LoggerFactory.getLogger(Command.class); + private static final Charset UTF_8 = Charset.forName("UTF-8"); + + private final byte operator; + private final String region; + private final String key; + + public Command(byte operator, String region, Object key) { + this.operator = operator; + this.region = region; + this.key = String.valueOf(key); + } + + public byte getOperator() { + return operator; + } + + public String getRegion() { + return region; + } + + public Object getKey() { + return key; + } + + // ----------------------------------------------------------------------- + + /** + * 转换为传输buff + * @return {@link byte} + */ + public byte[] toBuff() { + byte[] kBuff = key.getBytes(UTF_8); + byte[] rBytes = region.getBytes(UTF_8); + + int rLen = rBytes.length; + int kLen = kBuff.length; + + byte[] buff = new byte[5 + rLen + kLen]; + int idx = 0; + + buff[idx] = operator; + + buff[++idx] = (byte) (rLen >> 8); + buff[++idx] = (byte) (rLen & 0xFF); + System.arraycopy(rBytes, 0, buff, ++idx, rLen); + idx += rLen; + + buff[idx++] = (byte) (kLen >> 8); + buff[idx++] = (byte) (kLen & 0xFF); + System.arraycopy(kBuff, 0, buff, idx, kLen); + + return buff; + } + + /** + * 接收到广播消息后,解析为{@link Command}对象 + * @param buff 消息buff数据 + * @return {@link Command} + */ + public static Command parse(byte[] buff) { + Command cmd = null; + + try { + int idx = 0; + byte operator = buff[idx]; // 取得操作KEY, 如:{@see CacheCustoms#OPT_DELTED_KEY} + + int rLen = buff[++idx] << 8; + rLen += buff[++idx]; + + if (rLen > 0) { + String region = new String(buff, ++idx, rLen, UTF_8); + idx += rLen; + + int kLen = buff[idx++] << 8; + kLen += buff[idx++]; + + if (kLen > 0) { + byte[] kBuff = new byte[kLen]; + System.arraycopy(buff, idx, kBuff, 0, kLen); + Object key = new String(kBuff, UTF_8); + cmd = new Command(operator, region, key); + } + } + + } catch (Exception e) { + logger.error("解析缓存JGroup广播事件消息为Command对象失败.", e); + } + + return cmd; + } +} diff --git a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/broadcast/JGroupBroadcastChannel.java b/jun_cache/src/main/java/net/oschina/j2cache/broadcast/JGroupBroadcastChannel.java similarity index 99% rename from jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/broadcast/JGroupBroadcastChannel.java rename to jun_cache/src/main/java/net/oschina/j2cache/broadcast/JGroupBroadcastChannel.java index 8cad961103..eff0c84ca1 100644 --- a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/broadcast/JGroupBroadcastChannel.java +++ b/jun_cache/src/main/java/net/oschina/j2cache/broadcast/JGroupBroadcastChannel.java @@ -17,7 +17,7 @@ /** * 缓存信息变更的广播通道 - JGROUP的多播模式实现 * - * @author FY + * @author Wujun */ public class JGroupBroadcastChannel extends ReceiverAdapter implements CacheExpiredListener, CacheBroadcastChannel { private static final Logger logger = LoggerFactory.getLogger(JGroupBroadcastChannel.class); diff --git a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/broadcast/RedisBroadcastChannel.java b/jun_cache/src/main/java/net/oschina/j2cache/broadcast/RedisBroadcastChannel.java similarity index 99% rename from jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/broadcast/RedisBroadcastChannel.java rename to jun_cache/src/main/java/net/oschina/j2cache/broadcast/RedisBroadcastChannel.java index fbd40132d8..03136525df 100644 --- a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/broadcast/RedisBroadcastChannel.java +++ b/jun_cache/src/main/java/net/oschina/j2cache/broadcast/RedisBroadcastChannel.java @@ -15,7 +15,7 @@ import java.util.List; /** - * @author FY + * @author Wujun */ public class RedisBroadcastChannel extends BinaryJedisPubSub implements CacheExpiredListener, CacheBroadcastChannel { private static final Logger logger = LoggerFactory.getLogger(RedisBroadcastChannel.class); diff --git a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/serializer/FstSerializer.java b/jun_cache/src/main/java/net/oschina/j2cache/serializer/FstSerializer.java similarity index 100% rename from jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/serializer/FstSerializer.java rename to jun_cache/src/main/java/net/oschina/j2cache/serializer/FstSerializer.java diff --git a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/serializer/FstSnappySerializer.java b/jun_cache/src/main/java/net/oschina/j2cache/serializer/FstSnappySerializer.java similarity index 100% rename from jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/serializer/FstSnappySerializer.java rename to jun_cache/src/main/java/net/oschina/j2cache/serializer/FstSnappySerializer.java diff --git a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/serializer/JdkSerializer.java b/jun_cache/src/main/java/net/oschina/j2cache/serializer/JdkSerializer.java similarity index 100% rename from jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/serializer/JdkSerializer.java rename to jun_cache/src/main/java/net/oschina/j2cache/serializer/JdkSerializer.java diff --git a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/serializer/Serializer.java b/jun_cache/src/main/java/net/oschina/j2cache/serializer/Serializer.java similarity index 100% rename from jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/serializer/Serializer.java rename to jun_cache/src/main/java/net/oschina/j2cache/serializer/Serializer.java diff --git a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/serializer/SerializerTools.java b/jun_cache/src/main/java/net/oschina/j2cache/serializer/SerializerTools.java similarity index 100% rename from jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/serializer/SerializerTools.java rename to jun_cache/src/main/java/net/oschina/j2cache/serializer/SerializerTools.java diff --git a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/serializer/StringSerializer.java b/jun_cache/src/main/java/net/oschina/j2cache/serializer/StringSerializer.java similarity index 100% rename from jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/serializer/StringSerializer.java rename to jun_cache/src/main/java/net/oschina/j2cache/serializer/StringSerializer.java diff --git a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/store/StoreType.java b/jun_cache/src/main/java/net/oschina/j2cache/store/StoreType.java similarity index 100% rename from jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/store/StoreType.java rename to jun_cache/src/main/java/net/oschina/j2cache/store/StoreType.java diff --git a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/store/ehcache/EhCache.java b/jun_cache/src/main/java/net/oschina/j2cache/store/ehcache/EhCache.java similarity index 100% rename from jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/store/ehcache/EhCache.java rename to jun_cache/src/main/java/net/oschina/j2cache/store/ehcache/EhCache.java diff --git a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/store/ehcache/EhCacheProvider.java b/jun_cache/src/main/java/net/oschina/j2cache/store/ehcache/EhCacheProvider.java similarity index 100% rename from jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/store/ehcache/EhCacheProvider.java rename to jun_cache/src/main/java/net/oschina/j2cache/store/ehcache/EhCacheProvider.java diff --git a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/store/map/MapCache.java b/jun_cache/src/main/java/net/oschina/j2cache/store/map/MapCache.java similarity index 100% rename from jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/store/map/MapCache.java rename to jun_cache/src/main/java/net/oschina/j2cache/store/map/MapCache.java diff --git a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/store/redis/RedisCache.java b/jun_cache/src/main/java/net/oschina/j2cache/store/redis/RedisCache.java similarity index 100% rename from jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/store/redis/RedisCache.java rename to jun_cache/src/main/java/net/oschina/j2cache/store/redis/RedisCache.java diff --git a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/store/redis/RedisCacheProvider.java b/jun_cache/src/main/java/net/oschina/j2cache/store/redis/RedisCacheProvider.java similarity index 100% rename from jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/store/redis/RedisCacheProvider.java rename to jun_cache/src/main/java/net/oschina/j2cache/store/redis/RedisCacheProvider.java diff --git a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/utils/CacheCodeUtils.java b/jun_cache/src/main/java/net/oschina/j2cache/utils/CacheCodeUtils.java similarity index 96% rename from jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/utils/CacheCodeUtils.java rename to jun_cache/src/main/java/net/oschina/j2cache/utils/CacheCodeUtils.java index 54d0a8fa91..044972bb67 100644 --- a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/utils/CacheCodeUtils.java +++ b/jun_cache/src/main/java/net/oschina/j2cache/utils/CacheCodeUtils.java @@ -1,7 +1,7 @@ package net.oschina.j2cache.utils; /** - * @author FY + * @author Wujun */ public class CacheCodeUtils { diff --git a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/utils/CacheCustoms.java b/jun_cache/src/main/java/net/oschina/j2cache/utils/CacheCustoms.java similarity index 94% rename from jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/utils/CacheCustoms.java rename to jun_cache/src/main/java/net/oschina/j2cache/utils/CacheCustoms.java index fb859918f4..15cd62fde3 100644 --- a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/utils/CacheCustoms.java +++ b/jun_cache/src/main/java/net/oschina/j2cache/utils/CacheCustoms.java @@ -3,7 +3,7 @@ /** * 缓存中用到的一些常量 * - * @author FY + * @author Wujun */ public interface CacheCustoms { diff --git a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/utils/PropertiesLoader.java b/jun_cache/src/main/java/net/oschina/j2cache/utils/PropertiesLoader.java similarity index 99% rename from jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/utils/PropertiesLoader.java rename to jun_cache/src/main/java/net/oschina/j2cache/utils/PropertiesLoader.java index a9b037750a..159bed08ae 100644 --- a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/utils/PropertiesLoader.java +++ b/jun_cache/src/main/java/net/oschina/j2cache/utils/PropertiesLoader.java @@ -12,7 +12,7 @@ /** * Properties文件载入工具类. 可载入多个properties文件, 相同的属性在最后载入的文件中的值将会覆盖之前的值,但以System的Property优先. * - * @author calvin + * @author Wujun */ public class PropertiesLoader { diff --git a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/utils/StrExtUtils.java b/jun_cache/src/main/java/net/oschina/j2cache/utils/StrExtUtils.java similarity index 87% rename from jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/utils/StrExtUtils.java rename to jun_cache/src/main/java/net/oschina/j2cache/utils/StrExtUtils.java index a7f96eaf6a..8fb56fb82c 100644 --- a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/utils/StrExtUtils.java +++ b/jun_cache/src/main/java/net/oschina/j2cache/utils/StrExtUtils.java @@ -1,8 +1,7 @@ package net.oschina.j2cache.utils; /** - * @author FY - * @since 1.0 + * @author Wujun */ public class StrExtUtils { public static boolean isNullOrEmpty(String string) { diff --git a/jun_java_plugins/jun_j2cache/src/test/java/net/oschina/j2cache/CacheTemplateTest.java b/jun_cache/src/test/java/net/oschina/j2cache/CacheTemplateTest.java similarity index 97% rename from jun_java_plugins/jun_j2cache/src/test/java/net/oschina/j2cache/CacheTemplateTest.java rename to jun_cache/src/test/java/net/oschina/j2cache/CacheTemplateTest.java index 15f20a84f0..57d27e62a9 100644 --- a/jun_java_plugins/jun_j2cache/src/test/java/net/oschina/j2cache/CacheTemplateTest.java +++ b/jun_cache/src/test/java/net/oschina/j2cache/CacheTemplateTest.java @@ -8,8 +8,9 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** - * @author FY - * @since 1.0 + * + * @author Wujun + * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:/spring-cache-test.xml"}) diff --git a/jun_java_plugins/jun_j2cache/src/test/java/net/oschina/j2cache/serializer/SerializerBaseTest.java b/jun_cache/src/test/java/net/oschina/j2cache/serializer/SerializerBaseTest.java similarity index 96% rename from jun_java_plugins/jun_j2cache/src/test/java/net/oschina/j2cache/serializer/SerializerBaseTest.java rename to jun_cache/src/test/java/net/oschina/j2cache/serializer/SerializerBaseTest.java index 8a1ad0dc84..0ddab71ddd 100644 --- a/jun_java_plugins/jun_j2cache/src/test/java/net/oschina/j2cache/serializer/SerializerBaseTest.java +++ b/jun_cache/src/test/java/net/oschina/j2cache/serializer/SerializerBaseTest.java @@ -4,11 +4,10 @@ import org.junit.Before; import org.junit.Test; -/** - * 序列化工具测试 +/** + * 序列化工具测试 + * @author Wujun * - * @author FY - * @since 1.0 */ public class SerializerBaseTest { private String cacheKey = "cacheKey"; diff --git a/jun_java_plugins/jun_j2cache/src/test/java/net/oschina/j2cache/serializer/SerializerBenchmarkTest.java b/jun_cache/src/test/java/net/oschina/j2cache/serializer/SerializerBenchmarkTest.java similarity index 96% rename from jun_java_plugins/jun_j2cache/src/test/java/net/oschina/j2cache/serializer/SerializerBenchmarkTest.java rename to jun_cache/src/test/java/net/oschina/j2cache/serializer/SerializerBenchmarkTest.java index 7a3a2a5a32..d9d23e4da2 100644 --- a/jun_java_plugins/jun_j2cache/src/test/java/net/oschina/j2cache/serializer/SerializerBenchmarkTest.java +++ b/jun_cache/src/test/java/net/oschina/j2cache/serializer/SerializerBenchmarkTest.java @@ -3,16 +3,10 @@ import org.junit.Before; import org.junit.Test; -/** +/** * 序列化工具的简单性能测试 - *
- *     OS  : Windows 10 专业版
- *     CPU : Inter(R)Core(TM) i7-4720HQ @2.60GHz
- *     Mem : 8G
- * 
+ * @author Wujun * - * @author FY - * @since 1.0 */ public class SerializerBenchmarkTest { diff --git a/jun_java_plugins/jun_j2cache/src/test/java/net/oschina/j2cache/serializer/TestObj.java b/jun_cache/src/test/java/net/oschina/j2cache/serializer/TestObj.java similarity index 95% rename from jun_java_plugins/jun_j2cache/src/test/java/net/oschina/j2cache/serializer/TestObj.java rename to jun_cache/src/test/java/net/oschina/j2cache/serializer/TestObj.java index 57bc04fdbb..f2bebc1fe8 100644 --- a/jun_java_plugins/jun_j2cache/src/test/java/net/oschina/j2cache/serializer/TestObj.java +++ b/jun_cache/src/test/java/net/oschina/j2cache/serializer/TestObj.java @@ -2,9 +2,10 @@ import java.io.Serializable; -/** - * @author FY - * @since 1.0 +/** + * + * @author Wujun + * */ public class TestObj implements Serializable { private String id; diff --git a/jun_java_plugins/jun_j2cache/src/test/resources/cache/ehcache.xml b/jun_cache/src/test/resources/cache/ehcache.xml similarity index 100% rename from jun_java_plugins/jun_j2cache/src/test/resources/cache/ehcache.xml rename to jun_cache/src/test/resources/cache/ehcache.xml diff --git a/jun_java_plugins/jun_j2cache/src/test/resources/cache/jgourps_network_udp.xml b/jun_cache/src/test/resources/cache/jgourps_network_udp.xml similarity index 100% rename from jun_java_plugins/jun_j2cache/src/test/resources/cache/jgourps_network_udp.xml rename to jun_cache/src/test/resources/cache/jgourps_network_udp.xml diff --git a/jun_java_plugins/jun_j2cache/src/test/resources/cache/redis.properties b/jun_cache/src/test/resources/cache/redis.properties similarity index 100% rename from jun_java_plugins/jun_j2cache/src/test/resources/cache/redis.properties rename to jun_cache/src/test/resources/cache/redis.properties diff --git a/jun_java_plugins/jun_j2cache/src/test/resources/spring-cache-test.xml b/jun_cache/src/test/resources/spring-cache-test.xml similarity index 100% rename from jun_java_plugins/jun_j2cache/src/test/resources/spring-cache-test.xml rename to jun_cache/src/test/resources/spring-cache-test.xml diff --git a/jun_java_plugins/jun_easycaptcha/README.md b/jun_captcha_code/README.md similarity index 100% rename from jun_java_plugins/jun_easycaptcha/README.md rename to jun_captcha_code/README.md diff --git a/jun_captcha_code/pom.xml b/jun_captcha_code/pom.xml new file mode 100644 index 0000000000..cb7494f927 --- /dev/null +++ b/jun_captcha_code/pom.xml @@ -0,0 +1,108 @@ + + 4.0.0 + + com.jun.plugin + jun_captcha_code + 1.0 + + + + org.apache.maven.plugins + maven-compiler-plugin + + 8 + 8 + + + + + jar + + jun_captcha_code + Java web graphics verification code, support gif verification code. + + + UTF-8 + UTF-8 + 1.8 + + + + + + javax.servlet + javax.servlet-api + 3.1.0 + provided + + + junit + junit + 4.12 + test + + + + + + release + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + package + + jar-no-fork + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.9.1 + + + package + + jar + + + + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + verify + + sign + + + + + + + + + oss + https://oss.sonatype.org/content/repositories/snapshots/ + + + oss + https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + + + + \ No newline at end of file diff --git a/jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/ArithmeticCaptcha.java b/jun_captcha_code/src/main/java/com/wf/captcha/ArithmeticCaptcha.java similarity index 100% rename from jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/ArithmeticCaptcha.java rename to jun_captcha_code/src/main/java/com/wf/captcha/ArithmeticCaptcha.java diff --git a/jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/ChineseCaptcha.java b/jun_captcha_code/src/main/java/com/wf/captcha/ChineseCaptcha.java similarity index 100% rename from jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/ChineseCaptcha.java rename to jun_captcha_code/src/main/java/com/wf/captcha/ChineseCaptcha.java diff --git a/jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/ChineseGifCaptcha.java b/jun_captcha_code/src/main/java/com/wf/captcha/ChineseGifCaptcha.java similarity index 100% rename from jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/ChineseGifCaptcha.java rename to jun_captcha_code/src/main/java/com/wf/captcha/ChineseGifCaptcha.java diff --git a/jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/GifCaptcha.java b/jun_captcha_code/src/main/java/com/wf/captcha/GifCaptcha.java similarity index 100% rename from jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/GifCaptcha.java rename to jun_captcha_code/src/main/java/com/wf/captcha/GifCaptcha.java diff --git a/jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/SpecCaptcha.java b/jun_captcha_code/src/main/java/com/wf/captcha/SpecCaptcha.java similarity index 100% rename from jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/SpecCaptcha.java rename to jun_captcha_code/src/main/java/com/wf/captcha/SpecCaptcha.java diff --git a/jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/base/ArithmeticCaptchaAbstract.java b/jun_captcha_code/src/main/java/com/wf/captcha/base/ArithmeticCaptchaAbstract.java similarity index 100% rename from jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/base/ArithmeticCaptchaAbstract.java rename to jun_captcha_code/src/main/java/com/wf/captcha/base/ArithmeticCaptchaAbstract.java diff --git a/jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/base/Captcha.java b/jun_captcha_code/src/main/java/com/wf/captcha/base/Captcha.java similarity index 97% rename from jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/base/Captcha.java rename to jun_captcha_code/src/main/java/com/wf/captcha/base/Captcha.java index 712c5a4912..e38e4d4e3b 100644 --- a/jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/base/Captcha.java +++ b/jun_captcha_code/src/main/java/com/wf/captcha/base/Captcha.java @@ -1,11 +1,11 @@ package com.wf.captcha.base; -import com.wf.captcha.utils.FontsUtil; - import java.awt.*; import java.awt.geom.CubicCurve2D; import java.awt.geom.QuadCurve2D; -import java.io.*; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; import java.util.Base64; /** @@ -274,7 +274,7 @@ public void setFont(int font, float size) throws IOException, FontFormatExceptio } public void setFont(int font, int style, float size) throws IOException, FontFormatException { - this.font = FontsUtil.getFont(FONT_NAMES[font], style, size); + this.font = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream("/" + FONT_NAMES[font])).deriveFont(style, size); } public int getLen() { diff --git a/jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/base/ChineseCaptchaAbstract.java b/jun_captcha_code/src/main/java/com/wf/captcha/base/ChineseCaptchaAbstract.java similarity index 100% rename from jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/base/ChineseCaptchaAbstract.java rename to jun_captcha_code/src/main/java/com/wf/captcha/base/ChineseCaptchaAbstract.java diff --git a/jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/base/Randoms.java b/jun_captcha_code/src/main/java/com/wf/captcha/base/Randoms.java similarity index 100% rename from jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/base/Randoms.java rename to jun_captcha_code/src/main/java/com/wf/captcha/base/Randoms.java diff --git a/jun_captcha_code/src/main/java/com/wf/captcha/servlet/CaptchaServlet.java b/jun_captcha_code/src/main/java/com/wf/captcha/servlet/CaptchaServlet.java new file mode 100644 index 0000000000..e273a03a44 --- /dev/null +++ b/jun_captcha_code/src/main/java/com/wf/captcha/servlet/CaptchaServlet.java @@ -0,0 +1,29 @@ +package com.wf.captcha.servlet; + +import java.io.IOException; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import com.wf.captcha.utils.CaptchaUtil; + +/** + * 验证码servlet + * Created by 王帆 on 2018-07-27 上午 10:08. + */ +public class CaptchaServlet extends HttpServlet { + private static final long serialVersionUID = -90304944339413093L; + + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + CaptchaUtil.out(request, response); + } + + public void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + doGet(request, response); + } + +} diff --git a/jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/utils/CaptchaUtil.java b/jun_captcha_code/src/main/java/com/wf/captcha/utils/CaptchaUtil.java similarity index 100% rename from jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/utils/CaptchaUtil.java rename to jun_captcha_code/src/main/java/com/wf/captcha/utils/CaptchaUtil.java diff --git a/jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/utils/Encoder.java b/jun_captcha_code/src/main/java/com/wf/captcha/utils/Encoder.java similarity index 100% rename from jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/utils/Encoder.java rename to jun_captcha_code/src/main/java/com/wf/captcha/utils/Encoder.java diff --git a/jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/utils/GifEncoder.java b/jun_captcha_code/src/main/java/com/wf/captcha/utils/GifEncoder.java similarity index 100% rename from jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/utils/GifEncoder.java rename to jun_captcha_code/src/main/java/com/wf/captcha/utils/GifEncoder.java diff --git a/jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/utils/Quant.java b/jun_captcha_code/src/main/java/com/wf/captcha/utils/Quant.java similarity index 100% rename from jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/utils/Quant.java rename to jun_captcha_code/src/main/java/com/wf/captcha/utils/Quant.java diff --git a/jun_java_plugins/jun_easycaptcha/src/main/resources/actionj.ttf b/jun_captcha_code/src/main/resources/actionj.ttf similarity index 100% rename from jun_java_plugins/jun_easycaptcha/src/main/resources/actionj.ttf rename to jun_captcha_code/src/main/resources/actionj.ttf diff --git a/jun_java_plugins/jun_easycaptcha/src/main/resources/epilog.ttf b/jun_captcha_code/src/main/resources/epilog.ttf similarity index 100% rename from jun_java_plugins/jun_easycaptcha/src/main/resources/epilog.ttf rename to jun_captcha_code/src/main/resources/epilog.ttf diff --git a/jun_java_plugins/jun_easycaptcha/src/main/resources/fresnel.ttf b/jun_captcha_code/src/main/resources/fresnel.ttf similarity index 100% rename from jun_java_plugins/jun_easycaptcha/src/main/resources/fresnel.ttf rename to jun_captcha_code/src/main/resources/fresnel.ttf diff --git a/jun_java_plugins/jun_easycaptcha/src/main/resources/headache.ttf b/jun_captcha_code/src/main/resources/headache.ttf similarity index 100% rename from jun_java_plugins/jun_easycaptcha/src/main/resources/headache.ttf rename to jun_captcha_code/src/main/resources/headache.ttf diff --git a/jun_java_plugins/jun_easycaptcha/src/main/resources/lexo.ttf b/jun_captcha_code/src/main/resources/lexo.ttf similarity index 100% rename from jun_java_plugins/jun_easycaptcha/src/main/resources/lexo.ttf rename to jun_captcha_code/src/main/resources/lexo.ttf diff --git a/jun_java_plugins/jun_easycaptcha/src/main/resources/prefix.ttf b/jun_captcha_code/src/main/resources/prefix.ttf similarity index 100% rename from jun_java_plugins/jun_easycaptcha/src/main/resources/prefix.ttf rename to jun_captcha_code/src/main/resources/prefix.ttf diff --git a/jun_java_plugins/jun_easycaptcha/src/main/resources/progbot.ttf b/jun_captcha_code/src/main/resources/progbot.ttf similarity index 100% rename from jun_java_plugins/jun_easycaptcha/src/main/resources/progbot.ttf rename to jun_captcha_code/src/main/resources/progbot.ttf diff --git a/jun_java_plugins/jun_easycaptcha/src/main/resources/ransom.ttf b/jun_captcha_code/src/main/resources/ransom.ttf similarity index 100% rename from jun_java_plugins/jun_easycaptcha/src/main/resources/ransom.ttf rename to jun_captcha_code/src/main/resources/ransom.ttf diff --git a/jun_java_plugins/jun_easycaptcha/src/main/resources/robot.ttf b/jun_captcha_code/src/main/resources/robot.ttf similarity index 100% rename from jun_java_plugins/jun_easycaptcha/src/main/resources/robot.ttf rename to jun_captcha_code/src/main/resources/robot.ttf diff --git a/jun_java_plugins/jun_easycaptcha/src/main/resources/scandal.ttf b/jun_captcha_code/src/main/resources/scandal.ttf similarity index 100% rename from jun_java_plugins/jun_easycaptcha/src/main/resources/scandal.ttf rename to jun_captcha_code/src/main/resources/scandal.ttf diff --git a/jun_captcha_code/src/test/java/com/wf/captcha/CaptchaTest.java b/jun_captcha_code/src/test/java/com/wf/captcha/CaptchaTest.java new file mode 100644 index 0000000000..084aac6ffe --- /dev/null +++ b/jun_captcha_code/src/test/java/com/wf/captcha/CaptchaTest.java @@ -0,0 +1,71 @@ +package com.wf.captcha; + +import org.junit.Test; + +import java.io.File; +import java.io.FileOutputStream; + +/** + * 测试类 + * Created by 王帆 on 2018-07-27 上午 10:08. + */ +public class CaptchaTest { + + @Test + public void test() throws Exception { + for (int i = 0; i < 10; i++) { + SpecCaptcha specCaptcha = new SpecCaptcha(); + specCaptcha.setLen(4); + specCaptcha.setFont(i, 32f); + System.out.println(specCaptcha.text()); + specCaptcha.out(new FileOutputStream(new File("D:/Java/aa" + i + ".png"))); + } + } + + @Test + public void testGIf() throws Exception { + for (int i = 0; i < 10; i++) { + GifCaptcha gifCaptcha = new GifCaptcha(); + gifCaptcha.setLen(5); + gifCaptcha.setFont(i, 32f); + System.out.println(gifCaptcha.text()); + gifCaptcha.out(new FileOutputStream(new File("D:/Java/bb" + i + ".gif"))); + } + } + + @Test + public void testHan() throws Exception { + for (int i = 0; i < 10; i++) { + ChineseCaptcha chineseCaptcha = new ChineseCaptcha(); + System.out.println(chineseCaptcha.text()); + chineseCaptcha.out(new FileOutputStream(new File("D:/Java/cc" + i + ".png"))); + } + } + + @Test + public void testGifHan() throws Exception { + for (int i = 0; i < 10; i++) { + ChineseGifCaptcha chineseGifCaptcha = new ChineseGifCaptcha(); + System.out.println(chineseGifCaptcha.text()); + chineseGifCaptcha.out(new FileOutputStream(new File("D:/Java/dd" + i + ".gif"))); + } + } + + @Test + public void testArit() throws Exception { + for (int i = 0; i < 10; i++) { + ArithmeticCaptcha specCaptcha = new ArithmeticCaptcha(); + specCaptcha.setLen(3); + specCaptcha.setFont(i, 28f); + System.out.println(specCaptcha.getArithmeticString() + " " + specCaptcha.text()); + specCaptcha.out(new FileOutputStream(new File("D:/Java/ee" + i + ".png"))); + } + } + + @Test + public void testBase64() throws Exception { + GifCaptcha specCaptcha = new GifCaptcha(); + System.out.println(specCaptcha.toBase64("")); + } + +} diff --git a/jun_captcha_slider/README.md b/jun_captcha_slider/README.md new file mode 100644 index 0000000000..ca034f12bf --- /dev/null +++ b/jun_captcha_slider/README.md @@ -0,0 +1,234 @@ +## Slider Captcha + +English | 中文 + +--- + +The user completes the verification by dragging the slider to support the PC and mobile terminals. The time, accuracy and sliding trajectory information of user dragging behavior can be sent to the server, and then the background algorithm verification can be carried out. + +## Blazor Version + +http://blazor.sdgxgz.com/captchas + +## Online Demonstration +Single page presentation: http://longbowenterprise.gitee.io/slidercaptcha/ +In-Project Demonstration: https://argo.zylweb.cn/ (Open source Admin Control Pannel [[BootstrapAdmin](https://github.com/ArgoZhang/BootstrapAdmin)]) +**Slide captcha appears for the fourth time after three times of incorrect password input** + +## Screenshot +![输入图片说明](https://images.gitee.com/uploads/images/2019/0316/003740_c5175e6b_554725.png "SliderCaptcha.png") +![输入图片说明](https://gitee.com/uploads/images/2019/0410/124955_f9b6d54c_554725.png "Untitled.png") + +## Quick Start + +### Dependencies +jQuery bootstrap font-awesome + +### CSS + +```html + + + +``` +Copy-paste the stylesheet `` into your `` before all other stylesheets to load our CSS. + +### JS + +```html + + +``` + +Place the following ` +``` + +### Options + +```html +
+ +``` + +Name | Type | Default | Description | +---|---|---|--- +width | integer | 280 | Background picture width +height | integer | 150 | Background picture height +sliderL | integer | 42 | Puzzle Width +sliderR | integer | 9 | Puzzle Outburst Radius +offset | integer | 5 | Validation of error tolerance deviation. default 5px +loadingText | string | "Loading..." | Text information displayed when images are loaded +failedText | string | "Try again" | Text information displayed when validation fails +barText | integer | "Slide right to fill" | Text information displayed when dragging the slider to prepare for dragging +repeatIcon | string | "fa fa-redo" | Reload icons. dependent on `font-awesome` +setSrc | function | "https://picsum.photos/?image=random" | Setting the Picture Loading Path +onSuccess | function | *null* | Callback this function when validation passes +onFail | function | *null* | Callback this function when validation fails +onRefresh | function | *null* | Callback this function when click on the reload icon +localImages | function | function () { return 'images/Pic' + Math.round(Math.random() * 4) + '.jpg'; } | Call this function when the image loading fails + +### Methods + +```html +
+ +``` + +Method | Example | Description +---|---|--- +reset | $('#captcha').sliderCaptcha('reset') | reset + +## Events + +None + +## Issue +Please go to [Issue](../../issues) page to create issue + +## Verify On Server Side +### Client Code Example +#### 1. JavaScript +```js +verify: function (arr, url) { + var ret = false; + $.ajax({ + url: url, + data: JSON.stringify(arr), + async: false, + cache: false, + type: 'POST', + contentType: 'application/json', + dataType: 'json', + success: function (result) { + ret = result; + } + }); + return ret; +} +``` + +Parameter | Type | Default | Descript | +---|---|---|--- +arr | array | object | trails of user dragging slider | +url | string | remoteUrl | option.remoteUrl | + +sample code +```js +$('#captcha').sliderCaptcha({ + repeatIcon: 'fa fa-redo', + setSrc: function () { + return 'https://imgs.sdgxgz.com/images/Pic' + Math.round(Math.random() * 136) + '.jpg'; + }, + onSuccess: function () { + window.location.href = 'https://gitee.com/LongbowEnterprise/SliderCaptcha'; + }, + remoteUrl: "api/Captcha" +}); +``` + +### Server Code Example +#### 1. NETCore WebApi +```csharp +/// +/// slider verify web api +/// +[Route("api/[controller]")] +[ApiController] +[AllowAnonymous] +public class CaptchaController : ControllerBase +{ + /// + /// 服务器端滑块验证方法 + /// + /// + [HttpPost] + public bool Post([FromBody]List datas) + { + var sum = datas.Sum(); + var avg = sum * 1.0 / datas.Count; + var stddev = datas.Select(v => Math.Pow(v - avg, 2)).Sum() / datas.Count; + return stddev != 0; + } +} +``` + +#### 2. JAVA SpringBoot +You may have precision problems, but you can use BigDecimal optimization +```java +@RestController +@RequestMapping("/sliderCaptcha") +public class SliderCaptchaController { + + @PostMapping("/isVerify") + public boolean isVerify(List datas) { + int sum = 0; + for (Integer data : datas) { + sum += data; + } + double avg = sum * 1.0 / datas.size(); + + double sum2 = 0.0; + for (Integer data : datas) { + sum2 += Math.pow(data - avg, 2); + } + + double stddev = sum2 / datas.size(); + return stddev != 0; + } + +} +``` + +## Q&A + +[linked issue](https://gitee.com/LongbowEnterprise/SliderCaptcha/issues/I110MF?from=project-issue) + +## Contribution + +1. Fork this project +2. Create new Feat_xxx branch +3. Commit +4. Create Pull Request \ No newline at end of file diff --git a/jun_captcha_slider/README.zh-CN.md b/jun_captcha_slider/README.zh-CN.md new file mode 100644 index 0000000000..e570c5a4f5 --- /dev/null +++ b/jun_captcha_slider/README.zh-CN.md @@ -0,0 +1,245 @@ +## 滑块式验证码 + +English | 中文 + +--- + +用户通过拖动滑块行为来完成校验,支持PC端及移动端。可以将用户拖动行为的时间、精度,滑动轨迹等信息到服务器,然后进行后台算法验证。 + +## **特别介绍** + + **Blazor 版本的滑块验证码** [传送门](http://blazor.sdgxgz.com/captchas) + +## 在线演示 +单页面演示:http://longbowenterprise.gitee.io/slidercaptcha/ +项目内演示:http://ba.sdgxgz.com/ (本项目为开源后台管理框架 [[BootstrapAdmin](https://gitee.com/LongbowEnterprise/BootstrapAdmin)]) +**输入三次错误密码后第四次出现滑块式行为验证码** + +## 效果图 +![输入图片说明](https://images.gitee.com/uploads/images/2019/0316/003740_c5175e6b_554725.png "SliderCaptcha.png") +![输入图片说明](https://gitee.com/uploads/images/2019/0410/124955_f9b6d54c_554725.png "Untitled.png") + +## 快速开始 + +### 组件依赖 jQuery bootstrap font-awesome + +### CSS + +```html + + + +``` +将引入样式表的 <link> 标签复制并粘贴到 <head> 中,并放在所有其他样式表之前。 + +### JS + +```html + + +``` + +将引入脚本的 <script> 标签复制并粘贴到 <body> 最后面。 + +## 用法 + +添加网页Html元素 + +```html +
+``` + +## API + +### 通过 javascript 初始化控件 + +```html +
+ +``` + +### Options + +可以根据自己需要设置宽度与高度等配置 + +```html +
+ +``` + +名称 | 类型 | 默认值 | 说明 | +---|---|---|--- +width | integer | 280 | 背景图片宽度 +height | integer | 150 | 背景图标高度 +sliderL | integer | 42 | 拼图宽度 +sliderR | integer | 9 | 拼图突出半径 +offset | integer | 5 | 验证容错偏差值 默认5个像素偏差即认为验证通过 +loadingText | string | "正在加载中..." | 图片加载时显示的文本信息 +failedText | string | "再试一次" | 验证失败时显示的文本信息 +barText | integer | "向右滑动填充拼图" | 拖动滑块准备拖动时显示的文本信息 +repeatIcon | string | "fa fa-redo" | 重新加载图标 需引用 font-awesome +setSrc | function | "https://picsum.photos/?image=random" | 设置图片加载路径 +onSuccess | function | *null* | 验证通过时回调此函数 +onFail | function | *null* | 验证失败时回调此函数 +onRefresh | function | *null* | 点击重新加载图标时回调此函数 +localImages | function | function () { return 'images/Pic' + Math.round(Math.random() * 4) + '.jpg'; } | 图床图片加载失败时调用此方法返回本地图片路径 +remoteUrl | string | null | 服务器端验证请求地址,请求方式默认为 post 方式 +verify | function | function (arr, url) { return true; } | 服务器端验证方法 arr 为客户端拖动滑块轨迹,url 为服务器端请求地址,返回值为布尔值 + +### 方法 + +```html +
+ +``` + +Method | Example | Description +---|---|--- +reset | $('#captcha').sliderCaptcha('reset') | 重置控件 + +## 事件 +无 + +## Issue +请前往 [Issue](../../issues) 页面添加问题 + +## 服务器端认证 +### 客户端代码示例 +#### 1. JavaScript +控件配置信息中有 remoteUrl 和 verify 两个配置项,合理正确的设置这两个配置项即可达到想要的服务器端认证逻辑 +remoteUrl 默认值为 null 表示未启用服务器端认证方式,设置请求的 webapi 地址后启用服务器端认证方法 +控件默认请求服务器端方法如下,可适当进行更改 +```js +verify: function (arr, url) { + var ret = false; + $.ajax({ + url: url, + data: JSON.stringify(arr), + async: false, + cache: false, + type: 'POST', + contentType: 'application/json', + dataType: 'json', + success: function (result) { + ret = result; + } + }); + return ret; +} +``` + +参数 | 类型 | 默认值 | 说明 | +---|---|---|--- +arr | array | object | 客户端拖动滑块轨迹数组 | +url | string | remoteUrl | 配置项中的 remoteUrl 参数值 | + +完整示例代码 +```js +$('#captcha').sliderCaptcha({ + repeatIcon: 'fa fa-redo', + setSrc: function () { + return 'https://imgs.sdgxgz.com/images/Pic' + Math.round(Math.random() * 136) + '.jpg'; + }, + onSuccess: function () { + window.location.href = 'https://gitee.com/LongbowEnterprise/SliderCaptcha'; + }, + remoteUrl: "api/Captcha" +}); +``` + +### 服务器端代码示例 +#### 1. NETCore WebApi +```csharp +/// +/// 滑块服务器端验证方法 +/// +[Route("api/[controller]")] +[ApiController] +[AllowAnonymous] +public class CaptchaController : ControllerBase +{ + /// + /// 服务器端滑块验证方法 + /// + /// + [HttpPost] + public bool Post([FromBody]List datas) + { + var sum = datas.Sum(); + var avg = sum * 1.0 / datas.Count; + var stddev = datas.Select(v => Math.Pow(v - avg, 2)).Sum() / datas.Count; + return stddev != 0; + } +} +``` + +#### 2. JAVA SpringBoot +可能会存在精度问题,采用BigDecimal计算即可 +```java +@RestController +@RequestMapping("/sliderCaptcha") +public class SliderCaptchaController { + + @PostMapping("/isVerify") + public boolean isVerify(List datas) { + int sum = 0; + for (Integer data : datas) { + sum += data; + } + double avg = sum * 1.0 / datas.size(); + + double sum2 = 0.0; + for (Integer data : datas) { + sum2 += Math.pow(data - avg, 2); + } + + double stddev = sum2 / datas.size(); + return stddev != 0; + } + +} +``` + +## 常见问题 + +### 服务端验证的返回结果怎么一直都是true + +示例代码中演示的是前端提交用户滑动轨迹到服务器端进行了 Y 轴的平方差校验,为零时才返回 false,否则返回 true,为 true 表示 Y 轴有偏移,简单的认为此操作是人为操作,因为人手拖动过程中的抖动 Y 轴理论上是不可能没有偏移的。因此依据此值进行是否是人为拖动滑块。 + +[相关问题](https://gitee.com/LongbowEnterprise/SliderCaptcha/issues/I110MF?from=project-issue) + +## 参与贡献 + +1. Fork 本项目 +2. 新建 Feat_xxx 分支 +3. 提交代码 +4. 新建 Pull Request \ No newline at end of file diff --git a/jun_captcha_slider/pom.xml b/jun_captcha_slider/pom.xml new file mode 100644 index 0000000000..21dde8743c --- /dev/null +++ b/jun_captcha_slider/pom.xml @@ -0,0 +1,40 @@ + + + 4.0.0 + + com.jun.plugin + jun_plugin + 1.0 + + + jun_captcha_slider + 0.0.1-SNAPSHOT + war + + jun_captcha Maven Webapp + http://maven.apache.org + + + UTF-8 + + + + + junit + junit + 3.8.1 + test + + + + + mysql + mysql-connector-java + 5.1.40 + + + + jun_captcha_slider + + diff --git a/jun_java_plugins/jun_datasource/src/main/webapp/WEB-INF/web.xml b/jun_captcha_slider/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from jun_java_plugins/jun_datasource/src/main/webapp/WEB-INF/web.xml rename to jun_captcha_slider/src/main/webapp/WEB-INF/web.xml diff --git a/jun_captcha_slider/src/main/webapp/disk/longbow.slidercaptcha.js b/jun_captcha_slider/src/main/webapp/disk/longbow.slidercaptcha.js new file mode 100644 index 0000000000..4529702032 --- /dev/null +++ b/jun_captcha_slider/src/main/webapp/disk/longbow.slidercaptcha.js @@ -0,0 +1,322 @@ +(function ($) { + 'use strict'; + + var SliderCaptcha = function (element, options) { + this.$element = $(element); + this.options = $.extend({}, SliderCaptcha.DEFAULTS, options); + this.$element.css({ 'position': 'relative', 'width': this.options.width + 'px', 'margin': '0 auto' }); + this.init(); + }; + + SliderCaptcha.VERSION = '1.0'; + SliderCaptcha.Author = 'argo@163.com'; + SliderCaptcha.DEFAULTS = { + width: 280, // canvas宽度 + height: 155, // canvas高度 + PI: Math.PI, + sliderL: 42, // 滑块边长 + sliderR: 9, // 滑块半径 + offset: 5, // 容错偏差 + loadingText: '正在加载中...', + failedText: '再试一次', + barText: '向右滑动填充拼图', + repeatIcon: 'fa fa-repeat', + maxLoadCount: 3, + localImages: function () { + return 'images/Pic' + Math.round(Math.random() * 4) + '.jpg'; + }, + verify: function (arr, url) { + var ret = false; + $.ajax({ + url: url, + data: JSON.stringify(arr), + async: false, + cache: false, + type: 'POST', + contentType: 'application/json', + dataType: 'json', + success: function (result) { + ret = result; + } + }); + return ret; + }, + remoteUrl: null + }; + + function Plugin(option) { + return this.each(function () { + var $this = $(this); + var data = $this.data('lgb.SliderCaptcha'); + var options = typeof option === 'object' && option; + + if (data && !/reset/.test(option)) return; + if (!data) $this.data('lgb.SliderCaptcha', data = new SliderCaptcha(this, options)); + if (typeof option === 'string') data[option](); + }); + } + + $.fn.sliderCaptcha = Plugin; + $.fn.sliderCaptcha.Constructor = SliderCaptcha; + + var _proto = SliderCaptcha.prototype; + _proto.init = function () { + this.initDOM(); + this.initImg(); + this.bindEvents(); + }; + + _proto.initDOM = function () { + var createElement = function (tagName, className) { + var elment = document.createElement(tagName); + elment.className = className; + return elment; + }; + + var createCanvas = function (width, height) { + var canvas = document.createElement('canvas'); + canvas.width = width; + canvas.height = height; + return canvas; + }; + + var canvas = createCanvas(this.options.width - 2, this.options.height); // 画布 + var block = canvas.cloneNode(true); // 滑块 + var sliderContainer = createElement('div', 'sliderContainer'); + var refreshIcon = createElement('i', 'refreshIcon ' + this.options.repeatIcon); + var sliderMask = createElement('div', 'sliderMask'); + var sliderbg = createElement('div', 'sliderbg'); + var slider = createElement('div', 'slider'); + var sliderIcon = createElement('i', 'fa fa-arrow-right sliderIcon'); + var text = createElement('span', 'sliderText'); + + block.className = 'block'; + text.innerHTML = this.options.barText; + + var el = this.$element; + el.append($(canvas)); + el.append($(refreshIcon)); + el.append($(block)); + slider.appendChild(sliderIcon); + sliderMask.appendChild(slider); + sliderContainer.appendChild(sliderbg); + sliderContainer.appendChild(sliderMask); + sliderContainer.appendChild(text); + el.append($(sliderContainer)); + + var _canvas = { + canvas: canvas, + block: block, + sliderContainer: $(sliderContainer), + refreshIcon: refreshIcon, + slider: slider, + sliderMask: sliderMask, + sliderIcon: sliderIcon, + text: $(text), + canvasCtx: canvas.getContext('2d'), + blockCtx: block.getContext('2d') + }; + + if ($.isFunction(Object.assign)) { + Object.assign(this, _canvas); + } + else { + $.extend(this, _canvas); + } + }; + + _proto.initImg = function () { + var that = this; + var isIE = window.navigator.userAgent.indexOf('Trident') > -1; + var L = this.options.sliderL + this.options.sliderR * 2 + 3; // 滑块实际边长 + var drawImg = function (ctx, operation) { + var l = that.options.sliderL; + var r = that.options.sliderR; + var PI = that.options.PI; + var x = that.x; + var y = that.y; + ctx.beginPath(); + ctx.moveTo(x, y); + ctx.arc(x + l / 2, y - r + 2, r, 0.72 * PI, 2.26 * PI); + ctx.lineTo(x + l, y); + ctx.arc(x + l + r - 2, y + l / 2, r, 1.21 * PI, 2.78 * PI); + ctx.lineTo(x + l, y + l); + ctx.lineTo(x, y + l); + ctx.arc(x + r - 2, y + l / 2, r + 0.4, 2.76 * PI, 1.24 * PI, true); + ctx.lineTo(x, y); + ctx.lineWidth = 2; + ctx.fillStyle = 'rgba(255, 255, 255, 0.7)'; + ctx.strokeStyle = 'rgba(255, 255, 255, 0.7)'; + ctx.stroke(); + ctx[operation](); + ctx.globalCompositeOperation = isIE ? 'xor' : 'destination-over'; + }; + + var getRandomNumberByRange = function (start, end) { + return Math.round(Math.random() * (end - start) + start); + }; + var img = new Image(); + img.crossOrigin = "Anonymous"; + var loadCount = 0; + img.onload = function () { + // 随机创建滑块的位置 + that.x = getRandomNumberByRange(L + 10, that.options.width - (L + 10)); + that.y = getRandomNumberByRange(10 + that.options.sliderR * 2, that.options.height - (L + 10)); + drawImg(that.canvasCtx, 'fill'); + drawImg(that.blockCtx, 'clip'); + + that.canvasCtx.drawImage(img, 0, 0, that.options.width - 2, that.options.height); + that.blockCtx.drawImage(img, 0, 0, that.options.width - 2, that.options.height); + var y = that.y - that.options.sliderR * 2 - 1; + var ImageData = that.blockCtx.getImageData(that.x - 3, y, L, L); + that.block.width = L; + that.blockCtx.putImageData(ImageData, 0, y + 1); + that.text.text(that.text.attr('data-text')); + }; + img.onerror = function () { + loadCount++; + if (window.location.protocol === 'file:') { + loadCount = that.options.maxLoadCount; + console.error("can't load pic resource file from File protocal. Please try http or https"); + } + if (loadCount >= that.options.maxLoadCount) { + that.text.text('加载失败').addClass('text-danger'); + return; + } + img.src = that.options.localImages(); + }; + img.setSrc = function () { + var src = ''; + loadCount = 0; + that.text.removeClass('text-danger'); + if ($.isFunction(that.options.setSrc)) src = that.options.setSrc(); + if (!src || src === '') src = 'https://picsum.photos/' + that.options.width + '/' + that.options.height + '/?image=' + Math.round(Math.random() * 20); + if (isIE) { // IE浏览器无法通过img.crossOrigin跨域,使用ajax获取图片blob然后转为dataURL显示 + var xhr = new XMLHttpRequest(); + xhr.onloadend = function (e) { + var file = new FileReader(); // FileReader仅支持IE10+ + file.readAsDataURL(e.target.response); + file.onloadend = function (e) { + img.src = e.target.result; + }; + }; + xhr.open('GET', src); + xhr.responseType = 'blob'; + xhr.send(); + } else img.src = src; + }; + img.setSrc(); + this.text.attr('data-text', this.options.barText); + this.text.text(this.options.loadingText); + this.img = img; + }; + + _proto.clean = function () { + this.canvasCtx.clearRect(0, 0, this.options.width, this.options.height); + this.blockCtx.clearRect(0, 0, this.options.width, this.options.height); + this.block.width = this.options.width; + }; + + _proto.bindEvents = function () { + var that = this; + this.$element.on('selectstart', function () { + return false; + }); + + $(this.refreshIcon).on('click', function () { + that.text.text(that.options.barText); + that.reset(); + if ($.isFunction(that.options.onRefresh)) that.options.onRefresh.call(that.$element); + }); + + var originX, originY, trail = [], + isMouseDown = false; + + var handleDragStart = function (e) { + if (that.text.hasClass('text-danger')) return; + originX = e.clientX || e.touches[0].clientX; + originY = e.clientY || e.touches[0].clientY; + isMouseDown = true; + }; + + var handleDragMove = function (e) { + if (!isMouseDown) return false; + var eventX = e.clientX || e.touches[0].clientX; + var eventY = e.clientY || e.touches[0].clientY; + var moveX = eventX - originX; + var moveY = eventY - originY; + if (moveX < 0 || moveX + 40 > that.options.width) return false; + that.slider.style.left = (moveX - 1) + 'px'; + var blockLeft = (that.options.width - 40 - 20) / (that.options.width - 40) * moveX; + that.block.style.left = blockLeft + 'px'; + + that.sliderContainer.addClass('sliderContainer_active'); + that.sliderMask.style.width = (moveX + 4) + 'px'; + trail.push(Math.round(moveY)); + }; + + var handleDragEnd = function (e) { + if (!isMouseDown) return false; + isMouseDown = false; + var eventX = e.clientX || e.changedTouches[0].clientX; + if (eventX === originX) return false; + that.sliderContainer.removeClass('sliderContainer_active'); + that.trail = trail; + var data = that.verify(); + if (data.spliced && data.verified) { + that.sliderContainer.addClass('sliderContainer_success'); + if ($.isFunction(that.options.onSuccess)) that.options.onSuccess.call(that.$element); + } else { + that.sliderContainer.addClass('sliderContainer_fail'); + if ($.isFunction(that.options.onFail)) that.options.onFail.call(that.$element); + setTimeout(function () { + that.text.text(that.options.failedText); + that.reset(); + }, 1000); + } + }; + + this.slider.addEventListener('mousedown', handleDragStart); + this.slider.addEventListener('touchstart', handleDragStart); + document.addEventListener('mousemove', handleDragMove); + document.addEventListener('touchmove', handleDragMove); + document.addEventListener('mouseup', handleDragEnd); + document.addEventListener('touchend', handleDragEnd); + + document.addEventListener('mousedown', function () { return false; }); + document.addEventListener('touchstart', function () { return false; }); + document.addEventListener('swipe', function () { return false; }); + }; + + _proto.verify = function () { + var arr = this.trail; // 拖动时y轴的移动距离 + var left = parseInt(this.block.style.left); + var verified = false; + if (this.options.remoteUrl !== null) { + verified = this.options.verify(arr, this.options.remoteUrl); + } + else { + var sum = function (x, y) { return x + y; }; + var square = function (x) { return x * x; }; + var average = arr.reduce(sum) / arr.length; + var deviations = arr.map(function (x) { return x - average; }); + var stddev = Math.sqrt(deviations.map(square).reduce(sum) / arr.length); + verified = stddev !== 0; + } + return { + spliced: Math.abs(left - this.x) < this.options.offset, + verified: verified + }; + }; + + _proto.reset = function () { + this.sliderContainer.removeClass('sliderContainer_fail sliderContainer_success'); + this.slider.style.left = 0; + this.block.style.left = 0; + this.sliderMask.style.width = 0; + this.clean(); + this.text.attr('data-text', this.text.text()); + this.text.text(this.options.loadingText); + this.img.setSrc(); + }; +})(jQuery); \ No newline at end of file diff --git a/jun_captcha_slider/src/main/webapp/disk/slidercaptcha.css b/jun_captcha_slider/src/main/webapp/disk/slidercaptcha.css new file mode 100644 index 0000000000..cf3e91be6c --- /dev/null +++ b/jun_captcha_slider/src/main/webapp/disk/slidercaptcha.css @@ -0,0 +1,131 @@ +body { + overflow-x: hidden; +} + +.block { + position: absolute; + left: 0; + top: 0; +} + +.sliderContainer { + position: relative; + text-align: center; + line-height: 40px; + background: #f7f9fa; + color: #45494c; + border-radius: 2px; +} + +.sliderbg { + position: absolute; + left: 0; + right: 0; + top: 0; + background-color: #f7f9fa; + height: 40px; + border-radius: 2px; + border: 1px solid #e6e8eb; +} + +.sliderContainer_active .slider { + top: -1px; + border: 1px solid #1991FA; +} + +.sliderContainer_active .sliderMask { + border-width: 1px 0 1px 1px; +} + +.sliderContainer_success .slider { + top: -1px; + border: 1px solid #52CCBA; + background-color: #52CCBA !important; +} + +.sliderContainer_success .sliderMask { + border: 1px solid #52CCBA; + border-width: 1px 0 1px 1px; + background-color: #D2F4EF; +} + +.sliderContainer_success .sliderIcon:before { + content: "\f00c"; +} + +.sliderContainer_fail .slider { + top: -1px; + border: 1px solid #f57a7a; + background-color: #f57a7a !important; +} + +.sliderContainer_fail .sliderMask { + border: 1px solid #f57a7a; + background-color: #fce1e1; + border-width: 1px 0 1px 1px; +} + +.sliderContainer_fail .sliderIcon:before { + content: "\f00d"; +} +.sliderContainer_active .sliderText, .sliderContainer_success .sliderText, .sliderContainer_fail .sliderText { + display: none; +} + +.sliderMask { + position: absolute; + left: 0; + top: 0; + height: 40px; + border: 0 solid #1991FA; + background: #D1E9FE; + border-radius: 2px; +} + +.slider { + position: absolute; + top: 0; + left: 0; + width: 40px; + height: 40px; + background: #fff; + box-shadow: 0 0 3px rgba(0, 0, 0, 0.3); + cursor: pointer; + transition: background .2s linear; + border-radius: 2px; + display: flex; + align-items: center; + justify-content: center; +} + +.slider:hover { + background: #1991FA; +} + +.slider:hover .sliderIcon { + background-position: 0 -13px; +} + +.sliderText { + position: relative; +} + +.sliderIcon { + +} + +.refreshIcon { + position: absolute; + right: 0; + top: 0; + cursor: pointer; + margin: 6px; + color: rgba(0,0,0,.25); + font-size: 1rem; + z-index: 5; + transition: color .3s linear; +} + + .refreshIcon:hover { + color: #6c757d; + } diff --git a/jun_captcha_slider/src/main/webapp/images/Pic0.jpg b/jun_captcha_slider/src/main/webapp/images/Pic0.jpg new file mode 100644 index 0000000000..ccfbedd1a2 Binary files /dev/null and b/jun_captcha_slider/src/main/webapp/images/Pic0.jpg differ diff --git a/jun_captcha_slider/src/main/webapp/images/Pic1.jpg b/jun_captcha_slider/src/main/webapp/images/Pic1.jpg new file mode 100644 index 0000000000..689cc20c00 Binary files /dev/null and b/jun_captcha_slider/src/main/webapp/images/Pic1.jpg differ diff --git a/jun_captcha_slider/src/main/webapp/images/Pic2.jpg b/jun_captcha_slider/src/main/webapp/images/Pic2.jpg new file mode 100644 index 0000000000..6ec8425581 Binary files /dev/null and b/jun_captcha_slider/src/main/webapp/images/Pic2.jpg differ diff --git a/jun_captcha_slider/src/main/webapp/images/Pic3.jpg b/jun_captcha_slider/src/main/webapp/images/Pic3.jpg new file mode 100644 index 0000000000..d1d1553de1 Binary files /dev/null and b/jun_captcha_slider/src/main/webapp/images/Pic3.jpg differ diff --git a/jun_captcha_slider/src/main/webapp/images/Pic4.jpg b/jun_captcha_slider/src/main/webapp/images/Pic4.jpg new file mode 100644 index 0000000000..d718c2bb98 Binary files /dev/null and b/jun_captcha_slider/src/main/webapp/images/Pic4.jpg differ diff --git a/jun_captcha_slider/src/main/webapp/index.html b/jun_captcha_slider/src/main/webapp/index.html new file mode 100644 index 0000000000..15fbdc9ed8 --- /dev/null +++ b/jun_captcha_slider/src/main/webapp/index.html @@ -0,0 +1,79 @@ + + + + + + + + Slider Captcha Demo + + + + + + + +
+
+
+
+
+ 请完成安全验证! +
+
+
+
+
+
+
+
+ + + + + + + \ No newline at end of file diff --git a/jun_captcha_slider/src/main/webapp/lib/font-awesome/css/font-awesome.css b/jun_captcha_slider/src/main/webapp/lib/font-awesome/css/font-awesome.css new file mode 100644 index 0000000000..ee906a8196 --- /dev/null +++ b/jun_captcha_slider/src/main/webapp/lib/font-awesome/css/font-awesome.css @@ -0,0 +1,2337 @@ +/*! + * Font Awesome 4.7.0 by @davegandy - http://fontawesome.io - @fontawesome + * License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License) + */ +/* FONT PATH + * -------------------------- */ +@font-face { + font-family: 'FontAwesome'; + src: url('../fonts/fontawesome-webfont.eot?v=4.7.0'); + src: url('../fonts/fontawesome-webfont.eot?#iefix&v=4.7.0') format('embedded-opentype'), url('../fonts/fontawesome-webfont.woff2?v=4.7.0') format('woff2'), url('../fonts/fontawesome-webfont.woff?v=4.7.0') format('woff'), url('../fonts/fontawesome-webfont.ttf?v=4.7.0') format('truetype'), url('../fonts/fontawesome-webfont.svg?v=4.7.0#fontawesomeregular') format('svg'); + font-weight: normal; + font-style: normal; +} +.fa { + display: inline-block; + font: normal normal normal 14px/1 FontAwesome; + font-size: inherit; + text-rendering: auto; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} +/* makes the font 33% larger relative to the icon container */ +.fa-lg { + font-size: 1.33333333em; + line-height: 0.75em; + vertical-align: -15%; +} +.fa-2x { + font-size: 2em; +} +.fa-3x { + font-size: 3em; +} +.fa-4x { + font-size: 4em; +} +.fa-5x { + font-size: 5em; +} +.fa-fw { + width: 1.28571429em; + text-align: center; +} +.fa-ul { + padding-left: 0; + margin-left: 2.14285714em; + list-style-type: none; +} +.fa-ul > li { + position: relative; +} +.fa-li { + position: absolute; + left: -2.14285714em; + width: 2.14285714em; + top: 0.14285714em; + text-align: center; +} +.fa-li.fa-lg { + left: -1.85714286em; +} +.fa-border { + padding: .2em .25em .15em; + border: solid 0.08em #eeeeee; + border-radius: .1em; +} +.fa-pull-left { + float: left; +} +.fa-pull-right { + float: right; +} +.fa.fa-pull-left { + margin-right: .3em; +} +.fa.fa-pull-right { + margin-left: .3em; +} +/* Deprecated as of 4.4.0 */ +.pull-right { + float: right; +} +.pull-left { + float: left; +} +.fa.pull-left { + margin-right: .3em; +} +.fa.pull-right { + margin-left: .3em; +} +.fa-spin { + -webkit-animation: fa-spin 2s infinite linear; + animation: fa-spin 2s infinite linear; +} +.fa-pulse { + -webkit-animation: fa-spin 1s infinite steps(8); + animation: fa-spin 1s infinite steps(8); +} +@-webkit-keyframes fa-spin { + 0% { + -webkit-transform: rotate(0deg); + transform: rotate(0deg); + } + 100% { + -webkit-transform: rotate(359deg); + transform: rotate(359deg); + } +} +@keyframes fa-spin { + 0% { + -webkit-transform: rotate(0deg); + transform: rotate(0deg); + } + 100% { + -webkit-transform: rotate(359deg); + transform: rotate(359deg); + } +} +.fa-rotate-90 { + -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=1)"; + -webkit-transform: rotate(90deg); + -ms-transform: rotate(90deg); + transform: rotate(90deg); +} +.fa-rotate-180 { + -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=2)"; + -webkit-transform: rotate(180deg); + -ms-transform: rotate(180deg); + transform: rotate(180deg); +} +.fa-rotate-270 { + -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=3)"; + -webkit-transform: rotate(270deg); + -ms-transform: rotate(270deg); + transform: rotate(270deg); +} +.fa-flip-horizontal { + -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1)"; + -webkit-transform: scale(-1, 1); + -ms-transform: scale(-1, 1); + transform: scale(-1, 1); +} +.fa-flip-vertical { + -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1)"; + -webkit-transform: scale(1, -1); + -ms-transform: scale(1, -1); + transform: scale(1, -1); +} +:root .fa-rotate-90, +:root .fa-rotate-180, +:root .fa-rotate-270, +:root .fa-flip-horizontal, +:root .fa-flip-vertical { + filter: none; +} +.fa-stack { + position: relative; + display: inline-block; + width: 2em; + height: 2em; + line-height: 2em; + vertical-align: middle; +} +.fa-stack-1x, +.fa-stack-2x { + position: absolute; + left: 0; + width: 100%; + text-align: center; +} +.fa-stack-1x { + line-height: inherit; +} +.fa-stack-2x { + font-size: 2em; +} +.fa-inverse { + color: #ffffff; +} +/* Font Awesome uses the Unicode Private Use Area (PUA) to ensure screen + readers do not read off random characters that represent icons */ +.fa-glass:before { + content: "\f000"; +} +.fa-music:before { + content: "\f001"; +} +.fa-search:before { + content: "\f002"; +} +.fa-envelope-o:before { + content: "\f003"; +} +.fa-heart:before { + content: "\f004"; +} +.fa-star:before { + content: "\f005"; +} +.fa-star-o:before { + content: "\f006"; +} +.fa-user:before { + content: "\f007"; +} +.fa-film:before { + content: "\f008"; +} +.fa-th-large:before { + content: "\f009"; +} +.fa-th:before { + content: "\f00a"; +} +.fa-th-list:before { + content: "\f00b"; +} +.fa-check:before { + content: "\f00c"; +} +.fa-remove:before, +.fa-close:before, +.fa-times:before { + content: "\f00d"; +} +.fa-search-plus:before { + content: "\f00e"; +} +.fa-search-minus:before { + content: "\f010"; +} +.fa-power-off:before { + content: "\f011"; +} +.fa-signal:before { + content: "\f012"; +} +.fa-gear:before, +.fa-cog:before { + content: "\f013"; +} +.fa-trash-o:before { + content: "\f014"; +} +.fa-home:before { + content: "\f015"; +} +.fa-file-o:before { + content: "\f016"; +} +.fa-clock-o:before { + content: "\f017"; +} +.fa-road:before { + content: "\f018"; +} +.fa-download:before { + content: "\f019"; +} +.fa-arrow-circle-o-down:before { + content: "\f01a"; +} +.fa-arrow-circle-o-up:before { + content: "\f01b"; +} +.fa-inbox:before { + content: "\f01c"; +} +.fa-play-circle-o:before { + content: "\f01d"; +} +.fa-rotate-right:before, +.fa-repeat:before { + content: "\f01e"; +} +.fa-refresh:before { + content: "\f021"; +} +.fa-list-alt:before { + content: "\f022"; +} +.fa-lock:before { + content: "\f023"; +} +.fa-flag:before { + content: "\f024"; +} +.fa-headphones:before { + content: "\f025"; +} +.fa-volume-off:before { + content: "\f026"; +} +.fa-volume-down:before { + content: "\f027"; +} +.fa-volume-up:before { + content: "\f028"; +} +.fa-qrcode:before { + content: "\f029"; +} +.fa-barcode:before { + content: "\f02a"; +} +.fa-tag:before { + content: "\f02b"; +} +.fa-tags:before { + content: "\f02c"; +} +.fa-book:before { + content: "\f02d"; +} +.fa-bookmark:before { + content: "\f02e"; +} +.fa-print:before { + content: "\f02f"; +} +.fa-camera:before { + content: "\f030"; +} +.fa-font:before { + content: "\f031"; +} +.fa-bold:before { + content: "\f032"; +} +.fa-italic:before { + content: "\f033"; +} +.fa-text-height:before { + content: "\f034"; +} +.fa-text-width:before { + content: "\f035"; +} +.fa-align-left:before { + content: "\f036"; +} +.fa-align-center:before { + content: "\f037"; +} +.fa-align-right:before { + content: "\f038"; +} +.fa-align-justify:before { + content: "\f039"; +} +.fa-list:before { + content: "\f03a"; +} +.fa-dedent:before, +.fa-outdent:before { + content: "\f03b"; +} +.fa-indent:before { + content: "\f03c"; +} +.fa-video-camera:before { + content: "\f03d"; +} +.fa-photo:before, +.fa-image:before, +.fa-picture-o:before { + content: "\f03e"; +} +.fa-pencil:before { + content: "\f040"; +} +.fa-map-marker:before { + content: "\f041"; +} +.fa-adjust:before { + content: "\f042"; +} +.fa-tint:before { + content: "\f043"; +} +.fa-edit:before, +.fa-pencil-square-o:before { + content: "\f044"; +} +.fa-share-square-o:before { + content: "\f045"; +} +.fa-check-square-o:before { + content: "\f046"; +} +.fa-arrows:before { + content: "\f047"; +} +.fa-step-backward:before { + content: "\f048"; +} +.fa-fast-backward:before { + content: "\f049"; +} +.fa-backward:before { + content: "\f04a"; +} +.fa-play:before { + content: "\f04b"; +} +.fa-pause:before { + content: "\f04c"; +} +.fa-stop:before { + content: "\f04d"; +} +.fa-forward:before { + content: "\f04e"; +} +.fa-fast-forward:before { + content: "\f050"; +} +.fa-step-forward:before { + content: "\f051"; +} +.fa-eject:before { + content: "\f052"; +} +.fa-chevron-left:before { + content: "\f053"; +} +.fa-chevron-right:before { + content: "\f054"; +} +.fa-plus-circle:before { + content: "\f055"; +} +.fa-minus-circle:before { + content: "\f056"; +} +.fa-times-circle:before { + content: "\f057"; +} +.fa-check-circle:before { + content: "\f058"; +} +.fa-question-circle:before { + content: "\f059"; +} +.fa-info-circle:before { + content: "\f05a"; +} +.fa-crosshairs:before { + content: "\f05b"; +} +.fa-times-circle-o:before { + content: "\f05c"; +} +.fa-check-circle-o:before { + content: "\f05d"; +} +.fa-ban:before { + content: "\f05e"; +} +.fa-arrow-left:before { + content: "\f060"; +} +.fa-arrow-right:before { + content: "\f061"; +} +.fa-arrow-up:before { + content: "\f062"; +} +.fa-arrow-down:before { + content: "\f063"; +} +.fa-mail-forward:before, +.fa-share:before { + content: "\f064"; +} +.fa-expand:before { + content: "\f065"; +} +.fa-compress:before { + content: "\f066"; +} +.fa-plus:before { + content: "\f067"; +} +.fa-minus:before { + content: "\f068"; +} +.fa-asterisk:before { + content: "\f069"; +} +.fa-exclamation-circle:before { + content: "\f06a"; +} +.fa-gift:before { + content: "\f06b"; +} +.fa-leaf:before { + content: "\f06c"; +} +.fa-fire:before { + content: "\f06d"; +} +.fa-eye:before { + content: "\f06e"; +} +.fa-eye-slash:before { + content: "\f070"; +} +.fa-warning:before, +.fa-exclamation-triangle:before { + content: "\f071"; +} +.fa-plane:before { + content: "\f072"; +} +.fa-calendar:before { + content: "\f073"; +} +.fa-random:before { + content: "\f074"; +} +.fa-comment:before { + content: "\f075"; +} +.fa-magnet:before { + content: "\f076"; +} +.fa-chevron-up:before { + content: "\f077"; +} +.fa-chevron-down:before { + content: "\f078"; +} +.fa-retweet:before { + content: "\f079"; +} +.fa-shopping-cart:before { + content: "\f07a"; +} +.fa-folder:before { + content: "\f07b"; +} +.fa-folder-open:before { + content: "\f07c"; +} +.fa-arrows-v:before { + content: "\f07d"; +} +.fa-arrows-h:before { + content: "\f07e"; +} +.fa-bar-chart-o:before, +.fa-bar-chart:before { + content: "\f080"; +} +.fa-twitter-square:before { + content: "\f081"; +} +.fa-facebook-square:before { + content: "\f082"; +} +.fa-camera-retro:before { + content: "\f083"; +} +.fa-key:before { + content: "\f084"; +} +.fa-gears:before, +.fa-cogs:before { + content: "\f085"; +} +.fa-comments:before { + content: "\f086"; +} +.fa-thumbs-o-up:before { + content: "\f087"; +} +.fa-thumbs-o-down:before { + content: "\f088"; +} +.fa-star-half:before { + content: "\f089"; +} +.fa-heart-o:before { + content: "\f08a"; +} +.fa-sign-out:before { + content: "\f08b"; +} +.fa-linkedin-square:before { + content: "\f08c"; +} +.fa-thumb-tack:before { + content: "\f08d"; +} +.fa-external-link:before { + content: "\f08e"; +} +.fa-sign-in:before { + content: "\f090"; +} +.fa-trophy:before { + content: "\f091"; +} +.fa-github-square:before { + content: "\f092"; +} +.fa-upload:before { + content: "\f093"; +} +.fa-lemon-o:before { + content: "\f094"; +} +.fa-phone:before { + content: "\f095"; +} +.fa-square-o:before { + content: "\f096"; +} +.fa-bookmark-o:before { + content: "\f097"; +} +.fa-phone-square:before { + content: "\f098"; +} +.fa-twitter:before { + content: "\f099"; +} +.fa-facebook-f:before, +.fa-facebook:before { + content: "\f09a"; +} +.fa-github:before { + content: "\f09b"; +} +.fa-unlock:before { + content: "\f09c"; +} +.fa-credit-card:before { + content: "\f09d"; +} +.fa-feed:before, +.fa-rss:before { + content: "\f09e"; +} +.fa-hdd-o:before { + content: "\f0a0"; +} +.fa-bullhorn:before { + content: "\f0a1"; +} +.fa-bell:before { + content: "\f0f3"; +} +.fa-certificate:before { + content: "\f0a3"; +} +.fa-hand-o-right:before { + content: "\f0a4"; +} +.fa-hand-o-left:before { + content: "\f0a5"; +} +.fa-hand-o-up:before { + content: "\f0a6"; +} +.fa-hand-o-down:before { + content: "\f0a7"; +} +.fa-arrow-circle-left:before { + content: "\f0a8"; +} +.fa-arrow-circle-right:before { + content: "\f0a9"; +} +.fa-arrow-circle-up:before { + content: "\f0aa"; +} +.fa-arrow-circle-down:before { + content: "\f0ab"; +} +.fa-globe:before { + content: "\f0ac"; +} +.fa-wrench:before { + content: "\f0ad"; +} +.fa-tasks:before { + content: "\f0ae"; +} +.fa-filter:before { + content: "\f0b0"; +} +.fa-briefcase:before { + content: "\f0b1"; +} +.fa-arrows-alt:before { + content: "\f0b2"; +} +.fa-group:before, +.fa-users:before { + content: "\f0c0"; +} +.fa-chain:before, +.fa-link:before { + content: "\f0c1"; +} +.fa-cloud:before { + content: "\f0c2"; +} +.fa-flask:before { + content: "\f0c3"; +} +.fa-cut:before, +.fa-scissors:before { + content: "\f0c4"; +} +.fa-copy:before, +.fa-files-o:before { + content: "\f0c5"; +} +.fa-paperclip:before { + content: "\f0c6"; +} +.fa-save:before, +.fa-floppy-o:before { + content: "\f0c7"; +} +.fa-square:before { + content: "\f0c8"; +} +.fa-navicon:before, +.fa-reorder:before, +.fa-bars:before { + content: "\f0c9"; +} +.fa-list-ul:before { + content: "\f0ca"; +} +.fa-list-ol:before { + content: "\f0cb"; +} +.fa-strikethrough:before { + content: "\f0cc"; +} +.fa-underline:before { + content: "\f0cd"; +} +.fa-table:before { + content: "\f0ce"; +} +.fa-magic:before { + content: "\f0d0"; +} +.fa-truck:before { + content: "\f0d1"; +} +.fa-pinterest:before { + content: "\f0d2"; +} +.fa-pinterest-square:before { + content: "\f0d3"; +} +.fa-google-plus-square:before { + content: "\f0d4"; +} +.fa-google-plus:before { + content: "\f0d5"; +} +.fa-money:before { + content: "\f0d6"; +} +.fa-caret-down:before { + content: "\f0d7"; +} +.fa-caret-up:before { + content: "\f0d8"; +} +.fa-caret-left:before { + content: "\f0d9"; +} +.fa-caret-right:before { + content: "\f0da"; +} +.fa-columns:before { + content: "\f0db"; +} +.fa-unsorted:before, +.fa-sort:before { + content: "\f0dc"; +} +.fa-sort-down:before, +.fa-sort-desc:before { + content: "\f0dd"; +} +.fa-sort-up:before, +.fa-sort-asc:before { + content: "\f0de"; +} +.fa-envelope:before { + content: "\f0e0"; +} +.fa-linkedin:before { + content: "\f0e1"; +} +.fa-rotate-left:before, +.fa-undo:before { + content: "\f0e2"; +} +.fa-legal:before, +.fa-gavel:before { + content: "\f0e3"; +} +.fa-dashboard:before, +.fa-tachometer:before { + content: "\f0e4"; +} +.fa-comment-o:before { + content: "\f0e5"; +} +.fa-comments-o:before { + content: "\f0e6"; +} +.fa-flash:before, +.fa-bolt:before { + content: "\f0e7"; +} +.fa-sitemap:before { + content: "\f0e8"; +} +.fa-umbrella:before { + content: "\f0e9"; +} +.fa-paste:before, +.fa-clipboard:before { + content: "\f0ea"; +} +.fa-lightbulb-o:before { + content: "\f0eb"; +} +.fa-exchange:before { + content: "\f0ec"; +} +.fa-cloud-download:before { + content: "\f0ed"; +} +.fa-cloud-upload:before { + content: "\f0ee"; +} +.fa-user-md:before { + content: "\f0f0"; +} +.fa-stethoscope:before { + content: "\f0f1"; +} +.fa-suitcase:before { + content: "\f0f2"; +} +.fa-bell-o:before { + content: "\f0a2"; +} +.fa-coffee:before { + content: "\f0f4"; +} +.fa-cutlery:before { + content: "\f0f5"; +} +.fa-file-text-o:before { + content: "\f0f6"; +} +.fa-building-o:before { + content: "\f0f7"; +} +.fa-hospital-o:before { + content: "\f0f8"; +} +.fa-ambulance:before { + content: "\f0f9"; +} +.fa-medkit:before { + content: "\f0fa"; +} +.fa-fighter-jet:before { + content: "\f0fb"; +} +.fa-beer:before { + content: "\f0fc"; +} +.fa-h-square:before { + content: "\f0fd"; +} +.fa-plus-square:before { + content: "\f0fe"; +} +.fa-angle-double-left:before { + content: "\f100"; +} +.fa-angle-double-right:before { + content: "\f101"; +} +.fa-angle-double-up:before { + content: "\f102"; +} +.fa-angle-double-down:before { + content: "\f103"; +} +.fa-angle-left:before { + content: "\f104"; +} +.fa-angle-right:before { + content: "\f105"; +} +.fa-angle-up:before { + content: "\f106"; +} +.fa-angle-down:before { + content: "\f107"; +} +.fa-desktop:before { + content: "\f108"; +} +.fa-laptop:before { + content: "\f109"; +} +.fa-tablet:before { + content: "\f10a"; +} +.fa-mobile-phone:before, +.fa-mobile:before { + content: "\f10b"; +} +.fa-circle-o:before { + content: "\f10c"; +} +.fa-quote-left:before { + content: "\f10d"; +} +.fa-quote-right:before { + content: "\f10e"; +} +.fa-spinner:before { + content: "\f110"; +} +.fa-circle:before { + content: "\f111"; +} +.fa-mail-reply:before, +.fa-reply:before { + content: "\f112"; +} +.fa-github-alt:before { + content: "\f113"; +} +.fa-folder-o:before { + content: "\f114"; +} +.fa-folder-open-o:before { + content: "\f115"; +} +.fa-smile-o:before { + content: "\f118"; +} +.fa-frown-o:before { + content: "\f119"; +} +.fa-meh-o:before { + content: "\f11a"; +} +.fa-gamepad:before { + content: "\f11b"; +} +.fa-keyboard-o:before { + content: "\f11c"; +} +.fa-flag-o:before { + content: "\f11d"; +} +.fa-flag-checkered:before { + content: "\f11e"; +} +.fa-terminal:before { + content: "\f120"; +} +.fa-code:before { + content: "\f121"; +} +.fa-mail-reply-all:before, +.fa-reply-all:before { + content: "\f122"; +} +.fa-star-half-empty:before, +.fa-star-half-full:before, +.fa-star-half-o:before { + content: "\f123"; +} +.fa-location-arrow:before { + content: "\f124"; +} +.fa-crop:before { + content: "\f125"; +} +.fa-code-fork:before { + content: "\f126"; +} +.fa-unlink:before, +.fa-chain-broken:before { + content: "\f127"; +} +.fa-question:before { + content: "\f128"; +} +.fa-info:before { + content: "\f129"; +} +.fa-exclamation:before { + content: "\f12a"; +} +.fa-superscript:before { + content: "\f12b"; +} +.fa-subscript:before { + content: "\f12c"; +} +.fa-eraser:before { + content: "\f12d"; +} +.fa-puzzle-piece:before { + content: "\f12e"; +} +.fa-microphone:before { + content: "\f130"; +} +.fa-microphone-slash:before { + content: "\f131"; +} +.fa-shield:before { + content: "\f132"; +} +.fa-calendar-o:before { + content: "\f133"; +} +.fa-fire-extinguisher:before { + content: "\f134"; +} +.fa-rocket:before { + content: "\f135"; +} +.fa-maxcdn:before { + content: "\f136"; +} +.fa-chevron-circle-left:before { + content: "\f137"; +} +.fa-chevron-circle-right:before { + content: "\f138"; +} +.fa-chevron-circle-up:before { + content: "\f139"; +} +.fa-chevron-circle-down:before { + content: "\f13a"; +} +.fa-html5:before { + content: "\f13b"; +} +.fa-css3:before { + content: "\f13c"; +} +.fa-anchor:before { + content: "\f13d"; +} +.fa-unlock-alt:before { + content: "\f13e"; +} +.fa-bullseye:before { + content: "\f140"; +} +.fa-ellipsis-h:before { + content: "\f141"; +} +.fa-ellipsis-v:before { + content: "\f142"; +} +.fa-rss-square:before { + content: "\f143"; +} +.fa-play-circle:before { + content: "\f144"; +} +.fa-ticket:before { + content: "\f145"; +} +.fa-minus-square:before { + content: "\f146"; +} +.fa-minus-square-o:before { + content: "\f147"; +} +.fa-level-up:before { + content: "\f148"; +} +.fa-level-down:before { + content: "\f149"; +} +.fa-check-square:before { + content: "\f14a"; +} +.fa-pencil-square:before { + content: "\f14b"; +} +.fa-external-link-square:before { + content: "\f14c"; +} +.fa-share-square:before { + content: "\f14d"; +} +.fa-compass:before { + content: "\f14e"; +} +.fa-toggle-down:before, +.fa-caret-square-o-down:before { + content: "\f150"; +} +.fa-toggle-up:before, +.fa-caret-square-o-up:before { + content: "\f151"; +} +.fa-toggle-right:before, +.fa-caret-square-o-right:before { + content: "\f152"; +} +.fa-euro:before, +.fa-eur:before { + content: "\f153"; +} +.fa-gbp:before { + content: "\f154"; +} +.fa-dollar:before, +.fa-usd:before { + content: "\f155"; +} +.fa-rupee:before, +.fa-inr:before { + content: "\f156"; +} +.fa-cny:before, +.fa-rmb:before, +.fa-yen:before, +.fa-jpy:before { + content: "\f157"; +} +.fa-ruble:before, +.fa-rouble:before, +.fa-rub:before { + content: "\f158"; +} +.fa-won:before, +.fa-krw:before { + content: "\f159"; +} +.fa-bitcoin:before, +.fa-btc:before { + content: "\f15a"; +} +.fa-file:before { + content: "\f15b"; +} +.fa-file-text:before { + content: "\f15c"; +} +.fa-sort-alpha-asc:before { + content: "\f15d"; +} +.fa-sort-alpha-desc:before { + content: "\f15e"; +} +.fa-sort-amount-asc:before { + content: "\f160"; +} +.fa-sort-amount-desc:before { + content: "\f161"; +} +.fa-sort-numeric-asc:before { + content: "\f162"; +} +.fa-sort-numeric-desc:before { + content: "\f163"; +} +.fa-thumbs-up:before { + content: "\f164"; +} +.fa-thumbs-down:before { + content: "\f165"; +} +.fa-youtube-square:before { + content: "\f166"; +} +.fa-youtube:before { + content: "\f167"; +} +.fa-xing:before { + content: "\f168"; +} +.fa-xing-square:before { + content: "\f169"; +} +.fa-youtube-play:before { + content: "\f16a"; +} +.fa-dropbox:before { + content: "\f16b"; +} +.fa-stack-overflow:before { + content: "\f16c"; +} +.fa-instagram:before { + content: "\f16d"; +} +.fa-flickr:before { + content: "\f16e"; +} +.fa-adn:before { + content: "\f170"; +} +.fa-bitbucket:before { + content: "\f171"; +} +.fa-bitbucket-square:before { + content: "\f172"; +} +.fa-tumblr:before { + content: "\f173"; +} +.fa-tumblr-square:before { + content: "\f174"; +} +.fa-long-arrow-down:before { + content: "\f175"; +} +.fa-long-arrow-up:before { + content: "\f176"; +} +.fa-long-arrow-left:before { + content: "\f177"; +} +.fa-long-arrow-right:before { + content: "\f178"; +} +.fa-apple:before { + content: "\f179"; +} +.fa-windows:before { + content: "\f17a"; +} +.fa-android:before { + content: "\f17b"; +} +.fa-linux:before { + content: "\f17c"; +} +.fa-dribbble:before { + content: "\f17d"; +} +.fa-skype:before { + content: "\f17e"; +} +.fa-foursquare:before { + content: "\f180"; +} +.fa-trello:before { + content: "\f181"; +} +.fa-female:before { + content: "\f182"; +} +.fa-male:before { + content: "\f183"; +} +.fa-gittip:before, +.fa-gratipay:before { + content: "\f184"; +} +.fa-sun-o:before { + content: "\f185"; +} +.fa-moon-o:before { + content: "\f186"; +} +.fa-archive:before { + content: "\f187"; +} +.fa-bug:before { + content: "\f188"; +} +.fa-vk:before { + content: "\f189"; +} +.fa-weibo:before { + content: "\f18a"; +} +.fa-renren:before { + content: "\f18b"; +} +.fa-pagelines:before { + content: "\f18c"; +} +.fa-stack-exchange:before { + content: "\f18d"; +} +.fa-arrow-circle-o-right:before { + content: "\f18e"; +} +.fa-arrow-circle-o-left:before { + content: "\f190"; +} +.fa-toggle-left:before, +.fa-caret-square-o-left:before { + content: "\f191"; +} +.fa-dot-circle-o:before { + content: "\f192"; +} +.fa-wheelchair:before { + content: "\f193"; +} +.fa-vimeo-square:before { + content: "\f194"; +} +.fa-turkish-lira:before, +.fa-try:before { + content: "\f195"; +} +.fa-plus-square-o:before { + content: "\f196"; +} +.fa-space-shuttle:before { + content: "\f197"; +} +.fa-slack:before { + content: "\f198"; +} +.fa-envelope-square:before { + content: "\f199"; +} +.fa-wordpress:before { + content: "\f19a"; +} +.fa-openid:before { + content: "\f19b"; +} +.fa-institution:before, +.fa-bank:before, +.fa-university:before { + content: "\f19c"; +} +.fa-mortar-board:before, +.fa-graduation-cap:before { + content: "\f19d"; +} +.fa-yahoo:before { + content: "\f19e"; +} +.fa-google:before { + content: "\f1a0"; +} +.fa-reddit:before { + content: "\f1a1"; +} +.fa-reddit-square:before { + content: "\f1a2"; +} +.fa-stumbleupon-circle:before { + content: "\f1a3"; +} +.fa-stumbleupon:before { + content: "\f1a4"; +} +.fa-delicious:before { + content: "\f1a5"; +} +.fa-digg:before { + content: "\f1a6"; +} +.fa-pied-piper-pp:before { + content: "\f1a7"; +} +.fa-pied-piper-alt:before { + content: "\f1a8"; +} +.fa-drupal:before { + content: "\f1a9"; +} +.fa-joomla:before { + content: "\f1aa"; +} +.fa-language:before { + content: "\f1ab"; +} +.fa-fax:before { + content: "\f1ac"; +} +.fa-building:before { + content: "\f1ad"; +} +.fa-child:before { + content: "\f1ae"; +} +.fa-paw:before { + content: "\f1b0"; +} +.fa-spoon:before { + content: "\f1b1"; +} +.fa-cube:before { + content: "\f1b2"; +} +.fa-cubes:before { + content: "\f1b3"; +} +.fa-behance:before { + content: "\f1b4"; +} +.fa-behance-square:before { + content: "\f1b5"; +} +.fa-steam:before { + content: "\f1b6"; +} +.fa-steam-square:before { + content: "\f1b7"; +} +.fa-recycle:before { + content: "\f1b8"; +} +.fa-automobile:before, +.fa-car:before { + content: "\f1b9"; +} +.fa-cab:before, +.fa-taxi:before { + content: "\f1ba"; +} +.fa-tree:before { + content: "\f1bb"; +} +.fa-spotify:before { + content: "\f1bc"; +} +.fa-deviantart:before { + content: "\f1bd"; +} +.fa-soundcloud:before { + content: "\f1be"; +} +.fa-database:before { + content: "\f1c0"; +} +.fa-file-pdf-o:before { + content: "\f1c1"; +} +.fa-file-word-o:before { + content: "\f1c2"; +} +.fa-file-excel-o:before { + content: "\f1c3"; +} +.fa-file-powerpoint-o:before { + content: "\f1c4"; +} +.fa-file-photo-o:before, +.fa-file-picture-o:before, +.fa-file-image-o:before { + content: "\f1c5"; +} +.fa-file-zip-o:before, +.fa-file-archive-o:before { + content: "\f1c6"; +} +.fa-file-sound-o:before, +.fa-file-audio-o:before { + content: "\f1c7"; +} +.fa-file-movie-o:before, +.fa-file-video-o:before { + content: "\f1c8"; +} +.fa-file-code-o:before { + content: "\f1c9"; +} +.fa-vine:before { + content: "\f1ca"; +} +.fa-codepen:before { + content: "\f1cb"; +} +.fa-jsfiddle:before { + content: "\f1cc"; +} +.fa-life-bouy:before, +.fa-life-buoy:before, +.fa-life-saver:before, +.fa-support:before, +.fa-life-ring:before { + content: "\f1cd"; +} +.fa-circle-o-notch:before { + content: "\f1ce"; +} +.fa-ra:before, +.fa-resistance:before, +.fa-rebel:before { + content: "\f1d0"; +} +.fa-ge:before, +.fa-empire:before { + content: "\f1d1"; +} +.fa-git-square:before { + content: "\f1d2"; +} +.fa-git:before { + content: "\f1d3"; +} +.fa-y-combinator-square:before, +.fa-yc-square:before, +.fa-hacker-news:before { + content: "\f1d4"; +} +.fa-tencent-weibo:before { + content: "\f1d5"; +} +.fa-qq:before { + content: "\f1d6"; +} +.fa-wechat:before, +.fa-weixin:before { + content: "\f1d7"; +} +.fa-send:before, +.fa-paper-plane:before { + content: "\f1d8"; +} +.fa-send-o:before, +.fa-paper-plane-o:before { + content: "\f1d9"; +} +.fa-history:before { + content: "\f1da"; +} +.fa-circle-thin:before { + content: "\f1db"; +} +.fa-header:before { + content: "\f1dc"; +} +.fa-paragraph:before { + content: "\f1dd"; +} +.fa-sliders:before { + content: "\f1de"; +} +.fa-share-alt:before { + content: "\f1e0"; +} +.fa-share-alt-square:before { + content: "\f1e1"; +} +.fa-bomb:before { + content: "\f1e2"; +} +.fa-soccer-ball-o:before, +.fa-futbol-o:before { + content: "\f1e3"; +} +.fa-tty:before { + content: "\f1e4"; +} +.fa-binoculars:before { + content: "\f1e5"; +} +.fa-plug:before { + content: "\f1e6"; +} +.fa-slideshare:before { + content: "\f1e7"; +} +.fa-twitch:before { + content: "\f1e8"; +} +.fa-yelp:before { + content: "\f1e9"; +} +.fa-newspaper-o:before { + content: "\f1ea"; +} +.fa-wifi:before { + content: "\f1eb"; +} +.fa-calculator:before { + content: "\f1ec"; +} +.fa-paypal:before { + content: "\f1ed"; +} +.fa-google-wallet:before { + content: "\f1ee"; +} +.fa-cc-visa:before { + content: "\f1f0"; +} +.fa-cc-mastercard:before { + content: "\f1f1"; +} +.fa-cc-discover:before { + content: "\f1f2"; +} +.fa-cc-amex:before { + content: "\f1f3"; +} +.fa-cc-paypal:before { + content: "\f1f4"; +} +.fa-cc-stripe:before { + content: "\f1f5"; +} +.fa-bell-slash:before { + content: "\f1f6"; +} +.fa-bell-slash-o:before { + content: "\f1f7"; +} +.fa-trash:before { + content: "\f1f8"; +} +.fa-copyright:before { + content: "\f1f9"; +} +.fa-at:before { + content: "\f1fa"; +} +.fa-eyedropper:before { + content: "\f1fb"; +} +.fa-paint-brush:before { + content: "\f1fc"; +} +.fa-birthday-cake:before { + content: "\f1fd"; +} +.fa-area-chart:before { + content: "\f1fe"; +} +.fa-pie-chart:before { + content: "\f200"; +} +.fa-line-chart:before { + content: "\f201"; +} +.fa-lastfm:before { + content: "\f202"; +} +.fa-lastfm-square:before { + content: "\f203"; +} +.fa-toggle-off:before { + content: "\f204"; +} +.fa-toggle-on:before { + content: "\f205"; +} +.fa-bicycle:before { + content: "\f206"; +} +.fa-bus:before { + content: "\f207"; +} +.fa-ioxhost:before { + content: "\f208"; +} +.fa-angellist:before { + content: "\f209"; +} +.fa-cc:before { + content: "\f20a"; +} +.fa-shekel:before, +.fa-sheqel:before, +.fa-ils:before { + content: "\f20b"; +} +.fa-meanpath:before { + content: "\f20c"; +} +.fa-buysellads:before { + content: "\f20d"; +} +.fa-connectdevelop:before { + content: "\f20e"; +} +.fa-dashcube:before { + content: "\f210"; +} +.fa-forumbee:before { + content: "\f211"; +} +.fa-leanpub:before { + content: "\f212"; +} +.fa-sellsy:before { + content: "\f213"; +} +.fa-shirtsinbulk:before { + content: "\f214"; +} +.fa-simplybuilt:before { + content: "\f215"; +} +.fa-skyatlas:before { + content: "\f216"; +} +.fa-cart-plus:before { + content: "\f217"; +} +.fa-cart-arrow-down:before { + content: "\f218"; +} +.fa-diamond:before { + content: "\f219"; +} +.fa-ship:before { + content: "\f21a"; +} +.fa-user-secret:before { + content: "\f21b"; +} +.fa-motorcycle:before { + content: "\f21c"; +} +.fa-street-view:before { + content: "\f21d"; +} +.fa-heartbeat:before { + content: "\f21e"; +} +.fa-venus:before { + content: "\f221"; +} +.fa-mars:before { + content: "\f222"; +} +.fa-mercury:before { + content: "\f223"; +} +.fa-intersex:before, +.fa-transgender:before { + content: "\f224"; +} +.fa-transgender-alt:before { + content: "\f225"; +} +.fa-venus-double:before { + content: "\f226"; +} +.fa-mars-double:before { + content: "\f227"; +} +.fa-venus-mars:before { + content: "\f228"; +} +.fa-mars-stroke:before { + content: "\f229"; +} +.fa-mars-stroke-v:before { + content: "\f22a"; +} +.fa-mars-stroke-h:before { + content: "\f22b"; +} +.fa-neuter:before { + content: "\f22c"; +} +.fa-genderless:before { + content: "\f22d"; +} +.fa-facebook-official:before { + content: "\f230"; +} +.fa-pinterest-p:before { + content: "\f231"; +} +.fa-whatsapp:before { + content: "\f232"; +} +.fa-server:before { + content: "\f233"; +} +.fa-user-plus:before { + content: "\f234"; +} +.fa-user-times:before { + content: "\f235"; +} +.fa-hotel:before, +.fa-bed:before { + content: "\f236"; +} +.fa-viacoin:before { + content: "\f237"; +} +.fa-train:before { + content: "\f238"; +} +.fa-subway:before { + content: "\f239"; +} +.fa-medium:before { + content: "\f23a"; +} +.fa-yc:before, +.fa-y-combinator:before { + content: "\f23b"; +} +.fa-optin-monster:before { + content: "\f23c"; +} +.fa-opencart:before { + content: "\f23d"; +} +.fa-expeditedssl:before { + content: "\f23e"; +} +.fa-battery-4:before, +.fa-battery:before, +.fa-battery-full:before { + content: "\f240"; +} +.fa-battery-3:before, +.fa-battery-three-quarters:before { + content: "\f241"; +} +.fa-battery-2:before, +.fa-battery-half:before { + content: "\f242"; +} +.fa-battery-1:before, +.fa-battery-quarter:before { + content: "\f243"; +} +.fa-battery-0:before, +.fa-battery-empty:before { + content: "\f244"; +} +.fa-mouse-pointer:before { + content: "\f245"; +} +.fa-i-cursor:before { + content: "\f246"; +} +.fa-object-group:before { + content: "\f247"; +} +.fa-object-ungroup:before { + content: "\f248"; +} +.fa-sticky-note:before { + content: "\f249"; +} +.fa-sticky-note-o:before { + content: "\f24a"; +} +.fa-cc-jcb:before { + content: "\f24b"; +} +.fa-cc-diners-club:before { + content: "\f24c"; +} +.fa-clone:before { + content: "\f24d"; +} +.fa-balance-scale:before { + content: "\f24e"; +} +.fa-hourglass-o:before { + content: "\f250"; +} +.fa-hourglass-1:before, +.fa-hourglass-start:before { + content: "\f251"; +} +.fa-hourglass-2:before, +.fa-hourglass-half:before { + content: "\f252"; +} +.fa-hourglass-3:before, +.fa-hourglass-end:before { + content: "\f253"; +} +.fa-hourglass:before { + content: "\f254"; +} +.fa-hand-grab-o:before, +.fa-hand-rock-o:before { + content: "\f255"; +} +.fa-hand-stop-o:before, +.fa-hand-paper-o:before { + content: "\f256"; +} +.fa-hand-scissors-o:before { + content: "\f257"; +} +.fa-hand-lizard-o:before { + content: "\f258"; +} +.fa-hand-spock-o:before { + content: "\f259"; +} +.fa-hand-pointer-o:before { + content: "\f25a"; +} +.fa-hand-peace-o:before { + content: "\f25b"; +} +.fa-trademark:before { + content: "\f25c"; +} +.fa-registered:before { + content: "\f25d"; +} +.fa-creative-commons:before { + content: "\f25e"; +} +.fa-gg:before { + content: "\f260"; +} +.fa-gg-circle:before { + content: "\f261"; +} +.fa-tripadvisor:before { + content: "\f262"; +} +.fa-odnoklassniki:before { + content: "\f263"; +} +.fa-odnoklassniki-square:before { + content: "\f264"; +} +.fa-get-pocket:before { + content: "\f265"; +} +.fa-wikipedia-w:before { + content: "\f266"; +} +.fa-safari:before { + content: "\f267"; +} +.fa-chrome:before { + content: "\f268"; +} +.fa-firefox:before { + content: "\f269"; +} +.fa-opera:before { + content: "\f26a"; +} +.fa-internet-explorer:before { + content: "\f26b"; +} +.fa-tv:before, +.fa-television:before { + content: "\f26c"; +} +.fa-contao:before { + content: "\f26d"; +} +.fa-500px:before { + content: "\f26e"; +} +.fa-amazon:before { + content: "\f270"; +} +.fa-calendar-plus-o:before { + content: "\f271"; +} +.fa-calendar-minus-o:before { + content: "\f272"; +} +.fa-calendar-times-o:before { + content: "\f273"; +} +.fa-calendar-check-o:before { + content: "\f274"; +} +.fa-industry:before { + content: "\f275"; +} +.fa-map-pin:before { + content: "\f276"; +} +.fa-map-signs:before { + content: "\f277"; +} +.fa-map-o:before { + content: "\f278"; +} +.fa-map:before { + content: "\f279"; +} +.fa-commenting:before { + content: "\f27a"; +} +.fa-commenting-o:before { + content: "\f27b"; +} +.fa-houzz:before { + content: "\f27c"; +} +.fa-vimeo:before { + content: "\f27d"; +} +.fa-black-tie:before { + content: "\f27e"; +} +.fa-fonticons:before { + content: "\f280"; +} +.fa-reddit-alien:before { + content: "\f281"; +} +.fa-edge:before { + content: "\f282"; +} +.fa-credit-card-alt:before { + content: "\f283"; +} +.fa-codiepie:before { + content: "\f284"; +} +.fa-modx:before { + content: "\f285"; +} +.fa-fort-awesome:before { + content: "\f286"; +} +.fa-usb:before { + content: "\f287"; +} +.fa-product-hunt:before { + content: "\f288"; +} +.fa-mixcloud:before { + content: "\f289"; +} +.fa-scribd:before { + content: "\f28a"; +} +.fa-pause-circle:before { + content: "\f28b"; +} +.fa-pause-circle-o:before { + content: "\f28c"; +} +.fa-stop-circle:before { + content: "\f28d"; +} +.fa-stop-circle-o:before { + content: "\f28e"; +} +.fa-shopping-bag:before { + content: "\f290"; +} +.fa-shopping-basket:before { + content: "\f291"; +} +.fa-hashtag:before { + content: "\f292"; +} +.fa-bluetooth:before { + content: "\f293"; +} +.fa-bluetooth-b:before { + content: "\f294"; +} +.fa-percent:before { + content: "\f295"; +} +.fa-gitlab:before { + content: "\f296"; +} +.fa-wpbeginner:before { + content: "\f297"; +} +.fa-wpforms:before { + content: "\f298"; +} +.fa-envira:before { + content: "\f299"; +} +.fa-universal-access:before { + content: "\f29a"; +} +.fa-wheelchair-alt:before { + content: "\f29b"; +} +.fa-question-circle-o:before { + content: "\f29c"; +} +.fa-blind:before { + content: "\f29d"; +} +.fa-audio-description:before { + content: "\f29e"; +} +.fa-volume-control-phone:before { + content: "\f2a0"; +} +.fa-braille:before { + content: "\f2a1"; +} +.fa-assistive-listening-systems:before { + content: "\f2a2"; +} +.fa-asl-interpreting:before, +.fa-american-sign-language-interpreting:before { + content: "\f2a3"; +} +.fa-deafness:before, +.fa-hard-of-hearing:before, +.fa-deaf:before { + content: "\f2a4"; +} +.fa-glide:before { + content: "\f2a5"; +} +.fa-glide-g:before { + content: "\f2a6"; +} +.fa-signing:before, +.fa-sign-language:before { + content: "\f2a7"; +} +.fa-low-vision:before { + content: "\f2a8"; +} +.fa-viadeo:before { + content: "\f2a9"; +} +.fa-viadeo-square:before { + content: "\f2aa"; +} +.fa-snapchat:before { + content: "\f2ab"; +} +.fa-snapchat-ghost:before { + content: "\f2ac"; +} +.fa-snapchat-square:before { + content: "\f2ad"; +} +.fa-pied-piper:before { + content: "\f2ae"; +} +.fa-first-order:before { + content: "\f2b0"; +} +.fa-yoast:before { + content: "\f2b1"; +} +.fa-themeisle:before { + content: "\f2b2"; +} +.fa-google-plus-circle:before, +.fa-google-plus-official:before { + content: "\f2b3"; +} +.fa-fa:before, +.fa-font-awesome:before { + content: "\f2b4"; +} +.fa-handshake-o:before { + content: "\f2b5"; +} +.fa-envelope-open:before { + content: "\f2b6"; +} +.fa-envelope-open-o:before { + content: "\f2b7"; +} +.fa-linode:before { + content: "\f2b8"; +} +.fa-address-book:before { + content: "\f2b9"; +} +.fa-address-book-o:before { + content: "\f2ba"; +} +.fa-vcard:before, +.fa-address-card:before { + content: "\f2bb"; +} +.fa-vcard-o:before, +.fa-address-card-o:before { + content: "\f2bc"; +} +.fa-user-circle:before { + content: "\f2bd"; +} +.fa-user-circle-o:before { + content: "\f2be"; +} +.fa-user-o:before { + content: "\f2c0"; +} +.fa-id-badge:before { + content: "\f2c1"; +} +.fa-drivers-license:before, +.fa-id-card:before { + content: "\f2c2"; +} +.fa-drivers-license-o:before, +.fa-id-card-o:before { + content: "\f2c3"; +} +.fa-quora:before { + content: "\f2c4"; +} +.fa-free-code-camp:before { + content: "\f2c5"; +} +.fa-telegram:before { + content: "\f2c6"; +} +.fa-thermometer-4:before, +.fa-thermometer:before, +.fa-thermometer-full:before { + content: "\f2c7"; +} +.fa-thermometer-3:before, +.fa-thermometer-three-quarters:before { + content: "\f2c8"; +} +.fa-thermometer-2:before, +.fa-thermometer-half:before { + content: "\f2c9"; +} +.fa-thermometer-1:before, +.fa-thermometer-quarter:before { + content: "\f2ca"; +} +.fa-thermometer-0:before, +.fa-thermometer-empty:before { + content: "\f2cb"; +} +.fa-shower:before { + content: "\f2cc"; +} +.fa-bathtub:before, +.fa-s15:before, +.fa-bath:before { + content: "\f2cd"; +} +.fa-podcast:before { + content: "\f2ce"; +} +.fa-window-maximize:before { + content: "\f2d0"; +} +.fa-window-minimize:before { + content: "\f2d1"; +} +.fa-window-restore:before { + content: "\f2d2"; +} +.fa-times-rectangle:before, +.fa-window-close:before { + content: "\f2d3"; +} +.fa-times-rectangle-o:before, +.fa-window-close-o:before { + content: "\f2d4"; +} +.fa-bandcamp:before { + content: "\f2d5"; +} +.fa-grav:before { + content: "\f2d6"; +} +.fa-etsy:before { + content: "\f2d7"; +} +.fa-imdb:before { + content: "\f2d8"; +} +.fa-ravelry:before { + content: "\f2d9"; +} +.fa-eercast:before { + content: "\f2da"; +} +.fa-microchip:before { + content: "\f2db"; +} +.fa-snowflake-o:before { + content: "\f2dc"; +} +.fa-superpowers:before { + content: "\f2dd"; +} +.fa-wpexplorer:before { + content: "\f2de"; +} +.fa-meetup:before { + content: "\f2e0"; +} +.sr-only { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + border: 0; +} +.sr-only-focusable:active, +.sr-only-focusable:focus { + position: static; + width: auto; + height: auto; + margin: 0; + overflow: visible; + clip: auto; +} diff --git a/jun_captcha_slider/src/main/webapp/lib/font-awesome/css/font-awesome.css.map b/jun_captcha_slider/src/main/webapp/lib/font-awesome/css/font-awesome.css.map new file mode 100644 index 0000000000..60763a8640 --- /dev/null +++ b/jun_captcha_slider/src/main/webapp/lib/font-awesome/css/font-awesome.css.map @@ -0,0 +1,7 @@ +{ +"version": 3, +"mappings": ";;;;;;;AAGA,UAUC;EATC,WAAW,EAAE,aAAa;EAC1B,GAAG,EAAE,+CAAgE;EACrE,GAAG,EAAE,ySAAmG;EAKxG,WAAW,EAAE,MAAM;EACnB,UAAU,EAAE,MAAM;ACTpB,GAAmB;EACjB,OAAO,EAAE,YAAY;EACrB,IAAI,EAAE,uCAAwD;EAC9D,SAAS,EAAE,OAAO;EAClB,cAAc,EAAE,IAAI;EACpB,sBAAsB,EAAE,WAAW;EACnC,uBAAuB,EAAE,SAAS;EAClC,SAAS,EAAE,eAAe;;;ACN5B,MAAsB;EACpB,SAAS,EAAE,SAAS;EACpB,WAAW,EAAE,MAAS;EACtB,cAAc,EAAE,IAAI;;AAEtB,MAAsB;EAAE,SAAS,EAAE,GAAG;;AACtC,MAAsB;EAAE,SAAS,EAAE,GAAG;;AACtC,MAAsB;EAAE,SAAS,EAAE,GAAG;;AACtC,MAAsB;EAAE,SAAS,EAAE,GAAG;;ACVtC,MAAsB;EACpB,KAAK,EAAE,SAAW;EAClB,UAAU,EAAE,MAAM;;ACDpB,MAAsB;EACpB,YAAY,EAAE,CAAC;EACf,WAAW,ECKU,SAAS;EDJ9B,eAAe,EAAE,IAAI;EACrB,WAAK;IAAE,QAAQ,EAAE,QAAQ;;AAE3B,MAAsB;EACpB,QAAQ,EAAE,QAAQ;EAClB,IAAI,EAAE,UAAa;EACnB,KAAK,ECFgB,SAAS;EDG9B,GAAG,EAAE,SAAU;EACf,UAAU,EAAE,MAAM;EAClB,YAAuB;IACrB,IAAI,EAAE,UAA0B;;AEbpC,UAA0B;EACxB,OAAO,EAAE,gBAAgB;EACzB,MAAM,EAAE,iBAA4B;EACpC,aAAa,EAAE,IAAI;;AAGrB,WAAY;EAAE,KAAK,EAAE,KAAK;;AAC1B,UAAW;EAAE,KAAK,EAAE,IAAI;;AAGtB,aAAY;EAAE,YAAY,EAAE,IAAI;AAChC,cAAa;EAAE,WAAW,EAAE,IAAI;;ACXlC,QAAwB;EACtB,iBAAiB,EAAE,0BAA0B;EACrC,SAAS,EAAE,0BAA0B;;AAG/C,SAAyB;EACvB,iBAAiB,EAAE,4BAA4B;EACvC,SAAS,EAAE,4BAA4B;;AAGjD,0BASC;EARC,EAAG;IACD,iBAAiB,EAAE,YAAY;IACvB,SAAS,EAAE,YAAY;EAEjC,IAAK;IACH,iBAAiB,EAAE,cAAc;IACzB,SAAS,EAAE,cAAc;AAIrC,kBASC;EARC,EAAG;IACD,iBAAiB,EAAE,YAAY;IACvB,SAAS,EAAE,YAAY;EAEjC,IAAK;IACH,iBAAiB,EAAE,cAAc;IACzB,SAAS,EAAE,cAAc;AC5BrC,aAA8B;ECY5B,MAAM,EAAE,wDAAmE;EAC3E,iBAAiB,EAAE,aAAgB;EAC/B,aAAa,EAAE,aAAgB;EAC3B,SAAS,EAAE,aAAgB;;ADdrC,cAA8B;ECW5B,MAAM,EAAE,wDAAmE;EAC3E,iBAAiB,EAAE,cAAgB;EAC/B,aAAa,EAAE,cAAgB;EAC3B,SAAS,EAAE,cAAgB;;ADbrC,cAA8B;ECU5B,MAAM,EAAE,wDAAmE;EAC3E,iBAAiB,EAAE,cAAgB;EAC/B,aAAa,EAAE,cAAgB;EAC3B,SAAS,EAAE,cAAgB;;ADXrC,mBAAmC;ECejC,MAAM,EAAE,wDAAmE;EAC3E,iBAAiB,EAAE,YAAoB;EACnC,aAAa,EAAE,YAAoB;EAC/B,SAAS,EAAE,YAAoB;;ADjBzC,iBAAmC;ECcjC,MAAM,EAAE,wDAAmE;EAC3E,iBAAiB,EAAE,YAAoB;EACnC,aAAa,EAAE,YAAoB;EAC/B,SAAS,EAAE,YAAoB;;ADZzC;;;;uBAIuC;EACrC,MAAM,EAAE,IAAI;;AEfd,SAAyB;EACvB,QAAQ,EAAE,QAAQ;EAClB,OAAO,EAAE,YAAY;EACrB,KAAK,EAAE,GAAG;EACV,MAAM,EAAE,GAAG;EACX,WAAW,EAAE,GAAG;EAChB,cAAc,EAAE,MAAM;;AAExB,0BAAyD;EACvD,QAAQ,EAAE,QAAQ;EAClB,IAAI,EAAE,CAAC;EACP,KAAK,EAAE,IAAI;EACX,UAAU,EAAE,MAAM;;AAEpB,YAA4B;EAAE,WAAW,EAAE,OAAO;;AAClD,YAA4B;EAAE,SAAS,EAAE,GAAG;;AAC5C,WAA2B;EAAE,KAAK,ELVZ,IAAI;;;;AMN1B,gBAAgC;EAAE,OAAO,ENoQ1B,GAAO;;AMnQtB,gBAAgC;EAAE,OAAO,EN0W1B,GAAO;;AMzWtB,iBAAiC;EAAE,OAAO,ENmb1B,GAAO;;AMlbvB,qBAAqC;EAAE,OAAO,ENmL1B,GAAO;;AMlL3B,gBAAgC;EAAE,OAAO,ENkR1B,GAAO;;AMjRtB,eAA+B;EAAE,OAAO,ENke1B,GAAO;;AMjerB,iBAAiC;EAAE,OAAO,ENse1B,GAAO;;AMrevB,eAA+B;EAAE,OAAO,EN+iB1B,GAAO;;AM9iBrB,eAA+B;EAAE,OAAO,ENyN1B,GAAO;;AMxNrB,mBAAmC;EAAE,OAAO,ENggB1B,GAAO;;AM/fzB,aAA6B;EAAE,OAAO,EN8f1B,GAAO;;AM7fnB,kBAAkC;EAAE,OAAO,EN+f1B,GAAO;;AM9fxB,gBAAgC;EAAE,OAAO,ENoG1B,GAAO;;AMnGtB;;gBAEgC;EAAE,OAAO,ENkgB1B,GAAO;;AMjgBtB,sBAAsC;EAAE,OAAO,ENua1B,GAAO;;AMta5B,uBAAuC;EAAE,OAAO,ENqa1B,GAAO;;AMpa7B,oBAAoC;EAAE,OAAO,EN+X1B,GAAO;;AM9X1B,iBAAiC;EAAE,OAAO,ENsb1B,GAAO;;AMrbvB;cAC8B;EAAE,OAAO,ENwH1B,GAAO;;AMvHpB,kBAAkC;EAAE,OAAO,ENygB1B,GAAO;;AMxgBxB,eAA+B;EAAE,OAAO,ENmQ1B,GAAO;;AMlQrB,iBAAiC;EAAE,OAAO,EN6L1B,GAAO;;AM5LvB,kBAAkC;EAAE,OAAO,EN0G1B,GAAO;;AMzGxB,eAA+B;EAAE,OAAO,EN+Y1B,GAAO;;AM9YrB,mBAAmC;EAAE,OAAO,ENiJ1B,GAAO;;AMhJzB,8BAA8C;EAAE,OAAO,ENI1B,GAAO;;AMHpC,4BAA4C;EAAE,OAAO,ENM1B,GAAO;;AMLlC,gBAAgC;EAAE,OAAO,ENkQ1B,GAAO;;AMjQtB,wBAAwC;EAAE,OAAO,EN4W1B,GAAO;;AM3W9B;iBACiC;EAAE,OAAO,ENmY1B,GAAO;;AMlYvB,kBAAkC;EAAE,OAAO,EN8X1B,GAAO;;AM7XxB,mBAAmC;EAAE,OAAO,ENiS1B,GAAO;;AMhSzB,eAA+B;EAAE,OAAO,ENoS1B,GAAO;;AMnSrB,eAA+B;EAAE,OAAO,ENgM1B,GAAO;;AM/LrB,qBAAqC;EAAE,OAAO,EN+O1B,GAAO;;AM9O3B,qBAAqC;EAAE,OAAO,EN8hB1B,GAAO;;AM7hB3B,sBAAsC;EAAE,OAAO,EN4hB1B,GAAO;;AM3hB5B,oBAAoC;EAAE,OAAO,EN6hB1B,GAAO;;AM5hB1B,iBAAiC;EAAE,OAAO,EN2W1B,GAAO;;AM1WvB,kBAAkC;EAAE,OAAO,ENW1B,GAAO;;AMVxB,cAA8B;EAAE,OAAO,ENod1B,GAAO;;AMndpB,eAA+B;EAAE,OAAO,ENod1B,GAAO;;AMndrB,eAA+B;EAAE,OAAO,EN2B1B,GAAO;;AM1BrB,mBAAmC;EAAE,OAAO,EN2B1B,GAAO;;AM1BzB,gBAAgC;EAAE,OAAO,ENkW1B,GAAO;;AMjWtB,iBAAiC;EAAE,OAAO,ENwC1B,GAAO;;AMvCvB,eAA+B;EAAE,OAAO,EN8L1B,GAAO;;AM7LrB,eAA+B;EAAE,OAAO,ENmB1B,GAAO;;AMlBrB,iBAAiC;EAAE,OAAO,ENoP1B,GAAO;;AMnPvB,sBAAsC;EAAE,OAAO,ENid1B,GAAO;;AMhd5B,qBAAqC;EAAE,OAAO,ENid1B,GAAO;;AMhd3B,qBAAqC;EAAE,OAAO,EN1C1B,GAAO;;AM2C3B,uBAAuC;EAAE,OAAO,EN7C1B,GAAO;;AM8C7B,sBAAsC;EAAE,OAAO,EN3C1B,GAAO;;AM4C5B,wBAAwC;EAAE,OAAO,EN9C1B,GAAO;;AM+C9B,eAA+B;EAAE,OAAO,ENwQ1B,GAAO;;AMvQrB;kBACkC;EAAE,OAAO,ENmT1B,GAAO;;AMlTxB,iBAAiC;EAAE,OAAO,ENmO1B,GAAO;;AMlOvB,uBAAuC;EAAE,OAAO,ENigB1B,GAAO;;AMhgB7B;;oBAEoC;EAAE,OAAO,EN+T1B,GAAO;;AM9T1B,iBAAiC;EAAE,OAAO,ENwT1B,GAAO;;AMvTvB,qBAAqC;EAAE,OAAO,EN+Q1B,GAAO;;AM9Q3B,iBAAiC;EAAE,OAAO,EN5D1B,GAAO;;AM6DvB,eAA+B;EAAE,OAAO,EN8c1B,GAAO;;AM7crB;0BAC0C;EAAE,OAAO,ENqT1B,GAAO;;AMpThC,yBAAyC;EAAE,OAAO,ENuX1B,GAAO;;AMtX/B,yBAAyC;EAAE,OAAO,EN0C1B,GAAO;;AMzC/B,iBAAiC;EAAE,OAAO,ENjC1B,GAAO;;AMkCvB,wBAAwC;EAAE,OAAO,ENma1B,GAAO;;AMla9B,wBAAwC;EAAE,OAAO,EN4H1B,GAAO;;AM3H9B,mBAAmC;EAAE,OAAO,EN7B1B,GAAO;;AM8BzB,eAA+B;EAAE,OAAO,EN0T1B,GAAO;;AMzTrB,gBAAgC;EAAE,OAAO,ENwS1B,GAAO;;AMvStB,eAA+B;EAAE,OAAO,ENia1B,GAAO;;AMharB,kBAAkC;EAAE,OAAO,ENgK1B,GAAO;;AM/JxB,uBAAuC;EAAE,OAAO,ENuH1B,GAAO;;AMtH7B,uBAAuC;EAAE,OAAO,EN4Z1B,GAAO;;AM3Z7B,gBAAgC;EAAE,OAAO,EN4F1B,GAAO;;AM3FtB,uBAAuC;EAAE,OAAO,ENoC1B,GAAO;;AMnC7B,wBAAwC;EAAE,OAAO,ENoC1B,GAAO;;AMnC9B,sBAAsC;EAAE,OAAO,ENsT1B,GAAO;;AMrT5B,uBAAuC;EAAE,OAAO,ENyQ1B,GAAO;;AMxQ7B,uBAAuC;EAAE,OAAO,ENwb1B,GAAO;;AMvb7B,uBAAuC;EAAE,OAAO,ENsB1B,GAAO;;AMrB7B,0BAA0C;EAAE,OAAO,EN2T1B,GAAO;;AM1ThC,sBAAsC;EAAE,OAAO,ENsM1B,GAAO;;AMrM5B,qBAAqC;EAAE,OAAO,EN6D1B,GAAO;;AM5D3B,yBAAyC;EAAE,OAAO,ENob1B,GAAO;;AMnb/B,yBAAyC;EAAE,OAAO,ENkB1B,GAAO;;AMjB/B,cAA8B;EAAE,OAAO,EN/C1B,GAAO;;AMgDpB,qBAAqC;EAAE,OAAO,EN3D1B,GAAO;;AM4D3B,sBAAsC;EAAE,OAAO,EN3D1B,GAAO;;AM4D5B,mBAAmC;EAAE,OAAO,EN3D1B,GAAO;;AM4DzB,qBAAqC;EAAE,OAAO,EN/D1B,GAAO;;AMgE3B;gBACgC;EAAE,OAAO,ENqV1B,GAAO;;AMpVtB,iBAAiC;EAAE,OAAO,ENuF1B,GAAO;;AMtFvB,mBAAmC;EAAE,OAAO,EN4C1B,GAAO;;AM3CzB,eAA+B;EAAE,OAAO,ENmS1B,GAAO;;AMlSrB,gBAAgC;EAAE,OAAO,ENsP1B,GAAO;;AMrPtB,mBAAmC;EAAE,OAAO,EN9D1B,GAAO;;AM+DzB,6BAA6C;EAAE,OAAO,ENgF1B,GAAO;;AM/EnC,eAA+B;EAAE,OAAO,EN+I1B,GAAO;;AM9IrB,eAA+B;EAAE,OAAO,ENoM1B,GAAO;;AMnMrB,eAA+B;EAAE,OAAO,ENmH1B,GAAO;;AMlHrB,cAA8B;EAAE,OAAO,ENiF1B,GAAO;;AMhFpB,oBAAoC;EAAE,OAAO,ENiF1B,GAAO;;AMhF1B;+BAC+C;EAAE,OAAO,EN0E1B,GAAO;;AMzErC,gBAAgC;EAAE,OAAO,ENmR1B,GAAO;;AMlRtB,mBAAmC;EAAE,OAAO,EN/B1B,GAAO;;AMgCzB,iBAAiC;EAAE,OAAO,ENoS1B,GAAO;;AMnSvB,kBAAkC;EAAE,OAAO,ENwB1B,GAAO;;AMvBxB,iBAAiC;EAAE,OAAO,ENqN1B,GAAO;;AMpNvB,qBAAqC;EAAE,OAAO,ENE1B,GAAO;;AMD3B,uBAAuC;EAAE,OAAO,ENF1B,GAAO;;AMG7B,kBAAkC;EAAE,OAAO,EN2S1B,GAAO;;AM1SxB,wBAAwC;EAAE,OAAO,ENyU1B,GAAO;;AMxU9B,iBAAiC;EAAE,OAAO,EN8G1B,GAAO;;AM7GvB,sBAAsC;EAAE,OAAO,EN+G1B,GAAO;;AM9G5B,mBAAmC;EAAE,OAAO,ENnF1B,GAAO;;AMoFzB,mBAAmC;EAAE,OAAO,ENrF1B,GAAO;;AMsFzB;oBACoC;EAAE,OAAO,EN/E1B,GAAO;;AMgF1B,yBAAyC;EAAE,OAAO,ENua1B,GAAO;;AMta/B,0BAA0C;EAAE,OAAO,ENmE1B,GAAO;;AMlEhC,uBAAuC;EAAE,OAAO,EN5C1B,GAAO;;AM6C7B,cAA8B;EAAE,OAAO,ENqK1B,GAAO;;AMpKpB;eAC+B;EAAE,OAAO,ENK1B,GAAO;;AMJrB,mBAAmC;EAAE,OAAO,ENQ1B,GAAO;;AMPzB,sBAAsC;EAAE,OAAO,ENmY1B,GAAO;;AMlY5B,wBAAwC;EAAE,OAAO,ENiY1B,GAAO;;AMhY9B,oBAAoC;EAAE,OAAO,EN2V1B,GAAO;;AM1V1B,kBAAkC;EAAE,OAAO,ENyI1B,GAAO;;AMxIxB,mBAAmC;EAAE,OAAO,ENyT1B,GAAO;;AMxTzB,0BAA0C;EAAE,OAAO,ENiL1B,GAAO;;AMhLhC,qBAAqC;EAAE,OAAO,EN0X1B,GAAO;;AMzX3B,wBAAwC;EAAE,OAAO,EN8C1B,GAAO;;AM7C9B,kBAAkC;EAAE,OAAO,ENoT1B,GAAO;;AMnTxB,iBAAiC;EAAE,OAAO,EN8Y1B,GAAO;;AM7YvB,wBAAwC;EAAE,OAAO,EN6G1B,GAAO;;AM5G9B,iBAAiC;EAAE,OAAO,EN8Z1B,GAAO;;AM7ZvB,kBAAkC;EAAE,OAAO,EN+J1B,GAAO;;AM9JxB,gBAAgC;EAAE,OAAO,ENsO1B,GAAO;;AMrOtB,mBAAmC;EAAE,OAAO,EN2U1B,GAAO;;AM1UzB,qBAAqC;EAAE,OAAO,EN/E1B,GAAO;;AMgF3B,uBAAuC;EAAE,OAAO,ENoO1B,GAAO;;AMnO7B,kBAAkC;EAAE,OAAO,EN8Y1B,GAAO;;AM7YxB;mBACmC;EAAE,OAAO,ENuC1B,GAAO;;AMtCzB,iBAAiC;EAAE,OAAO,ENiG1B,GAAO;;AMhGvB,iBAAiC;EAAE,OAAO,ENiZ1B,GAAO;;AMhZvB,sBAAsC;EAAE,OAAO,ENR1B,GAAO;;AMS5B,cAA8B;EAAE,OAAO,EN4Q1B,GAAO;;AM3QpB,gBAAgC;EAAE,OAAO,ENgH1B,GAAO;;AM/GtB,mBAAmC;EAAE,OAAO,ENnF1B,GAAO;;AMoFzB,eAA+B;EAAE,OAAO,ENzG1B,GAAO;;AM0GrB,sBAAsC;EAAE,OAAO,ENzD1B,GAAO;;AM0D5B,uBAAuC;EAAE,OAAO,EN0G1B,GAAO;;AMzG7B,sBAAsC;EAAE,OAAO,ENwG1B,GAAO;;AMvG5B,oBAAoC;EAAE,OAAO,ENyG1B,GAAO;;AMxG1B,sBAAsC;EAAE,OAAO,ENqG1B,GAAO;;AMpG5B,4BAA4C;EAAE,OAAO,EN5I1B,GAAO;;AM6IlC,6BAA6C;EAAE,OAAO,ENxI1B,GAAO;;AMyInC,0BAA0C;EAAE,OAAO,ENxI1B,GAAO;;AMyIhC,4BAA4C;EAAE,OAAO,ENhJ1B,GAAO;;AMiJlC,gBAAgC;EAAE,OAAO,ENsF1B,GAAO;;AMrFtB,iBAAiC;EAAE,OAAO,ENia1B,GAAO;;AMhavB,gBAAgC;EAAE,OAAO,ENiV1B,GAAO;;AMhVtB,iBAAiC;EAAE,OAAO,ENgD1B,GAAO;;AM/CvB,oBAAoC;EAAE,OAAO,ENvG1B,GAAO;;AMwG1B,qBAAqC;EAAE,OAAO,ENzI1B,GAAO;;AM0I3B;gBACgC;EAAE,OAAO,ENqY1B,GAAO;;AMpYtB;eAC+B;EAAE,OAAO,ENuI1B,GAAO;;AMtIrB,gBAAgC;EAAE,OAAO,ENpD1B,GAAO;;AMqDtB,gBAAgC;EAAE,OAAO,EN+C1B,GAAO;;AM9CtB;mBACmC;EAAE,OAAO,ENwP1B,GAAO;;AMvPzB;kBACkC;EAAE,OAAO,ENkC1B,GAAO;;AMjCxB,oBAAoC;EAAE,OAAO,ENsL1B,GAAO;;AMrL1B;mBACmC;EAAE,OAAO,EN0C1B,GAAO;;AMzCzB,iBAAiC;EAAE,OAAO,ENiS1B,GAAO;;AMhSvB;;eAE+B;EAAE,OAAO,EN9I1B,GAAO;;AM+IrB,kBAAkC;EAAE,OAAO,ENgI1B,GAAO;;AM/HxB,kBAAkC;EAAE,OAAO,EN8H1B,GAAO;;AM7HxB,wBAAwC;EAAE,OAAO,EN4S1B,GAAO;;AM3S9B,oBAAoC;EAAE,OAAO,ENoW1B,GAAO;;AMnW1B,gBAAgC;EAAE,OAAO,ENmT1B,GAAO;;AMlTtB,gBAAgC;EAAE,OAAO,ENkI1B,GAAO;;AMjItB,gBAAgC;EAAE,OAAO,ENuV1B,GAAO;;AMtVtB,oBAAoC;EAAE,OAAO,ENwL1B,GAAO;;AMvL1B,2BAA2C;EAAE,OAAO,ENyL1B,GAAO;;AMxLjC,6BAA6C;EAAE,OAAO,ENyD1B,GAAO;;AMxDnC,sBAAsC;EAAE,OAAO,ENuD1B,GAAO;;AMtD5B,gBAAgC;EAAE,OAAO,ENsJ1B,GAAO;;AMrJtB,qBAAqC;EAAE,OAAO,ENtH1B,GAAO;;AMuH3B,mBAAmC;EAAE,OAAO,ENhH1B,GAAO;;AMiHzB,qBAAqC;EAAE,OAAO,ENvH1B,GAAO;;AMwH3B,sBAAsC;EAAE,OAAO,ENvH1B,GAAO;;AMwH5B,kBAAkC;EAAE,OAAO,ENvE1B,GAAO;;AMwExB;eAC+B;EAAE,OAAO,EN2P1B,GAAO;;AM1PrB;oBACoC;EAAE,OAAO,EN+P1B,GAAO;;AM9P1B;mBACmC;EAAE,OAAO,EN4P1B,GAAO;;AM3PzB,mBAAmC;EAAE,OAAO,ENxC1B,GAAO;;AMyCzB,mBAAmC;EAAE,OAAO,ENkG1B,GAAO;;AMjGzB;eAC+B;EAAE,OAAO,EN8U1B,GAAO;;AM7UrB;gBACgC;EAAE,OAAO,ENqB1B,GAAO;;AMpBtB;qBACqC;EAAE,OAAO,EN2R1B,GAAO;;AM1R3B,oBAAoC;EAAE,OAAO,ENpF1B,GAAO;;AMqF1B,qBAAqC;EAAE,OAAO,ENnF1B,GAAO;;AMoF3B;eAC+B;EAAE,OAAO,ENjK1B,GAAO;;AMkKrB,kBAAkC;EAAE,OAAO,ENkO1B,GAAO;;AMjOxB,mBAAmC;EAAE,OAAO,ENkU1B,GAAO;;AMjUzB;oBACoC;EAAE,OAAO,EN1G1B,GAAO;;AM2G1B,sBAAsC;EAAE,OAAO,ENgF1B,GAAO;;AM/E5B,mBAAmC;EAAE,OAAO,ENnD1B,GAAO;;AMoDzB,yBAAyC;EAAE,OAAO,ENzG1B,GAAO;;AM0G/B,uBAAuC;EAAE,OAAO,ENzG1B,GAAO;;AM0G7B,kBAAkC;EAAE,OAAO,ENsU1B,GAAO;;AMrUxB,sBAAsC;EAAE,OAAO,EN+P1B,GAAO;;AM9P5B,mBAAmC;EAAE,OAAO,ENsQ1B,GAAO;;AMrQzB,iBAAiC;EAAE,OAAO,ENvL1B,GAAO;;AMwLvB,iBAAiC;EAAE,OAAO,ENzG1B,GAAO;;AM0GvB,kBAAkC;EAAE,OAAO,ENtF1B,GAAO;;AMuFxB,sBAAsC;EAAE,OAAO,EN3B1B,GAAO;;AM4B5B,qBAAqC;EAAE,OAAO,ENxK1B,GAAO;;AMyK3B,qBAAqC;EAAE,OAAO,ENkC1B,GAAO;;AMjC3B,oBAAoC;EAAE,OAAO,EN3O1B,GAAO;;AM4O1B,iBAAiC;EAAE,OAAO,ENiG1B,GAAO;;AMhGvB,sBAAsC;EAAE,OAAO,EN/C1B,GAAO;;AMgD5B,eAA+B;EAAE,OAAO,ENpM1B,GAAO;;AMqMrB,mBAAmC;EAAE,OAAO,ENe1B,GAAO;;AMdzB,sBAAsC;EAAE,OAAO,ENgJ1B,GAAO;;AM/I5B,4BAA4C;EAAE,OAAO,EN5O1B,GAAO;;AM6OlC,6BAA6C;EAAE,OAAO,EN5O1B,GAAO;;AM6OnC,0BAA0C;EAAE,OAAO,EN5O1B,GAAO;;AM6OhC,4BAA4C;EAAE,OAAO,ENhP1B,GAAO;;AMiPlC,qBAAqC;EAAE,OAAO,EN5O1B,GAAO;;AM6O3B,sBAAsC;EAAE,OAAO,EN5O1B,GAAO;;AM6O5B,mBAAmC;EAAE,OAAO,EN5O1B,GAAO;;AM6OzB,qBAAqC;EAAE,OAAO,ENhP1B,GAAO;;AMiP3B,kBAAkC;EAAE,OAAO,ENlG1B,GAAO;;AMmGxB,iBAAiC;EAAE,OAAO,ENuC1B,GAAO;;AMtCvB,iBAAiC;EAAE,OAAO,ENoP1B,GAAO;;AMnPvB;iBACiC;EAAE,OAAO,ENyF1B,GAAO;;AMxFvB,mBAAmC;EAAE,OAAO,EN9I1B,GAAO;;AM+IzB,qBAAqC;EAAE,OAAO,EN0I1B,GAAO;;AMzI3B,sBAAsC;EAAE,OAAO,EN0I1B,GAAO;;AMzI5B,kBAAkC;EAAE,OAAO,ENgN1B,GAAO;;AM/MxB,iBAAiC;EAAE,OAAO,ENnJ1B,GAAO;;AMoJvB;gBACgC;EAAE,OAAO,ENkJ1B,GAAO;;AMjJtB,qBAAqC;EAAE,OAAO,ENnB1B,GAAO;;AMoB3B,mBAAmC;EAAE,OAAO,ENxC1B,GAAO;;AMyCzB,wBAAwC;EAAE,OAAO,ENvC1B,GAAO;;AMwC9B,kBAAkC;EAAE,OAAO,EN0L1B,GAAO;;AMzLxB,kBAAkC;EAAE,OAAO,ENpC1B,GAAO;;AMqCxB,gBAAgC;EAAE,OAAO,ENoE1B,GAAO;;AMnEtB,kBAAkC;EAAE,OAAO,ENpC1B,GAAO;;AMqCxB,qBAAqC;EAAE,OAAO,ENkB1B,GAAO;;AMjB3B,iBAAiC;EAAE,OAAO,ENrD1B,GAAO;;AMsDvB,yBAAyC;EAAE,OAAO,ENvD1B,GAAO;;AMwD/B,mBAAmC;EAAE,OAAO,ENuO1B,GAAO;;AMtOzB,eAA+B;EAAE,OAAO,ENtJ1B,GAAO;;AMuJrB;oBACoC;EAAE,OAAO,ENqI1B,GAAO;;AMpI1B;;sBAEsC;EAAE,OAAO,ENuM1B,GAAO;;AMtM5B,yBAAyC;EAAE,OAAO,ENkC1B,GAAO;;AMjC/B,eAA+B;EAAE,OAAO,EN5I1B,GAAO;;AM6IrB,oBAAoC;EAAE,OAAO,EN7J1B,GAAO;;AM8J1B;uBACuC;EAAE,OAAO,EN1L1B,GAAO;;AM2L7B,mBAAmC;EAAE,OAAO,EN4G1B,GAAO;;AM3GzB,eAA+B;EAAE,OAAO,ENT1B,GAAO;;AMUrB,sBAAsC;EAAE,OAAO,ENhH1B,GAAO;;AMiH5B,sBAAsC;EAAE,OAAO,EN8M1B,GAAO;;AM7M5B,oBAAoC;EAAE,OAAO,ENyM1B,GAAO;;AMxM1B,iBAAiC;EAAE,OAAO,ENvH1B,GAAO;;AMwHvB,uBAAuC;EAAE,OAAO,ENmG1B,GAAO;;AMlG7B,qBAAqC;EAAE,OAAO,EN8C1B,GAAO;;AM7C3B,2BAA2C;EAAE,OAAO,EN8C1B,GAAO;;AM7CjC,iBAAiC;EAAE,OAAO,ENgJ1B,GAAO;;AM/IvB,qBAAqC;EAAE,OAAO,EN5N1B,GAAO;;AM6N3B,4BAA4C;EAAE,OAAO,ENjF1B,GAAO;;AMkFlC,iBAAiC;EAAE,OAAO,ENoH1B,GAAO;;AMnHvB,iBAAiC;EAAE,OAAO,ENkC1B,GAAO;;AMjCvB,8BAA8C;EAAE,OAAO,ENlM1B,GAAO;;AMmMpC,+BAA+C;EAAE,OAAO,ENlM1B,GAAO;;AMmMrC,4BAA4C;EAAE,OAAO,ENlM1B,GAAO;;AMmMlC,8BAA8C;EAAE,OAAO,ENtM1B,GAAO;;AMuMpC,gBAAgC;EAAE,OAAO,EN/B1B,GAAO;;AMgCtB,eAA+B;EAAE,OAAO,ENjK1B,GAAO;;AMkKrB,iBAAiC;EAAE,OAAO,EN9S1B,GAAO;;AM+SvB,qBAAqC;EAAE,OAAO,ENmP1B,GAAO;;AMlP3B,mBAAmC;EAAE,OAAO,EN9O1B,GAAO;;AM+OzB,qBAAqC;EAAE,OAAO,EN/I1B,GAAO;;AMgJ3B,qBAAqC;EAAE,OAAO,EN/I1B,GAAO;;AMgJ3B,qBAAqC;EAAE,OAAO,EN4G1B,GAAO;;AM3G3B,sBAAsC;EAAE,OAAO,ENsE1B,GAAO;;AMrE5B,iBAAiC;EAAE,OAAO,EN2M1B,GAAO;;AM1MvB,uBAAuC;EAAE,OAAO,EN6B1B,GAAO;;AM5B7B,yBAAyC;EAAE,OAAO,EN6B1B,GAAO;;AM5B/B,mBAAmC;EAAE,OAAO,ENhB1B,GAAO;;AMiBzB,qBAAqC;EAAE,OAAO,ENlB1B,GAAO;;AMmB3B,uBAAuC;EAAE,OAAO,ENvN1B,GAAO;;AMwN7B,wBAAwC;EAAE,OAAO,ENiD1B,GAAO;;AMhD9B,+BAA+C;EAAE,OAAO,EN3I1B,GAAO;;AM4IrC,uBAAuC;EAAE,OAAO,ENkH1B,GAAO;;AMjH7B,kBAAkC;EAAE,OAAO,EN1L1B,GAAO;;AM2LxB;8BAC8C;EAAE,OAAO,ENjP1B,GAAO;;AMkPpC;4BAC4C;EAAE,OAAO,ENhP1B,GAAO;;AMiPlC;+BAC+C;EAAE,OAAO,ENnP1B,GAAO;;AMoPrC;cAC8B;EAAE,OAAO,EN7J1B,GAAO;;AM8JpB,cAA8B;EAAE,OAAO,EN/F1B,GAAO;;AMgGpB;cAC8B;EAAE,OAAO,EN4N1B,GAAO;;AM3NpB;cAC8B;EAAE,OAAO,ENvD1B,GAAO;;AMwDpB;;;cAG8B;EAAE,OAAO,ENrD1B,GAAO;;AMsDpB;;cAE8B;EAAE,OAAO,EN8E1B,GAAO;;AM7EpB;cAC8B;EAAE,OAAO,ENtD1B,GAAO;;AMuDpB;cAC8B;EAAE,OAAO,ENzR1B,GAAO;;AM0RpB,eAA+B;EAAE,OAAO,ENzJ1B,GAAO;;AM0JrB,oBAAoC;EAAE,OAAO,EN7I1B,GAAO;;AM8I1B,yBAAyC;EAAE,OAAO,EN2G1B,GAAO;;AM1G/B,0BAA0C;EAAE,OAAO,EN2G1B,GAAO;;AM1GhC,0BAA0C;EAAE,OAAO,EN2G1B,GAAO;;AM1GhC,2BAA2C;EAAE,OAAO,EN2G1B,GAAO;;AM1GjC,2BAA2C;EAAE,OAAO,EN8G1B,GAAO;;AM7GjC,4BAA4C;EAAE,OAAO,EN8G1B,GAAO;;AM7GlC,oBAAoC;EAAE,OAAO,ENgK1B,GAAO;;AM/J1B,sBAAsC;EAAE,OAAO,EN4J1B,GAAO;;AM3J5B,yBAAyC;EAAE,OAAO,ENwO1B,GAAO;;AMvO/B,kBAAkC;EAAE,OAAO,ENqO1B,GAAO;;AMpOxB,eAA+B;EAAE,OAAO,EN+N1B,GAAO;;AM9NrB,sBAAsC;EAAE,OAAO,EN+N1B,GAAO;;AM9N5B,uBAAuC;EAAE,OAAO,ENmO1B,GAAO;;AMlO7B,kBAAkC;EAAE,OAAO,ENxM1B,GAAO;;AMyMxB,yBAAyC;EAAE,OAAO,EN+G1B,GAAO;;AM9G/B,oBAAoC;EAAE,OAAO,ENnF1B,GAAO;;AMoF1B,iBAAiC;EAAE,OAAO,EN/I1B,GAAO;;AMgJvB,cAA8B;EAAE,OAAO,ENhX1B,GAAO;;AMiXpB,oBAAoC;EAAE,OAAO,ENxT1B,GAAO;;AMyT1B,2BAA2C;EAAE,OAAO,ENxT1B,GAAO;;AMyTjC,iBAAiC;EAAE,OAAO,ENyK1B,GAAO;;AMxKvB,wBAAwC;EAAE,OAAO,ENyK1B,GAAO;;AMxK9B,0BAA0C;EAAE,OAAO,ENtD1B,GAAO;;AMuDhC,wBAAwC;EAAE,OAAO,ENpD1B,GAAO;;AMqD9B,0BAA0C;EAAE,OAAO,ENvD1B,GAAO;;AMwDhC,2BAA2C;EAAE,OAAO,ENvD1B,GAAO;;AMwDjC,gBAAgC;EAAE,OAAO,ENxW1B,GAAO;;AMyWtB,kBAAkC;EAAE,OAAO,EN0M1B,GAAO;;AMzMxB,kBAAkC;EAAE,OAAO,ENpX1B,GAAO;;AMqXxB,gBAAgC;EAAE,OAAO,ENpE1B,GAAO;;AMqEtB,mBAAmC;EAAE,OAAO,EN1N1B,GAAO;;AM2NzB,gBAAgC;EAAE,OAAO,ENqE1B,GAAO;;AMpEtB,qBAAqC;EAAE,OAAO,ENtJ1B,GAAO;;AMuJ3B,iBAAiC;EAAE,OAAO,ENuJ1B,GAAO;;AMtJvB,iBAAiC;EAAE,OAAO,EN/L1B,GAAO;;AMgMvB,eAA+B;EAAE,OAAO,EN1D1B,GAAO;;AM2DrB;mBACmC;EAAE,OAAO,ENnI1B,GAAO;;AMoIzB,gBAAgC;EAAE,OAAO,EN2G1B,GAAO;;AM1GtB,iBAAiC;EAAE,OAAO,ENxC1B,GAAO;;AMyCvB,kBAAkC;EAAE,OAAO,ENrX1B,GAAO;;AMsXxB,cAA8B;EAAE,OAAO,ENpU1B,GAAO;;AMqUpB,aAA6B;EAAE,OAAO,ENgL1B,GAAO;;AM/KnB,gBAAgC;EAAE,OAAO,ENqL1B,GAAO;;AMpLtB,iBAAiC;EAAE,OAAO,ENa1B,GAAO;;AMZvB,oBAAoC;EAAE,OAAO,ENrC1B,GAAO;;AMsC1B,yBAAyC;EAAE,OAAO,EN8E1B,GAAO;;AM7E/B,+BAA+C;EAAE,OAAO,ENtX1B,GAAO;;AMuXrC,8BAA8C;EAAE,OAAO,ENxX1B,GAAO;;AMyXpC;8BAC8C;EAAE,OAAO,EN3T1B,GAAO;;AM4TpC,uBAAuC;EAAE,OAAO,ENjP1B,GAAO;;AMkP7B,qBAAqC;EAAE,OAAO,EN+K1B,GAAO;;AM9K3B,uBAAuC;EAAE,OAAO,ENmK1B,GAAO;;AMlK7B;cAC8B;EAAE,OAAO,ENoI1B,GAAO;;AMnIpB,wBAAwC;EAAE,OAAO,ENjB1B,GAAO;;AMkB9B,wBAAwC;EAAE,OAAO,EN6D1B,GAAO;;AM5D9B,gBAAgC;EAAE,OAAO,EN2C1B,GAAO;;AM1CtB,0BAA0C;EAAE,OAAO,EN7O1B,GAAO;;AM8OhC,oBAAoC;EAAE,OAAO,EN2K1B,GAAO;;AM1K1B,iBAAiC;EAAE,OAAO,ENvD1B,GAAO;;AMwDvB;;qBAEqC;EAAE,OAAO,ENsI1B,GAAO;;AMrI3B;yBACyC;EAAE,OAAO,ENjK1B,GAAO;;AMkK/B,gBAAgC;EAAE,OAAO,ENwK1B,GAAO;;AMvKtB,iBAAiC;EAAE,OAAO,ENvK1B,GAAO;;AMwKvB,iBAAiC;EAAE,OAAO,ENhB1B,GAAO;;AMiBvB,wBAAwC;EAAE,OAAO,ENhB1B,GAAO;;AMiB9B,6BAA6C;EAAE,OAAO,ENsE1B,GAAO;;AMrEnC,sBAAsC;EAAE,OAAO,ENoE1B,GAAO;;AMnE5B,oBAAoC;EAAE,OAAO,EN7Q1B,GAAO;;AM8Q1B,eAA+B;EAAE,OAAO,EN1Q1B,GAAO;;AM2QrB,qBAAqC;EAAE,OAAO,ENjD1B,GAAO;;AMkD3B,yBAAyC;EAAE,OAAO,ENjD1B,GAAO;;AMkD/B,iBAAiC;EAAE,OAAO,ENvQ1B,GAAO;;AMwQvB,iBAAiC;EAAE,OAAO,EN9I1B,GAAO;;AM+IvB,mBAAmC;EAAE,OAAO,ENzI1B,GAAO;;AM0IzB,cAA8B;EAAE,OAAO,EN9O1B,GAAO;;AM+OpB,mBAAmC;EAAE,OAAO,EN3W1B,GAAO;;AM4WzB,gBAAgC;EAAE,OAAO,EN9T1B,GAAO;;AM+TtB,cAA8B;EAAE,OAAO,ENnE1B,GAAO;;AMoEpB,gBAAgC;EAAE,OAAO,ENoC1B,GAAO;;AMnCtB,eAA+B;EAAE,OAAO,ENjS1B,GAAO;;AMkSrB,gBAAgC;EAAE,OAAO,ENjS1B,GAAO;;AMkStB,kBAAkC;EAAE,OAAO,ENtY1B,GAAO;;AMuYxB,yBAAyC;EAAE,OAAO,ENtY1B,GAAO;;AMuY/B,gBAAgC;EAAE,OAAO,EN2C1B,GAAO;;AM1CtB,uBAAuC;EAAE,OAAO,EN2C1B,GAAO;;AM1C7B,kBAAkC;EAAE,OAAO,ENvC1B,GAAO;;AMwCxB;cAC8B;EAAE,OAAO,EN3W1B,GAAO;;AM4WpB;eAC+B;EAAE,OAAO,EN2D1B,GAAO;;AM1DrB,eAA+B;EAAE,OAAO,ENuF1B,GAAO;;AMtFrB,kBAAkC;EAAE,OAAO,ENwB1B,GAAO;;AMvBxB,qBAAqC;EAAE,OAAO,ENpS1B,GAAO;;AMqS3B,qBAAqC;EAAE,OAAO,ENkB1B,GAAO;;AMjB3B,mBAAmC;EAAE,OAAO,EN1S1B,GAAO;;AM2SzB,qBAAqC;EAAE,OAAO,ENxP1B,GAAO;;AMyP3B,sBAAsC;EAAE,OAAO,ENjP1B,GAAO;;AMkP5B,uBAAuC;EAAE,OAAO,EN9P1B,GAAO;;AM+P7B,4BAA4C;EAAE,OAAO,ENxP1B,GAAO;;AMyPlC;;uBAEuC;EAAE,OAAO,ENjQ1B,GAAO;;AMkQ7B;yBACyC;EAAE,OAAO,ENvQ1B,GAAO;;AMwQ/B;uBACuC;EAAE,OAAO,ENxQ1B,GAAO;;AMyQ7B;uBACuC;EAAE,OAAO,EN7P1B,GAAO;;AM8P7B,sBAAsC;EAAE,OAAO,EN1Q1B,GAAO;;AM2Q5B,eAA+B;EAAE,OAAO,ENsG1B,GAAO;;AMrGrB,kBAAkC;EAAE,OAAO,ENlV1B,GAAO;;AMmVxB,mBAAmC;EAAE,OAAO,ENnL1B,GAAO;;AMoLzB;;;;oBAIoC;EAAE,OAAO,ENxK1B,GAAO;;AMyK1B,yBAAyC;EAAE,OAAO,ENpW1B,GAAO;;AMqW/B;gBACgC;EAAE,OAAO,EN1E1B,GAAO;;AM2EtB;iBACiC;EAAE,OAAO,ENpT1B,GAAO;;AMqTvB,qBAAqC;EAAE,OAAO,EN1O1B,GAAO;;AM2O3B,cAA8B;EAAE,OAAO,EN5O1B,GAAO;;AM6OpB,sBAAsC;EAAE,OAAO,EN7N1B,GAAO;;AM8N5B,wBAAwC;EAAE,OAAO,ENwB1B,GAAO;;AMvB9B,aAA6B;EAAE,OAAO,ENzF1B,GAAO;;AM0FnB;iBACiC;EAAE,OAAO,EN2F1B,GAAO;;AM1FvB;sBACsC;EAAE,OAAO,EN9H1B,GAAO;;AM+H5B;wBACwC;EAAE,OAAO,EN/H1B,GAAO;;AMgI9B,kBAAkC;EAAE,OAAO,EN3N1B,GAAO;;AM4NxB;sBACsC;EAAE,OAAO,ENrX1B,GAAO;;AMsX5B,iBAAiC;EAAE,OAAO,ENnO1B,GAAO;;AMoOvB,oBAAoC;EAAE,OAAO,ENlI1B,GAAO;;AMmI1B,kBAAkC;EAAE,OAAO,EN1C1B,GAAO;;AM2CxB,oBAAoC;EAAE,OAAO,EN7D1B,GAAO;;AM8D1B,2BAA2C;EAAE,OAAO,EN7D1B,GAAO;;AM8DjC,eAA+B;EAAE,OAAO,ENpb1B,GAAO;;AMqbrB;mBACmC;EAAE,OAAO,ENzQ1B,GAAO;;AM0QzB,cAA8B;EAAE,OAAO,ENsC1B,GAAO;;AMrCpB,qBAAqC;EAAE,OAAO,EN/b1B,GAAO;;AMgc3B,eAA+B;EAAE,OAAO,ENrH1B,GAAO;;AMsHrB,qBAAqC;EAAE,OAAO,ENlD1B,GAAO;;AMmD3B,iBAAiC;EAAE,OAAO,ENsC1B,GAAO;;AMrCvB,eAA+B;EAAE,OAAO,ENiF1B,GAAO;;AMhFrB,sBAAsC;EAAE,OAAO,ENvJ1B,GAAO;;AMwJ5B,eAA+B;EAAE,OAAO,ENuE1B,GAAO;;AMtErB,qBAAqC;EAAE,OAAO,ENjb1B,GAAO;;AMkb3B,iBAAiC;EAAE,OAAO,EN9I1B,GAAO;;AM+IvB,wBAAwC;EAAE,OAAO,ENhQ1B,GAAO;;AMiQ9B,kBAAkC;EAAE,OAAO,EN9Z1B,GAAO;;AM+ZxB,wBAAwC;EAAE,OAAO,ENla1B,GAAO;;AMma9B,sBAAsC;EAAE,OAAO,ENpa1B,GAAO;;AMqa5B,kBAAkC;EAAE,OAAO,ENta1B,GAAO;;AMuaxB,oBAAoC;EAAE,OAAO,ENpa1B,GAAO;;AMqa1B,oBAAoC;EAAE,OAAO,ENpa1B,GAAO;;AMqa1B,qBAAqC;EAAE,OAAO,ENld1B,GAAO;;AMmd3B,uBAAuC;EAAE,OAAO,ENld1B,GAAO;;AMmd7B,gBAAgC;EAAE,OAAO,ENY1B,GAAO;;AMXtB,oBAAoC;EAAE,OAAO,EN3X1B,GAAO;;AM4X1B,aAA6B;EAAE,OAAO,ENre1B,GAAO;;AMsenB,qBAAqC;EAAE,OAAO,ENjV1B,GAAO;;AMkV3B,sBAAsC;EAAE,OAAO,ENpK1B,GAAO;;AMqK5B,wBAAwC;EAAE,OAAO,ENrd1B,GAAO;;AMsd9B,qBAAqC;EAAE,OAAO,EN3f1B,GAAO;;AM4f3B,oBAAoC;EAAE,OAAO,ENvJ1B,GAAO;;AMwJ1B,qBAAqC;EAAE,OAAO,EN5N1B,GAAO;;AM6N3B,iBAAiC;EAAE,OAAO,EN1O1B,GAAO;;AM2OvB,wBAAwC;EAAE,OAAO,EN1O1B,GAAO;;AM2O9B,qBAAqC;EAAE,OAAO,ENN1B,GAAO;;AMO3B,oBAAoC;EAAE,OAAO,ENN1B,GAAO;;AMO1B,kBAAkC;EAAE,OAAO,EN/d1B,GAAO;;AMgexB,cAA8B;EAAE,OAAO,EN7c1B,GAAO;;AM8cpB,kBAAkC;EAAE,OAAO,EN1P1B,GAAO;;AM2PxB,oBAAoC;EAAE,OAAO,ENhhB1B,GAAO;;AMihB1B,aAA6B;EAAE,OAAO,EN7b1B,GAAO;;AM8bnB;;cAE8B;EAAE,OAAO,ENxQ1B,GAAO;;AMyQpB,mBAAmC;EAAE,OAAO,EN7M1B,GAAO;;AM8MzB,qBAAqC;EAAE,OAAO,ENpd1B,GAAO;;AMqd3B,yBAAyC;EAAE,OAAO,ENnZ1B,GAAO;;AMoZ/B,mBAAmC;EAAE,OAAO,ENxY1B,GAAO;;AMyYzB,mBAAmC;EAAE,OAAO,EN1T1B,GAAO;;AM2TzB,kBAAkC;EAAE,OAAO,ENxP1B,GAAO;;AMyPxB,iBAAiC;EAAE,OAAO,ENrH1B,GAAO;;AMsHvB,uBAAuC;EAAE,OAAO,ENzG1B,GAAO;;AM0G7B,sBAAsC;EAAE,OAAO,ENrG1B,GAAO;;AMsG5B,mBAAmC;EAAE,OAAO,ENpG1B,GAAO;;AMqGzB,oBAAoC;EAAE,OAAO,EN5c1B,GAAO;;AM6c1B,0BAA0C;EAAE,OAAO,EN9c1B,GAAO;;AM+chC,kBAAkC;EAAE,OAAO,EN3Y1B,GAAO;;AM4YxB,eAA+B;EAAE,OAAO,ENhH1B,GAAO;;AMiHrB,sBAAsC;EAAE,OAAO,ENI1B,GAAO;;AMH5B,qBAAqC;EAAE,OAAO,EN5M1B,GAAO;;AM6M3B,sBAAsC;EAAE,OAAO,ENpE1B,GAAO;;AMqE5B,oBAAoC;EAAE,OAAO,ENhS1B,GAAO;;AMiS1B,gBAAgC;EAAE,OAAO,ENG1B,GAAO;;AMFtB,eAA+B;EAAE,OAAO,ENtO1B,GAAO;;AMuOrB,kBAAkC;EAAE,OAAO,EN7N1B,GAAO;;AM8NxB,sBAAsC;EAAE,OAAO,ENhC1B,GAAO;;AMiC5B,0BAA0C;EAAE,OAAO,ENhC1B,GAAO;;AMiChC,uBAAuC;EAAE,OAAO,END1B,GAAO;;AME7B,sBAAsC;EAAE,OAAO,EN1O1B,GAAO;;AM2O5B,qBAAqC;EAAE,OAAO,ENF1B,GAAO;;AMG3B,sBAAsC;EAAE,OAAO,EN3O1B,GAAO;;AM4O5B,wBAAwC;EAAE,OAAO,EN1O1B,GAAO;;AM2O9B,wBAAwC;EAAE,OAAO,EN5O1B,GAAO;;AM6O9B,iBAAiC;EAAE,OAAO,ENvN1B,GAAO;;AMwNvB,4BAA4C;EAAE,OAAO,EN9X1B,GAAO;;AM+XlC,sBAAsC;EAAE,OAAO,ENhM1B,GAAO;;AMiM5B,mBAAmC;EAAE,OAAO,ENI1B,GAAO;;AMHzB,iBAAiC;EAAE,OAAO,EN7I1B,GAAO;;AM8IvB,oBAAoC;EAAE,OAAO,ENjB1B,GAAO;;AMkB1B,qBAAqC;EAAE,OAAO,ENhB1B,GAAO;;AMiB3B;cAC8B;EAAE,OAAO,ENphB1B,GAAO;;AMqhBpB,kBAAkC;EAAE,OAAO,ENd1B,GAAO;;AMexB,gBAAgC;EAAE,OAAO,ENnD1B,GAAO;;AMoDtB,iBAAiC;EAAE,OAAO,ENvF1B,GAAO;;AMwFvB,iBAAiC;EAAE,OAAO,ENrP1B,GAAO", +"sources": ["../scss/_path.scss","../scss/_core.scss","../scss/_larger.scss","../scss/_fixed-width.scss","../scss/_list.scss","../scss/_variables.scss","../scss/_bordered-pulled.scss","../scss/_animated.scss","../scss/_rotated-flipped.scss","../scss/_mixins.scss","../scss/_stacked.scss","../scss/_icons.scss"], +"names": [], +"file": "font-awesome.css" +} diff --git a/jun_captcha_slider/src/main/webapp/lib/font-awesome/css/font-awesome.min.css b/jun_captcha_slider/src/main/webapp/lib/font-awesome/css/font-awesome.min.css new file mode 100644 index 0000000000..540440ce89 --- /dev/null +++ b/jun_captcha_slider/src/main/webapp/lib/font-awesome/css/font-awesome.min.css @@ -0,0 +1,4 @@ +/*! + * Font Awesome 4.7.0 by @davegandy - http://fontawesome.io - @fontawesome + * License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License) + */@font-face{font-family:'FontAwesome';src:url('../fonts/fontawesome-webfont.eot?v=4.7.0');src:url('../fonts/fontawesome-webfont.eot?#iefix&v=4.7.0') format('embedded-opentype'),url('../fonts/fontawesome-webfont.woff2?v=4.7.0') format('woff2'),url('../fonts/fontawesome-webfont.woff?v=4.7.0') format('woff'),url('../fonts/fontawesome-webfont.ttf?v=4.7.0') format('truetype'),url('../fonts/fontawesome-webfont.svg?v=4.7.0#fontawesomeregular') format('svg');font-weight:normal;font-style:normal}.fa{display:inline-block;font:normal normal normal 14px/1 FontAwesome;font-size:inherit;text-rendering:auto;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.fa-lg{font-size:1.33333333em;line-height:.75em;vertical-align:-15%}.fa-2x{font-size:2em}.fa-3x{font-size:3em}.fa-4x{font-size:4em}.fa-5x{font-size:5em}.fa-fw{width:1.28571429em;text-align:center}.fa-ul{padding-left:0;margin-left:2.14285714em;list-style-type:none}.fa-ul>li{position:relative}.fa-li{position:absolute;left:-2.14285714em;width:2.14285714em;top:.14285714em;text-align:center}.fa-li.fa-lg{left:-1.85714286em}.fa-border{padding:.2em .25em .15em;border:solid .08em #eee;border-radius:.1em}.fa-pull-left{float:left}.fa-pull-right{float:right}.fa.fa-pull-left{margin-right:.3em}.fa.fa-pull-right{margin-left:.3em}.pull-right{float:right}.pull-left{float:left}.fa.pull-left{margin-right:.3em}.fa.pull-right{margin-left:.3em}.fa-spin{-webkit-animation:fa-spin 2s infinite linear;animation:fa-spin 2s infinite linear}.fa-pulse{-webkit-animation:fa-spin 1s infinite steps(8);animation:fa-spin 1s infinite steps(8)}@-webkit-keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}@keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}.fa-rotate-90{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=1)";-webkit-transform:rotate(90deg);-ms-transform:rotate(90deg);transform:rotate(90deg)}.fa-rotate-180{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=2)";-webkit-transform:rotate(180deg);-ms-transform:rotate(180deg);transform:rotate(180deg)}.fa-rotate-270{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=3)";-webkit-transform:rotate(270deg);-ms-transform:rotate(270deg);transform:rotate(270deg)}.fa-flip-horizontal{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1)";-webkit-transform:scale(-1, 1);-ms-transform:scale(-1, 1);transform:scale(-1, 1)}.fa-flip-vertical{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1)";-webkit-transform:scale(1, -1);-ms-transform:scale(1, -1);transform:scale(1, -1)}:root .fa-rotate-90,:root .fa-rotate-180,:root .fa-rotate-270,:root .fa-flip-horizontal,:root .fa-flip-vertical{filter:none}.fa-stack{position:relative;display:inline-block;width:2em;height:2em;line-height:2em;vertical-align:middle}.fa-stack-1x,.fa-stack-2x{position:absolute;left:0;width:100%;text-align:center}.fa-stack-1x{line-height:inherit}.fa-stack-2x{font-size:2em}.fa-inverse{color:#fff}.fa-glass:before{content:"\f000"}.fa-music:before{content:"\f001"}.fa-search:before{content:"\f002"}.fa-envelope-o:before{content:"\f003"}.fa-heart:before{content:"\f004"}.fa-star:before{content:"\f005"}.fa-star-o:before{content:"\f006"}.fa-user:before{content:"\f007"}.fa-film:before{content:"\f008"}.fa-th-large:before{content:"\f009"}.fa-th:before{content:"\f00a"}.fa-th-list:before{content:"\f00b"}.fa-check:before{content:"\f00c"}.fa-remove:before,.fa-close:before,.fa-times:before{content:"\f00d"}.fa-search-plus:before{content:"\f00e"}.fa-search-minus:before{content:"\f010"}.fa-power-off:before{content:"\f011"}.fa-signal:before{content:"\f012"}.fa-gear:before,.fa-cog:before{content:"\f013"}.fa-trash-o:before{content:"\f014"}.fa-home:before{content:"\f015"}.fa-file-o:before{content:"\f016"}.fa-clock-o:before{content:"\f017"}.fa-road:before{content:"\f018"}.fa-download:before{content:"\f019"}.fa-arrow-circle-o-down:before{content:"\f01a"}.fa-arrow-circle-o-up:before{content:"\f01b"}.fa-inbox:before{content:"\f01c"}.fa-play-circle-o:before{content:"\f01d"}.fa-rotate-right:before,.fa-repeat:before{content:"\f01e"}.fa-refresh:before{content:"\f021"}.fa-list-alt:before{content:"\f022"}.fa-lock:before{content:"\f023"}.fa-flag:before{content:"\f024"}.fa-headphones:before{content:"\f025"}.fa-volume-off:before{content:"\f026"}.fa-volume-down:before{content:"\f027"}.fa-volume-up:before{content:"\f028"}.fa-qrcode:before{content:"\f029"}.fa-barcode:before{content:"\f02a"}.fa-tag:before{content:"\f02b"}.fa-tags:before{content:"\f02c"}.fa-book:before{content:"\f02d"}.fa-bookmark:before{content:"\f02e"}.fa-print:before{content:"\f02f"}.fa-camera:before{content:"\f030"}.fa-font:before{content:"\f031"}.fa-bold:before{content:"\f032"}.fa-italic:before{content:"\f033"}.fa-text-height:before{content:"\f034"}.fa-text-width:before{content:"\f035"}.fa-align-left:before{content:"\f036"}.fa-align-center:before{content:"\f037"}.fa-align-right:before{content:"\f038"}.fa-align-justify:before{content:"\f039"}.fa-list:before{content:"\f03a"}.fa-dedent:before,.fa-outdent:before{content:"\f03b"}.fa-indent:before{content:"\f03c"}.fa-video-camera:before{content:"\f03d"}.fa-photo:before,.fa-image:before,.fa-picture-o:before{content:"\f03e"}.fa-pencil:before{content:"\f040"}.fa-map-marker:before{content:"\f041"}.fa-adjust:before{content:"\f042"}.fa-tint:before{content:"\f043"}.fa-edit:before,.fa-pencil-square-o:before{content:"\f044"}.fa-share-square-o:before{content:"\f045"}.fa-check-square-o:before{content:"\f046"}.fa-arrows:before{content:"\f047"}.fa-step-backward:before{content:"\f048"}.fa-fast-backward:before{content:"\f049"}.fa-backward:before{content:"\f04a"}.fa-play:before{content:"\f04b"}.fa-pause:before{content:"\f04c"}.fa-stop:before{content:"\f04d"}.fa-forward:before{content:"\f04e"}.fa-fast-forward:before{content:"\f050"}.fa-step-forward:before{content:"\f051"}.fa-eject:before{content:"\f052"}.fa-chevron-left:before{content:"\f053"}.fa-chevron-right:before{content:"\f054"}.fa-plus-circle:before{content:"\f055"}.fa-minus-circle:before{content:"\f056"}.fa-times-circle:before{content:"\f057"}.fa-check-circle:before{content:"\f058"}.fa-question-circle:before{content:"\f059"}.fa-info-circle:before{content:"\f05a"}.fa-crosshairs:before{content:"\f05b"}.fa-times-circle-o:before{content:"\f05c"}.fa-check-circle-o:before{content:"\f05d"}.fa-ban:before{content:"\f05e"}.fa-arrow-left:before{content:"\f060"}.fa-arrow-right:before{content:"\f061"}.fa-arrow-up:before{content:"\f062"}.fa-arrow-down:before{content:"\f063"}.fa-mail-forward:before,.fa-share:before{content:"\f064"}.fa-expand:before{content:"\f065"}.fa-compress:before{content:"\f066"}.fa-plus:before{content:"\f067"}.fa-minus:before{content:"\f068"}.fa-asterisk:before{content:"\f069"}.fa-exclamation-circle:before{content:"\f06a"}.fa-gift:before{content:"\f06b"}.fa-leaf:before{content:"\f06c"}.fa-fire:before{content:"\f06d"}.fa-eye:before{content:"\f06e"}.fa-eye-slash:before{content:"\f070"}.fa-warning:before,.fa-exclamation-triangle:before{content:"\f071"}.fa-plane:before{content:"\f072"}.fa-calendar:before{content:"\f073"}.fa-random:before{content:"\f074"}.fa-comment:before{content:"\f075"}.fa-magnet:before{content:"\f076"}.fa-chevron-up:before{content:"\f077"}.fa-chevron-down:before{content:"\f078"}.fa-retweet:before{content:"\f079"}.fa-shopping-cart:before{content:"\f07a"}.fa-folder:before{content:"\f07b"}.fa-folder-open:before{content:"\f07c"}.fa-arrows-v:before{content:"\f07d"}.fa-arrows-h:before{content:"\f07e"}.fa-bar-chart-o:before,.fa-bar-chart:before{content:"\f080"}.fa-twitter-square:before{content:"\f081"}.fa-facebook-square:before{content:"\f082"}.fa-camera-retro:before{content:"\f083"}.fa-key:before{content:"\f084"}.fa-gears:before,.fa-cogs:before{content:"\f085"}.fa-comments:before{content:"\f086"}.fa-thumbs-o-up:before{content:"\f087"}.fa-thumbs-o-down:before{content:"\f088"}.fa-star-half:before{content:"\f089"}.fa-heart-o:before{content:"\f08a"}.fa-sign-out:before{content:"\f08b"}.fa-linkedin-square:before{content:"\f08c"}.fa-thumb-tack:before{content:"\f08d"}.fa-external-link:before{content:"\f08e"}.fa-sign-in:before{content:"\f090"}.fa-trophy:before{content:"\f091"}.fa-github-square:before{content:"\f092"}.fa-upload:before{content:"\f093"}.fa-lemon-o:before{content:"\f094"}.fa-phone:before{content:"\f095"}.fa-square-o:before{content:"\f096"}.fa-bookmark-o:before{content:"\f097"}.fa-phone-square:before{content:"\f098"}.fa-twitter:before{content:"\f099"}.fa-facebook-f:before,.fa-facebook:before{content:"\f09a"}.fa-github:before{content:"\f09b"}.fa-unlock:before{content:"\f09c"}.fa-credit-card:before{content:"\f09d"}.fa-feed:before,.fa-rss:before{content:"\f09e"}.fa-hdd-o:before{content:"\f0a0"}.fa-bullhorn:before{content:"\f0a1"}.fa-bell:before{content:"\f0f3"}.fa-certificate:before{content:"\f0a3"}.fa-hand-o-right:before{content:"\f0a4"}.fa-hand-o-left:before{content:"\f0a5"}.fa-hand-o-up:before{content:"\f0a6"}.fa-hand-o-down:before{content:"\f0a7"}.fa-arrow-circle-left:before{content:"\f0a8"}.fa-arrow-circle-right:before{content:"\f0a9"}.fa-arrow-circle-up:before{content:"\f0aa"}.fa-arrow-circle-down:before{content:"\f0ab"}.fa-globe:before{content:"\f0ac"}.fa-wrench:before{content:"\f0ad"}.fa-tasks:before{content:"\f0ae"}.fa-filter:before{content:"\f0b0"}.fa-briefcase:before{content:"\f0b1"}.fa-arrows-alt:before{content:"\f0b2"}.fa-group:before,.fa-users:before{content:"\f0c0"}.fa-chain:before,.fa-link:before{content:"\f0c1"}.fa-cloud:before{content:"\f0c2"}.fa-flask:before{content:"\f0c3"}.fa-cut:before,.fa-scissors:before{content:"\f0c4"}.fa-copy:before,.fa-files-o:before{content:"\f0c5"}.fa-paperclip:before{content:"\f0c6"}.fa-save:before,.fa-floppy-o:before{content:"\f0c7"}.fa-square:before{content:"\f0c8"}.fa-navicon:before,.fa-reorder:before,.fa-bars:before{content:"\f0c9"}.fa-list-ul:before{content:"\f0ca"}.fa-list-ol:before{content:"\f0cb"}.fa-strikethrough:before{content:"\f0cc"}.fa-underline:before{content:"\f0cd"}.fa-table:before{content:"\f0ce"}.fa-magic:before{content:"\f0d0"}.fa-truck:before{content:"\f0d1"}.fa-pinterest:before{content:"\f0d2"}.fa-pinterest-square:before{content:"\f0d3"}.fa-google-plus-square:before{content:"\f0d4"}.fa-google-plus:before{content:"\f0d5"}.fa-money:before{content:"\f0d6"}.fa-caret-down:before{content:"\f0d7"}.fa-caret-up:before{content:"\f0d8"}.fa-caret-left:before{content:"\f0d9"}.fa-caret-right:before{content:"\f0da"}.fa-columns:before{content:"\f0db"}.fa-unsorted:before,.fa-sort:before{content:"\f0dc"}.fa-sort-down:before,.fa-sort-desc:before{content:"\f0dd"}.fa-sort-up:before,.fa-sort-asc:before{content:"\f0de"}.fa-envelope:before{content:"\f0e0"}.fa-linkedin:before{content:"\f0e1"}.fa-rotate-left:before,.fa-undo:before{content:"\f0e2"}.fa-legal:before,.fa-gavel:before{content:"\f0e3"}.fa-dashboard:before,.fa-tachometer:before{content:"\f0e4"}.fa-comment-o:before{content:"\f0e5"}.fa-comments-o:before{content:"\f0e6"}.fa-flash:before,.fa-bolt:before{content:"\f0e7"}.fa-sitemap:before{content:"\f0e8"}.fa-umbrella:before{content:"\f0e9"}.fa-paste:before,.fa-clipboard:before{content:"\f0ea"}.fa-lightbulb-o:before{content:"\f0eb"}.fa-exchange:before{content:"\f0ec"}.fa-cloud-download:before{content:"\f0ed"}.fa-cloud-upload:before{content:"\f0ee"}.fa-user-md:before{content:"\f0f0"}.fa-stethoscope:before{content:"\f0f1"}.fa-suitcase:before{content:"\f0f2"}.fa-bell-o:before{content:"\f0a2"}.fa-coffee:before{content:"\f0f4"}.fa-cutlery:before{content:"\f0f5"}.fa-file-text-o:before{content:"\f0f6"}.fa-building-o:before{content:"\f0f7"}.fa-hospital-o:before{content:"\f0f8"}.fa-ambulance:before{content:"\f0f9"}.fa-medkit:before{content:"\f0fa"}.fa-fighter-jet:before{content:"\f0fb"}.fa-beer:before{content:"\f0fc"}.fa-h-square:before{content:"\f0fd"}.fa-plus-square:before{content:"\f0fe"}.fa-angle-double-left:before{content:"\f100"}.fa-angle-double-right:before{content:"\f101"}.fa-angle-double-up:before{content:"\f102"}.fa-angle-double-down:before{content:"\f103"}.fa-angle-left:before{content:"\f104"}.fa-angle-right:before{content:"\f105"}.fa-angle-up:before{content:"\f106"}.fa-angle-down:before{content:"\f107"}.fa-desktop:before{content:"\f108"}.fa-laptop:before{content:"\f109"}.fa-tablet:before{content:"\f10a"}.fa-mobile-phone:before,.fa-mobile:before{content:"\f10b"}.fa-circle-o:before{content:"\f10c"}.fa-quote-left:before{content:"\f10d"}.fa-quote-right:before{content:"\f10e"}.fa-spinner:before{content:"\f110"}.fa-circle:before{content:"\f111"}.fa-mail-reply:before,.fa-reply:before{content:"\f112"}.fa-github-alt:before{content:"\f113"}.fa-folder-o:before{content:"\f114"}.fa-folder-open-o:before{content:"\f115"}.fa-smile-o:before{content:"\f118"}.fa-frown-o:before{content:"\f119"}.fa-meh-o:before{content:"\f11a"}.fa-gamepad:before{content:"\f11b"}.fa-keyboard-o:before{content:"\f11c"}.fa-flag-o:before{content:"\f11d"}.fa-flag-checkered:before{content:"\f11e"}.fa-terminal:before{content:"\f120"}.fa-code:before{content:"\f121"}.fa-mail-reply-all:before,.fa-reply-all:before{content:"\f122"}.fa-star-half-empty:before,.fa-star-half-full:before,.fa-star-half-o:before{content:"\f123"}.fa-location-arrow:before{content:"\f124"}.fa-crop:before{content:"\f125"}.fa-code-fork:before{content:"\f126"}.fa-unlink:before,.fa-chain-broken:before{content:"\f127"}.fa-question:before{content:"\f128"}.fa-info:before{content:"\f129"}.fa-exclamation:before{content:"\f12a"}.fa-superscript:before{content:"\f12b"}.fa-subscript:before{content:"\f12c"}.fa-eraser:before{content:"\f12d"}.fa-puzzle-piece:before{content:"\f12e"}.fa-microphone:before{content:"\f130"}.fa-microphone-slash:before{content:"\f131"}.fa-shield:before{content:"\f132"}.fa-calendar-o:before{content:"\f133"}.fa-fire-extinguisher:before{content:"\f134"}.fa-rocket:before{content:"\f135"}.fa-maxcdn:before{content:"\f136"}.fa-chevron-circle-left:before{content:"\f137"}.fa-chevron-circle-right:before{content:"\f138"}.fa-chevron-circle-up:before{content:"\f139"}.fa-chevron-circle-down:before{content:"\f13a"}.fa-html5:before{content:"\f13b"}.fa-css3:before{content:"\f13c"}.fa-anchor:before{content:"\f13d"}.fa-unlock-alt:before{content:"\f13e"}.fa-bullseye:before{content:"\f140"}.fa-ellipsis-h:before{content:"\f141"}.fa-ellipsis-v:before{content:"\f142"}.fa-rss-square:before{content:"\f143"}.fa-play-circle:before{content:"\f144"}.fa-ticket:before{content:"\f145"}.fa-minus-square:before{content:"\f146"}.fa-minus-square-o:before{content:"\f147"}.fa-level-up:before{content:"\f148"}.fa-level-down:before{content:"\f149"}.fa-check-square:before{content:"\f14a"}.fa-pencil-square:before{content:"\f14b"}.fa-external-link-square:before{content:"\f14c"}.fa-share-square:before{content:"\f14d"}.fa-compass:before{content:"\f14e"}.fa-toggle-down:before,.fa-caret-square-o-down:before{content:"\f150"}.fa-toggle-up:before,.fa-caret-square-o-up:before{content:"\f151"}.fa-toggle-right:before,.fa-caret-square-o-right:before{content:"\f152"}.fa-euro:before,.fa-eur:before{content:"\f153"}.fa-gbp:before{content:"\f154"}.fa-dollar:before,.fa-usd:before{content:"\f155"}.fa-rupee:before,.fa-inr:before{content:"\f156"}.fa-cny:before,.fa-rmb:before,.fa-yen:before,.fa-jpy:before{content:"\f157"}.fa-ruble:before,.fa-rouble:before,.fa-rub:before{content:"\f158"}.fa-won:before,.fa-krw:before{content:"\f159"}.fa-bitcoin:before,.fa-btc:before{content:"\f15a"}.fa-file:before{content:"\f15b"}.fa-file-text:before{content:"\f15c"}.fa-sort-alpha-asc:before{content:"\f15d"}.fa-sort-alpha-desc:before{content:"\f15e"}.fa-sort-amount-asc:before{content:"\f160"}.fa-sort-amount-desc:before{content:"\f161"}.fa-sort-numeric-asc:before{content:"\f162"}.fa-sort-numeric-desc:before{content:"\f163"}.fa-thumbs-up:before{content:"\f164"}.fa-thumbs-down:before{content:"\f165"}.fa-youtube-square:before{content:"\f166"}.fa-youtube:before{content:"\f167"}.fa-xing:before{content:"\f168"}.fa-xing-square:before{content:"\f169"}.fa-youtube-play:before{content:"\f16a"}.fa-dropbox:before{content:"\f16b"}.fa-stack-overflow:before{content:"\f16c"}.fa-instagram:before{content:"\f16d"}.fa-flickr:before{content:"\f16e"}.fa-adn:before{content:"\f170"}.fa-bitbucket:before{content:"\f171"}.fa-bitbucket-square:before{content:"\f172"}.fa-tumblr:before{content:"\f173"}.fa-tumblr-square:before{content:"\f174"}.fa-long-arrow-down:before{content:"\f175"}.fa-long-arrow-up:before{content:"\f176"}.fa-long-arrow-left:before{content:"\f177"}.fa-long-arrow-right:before{content:"\f178"}.fa-apple:before{content:"\f179"}.fa-windows:before{content:"\f17a"}.fa-android:before{content:"\f17b"}.fa-linux:before{content:"\f17c"}.fa-dribbble:before{content:"\f17d"}.fa-skype:before{content:"\f17e"}.fa-foursquare:before{content:"\f180"}.fa-trello:before{content:"\f181"}.fa-female:before{content:"\f182"}.fa-male:before{content:"\f183"}.fa-gittip:before,.fa-gratipay:before{content:"\f184"}.fa-sun-o:before{content:"\f185"}.fa-moon-o:before{content:"\f186"}.fa-archive:before{content:"\f187"}.fa-bug:before{content:"\f188"}.fa-vk:before{content:"\f189"}.fa-weibo:before{content:"\f18a"}.fa-renren:before{content:"\f18b"}.fa-pagelines:before{content:"\f18c"}.fa-stack-exchange:before{content:"\f18d"}.fa-arrow-circle-o-right:before{content:"\f18e"}.fa-arrow-circle-o-left:before{content:"\f190"}.fa-toggle-left:before,.fa-caret-square-o-left:before{content:"\f191"}.fa-dot-circle-o:before{content:"\f192"}.fa-wheelchair:before{content:"\f193"}.fa-vimeo-square:before{content:"\f194"}.fa-turkish-lira:before,.fa-try:before{content:"\f195"}.fa-plus-square-o:before{content:"\f196"}.fa-space-shuttle:before{content:"\f197"}.fa-slack:before{content:"\f198"}.fa-envelope-square:before{content:"\f199"}.fa-wordpress:before{content:"\f19a"}.fa-openid:before{content:"\f19b"}.fa-institution:before,.fa-bank:before,.fa-university:before{content:"\f19c"}.fa-mortar-board:before,.fa-graduation-cap:before{content:"\f19d"}.fa-yahoo:before{content:"\f19e"}.fa-google:before{content:"\f1a0"}.fa-reddit:before{content:"\f1a1"}.fa-reddit-square:before{content:"\f1a2"}.fa-stumbleupon-circle:before{content:"\f1a3"}.fa-stumbleupon:before{content:"\f1a4"}.fa-delicious:before{content:"\f1a5"}.fa-digg:before{content:"\f1a6"}.fa-pied-piper-pp:before{content:"\f1a7"}.fa-pied-piper-alt:before{content:"\f1a8"}.fa-drupal:before{content:"\f1a9"}.fa-joomla:before{content:"\f1aa"}.fa-language:before{content:"\f1ab"}.fa-fax:before{content:"\f1ac"}.fa-building:before{content:"\f1ad"}.fa-child:before{content:"\f1ae"}.fa-paw:before{content:"\f1b0"}.fa-spoon:before{content:"\f1b1"}.fa-cube:before{content:"\f1b2"}.fa-cubes:before{content:"\f1b3"}.fa-behance:before{content:"\f1b4"}.fa-behance-square:before{content:"\f1b5"}.fa-steam:before{content:"\f1b6"}.fa-steam-square:before{content:"\f1b7"}.fa-recycle:before{content:"\f1b8"}.fa-automobile:before,.fa-car:before{content:"\f1b9"}.fa-cab:before,.fa-taxi:before{content:"\f1ba"}.fa-tree:before{content:"\f1bb"}.fa-spotify:before{content:"\f1bc"}.fa-deviantart:before{content:"\f1bd"}.fa-soundcloud:before{content:"\f1be"}.fa-database:before{content:"\f1c0"}.fa-file-pdf-o:before{content:"\f1c1"}.fa-file-word-o:before{content:"\f1c2"}.fa-file-excel-o:before{content:"\f1c3"}.fa-file-powerpoint-o:before{content:"\f1c4"}.fa-file-photo-o:before,.fa-file-picture-o:before,.fa-file-image-o:before{content:"\f1c5"}.fa-file-zip-o:before,.fa-file-archive-o:before{content:"\f1c6"}.fa-file-sound-o:before,.fa-file-audio-o:before{content:"\f1c7"}.fa-file-movie-o:before,.fa-file-video-o:before{content:"\f1c8"}.fa-file-code-o:before{content:"\f1c9"}.fa-vine:before{content:"\f1ca"}.fa-codepen:before{content:"\f1cb"}.fa-jsfiddle:before{content:"\f1cc"}.fa-life-bouy:before,.fa-life-buoy:before,.fa-life-saver:before,.fa-support:before,.fa-life-ring:before{content:"\f1cd"}.fa-circle-o-notch:before{content:"\f1ce"}.fa-ra:before,.fa-resistance:before,.fa-rebel:before{content:"\f1d0"}.fa-ge:before,.fa-empire:before{content:"\f1d1"}.fa-git-square:before{content:"\f1d2"}.fa-git:before{content:"\f1d3"}.fa-y-combinator-square:before,.fa-yc-square:before,.fa-hacker-news:before{content:"\f1d4"}.fa-tencent-weibo:before{content:"\f1d5"}.fa-qq:before{content:"\f1d6"}.fa-wechat:before,.fa-weixin:before{content:"\f1d7"}.fa-send:before,.fa-paper-plane:before{content:"\f1d8"}.fa-send-o:before,.fa-paper-plane-o:before{content:"\f1d9"}.fa-history:before{content:"\f1da"}.fa-circle-thin:before{content:"\f1db"}.fa-header:before{content:"\f1dc"}.fa-paragraph:before{content:"\f1dd"}.fa-sliders:before{content:"\f1de"}.fa-share-alt:before{content:"\f1e0"}.fa-share-alt-square:before{content:"\f1e1"}.fa-bomb:before{content:"\f1e2"}.fa-soccer-ball-o:before,.fa-futbol-o:before{content:"\f1e3"}.fa-tty:before{content:"\f1e4"}.fa-binoculars:before{content:"\f1e5"}.fa-plug:before{content:"\f1e6"}.fa-slideshare:before{content:"\f1e7"}.fa-twitch:before{content:"\f1e8"}.fa-yelp:before{content:"\f1e9"}.fa-newspaper-o:before{content:"\f1ea"}.fa-wifi:before{content:"\f1eb"}.fa-calculator:before{content:"\f1ec"}.fa-paypal:before{content:"\f1ed"}.fa-google-wallet:before{content:"\f1ee"}.fa-cc-visa:before{content:"\f1f0"}.fa-cc-mastercard:before{content:"\f1f1"}.fa-cc-discover:before{content:"\f1f2"}.fa-cc-amex:before{content:"\f1f3"}.fa-cc-paypal:before{content:"\f1f4"}.fa-cc-stripe:before{content:"\f1f5"}.fa-bell-slash:before{content:"\f1f6"}.fa-bell-slash-o:before{content:"\f1f7"}.fa-trash:before{content:"\f1f8"}.fa-copyright:before{content:"\f1f9"}.fa-at:before{content:"\f1fa"}.fa-eyedropper:before{content:"\f1fb"}.fa-paint-brush:before{content:"\f1fc"}.fa-birthday-cake:before{content:"\f1fd"}.fa-area-chart:before{content:"\f1fe"}.fa-pie-chart:before{content:"\f200"}.fa-line-chart:before{content:"\f201"}.fa-lastfm:before{content:"\f202"}.fa-lastfm-square:before{content:"\f203"}.fa-toggle-off:before{content:"\f204"}.fa-toggle-on:before{content:"\f205"}.fa-bicycle:before{content:"\f206"}.fa-bus:before{content:"\f207"}.fa-ioxhost:before{content:"\f208"}.fa-angellist:before{content:"\f209"}.fa-cc:before{content:"\f20a"}.fa-shekel:before,.fa-sheqel:before,.fa-ils:before{content:"\f20b"}.fa-meanpath:before{content:"\f20c"}.fa-buysellads:before{content:"\f20d"}.fa-connectdevelop:before{content:"\f20e"}.fa-dashcube:before{content:"\f210"}.fa-forumbee:before{content:"\f211"}.fa-leanpub:before{content:"\f212"}.fa-sellsy:before{content:"\f213"}.fa-shirtsinbulk:before{content:"\f214"}.fa-simplybuilt:before{content:"\f215"}.fa-skyatlas:before{content:"\f216"}.fa-cart-plus:before{content:"\f217"}.fa-cart-arrow-down:before{content:"\f218"}.fa-diamond:before{content:"\f219"}.fa-ship:before{content:"\f21a"}.fa-user-secret:before{content:"\f21b"}.fa-motorcycle:before{content:"\f21c"}.fa-street-view:before{content:"\f21d"}.fa-heartbeat:before{content:"\f21e"}.fa-venus:before{content:"\f221"}.fa-mars:before{content:"\f222"}.fa-mercury:before{content:"\f223"}.fa-intersex:before,.fa-transgender:before{content:"\f224"}.fa-transgender-alt:before{content:"\f225"}.fa-venus-double:before{content:"\f226"}.fa-mars-double:before{content:"\f227"}.fa-venus-mars:before{content:"\f228"}.fa-mars-stroke:before{content:"\f229"}.fa-mars-stroke-v:before{content:"\f22a"}.fa-mars-stroke-h:before{content:"\f22b"}.fa-neuter:before{content:"\f22c"}.fa-genderless:before{content:"\f22d"}.fa-facebook-official:before{content:"\f230"}.fa-pinterest-p:before{content:"\f231"}.fa-whatsapp:before{content:"\f232"}.fa-server:before{content:"\f233"}.fa-user-plus:before{content:"\f234"}.fa-user-times:before{content:"\f235"}.fa-hotel:before,.fa-bed:before{content:"\f236"}.fa-viacoin:before{content:"\f237"}.fa-train:before{content:"\f238"}.fa-subway:before{content:"\f239"}.fa-medium:before{content:"\f23a"}.fa-yc:before,.fa-y-combinator:before{content:"\f23b"}.fa-optin-monster:before{content:"\f23c"}.fa-opencart:before{content:"\f23d"}.fa-expeditedssl:before{content:"\f23e"}.fa-battery-4:before,.fa-battery:before,.fa-battery-full:before{content:"\f240"}.fa-battery-3:before,.fa-battery-three-quarters:before{content:"\f241"}.fa-battery-2:before,.fa-battery-half:before{content:"\f242"}.fa-battery-1:before,.fa-battery-quarter:before{content:"\f243"}.fa-battery-0:before,.fa-battery-empty:before{content:"\f244"}.fa-mouse-pointer:before{content:"\f245"}.fa-i-cursor:before{content:"\f246"}.fa-object-group:before{content:"\f247"}.fa-object-ungroup:before{content:"\f248"}.fa-sticky-note:before{content:"\f249"}.fa-sticky-note-o:before{content:"\f24a"}.fa-cc-jcb:before{content:"\f24b"}.fa-cc-diners-club:before{content:"\f24c"}.fa-clone:before{content:"\f24d"}.fa-balance-scale:before{content:"\f24e"}.fa-hourglass-o:before{content:"\f250"}.fa-hourglass-1:before,.fa-hourglass-start:before{content:"\f251"}.fa-hourglass-2:before,.fa-hourglass-half:before{content:"\f252"}.fa-hourglass-3:before,.fa-hourglass-end:before{content:"\f253"}.fa-hourglass:before{content:"\f254"}.fa-hand-grab-o:before,.fa-hand-rock-o:before{content:"\f255"}.fa-hand-stop-o:before,.fa-hand-paper-o:before{content:"\f256"}.fa-hand-scissors-o:before{content:"\f257"}.fa-hand-lizard-o:before{content:"\f258"}.fa-hand-spock-o:before{content:"\f259"}.fa-hand-pointer-o:before{content:"\f25a"}.fa-hand-peace-o:before{content:"\f25b"}.fa-trademark:before{content:"\f25c"}.fa-registered:before{content:"\f25d"}.fa-creative-commons:before{content:"\f25e"}.fa-gg:before{content:"\f260"}.fa-gg-circle:before{content:"\f261"}.fa-tripadvisor:before{content:"\f262"}.fa-odnoklassniki:before{content:"\f263"}.fa-odnoklassniki-square:before{content:"\f264"}.fa-get-pocket:before{content:"\f265"}.fa-wikipedia-w:before{content:"\f266"}.fa-safari:before{content:"\f267"}.fa-chrome:before{content:"\f268"}.fa-firefox:before{content:"\f269"}.fa-opera:before{content:"\f26a"}.fa-internet-explorer:before{content:"\f26b"}.fa-tv:before,.fa-television:before{content:"\f26c"}.fa-contao:before{content:"\f26d"}.fa-500px:before{content:"\f26e"}.fa-amazon:before{content:"\f270"}.fa-calendar-plus-o:before{content:"\f271"}.fa-calendar-minus-o:before{content:"\f272"}.fa-calendar-times-o:before{content:"\f273"}.fa-calendar-check-o:before{content:"\f274"}.fa-industry:before{content:"\f275"}.fa-map-pin:before{content:"\f276"}.fa-map-signs:before{content:"\f277"}.fa-map-o:before{content:"\f278"}.fa-map:before{content:"\f279"}.fa-commenting:before{content:"\f27a"}.fa-commenting-o:before{content:"\f27b"}.fa-houzz:before{content:"\f27c"}.fa-vimeo:before{content:"\f27d"}.fa-black-tie:before{content:"\f27e"}.fa-fonticons:before{content:"\f280"}.fa-reddit-alien:before{content:"\f281"}.fa-edge:before{content:"\f282"}.fa-credit-card-alt:before{content:"\f283"}.fa-codiepie:before{content:"\f284"}.fa-modx:before{content:"\f285"}.fa-fort-awesome:before{content:"\f286"}.fa-usb:before{content:"\f287"}.fa-product-hunt:before{content:"\f288"}.fa-mixcloud:before{content:"\f289"}.fa-scribd:before{content:"\f28a"}.fa-pause-circle:before{content:"\f28b"}.fa-pause-circle-o:before{content:"\f28c"}.fa-stop-circle:before{content:"\f28d"}.fa-stop-circle-o:before{content:"\f28e"}.fa-shopping-bag:before{content:"\f290"}.fa-shopping-basket:before{content:"\f291"}.fa-hashtag:before{content:"\f292"}.fa-bluetooth:before{content:"\f293"}.fa-bluetooth-b:before{content:"\f294"}.fa-percent:before{content:"\f295"}.fa-gitlab:before{content:"\f296"}.fa-wpbeginner:before{content:"\f297"}.fa-wpforms:before{content:"\f298"}.fa-envira:before{content:"\f299"}.fa-universal-access:before{content:"\f29a"}.fa-wheelchair-alt:before{content:"\f29b"}.fa-question-circle-o:before{content:"\f29c"}.fa-blind:before{content:"\f29d"}.fa-audio-description:before{content:"\f29e"}.fa-volume-control-phone:before{content:"\f2a0"}.fa-braille:before{content:"\f2a1"}.fa-assistive-listening-systems:before{content:"\f2a2"}.fa-asl-interpreting:before,.fa-american-sign-language-interpreting:before{content:"\f2a3"}.fa-deafness:before,.fa-hard-of-hearing:before,.fa-deaf:before{content:"\f2a4"}.fa-glide:before{content:"\f2a5"}.fa-glide-g:before{content:"\f2a6"}.fa-signing:before,.fa-sign-language:before{content:"\f2a7"}.fa-low-vision:before{content:"\f2a8"}.fa-viadeo:before{content:"\f2a9"}.fa-viadeo-square:before{content:"\f2aa"}.fa-snapchat:before{content:"\f2ab"}.fa-snapchat-ghost:before{content:"\f2ac"}.fa-snapchat-square:before{content:"\f2ad"}.fa-pied-piper:before{content:"\f2ae"}.fa-first-order:before{content:"\f2b0"}.fa-yoast:before{content:"\f2b1"}.fa-themeisle:before{content:"\f2b2"}.fa-google-plus-circle:before,.fa-google-plus-official:before{content:"\f2b3"}.fa-fa:before,.fa-font-awesome:before{content:"\f2b4"}.fa-handshake-o:before{content:"\f2b5"}.fa-envelope-open:before{content:"\f2b6"}.fa-envelope-open-o:before{content:"\f2b7"}.fa-linode:before{content:"\f2b8"}.fa-address-book:before{content:"\f2b9"}.fa-address-book-o:before{content:"\f2ba"}.fa-vcard:before,.fa-address-card:before{content:"\f2bb"}.fa-vcard-o:before,.fa-address-card-o:before{content:"\f2bc"}.fa-user-circle:before{content:"\f2bd"}.fa-user-circle-o:before{content:"\f2be"}.fa-user-o:before{content:"\f2c0"}.fa-id-badge:before{content:"\f2c1"}.fa-drivers-license:before,.fa-id-card:before{content:"\f2c2"}.fa-drivers-license-o:before,.fa-id-card-o:before{content:"\f2c3"}.fa-quora:before{content:"\f2c4"}.fa-free-code-camp:before{content:"\f2c5"}.fa-telegram:before{content:"\f2c6"}.fa-thermometer-4:before,.fa-thermometer:before,.fa-thermometer-full:before{content:"\f2c7"}.fa-thermometer-3:before,.fa-thermometer-three-quarters:before{content:"\f2c8"}.fa-thermometer-2:before,.fa-thermometer-half:before{content:"\f2c9"}.fa-thermometer-1:before,.fa-thermometer-quarter:before{content:"\f2ca"}.fa-thermometer-0:before,.fa-thermometer-empty:before{content:"\f2cb"}.fa-shower:before{content:"\f2cc"}.fa-bathtub:before,.fa-s15:before,.fa-bath:before{content:"\f2cd"}.fa-podcast:before{content:"\f2ce"}.fa-window-maximize:before{content:"\f2d0"}.fa-window-minimize:before{content:"\f2d1"}.fa-window-restore:before{content:"\f2d2"}.fa-times-rectangle:before,.fa-window-close:before{content:"\f2d3"}.fa-times-rectangle-o:before,.fa-window-close-o:before{content:"\f2d4"}.fa-bandcamp:before{content:"\f2d5"}.fa-grav:before{content:"\f2d6"}.fa-etsy:before{content:"\f2d7"}.fa-imdb:before{content:"\f2d8"}.fa-ravelry:before{content:"\f2d9"}.fa-eercast:before{content:"\f2da"}.fa-microchip:before{content:"\f2db"}.fa-snowflake-o:before{content:"\f2dc"}.fa-superpowers:before{content:"\f2dd"}.fa-wpexplorer:before{content:"\f2de"}.fa-meetup:before{content:"\f2e0"}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);border:0}.sr-only-focusable:active,.sr-only-focusable:focus{position:static;width:auto;height:auto;margin:0;overflow:visible;clip:auto} diff --git a/jun_captcha_slider/src/main/webapp/lib/font-awesome/fonts/FontAwesome.otf b/jun_captcha_slider/src/main/webapp/lib/font-awesome/fonts/FontAwesome.otf new file mode 100644 index 0000000000..401ec0f36e Binary files /dev/null and b/jun_captcha_slider/src/main/webapp/lib/font-awesome/fonts/FontAwesome.otf differ diff --git a/jun_captcha_slider/src/main/webapp/lib/font-awesome/fonts/fontawesome-webfont.eot b/jun_captcha_slider/src/main/webapp/lib/font-awesome/fonts/fontawesome-webfont.eot new file mode 100644 index 0000000000..e9f60ca953 Binary files /dev/null and b/jun_captcha_slider/src/main/webapp/lib/font-awesome/fonts/fontawesome-webfont.eot differ diff --git a/jun_captcha_slider/src/main/webapp/lib/font-awesome/fonts/fontawesome-webfont.svg b/jun_captcha_slider/src/main/webapp/lib/font-awesome/fonts/fontawesome-webfont.svg new file mode 100644 index 0000000000..855c845e53 --- /dev/null +++ b/jun_captcha_slider/src/main/webapp/lib/font-awesome/fonts/fontawesome-webfont.svg @@ -0,0 +1,2671 @@ + + + + +Created by FontForge 20120731 at Mon Oct 24 17:37:40 2016 + By ,,, +Copyright Dave Gandy 2016. All rights reserved. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/jun_captcha_slider/src/main/webapp/lib/font-awesome/fonts/fontawesome-webfont.ttf b/jun_captcha_slider/src/main/webapp/lib/font-awesome/fonts/fontawesome-webfont.ttf new file mode 100644 index 0000000000..35acda2fa1 Binary files /dev/null and b/jun_captcha_slider/src/main/webapp/lib/font-awesome/fonts/fontawesome-webfont.ttf differ diff --git a/jun_captcha_slider/src/main/webapp/lib/font-awesome/fonts/fontawesome-webfont.woff b/jun_captcha_slider/src/main/webapp/lib/font-awesome/fonts/fontawesome-webfont.woff new file mode 100644 index 0000000000..400014a4b0 Binary files /dev/null and b/jun_captcha_slider/src/main/webapp/lib/font-awesome/fonts/fontawesome-webfont.woff differ diff --git a/jun_captcha_slider/src/main/webapp/lib/font-awesome/fonts/fontawesome-webfont.woff2 b/jun_captcha_slider/src/main/webapp/lib/font-awesome/fonts/fontawesome-webfont.woff2 new file mode 100644 index 0000000000..4d13fc6040 Binary files /dev/null and b/jun_captcha_slider/src/main/webapp/lib/font-awesome/fonts/fontawesome-webfont.woff2 differ diff --git a/jun_captcha_slider/src/main/webapp/lib/jquery/jquery.js b/jun_captcha_slider/src/main/webapp/lib/jquery/jquery.js new file mode 100644 index 0000000000..9b5206bcc6 --- /dev/null +++ b/jun_captcha_slider/src/main/webapp/lib/jquery/jquery.js @@ -0,0 +1,10364 @@ +/*! + * 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/jun_java_plugins/jun_aliyun_sms/src/main/webapp/js/jquery-3.4.1.js b/jun_java_plugins/jun_aliyun_sms/src/main/webapp/js/jquery-3.4.1.js deleted file mode 100644 index 773ad95c56..0000000000 --- a/jun_java_plugins/jun_aliyun_sms/src/main/webapp/js/jquery-3.4.1.js +++ /dev/null @@ -1,10598 +0,0 @@ -/*! - * jQuery JavaScript Library v3.4.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: 2019-05-01T21:04Z - */ -( 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, - nonce: true, - noModule: true - }; - - function DOMEval( code, node, doc ) { - doc = doc || document; - - var i, val, - script = doc.createElement( "script" ); - - script.text = code; - if ( node ) { - for ( i in preservedScriptAttributes ) { - - // Support: Firefox 64+, Edge 18+ - // Some browsers don't support the "nonce" property on scripts. - // On the other hand, just using `getAttribute` is not enough as - // the `nonce` attribute is reset to an empty string whenever it - // becomes browsing-context connected. - // See https://github.com/whatwg/html/issues/2369 - // See https://html.spec.whatwg.org/#nonce-attributes - // The `node.getAttribute` check was added for the sake of - // `jQuery.globalEval` so that it can fake a nonce-containing node - // via an object. - val = node[ i ] || node.getAttribute && node.getAttribute( i ); - if ( val ) { - script.setAttribute( i, val ); - } - } - } - 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.4.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 ) { - copy = options[ name ]; - - // Prevent Object.prototype pollution - // Prevent never-ending loop - if ( name === "__proto__" || target === copy ) { - continue; - } - - // Recurse if we're merging plain objects or arrays - if ( deep && copy && ( jQuery.isPlainObject( copy ) || - ( copyIsArray = Array.isArray( copy ) ) ) ) { - src = target[ name ]; - - // Ensure proper type for the source value - if ( copyIsArray && !Array.isArray( src ) ) { - clone = []; - } else if ( !copyIsArray && !jQuery.isPlainObject( src ) ) { - clone = {}; - } else { - clone = src; - } - copyIsArray = false; - - // 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 ) { - var name; - - for ( name in obj ) { - return false; - } - return true; - }, - - // Evaluates a script in a global context - globalEval: function( code, options ) { - DOMEval( code, { nonce: options && options.nonce } ); - }, - - 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.4 - * https://sizzlejs.com/ - * - * Copyright JS Foundation and other contributors - * Released under the MIT license - * https://js.foundation/ - * - * Date: 2019-04-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(), - nonnativeSelectorCache = 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 + "*" ), - rdescend = new RegExp( whitespace + "|>" ), - - 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" ) - }, - - rhtml = /HTML$/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(); - }, - - inDisabledFieldset = addCombinator( - function( elem ) { - return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset"; - }, - { 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 && - !nonnativeSelectorCache[ selector + " " ] && - (!rbuggyQSA || !rbuggyQSA.test( selector )) && - - // Support: IE 8 only - // Exclude object elements - (nodeType !== 1 || context.nodeName.toLowerCase() !== "object") ) { - - newSelector = selector; - newContext = context; - - // qSA considers elements outside a scoping root when evaluating child or - // descendant combinators, which is not what we want. - // In such cases, we work around the behavior by prefixing every selector in the - // list with an ID selector referencing the scope context. - // Thanks to Andrew Dupont for this technique. - if ( nodeType === 1 && rdescend.test( selector ) ) { - - // 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; - } - - try { - push.apply( results, - newContext.querySelectorAll( newSelector ) - ); - return results; - } catch ( qsaError ) { - nonnativeSelectorCache( selector, true ); - } 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 && - inDisabledFieldset( 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 ) { - var namespace = elem.namespaceURI, - docElem = (elem.ownerDocument || elem).documentElement; - - // Support: IE <=8 - // Assume HTML when documentElement doesn't yet exist, such as inside loading iframes - // https://bugs.jquery.com/ticket/4833 - return !rhtml.test( namespace || docElem && docElem.nodeName || "HTML" ); -}; - -/** - * 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 ); - } - - if ( support.matchesSelector && documentIsHTML && - !nonnativeSelectorCache[ 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) { - nonnativeSelectorCache( expr, true ); - } - } - - 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 || 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 > length ? - 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 ( typeof elem.contentDocument !== "undefined" ) { - 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 documentElement = document.documentElement; - - - - var isAttached = function( elem ) { - return jQuery.contains( elem.ownerDocument, elem ); - }, - composed = { composed: true }; - - // Support: IE 9 - 11+, Edge 12 - 18+, iOS 10.0 - 10.2 only - // Check attachment across shadow DOM boundaries when possible (gh-3504) - // Support: iOS 10.0-10.2 only - // Early iOS 10 versions support `attachShadow` but not `getRootNode`, - // leading to errors. We need to check for `getRootNode`. - if ( documentElement.getRootNode ) { - isAttached = function( elem ) { - return jQuery.contains( elem.ownerDocument, elem ) || - elem.getRootNode( composed ) === elem.ownerDocument; - }; - } -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. - isAttached( 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 = elem.nodeType && - ( 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, attached, 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; - } - - attached = isAttached( elem ); - - // Append to fragment - tmp = getAll( fragment.appendChild( elem ), "script" ); - - // Preserve script evaluation history - if ( attached ) { - 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 - rkeyEvent = /^key/, - rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, - rtypenamespace = /^([^.]*)(?:\.(.+)|)/; - -function returnTrue() { - return true; -} - -function returnFalse() { - return false; -} - -// Support: IE <=9 - 11+ -// focus() and blur() are asynchronous, except when they are no-op. -// So expect focus to be synchronous when the element is already active, -// and blur to be synchronous when the element is not already active. -// (focus and blur are always synchronous in other supported browsers, -// this just defines when we can count on it). -function expectSync( elem, type ) { - return ( elem === safeActiveElement() ) === ( type === "focus" ); -} - -// Support: IE <=9 only -// Accessing document.activeElement can throw unexpectedly -// https://bugs.jquery.com/ticket/13393 -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() ) { - - // If the event is namespaced, then each handler is only invoked if it is - // specially universal or its namespaces are a superset of the event's. - if ( !event.rnamespace || handleObj.namespace === false || - 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 - }, - click: { - - // Utilize native event to ensure correct state for checkable inputs - setup: function( data ) { - - // For mutual compressibility with _default, replace `this` access with a local var. - // `|| data` is dead code meant only to preserve the variable through minification. - var el = this || data; - - // Claim the first handler - if ( rcheckableType.test( el.type ) && - el.click && nodeName( el, "input" ) ) { - - // dataPriv.set( el, "click", ... ) - leverageNative( el, "click", returnTrue ); - } - - // Return false to allow normal processing in the caller - return false; - }, - trigger: function( data ) { - - // For mutual compressibility with _default, replace `this` access with a local var. - // `|| data` is dead code meant only to preserve the variable through minification. - var el = this || data; - - // Force setup before triggering a click - if ( rcheckableType.test( el.type ) && - el.click && nodeName( el, "input" ) ) { - - leverageNative( el, "click" ); - } - - // Return non-false to allow normal event-path propagation - return true; - }, - - // For cross-browser consistency, suppress native .click() on links - // Also prevent it if we're currently inside a leveraged native-event stack - _default: function( event ) { - var target = event.target; - return rcheckableType.test( target.type ) && - target.click && nodeName( target, "input" ) && - dataPriv.get( target, "click" ) || - nodeName( 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; - } - } - } - } -}; - -// Ensure the presence of an event listener that handles manually-triggered -// synthetic events by interrupting progress until reinvoked in response to -// *native* events that it fires directly, ensuring that state changes have -// already occurred before other listeners are invoked. -function leverageNative( el, type, expectSync ) { - - // Missing expectSync indicates a trigger call, which must force setup through jQuery.event.add - if ( !expectSync ) { - if ( dataPriv.get( el, type ) === undefined ) { - jQuery.event.add( el, type, returnTrue ); - } - return; - } - - // Register the controller as a special universal handler for all event namespaces - dataPriv.set( el, type, false ); - jQuery.event.add( el, type, { - namespace: false, - handler: function( event ) { - var notAsync, result, - saved = dataPriv.get( this, type ); - - if ( ( event.isTrigger & 1 ) && this[ type ] ) { - - // Interrupt processing of the outer synthetic .trigger()ed event - // Saved data should be false in such cases, but might be a leftover capture object - // from an async native handler (gh-4350) - if ( !saved.length ) { - - // Store arguments for use when handling the inner native event - // There will always be at least one argument (an event object), so this array - // will not be confused with a leftover capture object. - saved = slice.call( arguments ); - dataPriv.set( this, type, saved ); - - // Trigger the native event and capture its result - // Support: IE <=9 - 11+ - // focus() and blur() are asynchronous - notAsync = expectSync( this, type ); - this[ type ](); - result = dataPriv.get( this, type ); - if ( saved !== result || notAsync ) { - dataPriv.set( this, type, false ); - } else { - result = {}; - } - if ( saved !== result ) { - - // Cancel the outer synthetic event - event.stopImmediatePropagation(); - event.preventDefault(); - return result.value; - } - - // If this is an inner synthetic event for an event with a bubbling surrogate - // (focus or blur), assume that the surrogate already propagated from triggering the - // native event and prevent that from happening again here. - // This technically gets the ordering wrong w.r.t. to `.trigger()` (in which the - // bubbling surrogate propagates *after* the non-bubbling base), but that seems - // less bad than duplication. - } else if ( ( jQuery.event.special[ type ] || {} ).delegateType ) { - event.stopPropagation(); - } - - // If this is a native event triggered above, everything is now in order - // Fire an inner synthetic event with the original arguments - } else if ( saved.length ) { - - // ...and capture the result - dataPriv.set( this, type, { - value: jQuery.event.trigger( - - // Support: IE <=9 - 11+ - // Extend with the prototype to reset the above stopImmediatePropagation() - jQuery.extend( saved[ 0 ], jQuery.Event.prototype ), - saved.slice( 1 ), - this - ) - } ); - - // Abort handling of the native event - event.stopImmediatePropagation(); - } - } - } ); -} - -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, - code: 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 ); - -jQuery.each( { focus: "focusin", blur: "focusout" }, function( type, delegateType ) { - jQuery.event.special[ type ] = { - - // Utilize native event if possible so blur/focus sequence is correct - setup: function() { - - // Claim the first handler - // dataPriv.set( this, "focus", ... ) - // dataPriv.set( this, "blur", ... ) - leverageNative( this, type, expectSync ); - - // Return false to allow normal processing in the caller - return false; - }, - trigger: function() { - - // Force setup before trigger - leverageNative( this, type ); - - // Return non-false to allow normal event-path propagation - return true; - }, - - delegateType: delegateType - }; -} ); - -// 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 && !node.noModule ) { - jQuery._evalUrl( node.src, { - nonce: node.nonce || node.getAttribute( "nonce" ) - } ); - } - } else { - DOMEval( node.textContent.replace( rcleanScript, "" ), node, doc ); - } - } - } - } - } - } - - 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 && isAttached( 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 = isAttached( 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) - // Support: Chrome <=64 - // Don't get tricked when zoom affects offsetWidth (gh-4029) - div.style.position = "absolute"; - scrollboxSizeVal = roundPixelMeasures( div.offsetWidth / 3 ) === 12; - - 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 === "" && !isAttached( 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 cssPrefixes = [ "Webkit", "Moz", "ms" ], - emptyStyle = document.createElement( "div" ).style, - vendorProps = {}; - -// Return a vendor-prefixed property or undefined -function vendorPropName( 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 potentially-mapped jQuery.cssProps or vendor prefixed property -function finalPropName( name ) { - var final = jQuery.cssProps[ name ] || vendorProps[ name ]; - - if ( final ) { - return final; - } - if ( name in emptyStyle ) { - return name; - } - return vendorProps[ name ] = vendorPropName( name ) || name; -} - - -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" - }; - -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 - - // If offsetWidth/offsetHeight is unknown, then we can't determine content-box scroll gutter - // Use an explicit zero to avoid NaN (gh-3964) - ) ) || 0; - } - - return delta; -} - -function getWidthOrHeight( elem, dimension, extra ) { - - // Start with computed style - var styles = getStyles( elem ), - - // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-4322). - // Fake content-box until we know it's needed to know the true value. - boxSizingNeeded = !support.boxSizingReliable() || extra, - isBorderBox = boxSizingNeeded && - jQuery.css( elem, "boxSizing", false, styles ) === "border-box", - valueIsBorderBox = isBorderBox, - - val = curCSS( elem, dimension, styles ), - offsetProp = "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ); - - // Support: Firefox <=54 - // Return a confounding non-pixel value or feign ignorance, as appropriate. - if ( rnumnonpx.test( val ) ) { - if ( !extra ) { - return val; - } - val = "auto"; - } - - - // 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) - // Support: IE 9-11 only - // Also use offsetWidth/offsetHeight for when box sizing is unreliable - // We use getClientRects() to check for hidden/disconnected. - // In those cases, the computed value can be trusted to be border-box - if ( ( !support.boxSizingReliable() && isBorderBox || - val === "auto" || - !parseFloat( val ) && jQuery.css( elem, "display", false, styles ) === "inline" ) && - elem.getClientRects().length ) { - - isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; - - // Where available, offsetWidth/offsetHeight approximate border box dimensions. - // Where not available (e.g., SVG), assume unreliable box-sizing and interpret the - // retrieved value as a content box dimension. - valueIsBorderBox = offsetProp in elem; - if ( valueIsBorderBox ) { - val = elem[ offsetProp ]; - } - } - - // 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, - "gridArea": true, - "gridColumn": true, - "gridColumnEnd": true, - "gridColumnStart": true, - "gridRow": true, - "gridRowEnd": true, - "gridRowStart": 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) - // The isCustomProp check can be removed in jQuery 4.0 when we only auto-append - // "px" to a few hardcoded values. - if ( type === "number" && !isCustomProp ) { - 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 ), - - // Only read styles.position if the test has a chance to fail - // to avoid forcing a reflow. - scrollboxSizeBuggy = !support.scrollboxSize() && - styles.position === "absolute", - - // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-3991) - boxSizingNeeded = scrollboxSizeBuggy || extra, - isBorderBox = boxSizingNeeded && - jQuery.css( elem, "boxSizing", false, styles ) === "border-box", - subtract = extra ? - boxModelAdjustment( - elem, - dimension, - extra, - isBorderBox, - styles - ) : - 0; - - // 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 && scrollboxSizeBuggy ) { - 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 && ( - jQuery.cssHooks[ tween.prop ] || - tween.elem.style[ finalPropName( tween.prop ) ] != null ) ) { - 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 ( a == null ) { - return ""; - } - - // 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() + " " ] = - ( responseHeaders[ match[ 1 ].toLowerCase() + " " ] || [] ) - .concat( match[ 2 ] ); - } - } - match = responseHeaders[ key.toLowerCase() + " " ]; - } - return match == null ? null : match.join( ", " ); - }, - - // 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, options ) { - 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, - - // Only evaluate the response if it is successful (gh-4126) - // dataFilter is not invoked for failure responses, so using it instead - // of the default converter is kludgy but it works. - converters: { - "text script": function() {} - }, - dataFilter: function( response ) { - jQuery.globalEval( response, options ); - } - } ); -}; - - -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 or forced-by-attrs requests - if ( s.crossDomain || s.scriptAttrs ) { - var script, callback; - return { - send: function( _, complete ) { - script = jQuery( " - - - - - - - -

数据库名称:renren

- -
-

目录

- -
-
- - - - - - - - - - -
- -
- - - - - - - - - - - - - - - -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- - - -
- -
- - - - - -
- -
- -
- -
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_db_document/doc/html.gif b/jun_java_plugins/jun_db_document/doc/html.gif deleted file mode 100644 index 19d134e7e5..0000000000 Binary files a/jun_java_plugins/jun_db_document/doc/html.gif and /dev/null differ diff --git a/jun_java_plugins/jun_db_document/pom.xml b/jun_java_plugins/jun_db_document/pom.xml deleted file mode 100644 index 803be72e5a..0000000000 --- a/jun_java_plugins/jun_db_document/pom.xml +++ /dev/null @@ -1,89 +0,0 @@ - - - 4.0.0 - - io.github.wujun728 - jun_db_document - 1.0 - jar - - 数据库文档生成工具 - - - org.springframework.boot - spring-boot-starter-parent - 2.0.3.RELEASE - - - - - UTF-8 - UTF-8 - 1.8 - 1.0.5 - 2.1.8 - - - - - org.springframework.boot - spring-boot-starter - - - - org.springframework.boot - spring-boot-starter-jdbc - - - - - mysql - mysql-connector-java - runtime - - - org.freemarker - freemarker - - - org.springframework.boot - spring-boot-starter-test - test - - - - org.springframework.boot - spring-boot-configuration-processor - true - - - org.apache.commons - commons-lang3 - 3.4 - - - commons-io - commons-io - 2.3 - - - org.apache.poi - poi - 3.17 - - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - diff --git a/jun_java_plugins/jun_db_document/readme.md b/jun_java_plugins/jun_db_document/readme.md deleted file mode 100644 index f2aaf5a325..0000000000 --- a/jun_java_plugins/jun_db_document/readme.md +++ /dev/null @@ -1,59 +0,0 @@ -数据库文档生成工具 -==== - 简单配置,就能够生成数据库文档。欢迎大家提意见 - -使用方法 ----- - 1.修改application.properties的数据库配置信息 - 2.修改application.properties中的属性 application.generator中的信息 - 3.运行Application.java - 4.生成文件的格式类似2018-03-07_05-45-453.xls - -使用的框架 ----- - 1.spring boot - 2.spring jdbc - 3.freemaker - -支持的数据库 ----- - 1.mysql - -支持生成的文档类型 ----- - 1.word,不太好看,但是可以修改文档,v.15移除,不再支持 - 2.excel,还算好看吧,可以修改文档 - 3.html,最好看了,ヾ(◍°∇°◍)ノ゙,但是不能修改 - -如何扩展已支持更多数据库 ----- - 1.在pom.xml加入数据库驱动包 - 2.修改application.properties的数据库配置信息 - 3.创建一个新的类,继承cn.wuwenyao.db.doc.generator.dao.impl.AbstractDbInfoDao - 4.在枚举类cn.wuwenyao.db.doc.generator.enums.DbType增加一个新的枚举 - -如何扩展已支持更多的生成文档类型 ----- - 1.创建一个新的类,继承cn.wuwenyao.db.doc.generator.service.impl.AbstractGeneratorServiceImpl - 2.在枚举类cn.wuwenyao.db.doc.generator.enums.TargetFileType中增加一个新的枚举 - -更新日志 ----- - 1.v1.0,完成基本架构,支持生成word文档 - 2.v1.1,优化架构,支持生成excel文档,比word文档好看点,笑 - 3.v1.2,支持生成html文档 - 4.v1.3,增加索引信息的生成 - 5.v1.3.1 增加新的html模板,优化生成文档的速度 - 6.v1.3.2 支持白名单和黑名单,优化excel模板 - -效果图 ----- - ![Excel例子](https://gitee.com/shiqiyue/dbDocGenerator/raw/master/doc/excel.gif "例子") - ![Html例子](https://gitee.com/shiqiyue/dbDocGenerator/raw/master/doc/html.gif "例子") - ![Html例子](https://gitee.com/shiqiyue/dbDocGenerator/raw/master/doc/html-menu.gif "例子") -样例下载 ----- - 1.[WORD样例](http://gitee.com/shiqiyue/dbDocGenerator/tree/master/doc/word-sample.doc) - 2.[EXCEL样例](http://gitee.com/shiqiyue/dbDocGenerator/tree/master/doc/excel-sample.xls) - 3.[HTML样例](http://gitee.com/shiqiyue/dbDocGenerator/tree/master/doc/html-sample.html) - \ No newline at end of file diff --git a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/Application.java b/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/Application.java deleted file mode 100644 index 20c3a1e70e..0000000000 --- a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/Application.java +++ /dev/null @@ -1,48 +0,0 @@ -package cn.wuwenyao.db.doc.generator; - -import cn.wuwenyao.db.doc.generator.service.GeneratorService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.CommandLineRunner; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.context.properties.EnableConfigurationProperties; - -import cn.wuwenyao.db.doc.generator.config.ApplicationConfig; - -import static org.slf4j.LoggerFactory.getLogger; - -/*** - * 应用启动 - * - * @author wwy - * - */ -@EnableConfigurationProperties({ ApplicationConfig.class }) -@SpringBootApplication -public class Application implements CommandLineRunner { - - private GeneratorService generatorService; - - private static final Logger logger = getLogger(Application.class); - - public Application(GeneratorService generatorService) { - this.generatorService = generatorService; - } - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - - @Override - public void run(String... args) throws Exception { - // 生成doc - try { - generatorService.generate(); - } catch (Exception e) { - logger.error("生成数据库文档错误", e); - return; - } - logger.info("生成数据库文档成功"); - } -} diff --git a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/config/ApplicationConfig.java b/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/config/ApplicationConfig.java deleted file mode 100644 index a7f6fbb3fe..0000000000 --- a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/config/ApplicationConfig.java +++ /dev/null @@ -1,25 +0,0 @@ -package cn.wuwenyao.db.doc.generator.config; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.context.properties.NestedConfigurationProperty; - -/*** - * 应用配置信息 - * - * @author wwy shiqiyue.github.com - * - */ -@ConfigurationProperties(prefix = "application") -public class ApplicationConfig { - - @NestedConfigurationProperty - private GeneratorConfig generator = new GeneratorConfig(); - - public GeneratorConfig getGenerator() { - return generator; - } - - public void setGenerator(GeneratorConfig generator) { - this.generator = generator; - } -} diff --git a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/config/GeneratorConfig.java b/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/config/GeneratorConfig.java deleted file mode 100644 index 8848c69e99..0000000000 --- a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/config/GeneratorConfig.java +++ /dev/null @@ -1,95 +0,0 @@ -package cn.wuwenyao.db.doc.generator.config; - -import cn.wuwenyao.db.doc.generator.enums.DbType; -import cn.wuwenyao.db.doc.generator.enums.TargetFileType; - -import java.util.ArrayList; -import java.util.List; - -/*** - * 生成器配置信息 - * - * @author wwy shiqiyue.github.com - * - */ -public class GeneratorConfig { - - /*** - * 数据库类型 - */ - private DbType dbtype = DbType.MYSQL; - - /*** - * 生成文件类型 - */ - private TargetFileType targetFileType = TargetFileType.WORD; - - /*** - * 生成文件目录 - */ - private String targetFileDir = ""; - - /*** - * 模板文件地址 - */ - private String templateFilePath = ""; - - /*** - * 黑名单,支持正则表达式 - */ - private List blacklist = new ArrayList<>(); - - /*** - * 白名单,支持正则表达式 - */ - private List whitelist = new ArrayList<>(); - - public DbType getDbtype() { - return dbtype; - } - - public void setDbtype(DbType dbtype) { - this.dbtype = dbtype; - } - - public TargetFileType getTargetFileType() { - return targetFileType; - } - - public void setTargetFileType(TargetFileType targetFileType) { - this.targetFileType = targetFileType; - } - - public String getTargetFileDir() { - return targetFileDir; - } - - public void setTargetFileDir(String targetFileDir) { - this.targetFileDir = targetFileDir; - } - - - public String getTemplateFilePath() { - return templateFilePath; - } - - public void setTemplateFilePath(String templateFilePath) { - this.templateFilePath = templateFilePath; - } - - public List getBlacklist() { - return blacklist; - } - - public void setBlacklist(List blacklist) { - this.blacklist = blacklist; - } - - public List getWhitelist() { - return whitelist; - } - - public void setWhitelist(List whitelist) { - this.whitelist = whitelist; - } -} diff --git a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/config/GeneratorConfiguration.java b/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/config/GeneratorConfiguration.java deleted file mode 100644 index 170292d8de..0000000000 --- a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/config/GeneratorConfiguration.java +++ /dev/null @@ -1,44 +0,0 @@ -package cn.wuwenyao.db.doc.generator.config; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.jdbc.core.JdbcTemplate; - -import cn.wuwenyao.db.doc.generator.dao.DbInfoDao; -import cn.wuwenyao.db.doc.generator.service.GeneratorService; - -/*** - * 生成器配置 - * - * @author wwy shiqiyue.github.com - * - */ -@Configuration -public class GeneratorConfiguration { - - @Autowired - private ApplicationConfig applicationConfig; - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Bean - public DbInfoDao dbInfoDao() throws InstantiationException, IllegalAccessException { - DbInfoDao dbInfoDao = (DbInfoDao) applicationConfig.getGenerator().getDbtype().getDbInfoDaoImpl().newInstance(); - dbInfoDao.setJdbcTemplate(jdbcTemplate); - dbInfoDao.setApplicationConfig(applicationConfig); - return dbInfoDao; - } - - @Bean - public GeneratorService generatorService(DbInfoDao dbInfoDao) - throws InstantiationException, IllegalAccessException { - GeneratorService generatorService = (GeneratorService) applicationConfig.getGenerator().getTargetFileType() - .getGeneratorServiceImpl().newInstance(); - generatorService.setDbInfoDao(dbInfoDao); - generatorService.setGeneratorConfig(applicationConfig.getGenerator()); - return generatorService; - } - -} diff --git a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/dao/DbInfoDao.java b/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/dao/DbInfoDao.java deleted file mode 100644 index 9aa81e329e..0000000000 --- a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/dao/DbInfoDao.java +++ /dev/null @@ -1,44 +0,0 @@ -package cn.wuwenyao.db.doc.generator.dao; - -import cn.wuwenyao.db.doc.generator.config.ApplicationConfig; -import cn.wuwenyao.db.doc.generator.entity.TableInfo; -import org.springframework.jdbc.core.JdbcTemplate; - -import java.util.List; - -/*** - * 获取数据库信息的dao接口 - * - * @author wwy - * - */ -public interface DbInfoDao { - - /**** - * 获取数据库名称 - * - * @return - */ - public String databaseName(); - - /*** - * 获取表的信息 - * - * @return - */ - public List tableInfoList(); - - /*** - * 设置jdbcTemplate - * - * @param jdbcTemplate - */ - public void setJdbcTemplate(JdbcTemplate jdbcTemplate); - - /*** - * 设置配置信息 - * @param applicationConfig - */ - public void setApplicationConfig(ApplicationConfig applicationConfig); - -} diff --git a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/dao/impl/PackageInfo.java b/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/dao/impl/PackageInfo.java deleted file mode 100644 index 888c89be50..0000000000 --- a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/dao/impl/PackageInfo.java +++ /dev/null @@ -1,9 +0,0 @@ -package cn.wuwenyao.db.doc.generator.dao.impl; - -/*** - * - * @author wenyao.wu - * @date 2019/1/30 - */ -public class PackageInfo { -} diff --git a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/dao/impl/dbinfo/AbstractDbInfoDao.java b/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/dao/impl/dbinfo/AbstractDbInfoDao.java deleted file mode 100644 index e85807fcc4..0000000000 --- a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/dao/impl/dbinfo/AbstractDbInfoDao.java +++ /dev/null @@ -1,97 +0,0 @@ -package cn.wuwenyao.db.doc.generator.dao.impl.dbinfo; - -import cn.wuwenyao.db.doc.generator.config.ApplicationConfig; -import cn.wuwenyao.db.doc.generator.dao.DbInfoDao; -import cn.wuwenyao.db.doc.generator.entity.TableInfo; -import org.apache.commons.collections4.CollectionUtils; -import org.springframework.jdbc.core.JdbcTemplate; - -import java.util.List; - -/*** - * 获取数据库信息的dao实现-抽象基类 - * - * @author wwy shiqiyue.github.com - * - */ -public abstract class AbstractDbInfoDao implements DbInfoDao { - - protected JdbcTemplate jdbcTemplate; - - protected ApplicationConfig applicationConfig; - - - /*** - * 判断表是否可以生成 - * @param tableName - * @return - */ - protected boolean isTableGenerate(String tableName) { - if (matchWhiteList(tableName)) { - return true; - } - if (matchBlackList(tableName)) { - return false; - } - return true; - } - - /*** - * 是否匹配白名单 - * @param tableName - * @return - */ - private Boolean matchWhiteList(String tableName) { - List whiteList = applicationConfig.getGenerator().getWhitelist(); - if (CollectionUtils.isNotEmpty(whiteList)) { - for (String whiteItem : whiteList) { - if (tableName.matches(whiteItem)) { - return true; - } - } - } - return false; - } - - /*** - * 是否匹配黑名单 - * @param tableName - * @return - */ - private Boolean matchBlackList(String tableName) { - List blackList = applicationConfig.getGenerator().getBlacklist(); - if (CollectionUtils.isEmpty(blackList)) { - return false; - } - for (String blackItem : blackList) { - if (tableName.matches(blackItem)) { - return true; - } - } - - return false; - } - - - @Override - public String databaseName() { - return null; - } - - @Override - public List tableInfoList() { - return null; - } - - @Override - public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { - this.jdbcTemplate = jdbcTemplate; - } - - @Override - public void setApplicationConfig(ApplicationConfig applicationConfig) { - this.applicationConfig = applicationConfig; - } - - -} diff --git a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/dao/impl/dbinfo/mysql/GetTableInfoTask.java b/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/dao/impl/dbinfo/mysql/GetTableInfoTask.java deleted file mode 100644 index 62d0833f73..0000000000 --- a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/dao/impl/dbinfo/mysql/GetTableInfoTask.java +++ /dev/null @@ -1,98 +0,0 @@ -package cn.wuwenyao.db.doc.generator.dao.impl.dbinfo.mysql; - -import cn.wuwenyao.db.doc.generator.entity.TableFieldInfo; -import cn.wuwenyao.db.doc.generator.entity.TableInfo; -import cn.wuwenyao.db.doc.generator.entity.TableKeyInfo; -import org.slf4j.Logger; -import org.springframework.jdbc.core.ColumnMapRowMapper; -import org.springframework.jdbc.core.JdbcTemplate; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CountDownLatch; - -import static org.slf4j.LoggerFactory.getLogger; - -/*** - * 任务-获取表信息 - * @author wenyao.wu - * @date 2019/1/30 - */ -public class GetTableInfoTask implements Runnable { - - private static final Logger logger = getLogger(GetTableInfoTask.class); - - private TableInfo tableInfo; - - private CountDownLatch countDownLatch; - - private JdbcTemplate jdbcTemplate; - - public GetTableInfoTask(TableInfo tableInfo, CountDownLatch countDownLatch, JdbcTemplate jdbcTemplate) { - this.tableInfo = tableInfo; - this.countDownLatch = countDownLatch; - this.jdbcTemplate = jdbcTemplate; - } - - - @Override - public void run() { - try { - tableInfo.setFields(queryFields()); - tableInfo.setKeys(queryKeys()); - logger.info("表:{}信息查询完毕", tableInfo.getTableName()); - } catch (Exception e) { - logger.error("任务-获取表信息-异常", e); - } finally { - countDownLatch.countDown(); - } - - } - - /*** - * 查询 fields - * @return - */ - private List queryFields() { - Object[] params = new Object[]{tableInfo.getTableName()}; - List fields = jdbcTemplate.query( - "select COLUMN_NAME, COLUMN_COMMENT,COLUMN_DEFAULT,IS_NULLABLE,COLUMN_TYPE,COLUMN_KEY,EXTRA from information_schema.columns where table_schema =database() and table_name = ?", - params, new TableFieldInfoRowMapper()); - return fields; - } - - /*** - * 查询 索引 - * @return - */ - private List queryKeys() { - List> rawKeyInfos = jdbcTemplate.query("show keys from " + tableInfo.getTableName(), - new ColumnMapRowMapper()); - - Map keyMap = new HashMap<>(5); - for (Map rawKeyInfo : rawKeyInfos) { - TableKeyInfo tableKeyInfo = keyMap.get(rawKeyInfo.get("Key_name").toString()); - String columnName = rawKeyInfo.get("Column_name").toString(); - if (tableKeyInfo == null) { - tableKeyInfo = new TableKeyInfo(); - ArrayList columns = new ArrayList<>(); - columns.add(columnName); - tableKeyInfo.setColumns(columns); - tableKeyInfo.setIndexComment(rawKeyInfo.get("Index_comment").toString()); - tableKeyInfo.setIndexType(rawKeyInfo.get("Index_type").toString()); - tableKeyInfo.setName(rawKeyInfo.get("Key_name").toString()); - tableKeyInfo.setUnique("0".equals(rawKeyInfo.get("Non_unique").toString())); - } else { - tableKeyInfo.getColumns().add(columnName); - } - keyMap.put(rawKeyInfo.get("Key_name").toString(), tableKeyInfo); - } - //索引信息进行排序 - List tableKeyInfoList = new ArrayList<>(keyMap.values()); - tableKeyInfoList.sort(null); - return tableKeyInfoList; - } - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/dao/impl/dbinfo/mysql/MysqlDbInfoDao.java b/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/dao/impl/dbinfo/mysql/MysqlDbInfoDao.java deleted file mode 100644 index 787466b394..0000000000 --- a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/dao/impl/dbinfo/mysql/MysqlDbInfoDao.java +++ /dev/null @@ -1,67 +0,0 @@ -package cn.wuwenyao.db.doc.generator.dao.impl.dbinfo.mysql; - -import cn.wuwenyao.db.doc.generator.dao.impl.dbinfo.AbstractDbInfoDao; -import cn.wuwenyao.db.doc.generator.entity.TableInfo; -import org.apache.commons.collections4.CollectionUtils; -import org.slf4j.Logger; - -import java.util.List; -import java.util.concurrent.*; -import java.util.stream.Collectors; - -import static org.slf4j.LoggerFactory.getLogger; - -/*** - * 获取mysql数据库信息 - * - * @author wwy - * - */ - -public final class MysqlDbInfoDao extends AbstractDbInfoDao { - - - private static final Logger logger = getLogger(MysqlDbInfoDao.class); - - @Override - public String databaseName() { - String databaseName = jdbcTemplate.queryForObject("select database()", String.class); - return databaseName; - } - - private List queryTableInfo() { - List tableInfos = jdbcTemplate.query( - "select table_name,table_comment from information_schema.tables where table_schema = database()", - new TableInfoRowMapper()); - return tableInfos; - } - - @Override - public List tableInfoList() { - //查询表信息 - List tableInfos = queryTableInfo(); - if (CollectionUtils.isEmpty(tableInfos)) { - return tableInfos; - } - //过滤黑名单 - tableInfos = tableInfos.stream().filter(tableInfo -> { - return isTableGenerate(tableInfo.getTableName()); - }).collect(Collectors.toList()); - //查询表-列信息 - CountDownLatch countDownLatch = new CountDownLatch(tableInfos.size()); - ExecutorService executor = new ThreadPoolExecutor(10, 10, - 0L, TimeUnit.MILLISECONDS, - new LinkedBlockingQueue(tableInfos.size())); - tableInfos.stream().forEach((tableInfo) -> { - executor.execute(new GetTableInfoTask(tableInfo, countDownLatch, jdbcTemplate)); - }); - try { - countDownLatch.await(); - } catch (InterruptedException e) { - logger.error("countDownLatch error", e); - } - executor.shutdown(); - return tableInfos; - } - -} diff --git a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/dao/impl/dbinfo/mysql/TableFieldInfoRowMapper.java b/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/dao/impl/dbinfo/mysql/TableFieldInfoRowMapper.java deleted file mode 100644 index 543b3b3e7f..0000000000 --- a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/dao/impl/dbinfo/mysql/TableFieldInfoRowMapper.java +++ /dev/null @@ -1,32 +0,0 @@ -package cn.wuwenyao.db.doc.generator.dao.impl.dbinfo.mysql; - -import cn.wuwenyao.db.doc.generator.entity.TableFieldInfo; -import org.springframework.jdbc.core.RowMapper; - -import java.sql.ResultSet; -import java.sql.SQLException; - -/*** - * 列信息RowMapper - * @author wenyao.wu - * @date 2019/1/30 - */ -public class TableFieldInfoRowMapper implements RowMapper { - - @Override - public TableFieldInfo mapRow(ResultSet rs, int rowNum) throws SQLException { - TableFieldInfo tableFieldInfo = new TableFieldInfo(); - tableFieldInfo.setDefaultValue(rs.getString("COLUMN_DEFAULT")); - tableFieldInfo.setExtra(rs.getString("EXTRA")); - tableFieldInfo.setField(rs.getString("COLUMN_NAME")); - tableFieldInfo.setKey(rs.getString("COLUMN_KEY")); - tableFieldInfo.setNullAble(rs.getString("IS_NULLABLE")); - tableFieldInfo.setType(rs.getString("COLUMN_TYPE")); - tableFieldInfo.setRemark(rs.getString("COLUMN_COMMENT")); - if (tableFieldInfo.getDefaultValue() == null) { - tableFieldInfo.setDefaultValue("无"); - } - return tableFieldInfo; - } - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/dao/impl/dbinfo/mysql/TableInfoRowMapper.java b/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/dao/impl/dbinfo/mysql/TableInfoRowMapper.java deleted file mode 100644 index 67717badc3..0000000000 --- a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/dao/impl/dbinfo/mysql/TableInfoRowMapper.java +++ /dev/null @@ -1,26 +0,0 @@ -package cn.wuwenyao.db.doc.generator.dao.impl.dbinfo.mysql; - -import cn.wuwenyao.db.doc.generator.entity.TableInfo; -import org.springframework.jdbc.core.RowMapper; - -import java.sql.ResultSet; -import java.sql.SQLException; - -/*** - * 表信息RowMapper - * @author wenyao.wu - * @date 2019/1/30 - */ -public class TableInfoRowMapper implements RowMapper { - - @Override - public TableInfo mapRow(ResultSet rs, int rowNum) throws SQLException { - String tableName = rs.getString(1); - String remark = rs.getString(2); - TableInfo tableInfo = new TableInfo(); - tableInfo.setTableRemark(remark); - tableInfo.setTableName(tableName); - return tableInfo; - } - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/entity/TableFieldInfo.java b/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/entity/TableFieldInfo.java deleted file mode 100644 index d06fbdd816..0000000000 --- a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/entity/TableFieldInfo.java +++ /dev/null @@ -1,102 +0,0 @@ -package cn.wuwenyao.db.doc.generator.entity; - -/*** - * 列信息 - * - * @author wwy - * - */ -public class TableFieldInfo { - - /*** - * 列名 - */ - private String field; - - /*** - * 类型 - */ - private String type; - - /*** - * 是否能为空 - */ - private String nullAble; - - /*** - * 键 - */ - private String key; - - /*** - * 默认值 - */ - private String defaultValue; - - /*** - * 额外信息 - */ - private String extra; - - /*** - * 备注信息 - */ - private String remark; - - public String getField() { - return field; - } - - public void setField(String field) { - this.field = field; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getNullAble() { - return nullAble; - } - - public void setNullAble(String nullAble) { - this.nullAble = nullAble; - } - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - public String getDefaultValue() { - return defaultValue; - } - - public void setDefaultValue(String defaultValue) { - this.defaultValue = defaultValue; - } - - public String getExtra() { - return extra; - } - - public void setExtra(String extra) { - this.extra = extra; - } - - public String getRemark() { - return remark; - } - - public void setRemark(String remark) { - this.remark = remark; - } - -} diff --git a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/entity/TableInfo.java b/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/entity/TableInfo.java deleted file mode 100644 index b22099fd98..0000000000 --- a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/entity/TableInfo.java +++ /dev/null @@ -1,65 +0,0 @@ -package cn.wuwenyao.db.doc.generator.entity; - -import java.util.List; - -/*** - * 表信息 - * - * @author wwy - * - */ -public class TableInfo { - - /*** - * 表名 - */ - private String tableName; - - /*** - * 备注信息 - */ - private String tableRemark; - - /*** - * 列 - */ - private List fields; - - /** - * 索引信息 - */ - private List keys; - - public String getTableName() { - return tableName; - } - - public void setTableName(String tableName) { - this.tableName = tableName; - } - - public List getFields() { - return fields; - } - - public void setFields(List fields) { - this.fields = fields; - } - - public String getTableRemark() { - return tableRemark; - } - - public void setTableRemark(String tableRemark) { - this.tableRemark = tableRemark; - } - - public List getKeys() { - return keys; - } - - public void setKeys(List keys) { - this.keys = keys; - } - -} diff --git a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/entity/TableKeyInfo.java b/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/entity/TableKeyInfo.java deleted file mode 100644 index 3a5217a28e..0000000000 --- a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/entity/TableKeyInfo.java +++ /dev/null @@ -1,106 +0,0 @@ -package cn.wuwenyao.db.doc.generator.entity; - -import java.util.List; - -import org.apache.commons.lang3.StringUtils; - -/*** - * 表的索引信息 - * - * @author wwy - * - */ -public class TableKeyInfo implements Comparable{ - - public static final String PRIMARY_KEY = "PRIMARY"; - - - /*** - * 索引名称 - */ - private String name; - - /*** - * 包含那些字段 - */ - private List columns; - - /*** - * 是否唯一 - */ - private Boolean unique; - - /*** - * 索引类型 - */ - private String indexType; - - /*** - * 索引注释 - */ - private String indexComment; - - public TableKeyInfo() { - - } - - public String getColumnCombine() { - return StringUtils.join(columns, ","); - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getColumns() { - return columns; - } - - public void setColumns(List columns) { - this.columns = columns; - } - - public Boolean getUnique() { - return unique; - } - - public void setUnique(Boolean unique) { - this.unique = unique; - } - - public String getIndexType() { - return indexType; - } - - public void setIndexType(String indexType) { - this.indexType = indexType; - } - - public String getIndexComment() { - return indexComment; - } - - public void setIndexComment(String indexComment) { - this.indexComment = indexComment; - } - - @Override - public int compareTo(Object o) { - if(this.equals(o)){ - return 0; - } - TableKeyInfo keyInfo2 = (TableKeyInfo) o; - String name2 = keyInfo2.getName(); - if(PRIMARY_KEY.equalsIgnoreCase(this.name)){ - return -1; - } - if(PRIMARY_KEY.equalsIgnoreCase(name2)){ - return 1; - } - return this.name.compareTo(name2); - } -} diff --git a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/enums/DbType.java b/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/enums/DbType.java deleted file mode 100644 index a0edbd98cb..0000000000 --- a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/enums/DbType.java +++ /dev/null @@ -1,26 +0,0 @@ -package cn.wuwenyao.db.doc.generator.enums; - - -import cn.wuwenyao.db.doc.generator.dao.impl.dbinfo.mysql.MysqlDbInfoDao; - -/*** - * 数据库类型 - * - * @author wwy shiqiyue.github.com - * - */ -public enum DbType { - /** mysql */ - MYSQL(MysqlDbInfoDao.class); - - private Class dbInfoDaoImpl; - - private DbType(Class dbInfoDaoImpl) { - this.dbInfoDaoImpl = dbInfoDaoImpl; - } - - public Class getDbInfoDaoImpl() { - return dbInfoDaoImpl; - } - -} diff --git a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/enums/TargetFileType.java b/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/enums/TargetFileType.java deleted file mode 100644 index 49286e7fdb..0000000000 --- a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/enums/TargetFileType.java +++ /dev/null @@ -1,34 +0,0 @@ -package cn.wuwenyao.db.doc.generator.enums; - -import cn.wuwenyao.db.doc.generator.service.impl.ExcelGeneratorServiceImpl; -import cn.wuwenyao.db.doc.generator.service.impl.HtmlGeneratorServiceImpl; -import cn.wuwenyao.db.doc.generator.service.impl.WordGeneratorServiceImpl; - -/*** - * 生成文件类型 - * - * @author wwy shiqiyue.github.com - * - */ -public enum TargetFileType { - - /** word文档 */ - WORD(WordGeneratorServiceImpl.class), - /** excel文档 */ - EXCEL(ExcelGeneratorServiceImpl.class), - /** html文档 */ - HTML(HtmlGeneratorServiceImpl.class) - - ; - - private Class generatorServiceImpl; - - private TargetFileType(Class generatorServiceImpl) { - this.generatorServiceImpl = generatorServiceImpl; - } - - public Class getGeneratorServiceImpl() { - return generatorServiceImpl; - } - -} diff --git a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/service/GeneratorService.java b/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/service/GeneratorService.java deleted file mode 100644 index 0217d3a447..0000000000 --- a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/service/GeneratorService.java +++ /dev/null @@ -1,42 +0,0 @@ -package cn.wuwenyao.db.doc.generator.service; - -import cn.wuwenyao.db.doc.generator.config.GeneratorConfig; -import cn.wuwenyao.db.doc.generator.dao.DbInfoDao; - -/*** - * 生成文件-服务 - * - * @author wwy shiqiyue.github.com - * - */ -public interface GeneratorService { - - - /*** - * 生成 - * @throws Exception - */ - void generate() throws Exception; - - /*** - * 生成数据库文档 - * - * @throws Exception - */ - void generateDbDoc() throws Exception; - - /*** - * 设置数据库信息Dao - * - * @param dbInfoDao - */ - public void setDbInfoDao(DbInfoDao dbInfoDao); - - /*** - * 设置配置信息 - * - * @param generatorConfig - */ - public void setGeneratorConfig(GeneratorConfig generatorConfig); - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/service/impl/AbstractGeneratorServiceImpl.java b/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/service/impl/AbstractGeneratorServiceImpl.java deleted file mode 100644 index e2aef4729f..0000000000 --- a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/service/impl/AbstractGeneratorServiceImpl.java +++ /dev/null @@ -1,75 +0,0 @@ -package cn.wuwenyao.db.doc.generator.service.impl; - -import cn.wuwenyao.db.doc.generator.config.GeneratorConfig; -import cn.wuwenyao.db.doc.generator.dao.DbInfoDao; -import cn.wuwenyao.db.doc.generator.service.GeneratorService; -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang3.time.DateFormatUtils; - -import java.io.File; -import java.io.IOException; -import java.util.Date; -import java.util.Random; - -/*** - * 文档生成服务-抽象基类 - * - * @author wwy shiqiyue.github.com - * - */ -public abstract class AbstractGeneratorServiceImpl implements GeneratorService { - - protected DbInfoDao dbInfoDao; - - protected GeneratorConfig generatorConfig; - - /** - * windows系统名称前缀 - */ - private static final String SYSTEM_WINDOWS_PREFIX = "win"; - - - @Override - public void generate() throws Exception { - generateDbDoc(); - openDir(); - } - - /*** - * 打开目录 - */ - private void openDir() throws IOException { - // 弹出目标文件夹 - String os = System.getProperty("os.name"); - if (os.toLowerCase().startsWith(SYSTEM_WINDOWS_PREFIX)) { - Runtime.getRuntime().exec("explorer " + generatorConfig.getTargetFileDir()); - } - - } - - /*** - * 创建文件 - * @param fileSuffix 文件后缀 - * @return - */ - protected File createFile(String fileSuffix) throws IOException { - File dir = new File(generatorConfig.getTargetFileDir()); - FileUtils.forceMkdir(dir); - Random random = new Random(); - String filename = DateFormatUtils.format(new Date(), "yyyy-MM-dd_hh-mm-ss") + random.nextInt(10) + "." + fileSuffix; - File file = new File(dir, filename); - return file; - } - - @Override - public void setDbInfoDao(DbInfoDao dbInfoDao) { - this.dbInfoDao = dbInfoDao; - } - - @Override - public void setGeneratorConfig(GeneratorConfig generatorConfig) { - this.generatorConfig = generatorConfig; - } - - -} diff --git a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/service/impl/ExcelGeneratorServiceImpl.java b/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/service/impl/ExcelGeneratorServiceImpl.java deleted file mode 100644 index 372771219d..0000000000 --- a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/service/impl/ExcelGeneratorServiceImpl.java +++ /dev/null @@ -1,256 +0,0 @@ -package cn.wuwenyao.db.doc.generator.service.impl; - -import cn.wuwenyao.db.doc.generator.entity.TableFieldInfo; -import cn.wuwenyao.db.doc.generator.entity.TableInfo; -import cn.wuwenyao.db.doc.generator.entity.TableKeyInfo; -import org.apache.poi.common.usermodel.HyperlinkType; -import org.apache.poi.hssf.usermodel.*; -import org.apache.poi.hssf.util.HSSFColor; -import org.apache.poi.ss.usermodel.*; - -import java.io.File; -import java.io.FileOutputStream; -import java.util.List; - -/*** - * 生成文档服务-excel实现 - * - * @author wwy - * - */ -public final class ExcelGeneratorServiceImpl extends AbstractGeneratorServiceImpl { - - /*** - * excel对象 - */ - private HSSFWorkbook workbook; - - /*** - * 标题样式 - */ - private HSSFCellStyle titleCellStyle; - - /*** - * 一般样式 - */ - private HSSFCellStyle simpleCellStyle; - - /*** - * 链接样式 - */ - private HSSFCellStyle linkCellStyle; - - /*** - * 目录sheet的名称 - */ - private String indexSheetName = "目录"; - - - public ExcelGeneratorServiceImpl() { - workbook = new HSSFWorkbook(); - initCellStyle(); - } - - /*** - * 初始化样式 - */ - public void initCellStyle() { - // 创建标题样式 - titleCellStyle = workbook.createCellStyle(); - HSSFFont titleFont = workbook.createFont(); - titleFont.setFontName("微软雅黑"); - titleFont.setBold(false); - titleFont.setFontHeightInPoints((short) 20); - titleCellStyle.setFont(titleFont); - titleCellStyle.setBorderLeft(BorderStyle.THIN); - titleCellStyle.setBorderRight(BorderStyle.THIN); - titleCellStyle.setBorderTop(BorderStyle.THIN); - titleCellStyle.setBorderBottom(BorderStyle.THIN); - titleCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); - titleCellStyle.setFillForegroundColor(HSSFColor.HSSFColorPredefined.CORAL.getIndex()); - - // 创建一般样式 - simpleCellStyle = workbook.createCellStyle(); - simpleCellStyle.setBorderLeft(BorderStyle.THIN); - simpleCellStyle.setBorderRight(BorderStyle.THIN); - simpleCellStyle.setBorderTop(BorderStyle.THIN); - simpleCellStyle.setBorderBottom(BorderStyle.THIN); - HSSFFont simpleFont = workbook.createFont(); - simpleFont.setFontName("微软雅黑"); - simpleFont.setFontHeightInPoints((short) 16); - simpleCellStyle.setFont(simpleFont); - - // 创建超链接样式 - linkCellStyle = workbook.createCellStyle(); - linkCellStyle.setBorderLeft(BorderStyle.THIN); - linkCellStyle.setBorderRight(BorderStyle.THIN); - linkCellStyle.setBorderTop(BorderStyle.THIN); - linkCellStyle.setBorderBottom(BorderStyle.THIN); - HSSFFont linkFont = workbook.createFont(); - linkFont.setFontName("YAHEI"); - linkFont.setFontHeightInPoints((short) 16); - linkFont.setItalic(true); - linkCellStyle.setFont(linkFont); - - - } - - - @Override - public void generateDbDoc() throws Exception { - String databaseName = dbInfoDao.databaseName(); - List tableInfos = dbInfoDao.tableInfoList(); - // 生成文件 - File file = createFile("xls"); - // 初始化样式 - initCellStyle(); - // 创建目录sheet - createIndexSheet(); - // 创建各种表格sheet - for (int i = 0; i < tableInfos.size(); i++) { - TableInfo tableInfo = tableInfos.get(i); - createTableSheet(tableInfo); - } - FileOutputStream exportXls = new FileOutputStream(file); - workbook.write(exportXls); - workbook.close(); - exportXls.close(); - } - - private Integer emptyRows(HSSFSheet sheet, Integer rowIndex, Integer rows) { - for (int i = 0; i < rows; i++) { - sheet.createRow(rowIndex++); - } - return rowIndex; - } - - private void createIndexSheet() { - String databaseName = dbInfoDao.databaseName(); - List tableInfos = dbInfoDao.tableInfoList(); - CreationHelper createHelper = workbook.getCreationHelper(); - // 创建目录sheet - HSSFSheet indexSheet = workbook.createSheet(indexSheetName); - indexSheet.setActive(true); - indexSheet.setDefaultColumnWidth(40); - // 创建数据库名称row - HSSFRow dbNameRow = indexSheet.createRow(0); - createCell(0, dbNameRow, "数据库名称:" + databaseName, simpleCellStyle); - - HSSFRow tablesRow = indexSheet.createRow(2); - createCell(0, tablesRow, "表", simpleCellStyle); - // 创建返回目录sheet的超链接 - Hyperlink toIndexLink = createHelper.createHyperlink(HyperlinkType.DOCUMENT); - toIndexLink.setAddress(String.format("'%s'!A1", indexSheetName)); - - // 创建表目录 - for (int i = 0; i < tableInfos.size(); i++) { - TableInfo tableInfo = tableInfos.get(i); - // 目录sheet创建一个cell超链接到表格Sheet - HSSFRow indexRow = indexSheet.createRow(i + 3); - HSSFCell indexRowCell = createCell(0, indexRow, tableInfo.getTableName(), linkCellStyle); - Hyperlink toTableLink = createHelper.createHyperlink(HyperlinkType.DOCUMENT); - toTableLink.setAddress(String.format("'%s'!A1", tableInfo.getTableName())); - indexRowCell.setHyperlink(toTableLink); - createCell(1, indexRow, tableInfo.getTableRemark(), linkCellStyle); - } - } - - private void createTableSheet(TableInfo tableInfo) { - CreationHelper createHelper = workbook.getCreationHelper(); - Hyperlink toIndexLink = createHelper.createHyperlink(HyperlinkType.DOCUMENT); - toIndexLink.setAddress(String.format("'%s'!A1", indexSheetName)); - // 创建表格sheet,sheet名称长度最大32个字符 - HSSFSheet tableSheet = workbook.createSheet(tableInfo.getTableName()); - tableSheet.setDefaultColumnWidth(45); - Integer rowIndex = new Integer(3); - // 创建第一行,包含返回首页的按钮和表名 - HSSFRow tableSheetIndexRow = tableSheet.createRow(rowIndex++); - HSSFCell tableSheetIndexRowFirstCell = createCell(0, tableSheetIndexRow, "返回目录", linkCellStyle); - tableSheetIndexRowFirstCell.setHyperlink(toIndexLink); - - // 创建第二行,显示表名 - HSSFRow tableSheetTableNameRow = tableSheet.createRow(rowIndex++); - createCell(0, tableSheetTableNameRow, "表名:" + tableInfo.getTableName(), simpleCellStyle); - - // 创建第三行,注释 - HSSFRow tableSheetTableCommentRow = tableSheet.createRow(rowIndex++); - createCell(0, tableSheetTableCommentRow, "注释:" + tableInfo.getTableRemark(), simpleCellStyle); - - // 创建field表格 - rowIndex = createFieldTable(tableInfo, tableSheet, rowIndex); - // 空三行 - rowIndex = emptyRows(tableSheet, rowIndex, 3); - // 创建key表格 - rowIndex = createKeyTable(tableInfo, tableSheet, rowIndex); - } - - private Integer createFieldTable(TableInfo tableInfo, HSSFSheet tableSheet, Integer rowIndex) { - // 创建表格头部 - HSSFRow tableSheetHeadRow = tableSheet.createRow(rowIndex++); - - createCell(0, tableSheetHeadRow, "字段", titleCellStyle); - createCell(1, tableSheetHeadRow, "注释", titleCellStyle); - createCell(2, tableSheetHeadRow, "类型", titleCellStyle); - createCell(3, tableSheetHeadRow, "键", titleCellStyle); - createCell(4, tableSheetHeadRow, "能否为空", titleCellStyle); - createCell(5, tableSheetHeadRow, "默认值", titleCellStyle); - - // 创建表格内容 - for (int j = 0; j < tableInfo.getFields().size(); j++) { - - TableFieldInfo tableFieldInfo = tableInfo.getFields().get(j); - HSSFRow fieldRow = tableSheet.createRow(rowIndex++); - createCell(0, fieldRow, tableFieldInfo.getField(), simpleCellStyle); - createCell(1, fieldRow, tableFieldInfo.getRemark(), simpleCellStyle); - createCell(2, fieldRow, tableFieldInfo.getType(), simpleCellStyle); - createCell(3, fieldRow, tableFieldInfo.getKey(), simpleCellStyle); - createCell(4, fieldRow, tableFieldInfo.getNullAble(), simpleCellStyle); - createCell(5, fieldRow, tableFieldInfo.getDefaultValue(), simpleCellStyle); - } - return rowIndex; - } - - private Integer createKeyTable(TableInfo tableInfo, HSSFSheet tableSheet, Integer rowIndex) { - //索引标题 - createCell(0, tableSheet.createRow(rowIndex++), "索引信息", simpleCellStyle); - //索引头部 - HSSFRow indexSheetHeadRow = tableSheet.createRow(rowIndex++); - createCell(0, indexSheetHeadRow, "名称", simpleCellStyle); - createCell(1, indexSheetHeadRow, "栏位", simpleCellStyle); - createCell(2, indexSheetHeadRow, "索引类型", simpleCellStyle); - createCell(3, indexSheetHeadRow, "索引方式", simpleCellStyle); - createCell(4, indexSheetHeadRow, "索引备注", simpleCellStyle); - //创建索引内容 - for (int j = 0; j < tableInfo.getKeys().size(); j++) { - TableKeyInfo tableKeyInfo = tableInfo.getKeys().get(j); - HSSFRow keyRow = tableSheet.createRow(rowIndex++); - createCell(0, keyRow, tableKeyInfo.getName(), simpleCellStyle); - createCell(1, keyRow, tableKeyInfo.getColumnCombine(), simpleCellStyle); - createCell(2, keyRow, tableKeyInfo.getUnique() ? "Unique" : "Normal", simpleCellStyle); - createCell(3, keyRow, tableKeyInfo.getIndexType(), simpleCellStyle); - createCell(4, keyRow, tableKeyInfo.getIndexComment(), simpleCellStyle); - } - return rowIndex; - } - - /*** - * 创建单元格 - * - * @param indexColumn - * 第几个单元格 - * @param row - * HSSFRow - * @param value - * 值 - * @param style - * 样式 - * @return - */ - public HSSFCell createCell(int indexColumn, HSSFRow row, String value, HSSFCellStyle style) { - HSSFCell cell = row.createCell(indexColumn, CellType.STRING); - cell.setCellValue(value); - cell.setCellStyle(style); - return cell; - } - -} diff --git a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/service/impl/HtmlGeneratorServiceImpl.java b/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/service/impl/HtmlGeneratorServiceImpl.java deleted file mode 100644 index c2045fd295..0000000000 --- a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/service/impl/HtmlGeneratorServiceImpl.java +++ /dev/null @@ -1,45 +0,0 @@ -package cn.wuwenyao.db.doc.generator.service.impl; - -import java.io.File; -import java.io.FileWriter; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Random; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.time.DateFormatUtils; - -import cn.wuwenyao.db.doc.generator.entity.TableInfo; -import cn.wuwenyao.db.doc.generator.utils.FreemarkerUtils; -import freemarker.template.Template; - -/*** - * 生成文档服务-html实现 - * - * @author wwy - * - */ -public final class HtmlGeneratorServiceImpl extends AbstractGeneratorServiceImpl { - - /** 模板名称 */ - private String templateFileName = "htmlTemplate.html"; - - @Override - public void generateDbDoc() throws Exception { - String databaseName = dbInfoDao.databaseName(); - List tableInfos = dbInfoDao.tableInfoList(); - templateFileName = StringUtils.defaultIfBlank(generatorConfig.getTemplateFilePath(), templateFileName); - // 获取模板 - Template template = FreemarkerUtils.getTemplate(templateFileName); - File file = this.createFile("html"); - Map map = new HashMap<>(2); - map.put("tableInfos", tableInfos); - map.put("databaseName", databaseName); - // 根据模板生成文件 - template.process(map, new FileWriter(file)); - } - -} diff --git a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/service/impl/WordGeneratorServiceImpl.java b/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/service/impl/WordGeneratorServiceImpl.java deleted file mode 100644 index 5ab26e62fb..0000000000 --- a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/service/impl/WordGeneratorServiceImpl.java +++ /dev/null @@ -1,51 +0,0 @@ -package cn.wuwenyao.db.doc.generator.service.impl; - -import java.io.File; -import java.io.FileWriter; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Random; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.time.DateFormatUtils; - -import cn.wuwenyao.db.doc.generator.entity.TableInfo; -import cn.wuwenyao.db.doc.generator.utils.FreemarkerUtils; -import freemarker.template.Template; - -/*** - * 生成文档服务,word格式 - *

- * 格式难以控制,不再支持,版本1.5移除 - *

- * - * @deprecated - * - * - * @author wwy - * - */ -public final class WordGeneratorServiceImpl extends AbstractGeneratorServiceImpl { - - /** 模板名称 */ - private String templateFileName = "wordTemplate.ftl"; - - @Override - public void generateDbDoc() throws Exception { - String databaseName = dbInfoDao.databaseName(); - List tableInfos = dbInfoDao.tableInfoList(); - // 获取模板 - templateFileName = StringUtils.defaultIfBlank(generatorConfig.getTemplateFilePath(), templateFileName); - Template template = FreemarkerUtils.getTemplate(templateFileName); - File file = this.createFile("doc"); - Map map = new HashMap<>(2); - map.put("tableInfos", tableInfos); - map.put("databaseName", databaseName); - // 根据模板生成文件 - template.process(map, new FileWriter(file)); - } - -} diff --git a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/utils/FreemarkerUtils.java b/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/utils/FreemarkerUtils.java deleted file mode 100644 index e8504b8a35..0000000000 --- a/jun_java_plugins/jun_db_document/src/main/java/cn/wuwenyao/db/doc/generator/utils/FreemarkerUtils.java +++ /dev/null @@ -1,54 +0,0 @@ -package cn.wuwenyao.db.doc.generator.utils; - -import freemarker.cache.StringTemplateLoader; -import freemarker.template.Configuration; -import freemarker.template.Template; -import org.apache.commons.io.IOUtils; - -import java.io.File; -import java.io.IOException; -import java.util.Locale; - -/*** - * freemaker工具类 - * - * @author wwy - * - */ -public class FreemarkerUtils { - - private static final String COLON = ":"; - - /** - * 通过文件名加载模版 - * - * @param ftlName - */ - public static Template getTemplate(String ftlName) throws Exception { - try { - // 通过Freemaker的Configuration读取相应的ftl - Configuration cfg = new Configuration(); - StringTemplateLoader stringLoader = new StringTemplateLoader(); - stringLoader.putTemplate(ftlName, IOUtils.toString(FreemarkerUtils.class.getClassLoader().getResourceAsStream(ftlName))); - cfg.setEncoding(Locale.CHINA, "utf-8"); - // 设定去哪里读取相应的ftl模板文件 - cfg.setTemplateLoader(stringLoader); - // 在模板文件目录中找到名称为name的文件 - Template temp = cfg.getTemplate(ftlName); - return temp; - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } - - public static String getClassResources() { - String path = (String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))) - .replaceAll("file:/", "").replaceAll("%20", " ").trim(); - if (path.indexOf(COLON) != 1) { - path = File.separator + path; - } - return path; - } - -} diff --git a/jun_java_plugins/jun_db_document/src/main/resources/application.yml b/jun_java_plugins/jun_db_document/src/main/resources/application.yml deleted file mode 100644 index c74bc1bb5f..0000000000 --- a/jun_java_plugins/jun_db_document/src/main/resources/application.yml +++ /dev/null @@ -1,22 +0,0 @@ -spring: - datasource: - driver-class-name: com.mysql.jdbc.Driver - password: 'root' - url: jdbc:mysql://localhost:3306/information_schema?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8 - username: root -application: - generator: - #数据库类型,当前支持mysql - dbtype: mysql - #生成文件的类型,当前支持excel和word和html - target-file-type: html - #使用的模板文件地址 - template-file-path: htmlTemplate2.html - #生成文件的目录 - target-file-dir: D:\generator2\doc - #黑名单,支持正则表达式 - #blacklist: - # - '.*' - #白名单,支持正则表达式 - #whitelist: - # - 't_cc.*' diff --git a/jun_java_plugins/jun_db_document/src/main/resources/htmlTemplate.html b/jun_java_plugins/jun_db_document/src/main/resources/htmlTemplate.html deleted file mode 100644 index d25effb292..0000000000 --- a/jun_java_plugins/jun_db_document/src/main/resources/htmlTemplate.html +++ /dev/null @@ -1,159 +0,0 @@ - - - - - - - - - - ${databaseName} - - - - - - - - - -

数据库名称:${databaseName}

- - - - - - <#list tableInfos as tableInfo> - - - - - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_db_document/src/main/resources/htmlTemplate2.html b/jun_java_plugins/jun_db_document/src/main/resources/htmlTemplate2.html deleted file mode 100644 index 9a605a030b..0000000000 --- a/jun_java_plugins/jun_db_document/src/main/resources/htmlTemplate2.html +++ /dev/null @@ -1,158 +0,0 @@ - - - - - - - - - - ${databaseName} - - - - - - - - - - - - -
- -

数据库名称:${databaseName}

- - <#list tableInfos as tableInfo> -
-

表名:${tableInfo.tableName}

-

注释:${tableInfo.tableRemark}

- - - - - - - - - - - - - - - <#list tableInfo.fields as field> - - - - - - - - - - - - -
表格信息
字段类型注释能否为空默认值其他
${field.field}${field.type}${field.remark}${field.key}${field.nullAble}${field.defaultValue}${field.extra}
- - - - - - - - - - - - - - <#list tableInfo.keys as key> - - - - - - - - - - -
索引信息
名称栏位索引类型索引方式索引备注
${key.name}${key.getColumnCombine()} - <#if key.unique> - UNIQUE - <#else> - NORMAL - - ${key.indexType}${key.indexComment}
-
- - -
- - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_db_document/src/main/resources/wordTemplate.ftl b/jun_java_plugins/jun_db_document/src/main/resources/wordTemplate.ftl deleted file mode 100644 index 858bad9d74..0000000000 --- a/jun_java_plugins/jun_db_document/src/main/resources/wordTemplate.ftl +++ /dev/null @@ -1,1664 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ${databaseName} - - - - - - - - - - - - - - - - - - <#list tableInfos as tableInfo> - - - - - - 数据表名: - - - - - - - - ${tableInfo.tableName} - - - - - - 注释: - - - - - - - - ${tableInfo.tableRemark} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 字段 - - - - - - - - - - - 类型 - - - - - - - - - - - 注释 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 能否为空 - - - - - - - - - - - - - - - - - - - - - 默认值 - - - - - - - - - - - - - - - - - - - - - 其他 - - - - - <#list tableInfo.fields as field> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ${field.field} - - - - - - - - - - - - - - - - - - - - - - - ${field.type} - - - - - - - - - - - - - - - - - - - - - - - ${field.remark} - - - - - - - - - - - - - - - - - - - - - - - ${field.key} - - - - - - - - - - - - - - - - - - - - - - - - - ${field.nullAble} - - - - - - - - - - - - - - - - - - - - - - - - - ${field.defaultValue} - - - - - - - - - - - - - - - - - - - - - - - - - ${field.extra} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - 0 - 0 - 0 - 0 - false - false - 0 - WPS - Office_10.1.0.6690_F1E327BC-269C-435d-A152-05C5408002CA - - 0 - - - - - - - 2017-05-22T08:36:00Z - - Apache POI - Administrator - 2018-01-11T09:51:07Z - - - - - - - - - 2052-10.1.0.6690 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_dbutil/pom.xml b/jun_java_plugins/jun_dbutil/pom.xml deleted file mode 100644 index 6605049c7b..0000000000 --- a/jun_java_plugins/jun_dbutil/pom.xml +++ /dev/null @@ -1,80 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_dbutil - 1.0 - war - - jun_dbutil - http://maven.apache.org - - - UTF-8 - - - - - io.github.wujun728 - jun_datasource - 1.0 - - - - commons-dbutils - commons-dbutils - 1.7 - - - commons-beanutils - commons-beanutils - 1.9.4 - - - - commons-io - commons-io - 2.7 - - - - org.apache.commons - commons-lang3 - 3.11 - - - - junit - junit - 4.13.1 - test - - - commons-logging - commons-logging - 1.2 - - - log4j - log4j - 1.2.17 - - - - mysql - mysql-connector-java - 5.1.40 - - - com.oracle.database.jdbc - ojdbc5 - 11.2.0.4 - - - - jun_base_dbutil - - diff --git a/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/JdbcUtils.java b/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/JdbcUtils.java deleted file mode 100644 index 4402064754..0000000000 --- a/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/JdbcUtils.java +++ /dev/null @@ -1,43 +0,0 @@ - - package com.jun.plugin.dbutils; - - import java.sql.Connection; - import java.sql.SQLException; - import javax.sql.DataSource; - import org.apache.commons.dbutils.QueryRunner; - import com.mchange.v2.c3p0.ComboPooledDataSource; - - // NOTE: This class uses hardcoded C3P0 configuration. - // For a more flexible connection pool setup, consider using jun_datasource module - // which provides DataSourceC3p0 with configurable properties. - public class JdbcUtils{ - - //读取c3p0-config.xml文件的默认配置 - private static ComboPooledDataSource datasource =new ComboPooledDataSource(); - - /* - * 使用连接池返回连接对象 - */ - // 测试连接 - /* - * @Test - public void test() throws SQLException{ - System.out.println(getconnection()); - } - */ - - public static Connection getconnection() throws SQLException{ - - return datasource.getConnection(); - } - /* - * 返回连接池对象 - */ - public static DataSource getDataSource(){ - return datasource; - } - public static QueryRunner getQueryRunner(){ - - return new QueryRunner(datasource); - } - } diff --git a/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/dbutil/DBUtil.java b/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/dbutil/DBUtil.java deleted file mode 100644 index 5a4359df6b..0000000000 --- a/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/dbutil/DBUtil.java +++ /dev/null @@ -1,457 +0,0 @@ -package com.jun.plugin.dbutils.dbutil; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.dbutils.QueryRunner; -import org.apache.commons.dbutils.ResultSetHandler; -import org.apache.commons.dbutils.handlers.BeanHandler; -import org.apache.commons.dbutils.handlers.BeanListHandler; -import org.apache.commons.dbutils.handlers.MapHandler; -import org.apache.commons.dbutils.handlers.MapListHandler; -import org.apache.commons.dbutils.handlers.ScalarHandler; -import org.apache.log4j.Logger; -//import org.junit.Test; - -import com.jun.plugin.datasource.DataSourceUtil; - - -public class DBUtil { - - private static final Logger log = Logger.getLogger(DBUtil.class); - - public static QueryRunner run = new QueryRunner(DataSourceUtil.getDataSource()); - public static Connection conn = DataSourceUtil.getConn(); - static { - run = new QueryRunner(DataSourceUtil.getDataSource()); - conn = DataSourceUtil.getConn(); - } - - public DBUtil() { - - } - - public static QueryRunner getRunner() { - return new QueryRunner(); - } - - public List> queryForJdbc(String sql) { - List> list = new ArrayList>(); - try { - Statement st = conn.createStatement(); - ResultSet rs = st.executeQuery(sql); - ResultSetMetaData rsmd = rs.getMetaData(); - int cols = rsmd.getColumnCount(); - while (rs.next()) { - Map mm = new HashMap(); - for (int i = 0; i < cols; i++) { - String colName = rsmd.getColumnName(i + 1); - Object val = rs.getObject(i + 1); - mm.put(colName, val); - } - list.add(mm); - } - } catch (Exception e) { - throw new RuntimeException(e); - } - return list; - } - - /** - * - * @param sql - * @param params - */ - public int insert(String sql, Object[] params) { - int affectedRows = 0; - try { - if (params == null) { - affectedRows = run.update(sql); - } else { - affectedRows = run.update(sql, params); - } - } catch (SQLException e) { - e.printStackTrace(); - log.error("insert.test" + sql, e); - } - return affectedRows; - } - - /** - * - * @param sql - */ - public int update(String sql) { - return update(sql, null); - } - - /** - * @param sql - * @param param - */ - public int update(String sql, Object param) { - return update(sql, new Object[] { param }); - } - - /** - * @param sql - * @param params - */ - public int update(String sql, Object[] params) { - int affectedRows = 0; - try { - if (params == null) { - affectedRows = run.update(sql); - } else { - affectedRows = run.update(sql, params); - } - } catch (SQLException e) { - e.printStackTrace(); - log.error("update.1111" + sql, e); - } - return affectedRows; - } - - /** - * - * @param sql - * @param params - */ - public int[] batchUpdate(String sql, Object[][] params) { - int[] affectedRows = new int[0]; - try { - affectedRows = run.batch(sql, params); - } catch (SQLException e) { - e.printStackTrace(); - log.error("update.1111" + sql, e); - } - return affectedRows; - } - - - public List> find(String sql) { - return find(sql, null); - } - - - public List> find(String sql, Object param) { - return find(sql, new Object[] { param }); - } - - - - public List> findPage(String sql, int page, int count, Object... params) { - sql = sql + " LIMIT ?,?"; - List> list = new ArrayList>(); - try { - if (params == null) { - list = (List>) run.query(sql, new MapListHandler(), new Integer[] { page, count }); - } else { - // list = (List>) run.query(sql, new MapListHandler(), - // ArrayUtils.addAll(params, new Integer[] { page, count })); - } - } catch (SQLException e) { - e.printStackTrace(); - log.error("map 11111", e); - } - return list; - } - - @SuppressWarnings("unchecked") - public List> find(String sql, Object[] params) { - List> list = new ArrayList>(); - try { - if (params == null) { - list = (List>) run.query(sql, new MapListHandler()); - } else { - list = (List>) run.query(sql, new MapListHandler(), params); - } - } catch (SQLException e) { - e.printStackTrace(); - log.error("map 111", e); - } - return list; - } - - public List find(Class entityClass, String sql) { - return find(entityClass, sql, null); - } - - - public List find(Class entityClass, String sql, Object param) { - return find(entityClass, sql, new Object[] { param }); - } - - @SuppressWarnings("unchecked") - public List find(Class entityClass, String sql, Object[] params) { - List list = new ArrayList(); - try { - if (params == null) { - list = (List) run.query(sql, new BeanListHandler(entityClass)); - } else { - list = (List) run.query(sql, new BeanListHandler(entityClass), params); - } - } catch (SQLException e) { - e.printStackTrace(); - log.error("Error occured while attempting to query data", e); - } - return list; - } - - public T findFirst(Class entityClass, String sql) { - return findFirst(entityClass, sql, null); - } - - - public T findFirst(Class entityClass, String sql, Object param) { - return findFirst(entityClass, sql, new Object[] { param }); - } - - - @SuppressWarnings("unchecked") - public T findFirst(Class entityClass, String sql, Object[] params) { - Object object = null; - try { - if (params == null) { - object = run.query(sql, new BeanHandler(entityClass)); - } else { - object = run.query(sql, new BeanHandler(entityClass), params); - } - } catch (SQLException e) { - log.error("1111 findFirst" + e.getMessage()); - e.printStackTrace(); - } - return (T) object; - } - - - public Map findFirst(String sql) { - return findFirst(sql, null); - } - - - public Map findFirst(String sql, Object param) { - return findFirst(sql, new Object[] { param }); - } - - @SuppressWarnings("unchecked") - public Map findFirst(String sql, Object[] params) { - Map map = null; - try { - if (params == null) { - map = (Map) run.query(sql, new MapHandler()); - } else { - map = (Map) run.query(sql, new MapHandler(), params); - } - } catch (SQLException e) { - e.printStackTrace(); - log.error("findFirst.11111" + sql, e); - } - return map; - } - - - public Object findBy(String sql, String params) { - return findBy(sql, params, null); - } - - - public Object findBy(String sql, String columnName, Object param) { - return findBy(sql, columnName, new Object[] { param }); - } - - - public Object findBy(String sql, String columnName, Object[] params) { - Object object = null; - try { - if (params == null) { - object = run.query(sql, new ScalarHandler(columnName)); - } else { - object = run.query(sql, new ScalarHandler(columnName), params); - } - } catch (SQLException e) { - e.printStackTrace(); - log.error("findBy1111" + sql, e); - } - return object; - } - - public Object findBy(String sql, int columnIndex) { - return findBy(sql, columnIndex, null); - } - - - public Object findBy(String sql, int columnIndex, Object param) { - return findBy(sql, columnIndex, new Object[] { param }); - } - - public Object findBy(String sql, int columnIndex, Object[] params) { - Object object = null; - try { - if (params == null) { - object = run.query(sql, new ScalarHandler(columnIndex)); - } else { - object = run.query(sql, new ScalarHandler(columnIndex), params); - } - } catch (SQLException e) { - e.printStackTrace(); - log.error("findBy.123" + sql, e); - } - return object; - } - - - @SuppressWarnings({ "unchecked", "deprecation" }) - public int[] batch(String sql, Object[][] params) throws Exception { - int[] rows = null; - - try { - rows = run.batch(conn, sql, params); - } finally { - - } - - return rows; - } - - public int executeUpdate(String sql) throws Exception { - int rows = 0; - - try { - rows = run.update(conn, sql); - } finally { - - } - return rows; - } - - @SuppressWarnings({ "unchecked", "deprecation" }) - public int executeUpdate(String sql, Object param) throws Exception { - int rows = 0; - - try { - rows = run.update(conn, sql, param); - } finally { - - } - - return rows; - } - - @SuppressWarnings({ "unchecked", "deprecation" }) - public int executeUpdate(String sql, Object[] params) throws Exception { - int rows = 0; - - try { - - rows = run.update(conn, sql, params); - - } finally { - - } - - return rows; - } - - public Object queryToBean(Class type, String sql) throws Exception { - - Object result = null; - - ResultSetHandler h = new BeanHandler(type); - try { - - result = run.query(conn, sql, h); - - } finally { - - } - - return result; - } - - @SuppressWarnings({ "unchecked", "deprecation" }) - public Object queryToBean(Class type, String sql, Object param) throws Exception { - - Object result = null; - - ResultSetHandler h = new BeanHandler(type); - try { - - result = run.query(conn, sql, param, h); - - } finally { - - } - - return result; - } - - @SuppressWarnings({ "unchecked", "deprecation" }) - public Object queryToBean(Class type, String sql, Object[] params) throws Exception { - - Object result = null; - - ResultSetHandler h = new BeanHandler(type); - try { - result = run.query(conn, sql, params, h); - } finally { - - } - return result; - } - - @SuppressWarnings({ "unchecked", "deprecation" }) - public ArrayList queryToBeanList(Class type, String sql) throws Exception { - - ArrayList result = null; - - ResultSetHandler h = new BeanListHandler(type); - try { - result = (ArrayList) run.query(conn, sql, h); - } finally { - - } - return result; - } - - @SuppressWarnings({ "unchecked", "deprecation" }) - public ArrayList queryToBeanList(Class type, String sql, Object param) throws Exception { - - ArrayList result = null; - - ResultSetHandler h = new BeanListHandler(type); - try { - - result = (ArrayList) run.query(conn, sql, param, h); - - } finally { - - } - - return result; - } - - public ArrayList queryToBeanList(Class type, String sql, Object[] params) throws Exception { - - ArrayList result = null; - ResultSetHandler h = new BeanListHandler(type); - try { - - result = (ArrayList) run.query(conn, sql, params, h); - - } finally { - - } - - return result; - } - - -} diff --git a/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/hander/BeanHandler2.java b/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/hander/BeanHandler2.java deleted file mode 100644 index 7589cb6c9f..0000000000 --- a/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/hander/BeanHandler2.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.jun.plugin.dbutils.hander; - -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.util.Date; - -import org.apache.commons.beanutils.BeanUtils; -import org.apache.commons.dbutils.ResultSetHandler; - - -public class BeanHandler2 implements ResultSetHandler { - - private Class clazz; - - public BeanHandler2(Class clazz) { - this.clazz = clazz; - } - - // 将结果集的第一行数据封装到bean返回 - public Object handle(ResultSet rs) { - try { - if (rs.next()) { - Object bean = this.clazz.newInstance(); - ResultSetMetaData metaData = rs.getMetaData();// 获取rs的元数据,该元数据可以获得列的数量和对应列索引处的列的名称值 - int columnCount = metaData.getColumnCount(); - for (int i = 1; i <= columnCount; i++) { - String columnName = metaData.getColumnName(i); - Object value = rs.getObject(columnName);// 根据列的名称获取对应的值 - if (value instanceof Integer) { - BeanUtils.setProperty(bean, columnName, (Integer) value);// 将值转化为对应的类型然后反射到对应对象属性中。 - } else if (value instanceof String) { - BeanUtils.setProperty(bean, columnName, (String) value); - } else if (value instanceof Date) { - BeanUtils.setProperty(bean, columnName, (Date) value); - } else if (value instanceof Boolean) { - BeanUtils.setProperty(bean, columnName, (Boolean) value); - } else if (value instanceof Float) { - BeanUtils.setProperty(bean, columnName, (Float) value); - } - } - return bean; - } - return null; - } catch (Exception e) { - try { - throw new Exception(e); - } catch (Exception e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - } - return rs; - } - -} diff --git a/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/hander/BeanListHandler2.java b/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/hander/BeanListHandler2.java deleted file mode 100644 index 5fffc13dae..0000000000 --- a/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/hander/BeanListHandler2.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.jun.plugin.dbutils.hander; - -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import org.apache.commons.beanutils.BeanUtils; -import org.apache.commons.dbutils.ResultSetHandler; - -public class BeanListHandler2 implements ResultSetHandler { - - private Class clazz; - - public BeanListHandler2(Class clazz) { - this.clazz = clazz; - } - - // 将结果集的每一行封装到bean,将bean加入一个list返回 - public Object handle(ResultSet rs) { - try { - List list = new ArrayList(); - while (rs.next()) { - Object bean = this.clazz.newInstance(); - ResultSetMetaData metaData = rs.getMetaData(); - int columnCount = metaData.getColumnCount(); - for (int i = 1; i <= columnCount; i++) { - String columnName = metaData.getColumnName(i); - Object value = rs.getObject(columnName); - - if (value instanceof Integer) { - BeanUtils.setProperty(bean, columnName, (Integer) value); - } else if (value instanceof String) { - BeanUtils.setProperty(bean, columnName, (String) value); - } else if (value instanceof Date) { - BeanUtils.setProperty(bean, columnName, (Date) value); - } else if (value instanceof Boolean) { - BeanUtils.setProperty(bean, columnName, (Boolean) value); - } - } - list.add(bean); - } - return list; - } catch (Exception e) { - e.printStackTrace(); - } - return rs; - } - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/hander/HnadlerFactory.java b/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/hander/HnadlerFactory.java deleted file mode 100644 index 316e7ca28b..0000000000 --- a/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/hander/HnadlerFactory.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.jun.plugin.dbutils.hander; - -import java.util.Map; - -import org.apache.commons.dbutils.handlers.BeanListHandler; - -public class HnadlerFactory { - - public static void main(String[] args) { - // TODO Auto-generated method stub - - } - - public static BeanListHandler BeanListHandler(Object obj) { - BeanListHandler handler = new BeanListHandler(obj.getClass()); - return handler; - } - - public static BeanListHandler BeanListHandlerForObject() { - BeanListHandler handler = new BeanListHandler(Object.class); - return handler; - } - - public static BeanListHandler BeanListHandlerForMap() { - BeanListHandler handler = new BeanListHandler(Map.class); - return handler; - } - -} diff --git a/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/jdbc/JdbcUtils.java b/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/jdbc/JdbcUtils.java deleted file mode 100644 index 42d6ec87ff..0000000000 --- a/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/jdbc/JdbcUtils.java +++ /dev/null @@ -1,122 +0,0 @@ -package com.jun.plugin.dbutils.jdbc; - -import com.mchange.v2.c3p0.ComboPooledDataSource; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.sql.DataSource; -import java.sql.Connection; -import java.sql.SQLException; - -/** - * Created by chenghui.zhang on 2018/2/10. - */ -public class JdbcUtils { - private static final Logger logger = LoggerFactory.getLogger(JdbcUtils.class); - - /** - * 采用饿汉模式,默认 c3p0-copnfig.xml 文件,所以使用该工具需在 classpath 中添加 c3p0-copnfig.xml 配置文件 - */ - private static DataSource ds = new ComboPooledDataSource(); - - /** - * 它为null表示没有事务 - * 它不为null表示有事务 - * 当开启事务时,需要给它赋值 - * 当结束事务时,需要给它赋值为null - * 并且在开启事务时,让dao的多个方法共享这个Connection - */ - private static ThreadLocal tl = new ThreadLocal<>(); - - public static DataSource getDataSource() { - return ds; - } -// -// private static void setDataSource(DataSource ds) { -// JdbcUtils.ds = ds; -// } - - /** - * 获取当前线程数据库连接 - * - * @return Connection - * @throws SQLException - */ - public static Connection getConnection() throws SQLException { - // 如果有事务,返回当前事务的con - // 如果没有事务,通过连接池返回新的con - Connection con = tl.get(); - if (con != null) { - return con; - } - return ds.getConnection(); - } - - /** - * 开启事务 - * - * @throws SQLException - */ - public static void begin() throws SQLException { - //获取当前线程的事务连接 - Connection con = tl.get(); - if (con != null) { - throw new SQLException("已经开启了事务,不能重复开启!"); - } - //给con赋值,表示开启了事务 - con = ds.getConnection(); - //设置为手动提交 - con.setAutoCommit(false); - tl.set(con); - } - - /** - * 提交事务 - * - * @throws SQLException - */ - public static void commit() throws SQLException { - //获取当前线程的事务连接 - Connection con = tl.get(); - if (con == null) { - throw new SQLException("没有事务不能提交!"); - } - con.commit(); - con.close(); - tl.remove(); - } - - /** - * 回滚事务 - * - * @throws SQLException - */ - public static void rollback() throws SQLException { - Connection con = tl.get(); - //获取当前线程的事务连接 - if (con == null) { - throw new SQLException("没有事务不能回滚!"); - } - con.rollback(); - con.close(); - tl.remove(); - } - - /** - * 释放Connection - * - * @param connection - * @throws SQLException - */ - public static void releaseConnection(Connection connection) throws SQLException { - //获取当前线程的事务连接 - Connection con = tl.get(); - //如果参数连接,与当前事务连接不同,说明这个连接不是当前事务,可以关闭! - if (connection != con) { - //如果参数连接没有关闭,关闭之! - if (connection != null && !connection.isClosed()) { - connection.close(); - } - } - } -} diff --git a/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/jdbc/TxQueryRunner.java b/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/jdbc/TxQueryRunner.java deleted file mode 100644 index 7f8a3d2ad4..0000000000 --- a/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/jdbc/TxQueryRunner.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.jun.plugin.dbutils.jdbc; - -import org.apache.commons.dbutils.QueryRunner; -import org.apache.commons.dbutils.ResultSetHandler; - -import java.sql.Connection; -import java.sql.SQLException; - -/** - * 这个类中的方法,自己来处理连接的问题 - * 通过JdbcUtils.getConnection()得到连接!有可能是事务连接,也可能是普通的连接! - * JdbcUtils.releaseConnection()完成对连接的释放!如果是普通连接,关闭之! - *

- * Created by chenghui.zhang on 2018/2/10. - */ -public class TxQueryRunner extends QueryRunner { - @Override - public int[] batch(String sql, Object[][] params) throws SQLException { - /* - * 1. 得到连接 - * 2. 执行父类方法,传递连接对象 - * 3. 释放连接 - * 4. 返回值 - */ - Connection con = JdbcUtils.getConnection();//这个类就把调用这个方法的人少写了这两行代码,如在dao层调用的时候使代码更优雅 - int[] result = super.batch(con, sql, params); - JdbcUtils.releaseConnection(con); - return result; - } - - @Override - public T query(String sql, Object param, ResultSetHandler rsh) - throws SQLException { - Connection con = JdbcUtils.getConnection(); - T result = super.query(con, sql, param, rsh); - JdbcUtils.releaseConnection(con); - return result; - } - - @Override - public T query(String sql, Object[] params, ResultSetHandler rsh) - throws SQLException { - Connection con = JdbcUtils.getConnection(); - T result = super.query(con, sql, params, rsh); - JdbcUtils.releaseConnection(con); - return result; - } - - @Override - public T query(String sql, ResultSetHandler rsh, Object... params) - throws SQLException { - Connection con = JdbcUtils.getConnection(); - T result = super.query(con, sql, rsh, params); - JdbcUtils.releaseConnection(con); - return result; - } - - @Override - public T query(String sql, ResultSetHandler rsh) throws SQLException { - Connection con = JdbcUtils.getConnection(); - T result = super.query(con, sql, rsh); - JdbcUtils.releaseConnection(con); - return result; - } - - @Override - public int update(String sql) throws SQLException { - Connection con = JdbcUtils.getConnection(); - int result = super.update(con, sql); - JdbcUtils.releaseConnection(con); - return result; - } - - @Override - public int update(String sql, Object param) throws SQLException { - Connection con = JdbcUtils.getConnection(); - int result = super.update(con, sql, param); - JdbcUtils.releaseConnection(con); - return result; - } - - @Override - public int update(String sql, Object... params) throws SQLException { - Connection con = JdbcUtils.getConnection(); - int result = super.update(con, sql, params); - JdbcUtils.releaseConnection(con); - return result; - } -} diff --git a/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/metadata/TestDatabaseMetaData.java b/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/metadata/TestDatabaseMetaData.java deleted file mode 100644 index 455ddb1e58..0000000000 --- a/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/metadata/TestDatabaseMetaData.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.jun.plugin.dbutils.metadata; - - -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import com.jun.plugin.dbutils.test.JdbcByPropertiesUtil; - - -public class TestDatabaseMetaData { - private JdbcByPropertiesUtil jbpu = JdbcByPropertiesUtil.getInstance(); - - public JdbcByPropertiesUtil getJbpu() { - return jbpu; - } - - public void setJbpu(JdbcByPropertiesUtil jbpu){ - this.jbpu = jbpu; - } - - public Properties getProperties(){ - Properties pros = JdbcByPropertiesUtil.readPropertiesFile(); - return pros; - } - - /** - * 读取配置文件jdbc.properties中的数据库名称 - * @return - * @throws Exception - */ - public String getDataSourceName()throws Exception{ - Properties pros = this.getProperties(); - String dbName = pros.get("dbName").toString(); - return dbName; - } - - /** - * 获取数据库中的表名称与视图名称 - * @return - */ - public List getTablesAndViews()throws Exception{ - Connection conn = jbpu.getConnection(); - ResultSet rs = null; - List list = new ArrayList(); - try { - Properties pros = this.getProperties(); - String schema = pros.get("user").toString(); - DatabaseMetaData metaData = conn.getMetaData(); - rs = metaData.getTables(null, schema, null, new String[]{"TABLE","VIEW"}); - while(rs.next()){ - String tableName = rs.getString("TABLE_NAME"); - list.add(tableName); - } - } catch (SQLException e) { - e.printStackTrace(); - } finally{ - jbpu.close(rs, null, conn); - } - return list; - } - - /** - * 利用表名和数据库用户名查询出该表对应的字段类型 - * @param tableName 表名 - * @return - * @throws Exception - */ - public String generateBean()throws Exception{ - Connection conn = jbpu.getConnection(); - ResultSet rs = null; - String strJavaBean = ""; - String tableName = this.getDataSourceName(); - try{ - Properties pros = this.getProperties(); - String schema = pros.get("user").toString(); - DatabaseMetaData metaData = conn.getMetaData(); - rs = metaData.getColumns(null, schema, tableName, null); - Map map = new HashMap(); - while(rs.next()){ - String columnName = rs.getString("COLUMN_NAME");//列名 - String dataType = rs.getString("DATA_TYPE");//字段数据类型(对应java.sql.Types中的常量) - String typeName = rs.getString("TYPE_NAME");//字段类型名称(例如:VACHAR2) - map.put(columnName, dataType+":"+typeName); - } - - // 其它生成javaBean的相关操作 - - }catch(Exception e){ - e.printStackTrace(); - }finally{ - jbpu.close(rs, null, conn); - } - return strJavaBean; - } - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/metadata/TestMetaData.java b/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/metadata/TestMetaData.java deleted file mode 100644 index 466c162197..0000000000 --- a/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/metadata/TestMetaData.java +++ /dev/null @@ -1,307 +0,0 @@ -package com.jun.plugin.dbutils.metadata; - -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; - - -public class TestMetaData { - - static Connection con = null; - - static { - - try { - Class.forName("com.mysql.jdbc.Driver"); - - con = DriverManager - .getConnection( - "jdbc:mysql://localhost:3306/erp2?useUnicode=true&characterEncoding=utf-8", - "root", "mysqladmin"); - - PreparedStatement pst = con - .prepareStatement("drop table if exists user;"); - - pst.execute(); - - pst = con - .prepareStatement("create table user(id int auto_increment primary key comment '主键啊',name varchar(20) not" - + " null comment '名称啊',age int default 18 comment '年龄啊',salary float(8,2) comment '薪水啊',rq date,sj time,rj timestamp);"); - - pst.execute(); - - String sql = "insert into user (name,age,salary,rq,sj,rj) values (?,?,?,?,?,?)"; - - pst = con.prepareStatement(sql); - - for (int i = 1; i <= 10; i++) { - - pst.setString(1, "zs" + i); - - pst.setInt(2, 17 + i); - - pst.setFloat(3, 2600 + i * 100.0f); - - long time = System.currentTimeMillis(); - - pst.setDate(4, new java.sql.Date(time)); - - pst.setTime(5, new java.sql.Time(time)); - - pst.setTimestamp(6, new java.sql.Timestamp(time)); - - pst.addBatch(); - - } - - pst.executeBatch(); - - pst.close(); - - } catch (Exception ex) { - throw new ExceptionInInitializerError(ex); - } - } - - /** - * DatabaseMetaData一些用法 - * @throws Exception - */ - public static void getDBInfo() throws Exception { - - DatabaseMetaData dbmd = con.getMetaData(); - - System.out.println(dbmd.getDatabaseProductName());//获取数据库产品名称 - - System.out.println(dbmd.getDatabaseProductVersion());//获取数据库产品版本号 - - System.out.println(dbmd.getCatalogSeparator());//获取数据库用作类别和表名之间的分隔符 如test.user - - System.out.println(dbmd.getDriverVersion());//获取驱动版本 - - System.out.println("*******************可用的数据库列表*********************"); - ResultSet rs = dbmd.getCatalogs();//取可在此数据库中使用的类别名,在mysql中说白了就是可用的数据库名称,只有一列 - - while(rs.next()){ - - System.out.println(rs.getString(1)); - } - - System.out.println("********************所有表********************************"); - /** - * catalog 类别名称 - * schemaPattern 用户方案模式, - * tableNamePattern 表 - * types 类型 - * 获取所有表 - * dbmd.getTables(catalog, schemaPattern, tableNamePattern, types) - */ - - rs = dbmd.getTables(null, null, null, new String[]{"TABLE"});//参数列表 1:类别名称,2: 模式名称的模式,3:表名称模式,4:要包括的表类型所组成的列表 - - while(rs.next()){ - - /** 所有的列信息。如下 - * TABLE_CAT String => 表类别(可为 null) - TABLE_SCHEM String => 表模式(可为 null) - TABLE_NAME String => 表名称 - COLUMN_NAME String => 列名称 - DATA_TYPE int => 来自 java.sql.Types 的 SQL 类型 - TYPE_NAME String => 数据源依赖的类型名称,对于 UDT,该类型名称是完全限定的 - COLUMN_SIZE int => 列的大小。 - BUFFER_LENGTH 未被使用。 - DECIMAL_DIGITS int => 小数部分的位数。对于 DECIMAL_DIGITS 不适用的数据类型,则返回 Null。 - NUM_PREC_RADIX int => 基数(通常为 10 或 2) - NULLABLE int => 是否允许使用 NULL。 - columnNoNulls - 可能不允许使用 NULL 值 - columnNullable - 明确允许使用 NULL 值 - columnNullableUnknown - 不知道是否可使用 null - REMARKS String => 描述列的注释(可为 null) - COLUMN_DEF String => 该列的默认值,当值在单引号内时应被解释为一个字符串(可为 null) - SQL_DATA_TYPE int => 未使用 - SQL_DATETIME_SUB int => 未使用 - CHAR_OCTET_LENGTH int => 对于 char 类型,该长度是列中的最大字节数 - ORDINAL_POSITION int => 表中的列的索引(从 1 开始) - IS_NULLABLE String => ISO 规则用于确定列是否包括 null。 - YES --- 如果参数可以包括 NULL - NO --- 如果参数不可以包括 NULL - 空字符串 --- 如果不知道参数是否可以包括 null - SCOPE_CATLOG String => 表的类别,它是引用属性的作用域(如果 DATA_TYPE 不是 REF,则为 null) - SCOPE_SCHEMA String => 表的模式,它是引用属性的作用域(如果 DATA_TYPE 不是 REF,则为 null) - SCOPE_TABLE String => 表名称,它是引用属性的作用域(如果 DATA_TYPE 不是 REF,则为 null) - SOURCE_DATA_TYPE short => 不同类型或用户生成 Ref 类型、来自 java.sql.Types 的 SQL 类型的源类型(如果 DATA_TYPE 不是 DISTINCT 或用户生成的 REF,则为 null) - IS_AUTOINCREMENT String => 指示此列是否自动增加 - YES --- 如果该列自动增加 - NO --- 如果该列不自动增加 - 空字符串 --- 如果不能确定该列是否是自动增加参数 - - */ - System.out.println(rs.getString(3) + "->" + rs.getString(4));//打印表类别,表模式,表名称,列名称, - - - } - - - System.out.println("##############################################################"); - - /** - * catalog 类别名称 - * schema 用户方案名称 - * table 表名 - * 获取指定表的主键信息 - * dbmd.getPrimaryKeys(catalog, schema, table) - * - */ - rs = dbmd.getPrimaryKeys("test", null, "user"); - - while(rs.next()){ - - /** - * 所有列信息如下: - * TABLE_CAT String => 表类别(可为 null) - TABLE_SCHEM String => 表模式(可为 null) - TABLE_NAME String => 表名称 - COLUMN_NAME String => 列名称 - KEY_SEQ short => 主键中的序列号(值 1 表示主键中的第一列,值 2 表示主键中的第二列)。 - PK_NAME String => 主键的名称(可为 null) - - */ - - System.out.println(rs.getString(1) + "," + rs.getString(2) + "," + rs.getString(3) + "," - + rs.getString(4) + "," + rs.getShort(5) + "," + rs.getString(6)); - - } - - - System.out.println("##############################################################"); - - /** - * catalog 类别名称 - * schemaPattern 用户方案,模式 - * tableNamePattern 表 - * columnNamePattern 列 - * 获取表的列信息 - * dbmd.getColumns(catalog, schemaPattern, tableNamePattern, columnNamePattern) - */ - rs = dbmd.getColumns("test", null, "user", null); - - while(rs.next()){ - - /** - * 所有列如下: - * TABLE_CAT String => 表类别(可为 null) - TABLE_SCHEM String => 表模式(可为 null) - TABLE_NAME String => 表名称 - COLUMN_NAME String => 列名称 - DATA_TYPE int => 来自 java.sql.Types 的 SQL 类型 - TYPE_NAME String => 数据源依赖的类型名称,对于 UDT,该类型名称是完全限定的 - COLUMN_SIZE int => 列的大小。 - BUFFER_LENGTH 未被使用。 - DECIMAL_DIGITS int => 小数部分的位数。对于 DECIMAL_DIGITS 不适用的数据类型,则返回 Null。 - NUM_PREC_RADIX int => 基数(通常为 10 或 2) - NULLABLE int => 是否允许使用 NULL。 - columnNoNulls - 可能不允许使用 NULL 值 - columnNullable - 明确允许使用 NULL 值 - columnNullableUnknown - 不知道是否可使用 null - REMARKS String => 描述列的注释(可为 null) - COLUMN_DEF String => 该列的默认值,当值在单引号内时应被解释为一个字符串(可为 null) - SQL_DATA_TYPE int => 未使用 - SQL_DATETIME_SUB int => 未使用 - CHAR_OCTET_LENGTH int => 对于 char 类型,该长度是列中的最大字节数 - ORDINAL_POSITION int => 表中的列的索引(从 1 开始) - IS_NULLABLE String => ISO 规则用于确定列是否包括 null。 - YES --- 如果参数可以包括 NULL - NO --- 如果参数不可以包括 NULL - 空字符串 --- 如果不知道参数是否可以包括 null - SCOPE_CATLOG String => 表的类别,它是引用属性的作用域(如果 DATA_TYPE 不是 REF,则为 null) - SCOPE_SCHEMA String => 表的模式,它是引用属性的作用域(如果 DATA_TYPE 不是 REF,则为 null) - SCOPE_TABLE String => 表名称,它是引用属性的作用域(如果 DATA_TYPE 不是 REF,则为 null) - SOURCE_DATA_TYPE short => 不同类型或用户生成 Ref 类型、来自 java.sql.Types 的 SQL 类型的源类型(如果 DATA_TYPE 不是 DISTINCT 或用户生成的 REF,则为 null) - IS_AUTOINCREMENT String => 指示此列是否自动增加 - YES --- 如果该列自动增加 - NO --- 如果该列不自动增加 - 空字符串 --- 如果不能确定该列是否是自动增加参数 - - */ - - - System.out.println(rs.getString("COLUMN_NAME") + " 类型=" + rs.getInt("DATA_TYPE") + " 列大小=" + rs.getInt("COLUMN_SIZE") + - " 注释=" + rs.getString("REMARKS") + - " 是否允许为NULL=" + rs.getInt("NULLABLE")); - - - - //还有很多很多方法,在这里就不一一列举了 - - } - - - } - - /** - * ResultSetMetaData一些用法 - * @throws Exception - */ - public static void getRsInfo() throws Exception { - - PreparedStatement pst = con.prepareStatement("select * from user"); - - ResultSet rs = pst.executeQuery(); - - ResultSetMetaData rsmd = rs.getMetaData();//结果集元 - - System.out.println("下面这些方法是ResultSetMetaData中方法"); - - System.out.println("获得1列所在的Catalog名字 : " + rsmd.getCatalogName(1)); - - System.out.println("获得1列对应数据类型的类 " + rsmd.getColumnClassName(1)); - - System.out.println("获得该ResultSet所有列的数目 " + rsmd.getColumnCount()); - - System.out.println("1列在数据库中类型的最大字符个数" + rsmd.getColumnDisplaySize(1)); - - System.out.println(" 1列的默认的列的标题" + rsmd.getColumnLabel(1)); - - //System.out.println("1列的模式" + rsmd.GetSchemaName(1)); - - System.out.println("1列的类型,返回SqlType中的编号 " + rsmd.getColumnType(1)); - - System.out.println("1列在数据库中的类型,返回类型全名" + rsmd.getColumnTypeName(1)); - - System.out.println("1列类型的精确度(类型的长度): " + rsmd.getPrecision(1)); - - System.out.println("1列小数点后的位数 " + rsmd.getScale(1)); - - System.out.println("1列对应的模式的名称(应该用于Oracle) " + rsmd.getSchemaName(1)); - - System.out.println("1列对应的表名 " + rsmd.getTableName(1)); - - System.out.println("1列是否自动递增" + rsmd.isAutoIncrement(1)); - - System.out.println("1列在数据库中是否为货币型" + rsmd.isCurrency(1)); - - System.out.println("1列是否为空" + rsmd.isNullable(1)); - - System.out.println("1列是否为只读" + rsmd.isReadOnly(1)); - - System.out.println("1列能否出现在where中" + rsmd.isSearchable(1)); - - - rs.close(); - - pst.close(); - - } - - public static void main(String[] args) throws Exception { - - getRsInfo(); - -// getDBInfo(); - - } - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/test/DBUtil.java b/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/test/DBUtil.java deleted file mode 100644 index 6b8cf3ae14..0000000000 --- a/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/test/DBUtil.java +++ /dev/null @@ -1,658 +0,0 @@ -package com.jun.plugin.dbutils.test; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.dbutils.QueryRunner; -import org.apache.commons.dbutils.ResultSetHandler; -import org.apache.commons.dbutils.handlers.BeanHandler; -import org.apache.commons.dbutils.handlers.BeanListHandler; -import org.apache.commons.dbutils.handlers.MapHandler; -import org.apache.commons.dbutils.handlers.MapListHandler; -import org.apache.commons.dbutils.handlers.ScalarHandler; -//import org.apache.commons.lang.ArrayUtils; -//import org.junit.Test; -import org.apache.log4j.Logger; - -import com.jun.plugin.datasource.DataSourceUtil; - -public class DBUtil { - - private static final Logger log = Logger.getLogger(DBUtil.class); - - public static QueryRunner run = null; - private static Connection conn = null; - static { - run = new QueryRunner(DataSourceUtil.getDataSource()); - conn = DataSourceUtil.getConn(); - } - - public DBUtil() { - - } - - public static QueryRunner getRunner() { - return new QueryRunner(); - } - - public List> queryForJdbc(String sql) { - // 灏佽鏁版嵁鐢� - List> list = new ArrayList>();// 澹版槑杩斿洖鐨勫璞� - try { - // 鎵ц鏌ヨ - Statement st = conn.createStatement(); - ResultSet rs = st.executeQuery(sql); - // 鍒嗘瀽缁撴灉闆� - ResultSetMetaData rsmd = rs.getMetaData(); - // 鑾峰彇鍒楁暟 - int cols = rsmd.getColumnCount(); - // 閬嶅巻鏁版嵁 - while (rs.next()) { - // 涓�琛屾暟鎹� - Map mm = new HashMap(); - // 閬嶅巻鍒� - for (int i = 0; i < cols; i++) { - // 鑾峰彇鍒楀悕 - String colName = rsmd.getColumnName(i + 1); - // 鑾峰彇鏁版嵁 - Object val = rs.getObject(i + 1); - // 灏佽鍒癿ap - mm.put(colName, val); - } - // 灏嗚繖涓猰ap鏀惧埌list - list.add(mm); - } - } catch (Exception e) { - throw new RuntimeException(e); - } - return list; - } - - /** - * - * @param sql - * 鎻掑叆sql璇彞 - * @param params - * 鎻掑叆鍙傛暟 - * @return 杩斿洖褰卞搷琛屾暟 - */ - public int insert(String sql, Object[] params) { - int affectedRows = 0; - try { - if (params == null) { - affectedRows = run.update(sql); - } else { - affectedRows = run.update(sql, params); - } - } catch (SQLException e) { - e.printStackTrace(); - log.error("insert.鎻掑叆璁板綍閿欒锛�" + sql, e); - } - return affectedRows; - } - - /** - * 鎵цsql璇彞 - * - * @param sql - * sql璇彞 - * @return 鍙楀奖鍝嶇殑琛屾暟 - */ - public int update(String sql) { - return update(sql, null); - } - - /** - * 鍗曟潯淇敼璁板綍 - * - * @param sql - * sql璇彞 - * @param param - * 鍙傛暟 - * @return 鍙楀奖鍝嶇殑琛屾暟 - */ - public int update(String sql, Object param) { - return update(sql, new Object[] { param }); - } - - /** - * 鍗曟潯淇敼璁板綍 - * - * @param sql - * sql璇彞 - * @param params - * 鍙傛暟鏁扮粍 - * @return 鍙楀奖鍝嶇殑琛屾暟 - */ - public int update(String sql, Object[] params) { - int affectedRows = 0; - try { - if (params == null) { - affectedRows = run.update(sql); - } else { - affectedRows = run.update(sql, params); - } - } catch (SQLException e) { - e.printStackTrace(); - log.error("update.鍗曟潯淇敼璁板綍閿欒锛�" + sql, e); - } - return affectedRows; - } - - /** - * 鎵归噺淇敼璁板綍 - * - * @param sql - * sql璇彞 - * @param params - * 浜岀淮鍙傛暟鏁扮粍 - * @return 鍙楀奖鍝嶇殑琛屾暟鐨勬暟缁� - */ - public int[] batchUpdate(String sql, Object[][] params) { - int[] affectedRows = new int[0]; - try { - affectedRows = run.batch(sql, params); - } catch (SQLException e) { - e.printStackTrace(); - log.error("update.鎵归噺淇敼璁板綍閿欒锛�" + sql, e); - } - return affectedRows; - } - - /** - * 鎵ц鏌ヨ锛屽皢姣忚鐨勭粨鏋滀繚瀛樺埌涓�涓狹ap瀵硅薄涓紝鐒跺悗灏嗘墍鏈塎ap瀵硅薄淇濆瓨鍒癓ist涓� - * - * @param sql - * sql璇彞 - * @return 鏌ヨ缁撴灉 - */ - public List> find(String sql) { - return find(sql, null); - } - - /** - * 鎵ц鏌ヨ锛屽皢姣忚鐨勭粨鏋滀繚瀛樺埌涓�涓狹ap瀵硅薄涓紝鐒跺悗灏嗘墍鏈塎ap瀵硅薄淇濆瓨鍒癓ist涓� - * - * @param sql - * sql璇彞 - * @param param - * 鍙傛暟 - * @return 鏌ヨ缁撴灉 - */ - public List> find(String sql, Object param) { - return find(sql, new Object[] { param }); - } - - /** - * 鎵ц鏌ヨ锛屽皢姣忚鐨勭粨鏋滀繚瀛樺埌涓�涓狹ap瀵硅薄涓紝鐒跺悗灏嗘墍鏈塎ap瀵硅薄淇濆瓨鍒癓ist涓� - * - * @param sql - * sql璇彞 - * @param params - * 鍙傛暟鏁扮粍 - * @return 鏌ヨ缁撴灉 - */ - @SuppressWarnings("unchecked") - public List> findPage(String sql, int page, int count, Object... params) { - sql = sql + " LIMIT ?,?"; - List> list = new ArrayList>(); - try { - if (params == null) { - list = (List>) run.query(sql, new MapListHandler(), new Integer[] { page, count }); - } else { - // list = (List>) run.query(sql, new MapListHandler(), - // ArrayUtils.addAll(params, new Integer[] { page, count })); - } - } catch (SQLException e) { - e.printStackTrace(); - log.error("map 鏁版嵁鍒嗛〉鏌ヨ閿欒", e); - } - return list; - } - - /** - * 鎵ц鏌ヨ锛屽皢姣忚鐨勭粨鏋滀繚瀛樺埌涓�涓狹ap瀵硅薄涓紝鐒跺悗灏嗘墍鏈塎ap瀵硅薄淇濆瓨鍒癓ist涓� - * - * @param sql - * sql璇彞 - * @param params - * 鍙傛暟鏁扮粍 - * @return 鏌ヨ缁撴灉 - */ - @SuppressWarnings("unchecked") - public List> find(String sql, Object[] params) { - List> list = new ArrayList>(); - try { - if (params == null) { - list = (List>) run.query(sql, new MapListHandler()); - } else { - list = (List>) run.query(sql, new MapListHandler(), params); - } - } catch (SQLException e) { - e.printStackTrace(); - log.error("map 鏁版嵁鏌ヨ閿欒", e); - } - return list; - } - - /** - * 鎵ц鏌ヨ锛屽皢姣忚鐨勭粨鏋滀繚瀛樺埌Bean涓紝鐒跺悗灏嗘墍鏈塀ean淇濆瓨鍒癓ist涓� - * - * @param entityClass - * 绫诲悕 - * @param sql - * sql璇彞 - * @return 鏌ヨ缁撴灉 - */ - public List find(Class entityClass, String sql) { - return find(entityClass, sql, null); - } - - /** - * 鎵ц鏌ヨ锛屽皢姣忚鐨勭粨鏋滀繚瀛樺埌Bean涓紝鐒跺悗灏嗘墍鏈塀ean淇濆瓨鍒癓ist涓� - * - * @param entityClass - * 绫诲悕 - * @param sql - * sql璇彞 - * @param param - * 鍙傛暟 - * @return 鏌ヨ缁撴灉 - */ - public List find(Class entityClass, String sql, Object param) { - return find(entityClass, sql, new Object[] { param }); - } - - /** - * 鎵ц鏌ヨ锛屽皢姣忚鐨勭粨鏋滀繚瀛樺埌Bean涓紝鐒跺悗灏嗘墍鏈塀ean淇濆瓨鍒癓ist涓� - * - * @param entityClass - * 绫诲悕 - * @param sql - * sql璇彞 - * @param params - * 鍙傛暟鏁扮粍 - * @return 鏌ヨ缁撴灉 - */ - @SuppressWarnings("unchecked") - public List find(Class entityClass, String sql, Object[] params) { - List list = new ArrayList(); - try { - if (params == null) { - list = (List) run.query(sql, new BeanListHandler(entityClass)); - } else { - list = (List) run.query(sql, new BeanListHandler(entityClass), params); - } - } catch (SQLException e) { - e.printStackTrace(); - log.error("Error occured while attempting to query data", e); - } - return list; - } - - /** - * 鏌ヨ鍑虹粨鏋滈泦涓殑绗竴鏉¤褰曪紝骞跺皝瑁呮垚瀵硅薄 - * - * @param entityClass - * 绫诲悕 - * @param sql - * sql璇彞 - * @return 瀵硅薄 - */ - public T findFirst(Class entityClass, String sql) { - return findFirst(entityClass, sql, null); - } - - /** - * 鏌ヨ鍑虹粨鏋滈泦涓殑绗竴鏉¤褰曪紝骞跺皝瑁呮垚瀵硅薄 - * - * @param entityClass - * 绫诲悕 - * @param sql - * sql璇彞 - * @param param - * 鍙傛暟 - * @return 瀵硅薄 - */ - public T findFirst(Class entityClass, String sql, Object param) { - return findFirst(entityClass, sql, new Object[] { param }); - } - - /** - * 鏌ヨ鍑虹粨鏋滈泦涓殑绗竴鏉¤褰曪紝骞跺皝瑁呮垚瀵硅薄 - * - * @param entityClass - * 绫诲悕 - * @param sql - * sql璇彞 - * @param params - * 鍙傛暟鏁扮粍 - * @return 瀵硅薄 - */ - @SuppressWarnings("unchecked") - public T findFirst(Class entityClass, String sql, Object[] params) { - Object object = null; - try { - if (params == null) { - object = run.query(sql, new BeanHandler(entityClass)); - } else { - object = run.query(sql, new BeanHandler(entityClass), params); - } - } catch (SQLException e) { - log.error("杩斿洖涓�鏉¤褰曢敊璇細findFirst" + e.getMessage()); - e.printStackTrace(); - } - return (T) object; - } - - /** - * 鏌ヨ鍑虹粨鏋滈泦涓殑绗竴鏉¤褰曪紝骞跺皝瑁呮垚Map瀵硅薄 - * - * @param sql - * sql璇彞 - * @return 灏佽涓篗ap鐨勫璞� - */ - public Map findFirst(String sql) { - return findFirst(sql, null); - } - - /** - * 鏌ヨ鍑虹粨鏋滈泦涓殑绗竴鏉¤褰曪紝骞跺皝瑁呮垚Map瀵硅薄 - * - * @param sql - * sql璇彞 - * @param param - * 鍙傛暟 - * @return 灏佽涓篗ap鐨勫璞� - */ - public Map findFirst(String sql, Object param) { - return findFirst(sql, new Object[] { param }); - } - - /** - * 鏌ヨ鍑虹粨鏋滈泦涓殑绗竴鏉¤褰曪紝骞跺皝瑁呮垚Map瀵硅薄 - * - * @param sql - * sql璇彞 - * @param params - * 鍙傛暟鏁扮粍 - * @return 灏佽涓篗ap鐨勫璞� - */ - @SuppressWarnings("unchecked") - public Map findFirst(String sql, Object[] params) { - Map map = null; - try { - if (params == null) { - map = (Map) run.query(sql, new MapHandler()); - } else { - map = (Map) run.query(sql, new MapHandler(), params); - } - } catch (SQLException e) { - e.printStackTrace(); - log.error("findFirst.鏌ヨ涓�鏉¤褰曢敊璇�" + sql, e); - } - return map; - } - - /** - * 鏌ヨ鏌愪竴鏉¤褰曪紝骞跺皢鎸囧畾鍒楃殑鏁版嵁杞崲涓篛bject - * - * @param sql - * sql璇彞 - * @param columnName - * 鍒楀悕 - * @return 缁撴灉瀵硅薄 - */ - public Object findBy(String sql, String params) { - return findBy(sql, params, null); - } - - /** - * 鏌ヨ鏌愪竴鏉¤褰曪紝骞跺皢鎸囧畾鍒楃殑鏁版嵁杞崲涓篛bject - * - * @param sql - * sql璇彞 - * @param columnName - * 鍒楀悕 - * @param param - * 鍙傛暟 - * @return 缁撴灉瀵硅薄 - */ - public Object findBy(String sql, String columnName, Object param) { - return findBy(sql, columnName, new Object[] { param }); - } - - /** - * 鏌ヨ鏌愪竴鏉¤褰曪紝骞跺皢鎸囧畾鍒楃殑鏁版嵁杞崲涓篛bject - * - * @param sql - * sql璇彞 - * @param columnName - * 鍒楀悕 - * @param params - * 鍙傛暟鏁扮粍 - * @return 缁撴灉瀵硅薄 - */ - public Object findBy(String sql, String columnName, Object[] params) { - Object object = null; - try { - if (params == null) { - object = run.query(sql, new ScalarHandler(columnName)); - } else { - object = run.query(sql, new ScalarHandler(columnName), params); - } - } catch (SQLException e) { - e.printStackTrace(); - log.error("findBy銆傞敊璇�" + sql, e); - } - return object; - } - - /** - * 鏌ヨ鏌愪竴鏉¤褰曪紝骞跺皢鎸囧畾鍒楃殑鏁版嵁杞崲涓篛bject - * - * @param sql - * sql璇彞 - * @param columnIndex - * 鍒楃储寮� - * @return 缁撴灉瀵硅薄 - */ - public Object findBy(String sql, int columnIndex) { - return findBy(sql, columnIndex, null); - } - - /** - * 鏌ヨ鏌愪竴鏉¤褰曪紝骞跺皢鎸囧畾鍒楃殑鏁版嵁杞崲涓篛bject - * - * @param sql - * sql璇彞 - * @param columnIndex - * 鍒楃储寮� - * @param param - * 鍙傛暟 - * @return 缁撴灉瀵硅薄 - */ - public Object findBy(String sql, int columnIndex, Object param) { - return findBy(sql, columnIndex, new Object[] { param }); - } - - public Object findBy(String sql, int columnIndex, Object[] params) { - Object object = null; - try { - if (params == null) { - object = run.query(sql, new ScalarHandler(columnIndex)); - } else { - object = run.query(sql, new ScalarHandler(columnIndex), params); - } - } catch (SQLException e) { - e.printStackTrace(); - log.error("findBy.閿欒" + sql, e); - } - return object; - } - - public static void main1(String[] args) throws Exception { - QueryRunner run = new QueryRunner(); - String sql = "insert into users values (?,?,?)"; - for (int i = 1; i <= 1043; i++) { - String uuid = "U"; - String num = "00000" + i;// 0001 - num = num.substring(num.length() - 6); - uuid = uuid + "-" + num; - run.update(sql, uuid, "Jack" + i, "AA"); - } - } - - @SuppressWarnings({ "unchecked", "deprecation" }) - public int[] batch99(String sql, Object[][] params) throws Exception { - int[] rows = null; - - try { - rows = run.batch(conn, sql, params); - } finally { - - } - - return rows; - } - - public int executeUpdate(String sql) throws Exception { - int rows = 0; - - try { - rows = run.update(conn, sql); - } finally { - - } - return rows; - } - - @SuppressWarnings({ "unchecked", "deprecation" }) - public int executeUpdate(String sql, Object param) throws Exception { - int rows = 0; - - try { - rows = run.update(conn, sql, param); - } finally { - - } - - return rows; - } - - @SuppressWarnings({ "unchecked", "deprecation" }) - public int executeUpdate(String sql, Object[] params) throws Exception { - int rows = 0; - - try { - - rows = run.update(conn, sql, params); - - } finally { - - } - - return rows; - } - - public Object queryToBean(Class type, String sql) throws Exception { - - Object result = null; - - ResultSetHandler h = new BeanHandler(type); - try { - - result = run.query(conn, sql, h); - - } finally { - - } - - return result; - } - - @SuppressWarnings({ "unchecked", "deprecation" }) - public Object queryToBean(Class type, String sql, Object param) throws Exception { - - Object result = null; - - ResultSetHandler h = new BeanHandler(type); - try { - - result = run.query(conn, sql, param, h); - - } finally { - - } - - return result; - } - - @SuppressWarnings({ "unchecked", "deprecation" }) - public Object queryToBean(Class type, String sql, Object[] params) throws Exception { - - Object result = null; - - ResultSetHandler h = new BeanHandler(type); - try { - result = run.query(conn, sql, params, h); - } finally { - - } - return result; - } - - @SuppressWarnings({ "unchecked", "deprecation" }) - public ArrayList queryToBeanList(Class type, String sql) throws Exception { - - ArrayList result = null; - - ResultSetHandler h = new BeanListHandler(type); - try { - result = (ArrayList) run.query(conn, sql, h); - } finally { - - } - return result; - } - - @SuppressWarnings({ "unchecked", "deprecation" }) - public ArrayList queryToBeanList(Class type, String sql, Object param) throws Exception { - - ArrayList result = null; - - ResultSetHandler h = new BeanListHandler(type); - try { - - result = (ArrayList) run.query(conn, sql, param, h); - - } finally { - - } - - return result; - } - - public ArrayList queryToBeanList(Class type, String sql, Object[] params) throws Exception { - - ArrayList result = null; - ResultSetHandler h = new BeanListHandler(type); - try { - - result = (ArrayList) run.query(conn, sql, params, h); - - } finally { - - } - - return result; - } - -} diff --git a/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/test/JdbcByPropertiesUtil.java b/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/test/JdbcByPropertiesUtil.java deleted file mode 100644 index 334f4135b3..0000000000 --- a/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/test/JdbcByPropertiesUtil.java +++ /dev/null @@ -1,185 +0,0 @@ -package com.jun.plugin.dbutils.test; -import java.io.BufferedInputStream; -import java.io.FileInputStream; -import java.io.InputStream; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.Properties; - -/** - * @author adam.胡升阳 - * - */ -public class JdbcByPropertiesUtil { - private static String filePath = "jdbc.properties"; - private static JdbcByPropertiesUtil instance = null; - - public JdbcByPropertiesUtil() { - super(); - } - - /** - * 单例方式创建对象 - * @return - */ - public static JdbcByPropertiesUtil getInstance() { - if (instance == null) { - synchronized (JdbcByPropertiesUtil.class) { - if (instance == null) { - instance = new JdbcByPropertiesUtil(); - } - } - } - return instance; - } - - /** - * 读取properties文件中 数据库连接信息 - * @param filePath - * add 2012-4-17 - */ - public static Properties readPropertiesFile(){ - String realFilePath = Thread.currentThread().getContextClassLoader().getResource("").getPath()+filePath; - Properties pros = new Properties(); - try { - InputStream is = new BufferedInputStream(new FileInputStream(realFilePath)); - pros.load(is); - } catch (Exception e) { - e.printStackTrace(); - } - return pros; - } - - /** - * 注册驱动 - * 静态代码块 用于启动web服务器时加载驱动 - */ - static{ - Properties pros = readPropertiesFile(); - String className = (String) pros.get("className"); - try { - Class.forName(className).newInstance(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * 获取数据库连接 - * modify 2012-4-17 - * @param con - * @return - */ - public Connection getConnection(){ - Properties pros = readPropertiesFile(); - String url = (String) pros.get("url"); - String user = (String) pros.get("user"); - String password = (String) pros.get("password"); - Connection conn = null; - try { - conn = DriverManager.getConnection(url,user,password); - } catch (Exception e) { - e.printStackTrace(); - } - return conn; - } - - /** - * 依次关闭ResultSet、Statement、Connection - * 若对象不存在则创建一个空对象 - * @param rs - * @param st - * @param pst - * @param conn - */ - public void close(ResultSet rs,Statement st,Connection conn){ - if(rs != null){ - try { - rs.close(); - } catch (SQLException e) { - e.printStackTrace(); - } finally{ - if(st != null){ - try { - st.close(); - } catch (SQLException e) { - e.printStackTrace(); - } finally{ - if(conn != null){ - try { - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - } - } - } - } - } - - - /** - * 新增、修改、删除、查询记录(也可以改为有结果集ResultSet返回的查询方法) - * @param sql - * @throws - */ - public void execute(String sql){ - JdbcByPropertiesUtil jbpu = getInstance(); - Connection conn = null; - PreparedStatement pst = null; - try { - conn = jbpu.getConnection(); - conn.setAutoCommit(false); - pst = conn.prepareStatement(sql); - pst.execute(); - conn.commit(); - } catch (Exception e) { - try { - conn.rollback(); - } catch (SQLException e1) { - e1.printStackTrace(); - } - e.printStackTrace(); - } finally{ - //Statement st = null; - ResultSet rs = null; - jbpu.close(rs, pst, conn); - } - } - - /** - * 新增、修改、删除记录 - * @param sql - * @throws - */ - public void executeUpdate(String sql) { - JdbcByPropertiesUtil jbpu = getInstance(); - Connection conn = null; - PreparedStatement pst = null; - try { - conn = jbpu.getConnection(); - conn.setAutoCommit(false); - pst = conn.prepareStatement(sql); - pst.executeUpdate(); - conn.commit(); - } catch (Exception e) { - try { - conn.rollback(); - } catch (SQLException e1) { - e1.printStackTrace(); - } - e.printStackTrace(); - } finally{ - //Statement st = null; - ResultSet rs = null; - jbpu.close(rs, pst, conn); - } - } - - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/test/JdbcUtil.java b/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/test/JdbcUtil.java deleted file mode 100644 index 7a85f3b0fd..0000000000 --- a/jun_java_plugins/jun_dbutil/src/main/java/com/jun/plugin/dbutils/test/JdbcUtil.java +++ /dev/null @@ -1,421 +0,0 @@ -package com.jun.plugin.dbutils.test; - - -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; - - -//import oracle.jdbc.driver.OracleConnection; - -/** - * @Description: JDBC操作元数据示例-- DatabaseMetaData接口 - * @CreateTime: 2014-1-19 下午9:46:44 - * @author: chenzw - * @version V1.0 - */ -public class JdbcUtil { - //获得驱动 - private static String DRIVER = "oracle.jdbc.driver.OracleDriver"; - //获得url - private static String URL = "jdbc:oracle:thin:@localhost:test"; - //获得连接数据库的用户名 - private static String USER = "root"; - //获得连接数据库的密码 - private static String PASS = "root"; - static { - try { - //初始化JDBC驱动并让驱动加载到jvm中 - Class.forName(DRIVER); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } - } - - public static Connection getConnection(){ - Connection conn = null; - try { - //连接数据库 - - /* - * 设置可获取REMARK备注信息 - Properties props =new Properties(); - props.put("remarksReporting","true"); - props.put("user", USER); - props.put("password", PASS); - conn =DriverManager.getConnection(URL,props);*/ - -// conn = DriverManager.getConnection(URL,USER,PASS); - conn = JdbcUtil.getConnection(); - conn.setAutoCommit(true); - } catch (SQLException e) { - e.printStackTrace(); - } - return conn; - } - - //关闭连接 - public static void close(Object o){ - if (o == null){ - return; - } - if (o instanceof ResultSet){ - try { - ((ResultSet)o).close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } else if(o instanceof Statement){ - try { - ((Statement)o).close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } else if (o instanceof Connection){ - Connection c = (Connection)o; - try { - if (!c.isClosed()){ - c.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - } - - - public static void close(ResultSet rs, Statement stmt, - Connection conn){ - close(rs); - close(stmt); - close(conn); - } - - public static void close(ResultSet rs, - Connection conn){ - close(rs); - close(conn); - } - - - - /** - * @Description: 获取数据库相关信息 - * @author: chenzw - * @CreateTime: 2014-1-27 下午5:09:12 - * @throws - */ - public static void getDataBaseInfo() { - Connection conn = getConnection(); - ResultSet rs = null; - try{ - DatabaseMetaData dbmd = conn.getMetaData(); - System.out.println("数据库已知的用户: "+ dbmd.getUserName()); - System.out.println("数据库的系统函数的逗号分隔列表: "+ dbmd.getSystemFunctions()); - System.out.println("数据库的时间和日期函数的逗号分隔列表: "+ dbmd.getTimeDateFunctions()); - System.out.println("数据库的字符串函数的逗号分隔列表: "+ dbmd.getStringFunctions()); - System.out.println("数据库供应商用于 'schema' 的首选术语: "+ dbmd.getSchemaTerm()); - System.out.println("数据库URL: " + dbmd.getURL()); - System.out.println("是否允许只读:" + dbmd.isReadOnly()); - System.out.println("数据库的产品名称:" + dbmd.getDatabaseProductName()); - System.out.println("数据库的版本:" + dbmd.getDatabaseProductVersion()); - System.out.println("驱动程序的名称:" + dbmd.getDriverName()); - System.out.println("驱动程序的版本:" + dbmd.getDriverVersion()); - - System.out.println("数据库中使用的表类型"); - rs = dbmd.getTableTypes(); - while (rs.next()) { - System.out.println(rs.getString("TABLE_TYPE")); - } - }catch (SQLException e){ - e.printStackTrace(); - } finally{ - JdbcUtil.close(rs,conn); - } - } - - /** - * @Description:获得数据库中所有Schemas(对应于oracle中的Tablespace) - * @author: chenzw - * @CreateTime: 2014-1-27 下午5:10:35 - * @throws - */ - public static void getSchemasInfo(){ - Connection conn = getConnection(); - ResultSet rs = null; - try{ - DatabaseMetaData dbmd = conn.getMetaData(); - rs = dbmd.getSchemas(); - while (rs.next()){ - String tableSchem = rs.getString("TABLE_SCHEM"); - System.out.println(tableSchem); - } - } catch (SQLException e){ - e.printStackTrace(); - } finally{ - JdbcUtil.close(rs,conn); - } - } - - /** - * @Description: 获取数据库中所有的表信息 - * @author: chenzw - * @CreateTime: 2014-1-27 下午5:08:28 - * @throws - */ - public static void getTablesList() { - Connection conn = getConnection(); - ResultSet rs = null; - try { - /** - * 设置连接属性,使得可获取到表的REMARK(备注) - */ -// ((OracleConnection)conn).setRemarksReporting(true); - DatabaseMetaData dbmd = conn.getMetaData(); - String[] types = { "TABLE" }; - rs = dbmd.getTables(null, null, "%", types); - while (rs.next()) { - String tableName = rs.getString("TABLE_NAME"); //表名 - String tableType = rs.getString("TABLE_TYPE"); //表类型 - String remarks = rs.getString("REMARKS"); //表备注 - System.out.println(tableName + " - " + tableType + " - " + remarks); - } - } catch (SQLException e) { - e.printStackTrace(); - } finally{ - JdbcUtil.close(rs,conn); - } - } - - /** - * @Description: 获取某表信息 - * @author: chenzw - * @CreateTime: 2014-1-27 下午3:26:30 - * @throws - */ - public static void getTablesInfo(){ - Connection conn = getConnection(); - ResultSet rs = null; - try { - /** - * 设置连接属性,使得可获取到表的REMARK(备注) - */ -// ((OracleConnection)conn).setRemarksReporting(true); - DatabaseMetaData dbmd = conn.getMetaData(); - /** - * 获取给定类别中使用的表的描述。 - * 方法原型:ResultSet getTables(String catalog,String schemaPattern,String tableNamePattern,String[] types); - * catalog - 表所在的类别名称;""表示获取没有类别的列,null表示获取所有类别的列。 - * schema - 表所在的模式名称(oracle中对应于Tablespace);""表示获取没有模式的列,null标识获取所有模式的列; 可包含单字符通配符("_"),或多字符通配符("%"); - * tableNamePattern - 表名称;可包含单字符通配符("_"),或多字符通配符("%"); - * types - 表类型数组; "TABLE"、"VIEW"、"SYSTEM TABLE"、"GLOBAL TEMPORARY"、"LOCAL TEMPORARY"、"ALIAS" 和 "SYNONYM";null表示包含所有的表类型;可包含单字符通配符("_"),或多字符通配符("%"); - */ - rs = dbmd.getTables(null, null, "CUST_INTER_TF_SERVICE_REQ", new String[]{"TABLE","VIEW"}); - - - while(rs.next()){ - String tableCat = rs.getString("TABLE_CAT"); //表类别(可为null) - String tableSchemaName = rs.getString("TABLE_SCHEM");//表模式(可能为空),在oracle中获取的是命名空间,其它数据库未知 - String tableName = rs.getString("TABLE_NAME"); //表名 - String tableType = rs.getString("TABLE_TYPE"); //表类型,典型的类型是 "TABLE"、"VIEW"、"SYSTEM TABLE"、"GLOBAL TEMPORARY"、"LOCAL TEMPORARY"、"ALIAS" 和 "SYNONYM"。 - String remarks = rs.getString("REMARKS"); //表备注 - - System.out.println(tableCat + " - " + tableSchemaName + " - " +tableName + " - " + tableType + " - " - + remarks); - } - } catch (Exception ex) { - ex.printStackTrace(); - }finally{ - JdbcUtil.close(rs,conn); - } - } - - /** - * @Description: 获取表主键信息 - * @author: chenzw - * @CreateTime: 2014-1-27 下午5:12:53 - * @throws - */ - public static void getPrimaryKeysInfo() { - Connection conn = getConnection(); - ResultSet rs = null; - try{ - DatabaseMetaData dbmd = conn.getMetaData(); - /** - * 获取对给定表的主键列的描述 - * 方法原型:ResultSet getPrimaryKeys(String catalog,String schema,String table); - * catalog - 表所在的类别名称;""表示获取没有类别的列,null表示获取所有类别的列。 - * schema - 表所在的模式名称(oracle中对应于Tablespace);""表示获取没有模式的列,null标识获取所有模式的列; 可包含单字符通配符("_"),或多字符通配符("%"); - * table - 表名称;可包含单字符通配符("_"),或多字符通配符("%"); - */ -// rs = dbmd.getPrimaryKeys(null, null, "CUST_INTER_TF_SERVICE_REQ"); - rs = dbmd.getPrimaryKeys(null, null, "sys_fileupload"); - - while (rs.next()){ - String tableCat = rs.getString("TABLE_CAT"); //表类别(可为null) - String tableSchemaName = rs.getString("TABLE_SCHEM");//表模式(可能为空),在oracle中获取的是命名空间,其它数据库未知 - String tableName = rs.getString("TABLE_NAME"); //表名 - String columnName = rs.getString("COLUMN_NAME");//列名 - short keySeq = rs.getShort("KEY_SEQ");//序列号(主键内值1表示第一列的主键,值2代表主键内的第二列) - String pkName = rs.getString("PK_NAME"); //主键名称 - - System.out.println(tableCat + " - " + tableSchemaName + " - " + tableName + " - " + columnName + " - " - + keySeq + " - " + pkName); - } - }catch (SQLException e){ - e.printStackTrace(); - }finally{ - JdbcUtil.close(rs,conn); - } - } - - /** - * @Description: 获取表索引信息 - * @author: chenzw - * @CreateTime: 2014-1-27 下午5:12:04 - * @throws - */ - public static void getIndexInfo() { - Connection conn = getConnection(); - ResultSet rs = null; - try{ - DatabaseMetaData dbmd = conn.getMetaData(); - /** - * 获取给定表的索引和统计信息的描述 - * 方法原型:ResultSet getIndexInfo(String catalog,String schema,String table,boolean unique,boolean approximate) - * catalog - 表所在的类别名称;""表示获取没有类别的列,null表示获取所有类别的列。 - * schema - 表所在的模式名称(oracle中对应于Tablespace);""表示获取没有模式的列,null标识获取所有模式的列; 可包含单字符通配符("_"),或多字符通配符("%"); - * table - 表名称;可包含单字符通配符("_"),或多字符通配符("%"); - * unique - 该参数为 true时,仅返回唯一值的索引; 该参数为 false时,返回所有索引; - * approximate - 该参数为true时,允许结果是接近的数据值或这些数据值以外的值;该参数为 false时,要求结果是精确结果; - */ - rs = dbmd.getIndexInfo(null, null, "CUST_INTER_TF_SERVICE_REQ", false, true); - while (rs.next()){ - String tableCat = rs.getString("TABLE_CAT"); //表类别(可为null) - String tableSchemaName = rs.getString("TABLE_SCHEM");//表模式(可能为空),在oracle中获取的是命名空间,其它数据库未知 - String tableName = rs.getString("TABLE_NAME"); //表名 - boolean nonUnique = rs.getBoolean("NON_UNIQUE");// 索引值是否可以不唯一,TYPE为 tableIndexStatistic时索引值为 false; - String indexQualifier = rs.getString("INDEX_QUALIFIER");//索引类别(可能为空),TYPE为 tableIndexStatistic 时索引类别为 null; - String indexName = rs.getString("INDEX_NAME");//索引的名称 ;TYPE为 tableIndexStatistic 时索引名称为 null; - /** - * 索引类型: - * tableIndexStatistic - 此标识与表的索引描述一起返回的表统计信息 - * tableIndexClustered - 此为集群索引 - * tableIndexHashed - 此为散列索引 - * tableIndexOther - 此为某种其他样式的索引 - */ - short type = rs.getShort("TYPE");//索引类型; - short ordinalPosition = rs.getShort("ORDINAL_POSITION");//在索引列顺序号;TYPE为 tableIndexStatistic 时该序列号为零; - String columnName = rs.getString("COLUMN_NAME");//列名;TYPE为 tableIndexStatistic时列名称为 null; - String ascOrDesc = rs.getString("ASC_OR_DESC");//列排序顺序:升序还是降序[A:升序; B:降序];如果排序序列不受支持,可能为 null;TYPE为 tableIndexStatistic时排序序列为 null; - int cardinality = rs.getInt("CARDINALITY"); //基数;TYPE为 tableIndexStatistic 时,它是表中的行数;否则,它是索引中唯一值的数量。 - int pages = rs.getInt("PAGES"); //TYPE为 tableIndexStatisic时,它是用于表的页数,否则它是用于当前索引的页数。 - String filterCondition = rs.getString("FILTER_CONDITION"); //过滤器条件,如果有的话(可能为 null)。 - - System.out.println(tableCat + " - " + tableSchemaName + " - " + tableName + " - " + nonUnique + " - " - + indexQualifier + " - " + indexName + " - " + type + " - " + ordinalPosition + " - " + columnName - + " - " + ascOrDesc + " - " + cardinality + " - " + pages + " - " + filterCondition); - } - } catch (SQLException e){ - e.printStackTrace(); - } finally{ - JdbcUtil.close(rs,conn); - } - } - - - /** - * @Description: 获取表中列值信息 - * @author: chenzw - * @CreateTime: 2014-1-27 下午2:55:56 - * @throws - */ - public static void getColumnsInfo(){ - Connection conn = getConnection(); - ResultSet rs = null; - - try{ - /** - * 设置连接属性,使得可获取到列的REMARK(备注) - */ -// ((OracleConnection)conn).setRemarksReporting(true); - DatabaseMetaData dbmd = conn.getMetaData(); - /** - * 获取可在指定类别中使用的表列的描述。 - * 方法原型:ResultSet getColumns(String catalog,String schemaPattern,String tableNamePattern,String columnNamePattern) - * catalog - 表所在的类别名称;""表示获取没有类别的列,null表示获取所有类别的列。 - * schema - 表所在的模式名称(oracle中对应于Tablespace);""表示获取没有模式的列,null标识获取所有模式的列; 可包含单字符通配符("_"),或多字符通配符("%"); - * tableNamePattern - 表名称;可包含单字符通配符("_"),或多字符通配符("%"); - * columnNamePattern - 列名称; ""表示获取列名为""的列(当然获取不到);null表示获取所有的列;可包含单字符通配符("_"),或多字符通配符("%"); - */ - rs =dbmd.getColumns(null, null, "sys_fileupload", null); - - while(rs.next()){ - String tableCat = rs.getString("TABLE_CAT"); //表类别(可能为空) - String tableSchemaName = rs.getString("TABLE_SCHEM"); //表模式(可能为空),在oracle中获取的是命名空间,其它数据库未知 - String tableName_ = rs.getString("TABLE_NAME"); //表名 - String columnName = rs.getString("COLUMN_NAME"); //列名 - int dataType = rs.getInt("DATA_TYPE"); //对应的java.sql.Types的SQL类型(列类型ID) - String dataTypeName = rs.getString("TYPE_NAME"); //java.sql.Types类型名称(列类型名称) - int columnSize = rs.getInt("COLUMN_SIZE"); //列大小 - int decimalDigits = rs.getInt("DECIMAL_DIGITS"); //小数位数 - int numPrecRadix = rs.getInt("NUM_PREC_RADIX"); //基数(通常是10或2) --未知 - /** - * 0 (columnNoNulls) - 该列不允许为空 - * 1 (columnNullable) - 该列允许为空 - * 2 (columnNullableUnknown) - 不确定该列是否为空 - */ - int nullAble = rs.getInt("NULLABLE"); //是否允许为null - String remarks = rs.getString("REMARKS"); //列描述 - String columnDef = rs.getString("COLUMN_DEF"); //默认值 - int charOctetLength = rs.getInt("CHAR_OCTET_LENGTH"); // 对于 char 类型,该长度是列中的最大字节数 - int ordinalPosition = rs.getInt("ORDINAL_POSITION"); //表中列的索引(从1开始) - /** - * ISO规则用来确定某一列的是否可为空(等同于NULLABLE的值:[ 0:'YES'; 1:'NO'; 2:''; ]) - * YES -- 该列可以有空值; - * NO -- 该列不能为空; - * 空字符串--- 不知道该列是否可为空 - */ - String isNullAble = rs.getString("IS_NULLABLE"); - - /** - * 指示此列是否是自动递增 - * YES -- 该列是自动递增的 - * NO -- 该列不是自动递增 - * 空字串--- 不能确定该列是否自动递增 - */ - //String isAutoincrement = rs.getString("IS_AUTOINCREMENT"); //该参数测试报错 - - - System.out.println(tableCat + " - " + tableSchemaName + " - " + tableName_ + " - " + columnName + - " - " + dataType + " - " + dataTypeName + " - " + columnSize + " - " + decimalDigits + " - " - + numPrecRadix + " - " + nullAble + " - " + remarks + " - " + columnDef + " - " + charOctetLength - + " - " + ordinalPosition + " - " + isNullAble ); - - } - }catch(SQLException ex){ - ex.printStackTrace(); - }finally{ - JdbcUtil.close(rs,conn); - } - } - - /** - * @Description: TODO - * @author: chenzw - * @CreateTime: 2014-1-17 下午2:47:45 - * @param args - * @throws - */ - public static void main(String[] args) { - getDataBaseInfo(); //获取数据库信息 - getSchemasInfo(); //获取数据库所有Schema - getTablesList(); //获取某用户下所有的表 - getTablesInfo(); //获取表信息 - getPrimaryKeysInfo(); //获取表主键信息 - getIndexInfo(); //获取表索引信息 - getColumnsInfo(); //获取表中列值信息 - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_dbutil/src/test/java/DBUtilTest6.java b/jun_java_plugins/jun_dbutil/src/test/java/DBUtilTest6.java deleted file mode 100644 index b8ac18e17f..0000000000 --- a/jun_java_plugins/jun_dbutil/src/test/java/DBUtilTest6.java +++ /dev/null @@ -1,508 +0,0 @@ - - -import java.sql.Connection; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Scanner; - -import javax.sql.DataSource; - -import org.apache.commons.dbutils.QueryRunner; -import org.apache.commons.dbutils.handlers.KeyedHandler; -import org.apache.commons.dbutils.handlers.MapHandler; -import org.apache.commons.dbutils.handlers.MapListHandler; -import org.apache.commons.dbutils.handlers.ScalarHandler; -//import org.junit.Test; -import org.junit.Test; - -import com.jun.plugin.datasource.DataSourceUtil; -import com.jun.plugin.dbutils.dbutil.DBUtil; -import com.jun.plugin.dbutils.test.JdbcUtil; - -public class DBUtilTest6 { - - private DataSource ds = null; - // private static QueryRunner run =null; - public static QueryRunner run = null; - private static Connection conn = null; - static { - run = new QueryRunner(DataSourceUtil.getDataSource()); - conn = DataSourceUtil.getConn(); - run = run; - } - - @Test - public void TestDBTemplate() { - Object[] params = { "22" }; - List> list = new DBUtil().find(" select name,content,id from test where name= ? ", params); - System.out.println(list.size()); - } - - - @Test - public void query1() throws Exception { - // DBUtil run = new DBUtil(); - String sql = "select * from users"; - Map> mm = (Map>) run.query(sql, new KeyedHandler("id")); - System.err.println(mm); - Iterator it = mm.keySet().iterator(); - while (it.hasNext()) { - Map m1 = mm.get(it.next()); - System.err.println(m1.get("id") + "," + m1.get("name") + "," + m1.get("pwd")); - } - - } - - // 返回Map一行 - @Test - public void query5() throws Exception { - // DBUtil run = new DBUtil(); - String sql = "SELECT u.name as uname,c.name as cname" + " FROM users u INNER JOIN contacts c ON u.id=c.uid where u.id='U001'"; - System.err.println(sql); - Map mm = run.query(sql, new MapHandler()); - System.err.println(mm); - } - - @Test - public void query6() throws Exception { - // DBUtil run = new DBUtil(); - String sql = "SELECT u.name as uname,c.name as cname" + " FROM users u INNER JOIN contacts c ON u.id=c.uid"; - System.err.println(sql); - List> mm = run.query(sql, new MapListHandler()); - System.err.println(mm); - } - - @Test - public void query7() throws Exception { - // DBUtil run = new DBUtil(); - String sql = "select count(*) from contacts"; - Object o = run.query(sql, new ScalarHandler()); - Integer ss = Integer.valueOf(o.toString()); - System.err.println(ss); - } - - - - // 封装成唯一的一个bean - // @Test - // public void query2() throws Exception { - // DBUtil run = new DBUtil(); - // String sql = "select * from users where id=?"; - // User user = run.query(sql, new BeanHandler(User.class), "U003"); - // System.err.println(user); - // } - - /** - * 查询返回List< Bean> - * - * @throws Exception - */ - // @Test - // public void query3() throws Exception { - // DBUtil run = new DBUtil(); - // String sql = "select * from users"; - // List us = run.query(sql, new BeanListHandler(User.class)); - // for (User u : us) { - // System.err.println(u); - // } - // - // } - - @Test - public void insert1() throws Exception { - String sql = "insert into users values('U002','李四','888')"; - run.update(sql); - } - - // 接收? - @Test - public void insert2() throws Exception { - String sql = "insert into users values(?,?,?)"; - run.update(sql, "U003", "王五", "7777"); - } - - // 删除 - @Test - public void del1() throws Exception { - String sql = "delete from users where name=?"; - int len = run.update(sql, "李四"); - System.err.println(len); - } - - @Test - public void udpate1() throws Exception { - String sql = "update users set name=? where id=?"; - run.update(sql, "赵'七", "U001"); - } - - - - public static void main(String[] args) throws Exception { - // DBUtil run = new DBUtil(); - String sql = "insert into users values (?,?,?)"; - for (int i = 1; i <= 1043; i++) { - String uuid = "U"; - String num = "00000" + i;// 0001 - num = num.substring(num.length() - 6); - uuid = uuid + "-" + num; - run.update(sql, uuid, "Jack" + i, "AA"); - } - } - - - - - - @Test - public void tx1() throws Exception { - Connection con = DataSourceUtil.getConn(); - try { - String sql = "insert into users values('U008','AA','AA')"; - // 设置事务的开始标记 - con.setAutoCommit(false); - run.update(con, sql); - String sql2 = "insert into users values('U009,'AA','AA')"; - run.update(con, sql2); - // 提交 - con.commit(); - } catch (Exception e) { - System.err.println("出错了"); - con.rollback(); - } finally { - con.close(); - } - } - - @Test - public void login() throws Exception { - Scanner sc = new Scanner(System.in); - String name = sc.nextLine(); - String pwd = sc.nextLine(); - // DBUtil run = new DBUtil(); - String sql = "select * from users where name='" + name + "' and pwd='" + pwd + "'"; - System.err.println(sql); - List list = run.query(sql, new MapListHandler()); - if (list.size() > 0) { - System.err.println("OK"); - } else { - System.err.println("errorlll"); - } - } - - @Test - public void query11188() throws Exception { - QueryRunner run = new QueryRunner(); - String sql = "select * from users"; - Map> mm = (Map>) run.query(sql, new KeyedHandler("id")); - System.err.println(mm); - Iterator it = mm.keySet().iterator(); - while (it.hasNext()) { - Map m1 = mm.get(it.next()); - System.err.println(m1.get("id") + "," + m1.get("name") + "," + m1.get("pwd")); - } - - } - - // 返回Map一行 - @Test - public void query5188() throws Exception { - QueryRunner run = new QueryRunner(); - String sql = "SELECT u.name as uname,c.name as cname" + " FROM users u INNER JOIN contacts c ON u.id=c.uid where u.id='U001'"; - System.err.println(sql); - Map mm = run.query(sql, new MapHandler()); - System.err.println(mm); - } - - @Test - public void query688() throws Exception { - QueryRunner run = new QueryRunner(); - String sql = "SELECT u.name as uname,c.name as cname" + " FROM users u INNER JOIN contacts c ON u.id=c.uid"; - System.err.println(sql); - List> mm = run.query(sql, new MapListHandler()); - System.err.println(mm); - } - - @Test - public void query788() throws Exception { - QueryRunner run = new QueryRunner(); - String sql = "select count(*) from contacts"; - Object o = run.query(sql, new ScalarHandler()); - Integer ss = Integer.valueOf(o.toString()); - System.err.println(ss); - } - /* - * @Test public void query8() throws Exception{ QueryRunner run = new - * QueryRunner(); String sql = - * "select id as cid,name as cname,tel as ctel,sex from contacts"; - * List cs = run.query(sql,new - * BeanListHandler(Contact.class)); System.err.println(cs); } - */ - - /* - * @Test public void query9() throws Exception{ QueryRunner run = new - * QueryRunner(); String sql = "select * from contacts"; List cs = - * run.query(sql, new ResultSetHandler>(){ - * - * @Override public List handle(ResultSet rs) throws SQLException { - * List list = new ArrayList(); while(rs.next()){ Contact - * c = new Contact(); c.setCid(rs.getString("name")); - * c.setCname(rs.getString("id")); c.setCtel(rs.getString("tel")); - * list.add(c); } return list; } }); System.err.println(">>>:"+cs); } - */ - - // 封装成唯一的一个bean - /* - * @Test public void query2() throws Exception{ QueryRunner run = new - * QueryRunner(); String sql = "select * from users where id=?"; User user = - * run.query(sql,new BeanHandler(User.class),"U003"); - * System.err.println(user); } - */ - /** - * 查询返回List< Bean> - * - * @throws Exception - */ - /* - * @Test public void query3() throws Exception{ QueryRunner run = new - * QueryRunner(); String sql = "select * from users" ; List us = - * run.query(sql,new BeanListHandler(User.class)); for(User u:us){ - * System.err.println(u); } - * - * } - */ - - @Test - public void insert11() throws Exception { - QueryRunner run = new QueryRunner(); - String sql = "insert into users values('U002','李四','888')"; - run.update(sql); - } - - // 接收? - @Test - public void insert21() throws Exception { - QueryRunner run = new QueryRunner(); - String sql = "insert into users values(?,?,?)"; - run.update(sql, "U003", "王五", "7777"); - } - - // 删除 - @Test - public void del11() throws Exception { - QueryRunner run = new QueryRunner(); - String sql = "delete from users where name=?"; - int len = run.update(sql, "李四"); - System.err.println(len); - } - - @Test - public void udpate11() throws Exception { - QueryRunner run = new QueryRunner(); - String sql = "update users set name=? where id=?"; - run.update(sql, "赵'七", "U001"); - } - - // 接收一个ds - // private DataSource ds; - /* - * public QueryRunner() { } public QueryRunner(DataSource ds) { this.ds = - * ds; } - */ - - // @Test - /* - * public void myutils2(){ QueryRunner run = new QueryRunner(); String sql = - * "select * from contacts"; List us = - * run.queryForBean(sql,Contact.class); for(Contact u:us){ - * System.err.println(u); } - * - * } - */ - /* - * @Test public void myutils3(){ QueryRunner run = new QueryRunner(); String - * sql = "select * from users" ; List cs = run.query(sql,new - * MyBeanListHandler(User.class)); for(User c:cs){ - * System.err.println(">>:"+c); } } - */ - - // 不确定条件的查询 - /* - * @Test public void query1() throws Exception{ QueryRunner run = new - * QueryRunner(); Contact c = new Contact(); //c.setId("C001"); - * c.setName("王'"); c.setSex("1"); c.setTel("123"); c.setAddr("中国"); - * c.setAge(55); String sql = "select * from contacts where 1=1"; - * List params = new ArrayList(); if(c.getId()!=null){ - * sql+=" and id=?"; params.add(c.getId()); } if(c.getSex()!=null){ sql = - * sql+" and sex=?"; params.add(c.getSex()); } if(c.getName()!=null){ - * sql+=" and name like ?"; params.add("%"+c.getName()+"%"); } - * if(c.getAddr()!=null){ sql+= " and addr like ?"; - * params.add("%"+c.getAddr()+"%"); } if(c.getTel()!=null){ - * sql+=" and tel like ?"; params.add("%"+c.getTel()+"%"); } - * if(c.getAge()!=null){ sql+=" and age=?" ; params.add(c.getAge()); } - * System.err.println(">>>>>>:"+sql); System.err.println(params); - * List cs = run.query(sql, new - * BeanListHandler(Contact.class), params.toArray()); for(Contact - * cc:cs){ System.err.println(cc); } } - */ - - @Test - public void tx188() throws Exception { - QueryRunner run = new QueryRunner(); - Connection con = JdbcUtil.getConnection(); - try { - String sql = "insert into users values('U008','AA','AA')"; - // 设置事务的开始标记 - con.setAutoCommit(false); - run.update(con, sql); - String sql2 = "insert into users values('U009,'AA','AA')"; - run.update(con, sql2); - // 提交 - con.commit(); - } catch (Exception e) { - System.err.println("出错了"); - con.rollback(); - } finally { - con.close(); - } - } - - @Test - public void login88() throws Exception { - Scanner sc = new Scanner(System.in); - String name = sc.nextLine(); - String pwd = sc.nextLine(); - QueryRunner run = new QueryRunner(); - String sql = "select * from users where name='" + name + "' and pwd='" + pwd + "'"; - System.err.println(sql); - List list = run.query(sql, new MapListHandler()); - if (list.size() > 0) { - System.err.println("OK"); - } else { - System.err.println("errorlll"); - } - } - - public static void main1188(String[] args) throws Exception { - QueryRunner run = new QueryRunner(); - String sql = "insert into users values (?,?,?)"; - for (int i = 1; i <= 1043; i++) { - String uuid = "U"; - String num = "00000" + i;// 0001 - num = num.substring(num.length() - 6); - uuid = uuid + "-" + num; - run.update(sql, uuid, "Jack" + i, "AA"); - } - } - - @Test - public void query111() throws Exception { - QueryRunner run = new QueryRunner(); - String sql = "select * from users"; - Map> mm = (Map>) run.query(sql, new KeyedHandler("id")); - System.err.println(mm); - Iterator it = mm.keySet().iterator(); - while (it.hasNext()) { - Map m1 = mm.get(it.next()); - System.err.println(m1.get("id") + "," + m1.get("name") + "," + m1.get("pwd")); - } - - } - - // 返回Map一行 - @Test - public void query51() throws Exception { - QueryRunner run = new QueryRunner(); - String sql = "SELECT u.name as uname,c.name as cname" + " FROM users u INNER JOIN contacts c ON u.id=c.uid where u.id='U001'"; - System.err.println(sql); - Map mm = run.query(sql, new MapHandler()); - System.err.println(mm); - } - - @Test - public void query61() throws Exception { - QueryRunner run = new QueryRunner(); - String sql = "SELECT u.name as uname,c.name as cname" + " FROM users u INNER JOIN contacts c ON u.id=c.uid"; - System.err.println(sql); - List> mm = run.query(sql, new MapListHandler()); - System.err.println(mm); - } - - /* - * @Test public void query7() throws Exception{ QueryRunner run = new - * QueryRunner(); String sql = "select count(*) from contacts"; Object o = - * run.query(sql,new ScalarHandler()); Integer ss = - * Integer.valueOf(o.toString()); System.err.println(ss); } - * - * @Test public void query8() throws Exception{ QueryRunner run = new - * QueryRunner(); String sql = - * "select id as cid,name as cname,tel as ctel,sex from contacts"; - * List cs = run.query(sql,new - * BeanListHandler(Contact.class)); System.err.println(cs); } - */ - - /* - * @Test public void query9() throws Exception{ QueryRunner run = new - * QueryRunner(); String sql = "select * from contacts"; List cs = - * run.query(sql, new ResultSetHandler>(){ - * - * @Override public List handle(ResultSet rs) throws SQLException { - * List list = new ArrayList(); while(rs.next()){ Contact - * c = new Contact(); c.setCid(rs.getString("name")); - * c.setCname(rs.getString("id")); c.setCtel(rs.getString("tel")); - * list.add(c); } return list; } }); System.err.println(">>>:"+cs); } - */ - - // 封装成唯一的一个bean - /* - * @Test public void query2() throws Exception{ QueryRunner run = new - * QueryRunner(); String sql = "select * from users where id=?"; User user = - * run.query(sql,new BeanHandler(User.class),"U003"); - * System.err.println(user); } - */ - /** - * 查询返回List< Bean> - * - * @throws Exception - */ - /* - * @Test public void query3() throws Exception{ QueryRunner run = new - * QueryRunner(); String sql = "select * from users" ; List us = - * run.query(sql,new BeanListHandler(User.class)); for(User u:us){ - * System.err.println(u); } - * - * } - */ - - @Test - public void insert188() throws Exception { - QueryRunner run = new QueryRunner(); - String sql = "insert into users values('U002','李四','888')"; - run.update(sql); - } - - // 接收? - @Test - public void insert288() throws Exception { - QueryRunner run = new QueryRunner(); - String sql = "insert into users values(?,?,?)"; - run.update(sql, "U003", "王五", "7777"); - } - - // 删除 - @Test - public void del188() throws Exception { - QueryRunner run = new QueryRunner(); - String sql = "delete from users where name=?"; - int len = run.update(sql, "李四"); - System.err.println(len); - } - - @Test - public void udpate881() throws Exception { - QueryRunner run = new QueryRunner(); - String sql = "update users set name=? where id=?"; - run.update(sql, "赵'七", "U001"); - } - -} diff --git a/jun_java_plugins/jun_dbutil/src/test/java/HandlerTest.java b/jun_java_plugins/jun_dbutil/src/test/java/HandlerTest.java deleted file mode 100644 index 3a7ebe68ac..0000000000 --- a/jun_java_plugins/jun_dbutil/src/test/java/HandlerTest.java +++ /dev/null @@ -1,80 +0,0 @@ -import org.apache.commons.dbutils.QueryRunner; -import org.apache.commons.dbutils.handlers.BeanListHandler; -import org.apache.commons.dbutils.handlers.MapHandler; -import org.apache.commons.dbutils.handlers.MapListHandler; -import org.apache.commons.dbutils.handlers.ScalarHandler; -import org.junit.Test; - -import com.jun.plugin.dbutils.jdbc.JdbcUtils; - -import java.sql.SQLException; -import java.util.List; -import java.util.Map; - -/** - * Created by chenghui.zhang on 2018/2/10. - */ -public class HandlerTest { - - /** - * BeanListHandler的应用,它是多行处理器 - * 每行对象一个Stu对象! - * - * @throws Exception - */ - @Test - public void fun3() throws Exception { - QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource()); - String sql = "select * from user"; - List stuList = qr.query(sql, new BeanListHandler<>(User.class)); - - System.out.println(stuList); - } - - /** - * MapHandler的应用,它是单行处理器,把一行转换成一个Map对象 - * - * @throws SQLException - */ - @Test - public void fun4() throws SQLException { - QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource()); - String sql = "select * from user where uid=?"; - Object[] params = {1001}; - Map map = qr.query(sql, new MapHandler(), params); - - System.out.println(map); - } - - /** - * MapListHandler,它是多行处理器,把每行都转换成一个Map,即List - * - * @throws SQLException - */ - @Test - public void fun5() throws SQLException { - QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource()); - String sql = "select * from user"; - List> mapList = qr.query(sql, new MapListHandler()); - - System.out.println(mapList); - } - - /** - * ScalarHandler,它是单行单列时使用,最为合适! - * - * @throws SQLException - */ - @Test - public void fun6() throws SQLException { - QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource()); - String sql = "select count(*) from user"; - /* - * Integer、Long、BigInteger - */ - Number cnt = (Number) qr.query(sql, new ScalarHandler()); - - long c = cnt.longValue(); - System.out.println(c); - } -} diff --git a/jun_java_plugins/jun_dbutil/src/test/java/User.java b/jun_java_plugins/jun_dbutil/src/test/java/User.java deleted file mode 100644 index 6e6773c419..0000000000 --- a/jun_java_plugins/jun_dbutil/src/test/java/User.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Created by chenghui.zhang on 2018/2/10. - */ -public class User { - private Long uid; - private String username; - private String gender; - private Integer age; - - public Long getUid() { - return uid; - } - - public void setUid(Long uid) { - this.uid = uid; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getGender() { - return gender; - } - - public void setGender(String gender) { - this.gender = gender; - } - - public Integer getAge() { - return age; - } - - public void setAge(Integer age) { - this.age = age; - } -} diff --git a/jun_java_plugins/jun_dbutil/src/test/java/jdbc/HandlerTest.java b/jun_java_plugins/jun_dbutil/src/test/java/jdbc/HandlerTest.java deleted file mode 100644 index f8245fec03..0000000000 --- a/jun_java_plugins/jun_dbutil/src/test/java/jdbc/HandlerTest.java +++ /dev/null @@ -1,81 +0,0 @@ -package jdbc; -import org.apache.commons.dbutils.QueryRunner; -import org.apache.commons.dbutils.handlers.BeanListHandler; -import org.apache.commons.dbutils.handlers.MapHandler; -import org.apache.commons.dbutils.handlers.MapListHandler; -import org.apache.commons.dbutils.handlers.ScalarHandler; -import org.junit.Test; - -import com.jun.plugin.dbutils.jdbc.JdbcUtils; - -import java.sql.SQLException; -import java.util.List; -import java.util.Map; - -/** - * Created by chenghui.zhang on 2018/2/10. - */ -public class HandlerTest { - - /** - * BeanListHandler的应用,它是多行处理器 - * 每行对象一个Stu对象! - * - * @throws Exception - */ - @Test - public void fun3() throws Exception { - QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource()); - String sql = "select * from user"; - List stuList = qr.query(sql, new BeanListHandler<>(User.class)); - - System.out.println(stuList); - } - - /** - * MapHandler的应用,它是单行处理器,把一行转换成一个Map对象 - * - * @throws SQLException - */ - @Test - public void fun4() throws SQLException { - QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource()); - String sql = "select * from user where uid=?"; - Object[] params = {1001}; - Map map = qr.query(sql, new MapHandler(), params); - - System.out.println(map); - } - - /** - * MapListHandler,它是多行处理器,把每行都转换成一个Map,即List - * - * @throws SQLException - */ - @Test - public void fun5() throws SQLException { - QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource()); - String sql = "select * from user"; - List> mapList = qr.query(sql, new MapListHandler()); - - System.out.println(mapList); - } - - /** - * ScalarHandler,它是单行单列时使用,最为合适! - * - * @throws SQLException - */ - @Test - public void fun6() throws SQLException { - QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource()); - String sql = "select count(*) from user"; - /* - * Integer、Long、BigInteger - */ - Number cnt = (Number) qr.query(sql, new ScalarHandler()); - - long c = cnt.longValue(); - System.out.println(c); - } -} diff --git a/jun_java_plugins/jun_dbutil/src/test/java/jdbc/README.md b/jun_java_plugins/jun_dbutil/src/test/java/jdbc/README.md deleted file mode 100644 index b39f581008..0000000000 --- a/jun_java_plugins/jun_dbutil/src/test/java/jdbc/README.md +++ /dev/null @@ -1,65 +0,0 @@ -# jdbc-utils - -Jdbc-utils 工具利用 ThreadLocal 使其获取的数据库连接具有事务性,并解决并发的问题,继承 commons-dbutils 的 QueryRunner 类,再复写它的方法,复写方法中用 Jdbc-utils 提供具有事务的连接对象,这样就实现了方法本身自动处理连接对象,使操作数据库的代码更加优雅! - - - -### ThreadLocal - -ThreadLocal 类只有三个方法: - -```java -void set(T value); //保存值 -T get(); //获取值 -void remove(); //移除值 -``` - -ThreadLocal 内部其实是个 Map 来保存数据。虽然在使用 ThreadLocal 时只给出了值,没有给出键,其实它内部使用了当前线程做为键。 - -![threadlocal](https://raw.githubusercontent.com/objcoding/objcoding.github.io/master/images/threadlocal.png) - - - -### QueryRunner API - -- update - -```java -int update(String sql, Object... params); //可执行增、删、改语句 -int update(Connection con, String sql, Object... parmas); //需要调用者提供Connection,这说明本方法不再管理Connection了。支持事务! -``` - -- query - -```java -T query(String sql, ResultSetHandler rsh, Object... params); //可执行查询,它会先得到ResultSet,然后调用rsh的handle()把rs转换成需要的类型! -T query(Connection con, String sql, ResultSetHadler rsh, Object... params); //支持事务。 -``` - - - -### ResultSetHandler 接口 - -- BeanHandler (单行) --> 构造器需要一个 Class 类型的参数,用来把一行结果转换成指定类型的 javaBean 对象; - - -- BeanListHandler (多行) --> 构造器也是需要一个 Class 类型的参数,用来把一行结果集转换成一个javabean,那么多行就是转换成 List 对象,一堆 javabean; - - - -- MapHandler (单行) --> 把一行结果集转换Map对象: - - -一行记录: - -| uid | username | age | gender | -| ---- | --------- | ---- | ------ | -| 1001 | objcoding | 18 | Male | - -对应一个Map: - -```json -{uid:1001, username:zs, age:99, gender:male} -``` - -- MapListHandler (多行) --> 把一行记录转换成一个 Map,多行就是多个 Map,即 List!ScalarHandler (单行单列) --> 通常用与 select count(*) from user 语句!结果集是单行单列的!它返回一个 Object。 \ No newline at end of file diff --git a/jun_java_plugins/jun_dbutil/src/test/java/jdbc/User.java b/jun_java_plugins/jun_dbutil/src/test/java/jdbc/User.java deleted file mode 100644 index 1e4a53bf75..0000000000 --- a/jun_java_plugins/jun_dbutil/src/test/java/jdbc/User.java +++ /dev/null @@ -1,42 +0,0 @@ -package jdbc; -/** - * Created by chenghui.zhang on 2018/2/10. - */ -public class User { - private Long uid; - private String username; - private String gender; - private Integer age; - - public Long getUid() { - return uid; - } - - public void setUid(Long uid) { - this.uid = uid; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getGender() { - return gender; - } - - public void setGender(String gender) { - this.gender = gender; - } - - public Integer getAge() { - return age; - } - - public void setAge(Integer age) { - this.age = age; - } -} diff --git a/jun_java_plugins/jun_designpattern/pom.xml b/jun_java_plugins/jun_designpattern/pom.xml deleted file mode 100644 index f0438bc73f..0000000000 --- a/jun_java_plugins/jun_designpattern/pom.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_designpattern - 1.0 - jar - - - - UTF-8 - - - - - junit - junit - 3.8.1 - test - - - - - mysql - mysql-connector-java - 5.1.40 - - - - - jun_designpattern - - - - - org.apache.maven.plugins - - maven-war-plugin - - 2.6 - - - - false - - - - - - - - - diff --git a/jun_java_plugins/jun_designpattern/src/main/java/decorator/Test.java b/jun_java_plugins/jun_designpattern/src/main/java/decorator/Test.java deleted file mode 100644 index 8e936a0a64..0000000000 --- a/jun_java_plugins/jun_designpattern/src/main/java/decorator/Test.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - *
- * Copyright:		Copyright(C) 2011-2012, ketayao.com
- * Filename:		decorator.Test.java
- * Class:			Test
- * Date:			2012-5-7
- * Author:			ketayao
- * Version          1.1.0
- * Description:		
- *
- * 
- **/ - -package decorator; - -/** - * - * @author Wujun - * Version 1.1.0 - * @since 2012-5-7 上午10:38:48 - */ - -public class Test { - - /** - * 描述 - * @param args - */ - public static void main(String[] args) { - Decorator decorator = new ConcreteDecoratorA(new ConcreteComponentA()); - decorator.setAddedState("我是新增功能!"); - decorator.operation(); - } - -} diff --git a/jun_java_plugins/jun_designpattern/src/main/java/memento/Memento.java b/jun_java_plugins/jun_designpattern/src/main/java/memento/Memento.java deleted file mode 100644 index 3ad4a17a12..0000000000 --- a/jun_java_plugins/jun_designpattern/src/main/java/memento/Memento.java +++ /dev/null @@ -1,9 +0,0 @@ -package memento; - -/** - * @author Wujun - * - */ -public interface Memento { - -} diff --git a/jun_java_plugins/jun_designpattern/src/main/java/proxy/Test.java b/jun_java_plugins/jun_designpattern/src/main/java/proxy/Test.java deleted file mode 100644 index 1c3aecf463..0000000000 --- a/jun_java_plugins/jun_designpattern/src/main/java/proxy/Test.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - *
- * Copyright:		Copyright(C) 2011-2012, ketayao.com
- * Filename:		proxy.Test.java
- * Class:			Test
- * Date:			2012-5-7
- * Author:			ketayao
- * Version          1.1.0
- * Description:		
- *
- * 
- **/ - -package proxy; - - -/** - * - * @author Wujun - * Version 1.1.0 - * @since 2012-5-7 上午11:04:43 - */ - -public class Test { - - /** - * 描述 - * @param args - */ - public static void main(String[] args) { - RealSubject subject = new RealSubject(); - subject.request(); - Proxy proxy = new Proxy(subject); - proxy.request(); - - // 动态代理 - DynamicProxy dynamicProxy = new DynamicProxy(); - Subject proxySubject = dynamicProxy.getProxyInterface(subject); - proxySubject.request(); - - } - -} diff --git a/jun_java_plugins/jun_designpattern/src/main/java/simplefactory/TestFactory.java b/jun_java_plugins/jun_designpattern/src/main/java/simplefactory/TestFactory.java deleted file mode 100644 index 6eb9bb9f78..0000000000 --- a/jun_java_plugins/jun_designpattern/src/main/java/simplefactory/TestFactory.java +++ /dev/null @@ -1,24 +0,0 @@ -/** - * - */ -package simplefactory; - -/** - * @author Wujun - * - */ -public class TestFactory { - - /** - * @param args - */ - public static void main(String[] args) { - //Api api = ApiFactory.createApi(1); - Api api = ApiFactory.createApi(2); - api.print(); - - Api api2 = ApiFactory.createApiByPropertites(); - api2.print(); - } - -} diff --git a/jun_java_plugins/jun_designpattern/src/main/java/strategy/Test.java b/jun_java_plugins/jun_designpattern/src/main/java/strategy/Test.java deleted file mode 100644 index a9cb0d9deb..0000000000 --- a/jun_java_plugins/jun_designpattern/src/main/java/strategy/Test.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - *
- * Copyright:		Copyright(C) 2011-2012, ketayao.com
- * Filename:		strategy.Test.java
- * Class:			Test
- * Date:			2012-5-7
- * Author:			ketayao
- * Version          1.1.0
- * Description:		
- *
- * 
- **/ - -package strategy; - -/** - * - * @author Wujun - * Version 1.1.0 - * @since 2012-5-7 上午10:59:53 - */ - -public class Test { - - /** - * 描述 - * @param args - */ - public static void main(String[] args) { - Context context = new Context(new ConcreteStrategyA()); - context.contextInterface(); - - Context context2 = new Context(new ConcreteStrategyB()); - context2.contextInterface(); - } - -} diff --git a/jun_java_plugins/jun_drools/README.md b/jun_java_plugins/jun_drools/README.md deleted file mode 100644 index 30404ce4c5..0000000000 --- a/jun_java_plugins/jun_drools/README.md +++ /dev/null @@ -1 +0,0 @@ -TODO \ No newline at end of file diff --git a/jun_java_plugins/jun_drools/pom.xml b/jun_java_plugins/jun_drools/pom.xml deleted file mode 100644 index fea937a422..0000000000 --- a/jun_java_plugins/jun_drools/pom.xml +++ /dev/null @@ -1,71 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_drools - 1.0 - pom - - - UTF-8 - 1.8 - 1.8 - - - - - - - - - junit - junit - 3.8.1 - test - - - javax.servlet - javax.servlet-api - 3.1.0 - provided - - - mysql - mysql-connector-java - 5.1.40 - - - - - - - jdk-1.8 - - true - 1.8 - - - 1.8 - 1.8 - 1.8 - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.0 - - 1.8 - 1.8 - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_easycaptcha/pom.xml b/jun_java_plugins/jun_easycaptcha/pom.xml deleted file mode 100644 index 6fee82ee8b..0000000000 --- a/jun_java_plugins/jun_easycaptcha/pom.xml +++ /dev/null @@ -1,106 +0,0 @@ - - 4.0.0 - - io.github.wujun728 - jun_easycaptcha - 1.0 - jar - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 8 - 8 - - - - - - - UTF-8 - UTF-8 - 1.8 - - - - - - javax.servlet - javax.servlet-api - 3.1.0 - provided - - - junit - junit - 4.12 - test - - - - - - release - - - - - org.apache.maven.plugins - maven-source-plugin - 2.2.1 - - - package - - jar-no-fork - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.9.1 - - - package - - jar - - - - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.5 - - - verify - - sign - - - - - - - - - oss - https://oss.sonatype.org/content/repositories/snapshots/ - - - oss - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/servlet/CaptchaServlet.java b/jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/servlet/CaptchaServlet.java deleted file mode 100644 index 21177591cb..0000000000 --- a/jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/servlet/CaptchaServlet.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.wf.captcha.servlet; - -import java.awt.*; -import java.io.IOException; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.wf.captcha.GifCaptcha; -import com.wf.captcha.SpecCaptcha; -import com.wf.captcha.base.Captcha; -import com.wf.captcha.utils.CaptchaUtil; - -/** - * 验证码servlet - * Created by 王帆 on 2018-07-27 上午 10:08. - */ -public class CaptchaServlet extends HttpServlet { - private static final long serialVersionUID = -90304944339413093L; - - public void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { -// SpecCaptcha captcha = new SpecCaptcha(130, 48, 6); - GifCaptcha captcha = new GifCaptcha(130, 48, 6); - - // 设置内置字体 - try { - captcha.setFont(Captcha.FONT_10); - } catch (FontFormatException e) { - e.printStackTrace(); - } - CaptchaUtil.out(captcha, request, response); - } - - public void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - doGet(request, response); - } - -} diff --git a/jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/utils/FileUtil.java b/jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/utils/FileUtil.java deleted file mode 100644 index 41900dc0f8..0000000000 --- a/jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/utils/FileUtil.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.wf.captcha.utils; - -import java.io.*; -import java.util.Objects; - -/** - * 文件操作工具类,此类源码从org.apache.commons.io.FileUtils中复制 - * - * @author zrh 455741807@qq.com - * @date 2022-05-07 - */ -public class FileUtil { - public static final int DEFAULT_BUFFER_SIZE = 8192; - public static final int EOF = -1; - - /** - * 文件流复制 - * @param inputStream - * @param file - * @throws IOException - */ - public static void copyToFile(final InputStream inputStream, final File file) throws IOException { - try (OutputStream out = openOutputStream(file)) { - copy(inputStream, out); - } - } - - public static FileOutputStream openOutputStream(final File file) throws IOException { - return openOutputStream(file, false); - } - - public static FileOutputStream openOutputStream(final File file, final boolean append) throws IOException { - Objects.requireNonNull(file, "file"); - if (file.exists()) { - requireFile(file, "file"); - requireCanWrite(file, "file"); - } else { - createParentDirectories(file); - } - return new FileOutputStream(file, append); - } - - private static File requireFile(final File file, final String name) { - Objects.requireNonNull(file, name); - if (!file.isFile()) { - throw new IllegalArgumentException("Parameter '" + name + "' is not a file: " + file); - } - return file; - } - - private static void requireCanWrite(final File file, final String name) { - Objects.requireNonNull(file, "file"); - if (!file.canWrite()) { - throw new IllegalArgumentException("File parameter '" + name + " is not writable: '" + file + "'"); - } - } - - public static File createParentDirectories(final File file) throws IOException { - return mkdirs(getParentFile(file)); - } - - private static File mkdirs(final File directory) throws IOException { - if ((directory != null) && (!directory.mkdirs() && !directory.isDirectory())) { - throw new IOException("Cannot create directory '" + directory + "'."); - } - return directory; - } - - private static File getParentFile(final File file) { - return file == null ? null : file.getParentFile(); - } - - public static int copy(final InputStream inputStream, final OutputStream outputStream) throws IOException { - final long count = copyLarge(inputStream, outputStream); - if (count > Integer.MAX_VALUE) { - return EOF; - } - return (int) count; - } - - public static long copyLarge(final InputStream inputStream, final OutputStream outputStream) - throws IOException { - return copy(inputStream, outputStream, DEFAULT_BUFFER_SIZE); - } - - public static long copy(final InputStream inputStream, final OutputStream outputStream, final int bufferSize) - throws IOException { - return copyLarge(inputStream, outputStream, byteArray(bufferSize)); - } - - public static long copyLarge(final InputStream inputStream, final OutputStream outputStream, final byte[] buffer) - throws IOException { - Objects.requireNonNull(inputStream, "inputStream"); - Objects.requireNonNull(outputStream, "outputStream"); - long count = 0; - int n; - while (EOF != (n = inputStream.read(buffer))) { - outputStream.write(buffer, 0, n); - count += n; - } - return count; - } - - public static byte[] byteArray(final int size) { - return new byte[size]; - } -} diff --git a/jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/utils/FontsUtil.java b/jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/utils/FontsUtil.java deleted file mode 100644 index 29ae619042..0000000000 --- a/jun_java_plugins/jun_easycaptcha/src/main/java/com/wf/captcha/utils/FontsUtil.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.wf.captcha.utils; - -import sun.security.action.GetPropertyAction; - -import java.awt.*; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Path; -import java.nio.file.Paths; - -import static java.security.AccessController.doPrivileged; - -/** - * 解决自定义字体读取时,产生.tmp临时文件耗磁盘的问题。 - * - * 解决思路: - * Font类的createFont有个重载方法–>java.awt.Font#createFont(int, java.io.File), - * 不产生临时文件获取字体代码实现 - * - * URL url = FontLoader.class.getResource("font/SourceHanSansCN-Regular.otf"); - * String pathString = url.getFile(); - * Font selfFont = Font.createFont(Font.TRUETYPE_FONT, new File(pathString)); - * - * 上面的解决方案会导致另一个问题,字体文件在生产环境是在jar包里,部分操作系统环境下,直接读取读取不到,只能通过流的方式获取。 - * - * 因此,本方案采用的办法是把jar包中的字体文件复制到java.io.tmpdir临时文件夹中 - * ,再采用java.awt.Font#createFont(int, java.io.File)的方式产生字体,既解决了临时文件tmp消耗磁盘的问题,也解决了 - * 部分操作系统下读不到文件的问题。 - * - * @author zrh 455741807@qq.com - * @date 2022-05-07 - * - */ -public class FontsUtil { - private static final Path tmpdir = Paths.get(doPrivileged(new GetPropertyAction("java.io.tmpdir"))); - - /** - * 手动复制字体文件到临时目录. 调用传文件的构造方法创建字体 - * @param fontName 字体文件名称 - * @return - */ - public static Font getFont(String fontName, int style, float size) { - Font font = null; - - File tempFontFile = new File(tmpdir.toUri().getPath() + fontName); - if(!tempFontFile.exists()){ - //临时文件不存在 - copyTempFontFile(fontName, tempFontFile); - } - if(tempFontFile.exists()) { - try { - font = Font.createFont(Font.TRUETYPE_FONT, tempFontFile).deriveFont(style, size);; - } catch (FontFormatException | IOException e) { - e.printStackTrace(); - tempFontFile.delete(); - } - } - return font; - } - - /** - * 复制字体文件到临时文件目录 - * @param fontName - * @param tempFontFile - */ - private static synchronized void copyTempFontFile(String fontName, File tempFontFile){ - try(InputStream is = FontsUtil.class.getResourceAsStream("/" + fontName)){ - FileUtil.copyToFile(is, tempFontFile); - } catch (IOException e) { - e.printStackTrace(); - } - } - -} diff --git a/jun_java_plugins/jun_easycaptcha/src/test/java/com/wf/captcha/CaptchaTest.java b/jun_java_plugins/jun_easycaptcha/src/test/java/com/wf/captcha/CaptchaTest.java deleted file mode 100644 index d4ee3d5d51..0000000000 --- a/jun_java_plugins/jun_easycaptcha/src/test/java/com/wf/captcha/CaptchaTest.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.wf.captcha; - -import org.junit.Test; - -import java.io.File; -import java.io.FileOutputStream; - -/** - * 测试类 - * Created by 王帆 on 2018-07-27 上午 10:08. - */ -public class CaptchaTest { - - @Test - public void test() throws Exception { - /*for (int i = 0; i < 10; i++) { - SpecCaptcha specCaptcha = new SpecCaptcha(); - specCaptcha.setLen(4); - specCaptcha.setFont(i, 32f); - System.out.println(specCaptcha.text()); - specCaptcha.out(new FileOutputStream(new File("C:/Java/aa" + i + ".png"))); - }*/ - } - - @Test - public void testGIf() throws Exception { - /*for (int i = 0; i < 10; i++) { - GifCaptcha gifCaptcha = new GifCaptcha(); - gifCaptcha.setLen(5); - gifCaptcha.setFont(i, 32f); - System.out.println(gifCaptcha.text()); - gifCaptcha.out(new FileOutputStream(new File("C:/Java/aa" + i + ".gif"))); - }*/ - } - - @Test - public void testHan() throws Exception { - /*for (int i = 0; i < 10; i++) { - ChineseCaptcha chineseCaptcha = new ChineseCaptcha(); - System.out.println(chineseCaptcha.text()); - chineseCaptcha.out(new FileOutputStream(new File("C:/Java/aa" + i + ".png"))); - }*/ - } - - @Test - public void testGifHan() throws Exception { - /*for (int i = 0; i < 10; i++) { - ChineseGifCaptcha chineseGifCaptcha = new ChineseGifCaptcha(); - System.out.println(chineseGifCaptcha.text()); - chineseGifCaptcha.out(new FileOutputStream(new File("C:/Java/aa" + i + ".gif"))); - }*/ - } - - @Test - public void testArit() throws Exception { - /*for (int i = 0; i < 10; i++) { - ArithmeticCaptcha specCaptcha = new ArithmeticCaptcha(); - specCaptcha.setLen(3); - specCaptcha.setFont(i, 28f); - System.out.println(specCaptcha.getArithmeticString() + " " + specCaptcha.text()); - specCaptcha.out(new FileOutputStream(new File("C:/Java/aa" + i + ".png"))); - }*/ - } - - @Test - public void testBase64() throws Exception { - /*GifCaptcha specCaptcha = new GifCaptcha(); - System.out.println(specCaptcha.toBase64(""));*/ - } - -} diff --git a/jun_java_plugins/jun_easycaptcha/web/WEB-INF/web.xml b/jun_java_plugins/jun_easycaptcha/web/WEB-INF/web.xml deleted file mode 100644 index ebe475abdb..0000000000 --- a/jun_java_plugins/jun_easycaptcha/web/WEB-INF/web.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - CaptchaServlet - com.wf.captcha.servlet.CaptchaServlet - - - CaptchaServlet - /captcha - - \ No newline at end of file diff --git a/jun_java_plugins/jun_easycaptcha/web/index.html b/jun_java_plugins/jun_easycaptcha/web/index.html deleted file mode 100644 index 607f9deccc..0000000000 --- a/jun_java_plugins/jun_easycaptcha/web/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - - 验证码测试 - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_ehcache/pom.xml b/jun_java_plugins/jun_ehcache/pom.xml deleted file mode 100644 index 35fdad1dbf..0000000000 --- a/jun_java_plugins/jun_ehcache/pom.xml +++ /dev/null @@ -1,18 +0,0 @@ - - 4.0.0 - io.github.wujun728 - 1.0 - jun_ehcache - - - - - net.sf.ehcache - ehcache - 2.10.3 - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_ehcache/src/main/java/com/jun/plugin/ehcache/EhcacheTest.java b/jun_java_plugins/jun_ehcache/src/main/java/com/jun/plugin/ehcache/EhcacheTest.java deleted file mode 100644 index ed190a462b..0000000000 --- a/jun_java_plugins/jun_ehcache/src/main/java/com/jun/plugin/ehcache/EhcacheTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.jun.plugin.ehcache; - -import net.sf.ehcache.Cache; -import net.sf.ehcache.CacheManager; -import net.sf.ehcache.Element; - -public class EhcacheTest { - - public static void main(String[] args) { - CacheManager manager=CacheManager.create("./src/main/resources/ehcache.xml"); - Cache c=manager.getCache("a"); - Element e=new Element("test","abcde"); - c.put(e); - - Element e2=c.get("test"); - System.out.println(e2); - System.out.println(e2.getObjectValue()); - - c.flush(); - manager.shutdown(); - - } -} diff --git a/jun_java_plugins/jun_ehcache/src/main/resources/ehcache.xml b/jun_java_plugins/jun_ehcache/src/main/resources/ehcache.xml deleted file mode 100644 index a199a7c18f..0000000000 --- a/jun_java_plugins/jun_ehcache/src/main/resources/ehcache.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_email/doc/myemail.md b/jun_java_plugins/jun_email/doc/myemail.md deleted file mode 100644 index ca1fd8b1e3..0000000000 --- a/jun_java_plugins/jun_email/doc/myemail.md +++ /dev/null @@ -1,141 +0,0 @@ -# myemail - -## 特性 - -- 简洁的邮件发送API -- 支持自定义发件人昵称 -- 支持扩展邮件Message -- 支持抄送/HTML/附件 -- 支持异步发送 -- 支持邮件模板 - -## 使用 - -**maven坐标** - -```xml - - io.github.biezhi - oh-my-email - 0.0.4 - -``` - -## 举个栗子🌰 - -```java -@Before -public void before() throws GeneralSecurityException { - // 配置,一次即可 - OhMyEmail.config(SMTP_QQ(), "xiaojiejie@qq.com", "your@password"); -} - -@Test -public void testSendText() throws MessagingException { - OhMyEmail.subject("这是一封测试TEXT邮件") - .from("小姐姐的邮箱") - .to("xiaojiejie@gmail.com") - .text("信件内容") - .send(); -} - -@Test -public void testSendHtml() throws MessagingException { - OhMyEmail.subject("这是一封测试HTML邮件") - .from("小姐姐的邮箱") - .to("xiaojiejie@gmail.com") - .html("

信件内容

") - .send(); -} - -@Test -public void testSendAttach() throws MessagingException { - OhMyEmail.subject("这是一封测试附件邮件") - .from("小姐姐的邮箱") - .to("xiaojiejie@gmail.com") - .html("

信件内容

") - .attach(new File("/Users/biezhi/Downloads/hello.jpeg"), "测试图片.jpeg") - .send(); -} - -@Test -public void testSendAttachURL() throws MessagingException { - try { - OhMyEmail.subject("这是一封测试网络资源作为附件的邮件") - .from("小姐姐的邮箱") - .to("xiaojiejie@gmail.com") - .html("

信件内容

") - .attachURL(new URL("https://avatars1.githubusercontent.com/u/2784452?s=40&v=4"), "测试图片.jpeg") - .send(); - } catch (MalformedURLException e) { - e.printStackTrace(); - } -} - - -@Test -public void testPebble() throws IOException, PebbleException, MessagingException { - PebbleEngine engine = new PebbleEngine.Builder().build(); - PebbleTemplate compiledTemplate = engine.getTemplate("register.html"); - - Map context = new HashMap(); - context.put("username", "biezhi"); - context.put("email", "admin@biezhi.me"); - - Writer writer = new StringWriter(); - compiledTemplate.evaluate(writer, context); - - String output = writer.toString(); - System.out.println(output); - - OhMyEmail.subject("这是一封测试Pebble模板邮件") - .from("小姐姐的邮箱") - .to("xiaojiejie@gmail.com") - .html(output) - .send(); -} - -@Test -public void testJetx() throws IOException, PebbleException, MessagingException { - JetEngine engine = JetEngine.create(); - JetTemplate template = engine.getTemplate("/register.jetx"); - - Map context = new HashMap(); - context.put("username", "biezhi"); - context.put("email", "admin@biezhi.me"); - context.put("url", "https://biezhi.me/active/asdkjajdasjdkaweoi"); - - StringWriter writer = new StringWriter(); - template.render(context, writer); - String output = writer.toString(); - System.out.println(output); - - OhMyEmail.subject("这是一封测试Jetx模板邮件") - .from("小姐姐的邮箱") - .to("xiaojiejie@gmail.com") - .html(output) - .send(); -} -``` - -### 邮件模版 - -```html -
-

亲爱的{{ username }}, 欢迎加入 biezhi !

-

当您收到这封信的时候,您已经可以正常登录了。

-

请点击链接登录首页: http://biezhi.me/xxxxx

-

如果您的 email 程序不支持链接点击,请将上面的地址拷贝至您的浏览器(如IE)的地址栏进入。

-

如果您还想申请管理员权限,可以联系管理员 {{ email }}

-

我们对您产生的不便,深表歉意。

-

希望您在 biezhi 系统度过快乐的时光!

-

-

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

-

-

(这是一封自动产生的email,请勿回复。)

-
-``` - -## 问题建议 - -- 我的邮箱:`biezhi.me#gmail.com` diff --git a/jun_java_plugins/jun_email/pom.xml b/jun_java_plugins/jun_email/pom.xml deleted file mode 100644 index 7f10131c80..0000000000 --- a/jun_java_plugins/jun_email/pom.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_email - 1.0 - war - - - - UTF-8 - - - - - junit - junit - 4.13 - - - org.apache.commons - commons-email - 1.5 - - - com.sun.mail - javax.mail - 1.6.2 - - - - javax.servlet - javax.servlet-api - 4.0.1 - provided - - - - - jun_email - - diff --git a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/base/email/javamail/MailUtil.java b/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/base/email/javamail/MailUtil.java deleted file mode 100644 index 5b676b26eb..0000000000 --- a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/base/email/javamail/MailUtil.java +++ /dev/null @@ -1,248 +0,0 @@ -package com.jun.plugin.base.email.javamail; - -import java.util.List; -import java.util.Properties; - -import javax.activation.DataHandler; -import javax.activation.FileDataSource; -import javax.mail.Message; -import javax.mail.MessagingException; -import javax.mail.Multipart; -import javax.mail.Session; -import javax.mail.Transport; -import javax.mail.internet.InternetAddress; -import javax.mail.internet.MimeBodyPart; -import javax.mail.internet.MimeMessage; -import javax.mail.internet.MimeMultipart; - -public class MailUtil { - - /** - * 变量名 userName: TODO 邮箱用户名 - */ - private String userName; - - /** - * 变量名 password: TODO 邮箱地址 - */ - private String password; - - /** - * 变量名 smtpHost: TODO 邮箱smtp地址,发送地址 - */ - private String smtpHost; - - /** - * 变量名 targetAddress: TODO 目标邮箱地址 - */ - private String targetAddress; - - /** - * 发送单邮件 - * @param userName - * @param password - * @param targetAddress - * @param mimeDTO - * @return - */ - public static boolean sendEmail(String userName,String password,String targetAddress, - MimeMessageDTO mimeDTO){ - return publicsendEmail(userName,password,targetAddress,mimeDTO,false,null); - } - /** - * 发送单邮件(附件) - * @param userName - * @param password - * @param targetAddress - * @param mimeDTO - * @param filepath 文件本地绝对路径 - * @return - */ - public static boolean sendEmailByFile(String userName,String password,String targetAddress, - MimeMessageDTO mimeDTO,List filepath){ - return publicsendEmail(userName,password,targetAddress,mimeDTO,true,filepath); - } - /** - * 群发邮件 - * @param userName - * @param password - * @param targetAddress 多个邮件发送地址,以,分隔 - * @param mimeDTO - * @return - */ - public static boolean sendGroupEmail(String userName,String password,String targetAddress, - MimeMessageDTO mimeDTO){ - return publicsendEmail(userName,password,targetAddress,mimeDTO,true,null); - } - /** - * 群发邮件 (附件) - * @param userName - * @param password - * @param targetAddress 多个邮件发送地址,以,分隔 - * @param mimeDTO - * @param filepath 文件本地绝对路径 - * @return - */ - public static boolean sendGroupEmailByFile(String userName,String password,String targetAddress, - MimeMessageDTO mimeDTO,List filepath){ - return publicsendEmail(userName,password,targetAddress,mimeDTO,true,filepath); - } - - - - /** - * 邮件发送基础方法 - * @param userName - * @param password - * @param targetAddress - * @param mimeDTO - * @param isGroup - * @param filepath - * @return - */ - private static boolean publicsendEmail(String userName,String password,String targetAddress, - MimeMessageDTO mimeDTO,boolean isGroup,List filepath){ - Properties props = makeMailProperties(userName); - String hostname=SMTPUtil.SimpleMailSender(userName); - Session session = Session.getInstance(props, new PopupAuthenticator(userName, password)); - session.setDebug(true); - try { - Transport ts = session.getTransport(); - ts.connect(hostname,userName,password); - Message message =!isGroup?createEmail(session,userName,targetAddress,mimeDTO) - :createEmailByGroupAndFile(session,userName, - targetAddress,mimeDTO,filepath==null?null:filepath); - ts.sendMessage(message,message.getAllRecipients()); - ts.close(); - } catch (Exception mex) { - mex.printStackTrace(); - return false; - } - return true; - } - - - - - - /** - * 创建邮件信息 - * @param userName - * @return - */ - private static Properties makeMailProperties(String userName){ - Properties props = new Properties(); - String hostname=SMTPUtil.SimpleMailSender(userName); - props.put("mail.smtp.host", hostname); - props.setProperty("mail.smtp.auth", "true"); - props.setProperty("mail.transport.protocol", "smtp"); - if(hostname.indexOf(".qq.com")!=-1){ - props.setProperty("mail.smtp.socketFactory.port", "465"); - props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); - } - return props; - } - - - - /** - * 创建邮件 - * @author Wujun - * Create_time:2015年10月17日 下午7:45:57 - * description: - */ - private static Message createEmail(Session session,String userName,String regMail,MimeMessageDTO mimeDTO){ - MimeMessage message = new MimeMessage(session); - try { - message.setFrom(new InternetAddress(userName)); - message.setRecipient(Message.RecipientType.TO, new InternetAddress(regMail)); - message.setSubject(mimeDTO.getSubject()); - message.setContent(mimeDTO.getText(),"text/html;charset=UTF-8"); - message.saveChanges(); - } catch (MessagingException e) { - e.printStackTrace(); - } - return message; - } - /** - * 创建群发带附件 - * @return - */ - private static Message createEmailByGroupAndFile(Session session,String userName, - String regMail,MimeMessageDTO mimeDTO,List filepath){ - MimeMessage message = new MimeMessage(session); - try { - message.setFrom(new InternetAddress(userName)); - // 创建收件人列表 - if (regMail != null && regMail.trim().length() > 0) { - String[] arr = regMail.split(","); - int receiverCount = arr.length; - if (receiverCount > 0) { - InternetAddress[] address = new InternetAddress[receiverCount]; - for (int i = 0; i < receiverCount; i++) { - address[i] = new InternetAddress(arr[i]); - } - message.setRecipients(Message.RecipientType.TO, address); - } - } - // 后面的BodyPart将加入到此处创建的Multipart中 - Multipart mp = new MimeMultipart(); - // 附件操作 - if (filepath != null && filepath.size() > 0) { - for (String filename : filepath) { - MimeBodyPart mbp = new MimeBodyPart(); - // 得到数据源 - FileDataSource fds = new FileDataSource(filename); - // 得到附件本身并至入BodyPart - mbp.setDataHandler(new DataHandler(fds)); - // 得到文件名同样至入BodyPart - mbp.setFileName(fds.getName()); - mp.addBodyPart(mbp); - } - MimeBodyPart mbp = new MimeBodyPart(); - mbp.setText(mimeDTO.getText()); - mp.addBodyPart(mbp); - // 移走集合中的所有元素 - filepath.clear(); - // Multipart加入到信件 - message.setContent(mp); - } else { - // 设置邮件正文 -// message.setText(mimeDTO.getText()); - message.setContent(mimeDTO.getText(),"text/html;charset=UTF-8"); - } - message.setSubject(mimeDTO.getSubject()); - message.saveChanges(); - } catch (MessagingException e) { - e.printStackTrace(); - } - return message; - } - - - - public String getUserName() { - return userName; - } - public void setUserName(String userName) { - this.userName = userName; - } - public String getPassword() { - return password; - } - public void setPassword(String password) { - this.password = password; - } - public String getSmtpHost() { - return smtpHost; - } - public void setSmtpHost(String smtpHost) { - this.smtpHost = smtpHost; - } - public String getTargetAddress() { - return targetAddress; - } - public void setTargetAddress(String targetAddress) { - this.targetAddress = targetAddress; - } -} diff --git a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/base/email/javamail/MimeMessageDTO.java b/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/base/email/javamail/MimeMessageDTO.java deleted file mode 100644 index 43274c4363..0000000000 --- a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/base/email/javamail/MimeMessageDTO.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.jun.plugin.base.email.javamail; - -import java.util.Date; - - -/** - * 上午9:29:51 - * - * @version V1.0 - */ -public class MimeMessageDTO { - /** - * 变量名 subject: TODO 邮件标题 - */ - private String subject; - - /** - * 变量名 sentDate: TODO 邮件日期 - */ - private Date sentDate; - - /** - * 变量名 text: TODO 邮件内容 - */ - private String text; - - /** - * 方法名: initMimeMessage - * 功能描述: TODO 初始化 - * @param: @param subject - * @param: @param date - * @param: @param text - * @param: @return - * @return: MimeMessageDTO - */ - public MimeMessageDTO initMimeMessage(String subject, Date date, String text) { - return new MimeMessageDTO(subject, date, text); - } - - public MimeMessageDTO() { - super(); - } - - public MimeMessageDTO(String subject, Date sentDate, String text) { - super(); - this.subject = subject; - this.sentDate = sentDate; - this.text = text; - } - - public String getSubject() { - return subject; - } - - public void setSubject(String subject) { - this.subject = subject; - } - - public Date getSentDate() { - return sentDate; - } - - public void setSentDate(Date sentDate) { - this.sentDate = sentDate; - } - - public String getText() { - return text; - } - - public void setText(String text) { - this.text = text; - } - -} diff --git a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/base/email/javamail/PopupAuthenticator.java b/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/base/email/javamail/PopupAuthenticator.java deleted file mode 100644 index e2f10d2d13..0000000000 --- a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/base/email/javamail/PopupAuthenticator.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.jun.plugin.base.email.javamail; - -import javax.mail.Authenticator; -import javax.mail.PasswordAuthentication; - -/** - * 类名称: PopupAuthenticator - * 功能描述: TODO - * 创建人: GavinNie 邮件 账号 密码 - * 创建时间: 2014-12-4 上午11:07:10 - * @version V1.0 - */ -public class PopupAuthenticator extends Authenticator { - private String username = null; - private String password = null; - - public PopupAuthenticator(String user, String pass) { - this.username = user; - this.password = pass; - } - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication(username, password); - } -} diff --git a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/base/email/javamail/SMTPUtil.java b/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/base/email/javamail/SMTPUtil.java deleted file mode 100644 index 2ae5e05115..0000000000 --- a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/base/email/javamail/SMTPUtil.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.jun.plugin.base.email.javamail; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -/** - * 类名称: SMTPUtil - * 功能描述: TODO 得到smtp - * 创建人: GavinNie - * 创建时间: 2014-12-4 上午10:36:00 - * @version V1.0 - */ -public class SMTPUtil { - /** - * 方法名: SimpleMailSender - * 功能描述: TODO 简单的smtp生成,大部分是有用的,建议自己建立smtp库.... - * @param: @param userName - * @param: @return - * @return: String - */ - public static String SimpleMailSender(String userName) { - return "smtp." + getHost(userName); - } - - - /** - * @Title: getSMTPAddress - * @Description: TODO (这里用一句话描述这个方法的作用) - * @param @param userName - * @param @return 设定文件 - * @return String 返回类型 - * @throws - */ - public static String getSMTPAddress(String userName){ - String smtpAddress = null; - Properties props = new Properties(); - try { - InputStream in = SMTPUtil.class.getResourceAsStream("/smtp.properties"); - props.load(in); - //读取properties的内容 - smtpAddress = props.getProperty(getHost(userName).trim()); - //没有获取到 - if(smtpAddress == null){ - //生成简单得 - smtpAddress = SimpleMailSender(userName); - } - } catch (IOException e) { - e.printStackTrace(); - } - return smtpAddress; - } - - - /** - * @Title: getHost - * @Description: TODO 得到 邮箱@后面得字符 - * @param @param userName - * @param @return 设定文件 - * @return String 返回类型 - * @throws - */ - public static String getHost(String userName){ - return userName.split("@")[1]; - } - -// public static void main(String[] args) { -// String s = getSMTPAddress("nie_zw@qq.com"); -// System.out.println(s); -// } -} diff --git a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/base/email/javamail2/JavaMail.java b/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/base/email/javamail2/JavaMail.java deleted file mode 100644 index 009e841808..0000000000 --- a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/base/email/javamail2/JavaMail.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.jun.plugin.base.email.javamail2; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; -import javax.mail.Message; -import javax.mail.MessagingException; -import javax.mail.Session; -import javax.mail.Transport; -import javax.mail.internet.InternetAddress; -import javax.mail.internet.MimeMessage; -import javax.mail.internet.MimeUtility; - -public class JavaMail { - /** - * * Message对象将存储我们实际发送的电子邮件信息, * - * Message对象被作为一个MimeMessage对象来创建并且需要知道应当选择哪一个JavaMail session。 - */ - private MimeMessage message; - /** - * * Session类代表JavaMail中的一个邮件会话。 * - * 每一个基于JavaMail的应用程序至少有一个Session(可以有任意多的Session)。 * * - * JavaMail需要Properties来创建一个session对象。 * 寻找"mail.smtp.host" 属性值就是发送邮件的主机 * - * 寻找"mail.smtp.auth" 身份验证,目前免费邮件服务器都需要这一项 - */ - private Session session; - /*** - * * 邮件是既可以被发送也可以被受到。JavaMail使用了两个不同的类来完成这两个功能:Transport 和 Store。 * - * Transport 是用来发送信息的,而Store用来收信。对于这的教程我们只需要用到Transport对象。 - */ - private Transport transport; - private String mailHost = ""; - private String sender_username = ""; - private String sender_password = ""; - private Properties properties = new Properties(); - - /* * 初始化方法 */ - public JavaMail(boolean debug) { - InputStream in = JavaMail.class.getResourceAsStream("MailServer.properties"); - try { - properties.load(in); - this.mailHost = properties.getProperty("mail.smtp.host"); - this.sender_username = properties.getProperty("mail.sender.username"); - this.sender_password = properties.getProperty("mail.sender.password"); - } catch (IOException e) { - e.printStackTrace(); - } - session = Session.getInstance(properties); - session.setDebug(debug); - // 开启后有调试信息 message = new MimeMessage(session); - } - - /** - * * 发送邮件 * * @param subject * 邮件主题 * @param sendHtml * 邮件内容 * @param - * receiveUser * 收件人地址 - */ - public void doSendHtmlEmail(String subject, String sendHtml, String receiveUser) { - try { - // 发件人 // - // InternetAddress from = new InternetAddress(sender_username); - // 下面这个是设置发送人的Nick name - InternetAddress from = new InternetAddress(MimeUtility.encodeWord("幻影") + " < sender_username>"); - message.setFrom(from); - // 收件人 - InternetAddress to = new InternetAddress(receiveUser); - message.setRecipient(Message.RecipientType.TO, to);// 还可以有CC、BCC // - // 邮件主题 - message.setSubject(subject); - String content = sendHtml.toString(); - // 邮件内容,也可以使纯文本"text/plain" - message.setContent(content, "text/html;charset=UTF-8"); - // 保存邮件 - message.saveChanges(); - transport = session.getTransport("smtp"); // smtp验证,就是你用来发邮件的邮箱用户名密码 - transport.connect(mailHost, sender_username, sender_password); // 发送 - transport.sendMessage(message, message.getAllRecipients()); // - System.out.println("send success!"); - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (transport != null) { - try { - transport.close(); - } catch (MessagingException e) { - e.printStackTrace(); - } - } - } - } - - public static void main(String[] args) { - JavaMail se = new JavaMail(false); - se.doSendHtmlEmail("邮件主题", "邮件内容", "xxx@XX.com"); - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/base/email/javamail2/JavaMailWithAttachment.java b/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/base/email/javamail2/JavaMailWithAttachment.java deleted file mode 100644 index 18013854b7..0000000000 --- a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/base/email/javamail2/JavaMailWithAttachment.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.jun.plugin.base.email.javamail2; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.Base64; -import java.util.Properties; -import javax.activation.DataHandler; -import javax.activation.DataSource; -import javax.activation.FileDataSource; -import javax.mail.BodyPart; -import javax.mail.Message; -import javax.mail.MessagingException; -import javax.mail.Multipart; -import javax.mail.Session; -import javax.mail.Transport; -import javax.mail.internet.InternetAddress; -import javax.mail.internet.MimeBodyPart; -import javax.mail.internet.MimeMessage; -import javax.mail.internet.MimeMultipart; -import javax.mail.internet.MimeUtility; - -public class JavaMailWithAttachment { - private MimeMessage message; - private Session session; - private Transport transport; - private String mailHost = ""; - private String sender_username = ""; - private String sender_password = ""; - private Properties properties = new Properties(); - - /* * 初始化方法 */public JavaMailWithAttachment(boolean debug) { - InputStream in = JavaMailWithAttachment.class.getResourceAsStream("MailServer.properties"); - try { - properties.load(in); - this.mailHost = properties.getProperty("mail.smtp.host"); - this.sender_username = properties.getProperty("mail.sender.username"); - this.sender_password = properties.getProperty("mail.sender.password"); - } catch (IOException e) { - e.printStackTrace(); - } - session = Session.getInstance(properties); - session.setDebug(debug);// - // 开启后有调试信息 C - message = new MimeMessage(session); - } - - /** - * * 发送邮件 * * @param subject * 邮件主题 * @param sendHtml * 邮件内容 * @param - * receiveUser * 收件人地址 * @param attachment * 附件 - */ - public void doSendHtmlEmail(String subject, String sendHtml, String receiveUser, File attachment) { - try { // - // 发件人 - InternetAddress from = new InternetAddress(sender_username); - message.setFrom(from); // - // 收件人 - InternetAddress to = new InternetAddress(receiveUser); - message.setRecipient(Message.RecipientType.TO, to); // - // 邮件主题 - message.setSubject(subject); // - // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件 - Multipart multipart = new MimeMultipart(); // - // 添加邮件正文 - BodyPart contentPart = new MimeBodyPart(); - contentPart.setContent(sendHtml, "text/html;charset=UTF-8"); - multipart.addBodyPart(contentPart); // - // 添加附件的内容 - if (attachment != null) { - BodyPart attachmentBodyPart = new MimeBodyPart(); - DataSource source = new FileDataSource(attachment); - attachmentBodyPart.setDataHandler(new DataHandler(source)); // - // 网上流传的解决文件名乱码的方法,其实用MimeUtility.encodeWord就可以很方便的搞定 // - // 这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码 // - // 使用Java标准库的Base64编码器替代已废弃的sun.misc.BASE64Encoder -// messageBodyPart.setFileName("=?GBK?B?" + Base64.getEncoder().encodeToString(attachment.getName().getBytes()) + "?="); // - message.setFileName("=?GBK?B?" + Base64.getEncoder().encodeToString(attachment.getName().getBytes()) + "?="); // - // MimeUtility.encodeWord可以避免文件名乱码 - attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName())); - multipart.addBodyPart(attachmentBodyPart); - } // - // 将multipart对象放到message中 - message.setContent(multipart); // - // 保存邮件 - message.saveChanges(); - transport = session.getTransport("smtp"); // - // smtp验证,就是你用来发邮件的邮箱用户名密码 - transport.connect(mailHost, sender_username, sender_password); // - // 发送 - transport.sendMessage(message, message.getAllRecipients()); - System.out.println("send success!"); - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (transport != null) { - try { - transport.close(); - } catch (MessagingException e) { - e.printStackTrace(); - } - } - } - } - - public static void main(String[] args) { - JavaMailWithAttachment se = new JavaMailWithAttachment(true); - File affix = new File("c:\\测试-test.txt"); - se.doSendHtmlEmail("邮件主题", "邮件内容", "xxx@XXX.com", affix);// - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/base/email/javamail2/mail_imap.java b/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/base/email/javamail2/mail_imap.java deleted file mode 100644 index b4a710eeca..0000000000 --- a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/base/email/javamail2/mail_imap.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.jun.plugin.base.email.javamail2; - -import java.util.Properties; - -import javax.mail.Flags; -import javax.mail.Folder; -import javax.mail.Message; -import javax.mail.Session; - -import com.sun.mail.imap.IMAPFolder; -import com.sun.mail.imap.IMAPStore; - -public class mail_imap { - /** - * 使用imap协议获取未读邮件数 - * - * @author Wujun - * - */ - public static void main(String[] args) throws Exception { - String user = "username@sohu.com";// 邮箱的用户名 - String password = "password"; // 邮箱的密码 - Properties prop = System.getProperties(); - prop.put("mail.store.protocol", "imap"); - prop.put("mail.imap.host", "imap.sohu.com"); - Session session = Session.getInstance(prop); - int total = 0; - IMAPStore store = (IMAPStore) session.getStore("imap"); // 使用imap会话机制,连接服务器 - store.connect(user, password); - IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX"); // 收件箱 - folder.open(Folder.READ_WRITE); - // 获取总邮件数 - total = folder.getMessageCount(); - System.out.println("-----------------共有邮件:" + total + " 封--------------"); - // 得到收件箱文件夹信息,获取邮件列表 - System.out.println("未读邮件数:" + folder.getUnreadMessageCount()); - Message[] messages = folder.getMessages(); - int messageNumber = 0; - for (Message message : messages) { - System.out.println("发送时间:" + message.getSentDate()); - System.out.println("主题:" + message.getSubject()); - System.out.println("内容:" + message.getContent()); - Flags flags = message.getFlags(); - if (flags.contains(Flags.Flag.SEEN)) - System.out.println("这是一封已读邮件"); - else { - System.out.println("未读邮件"); - } - System.out.println("========================================================"); - System.out.println("========================================================"); - // 每封邮件都有一个MessageNumber,可以通过邮件的MessageNumber在收件箱里面取得该邮件 - messageNumber = message.getMessageNumber(); - } - Message message = folder.getMessage(messageNumber); - System.out.println(message.getContent() + message.getContentType()); - // 释放资源 - if (folder != null) - folder.close(true); - if (store != null) - store.close(); - } -} diff --git a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/base/email/javamail2/mail_pop3.java b/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/base/email/javamail2/mail_pop3.java deleted file mode 100644 index 74c356cf09..0000000000 --- a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/base/email/javamail2/mail_pop3.java +++ /dev/null @@ -1,123 +0,0 @@ -package com.jun.plugin.base.email.javamail2; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Enumeration; -import java.util.Properties; - -import javax.mail.BodyPart; -import javax.mail.Folder; -import javax.mail.Message; -import javax.mail.MessagingException; -import javax.mail.Multipart; -import javax.mail.Session; -import javax.mail.Store; -import javax.mail.internet.MimeMultipart; - -public class mail_pop3 { - - public static void main(String args[]) throws MessagingException, IOException { - Properties props = new Properties(); - props.setProperty("mail.store.protocol", "pop3"); - props.setProperty("mail.pop3.host", "pop3.sohu.com"); - Session session = Session.getDefaultInstance(props); - Store store = session.getStore("pop3"); - store.connect("username@sohu.com", "password"); - Folder folder = store.getFolder("INBOX"); - folder.open(Folder.READ_WRITE); - // 全部邮件数 - int messageCount = folder.getMessageCount(); - System.out.println(messageCount); - Message[] messages = folder.getMessages(); - for (int i = 0; i < messages.length; i++) { - Message message = messages[i]; - System.out.println(message.getSubject()); - // 删除邮件 - // message.setFlag(Flags.Flag.DELETED, true); - // 标记为已读 - // message.setFlag(Flags.Flag.SEEN, true); - // pop3没有判断邮件是否为已读的功能,要使用Imap才可以 - /* - * Flags flags = message.getFlags(); if - * (flags.contains(Flags.Flag.SEEN)) System.out.println("这是一封已读邮件"); - * else { System.out.println("未读邮件"); - * message.setFlag(Flags.Flag.SEEN, true); } - */ - System.out.println("发送时间:" + message.getSentDate()); - System.out.println("主题:" + message.getSubject()); - System.out.println("内容:" + message.getContent()); - // 获取所有的Header,头信息 - Enumeration headers = message.getAllHeaders(); - System.out.println("----------------------allHeaders-----------------------------"); - /* - * while (headers.hasMoreElements()) { Header header = - * (Header)headers.nextElement(); - * System.out.println(header.getName()+" ======= "+header.getValue() - * ); } - */ - // 解析邮件内容 - Object content = message.getContent(); - if (content instanceof MimeMultipart) { - MimeMultipart multipart = (MimeMultipart) content; - parseMultipart(multipart); - } - System.out.println("========================================================"); - System.out.println("========================================================"); - } - folder.close(true); - store.close(); - } - - /** - * 对复杂邮件的解析 - * - * @param multipart - * @throws MessagingException - * @throws IOException - */ - public static void parseMultipart(Multipart multipart) throws MessagingException, IOException { - int count = multipart.getCount(); - System.out.println("couont = " + count); - for (int idx = 0; idx < count; idx++) { - BodyPart bodyPart = multipart.getBodyPart(idx); - System.out.println(bodyPart.getContentType()); - if (bodyPart.isMimeType("text/plain")) { - System.out.println("plain................." + bodyPart.getContent()); - } else if (bodyPart.isMimeType("text/html")) { - System.out.println("html..................." + bodyPart.getContent()); - } else if (bodyPart.isMimeType("multipart/*")) { - Multipart mpart = (Multipart) bodyPart.getContent(); - parseMultipart(mpart); - } else if (bodyPart.isMimeType("application/octet-stream")) { - String disposition = bodyPart.getDisposition(); - System.out.println(disposition); - if (disposition.equalsIgnoreCase(BodyPart.ATTACHMENT)) { - String fileName = bodyPart.getFileName(); - InputStream is = bodyPart.getInputStream(); - copy(is, new FileOutputStream("D:\\" + fileName)); - } - } - } - } - - /** - * 文件拷贝,在用户进行附件下载的时候,可以把附件的InputStream传给用户进行下载 - * - * @param is - * @param os - * @throws IOException - */ - public static void copy(InputStream is, OutputStream os) throws IOException { - byte[] bytes = new byte[1024]; - int len = 0; - while ((len = is.read(bytes)) != -1) { - os.write(bytes, 0, len); - } - if (os != null) - os.close(); - if (is != null) - is.close(); - } -} diff --git a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/base/email/javamail2/sendMail.java b/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/base/email/javamail2/sendMail.java deleted file mode 100644 index f04c2da899..0000000000 --- a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/base/email/javamail2/sendMail.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.jun.plugin.base.email.javamail2; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Enumeration; -import java.util.Properties; -import javax.mail.BodyPart; -import javax.mail.Folder; -import javax.mail.Message; -import javax.mail.MessagingException; -import javax.mail.Multipart; -import javax.mail.Session; -import javax.mail.Store; -import javax.mail.internet.MimeMultipart; - -public class sendMail { - public static void main(String args[]) throws MessagingException, IOException { - Properties props = new Properties(); - props.setProperty("mail.store.protocol", "pop3"); - props.setProperty("mail.pop3.host", "pop3.sohu.com"); - Session session = Session.getDefaultInstance(props); - Store store = session.getStore("pop3"); - store.connect("username@sohu.com", "password"); - Folder folder = store.getFolder("INBOX"); - folder.open(Folder.READ_WRITE); - // 全部邮件数 - int messageCount = folder.getMessageCount(); - System.out.println(messageCount); - Message[] messages = folder.getMessages(); - for (int i = 0; i < messages.length; i++) { - Message message = messages[i]; - System.out.println(message.getSubject()); - // 删除邮件 - // message.setFlag(Flags.Flag.DELETED, true); - // 标记为已读 - // message.setFlag(Flags.Flag.SEEN, true); - // pop3没有判断邮件是否为已读的功能,要使用Imap才可以 - /* - * Flags flags = message.getFlags(); if - * (flags.contains(Flags.Flag.SEEN)) System.out.println("这是一封已读邮件"); - * else { System.out.println("未读邮件"); - * message.setFlag(Flags.Flag.SEEN, true); } - */ - System.out.println("发送时间:" + message.getSentDate()); - System.out.println("主题:" + message.getSubject()); - System.out.println("内容:" + message.getContent()); - // 获取所有的Header,头信息 - Enumeration headers = message.getAllHeaders(); - System.out.println("----------------------allHeaders-----------------------------"); - /* - * while (headers.hasMoreElements()) { Header header = - * (Header)headers.nextElement(); - * System.out.println(header.getName()+" ======= "+header.getValue() - * ); } - */ - // 解析邮件内容 - Object content = message.getContent(); - if (content instanceof MimeMultipart) { - MimeMultipart multipart = (MimeMultipart) content; - parseMultipart(multipart); - } - System.out.println("========================================================"); - System.out.println("========================================================"); - } - folder.close(true); - store.close(); - } - - /** - * 对复杂邮件的解析 - * - * @param multipart - * @throws MessagingException - * @throws IOException - */ - public static void parseMultipart(Multipart multipart) throws MessagingException, IOException { - int count = multipart.getCount(); - System.out.println("couont = " + count); - for (int idx = 0; idx < count; idx++) { - BodyPart bodyPart = multipart.getBodyPart(idx); - System.out.println(bodyPart.getContentType()); - if (bodyPart.isMimeType("text/plain")) { - System.out.println("plain................." + bodyPart.getContent()); - } else if (bodyPart.isMimeType("text/html")) { - System.out.println("html..................." + bodyPart.getContent()); - } else if (bodyPart.isMimeType("multipart/*")) { - Multipart mpart = (Multipart) bodyPart.getContent(); - parseMultipart(mpart); - } else if (bodyPart.isMimeType("application/octet-stream")) { - String disposition = bodyPart.getDisposition(); - System.out.println(disposition); - if (disposition.equalsIgnoreCase(BodyPart.ATTACHMENT)) { - String fileName = bodyPart.getFileName(); - InputStream is = bodyPart.getInputStream(); - copy(is, new FileOutputStream("D:\\" + fileName)); - } - } - } - } - - /** - * 文件拷贝,在用户进行附件下载的时候,可以把附件的InputStream传给用户进行下载 - * - * @param is - * @param os - * @throws IOException - */ - public static void copy(InputStream is, OutputStream os) throws IOException { - byte[] bytes = new byte[1024]; - int len = 0; - while ((len = is.read(bytes)) != -1) { - os.write(bytes, 0, len); - } - if (os != null) - os.close(); - if (is != null) - is.close(); - } -} diff --git a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/itcast/javamail2/Base64Util.java b/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/itcast/javamail2/Base64Util.java deleted file mode 100644 index d8b14bae55..0000000000 --- a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/itcast/javamail2/Base64Util.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.jun.plugin.itcast.javamail2; - -import java.io.BufferedReader; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; -import java.util.Base64; -import java.util.Properties; - -import javax.activation.DataHandler; -import javax.activation.DataSource; -import javax.activation.FileDataSource; -import javax.mail.Address; -import javax.mail.Authenticator; -import javax.mail.Message; -import javax.mail.MessagingException; -import javax.mail.PasswordAuthentication; -import javax.mail.Session; -import javax.mail.Transport; -import javax.mail.Message.RecipientType; -import javax.mail.internet.AddressException; -import javax.mail.internet.InternetAddress; -import javax.mail.internet.MimeBodyPart; -import javax.mail.internet.MimeMessage; -import javax.mail.internet.MimeMultipart; -import javax.mail.internet.MimeUtility; - -public class Base64Util { - - /** - * @param args add by zxx ,Dec 30, 2008 - * @throws IOException - */ - public static void main(String[] args) throws IOException { - // TODO Auto-generated method stub - System.out.println("please input user name:"); - String username = new BufferedReader( - new InputStreamReader(System.in)) - .readLine(); - System.out.println(Base64.getEncoder().encodeToString(username.getBytes())); - System.out.println("please input password:"); - String password = new BufferedReader( - new InputStreamReader(System.in)) - .readLine(); - System.out.println(Base64.getEncoder().encodeToString(password.getBytes())); - } - - -} diff --git a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/mail/CommonMail.java b/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/mail/CommonMail.java deleted file mode 100644 index 25bb8ffc31..0000000000 --- a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/mail/CommonMail.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.jun.plugin.mail; - -import java.net.MalformedURLException; -import java.net.URL; - -import javax.mail.internet.MimeUtility; -import org.apache.commons.mail.EmailAttachment; -import org.apache.commons.mail.EmailException; -import org.apache.commons.mail.HtmlEmail; -import org.apache.commons.mail.MultiPartEmail; -import org.apache.commons.mail.SimpleEmail; - -public class CommonMail { - public static void main(String[] args) throws Exception { - CommonMail mail = new CommonMail(); -// mail.sendSimpleMail(); -// mail.sendMutiMail(); - mail.sendHtml(); - } - - @SuppressWarnings("deprecation") - public void sendSimpleMail() throws Exception { - SimpleEmail email = new SimpleEmail(); - email.setHostName("smtp.163.com"); - email.setAuthentication("jsjs9494@163.com", "password.jsjs"); - email.addTo("245783660@qq.com", "245783660@qq.com"); - email.setFrom("jsjs9494@163.com", "发信人列表"); - email.setSubject("邮件大标题");// - email.setMsg(" 邮件内容 "); // - email.setSmtpPort(465); // - email.setSSL(true); // - email.setCharset("GBK"); // - email.send(); - } - - public void sendMutiMail() throws Exception { - EmailAttachment attachment = new EmailAttachment(); - attachment.setDisposition(EmailAttachment.ATTACHMENT); - attachment.setDescription("python resource"); - attachment.setPath("src_mail/com/jun/plugin/mail/File.html"); - attachment.setName(MimeUtility.encodeText("File.html")); - - MultiPartEmail email = new MultiPartEmail(); - email.setHostName("smtp.163.com"); - email.setAuthentication("jsjs9494@163.com", "password.jsjs"); - email.addTo("245783660@qq.com", "收信显示名称"); - email.setFrom("jsjs9494@163.com", " 发信人列表 "); - email.setSubject("邮件大标题"); - email.setMsg(" 邮件内容 sendMutiMail "); - email.setCharset("GBK"); - email.attach(attachment); - email.send(); - } - - - /** - * 慢 - */ - @SuppressWarnings("deprecation") - public void sendHtml() { - try { - HtmlEmail email = new HtmlEmail(); - email.setTLS(true); - email.setHostName("smtp.qq.com"); - email.setAuthentication("245783660@qq.com", "qq245783660."); - email.addTo("jsjs9494@163.com", " 收信显示名称 "); - email.setFrom("245783660@qq.com"); - email.setSubject(" 邮件标题 "); - email.setCharset("GBK"); - email.setMsg(" sendHtml content "); - - URL url; - url = new URL("http://img.baidu.com/img/image/ilogob.gif"); - String cid = email.embed(url, "baidu logo"); - email.setHtmlMsg("baidu.com

haha

"); - email.send(); - System.out.println(" sendHtml sucessed "); - } catch (EmailException e) { - e.printStackTrace(); - } catch (MalformedURLException e) { - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/mail/File.html b/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/mail/File.html deleted file mode 100644 index 3e363d88f0..0000000000 --- a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/mail/File.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - -Insert title here - - -abcd - - \ No newline at end of file diff --git a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/mail/JavaMail.java b/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/mail/JavaMail.java deleted file mode 100644 index 85e7e03c69..0000000000 --- a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/mail/JavaMail.java +++ /dev/null @@ -1,154 +0,0 @@ -package com.jun.plugin.mail; - -import java.util.Date; -import java.util.Properties; - -import javax.mail.Authenticator; -import javax.mail.Message; -import javax.mail.MessagingException; -import javax.mail.PasswordAuthentication; -import javax.mail.Session; -import javax.mail.Transport; -import javax.mail.Message.RecipientType; -import javax.mail.internet.AddressException; -import javax.mail.internet.InternetAddress; -import javax.mail.internet.MimeMessage; - -import com.sun.mail.util.MailSSLSocketFactory; - -public class JavaMail { - public static void main(String[] args) { - // JavaMail.send(" aaaaaaaaaaaaaaa "); - // JavaMail.send("title "," bbbbbbbbbbbbb "); - // JavaMail.sendHtml(" ccccccccccccccccc "); - // JavaMail.sendMail("jsjs9494@163.com", "abcd"); - } - - static final String fromMail = "jsjs9494@163.com"; - static final String user = "jsjs9494@163.com"; - static final String password = "password.jsjs"; - static final String toMail = "jsjs9494@163.com"; - static final String toHtmlMail = "jsjs9494@163.com"; - static final String mailTitle = "[ALERTS]-System Tips"; - static final String htmlMailTitle = "[REPORT] - Operator Data"; - - public static void send(String title, String mailContent) { - sendMail(fromMail, user, password, toMail, title, mailContent); - } - - public static void send(String mailContent) { - sendMail(fromMail, user, password, toMail, mailTitle, mailContent); - } - - public static void sendHtml(String mailContent) { - if (mailContent == null || mailContent.trim().isEmpty() || mailContent.length() < 20) { - return; - } - sendHtmlMail(fromMail, user, password, toHtmlMail, htmlMailTitle, mailContent); - } - - /** - * @param fromMail - * @param user - * @param password - * @param toMail - * @param mailTitle - * @param mailContent - */ - private static void sendMail(String fromMail, String user, String password, String toMail, String mailTitle, - String mailContent) { - try { - // String hostIP = ServerInfoCache.instance().getHostIP(); - // String hostName = ServerInfoCache.instance().getHostName(); - // String SERVER_INFO = String.format("SERVER IP -> [%s] - SERVER NAME -> - // [%s]\r\n The following is the email body - // :\r\n========================================================", hostIP, - // hostName); - - MailSSLSocketFactory sf = new MailSSLSocketFactory(); - sf.setTrustAllHosts(true); - - Properties props = new Properties(); - props.put("mail.smtp.host", "smtp.163.com"); - props.put("mail.smtp.port", 465); - props.put("mail.transport.protocol", "smtp"); - props.put("mail.smtp.auth", "true"); - props.put("mail.smtp.ssl.enable", "true"); - props.put("mail.smtp.ssl.socketFactory", sf); - - Session session = Session.getInstance(props); - - MimeMessage message = new MimeMessage(session); - message.setFrom(new InternetAddress(fromMail)); - message.setRecipient(Message.RecipientType.TO, new InternetAddress(toMail)); - message.setSubject(mailTitle); - message.setText("\r\n\r\n\r\n" + mailContent); - message.setSentDate(new Date()); - message.saveChanges(); - Transport transport = session.getTransport(); - transport.connect(user, password); - transport.sendMessage(message, message.getAllRecipients()); - transport.close(); - } catch (Exception e) { - // LogUtil.error(e); - } - } - - private static void sendHtmlMail(String fromMail, String user, String password, String toMail, String mailTitle, - String mailContent) { - try { - // String hostIP = ServerInfoCache.instance().getHostIP(); - // String hostName = ServerInfoCache.instance().getHostName(); - // String SERVER_INFO = String.format("SERVER IP -> [%s] - SERVER NAME -> [%s] - // %s ", hostIP, hostName); - - MailSSLSocketFactory sf = new MailSSLSocketFactory(); - sf.setTrustAllHosts(true); - - Properties props = new Properties(); - props.put("mail.smtp.host", "mail.163.com"); - props.put("mail.smtp.port", 465); - props.put("mail.transport.protocol", "smtp"); - props.put("mail.smtp.auth", "true"); - props.put("mail.smtp.ssl.enable", "true"); - props.put("mail.smtp.ssl.socketFactory", sf); - - Session session = Session.getInstance(props); - - MimeMessage message = new MimeMessage(session); - message.setFrom(new InternetAddress(fromMail)); - message.setRecipient(Message.RecipientType.TO, new InternetAddress(toMail)); - message.setSubject(mailTitle); - message.setContent(mailContent, "text/html"); - message.setSentDate(new Date()); - message.saveChanges(); - Transport transport = session.getTransport(); - transport.connect(user, password); - transport.sendMessage(message, message.getAllRecipients()); - transport.close(); - } catch (Exception e) { - // LogUtil.error(e); - } - } - - public static void sendMail(String email, String emailMsg) throws AddressException, MessagingException { - Properties props = new Properties(); - props.setProperty("mail.transport.protocol", "SMTP"); - props.setProperty("mail.host", "smtp.163.com"); - props.setProperty("mail.smtp.auth", "true");// 指定验证为true - Authenticator auth = new Authenticator() { - public PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication("jsjs9494@163.com", "password.jsjs"); - } - }; - Session session = Session.getInstance(props, auth); - Message message = new MimeMessage(session); - message.setFrom(new InternetAddress("jsjs9494@163.com")); - message.setRecipient(RecipientType.TO, new InternetAddress(email)); - message.setSubject("用户注册确认邮件"); - // message.setText("这是封激活邮件,点击"); - message.setContent(emailMsg, "text/html;charset=utf-8"); - Transport.send(message); - } - -} diff --git a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/email/demo/dto/MimeMessageDTO.java b/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/email/demo/dto/MimeMessageDTO.java deleted file mode 100644 index 17ccf935d8..0000000000 --- a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/email/demo/dto/MimeMessageDTO.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.jun.plugin.plugin.email.demo.dto; - -import java.util.Date; - - -/** - * 上午9:29:51 - * - * @version V1.0 - */ -public class MimeMessageDTO { - /** - * 变量名 subject: TODO 邮件标题 - */ - private String subject; - - /** - * 变量名 sentDate: TODO 邮件日期 - */ - private Date sentDate; - - /** - * 变量名 text: TODO 邮件内容 - */ - private String text; - - /** - * 方法名: initMimeMessage - * 功能描述: TODO 初始化 - * @param: @param subject - * @param: @param date - * @param: @param text - * @param: @return - * @return: MimeMessageDTO - */ - public MimeMessageDTO initMimeMessage(String subject, Date date, String text) { - return new MimeMessageDTO(subject, date, text); - } - - public MimeMessageDTO() { - super(); - } - - public MimeMessageDTO(String subject, Date sentDate, String text) { - super(); - this.subject = subject; - this.sentDate = sentDate; - this.text = text; - } - - public String getSubject() { - return subject; - } - - public void setSubject(String subject) { - this.subject = subject; - } - - public Date getSentDate() { - return sentDate; - } - - public void setSentDate(Date sentDate) { - this.sentDate = sentDate; - } - - public String getText() { - return text; - } - - public void setText(String text) { - this.text = text; - } - -} diff --git a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/email/demo/util/MailUtil.java b/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/email/demo/util/MailUtil.java deleted file mode 100644 index 6a97c8ed1c..0000000000 --- a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/email/demo/util/MailUtil.java +++ /dev/null @@ -1,257 +0,0 @@ -package com.jun.plugin.plugin.email.demo.util; - -import java.util.List; -import java.util.Properties; - -import javax.activation.DataHandler; -import javax.activation.FileDataSource; -import javax.mail.Message; -import javax.mail.MessagingException; -import javax.mail.Multipart; -import javax.mail.Session; -import javax.mail.Transport; -import javax.mail.internet.InternetAddress; -import javax.mail.internet.MimeBodyPart; -import javax.mail.internet.MimeMessage; -import javax.mail.internet.MimeMultipart; - -import com.jun.plugin.plugin.email.demo.dto.MimeMessageDTO; - -/** - * 类名称: mailUtil - * 功能描述: TODO 邮件发送例子 - * 创建人: Gavin-Nie - * 创建时间: 2014-12-4 上午9:20:16 - * @version V1.0 - */ -public class MailUtil { - - /** - * 变量名 userName: TODO 邮箱用户名 - */ - private String userName; - - /** - * 变量名 password: TODO 邮箱地址 - */ - private String password; - - /** - * 变量名 smtpHost: TODO 邮箱smtp地址,发送地址 - */ - private String smtpHost; - - /** - * 变量名 targetAddress: TODO 目标邮箱地址 - */ - private String targetAddress; - - /** - * 发送单邮件 - * @param userName - * @param password - * @param targetAddress - * @param mimeDTO - * @return - */ - public static boolean sendEmail(String userName,String password,String targetAddress, - MimeMessageDTO mimeDTO){ - return publicsendEmail(userName,password,targetAddress,mimeDTO,false,null); - } - /** - * 发送单邮件(附件) - * @param userName - * @param password - * @param targetAddress - * @param mimeDTO - * @param filepath 文件本地绝对路径 - * @return - */ - public static boolean sendEmailByFile(String userName,String password,String targetAddress, - MimeMessageDTO mimeDTO,List filepath){ - return publicsendEmail(userName,password,targetAddress,mimeDTO,true,filepath); - } - /** - * 群发邮件 - * @param userName - * @param password - * @param targetAddress 多个邮件发送地址,以,分隔 - * @param mimeDTO - * @return - */ - public static boolean sendGroupEmail(String userName,String password,String targetAddress, - MimeMessageDTO mimeDTO){ - return publicsendEmail(userName,password,targetAddress,mimeDTO,true,null); - } - /** - * 群发邮件 (附件) - * @param userName - * @param password - * @param targetAddress 多个邮件发送地址,以,分隔 - * @param mimeDTO - * @param filepath 文件本地绝对路径 - * @return - */ - public static boolean sendGroupEmailByFile(String userName,String password,String targetAddress, - MimeMessageDTO mimeDTO,List filepath){ - return publicsendEmail(userName,password,targetAddress,mimeDTO,true,filepath); - } - - - - /** - * 邮件发送基础方法 - * @param userName - * @param password - * @param targetAddress - * @param mimeDTO - * @param isGroup - * @param filepath - * @return - */ - private static boolean publicsendEmail(String userName,String password,String targetAddress, - MimeMessageDTO mimeDTO,boolean isGroup,List filepath){ - Properties props = makeMailProperties(userName); - String hostname=SMTPUtil.SimpleMailSender(userName); - Session session = Session.getInstance(props, new PopupAuthenticator(userName, password)); - session.setDebug(true); - try { - Transport ts = session.getTransport(); - ts.connect(hostname,userName,password); - Message message =!isGroup?createEmail(session,userName,targetAddress,mimeDTO) - :createEmailByGroupAndFile(session,userName, - targetAddress,mimeDTO,filepath==null?null:filepath); - ts.sendMessage(message,message.getAllRecipients()); - ts.close(); - } catch (Exception mex) { - mex.printStackTrace(); - return false; - } - return true; - } - - - - - - /** - * 创建邮件信息 - * @param userName - * @return - */ - private static Properties makeMailProperties(String userName){ - Properties props = new Properties(); - String hostname=SMTPUtil.SimpleMailSender(userName); - props.put("mail.smtp.host", hostname); - props.setProperty("mail.smtp.auth", "true"); - props.setProperty("mail.transport.protocol", "smtp"); - if(hostname.indexOf(".qq.com")!=-1){ - props.setProperty("mail.smtp.socketFactory.port", "465"); - props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); - } - return props; - } - - - - /** - * 创建邮件 - * @author Wujun - * Create_time:2015年10月17日 下午7:45:57 - * description: - */ - private static Message createEmail(Session session,String userName,String regMail,MimeMessageDTO mimeDTO){ - MimeMessage message = new MimeMessage(session); - try { - message.setFrom(new InternetAddress(userName)); - message.setRecipient(Message.RecipientType.TO, new InternetAddress(regMail)); - message.setSubject(mimeDTO.getSubject()); - message.setContent(mimeDTO.getText(),"text/html;charset=UTF-8"); - message.saveChanges(); - } catch (MessagingException e) { - e.printStackTrace(); - } - return message; - } - /** - * 创建群发带附件 - * @return - */ - private static Message createEmailByGroupAndFile(Session session,String userName, - String regMail,MimeMessageDTO mimeDTO,List filepath){ - MimeMessage message = new MimeMessage(session); - try { - message.setFrom(new InternetAddress(userName)); - // 创建收件人列表 - if (regMail != null && regMail.trim().length() > 0) { - String[] arr = regMail.split(","); - int receiverCount = arr.length; - if (receiverCount > 0) { - InternetAddress[] address = new InternetAddress[receiverCount]; - for (int i = 0; i < receiverCount; i++) { - address[i] = new InternetAddress(arr[i]); - } - message.setRecipients(Message.RecipientType.TO, address); - } - } - // 后面的BodyPart将加入到此处创建的Multipart中 - Multipart mp = new MimeMultipart(); - // 附件操作 - if (filepath != null && filepath.size() > 0) { - for (String filename : filepath) { - MimeBodyPart mbp = new MimeBodyPart(); - // 得到数据源 - FileDataSource fds = new FileDataSource(filename); - // 得到附件本身并至入BodyPart - mbp.setDataHandler(new DataHandler(fds)); - // 得到文件名同样至入BodyPart - mbp.setFileName(fds.getName()); - mp.addBodyPart(mbp); - } - MimeBodyPart mbp = new MimeBodyPart(); - mbp.setText(mimeDTO.getText()); - mp.addBodyPart(mbp); - // 移走集合中的所有元素 - filepath.clear(); - // Multipart加入到信件 - message.setContent(mp); - } else { - // 设置邮件正文 -// message.setText(mimeDTO.getText()); - message.setContent(mimeDTO.getText(),"text/html;charset=UTF-8"); - } - message.setSubject(mimeDTO.getSubject()); - message.saveChanges(); - } catch (MessagingException e) { - e.printStackTrace(); - } - return message; - } - - - - public String getUserName() { - return userName; - } - public void setUserName(String userName) { - this.userName = userName; - } - public String getPassword() { - return password; - } - public void setPassword(String password) { - this.password = password; - } - public String getSmtpHost() { - return smtpHost; - } - public void setSmtpHost(String smtpHost) { - this.smtpHost = smtpHost; - } - public String getTargetAddress() { - return targetAddress; - } - public void setTargetAddress(String targetAddress) { - this.targetAddress = targetAddress; - } -} diff --git a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/email/demo/util/PopupAuthenticator.java b/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/email/demo/util/PopupAuthenticator.java deleted file mode 100644 index 819cf9dd53..0000000000 --- a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/email/demo/util/PopupAuthenticator.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.jun.plugin.plugin.email.demo.util; - -import javax.mail.Authenticator; -import javax.mail.PasswordAuthentication; - -/** - * 类名称: PopupAuthenticator - * 功能描述: TODO - * 创建人: GavinNie 邮件 账号 密码 - * 创建时间: 2014-12-4 上午11:07:10 - * @version V1.0 - */ -public class PopupAuthenticator extends Authenticator { - private String username = null; - private String password = null; - - public PopupAuthenticator(String user, String pass) { - this.username = user; - this.password = pass; - } - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication(username, password); - } -} diff --git a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/email/demo/util/SMTPUtil.java b/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/email/demo/util/SMTPUtil.java deleted file mode 100644 index a29e105852..0000000000 --- a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/email/demo/util/SMTPUtil.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.jun.plugin.plugin.email.demo.util; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -/** - * 类名称: SMTPUtil - * 功能描述: TODO 得到smtp - * 创建人: GavinNie - * 创建时间: 2014-12-4 上午10:36:00 - * @version V1.0 - */ -public class SMTPUtil { - /** - * 方法名: SimpleMailSender - * 功能描述: TODO 简单的smtp生成,大部分是有用的,建议自己建立smtp库.... - * @param: @param userName - * @param: @return - * @return: String - */ - public static String SimpleMailSender(String userName) { - return "smtp." + getHost(userName); - } - - - /** - * @Title: getSMTPAddress - * @Description: TODO (这里用一句话描述这个方法的作用) - * @param @param userName - * @param @return 设定文件 - * @return String 返回类型 - * @throws - */ - public static String getSMTPAddress(String userName){ - String smtpAddress = null; - Properties props = new Properties(); - try { - InputStream in = SMTPUtil.class.getResourceAsStream("/smtp.properties"); - props.load(in); - //读取properties的内容 - smtpAddress = props.getProperty(getHost(userName).trim()); - //没有获取到 - if(smtpAddress == null){ - //生成简单得 - smtpAddress = SimpleMailSender(userName); - } - } catch (IOException e) { - e.printStackTrace(); - } - return smtpAddress; - } - - - /** - * @Title: getHost - * @Description: TODO 得到 邮箱@后面得字符 - * @param @param userName - * @param @return 设定文件 - * @return String 返回类型 - * @throws - */ - public static String getHost(String userName){ - return userName.split("@")[1]; - } - -// public static void main(String[] args) { -// String s = getSMTPAddress("nie_zw@qq.com"); -// System.out.println(s); -// } -} diff --git a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/email/java_mail/JavaMail.java b/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/email/java_mail/JavaMail.java deleted file mode 100644 index 5cfc0caa83..0000000000 --- a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/email/java_mail/JavaMail.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.jun.plugin.plugin.email.java_mail; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; -import javax.mail.Message; -import javax.mail.MessagingException; -import javax.mail.Session; -import javax.mail.Transport; -import javax.mail.internet.InternetAddress; -import javax.mail.internet.MimeMessage; -import javax.mail.internet.MimeUtility; - -public class JavaMail { - /** - * * Message对象将存储我们实际发送的电子邮件信息, * - * Message对象被作为一个MimeMessage对象来创建并且需要知道应当选择哪一个JavaMail session。 - */ - private MimeMessage message; - /** - * * Session类代表JavaMail中的一个邮件会话。 * - * 每一个基于JavaMail的应用程序至少有一个Session(可以有任意多的Session)。 * * - * JavaMail需要Properties来创建一个session对象。 * 寻找"mail.smtp.host" 属性值就是发送邮件的主机 * - * 寻找"mail.smtp.auth" 身份验证,目前免费邮件服务器都需要这一项 - */ - private Session session; - /*** - * * 邮件是既可以被发送也可以被受到。JavaMail使用了两个不同的类来完成这两个功能:Transport 和 Store。 * - * Transport 是用来发送信息的,而Store用来收信。对于这的教程我们只需要用到Transport对象。 - */ - private Transport transport; - private String mailHost = ""; - private String sender_username = ""; - private String sender_password = ""; - private Properties properties = new Properties(); - - /* * 初始化方法 */ - public JavaMail(boolean debug) { - InputStream in = JavaMail.class.getResourceAsStream("MailServer.properties"); - try { - properties.load(in); - this.mailHost = properties.getProperty("mail.smtp.host"); - this.sender_username = properties.getProperty("mail.sender.username"); - this.sender_password = properties.getProperty("mail.sender.password"); - } catch (IOException e) { - e.printStackTrace(); - } - session = Session.getInstance(properties); - session.setDebug(debug); - // 开启后有调试信息 message = new MimeMessage(session); - } - - /** - * * 发送邮件 * * @param subject * 邮件主题 * @param sendHtml * 邮件内容 * @param - * receiveUser * 收件人地址 - */ - public void doSendHtmlEmail(String subject, String sendHtml, String receiveUser) { - try { - // 发件人 // - // InternetAddress from = new InternetAddress(sender_username); - // 下面这个是设置发送人的Nick name - InternetAddress from = new InternetAddress(MimeUtility.encodeWord("幻影") + " < sender_username>"); - message.setFrom(from); - // 收件人 - InternetAddress to = new InternetAddress(receiveUser); - message.setRecipient(Message.RecipientType.TO, to);// 还可以有CC、BCC // - // 邮件主题 - message.setSubject(subject); - String content = sendHtml.toString(); - // 邮件内容,也可以使纯文本"text/plain" - message.setContent(content, "text/html;charset=UTF-8"); - // 保存邮件 - message.saveChanges(); - transport = session.getTransport("smtp"); // smtp验证,就是你用来发邮件的邮箱用户名密码 - transport.connect(mailHost, sender_username, sender_password); // 发送 - transport.sendMessage(message, message.getAllRecipients()); // - System.out.println("send success!"); - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (transport != null) { - try { - transport.close(); - } catch (MessagingException e) { - e.printStackTrace(); - } - } - } - } - - public static void main(String[] args) { - JavaMail se = new JavaMail(false); - se.doSendHtmlEmail("邮件主题", "邮件内容", "xxx@XX.com"); - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/email/java_mail/JavaMailWithAttachment.java b/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/email/java_mail/JavaMailWithAttachment.java deleted file mode 100644 index 6ff1a5eeaf..0000000000 --- a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/email/java_mail/JavaMailWithAttachment.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.jun.plugin.plugin.email.java_mail; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.Base64; -import java.util.Properties; -import javax.activation.DataHandler; -import javax.activation.DataSource; -import javax.activation.FileDataSource; -import javax.mail.BodyPart; -import javax.mail.Message; -import javax.mail.MessagingException; -import javax.mail.Multipart; -import javax.mail.Session; -import javax.mail.Transport; -import javax.mail.internet.InternetAddress; -import javax.mail.internet.MimeBodyPart; -import javax.mail.internet.MimeMessage; -import javax.mail.internet.MimeMultipart; -import javax.mail.internet.MimeUtility; - -public class JavaMailWithAttachment { - private MimeMessage message; - private Session session; - private Transport transport; - private String mailHost = ""; - private String sender_username = ""; - private String sender_password = ""; - private Properties properties = new Properties(); - - /* * 初始化方法 */public JavaMailWithAttachment(boolean debug) { - InputStream in = JavaMailWithAttachment.class.getResourceAsStream("MailServer.properties"); - try { - properties.load(in); - this.mailHost = properties.getProperty("mail.smtp.host"); - this.sender_username = properties.getProperty("mail.sender.username"); - this.sender_password = properties.getProperty("mail.sender.password"); - } catch (IOException e) { - e.printStackTrace(); - } - session = Session.getInstance(properties); - session.setDebug(debug);// - // 开启后有调试信息 C - message = new MimeMessage(session); - } - - /** - * * 发送邮件 * * @param subject * 邮件主题 * @param sendHtml * 邮件内容 * @param - * receiveUser * 收件人地址 * @param attachment * 附件 - */ - public void doSendHtmlEmail(String subject, String sendHtml, String receiveUser, File attachment) { - try { // - // 发件人 - InternetAddress from = new InternetAddress(sender_username); - message.setFrom(from); // - // 收件人 - InternetAddress to = new InternetAddress(receiveUser); - message.setRecipient(Message.RecipientType.TO, to); // - // 邮件主题 - message.setSubject(subject); // - // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件 - Multipart multipart = new MimeMultipart(); // - // 添加邮件正文 - BodyPart contentPart = new MimeBodyPart(); - contentPart.setContent(sendHtml, "text/html;charset=UTF-8"); - multipart.addBodyPart(contentPart); // - // 添加附件的内容 - if (attachment != null) { - BodyPart attachmentBodyPart = new MimeBodyPart(); - DataSource source = new FileDataSource(attachment); - attachmentBodyPart.setDataHandler(new DataHandler(source)); // - // 网上流传的解决文件名乱码的方法,其实用MimeUtility.encodeWord就可以很方便的搞定 // - // 这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码 // - // 使用Java标准库的Base64编码器替代已废弃的sun.misc.BASE64Encoder -// messageBodyPart.setFileName("=?GBK?B?" + Base64.getEncoder().encodeToString(attachment.getName().getBytes()) + "?="); // - message.setFileName("=?GBK?B?" + Base64.getEncoder().encodeToString(attachment.getName().getBytes()) + "?="); // - // MimeUtility.encodeWord可以避免文件名乱码 - attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName())); - multipart.addBodyPart(attachmentBodyPart); - } // - // 将multipart对象放到message中 - message.setContent(multipart); // - // 保存邮件 - message.saveChanges(); - transport = session.getTransport("smtp"); // - // smtp验证,就是你用来发邮件的邮箱用户名密码 - transport.connect(mailHost, sender_username, sender_password); // - // 发送 - transport.sendMessage(message, message.getAllRecipients()); - System.out.println("send success!"); - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (transport != null) { - try { - transport.close(); - } catch (MessagingException e) { - e.printStackTrace(); - } - } - } - } - - public static void main(String[] args) { - JavaMailWithAttachment se = new JavaMailWithAttachment(true); - File affix = new File("c:\\测试-test.txt"); - se.doSendHtmlEmail("邮件主题", "邮件内容", "xxx@XXX.com", affix);// - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/email/java_mail/mail_imap.java b/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/email/java_mail/mail_imap.java deleted file mode 100644 index 1a999a24db..0000000000 --- a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/email/java_mail/mail_imap.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.jun.plugin.plugin.email.java_mail; - -import java.util.Properties; - -import javax.mail.Flags; -import javax.mail.Folder; -import javax.mail.Message; -import javax.mail.Session; - -import com.sun.mail.imap.IMAPFolder; -import com.sun.mail.imap.IMAPStore; - -public class mail_imap { - /** - * 使用imap协议获取未读邮件数 - * - * @author Wujun - * - */ - public static void main(String[] args) throws Exception { - String user = "username@sohu.com";// 邮箱的用户名 - String password = "password"; // 邮箱的密码 - Properties prop = System.getProperties(); - prop.put("mail.store.protocol", "imap"); - prop.put("mail.imap.host", "imap.sohu.com"); - Session session = Session.getInstance(prop); - int total = 0; - IMAPStore store = (IMAPStore) session.getStore("imap"); // 使用imap会话机制,连接服务器 - store.connect(user, password); - IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX"); // 收件箱 - folder.open(Folder.READ_WRITE); - // 获取总邮件数 - total = folder.getMessageCount(); - System.out.println("-----------------共有邮件:" + total + " 封--------------"); - // 得到收件箱文件夹信息,获取邮件列表 - System.out.println("未读邮件数:" + folder.getUnreadMessageCount()); - Message[] messages = folder.getMessages(); - int messageNumber = 0; - for (Message message : messages) { - System.out.println("发送时间:" + message.getSentDate()); - System.out.println("主题:" + message.getSubject()); - System.out.println("内容:" + message.getContent()); - Flags flags = message.getFlags(); - if (flags.contains(Flags.Flag.SEEN)) - System.out.println("这是一封已读邮件"); - else { - System.out.println("未读邮件"); - } - System.out.println("========================================================"); - System.out.println("========================================================"); - // 每封邮件都有一个MessageNumber,可以通过邮件的MessageNumber在收件箱里面取得该邮件 - messageNumber = message.getMessageNumber(); - } - Message message = folder.getMessage(messageNumber); - System.out.println(message.getContent() + message.getContentType()); - // 释放资源 - if (folder != null) - folder.close(true); - if (store != null) - store.close(); - } -} diff --git a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/email/java_mail/mail_pop3.java b/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/email/java_mail/mail_pop3.java deleted file mode 100644 index 9e93de264c..0000000000 --- a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/email/java_mail/mail_pop3.java +++ /dev/null @@ -1,123 +0,0 @@ -package com.jun.plugin.plugin.email.java_mail; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Enumeration; -import java.util.Properties; - -import javax.mail.BodyPart; -import javax.mail.Folder; -import javax.mail.Message; -import javax.mail.MessagingException; -import javax.mail.Multipart; -import javax.mail.Session; -import javax.mail.Store; -import javax.mail.internet.MimeMultipart; - -public class mail_pop3 { - - public static void main(String args[]) throws MessagingException, IOException { - Properties props = new Properties(); - props.setProperty("mail.store.protocol", "pop3"); - props.setProperty("mail.pop3.host", "pop3.sohu.com"); - Session session = Session.getDefaultInstance(props); - Store store = session.getStore("pop3"); - store.connect("username@sohu.com", "password"); - Folder folder = store.getFolder("INBOX"); - folder.open(Folder.READ_WRITE); - // 全部邮件数 - int messageCount = folder.getMessageCount(); - System.out.println(messageCount); - Message[] messages = folder.getMessages(); - for (int i = 0; i < messages.length; i++) { - Message message = messages[i]; - System.out.println(message.getSubject()); - // 删除邮件 - // message.setFlag(Flags.Flag.DELETED, true); - // 标记为已读 - // message.setFlag(Flags.Flag.SEEN, true); - // pop3没有判断邮件是否为已读的功能,要使用Imap才可以 - /* - * Flags flags = message.getFlags(); if - * (flags.contains(Flags.Flag.SEEN)) System.out.println("这是一封已读邮件"); - * else { System.out.println("未读邮件"); - * message.setFlag(Flags.Flag.SEEN, true); } - */ - System.out.println("发送时间:" + message.getSentDate()); - System.out.println("主题:" + message.getSubject()); - System.out.println("内容:" + message.getContent()); - // 获取所有的Header,头信息 - Enumeration headers = message.getAllHeaders(); - System.out.println("----------------------allHeaders-----------------------------"); - /* - * while (headers.hasMoreElements()) { Header header = - * (Header)headers.nextElement(); - * System.out.println(header.getName()+" ======= "+header.getValue() - * ); } - */ - // 解析邮件内容 - Object content = message.getContent(); - if (content instanceof MimeMultipart) { - MimeMultipart multipart = (MimeMultipart) content; - parseMultipart(multipart); - } - System.out.println("========================================================"); - System.out.println("========================================================"); - } - folder.close(true); - store.close(); - } - - /** - * 对复杂邮件的解析 - * - * @param multipart - * @throws MessagingException - * @throws IOException - */ - public static void parseMultipart(Multipart multipart) throws MessagingException, IOException { - int count = multipart.getCount(); - System.out.println("couont = " + count); - for (int idx = 0; idx < count; idx++) { - BodyPart bodyPart = multipart.getBodyPart(idx); - System.out.println(bodyPart.getContentType()); - if (bodyPart.isMimeType("text/plain")) { - System.out.println("plain................." + bodyPart.getContent()); - } else if (bodyPart.isMimeType("text/html")) { - System.out.println("html..................." + bodyPart.getContent()); - } else if (bodyPart.isMimeType("multipart/*")) { - Multipart mpart = (Multipart) bodyPart.getContent(); - parseMultipart(mpart); - } else if (bodyPart.isMimeType("application/octet-stream")) { - String disposition = bodyPart.getDisposition(); - System.out.println(disposition); - if (disposition.equalsIgnoreCase(BodyPart.ATTACHMENT)) { - String fileName = bodyPart.getFileName(); - InputStream is = bodyPart.getInputStream(); - copy(is, new FileOutputStream("D:\\" + fileName)); - } - } - } - } - - /** - * 文件拷贝,在用户进行附件下载的时候,可以把附件的InputStream传给用户进行下载 - * - * @param is - * @param os - * @throws IOException - */ - public static void copy(InputStream is, OutputStream os) throws IOException { - byte[] bytes = new byte[1024]; - int len = 0; - while ((len = is.read(bytes)) != -1) { - os.write(bytes, 0, len); - } - if (os != null) - os.close(); - if (is != null) - is.close(); - } -} diff --git a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/email/java_mail/sendMail.java b/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/email/java_mail/sendMail.java deleted file mode 100644 index 8d914e51ef..0000000000 --- a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/email/java_mail/sendMail.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.jun.plugin.plugin.email.java_mail; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Enumeration; -import java.util.Properties; -import javax.mail.BodyPart; -import javax.mail.Folder; -import javax.mail.Message; -import javax.mail.MessagingException; -import javax.mail.Multipart; -import javax.mail.Session; -import javax.mail.Store; -import javax.mail.internet.MimeMultipart; - -public class sendMail { - public static void main(String args[]) throws MessagingException, IOException { - Properties props = new Properties(); - props.setProperty("mail.store.protocol", "pop3"); - props.setProperty("mail.pop3.host", "pop3.sohu.com"); - Session session = Session.getDefaultInstance(props); - Store store = session.getStore("pop3"); - store.connect("username@sohu.com", "password"); - Folder folder = store.getFolder("INBOX"); - folder.open(Folder.READ_WRITE); - // 全部邮件数 - int messageCount = folder.getMessageCount(); - System.out.println(messageCount); - Message[] messages = folder.getMessages(); - for (int i = 0; i < messages.length; i++) { - Message message = messages[i]; - System.out.println(message.getSubject()); - // 删除邮件 - // message.setFlag(Flags.Flag.DELETED, true); - // 标记为已读 - // message.setFlag(Flags.Flag.SEEN, true); - // pop3没有判断邮件是否为已读的功能,要使用Imap才可以 - /* - * Flags flags = message.getFlags(); if - * (flags.contains(Flags.Flag.SEEN)) System.out.println("这是一封已读邮件"); - * else { System.out.println("未读邮件"); - * message.setFlag(Flags.Flag.SEEN, true); } - */ - System.out.println("发送时间:" + message.getSentDate()); - System.out.println("主题:" + message.getSubject()); - System.out.println("内容:" + message.getContent()); - // 获取所有的Header,头信息 - Enumeration headers = message.getAllHeaders(); - System.out.println("----------------------allHeaders-----------------------------"); - /* - * while (headers.hasMoreElements()) { Header header = - * (Header)headers.nextElement(); - * System.out.println(header.getName()+" ======= "+header.getValue() - * ); } - */ - // 解析邮件内容 - Object content = message.getContent(); - if (content instanceof MimeMultipart) { - MimeMultipart multipart = (MimeMultipart) content; - parseMultipart(multipart); - } - System.out.println("========================================================"); - System.out.println("========================================================"); - } - folder.close(true); - store.close(); - } - - /** - * 对复杂邮件的解析 - * - * @param multipart - * @throws MessagingException - * @throws IOException - */ - public static void parseMultipart(Multipart multipart) throws MessagingException, IOException { - int count = multipart.getCount(); - System.out.println("couont = " + count); - for (int idx = 0; idx < count; idx++) { - BodyPart bodyPart = multipart.getBodyPart(idx); - System.out.println(bodyPart.getContentType()); - if (bodyPart.isMimeType("text/plain")) { - System.out.println("plain................." + bodyPart.getContent()); - } else if (bodyPart.isMimeType("text/html")) { - System.out.println("html..................." + bodyPart.getContent()); - } else if (bodyPart.isMimeType("multipart/*")) { - Multipart mpart = (Multipart) bodyPart.getContent(); - parseMultipart(mpart); - } else if (bodyPart.isMimeType("application/octet-stream")) { - String disposition = bodyPart.getDisposition(); - System.out.println(disposition); - if (disposition.equalsIgnoreCase(BodyPart.ATTACHMENT)) { - String fileName = bodyPart.getFileName(); - InputStream is = bodyPart.getInputStream(); - copy(is, new FileOutputStream("D:\\" + fileName)); - } - } - } - } - - /** - * 文件拷贝,在用户进行附件下载的时候,可以把附件的InputStream传给用户进行下载 - * - * @param is - * @param os - * @throws IOException - */ - public static void copy(InputStream is, OutputStream os) throws IOException { - byte[] bytes = new byte[1024]; - int len = 0; - while ((len = is.read(bytes)) != -1) { - os.write(bytes, 0, len); - } - if (os != null) - os.close(); - if (is != null) - is.close(); - } -} diff --git a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/me/MyEmail.java b/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/me/MyEmail.java deleted file mode 100644 index c584373cf7..0000000000 --- a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/me/MyEmail.java +++ /dev/null @@ -1,330 +0,0 @@ -package com.jun.plugin.plugin.me; - -import javax.activation.DataHandler; -import javax.activation.FileDataSource; -import javax.mail.*; -import javax.mail.internet.*; -import java.io.File; -import java.net.URL; -import java.util.*; - -/** - * Oh My email - *

- * May be the smallest mail send library. - * - * @author biezhi - * 2017/5/30 - */ -public class MyEmail { - - private static Session session; - private static String user; - - private MimeMessage msg; - private String text; - private String html; - private List attachments = new ArrayList(); - - private MyEmail() { - } - - public static Properties defaultConfig(Boolean debug) { - Properties props = new Properties(); - props.put("mail.smtp.auth", "true"); - props.put("mail.smtp.ssl.enable", "true"); - props.put("mail.transport.protocol", "smtp"); - props.put("mail.debug", null != debug ? debug.toString() : "false"); - props.put("mail.smtp.timeout", "10000"); - props.put("mail.smtp.port", "465"); - return props; - } - - /** - * smtp entnterprise qq - * - * @param debug - * @return - */ - public static Properties SMTP_ENT_QQ(boolean debug) { - Properties props = defaultConfig(debug); - props.put("mail.smtp.host", "smtp.exmail.qq.com"); - return props; - } - - /** - * smtp qq - * - * @param debug enable debug - * @return - */ - public static Properties SMTP_QQ(boolean debug) { - Properties props = defaultConfig(debug); - props.put("mail.smtp.host", "smtp.qq.com"); - return props; - } - - /** - * smtp 163 - * - * @param debug enable debug - * @return - */ - public static Properties SMTP_163(Boolean debug) { - Properties props = defaultConfig(debug); - props.put("mail.smtp.host", "smtp.163.com"); - return props; - } - - /** - * config username and password - * - * @param props email property config - * @param username email auth username - * @param password email auth password - */ - public static void config(Properties props, final String username, final String password) { - props.setProperty("username", username); - props.setProperty("password", password); - config(props); - } - - public static void config(Properties props) { - final String username = props.getProperty("username"); - final String password = props.getProperty("password"); - user = username; - session = Session.getInstance(props, new Authenticator() { - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication(username, password); - } - }); - } - - /** - * set email subject - * - * @param subject subject title - */ - public static MyEmail subject(String subject) throws SendMailException { - MyEmail ohMyEmail = new MyEmail(); - ohMyEmail.msg = new MimeMessage(session); - try { - ohMyEmail.msg.setSubject(subject, "UTF-8"); - } catch (Exception e) { - throw new SendMailException(e); - } - return ohMyEmail; - } - - /** - * set email from - * - * @param nickName from nickname - */ - public MyEmail from(String nickName) throws SendMailException { - return from(nickName, user); - } - - /** - * set email nickname and from user - * - * @param nickName from nickname - * @param from from email - */ - public MyEmail from(String nickName, String from) throws SendMailException { - try { - String encodeNickName = MimeUtility.encodeText(nickName); - msg.setFrom(new InternetAddress(encodeNickName + " <" + from + ">")); - } catch (Exception e) { - throw new SendMailException(e); - } - return this; - } - - public MyEmail replyTo(String... replyTo) throws SendMailException { - String result = Arrays.asList(replyTo).toString().replaceAll("(^\\[|\\]$)", "").replace(", ", ","); - try { - msg.setReplyTo(InternetAddress.parse(result)); - } catch (Exception e) { - throw new SendMailException(e); - } - return this; - } - - public MyEmail replyTo(String replyTo) throws SendMailException { - try { - msg.setReplyTo(InternetAddress.parse(replyTo.replace(";", ","))); - } catch (Exception e) { - throw new SendMailException(e); - } - return this; - } - - public MyEmail to(String... to) throws SendMailException { - try { - return addRecipients(to, Message.RecipientType.TO); - } catch (MessagingException e) { - throw new SendMailException(e); - } - } - - public MyEmail to(String to) throws SendMailException { - try { - return addRecipient(to, Message.RecipientType.TO); - } catch (MessagingException e) { - throw new SendMailException(e); - } - } - - public MyEmail cc(String... cc) throws SendMailException { - try { - return addRecipients(cc, Message.RecipientType.CC); - } catch (MessagingException e) { - throw new SendMailException(e); - } - } - - public MyEmail cc(String cc) throws SendMailException { - try { - return addRecipient(cc, Message.RecipientType.CC); - } catch (MessagingException e) { - throw new SendMailException(e); - } - } - - public MyEmail bcc(String... bcc) throws SendMailException { - try { - return addRecipients(bcc, Message.RecipientType.BCC); - } catch (MessagingException e) { - throw new SendMailException(e); - } - } - - public MyEmail bcc(String bcc) throws MessagingException { - return addRecipient(bcc, Message.RecipientType.BCC); - } - - private MyEmail addRecipients(String[] recipients, Message.RecipientType type) throws MessagingException { - String result = Arrays.asList(recipients).toString().replace("(^\\[|\\]$)", "").replace(", ", ","); - msg.setRecipients(type, InternetAddress.parse(result)); - return this; - } - - private MyEmail addRecipient(String recipient, Message.RecipientType type) throws MessagingException { - msg.setRecipients(type, InternetAddress.parse(recipient.replace(";", ","))); - return this; - } - - public MyEmail text(String text) { - this.text = text; - return this; - } - - public MyEmail html(String html) { - this.html = html; - return this; - } - - public MyEmail attach(File file) throws SendMailException { - attachments.add(createAttachment(file, null)); - return this; - } - - public MyEmail attach(File file, String fileName) throws SendMailException { - attachments.add(createAttachment(file, fileName)); - return this; - } - - public MyEmail attachURL(URL url, String fileName) throws SendMailException { - attachments.add(createURLAttachment(url, fileName)); - return this; - } - - private MimeBodyPart createAttachment(File file, String fileName) throws SendMailException { - MimeBodyPart attachmentPart = new MimeBodyPart(); - FileDataSource fds = new FileDataSource(file); - try { - attachmentPart.setDataHandler(new DataHandler(fds)); - attachmentPart.setFileName(null == fileName ? MimeUtility.encodeText(fds.getName()) : MimeUtility.encodeText(fileName)); - } catch (Exception e) { - throw new SendMailException(e); - } - return attachmentPart; - } - - private MimeBodyPart createURLAttachment(URL url, String fileName) throws SendMailException { - MimeBodyPart attachmentPart = new MimeBodyPart(); - - DataHandler dataHandler = new DataHandler(url); - try { - attachmentPart.setDataHandler(dataHandler); - attachmentPart.setFileName(null == fileName ? MimeUtility.encodeText(fileName) : MimeUtility.encodeText(fileName)); - } catch (Exception e) { - throw new SendMailException(e); - } - return attachmentPart; - } - - public void send() throws SendMailException { - if (text == null && html == null) { - throw new IllegalArgumentException("At least one context has to be provided: Text or Html"); - } - - MimeMultipart cover; - boolean usingAlternative = false; - boolean hasAttachments = attachments.size() > 0; - - try { - if (text != null && html == null) { - // TEXT ONLY - cover = new MimeMultipart("mixed"); - cover.addBodyPart(textPart()); - } else if (text == null && html != null) { - // HTML ONLY - cover = new MimeMultipart("mixed"); - cover.addBodyPart(htmlPart()); - } else { - // HTML + TEXT - cover = new MimeMultipart("alternative"); - cover.addBodyPart(textPart()); - cover.addBodyPart(htmlPart()); - usingAlternative = true; - } - - MimeMultipart content = cover; - if (usingAlternative && hasAttachments) { - content = new MimeMultipart("mixed"); - content.addBodyPart(toBodyPart(cover)); - } - - for (MimeBodyPart attachment : attachments) { - content.addBodyPart(attachment); - } - - msg.setContent(content); - msg.setSentDate(new Date()); - Transport.send(msg); - } catch (Exception e) { - throw new SendMailException(e); - } - } - - private MimeBodyPart toBodyPart(MimeMultipart cover) throws MessagingException { - MimeBodyPart wrap = new MimeBodyPart(); - wrap.setContent(cover); - return wrap; - } - - private MimeBodyPart textPart() throws MessagingException { - MimeBodyPart bodyPart = new MimeBodyPart(); - bodyPart.setText(text); - return bodyPart; - } - - private MimeBodyPart htmlPart() throws MessagingException { - MimeBodyPart bodyPart = new MimeBodyPart(); - bodyPart.setContent(html, "text/html; charset=utf-8"); - return bodyPart; - } - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/me/SendMailException.java b/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/me/SendMailException.java deleted file mode 100644 index cb8ca7064c..0000000000 --- a/jun_java_plugins/jun_email/src/main/java/com/jun/plugin/plugin/me/SendMailException.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jun.plugin.plugin.me; - -/** - * Send Email Exception - * - * @author biezhi - * @date 2018/10/9 - */ -public class SendMailException extends Exception { - - public SendMailException() { - } - - public SendMailException(String message) { - super(message); - } - - public SendMailException(Throwable cause) { - super(cause); - } -} diff --git a/jun_java_plugins/jun_email/src/test/java/com/jun/plugin/me/MyEmailTest.java b/jun_java_plugins/jun_email/src/test/java/com/jun/plugin/me/MyEmailTest.java deleted file mode 100644 index 3c1c2ee4e4..0000000000 --- a/jun_java_plugins/jun_email/src/test/java/com/jun/plugin/me/MyEmailTest.java +++ /dev/null @@ -1,130 +0,0 @@ -package com.jun.plugin.me; - -import com.jun.plugin.plugin.me.MyEmail; -import com.jun.plugin.plugin.me.SendMailException; -//import jetbrick.template.JetEngine; -//import jetbrick.template.JetTemplate; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import static com.jun.plugin.plugin.me.MyEmail.SMTP_ENT_QQ; -import static com.jun.plugin.plugin.me.MyEmail.SMTP_QQ; - -import java.io.File; -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; - -/** - * 发送邮件测试 - * - * @author biezhi - * 2017/5/30 - */ -public class MyEmailTest { - - // 该邮箱修改为你需要测试的邮箱地址 - private static final String TO_EMAIL = "xiaojiejie@gmail.com"; - - @Before - public void before() { - // 配置,一次即可 - MyEmail.config(SMTP_QQ(false), "xxx@qq.com", "*******"); - // 如果是企业邮箱则使用下面配置 - MyEmail.config(SMTP_ENT_QQ(false), "xxx@qq.com", "*******"); - } - - @Test - public void testSendText() throws SendMailException { - MyEmail.subject("这是一封测试TEXT邮件") - .from("小姐姐的邮箱") - .to(TO_EMAIL) - .text("信件内容") - .send(); - Assert.assertTrue(true); - } - - @Test - public void testSendHtml() throws SendMailException { - MyEmail.subject("这是一封测试HTML邮件") - .from("小姐姐的邮箱") - .to(TO_EMAIL) - .html("

信件内容

") - .send(); - Assert.assertTrue(true); - } - - @Test - public void testSendAttach() throws SendMailException { - MyEmail.subject("这是一封测试附件邮件") - .from("小姐姐的邮箱") - .to(TO_EMAIL) - .html("

信件内容

") - .attach(new File("/Users/biezhi/Downloads/hello.jpeg"), "测试图片.jpeg") - .send(); - Assert.assertTrue(true); - } - - @Test - public void testSendAttachURL() throws SendMailException, MalformedURLException { - MyEmail.subject("这是一封测试网络资源作为附件的邮件") - .from("小姐姐的邮箱") - .to(TO_EMAIL) - .html("

信件内容

") - .attachURL(new URL("https://avatars1.githubusercontent.com/u/2784452?s=40&v=4"), "测试图片.jpeg") - .send(); - Assert.assertTrue(true); - } - -// @Test -// public void testPebble() throws IOException, PebbleException, SendMailException { -// PebbleEngine engine = new PebbleEngine.Builder().build(); -// PebbleTemplate compiledTemplate = engine.getTemplate("register.html"); -// -// Map context = new HashMap(); -// context.put("username", "biezhi"); -// context.put("email", "admin@biezhi.me"); -// -// Writer writer = new StringWriter(); -// compiledTemplate.evaluate(writer, context); -// -// String output = writer.toString(); -// System.out.println(output); -// -// MyEmail.subject("这是一封测试Pebble模板邮件") -// .from("小姐姐的邮箱") -// .to(TO_EMAIL) -// .html(output) -// .send(); -// Assert.assertTrue(true); -// } - -// @Test -// public void testJetx() throws SendMailException { -// JetEngine engine = JetEngine.create(); -// JetTemplate template = engine.getTemplate("/register.jetx"); -// -// Map context = new HashMap(); -// context.put("username", "biezhi"); -// context.put("email", "admin@biezhi.me"); -// context.put("url", "https://biezhi.me/active/asdkjajdasjdkaweoi"); -// -// StringWriter writer = new StringWriter(); -// template.render(context, writer); -// String output = writer.toString(); -// System.out.println(output); -// -// MyEmail.subject("这是一封测试Jetx模板邮件") -// .from("小姐姐的邮箱") -// .to(TO_EMAIL) -// .html(output) -// .send(); -// Assert.assertTrue(true); -// } - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_email/src/test/resources/register.html b/jun_java_plugins/jun_email/src/test/resources/register.html deleted file mode 100644 index 008f04cd61..0000000000 --- a/jun_java_plugins/jun_email/src/test/resources/register.html +++ /dev/null @@ -1,13 +0,0 @@ -
-

亲爱的{{ username }}, 欢迎加入 biezhi !

-

当您收到这封信的时候,您已经可以正常登录了。

-

请点击链接登录首页: http://biezhi.me/xxxxx

-

如果您的 email 程序不支持链接点击,请将上面的地址拷贝至您的浏览器(如IE)的地址栏进入。

-

如果您还想申请管理员权限,可以联系管理员 {{ email }}

-

我们对您产生的不便,深表歉意。

-

希望您在 biezhi 系统度过快乐的时光!

-

-

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

-

-

(这是一封自动产生的email,请勿回复。)

-
\ No newline at end of file diff --git a/jun_java_plugins/jun_email/src/test/resources/register.jetx b/jun_java_plugins/jun_email/src/test/resources/register.jetx deleted file mode 100644 index dc3e35de6a..0000000000 --- a/jun_java_plugins/jun_email/src/test/resources/register.jetx +++ /dev/null @@ -1,13 +0,0 @@ -
-

亲爱的${username}, 欢迎加入 biezhi!

-

当您收到这封信的时候,您已经可以正常登录了。

-

请点击链接登录首页: ${url}

-

如果您的 email 程序不支持链接点击,请将上面的地址拷贝至您的浏览器(如IE)的地址栏进入。

-

如果您还想申请管理员权限,可以联系管理员 ${email}

-

我们对您产生的不便,深表歉意。

-

希望您在 biezhi 系统度过快乐的时光!

-

-

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

-

-

(这是一封自动产生的email,请勿回复。)

-
\ No newline at end of file diff --git a/jun_java_plugins/jun_excel/README.md b/jun_java_plugins/jun_excel/README.md deleted file mode 100644 index 47da01cdf5..0000000000 --- a/jun_java_plugins/jun_excel/README.md +++ /dev/null @@ -1,40 +0,0 @@ -# jun_excel 快速简单读取excel数据,将Apache POI进行了薄封装,基于注解,更加易于使用 - - -快速简单读取excel数据,将Apache POI进行了薄封装,基于注解,更加易于使用
- -###使用样例 -```java -FastExcel fastExcel = new FastExcel("E:/data.xlsx"); - fastExcel.setSheetName("活动信息数据"); - List tests = fastExcel.parse(MyTest.class); - if(null != tests && !tests.isEmpty()) { - for(MyTest myTest : tests) { - LOG.debug("记录:{}", myTest.toString()); - } - } else { - LOG.debug("没有结果"); - } -``` - -###映射类 -```java - public class MyTest { - - @MapperCell(cellName = "名称") - private String name; - - @MapperCell(cellName = "联系电话") - private String phone; - - @MapperCell(cellName = "地址") - private String address; - - @MapperCell(cellName = "一级分类ID") - private int type; - - @MapperCell(cellName = "经度") - private double lat; - -} -``` diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/.gitignore b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/.gitignore deleted file mode 100644 index 4e52a229af..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/.gitignore +++ /dev/null @@ -1,26 +0,0 @@ -# Compiled class file -*.class - -# Log file -*.log - -# BlueJ files -*.ctxt - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ - -# Package Files # -*.jar -*.war -*.nar -*.ear -*.zip -*.tar.gz -*.rar - -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* - -*.iml -.idea/ diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/README.md b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/README.md deleted file mode 100644 index d88ee05ba7..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/README.md +++ /dev/null @@ -1,213 +0,0 @@ -# sanri-excel-poi Excel 导入导出工具 - -sanri-excel-poi 是一个开源的用于企业开发的 Excel 导入导出,在 2017 年完成第一版,已经在线上环境实验过两年。主要用于解决 Excel 导出麻烦 ,导出慢,及 Excel 导入数据的空行,空格,数字精度,日期转换,Excel 公式 等问题。 - -博客地址:https://blog.csdn.net/sanri1993/article/details/100601578 - -javaDoc:https://apidoc.gitee.com/sanri/sanri-excel-poi - ------ - -## 优势 - -1. 支持 Excel 公式 -2. 导入的时候空行问题 -3. 导入数据去前后空格 -4. 继承类也可以导出数据 -5. 完美的支持日期格式的导入导出 -6. 数字为浮点型的精度处理 -7. 完美解决导出时的中文列宽问题 -8. 可自定义列的顺序 -9. 增加列转化器 - -## 快速上手 - -* 引入 maven 依赖 - -```xml - - com.sanri.excel - sanri-excel-poi - 1.0-RELEASE - -``` - -目前需要自己下载代码来构建,或下载已经构建好的 release 包 : -https://github.com/sanri1993/sanri-excel-poi/releases/tag/v1.0-RELEASE - -* 还需要添加第三方依赖,如果项目中已经存在依赖,请忽略。(真实项目一般都是有依赖的) - -```xml - - - org.apache.poi - poi - 3.10-FINAL - - - org.apache.poi - poi-ooxml - 3.10-FINAL - - - - - org.apache.commons - commons-lang3 - 3.8.1 - - - commons-io - commons-io - 2.6 - - - org.apache.commons - commons-csv - 1.2 - - - - - log4j - log4j - 1.2.17 - - - org.slf4j - slf4j-log4j12 - 1.7.21 - -``` - -* 最简单的导出示例 - -```java -// 定义导出实体 -@ExcelExport -@Data -public class Simple { - @ExcelColumn(value = "姓名",order = 0) - private String name; -} - -//获取数据 -List datas = new ArrayList(); -datas.add(new Simple()); - -//导出Excel -ExcelExportWriter excelExportWriter = new ExcelExportWriter(Simple.class); -excelExportWriter.export(simpleList); //这一步只是生成了 Workbook 的数据,还需要用户来决定输出到哪 -//写到文件流 -excelExportWriter.writeTo(new FileOutputStream("d:/test/"+System.currentTimeMillis()+".xlsx")); -//或写到响应流 -excelExportWriter.writeTo(response.getOutputStream()); -``` - - `order` 属性在导出不存在问题,但如果**使用导入下标必须从 0 开始** - - - -* 最简单的导入示例 - -```java -// 定义导入实体 -@ExcelImport(startRow = 1) -@Data -public class Simple { - @ExcelColumn(value = "姓名",order = 0) - private String name; -} - -//获取输入流 -InputStream fileInputStream = new FileInputStream("simple.xlsx"); -//创建错误行处理器,可以使用默认收集处理器 - ErrorRowHandler collectErrorRowHandler = new CollectErrorRowHandler(); - //导入数据 -List simples = ExcelImportUtil.importData(fileInputStream, Simple.class,collectErrorRowHandler); -``` - ------ - -## 配置你的导入导出 - -### 注解 @ExcelExport 相关配置 - -```java -// Excel 导出版本,可选值 ExcelVersion.EXCEL2007,ExcelVersion.EXCEL2003 -ExcelVersion version() default ExcelVersion.EXCEL2007; - -// 当导出有设置标题时,设置标题行的高度 -short titleRowHeight() default 40; - -// 头部行的高度,即列说明行的高度 -short headRowHeight() default 30; - -// 每一行数据的高度 -short bodyRowHeight() default 25; - -// 是否自动宽度,Excel 的自动宽度对中文支持不好,我这里对中文宽度做了适应 -boolean autoWidth() default true; - -// 一个 sheet 页的最大数据量,设置 -1 表示不限制,2003 版本最大 60000 行;超过的行数会另起 sheet 页 -int sheetMaxRow() default -1; - -// 快速导出模式,使用 new SXSSFWorkbook(rowAccessWindowSize) workbook 对象 -boolean fastModel() default true; - -// 快速导出模式的一个设置,一般默认就行 -int rowAccessWindowSize() default 1000; - -``` - -### 注解 @ExcelImport 相关配置 - -```java -// 数据起始行,一般设置 1 就行,从 0 开始 -int startRow(); - -// 支持导入的版本,默认都支持 -ExcelVersion[] support() default {ExcelVersion.EXCEL2003,ExcelVersion.EXCEL2007}; -``` - - - -### 列注解 @ExcelColumn 相关配置 - -```java -// 导出的中文头部列的值,导入不用管 -String value(); -// 导入的顺序,默认从 0 开始,导出不用管 -int order() default -1; - - -// 宽度,Excel 宽度单元 -int width() default -1; -// 使用字符数来定义宽度,一个中文算一个字符 -int charWidth() default -1; -// 使用像素值来定义宽度 -int pxWidth() default -1; -// 在使用自动宽度的时候,标记当前列是中文列 -boolean chineseWidth() default false; - -// 导出是否隐藏当前列 -boolean hidden() default false; -// 导入的时候对当前列做字符串前后空格过滤 -boolean trim() default true; -// 导出的时候的单元格类型,可选值有CELL_TYPE_NUMERIC,CELL_TYPE_STRING,CELL_TYPE_BLANK,CELL_TYPE_BOOLEAN -CellType cellType() default CellType.CELL_TYPE_STRING; - -// 导入、导出日期格式 -String pattern() default "yyyy-MM-dd"; -// 导入、导出的数字精度设置,会对浮点型做处理 -int precision() default -1; -``` - - - -## 更新记录 - -### 更新于 2019/09/13 - -- 增加错误行处理器,解决导入有错误行不能处理问题 -- 更新测试类 \ No newline at end of file diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/pom.xml b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/pom.xml deleted file mode 100644 index b161708e04..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/pom.xml +++ /dev/null @@ -1,97 +0,0 @@ - - - 4.0.0 - - com.sanri.excel - sanri-excel-poi - 1.1-RELEASE - - - - org.apache.poi - poi - 3.10-FINAL - - - org.apache.poi - poi-ooxml - 3.10-FINAL - - - - org.apache.commons - commons-lang3 - 3.8.1 - - - commons-io - commons-io - 2.6 - - - org.apache.commons - commons-csv - 1.2 - - - - log4j - log4j - 1.2.17 - - - org.slf4j - slf4j-log4j12 - 1.7.21 - - - junit - junit - 4.12 - test - - - com.alibaba - fastjson - 1.2.30 - test - - - - - sanri-excel-poi - - - - src/main/java - - **/*.json - **/*.string - - false - - - src/main/resources - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.1 - - 1.8 - 1.8 - - - - org.apache.maven.plugins - maven-javadoc-plugin - 3.0.0 - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/csv/CsvUtil.java b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/csv/CsvUtil.java deleted file mode 100644 index bb1ab15085..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/csv/CsvUtil.java +++ /dev/null @@ -1,279 +0,0 @@ -package com.sanri.csv; - -import com.sanri.excel.poi.ColumnConfig; -import com.sanri.excel.poi.ColumnConfigUtil; -import com.sanri.excel.poi.annotation.ExcelExport; -import com.sanri.excel.poi.annotation.ExcelImport; -import org.apache.commons.csv.CSVFormat; -import org.apache.commons.csv.CSVParser; -import org.apache.commons.csv.CSVPrinter; -import org.apache.commons.csv.CSVRecord; -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.ObjectUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.math.NumberUtils; -import org.apache.commons.lang3.time.DateFormatUtils; -import org.apache.commons.lang3.time.DateUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.beans.IntrospectionException; -import java.beans.PropertyDescriptor; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.nio.charset.Charset; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.Map; - -/** - * csv 工具类 - * @param - */ -public class CsvUtil { - //CSV文件分隔符 - private static final String NEW_LINE_SEPARATOR="\n"; - //初始化csvformat - private static final CSVFormat CSV_FORMAT = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR); - - private static Logger logger = LoggerFactory.getLogger(CsvUtil.class); - - /** - * 导出数据到文件; 支持 list 导出 - * 需要 Bean 有 ExcelExport 注解 列有 ExcelColumn 注解 - * 只需要列有 中文注解信息和顺序信息即可 - * @param filePath - * @param data - * @param charset 建议使用 gbk 编码,用 excel 打开默认是 gbk 编码; 用 utf-8 编码用于程序解析 - */ - public static File export(String filePath, List data, Charset charset) throws IOException { - if(data == null || data.isEmpty()){ - return null; - } - - T firstData = data.get(0); - Class dataTypeClass = firstData.getClass(); - ExcelExport excelExport = dataTypeClass.getAnnotation(ExcelExport.class); - if(excelExport == null ){ - throw new IllegalArgumentException("导出类 "+dataTypeClass.getName()+" 需要配置 "+ExcelExport.class.getName()+" 注解才可以导出"); - } - - CSVPrinter csvPrinter = null; - File csvFile = null; - try { - List columnConfigs = ColumnConfigUtil.parseColumnConfig(dataTypeClass, false); - if(columnConfigs.isEmpty()){ - throw new IllegalArgumentException(dataTypeClass.getName()+" 请配置需要导出的列"); - } - - //对属性进行排序 - Collections.sort(columnConfigs); - - //得得数据列的头部 - String [] heads = new String[columnConfigs.size()]; - for (int i=0;i propertyMap = ColumnConfigUtil.getPropertyMap(dataTypeClass); - //遍历获取数据行 - List records = new ArrayList(); - for (int j=0 ;j dataType = columnConfig.getDataType(); - if(dataType == Date.class){ - Date propertyDate = (Date) propertyValue; - String pattern = columnConfig.getPattern(); - if(StringUtils.isNotEmpty(pattern)){ - try{ - values[i] = DateFormatUtils.format(propertyDate,pattern); - }catch (Exception e){ - logger.error("第 "+(j + 1)+" 行日期格式化出错,列为:"+columnConfig.getPropertyName()); - } - }else{ - //格式化为 long 型值 - values[i] = propertyDate.getTime()+""; - } - - }else{ - values [i] = ObjectUtils.toString(propertyValue); - } - } - } - } - - - csvFile = checkFilePath(filePath); - - OutputStreamWriter fileWriter = new OutputStreamWriter(new FileOutputStream(csvFile),charset); - csvPrinter = new CSVPrinter(fileWriter, CSV_FORMAT); - - //写入头部 - csvPrinter.printRecord(heads); - //循环写入数据 - for (String[] record : records) { - csvPrinter.printRecord(record); - } - - } finally { - IOUtils.closeQuietly(csvPrinter); - } - - return csvFile; - } - - - /** - * 导出 csv 文件生成 List 需要要 ExcelImport 标志,需要设置起始行以忽略头 - * @param in - * @param clazz - * @param - * @return - */ - public static List importData(InputStream in, Class clazz,Charset charset) throws IOException { - ExcelImport excelImport = clazz.getAnnotation(ExcelImport.class); - if(excelImport == null){ - throw new IllegalArgumentException("导出类 "+clazz.getName()+" 需要配置 "+ExcelImport.class.getName()+" 注解才可以导入"); - } - int startRow = excelImport.startRow(); - - CSVParser csvParser = null; - try { - List columnConfigs = ColumnConfigUtil.parseColumnConfig(clazz, true); - String [] headers = new String[columnConfigs.size()]; - - //设置头部不读 - for (int i =0;i records = csvParser.getRecords(); - - List data = new ArrayList(); - //数据注入 - try { - Map propertyMap = ColumnConfigUtil.getPropertyMap(clazz); - - if(records != null && !records.isEmpty()){ - for (int i=startRow;i dataType = columnConfig.getDataType(); - if(dataType == Date.class){ - Date dateValue = null; - String pattern = columnConfig.getPattern(); - if(StringUtils.isNotEmpty(pattern)){ - try{ - dateValue = DateUtils.parseDate(value,new String[]{pattern}); - }catch (ParseException e){ - logger.error("第 行日期解析失败,当前日期格式为 "+pattern); - } - }else{ - long timeValue = NumberUtils.toLong(value); - dateValue = new Date(timeValue); - } - - if(dateValue != null){ - ColumnConfigUtil.setPropertyValue(propertyDescriptor,item,dateValue); - } - }else if(dataType == String.class){ - ColumnConfigUtil.setPropertyValue(propertyDescriptor,item,value); - }else if(dataType == Integer.class || dataType == int.class){ - ColumnConfigUtil.setPropertyValue(propertyDescriptor,item,NumberUtils.toInt(value)); - }else if(dataType == Long.class || dataType == long.class){ - ColumnConfigUtil.setPropertyValue(propertyDescriptor,item,NumberUtils.toLong(value)); - }else if(dataType == Float.class || dataType == float.class){ - ColumnConfigUtil.setPropertyValue(propertyDescriptor,item,NumberUtils.toFloat(value)); - }else if(dataType == Double.class || dataType == double.class){ - ColumnConfigUtil.setPropertyValue(propertyDescriptor,item,NumberUtils.toDouble(value)); - }else{ - logger.error("当前列数据类型"+dataType.getName()+"不支持自动注入,只支持[int,float,long,double]中的一种,在:"+columnConfig.getChinese()); - } - } - } - } - } catch (InstantiationException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - return data; - } finally { - if(csvParser != null){ - csvParser.close(); - } - IOUtils.closeQuietly(in); - } - } - - /** - * 检查文件路径 ,并创建父路径 - * @param filePath - * @return - */ - private static File checkFilePath(String filePath) { - File csvFile = new File(filePath); - if(csvFile.exists()){ - String extension = FilenameUtils.getExtension(filePath); - // 如果文件存在,则创建一个指定时间戳的文件 - return new File(filePath + "-"+System.currentTimeMillis()+"."+extension); - - } - - File parentFile = csvFile.getParentFile(); - if(!parentFile.exists()){ - parentFile.mkdirs(); - } - return csvFile; - } -} diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/ExcelException.java b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/ExcelException.java deleted file mode 100644 index e27c06025f..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/ExcelException.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.sanri.excel; - -/** - * Excel 异常信息 - */ -public class ExcelException extends RuntimeException { - public ExcelException(String message) { - super(message); - } - - public ExcelException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/ColumnConfig.java b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/ColumnConfig.java deleted file mode 100644 index e720669fb2..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/ColumnConfig.java +++ /dev/null @@ -1,208 +0,0 @@ -package com.sanri.excel.poi; - -import com.sanri.excel.poi.converter.ExcelConverter; -import com.sanri.excel.poi.enums.CellType; -import org.apache.commons.lang3.StringUtils; - -import java.lang.reflect.Method; - -/** - * - * 作者:sanri
- * 时间:2017-8-12下午2:47:48
- * 功能:列配置,用于排序
- */ -public class ColumnConfig implements Comparable{ - private boolean hidden; - private boolean chineseWidth; - private boolean trim; - - private String pattern; - private String chinese; - private int width; - private int charWidth; - private int pxWidth; - private int order; - private int precision; - - //属性名,必须不为空 - private String propertyName; - private Method readMethod; - private Method writeMethod; - private Class dataType; - private CellType cellType; - private ExcelConverter excelConverter; - - public ColumnConfig(String propertyName, Method readMethod, Method writeMethod) { - super(); - this.propertyName = propertyName; - this.readMethod = readMethod; - this.writeMethod = writeMethod; - } - - /** - * - * 作者:sanri
- * 时间:2017-8-12下午2:56:02
- * 功能:配置所有的配置,如果传入值为非默认值,则配置
- * @param chinese - * @param width - * @param index - * @param hidden - * @param pattern - */ - public void config(String chinese,int width,int charWidth,int pxWidth,int index,boolean hidden,String pattern,boolean chineseWidth,boolean trim,CellType cellType,int precision){ - if(StringUtils.isNotBlank(chinese)){ - this.chinese = chinese; - } - this.width = width; - this.charWidth = charWidth; - this.pxWidth = pxWidth; - if(index != -1){ - this.order = index; - } - this.hidden = hidden; - if(StringUtils.isNotBlank(pattern)){ - this.pattern = pattern; - } - this.precision = precision; - this.chineseWidth = chineseWidth; - this.cellType = cellType; - this.trim = trim; - } - - public boolean isHidden() { - return hidden; - } - - public void setHidden(boolean hidden) { - this.hidden = hidden; - } - - public String getPattern() { - return pattern; - } - - public void setPattern(String pattern) { - this.pattern = pattern; - } - - public String getChinese() { - return chinese; - } - - public void setChinese(String chinese) { - this.chinese = chinese; - } - - public int getWidth() { - return width; - } - - public void setWidth(int width) { - this.width = width; - } - - public int getOrder() { - return order; - } - - public void setOrder(int order) { - this.order = order; - } - - public String getPropertyName() { - return propertyName; - } - - public void setPropertyName(String propertyName) { - this.propertyName = propertyName; - } - - public Method getReadMethod() { - return readMethod; - } - - public void setReadMethod(Method readMethod) { - this.readMethod = readMethod; - } - - public Method getWriteMethod() { - return writeMethod; - } - - public void setWriteMethod(Method writeMethod) { - this.writeMethod = writeMethod; - } - - public int compareTo(ColumnConfig o) { - if(this.order != -1 && o.order != -1){ - return this.order - o.order; - } - return this.propertyName.compareTo(o.propertyName); - } - - public Class getDataType() { - return dataType; - } - - public void setDataType(Class dataType) { - this.dataType = dataType; - } - - public boolean isChineseWidth() { - return chineseWidth; - } - - public void setChineseWidth(boolean chineseWidth) { - this.chineseWidth = chineseWidth; - } - - public int getCharWidth() { - return charWidth; - } - - public void setCharWidth(int charWidth) { - this.charWidth = charWidth; - } - - public int getPxWidth() { - return pxWidth; - } - - public void setPxWidth(int pxWidth) { - this.pxWidth = pxWidth; - } - - public CellType getCellType() { - return cellType; - } - - public void setCellType(CellType cellType) { - this.cellType = cellType; - } - - public boolean isTrim() { - return trim; - } - - public void setTrim(boolean trim) { - this.trim = trim; - } - - public int getPrecision() { - return precision; - } - - public void setPrecision(int precision) { - this.precision = precision; - } - - public ExcelConverter getExcelConverter() { - return excelConverter; - } - - public void setExcelConverter(ExcelConverter excelConverter) { - this.excelConverter = excelConverter; - } -} diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/ColumnConfigUtil.java b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/ColumnConfigUtil.java deleted file mode 100644 index 12907f2a1f..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/ColumnConfigUtil.java +++ /dev/null @@ -1,199 +0,0 @@ -package com.sanri.excel.poi; - -import com.sanri.excel.ExcelException; -import com.sanri.excel.poi.ColumnConfig; -import com.sanri.excel.poi.annotation.ExcelColumn; -import com.sanri.excel.poi.converter.ExcelConverter; -import com.sanri.excel.poi.converter.NULLConverter; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.ClassUtils; -import org.apache.commons.lang3.time.DateFormatUtils; -import org.apache.commons.lang3.time.DateUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.beans.BeanInfo; -import java.beans.IntrospectionException; -import java.beans.Introspector; -import java.beans.PropertyDescriptor; -import java.lang.reflect.*; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class ColumnConfigUtil { - private static Logger logger = LoggerFactory.getLogger(ColumnConfigUtil.class); - - /** - * 功能:获取类的列配置
- * 创建时间:2017-8-12下午10:08:21
- * 作者:sanri
- * @param clazz - * @param readWrite 解析读时为真,解析写时为假 - * @return - */ - public static List parseColumnConfig(Class clazz, boolean readWrite) { - List columnConfigs = new ArrayList(); - - try{ - //获取列配置,所有需要导出的类,最后应该都是从 Object 继承 - BeanInfo beanInfo = Introspector.getBeanInfo(clazz, Object.class); - PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); - if(propertyDescriptors == null || propertyDescriptors.length == 0 ){ - //必须要有属性配置 - throw new ExcelException("bean 和其父类, 必须至少包含一个属性"); - } - - //获取 bean 上所有的列配置 - for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { - Method readMethod = propertyDescriptor.getReadMethod(); - Method writeMethod = propertyDescriptor.getWriteMethod(); - String propertyName = propertyDescriptor.getName(); - Class propertyType = propertyDescriptor.getPropertyType(); - if(!typeSupport(propertyType)){ - throw new ExcelException("不支持的类型:"+propertyType); - } - //只导出属性可读的属性,没有 get 方法的属性不进行导出 - if((readMethod != null && readWrite) || (writeMethod != null && !readWrite)){ - //先从属性列上获取配置,如果属性列上没有,就从读方法上获取,并覆盖属性列上的配置 - ColumnConfig columnConfig = new ColumnConfig(propertyName, readMethod, writeMethod); - columnConfig.setDataType(propertyType); - Field propertyField = null; - Class currentClass = clazz; - while(currentClass != Object.class && propertyField == null){ - try{ - propertyField = currentClass.getDeclaredField(propertyName); - }catch(NoSuchFieldException e){ - currentClass = currentClass.getSuperclass(); - } - } - if(propertyField == null){ - throw new NoSuchFieldException("未找到属性:"+propertyName); - } - ExcelColumn excelColumn = propertyField.getAnnotation(ExcelColumn.class); - if(excelColumn != null) { - columnConfig.config(excelColumn.value(), excelColumn.width(), excelColumn.charWidth(), excelColumn.pxWidth(), excelColumn.order(), excelColumn.hidden(), excelColumn.pattern(), excelColumn.chineseWidth(), excelColumn.trim(), excelColumn.cellType(), excelColumn.precision()); - Class converter = excelColumn.converter(); - if(converter != NULLConverter.class) { - //检测原类型是否匹配 - ParameterizedType genericInterface = (ParameterizedType) converter.getGenericInterfaces()[0]; - Type sourceType = genericInterface.getActualTypeArguments()[0]; - if(sourceType != propertyType && sourceType != ClassUtils.primitiveToWrapper(propertyType)){ - throw new ExcelException("转换器["+converter+"]不能匹配目标类型["+propertyType+"]在列["+excelColumn.value()+"]"); - } - - try { - ExcelConverter excelConverter = converter.newInstance(); - columnConfig.setExcelConverter(excelConverter); - } catch (Exception e) { - logger.error("初始化转化器出错,当前列:" + excelColumn.value()); - } - } - } - //使用方法上的配置,覆盖属性上的配置 - ExcelColumn methodExcelColumn = null; - if(readWrite){ - //从读方法上覆盖配置 - methodExcelColumn = readMethod.getAnnotation(ExcelColumn.class); - }else{ - //从写方法上覆盖配置 - methodExcelColumn = writeMethod.getAnnotation(ExcelColumn.class); - } - if(methodExcelColumn != null){ - columnConfig.config(methodExcelColumn.value(), methodExcelColumn.width(),excelColumn.charWidth(),excelColumn.pxWidth(), methodExcelColumn.order(), methodExcelColumn.hidden(), methodExcelColumn.pattern(),excelColumn.chineseWidth(),excelColumn.trim(),excelColumn.cellType(),excelColumn.precision()); - } - //add by sanri at 2017/08/30 只有配置了 ExcelColumn 的才可进行导入导出 - if(excelColumn != null || methodExcelColumn != null){ - columnConfigs.add(columnConfig); - } - } - } - //对导出的属性配置进行排序 - Collections.sort(columnConfigs); - }catch (ExcelException e){throw e;} - catch (Exception e){ - throw new ExcelException("解析列配置出错:"+e.getMessage(),e); - } - return columnConfigs; - } - - /** - * - * 作者:sanri
- * 时间:2017-8-12下午2:29:59
- * 功能: 是否支持给定的类型
- * @param clazz - * @return - */ - private static boolean typeSupport(Class clazz){ - return clazz.isPrimitive() || clazz == String.class - || clazz == Integer.class || clazz == Short.class - || clazz == Long.class || clazz == Float.class - || clazz == Double.class || clazz == Character.class - || clazz == Boolean.class || clazz == Byte.class - || clazz == Date.class; - } - - /** - * 获取属性描述器映射 - * @param clazz - * @return - */ - public static Map getPropertyMap(Class clazz){ - Map propertyDescriptorMap = new HashMap(); - try { - BeanInfo beanInfo = Introspector.getBeanInfo(clazz, Object.class); - PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); - if(ArrayUtils.isNotEmpty(propertyDescriptors)){ - for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { - String name = propertyDescriptor.getName(); - propertyDescriptorMap.put(name,propertyDescriptor); - } - } - } catch (IntrospectionException e) { - e.printStackTrace(); - } - - return propertyDescriptorMap; - } - - /** - * 获取属性值 - * @param propertyDescriptor - * @param object - * @return - */ - public static Object getPropertyValue(PropertyDescriptor propertyDescriptor,Object object){ - Method readMethod = propertyDescriptor.getReadMethod(); - try { - Object invoke = readMethod.invoke(object); - return invoke; - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } - return null; - } - - /** - * 设置属性值 - * @param propertyDescriptor - * @param object - * @param value - */ - public static void setPropertyValue(PropertyDescriptor propertyDescriptor,Object object,Object value){ - Method writeMethod = propertyDescriptor.getWriteMethod(); - try { - writeMethod.invoke(object,value); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } - } - -} diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/ExcelExportWriter.java b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/ExcelExportWriter.java deleted file mode 100644 index ab040aef61..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/ExcelExportWriter.java +++ /dev/null @@ -1,571 +0,0 @@ -package com.sanri.excel.poi; - -import com.sanri.excel.ExcelException; -import com.sanri.excel.poi.annotation.ExcelExport; -import com.sanri.excel.poi.converter.DefaultBooleanStringConverter; -import com.sanri.excel.poi.converter.ExcelConverter; -import com.sanri.excel.poi.enums.CellType; -import com.sanri.excel.poi.enums.ExcelVersion; -import org.apache.commons.lang3.ClassUtils; -import org.apache.commons.lang3.ObjectUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.math.NumberUtils; -import org.apache.commons.lang3.time.DateFormatUtils; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.*; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.util.*; - -/** - * 导出 Excel - */ -public class ExcelExportWriter { - public static final float BASE_WIDTH_1_PX = 35.7f; - public static final float BASE_HEIGHT_1_PX = 15.625f; - public static final float BASE_CHINESE = 2 * 256; - - private Logger logger = LoggerFactory.getLogger(ExcelExportWriter.class); - - private Workbook workbook = null; - private ExcelExport excelExport; - private Class clazz; - - public ExcelExportWriter(Class clazz) { - this.clazz = clazz; - ExcelExport excelExport = clazz.getAnnotation(ExcelExport.class); - if (excelExport == null) { - throw new ExcelException("导出类[" + clazz.getName() + "]需要注解 @ExcelExport"); - } - this.excelExport = excelExport; - - ExcelVersion excelVersion = excelExport.version(); - switch (excelVersion) { - case EXCEL2003: - workbook = new HSSFWorkbook(); - case EXCEL2007: - boolean fastModel = excelExport.fastModel(); - if (fastModel) { - int rowAccessWindowSize = excelExport.rowAccessWindowSize(); - workbook = new SXSSFWorkbook(rowAccessWindowSize); - } else { - workbook = new XSSFWorkbook(); - } - } - } - - /** - * @param excelVersion - * @param tips 提示文本,调用导出为空时可使用此方法返回一个带提示文本的工作薄 - * @作者: sanri - * @时间: 2017/8/12 21:32 - * @功能: 创建空的工作薄 - */ - public static Workbook createEmptyWorkbook(String tips,ExcelVersion excelVersion) { - Workbook workbook = null; - if(excelVersion == ExcelVersion.EXCEL2003){ - workbook = new HSSFWorkbook(); - }else { - workbook = new XSSFWorkbook(); - } - if (StringUtils.isNotBlank(tips)) { - Sheet sheet = workbook.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - cell.setCellValue(tips); - //设置列宽为 tips中文列宽 - sheet.setColumnWidth(0, (int) (tips.length() * BASE_CHINESE)); - } - return workbook; - } - - /** - * 功能:创建单元格样式
- * 创建时间:2017-8-13上午7:46:59
- * 作者:sanri
- * - * @param workbook - * @param font 字体设置 - * @param background 背景色 - * @param center 是否居中 - * @param wrapText 是否自动换行 - * @return
- */ - public CellStyle createCellStyle(Font font, IndexedColors background, boolean center, boolean wrapText) { - CellStyle createCellStyle = workbook.createCellStyle(); - if (font != null) { - createCellStyle.setFont(font); - } - createCellStyle.setFillForegroundColor(background.getIndex()); - createCellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND); - createCellStyle.setBorderBottom(CellStyle.BORDER_THIN); - createCellStyle.setBorderLeft(CellStyle.BORDER_THIN); - createCellStyle.setBorderRight(CellStyle.BORDER_THIN); - createCellStyle.setBorderTop(CellStyle.BORDER_THIN); - if (center) {//水平居中,垂直居中 - createCellStyle.setAlignment(CellStyle.ALIGN_CENTER); - createCellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER); - } - createCellStyle.setWrapText(wrapText); - return createCellStyle; - } - - /** - * 功能:创建字体
- * 创建时间:2017-8-13上午7:37:34
- * 作者:sanri
- * - * @param workbook - * @param family 字体种类 - * @param color 字体颜色 - * @param size 字体大小 - * @param b 是否加粗 - * @return
- */ - public Font createCellFont(String family, IndexedColors color, short size, boolean b) { - Font createFont = workbook.createFont(); - createFont.setCharSet(Font.DEFAULT_CHARSET); - createFont.setColor(color.getIndex()); - createFont.setFontName(family); -// createFont.setFontHeight(size); - //modify by sanri at 2017/09/19 字体使用点数 - createFont.setFontHeightInPoints(size); - if (b) { - createFont.setBoldweight((short) 700); - } - return createFont; - } - - /** - * 作者:sanri
- * 时间:2017-9-19下午4:59:04
- * 功能:创建字体
- * - * @param family 字体种类 - * @param color 字体颜色 - * @param size 字体大小 - * @param b 是否加粗 - * @param i 是否斜体 - * @param u 是否加下划线 - * @return - */ - public Font createCellFont(String family, IndexedColors color, short size, boolean b, boolean i, boolean u) { - Font createFont = createCellFont(family, color, size, b); - createFont.setItalic(i); - if (u) { - createFont.setUnderline((byte) 1); - } - return createFont; - } - - /** - * 作者:sanri
- * 时间:2017-8-12下午1:53:58
- * 功能: 导出 excel
- * - * @param title 标题 - * @param data 数据列表 - * @param titleStyle 标题样式 - * @param headStyle 头部样式 - * @param bodyStyle 主体数据样式 - * @return - */ - public Workbook export(String title, List data, CellStyle titleStyle, CellStyle headStyle, CellStyle bodyStyle) { - if (data == null || data.size() == 0) { - //无数据直接反回空 - return null; - } - //解析列配置 - List columnConfigs = ColumnConfigUtil.parseColumnConfig(clazz, true); - - ExcelVersion version = excelExport.version(); - int sheetMaxRow = -1; - if (excelExport.sheetMaxRow() == -1 && version == ExcelVersion.EXCEL2003) { - //设置配置为最大行数 - sheetMaxRow = 60000; - } - try { - //计算数据是否超量,是否需要创建多个 sheet - List sheets = new ArrayList(); - if (sheetMaxRow == -1 || data.size() <= sheetMaxRow) { - //只会创建一个 sheet - Sheet createSheet = workbook.createSheet("全部数据"); - sheets.add(createSheet); - } else { - int sheetCount = (data.size() - 1) / sheetMaxRow + 1; - for (int i = 0; i < sheetCount; i++) { - Sheet createSheet = workbook.createSheet("部分数据_part" + i); - sheets.add(createSheet); - } - } - //正式添加数据 - if (sheets.size() == 1) { //添加全部数据到一张 sheet 页中,如果只有一张 sheet 页的话 - Sheet sheet = sheets.get(0); - int startRow = createSheetTitle(title, titleStyle, columnConfigs, sheet); - insertDataToSheet(sheet, data, columnConfigs, startRow, headStyle, bodyStyle); - } else { - for (int i = 0; i < sheets.size(); i++) { - Sheet sheet = sheets.get(i); - //如果有标题,添加标题 - int startRow = createSheetTitle(title, titleStyle, columnConfigs, sheet); - //复制截断的数据,到数据表 sheet 页 - int startDataIndex = i * sheetMaxRow; - int endDataIndex = (i + 1) * sheetMaxRow; - if (endDataIndex > data.size()) { - endDataIndex = data.size(); - } - List partData = new ArrayList(); - for (int j = startDataIndex; j < endDataIndex; j++) { - partData.add(data.get(j)); - } - insertDataToSheet(sheet, partData, columnConfigs, startRow, headStyle, bodyStyle); - } - } - } catch (Exception e){ - throw new ExcelException("注入数据出错 insertDataToSheet "+e.getMessage(),e); - } - return workbook; - } - - /** - * 功能:下面都是各种需要的导出方法重载
- * 创建时间:2017-8-13上午8:57:04
- * 作者:sanri
- */ - public Workbook export(List data, CellStyle headStyle, CellStyle bodyStyle) { - return export("", data, null, headStyle, bodyStyle); - } - - public Workbook export(List data) { - return export(data, null, null); - } - - public Workbook export(String title, List data) { - return export(title, data, null); - } - - public Workbook export(String title, List data, CellStyle titleStyle) { - return export(title, data, titleStyle, null, null); - } - - /** - * 作者:sanri
- * 时间:2017-9-1下午2:31:33
- * 功能:写到输入流
- * 此方法只能用于导出
- * - * @param outputStream - * @throws IOException - */ - public void writeTo(OutputStream outputStream) throws IOException { - workbook.write(outputStream); - } - - /** - * 作者:sanri
- * 时间:2017-9-1下午2:27:29
- * 功能:将当前的 workbook 转为输入流,此方法只能用于导出
- * - * @return - * @throws IOException - */ - public InputStream toInputStream() throws IOException { - return toInputStream(workbook); - } - - /** - * 作者:sanri
- * 时间:2017-9-1下午2:30:33
- * 功能:将任何一个 workbook 转为输入流
- * - * @param workbook - * @return - * @throws IOException - */ - public static InputStream toInputStream(Workbook workbook) throws IOException { - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - try { - workbook.write(byteArrayOutputStream); - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); - return byteArrayInputStream; - } finally { - if (byteArrayOutputStream != null) { - byteArrayOutputStream.close(); - } - } - } - - /** - * 作者:sanri
- * 时间:2017-9-19下午5:06:41
- * 功能:以默认样式导出
- * - * @param title - * @param data - * @return - */ - public Workbook exportDefaultStyle(String title, List data) { -// createCellFont("宋体", IndexedColors.BLACK, 15, b, i, u) - CellStyle titleStyle = createCellStyle(null, IndexedColors.WHITE, true, false); - CellStyle headStyle = createCellStyle(null, IndexedColors.LIGHT_GREEN, true, false); - CellStyle bodyStyle = createCellStyle(null, IndexedColors.LIGHT_YELLOW, true, false); - return export(title, data, titleStyle, headStyle, bodyStyle); - } - - public Workbook exportDefaultStyle(List data) { - return exportDefaultStyle("", data); - } - - /** - * 作者: sanri - * 时间 : 2017/08/12 - * 功能 : 创建 sheet 标题,如果存在的话 - * - * @param title - * @param titleStyle - * @param excelExport - * @param columnConfigs - * @param sheet - * @return 返回当前 sheet 起始行 - */ - private int createSheetTitle(String title, CellStyle titleStyle, List columnConfigs, Sheet sheet) { - int startRow = 0; - if (StringUtils.isNotBlank(title)) { - Row titleRow = sheet.createRow(startRow++); - Cell titleCell = titleRow.createCell(0); - titleCell.setCellValue(title); - if (titleStyle != null) { - titleCell.setCellStyle(titleStyle); - } - //合并单元格 - sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, columnConfigs.size() - 1)); - short titleRowHeight = excelExport.titleRowHeight(); - titleRowHeight = (short) (titleRowHeight * BASE_HEIGHT_1_PX); - titleRow.setHeight(titleRowHeight); - } - return startRow; - } - - /** - * 作者:sanri
- * 时间:2017-8-12下午6:35:29
- * 功能:添加数据到 sheet 页
- * - * @param - * @throws InvocationTargetException - * @throws IllegalArgumentException - * @throws IllegalAccessException - */ - private void insertDataToSheet(Sheet sheet, List partData, List columnConfigs, int startRow, CellStyle headStyle, CellStyle bodyStyle) throws Exception { - Row headRow = sheet.createRow(startRow++); - headRow.setHeight((short) (excelExport.headRowHeight() * BASE_HEIGHT_1_PX)); - //创建标题列 - for (int i = 0; i < columnConfigs.size(); i++) { - ColumnConfig columnConfig = columnConfigs.get(i); - String chinese = columnConfig.getChinese(); - Cell headCell = headRow.createCell(i); - headCell.setCellValue(chinese); - if (headStyle != null) { - headCell.setCellStyle(headStyle); - } - } - - //创建数据列 - for (int i = 0; i < partData.size(); i++) { - Row bodyRow = sheet.createRow(startRow++); - bodyRow.setHeight((short) (excelExport.bodyRowHeight() * BASE_HEIGHT_1_PX)); - T dataItem = partData.get(i); - for (int j = 0; j < columnConfigs.size(); j++) { - ColumnConfig columnConfig = columnConfigs.get(j); - Method readMethod = columnConfig.getReadMethod(); - Cell bodyCell = bodyRow.createCell(j); - if (bodyStyle != null) { - bodyCell.setCellStyle(bodyStyle); - } - //add by sanri at 2018/11/05 设置 bodyCell 单元格格式 - CellType cellType = columnConfig.getCellType(); - bodyCell.setCellType(cellType.getValue()); - - Object cellData = readMethod.invoke(dataItem); - ExcelConverter excelConverter = columnConfig.getExcelConverter(); - if(excelConverter != null){ //如果存在转换器,则转换数据 - cellData = excelConverter.convert(cellData); - } - Class dataType = columnConfig.getDataType(); - - //解决数据为 null 的情况,设置对应的空值 - if (cellData == null) { - switch (cellType) { - case CELL_TYPE_STRING: - bodyCell.setCellType(Cell.CELL_TYPE_STRING); - bodyCell.setCellValue(""); - break; - case CELL_TYPE_BOOLEAN: - bodyCell.setCellType(Cell.CELL_TYPE_BOOLEAN); - bodyCell.setCellValue(false); - break; - case CELL_TYPE_NUMERIC: - bodyCell.setCellType(Cell.CELL_TYPE_NUMERIC); - bodyCell.setCellValue(0); - break; - case CELL_TYPE_BLANK: - } - continue; - } - - //后面的数据都是在有值的情况下 - //如果数据类型是 double 或 Double 需要设置精度值 - if (dataType == double.class || dataType == Double.class || dataType == float.class || dataType == Float.class) { - String cellDataString = ObjectUtils.toString(cellData); - int precision = columnConfig.getPrecision(); - if (precision != -1) { - BigDecimal bigDecimal = new BigDecimal(cellDataString); - if(dataType == double.class || dataType == Double.class) { - //TODO bigDecimal 对于超大数无法设置小数,比如 RandomUtils.nextDouble() 方法生成的值 - cellData = bigDecimal.setScale(precision, RoundingMode.HALF_EVEN).doubleValue(); - }else if(dataType == float.class || dataType == Float.class){ - cellData = bigDecimal.setScale(precision, RoundingMode.HALF_EVEN).floatValue(); - } - } - } - - switch (cellType) { - case CELL_TYPE_STRING: - bodyCell.setCellType(Cell.CELL_TYPE_STRING); - - if (dataType == Date.class) { - //获取日期对象数据 - Date cellDataReal = null; - if (cellData != null) { - cellDataReal = (Date) cellData; - } - - //如果是日期类型,则调用转换规则进行转换 - String pattern = columnConfig.getPattern(); - if (StringUtils.isBlank(pattern)) { - //如果是空格式,直接设置日期数据 - bodyCell.setCellValue(cellDataReal); - } else { - bodyCell.setCellValue(DateFormatUtils.format(cellDataReal, pattern)); - } - } else { - bodyCell.setCellValue(ObjectUtils.toString(cellData)); - } - break; - case CELL_TYPE_NUMERIC: - bodyCell.setCellType(Cell.CELL_TYPE_NUMERIC); - - String cellDataString = ObjectUtils.toString(cellData, "0"); - boolean primitiveOrWrapper = ClassUtils.isPrimitiveOrWrapper(dataType); - if(primitiveOrWrapper){ - if(dataType == int.class || dataType == Integer.class){ - bodyCell.setCellValue(NumberUtils.toInt(cellDataString)); - }else if(dataType == long.class || dataType == Long.class){ - bodyCell.setCellValue(NumberUtils.toLong(cellDataString)); - }else if(dataType == double.class || dataType == Double.class){ - bodyCell.setCellValue(NumberUtils.toDouble(cellDataString)); - }else if(dataType == float.class || dataType == Float.class){ - bodyCell.setCellValue(NumberUtils.toFloat(cellDataString)); - }else { - logger.warn("单元格类型设置 numeric ,但数据类型不支持; 列为:" + columnConfig.getPropertyName() + ",类型为:" + dataType + ",支持的类型有[int,long,double,float]"); - } - }else if(dataType == Date.class){ //如果日期需要设置进数值单元格,强转化为毫秒值 - Date cellDataReal = (Date) cellData; - bodyCell.setCellValue(cellDataReal.getTime()); - }else { - logger.warn("单元格类型设置 numeric ,但数据类型不是 numeric ; 列为:" + columnConfig.getPropertyName() + ",类型为:" + dataType); - } - break; - case CELL_TYPE_BOOLEAN: - if (dataType == Boolean.TYPE || dataType == Boolean.class) { - bodyCell.setCellValue((Boolean) cellData); - } else { - logger.warn("单元格类型设置 boolean ,但数据类型不是 Boolean ; 列为:" + columnConfig.getPropertyName()+",类型为:"+dataType); - } - break; - case CELL_TYPE_BLANK: - //空值不设置数据 - break; - } - - } - } - - //设置列宽 - boolean autoWidth = excelExport.autoWidth(); - if (autoWidth) { - //自动列宽后使用两倍自动列宽 - for (int i = 0; i < columnConfigs.size(); i++) { - sheet.autoSizeColumn(i); - ColumnConfig columnConfig = columnConfigs.get(i); - - int width = sheet.getColumnWidth(i); - String titleChinese = columnConfig.getChinese(); - float titleWidth = titleChinese.length() * BASE_CHINESE; - if (width < titleWidth) { - width = (int) titleWidth; - sheet.setColumnWidth(i, width); - } - - if (columnConfig.isChineseWidth()) { - // 宽度设置为原来两倍,并且加一个中文字宽度 - int width_2 = (int) (width * 2 + 1 * BASE_CHINESE); - //add by sanri at 2017/12/02 解决最大宽度超出限制问题 - if (width_2 > 65280) { - width_2 = 65280; - } - sheet.setColumnWidth(i, width_2); - } - } - } else { - //宽度配置策略 如果没有配置任何宽度,则取标题中文字宽度,如果有配置,则使用配置 - for (int i = 0; i < columnConfigs.size(); i++) { - ColumnConfig columnConfig = columnConfigs.get(i); - //begin modify by sanri at 2017/09/19 增加列宽配置策略 - int width = columnConfig.getWidth(); - int charWidth = columnConfig.getCharWidth(); - int pxWidth = columnConfig.getPxWidth(); - int finalWidth = -1; - if (width == -1 && charWidth == -1 && pxWidth == -1) { - //没有配置任何宽度,使用标题中文字宽度 - finalWidth = (int) (columnConfig.getChinese().length() * BASE_CHINESE); - } else { - if (width != -1) { - finalWidth = width; - } else if (charWidth != -1) { - finalWidth = (int) (charWidth * BASE_CHINESE); - } else { - finalWidth = (int) (pxWidth * BASE_WIDTH_1_PX); - } - } -// if(width < columnConfig.getChinese().length()){ -// //如果默认宽度是小于了中文字的宽度,则取中文字的宽度 -// width = (int) (columnConfig.getChinese().length() * BASE_CHINESE); -// } - //add by sanri at 2017/12/02 解决最大宽度超出限制问题 - if (finalWidth > 65280) { - finalWidth = 65280; - } - sheet.setColumnWidth(i, finalWidth); - //end modify by sanri at 2017/09/19 增加列宽配置策略 - } - } - - //隐藏列配置 - for (int i = 0; i < columnConfigs.size(); i++) { - ColumnConfig columnConfig = columnConfigs.get(i); - boolean hidden = columnConfig.isHidden(); - sheet.setColumnHidden(i, hidden); - } - } - -} diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/ExcelImportUtil.java b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/ExcelImportUtil.java deleted file mode 100644 index 75204a9710..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/ExcelImportUtil.java +++ /dev/null @@ -1,481 +0,0 @@ -package com.sanri.excel.poi; - -import com.sanri.excel.ExcelException; -import com.sanri.excel.poi.annotation.ExcelImport; -import com.sanri.excel.poi.handler.ErrorRowHandler; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.ClassUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.math.NumberUtils; -import org.apache.commons.lang3.time.DateFormatUtils; -import org.apache.commons.lang3.time.DateUtils; -import org.apache.commons.lang3.time.FastDateFormat; -import org.apache.poi.ss.usermodel.*; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.InputStream; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.text.DecimalFormat; -import java.util.*; - -/** - * 导入 Excel 工具类 - */ -public class ExcelImportUtil { - private static Logger logger = LoggerFactory.getLogger(ExcelImportUtil.class); - /** - * - * 作者:sanri
- * 时间:2017-11-15下午12:28:58
- * 功能:简单数据导入
- * @param in 输入流 - * @param clazz 导的数据是什么类型 - * @param whichCol 导哪一列数据 从 0 开始 - * @param startRow 从 0 开始 - * @return - * 注:只支持第一个 sheet 页 - */ - public static List importListData(InputStream in,Class clazz,int whichCol,int startRow){ - List data = new ArrayList(); - - Workbook workbook = getWorkbookFromInputStream(in); - Sheet sheet = workbook.getSheetAt(0); - int physicalNumberOfRows = sheet.getPhysicalNumberOfRows(); - - //起始行大于总行数,返回空数据 - if(startRow >= physicalNumberOfRows){ - return data; - } - - CreationHelper creationHelper = workbook.getCreationHelper(); - //开始处理每一行数据 - for(int i=startRow;i= physicalNumberOfCells){ - data.add(null); - continue; - } - Cell cell = row.getCell(whichCol); - //转换 cell 数据,并加入 - if(cell == null){ - continue; - } - T cellData = transferCellData(cell.getCellType(),cell,clazz,DateFormatUtils.ISO_DATE_FORMAT,decimalFormat,creationHelper); - data.add(cellData); - } - return data; - } - - /** - * - * 作者:sanri
- * 时间:2017-11-15下午12:31:59
- * 功能:导入 map 类型数据
- * @param in - * @param clazz - * @param keyCol 键列 从 0 开始 - * @param valueCol 值列 从 0 开始 - * @param startRow 起始行 从 0 开始 - * @return - */ - public static Map importMapData(InputStream in,Class clazz,int keyCol,int valueCol,int startRow){ - Map mapData = new HashMap(); - - Workbook workbook = getWorkbookFromInputStream(in); - Sheet sheet = workbook.getSheetAt(0); - int physicalNumberOfRows = sheet.getPhysicalNumberOfRows(); - - //起始行大于总行数,返回空数据 - if(startRow >= physicalNumberOfRows){ - return mapData; - } - - CreationHelper creationHelper = workbook.getCreationHelper(); - - //开始处理每一行数据 - for(int i=startRow;i= physicalNumberOfCells){ - throw new ExcelException("键列不能为空 [row:"+i+",col:"+keyCol+"]"); - } - - //获取键数据 - Cell keyCell = row.getCell(keyCol); - if(keyCell == null){ - continue; - } - String key = transferCellData(keyCell.getCellType(),keyCell, String.class, DateFormatUtils.ISO_DATE_FORMAT, decimalFormat,creationHelper); - - //获取值数据 - V value = null; - if(valueCol < physicalNumberOfCells){ - Cell valueCell = row.getCell(valueCol); - if(valueCell == null){ - continue; - } - value = transferCellData(valueCell.getCellType(),valueCell, clazz, DateFormatUtils.ISO_DATE_FORMAT, decimalFormat,creationHelper); - } - - mapData.put(key, value); - } - - return mapData; - } - - /** - * 从输入流导入 excel 数据,只支持一个 sheet 页 - * @param in 输入流 - * @param clazz 导入目标类 - * @param errorRowHandler 错误行处理器 {@link com.sanri.excel.poi.handler.CollectErrorRowHandler} - * @param - * @return - */ - public static List importData(InputStream in, Class clazz, ErrorRowHandler errorRowHandler){ - ExcelImport excelImport = clazz.getAnnotation(ExcelImport.class); - if(excelImport == null){ - throw new ExcelException("需要在目标类加注解 ExcelImport 才可实现导入"); - } - List columnConfigs = ColumnConfigUtil.parseColumnConfig(clazz,false); - - List data = new ArrayList(); - try{ - Workbook workbook = getWorkbookFromInputStream(in); - - //真正解析 excel 流,只解析第一个 sheet 页 - int startRow = excelImport.startRow(); - CreationHelper creationHelper = workbook.getCreationHelper(); - - Sheet sheet = workbook.getSheetAt(0); - int physicalNumberOfRows = sheet.getPhysicalNumberOfRows(); - for(int i = startRow;i - * 时间:2018-3-13下午3:18:12
- * 功能:判断当前行是否全为空,如果全为空,返回 true
- * @param row - * @return - */ - private static boolean isEmptyRow(Row row) { - if (row == null) { - return true; - } - short firstCellNum = row.getFirstCellNum(); - short lastCellNum = row.getLastCellNum(); - - for (int i = firstCellNum; i < lastCellNum; i++) { - Cell cell = row.getCell(i); - if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) { - return false; - } - } - return true; - } - - /** - * - * 作者:sanri
- * 时间:2017-12-2下午4:11:26
- * 功能:从输入流获取工作薄
- * @param in - * @return - */ - public static Workbook getWorkbookFromInputStream(InputStream in)throws ExcelException { -// Workbook workbook = null; -// if (!in.markSupported()) { -// in = new PushbackInputStream(in, 8); -// } -// try { -// if (POIFSFileSystem.hasPOIFSHeader(in)) { -// workbook = new HSSFWorkbook(in); -// } -// if (POIXMLDocument.hasOOXMLHeader(in)) { -// workbook = new XSSFWorkbook(OPCPackage.open(in)); -// } -// } catch (Exception e) { -// throw new ParseException("excel 流解析失败", e); -// } -// return workbook; - try { - return WorkbookFactory.create(in); - } catch (Exception e) { - throw new ExcelException("excel 流解析失败 ",e); - } - } - - /** - * - * 作者:sanri
- * 时间:2017-12-2下午4:21:40
- * 功能:将单元格数据转换成指定类型
- * @param cell - * @param clazz - * @param creationHelper CreationHelper creationHelper = workbook.getCreationHelper(); - * @return - */ - public static T transferCellData(int cellType,Cell cell,Class dataType,FastDateFormat dateFormat,DecimalFormat numberFormat,CreationHelper creationHelper ){ - if(cell == null){ - // 处理单元格为绝对空的问题 add by sanri at 2017/12/12 - return null; - } - switch (cellType) { - case Cell.CELL_TYPE_BOOLEAN: - boolean booleanCellValue = cell.getBooleanCellValue(); - if(dataType == Boolean.class || dataType == boolean.class){ - return dataType.cast(booleanCellValue); - } - logger.warn("boolean 单元格数据无法转换成类型:"+dataType+",在["+cell.getRowIndex()+"]行,["+cell.getColumnIndex()+"]列"); - return null; - case Cell.CELL_TYPE_BLANK: - //null 值无需写入 - return null; - case Cell.CELL_TYPE_FORMULA: - FormulaEvaluator formulaEvaluator = creationHelper.createFormulaEvaluator(); - CellValue cellValue = formulaEvaluator.evaluate(cell); - int newCellType = cellValue.getCellType(); - return transferCellData(newCellType, cell, dataType, dateFormat, numberFormat, creationHelper); - case Cell.CELL_TYPE_NUMERIC: - //add by sanri at 2017/09/08 判断是否为日期单元格,使用 excel 日期进行转换 - double doubleValue = cell.getNumericCellValue(); - //根据目标类型来判断需要设置的值 - if(dataType == Date.class){ - //目标类型为 Date - Date javaDate = DateUtil.getJavaDate(doubleValue); - return dataType.cast(javaDate); - } - - if(dataType == String.class){ - if( DateUtil.isCellDateFormatted(cell)){ - //如果单元格是 date 类型,则转为 date 字符串 - Date javaDate = DateUtil.getJavaDate(doubleValue); - return dataType.cast(dateFormat.format(javaDate)); - } - - String realValue = decimalFormat.format(doubleValue); - return dataType.cast(realValue); - } - - if(dataType== int.class || dataType== Integer.class){ - return dataType.cast(new Double(doubleValue).intValue()); - } - - if(dataType == Float.class || dataType == Float.class){ - return dataType.cast(new Double(doubleValue).floatValue()); - } - - if(dataType == Double.class || dataType == double.class){ - return dataType.cast(doubleValue); - } - - if(dataType == Long.class || dataType == long.class){ - return dataType.cast(new Double(doubleValue).longValue()); - } - logger.error("不支持的数字类型转换,只支持[int,float,long,double]中的一种,在:"+cell.getRowIndex()+" 行,"+cell.getColumnIndex()+" 列"); - break; - case Cell.CELL_TYPE_STRING: - String stringCellValue = cell.getStringCellValue(); - - if(ClassUtils.isPrimitiveOrWrapper(dataType)){ - Object realData = stringCell2RealTypeValue(dataType, stringCellValue); - if(realData != null){ - return dataType.cast(realData); - } - logger.error("当前列数据未注入,不支持的类型:"+dataType+",只支持[int,long,double,float,boolean,date,String]"); - return null; - } - - if(dataType == Date.class){ - String pattern = dateFormat.getPattern(); - try { - Date parseDate = DateUtils.parseDate(stringCellValue, new String []{pattern}); - return dataType.cast(parseDate); - } catch (java.text.ParseException e) { - logger.error("单元格日期解析错误,给定的日期值为 :"+stringCellValue+",要求的日期格式为:"+pattern+"; 在:"+cell.getRowIndex()+" 行,"+cell.getColumnIndex()+" 列",e); - } - } - - return dataType.cast(stringCellValue); - case Cell.CELL_TYPE_ERROR: - //作为 null 值写入 - return null; - default: - break; - } - return null; - } - - /** - * - * 功能:注入数据,这里可能会有很多问题,还有数据小数点问题
- * 创建时间:2017-8-12下午10:52:05
- * 作者:sanri
- * @param cellType - * @param cell - * @param writeMethod - * @param columnConfig - * @param dataItem - * @param creationHelper - */ - static final DecimalFormat decimalFormat = new DecimalFormat("0"); - private static void invokeData(int cellType,Cell cell,Method writeMethod,ColumnConfig columnConfig,Object dataItem,CreationHelper creationHelper) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{ - Class dataType = columnConfig.getDataType(); - switch (cellType) { - case Cell.CELL_TYPE_BOOLEAN: - boolean booleanCellValue = cell.getBooleanCellValue(); - if(dataType == Boolean.class || dataType == boolean.class){ - writeMethod.invoke(dataItem, booleanCellValue); - }else{ - writeMethod.invoke(dataItem, String.valueOf(booleanCellValue)); - } - break; - case Cell.CELL_TYPE_BLANK: - //null 值无需写入 - break; - case Cell.CELL_TYPE_FORMULA: - FormulaEvaluator formulaEvaluator = creationHelper.createFormulaEvaluator(); - CellValue cellValue = formulaEvaluator.evaluate(cell); - int newCellType = cellValue.getCellType(); - invokeData(newCellType, cell, writeMethod, columnConfig, dataItem, creationHelper); - break; - case Cell.CELL_TYPE_NUMERIC: - //add by sanri at 2017/09/08 判断是否为日期单元格,使用 excel 日期进行转换 - double doubleValue = cell.getNumericCellValue(); - //根据目标类型来判断需要设置的值 - if(dataType == Date.class){ - //目标类型为 Date - Date javaDate = DateUtil.getJavaDate(doubleValue); - writeMethod.invoke(dataItem, javaDate); - }else if(dataType == String.class){ - if( DateUtil.isCellDateFormatted(cell)){ - //如果单元格是 date 类型,则转为 date 字符串 - Date javaDate = DateUtil.getJavaDate(doubleValue); - writeMethod.invoke(dataItem, DateFormatUtils.format(javaDate,columnConfig.getPattern())); - }else{ - //add by sanri at 2017/09/08 解决读出科学计数法的字符串问题; string 读数值单元格,是否需要取精度值 - int precision = columnConfig.getPrecision(); - if(precision != -1) { - String realValue = new BigDecimal(String.valueOf(doubleValue)).setScale(precision, RoundingMode.HALF_EVEN).toPlainString(); - writeMethod.invoke(dataItem, realValue); - }else{ - writeMethod.invoke(dataItem,String.valueOf(doubleValue)); - } - } - }else if(dataType== int.class || dataType== Integer.class){ - writeMethod.invoke(dataItem, (int)doubleValue); - }else if(dataType == Float.class || dataType == Float.class){ - writeMethod.invoke(dataItem, (float)doubleValue); - }else if(dataType == Double.class || dataType == double.class){ - writeMethod.invoke(dataItem, doubleValue); - }else if(dataType == Long.class || dataType == long.class){ - writeMethod.invoke(dataItem, (long)doubleValue); - }else{ - logger.error("不支持的数字类型转换,只支持[int,float,long,double]中的一种,在:"+columnConfig.getChinese()); - } - break; - case Cell.CELL_TYPE_STRING: - String stringCellValue = cell.getStringCellValue(); - if(columnConfig.isTrim()){ - stringCellValue = StringUtils.trim(stringCellValue); - } - if(ClassUtils.isPrimitiveOrWrapper(dataType) ){ - Object realValue = stringCell2RealTypeValue(dataType, stringCellValue); - if(realValue == null){ - logger.warn("列["+columnConfig.getPropertyName()+"]数据未注入,不支持的类型:"+dataType+",只支持[int,long,double,float,boolean,date,String]"); - }else { - writeMethod.invoke(dataItem, realValue); - } - }else if(dataType == Date.class){ - try { - writeMethod.invoke(dataItem, DateUtils.parseDate(stringCellValue, new String[]{columnConfig.getPattern()})); - } catch (java.text.ParseException e) { - logger.error("单元格日期解析错误,给定的日期值为 :"+stringCellValue+",要求的日期格式为:"+columnConfig.getPattern(),e); - } - }else{ - writeMethod.invoke(dataItem, stringCellValue); - } - break; - case Cell.CELL_TYPE_ERROR: - //作为 null 值写入 - break; - default: - break; - } - } - - /** - * 字符串单元格,解析实际类型数据 - * @param dataType - * @param stringCellValue - * @return - */ - private static Object stringCell2RealTypeValue(Class dataType, String stringCellValue) { - Object realValue = null; - if(dataType == int.class || dataType == Integer.class){ - realValue = NumberUtils.toInt(stringCellValue); - }else if(dataType == long.class || dataType == Long.class){ - realValue = NumberUtils.toLong(stringCellValue); - }else if(dataType == double.class || dataType == Double.class){ - realValue = NumberUtils.toDouble(stringCellValue); - }else if(dataType == float.class || dataType == Float.class){ - realValue = NumberUtils.toFloat(stringCellValue); - }else if(dataType == boolean.class || dataType == Boolean.class){ - realValue = Boolean.parseBoolean(stringCellValue); - } - return realValue; - } - -} diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/annotation/ExcelColumn.java b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/annotation/ExcelColumn.java deleted file mode 100644 index 40ac8b98ac..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/annotation/ExcelColumn.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.sanri.excel.poi.annotation; - -import com.sanri.excel.poi.converter.ExcelConverter; -import com.sanri.excel.poi.converter.NULLConverter; -import com.sanri.excel.poi.enums.CellType; - -import java.lang.annotation.*; - -/** - * - * 作者:sanri
- * 时间:2017-8-12上午11:45:39
- * 功能:导入导出列配置,注解加到属性上说明对于导入和导出的配置是一样的, - * 加到 set 上只针对导入,get 上只针对导出,get,set 上的配置会覆盖属性上的配置
- */ -@Target(value={ElementType.METHOD,ElementType.FIELD}) -@Retention(value=RetentionPolicy.RUNTIME) -@Documented -public @interface ExcelColumn { - /** - * 作者:sanri
- * 时间:2017-8-12上午11:47:56
- * 功能:导出,导入的单元格标题 ,必填
- * @return - */ - String value() ; - /** - * 作者:sanri
- * 时间:2017-8-12上午11:49:29
- * 功能:导入,导出时的索引配置,从 0 开始,必须提供
- * @return - */ - int order() default -1; - - /** - * - * 作者:sanri
- * 时间:2017-8-12下午12:23:19
- * 功能: 列的宽度配置,如果这里有配置,则使用这里的配置,否则使用自动宽度(如果配置为 true 的话,为 false 不设置)
- * 注:使用 excel 的宽度设置,一个中文字对应 2 * 256 长度单位 - * @return - */ - int width() default -1; - - /** - * - * 作者:sanri
- * 时间:2017-9-19下午4:46:29
- * 功能:使用字符宽度,一个中文字填写 1
- * @return - */ - int charWidth() default -1; - - /** - * - * 作者:sanri
- * 时间:2017-9-19下午4:47:40
- * 功能:使用像素宽度, 1 像素填写 1
- * @return - */ - int pxWidth() default -1; - - /** - * - * 功能:由于自动宽度对中文支持不太好,所以这里加个中文的自动宽度支持,这个只在自动宽度设置为 true 时生效
- * 创建时间:2017-8-13上午8:35:54
- * 作者:sanri
- * @return
- */ - boolean chineseWidth() default false; - - /** - * - * 作者:sanri
- * 时间:2017-8-12下午12:26:47
- * 功能: 当前列是否隐藏 默认 false
- * @return - */ - boolean hidden() default false; - - /** - * - * 作者:sanri
- * 时间:2017-8-12下午1:46:24
- * 功能: 时间格式化,默认 yyyy-MM-dd
- * @return - */ - String pattern() default "yyyy-MM-dd"; - - /** - * 如果是浮点型,保留几位小数 ,默认不处理 - * 如果需要设置精度,修改此值 - * @return - */ - int precision() default -1; - - /** - * 单元格类型,默认 String - * @return - */ - CellType cellType() default CellType.CELL_TYPE_STRING; - - /** - * 是否需要去除两边空格 - * @return - */ - boolean trim() default true; - - /** - * 转换器设置,写 Excel 的时候,将当前列的值转换为目标值 - * 注意:一个 Writer 只会有一个转换器实例,不能保存状态信息 - * @return - */ - Class converter() default NULLConverter.class; -} diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/annotation/ExcelExport.java b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/annotation/ExcelExport.java deleted file mode 100644 index c4933149ec..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/annotation/ExcelExport.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.sanri.excel.poi.annotation; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import com.sanri.excel.poi.enums.ExcelVersion; - -/** - * - * 作者:sanri
- * 时间:2017-8-12上午11:44:36
- * 功能:excel 导出标记,支持 excel 导出
- */ -@Target(value=ElementType.TYPE) -@Retention(value=RetentionPolicy.RUNTIME) -@Documented -public @interface ExcelExport { - /** - * - * 作者:sanri
- * 时间:2017-8-12上午11:57:21
- * 功能:导出版本,默认导出 2007 版本
- * @return - */ - ExcelVersion version() default ExcelVersion.EXCEL2007; - - /** - * - * 作者:sanri
- * 时间:2017-8-12下午6:43:35
- * 功能:最顶部的标题行高度,需要设置 title 才能使其生效
- * @return - */ - short titleRowHeight() default 40; - - /** - * - * 作者:sanri
- * 时间:2017-8-12下午12:16:06
- * 功能: 头标题行高度,以像素为单位
- * @return - */ - short headRowHeight() default 30; - - /** - * - * 作者:sanri
- * 时间:2017-8-12下午12:16:18
- * 功能:内容行高度,以像素为单位
- * @return - */ - short bodyRowHeight() default 25; - - /** - * - * 作者:sanri
- * 时间:2017-8-12下午12:18:30
- * 功能:是否自动宽度,默认为 true
- * @return - */ - boolean autoWidth() default true; - - /** - * 作者:sanri
- * 时间:2017-8-12下午1:32:57
- * 功能:一个sheet 页的最大记录数,默认是不限制的,如果是 2003 版本,限制为 60000 行
- * @return - */ - int sheetMaxRow() default -1; - - /** - * 使用 new SXSSFWorkbook(rowAccessWindowSize) 快速导出 Excel - * @return - */ - boolean fastModel() default true; - - /** - * rowAccessWindowSize 数量,根据内存大小来确定 - * @return - */ - int rowAccessWindowSize() default 1000; -} diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/annotation/ExcelImport.java b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/annotation/ExcelImport.java deleted file mode 100644 index 2df8631e75..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/annotation/ExcelImport.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.sanri.excel.poi.annotation; - -import com.sanri.excel.poi.enums.ExcelVersion; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * - * 作者:sanri
- * 时间:2017-8-12上午11:45:14
- * 功能:excel 导入标记,支持 excel 导入
- */ -@Target(value=ElementType.TYPE) -@Retention(value=RetentionPolicy.RUNTIME) -@Documented -public @interface ExcelImport { - /** - * - * 作者:sanri
- * 时间:2017-8-12上午11:47:03
- * 功能:导入版本支持,默认支持 2007 和 2003
- * @return - */ - ExcelVersion[] support() default {ExcelVersion.EXCEL2003,ExcelVersion.EXCEL2007}; - - /** - * - * 功能:指定哪一行才是真正的数据开始的地方 从 0 开始
- * 创建时间:2017-8-12下午10:19:15
- * 作者:sanri
- * @return
- */ - int startRow() default 1; -} diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/converter/DefaultBooleanStringConverter.java b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/converter/DefaultBooleanStringConverter.java deleted file mode 100644 index d95c190d96..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/converter/DefaultBooleanStringConverter.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.sanri.excel.poi.converter; - -public class DefaultBooleanStringConverter implements ExcelConverter { - @Override - public String convert(Boolean source) { - return String.valueOf(source); - } -} diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/converter/ExcelConverter.java b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/converter/ExcelConverter.java deleted file mode 100644 index 56e468a76a..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/converter/ExcelConverter.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.sanri.excel.poi.converter; - -/** - * 类型转换器只针对于写 Excel 模式 - * @param - * @param - */ -public interface ExcelConverter { - T convert(S source); -} diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/converter/NULLConverter.java b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/converter/NULLConverter.java deleted file mode 100644 index 7bc3a5ec5a..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/converter/NULLConverter.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.sanri.excel.poi.converter; - -/** - * 不做任何转换 - */ -public class NULLConverter implements ExcelConverter { - @Override - public Object convert(Object source) { - return source; - } -} diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/enums/CellType.java b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/enums/CellType.java deleted file mode 100644 index a2d795b94f..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/enums/CellType.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.sanri.excel.poi.enums; - -/** - * 单元格类型,用于导出的时候设置单元格类型 - */ -public enum CellType { - CELL_TYPE_NUMERIC(0),CELL_TYPE_STRING(1), - CELL_TYPE_BLANK(3),CELL_TYPE_BOOLEAN(4),; - - private int value; - - CellType(int value){ - this.value = value; - } - - public int getValue() { - return value; - } -} diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/enums/ExcelVersion.java b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/enums/ExcelVersion.java deleted file mode 100644 index 4a7fc8b5f9..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/enums/ExcelVersion.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.sanri.excel.poi.enums; - -/** - * - * 作者:sanri
- * 时间:2017-8-12下午1:37:27
- * 功能:excel 的版本,支持 2007 和 2003 版本
- */ -public enum ExcelVersion { - EXCEL2007(2007),EXCEL2003(2003); - - private int version; - ExcelVersion(int version){ - this.version = version; - } - - public int getVersion(int version) { - return this.version; - } - -} diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/handler/CollectErrorRowHandler.java b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/handler/CollectErrorRowHandler.java deleted file mode 100644 index 415abecd94..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/handler/CollectErrorRowHandler.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.sanri.excel.poi.handler; - -import com.sanri.excel.poi.ColumnConfig; -import org.apache.poi.ss.usermodel.Cell; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; - -/** - * 默认错误行处理器,收集所有错误行 - */ -public class CollectErrorRowHandler implements ErrorRowHandler { - private List errorDatas = new ArrayList<>(); - - @Override - public boolean handlerRow(Cell cell, Method writeMethod, ColumnConfig columnConfig) { - CellData cellData = new CellData(cell.getRowIndex(), cell.getColumnIndex(), cell.getStringCellValue(), columnConfig); - errorDatas.add(cellData); - return true; - } - - public static class CellData{ - private int rowIndex; - private int cellIndex; - private String cellValue; - private ColumnConfig columnConfig; - - public CellData() { - } - - public CellData(int rowIndex, int cellIndex, String cellValue, ColumnConfig columnConfig) { - this.rowIndex = rowIndex; - this.cellIndex = cellIndex; - this.cellValue = cellValue; - this.columnConfig = columnConfig; - } - } - - public List getErrorDatas() { - return errorDatas; - } -} diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/handler/ErrorRowHandler.java b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/handler/ErrorRowHandler.java deleted file mode 100644 index ebcb8c05a0..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/java/com/sanri/excel/poi/handler/ErrorRowHandler.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.sanri.excel.poi.handler; - -import com.sanri.excel.poi.ColumnConfig; -import org.apache.poi.ss.usermodel.Cell; - -import java.lang.reflect.Method; - -public interface ErrorRowHandler { - /** - * 处理错误行数据,返回是否需要继续处理 - * true: 继续导入 ,false: 停止处理 - * @param cell - * @param writeMethod - * @param columnConfig - * @return - */ - boolean handlerRow(Cell cell, Method writeMethod, ColumnConfig columnConfig); -} diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/resources/log4j.properties b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/resources/log4j.properties deleted file mode 100644 index 69272d3455..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/main/resources/log4j.properties +++ /dev/null @@ -1,53 +0,0 @@ -# Output pattern : date [thread] priority category - message -rootdir=e:/logs -module=sanritools -log4j.rootLogger=info,Console,errorAppender - -log4j.logger.org.apache.kafka.common.config=warning,Console,errorAppender -log4j.additivity.org.apache.kafka.common.config=false - -# -## \u81EA\u5DF1\u7CFB\u7EDF\u7684\u9700\u8981\u8BE6\u7EC6\u6253\u5370 -log4j.logger.com.sanri=debug,Console,debugAppender,errorAppender,RollingFile -log4j.additivity.com.sanri=false -log4j.logger.sanri=debug,Console,debugAppender,errorAppender,RollingFile -log4j.additivity.sanri=false -log4j.logger.learn=debug,Console,debugAppender,errorAppender,RollingFile -log4j.additivity.learn=false - -## \u4FE1\u606F\u8FFD\u52A0\u5668 -log4j.appender.debugAppender=org.apache.log4j.RollingFileAppender -log4j.appender.debugAppender.File=${rootdir}/sanri-${module}_debug.log -log4j.appender.debugAppender.append=true -log4j.appender.debugAppender.threshold=debug -log4j.appender.debugAppender.encoding=UTF-8 -log4j.appender.debugAppender.MaxFileSize=64MB -log4j.appender.debugAppender.MaxBackupIndex=10 -log4j.appender.debugAppender.layout=org.apache.log4j.PatternLayout -log4j.appender.debugAppender.layout.ConversionPattern=%-5p %d{yyyyMMdd HH:mm:ss} [%c:%L] - %n [LOG] %m%n - -## \u5F02\u5E38\u8FFD\u52A0\u5668 -log4j.appender.errorAppender=org.apache.log4j.RollingFileAppender -log4j.appender.errorAppender.File=${rootdir}/sanri-${module}_error.log -log4j.appender.errorAppender.append=true -log4j.appender.errorAppender.threshold=error -log4j.appender.errorAppender.encoding=UTF-8 -log4j.appender.errorAppender.MaxFileSize=64MB -log4j.appender.errorAppender.MaxBackupIndex=10 -log4j.appender.errorAppender.layout=org.apache.log4j.PatternLayout -#log4j.appender.errorAppender.layout.ConversionPattern=%-5p %d{yyyyMMdd HH\:mm\:ss} [%c\:%L] - %n -log4j.appender.errorAppender.layout.ConversionPattern=%d [%t] %-5p [%C->%M(%L)] - %m%n -# -##Console -log4j.appender.Console=org.apache.log4j.ConsoleAppender -log4j.appender.Console.layout=org.apache.log4j.PatternLayout -log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%C->%M(%L)] - %m%n - -#RollingFile -log4j.appender.RollingFile=org.apache.log4j.DailyRollingFileAppender -log4j.appender.RollingFile.File=${rootdir}/sanri-${module}.log -log4j.appender.RollingFile.layout=org.apache.log4j.PatternLayout -#log4j.appender.RollingFile.layout.ConversionPattern=[%d{yyyy-MM-dd HH:mm:ss}] %-5p [%t] - %m%n -log4j.appender.RollingFile.layout.ConversionPattern=%d [%t] %-5p [%C->%M(%L)] - %m%n - - diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/java/test/ExcelTest.java b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/java/test/ExcelTest.java deleted file mode 100644 index dad86e30b5..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/java/test/ExcelTest.java +++ /dev/null @@ -1,139 +0,0 @@ -package test; - -import com.sanri.excel.poi.ExcelExportWriter; -import com.sanri.excel.poi.ExcelImportUtil; -import com.sanri.excel.poi.handler.CollectErrorRowHandler; -import com.sanri.excel.poi.handler.ErrorRowHandler; -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang3.RandomUtils; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; -import org.apache.commons.lang3.time.StopWatch; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.Test; -import vo.ConverterBean; -import vo.ExtendSimple; -import vo.Simple; - -import java.io.*; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; - -public class ExcelTest { - /** - * 简单多类型 Excel 生成 - */ - @Test - public void testSimpleBean() throws IOException { - ExcelExportWriter excelExportWriter = new ExcelExportWriter(Simple.class); - - List simpleList = simpleBeanDatas(10); - excelExportWriter.export(simpleList); - excelExportWriter.writeTo(new FileOutputStream("d:/test/"+System.currentTimeMillis()+".xlsx")); - } - - /** - * 10w 数据导出大概需要 5 秒左右 - * @throws IOException - */ - @Test - public void test10wData() throws IOException { - List simpleList = simpleBeanDatas(100000); - - StopWatch stopWatch = new StopWatch();stopWatch.start(); - ExcelExportWriter excelExportWriter = new ExcelExportWriter(Simple.class); - excelExportWriter.export(simpleList); - excelExportWriter.writeTo(new FileOutputStream("d:/test/"+System.currentTimeMillis()+".xlsx")); - stopWatch.stop(); - System.out.println("10 万数据导出用时:"+stopWatch.getTime()+" ms"); - } - - /** - * 测试继承 bean Excel 生成 - */ - @Test - public void testExtendBean() throws IOException { - ExcelExportWriter excelExportWriter = new ExcelExportWriter(ExtendSimple.class); - - List simpleList = simpleBeanDatas(10); - List extendSimples = new ArrayList(); - for (Simple simple : simpleList) { - ExtendSimple extendSimple = new ExtendSimple(simple); - extendSimple.setIdcard(RandomUtil.idcard()); - extendSimples.add(extendSimple); - } - excelExportWriter.export(extendSimples); - excelExportWriter.writeTo(new FileOutputStream("d:/test/"+System.currentTimeMillis()+".xlsx")); - } - - @Test - public void testImportExcel() throws IOException { - FileInputStream fileInputStream = FileUtils.openInputStream(new File("D:\\test/1567833427823.xlsx")); - ErrorRowHandler collectErrorRowHandler = new CollectErrorRowHandler(); - List simples = ExcelImportUtil.importData(fileInputStream, Simple.class,collectErrorRowHandler); - for (Simple simple : simples) { - System.out.println(ToStringBuilder.reflectionToString(simple, ToStringStyle.SHORT_PREFIX_STYLE)); - } - } - - @Test - public void testImportExtendExcel() throws IOException { - FileInputStream fileInputStream = FileUtils.openInputStream(new File("D:\\test/1567833685699.xlsx")); - CollectErrorRowHandler collectErrorRowHandler = new CollectErrorRowHandler(); - List simples = ExcelImportUtil.importData(fileInputStream, ExtendSimple.class,collectErrorRowHandler); - for (Simple simple : simples) { - System.out.println(ToStringBuilder.reflectionToString(simple, ToStringStyle.SHORT_PREFIX_STYLE)); - } - } - - /** - * 测试单列导入 - * @throws IOException - */ - @Test - public void testImportList() throws IOException { - FileInputStream fileInputStream = FileUtils.openInputStream(new File("D:\\test/1567833685699.xlsx")); - List strings = ExcelImportUtil.importListData(fileInputStream, String.class, 0, 1); - System.out.println(strings); - } - - @Test - public void testImportMap() throws IOException { - FileInputStream fileInputStream = FileUtils.openInputStream(new File("D:\\test/1567833685699.xlsx")); - Map stringStringMap = ExcelImportUtil.importMapData(fileInputStream, String.class, 0, 8, 1); - System.out.println(stringStringMap); - } - - @Test - public void testConvert() throws IOException { - List converterBeans = new ArrayList<>(); - converterBeans.add(new ConverterBean(true,1)); - converterBeans.add(new ConverterBean(false,2)); - - ExcelExportWriter converterBeanExcelExportWriter = new ExcelExportWriter<>(ConverterBean.class); - Workbook export = converterBeanExcelExportWriter.export(converterBeans); - converterBeanExcelExportWriter.writeTo(new FileOutputStream("d:/test/"+System.currentTimeMillis()+".xlsx")); - } - - private List simpleBeanDatas(int count) { - List simples = new ArrayList(); - for (int i = 0; i < count; i++) { - String username = RandomUtil.username(); - int age = RandomUtils.nextInt(25,140); - int level = RandomUtils.nextInt(1,4); - Date birthday = RandomUtil.date(); - long id = RandomUtils.nextLong(); - boolean success = RandomUtils.nextBoolean(); - double money = RandomUtils.nextDouble(1,10); - float comm = RandomUtils.nextFloat(1,10); - - Simple simple = new Simple(age, level, username, birthday, id, success, money,comm); - simples.add(simple); - } - - return simples; - } - -} diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/java/test/RandomUtil.java b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/java/test/RandomUtil.java deleted file mode 100644 index 0dbb4652f9..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/java/test/RandomUtil.java +++ /dev/null @@ -1,302 +0,0 @@ -package test; - -import com.alibaba.fastjson.JSONObject; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.RandomStringUtils; -import org.apache.commons.lang3.RandomUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.time.DateFormatUtils; -import org.apache.commons.lang3.time.DateUtils; - -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.nio.charset.Charset; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.*; - -/** - * - * 创建时间:2016-9-24下午5:33:29
- * 创建者:sanri
- * 功能:扩展自 org.apache.commons.lang,加入一些源数据
- */ -public class RandomUtil extends RandomStringUtils { - public static final String FIRST_NAME="赵钱孙李周吴郑王冯陈褚卫蒋沈韩杨朱秦尤许何吕施张孔曹严华金魏陶姜戚谢邹喻柏水窦章云苏潘葛奚范彭郎鲁韦昌马苗凤花方俞任袁柳酆鲍史唐费廉岑薛雷贺倪汤滕殷罗毕郝邬安常乐于时傅皮卞齐康伍余元卜顾孟平黄和穆萧尹姚邵湛汪祁毛禹狄米贝明臧计伏成戴谈宋茅庞熊纪舒屈项祝董梁杜阮蓝闵席季麻强贾路娄危江童颜郭梅盛林刁钟徐邱骆高夏蔡田樊胡凌霍虞万支柯昝管卢莫经房裘缪干解应宗丁宣贲邓郁单杭洪包诸左石崔吉钮龚程嵇邢滑裴陆荣翁荀羊於惠甄麴家封芮羿储靳汲邴糜松井段富巫乌焦巴弓牧隗山谷车侯宓蓬全郗班仰秋仲伊宫宁仇栾暴甘钭厉戎祖武符刘景詹束龙叶幸司韶郜黎蓟薄印宿白怀蒲邰从鄂索咸籍赖卓蔺屠蒙池乔阴郁胥能苍双闻莘党翟谭贡劳逄姬申扶堵冉宰郦雍舄璩桑桂濮牛寿通边扈燕冀郏浦尚农温别庄晏柴瞿阎充慕连茹习宦艾鱼容向古易慎戈廖庾终暨居衡步都耿满弘匡国文寇广禄阙东殴殳沃利蔚越夔隆师巩厍聂晁勾敖融冷訾辛阚那简饶空曾毋沙乜养鞠须丰巢关蒯相查後荆红游竺权逯盖益桓公晋楚闫法汝鄢涂钦仉督岳帅缑亢况后有琴商牟佘佴伯赏墨哈谯笪年爱阳佟"; - public static final String GIRL="秀娟英华慧巧美娜静淑惠珠翠雅芝玉萍红娥玲芬芳燕彩春菊兰凤洁梅琳素云莲真环雪荣爱妹霞香月莺媛艳瑞凡佳嘉琼勤珍贞莉桂娣叶璧璐娅琦晶妍茜秋珊莎锦黛青倩婷姣婉娴瑾颖露瑶怡婵雁蓓纨仪荷丹蓉眉君琴蕊薇菁梦岚苑婕馨瑗琰韵融园艺咏卿聪澜纯毓悦昭冰爽琬茗羽希宁欣飘育滢馥筠柔竹霭凝晓欢霄枫芸菲寒伊亚宜可姬舒影荔枝思丽"; - public static final String BOY="伟刚勇毅俊峰强军平保东文辉力明永健鸿世广万志义兴良海山仁波宁贵福生龙元全国胜学祥才发武新利清飞彬富顺信子杰涛昌成康星光天达安岩中茂进林有坚和彪博诚先敬震振壮会思群豪心邦承乐绍功松善厚庆磊民友裕河哲江超浩亮政谦亨奇固之轮翰朗伯宏言若鸣朋斌梁栋维启克伦翔旭鹏泽晨辰士以建家致树炎德行时泰盛雄琛钧冠策腾楠榕风航弘正日"; - - public static JSONObject AREANO_MAP; - public static JSONObject CITY_LIST; - public static final String[] EMAIL_SUFFIX="@gmail.com,@yahoo.com,@msn.com,@hotmail.com,@aol.com,@ask.com,@live.com,@qq.com,@0355.net,@163.com,@163.net,@263.net,@3721.net,@yeah.net,@googlemail.com,@126.com,@sina.com,@sohu.com,@yahoo.com.cn".split(","); - public static final String[] PHONE_SEGMENT = "133,149,153,173,177,180,181,189,199,130,131,132,145,155,156,166,171,175,176,185,186,166,135,136,137,138,139,147,150,151,152,157,158,159,172,178,182,183,184,187,188,198,170".split(","); - public static String [] ADDRESS_LIST; - public static String [] JOBS; - static{ - InputStreamReader reader = null; - Charset charset = Charset.forName("utf-8"); - try { - URI resource = RandomUtil.class.getResource("/").toURI(); - URI addressURI = resource.resolve(new URI("data/address.string")); - URI citylistURI = resource.resolve(new URI("data/city.min.json")); - URI idcodeURI = resource.resolve(new URI("data/idcodearea.json")); - URI jobURI = resource.resolve(new URI("data/job")); - - ADDRESS_LIST = StringUtils.split(IOUtils.toString(addressURI,charset),','); - CITY_LIST = JSONObject.parseObject(IOUtils.toString(citylistURI,charset)); - AREANO_MAP = JSONObject.parseObject(IOUtils.toString(idcodeURI,charset)); - JOBS = StringUtils.split(IOUtils.toString(jobURI,charset),','); - } catch (Exception e) { - e.printStackTrace(); - }finally{ - IOUtils.closeQuietly(reader); - } - } - - /** - * 功能:生成 length 个中文
- * 创建时间:2016-4-16上午11:24:40 - * 作者:sanri - * */ - public static String chinese(int length, String src) { - String ret = ""; - if(!StringUtils.isBlank(src)){ - return random(length, src.toCharArray()); - } - for (int i = 0; i < length; i++) { - String str = null; - int hightPos, lowPos; // 定义高低位 - Random random = new Random(); - hightPos = (176 + Math.abs(random.nextInt(39))); // 获取高位值 - lowPos = (161 + Math.abs(random.nextInt(93))); // 获取低位值 - byte[] b = new byte[2]; - b[0] = (new Integer(hightPos).byteValue()); - b[1] = (new Integer(lowPos).byteValue()); - try { - str = new String(b, "GBk"); // 转成中文 - } catch (UnsupportedEncodingException ex) { - ex.printStackTrace(); - } - ret += str; - } - return ret; - } - - /** - * - * 功能:随机生成用户名
- * 创建时间:2017-8-13上午8:04:32
- * 作者:sanri
- * @return
- */ - public static String username(){ - boolean sex = (randomNumber(100) % 2 == 0 ); - int secondNameLength = (int) randomNumber(2); - String firstName = random(1, FIRST_NAME); - String srcChars = sex ? BOY : GIRL; - String secondName = random(secondNameLength,srcChars ); - return firstName+secondName; - } - /** - * - * 功能:给定格式 ,开始时间,结束时间,生成一个在开始和结束内的日期
- * 创建时间:2016-4-16下午3:57:38
- * 作者:sanri
- * 入参说明:
- * 出参说明:字符串日期类型由 format 格式化
- * @throws ParseException
- */ - public static String date(String format,String begin,String end) throws ParseException{ - if(StringUtils.isBlank(format)){ - format = "yyyyMMdd"; - } - long timstamp = timstamp(format, begin, end); - return DateFormatUtils.format(timstamp, format); - } - /** - * - * 功能:得到由开始时间和结束时间内的一个时间戳
- * 创建时间:2016-4-16下午4:07:31
- * 作者:sanri
- * 入参说明:
- * 出参说明:如果时间给的不对,则是当前时间
- * @param format - * @param begin - * @param end - * @return - * @throws ParseException
- */ - public static long timstamp(String format,String begin,String end) throws ParseException{ - if(StringUtils.isBlank(format)){ - format = "yyyyMMdd"; - } - Date now = new Date(); - if(StringUtils.isBlank(begin)){ - begin = DateFormatUtils.format(now,format); - } - if(StringUtils.isBlank(end)){ - end = DateFormatUtils.format(now,format); - } - String [] formats = new String []{format}; - long beginDateTime = DateUtils.parseDate(begin, formats).getTime(); - long endDateTime = DateUtils.parseDate(end, formats).getTime(); - if(beginDateTime > endDateTime){ - return now.getTime(); - } - long random = randomNumber(endDateTime - beginDateTime); - return random + beginDateTime; - } - /** - * - * 功能:生成限制数字内的数字 0 ~ limit 包括 limit
- * 创建时间:2016-9-24下午6:07:05
- * 作者:sanri
- */ - public static long randomNumber(long limit) { - return Math.round(Math.random() * limit); - } - /** - * - * 功能:生成身份证号
- * 创建时间:2016-4-16下午2:31:37
- * 作者:sanri
- * 入参说明:[area:区域号][yyyyMMdd:出生日期][sex:偶=女,奇=男]
- * 出参说明:330602 19770717 201 1
- * - * @param area - * @param yyyyMMdd - * @param sno - * @return
- */ - public static String idcard(String area, String yyyyMMdd, String sno) { - String idCard17 = area + yyyyMMdd + sno; - int[] validas = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }; - char[] idCards = idCard17.toCharArray(); - int count = 0; - for (int i = 0; i < validas.length; i++) { - count += Integer.valueOf(String.valueOf(idCards[i])) * validas[i]; - } - String lastNum = String.valueOf((12 - count % 11) % 11); - lastNum = "10".equals(lastNum) ? "x":lastNum; - return idCard17 + lastNum; - } - public static String idcard(String area){ - String format = "yyyyMMdd"; - SimpleDateFormat sdf = new SimpleDateFormat(format); - try { - String yyyyMMdd = date(format, "19990101", sdf.format(new Date())); - String sno = randomNumeric(3); - return idcard(area, yyyyMMdd, sno); - } catch (ParseException e) { - e.printStackTrace(); - } - return ""; - } - - /** - * 随机生成身份证号 - * 暂时有问题 TODO 先使用临时方案 - * @return - */ - public static String idcard(){ - Set areaNos = AREANO_MAP.keySet(); - List areaList = new ArrayList(); - areaList.addAll(areaNos); - String area = areaList.get((int)randomNumber(areaList.size() - 1)); - while (area.length() != 6){ - area = areaList.get((int)randomNumber(areaList.size() - 1)); - } - return idcard(area); - } - /** - * - * 功能:随机生成地址
- * 创建时间:2016-4-16下午6:19:14
- * 作者:sanri
- * 入参说明:
- * 出参说明:
- * @return
- */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - public static String address(){ - List cityList = (List) CITY_LIST.get("citylist"); - Map provinceEntry = cityList.get((int)randomNumber(cityList.size() - 1)); - String province = String.valueOf(provinceEntry.get("p")); - List city = (List) provinceEntry.get("c"); - Map areaEntry = city.get((int)randomNumber(city.size() - 1)); - String area = String.valueOf(areaEntry.get("n")); - List area2 = (List) areaEntry.get("a"); - String s = ""; - if(area2 != null){ - Map cityEntry = area2.get((int)randomNumber(area2.size() - 1)); - s = String.valueOf(cityEntry.get("s")); - } - return province + area + s + ADDRESS_LIST[(int)randomNumber(ADDRESS_LIST.length - 1)]; - } - /** - * - * 功能:随机邮件地址,length 指 用户名长度
- * 创建时间:2016-9-24下午6:11:54
- * 作者:sanri
- */ - public static String email(int length){ - return randomAlphanumeric(length)+EMAIL_SUFFIX[(int)randomNumber(EMAIL_SUFFIX.length - 1)]; - } - - /** - * 随机职业 - * @return - */ - public static String job(){ - return JOBS[(int)randomNumber(JOBS.length - 1)]; - } - /** - * 生成手机号 - * @param segment - * @return - */ - public static String phone(String segment){ - if(StringUtils.isBlank(segment)){ - return phone(); - } - int length = segment.length(); - int randomLength = 11 - length; - String randomNumeric = randomNumeric(randomLength); - return segment+randomNumeric; - } - - /** - * 随机前缀手机号 - * @return - */ - public static String phone(){ - String segment = PHONE_SEGMENT[(int)randomNumber(PHONE_SEGMENT.length - 1)]; - return phone(segment); - } - - /** - * 生成一个随机日期 - * @param begin - * @param end - * @return - */ - public static Date date(Date begin ,Date end){ - if(begin == null || end == null || end.before(begin)){ - throw new IllegalArgumentException("请传入正确数据"); - } - long minus = end.getTime() - begin.getTime(); - long computedMinus = RandomUtils.nextLong(0, minus); - long computedDateTime = begin.getTime() + computedMinus; - return new Date(computedDateTime); - } - - /** - * 随机日期 - * @return - */ - public static Date date(){ - return date(new Date(0L),new Date()); - } - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/java/vo/ConverterBean.java b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/java/vo/ConverterBean.java deleted file mode 100644 index 4dd8adba63..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/java/vo/ConverterBean.java +++ /dev/null @@ -1,41 +0,0 @@ -package vo; - -import com.sanri.excel.poi.annotation.ExcelColumn; -import com.sanri.excel.poi.annotation.ExcelExport; -import com.sanri.excel.poi.converter.DefaultBooleanStringConverter; - -@ExcelExport -public class ConverterBean { - @ExcelColumn(value = "是否成功",order = 0,converter = DefaultBooleanStringConverter.class) - private boolean success; - @ExcelColumn(value = "性别",order = 1,converter = GenderConverter.class) - private int gender; - - public ConverterBean() { - } - - public ConverterBean(boolean success) { - this.success = success; - } - - public ConverterBean(boolean success, int gender) { - this.success = success; - this.gender = gender; - } - - public boolean isSuccess() { - return success; - } - - public void setSuccess(boolean success) { - this.success = success; - } - - public int getGender() { - return gender; - } - - public void setGender(int gender) { - this.gender = gender; - } -} diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/java/vo/ExtendSimple.java b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/java/vo/ExtendSimple.java deleted file mode 100644 index 297c69b169..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/java/vo/ExtendSimple.java +++ /dev/null @@ -1,37 +0,0 @@ -package vo; - -import com.sanri.excel.poi.annotation.ExcelColumn; -import com.sanri.excel.poi.annotation.ExcelExport; -import com.sanri.excel.poi.annotation.ExcelImport; - -import java.util.Date; - -/** - * 测试继承类是否能够正确导出 - */ -@ExcelExport -@ExcelImport(startRow = 1) -public class ExtendSimple extends Simple{ - @ExcelColumn(value = "身份证号",order = 8) - private String idcard; - - public ExtendSimple() { - } - - public ExtendSimple(int age, Integer level, String name, Date birthday, long id, boolean success, double money, float comm, String idcard) { - super(age, level, name, birthday, id, success, money, comm); - this.idcard = idcard; - } - - public ExtendSimple(Simple simple) { - this(simple.getAge(),simple.getLevel(),simple.getName(),simple.getBirthday(),simple.getId(),simple.isSuccess(),simple.getMoney(),simple.getComm(),null); - } - - public String getIdcard() { - return idcard; - } - - public void setIdcard(String idcard) { - this.idcard = idcard; - } -} diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/java/vo/GenderConverter.java b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/java/vo/GenderConverter.java deleted file mode 100644 index 7981fecb0a..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/java/vo/GenderConverter.java +++ /dev/null @@ -1,10 +0,0 @@ -package vo; - -import com.sanri.excel.poi.converter.ExcelConverter; - -public class GenderConverter implements ExcelConverter { - @Override - public String convert(Integer source) { - return source == 1 ? "男":"女"; - } -} diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/java/vo/Simple.java b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/java/vo/Simple.java deleted file mode 100644 index 1d3c992784..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/java/vo/Simple.java +++ /dev/null @@ -1,109 +0,0 @@ -package vo; - -import com.sanri.excel.poi.annotation.ExcelColumn; -import com.sanri.excel.poi.annotation.ExcelExport; -import com.sanri.excel.poi.annotation.ExcelImport; - -import java.util.Date; - -/** - * 用于测试各种类型是否正常展示 - */ -@ExcelExport -@ExcelImport(startRow = 1) -public class Simple { - @ExcelColumn(value = "年龄",order = 2) - private int age; - @ExcelColumn(value = "级别",order = 1) - private Integer level; - @ExcelColumn(value = "姓名",order = 0,chineseWidth = true) - private String name; - @ExcelColumn(value = "生日",order = 3) - private Date birthday; - @ExcelColumn(value = "序号",order = 4,hidden = true) - private long id; - @ExcelColumn(value = "是否成功",order = 5) - private boolean success; - @ExcelColumn(value = "薪水",order = 6,precision = 2) - private double money; - @ExcelColumn(value = "奖金",order = 7,precision = 2) - private float comm; - - public Simple() { - } - - public Simple(int age, Integer level, String name, Date birthday, long id, boolean success, double money, float comm) { - this.age = age; - this.level = level; - this.name = name; - this.birthday = birthday; - this.id = id; - this.success = success; - this.money = money; - this.comm = comm; - } - - public int getAge() { - return age; - } - - public Integer getLevel() { - return level; - } - - public String getName() { - return name; - } - - public Date getBirthday() { - return birthday; - } - - public long getId() { - return id; - } - - public boolean isSuccess() { - return success; - } - - public double getMoney() { - return money; - } - - public float getComm() { - return comm; - } - - public void setAge(int age) { - this.age = age; - } - - public void setLevel(Integer level) { - this.level = level; - } - - public void setName(String name) { - this.name = name; - } - - public void setBirthday(Date birthday) { - this.birthday = birthday; - } - - public void setId(long id) { - this.id = id; - } - - public void setSuccess(boolean success) { - this.success = success; - } - - public void setMoney(double money) { - this.money = money; - } - - public void setComm(float comm) { - this.comm = comm; - } -} diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/test-resources/data/address.string b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/test-resources/data/address.string deleted file mode 100644 index 622a95d3a3..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/test-resources/data/address.string +++ /dev/null @@ -1 +0,0 @@ -重庆大厦,黑龙江路,十梅庵街,遵义路,湘潭街,瑞金广场,仙山街,仙山东路,仙山西大厦,白沙河路,赵红广场,机场路,民航街,长城南路,流亭立交桥,虹桥广场,长城大厦,礼阳路,风岗街,中川路,白塔广场,兴阳路,文阳街,绣城路,河城大厦,锦城广场,崇阳街,华城路,康城街,正阳路,和阳广场,中城路,江城大厦,顺城路,安城街,山城广场,春城街,国城路,泰城街,德阳路,明阳大厦,春阳路,艳阳街,秋阳路,硕阳街,青威高速,瑞阳街,丰海路,双元大厦,惜福镇街道,夏庄街道,古庙工业园,中山街,太平路,广西街,潍县广场,博山大厦,湖南路,济宁街,芝罘路,易州广场,荷泽四路,荷泽二街,荷泽一路,荷泽三大厦,观海二广场,广西支街,观海一路,济宁支街,莒县路,平度广场,明水路,蒙阴大厦,青岛路,湖北街,江宁广场,郯城街,天津路,保定街,安徽路,河北大厦,黄岛路,北京街,莘县路,济南街,宁阳广场,日照街,德县路,新泰大厦,荷泽路,山西广场,沂水路,肥城街,兰山路,四方街,平原广场,泗水大厦,浙江路,曲阜街,寿康路,河南广场,泰安路,大沽街,红山峡支路,西陵峡一大厦,台西纬一广场,台西纬四街,台西纬二路,西陵峡二街,西陵峡三路,台西纬三广场,台西纬五路,明月峡大厦,青铜峡路,台西二街,观音峡广场,瞿塘峡街,团岛二路,团岛一街,台西三路,台西一大厦,郓城南路,团岛三街,刘家峡路,西藏二街,西藏一广场,台西四街,三门峡路,城武支大厦,红山峡路,郓城北广场,龙羊峡路,西陵峡街,台西五路,团岛四街,石村广场,巫峡大厦,四川路,寿张街,嘉祥路,南村广场,范县路,西康街,云南路,巨野大厦,西江广场,鱼台街,单县路,定陶街,滕县路,钜野广场,观城路,汶上大厦,朝城路,滋阳街,邹县广场,濮县街,磁山路,汶水街,西藏路,城武大厦,团岛路,南阳街,广州路,东平街,枣庄广场,贵州街,费县路,南海大厦,登州路,文登广场,信号山支路,延安一街,信号山路,兴安支街,福山支广场,红岛支大厦,莱芜二路,吴县一街,金口三路,金口一广场,伏龙山路,鱼山支街,观象二路,吴县二大厦,莱芜一广场,金口二街,海阳路,龙口街,恒山路,鱼山广场,掖县路,福山大厦,红岛路,常州街,大学广场,龙华街,齐河路,莱阳街,黄县路,张店大厦,祚山路,苏州街,华山路,伏龙街,江苏广场,龙江街,王村路,琴屿大厦,齐东路,京山广场,龙山路,牟平街,延安三路,延吉街,南京广场,东海东大厦,银川西路,海口街,山东路,绍兴广场,芝泉路,东海中街,宁夏路,香港西大厦,隆德广场,扬州街,郧阳路,太平角一街,宁国二支路,太平角二广场,天台东一路,太平角三大厦,漳州路一路,漳州街二街,宁国一支广场,太平角六街,太平角四路,天台东二街,太平角五路,宁国三大厦,澳门三路,江西支街,澳门二路,宁国四街,大尧一广场,咸阳支街,洪泽湖路,吴兴二大厦,澄海三路,天台一广场,新湛二路,三明北街,新湛支路,湛山五街,泰州三广场,湛山四大厦,闽江三路,澳门四街,南海支路,吴兴三广场,三明南路,湛山二街,二轻新村镇,江南大厦,吴兴一广场,珠海二街,嘉峪关路,高邮湖街,湛山三路,澳门六广场,泰州二路,东海一大厦,天台二路,微山湖街,洞庭湖广场,珠海支街,福州南路,澄海二街,泰州四路,香港中大厦,澳门五路,新湛三街,澳门一路,正阳关街,宁武关广场,闽江四街,新湛一路,宁国一大厦,王家麦岛,澳门七广场,泰州一路,泰州六街,大尧二路,青大一街,闽江二广场,闽江一大厦,屏东支路,湛山一街,东海西路,徐家麦岛函谷关广场,大尧三路,晓望支街,秀湛二路,逍遥三大厦,澳门九广场,泰州五街,澄海一路,澳门八街,福州北路,珠海一广场,宁国二路,临淮关大厦,燕儿岛路,紫荆关街,武胜关广场,逍遥一街,秀湛四路,居庸关街,山海关路,鄱阳湖大厦,新湛路,漳州街,仙游路,花莲街,乐清广场,巢湖街,台南路,吴兴大厦,新田路,福清广场,澄海路,莆田街,海游路,镇江街,石岛广场,宜兴大厦,三明路,仰口街,沛县路,漳浦广场,大麦岛,台湾街,天台路,金湖大厦,高雄广场,海江街,岳阳路,善化街,荣成路,澳门广场,武昌路,闽江大厦,台北路,龙岩街,咸阳广场,宁德街,龙泉路,丽水街,海川路,彰化大厦,金田路,泰州街,太湖路,江西街,泰兴广场,青大街,金门路,南通大厦,旌德路,汇泉广场,宁国路,泉州街,如东路,奉化街,鹊山广场,莲岛大厦,华严路,嘉义街,古田路,南平广场,秀湛路,长汀街,湛山路,徐州大厦,丰县广场,汕头街,新竹路,黄海街,安庆路,基隆广场,韶关路,云霄大厦,新安路,仙居街,屏东广场,晓望街,海门路,珠海街,上杭路,永嘉大厦,漳平路,盐城街,新浦路,新昌街,高田广场,市场三街,金乡东路,市场二大厦,上海支路,李村支广场,惠民南路,市场纬街,长安南路,陵县支街,冠县支广场,小港一大厦,市场一路,小港二街,清平路,广东广场,新疆路,博平街,港通路,小港沿,福建广场,高唐街,茌平路,港青街,高密路,阳谷广场,平阴路,夏津大厦,邱县路,渤海街,恩县广场,旅顺街,堂邑路,李村街,即墨路,港华大厦,港环路,馆陶街,普集路,朝阳街,甘肃广场,港夏街,港联路,陵县大厦,上海路,宝山广场,武定路,长清街,长安路,惠民街,武城广场,聊城大厦,海泊路,沧口街,宁波路,胶州广场,莱州路,招远街,冠县路,六码头,金乡广场,禹城街,临清路,东阿街,吴淞路,大港沿,辽宁路,棣纬二大厦,大港纬一路,贮水山支街,无棣纬一广场,大港纬三街,大港纬五路,大港纬四街,大港纬二路,无棣二大厦,吉林支路,大港四街,普集支路,无棣三街,黄台支广场,大港三街,无棣一路,贮水山大厦,泰山支路,大港一广场,无棣四路,大连支街,大港二路,锦州支街,德平广场,高苑大厦,长山路,乐陵街,临邑路,嫩江广场,合江路,大连街,博兴路,蒲台大厦,黄台广场,城阳街,临淄路,安邱街,临朐路,青城广场,商河路,热河大厦,济阳路,承德街,淄川广场,辽北街,阳信路,益都街,松江路,流亭大厦,吉林路,恒台街,包头路,无棣街,铁山广场,锦州街,桓台路,兴安大厦,邹平路,胶东广场,章丘路,丹东街,华阳路,青海街,泰山广场,周村大厦,四平路,台东西七街,台东东二路,台东东七广场,台东西二路,东五街,云门二路,芙蓉山村,延安二广场,云门一街,台东四路,台东一街,台东二路,杭州支广场,内蒙古路,台东七大厦,台东六路,广饶支街,台东八广场,台东三街,四平支路,郭口东街,青海支路,沈阳支大厦,菜市二路,菜市一街,北仲三路,瑞云街,滨县广场,庆祥街,万寿路,大成大厦,芙蓉路,历城广场,大名路,昌平街,平定路,长兴街,浦口广场,诸城大厦,和兴路,德盛街,宁海路,威海广场,东山路,清和街,姜沟路,雒口大厦,松山广场,长春街,昆明路,顺兴街,利津路,阳明广场,人和路,郭口大厦,营口路,昌邑街,孟庄广场,丰盛街,埕口路,丹阳街,汉口路,洮南大厦,桑梓路,沾化街,山口路,沈阳街,南口广场,振兴街,通化路,福寺大厦,峄县路,寿光广场,曹县路,昌乐街,道口路,南九水街,台湛广场,东光大厦,驼峰路,太平山,标山路,云溪广场,太清路 \ No newline at end of file diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/test-resources/data/city.min.json b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/test-resources/data/city.min.json deleted file mode 100644 index 9c7015df77..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/test-resources/data/city.min.json +++ /dev/null @@ -1 +0,0 @@ -{"citylist":[{"p":"北京市","c":[{"n":"东城区"},{"n":"西城区"},{"n":"崇文区"},{"n":"宣武区"},{"n":"朝阳区"},{"n":"丰台区"},{"n":"石景山区"},{"n":"海淀区"},{"n":"门头沟区"},{"n":"房山区"},{"n":"通州区"},{"n":"顺义区"},{"n":"昌平区"},{"n":"大兴区"},{"n":"平谷区"},{"n":"怀柔区"},{"n":"密云县"},{"n":"延庆县"}]},{"p":"天津市","c":[{"n":"和平区"},{"n":"河东区"},{"n":"河西区"},{"n":"南开区"},{"n":"河北区"},{"n":"红挢区"},{"n":"滨海新区"},{"n":"东丽区"},{"n":"西青区"},{"n":"津南区"},{"n":"北辰区"},{"n":"宁河区"},{"n":"武清区"},{"n":"静海县"},{"n":"宝坻区"},{"n":"蓟县"}]},{"p":"河北省","c":[{"n":"石家庄","a":[{"s":"长安区"},{"s":"桥东区"},{"s":"桥西区"},{"s":"新华区"},{"s":"井陉矿区"},{"s":"裕华区"},{"s":"井陉县"},{"s":"正定县"},{"s":"栾城县"},{"s":"行唐县"},{"s":"灵寿县"},{"s":"高邑县"},{"s":"深泽县"},{"s":"赞皇县"},{"s":"无极县"},{"s":"平山县"},{"s":"元氏县"},{"s":"赵县"},{"s":"辛集市"},{"s":"藁城市"},{"s":"晋州市"},{"s":"新乐市"},{"s":"鹿泉市"}]},{"n":"唐山","a":[{"s":"路南区"},{"s":"路北区"},{"s":"古冶区"},{"s":"开平区"},{"s":"丰南区"},{"s":"丰润区"},{"s":"滦县"},{"s":"滦南县"},{"s":"乐亭县"},{"s":"迁西县"},{"s":"玉田县"},{"s":"唐海县"},{"s":"遵化市"},{"s":"迁安市"}]},{"n":"秦皇岛","a":[{"s":"海港区"},{"s":"山海关区"},{"s":"北戴河区"},{"s":"青龙满族自治县"},{"s":"昌黎县"},{"s":"抚宁县"},{"s":"卢龙县"}]},{"n":"邯郸","a":[{"s":"邯山区"},{"s":"丛台区"},{"s":"复兴区"},{"s":"峰峰矿区"},{"s":"邯郸县"},{"s":"临漳县"},{"s":"成安县"},{"s":"大名县"},{"s":"涉县"},{"s":"磁县"},{"s":"肥乡县"},{"s":"永年县"},{"s":"邱县"},{"s":"鸡泽县"},{"s":"广平县"},{"s":"馆陶县"},{"s":"魏县"},{"s":"曲周县"},{"s":"武安市"}]},{"n":"邢台","a":[{"s":"桥东区"},{"s":"桥西区"},{"s":"邢台县"},{"s":"临城县"},{"s":"内丘县"},{"s":"柏乡县"},{"s":"隆尧县"},{"s":"任县"},{"s":"南和县"},{"s":"宁晋县"},{"s":"巨鹿县"},{"s":"新河县"},{"s":"广宗县"},{"s":"平乡县"},{"s":"威县"},{"s":"清河县"},{"s":"临西县"},{"s":"南宫市"},{"s":"沙河市"}]},{"n":"保定","a":[{"s":"新市区"},{"s":"北市区"},{"s":"南市区"},{"s":"满城县"},{"s":"清苑县"},{"s":"涞水县"},{"s":"阜平县"},{"s":"徐水县"},{"s":"定兴县"},{"s":"唐县"},{"s":"高阳县"},{"s":"容城县"},{"s":"涞源县"},{"s":"望都县"},{"s":"安新县"},{"s":"易县"},{"s":"曲阳县"},{"s":"蠡县"},{"s":"顺平县"},{"s":"博野县"},{"s":"雄县"},{"s":"涿州市"},{"s":"定州市"},{"s":"安国市"},{"s":"高碑店市"}]},{"n":"张家口","a":[{"s":"桥东区"},{"s":"桥西区"},{"s":"宣化区"},{"s":"下花园区"},{"s":"宣化县"},{"s":"张北县"},{"s":"康保县"},{"s":"沽源县"},{"s":"尚义县"},{"s":"蔚县"},{"s":"阳原县"},{"s":"怀安县"},{"s":"万全县"},{"s":"怀来县"},{"s":"涿鹿县"},{"s":"赤城县"},{"s":"崇礼县"}]},{"n":"承德","a":[{"s":"双桥区"},{"s":"双滦区"},{"s":"鹰手营子矿区"},{"s":"承德县"},{"s":"兴隆县"},{"s":"平泉县"},{"s":"滦平县"},{"s":"隆化县"},{"s":"丰宁满族自治县"},{"s":"宽城满族自治县"},{"s":"围场满族蒙古族自治县"}]},{"n":"沧州","a":[{"s":"新华区"},{"s":"运河区"},{"s":"沧县"},{"s":"青县"},{"s":"东光县"},{"s":"海兴县"},{"s":"盐山县"},{"s":"肃宁县"},{"s":"南皮县"},{"s":"吴桥县"},{"s":"献县"},{"s":"孟村回族自治县"},{"s":"泊头市"},{"s":"任丘市"},{"s":"黄骅市"},{"s":"河间市"}]},{"n":"廊坊","a":[{"s":"安次区"},{"s":"广阳区"},{"s":"固安县"},{"s":"永清县"},{"s":"香河县"},{"s":"大城县"},{"s":"文安县"},{"s":"大厂回族自治县"},{"s":"霸州市"},{"s":"三河市"}]},{"n":"衡水","a":[{"s":"桃城区"},{"s":"枣强县"},{"s":"武邑县"},{"s":"武强县"},{"s":"饶阳县"},{"s":"安平县"},{"s":"故城县"},{"s":"景县"},{"s":"阜城县"},{"s":"冀州市"},{"s":"深州市"}]}]},{"p":"山西省","c":[{"n":"太原","a":[{"s":"小店区"},{"s":"迎泽区"},{"s":"杏花岭区"},{"s":"尖草坪区"},{"s":"万柏林区"},{"s":"晋源区"},{"s":"清徐县"},{"s":"阳曲县"},{"s":"娄烦县"},{"s":"古交市"}]},{"n":"大同","a":[{"s":"城区"},{"s":"矿区"},{"s":"南郊区"},{"s":"新荣区"},{"s":"阳高县"},{"s":"天镇县"},{"s":"广灵县"},{"s":"灵丘县"},{"s":"浑源县"},{"s":"左云县"},{"s":"大同县"}]},{"n":"阳泉","a":[{"s":"城区"},{"s":"矿区"},{"s":"郊区"},{"s":"平定县"},{"s":"盂县"}]},{"n":"长治","a":[{"s":"城区"},{"s":"郊区"},{"s":"长治县"},{"s":"襄垣县"},{"s":"屯留县"},{"s":"平顺县"},{"s":"黎城县"},{"s":"壶关县"},{"s":"长子县"},{"s":"武乡县"},{"s":"沁县"},{"s":"沁源县"},{"s":"潞城市"}]},{"n":"晋城","a":[{"s":"城区"},{"s":"沁水县"},{"s":"阳城县"},{"s":"陵川县"},{"s":"泽州县"},{"s":"高平市"}]},{"n":"朔州","a":[{"s":"朔城区"},{"s":"平鲁区"},{"s":"山阴县"},{"s":"应县"},{"s":"右玉县"},{"s":"怀仁县"}]},{"n":"晋中","a":[{"s":"榆次区"},{"s":"榆社县"},{"s":"左权县"},{"s":"和顺县"},{"s":"昔阳县"},{"s":"寿阳县"},{"s":"太谷县"},{"s":"祁县"},{"s":"平遥县"},{"s":"灵石县"},{"s":"介休市"}]},{"n":"运城","a":[{"s":"盐湖区"},{"s":"临猗县"},{"s":"万荣县"},{"s":"闻喜县"},{"s":"稷山县"},{"s":"新绛县"},{"s":"绛县"},{"s":"垣曲县"},{"s":"夏县"},{"s":"平陆县"},{"s":"芮城县"},{"s":"永济市"},{"s":"河津市"}]},{"n":"忻州","a":[{"s":"忻府区"},{"s":"定襄县"},{"s":"五台县"},{"s":"代县"},{"s":"繁峙县"},{"s":"宁武县"},{"s":"静乐县"},{"s":"神池县"},{"s":"五寨县"},{"s":"岢岚县"},{"s":"河曲县"},{"s":"保德县"},{"s":"偏关县"},{"s":"原平市"}]},{"n":"临汾","a":[{"s":"尧都区"},{"s":"曲沃县"},{"s":"翼城县"},{"s":"襄汾县"},{"s":"洪洞县"},{"s":"古县"},{"s":"安泽县"},{"s":"浮山县"},{"s":"吉县"},{"s":"乡宁县"},{"s":"大宁县"},{"s":"隰县"},{"s":"永和县"},{"s":"蒲县"},{"s":"汾西县"},{"s":"侯马市"},{"s":"霍州市"}]},{"n":"吕梁","a":[{"s":"离石区"},{"s":"文水县"},{"s":"交城县"},{"s":"兴县"},{"s":"临县"},{"s":"柳林县"},{"s":"石楼县"},{"s":"岚县"},{"s":"方山县"},{"s":"中阳县"},{"s":"交口县"},{"s":"孝义市"},{"s":"汾阳市"}]}]},{"p":"内蒙古","c":[{"n":"呼和浩特","a":[{"s":"新城区"},{"s":"回民区"},{"s":"玉泉区"},{"s":"玉泉区"},{"s":"赛罕区"},{"s":"土默特左旗"},{"s":"托克托县"},{"s":"和林格尔县"},{"s":"清水河县"},{"s":"武川县"}]},{"n":"包头","a":[{"s":"东河区"},{"s":"昆都仑区"},{"s":"青山区"},{"s":"石拐区"},{"s":"白云矿区"},{"s":"九原区"},{"s":"土默特右旗"},{"s":"固阳县"},{"s":"达尔罕茂明安联合旗"}]},{"n":"乌海","a":[{"s":"海勃湾区"},{"s":"海南区"},{"s":"乌达区"}]},{"n":"赤峰","a":[{"s":"红山区"},{"s":"元宝山区"},{"s":"松山区"},{"s":"阿鲁科尔沁旗"},{"s":"巴林左旗"},{"s":"巴林右旗"},{"s":"林西县"},{"s":"克什克腾旗"},{"s":"翁牛特旗"},{"s":"喀喇沁旗"},{"s":"宁城县"},{"s":"敖汉旗"}]},{"n":"通辽","a":[{"s":"科尔沁区"},{"s":"科尔沁左翼中旗"},{"s":"科尔沁左翼后旗"},{"s":"开鲁县"},{"s":"库伦旗"},{"s":"奈曼旗"},{"s":"扎鲁特旗"},{"s":"霍林郭勒市"}]},{"n":"鄂尔多斯","a":[{"s":"东胜区"},{"s":"达拉特旗"},{"s":"准格尔旗"},{"s":"鄂托克前旗"},{"s":"鄂托克旗"},{"s":"杭锦旗"},{"s":"乌审旗"},{"s":"伊金霍洛旗"}]},{"n":"呼伦贝尔","a":[{"s":"海拉尔区"},{"s":"阿荣旗"},{"s":"莫力达瓦达斡尔族自治旗"},{"s":"鄂伦春自治旗"},{"s":"鄂温克族自治旗"},{"s":"陈巴尔虎旗"},{"s":"新巴尔虎左旗"},{"s":"新巴尔虎右旗"},{"s":"满洲里市"},{"s":"牙克石市"},{"s":"扎兰屯市"},{"s":"额尔古纳市"},{"s":"根河市"}]},{"n":"巴彦淖尔","a":[{"s":"临河区"},{"s":"五原县"},{"s":"磴口县"},{"s":"乌拉特前旗"},{"s":"乌拉特中旗"},{"s":"乌拉特后旗"},{"s":"杭锦后旗"}]},{"n":"乌兰察布","a":[{"s":"集宁区"},{"s":"卓资县"},{"s":"化德县"},{"s":"商都县"},{"s":"兴和县"},{"s":"凉城县"},{"s":"察哈尔右翼前旗"},{"s":"察哈尔右翼中旗"},{"s":"察哈尔右翼后旗"},{"s":"四子王旗"},{"s":"丰镇市"}]},{"n":"兴安","a":[{"s":"乌兰浩特市"},{"s":"阿尔山市"},{"s":"科尔沁右翼前旗"},{"s":"科尔沁右翼中旗"},{"s":"扎赉特旗"},{"s":"突泉县"}]},{"n":"锡林郭勒","a":[{"s":"二连浩特市"},{"s":"锡林浩特市"},{"s":"阿巴嘎旗"},{"s":"苏尼特左旗"},{"s":"苏尼特右旗"},{"s":"东乌珠穆沁旗"},{"s":"西乌珠穆沁旗"},{"s":"太仆寺旗"},{"s":"镶黄旗"},{"s":"正镶白旗"},{"s":"正蓝旗"},{"s":"多伦县"}]},{"n":"阿拉善","a":[{"s":"阿拉善左旗"},{"s":"阿拉善右旗"},{"s":"额济纳旗"}]}]},{"p":"辽宁省","c":[{"n":"沈阳","a":[{"s":"和平区"},{"s":"沈河区"},{"s":"大东区"},{"s":"皇姑区"},{"s":"铁西区"},{"s":"苏家屯区"},{"s":"东陵区"},{"s":"新城子区"},{"s":"于洪区"},{"s":"辽中县"},{"s":"康平县"},{"s":"法库县"},{"s":"新民市"}]},{"n":"大连","a":[{"s":"中山区"},{"s":"西岗区"},{"s":"沙河口区"},{"s":"甘井子区"},{"s":"旅顺口区"},{"s":"金州区"},{"s":"长海县"},{"s":"瓦房店市"},{"s":"普兰店市"},{"s":"庄河市"}]},{"n":"鞍山","a":[{"s":"铁东区"},{"s":"铁西区"},{"s":"立山区"},{"s":"千山区"},{"s":"台安县"},{"s":"210323"},{"s":"海城市"}]},{"n":"抚顺","a":[{"s":"新抚区"},{"s":"东洲区"},{"s":"望花区"},{"s":"顺城区"},{"s":"抚顺县"},{"s":"新宾满族自治县"},{"s":"清原满族自治县"}]},{"n":"本溪","a":[{"s":"平山区"},{"s":"溪湖区"},{"s":"明山区"},{"s":"南芬区"},{"s":"本溪满族自治县"},{"s":"桓仁满族自治县"}]},{"n":"丹东","a":[{"s":"元宝区"},{"s":"振兴区"},{"s":"振安区"},{"s":"宽甸满族自治县"},{"s":"东港市"},{"s":"凤城市"}]},{"n":"锦州","a":[{"s":"古塔区"},{"s":"凌河区"},{"s":"太和区"},{"s":"黑山县"},{"s":"义县"},{"s":"凌海市"},{"s":"北镇市"}]},{"n":"营口","a":[{"s":"站前区"},{"s":"西市区"},{"s":"鲅鱼圈区"},{"s":"老边区"},{"s":"盖州市"},{"s":"大石桥市"}]},{"n":"阜新","a":[{"s":"海州区"},{"s":"新邱区"},{"s":"太平区"},{"s":"清河门区"},{"s":"细河区"},{"s":"阜新蒙古族自治县"},{"s":"彰武县"}]},{"n":"辽阳","a":[{"s":"白塔区"},{"s":"文圣区"},{"s":"宏伟区"},{"s":"弓长岭区"},{"s":"太子河区"},{"s":"辽阳县"},{"s":"灯塔市"}]},{"n":"盘锦","a":[{"s":"双台子区"},{"s":"兴隆台区"},{"s":"大洼县"},{"s":"盘山县"}]},{"n":"铁岭","a":[{"s":"银州区"},{"s":"清河区"},{"s":"铁岭县"},{"s":"西丰县"},{"s":"昌图县"},{"s":"调兵山市"},{"s":"开原市"}]},{"n":"朝阳","a":[{"s":"双塔区"},{"s":"龙城区"},{"s":"朝阳县"},{"s":"建平县"},{"s":"喀喇沁左翼蒙古族自治县"},{"s":"北票市"},{"s":"凌源市"}]},{"n":"葫芦岛","a":[{"s":"连山区"},{"s":"龙港区"},{"s":"南票区"},{"s":"绥中县"},{"s":"建昌县"},{"s":"兴城市"}]}]},{"p":"吉林省","c":[{"n":"长春","a":[{"s":"南关区"},{"s":"宽城区"},{"s":"朝阳区"},{"s":"二道区"},{"s":"绿园区"},{"s":"双阳区"},{"s":"农安县"},{"s":"九台市"},{"s":"榆树市"},{"s":"德惠市"}]},{"n":"吉林","a":[{"s":"昌邑区"},{"s":"龙潭区"},{"s":"船营区"},{"s":"丰满区"},{"s":"永吉县"},{"s":"蛟河市"},{"s":"桦甸市"},{"s":"舒兰市"},{"s":"磐石市"}]},{"n":"四平","a":[{"s":"铁西区"},{"s":"铁东区"},{"s":"梨树县"},{"s":"伊通满族自治县"},{"s":"公主岭市"},{"s":"双辽市"}]},{"n":"辽源","a":[{"s":"龙山区"},{"s":"西安区"},{"s":"东丰县"},{"s":"东辽县"}]},{"n":"通化","a":[{"s":"东昌区"},{"s":"二道江区"},{"s":"通化县"},{"s":"辉南县"},{"s":"柳河县"},{"s":"梅河口市"},{"s":"集安市"}]},{"n":"白山","a":[{"s":"八道江区"},{"s":"江源区"},{"s":"抚松县"},{"s":"靖宇县"},{"s":"长白朝鲜族自治县"},{"s":"临江市"}]},{"n":"松原","a":[{"s":"宁江区"},{"s":"前郭尔罗斯蒙古族自治县"},{"s":"长岭县"},{"s":"乾安县"},{"s":"扶余县"}]},{"n":"白城","a":[{"s":"洮北区"},{"s":"镇赉县"},{"s":"通榆县"},{"s":"洮南市"},{"s":"大安市"}]},{"n":"延边","a":[{"s":"延吉市"},{"s":"图们市"},{"s":"敦化市"},{"s":"珲春市"},{"s":"龙井市"},{"s":"和龙市"},{"s":"汪清县"},{"s":"安图县"}]}]},{"p":"黑龙江省","c":[{"n":"哈尔滨","a":[{"s":"道里区"},{"s":"南岗区"},{"s":"道外区"},{"s":"平房区"},{"s":"松北区"},{"s":"香坊区"},{"s":"呼兰区"},{"s":"阿城区"},{"s":"依兰县"},{"s":"方正县"},{"s":"宾县"},{"s":"巴彦县"},{"s":"木兰县"},{"s":"通河县"},{"s":"延寿县"},{"s":"双城市"},{"s":"尚志市"},{"s":"五常市"}]},{"n":"齐齐哈尔","a":[{"s":"龙沙区"},{"s":"建华区"},{"s":"铁锋区"},{"s":"昂昂溪区"},{"s":"富拉尔基区"},{"s":"碾子山区"},{"s":"梅里斯达斡尔族区"},{"s":"龙江县"},{"s":"依安县"},{"s":"泰来县"},{"s":"甘南县"},{"s":"富裕县"},{"s":"克山县"},{"s":"克东县"},{"s":"拜泉县"},{"s":"讷河市"}]},{"n":"鸡西","a":[{"s":"鸡冠区"},{"s":"恒山区"},{"s":"滴道区"},{"s":"梨树区"},{"s":"城子河区"},{"s":"麻山区"},{"s":"鸡东县"},{"s":"虎林市"},{"s":"密山市"}]},{"n":"鹤岗","a":[{"s":"向阳区"},{"s":"工农区"},{"s":"南山区"},{"s":"兴安区"},{"s":"东山区"},{"s":"兴山区"},{"s":"萝北县"},{"s":"绥滨县"}]},{"n":"双鸭山","a":[{"s":"尖山区"},{"s":"岭东区"},{"s":"四方台区"},{"s":"宝山区"},{"s":"集贤县"},{"s":"友谊县"},{"s":"宝清县"},{"s":"饶河县"}]},{"n":"大庆","a":[{"s":"萨尔图区"},{"s":"龙凤区"},{"s":"让胡路区"},{"s":"红岗区"},{"s":"大同区"},{"s":"肇州县"},{"s":"肇源县"},{"s":"林甸县"},{"s":"杜尔伯特蒙古族自治县"}]},{"n":"伊春","a":[{"s":"伊春区"},{"s":"南岔区"},{"s":"友好区"},{"s":"西林区"},{"s":"翠峦区"},{"s":"新青区"},{"s":"美溪区"},{"s":"金山屯区"},{"s":"五营区"},{"s":"乌马河区"},{"s":"汤旺河区"},{"s":"带岭区"},{"s":"乌伊岭区"},{"s":"红星区"},{"s":"上甘岭区"},{"s":"嘉荫县"},{"s":"铁力市"}]},{"n":"佳木斯","a":[{"s":"向阳区"},{"s":"前进区"},{"s":"东风区"},{"s":"郊区"},{"s":"桦南县"},{"s":"桦川县"},{"s":"汤原县"},{"s":"抚远县"},{"s":"同江市"},{"s":"富锦市"}]},{"n":"七台河","a":[{"s":"新兴区"},{"s":"桃山区"},{"s":"茄子河区"},{"s":"勃利县"}]},{"n":"牡丹江","a":[{"s":"东安区"},{"s":"阳明区"},{"s":"爱民区"},{"s":"西安区"},{"s":"东宁县"},{"s":"林口县"},{"s":"绥芬河市"},{"s":"海林市"},{"s":"宁安市"},{"s":"穆棱市"}]},{"n":"黑河","a":[{"s":"爱辉区"},{"s":"嫩江县"},{"s":"逊克县"},{"s":"孙吴县"},{"s":"北安市"},{"s":"五大连池市"}]},{"n":"绥化","a":[{"s":"北林区"},{"s":"望奎县"},{"s":"兰西县"},{"s":"青冈县"},{"s":"庆安县"},{"s":"明水县"},{"s":"绥棱县"},{"s":"安达市"},{"s":"肇东市"},{"s":"海伦市"}]},{"n":"大兴安岭","a":[{"s":"加格达奇区"},{"s":"松岭区"},{"s":"新林区"},{"s":"呼中区"},{"s":"呼玛县"},{"s":"塔河县"},{"s":"漠河县"}]}]},{"p":"上海市","c":[{"n":"黄浦区"},{"n":"卢湾区"},{"n":"徐汇区"},{"n":"长宁区"},{"n":"静安区"},{"n":"普陀区"},{"n":"闸北区"},{"n":"虹口区"},{"n":"杨浦区"},{"n":"闵行区"},{"n":"宝山区"},{"n":"嘉定区"},{"n":"浦东新区"},{"n":"金山区"},{"n":"松江区"},{"n":"奉贤区"},{"n":"青浦区"},{"n":"崇明县"}]},{"p":"江苏省","c":[{"n":"南京","a":[{"s":"玄武区"},{"s":"白下区"},{"s":"秦淮区"},{"s":"建邺区"},{"s":"鼓楼区"},{"s":"下关区"},{"s":"浦口区"},{"s":"栖霞区"},{"s":"雨花台区"},{"s":"江宁区"},{"s":"六合区"},{"s":"溧水县"},{"s":"高淳县"}]},{"n":"无锡","a":[{"s":"崇安区"},{"s":"南长区"},{"s":"北塘区"},{"s":"锡山区"},{"s":"惠山区"},{"s":"滨湖区"},{"s":"江阴市"},{"s":"宜兴市"}]},{"n":"徐州","a":[{"s":"鼓楼区"},{"s":"云龙区"},{"s":"九里区"},{"s":"贾汪区"},{"s":"泉山区"},{"s":"丰县"},{"s":"沛县"},{"s":"铜山县"},{"s":"睢宁县"},{"s":"新沂市"},{"s":"邳州市"}]},{"n":"常州","a":[{"s":"天宁区"},{"s":"钟楼区"},{"s":"戚墅堰区"},{"s":"新北区"},{"s":"武进区"},{"s":"溧阳市"},{"s":"金坛市"}]},{"n":"苏州","a":[{"s":"沧浪区"},{"s":"平江区"},{"s":"金阊区"},{"s":"虎丘区"},{"s":"吴中区"},{"s":"相城区"},{"s":"常熟市"},{"s":"张家港市"},{"s":"昆山市"},{"s":"吴江市"},{"s":"太仓市"}]},{"n":"南通","a":[{"s":"崇川区"},{"s":"港闸区"},{"s":"海安县"},{"s":"如东县"},{"s":"启东市"},{"s":"如皋市"},{"s":"通州市"},{"s":"海门市"}]},{"n":"连云港","a":[{"s":"连云区"},{"s":"新浦区"},{"s":"海州区"},{"s":"赣榆县"},{"s":"东海县"},{"s":"灌云县"},{"s":"灌南县"}]},{"n":"淮安","a":[{"s":"清河区"},{"s":"楚州区"},{"s":"淮阴区"},{"s":"清浦区"},{"s":"涟水县"},{"s":"洪泽县"},{"s":"盱眙县"},{"s":"金湖县"}]},{"n":"盐城","a":[{"s":"亭湖区"},{"s":"盐都区"},{"s":"响水县"},{"s":"滨海县"},{"s":"阜宁县"},{"s":"射阳县"},{"s":"建湖县"},{"s":"东台市"},{"s":"大丰市"}]},{"n":"扬州","a":[{"s":"广陵区"},{"s":"邗江区"},{"s":"维扬区"},{"s":"宝应县"},{"s":"仪征市"},{"s":"高邮市"},{"s":"江都市"}]},{"n":"镇江","a":[{"s":"京口区"},{"s":"润州区"},{"s":"丹徒区"},{"s":"丹阳市"},{"s":"扬中市"},{"s":"句容市"}]},{"n":"泰州","a":[{"s":"海陵区"},{"s":"高港区"},{"s":"兴化市"},{"s":"靖江市"},{"s":"泰兴市"},{"s":"姜堰市"}]},{"n":"宿迁","a":[{"s":"宿城区"},{"s":"宿豫区"},{"s":"沭阳县"},{"s":"泗阳县"},{"s":"泗洪县"}]}]},{"p":"浙江省","c":[{"n":"杭州","a":[{"s":"上城区"},{"s":"下城区"},{"s":"江干区"},{"s":"拱墅区"},{"s":"西湖区"},{"s":"滨江区"},{"s":"萧山区"},{"s":"余杭区"},{"s":"桐庐县"},{"s":"淳安县"},{"s":"建德市"},{"s":"富阳市"},{"s":"临安市"}]},{"n":"宁波","a":[{"s":"海曙区"},{"s":"江东区"},{"s":"江北区"},{"s":"北仑区"},{"s":"镇海区"},{"s":"鄞州区"},{"s":"象山县"},{"s":"宁海县"},{"s":"余姚市"},{"s":"慈溪市"},{"s":"奉化市"}]},{"n":"温州","a":[{"s":"鹿城区"},{"s":"龙湾区"},{"s":"瓯海区"},{"s":"洞头县"},{"s":"永嘉县"},{"s":"平阳县"},{"s":"苍南县"},{"s":"文成县"},{"s":"泰顺县"},{"s":"瑞安市"},{"s":"乐清市"}]},{"n":"嘉兴","a":[{"s":"南湖区"},{"s":"秀洲区"},{"s":"嘉善县"},{"s":"海盐县"},{"s":"海宁市"},{"s":"平湖市"},{"s":"桐乡市"}]},{"n":"湖州","a":[{"s":"吴兴区"},{"s":"南浔区"},{"s":"德清县"},{"s":"长兴县"},{"s":"安吉县"}]},{"n":"绍兴","a":[{"s":"越城区"},{"s":"绍兴县"},{"s":"新昌县"},{"s":"诸暨市"},{"s":"上虞市"},{"s":"嵊州市"}]},{"n":"金华","a":[{"s":"婺城区"},{"s":"金东区"},{"s":"武义县"},{"s":"浦江县"},{"s":"磐安县"},{"s":"兰溪市"},{"s":"义乌市"},{"s":"东阳市"},{"s":"永康市"}]},{"n":"衢州","a":[{"s":"柯城区"},{"s":"衢江区"},{"s":"常山县"},{"s":"开化县"},{"s":"龙游县"},{"s":"江山市"}]},{"n":"舟山","a":[{"s":"定海区"},{"s":"普陀区"},{"s":"岱山县"},{"s":"嵊泗县"}]},{"n":"台州","a":[{"s":"椒江区"},{"s":"黄岩区"},{"s":"路桥区"},{"s":"玉环县"},{"s":"三门县"},{"s":"天台县"},{"s":"仙居县"},{"s":"温岭市"},{"s":"临海市"}]},{"n":"丽水","a":[{"s":"莲都区"},{"s":"青田县"},{"s":"缙云县"},{"s":"遂昌县"},{"s":"松阳县"},{"s":"云和县"},{"s":"庆元县"},{"s":"景宁畲族自治县"},{"s":"龙泉市"}]}]},{"p":"安徽省","c":[{"n":"合肥","a":[{"s":"瑶海区"},{"s":"庐阳区"},{"s":"蜀山区"},{"s":"包河区"},{"s":"长丰县"},{"s":"肥东县"},{"s":"肥西县"}]},{"n":"芜湖","a":[{"s":"镜湖区"},{"s":"弋江区"},{"s":"鸠江区"},{"s":"三山区"},{"s":"芜湖县"},{"s":"繁昌县"},{"s":"南陵县"}]},{"n":"蚌埠","a":[{"s":"龙子湖区"},{"s":"蚌山区"},{"s":"禹会区"},{"s":"淮上区"},{"s":"怀远县"},{"s":"五河县"},{"s":"固镇县"}]},{"n":"淮南","a":[{"s":"大通区"},{"s":"田家庵区"},{"s":"谢家集区"},{"s":"八公山区"},{"s":"潘集区"},{"s":"凤台县"}]},{"n":"马鞍山","a":[{"s":"金家庄区"},{"s":"花山区"},{"s":"雨山区"},{"s":"当涂县"}]},{"n":"淮北","a":[{"s":"杜集区"},{"s":"相山区"},{"s":"烈山区"},{"s":"濉溪县"}]},{"n":"铜陵","a":[{"s":"铜官山区"},{"s":"狮子山区"},{"s":"郊区"},{"s":"铜陵县"}]},{"n":"安庆","a":[{"s":"迎江区"},{"s":"大观区"},{"s":"宜秀区"},{"s":"怀宁县"},{"s":"枞阳县"},{"s":"潜山县"},{"s":"太湖县"},{"s":"宿松县"},{"s":"望江县"},{"s":"岳西县"},{"s":"桐城市"}]},{"n":"黄山","a":[{"s":"屯溪区"},{"s":"黄山区"},{"s":"徽州区"},{"s":"歙县"},{"s":"休宁县"},{"s":"黟县"},{"s":"祁门县"}]},{"n":"滁州","a":[{"s":"琅琊区"},{"s":"南谯区"},{"s":"来安县"},{"s":"全椒县"},{"s":"定远县"},{"s":"凤阳县"},{"s":"天长市"},{"s":"明光市"}]},{"n":"阜阳","a":[{"s":"颍州区"},{"s":"颍东区"},{"s":"颍泉区"},{"s":"临泉县"},{"s":"太和县"},{"s":"阜南县"},{"s":"颍上县"},{"s":"界首市"}]},{"n":"宿州","a":[{"s":"埇桥区"},{"s":"砀山县"},{"s":"萧县"},{"s":"灵璧县"},{"s":"泗县"}]},{"n":"巢湖","a":[{"s":"居巢区"},{"s":"庐江县"},{"s":"无为县"},{"s":"含山县"},{"s":"和县"}]},{"n":"六安","a":[{"s":"金安区"},{"s":"裕安区"},{"s":"寿县"},{"s":"霍邱县"},{"s":"舒城县"},{"s":"金寨县"},{"s":"霍山县"}]},{"n":"亳州","a":[{"s":"谯城区"},{"s":"涡阳县"},{"s":"蒙城县"},{"s":"利辛县"}]},{"n":"池州","a":[{"s":"贵池区"},{"s":"东至县"},{"s":"石台县"},{"s":"青阳县"}]},{"n":"宣城","a":[{"s":"宣州区"},{"s":"郎溪县"},{"s":"广德县"},{"s":"泾县"},{"s":"绩溪县"},{"s":"旌德县"},{"s":"宁国市"}]}]},{"p":"福建省","c":[{"n":"福州","a":[{"s":"鼓楼区"},{"s":"台江区"},{"s":"仓山区"},{"s":"马尾区"},{"s":"晋安区"},{"s":"闽侯县"},{"s":"连江县"},{"s":"罗源县"},{"s":"闽清县"},{"s":"永泰县"},{"s":"平潭县"},{"s":"福清市"},{"s":"长乐市"}]},{"n":"厦门","a":[{"s":"思明区"},{"s":"海沧区"},{"s":"湖里区"},{"s":"集美区"},{"s":"同安区"},{"s":"翔安区"}]},{"n":"莆田","a":[{"s":"城厢区"},{"s":"涵江区"},{"s":"荔城区"},{"s":"秀屿区"},{"s":"仙游县"}]},{"n":"三明","a":[{"s":"梅列区"},{"s":"三元区"},{"s":"明溪县"},{"s":"清流县"},{"s":"宁化县"},{"s":"大田县"},{"s":"尤溪县"},{"s":"沙县"},{"s":"将乐县"},{"s":"泰宁县"},{"s":"建宁县"},{"s":"永安市"}]},{"n":"泉州","a":[{"s":"鲤城区"},{"s":"丰泽区"},{"s":"洛江区"},{"s":"泉港区"},{"s":"惠安县"},{"s":"安溪县"},{"s":"永春县"},{"s":"德化县"},{"s":"金门县"},{"s":"石狮市"},{"s":"晋江市"},{"s":"南安市"}]},{"n":"漳州","a":[{"s":"芗城区"},{"s":"龙文区"},{"s":"云霄县"},{"s":"漳浦县"},{"s":"诏安县"},{"s":"长泰县"},{"s":"东山县"},{"s":"南靖县"},{"s":"平和县"},{"s":"华安县"},{"s":"龙海市"}]},{"n":"南平","a":[{"s":"延平区"},{"s":"顺昌县"},{"s":"浦城县"},{"s":"光泽县"},{"s":"松溪县"},{"s":"政和县"},{"s":"邵武市"},{"s":"武夷山市"},{"s":"建瓯市"},{"s":"建阳市"}]},{"n":"龙岩","a":[{"s":"新罗区"},{"s":"长汀县"},{"s":"永定县"},{"s":"上杭县"},{"s":"武平县"},{"s":"连城县"},{"s":"漳平市"}]},{"n":"宁德","a":[{"s":"蕉城区"},{"s":"霞浦县"},{"s":"古田县"},{"s":"屏南县"},{"s":"寿宁县"},{"s":"周宁县"},{"s":"柘荣县"},{"s":"福安市"},{"s":"福鼎市"}]}]},{"p":"江西省","c":[{"n":"南昌","a":[{"s":"东湖区"},{"s":"西湖区"},{"s":"青云谱区"},{"s":"湾里区"},{"s":"青山湖区"},{"s":"南昌县"},{"s":"新建县"},{"s":"安义县"},{"s":"进贤县"}]},{"n":"景德镇","a":[{"s":"昌江区"},{"s":"珠山区"},{"s":"浮梁县"},{"s":"乐平市"}]},{"n":"萍乡","a":[{"s":"安源区"},{"s":"湘东区"},{"s":"莲花县"},{"s":"上栗县"},{"s":"芦溪县"}]},{"n":"九江","a":[{"s":"庐山区"},{"s":"浔阳区"},{"s":"九江县"},{"s":"武宁县"},{"s":"修水县"},{"s":"永修县"},{"s":"德安县"},{"s":"星子县"},{"s":"都昌县"},{"s":"湖口县"},{"s":"彭泽县"},{"s":"瑞昌市"}]},{"n":"新余","a":[{"s":"渝水区"},{"s":"分宜县"}]},{"n":"鹰潭","a":[{"s":"月湖区"},{"s":"余江县"},{"s":"贵溪市"}]},{"n":"赣州","a":[{"s":"章贡区"},{"s":"赣县"},{"s":"信丰县"},{"s":"大余县"},{"s":"上犹县"},{"s":"崇义县"},{"s":"安远县"},{"s":"龙南县"},{"s":"定南县"},{"s":"全南县"},{"s":"宁都县"},{"s":"于都县"},{"s":"兴国县"},{"s":"会昌县"},{"s":"寻乌县"},{"s":"石城县"},{"s":"瑞金市"},{"s":"南康市"}]},{"n":"吉安","a":[{"s":"吉州区"},{"s":"青原区"},{"s":"吉安县"},{"s":"吉水县"},{"s":"峡江县"},{"s":"新干县"},{"s":"永丰县"},{"s":"泰和县"},{"s":"遂川县"},{"s":"万安县"},{"s":"安福县"},{"s":"永新县"},{"s":"井冈山市"}]},{"n":"宜春","a":[{"s":"袁州区"},{"s":"奉新县"},{"s":"万载县"},{"s":"上高县"},{"s":"宜丰县"},{"s":"靖安县"},{"s":"铜鼓县"},{"s":"丰城市"},{"s":"樟树市"},{"s":"高安市"}]},{"n":"抚州","a":[{"s":"临川区"},{"s":"南城县"},{"s":"黎川县"},{"s":"南丰县"},{"s":"崇仁县"},{"s":"乐安县"},{"s":"宜黄县"},{"s":"金溪县"},{"s":"资溪县"},{"s":"东乡县"},{"s":"广昌县"}]},{"n":"上饶","a":[{"s":"信州区"},{"s":"上饶县"},{"s":"广丰县"},{"s":"玉山县"},{"s":"铅山县"},{"s":"横峰县"},{"s":"弋阳县"},{"s":"余干县"},{"s":"鄱阳县"},{"s":"万年县"},{"s":"婺源县"},{"s":"德兴市"}]}]},{"p":"山东省","c":[{"n":"济南","a":[{"s":"历下区"},{"s":"市中区"},{"s":"槐荫区"},{"s":"天桥区"},{"s":"历城区"},{"s":"长清区"},{"s":"平阴县"},{"s":"济阳县"},{"s":"商河县"},{"s":"章丘市"}]},{"n":"青岛","a":[{"s":"市南区"},{"s":"市北区"},{"s":"四方区"},{"s":"黄岛区"},{"s":"崂山区"},{"s":"李沧区"},{"s":"城阳区"},{"s":"胶州市"},{"s":"即墨市"},{"s":"平度市"},{"s":"胶南市"},{"s":"莱西市"}]},{"n":"淄博","a":[{"s":"淄川区"},{"s":"张店区"},{"s":"博山区"},{"s":"临淄区"},{"s":"周村区"},{"s":"桓台县"},{"s":"高青县"},{"s":"沂源县"}]},{"n":"枣庄","a":[{"s":"市中区"},{"s":"薛城区"},{"s":"峄城区"},{"s":"台儿庄区"},{"s":"山亭区"},{"s":"滕州市"}]},{"n":"东营","a":[{"s":"东营区"},{"s":"河口区"},{"s":"垦利县"},{"s":"利津县"},{"s":"广饶县"}]},{"n":"烟台","a":[{"s":"芝罘区"},{"s":"福山区"},{"s":"牟平区"},{"s":"莱山区"},{"s":"长岛县"},{"s":"龙口市"},{"s":"莱阳市"},{"s":"莱州市"},{"s":"蓬莱市"},{"s":"招远市"},{"s":"栖霞市"},{"s":"海阳市"}]},{"n":"潍坊","a":[{"s":"潍城区"},{"s":"寒亭区"},{"s":"坊子区"},{"s":"奎文区"},{"s":"临朐县"},{"s":"昌乐县"},{"s":"青州市"},{"s":"诸城市"},{"s":"寿光市"},{"s":"安丘市"},{"s":"高密市"},{"s":"昌邑市"}]},{"n":"济宁","a":[{"s":"市中区"},{"s":"任城区"},{"s":"微山县"},{"s":"鱼台县"},{"s":"金乡县"},{"s":"嘉祥县"},{"s":"汶上县"},{"s":"泗水县"},{"s":"梁山县"},{"s":"曲阜市"},{"s":"兖州市"},{"s":"邹城市"}]},{"n":"泰安","a":[{"s":"泰山区"},{"s":"岱岳区"},{"s":"宁阳县"},{"s":"东平县"},{"s":"新泰市"},{"s":"肥城市"}]},{"n":"威海","a":[{"s":"环翠区"},{"s":"文登市"},{"s":"荣成市"},{"s":"乳山市"}]},{"n":"日照","a":[{"s":"东港区"},{"s":"岚山区"},{"s":"五莲县"},{"s":"莒县"}]},{"n":"莱芜","a":[{"s":"莱城区"},{"s":"钢城区"}]},{"n":"临沂","a":[{"s":"兰山区"},{"s":"罗庄区"},{"s":"河东区"},{"s":"沂南县"},{"s":"郯城县"},{"s":"沂水县"},{"s":"苍山县"},{"s":"费县"},{"s":"平邑县"},{"s":"莒南县"},{"s":"蒙阴县"},{"s":"临沭县"}]},{"n":"德州","a":[{"s":"德城区"},{"s":"陵县"},{"s":"宁津县"},{"s":"庆云县"},{"s":"临邑县"},{"s":"齐河县"},{"s":"平原县"},{"s":"夏津县"},{"s":"武城县"},{"s":"乐陵市"},{"s":"禹城市"}]},{"n":"聊城","a":[{"s":"东昌府区"},{"s":"阳谷县"},{"s":"莘县"},{"s":"茌平县"},{"s":"东阿县"},{"s":"冠县"},{"s":"高唐县"},{"s":"临清市"}]},{"n":"滨州","a":[{"s":"滨城区"},{"s":"惠民县"},{"s":"阳信县"},{"s":"无棣县"},{"s":"沾化县"},{"s":"博兴县"},{"s":"邹平县"}]},{"n":"菏泽","a":[{"s":"牡丹区"},{"s":"曹县"},{"s":"单县"},{"s":"成武县"},{"s":"巨野县"},{"s":"郓城县"},{"s":"鄄城县"},{"s":"定陶县"},{"s":"东明县"}]}]},{"p":"河南省","c":[{"n":"郑州","a":[{"s":"中原区"},{"s":"二七区"},{"s":"管城回族区"},{"s":"金水区"},{"s":"上街区"},{"s":"惠济区"},{"s":"中牟县"},{"s":"巩义市"},{"s":"荥阳市"},{"s":"新密市"},{"s":"新郑市"},{"s":"登封市"}]},{"n":"开封","a":[{"s":"龙亭区"},{"s":"顺河回族区"},{"s":"鼓楼区"},{"s":"禹王台区"},{"s":"金明区"},{"s":"杞县"},{"s":"通许县"},{"s":"尉氏县"},{"s":"开封县"},{"s":"兰考县"}]},{"n":"洛阳","a":[{"s":"老城区"},{"s":"西工区"},{"s":"廛河回族区"},{"s":"涧西区"},{"s":"吉利区"},{"s":"洛龙区"},{"s":"孟津县"},{"s":"新安县"},{"s":"栾川县"},{"s":"嵩县"},{"s":"汝阳县"},{"s":"宜阳县"},{"s":"洛宁县"},{"s":"伊川县"},{"s":"偃师市"}]},{"n":"平顶山","a":[{"s":"新华区"},{"s":"卫东区"},{"s":"石龙区"},{"s":"湛河区"},{"s":"宝丰县"},{"s":"叶县"},{"s":"鲁山县"},{"s":"郏县"},{"s":"舞钢市"},{"s":"汝州市"}]},{"n":"安阳","a":[{"s":"文峰区"},{"s":"北关区"},{"s":"殷都区"},{"s":"龙安区"},{"s":"安阳县"},{"s":"汤阴县"},{"s":"滑县"},{"s":"内黄县"},{"s":"林州市"}]},{"n":"鹤壁","a":[{"s":"鹤山区"},{"s":"山城区"},{"s":"淇滨区"},{"s":"浚县"},{"s":"淇县"}]},{"n":"新乡","a":[{"s":"红旗区"},{"s":"卫滨区"},{"s":"凤泉区"},{"s":"牧野区"},{"s":"新乡县"},{"s":"获嘉县"},{"s":"原阳县"},{"s":"延津县"},{"s":"封丘县"},{"s":"长垣县"},{"s":"卫辉市"},{"s":"辉县市"}]},{"n":"焦作","a":[{"s":"解放区"},{"s":"中站区"},{"s":"马村区"},{"s":"山阳区"},{"s":"修武县"},{"s":"博爱县"},{"s":"武陟县"},{"s":"温县"},{"s":"沁阳市"},{"s":"孟州市"}]},{"n":"濮阳","a":[{"s":"华龙区"},{"s":"清丰县"},{"s":"南乐县"},{"s":"范县"},{"s":"台前县"},{"s":"濮阳县"}]},{"n":"许昌","a":[{"s":"魏都区"},{"s":"许昌县"},{"s":"鄢陵县"},{"s":"襄城县"},{"s":"禹州市"},{"s":"长葛市"}]},{"n":"漯河","a":[{"s":"源汇区"},{"s":"郾城区"},{"s":"召陵区"},{"s":"舞阳县"},{"s":"临颍县"}]},{"n":"三门峡","a":[{"s":"湖滨区"},{"s":"渑池县"},{"s":"陕县"},{"s":"卢氏县"},{"s":"义马市"},{"s":"灵宝市"}]},{"n":"南阳","a":[{"s":"宛城区"},{"s":"卧龙区"},{"s":"南召县"},{"s":"方城县"},{"s":"西峡县"},{"s":"镇平县"},{"s":"内乡县"},{"s":"淅川县"},{"s":"社旗县"},{"s":"唐河县"},{"s":"新野县"},{"s":"桐柏县"},{"s":"邓州市"}]},{"n":"商丘","a":[{"s":"梁园区"},{"s":"睢阳区"},{"s":"民权县"},{"s":"睢县"},{"s":"宁陵县"},{"s":"柘城县"},{"s":"虞城县"},{"s":"夏邑县"},{"s":"永城市"}]},{"n":"信阳","a":[{"s":"浉河区"},{"s":"平桥区"},{"s":"罗山县"},{"s":"光山县"},{"s":"新县"},{"s":"商城县"},{"s":"固始县"},{"s":"潢川县"},{"s":"淮滨县"},{"s":"息县"}]},{"n":"周口","a":[{"s":"川汇区"},{"s":"扶沟县"},{"s":"西华县"},{"s":"商水县"},{"s":"沈丘县"},{"s":"郸城县"},{"s":"淮阳县"},{"s":"太康县"},{"s":"鹿邑县"},{"s":"项城市"}]},{"n":"驻马店","a":[{"s":"驿城区"},{"s":"西平县"},{"s":"上蔡县"},{"s":"平舆县"},{"s":"正阳县"},{"s":"确山县"},{"s":"泌阳县"},{"s":"汝南县"},{"s":"遂平县"},{"s":"新蔡县"}]},{"n":"济源","a":[{"s":"济源"}]}]},{"p":"湖北省","c":[{"n":"武汉","a":[{"s":"江岸区"},{"s":"江汉区"},{"s":"硚口区"},{"s":"汉阳区"},{"s":"武昌区"},{"s":"青山区"},{"s":"洪山区"},{"s":"东西湖区"},{"s":"汉南区"},{"s":"蔡甸区"},{"s":"江夏区"},{"s":"黄陂区"},{"s":"新洲区"}]},{"n":"黄石","a":[{"s":"黄石港区"},{"s":"西塞山区"},{"s":"下陆区"},{"s":"铁山区"},{"s":"阳新县"},{"s":"大冶市"}]},{"n":"十堰","a":[{"s":"茅箭区"},{"s":"张湾区"},{"s":"郧县"},{"s":"郧西县"},{"s":"竹山县"},{"s":"竹溪县"},{"s":"房县"},{"s":"丹江口市"}]},{"n":"宜昌","a":[{"s":"西陵区"},{"s":"伍家岗区"},{"s":"点军区"},{"s":"猇亭区"},{"s":"夷陵区"},{"s":"远安县"},{"s":"兴山县"},{"s":"秭归县"},{"s":"长阳土家族自治县"},{"s":"五峰土家族自治县"},{"s":"宜都市"},{"s":"当阳市"},{"s":"枝江市"}]},{"n":"襄樊","a":[{"s":"襄城区"},{"s":"樊城区"},{"s":"襄阳区"},{"s":"南漳县"},{"s":"谷城县"},{"s":"保康县"},{"s":"老河口市"},{"s":"枣阳市"},{"s":"宜城市"}]},{"n":"鄂州","a":[{"s":"梁子湖区"},{"s":"华容区"},{"s":"鄂城区"}]},{"n":"荆门","a":[{"s":"东宝区"},{"s":"掇刀区"},{"s":"京山县"},{"s":"沙洋县"},{"s":"钟祥市"}]},{"n":"孝感","a":[{"s":"孝南区"},{"s":"孝昌县"},{"s":"大悟县"},{"s":"云梦县"},{"s":"应城市"},{"s":"安陆市"},{"s":"汉川市"}]},{"n":"荆州","a":[{"s":"沙市区"},{"s":"荆州区"},{"s":"公安县"},{"s":"监利县"},{"s":"江陵县"},{"s":"石首市"},{"s":"洪湖市"},{"s":"松滋市"}]},{"n":"黄冈","a":[{"s":"黄州区"},{"s":"团风县"},{"s":"红安县"},{"s":"罗田县"},{"s":"英山县"},{"s":"浠水县"},{"s":"蕲春县"},{"s":"黄梅县"},{"s":"麻城市"},{"s":"武穴市"}]},{"n":"咸宁","a":[{"s":"咸安区"},{"s":"嘉鱼县"},{"s":"通城县"},{"s":"崇阳县"},{"s":"通山县"},{"s":"赤壁市"}]},{"n":"随州","a":[{"s":"曾都区"},{"s":"随县"},{"s":"广水市"}]},{"n":"恩施","a":[{"s":"恩施市"},{"s":"利川市"},{"s":"建始县"},{"s":"巴东县"},{"s":"宣恩县"},{"s":"咸丰县"},{"s":"来凤县"},{"s":"鹤峰县"}]},{"n":"仙桃","a":[{"s":"仙桃"}]},{"n":"潜江","a":[{"s":"潜江"}]},{"n":"天门","a":[{"s":"天门"}]},{"n":"神农架","a":[{"s":"神农架"}]}]},{"p":"湖南省","c":[{"n":"长沙","a":[{"s":"芙蓉区"},{"s":"天心区"},{"s":"岳麓区"},{"s":"开福区"},{"s":"雨花区"},{"s":"长沙县"},{"s":"望城县"},{"s":"宁乡县"},{"s":"浏阳市"}]},{"n":"株洲","a":[{"s":"荷塘区"},{"s":"芦淞区"},{"s":"石峰区"},{"s":"天元区"},{"s":"株洲县"},{"s":"攸县"},{"s":"茶陵县"},{"s":"炎陵县"},{"s":"醴陵市"}]},{"n":"湘潭","a":[{"s":"雨湖区"},{"s":"岳塘区"},{"s":"湘潭县"},{"s":"湘乡市"},{"s":"韶山市"}]},{"n":"衡阳","a":[{"s":"珠晖区"},{"s":"雁峰区"},{"s":"石鼓区"},{"s":"蒸湘区"},{"s":"南岳区"},{"s":"衡阳县"},{"s":"衡南县"},{"s":"衡山县"},{"s":"衡东县"},{"s":"祁东县"},{"s":"耒阳市"},{"s":"常宁市"}]},{"n":"邵阳","a":[{"s":"双清区"},{"s":"大祥区"},{"s":"北塔区"},{"s":"邵东县"},{"s":"新邵县"},{"s":"邵阳县"},{"s":"隆回县"},{"s":"洞口县"},{"s":"绥宁县"},{"s":"新宁县"},{"s":"城步苗族自治县"},{"s":"武冈市"}]},{"n":"岳阳","a":[{"s":"岳阳楼区"},{"s":"云溪区"},{"s":"君山区"},{"s":"岳阳县"},{"s":"华容县"},{"s":"湘阴县"},{"s":"平江县"},{"s":"汨罗市"},{"s":"临湘市"}]},{"n":"常德","a":[{"s":"武陵区"},{"s":"鼎城区"},{"s":"安乡县"},{"s":"汉寿县"},{"s":"澧县"},{"s":"临澧县"},{"s":"桃源县"},{"s":"石门县"},{"s":"津市市"}]},{"n":"张家界","a":[{"s":"永定区"},{"s":"武陵源区"},{"s":"慈利县"},{"s":"桑植县"}]},{"n":"益阳","a":[{"s":"资阳区"},{"s":"赫山区"},{"s":"南县"},{"s":"桃江县"},{"s":"安化县"},{"s":"沅江市"}]},{"n":"郴州","a":[{"s":"北湖区"},{"s":"苏仙区"},{"s":"桂阳县"},{"s":"宜章县"},{"s":"永兴县"},{"s":"嘉禾县"},{"s":"临武县"},{"s":"汝城县"},{"s":"桂东县"},{"s":"安仁县"},{"s":"资兴市"}]},{"n":"永州","a":[{"s":"零陵区"},{"s":"冷水滩区"},{"s":"祁阳县"},{"s":"东安县"},{"s":"双牌县"},{"s":"道县"},{"s":"江永县"},{"s":"宁远县"},{"s":"蓝山县"},{"s":"新田县"},{"s":"江华瑶族自治县"}]},{"n":"怀化","a":[{"s":"鹤城区"},{"s":"中方县"},{"s":"沅陵县"},{"s":"辰溪县"},{"s":"溆浦县"},{"s":"会同县"},{"s":"麻阳苗族自治县"},{"s":"新晃侗族自治县"},{"s":"芷江侗族自治县"},{"s":"靖州苗族侗族自治县"},{"s":"通道侗族自治县"},{"s":"洪江市"}]},{"n":"娄底","a":[{"s":"娄星区"},{"s":"双峰县"},{"s":"新化县"},{"s":"冷水江市"},{"s":"涟源市"}]},{"n":"湘西","a":[{"s":"吉首市"},{"s":"泸溪县"},{"s":"凤凰县"},{"s":"花垣县"},{"s":"保靖县"},{"s":"古丈县"},{"s":"永顺县"},{"s":"龙山县"}]}]},{"p":"广东省","c":[{"n":"广州","a":[{"s":"荔湾区"},{"s":"越秀区"},{"s":"海珠区"},{"s":"天河区"},{"s":"白云区"},{"s":"黄埔区"},{"s":"番禺区"},{"s":"花都区"},{"s":"南沙区"},{"s":"萝岗区"},{"s":"增城市"},{"s":"从化市"}]},{"n":"韶关","a":[{"s":"武江区"},{"s":"浈江区"},{"s":"曲江区"},{"s":"始兴县"},{"s":"仁化县"},{"s":"翁源县"},{"s":"乳源瑶族自治县"},{"s":"新丰县"},{"s":"乐昌市"},{"s":"南雄市"}]},{"n":"深圳市","a":[{"s":"罗湖区"},{"s":"福田区"},{"s":"南山区"},{"s":"宝安区"},{"s":"龙岗区"},{"s":"盐田区"}]},{"n":"珠海","a":[{"s":"香洲区"},{"s":"斗门区"},{"s":"金湾区"}]},{"n":"汕头","a":[{"s":"龙湖区"},{"s":"金平区"},{"s":"濠江区"},{"s":"潮阳区"},{"s":"潮南区"},{"s":"澄海区"},{"s":"南澳县"}]},{"n":"佛山","a":[{"s":"禅城区"},{"s":"南海区"},{"s":"顺德区"},{"s":"三水区"},{"s":"高明区"}]},{"n":"江门","a":[{"s":"蓬江区"},{"s":"江海区"},{"s":"新会区"},{"s":"台山市"},{"s":"开平市"},{"s":"鹤山市"},{"s":"恩平市"}]},{"n":"湛江","a":[{"s":"赤坎区"},{"s":"霞山区"},{"s":"坡头区"},{"s":"麻章区"},{"s":"遂溪县"},{"s":"徐闻县"},{"s":"廉江市"},{"s":"雷州市"},{"s":"吴川市"}]},{"n":"茂名","a":[{"s":"茂南区"},{"s":"茂港区"},{"s":"电白县"},{"s":"高州市"},{"s":"化州市"},{"s":"信宜市"}]},{"n":"肇庆","a":[{"s":"端州区"},{"s":"鼎湖区"},{"s":"广宁县"},{"s":"怀集县"},{"s":"封开县"},{"s":"德庆县"},{"s":"高要市"},{"s":"四会市"}]},{"n":"惠州","a":[{"s":"惠城区"},{"s":"惠阳区"},{"s":"博罗县"},{"s":"惠东县"},{"s":"龙门县"}]},{"n":"梅州","a":[{"s":"梅江区"},{"s":"梅县"},{"s":"大埔县"},{"s":"丰顺县"},{"s":"五华县"},{"s":"平远县"},{"s":"蕉岭县"},{"s":"兴宁市"}]},{"n":"汕尾","a":[{"s":"城区"},{"s":"海丰县"},{"s":"陆河县"},{"s":"陆丰市"}]},{"n":"河源","a":[{"s":"源城区"},{"s":"紫金县"},{"s":"龙川县"},{"s":"连平县"},{"s":"和平县"},{"s":"东源县"}]},{"n":"阳江","a":[{"s":"江城区"},{"s":"阳西县"},{"s":"阳东县"},{"s":"阳春市"}]},{"n":"清远","a":[{"s":"清城区"},{"s":"佛冈县"},{"s":"阳山县"},{"s":"连山壮族瑶族自治县"},{"s":"连南瑶族自治县"},{"s":"清新县"},{"s":"英德市"},{"s":"连州市"}]},{"n":"东莞","a":[{"s":"东莞市"}]},{"n":"中山","a":[{"s":"中山市"}]},{"n":"潮州","a":[{"s":"湘桥区"},{"s":"潮安县"},{"s":"饶平县"}]},{"n":"揭阳","a":[{"s":"榕城区"},{"s":"揭东县"},{"s":"揭西县"},{"s":"惠来县"},{"s":"普宁市"}]},{"n":"云浮","a":[{"s":"云城区"},{"s":"新兴县"},{"s":"郁南县"},{"s":"云安县"},{"s":"罗定市"}]}]},{"p":"广西省","c":[{"n":"南宁","a":[{"s":"兴宁区"},{"s":"青秀区"},{"s":"江南区"},{"s":"西乡塘区"},{"s":"良庆区"},{"s":"邕宁区"},{"s":"武鸣县"},{"s":"隆安县"},{"s":"马山县"},{"s":"上林县"},{"s":"宾阳县"},{"s":"横县"}]},{"n":"柳州","a":[{"s":"城中区"},{"s":"鱼峰区"},{"s":"柳南区"},{"s":"柳北区"},{"s":"柳江县"},{"s":"柳城县"},{"s":"鹿寨县"},{"s":"融安县"},{"s":"融水苗族自治县"},{"s":"三江侗族自治县"}]},{"n":"桂林","a":[{"s":"秀峰区"},{"s":"叠彩区"},{"s":"象山区"},{"s":"七星区"},{"s":"雁山区"},{"s":"阳朔县"},{"s":"临桂县"},{"s":"灵川县"},{"s":"全州县"},{"s":"兴安县"},{"s":"永福县"},{"s":"灌阳县"},{"s":"龙胜各族自治县"},{"s":"资源县"},{"s":"平乐县"},{"s":"荔蒲县"},{"s":"恭城瑶族自治县"}]},{"n":"梧州","a":[{"s":"万秀区"},{"s":"蝶山区"},{"s":"长洲区"},{"s":"苍梧县"},{"s":"藤县"},{"s":"蒙山县"},{"s":"岑溪市"}]},{"n":"北海","a":[{"s":"海城区"},{"s":"银海区"},{"s":"铁山港区"},{"s":"合浦县"}]},{"n":"防城港","a":[{"s":"港口区"},{"s":"防城区"},{"s":"上思县"},{"s":"东兴市"}]},{"n":"钦州","a":[{"s":"钦南区"},{"s":"钦北区"},{"s":"灵山县"},{"s":"浦北县"}]},{"n":"贵港","a":[{"s":"港北区"},{"s":"港南区"},{"s":"覃塘区"},{"s":"平南县"},{"s":"桂平市"}]},{"n":"玉林","a":[{"s":"玉州区"},{"s":"容县"},{"s":"陆川县"},{"s":"博白县"},{"s":"兴业县"},{"s":"北流市"}]},{"n":"百色","a":[{"s":"右江区"},{"s":"田阳县"},{"s":"田东县"},{"s":"平果县"},{"s":"德保县"},{"s":"靖西县"},{"s":"那坡县"},{"s":"凌云县"},{"s":"乐业县"},{"s":"田林县"},{"s":"西林县"},{"s":"隆林各族自治县"}]},{"n":"贺州","a":[{"s":"八步区"},{"s":"昭平县"},{"s":"钟山县"},{"s":"富川瑶族自治县"}]},{"n":"河池","a":[{"s":"金城江区"},{"s":"南丹县"},{"s":"天峨县"},{"s":"凤山县"},{"s":"东兰县"},{"s":"罗城仫佬族自治县"},{"s":"环江毛南族自治县"},{"s":"巴马瑶族自治县"},{"s":"都安瑶族自治县"},{"s":"大化瑶族自治县"},{"s":"宜州市"}]},{"n":"来宾","a":[{"s":"兴宾区"},{"s":"忻城县"},{"s":"象州县"},{"s":"武宣县"},{"s":"金秀瑶族自治县"},{"s":"合山市"}]},{"n":"崇左","a":[{"s":"江洲区"},{"s":"扶绥县"},{"s":"宁明县"},{"s":"龙州县"},{"s":"大新县"},{"s":"天等县"},{"s":"凭祥市"}]}]},{"p":"海南省","c":[{"n":"海口","a":[{"s":"秀英区"},{"s":"龙华区"},{"s":"琼山区"},{"s":"美兰区"}]},{"n":"三亚","a":[{"s":"三亚市"}]},{"n":"五指山","a":[{"s":"五指山"}]},{"n":"琼海","a":[{"s":"琼海"}]},{"n":"儋州","a":[{"s":"儋州"}]},{"n":"文昌","a":[{"s":"文昌"}]},{"n":"万宁","a":[{"s":"万宁"}]},{"n":"东方","a":[{"s":"东方"}]}]},{"p":"重庆市","c":[{"n":"万州区"},{"n":"涪陵区"},{"n":"渝中区"},{"n":"大渡口区"},{"n":"江北区"},{"n":"沙坪坝区"},{"n":"九龙坡区"},{"n":"南岸区"},{"n":"北碚区"},{"n":"万盛区"},{"n":"双挢区"},{"n":"渝北区"},{"n":"巴南区"},{"n":"长寿区"},{"n":"綦江县"},{"n":"潼南县"},{"n":"铜梁县"},{"n":"大足县"},{"n":"荣昌县"},{"n":"壁山县"},{"n":"梁平县"},{"n":"城口县"},{"n":"丰都县"},{"n":"垫江县"},{"n":"武隆县"},{"n":"忠县"},{"n":"开县"},{"n":"云阳县"},{"n":"奉节县"},{"n":"巫山县"},{"n":"巫溪县"},{"n":"黔江区"},{"n":"石柱土家族自治县"},{"n":"秀山土家族苗族自治县"},{"n":"酉阳土家族苗族自治县"},{"n":"彭水苗族土家族自治县"},{"n":"江津区"},{"n":"合川区"},{"n":"永川区"},{"n":"南川区"}]},{"p":"四川省","c":[{"n":"成都","a":[{"s":"锦江区"},{"s":"青羊区"},{"s":"金牛区"},{"s":"武侯区"},{"s":"成华区"},{"s":"龙泉驿区"},{"s":"青白江区"},{"s":"新都区"},{"s":"温江区"},{"s":"金堂县"},{"s":"双流县"},{"s":"郫县"},{"s":"大邑县"},{"s":"蒲江县"},{"s":"新津县"},{"s":"都江堰市"},{"s":"彭州市"},{"s":"邛崃市"},{"s":"崇州市"}]},{"n":"自贡","a":[{"s":"自流井区"},{"s":"贡井区"},{"s":"大安区"},{"s":"沿滩区"},{"s":"荣县"},{"s":"富顺县"}]},{"n":"攀枝花","a":[{"s":"东区"},{"s":"西区"},{"s":"仁和区"},{"s":"米易县"},{"s":"盐边县"}]},{"n":"泸州","a":[{"s":"江阳区"},{"s":"纳溪区"},{"s":"龙马潭区"},{"s":"泸县"},{"s":"合江县"},{"s":"叙永县"},{"s":"古蔺县"}]},{"n":"德阳","a":[{"s":"旌阳区"},{"s":"中江县"},{"s":"罗江县"},{"s":"广汉市"},{"s":"什邡市"},{"s":"绵竹市"}]},{"n":"绵阳","a":[{"s":"涪城区"},{"s":"游仙区"},{"s":"三台县"},{"s":"盐亭县"},{"s":"安县"},{"s":"梓潼县"},{"s":"北川羌族自治县"},{"s":"平武县"},{"s":"江油市"}]},{"n":"广元","a":[{"s":"利州区"},{"s":"元坝区"},{"s":"朝天区"},{"s":"旺苍县"},{"s":"青川县"},{"s":"剑阁县"},{"s":"苍溪县"}]},{"n":"遂宁","a":[{"s":"船山区"},{"s":">安居区"},{"s":">蓬溪县"},{"s":">射洪县"},{"s":">大英县"}]},{"n":"内江","a":[{"s":"市中区"},{"s":"东兴区"},{"s":"威远县"},{"s":"资中县"},{"s":"隆昌县"}]},{"n":"乐山","a":[{"s":"市中区"},{"s":"沙湾区"},{"s":"五通桥区"},{"s":"金口河区"},{"s":"犍为县"},{"s":"井研县"},{"s":"夹江县"},{"s":"沐川县"},{"s":"峨边彝族自治县"},{"s":"马边彝族自治县"},{"s":"峨眉山市"}]},{"n":"南充","a":[{"s":"顺庆区"},{"s":"高坪区"},{"s":"嘉陵区"},{"s":"南部县"},{"s":"营山县"},{"s":"蓬安县"},{"s":"仪陇县"},{"s":"西充县"},{"s":"阆中市"}]},{"n":"眉山","a":[{"s":"东坡区"},{"s":"仁寿县"},{"s":"彭山县"},{"s":"洪雅县"},{"s":"丹棱县"},{"s":"青神县"}]},{"n":"宜宾","a":[{"s":"翠屏区"},{"s":"宜宾县"},{"s":"南溪县"},{"s":"江安县"},{"s":"长宁县"},{"s":"高县"},{"s":"珙县"},{"s":"筠连县"},{"s":"兴文县"},{"s":"屏山县"}]},{"n":"广安","a":[{"s":"广安区"},{"s":"岳池县"},{"s":"武胜县"},{"s":"邻水县"},{"s":"华蓥市"}]},{"n":"达川","a":[{"s":"通川区"},{"s":"达县"},{"s":"宣汉县"},{"s":"开江县"},{"s":"大竹县"},{"s":"渠县"},{"s":"万源市"}]},{"n":"雅安","a":[{"s":"雨城区"},{"s":"名山县"},{"s":"荥经县"},{"s":"汉源县"},{"s":"石棉县"},{"s":"天全县"},{"s":"芦山县"},{"s":"宝兴县"}]},{"n":"巴中","a":[{"s":"巴州区"},{"s":"通江县"},{"s":"南江县"},{"s":"平昌县"}]},{"n":"资阳","a":[{"s":"雁江区"},{"s":"安岳县"},{"s":"乐至县"},{"s":"简阳市"}]},{"n":"阿坝","a":[{"s":"汶川县"},{"s":"理县"},{"s":"茂县"},{"s":"松潘县"},{"s":"九寨沟县"},{"s":"金川县"},{"s":"小金县"},{"s":"黑水县"},{"s":"马尔康县"},{"s":"壤塘县"},{"s":"阿坝县"},{"s":"若尔盖县"},{"s":"红原县"}]},{"n":"甘孜","a":[{"s":"康定县"},{"s":"泸定县"},{"s":"丹巴县"},{"s":"九龙县"},{"s":"雅江县"},{"s":"道孚县"},{"s":"炉霍县"},{"s":"甘孜县"},{"s":"新龙县"},{"s":"德格县"},{"s":"白玉县"},{"s":"石渠县"},{"s":"色达县"},{"s":"理塘县"},{"s":"巴塘县"},{"s":"乡城县"},{"s":"稻城县"},{"s":"得荣县"}]},{"n":"凉山","a":[{"s":"西昌市"},{"s":"木里藏族自治县"},{"s":"盐源县"},{"s":"德昌县"},{"s":"会理县"},{"s":"会东县"},{"s":"宁南县"},{"s":"普格县"},{"s":"布拖县"},{"s":"金阳县"},{"s":"昭觉县"},{"s":"喜德县"},{"s":"冕宁县"},{"s":"越西县"},{"s":"甘洛县"},{"s":"美姑县"},{"s":"雷波县"}]}]},{"p":"贵州省","c":[{"n":"贵阳","a":[{"s":"南明区"},{"s":"云岩区"},{"s":"花溪区"},{"s":"乌当区"},{"s":"白云区"},{"s":"小河区"},{"s":"开阳县"},{"s":"息烽县"},{"s":"修文县"},{"s":"清镇市"}]},{"n":"六盘水","a":[{"s":"钟山区"},{"s":"六枝特区"},{"s":"水城县"},{"s":"盘县"}]},{"n":"遵义","a":[{"s":"红花岗区"},{"s":"汇川区"},{"s":"遵义县"},{"s":"桐梓县"},{"s":"绥阳县"},{"s":"正安县"},{"s":"道真仡佬族苗族自治县"},{"s":"务川仡佬族苗族自治县"},{"s":"凤冈县"},{"s":"湄潭县"},{"s":"余庆县"},{"s":"习水县"},{"s":"赤水市"},{"s":"仁怀市"}]},{"n":"安顺","a":[{"s":"西秀区"},{"s":"平坝县"},{"s":"普定县"},{"s":"镇宁布依族苗族自治县"},{"s":"关岭布依族苗族自治县"},{"s":"紫云苗族布依族自治县"}]},{"n":"铜仁","a":[{"s":"铜仁市"},{"s":"江口县"},{"s":"玉屏侗族自治县"},{"s":"石阡县"},{"s":"思南县"},{"s":"印江土家族苗族自治县"},{"s":"德江县"},{"s":"沿河土家族自治县"},{"s":"松桃苗族自治县"},{"s":"万山特区"}]},{"n":"黔西南","a":[{"s":"兴义市"},{"s":"兴仁县"},{"s":"普安县"},{"s":"晴隆县"},{"s":"贞丰县"},{"s":"望谟县"},{"s":"册亨县"},{"s":"安龙县"}]},{"n":"毕节","a":[{"s":"毕节市"},{"s":"大方县"},{"s":"黔西县"},{"s":"金沙县"},{"s":"织金县"},{"s":"纳雍县"},{"s":"威宁彝族回族苗族自治县"},{"s":"赫章县"}]},{"n":"黔东南","a":[{"s":"凯里市"},{"s":"黄平县"},{"s":"施秉县"},{"s":"三穗县"},{"s":"镇远县"},{"s":"岑巩县"},{"s":"天柱县"},{"s":"锦屏县"},{"s":"剑河县"},{"s":"台江县"},{"s":"黎平县"},{"s":"榕江县"},{"s":"从江县"},{"s":"雷山县"},{"s":"麻江县"},{"s":"丹寨县"}]},{"n":"黔南","a":[{"s":"都匀市"},{"s":"福泉市"},{"s":"荔波县"},{"s":"贵定县"},{"s":"瓮安县"},{"s":"独山县"},{"s":"平塘县"},{"s":"罗甸县"},{"s":"长顺县"},{"s":"龙里县"},{"s":"惠水县"},{"s":"三都水族自治县"}]}]},{"p":"云南省","c":[{"n":"昆明","a":[{"s":"五华区"},{"s":"盘龙区"},{"s":"官渡区"},{"s":"西山区"},{"s":"东川区"},{"s":"呈贡县"},{"s":"晋宁县"},{"s":"富民县"},{"s":"宜良县"},{"s":"石林彝族自治县"},{"s":"嵩明县"},{"s":"禄劝彝族苗族自治县"},{"s":"寻甸回族彝族自治县"},{"s":"安宁市"}]},{"n":"曲靖","a":[{"s":"麒麟区"},{"s":"马龙县"},{"s":"陆良县"},{"s":"师宗县"},{"s":"罗平县"},{"s":"富源县"},{"s":"会泽县"},{"s":"沾益县"},{"s":"宣威市"}]},{"n":"玉溪","a":[{"s":"红塔区"},{"s":"江川县"},{"s":"澄江县"},{"s":"通海县"},{"s":"华宁县"},{"s":"易门县"},{"s":"峨山彝族自治县"},{"s":"新平彝族傣族自治县"},{"s":"元江哈尼族彝族傣族自治县"}]},{"n":"保山","a":[{"s":"隆阳区"},{"s":"施甸县"},{"s":"腾冲县"},{"s":"龙陵县"},{"s":"昌宁县"}]},{"n":"昭通","a":[{"s":"昭阳区"},{"s":"鲁甸县"},{"s":"巧家县"},{"s":"盐津县"},{"s":"大关县"},{"s":"永善县"},{"s":"绥江县"},{"s":"镇雄县"},{"s":"彝良县"},{"s":"威信县"},{"s":"水富县"}]},{"n":"丽江","a":[{"s":"古城区"},{"s":"玉龙纳西族自治县"},{"s":"永胜县"},{"s":"华坪县"},{"s":"宁蒗彝族自治县"}]},{"n":"普洱","a":[{"s":"思茅区"},{"s":"宁洱镇"},{"s":"墨江哈尼族自治县"},{"s":"景东彝族自治县"},{"s":"景谷傣族彝族自治县"},{"s":"镇沅彝族哈尼族拉祜族自治县"},{"s":"江城哈尼族彝族自治县"},{"s":"孟连傣族拉祜族佤族自治县"},{"s":"澜沧拉祜族自治县"},{"s":"西盟佤族自治县"}]},{"n":"临沧","a":[{"s":"临翔区"},{"s":"凤庆县"},{"s":"云县"},{"s":"永德县"},{"s":"镇康县"},{"s":"双江拉祜族佤族布朗族傣族自治县"},{"s":"耿马傣族佤族自治县"},{"s":"沧源佤族自治县"}]},{"n":"楚雄","a":[{"s":"楚雄市"},{"s":"双柏县"},{"s":"牟定县"},{"s":"南华县"},{"s":"姚安县"},{"s":"大姚县"},{"s":"永仁县"},{"s":"元谋县"},{"s":"武定县"},{"s":"禄丰县"}]},{"n":"红河","a":[{"s":"个旧市"},{"s":"开远市"},{"s":"蒙自县"},{"s":"屏边苗族自治县"},{"s":"建水县"},{"s":"石屏县"},{"s":"弥勒县"},{"s":"泸西县"},{"s":"元阳县"},{"s":"红河县"},{"s":"金平苗族瑶族傣族自治县"},{"s":"绿春县"},{"s":"河口瑶族自治县"}]},{"n":"文山","a":[{"s":"文山县"},{"s":"砚山县"},{"s":"西畴县"},{"s":"麻栗坡县"},{"s":"马关县"},{"s":"丘北县"},{"s":"广南县"},{"s":"富宁县"}]},{"n":"西双版纳","a":[{"s":"景洪市"},{"s":"勐海县"},{"s":"勐腊县"}]},{"n":"大理","a":[{"s":"大理市"},{"s":"漾濞彝族自治县"},{"s":"祥云县"},{"s":"宾川县"},{"s":"弥渡县"},{"s":"南涧彝族自治县"},{"s":"巍山彝族回族自治县"},{"s":"永平县"},{"s":"云龙县"},{"s":"洱源县"},{"s":"剑川县"},{"s":"鹤庆县"}]},{"n":"德宏","a":[{"s":"瑞丽市"},{"s":"潞西市"},{"s":"梁河县"},{"s":"盈江县"},{"s":"陇川县"}]},{"n":"怒江傈","a":[{"s":"泸水县"},{"s":"福贡县"},{"s":"贡山独龙族怒族自治县"},{"s":"兰坪白族普米族自治县"}]},{"n":"迪庆","a":[{"s":"香格里拉县"},{"s":"德钦县"},{"s":"维西傈僳族自治县"}]}]},{"p":"西藏","c":[{"n":"拉萨","a":[{"s":"城关区"},{"s":"林周县"},{"s":"当雄县"},{"s":"尼木县"},{"s":"曲水县"},{"s":"堆龙德庆县"},{"s":"达孜县"},{"s":"墨竹工卡县"}]},{"n":"昌都","a":[{"s":"昌都县"},{"s":"江达县"},{"s":"贡觉县"},{"s":"类乌齐县"},{"s":"丁青县"},{"s":"察雅县"},{"s":"八宿县"},{"s":"左贡县"},{"s":"芒康县"},{"s":"洛隆县"},{"s":"边坝县"}]},{"n":"山南","a":[{"s":"乃东县"},{"s":"扎囊县"},{"s":"贡嘎县"},{"s":"桑日县"},{"s":"琼结县"},{"s":"曲松县"},{"s":"措美县"},{"s":"洛扎县"},{"s":"加查县"},{"s":"隆子县"},{"s":"错那县"},{"s":"浪卡子县"}]},{"n":"日喀则","a":[{"s":"日喀则市"},{"s":"南木林县"},{"s":"江孜县"},{"s":"定日县"},{"s":"萨迦县"},{"s":"拉孜县"},{"s":"昂仁县"},{"s":"谢通门县"},{"s":"白朗县"},{"s":"仁布县"},{"s":"康马县"},{"s":"定结县"},{"s":"仲巴县"},{"s":"亚东县"},{"s":"吉隆县"},{"s":"聂拉木县"},{"s":"萨嘎县"},{"s":"岗巴县"}]},{"n":"那曲","a":[{"s":"那曲县"},{"s":"嘉黎县"},{"s":"比如县"},{"s":"聂荣县"},{"s":"安多县"},{"s":"申扎县"},{"s":"索县"},{"s":"班戈县"},{"s":"巴青县"},{"s":"尼玛县"}]},{"n":"阿里","a":[{"s":"普兰县"},{"s":"札达县"},{"s":"噶尔县"},{"s":"日土县"},{"s":"革吉县"},{"s":"改则县"},{"s":"措勤县"}]},{"n":"林芝","a":[{"s":"林芝县"},{"s":"工布江达县"},{"s":"米林县"},{"s":"墨脱县"},{"s":"波密县"},{"s":"察隅县"},{"s":"朗县"}]}]},{"p":"陕西省","c":[{"n":"西安","a":[{"s":"新城区"},{"s":"碑林区"},{"s":"莲湖区"},{"s":"灞桥区"},{"s":"未央区"},{"s":"雁塔区"},{"s":"阎良区"},{"s":"临潼区"},{"s":"长安区"},{"s":"蓝田县"},{"s":"周至县"},{"s":"户县"},{"s":"高陵县"}]},{"n":"铜川","a":[{"s":"王益区"},{"s":"印台区"},{"s":"耀州区"},{"s":"宜君县"}]},{"n":"宝鸡","a":[{"s":"渭滨区"},{"s":"金台区"},{"s":"陈仓区"},{"s":"凤翔县"},{"s":"岐山县"},{"s":"扶风县"},{"s":"眉县"},{"s":"陇县"},{"s":"千阳县"},{"s":"麟游县"},{"s":"凤县"},{"s":"太白县"}]},{"n":"咸阳","a":[{"s":"秦都区"},{"s":"杨凌区"},{"s":"渭城区"},{"s":"三原县"},{"s":"泾阳县"},{"s":"乾县"},{"s":"礼泉县"},{"s":"永寿县"},{"s":"彬县"},{"s":"长武县"},{"s":"旬邑县"},{"s":"淳化县"},{"s":"武功县"},{"s":"兴平市"}]},{"n":"渭南","a":[{"s":"临渭区"},{"s":"华县"},{"s":"潼关县"},{"s":"大荔县"},{"s":"合阳县"},{"s":"澄城县"},{"s":"蒲城县"},{"s":"白水县"},{"s":"富平县"},{"s":"韩城市"},{"s":"华阴市"}]},{"n":"延安","a":[{"s":"宝塔区"},{"s":"延长县"},{"s":"延川县"},{"s":"子长县"},{"s":"安塞县"},{"s":"志丹县"},{"s":"吴起县"},{"s":"甘泉县"},{"s":"富县"},{"s":"洛川县"},{"s":"宜川县"},{"s":"黄龙县"},{"s":"黄陵县"}]},{"n":"汉中","a":[{"s":"汉台区"},{"s":"南郑县"},{"s":"城固县"},{"s":"洋县"},{"s":"西乡县"},{"s":"勉县"},{"s":"宁强县"},{"s":"略阳县"},{"s":"镇巴县"},{"s":"留坝县"},{"s":"佛坪县"}]},{"n":"榆林","a":[{"s":"榆阳区"},{"s":"神木县"},{"s":"府谷县"},{"s":"横山县"},{"s":"靖边县"},{"s":"定边县"},{"s":"绥德县"},{"s":"米脂县"},{"s":"佳县"},{"s":"吴堡县"},{"s":"清涧县"},{"s":"子洲县"}]},{"n":"安康","a":[{"s":"汉滨区"},{"s":"汉阴县"},{"s":"石泉县"},{"s":"宁陕县"},{"s":"紫阳县"},{"s":"岚皋县"},{"s":"平利县"},{"s":"镇坪县"},{"s":"旬阳县"},{"s":"白河县"}]},{"n":"商洛","a":[{"s":"商州区"},{"s":"洛南县"},{"s":"丹凤县"},{"s":"商南县"},{"s":"山阳县"},{"s":"镇安县"},{"s":"柞水县"}]}]},{"p":"甘肃省","c":[{"n":"兰州","a":[{"s":"区"},{"s":"城关区"},{"s":"七里河区"},{"s":"西固区"},{"s":"安宁区"},{"s":"红古区"},{"s":"永登县"},{"s":"皋兰县"},{"s":"榆中县"}]},{"n":"嘉峪关","a":[{"s":"嘉峪关市"}]},{"n":"金昌","a":[{"s":"金川区"},{"s":"永昌县"}]},{"n":"白银","a":[{"s":"白银区"},{"s":"平川区"},{"s":"靖远县"},{"s":"会宁县"},{"s":"景泰县"}]},{"n":"天水","a":[{"s":"秦城区"},{"s":"麦积区"},{"s":"清水县"},{"s":"秦安县"},{"s":"甘谷县"},{"s":"武山县"},{"s":"张家川回族自治县"}]},{"n":"武威","a":[{"s":"凉州区"},{"s":"民勤县"},{"s":"古浪县"},{"s":"天祝藏族自治县"}]},{"n":"张掖","a":[{"s":"甘州区"},{"s":"肃南裕固族自治县"},{"s":"民乐县"},{"s":"临泽县"},{"s":"高台县"},{"s":"山丹县"}]},{"n":"平凉","a":[{"s":"崆峒区"},{"s":"泾川县"},{"s":"灵台县"},{"s":"崇信县"},{"s":"华亭县"},{"s":"庄浪县"},{"s":"静宁县"}]},{"n":"酒泉","a":[{"s":"肃州区"},{"s":"金塔县"},{"s":"瓜州县"},{"s":"肃北蒙古族自治县"},{"s":"阿克塞哈萨克族自治县"},{"s":"玉门市"},{"s":"敦煌市"}]},{"n":"庆阳","a":[{"s":"西峰区"},{"s":"庆城县"},{"s":"环县"},{"s":"华池县"},{"s":"合水县"},{"s":"正宁县"},{"s":"宁县"},{"s":"镇原县"}]},{"n":"定西","a":[{"s":"安定区"},{"s":"通渭县"},{"s":"陇西县"},{"s":"渭源县"},{"s":"临洮县"},{"s":"漳县"},{"s":"岷县"}]},{"n":"陇南","a":[{"s":"武都区"},{"s":"成县"},{"s":"文县"},{"s":"宕昌县"},{"s":"康县"},{"s":"西和县"},{"s":"礼县"},{"s":"徽县"},{"s":"两当县"}]},{"n":"临夏","a":[{"s":"临夏市"},{"s":"临夏县"},{"s":"康乐县"},{"s":"永靖县"},{"s":"广河县"},{"s":"和政县"},{"s":"东乡族自治县"},{"s":"积石山保安族东乡族撒拉族自治县"}]},{"n":"甘南","a":[{"s":"合作市"},{"s":"临潭县"},{"s":"卓尼县"},{"s":"舟曲县"},{"s":"迭部县"},{"s":"玛曲县"},{"s":"碌曲县"},{"s":"夏河县"}]}]},{"p":"青海省","c":[{"n":"西宁","a":[{"s":"城东区"},{"s":"城中区"},{"s":"城西区"},{"s":"城北区"},{"s":"大通回族土族自治县"},{"s":"湟中县"},{"s":"湟源县"}]},{"n":"海东","a":[{"s":"平安县"},{"s":"民和回族土族自治县"},{"s":"乐都县"},{"s":"互助土族自治县"},{"s":"化隆回族自治县"},{"s":"循化撒拉族自治县"}]},{"n":"海北","a":[{"s":"门源回族自治县"},{"s":"祁连县"},{"s":"海晏县"},{"s":"刚察县"}]},{"n":"黄南","a":[{"s":"同仁县"},{"s":"尖扎县"},{"s":"泽库县"},{"s":"河南蒙古族自治县"}]},{"n":"海南","a":[{"s":"共和县"},{"s":"同德县"},{"s":"贵德县"},{"s":"兴海县"},{"s":"贵南县"}]},{"n":"果洛","a":[{"s":"玛沁县"},{"s":"班玛县"},{"s":"甘德县"},{"s":"达日县"},{"s":"久治县"},{"s":"玛多县"}]},{"n":"玉树","a":[{"s":"玉树县"},{"s":"杂多县"},{"s":"称多县"},{"s":"治多县"},{"s":"囊谦县"},{"s":"曲麻莱县"}]},{"n":"梅西","a":[{"s":"格尔木市"},{"s":"德令哈市"},{"s":"乌兰县"},{"s":"都兰县"},{"s":"天峻县"}]}]},{"p":"宁夏省","c":[{"n":"银川","a":[{"s":"兴庆区"},{"s":"西夏区"},{"s":"金凤区"},{"s":"永宁县"},{"s":"贺兰县"},{"s":"灵武市"}]},{"n":"石嘴山","a":[{"s":"大武口区"},{"s":"惠农区"},{"s":"平罗县"}]},{"n":"吴忠","a":[{"s":"利通区"},{"s":"红寺堡区"},{"s":"盐池县"},{"s":"同心县"},{"s":"青铜峡市"}]},{"n":"固原","a":[{"s":"原州区"},{"s":"西吉县"},{"s":"隆德县"},{"s":"泾源县"},{"s":"彭阳县"}]},{"n":"中卫","a":[{"s":"沙坡头区"},{"s":"中宁县"},{"s":"海原县"}]}]},{"p":"新疆","c":[{"n":"乌鲁木齐","a":[{"s":"天山区"},{"s":"沙依巴克区"},{"s":"新市区"},{"s":"水磨沟区"},{"s":"头屯河区"},{"s":"达坂城区"},{"s":"米东区"},{"s":"乌鲁木齐县"}]},{"n":"克拉玛依","a":[{"s":"独山子区"},{"s":"克拉玛依区"},{"s":"白碱滩区"},{"s":"乌尔禾区"}]},{"n":"吐鲁番","a":[{"s":"吐鲁番市"},{"s":"鄯善县"},{"s":"托克逊县"}]},{"n":"哈密","a":[{"s":"哈密市"},{"s":"巴里坤哈萨克自治县"},{"s":"伊吾县"}]},{"n":"昌吉","a":[{"s":"昌吉市"},{"s":"阜康市"},{"s":"呼图壁县"},{"s":"玛纳斯县"},{"s":"奇台县"},{"s":"吉木萨尔县"},{"s":"木垒哈萨克自治县"}]},{"n":"博尔塔拉","a":[{"s":"博乐市"},{"s":"精河县"},{"s":"温泉县"}]},{"n":"巴音郭楞","a":[{"s":"库尔勒市"},{"s":"轮台县"},{"s":"尉犁县"},{"s":"若羌县"},{"s":"且末县"},{"s":"焉耆回族自治县"},{"s":"和静县"},{"s":"和硕县"},{"s":"博湖县"}]},{"n":"阿克苏","a":[{"s":"阿克苏市"},{"s":"温宿县"},{"s":"库车县"},{"s":"沙雅县"},{"s":"新和县"},{"s":"拜城县"},{"s":"乌什县"},{"s":"阿瓦提县"},{"s":"柯坪县"}]},{"n":"克孜勒苏","a":[{"s":"阿图什市"},{"s":"阿克陶县"},{"s":"阿合奇县"},{"s":"乌恰县"}]},{"n":"喀什","a":[{"s":"喀什市"},{"s":"疏附县"},{"s":"疏勒县"},{"s":"英吉沙县"},{"s":"泽普县"},{"s":"莎车县"},{"s":"叶城县"},{"s":"麦盖提县"},{"s":"岳普湖县"},{"s":"伽师县"},{"s":"巴楚县"},{"s":"塔什库尔干县塔吉克自治"}]},{"n":"和田","a":[{"s":"和田市"},{"s":"和田县"},{"s":"墨玉县"},{"s":"皮山县"},{"s":"洛浦县"},{"s":"策勒县"},{"s":"于田县"},{"s":"民丰县"}]},{"n":"伊犁","a":[{"s":"伊宁市"},{"s":"奎屯市"},{"s":"伊宁县"},{"s":"察布查尔锡伯自治县"},{"s":"霍城县"},{"s":"巩留县"},{"s":"新源县"},{"s":"昭苏县"},{"s":"特克斯县"},{"s":"尼勒克县"}]},{"n":"塔城","a":[{"s":"塔城市"},{"s":"乌苏市"},{"s":"额敏县"},{"s":"沙湾县"},{"s":"托里县"},{"s":"裕民县"},{"s":"和布克赛尔蒙古自治县"}]},{"n":"阿勒泰","a":[{"s":"阿勒泰市"},{"s":"布尔津县"},{"s":"富蕴县"},{"s":"福海县"},{"s":"哈巴河县"},{"s":"青河县"},{"s":"吉木乃县"}]},{"n":"石河子","a":[{"s":"石河子"}]},{"n":"阿拉尔","a":[{"s":"阿拉尔"}]},{"n":"图木舒克","a":[{"s":"图木舒克"}]},{"n":"五家渠","a":[{"s":"五家渠"}]}]},{"p":"香港","c":[{"n":"中西区"},{"n":"东区"},{"n":"九龙城区"},{"n":"观塘区"},{"n":"南区"},{"n":"深水区"},{"n":"湾仔区"},{"n":"黄大仙区"},{"n":"油尖旺区"},{"n":"离岛区"},{"n":"葵青区"},{"n":"北区"},{"n":"西贡区"},{"n":"沙田区"},{"n":"屯门区"},{"n":"大埔区"},{"n":"荃湾区"},{"n":"元朗区"}]},{"p":"澳门","c":[{"n":"花地玛堂区"},{"n":"圣安多尼堂区"},{"n":"大堂区"},{"n":"望德堂区"},{"n":"风顺堂区"},{"n":"嘉模堂区"},{"n":"圣方济各堂区"}]},{"p":"台湾","c":[{"n":"台北市"},{"n":"高雄市"},{"n":"基隆市"},{"n":"台中市"},{"n":"台南市"},{"n":"新竹市"},{"n":"嘉义市"},{"n":"台北县"},{"n":"宜兰县"},{"n":"新竹县"},{"n":"桃园县"},{"n":"苗栗县"},{"n":"台中县"},{"n":"彰化县"},{"n":"南投县"},{"n":"嘉义县"},{"n":"云林县"},{"n":"台南县"},{"n":"高雄县"},{"n":"屏东县"},{"n":"台东县"},{"n":"花莲县"},{"n":"澎湖县"}]}]} \ No newline at end of file diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/test-resources/data/idcodearea.json b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/test-resources/data/idcodearea.json deleted file mode 100644 index 336b2aff4d..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/test-resources/data/idcodearea.json +++ /dev/null @@ -1 +0,0 @@ -{"11":"北京市","1101":"北京市市辖区","110101":"北京市东城区","110102":"北京市西城区","110103":"北京市崇文区","110104":"北京市宣武区","110105":"北京市朝阳区","110106":"北京市丰台区","110107":"北京市石景山区","110108":"北京市海淀区","110109":"北京市门头沟区","110111":"北京市房山区","1102":"北京市市辖县","110221":"北京市昌平县","110222":"北京市顺义县","110223":"北京市通县","110224":"北京市大兴县","110226":"北京市平谷县","110227":"北京市怀柔县","110228":"北京市密云县","110229":"北京市延庆县","12":"天津市","1201":"天津市市辖区","120101":"天津市和平区","120102":"天津市河东区","120103":"天津市河西区","120104":"天津市南开区","120105":"天津市河北区","120106":"天津市红桥区","120107":"天津市塘沽区","120108":"天津市汉沽区","120109":"天津市大港区","120110":"天津市东丽区","120111":"天津市西青区","120112":"天津市津南区","120113":"天津市北辰区","1202":"天津市市辖县","120221":"天津市宁河县","120222":"天津市武清县","120223":"天津市静海县","120224":"天津市宝坻县","120225":"天津市蓟县","13":"河北省","1301":"河北省石家庄市","130101":"河北省石家庄市市辖区","130102":"河北省石家庄市长安区","130103":"河北省石家庄市桥东区","130104":"河北省石家庄市桥西区","130105":"河北省石家庄市新华区","130106":"河北省石家庄市郊区","130107":"河北省石家庄市井陉矿区","130121":"河北省井陉县","130122":"河北省获鹿县","130123":"河北省正定县","130124":"河北省栾城县","130125":"河北省行唐县","130126":"河北省灵寿县","130127":"河北省高邑县","130128":"河北省深泽县","130129":"河北省赞皇县","130130":"河北省无极县","130131":"河北省平山县","130132":"河北省元氏县","130133":"河北省赵县","130181":"河北省辛集市","130182":"河北省藁城市","130183":"河北省晋州市","130184":"河北省新乐市","1302":"河北省唐山市","130201":"河北省唐山市市辖区","130202":"河北省唐山市路南区","130203":"河北省唐山市路北区","130204":"河北省唐山市东矿区","130205":"河北省唐山市开平区","130206":"河北省唐山市新区","130221":"河北省丰润县","130222":"河北省丰南县","130223":"河北省滦县","130224":"河北省滦南县","130225":"河北省乐亭县","130226":"河北省迁安县","130227":"河北省迁西县","130229":"河北省玉田县","130230":"河北省唐海县","130281":"河北省遵化市","1303":"河北省秦皇岛市","130301":"河北省秦皇岛市市辖区","130302":"河北省秦皇岛市海港区","130303":"河北省秦皇岛市山海关区","130304":"河北省秦皇岛市北戴河区","130321":"河北省青龙满族自治县","130322":"河北省昌黎县","130323":"河北省抚宁县","130324":"河北省卢龙县","1304":"河北省邯郸市","130401":"河北省邯郸市市辖区","130402":"河北省邯郸市邯山区","130403":"河北省邯郸市丛台区","130404":"河北省邯郸市复兴区","130406":"河北省邯郸市峰峰矿区","130421":"河北省邯郸县","130423":"河北省临漳县","130424":"河北省成安县","130425":"河北省大名县","130426":"河北省涉县","130427":"河北省磁县","130428":"河北省肥乡县","130429":"河北省永年县","130430":"河北省丘县","130431":"河北省鸡泽县","130432":"河北省广平县","130433":"河北省馆陶县","130434":"河北省魏县","130435":"河北省曲周县","130481":"河北省武安市","1305":"河北省邢台市","130501":"河北省邢台市市辖区","130502":"河北省邢台市桥东区","130503":"河北省邢台市桥西区","130521":"河北省邢台县","130522":"河北省临城县","130523":"河北省内丘县","130524":"河北省柏乡县","130525":"河北省隆尧县","130526":"河北省任县","130527":"河北省南和县","130528":"河北省宁晋县","130529":"河北省巨鹿县","130530":"河北省新河县","130531":"河北省广宗县","130532":"河北省平乡县","130533":"河北省威县","130534":"河北省清河县","130535":"河北省临西县","130581":"河北省南宫市","130582":"河北省沙河市","1306":"河北省保定市","130601":"河北省保定市市辖区","130602":"河北省保定市新市区","130603":"河北省保定市北市区","130604":"河北省保定市南市区","130621":"河北省满城县","130622":"河北省清苑县","1307":"河北省张家口市","130701":"河北省张家口市市辖区","130702":"河北省张家口市桥东区","130703":"河北省张家口市桥西区","130705":"河北省张家口市宣化区","130706":"河北省张家口市下花园区","130721":"河北省宣化县","130722":"河北省张北县","130723":"河北省康保县","130724":"河北省沽源县","130725":"河北省尚义县","130726":"河北省蔚县","130727":"河北省阳原县","130728":"河北省怀安县","130729":"河北省万全县","130730":"河北省怀来县","130731":"河北省涿鹿县","130732":"河北省赤城县","130733":"河北省崇礼县","1308":"河北省承德市","130801":"河北省承德市市辖区","130802":"河北省承德市双桥区","130803":"河北省承德市双滦区","130804":"河北省承德市鹰手营子矿区","130821":"河北省承德县","130822":"河北省兴隆县","130823":"河北省平泉县","130824":"河北省滦平县","130825":"河北省隆化县","130826":"河北省丰宁满族自治县","130827":"河北省宽城满族自治县","130828":"河北省围场满族蒙古族自治县","1309":"河北省沧洲市","130901":"河北省沧洲市市辖区","130902":"河北省沧洲市新华区","130903":"河北省沧洲市运河区","130904":"河北省沧洲市郊区","130921":"河北省沧县","130922":"河北省青县","130923":"河北省东光县","130924":"河北省海兴县","130925":"河北省盐山县","130926":"河北省肃宁县","130927":"河北省南皮县","130928":"河北省吴桥县","130929":"河北省献县","130930":"河北省孟村回族自治县","130981":"河北省泊头市","130982":"河北省任丘市","130983":"河北省黄骅市","130984":"河北省河间市","1310":"河北省廊坊市","131001":"河北省廊坊市市辖区","131002":"河北省廊坊市安次区","131022":"河北省固安县","131023":"河北省永清县","131024":"河北省香河县","131025":"河北省大城县","131026":"河北省文安县","131028":"河北省大厂回族自治县","131081":"河北省霸州市","131082":"河北省三河市","1324":"河北省保定地区","132401":"河北省定州市","132402":"河北省涿州市","132403":"河北省安国市","132404":"河北省高碑店市","132421":"河北省易县","132423":"河北省徐水县","132424":"河北省涞源县","132425":"河北省定兴县","132426":"河北省顺平县","132427":"河北省唐县","132428":"河北省望都县","132429":"河北省涞水县","132432":"河北省高阳县","132433":"河北省安新县","132434":"河北省雄县","132435":"河北省容城县","132437":"河北省曲阳县","132438":"河北省阜平县","132441":"河北省博野县","132442":"河北省蠡县","1330":"河北省衡水地区","133001":"河北省衡水市","133002":"河北省冀州县","133023":"河北省枣强县","133024":"河北省武邑县","133025":"河北省深县","133026":"河北省武强县","133027":"河北省饶阳县","133028":"河北省安平县","133029":"河北省故城县","133030":"河北省景县","133031":"河北省阜城县","14":"山西省","1401":"山西省太原市","140101":"山西省太原市市辖区","140102":"山西省太原市南城区","140103":"山西省太原市北城区","140104":"山西省太原市河西区","140112":"山西省太原市南郊区","140113":"山西省太原市北郊区","140121":"山西省清徐县","140122":"山西省阳曲县","140123":"山西省娄烦县","140181":"山西省古交市","1402":"山西省大同市","140201":"山西省大同市市辖区","140202":"山西省大同市城区","140203":"山西省大同市矿区","140211":"山西省大同市南郊区","140212":"山西省大同市新荣区","140221":"山西省阳高县","140222":"山西省天镇县","140223":"山西省广灵县","140224":"山西省灵丘县","140225":"山西省浑源县","140226":"山西省左云县","140227":"山西省大同县","1403":"山西省阳泉市","140301":"山西省阳泉市市辖区","140302":"山西省阳泉市城区","140303":"山西省阳泉市矿区","140311":"山西省阳泉市郊区","140321":"山西省平定县","140322":"山西省盂县","1404":"山西省长治市","140401":"山西省长治市市辖区","140402":"山西省长治市城区","140411":"山西省长治市郊区","140421":"山西省长治县","140422":"山西省潞城县","140423":"山西省襄垣县","140424":"山西省屯留县","140425":"山西省平顺县","140426":"山西省黎城县","140427":"山西省壶关县","140428":"山西省长子县","140429":"山西省武乡县","140430":"山西省沁县","140431":"山西省沁源县","1405":"山西省晋城市","140501":"山西省晋城市市辖区","140502":"山西省晋城市城区","140511":"山西省晋城市郊区","140521":"山西省沁水县","140522":"山西省阳城县","140524":"山西省陵川县","140581":"山西省高平市","1406":"山西省朔州市","140601":"山西省朔州市市辖区","140602":"山西省朔州市朔城区","140603":"山西省朔州市平鲁区","140621":"山西省山阴县","140622":"山西省应县","140623":"山西省右玉县","140624":"山西省怀仁县","1422":"山西省忻洲地区","142201":"山西省忻州市","142202":"山西省原平县","142222":"山西省定襄县","142223":"山西省五台县","142225":"山西省代县","142226":"山西省繁峙县","142227":"山西省宁武县","142228":"山西省静乐县","142229":"山西省神池县","142230":"山西省五寨县","142231":"山西省苛岚县","142232":"山西省河曲县","142233":"山西省保德县","142234":"山西省偏关县","1423":"山西省吕梁地区","142301":"山西省孝义市","142321":"山西省汾阳县","142322":"山西省文水县","142323":"山西省交城县","142325":"山西省兴县","142326":"山西省临县","142327":"山西省柳林县","142328":"山西省石楼县","142329":"山西省岚县","142330":"山西省方山县","142331":"山西省离石县","142332":"山西省中阳县","142333":"山西省交口县","1424":"山西省晋中地区","142401":"山西省榆次市","142402":"山西省介休市","142421":"山西省榆社县","142422":"山西省左权县","142423":"山西省和顺县","142424":"山西省昔阳县","142427":"山西省寿阳县","142429":"山西省太谷县","142430":"山西省祁县","142431":"山西省平遥县","142433":"山西省灵石县","1426":"山西省临汾地区","142601":"山西省临汾市","142602":"山西省侯马市","142603":"山西省霍州市","142621":"山西省曲沃县","142622":"山西省翼城县","142623":"山西省襄汾县","142625":"山西省洪洞县","142627":"山西省古县","142628":"山西省安泽县","142629":"山西省浮山县","142630":"山西省吉县","142631":"山西省乡宁县","142632":"山西省蒲县","142633":"山西省大宁县","142634":"山西省永和县","142635":"山西省隰县","142636":"山西省汾西县","1427":"山西省运城地区","142701":"山西省运城市","142722":"山西省永济县","142723":"山西省芮城县","142724":"山西省临猗县","142725":"山西省万荣县","142726":"山西省新绛县","142727":"山西省稷山县","142728":"山西省河津县","142729":"山西省闻喜县","142730":"山西省夏县","142731":"山西省绛县","142732":"山西省平陆县","142733":"山西省垣曲县","15":"内蒙古","1501":"内蒙古呼和浩特市","150101":"内蒙古呼和浩特市市辖区","150102":"内蒙古呼和浩特市新城区","150103":"内蒙古呼和浩特市回民区","150104":"内蒙古呼和浩特市玉泉区","150105":"内蒙古呼和浩特市郊区","150121":"内蒙古土默特左旗","150122":"内蒙古托克托县","1502":"内蒙古包头市","150201":"内蒙古包头市市辖区","150202":"内蒙古包头市东河区","150203":"内蒙古包头市昆都伦区","150204":"内蒙古包头市青山区","150205":"内蒙古包头市石拐矿区","150206":"内蒙古包头市白云矿区","150207":"内蒙古包头市郊区","150221":"内蒙古土默特右旗","150222":"内蒙古固阳县","1503":"内蒙古乌海市","150301":"内蒙古乌海市市辖区","150302":"内蒙古乌海市海勃湾区","150303":"内蒙古乌海市海南区","150304":"内蒙古乌海市乌达区","1504":"内蒙古赤峰市","150401":"内蒙古赤峰市市辖区","150402":"内蒙古赤峰市红山区","150403":"内蒙古赤峰市元宝山区","150404":"内蒙古赤峰市松山区","150421":"内蒙古阿鲁科尔沁旗","150422":"内蒙古巴林左旗","150423":"内蒙古巴林右旗","150424":"内蒙古林西县","150425":"内蒙古克什克腾旗","150426":"内蒙古翁牛特旗","150428":"内蒙古喀喇沁旗","150429":"内蒙古宁城县","150430":"内蒙古敖汉旗","1521":"内蒙古呼伦贝尔盟","152101":"内蒙古海拉尔市","152102":"内蒙古满洲里市","152103":"内蒙古扎兰屯市","152104":"内蒙古牙克石市","152122":"内蒙古阿荣旗","152123":"内蒙古莫力达瓦达翰尔族自治旗","152125":"内蒙古额尔古纳右旗","152126":"内蒙古额尔古纳左旗","152127":"内蒙古鄂伦春自治旗","152128":"内蒙古鄂温克族自治旗","152129":"内蒙古新巴尔虎右旗","152130":"内蒙古新巴尔虎左旗","152131":"内蒙古陈巴尔虎旗","1522":"内蒙古兴安盟","152201":"内蒙古乌兰浩特市","152221":"内蒙古科尔沁右翼前旗","152222":"内蒙古科尔沁右翼中旗","152223":"内蒙古扎赍特旗","152224":"内蒙古突泉县","1523":"内蒙古哲里木盟","152301":"内蒙古通辽市","152302":"内蒙古霍林郭勒市","152322":"内蒙古科尔沁左翼中旗","152323":"内蒙古科尔沁左翼后旗","152324":"内蒙古开鲁县","152325":"内蒙古库伦旗","152326":"内蒙古奈曼旗 ","152327":"内蒙古扎鲁特旗","1525":"内蒙古锡林郭勒盟","152501":"内蒙古二连浩特市","152502":"内蒙古锡林浩特市","152522":"内蒙古阿巴嘎旗","152523":"内蒙古苏尼特左旗","152524":"内蒙古苏尼特右旗","152525":"内蒙古东乌珠穆沁旗","152526":"内蒙古西乌珠穆沁旗","152527":"内蒙古太仆寺旗","152528":"内蒙古镶黄旗","152529":"内蒙古正镶白旗","152530":"内蒙古正蓝旗","152531":"内蒙古多伦县","1526":"内蒙古乌兰察布盟","152601":"内蒙古集宁市","152602":"内蒙古丰镇市","152621":"内蒙古武川县","152622":"内蒙古和林格尔县","152623":"内蒙古清水河县","152624":"内蒙古卓资县","152625":"内蒙古化德县","152626":"内蒙古商都县","152627":"内蒙古兴和县","152629":"内蒙古凉城县","152630":"内蒙古察哈尔右翼前旗","152631":"内蒙古察哈尔右翼中旗","152632":"内蒙古察哈尔右翼后旗","152633":"内蒙古达尔罕茂明安联合旗","152634":"内蒙古四子王旗","1527":"内蒙古伊克昭盟","152701":"内蒙古东胜市","152722":"内蒙古达拉特旗","152723":"内蒙古准格尔旗","152724":"内蒙古鄂托克前旗","152725":"内蒙古鄂托克旗","152726":"内蒙古杭锦旗 ","152727":"内蒙古乌审旗","152728":"内蒙古伊金霍洛旗","1528":"内蒙古巴彦淖尔盟","152801":"内蒙古临河市","152822":"内蒙古五原县","152823":"内蒙古磴口县","152824":"内蒙古乌拉特前旗","152825":"内蒙古乌拉特中旗","152826":"内蒙古乌拉特后旗","152827":"内蒙古杭锦后旗","1529":"内蒙古阿拉善盟","152921":"内蒙古阿拉善左旗","152922":"内蒙古阿拉善右旗","152923":"内蒙古额济纳旗","21":"辽宁省","2101":"辽宁省沈阳市","210101":"辽宁省沈阳市市辖区","210102":"辽宁省沈阳市和平区","210103":"辽宁省沈阳市沈河区","210104":"辽宁省沈阳市大东区","210105":"辽宁省沈阳市皇姑区","210106":"辽宁省沈阳市铁西区","210111":"辽宁省沈阳市苏家屯区","210112":"辽宁省沈阳市东陵区","210113":"辽宁省沈阳市新城子区","210114":"辽宁省沈阳市于洪区","210122":"辽宁省辽中县","210123":"辽宁省康平县","210124":"辽宁省法库县","210181":"辽宁省新民市","2102":"辽宁省大连市","210201":"辽宁省大连市市辖区","210202":"辽宁省大连市中山区","210203":"辽宁省大连市西岗区","210204":"辽宁省大连市沙河口区","210211":"辽宁省大连市甘井子区","210212":"辽宁省大连市旅顺口区","210213":"辽宁省大连市金州区","210224":"辽宁省长海县","210281":"辽宁省瓦房店市","210282":"辽宁省普兰店市","210283":"辽宁省庄河市","2103":"辽宁省鞍山市","210301":"辽宁省鞍山市市辖区","210302":"辽宁省鞍山市铁东区","210303":"辽宁省鞍山市铁西区","210304":"辽宁省鞍山市立山区","210311":"辽宁省鞍山市旧堡区","210321":"辽宁省台安县","210323":"辽宁省岫岩满族自治县","210381":"辽宁省海城市","2104":"辽宁省抚顺市","210401":"辽宁省抚顺市市辖区","210402":"辽宁省抚顺市新抚区","210403":"辽宁省抚顺市露天区","210404":"辽宁省抚顺市望花区","210411":"辽宁省抚顺市顺城区","210421":"辽宁省抚顺县","210422":"辽宁省新宾满族自治县","210423":"辽宁省清原满族自治县","2105":"辽宁省本溪市","210501":"辽宁省本溪市市辖区","210502":"辽宁省本溪市平山区","210503":"辽宁省本溪市溪湖区","210504":"辽宁省本溪市明山区","210511":"辽宁省本溪市南芬区","210521":"辽宁省本溪满族自治县","210522":"辽宁省桓仁满族自治县","2106":"辽宁省丹东市","210601":"辽宁省丹东市市辖区","210602":"辽宁省丹东市元宝区","210603":"辽宁省丹东市振兴区","210604":"辽宁省丹东市振安区","210621":"辽宁省凤城满族自治县","210624":"辽宁省宽甸满族自治县","210681":"辽宁省东港市","2107":"辽宁省锦州市","210701":"辽宁省锦州市市辖区","210702":"辽宁省锦州市古塔区","210703":"辽宁省锦州市凌河区","210711":"辽宁省锦州市太和区","210725":"辽宁省北镇满族自治县","210726":"辽宁省黑山县","210727":"辽宁省义县","210781":"辽宁省凌海市","2108":"辽宁省营口市","210801":"辽宁省营口市市辖区","210802":"辽宁省营口市站前区","210803":"辽宁省营口市西市区","210804":"辽宁省营口市鲅鱼圈区","210811":"辽宁省营口市老边区","210881":"辽宁省盖州市","210882":"辽宁省大石桥市","2109":"辽宁省阜新市","210901":"辽宁省阜新市市辖区","210902":"辽宁省阜新市海洲区","210903":"辽宁省阜新市新邱区","210904":"辽宁省阜新市太平区","210905":"辽宁省阜新市清河门区","210911":"辽宁省阜新市细河区","210921":"辽宁省阜新蒙古族自治县","210922":"辽宁省彰武县","2110":"辽宁省辽阳市","211001":"辽宁省辽阳市市辖区","211002":"辽宁省辽阳市白塔区","211003":"辽宁省辽阳市文圣区","211004":"辽宁省辽阳市宏伟区","211005":"辽宁省辽阳市弓长岭区","211011":"辽宁省辽阳市太子河区","211021":"辽宁省辽阳县","211022":"辽宁省灯塔县","2111":"辽宁省盘锦市","211101":"辽宁省盘锦市市辖区","211102":"辽宁省盘锦市双台子区","211103":"辽宁省盘锦市兴隆台区","211121":"辽宁省大洼县","211122":"辽宁省盘山县","2112":"辽宁省铁岭市","211201":"辽宁省铁岭市市辖区","211202":"辽宁省铁岭市银州区","211204":"辽宁省铁岭市清河区","211221":"辽宁省铁岭县","211223":"辽宁省西丰县","211224":"辽宁省昌图县","211281":"辽宁省铁法市","211282":"辽宁省开原市","2113":"辽宁省朝阳市","211301":"辽宁省朝阳市市辖区","211302":"辽宁省朝阳市双塔区","211303":"辽宁省朝阳市龙城区","211321":"辽宁省朝阳县","211322":"辽宁省建平县","211324":"辽宁省喀喇沁左翼蒙古族自治县","211381":"辽宁省北票市","211382":"辽宁省凌源市","2114":"辽宁省锦西市","211401":"辽宁省锦西市市辖区","211402":"辽宁省锦西市连山区","211403":"辽宁省锦西市葫芦岛区","211404":"辽宁省锦西市南票区","211421":"辽宁省绥中县","211422":"辽宁省建昌县","211481":"辽宁省兴城市","22":"吉林省","2201":"吉林省长春市","220101":"吉林省长春市市辖区","220102":"吉林省长春市南关区","220103":"吉林省长春市宽城区","220104":"吉林省长春市朝阳区","220105":"吉林省长春市二道河子区","220111":"吉林省长春市郊区","220122":"吉林省农安县","220124":"吉林省德惠县","220125":"吉林省双阳县","220181":"吉林省九台市","220182":"吉林省榆树市","2202":"吉林省吉林市","220201":"吉林省吉林市市辖区","220202":"吉林省吉林市昌邑区","220203":"吉林省吉林市龙潭区","220204":"吉林省吉林市船营区","220211":"吉林省吉林市丰满区","220221":"吉林省永吉县","220223":"吉林省磐石县","220281":"吉林省蛟河市","220282":"吉林省桦甸市","220283":"吉林省舒兰市","2203":"吉林省四平市","220301":"吉林省四平市市辖区","220302":"吉林省四平市铁西区","220303":"吉林省四平市铁东区","220322":"吉林省梨树县","220323":"吉林省伊通满族自治县","220324":"吉林省双辽县","220381":"吉林省公主岭市","2204":"吉林省辽源市","220401":"吉林省辽源市市辖区","220402":"吉林省辽源市龙山区","220403":"吉林省辽源市西安区","220421":"吉林省东丰县","220422":"吉林省东辽县","2205":"吉林省通化市","220501":"吉林省通化市市辖区","220502":"吉林省通化市东昌区","220503":"吉林省通化市二道江区","220521":"吉林省通化县","220523":"吉林省辉南县","220524":"吉林省柳河县","220581":"吉林省梅河口市","220582":"吉林省集安市","2206":"吉林省浑江市","220601":"吉林省浑江市市辖区","220602":"吉林省浑江市八道江区","220603":"吉林省浑江市三岔子区","220621":"吉林省抚松县","220622":"吉林省靖宇县","220623":"吉林省长白朝鲜族自治县","220681":"吉林省临江市","2207":"吉林省松原市","220701":"吉林省松原市市辖区","220702":"吉林省松原市扶余区","220721":"吉林省前郭尔罗斯蒙古族自治县","220722":"吉林省长岭县","220723":"吉林省乾安县","2208":"吉林省白城市","220801":"吉林省白城市市辖区","220802":"吉林省白城市洮北区","220821":"吉林省镇赍县","220822":"吉林省通榆县","220881":"吉林省洮南市","220882":"吉林省大安市","2224":"吉林省延边朝鲜族自治州","222401":"吉林省延吉市","222402":"吉林省图们市","222403":"吉林省敦化市","222404":"吉林省珲春市","222405":"吉林省龙井市","222406":"吉林省和龙市","222424":"吉林省汪清县","222426":"吉林省安图县","23":"黑龙江","2301":"黑龙江哈尔滨市","230101":"黑龙江哈尔滨市市辖区","230102":"黑龙江哈尔滨市道里区","230103":"黑龙江哈尔滨市南岗区","230104":"黑龙江哈尔滨市道外区","230105":"黑龙江哈尔滨市太平区","230106":"黑龙江哈尔滨市香坊区","230107":"黑龙江哈尔滨市动力区","230108":"黑龙江哈尔滨市平房区","230121":"黑龙江呼兰县","230123":"黑龙江依兰县","230124":"黑龙江方正县","230125":"黑龙江宾县","230181":"黑龙江阿城市","2302":"黑龙江齐齐哈尔市","230201":"黑龙江齐齐哈尔市市辖区","230202":"黑龙江齐齐哈尔市龙沙区","230203":"黑龙江齐齐哈尔市建华区","230204":"黑龙江齐齐哈尔市铁锋区","230205":"黑龙江齐齐哈尔市昂昂溪区","230206":"黑龙江齐齐哈尔市富拉尔基区","230207":"黑龙江齐齐哈尔市碾子山区","230208":"黑龙江齐齐哈尔市梅里斯达斡尔族","230221":"黑龙江龙江县","230223":"黑龙江依安县","230224":"黑龙江泰来县","230225":"黑龙江甘南县","230227":"黑龙江富裕县","230229":"黑龙江克山县","230230":"黑龙江克东县","230231":"黑龙江拜泉县","230281":"黑龙江讷河市","2303":"黑龙江鸡西市","230301":"黑龙江鸡西市市辖区","230302":"黑龙江鸡西市鸡冠区","230303":"黑龙江鸡西市恒山区","230304":"黑龙江鸡西市滴道区","230305":"黑龙江鸡西市梨树区","230306":"黑龙江鸡西市城子河区","230307":"黑龙江鸡西市麻山区","230321":"黑龙江鸡东县","230322":"黑龙江虎林县","2304":"黑龙江鹤岗市","230401":"黑龙江鹤岗市市辖区","230402":"黑龙江鹤岗市向阳区","230403":"黑龙江鹤岗市工农区","230404":"黑龙江鹤岗市南山区","230405":"黑龙江鹤岗市兴安区","230406":"黑龙江鹤岗市东山区","230407":"黑龙江鹤岗市兴山区","230421":"黑龙江萝北县","230422":"黑龙江绥滨县","2305":"黑龙江双鸭山市","230501":"黑龙江双鸭山市市辖区","230502":"黑龙江双鸭山市尖山区","230503":"黑龙江双鸭山市岭东区","230505":"黑龙江双鸭山市四方台区","230506":"黑龙江双鸭山市宝山区","230521":"黑龙江集贤县","230522":"黑龙江友谊县","230523":"黑龙江宝清县","230524":"黑龙江饶河县","2306":"黑龙江大庆市","230601":"黑龙江大庆市市辖区","230602":"黑龙江大庆市萨尔图区","230603":"黑龙江大庆市龙凤区","230604":"黑龙江大庆市让胡路区","230605":"黑龙江大庆市红岗区","230606":"黑龙江大庆市大同区","230621":"黑龙江肇州县","230622":"黑龙江肇源县","230623":"黑龙江林甸县","230624":"黑龙江杜尔伯特蒙古族自治县","2307":"黑龙江伊春市","230701":"黑龙江伊春市市辖区","230702":"黑龙江伊春市伊春区","230703":"黑龙江伊春市南岔区","230704":"黑龙江伊春市友好区","230705":"黑龙江伊春市西林区","230706":"黑龙江伊春市翠峦区","230707":"黑龙江伊春市新青区","230708":"黑龙江伊春市美溪区","230709":"黑龙江伊春市金山屯区","230710":"黑龙江伊春市五营区","230711":"黑龙江伊春市乌马河区","230712":"黑龙江伊春市汤旺河区","230713":"黑龙江伊春市带岭区","230714":"黑龙江伊春市乌伊岭区","230715":"黑龙江伊春市红星区","230716":"黑龙江伊春市上甘岭区","230722":"黑龙江嘉荫县","230781":"黑龙江铁力市","2308":"黑龙江佳木斯市","230801":"黑龙江佳木斯市市辖区","230802":"黑龙江佳木斯市永红区","230803":"黑龙江佳木斯市向阳区","230804":"黑龙江佳木斯市前进区","230805":"黑龙江佳木斯市东风区","230811":"黑龙江佳木斯市郊区","230822":"黑龙江桦南县","230826":"黑龙江桦川县","230828":"黑龙江汤原县","230833":"黑龙江扶远县","230881":"黑龙江同江市","230882":"黑龙江富锦市","2309":"黑龙江七台河市","230901":"黑龙江七台河市市辖区","230902":"黑龙江七台河市新兴区","230903":"黑龙江七台河市桃山区","230904":"黑龙江七台河市茄子河区","230921":"黑龙江勃利县","2310":"黑龙江牡丹江市","231001":"黑龙江牡丹江市市辖区","231002":"黑龙江牡丹江市东安区","231003":"黑龙江牡丹江市阳明区","231004":"黑龙江牡丹江市爱民区","231005":"黑龙江牡丹江市西安区","231011":"黑龙江牡丹江市郊区","231023":"黑龙江穆棱县","231024":"黑龙江东宁县","231025":"黑龙江林口县","231081":"黑龙江绥芬河市","231082":"黑龙江密山市","231083":"黑龙江海林市","231084":"黑龙江宁安市","2311":"黑龙江黑河市","231101":"黑龙江黑河市市辖区","231102":"黑龙江黑河市爱辉区","231121":"黑龙江嫩江县","231122":"黑龙江德都县","231123":"黑龙江逊克县","231124":"黑龙江孙吴县","231181":"黑龙江北安市","231182":"黑龙江五大连池市","2321":"黑龙江松花江地区","232101":"黑龙江双城市","232102":"黑龙江尚志市","232103":"黑龙江五常市","232126":"黑龙江巴彦县","232127":"黑龙江木兰县","232128":"黑龙江通河县","232131":"黑龙江延寿县","2323":"黑龙江绥化地区","232301":"黑龙江绥化市","232302":"黑龙江安达市","232303":"黑龙江肇东市","232304":"黑龙江海伦市","232324":"黑龙江望奎县","232325":"黑龙江兰西县","232326":"黑龙江青冈县","232330":"黑龙江庆安县","232331":"黑龙江明水县","232332":"黑龙江绥棱县","2327":"黑龙江大兴安岭地区","232721":"黑龙江呼玛县","232722":"黑龙江塔河县","232723":"黑龙江漠河县","31":"上海市","3101":"上海市市辖区","310101":"上海市黄浦区","310102":"上海市南市区","310103":"上海市卢湾区","310104":"上海市徐汇区","310105":"上海市长宁区","310106":"上海市静安区","310107":"上海市普陀区","310108":"上海市闸北区","310109":"上海市虹口区","310110":"上海市扬浦区","310112":"上海市闵行区","310113":"上海市宝山区","310114":"上海市嘉定区","310115":"上海市浦东新区","3102":"上海市市辖县","310225":"上海市南汇县","310226":"上海市奉贤县","310227":"上海市松江县","310228":"上海市金山县","310229":"上海市青浦县","310230":"上海市崇明县","32":"江苏省","3201":"江苏省南京市","320101":"江苏省南京市市辖区","320102":"江苏省南京市玄武区","320103":"江苏省南京市白下区","320104":"江苏省南京市秦淮区","320105":"江苏省南京市建邺区","320106":"江苏省南京市鼓楼区","320107":"江苏省南京市下关区","320111":"江苏省南京市浦口区","320112":"江苏省南京市大厂区","320113":"江苏省南京市栖霞区","320114":"江苏省南京市雨花台区","320121":"江苏省江宁县","320122":"江苏省江浦县","320123":"江苏省六合县","320124":"江苏省溧水县","320125":"江苏省高淳县","3202":"江苏省无锡市","320201":"江苏省无锡市市辖区","320202":"江苏省无锡市崇安区","320203":"江苏省无锡市南长区","320204":"江苏省无锡市北塘区","320211":"江苏省无锡市郊区","320212":"江苏省无锡市马山区","320222":"江苏省无锡县","320281":"江苏省江阴市","320282":"江苏省宜兴市","3203":"江苏省徐州市","320301":"江苏省徐州市市辖区","320302":"江苏省徐州市鼓楼区","320303":"江苏省徐州市云龙区","320304":"江苏省徐州市矿区","320305":"江苏省徐州市贾汪区","320311":"江苏省徐州市泉山区","320321":"江苏省丰县","320322":"江苏省沛县","320323":"江苏省铜山县","320324":"江苏省睢宁县","320381":"江苏省新沂市","320382":"江苏省邳州市","3204":"江苏省常州市","320401":"江苏省常州市市辖区","320402":"江苏省常州市天宁区","320404":"江苏省常州市钟楼区","320405":"江苏省常州市戚墅堰区","320411":"江苏省常州市郊区","320421":"江苏省武进县","320481":"江苏省溧阳市","320482":"江苏省金坛市","3205":"江苏省苏州市","320501":"江苏省苏州市市辖区","320502":"江苏省苏州市沧浪区","320503":"江苏省苏州市平江区","320504":"江苏省苏州市金阊区","320511":"江苏省苏州市郊区","320524":"江苏省吴县","320581":"江苏省常熟市","320582":"江苏省张家港市","320583":"江苏省昆山市","320584":"江苏省吴江市","320585":"江苏省太仓市","3206":"江苏省南通市","320601":"江苏省南通市市辖区","320602":"江苏省南通市崇川区","320611":"江苏省南通市港闸区","320621":"江苏省海安县","320623":"江苏省如东县","320625":"江苏省海门县","320681":"江苏省启东市","320682":"江苏省如皋市","320683":"江苏省通州市","3207":"江苏省连云港市","320701":"江苏省连云港市市辖区","320703":"江苏省连云港市连云区","320704":"江苏省连云港市云台区","320705":"江苏省连云港市新浦区","320706":"江苏省连云港市海州区","320721":"江苏省赣榆县","320722":"江苏省东海县","320723":"江苏省灌云县","3208":"江苏省淮阴市","320801":"江苏省淮阴市市辖区","320802":"江苏省淮阴市清河区","320811":"江苏省淮阴市清浦区","320821":"江苏省淮阴县","320822":"江苏省灌南县","320823":"江苏省沭阳县","320825":"江苏省泗阳县","320826":"江苏省涟水县","320827":"江苏省泗洪县","320829":"江苏省洪泽县","320830":"江苏省盱眙县","320831":"江苏省金湖县","320881":"江苏省宿迁市","320882":"江苏省淮安市","3209":"江苏省盐城市","320901":"江苏省盐城市市辖区","320902":"江苏省盐城市城区","320911":"江苏省盐城市郊区","320921":"江苏省响水县","320922":"江苏省滨海县","320923":"江苏省阜宁县","320924":"江苏省射阳县","320925":"江苏省建湖县","320926":"江苏省大丰县","320981":"江苏省东台市","3210":"江苏省扬州市","321001":"江苏省扬州市市辖区","321002":"江苏省扬州市广陵区","321011":"江苏省扬州市郊区","321023":"江苏省宝应县","321026":"江苏省江都县","321027":"江苏省邗江县","321028":"江苏省泰县","321081":"江苏省仪征市","321082":"江苏省泰州市","321083":"江苏省兴化市","321084":"江苏省高邮市","321085":"江苏省泰兴市","321086":"江苏省靖江市","3211":"江苏省镇江市","321101":"江苏省镇江市市辖区","321102":"江苏省镇江市京口区","321111":"江苏省镇江市润州区","321121":"江苏省丹徒县","321123":"江苏省句容县","321124":"江苏省扬中县","321181":"江苏省丹阳市","33":"浙江省","3301":"浙江省杭州市","330101":"浙江省杭州市市辖区","330102":"浙江省杭州市上城区","330103":"浙江省杭州市下城区","330104":"浙江省杭州市江干区","330105":"浙江省杭州市拱墅区","330106":"浙江省杭州市西湖区","330122":"浙江省桐庐县","330123":"浙江省富阳县","330124":"浙江省临安县","330125":"浙江省余杭县","330126":"浙江省建德县","330127":"浙江省淳安县","330181":"浙江省萧山市","3302":"浙江省宁波市","330201":"浙江省宁波市市辖区","330203":"浙江省宁波市海曙区","330204":"浙江省宁波市江东区","330205":"浙江省宁波市江北区","330206":"浙江省宁波市北仓区","330211":"浙江省宁波市镇海区","330225":"浙江省象山县","330226":"浙江省宁海县","330227":"浙江省鄞县","330281":"浙江省余姚市","330282":"浙江省慈溪市","330283":"浙江省奉化市","3303":"浙江省温州市","330301":"浙江省温州市市辖区","330302":"浙江省温州市鹿城区","330303":"浙江省温州市龙湾区","330304":"浙江省温州市瓯海区","330322":"浙江省洞头县","330324":"浙江省永嘉县","330326":"浙江省平阳县","330327":"浙江省苍南县","330328":"浙江省文成县","330329":"浙江省泰顺县","330381":"浙江省瑞安市","330382":"浙江省乐清市","3304":"浙江省嘉兴市","330401":"浙江省嘉兴市市辖区","330402":"浙江省嘉兴市城区","330411":"浙江省嘉兴市郊区","330421":"浙江省嘉善县","330424":"浙江省海盐县","330481":"浙江省海宁市","330482":"浙江省平湖市","330483":"浙江省桐乡市","3305":"浙江省湖洲市","330501":"浙江省湖洲市市辖区","330521":"浙江省德清县","330522":"浙江省长兴县","330523":"浙江省安吉县","3306":"浙江省绍兴市","330601":"浙江省绍兴市市辖区","330602":"浙江省绍兴市越城区","330621":"浙江省绍兴县","330623":"浙江省嵊县","330624":"浙江省新昌县","330681":"浙江省诸暨市","330682":"浙江省上虞市","3307":"浙江省金华市","330701":"浙江省金华市市辖区","330702":"浙江省金华市婺城区","330721":"浙江省金华县","330723":"浙江省武义县","330726":"浙江省浦江县","330727":"浙江省磐安县","330728":"浙江省永康市","330781":"浙江省兰溪市","330782":"浙江省义乌市","330783":"浙江省东阳市","3308":"浙江省衢州市","330801":"浙江省衢州市市辖区","330802":"浙江省衢州市柯城区","330821":"浙江省衢县","330822":"浙江省常山县","330824":"浙江省开化县","330825":"浙江省龙游县","330881":"浙江省江山市","3309":"浙江省舟山市","330901":"浙江省舟山市市辖区","330902":"浙江省舟山市定海区","330903":"浙江省舟山市普陀区","330921":"浙江省岱山县","330922":"浙江省嵊泗县","3325":"浙江省丽水地区","332501":"浙江省丽水市","332502":"浙江省龙泉市","332522":"浙江省青田县","332523":"浙江省云和县","332525":"浙江省庆元县","332526":"浙江省缙云县","332527":"浙江省遂昌县","332528":"浙江省松阳县","332529":"浙江省景宁畲族自治县","3326":"浙江省台州地区","332601":"浙江省椒江市","332602":"浙江省临海市","332603":"浙江省黄岩市","332623":"浙江省温岭县","332624":"浙江省仙居县","332625":"浙江省天台县","332626":"浙江省三门县","332627":"浙江省玉环县","34":"安徽省","3401":"安徽省合肥市","340101":"安徽省合肥市市辖区","340102":"安徽省合肥市东市区","340103":"安徽省合肥市中市区","340104":"安徽省合肥市西市区","340111":"安徽省合肥市郊区","340121":"安徽省长丰县","340122":"安徽省肥东县","340123":"安徽省肥西县","3402":"安徽省芜湖市","340201":"安徽省芜湖市市辖区","340202":"安徽省芜湖市镜湖区","340203":"安徽省芜湖市马塘区","340204":"安徽省芜湖市新芜区","340207":"安徽省芜湖市鸠江区","340221":"安徽省芜湖县","340222":"安徽省繁昌县","340223":"安徽省南陵县","3403":"安徽省蚌埠市","340301":"安徽省蚌埠市市辖区","340302":"安徽省蚌埠市东市区","340303":"安徽省蚌埠市中市区","340304":"安徽省蚌埠市西市区","340311":"安徽省蚌埠市郊区","340321":"安徽省怀远县","340322":"安徽省五河县","340323":"安徽省固镇县","3404":"安徽省淮南市","340401":"安徽省淮南市市辖区","340402":"安徽省淮南市大通区","340403":"安徽省淮南市田家庵区","340404":"安徽省淮南市谢家集区","340405":"安徽省淮南市八公山区","340406":"安徽省淮南市潘集区","340421":"安徽省凤台县","3405":"安徽省马鞍山市","340501":"安徽省马鞍山市市辖区","340502":"安徽省马鞍山市金家庄区","340503":"安徽省马鞍山市花山区","340504":"安徽省马鞍山市雨山区","340505":"安徽省马鞍山市向山区","340521":"安徽省当涂县","3406":"安徽省淮北市","340601":"安徽省淮北市市辖区","340602":"安徽省淮北市杜集区","340603":"安徽省淮北市相山区","340604":"安徽省淮北市烈山区","340621":"安徽省濉溪县","3407":"安徽省铜陵市","340701":"安徽省铜陵市市辖区","340702":"安徽省铜陵市铜官山区","340703":"安徽省铜陵市狮子山区","340711":"安徽省铜陵市郊区","340721":"安徽省铜陵县","3408":"安徽省安庆市","340801":"安徽省安庆市市辖区","340802":"安徽省安庆市迎江区","340803":"安徽省安庆市大观区","340811":"安徽省安庆市郊区","340821":"安徽省桐城县","340822":"安徽省怀宁县","340823":"安徽省枞阳县","340824":"安徽省潜山县","340825":"安徽省太湖县","340826":"安徽省宿松县","340827":"安徽省望江县","340828":"安徽省岳西县","3410":"安徽省黄山市","341001":"安徽省黄山市市辖区","341002":"安徽省黄山市屯溪区","341003":"安徽省黄山市黄山区","341004":"安徽省黄山市徽州区","341021":"安徽省歙县","341022":"安徽省休宁县","341023":"安徽省黟县","341024":"安徽省祁门县","3411":"安徽省滁州市","341101":"安徽省滁州市市辖区","341102":"安徽省滁州市琅琊区","341103":"安徽省滁州市南谯区","341122":"安徽省来安县","341124":"安徽省全椒县","341125":"安徽省定远县","341126":"安徽省凤阳县","341127":"安徽省嘉山县","341181":"安徽省天长县","3421":"安徽省阜阳地区","342101":"安徽省阜阳市","342102":"安徽省毫州市","342103":"安徽省界首市","342122":"安徽省临泉县","342123":"安徽省太和县","342124":"安徽省涡阳县","342125":"安徽省蒙城县","342127":"安徽省阜南县","342128":"安徽省颖上县","342130":"安徽省利辛县","3422":"安徽省宿县地区","342201":"安徽省宿州市","342221":"安徽省砀山县","342222":"安徽省萧县","342224":"安徽省灵壁县","342225":"安徽省泗县","3424":"安徽省六安地区","342401":"安徽省六安市","342422":"安徽省寿县","342423":"安徽省霍邱县","342425":"安徽省舒城县","342426":"安徽省金寨县","342427":"安徽省霍山县","3425":"安徽省宣城地区","342501":"安徽省宣州市","342522":"安徽省郎溪县","342523":"安徽省广德县","342524":"安徽省宁国县","342529":"安徽省泾县","342530":"安徽省旌德县","342531":"安徽省绩溪县","3426":"安徽省巢湖地区","342601":"安徽省巢湖市","342622":"安徽省庐江县","342623":"安徽省无为县","342625":"安徽省含山县","342626":"安徽省和县","3429":"安徽省池州地区","342901":"安徽省贵池县","342921":"安徽省东至县","342922":"安徽省石台县","342923":"安徽省青阳县","35":"福建省","3501":"福建省福州市","350101":"福建省福州市市辖区","350102":"福建省福州市鼓楼区","350103":"福建省福州市台江区","350104":"福建省福州市仓山区","350105":"福建省福州市马尾区","350111":"福建省福州市郊区","350121":"福建省闽侯县","350122":"福建省连江县","350123":"福建省罗源县","350124":"福建省闽清县","350125":"福建省永泰县","350126":"福建省长乐县","350128":"福建省平潭县","350181":"福建省福清市","3502":"福建省厦门市","350201":"福建省厦门市市辖区","350202":"福建省厦门市鼓浪屿区","350203":"福建省厦门市思明区","350204":"福建省厦门市开元区","350205":"福建省厦门市杏林区","350206":"福建省厦门市湖里区","350211":"福建省厦门市集美区","350221":"福建省同安县","3503":"福建省莆田市","350301":"福建省莆田市市辖区","350302":"福建省莆田市城厢区","350303":"福建省莆田市涵江区","350321":"福建省莆田县","350322":"福建省仙游县","3504":"福建省三明市","350401":"福建省三明市市辖区","350402":"福建省三明市梅列区","350403":"福建省三明市三元区","350421":"福建省明溪县","350423":"福建省清流县","350424":"福建省宁化县","350425":"福建省大田县","350426":"福建省尤溪县","350427":"福建省沙县","350428":"福建省将乐县","350429":"福建省泰宁县","350430":"福建省建宁县","350481":"福建省永安市","3505":"福建省泉州市","350501":"福建省泉州市市辖区","350502":"福建省泉州市鲤城区","350521":"福建省惠安县","350524":"福建省安溪县","350525":"福建省永春县","350526":"福建省德化县","350527":"福建省金门县","350581":"福建省石狮市","350582":"福建省晋江市","350583":"福建省南安市","3506":"福建省漳州市","350601":"福建省漳州市市辖区","350602":"福建省漳州市芗城区","350622":"福建省云霄县","350623":"福建省漳浦县","350624":"福建省诏安县","350625":"福建省长泰县","350626":"福建省东山县","350627":"福建省南靖县","350628":"福建省平和县","350629":"福建省华安县","350681":"福建省龙海市","3521":"福建省南平地区","352101":"福建省南平市","352102":"福建省邵武市","352103":"福建省武夷山市","352104":"福建省建瓯市","352121":"福建省顺昌县","352122":"福建省建阳县","352124":"福建省浦城县","352127":"福建省光泽县","352128":"福建省松溪县","352129":"福建省政和县","3522":"福建省宁德地区","352201":"福建省宁德市","352202":"福建省福安市","352224":"福建省福鼎县","352225":"福建省霞浦县","352227":"福建省古田县","352228":"福建省屏南县","352229":"福建省寿宁县","352230":"福建省周宁县","352231":"福建省柘荣县","3526":"福建省龙岩地区","352601":"福建省龙岩市","352602":"福建省漳平市","352622":"福建省长汀县","352623":"福建省永定县","352624":"福建省上杭县","352625":"福建省武平县","352627":"福建省连城县","36":"江西省","3601":"江西省南昌市","360101":"江西省南昌市市辖区","360102":"江西省南昌市东湖区","360103":"江西省南昌市西湖区","360104":"江西省南昌市青云谱区","360105":"江西省南昌市湾里区","360111":"江西省南昌市郊区","360121":"江西省南昌县","360122":"江西省新建县","360123":"江西省安义县","360124":"江西省进贤县","3602":"江西省景德镇市","360201":"江西省景德镇市市辖区","360202":"江西省景德镇市昌江区","360203":"江西省景德镇市珠山区","360222":"江西省浮梁县","360281":"江西省乐平市","3603":"江西省萍乡市","360301":"江西省萍乡市市辖区","360302":"江西省萍乡市安源区","360311":"江西省萍乡市上栗区","360312":"江西省萍乡市芦溪区","360313":"江西省萍乡市湘东区","360321":"江西省莲花县","3604":"江西省九江市","360401":"江西省九江市市辖区","360402":"江西省九江市庐山区","360403":"江西省浔阳县","360421":"江西省九江县","360423":"江西省武宁县","360424":"江西省修水县","360425":"江西省永修县","360426":"江西省德安县","360427":"江西省星子县","360428":"江西省都昌县","360429":"江西省湖口县","360430":"江西省彭泽县","360481":"江西省瑞昌市","3605":"江西省新余市","360501":"江西省新余市市辖区","360502":"江西省新余市渝水区","360521":"江西省分宜县","3606":"江西省鹰潭市","360601":"江西省鹰潭市市辖区","360602":"江西省鹰潭市月湖区","360621":"江西省贵溪县","360622":"江西省余江县","3621":"江西省赣州地区","362101":"江西省赣州市","362121":"江西省赣县","362122":"江西省南康县","362123":"江西省信丰县","362124":"江西省大余县","362125":"江西省上犹县","362126":"江西省崇义县","362127":"江西省安远县","362128":"江西省龙南县","362129":"江西省定南县","362130":"江西省全南县","362131":"江西省宁都县","362132":"江西省于都县","362133":"江西省兴国县","362134":"江西省瑞金县","362135":"江西省会昌县","362136":"江西省寻乌县","362137":"江西省石城县","3622":"江西省宜春地区","362201":"江西省宜春市","362202":"江西省丰城市","362203":"江西省樟树市","362204":"江西省高安市","362226":"江西省奉新县","362227":"江西省万载县","362228":"江西省上高县","362229":"江西省宜丰县","362232":"江西省靖安县","362233":"江西省铜鼓县","3623":"江西省上饶地区","362301":"江西省上饶市","362302":"江西省德兴市","362321":"江西省上饶县","362322":"江西省广丰县","362323":"江西省玉山县","362324":"江西省铅山县","362325":"江西省横峰县","362326":"江西省弋阳县","362329":"江西省余干县","362330":"江西省波阳县","362331":"江西省万年县","362334":"江西省婺源县","3624":"江西省吉安地区","362401":"江西省吉安市","362402":"江西省井岗山市","362421":"江西省吉安县","362422":"江西省吉水县","362423":"江西省峡江县","362424":"江西省新干县","362425":"江西省永丰县","362426":"江西省泰和县","362427":"江西省遂川县","362428":"江西省万安县","362429":"江西省安福县","362430":"江西省永新县","362432":"江西省宁冈县","3625":"江西省抚州地区","362502":"江西省临川市","362522":"江西省南城县","362523":"江西省黎川县","362524":"江西省南丰县","362525":"江西省崇仁县","362526":"江西省乐安县","362527":"江西省宜黄县","362528":"江西省金溪县","362529":"江西省资溪县","362531":"江西省东乡县","362532":"江西省广昌县","37":"山东省","3701":"山东省济南市","370101":"山东省济南市市辖区","370102":"山东省济南市历下区","370103":"山东省济南市市中区","370104":"山东省济南市槐荫区","370105":"山东省济南市天桥区","370112":"山东省济南市历城区","370123":"山东省长清县","370124":"山东省平阴县","370125":"山东省商河县","370126":"山东省济阳县","370181":"山东省章丘市","3702":"山东省青岛市","370201":"山东省青岛市市辖区","370202":"山东省青岛市市南区","370203":"山东省青岛市市北区","370204":"山东省青岛市台东区","370205":"山东省青岛市四方区","370206":"山东省青岛市沧口区","370211":"山东省青岛市黄岛区","370212":"山东省青岛市崂山区","370281":"山东省胶州市","370282":"山东省即墨市","370283":"山东省平度市","370284":"山东省胶南市","370285":"山东省菜西市","3703":"山东省淄博市","370301":"山东省淄博市市辖区","370302":"山东省淄博市淄川区","370303":"山东省淄博市张店区","370304":"山东省淄博市博山区","370305":"山东省淄博市临淄区","370306":"山东省淄博市周村区","370321":"山东省桓台县","370322":"山东省高青县","370323":"山东省沂源县","3704":"山东省枣庄市","370401":"山东省枣庄市市辖区","370402":"山东省枣庄市市中区","370403":"山东省枣庄市薛城区","370404":"山东省枣庄市峄城区","370405":"山东省枣庄市台儿庄区","370406":"山东省枣庄市山亭区","370481":"山东省滕州市","3705":"山东省东营市","370501":"山东省东营市市辖区","370502":"山东省东营市东营区","370503":"山东省东营市河口区","370521":"山东省垦利县","370522":"山东省利津县","370523":"山东省广饶县","3706":"山东省烟台市","370601":"山东省烟台市市辖区","370602":"山东省烟台市芝罘区","370611":"山东省烟台市福山区","370628":"山东省栖霞县","370629":"山东省海阳县","370631":"山东省牟平县","370634":"山东省长岛县","370681":"山东省龙口市","370682":"山东省莱阳市","370683":"山东省莱州市","370684":"山东省蓬莱市","370685":"山东省招远市","3707":"山东省潍坊市","370701":"山东省潍坊市市辖区","370702":"山东省潍坊市潍城区","370703":"山东省潍坊市寒亭区","370704":"山东省潍坊市坊子区","370722":"山东省安丘县","370724":"山东省临朐县","370725":"山东省昌乐县","370726":"山东省昌邑县","370727":"山东省高密县","370781":"山东省青州市","370782":"山东省诸城市","370783":"山东省寿光市","3708":"山东省济宁市","370801":"山东省济宁市市辖区","370802":"山东省济宁市市中区","370811":"山东省济宁市任城区","370826":"山东省微山县","370827":"山东省鱼台县","370828":"山东省金乡县","370829":"山东省嘉祥县","370830":"山东省汶上县","370831":"山东省泗水县","370832":"山东省梁山县","370881":"山东省曲阜市","370882":"山东省兖州市","370883":"山东省邹城市","3709":"山东省泰安市","370901":"山东省泰安市市辖区","370902":"山东省泰安市泰山区","370911":"山东省泰安市郊区","370921":"山东省宁阳县","370923":"山东省东平县","370982":"山东省新泰市","370983":"山东省肥城市","3710":"山东省威海市","371001":"山东省威海市市辖区","371002":"山东省威海市环翠区","371081":"山东省文登市","371082":"山东省荣城市","371083":"山东省乳山市","3711":"山东省日照市","371101":"山东省日照市市辖区","371102":"山东省日照市东港区","371121":"山东省五莲县","371122":"山东省莒县","3712":"山东省莱芜市","371201":"山东省莱芜市市辖区","371202":"山东省莱芜市莱城区","371203":"山东省莱芜市钢城区","3723":"山东省滨州地区","372301":"山东省滨州市","372321":"山东省惠民县","372323":"山东省阳信县","372324":"山东省无棣县","372325":"山东省沾化县","372328":"山东省博兴县","372330":"山东省邹平县","3724":"山东省德州地区","372401":"山东省德州市","372402":"山东省乐陵市","372403":"山东省禹城市","372421":"山东省陵县","372422":"山东省平原县","372423":"山东省夏津县","372424":"山东省武城县","372425":"山东省齐河县","372428":"山东省临邑县","372431":"山东省宁津县","372432":"山东省庆云县","3725":"山东省聊城地区","372501":"山东省聊城市","372502":"山东省临清市","372522":"山东省阳谷县","372523":"山东省莘县","372524":"山东省茌平县","372525":"山东省东阿县","372526":"山东省冠县","372527":"山东省高唐县","3728":"山东省临沂地区","372801":"山东省临沂市","372822":"山东省郯城县","372823":"山东省苍山县","372824":"山东省莒南县","372827":"山东省沂水县","372829":"山东省蒙阴县","372830":"山东省平邑县","372831":"山东省费县","372832":"山东省沂南县","372833":"山东省临沭县","3729":"山东省菏泽地区","372901":"山东省菏泽市","372922":"山东省曹县","372923":"山东省定陶县","372924":"山东省成武县","372925":"山东省单县","372926":"山东省巨野县","372928":"山东省郓城县","372929":"山东省鄄城县","372930":"山东省东明县","41":"河南省","4101":"河南省郑州市","410101":"河南省郑州市市辖区","410102":"河南省郑州市中原区","410103":"河南省郑州市二七区","410104":"河南省郑州市管城回族区","410105":"河南省郑州市金水区","410106":"河南省郑州市上街区","410108":"河南省郑州市邙山区","410121":"河南省荥阳县","410122":"河南省中牟县","410123":"河南省新郑县","410125":"河南省登封县","410126":"河南省密县","410181":"河南省巩义市","4102":"河南省开封市","410201":"河南省开封市市辖区","410202":"河南省开封市龙亭区","410203":"河南省开封市顺河回族区","410204":"河南省开封市鼓楼区","410205":"河南省开封市南关区","410211":"河南省开封市郊区","410221":"河南省杞县","410222":"河南省通许县","410223":"河南省尉氏县","410224":"河南省开封县","410225":"河南省兰考县","4103":"河南省洛阳市","410301":"河南省洛阳市市辖区","410302":"河南省洛阳市老城区","410303":"河南省洛阳市西工区","410304":"河南省洛阳市廛河回族区","410305":"河南省洛阳市涧西区","410306":"河南省洛阳市吉利区","410311":"河南省洛阳市郊区","410322":"河南省孟津县","410323":"河南省新安县","410324":"河南省栾川县","410325":"河南省嵩县","410326":"河南省汝阳县","410327":"河南省宜阳县","410328":"河南省洛宁县","410329":"河南省伊川县","410381":"河南省偃师市","4104":"河南省平顶山市","410401":"河南省平顶山市市辖区","410402":"河南省平顶山市新华区","410403":"河南省平顶山市卫东区","410411":"河南省平顶山市郊区","410421":"河南省宝丰县","410422":"河南省叶县","410423":"河南省鲁山县","410425":"河南省郏县","410426":"河南省襄城县","410481":"河南省舞钢市","410482":"河南省汝州市","4105":"河南省安阳市","410501":"河南省安阳市市辖区","410502":"河南省安阳市文峰区","410503":"河南省安阳市北关区","410504":"河南省安阳市铁西区","410511":"河南省安阳市郊区","410521":"河南省林县","410522":"河南省安阳县","410523":"河南省汤阴县","410526":"河南省滑县","410527":"河南省内黄县","4106":"河南省鹤壁市","410601":"河南省鹤壁市市辖区","410602":"河南省鹤壁市鹤山区","410603":"河南省鹤壁市山城区","410611":"河南省鹤壁市郊区","410621":"河南省浚县","410622":"河南省淇县","4107":"河南省新乡市      ","410701":"河南省新乡市市辖区","410702":"河南省新乡市红旗区","410703":"河南省新乡市新华区","410704":"河南省新乡市北站区","410711":"河南省新乡市郊区","410721":"河南省新乡县","410724":"河南省获嘉县","410725":"河南省原阳县","410726":"河南省延津县","410727":"河南省封丘县","410728":"河南省长恒县","410781":"河南省卫辉市","410782":"河南省辉县市","4108":"河南省焦作市","410801":"河南省焦作市市辖区","410802":"河南省焦作市解放区","410803":"河南省焦作市中站区","410804":"河南省焦作市马村区","410811":"河南省焦作市山阳区","410821":"河南省修武县","410822":"河南省博爱县","410823":"河南省武陟县","410825":"河南省温县","410826":"河南省孟县","410881":"河南省济源市","410882":"河南省沁阳市","4109":"河南省濮阳市","410901":"河南省濮阳市市辖区","410902":"河南省濮阳市市区","410922":"河南省清丰县","410923":"河南省南乐县","410926":"河南省范县","410927":"河南省台前县","410928":"河南省濮阳县","4110":"河南省许昌市","411001":"河南省许昌市市辖区","411002":"河南省许昌市魏都区","411023":"河南省许昌县","411024":"河南省鄢陵县","411081":"河南省禹州市","411082":"河南省长葛市","4111":"河南省漯河市","411101":"河南省漯河市市辖区","411102":"河南省漯河市源仁区","411121":"河南省舞阳县","411122":"河南省临颖县","411123":"河南省郾城县","4112":"河南省三门峡市","411201":"河南省三门峡市市辖区","411202":"河南省三门峡市湖滨区","411221":"河南省渑池县","411222":"河南省陕县","411224":"河南省卢氏县","411281":"河南省义马市","411282":"河南省灵宝市","4123":"河南省商丘地区","412301":"河南省商丘市","412321":"河南省虞城县","412322":"河南省商丘县","412323":"河南省民权县","412324":"河南省宁陵县","412325":"河南省睢县","412326":"河南省夏邑县","412327":"河南省柘城县","412328":"河南省永城县","4127":"河南省周口地区","412701":"河南省周口市","412702":"河南省项城市","412721":"河南省扶沟县","412722":"河南省西华县","412723":"河南省商水县","412724":"河南省太康县","412725":"河南省鹿邑县","412726":"河南省郸城县","412727":"河南省淮阳县","412728":"河南省沈丘县","4128":"河南省驻马店地区","412801":"河南省驻马店市","412821":"河南省确山县","412822":"河南省泌阳县","412823":"河南省遂平县","412824":"河南省西平县","412825":"河南省上蔡县","412826":"河南省汝南县","412827":"河南省平舆县","412828":"河南省新蔡县","412829":"河南省正阳县","4129":"河南省南阳地区","412901":"河南省南阳市","412902":"河南省邓州市","412921":"河南省南召县","412922":"河南省方城县","412923":"河南省西峡县","412924":"河南省南阳县","412925":"河南省镇平县","412926":"河南省内乡县","412927":"河南省淅川县","412928":"河南省社旗县","412929":"河南省唐河县","412931":"河南省新野县","412932":"河南省桐柏县","4130":"河南省信阳地区","413001":"河南省信阳市","413021":"河南省息县","413022":"河南省淮滨县","413023":"河南省信阳县","413024":"河南省横川县","413025":"河南省光山县","413026":"河南省固始县","413027":"河南省商城县","413028":"河南省罗山县","413029":"河南省新县","42":"湖北省","4201":"湖北省武汉市","420101":"湖北省武汉市市辖区","420102":"湖北省武汉市江岸区","420103":"湖北省武汉市江汉区","420104":"湖北省武汉市乔口区","420105":"湖北省武汉市汉阳区","420106":"湖北省武汉市武昌区","420107":"湖北省武汉市青山区","420111":"湖北省武汉市洪山区","420112":"湖北省武汉市东西湖区","420113":"湖北省武汉市汉南区","420114":"湖北省蔡甸区","420122":"湖北省武昌县","420123":"湖北省黄陂县","420124":"湖北省新洲县","4202":"湖北省黄石市","420201":"湖北省黄石市市辖区","420202":"湖北省黄石市黄石港区","420203":"湖北省黄石市石灰窑区","420204":"湖北省黄石市下陆区","420205":"湖北省黄石市铁山区","420221":"湖北省大冶县","4203":"湖北省十堰市","420301":"湖北省十堰市市辖区","420302":"湖北省十堰市茅箭区","420303":"湖北省十堰市张湾区","4204":"湖北省沙市市","420400":"湖北省沙市市","4205":"湖北省宜昌市","420501":"湖北省宜昌市市辖区","420502":"湖北省宜昌市西陵区","420503":"湖北省宜昌市伍家岗区","420504":"湖北省宜昌市点军区","420521":"湖北省宜昌县","420523":"湖北省枝江县","420525":"湖北省远安县","420526":"湖北省兴山县","420527":"湖北省秭归县","420528":"湖北省长阳土家族自治县","420529":"湖北省五峰土家族自治县","420581":"湖北省枝城市","420582":"湖北省当阳市","4206":"湖北省襄樊市","420601":"湖北省襄樊市市辖区","420602":"湖北省襄樊市襄城区","420603":"湖北省襄樊市樊东区","420604":"湖北省襄樊市樊西区","420605":"湖北省襄樊市郊区","420621":"湖北省襄阳县","420623":"湖北省宜城县","420624":"湖北省南漳县","420625":"湖北省谷城县","420626":"湖北省保康县","420681":"湖北省随州市","420682":"湖北省老河口市","420683":"湖北省枣阳市","4207":"湖北省鄂州市","420701":"湖北省鄂州市市辖区","420702":"湖北省鄂州市梁子湖区","420703":"湖北省鄂州市谷容区","420704":"湖北省鄂州市鄂城区","4208":"湖北省荆门市","420801":"湖北省荆门市市辖区","420802":"湖北省荆门市东宝区","420803":"湖北省荆门市沙洋区","4209":"湖北省孝感市","420901":"湖北省孝感市市辖区","420902":"湖北省孝感市孝南区","420903":"湖北省孝感市孝昌区","420922":"湖北省大悟县","420923":"湖北省云梦县","420924":"湖北省汉川县","420981":"湖北省应城市","420982":"湖北省安陆市","420983":"湖北省广水市","4221":"湖北省黄冈地区","422101":"湖北省麻城市","422102":"湖北省武穴市      ","422103":"湖北省黄州市","422123":"湖北省红安县","422125":"湖北省罗田县","422126":"湖北省英山县","422127":"湖北省浠水县","422128":"湖北省蕲春县","422130":"湖北省黄梅县","4223":"湖北省咸宁地区","422301":"湖北省咸宁市","422302":"湖北省蒲圻市","422322":"湖北省嘉鱼县","422324":"湖北省通城县","422325":"湖北省崇阳县","422326":"湖北省通山县","422327":"湖北省阳新县","4224":"湖北省荆州地区","422401":"湖北省仙桃市","422402":"湖北省石首市","422403":"湖北省洪湖市","422404":"湖北省天门市","422405":"湖北省潜江市","422406":"湖北省钟祥市","422421":"湖北省江陵县","422422":"湖北省松滋县","422423":"湖北省公安县","422425":"湖北省监利县","422432":"湖北省京山县","4226":"湖北省郧阳地区","422601":"湖北省丹江口市","422622":"湖北省郧县","422623":"湖北省郧西县","422624":"湖北省竹山县","422625":"湖北省竹溪县","422626":"湖北省房县","4228":"湖北省恩施土家族苗族自治州","422801":"湖北省恩施市","422802":"湖北省利川市","422822":"湖北省建始县","422823":"湖北省巴东县","422825":"湖北省宣恩县","422826":"湖北省咸丰县","422827":"湖北省来凤县","422828":"湖北省鹤峰县","4229":"湖北省省直辖行政单位","422921":"湖北省神农架林区","43":"湖南省","4301":"湖南省长沙市","430101":"湖南省长沙市市辖区","430102":"湖南省长沙市东区","430103":"湖南省长沙市南区","430104":"湖南省长沙市西区","430105":"湖南省长沙市北区","430111":"湖南省长沙市郊区","430121":"湖南省长沙县  ","430122":"湖南省望城县","430124":"湖南省宁乡县","430181":"湖南省浏阳市","4302":"湖南省株洲市","430201":"湖南省株洲市市辖区","430202":"湖南省株洲市东区","430203":"湖南省株洲市北区","430204":"湖南省株洲市南区","430211":"湖南省株洲市郊区","430221":"湖南省株洲县","430223":"湖南省攸县","430224":"湖南省茶陵县","430225":"湖南省酃县","430281":"湖南省醴陵市","4303":"湖南省湘潭市","430301":"湖南省湘潭市市辖区","430302":"湖南省湘潭市雨湖区","430304":"湖南省湘潭市岳塘区","430321":"湖南省湘潭县","430381":"湖南省湘乡市","430382":"湖南省韶山市","4304":"湖南省衡阳市","430401":"湖南省衡阳市市辖区","430402":"湖南省衡阳市江东区","430403":"湖南省衡阳市城南区","430404":"湖南省衡阳市城北区","430411":"湖南省衡阳市郊区","430412":"湖南省衡阳市南岳区","430421":"湖南省衡阳县","430422":"湖南省衡南县","430423":"湖南省衡山县","430424":"湖南省衡东县","430425":"湖南省常宁县","430426":"湖南省祁东县","430481":"湖南省耒阳市","4305":"湖南省邵阳市","430501":"湖南省邵阳市市辖区","430502":"湖南省邵阳市东区","430503":"湖南省邵阳市西区","430511":"湖南省邵阳市郊区","430521":"湖南省邵东县","430522":"湖南省新邵县","430523":"湖南省邵阳县","430524":"湖南省隆回县","430525":"湖南省洞口县","430526":"湖南省武冈县","430527":"湖南省绥宁县","430528":"湖南省新宁县","430529":"湖南省城步苗族自治县","4306":"湖南省岳阳市","430601":"湖南省岳阳市市辖区","430602":"湖南省岳阳市南区","430603":"湖南省岳阳市北区","430611":"湖南省岳阳市郊区","430621":"湖南省岳阳县","430623":"湖南省华容县","430624":"湖南省湘阴县","430626":"湖南省平江县","430681":"湖南省汨罗市","430682":"湖南省临湘市","4307":"湖南省常德市","430701":"湖南省常德市市辖区","430702":"湖南省常德市武陵区","430703":"湖南省常德市鼎城区","430721":"湖南省安乡县","430722":"湖南省汉寿县","430723":"湖南省澧县","430724":"湖南省临澧县","430725":"湖南省桃源县","430726":"湖南省石门县","430781":"湖南省津市市","4308":"湖南省大庸市","430801":"湖南省大庸市市辖区","430802":"湖南省大庸市永定区","430811":"湖南省大庸市武陵源区","430821":"湖南省慈利县","430822":"湖南省桑植县","4323":"湖南省益阳地区","432301":"湖南省益阳市","432302":"湖南省沅江市","432321":"湖南省益阳县","432322":"湖南省南县","432325":"湖南省桃江县","432326":"湖南省安化县","4325":"湖南省娄底地区","432501":"湖南省娄底市","432502":"湖南省冷水江市","432503":"湖南省涟源市","432522":"湖南省双峰县","432524":"湖南省新化县","4328":"湖南省郴州地区","432801":"湖南省郴州市","432802":"湖南省资兴市","432821":"湖南省郴县","432822":"湖南省桂阳县","432823":"湖南省永兴县","432824":"湖南省宜章县","432826":"湖南省嘉禾县","432827":"湖南省临武县","432828":"湖南省汝城县","432829":"湖南省桂东县","432831":"湖南省安仁县","4329":"湖南省零陵地区","432901":"湖南省永州市","432902":"湖南省冷水滩市","432922":"湖南省东安县","432923":"湖南省道县","432924":"湖南省宁远县","432925":"湖南省江永县","432926":"湖南省江华瑶族自治县","432927":"湖南省蓝山县","432928":"湖南省新田县 ","432929":"湖南省双牌县","432930":"湖南省祁阳县","4330":"湖南省怀化地区","433001":"湖南省怀化市","433002":"湖南省洪江市","433021":"湖南省黔阳县","433022":"湖南省沅陵县","433023":"湖南省辰溪县","433024":"湖南省溆浦县","433025":"湖南省麻阳苗族自治县","433026":"湖南省新晃侗族自治县","433027":"湖南省芷江侗族自治县","433029":"湖南省会同县","433030":"湖南省靖州苗族侗族自治县","433031":"湖南省通道侗族自治县","4331":"湖南省湘西土家族苗族自治州","433101":"湖南省吉首市","433122":"湖南省泸溪县","433123":"湖南省风凰县","433124":"湖南省花垣县","433125":"湖南省保靖县","433126":"湖南省古丈县","433127":"湖南省永顺县","433130":"湖南省龙山县","44":"广东省","4401":"广东省广州市","440101":"广东省广州市市辖区","440102":"广东省广州市东山区","440103":"广东省广州市荔湾区","440104":"广东省广州市越秀区","440105":"广东省广州市海珠区","440106":"广东省广州市天河区","440107":"广东省广州市芳村区","440111":"广东省广州市白云区","440112":"广东省广州市黄埔区","440122":"广东省从花县","440181":"广东省番禺市","440182":"广东省花都市","440183":"广东省增城市","4402":"广东省韶关市","440201":"广东省韶关市市辖区","440202":"广东省韶关市北江区","440203":"广东省韶关市武江区","440204":"广东省韶关市浈江区","440221":"广东省曲江县","440222":"广东省始兴县","440223":"广东省南雄县","440224":"广东省仁化县","440225":"广东省乐昌县","440229":"广东省翁源县","440232":"广东省乳源瑶族自治县","440233":"广东省新丰县","4403":"广东省深圳市","440301":"广东省深圳市市辖区","440303":"广东省深圳市罗湖区","440304":"广东省深圳市福田区","440305":"广东省深圳市南山区","440306":"广东省深圳市宝安区","440307":"广东省深圳市龙岗区","4404":"广东省珠海市","440401":"广东省珠海市市辖区","440402":"广东省珠海市香州区","440407":"广东省汕头市龙湖区","440421":"广东省斗门县","4405":"广东省汕头市","440501":"广东省汕头市市辖区","440506":"广东省汕头市达濠区","440508":"广东省汕头市金园区","440509":"广东省汕头市升平区","440521":"广东省澄海县","440523":"广东省南懊县","440582":"广东省潮阳市","4406":"广东省佛山市","440601":"广东省佛山市市辖区","440602":"广东省佛山市城区","440603":"广东省佛山市石湾区","440624":"广东省高明县","440681":"广东省顺德市","440682":"广东省南海市","440683":"广东省三水市","4407":"广东省江门市","440701":"广东省江门市市辖区","440702":"广东省江门市城区","440711":"广东省江门市郊区","440723":"广东省恩平县","440781":"广东省台山市","440782":"广东省新会市","440783":"广东省开平市","440784":"广东省鹤山市","4408":"广东省湛江市","440801":"广东省湛江市市辖区","440802":"广东省湛江市赤坎区","440803":"广东省湛江市霞山区","440804":"广东省湛江市坡头区","440811":"广东省湛江市郊区","440821":"广东省吴川县","440823":"广东省遂溪县","440824":"广东省海康县","440825":"广东省徐闻县","440881":"广东省廉江市","4409":"广东省茂名市","440901":"广东省茂名市市辖区","440902":"广东省茂名市茂南区","440921":"广东省信宜县","440923":"广东省电白县","440924":"广东省化州县","440981":"广东省高州市","4412":"广东省肇庆市","441201":"广东省肇庆市市辖区","441202":"广东省肇庆市端州区","441203":"广东省肇庆市鼎湖区","441223":"广东省广宁县","441224":"广东省怀集县","441225":"广东省封开县","441226":"广东省德庆县","441228":"广东省新兴县","441229":"广东省郁南县","441281":"广东省云浮市","441282":"广东省罗定市","441283":"广东省高要市","441284":"广东省四会市","4413":"广东省惠州市","441301":"广东省惠州市市辖区","441302":"广东省惠州市惠城区","441321":"广东省惠阳县","441322":"广东省博罗县","441323":"广东省惠东县","441324":"广东省龙门县","4414":"广东省梅州市","441401":"广东省梅州市市辖区","441402":"广东省梅州市梅江区","441421":"广东省梅县","441422":"广东省大埔县","441423":"广东省丰顺县","441424":"广东省五华县","441425":"广东省兴宁县","441426":"广东省平远县","441427":"广东省蕉岭县","4415":"广东省汕尾市","441501":"广东省汕尾市市辖区","441502":"广东省汕尾市城区","441521":"广东省海丰县","441522":"广东省陆丰县","441523":"广东省陆河县","4416":"广东省河源市","441601":"广东省河源市市辖区","441602":"广东省河源市源城区","441621":"广东省紫金县","441622":"广东省龙川县","441623":"广东省连平县","441624":"广东省和平县","441625":"广东省东源县","4417":"广东省阳江市","441701":"广东省阳江市市辖区","441702":"广东省阳江市江城区","441721":"广东省阳西县","441722":"广东省阳春县","441723":"广东省阳东县","4418":"广东省清远市","441801":"广东省清远市市辖区","441802":"广东省清远市清城区","441821":"广东省佛冈县","441822":"广东省英德县","441823":"广东省阳山县","441824":"广东省连县","441825":"广东省连山壮族瑶族自治县","441826":"广东省连南瑶族自治县","441827":"广东省清新县","4419":"广东省东莞市","441900":"广东省东莞市","4420":"广东省中山市","442000":"广东省中山市","4451":"广东省潮州市","445101":"广东省潮州市市辖区","445102":"广东省潮州市湘桥区","445121":"广东省潮州市潮安县","445122":"广东省饶平县","4452":"广东省揭阳市","445201":"广东省揭阳市市辖区","445202":"广东省揭阳市榕城区","445221":"广东省揭东县","445222":"广东省揭西县","445224":"广东省惠来县","445281":"广东省普宁县","45":"广西","4501":"广西南宁市","450101":"广西南宁市市辖区","450102":"广西南宁市兴宁区","450103":"广西南宁市新城区","450104":"广西南宁市城北区","450105":"广西南宁市江南区","450106":"广西南宁市永新区","450111":"广西南宁市市郊区","450121":"广西邕宁县","450122":"广西武鸣县","4502":"广西柳州市","450201":"广西柳州市市辖区","450202":"广西柳州市城中区","450203":"广西柳州市鱼峰区","450204":"广西柳州市柳南区","450205":"广西柳州市柳北区","450211":"广西柳州市市郊区","450221":"广西柳江县","450222":"广西柳城县","4503":"广西桂林市","450301":"广西桂林市市辖区","450302":"广西桂林市秀峰区","450303":"广西桂林市叠彩区","450304":"广西桂林市象山区","450305":"广西桂林市七星区","450311":"广西桂林市市郊区","450321":"广西阳朔县","450322":"广西临桂县","4504":"广西梧州市","450401":"广西梧州市市辖区","450403":"广西梧州市万秀区","450404":"广西梧州市蝶山区","450411":"广西梧州市市郊区","450421":"广西苍梧县","4505":"广西北海市 ","450501":"广西北海市市辖区","450502":"广西北海市海城区","450511":"广西北海市市郊区","450521":"广西合浦县","4506":"广西防城港市","450601":"广西防城港市市辖区","450602":"广西防城港市港口区","450603":"广西防城港市防城区","450621":"广西上思县","4521":"广西南宁地区","452101":"广西凭祥市","452122":"广西横县","452123":"广西宾阳县","452124":"广西上林县","452126":"广西隆安县","452127":"广西马山县","452128":"广西扶绥县","452129":"广西崇左县","452130":"广西大新县","452131":"广西天等县","452132":"广西宁明县","452133":"广西龙州县","4522":"广西柳州地区","452201":"广西合山市","452223":"广西鹿寨县","452224":"广西象州县","452225":"广西武宣县","452226":"广西来宾县","452227":"广西融安县","452228":"广西三江侗族自治县","452229":"广西融水苗族自治县","452230":"广西金秀瑶族自治县","452231":"广西忻城县","4523":"广西桂林地区","452322":"广西灵川县","452323":"广西全州县","452324":"广西兴安县","452325":"广西永福县","452327":"广西灌阳县","452328":"广西龙胜各族自治县","452329":"广西资源县","452330":"广西平乐县","452331":"广西荔浦县","452332":"广西恭城瑶族自治县","4524":"广西梧州地区","452421":"广西岑溪县","452423":"广西藤县","452424":"广西昭平县","452425":"广西蒙山县","452426":"广西贺县","452427":"广西钟山县","452428":"广西富川瑶族自治县","4525":"广西玉林地区","452501":"广西玉林市","452502":"广西贵港市","452523":"广西桂平县","452524":"广西平南县","452525":"广西容县","452526":"广西北流县","452527":"广西陆川县","452528":"广西博白县","4526":"广西百色地区","452601":"广西百色市","452622":"广西田阳县","452623":"广西田东县","452624":"广西平果县","452625":"广西德保县","452626":"广西靖西县","452627":"广西那坡县","452628":"广西凌云县","452629":"广西乐业县","452630":"广西田林县","452631":"广西隆林各族自治县","452632":"广西西林县","4527":"广西河池地区","452701":"广西河池市","452702":"广西宜州市","452723":"广西罗城仫佬族自治县","452724":"广西环江毛南族自治县","452725":"广西南丹县","452726":"广西天峨县","452727":"广西凤山县","452728":"广西东兰县","452729":"广西巴马瑶族自治县","452730":"广西都安瑶族自治县","452731":"广西大化瑶族自治县","4528":"广西钦州地区","452802":"广西钦州市","452824":"广西灵山县","452826":"广西浦北县","46":"海南省","4600":"海南省三亚各市县","460001":"海南省通什市","460002":"海南省琼海市","460003":"海南省儋州市","460021":"海南省琼山县","460022":"海南省文昌县","460024":"海南省万宁县","460025":"海南省定安县","460026":"海南省屯昌县","460027":"海南省澄迈县","460028":"海南省临高县","460030":"海南省白沙黎族自治县","460031":"海南省昌江黎族自治县","460032":"海南省东方黎族自治县","460033":"海南省乐东黎族自治县","460034":"海南省陵水黎族自治县","460035":"海南省保亭黎族苗族自治县","460036":"海南省琼中黎族苗族自治县","460037":"海南省西沙群岛","460038":"海南省南沙群岛","460039":"海南省中沙群岛的岛礁及其海域","4601":"海南省海口市","460101":"海南省海口市市辖区","460102":"海南省海口市振东区","460103":"海南省海口市新华区","460104":"海南省海口市秀英区","4602":"海南省三亚市       ","460201":"海南省三亚市市辖区","51":"四川省","5101":"四川省成都市","510101":"四川省成都市市辖区","510104":"四川省成都市锦江区","510105":"四川省成都市青羊区","510106":"四川省成都市金牛区","510107":"四川省成都市武候区","510108":"四川省成都市成华区","510112":"四川省成都市龙泉驿区","510113":"四川省成都市青白江区","510121":"四川省金堂县","510122":"四川省双流县","510123":"四川省温江县","510124":"四川省郫县","510125":"四川省新都县","510128":"四川省崇庆县","510129":"四川省大邑县","510130":"四川省邛崃县","510131":"四川省蒲江县","510132":"四川省新津县","510181":"四川省都江堰市","510182":"四川省彭州市","5102":"四川省重庆市","510201":"四川省重庆市市辖区","510202":"四川省重庆市市中区","510203":"四川省重庆市大渡口区","510211":"四川省重庆市江北区","510212":"四川省重庆市沙坪坝区","510213":"四川省重庆市九龙坡区","510214":"四川省重庆市南岸区","510215":"四川省重庆市北碚区","510216":"四川省重庆市万盛区","510217":"四川省重庆市双桥区","510221":"四川省长寿县","510222":"四川省巴县","510223":"四川省綦江县","510224":"四川省江北县","510227":"四川省潼南县","510228":"四川省铜梁县","510230":"四川省大足县","510231":"四川省荣昌县","510232":"四川省璧山县","510281":"四川省永川市","510282":"四川省江津市","510283":"四川省合川市","5103":"四川省自贡市","510301":"四川省自贡市市辖区","510302":"四川省自贡市自流井区","510303":"四川省自贡市贡井区","510304":"四川省自贡市大安区","510311":"四川省自贡市沿滩区","510321":"四川省荣县","510322":"四川省富顺县","5104":"四川省攀枝花市","510401":"四川省攀枝花市市辖区","510402":"四川省攀枝花市东区","510403":"四川省攀枝花市西区","510411":"四川省攀枝花市仁和区","510421":"四川省米易县","510422":"四川省盐边县","5105":"四川省泸州市","510501":"四川省泸州市市辖区","510502":"四川省泸州市市中区","510521":"四川省泸县","510522":"四川省合江县","510523":"四川省纳溪县","510524":"四川省叙永县","510525":"四川省古蔺县","5106":"四川省德阳市","510601":"四川省德阳市市辖区","510602":"四川省德阳市市中区","510622":"四川省绵竹县","510623":"四川省中江县","510625":"四川省什邡县","510681":"四川省广汉市","5107":"四川省绵阳市","510701":"四川省绵阳市市辖区","510703":"四川省绵阳市涪城区","510704":"四川省绵阳市游仙区","510722":"四川省三台县","510723":"四川省盐亭县","510724":"四川省安县","510725":"四川省梓潼县","510726":"四川省北川县","510727":"四川省平武县","510781":"四川省江油市","5108":"四川省广元市","510801":"四川省广元市市辖区","510802":"四川省广元市市中区","510811":"四川省广元市元坝区","510812":"四川省广元市朝天区","510821":"四川省旺苍县","510822":"四川省青川县","510823":"四川省剑阁县","510824":"四川省苍溪县","5109":"四川省遂宁市","510901":"四川省遂宁市市辖区","510902":"四川省遂宁市市中区","510921":"四川省蓬溪县","510922":"四川省射洪县","5110":"四川省内江市","511001":"四川省内江市市辖区","511002":"四川省内江市市中区","511011":"四川省内江市东兴区","511022":"四川省乐至县","511023":"四川省安岳县","511024":"四川省威远县","511025":"四川省资中县","511027":"四川省简阳县","511028":"四川省隆昌县","511081":"四川省资阳市","5111":"四川省乐山市","511101":"四川省乐山市市辖区","511102":"四川省乐山市市中区","511111":"四川省乐山市沙湾区","511112":"四川省乐山市五通桥区","511113":"四川省乐山市金口河区","511121":"四川省仁寿县","511122":"四川省眉山县","511123":"四川省犍为县","511124":"四川省井研县","511126":"四川省夹江县","511127":"四川省洪雅县","511128":"四川省彭山县","511129":"四川省沐川县","511130":"四川省青神县","511131":"四川省丹棱县","511132":"四川省峨边彝族自治县","511133":"四川省马边彝族自治县","511181":"四川省峨眉山市","5112":"四川省万县市","511201":"四川省万县市市辖区","511202":"四川省万县市龙宝区","511203":"四川省万县市天城区","511204":"四川省万县市五桥区","511221":"四川省开县","511222":"四川省忠县","511223":"四川省梁平县","511224":"四川省云阳县","511225":"四川省奉节县","511226":"四川省巫山县","511227":"四川省巫溪县","511228":"四川省城口县","5113":"四川省南充市","511301":"四川省南充市市辖区","511302":"四川省南充市顺庆区","511303":"四川省南充市高坪区","511304":"四川省南充市嘉陵区","511321":"四川省南部县","511322":"四川省营山县","511323":"四川省蓬安县","511324":"四川省仪陇县","511325":"四川省西充县","511381":"四川省阆中市","5123":"四川省涪陵地区","512301":"四川省涪陵市","512322":"四川省垫江县","512323":"四川省南川县","512324":"四川省丰都县","512326":"四川省武隆县","5125":"四川省宜宾地区","512501":"四川省宜宾市","512527":"四川省宜宾县","512528":"四川省南溪县","512529":"四川省江安县","512530":"四川省长宁县","512531":"四川省高县","512532":"四川省筠连县","512533":"四川省珙县","512534":"四川省兴文县","512535":"四川省屏山县","5130":"四川省达川地区","513001":"四川省达川市","513002":"四川省万源县","513021":"四川省达县","513022":"四川省宣汉县","513023":"四川省开江县","513029":"四川省大竹县","513030":"四川省渠县","5131":"四川省雅安地区","513101":"四川省雅安市","513122":"四川省名山县","513123":"四川省荥经县","513124":"四川省汉源县","513125":"四川省石棉县","513126":"四川省天全县","513127":"四川省芦山县","513128":"四川省宝兴县","5132":"四川省阿坝藏族羌族自治州","513221":"四川省汶川县","513222":"四川省理县","513223":"四川省茂县","513224":"四川省松潘县","513225":"四川省南坪县","513226":"四川省金川县","513227":"四川省小金县","513228":"四川省黑水县","513229":"四川省马尔康县","513230":"四川省壤塘县","513231":"四川省阿坝县","513232":"四川省若尔盖县","513233":"四川省红原县","5133":"四川省甘孜藏族自治州","513321":"四川省康定县","513322":"四川省泸定县","513323":"四川省丹巴县","513324":"四川省九龙县","513325":"四川省雅江县","513326":"四川省道孚县","513327":"四川省炉霍县","513328":"四川省甘孜县","513329":"四川省新龙县","513330":"四川省德格县","513331":"四川省白玉县","513332":"四川省石渠县","513333":"四川省色达县","513334":"四川省理塘县","513335":"四川省巴塘县","513336":"四川省乡城县","513337":"四川省稻城县","513338":"四川省得荣县","5134":"四川省凉山彝族自治州","513401":"四川省西昌市","513422":"四川省木里藏族自治县","513423":"四川省盐源县","513424":"四川省德昌县","513425":"四川省会理县","513426":"四川省会东县","513427":"四川省宁南县","513428":"四川省普格县","513429":"四川省布拖县","513430":"四川省金阳县","513431":"四川省昭觉县","513432":"四川省喜德县","513433":"四川省冕宁县","513434":"四川省越西县","513435":"四川省甘洛县","513436":"四川省美姑县","513437":"四川省雷波县","5135":"四川省黔江地区","513521":"四川省石柱土家族自治县","513522":"四川省秀山土家族苗族自治县","513523":"四川省黔江土家族苗族自治县","513524":"四川省酉阳土家族苗族自治县","513525":"四川省彭水苗族土家族自治县","5136":"四川省广安地区","513601":"四川省华蓥市","513621":"四川省岳池县","513622":"四川省广安县","513623":"四川省武胜县","513624":"四川省邻水县","5137":"四川省巴中地区","513701":"四川省巴中市","513721":"四川省通江县","513722":"四川省南江县","513723":"四川省平昌县","52":"贵州省","5201":"贵州省贵阳市","520101":"贵州省贵阳市市辖区","520102":"贵州省贵阳市南明区","520103":"贵州省贵阳市云岩区","520111":"贵州省贵阳市花溪区","520112":"贵州省贵阳市乌当区","520113":"贵州省贵阳市白云区","5202":"贵州省六盘水市","520201":"贵州省六盘水市钟山区","520202":"贵州省六盘水市盘县特区","520203":"贵州省六盘水市六枝特区","520221":"贵州省水城县","5221":"贵州省遵义地区","522101":"贵州省遵义市","522102":"贵州省赤水市","522121":"贵州省遵义县","522122":"贵州省桐梓县","522123":"贵州省绥阳县","522124":"贵州省正安县","522125":"贵州省道真仡佬苗族自治县","522126":"贵州省务川仡佬苗族自治县","522127":"贵州省凤冈县","522128":"贵州省湄潭县","522129":"贵州省余庆县","522130":"贵州省仁怀县","522132":"贵州省习水县","5222":"贵州省铜仁地区","522201":"贵州省铜仁市","522222":"贵州省江口县","522223":"贵州省玉屏侗族自治县","522224":"贵州省石阡县","522225":"贵州省思南县","522226":"贵州省印江土家族苗族自治县","522227":"贵州省德江县","522228":"贵州省沿河土家族自治县","522229":"贵州省松桃苗族自治县","522230":"贵州省万山特区","5223":"贵州省黔西南布依族苗族自治州","522301":"贵州省兴义市","522322":"贵州省兴仁县","522323":"贵州省普安县","522324":"贵州省晴隆县","522325":"贵州省贞丰县","522326":"贵州省望谟县","522327":"贵州省册亨县","522328":"贵州省安龙县","5224":"贵州省毕节地区","522401":"贵州省毕节市","522422":"贵州省大方县","522423":"贵州省黔西县","522424":"贵州省金沙县","522425":"贵州省织金县","522426":"贵州省纳雍县","522427":"贵州省威宁彝族回族苗族自治县","522428":"贵州省赫章县","5225":"贵州省安顺地区","522501":"贵州省安顺市","522502":"贵州省清镇市","522522":"贵州省开阳县","522523":"贵州省息烽县","522524":"贵州省修文县","522526":"贵州省平坝县","522527":"贵州省普定县","522528":"贵州省关岭布依族苗族自治县","522529":"贵州省镇宁布依族苗族自治县","522530":"贵州省紫云苗族布依族自治县","5226":"贵州省黔东南苗族侗族自治州","522601":"贵州省凯里市","522622":"贵州省黄平县 ","522623":"贵州省施秉县","522624":"贵州省三穗县","522625":"贵州省镇远县","522626":"贵州省岑巩县","522627":"贵州省天柱县","522628":"贵州省锦屏县","522629":"贵州省剑河县","522630":"贵州省台江县","522631":"贵州省黎平县","522632":"贵州省榕江县","522633":"贵州省从江县","522634":"贵州省雷山县","522635":"贵州省麻江县","522636":"贵州省丹寨县","5227":"贵州省黔南布依族苗族自治州","522701":"贵州省都匀市","522722":"贵州省荔波县","522723":"贵州省贵定县","522724":"贵州省福泉县","522725":"贵州省瓮安县","522726":"贵州省独山县","522727":"贵州省平塘县","522728":"贵州省罗甸县","522729":"贵州省长顺县","522730":"贵州省龙里县","522731":"贵州省惠水县","522732":"贵州省三都水族自治县","53":"云南省","5301":"云南省昆明市","530101":"云南省昆明市市辖区","530102":"云南省昆明市五华区","530103":"云南省昆明市盘龙区","530111":"云南省昆明市官渡区","530112":"云南省昆明市西山区","530121":"云南省呈贡县","530122":"云南省晋宁县","530123":"云南省安宁县","530124":"云南省富民县","530125":"云南省宜良县","530126":"云南省路南彝族自治县","530127":"云南省嵩明县","530128":"云南省禄劝彝族苗族自治区","5302":"云南省东川市","530201":"云南省东川市市辖区","5321":"云南省昭通地区","532101":"云南省昭通市","532122":"云南省鲁甸县","532123":"云南省巧家县","532124":"云南省盐津县","532125":"云南省大关县","532126":"云南省永善县","532127":"云南省绥江县","532128":"云南省镇雄县","532129":"云南省彝良县","532130":"云南省威信县","532131":"云南省水富县","5322":"云南省曲靖地区","532201":"云南省曲靖市","532223":"云南省马龙县","532224":"云南省宜威县","532225":"云南省富源县","532226":"云南省罗平县","532227":"云南省师宗县","532228":"云南省陆良县","532231":"云南省寻甸回族彝族自治县","532233":"云南省会泽县","5323":"云南省楚雄彝族自治州","532301":"云南省楚雄市","532322":"云南省双柏县","532323":"云南省牟定县","532324":"云南省南华县","532325":"云南省姚安县","532326":"云南省大姚县","532327":"云南省永仁县","532328":"云南省元谋县","532329":"云南省武定县","532331":"云南省禄丰县","5324":"云南省玉溪地区","532401":"云南省玉溪市","532422":"云南省江川县","532423":"云南省澄江县","532424":"云南省通海县","532425":"云南省华宁县","532426":"云南省易门县","532427":"云南省峨山彝族自治县","532428":"云南省新平彝族傣族自治县","532429":"云南省元江哈尼族彝族自治县","5325":"云南省红河哈尼族彝族自治州","532501":"云南省个旧市","532502":"云南省开远市","532522":"云南省蒙自县","532523":"云南省屏边苗族自治县","532524":"云南省建水县","532525":"云南省石屏县","532526":"云南省弥勒县","532527":"云南省泸西县","532528":"云南省元阳县","532529":"云南省红河县","532530":"云南省金平苗族瑶族傣族自治县","532531":"云南省绿春县","532532":"云南省河口瑶族自治县","5326":"云南省文山壮族苗族自治州","532621":"云南省文山县","532622":"云南省砚山县","532623":"云南省西畴县","532624":"云南省麻栗坡县","532625":"云南省马关县","532626":"云南省丘北县","532627":"云南省广南县","532628":"云南省富宁县","5327":"云南省思茅地区","532701":"云南省思茅市","532722":"云南省普洱哈尼族继族自治区","532723":"云南省墨江哈尼族自治县","532724":"云南省景东彝族自治区","532725":"云南省景谷傣族彝族自治区","532726":"云南省镇沅彝族哈尼族拉祜族自治","532727":"云南省江城哈尼族彝族自治县","532728":"云南省孟连傣族拉祜族佤族自治县","532729":"云南省澜沧拉祜族自治县","532730":"云南省西盟佤族自治县","5328":"云南省西双版纳傣族自治州","532801":"云南省景洪市","532822":"云南省勐海县","532823":"云南省勐腊县","5329":"云南省大理白族自治州","532901":"云南省大理市","532922":"云南省漾濞彝族自治县","532923":"云南省祥云县","532924":"云南省宾川县","532925":"云南省弥渡县","532926":"云南省南涧彝族自治县","532927":"云南省巍山彝族回族自治县","532928":"云南省永平县","532929":"云南省云龙县","532930":"云南省洱源县","532931":"云南省剑川县","532932":"云南省鹤庆县","5330":"云南省保山地区","533001":"云南省保山市","533022":"云南省施甸县","533023":"云南省腾冲县","533024":"云南省龙陵县","533025":"云南省昌宁县","5331":"云南省德宏傣族景颇族自治州","533101":"云南省畹町市","533102":"云南省瑞丽市","533121":"云南省潞西县","533122":"云南省梁河县","533123":"云南省盈江县","533124":"云南省陇川县","5332":"云南省丽江地区","533221":"云南省丽江纳西族自治县","533222":"云南省永胜县","533223":"云南省华坪县","533224":"云南省宁蒗彝族自治县","5333":"云南省怒江傈僳族自治州","533321":"云南省泸水县","533323":"云南省福贡县","533324":"云南省贡山独龙族怒族自治县","533325":"云南省兰坪白族普米族自治县","5334":"云南省迪庆藏族自治州","533421":"云南省中甸县","533422":"云南省德钦县","533423":"云南省维西傈傈族自治县","5335":"云南省临沧地区","533521":"云南省临沧县","533522":"云南省凤庆县","533523":"云南省云县","533524":"云南省永德县","533525":"云南省镇康县","533526":"云南省双江拉祜族佤族布朗族傣族","533527":"云南省耿马傣族佤族自治县","533528":"云南省沧源佤族自治县","54":"西藏自治区","5401":"西藏拉萨市","540101":"西藏拉萨市市辖区","540102":"西藏拉萨市城关区","540121":"西藏林周县","540122":"西藏当雄县","540123":"西藏尼木县","540124":"西藏曲水县","540125":"西藏堆龙德庆县","540126":"西藏达孜县","540127":"西藏墨竹工卡县","5421":"西藏昌都地区","542121":"西藏昌都县","542122":"西藏江达县","542123":"西藏贡觉县","542124":"西藏类乌齐县","542125":"西藏丁青县","542126":"西藏察雅县","542127":"西藏八宿县","542128":"西藏左贡县","542129":"西藏芒康县","542132":"西藏洛隆县","542133":"西藏边坝县","542134":"西藏盐井县","542135":"西藏碧土县","542136":"西藏妥坝县","542137":"西藏生达县","5422":"西藏山南地区","542221":"西藏乃东县","542222":"西藏扎襄县","542223":"西藏贡嘎县","542224":"西藏桑日县","542225":"西藏琼结县","542226":"西藏曲松县","542227":"西藏措美县","542228":"西藏洛扎县","542229":"西藏加查县","542231":"西藏隆子县","542232":"西藏错那县","542233":"西藏浪卡子县","5423":"西藏日喀则地区","542301":"西藏日喀则市","542322":"西藏南木林县","542323":"西藏江孜县","542324":"西藏定日县","542325":"西藏萨迦县","542326":"西藏拉孜县","542327":"西藏昂仁县","542328":"西藏谢通门县","542329":"西藏白朗县","542330":"西藏仁布县","542331":"西藏康马县","542332":"西藏定结县","542333":"西藏仲巴县","542334":"西藏亚东县","542335":"西藏吉隆县","542336":"西藏聂拉木县","542337":"西藏萨嘎县","542338":"西藏岗巴县","5424":"西藏那曲地区","542421":"西藏那曲县","542422":"西藏嘉黎县","542423":"西藏比如县","542424":"西藏聂荣县","542425":"西藏安多县","542426":"西藏申扎县","542427":"西藏索县","542428":"西藏班戈县","542429":"西藏巴青县","542430":"西藏尼玛县","5425":"西藏阿里地区","542521":"西藏普兰县","542522":"西藏札达县","542523":"西藏噶尔县","542524":"西藏日土县","542525":"西藏革吉县","542526":"西藏改则县","542527":"西藏措勤县","542528":"西藏隆格尔县","5426":"西藏林芝地区","542621":"西藏林芝县","542622":"西藏工布江达县","542623":"西藏米林县","542624":"西藏墨脱县","542625":"西藏波密县","542626":"西藏察隅县","542627":"西藏朗县","61":"陕西省","6101":"陕西省西安市","610101":"陕西省西安市市辖区","610102":"陕西省西安市新城区","610103":"陕西省西安市碑林区","610104":"陕西省西安市莲湖区","610111":"陕西省西安市灞桥区","610112":"陕西省西安市未央区","610113":"陕西省西安市雁塔区","610114":"陕西省西安市阎良区","610121":"陕西省长安县","610122":"陕西省蓝田县","610123":"陕西省临潼县","610124":"陕西省周至县","610125":"陕西省户县","610126":"陕西省高陵县","6102":"陕西省铜川市","610201":"陕西省铜川市市辖区","610202":"陕西省铜川市城区","610203":"陕西省铜川市郊区","610221":"陕西省耀县","610222":"陕西省宜君县","6103":"陕西省宝鸡市","610301":"陕西省宝鸡市市辖区","610302":"陕西省宝鸡市渭滨区","610303":"陕西省宝鸡市金台区","610321":"陕西省宝鸡县","610322":"陕西省凤翔县","610323":"陕西省岐山县","610324":"陕西省扶风县","610326":"陕西省眉县","610327":"陕西省陇县","610328":"陕西省千阳县","610329":"陕西省麟游县","610330":"陕西省凤县","610331":"陕西省太白县","6104":"陕西省咸阳市","610401":"陕西省咸阳市市辖区","610402":"陕西省咸阳市秦都区","610403":"陕西省咸阳市杨陵区","610404":"陕西省咸阳市渭城区","610422":"陕西省三原县","610423":"陕西省泾阳县","610424":"陕西省乾县","610425":"陕西省礼泉县","610426":"陕西省永寿县","610427":"陕西省彬县","610428":"陕西省长武县","610429":"陕西省旬邑县","610430":"陕西省淳化县","610431":"陕西省武功县","610481":"陕西省兴平市","6121":"陕西省渭南地区","612101":"陕西省渭南市","612102":"陕西省韩城市","612103":"陕西省华阴市","612124":"陕西省华县","612126":"陕西省潼关县","612127":"陕西省大荔县","612128":"陕西省蒲城县","612129":"陕西省澄城县","612130":"陕西省白水县","612132":"陕西省合阳县","612133":"陕西省富平县","6123":"陕西省汉中地区","612301":"陕西省汉中市","612321":"陕西省南郑县","612322":"陕西省城固县","612323":"陕西省洋县","612324":"陕西省西乡县","612325":"陕西省勉县","612326":"陕西省宁强县","612327":"陕西省略阳县","612328":"陕西省镇巴县","612329":"陕西省留坝县","612330":"陕西省佛坪县","6124":"陕西省安康地区","612401":"陕西省安康市","612422":"陕西省汉阳县","612423":"陕西省石泉县","612424":"陕西省宁陕县","612425":"陕西省紫阳县","612426":"陕西省岚皋县","612427":"陕西省平利县","612428":"陕西省镇坪县","612429":"陕西省旬阳县","612430":"陕西省白河县","6125":"陕西省商洛地区","612501":"陕西省商州市","612522":"陕西省洛南县","612523":"陕西省丹风县","612524":"陕西省商南县","612525":"陕西省山阳县","612526":"陕西省镇安县","612527":"陕西省柞水县","6126":"陕西省延安地区","612601":"陕西省延安市","612621":"陕西省延长县","612622":"陕西省延川县","612623":"陕西省子长县","612624":"陕西省安塞县","612625":"陕西省志丹县","612626":"陕西省吴旗县","612627":"陕西省甘泉县","612628":"陕西省富县","612629":"陕西省洛川县","612630":"陕西省宜川县","612631":"陕西省黄龙县","612632":"陕西省黄陵县","6127":"陕西省榆林地区","612701":"陕西省榆林市","612722":"陕西省神木县","612723":"陕西省府谷县","612724":"陕西省横山县","612725":"陕西省靖边县","612726":"陕西省定边县","612727":"陕西省绥德县","612728":"陕西省米脂县","612729":"陕西省佳县","612730":"陕西省吴堡县","612731":"陕西省清涧县","612732":"陕西省子洲县","62":"甘肃省","6201":"甘肃省兰州市","620101":"甘肃省兰州市市辖区","620102":"甘肃省兰州市城关区","620103":"甘肃省兰州市七里河区","620104":"甘肃省兰州市西固区","620105":"甘肃省兰州市安宁区","620111":"甘肃省兰州市红古区","620121":"甘肃省永登县","620122":"甘肃省皋兰县","620123":"甘肃省榆中县","6202":"甘肃省嘉峪关市","620201":"甘肃省嘉峪关市市辖区","6203":"甘肃省金昌市","620301":"甘肃省金昌市市辖区","620302":"甘肃省金昌市金川区","620321":"甘肃省永昌县","6204":"甘肃省白银市","620401":"甘肃省白银市市辖区","620402":"甘肃省白银市白银区","620403":"甘肃省白银市平川区","620421":"甘肃省清远县","620422":"甘肃省会宁县","620423":"甘肃省景泰县","6205":"甘肃省天水市","620501":"甘肃省天水市市辖区","620502":"甘肃省天水市秦城区","620503":"甘肃省天水市北道区","620521":"甘肃省清水县","620522":"甘肃省秦安县","620523":"甘肃省甘谷县","620524":"甘肃省武山县","620525":"甘肃省张家川回族自治县","6221":"甘肃省酒泉地区","622101":"甘肃省玉门市","622102":"甘肃省酒泉市","622103":"甘肃省敦煌市","622123":"甘肃省金塔县","622124":"甘肃省肃北蒙古族自治县","622125":"甘肃省阿克塞哈萨克族自治县","622126":"甘肃省安西县","6222":"甘肃省张掖地区","622201":"甘肃省张掖市","622222":"甘肃省肃南裕固族自治县","622223":"甘肃省民乐县","622224":"甘肃省临泽县","622225":"甘肃省高台县","622226":"甘肃省山丹县","6223":"甘肃省武威地区","622301":"甘肃省武威市","622322":"甘肃省民勤县 ","622323":"甘肃省古浪县","622326":"甘肃省天祝藏族自治县","6224":"甘肃省定西地区","622421":"甘肃省定西县","622424":"甘肃省通渭县","622425":"甘肃省陇西县","622426":"甘肃省渭源县","622427":"甘肃省临洮县","622428":"甘肃省漳县","622429":"甘肃省岷县","6226":"甘肃省陇南地区","622621":"甘肃省武都县","622623":"甘肃省宕昌县","622624":"甘肃省成县","622625":"甘肃省康县","622626":"甘肃省文县","622627":"甘肃省西和县","622628":"甘肃省礼县","622629":"甘肃省两当县","622630":"甘肃省徽县","6227":"甘肃省平凉地区","622701":"甘肃省平凉市","622722":"甘肃省泾川县","622723":"甘肃省灵台县","622724":"甘肃省崇信县","622725":"甘肃省华亭县","622726":"甘肃省庄浪县","622727":"甘肃省静宁县","6228":"甘肃省庆阳地区","622801":"甘肃省西峰市","622821":"甘肃省庆阳县","622822":"甘肃省环县","622823":"甘肃省华池县","622824":"甘肃省合水县","622825":"甘肃省正宁县","622826":"甘肃省宁县","622827":"甘肃省镇原县","6229":"甘肃省临夏回族自治州","622901":"甘肃省临夏市","622921":"甘肃省临夏县","622922":"甘肃省康乐县","622923":"甘肃省永靖县","622924":"甘肃省广河县","622925":"甘肃省和政县","622926":"甘肃省东乡族自治县","622927":"甘肃省积石山保安族东乡族撒拉族","6230":"甘肃省甘南藏族自治州","623021":"甘肃省临潭县","623022":"甘肃省卓尼县","623023":"甘肃省舟曲县","623024":"甘肃省迭部县","623025":"甘肃省玛曲县","623026":"甘肃省碌曲县","623027":"甘肃省夏河县","63":"青海省","6301":"青海省西宁市","630101":"青海省西宁市市辖区","630102":"青海省西宁市城东区","630103":"青海省西宁市城中区","630104":"青海省西宁市城西区","630105":"青海省西宁市城北区","630121":"青海省大通回族土族自治县","6321":"青海省海东地区","632121":"青海省平安县","632122":"青海省民和回族土族自治县","632123":"青海省乐都县","632124":"青海省湟中县","632125":"青海省湟源县","632126":"青海省互助土族自治县","632127":"青海省化隆回族自治县","632128":"青海省循化撒拉族自治县","6322":"青海省海北藏族自治州","632221":"青海省门源回族自治县","632222":"青海省祁连县","632223":"青海省海晏县","632224":"青海省刚察县","6323":"青海省黄南藏族自治州","632321":"青海省同仁县","632322":"青海省尖扎县","632323":"青海省泽库县","632324":"青海省河南蒙古族自治县","6325":"青海省海南藏族自治州","632521":"青海省共和县","632522":"青海省同德县","632523":"青海省贵德县","632524":"青海省兴海县","632525":"青海省贵南县","6326":"青海省果洛藏族自治州","632621":"青海省玛沁县","632622":"青海省班玛县","632623":"青海省甘德县","632624":"青海省达日县","632625":"青海省久治县","632626":"青海省玛多县","6327":"青海省玉树藏族自治州","632721":"青海省玉树县","632722":"青海省杂多县","632723":"青海省称多县","632724":"青海省治多县","632725":"青海省囊谦县","632726":"青海省曲麻莱县","6328":"青海省海西蒙古族藏族自治州","632801":"青海省格尔木市","632802":"青海省德令哈市","632821":"青海省乌兰县","632822":"青海省都兰县","632823":"青海省天峻县","64":"宁夏","6401":"宁夏银川市","640101":"宁夏银川市市辖区","640102":"宁夏银川市城区","640103":"宁夏银川市新城区","640111":"宁夏银川市郊区","640121":"宁夏永宁县","640122":"宁夏贺兰县","6402":"宁夏石嘴山市","640201":"宁夏石嘴山市市辖区","640202":"宁夏石嘴山市大武口区","640203":"宁夏石嘴山市石嘴山区","640204":"宁夏石嘴山市石炭井区","640221":"宁夏平罗县","640222":"宁夏陶乐县","640223":"宁夏惠农县","6421":"宁夏银南地区","642101":"宁夏吴忠市","642102":"宁夏青铜峡市","642123":"宁夏中卫县","642124":"宁夏中宁县","642125":"宁夏灵武县","642126":"宁夏盐池县","642127":"宁夏同心县","6422":"宁夏固原地区","642221":"宁夏固原县","642222":"宁夏海原县","642223":"宁夏西吉县","642224":"宁夏隆德县","642225":"宁夏泾源县","642226":"宁夏彭阳县","65":"新疆","6501":"新疆乌鲁木齐市","650101":"新疆乌鲁木齐市市辖区","650102":"新疆乌鲁木齐市天山区","650103":"新疆乌鲁木齐市沙衣巴克区","650104":"新疆乌鲁木齐市新市区","650105":"新疆乌鲁木齐市水磨沟区","650106":"新疆乌鲁木齐市头屯河区","650107":"新疆乌鲁木齐市南山矿区","650108":"新疆乌鲁木齐市东山区","650121":"新疆乌鲁木齐县","6502":"新疆克拉玛依市","650201":"新疆克拉玛依市市辖区","650202":"新疆克拉玛依市独山子区","650203":"新疆克拉玛依市克拉玛依区","650204":"新疆克拉玛依市白碱滩区","650205":"新疆克拉玛依市乌尔禾区","6521":"新疆吐鲁番地区","652101":"新疆吐鲁番市","652122":"新疆鄯善县","652123":"新疆托克逊县","6522":"新疆哈密地区","652201":"新疆哈密市","652222":"新疆巴里坤哈萨克自治县","652223":"新疆伊吾县","6523":"新疆昌吉回族自治州","652301":"新疆昌吉市","652302":"新疆阜康市","652322":"新疆米泉县","652323":"新疆呼图壁县","652324":"新疆玛纳斯县","652325":"新疆奇台县","652327":"新疆吉木萨尔县","652328":"新疆木垒哈萨克自治县","6527":"新疆博尔塔拉蒙古自治州","652701":"新疆博乐市","652722":"新疆精河县","652723":"新疆温泉县","6528":"新疆巴音郭楞蒙古自治州","652801":"新疆库尔勒市","652822":"新疆轮台县","652823":"新疆尉梨县","652824":"新疆若羌县","652825":"新疆且未县","652826":"新疆焉耆回族自治县","652827":"新疆和静县","652828":"新疆和硕县","652829":"新疆博湖县","6529":"新疆阿克苏地区","652901":"新疆阿克苏市","652922":"新疆温宿县","652923":"新疆库车县","652924":"新疆沙雅县","652925":"新疆新和县","652926":"新疆拜城县","652927":"新疆乌什县","652928":"新疆阿瓦提县","652929":"新疆柯坪县","6530":"新疆克孜勒苏柯尔克孜自治州","653001":"新疆阿图什市","653022":"新疆阿克陶县","653023":"新疆阿合奇县","653024":"新疆乌恰县","6531":"新疆喀什地区","653101":"新疆喀什市","653121":"新疆疏附县","653122":"新疆疏勒县","653123":"新疆英吉沙县","653124":"新疆泽普县","653125":"新疆莎车县","653126":"新疆叶城县","653127":"新疆麦盖提县","653128":"新疆岳普湖县","653129":"新疆伽师县","653130":"新疆巴楚县","653131":"新疆塔什库尔干塔吉克自治县","6532":"新疆和田地区","653201":"新疆和田市","653221":"新疆和田县","653222":"新疆墨玉县","653223":"新疆皮山县","653224":"新疆洛浦县","653225":"新疆策勒县","653226":"新疆于田县","653227":"新疆民丰县","6540":"新疆伊犁哈萨克自治州","654001":"新疆奎屯市","6541":"新疆伊犁地区","654101":"新疆伊宁市","654121":"新疆伊宁县","654122":"新疆察布查尔锡伯自治县","654123":"新疆霍城县","654124":"新疆巩留县","654125":"新疆新源县","654126":"新疆昭苏县","654127":"新疆特克斯县","654128":"新疆尼勒克县","6542":"新疆塔城地区","654201":"新疆塔城市","654221":"新疆额敏县","654222":"新疆乌苏县","654223":"新疆沙湾县","654224":"新疆托里县","654225":"新疆裕民县","654226":"新疆和布克赛尔蒙古自治县","6543":"新疆阿勒泰地区","654301":"新疆阿勒泰市","654321":"新疆布尔津县","654322":"新疆富蕴县","654323":"新疆福海县","654324":"新疆哈巴河县","654325":"新疆青河县","654326":"新疆吉木乃县","6590":"新疆省直辖行政单位","659001":"新疆石河子市","71":"台湾省","7100":"台湾","710000":"台湾省","72":"香港","7200":"香港特别行政区","720000":"香港特别行政区","73":"澳门","7300":"澳门特别行政区","91":"国外"} \ No newline at end of file diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/test-resources/data/job b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/test-resources/data/job deleted file mode 100644 index a6f7ca4e26..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/test-resources/data/job +++ /dev/null @@ -1 +0,0 @@ -Java,PHP,web前端,算法工程师,后端开发,C++,PHP,数据挖掘,C,C#,.NET,Hadoop,Python,Delphi,VB,Perl,Ruby,Node.js,搜索算法,Golang,自然语言处理,推荐算法,Erlang,算法工程师,语音/视频/图形开发,数据采集,移动开发,HTML5,Android,iOS,WP,移动web前端,Flash开发,JavaScript,U3D,COCOS2DX,测试工程师,自动化测试,功能测试,性能测试,测试开发,移动端测试,游戏测试,硬件测试,软件测试,运维工程师,运维开发工程师,网络工程师,系统工程师,IT技术支持,系统管理员,网络安全,系统安全,DBA,数据,ETL工程师,数据仓库,数据开发,数据挖掘,数据分析师,数据架构师,算法研究员,项目经理,项目主管,项目助理,项目专员,实施顾问,实施工程师,需求分析工程师,硬件,嵌入式,自动化,单片机,电路设计,驱动开发,系统集成,FPGA开发,DSP开发,ARM开发,PCB工艺,模具设计,热传导,材料工程师,精益工程师,射频工程师,前端开发,web前端,JavaScript,Flash开发,HTML5,通信技术工程师,通信研发工程师,数据通信工程师,移动通信工程师,电信网络工程师,电信交换工程师,有线传输工程师,无线射频工程师,通信电源工程师,通信标准化工程师,通信项目专员,通信项目经理,核心网工程师,通信测试工程师,通信设备工程师,光通信工程师,光传输工程师,光网络工程师,电子工程师,电气工程师,FAE,电气设计工程师,高端技术职位,技术经理,技术总监,测试经理,架构师,CTO,运维总监,技术合伙人,人工智能,机器学习,深度学习,图像算法,图像处理,语音识别,图像识别,算法研究员,软件销售支持,售前工程师,售后工程师,其他技术职位,产品经理,产品总监,数据产品经理,产品经理,网页产品经理,移动产品经理,产品助理,数据产品经理,电商产品经理,游戏策划,产品专员,高端产品职位,产品总监,游戏制作人,产品VP,其他产品职位,UI设计师,平面设计师,交互设计师,视觉设计,视觉设计师,网页设计师,Flash设计师,APP设计师,UI设计师,平面设计师,美术设计师(2D/3D),广告设计师,多媒体设计师,原画师,游戏特效,游戏界面设计师,游戏场景,游戏角色,游戏动作,三维/CAD/制图,美工,包装设计,设计师助理,动画设计师,插画师,交互设计师,无线交互设计师,网页交互设计师,硬件交互设计师,数据分析师,用户研究员,游戏数值策划,UX设计师,用户研究经理,用户研究总监,高端设计职位,设计经理/主管,设计总监,视觉设计经理,视觉设计总监,交互设计经理/主管,交互设计总监,非视觉设计,服装设计,工业设计,橱柜设计,家具设计,家居设计,珠宝设计,室内设计,陈列设计,景观设计,其他设计职位,新媒体运营,产品运营,网络推广,运营,用户运营,产品运营,数据运营,内容运营,活动运营,商家运营,品类运营,游戏运营,网络推广,网站运营,新媒体运营,社区运营,微信运营,微博运营,策略运营,线下拓展运营,电商运营,运营助理/专员,内容审核,销售运营,编辑,副主编,内容编辑,文案策划,网站编辑,记者,采编,售前咨询,售后咨询,网络客服,客服经理,客服专员/助理,客服主管,客服总监,电话客服,咨询热线/呼叫中心客服,高端运营职位,主编,运营总监,COO,客服总监,运营经理/主管,其他运营职位,市场营销,市场推广,品牌公关,策划经理,选址开发,市场营销,市场策划,市场顾问,市场推广,SEO,SEM,商务渠道,商业数据分析,活动策划,网络营销,海外市场,政府关系,APP推广,公关媒介,媒介经理,广告协调,品牌公关,媒介专员,活动策划执行,媒介策划,会务会展,会议活动销售,会议活动策划,会议活动执行,会展活动销售,会展活动策划,会展活动执行,广告,广告创意,美术指导,广告设计师,策划经理,文案,广告制作,媒介投放,媒介合作,媒介顾问,广告审核,高端市场职位,市场总监,CMO,公关总监,媒介总监,创意总监,其他市场职位,人事/HR,行政,财务,培训,绩效考核,人力资源主管,招聘,HRBP,人力资源专员/助理,培训,薪资福利,绩效考核,人力资源经理,人力资源VP/CHO,人力资源总监,员工关系,组织发展,行政专员/助理,前台,行政主管,经理助理,后勤,商务司机,行政经理,行政总监,财务,会计,出纳,财务顾问,结算,税务,审计,风控,财务经理,CFO,财务总监,财务主管,法务专员/助理,律师,专利,法律顾问,法务主管,法务经理,法务总监,其他职能职位,CEO/总裁/总经理,事业部负责人,高级管理职位,CEO/总裁/总经理,副总裁/副总经理,事业部负责人,区域/分公司/代表处负责人,总裁/总经理/董事长助理,合伙人,创始人,董事会秘书,销售专员,销售经理,销售工程师,销售,销售专员,销售经理,客户代表,大客户代表,BD经理,商务渠道,渠道销售,代理商销售,销售助理,电话销售,销售顾问,商品经理,广告销售,网络营销,营销主管,销售工程师,客户经理,销售管理,销售总监,商务总监,区域总监,城市经理,销售VP,团队经理,其他销售职位,文案,广告创意,编辑,记者,媒介经理,采编/写作/出版,记者,编辑,采编,撰稿人,出版发行,校对录入,总编,自媒体,公关媒介,媒介经理,媒介专员,广告协调,品牌公关,活动策划执行,媒介策划,会务会展,会议活动销售,会议活动策划,会议活动执行,会展活动销售,会展活动策划,会展活动执行,广告,广告创意,美术指导,广告设计师,策划经理,文案,广告制作,媒介投放,媒介合作,媒介顾问,广告审核,主持人/DJ,影视媒体,助理,统筹制片人,执行制片人,导演/编导,摄影/摄像,视频编辑,音频编辑,经纪人,后期制作,影视制作,影视发行,影视策划,主播,演员/配音/模特,化妆/造型/服装,放映管理,录音/音效,制片人,编剧,其他传媒职位,投资经理,投资总监,风控,证券,投融资,投资经理,行业研究,资产管理,投资总监,投资VP,投资合伙人,融资,并购,投后管理,投资助理,其他投融资职位,投资顾问,风控,律师,资信评估,合规稽查,审计,法务,会计,清算,银行,信用卡销售,分析师,柜员,商务渠道,大堂经理,理财顾问,客户经理,信贷管理,风控,互联网金融,金融产品经理,风控,催收员,分析师,投资经理,交易员,理财顾问,合规稽查,审计,清算,保险业务,精算师,保险理赔,证券,证券经纪人,证券分析师,其他金融职位,汽车销售,汽车维修,零部件设计,汽车设计,车身设计,底盘设计,机械设计,动力系统设计,电子工程设计,零部件设计,汽车工程项目管理,内外饰设计工程师,总装工程师,焊接工程师,冲压工程师,质量工程师,汽车销售与制造,汽车销售,汽车配件销售,汽车售后服务,汽车维修,汽车美容,汽车定损理赔,二手车评估师,4S店管理,汽车改装工程师,其他汽车职位,课程设计,教务管理,IT培训,教育产品研发,课程设计,课程编辑,教师,培训研究,培训师,培训策划,其他教育产品研发职位,教育行政,校长,教务管理,教学管理,班主任/辅导员,教师,助教,高中教师,初中教师,小学教师,幼教,理科教师,文科教师,外语教师,音乐教师,美术教师,体育教师,就业老师,IT培训,JAVA培训讲师,Android培训讲师,ios培训讲师,PHP培训讲师,.NET培训讲师,C++培训讲师,Unity 3D培训讲师,Web前端培训讲师,软件测试培训讲师,动漫培训讲师,UI设计培训讲师,财会培训讲师,HR培训讲师,培训师,拓展培训,课程顾问,招生顾问,留学顾问,教练,舞蹈教练,瑜伽教练,瘦身顾问,游泳教练,健身教练,篮球/羽毛球教练,跆拳道教练,其他教育培训职位,药剂师,营养师,医疗器械研究,医生/医技,医生助理,医学影像,B超医生,中医,医师,心理医生,药剂师,牙科医生,康复治疗师,验光师,放射科医师,检验科医师,其他医生职位,护士长,护士/护理,导医,健康整形,营养师,整形师,理疗师,针灸推拿,生物制药,药品注册,药品生产,临床研究,临床协调,临床数据分析,医学总监,医药研发,医疗器械注册,医疗器械生产/质量管理,医疗器械研究,药店,店长,执业药师/驻店药师,店员/营业员,市场营销/媒体,医疗器械销售,医学编辑,医学总监,药学编辑,医药代表,健康顾问,医美咨询,其他医疗健康类职位,采购经理,采购主管,进出口贸易,采购,采购总监,采购经理,采购专员,买手,采购工程师,采购主管,采购助理,进出口贸易,外贸经理,外贸专员,外贸业务员,贸易跟单,其他采购/贸易类职位,物流专员,贸易跟单,供应链经理,物流,供应链专员,供应链经理,物流专员,物流经理,物流运营,物流跟单,贸易跟单,物仓调度,物仓项目,运输经理/主管,货运代理专员,货运代理经理,水/空/陆运操作,报关员,报检员,核销员,单证员,仓储,仓储物料经理,仓储物料专员,仓储物料项目,仓储管理,仓库文员,配/理/拣/发货,运输,货运司机,集装箱管理,配送,快递,高端供应链职位,供应链总监,物流总监,其他供应链职位,物业管理,房地产规划开发,房地产规划开发,房产策划,地产项目管理,地产招投标,弱电工程师,设计装修与市政建设,高级建筑工程师,建筑工程师,建筑设计师,土木/土建/结构工程师,室内设计,园林设计,城市规划设计,工程监理,工程造价,预结算,工程资料管理,建筑施工现场管理,房地产经纪,地产置业顾问,地产评估,地产中介,物业管理,物业租赁销售 ,物业招商管理,高端房地产职位,地产项目总监,地产策划总监,地产招投标总监,物业总监,房地产销售总监,其他房地产职位,企业管理咨询,事务所律师,咨询/调研,企业管理咨询,数据分析师,财务咨询顾问,IT咨询顾问,人力资源顾问,咨询项目管理,战略咨询,猎头顾问,市场调研,其他咨询顾问,知识产权,事务所律师,公司法务,英语翻译,日语翻译,韩语/朝鲜语翻译,法语翻译,德语翻译,俄语翻译,西班牙语翻译,其他语种翻译,高端咨询类职位,咨询总监,咨询经理,高级翻译,同声传译 ,其他咨询/翻译类职位,实习生,管培生,储备干部,管理培训生,储备干部,其他实习/培训/储备职位,旅游顾问,导游,旅游产品开发/策划,旅游服务,计调,签证,旅游顾问,导游,预定票务,旅游产品开发/策划,旅游产品经理,旅游策划师,其他旅游职位,酒店前台,客房服务员,发型师,保安,保洁,花艺师,婚礼策划师,礼仪迎宾,酒店,收银,酒店前台,客房服务员,酒店经理,后厨,配菜打荷,茶艺师,西点师,餐饮学徒,餐饮,收银,服务员,厨师,咖啡师,送餐员,餐饮店长,领班,督导/巡店,陈列员,理货员,零售,收银,导购,店员/营业员,门店店长,发型师,美甲师,化妆师,会籍顾问,健身,瑜伽教练,瘦身顾问,游泳教练,美体教练,美容师/顾问,舞蹈教练,健身教练,其他服务业职位,生产总监,安全员,质量管理/测试,生产营运,厂长/工厂经理,生产总监,生产经理/车间主任,生产组长/拉长,生产员,生产设备管理,生产计划/物料控制,生产跟单,质检员,质量管理/测试,可靠度工程师,故障分析师,认证工程师,体系工程师,审核员,安全员,机械设计/制造,机械工程师,机械设计师,机械设备工程师,机械维修/保养,机械制图,机械结构工程师,工业工程师,工艺/制程工程师,材料工程师,机电工程师,CNC/数控,冲压工程师,夹具工程师,模具工程师,焊接工程师,注塑工程师,铸造/锻造工程师,化工,化工工程师,实验室技术员,化学分析,涂料研发,化妆品研发,食品/饮料研发,服装设计,女装设计,男装设计,童装设计,内衣设计,面料设计,面料辅料开发,面料辅料采购,打样/制版,服装/纺织/皮革跟单,普工/操作工,叉车,铲车,焊工,氩弧焊工,电工,木工,漆工,车工,磨工,铣工,钳工,钻工,铆工,钣金,抛光,机修工,折弯工,电镀工,喷塑工,注塑工,组装工,包装工,空调工,电梯工,锅炉工,学徒工,其他生产制造职位 \ No newline at end of file diff --git a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/test-resources/log4j.properties b/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/test-resources/log4j.properties deleted file mode 100644 index 69272d3455..0000000000 --- a/jun_java_plugins/jun_excel/doc/sanri-excel-poi/src/test/test-resources/log4j.properties +++ /dev/null @@ -1,53 +0,0 @@ -# Output pattern : date [thread] priority category - message -rootdir=e:/logs -module=sanritools -log4j.rootLogger=info,Console,errorAppender - -log4j.logger.org.apache.kafka.common.config=warning,Console,errorAppender -log4j.additivity.org.apache.kafka.common.config=false - -# -## \u81EA\u5DF1\u7CFB\u7EDF\u7684\u9700\u8981\u8BE6\u7EC6\u6253\u5370 -log4j.logger.com.sanri=debug,Console,debugAppender,errorAppender,RollingFile -log4j.additivity.com.sanri=false -log4j.logger.sanri=debug,Console,debugAppender,errorAppender,RollingFile -log4j.additivity.sanri=false -log4j.logger.learn=debug,Console,debugAppender,errorAppender,RollingFile -log4j.additivity.learn=false - -## \u4FE1\u606F\u8FFD\u52A0\u5668 -log4j.appender.debugAppender=org.apache.log4j.RollingFileAppender -log4j.appender.debugAppender.File=${rootdir}/sanri-${module}_debug.log -log4j.appender.debugAppender.append=true -log4j.appender.debugAppender.threshold=debug -log4j.appender.debugAppender.encoding=UTF-8 -log4j.appender.debugAppender.MaxFileSize=64MB -log4j.appender.debugAppender.MaxBackupIndex=10 -log4j.appender.debugAppender.layout=org.apache.log4j.PatternLayout -log4j.appender.debugAppender.layout.ConversionPattern=%-5p %d{yyyyMMdd HH:mm:ss} [%c:%L] - %n [LOG] %m%n - -## \u5F02\u5E38\u8FFD\u52A0\u5668 -log4j.appender.errorAppender=org.apache.log4j.RollingFileAppender -log4j.appender.errorAppender.File=${rootdir}/sanri-${module}_error.log -log4j.appender.errorAppender.append=true -log4j.appender.errorAppender.threshold=error -log4j.appender.errorAppender.encoding=UTF-8 -log4j.appender.errorAppender.MaxFileSize=64MB -log4j.appender.errorAppender.MaxBackupIndex=10 -log4j.appender.errorAppender.layout=org.apache.log4j.PatternLayout -#log4j.appender.errorAppender.layout.ConversionPattern=%-5p %d{yyyyMMdd HH\:mm\:ss} [%c\:%L] - %n -log4j.appender.errorAppender.layout.ConversionPattern=%d [%t] %-5p [%C->%M(%L)] - %m%n -# -##Console -log4j.appender.Console=org.apache.log4j.ConsoleAppender -log4j.appender.Console.layout=org.apache.log4j.PatternLayout -log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%C->%M(%L)] - %m%n - -#RollingFile -log4j.appender.RollingFile=org.apache.log4j.DailyRollingFileAppender -log4j.appender.RollingFile.File=${rootdir}/sanri-${module}.log -log4j.appender.RollingFile.layout=org.apache.log4j.PatternLayout -#log4j.appender.RollingFile.layout.ConversionPattern=[%d{yyyy-MM-dd HH:mm:ss}] %-5p [%t] - %m%n -log4j.appender.RollingFile.layout.ConversionPattern=%d [%t] %-5p [%C->%M(%L)] - %m%n - - diff --git a/jun_java_plugins/jun_excel/easyexcel.md b/jun_java_plugins/jun_excel/easyexcel.md deleted file mode 100644 index 1151e3870d..0000000000 --- a/jun_java_plugins/jun_excel/easyexcel.md +++ /dev/null @@ -1,211 +0,0 @@ -# easyexcel-encapsulation -easyexcel 项目地址 :https://github.com/alibaba/easyexcel - -#### 对 easyexcel 进行了方法的封装,可以做到一个函数完成简单的读取和导出 - -#### 目前 easyexcel 版本已经更新至 1.1.2-beta4 - ---- - -# 一. 依赖 -首先是添加该项目的依赖,目前的版本是 1.1.2-beta4 -``` - - com.alibaba - easyexcel - 1.1.2-beta4 - -``` - -# 二. 需要的类 -![](https://upload-images.jianshu.io/upload_images/8807674-5fe0519ac2597f96.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) - -## 1. ExcelUtil -工具类,可以直接调用该工具类的方法完成 Excel 的读或者写 - -## 2. ExcelListener -监听类,可以根据需要,自定义处理获取到的数据 -``` -public class ExcelListener extends AnalysisEventListener { - - //自定义用于暂时存储data。 - //可以通过实例获取该值 - private List datas = new ArrayList<>(); - - /** - * 通过 AnalysisContext 对象还可以获取当前 sheet,当前行等数据 - */ - @Override - public void invoke(Object object, AnalysisContext context) { - //数据存储到list,供批量处理,或后续自己业务逻辑处理。 - datas.add(object); - //根据自己业务做处理 - doSomething(object); - } - - private void doSomething(Object object) { - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - /* - datas.clear(); - 解析结束销毁不用的资源 - */ - } - - public List getDatas() { - return datas; - } - - public void setDatas(List datas) { - this.datas = datas; - } -} -``` - -## 3. ExcelWriterFactroy -用于导出多个 sheet 的 Excel,通过多次调用 write 方法写入多个 sheet - -## 4. ExcelException -捕获相关 Exception - -# 三. 读取 Excel -读取 Excel 时只需要调用 ```ExcelUtil.readExcel()``` 方法 -``` -@RequestMapping(value = "readExcel", method = RequestMethod.POST) -public Object readExcel(MultipartFile excel) { - return ExcelUtil.readExcel(excel, new ImportInfo()); -} -``` - -其中 excel 是 MultipartFile 类型的文件对象,而 new ImportInfo() 是该 Excel 所映射的实体对象,需要继承 **BaseRowModel** 类,如: -``` -public class ImportInfo extends BaseRowModel { - @ExcelProperty(index = 0) - private String name; - - @ExcelProperty(index = 1) - private String age; - - @ExcelProperty(index = 2) - private String email; - - /* - 作为 excel 的模型映射,需要 setter 方法 - */ - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getAge() { - return age; - } - - public void setAge(String age) { - this.age = age; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } -} -``` -作为映射实体类,通过 @ExcelProperty 注解与 index 变量可以标注成员变量所映射的列,同时不可缺少 setter 方法 - - - -# 四. 导出 Excel -### 1. 导出的 Excel 只拥有一个 sheet -只需要调用 ```ExcelUtil.writeExcelWithSheets()``` 方法: -``` -@RequestMapping(value = "writeExcel", method = RequestMethod.GET) -public void writeExcel(HttpServletResponse response) throws IOException { - List list = getList(); - String fileName = "一个 Excel 文件"; - String sheetName = "第一个 sheet"; - - ExcelUtil.writeExcelWithSheets(response, list, fileName, sheetName, new ExportInfo()); - } -``` -fileName,sheetName 分别是导出文件的文件名和 sheet 名,new ExportInfo() 为导出数据的映射实体对象,list 为导出数据。 - -对于映射实体类,可以根据需要通过 @ExcelProperty 注解自定义表头,当然同样需要继承 BaseRowModel 类,如: -``` -public class ExportInfo extends BaseRowModel { - @ExcelProperty(value = "姓名" ,index = 0) - private String name; - - @ExcelProperty(value = "年龄",index = 1) - private String age; - - @ExcelProperty(value = "邮箱",index = 2) - private String email; - - @ExcelProperty(value = "地址",index = 3) - private String address; -} -``` -value 为列名,index 为列的序号 - -如果需要复杂一点,可以实现如下图的效果: -![](https://upload-images.jianshu.io/upload_images/8807674-5cb70346428fea93.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) - -对应的实体类写法如下: -``` -public class MultiLineHeadExcelModel extends BaseRowModel { - - @ExcelProperty(value = {"表头1","表头1","表头31"},index = 0) - private String p1; - - @ExcelProperty(value = {"表头1","表头1","表头32"},index = 1) - private String p2; - - @ExcelProperty(value = {"表头3","表头3","表头3"},index = 2) - private int p3; - - @ExcelProperty(value = {"表头4","表头4","表头4"},index = 3) - private long p4; - - @ExcelProperty(value = {"表头5","表头51","表头52"},index = 4) - private String p5; - - @ExcelProperty(value = {"表头6","表头61","表头611"},index = 5) - private String p6; - - @ExcelProperty(value = {"表头6","表头61","表头612"},index = 6) - private String p7; - - @ExcelProperty(value = {"表头6","表头62","表头621"},index = 7) - private String p8; - - @ExcelProperty(value = {"表头6","表头62","表头622"},index = 8) - private String p9; -} -``` -### 2. 导出的 Excel 拥有多个 sheet -调用 ```ExcelUtil.writeExcelWithSheets()``` 处理第一个 sheet,之后调用 ```write()``` 方法依次处理之后的 sheet,最后使用 ```finish()``` 方法结束 -``` -public void writeExcelWithSheets(HttpServletResponse response) throws IOException { - List list = getList(); - String fileName = "一个 Excel 文件"; - String sheetName1 = "第一个 sheet"; - String sheetName2 = "第二个 sheet"; - String sheetName3 = "第三个 sheet"; - - ExcelUtil.writeExcelWithSheets(response, list, fileName, sheetName1, new ExportInfo()) - .write(list, sheetName2, new ExportInfo()) - .write(list, sheetName3, new ExportInfo()) - .finish(); -} -``` -write 方法的参数为当前 sheet 的 list 数据,当前 sheet 名以及对应的映射类 - diff --git a/jun_java_plugins/jun_excel/pom.xml b/jun_java_plugins/jun_excel/pom.xml deleted file mode 100644 index d335b0a9c5..0000000000 --- a/jun_java_plugins/jun_excel/pom.xml +++ /dev/null @@ -1,135 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_excel - 1.0 - - jar - jun_excel - - - - - 1.7.22 - - - - - junit - junit - 4.11 - test - - - - - org.apache.poi - poi - 3.15 - - - org.apache.poi - poi-ooxml - 3.15 - - - - org.slf4j - slf4j-api - ${slf4j.version} - - - - ch.qos.logback - logback-classic - 1.1.9 - test - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-test - test - - - - junit - junit - 4.12 - test - - - - com.alibaba - easyexcel - 1.1.2-beta4 - - - - - - jun_excel - - - org.apache.maven.plugins - maven-compiler-plugin - 3.5.1 - - 1.8 - 1.8 - UTF-8 - - - - org.apache.maven.plugins - maven-source-plugin - 2.4 - - true - - - - attach-sources - - jar - - - - - - org.apache.maven.plugins - maven-release-plugin - 2.5.3 - - v@{project.version} - - - - - - - - - org.springframework.boot - spring-boot-dependencies - 1.5.6.RELEASE - pom - import - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_excel/src/main/resources/application.properties b/jun_java_plugins/jun_excel/src/main/resources/application.properties deleted file mode 100644 index 54e696d589..0000000000 --- a/jun_java_plugins/jun_excel/src/main/resources/application.properties +++ /dev/null @@ -1,4 +0,0 @@ -spring.http.multipart.max-file-size=100MB -spring.http.multipart.max-request-size=100MB -spring.http.multipart.maxFileSize=100MB -spring.http.multipart.maxRequestSize=1000MB diff --git a/jun_java_plugins/jun_fileupload/pom.xml b/jun_java_plugins/jun_fileupload/pom.xml deleted file mode 100644 index 8fee3e8112..0000000000 --- a/jun_java_plugins/jun_fileupload/pom.xml +++ /dev/null @@ -1,68 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_fileupload - 1.0 - war - - - - UTF-8 - - - - - - - - - commons-fileupload - commons-fileupload - 1.4 - - - - log4j - log4j - 1.2.17 - - - - - com.alibaba - fastjson - 1.2.72 - - - - junit - junit - 3.8.1 - test - - - - - mysql - mysql-connector-java - 5.1.40 - - - javax.servlet - servlet-api - 3.0-alpha-1 - compile - - - - jun_fileupload - - diff --git a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/BreakDown.java b/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/BreakDown.java deleted file mode 100644 index 7f1fd7a7e0..0000000000 --- a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/BreakDown.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.jun.plugin.file; - -import java.io.File; -import java.io.InputStream; -import java.io.RandomAccessFile; -import java.net.HttpURLConnection; -import java.net.URL; - -public class BreakDown { - public static void main(String[] args) throws Exception { - String fileName = "video.avi"; - String path = "http://localhost:6666/website/up/"+fileName; - String savePath = "d:/a/"+fileName; - File file = new File(savePath); - long size = file.length(); - System.err.println(file.length()); - - URL url = new URL(path); - HttpURLConnection con = (HttpURLConnection) url.openConnection(); - con.setRequestMethod("GET"); - //设置下载区间 - con.setRequestProperty("range","bytes="+size+"-"); - con.connect(); - int code = con.getResponseCode();//只要断点下载,返回的已经不是200,206 - System.err.println(code); - if(code==206){ - InputStream in= con.getInputStream(); - int serverSize = con.getContentLength(); - System.err.println("服务器返回的长度:"+serverSize); - System.err.println("这次从哪开开始写:"+size); - //必须要使用 - RandomAccessFile out = new RandomAccessFile(file,"rw"); - out.seek(size); - - byte[] b = new byte[1024]; - int len = -1; - while((len=in.read(b))!=-1){ - out.write(b,0,len); - } - out.close(); - } - } -} diff --git a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/CommonDown.java b/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/CommonDown.java deleted file mode 100644 index ce598d19f2..0000000000 --- a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/CommonDown.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.jun.plugin.file; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.io.OutputStream; -import java.math.BigDecimal; -import java.net.HttpURLConnection; -import java.net.URL; -public class CommonDown { - public static void main(String[] args) throws Exception { - String path = "http://localhost:6666/day22_cos/up/video.avi"; - URL url = new URL(path); - HttpURLConnection con = (HttpURLConnection) url.openConnection(); - con.setRequestMethod("GET"); - con.setDoInput(true); - con.connect(); - int code = con.getResponseCode(); - System.err.println(code); - if (code == 200) { - //获取文件大小 - long size = con.getContentLength(); - System.err.println("总大小是:"+size); - //声明下载到的字节 - long sum=0; - BigDecimal bd = new BigDecimal(0D); - double already = 0D; - InputStream in = con.getInputStream(); - byte[] b = new byte[1024]; - int len = -1; - OutputStream out = new FileOutputStream("d:/a/video.avi"); - while ((len = in.read(b)) != -1) { - out.write(b, 0, len); - sum=sum+len; - double percent = ((double)sum)/((double)size); - percent*=100; - bd = new BigDecimal(percent); - bd = bd.divide(new BigDecimal(1),0,BigDecimal.ROUND_HALF_UP); - if(bd.doubleValue()!=already){ - System.err.println(bd.intValue()+"%"); - already=bd.doubleValue(); - } - } - out.close(); - } - } -} diff --git a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/FileTest.java b/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/FileTest.java deleted file mode 100644 index d5f0a73f99..0000000000 --- a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/FileTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.jun.plugin.file; - -import java.io.File; -import java.util.Arrays; -import java.util.Date; - -/** - * File类测试 - * - * @author cxy @ www.cxyapi.com - */ -public class FileTest { - public static void main(String[] args) throws Exception { - String filePath = "D:" + File.separator + "fileTest" + File.separator; - String fileName = "test.txt"; - File myFolder = new File(filePath); - // 文件夹不存在时创建文件夹 - if (!myFolder.exists()) { - // myFolder.mkdir(); //创建当前目录 - myFolder.mkdirs(); // 创建当前目录结构的所有目录 - } - // 文件不存在时创建文件 - File myFile = new File(filePath + fileName); - if (!myFile.exists()) { - myFile.createNewFile();// 创建一个文件 - } - System.out.println("------------------------"); - // 文件信息 - System.out.println("文件绝对路径:" + myFile.getAbsolutePath()); - System.out.println("文件名称:" + myFile.getName()); - System.out.println("文件父节点:" + myFile.getParent()); - System.out.println("是文件夹吗?:" + myFile.isDirectory()); - System.out.println("是文件吗?:" + myFile.isFile()); - System.out.println("是隐藏的吗?:" + myFile.isHidden()); - System.out.println("是可读的吗?:" + myFile.canRead()); - System.out.println("是可写的吗?:" + myFile.canWrite()); - System.out.println("是可执行的吗?:" + myFile.canExecute()); - System.out.println("最后一次修改时间?:" + new Date(myFile.lastModified())); - System.out.println("文件的大小:" + myFile.length()); - System.out.println(myFile.toURI()); - System.out.println("------------------------"); - // 文件列表 - String[] allFileNameInPath = myFolder.list(); // 当前路径下所有文件和文件夹的名称 - System.out.println(Arrays.asList(allFileNameInPath)); - File[] allFileInPath = myFolder.listFiles(); // 当前路径下所有文件和文件夹数组 - File[] roots = File.listRoots(); // 所有磁盘根路径,可以使用上面的方法继续对其进行遍历 - for (File one : roots) { - System.out.print(one + " "); - } - System.out.println(""); - System.out.println("------------------------"); - // 删除文件 和 文件夹 - myFile.delete(); - if (!myFile.exists()) { - System.out.println("文件删除成功"); - } - myFolder.delete(); - if (!myFolder.exists()) { - System.out.println("文件夹删除成功"); - } - System.out.println("------------------------"); - // 临时文件相关操作 - File tempFilePath = new File("."); // 在当前项目路径下 - // 以temp开头,txt结尾的临时文件,如果不带最后一个参数那么临时文件将生成到当前操作系统的临时文件目录中 - File tempFile = File.createTempFile("temp", ".txt", tempFilePath); - System.out.println("临时文件位置:" + tempFile.getAbsolutePath()); - tempFile.deleteOnExit(); // jvm结束的时候删除文件 - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/GetURL.java b/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/GetURL.java deleted file mode 100644 index 7a9a857607..0000000000 --- a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/GetURL.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.jun.plugin.file; -import java.io.*; -import java.net.*; - -public class GetURL { - public static void main(String[] args) { - InputStream in = null; - OutputStream out = null; - try { - // ��������в��� - if ((args.length != 1)&& (args.length != 2)) - throw new IllegalArgumentException("Wrong number of args"); - - // ������������� - URL url = new URL(args[0]); - in = url.openStream(); - if (args.length == 2) - out = new FileOutputStream(args[1]); - else out = System.out; - - // �� URL ����������� - byte[] buffer = new byte[4096]; - int bytes_read; - while((bytes_read = in.read(buffer)) != -1) - out.write(buffer, 0, bytes_read); - } - // �����쳣�����������Ϣ - catch (Exception e) { - System.err.println(e); - System.err.println("Usage: java GetURL []"); - } - finally { // ��֤�ر�������������� - try { in.close(); out.close(); } catch (Exception e) {} - } - } -} diff --git a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/GetWebPages.java b/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/GetWebPages.java deleted file mode 100644 index 8f004321d7..0000000000 --- a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/GetWebPages.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.jun.plugin.file; - -import java.io.BufferedReader; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.net.URL; -import java.net.URLConnection; - -public class GetWebPages { - - /** - * @param args - */ - public static void main(String[] args) { - try { - URL url = new URL("http://jj.24365pt.com/index.jhtml"); - - URLConnection conn = url.openConnection(); - conn.setDoOutput(true); - InputStream in = null; - in = url.openStream(); - String content = pipe(in,"utf-8"); - System.out.println(content); - } catch (Exception e) { - e.printStackTrace(); - } - } - - static String pipe(InputStream in,String charset) throws IOException { - StringBuffer s = new StringBuffer(); - if(charset==null||"".equals(charset)){ - charset="utf-8"; - } - String rLine = null; - BufferedReader bReader = new BufferedReader(new InputStreamReader(in,charset)); - PrintWriter pw = null; - - FileOutputStream fo = new FileOutputStream("../index.html"); - OutputStreamWriter writer = new OutputStreamWriter(fo, "utf-8"); - pw = new PrintWriter(writer); - while ( (rLine = bReader.readLine()) != null) { - String tmp_rLine = rLine; - int str_len = tmp_rLine.length(); - if (str_len > 0) { - s.append(tmp_rLine); - pw.println(tmp_rLine); - pw.flush(); - } - tmp_rLine = null; - } - in.close(); - pw.close(); - return s.toString(); - } -} diff --git a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/MultiThreadDown.java b/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/MultiThreadDown.java deleted file mode 100644 index 3c945e7f9d..0000000000 --- a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/MultiThreadDown.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.jun.plugin.file; -import java.io.File; -import java.io.InputStream; -import java.io.RandomAccessFile; -import java.net.HttpURLConnection; -import java.net.URL; -/** - * 多线程下载同一个文件 - 思想: - * - */ -public class MultiThreadDown { - public MultiThreadDown() throws Exception { - //声明url - String path = "http://localhost:6666/day23/up/bin.zip"; - //第一步:声明url对象 - URL url = new URL(path); - //第二步:返回连接对象 - HttpURLConnection con = (HttpURLConnection) url.openConnection(); - //第三步:设置请求类型 - con.setRequestMethod("GET"); - //第四步接收信息 - con.setDoInput(true); - //第五步:连接 - con.connect(); - //6:状态码 - int code = con.getResponseCode(); - if(code==200){ - //7:数据的长度 - int sum = con.getContentLength(); - System.err.println("总文件的大小:"+sum); - //7.1有了文件的长度,直接创建一个相同大小的文件 - String fileName = "d:/a/bin.zip"; - RandomAccessFile file = new RandomAccessFile(new File(fileName),"rw"); - file.setLength(sum); - file.close(); - //8:声明线程的个数 - int threadCount = 3; - //9:计算每个线程的下载量 - int threadSize = sum/threadCount +(sum%threadCount==0?0:1); - System.err.println("每个线程下载的数据量:"+threadSize); - //10:计算每个线程下载的数据量 - for(int i=0;i0 ? urlStr.lastIndexOf("?") : urlStr.length()); - if("".equalsIgnoreCase(this.fileName)){ - this.fileName = UUID.randomUUID().toString(); - } - - this.url = new URL(urlStr); - HttpURLConnection con = (HttpURLConnection) url.openConnection(); - setHeader(con); - // �õ�content�ij��� - contentLength = con.getContentLength(); - // ��context��ΪthreadNum�εĻ���ÿ�εij��ȡ� - this.threadLength = contentLength / threadNum; - - // ��һ�������������ص���ʱ�ļ������öϵ㣬������µ�������������Ŀ���ļ��� - startPos = setThreadBreakpoint(fileDir, fileName, contentLength, - startPos); - - // �ڶ������ֶ���߳������ļ� - ExecutorService exec = Executors.newCachedThreadPool(); - for (int i = 0; i < threadNum; i++) { - // �������߳�������������ݣ�ÿ����ݵ���ʼλ��Ϊ(threadLength * i + �����س���) - startPos[i] += threadLength * i; - - /* - * �������̵߳���ֹλ�ã������һ���̼߳�Ϊ(threadLength * (i + 1) - 1) - * ���һ���̵߳���ֹλ�ü�Ϊ�������ݵij��� - */ - if (i == threadNum - 1) { - endPos = contentLength; - } else { - endPos = threadLength * (i + 1) - 1; - } - // �������̣߳���ִ�С� - ChildThread thread = new ChildThread(this, latch, i, - startPos[i], endPos); - childThreads[i] = thread; - exec.execute(thread); - } - - try { - // �ȴ�CountdownLatch�ź�Ϊ0����ʾ�������̶߳����� - latch.await(); - exec.shutdown(); - - // ����ѷֶ�������������ʱ�ļ��е�����д��Ŀ���ļ��С� - tempFileToTargetFile(childThreads); - - } catch (InterruptedException e) { - e.printStackTrace(); - } - } catch (IOException e) { - e.printStackTrace(); - } - - return fileDir + fileName; - } - - private void tempFileToTargetFile(ChildThread[] childThreads) { - try { - BufferedOutputStream outputStream = new BufferedOutputStream( - new FileOutputStream(fileDir + fileName)); - - // �����������̴߳�������ʱ�ļ�����˳�����������д��Ŀ���ļ��� - for (int i = 0; i < threadNum; i++) { - if (statusError) { - for (int k = 0; k < threadNum; k++) { - if (childThreads[k].tempFile.length() == 0) - childThreads[k].tempFile.delete(); - } - System.out.println("�����������񲻳ɹ��������������߳���"); - break; - } - - BufferedInputStream inputStream = new BufferedInputStream( - new FileInputStream(childThreads[i].tempFile)); - System.out.println("Now is file " + childThreads[i].id); - int len = 0; - long count = 0; - byte[] b = new byte[1024]; - while ((len = inputStream.read(b)) != -1) { - count += len; - outputStream.write(b, 0, len); - if ((count % 4096) == 0) { - outputStream.flush(); - } - } - - inputStream.close(); - // ɾ����ʱ�ļ� - if (childThreads[i].status == ChildThread.STATUS_HAS_FINISHED) { - childThreads[i].tempFile.delete(); - } - } - - outputStream.flush(); - outputStream.close(); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - private long[] setThreadBreakpoint(String fileDir2, String fileName2, - long contentLength, long[] startPos) { - File file = new File(fileDir + fileName); - long localFileSize = file.length(); - - if (file.exists()) { - System.out.println("file " + fileName + " has exists!"); - // ���ص�Ŀ���ļ��Ѵ��ڣ��ж�Ŀ���ļ��Ƿ����� - if (localFileSize < contentLength) { - System.out.println("Now download continue ... "); - - // ����Ŀ���ļ���������ʱ�ļ������öϵ��λ�ã���ÿ����ʱ�ļ��ij��� - File tempFileDir = new File(fileDir); - File[] files = tempFileDir.listFiles(); - for (int k = 0; k < files.length; k++) { - String tempFileName = files[k].getName(); - // ��ʱ�ļ�������ʽΪ��Ŀ���ļ���+"_"+��� - if (tempFileName != null && files[k].length() > 0 - && tempFileName.startsWith(fileName + "_")) { - int fileLongNum = Integer.parseInt(tempFileName - .substring(tempFileName.lastIndexOf("_") + 1, - tempFileName.lastIndexOf("_") + 2)); - // Ϊÿ���߳����������ص�λ�� - startPos[fileLongNum] = files[k].length(); - } - } - } - } else { - // ������ص�Ŀ���ļ������ڣ��򴴽����ļ� - try { - file.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - return startPos; - } - - /** - * - * @author annegu - * @since 2009-07-16 - * - */ - public class ChildThread extends Thread { - public static final int STATUS_HASNOT_FINISHED = 0; - public static final int STATUS_HAS_FINISHED = 1; - public static final int STATUS_HTTPSTATUS_ERROR = 2; - private DownloadTask task; - private int id; - private long startPosition; - private long endPosition; - private final CountDownLatch latch; - // private RandomAccessFile tempFile = null; - private File tempFile = null; - //�߳�״̬�� - private int status = ChildThread.STATUS_HASNOT_FINISHED; - - public ChildThread(DownloadTask task, CountDownLatch latch, int id, - long startPos, long endPos) { - super(); - this.task = task; - this.id = id; - this.startPosition = startPos; - this.endPosition = endPos; - this.latch = latch; - - try { - tempFile = new File(this.task.fileDir + this.task.fileName - + "_" + id); - if (!tempFile.exists()) { - tempFile.createNewFile(); - } - } catch (IOException e) { - e.printStackTrace(); - } - - } - - public void run() { - System.out.println("Thread " + id + " run ..."); - HttpURLConnection con = null; - InputStream inputStream = null; - BufferedOutputStream outputStream = null; - long count = 0; - long threadDownloadLength = endPosition - startPosition; - - try { - outputStream = new BufferedOutputStream(new FileOutputStream( - tempFile.getPath(), true)); - } catch (FileNotFoundException e2) { - e2.printStackTrace(); - } - - for (;;) { - try { - // ��URLConnection - con = (HttpURLConnection) task.url.openConnection(); - setHeader(con); - con.setAllowUserInteraction(true); - // �������ӳ�ʱʱ��Ϊ10000ms - con.setConnectTimeout(10000); - // ���ö�ȡ��ݳ�ʱʱ��Ϊ10000ms - con.setReadTimeout(10000); - - if (startPosition < endPosition) { - // ����������ݵ���ֹ��� - con.setRequestProperty("Range", "bytes=" - + startPosition + "-" + endPosition); - System.out.println("Thread " + id - + " startPosition is " + startPosition); - System.out.println("Thread " + id + " endPosition is " - + endPosition); - - //�ж�http status�Ƿ�ΪHTTP/1.1 206 Partial Content����200 OK - //�������������״̬����status��ΪSTATUS_HTTPSTATUS_ERROR - if (con.getResponseCode() != HttpURLConnection.HTTP_OK - && con.getResponseCode() != HttpURLConnection.HTTP_PARTIAL) { - System.out.println("Thread " + id + ": code = " - + con.getResponseCode() + ", status = " - + con.getResponseMessage()); - status = ChildThread.STATUS_HTTPSTATUS_ERROR; - this.task.statusError = true; - outputStream.close(); - con.disconnect(); - System.out.println("Thread " + id + " finished."); - - //�ݼ�������ļ�����������㣬���ͷ����еȴ���̡߳� - latch.countDown(); - break; - } - - inputStream = con.getInputStream(); - int len = 0; - byte[] b = new byte[1024]; - while (!this.task.statusError - && (len = inputStream.read(b)) != -1) { - outputStream.write(b, 0, len); - - count += len; - startPosition += len; - // ÿ����4096��byte��һ���ڴ�ҳ�����������flushһ�� - if (count % 4096 == 0) { - outputStream.flush(); - } - } - - if (count >= threadDownloadLength) { - status = ChildThread.STATUS_HAS_FINISHED; - } - outputStream.flush(); - outputStream.close(); - inputStream.close(); - con.disconnect(); - } else { - status = ChildThread.STATUS_HAS_FINISHED; - } - - - System.out.println("Thread " + id + " finished."); - latch.countDown(); - break; - } catch (IOException e) { - try { - outputStream.flush(); - TimeUnit.SECONDS.sleep(getSleepSeconds()); - } catch (InterruptedException e1) { - e1.printStackTrace(); - } catch (IOException e2) { - e2.printStackTrace(); - } - continue; - } - } - if (outputStream != null) { - try { - outputStream.close(); - con.disconnect(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - } - - private void setHeader(URLConnection con) { - con.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.3) Gecko/2008092510 Ubuntu/8.04 (hardy) Firefox/3.0.3"); - con.setRequestProperty("Accept-Language", "en-us,en;q=0.7,zh-cn;q=0.3"); - con.setRequestProperty("Accept-Encoding", "aa"); - con.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); - con.setRequestProperty("Keep-Alive", "300"); - con.setRequestProperty("Connection", "keep-alive"); - con.setRequestProperty("If-Modified-Since", "Fri, 02 Jan 2009 17:00:05 GMT"); - con.setRequestProperty("If-None-Match", "\"1261d8-4290-df64d224\""); - con.setRequestProperty("Cache-Control", "max-age=0"); - con.setRequestProperty("Referer", "http://www.skycn.com/soft/14857.html"); - } - - public long getSleepSeconds() { - return sleepSeconds; - } - - public void setSleepSeconds(long sleepSeconds) { - this.sleepSeconds = sleepSeconds; - } - -} diff --git a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/file_server/File_client.java b/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/file_server/File_client.java deleted file mode 100644 index 4cd7238be4..0000000000 --- a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/file_server/File_client.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.jun.plugin.file.file_server; -import java.io.*; -import java.net.*; - -public class File_client { - - - public static void main(String[] args) throws Exception { - - Socket clientSocket = new Socket("localhost", 6789); - - BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); - //get the string from server - String content = ""; - StringBuilder sb = new StringBuilder(); - while(content != null){ - content = inFromServer.readLine(); - - if(content == null){ - break; - } - - sb.append(content.trim()); - break; - } - //print the string in buffer. - System.out.print("the string from the server is :\n"); - System.out.print(sb.toString()); - //safe in the file. - try { - File file = new File("client.txt"); - if (!file.exists()) { - file.createNewFile(); - } - FileOutputStream os = new FileOutputStream(file); - BufferedOutputStream bos = new BufferedOutputStream(os); - bos.write(sb.toString().getBytes()); - bos.close(); - os.close(); - } catch (Exception e) { - e.printStackTrace(); - } - - System.out.println("\nsafe finish."); - clientSocket.close(); - - } - -} diff --git a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/file_server/File_server.java b/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/file_server/File_server.java deleted file mode 100644 index 071135ddf2..0000000000 --- a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/file_server/File_server.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.jun.plugin.file.file_server; -import java.net.*; -import java.io.*; - -public class File_server { - - /** - * @param args - */ - public static void main(String[] args) throws Exception{ - File file = new File("server.txt"); - ServerSocket welcomeSocket = new ServerSocket(6789); - - while(true) - { - BufferedReader bf = new BufferedReader(new FileReader(file)); - String content = ""; - StringBuilder sb = new StringBuilder(); - - while(content != null){ - content = bf.readLine(); - - if(content == null){ - break; - } - - sb.append(content.trim()); - } - - bf.close(); - System.out.print(sb.toString()); - - Socket connectionSocket = welcomeSocket.accept(); - DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); - outToClient.writeBytes(sb.toString()); - outToClient.close(); - } - } - -} diff --git a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/fileupload/FileHelper.java b/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/fileupload/FileHelper.java deleted file mode 100644 index 489b29f7e8..0000000000 --- a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/fileupload/FileHelper.java +++ /dev/null @@ -1,157 +0,0 @@ -package com.jun.plugin.file.fileupload; - - -/* - * Static File routines. - * Copyright (C) 2002 Stephen Ostermiller - * http://ostermiller.org/contact.pl?regarding=Java+Utilities - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * See COPYING.TXT for details. - */ - -import java.io.*; -import java.text.MessageFormat; -import java.util.ResourceBundle; -import java.util.Locale; - -/** - * Utilities for File manipulation. - * More information about this class is available from ostermiller.org. - * - * @author Stephen Ostermiller http://ostermiller.org/contact.pl?regarding=Java+Utilities - * @since ostermillerutils 1.00.00 - */ -public class FileHelper { - - /** - * Locale specific strings displayed to the user. - * - * @since ostermillerutils 1.00.00 - */ - protected static ResourceBundle labels = ResourceBundle.getBundle("com.Ostermiller.util.FileHelper", Locale.getDefault()); - - - /** - * Move a file from one location to another. An attempt is made to rename - * the file and if that fails, the file is copied and the old file deleted. - * - * If the destination file already exists, an exception will be thrown. - * - * @param from file which should be moved. - * @param to desired destination of the file. - * @throws IOException if an error occurs. - * - * @since ostermillerutils 1.00.00 - */ - public static void move(File from, File to) throws IOException { - move(from, to, false); - } - - /** - * Move a file from one location to another. An attempt is made to rename - * the file and if that fails, the file is copied and the old file deleted. - * - * @param from file which should be moved. - * @param to desired destination of the file. - * @param overwrite If false, an exception will be thrown rather than overwrite a file. - * @throws IOException if an error occurs. - * - * @since ostermillerutils 1.00.00 - */ - public static void move(File from, File to, boolean overwrite) throws IOException { - if (to.exists()){ - if (overwrite){ - if (!to.delete()){ - throw new IOException( - MessageFormat.format( - labels.getString("deleteerror"), - (Object[])new String[] { - to.toString() - } - ) - ); - } - } else { - throw new IOException( - MessageFormat.format( - labels.getString("alreadyexistserror"), - (Object[])new String[] { - to.toString() - } - ) - ); - } - } - - if (from.renameTo(to)) return; - - InputStream in = null; - OutputStream out = null; - try { - in = new FileInputStream(from); - out = new FileOutputStream(to); - copy(in, out); - in.close(); - in = null; - out.flush(); - out.close(); - out = null; - if (!from.delete()){ - throw new IOException( - MessageFormat.format( - labels.getString("deleteoriginalerror"), - (Object[])new String[] { - from.toString(), - to.toString() - } - ) - ); - } - } finally { - if (in != null){ - in.close(); - in = null; - } - if (out != null){ - out.flush(); - out.close(); - out = null; - } - } - } - - /** - * Buffer size when reading from input stream. - * - * @since ostermillerutils 1.00.00 - */ - private final static int BUFFER_SIZE = 1024; - - /** - * Copy the data from the input stream to the output stream. - * - * @param in data source - * @param out data destination - * @throws IOException in an input or output error occurs - * - * @since ostermillerutils 1.00.00 - */ - private static void copy(InputStream in, OutputStream out) throws IOException { - byte[] buffer = new byte[BUFFER_SIZE]; - int read; - while((read = in.read(buffer)) != -1){ - out.write(buffer, 0, read); - } - } -} diff --git a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/fileupload/FileUpload.java b/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/fileupload/FileUpload.java deleted file mode 100644 index 53a45c24f2..0000000000 --- a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/fileupload/FileUpload.java +++ /dev/null @@ -1,140 +0,0 @@ -package com.jun.plugin.file.fileupload; - - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.ServletInputStream; -import java.util.Dictionary; -import java.util.Hashtable; -import java.io.*; - -public class FileUpload { - // ��������������洢�ϴ��ļ������֣�·����? - private String savePath, filepath, filename, contentType; - // �������û���??��������ݵ�����?/ֵ�� - private Dictionary fields; - - // ����ļ�����? - public String getFilename() { - return filename; - } - // ����ϴ��ļ���·��? - public String getFilepath() { - return filepath; - } - // �趨�ϴ��ļ���·�������û���趨�ͱ����ڷ�����Ĭ��Ŀ�? - public void setSavePath(String savePath) { - this.savePath = savePath; - } - // �õ��ļ����� - public String getContentType() { - return contentType; - } - - public String getFieldValue(String fieldName) { - if (fields == null || fieldName == null) - return null; - return (String) fields.get(fieldName); - } - - private void setFilename(String s) { - if (s == null) - return; - int pos = s.indexOf("filename=\""); - if (pos != -1) { - filepath = s.substring(pos + 10, s.length() - 1); - pos = filepath.lastIndexOf("\\"); - if (pos != -1) - filename = filepath.substring(pos + 1); - else - filename = filepath; - } - } - - private void setContentType(String s) { - if (s == null) - return; - int pos = s.indexOf(": "); - if (pos != -1) - contentType = s.substring(pos + 2, s.length()); - } - - public void doUpload(HttpServletRequest request) throws IOException { - ServletInputStream in = request.getInputStream(); - byte[] line = new byte[128]; - int i = in.readLine(line, 0, 128); - if (i < 3) - return; - int boundaryLength = i - 2; - String boundary = new String(line, 0, boundaryLength); //-2�������ַ� - fields = new Hashtable(); - - while (i != -1) { - String newLine = new String(line, 0, i); - if (newLine - .startsWith("Content-Disposition: form-data; name=\"")) { - if (newLine.indexOf("filename=\"") != -1) { - setFilename(new String(line, 0, i - 2)); - if (filename == null) - return; - - //�ļ����� - i = in.readLine(line, 0, 128); - setContentType(new String(line, 0, i - 2)); - i = in.readLine(line, 0, 128); - - //���� - i = in.readLine(line, 0, 128); - newLine = new String(line, 0, i); - PrintWriter pw = - new PrintWriter( - new BufferedWriter( - new FileWriter( - (savePath == null ? "" : savePath) - + filename))); - while (i != -1 && !newLine.startsWith(boundary)) { - // �ļ����ݵ����һ�а����ַ�? - - // ������DZ����鵱ǰ���Ƿ�����? - - // ��һ�� - i = in.readLine(line, 0, 128); - if ((i == boundaryLength + 2 - || i == boundaryLength + 4) - && (new String(line, 0, i).startsWith(boundary))) - pw.print( - newLine.substring(0, newLine.length() - 2)); - else - pw.print(newLine); - newLine = new String(line, 0, i); - } - pw.close(); - } else { - // ��ͨ�??����Ԫ�� - // ��ȡ����Ԫ������ - int pos = newLine.indexOf("name=\""); - String fieldName = - newLine.substring(pos + 6, newLine.length() - 3); - i = in.readLine(line, 0, 128); - i = in.readLine(line, 0, 128); - newLine = new String(line, 0, i); - StringBuffer fieldValue = new StringBuffer(128); - while (i != -1 && !newLine.startsWith(boundary)) { - // ���һ�а����ַ�? - // ������DZ����鵱ǰ���Ƿ������һ�� - i = in.readLine(line, 0, 128); - if ((i == boundaryLength + 2 - || i == boundaryLength + 4) - && (new String(line, 0, i).startsWith(boundary))) - fieldValue.append( - newLine.substring(0, newLine.length() - 2)); - else - fieldValue.append(newLine); - newLine = new String(line, 0, i); - } - fields.put(fieldName, fieldValue.toString()); - } - } - i = in.readLine(line, 0, 128); - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/fileupload/FileUtil.java b/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/fileupload/FileUtil.java deleted file mode 100644 index d2179fa20e..0000000000 --- a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/fileupload/FileUtil.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.jun.plugin.file.fileupload; - - -import java.io.BufferedReader; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * - * @author Jason Krebs - * @date 2015骞?2鏈?7鏃? - */ -public class FileUtil { - - private static final String CHARSET = "UTF-8"; - private static final Logger LOGGER = Logger.getLogger(FileUtil.class.getName()); - - /** - * 鍙互浠嶫ar鍖呭唴閮ㄥ姞杞? - * - * @param input - * @return - */ - public static String loadFrom(InputStream input) { - BufferedReader reader = null; - StringBuilder data = new StringBuilder(); - try { - reader = new BufferedReader(new InputStreamReader(input, CHARSET)); - String line = null; - while ((line = reader.readLine()) != null) { - data.append(line); - } - } - catch (Exception e) { - LOGGER.log(Level.WARNING, e.getMessage()); - } - finally { - try { - if (reader != null) { - reader.close(); - reader = null; - } - } - catch (IOException e) { - LOGGER.log(Level.WARNING, e.getMessage()); - } - } - return data.toString(); - } - - /** - * 浠庡閮ㄨ矾寰勫姞杞? - * - * @param path - * @return - */ - public static String loadFrom(String path) { - try { - return loadFrom(new FileInputStream(path)); - } - catch (FileNotFoundException e) { - LOGGER.log(Level.WARNING, e.getMessage()); - } - return ""; - } - - public static void main(String[] args) { - System.out.println(loadFrom("D:/BackUp/Desktop/nodes.json")); - } - - public static void saveTo(String path, String message) { - OutputStreamWriter writer = null; - FileOutputStream output = null; - try { - output = new FileOutputStream(path); - writer = new OutputStreamWriter(output, CHARSET); - writer.write(message); - writer.flush(); - } - catch (Exception e) { - LOGGER.log(Level.WARNING, e.getMessage()); - } - finally { - try { - if (writer != null) { - writer.close(); - writer = null; - } - if (output != null) { - output.close(); - output = null; - } - } - catch (IOException e) { - LOGGER.log(Level.WARNING, e.getMessage()); - } - } - } - - - -} diff --git a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/fileupload/FileUtilTest.java b/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/fileupload/FileUtilTest.java deleted file mode 100644 index 722b8a166f..0000000000 --- a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/fileupload/FileUtilTest.java +++ /dev/null @@ -1,180 +0,0 @@ -package com.jun.plugin.file.fileupload; - - -import java.io.File; -import java.io.FilenameFilter; -import java.util.Arrays; -import java.util.regex.Pattern; - -public class FileUtilTest { - - /** - * @param args - */ - public static void main(String[] args) { - - File dir = new File("e:\\demodir"); -// dir.delete(); - removeDir(dir); - } - - public static void main11(String[] args) { - - File f = new File("D:"+File.separator+"hello"); - try{ - f.mkdir(); - }catch(Exception e){ - e.printStackTrace(); - } - } - - public static void removeDir(File dir) { - - File[] files = dir.listFiles(); - - for(File file : files){ - - if(file.isDirectory()){ - removeDir(file); - }else{ - System.out.println(file+":"+file.delete()); - } - } - System.out.println(dir+":"+dir.delete()); - } - - - public static void mainDirList(String[] args) { - File path = new File("."); - String[] list; - if (args.length == 0) { - list = path.list(); - } else { - // ���ォ����IJ�����Ϊ��������? - list = path.list(new DirFilter(args[0])); - } - for (int i = 0; i < list.length; i++) { - System.out.println(list[i]); - } - } - - private static void usage() { - System.err.println( - "Usage:MakeDirectories path1 ...\n" + - "Creates each path\n" + - "Usage:MakeDirectories -d path1 ...\n" + - "Deletes each path\n" + - "Usage:MakeDirectories -r path1 path2\n" + - "Renames from path1 to path2"); - System.exit(1); - } - - //��ʾ�ļ�����Ŀ¼����ϸ��Ϣ - private static void fileData(File f) { - System.out.println( - "Absolute path: " + f.getAbsolutePath() + - "\n Can read: " + f.canRead() + - "\n Can write: " + f.canWrite() + - "\n getName: " + f.getName() + - "\n getParent: " + f.getParent() + - "\n getPath: " + f.getPath() + - "\n length: " + f.length() + - "\n lastModified: " + f.lastModified()); - if(f.isFile()) - System.out.println("It's a file"); - else if(f.isDirectory()) - System.out.println("It's a directory"); - } - - public static void main33(String[] args) { - if(args.length < 1) usage(); - if(args[0].equals("-r")) { - if(args.length != 3) usage(); - File - old = new File(args[1]), - rname = new File(args[2]); - old.renameTo(rname); - fileData(old); - fileData(rname); - return; - } - int count = 0; - boolean del = false; - if(args[0].equals("-d")) { - count++; - del = true; - } - count--; - while(++count < args.length) { - File f = new File(args[count]); - if(f.exists()) { - System.out.println(f + " exists"); - if(del) { - System.out.println("deleting..." + f); - f.delete(); - } - } - else { // Ŀ¼����������Ҫ���� - if(!del) { - f.mkdirs(); - System.out.println("created " + f); - } - } - fileData(f); - } - } - - - - - - - - - - - - - - - - - - public static void main44(String[] args) { - File path = new File("."); - String[] list; -// if(args.length==0) -// list = path.list(); -// else -// list = path.list(new DirFilter(args[0])); - System.out.println(path.getAbsolutePath()+" size:"+fileSize(path)+"b"); - list = path.list(new DirFilter("[a-z]*")); - Arrays.sort(list, String.CASE_INSENSITIVE_ORDER); - for(String dirItem : list) - System.out.println(dirItem); - } - public static long fileSize(File file){ - long size = 0; - if(file.isDirectory()){ - for(File f : file.listFiles()) - size += fileSize(f); - }else{ - size = file.length(); - } - return size; - } - } - - - -class DirFilter implements FilenameFilter { - private Pattern pattern; - - public DirFilter(String regex) { - pattern = Pattern.compile(regex); - } - - public boolean accept(File dir, String name) { - return pattern.matcher(new File(name).getName()).matches(); - } -} diff --git a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/fileupload/ImageServlet.java b/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/fileupload/ImageServlet.java deleted file mode 100644 index 903239e3d4..0000000000 --- a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/fileupload/ImageServlet.java +++ /dev/null @@ -1,369 +0,0 @@ -package com.jun.plugin.file.fileupload; - - -import java.awt.Color; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.image.BufferedImage; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.Random; - -import javax.imageio.ImageIO; -import javax.servlet.ServletException; -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -public class ImageServlet extends HttpServlet { - public void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - //设置响应类型 - resp.setContentType("image/jpeg"); - int width=60; - int height=30; - BufferedImage img = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB); - Graphics g = img.getGraphics(); - g.setColor(Color.WHITE); - g.fillRect(0,0, width, height); - g.setFont(new Font("宋体", Font.BOLD,18)); - Random r = new Random(); - for(int i=0;i<4;i++){ - Color c = new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)); - int code = r.nextInt(10); - g.setColor(c); - g.drawString(""+code,i*15,10+r.nextInt(20)); - } - for(int i=0;i<10;i++){ - Color c = new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)); - g.setColor(c); - g.drawLine(r.nextInt(60),r.nextInt(30),r.nextInt(60),r.nextInt(30)); - } - //图片生效 - g.dispose(); - //写到 - ImageIO.write(img, "JPEG",resp.getOutputStream()); - } - - - - - // ���С�? - private final int WIDTH = 120; // ctrl+shift+x / y - private final int HEIGHT = 30; - - public void CheckImageServlet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - // ������Ҫ���ڴ��й���һ��ͼƬ���� - BufferedImage bf = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); - - Graphics2D graphics = (Graphics2D) bf.getGraphics(); - - // ���ñ�����ɫ - Color color = new Color(203, 222, 225); - graphics.setColor(color); - graphics.fillRect(0, 0, WIDTH, HEIGHT); - - String base = "ABCDEFGHIJKLMN"; - Random random = new Random(); - - // ״̬��: ��������ù�֮ǰ�����?, �Ƕ�.����, ��С�ȵ���Щ��Ϣ, - // ��ô����������,�����û��? ��ȥ ���ö�Ӧapi ȥ�����Щ�?, - // ��ô��Ȼ������֮ǰ�����ù��״�? - - graphics.setColor(Color.RED); - graphics.setFont(new Font("����", Font.BOLD, 18)); - int m = 13; - - StringBuilder sb = new StringBuilder(); - - // ��4 ���ַ� - for (int i = 0; i < 4; i++) { - - int index = random.nextInt(base.length()); - char charAt = base.charAt(index); - - // -30 --- 30 15 - int jiaodu = random.nextInt(60) - 30; - - // �Ƕȱ� ����:�� ���е�ʱ��ѧ�� - double theta = jiaodu * Math.PI / 180; - - // ����theta Ҫ���� ����, - graphics.rotate(theta, m, 15); - graphics.drawString(charAt + "", m, 19); - sb.append(charAt); - - graphics.rotate(-theta, m, 15); - m += 20; - } - - // �� sb �浽 session ��������? - request.getSession().setAttribute("checkcode_session", sb.toString()); - - // �� 4 �������� - graphics.setColor(Color.BLUE); - for (int i = 0; i < 4; i++) { - // �������? ���� - int x1 = random.nextInt(WIDTH); - int x2 = random.nextInt(WIDTH); - int y1 = random.nextInt(HEIGHT); - int y2 = random.nextInt(HEIGHT); - graphics.drawLine(x1, y1, x2, y2); - } - - // �ͷ���Դ - graphics.dispose(); - - ImageIO.write(bf, "png", response.getOutputStream()); - } - - - - public void GetImageServlet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - - //获得�?张图�? - - // 创建图片 -- 在内存中 - int width = 80; - int height = 40; - BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); - - //创建图层,获得画�? - Graphics g = image.getGraphics(); - //确定画笔颜色 - g.setColor(Color.BLACK); - //填充�?个矩�? - g.fillRect(0, 0, width, height); - //只需要一个边�? - //设置颜色 - g.setColor(Color.WHITE); - //填充�?个矩�? - g.fillRect(1, 1, width -2, height -2); - - //填充字符 - String data = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; - //设置字体 - g.setFont(new Font("宋体",Font.BOLD,30)); - - //缓存随机生成的字�? - StringBuffer buf = new StringBuffer(); - - //随机获得4个字�? - Random random = new Random(); - for(int i = 0 ; i < 4 ; i++){ - //设置随机颜色 - g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255))); - //获得�?个随机字�? - int index = random.nextInt(62); - //截取字符�? - String str = data.substring(index, index + 1); //[) - //�?要将随机的字符,写到图片�? - g.drawString(str, 20 * i, 30); - //缓存 - buf.append(str); - } - - //将获得随机字符串,保存到session - // * 获得session - HttpSession session = request.getSession(); - // * 保存�? - session.setAttribute("number", buf.toString()); - - //干扰�? - for(int i = 0 ; i < 10 ; i ++){ - //设置随机颜色 - g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255))); - //随机画直�? - g.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height)); - } - - - - /** - * jpg - image/jpeg - */ - //通知浏览器发送的数据时一张图�? - response.setContentType("image/jpeg"); - //将图片发送给浏览�? - ImageIO.write(image, "jpg", response.getOutputStream()); - - - - } - - - - - /** - * 验证码图片宽�? - */ - private final int IMG_WIDTH = 90; - /** - * 验证码图片高�? - */ - private final int IMG_HEIGHT = 20; - /** - * 验证码字�? - */ - private final String strs = "1234567890abcdefghijklmnopqrstuvwxyz"; -// private final String strs = "1234567890abcdefghijklmnopqrstuvwxyz�?二三四五六七八九十壹贰叁肆伍陆柒捌玖�?"; - - protected void GetCodeServlet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - BufferedImage bi = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, BufferedImage.TYPE_INT_RGB); - Graphics2D g2d = bi.createGraphics(); - Random random = new Random(); - //设置字体 - g2d.setFont(new Font("宋体", Font.BOLD, 14)); - //填充白色矩形 - g2d.setColor(Color.WHITE); - g2d.fillRect(0, 0, IMG_WIDTH, IMG_HEIGHT); - - int x1, y1, x2, y2; - for(int i = 0; i < 50; i++){ - //随机�? - g2d.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256))); - x1 = random.nextInt(IMG_WIDTH); - y1 = random.nextInt(IMG_HEIGHT); - x2 = random.nextInt(3) + x1; - y2 = random.nextInt(3) + y1; - g2d.drawLine(x1, y1, x2, y2); - } - - //4字符验证�? - char[] charArray = strs.toCharArray(); - String code = ""; - for(int i = 0; i < 4; i++){ - g2d.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256))); - String s = String.valueOf(charArray[random.nextInt(charArray.length)]); - code += s; - g2d.drawString(s, 15 * (i + 1), 15); - } - - //将验证码值放入session中,以待验证。此Demo没有使用�? - HttpSession session = req.getSession(); - session.setAttribute("code", code); - // 禁止缓存 - resp.setHeader("Prama", "no-cache"); - resp.setHeader("Coche-Control", "no-cache"); - resp.setDateHeader("Expires", 0); - resp.setContentType("image/jpeg"); - // 将图像输出到 - ServletOutputStream sos = resp.getOutputStream(); - ImageIO.write(bi, "jpeg", sos); - sos.close(); - } - @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - doGet(req, resp); - } - - - - public static final int width = 120; - public static final int heigth = 30; - - public void RandomImage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - response.setContentType("test/html;charset=UTF-8"); - // image���ʾͼ��ͼ��?,BufferedImage��image�����ࣻImageͨ��������ȡͼƬ�� - // BufferedImage���пɷ���ͼ����ݻ�����?; BufferedImageͨ�������޸�ͼƬ��С������ͼƬ�����ȣ� - BufferedImage image = new BufferedImage(width, heigth, BufferedImage.TYPE_INT_RGB);// 8 λ RGB��ɫ������ͼ�� - // Graphics��ʾ�ɻ��Ƶ�ͼ�� Graphics2D�� Graphics�����࣬�ṩ������״�����ת������ɫ������ı����ֵȸ�Ϊ���ӵĿ��ơ� - Graphics g = image.getGraphics(); - - setBackGround(g);// ���ñ���ɫ - setBorder(g);// ���ñ߿� - drawRandomLine(g);// �������� - - // д�����? - String randomImage = drawRandomNumber((Graphics2D) g);// ���������? - request.getSession().setAttribute("randomImage", randomImage); - - response.setContentType("image/jpeg");// ����������򿪷��? - - // ������������ܻ����ͼƬ - response.setHeader("expires", "-1"); - response.setHeader("Cache-Control", "no-cache"); - response.setHeader("Pragma", "no-cache"); - - ImageIO.write(image, "jpg", response.getOutputStream());// ��ָ����ʽ��ͼƬд��ָ���������? - } - - private String drawRandomNumber(Graphics2D g) { - g.setColor(Color.RED);// ����ͼ�������ĵĵ�ǰ��ɫ����Ϊָ����ɫ�� - g.setFont(new Font("����", Font.BOLD, 20)); - String base = "\u8981\u8fc7\u53bb\uff0c\u4f46\u90a3\u771f\u6b63\u6e29\u6696\u7684\u6625\u5929\u8fd8\u8fdc\u8fdc\u5730\u6ca1\u6709\u5230\u6765\u3002\u5728\u8fd9\u6837\u96e8\u96ea\u4ea4\u52a0\u7684\u65e5\u5b50\u91cc\uff0c\u5982\u679c\u6ca1\u6709\u4ec0\u4e48\u7d27\u8981\u4e8b\uff0c\u4eba\u4eec\u5b81\u613f\u4e00\u6574\u5929\u8db3\u4e0d\u51fa\u6237\u3002\u56e0\u6b64\uff0c\u53bf\u57ce\u7684\u5927\u8857\u5c0f\u5df7\u5012\u4e5f\u6bd4\u5e73\u65f6\u5c11\u4e86\u8bb8\u591a\u5608\u6742\u3002\u8857\u5df7\u80cc\u9634\u7684\u5730\u65b9\u3002\u51ac\u5929\u6b8b\u7559\u7684\u79ef\u96ea\u548c\u51b0\u6e9c\u5b50\u6b63\u5728\u96e8\u70b9\u7684\u6572\u51fb\u4e0b\u8680\u5316\uff0c\u77f3\u677f\u8857\u4e0a\u5230\u5904\u90fd\u6f2b\u6d41\u7740\u80ae\u810f\u7684\u6c61\u6c34\u3002\u98ce\u4f9d\u7136\u662f\u5bd2\u51b7\u7684\u3002\u7a7a\u8361\u8361\u7684\u8857\u9053\u4e0a\uff0c\u6709\u65f6\u4f1a\u5076\u5c14\u8d70\u8fc7\u6765\u4e00\u4e2a\u4e61\u4e0b\u4eba\uff0c\u7834\u6be1\u5e3d\u62a4\u7740\u8111\u95e8\uff0c\u80f3\u818a\u4e0a\u633d\u4e00\u7b50\u5b50\u571f\u8c46\u6216\u841d\u535c\uff0c\u6709\u6c14\u65e0\u529b\u5730\u547c\u5524\u7740\u4e70\u4e3b\u3002\u5509\uff0c\u57ce\u5e02\u5728\u8fd9\u6837\u7684\u65e5\u5b50\u91cc\u5b8c\u5168\u4e27\u5931\u4e86\u751f\u6c14\uff0c\u53d8\u5f97\u6ca1\u6709\u4e00\u70b9\u53ef\u7231\u4e4b\u5904\u4e86\u3002\u53ea\u6709\u5728\u534a\u5c71\u8170\u53bf\u7acb\u9ad8\u4e2d\u7684\u5927\u9662\u575d\u91cc\uff0c\u6b64\u523b\u5374\u81ea\u6709\u4e00\u756a\u70ed\u95f9\u666f\u8c61\u3002\u5348\u996d\u94c3\u58f0\u521a\u521a\u54cd\u8fc7\uff0c\u4ece\u4e00\u6392\u6392\u9ad8\u4f4e\u9519\u843d\u7684\u77f3\u7a91\u6d1e\u91cc\uff0c\u5c31\u8dd1\u51fa\u6765\u4e86\u4e00\u7fa4\u4e00\u4f19\u7684\u7537\u7537\u5973\u5973\u3002\u4ed6\u4eec\u628a\u7897\u7b77\u6572\u5f97\u9707\u5929\u4ef7\u54cd\uff0c\u8e0f\u6ce5\u5e26\u6c34\u3001\u53eb\u53eb\u56b7\u56b7\u5730\u8dd1\u8fc7\u9662\u575d\uff0c\u5411\u5357\u9762\u603b\u52a1\u5904\u90a3\u4e00\u6392\u7a91\u6d1e\u7684\u5899\u6839\u4e0b\u8702\u6d8c\u800c\u53bb\u3002\u504c\u5927\u4e00\u4e2a\u9662\u5b50\uff0c\u970e\u65f6\u5c31\u88ab\u8fd9\u7eb7\u4e71\u7684\u4eba\u7fa4\u8e29\u8e0f\u6210\u4e86\u4e00\u7247\u70c2\u6ce5\u6ee9\u3002\u4e0e\u6b64\u540c\u65f6\uff0c\u90a3\u4e9b\u5bb6\u5728\u672c\u57ce\u7684\u8d70\u8bfb\u751f\u4eec\uff0c\u4e5f\u6b63\u4e09\u4e09\u4e24\u4e24\u6d8c\u51fa\u4e1c\u9762\u5b66\u6821\u7684\u5927\u95e8\u3002\u4ed6\u4eec\u6491\u7740\u96e8\u4f1e\uff0c\u4e00\u8def\u8bf4\u8bf4\u7b11\u7b11\uff0c\u901a\u8fc7\u4e00\u6bb5\u65e9\u5e74\u95f4\u7528\u6a2a\u77f3\u7247\u63d2\u8d77\u7684\u957f\u957f\u7684\u4e0b\u5761\u8def\uff0c\u4e0d\u591a\u65f6\u4fbf\u7eb7\u7eb7\u6d88\u5931\u5728\u57ce\u5e02\u7684\u5927\u8857\u5c0f\u5df7\u4e2d\u3002\u5728\u6821\u56ed\u5185\u7684\u5357\u5899\u6839\u4e0b\uff0c\u73b0\u5728\u5df2\u7ecf\u6309\u73ed\u7ea7\u6392\u8d77\u4e86\u5341\u51e0\u8def\u7eb5\u961f\u3002\u5404\u73ed\u7684\u503c\u65e5\u751f\u6b63\u5728\u5fd9\u788c\u5730\u7ed9\u4f17\u4eba\u5206\u996d\u83dc\u3002\u6bcf\u4e2a\u4eba\u7684\u996d\u83dc\u90fd\u662f\u6628\u5929\u767b\u8bb0\u597d\u5e76\u4ed8\u4e86\u996d\u7968\u7684\uff0c\u56e0\u6b64\u7a0b\u5e8f\u5e76\u4e0d\u590d\u6742\uff0c\u73b0\u5728\u503c\u65e5\u751f\u53ea\u662f\u6309\u996d\u8868\u4ed8\u7ed9\u6bcf\u4eba\u9884\u8ba2\u7684\u4e00\u4efd\u3002\u83dc\u5206\u7532\u3001\u4e59\u3001\u4e19\u4e09\u7b49\u3002\u7532\u83dc\u4ee5\u571f\u8c46\u3001\u767d\u83dc\u3001\u7c89\u6761\u4e3a\u4e3b\uff0c\u91cc\u9762\u6709\u4e9b\u53eb\u4eba\u5634\u998b\u7684\u5927\u8089\u7247\uff0c\u6bcf\u4efd\u4e09\u6bdb\u94b1\uff1b\u4e59\u83dc\u5176\u5b83\u5185\u5bb9\u548c\u7532\u83dc\u4e00\u6837\uff0c\u53ea\u662f\u6ca1\u6709\u8089\uff0c\u6bcf\u4efd\u4e00\u6bdb\u4e94\u5206\u94b1\u3002\u4e19\u83dc\u53ef\u5c31\u5dee\u8fdc\u4e86\uff0c\u6e05\u6c34\u716e\u767d\u841d\u535c\u2014\u2014\u4f3c\u4e4e\u53ea\u662f\u4e3a\u4e86\u63a9\u9970\u8fd9\u8fc7\u5206\u7684\u6e05\u6de1\uff0c\u624d\u5728\u91cc\u9762\u8c61\u5f81\u6027\u5730\u6f02\u4e86\u51e0\u70b9\u8fa3\u5b50\u6cb9\u82b1\u3002\u4e0d\u8fc7\uff0c\u8fd9\u83dc\u4ef7\u94b1\u5012\u4e5f\u4fbf\u5b9c\uff0c\u6bcf\u4efd\u4e94\u5206\u94b1\u3002\u5404\u73ed\u7684\u7532\u83dc\u53ea\u662f\u5728\u5c0f\u8138\u76c6\u91cc\u76db\u4e00\u70b9\uff0c\u770b\u6765\u5403\u5f97\u8d77\u8089\u83dc\u7684\u5b66\u751f\u6ca1\u6709\u51e0\u4e2a\u3002\u4e19\u83dc\u4e5f\u7528\u5c0f\u8138\u76c6\u76db\u4e00\u70b9\uff0c\u8bf4\u660e\u5403\u8fd9\u79cd\u4e0b\u7b49\u4f19\u98df\u7684\u4eba\u4e5f\u6ca1\u6709\u591a\u5c11\u3002\u53ea\u6709\u4e59\u83dc\u5404\u73ed\u90fd\u7528\u70e7\u74f7\u5927\u811a\u76c6\u76db\u7740\uff0c\u6d77\u6d77\u6f2b\u6f2b\u7684\uff0c\u663e\u7136\u5927\u90e8\u5206\u4eba\u90fd\u5403\u8fd9\u79cd\u65e2\u4e0d\u5962\u4f88\u4e5f\u4e0d\u5bd2\u9178\u7684\u83dc\u3002"; - int x = 5; - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < 4; i++) { - // n����=n*180/��(��) - int degree = new Random().nextInt() % 30; // �����?30����30�������? - // ��ȡָ�����λ�õ��ַ�? - String ch = base.charAt(new Random().nextInt(base.length())) + ""; - sb.append(ch); - g.rotate(degree * Math.PI / 180, x, 25); - g.drawString(ch, x, 25);// ���ַ�д��ָ��λ�ã� ������������½�Ϊ׼��? - g.rotate(-degree * Math.PI / 180, x, 25);// д��֮��ԭ��ת�Ƕȣ� - x += 30; - } - return sb.toString(); - } - - private void drawRandomLine(Graphics g) { - g.setColor(Color.GREEN); - for (int i = 0; i < 5; i++) { - int x = new Random().nextInt(width); - int y = new Random().nextInt(heigth); - int x1 = new Random().nextInt(width); - int y1 = new Random().nextInt(heigth); - g.drawLine(x, y, x1, y1); - } - } - - private void setBorder(Graphics g) { - g.setColor(Color.BLUE); - g.drawRect(1, 1, width - 2, heigth - 2); - } - - private void setBackGround(Graphics g) { - g.setColor(Color.WHITE); - g.fillRect(0, 0, width, heigth); - } - - - - public void ImageServlet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - // 设置响应类型 - resp.setContentType("image/jpeg"); - int width = 60; - int height = 30; - BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); - Graphics g = img.getGraphics(); - g.setColor(Color.WHITE); - g.fillRect(0, 0, width, height); - g.setFont(new Font("宋体", Font.BOLD, 18)); - Random r = new Random(); - for (int i = 0; i < 4; i++) { - Color c = new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256)); - int code = r.nextInt(10); - g.setColor(c); - g.drawString("" + code, i * 15, 10 + r.nextInt(20)); - } - for (int i = 0; i < 10; i++) { - Color c = new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256)); - g.setColor(c); - g.drawLine(r.nextInt(60), r.nextInt(30), r.nextInt(60), r.nextInt(30)); - } - // 图片生效 - g.dispose(); - // 写到 - ImageIO.write(img, "JPEG", resp.getOutputStream()); - } -} diff --git a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/fileupload/UploadHelper.java b/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/fileupload/UploadHelper.java deleted file mode 100644 index cac30b7c70..0000000000 --- a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/fileupload/UploadHelper.java +++ /dev/null @@ -1,212 +0,0 @@ -package com.jun.plugin.file.fileupload; -/** - * ???????? - */ - -/** - * @author advance - * - */ -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.RenderingHints; -import java.awt.image.BufferedImage; -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FileWriter; -import java.io.FilenameFilter; -import java.io.PrintWriter; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; - - - -public class UploadHelper { - - public final static String separator = "/"; - public final static String split = "_"; - - - class FilenameFilterImpl implements FilenameFilter - { - private String filter = "."; - - public FilenameFilterImpl(String aFilter) - { - filter = aFilter; - } - - public boolean accept(File dir, String name) - { - return name.startsWith(filter); - } - }; - /** - * ��õ�ǰ���ļ�·����ͨ����ǰ�������ɣ�? - * @param basePath - * @return - */ - public static String getNowFilePath(String basePath){ - SimpleDateFormat formater =new SimpleDateFormat("yyyy-MM-dd"); - String pathName = formater.format(new Date()); - File dir = new File(basePath + separator + pathName); - if(!dir.exists()) - dir.mkdir(); - return pathName; - } - - public static String getNewFileName(String oldFileName){ - oldFileName = oldFileName.replaceAll("'", "").replaceAll("\"", ""); - Calendar date = Calendar.getInstance(); - int hour = date.get(Calendar.HOUR_OF_DAY); - int minute = date.get(Calendar.MINUTE); - int second = date.get(Calendar.SECOND); - if(oldFileName.length()>30) - oldFileName = oldFileName.substring(oldFileName.length()-30); - return (new Integer(hour*3600 + minute*60 + second).toString()) - + split + oldFileName; - } - - public static String getThumbFileName(String fileName){ - int pos = fileName.lastIndexOf("."); - if(pos>=0) - return fileName.substring(0, pos) + "s" + fileName.substring(pos); - else - return fileName + "s"; - } - - /** - * This method checks if the given file exists on disk. If it does it's ignored because - * that means that the file is allready cached on the server. If not we dump - * the text on it. - */ - public void dumpAttributeToFile(String attributeValue, String fileName, String filePath) throws Exception - { - File outputFile = new File(filePath + separator + fileName); - PrintWriter pw = new PrintWriter(new FileWriter(outputFile)); - pw.println(attributeValue); - pw.close(); - } - - /** - * �����ļ� - * This method checks if the given file exists on disk. If it does it's ignored because - * that means that the file is allready cached on the server. If not we take out the stream from the - * digitalAsset-object and dumps it. - */ - public void dumpAsset(File file, String fileName, String filePath) throws Exception - { - long timer = System.currentTimeMillis(); - - File outputFile = new File(filePath + separator + fileName); - if(outputFile.exists()) - { - return; - } - - FileOutputStream fis = new FileOutputStream(outputFile); - BufferedOutputStream bos = new BufferedOutputStream(fis); - - BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); - - int character; - while ((character = bis.read()) != -1) - { - bos.write(character); - } - bos.flush(); - - bis.close(); - fis.close(); - bos.close(); - } - - /** - * ��������ͼ - * This method checks if the given file exists on disk. If it does it's ignored because - * that means that the file is allready cached on the server. If not we take out the stream from the - * digitalAsset-object and dumps a thumbnail to it. - */ - - public void dumpAssetThumbnail(File file, String fileName, String thumbnailFile, String filePath, int width, int height, int quality) throws Exception - { - long timer = System.currentTimeMillis(); - - File outputFile = new File(filePath + separator + thumbnailFile); - if(outputFile.exists()) - { - return; - } - -// ThumbnailGenerator tg = new ThumbnailGenerator(); - this.transform(filePath + separator + fileName, filePath + separator + thumbnailFile, width, height, quality); - -// log.info("Time for dumping file " + fileName + ":" + (System.currentTimeMillis() - timer)); - } - - /** - * This method removes all images in the digitalAsset directory which belongs to a certain digital asset. - */ - public void deleteDigitalAssets(String filePath, String filePrefix) throws Exception - { - try - { - File assetDirectory = new File(filePath); - File[] files = assetDirectory.listFiles(new FilenameFilterImpl(filePrefix)); - for(int i=0; i lstForms=upload.parseRequest(request); - //遍历�?有表单元�? - for (FileItem fileItem : lstForms) { - //判断每一个表单元素是否是普�?�表�? - if(fileItem.isFormField()){ - System.out.println(fileItem.getString("UTF-8")); - }else{ - //上传前准备工�? - //a、上传后的路径this.getServletContext().getRealPath("/")会出去当前项目在 部署的服务器上的绝对路径 - - String path=this.getServletContext().getRealPath("/")+"files/"; - //b、找出要上传的文件的名字 - String fileName=fileItem.getName(); - fileName=fileName.substring(fileName.lastIndexOf("\\")+1); - //c、上�? - fileItem.write(new File(path+fileName)); - out.println("

"+fileName+"上传成功�?

"); - } - } - } catch (Exception e) { - System.out.println("错误�?"+e.getMessage()); - } - }else{ - System.out.println("没有上传"); - } - - - out.flush(); - out.close(); - } - -} diff --git a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/fileupload/UploadUtil.java b/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/fileupload/UploadUtil.java deleted file mode 100644 index 3bb1560a8a..0000000000 --- a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/fileupload/UploadUtil.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.jun.plugin.file.fileupload; - - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.UUID; - -public final class UploadUtil { - // ȡ���ϴ�ʹ�õ���ʱ����ʵĿ¼ - public static final String tempPath = "/WEB-INF/temp"; - public static final String uploadPath = "/WEB-INF/upload"; - - // ȡ����ʵ�ļ��� - public static String getRealFileName(String realFileName) { - int index = realFileName.lastIndexOf("\\"); - if (index >= 0) { - // IE6�����? - realFileName = realFileName.substring(index + 1); - } - return realFileName; - } - - // ȡ��uuid�ļ��� - public static String makeUuidFilePath(String uploadPath, String uuidFileName) { - String uuidFilePath = null; - int code = uuidFileName.hashCode();// 8 - int dir1 = code & 0xF;// 3 - int dir2 = code >> 4 & 0xF;// A - File file = new File(uploadPath + "/" + dir1 + "/" + dir2); - // ����Ŀ¼δ���� - if (!file.exists()) { - // һ���Դ���N��Ŀ¼ - file.mkdirs(); - } - uuidFilePath = file.getPath(); - return uuidFilePath; - } - - // ȡ��upload/Ŀ¼�µķ�ɢĿ¼ - public static String makeUuidFileName(String realFileName) { - return UUID.randomUUID().toString() + "_" + realFileName; - } - - // �ļ����� - public static void doSave(InputStream is, String uuidFileName, - String uuidFilePath) { - OutputStream os = null; - try { - os = new FileOutputStream(uuidFilePath + "/" + uuidFileName); - byte[] buf = new byte[1024]; - int len = 0; - while ((len = is.read(buf)) > 0) { - os.write(buf, 0, len); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (is != null) { - try { - is.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - if (os != null) { - try { - os.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - } - - // public static void doSave(User user, String uploadPath,List upList) - // throws Exception { - // for(FileItem fileItem : fileItemList){ - // //����Up���� - // Up up = new Up(); - // up.setUsername(user.getUsername()); - // //ȡ�������� - // InputStream is = fileItem.getInputStream(); - // //ȡ����ʵ�ļ��� - // String realFileName = fileItem.getName(); - // realFileName = UploadUtil.getRealFileName(realFileName); - // //ȡ��UUID�ļ��� - // String uuidFileName = UploadUtil.makeUuidFileName(realFileName); - // //ȡ��UUID�ļ�·�� - // String uuidFilePath = - // UploadUtil.makeUuidFilePath(uploadPath,uuidFileName); - // //���� - // UploadUtil.doSave(is,uuidFileName,uuidFilePath); - // //�ռ�Up��Ϣ - // up.setUuidFileName(uuidFileName); - // up.setRealFileName(realFileName); - // upList.add(up); - // //ɾ����ʱ�ļ� - // fileItem.delete(); - // } - // } -} diff --git a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/fileupload/UploadUtils.java b/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/fileupload/UploadUtils.java deleted file mode 100644 index 924baee788..0000000000 --- a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/fileupload/UploadUtils.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.jun.plugin.file.fileupload; - - - -import java.util.UUID; - -public class UploadUtils { - /** - * ��ȡ��ʵ�ļ��� - * - * @param fileName - * @return - */ - public static String subFileName(String fileName) { - // �������һ��? \����λ�� - int index = fileName.lastIndexOf("\\"); // \ / - if (index == -1) { - return fileName; - } - return fileName.substring(index + 1); - } - - // ������UUID�ļ��� - public static String generateRandonFileName(String fileName) { - // �����չ��? - String ext = fileName.substring(fileName.lastIndexOf(".")); - return UUID.randomUUID().toString() + ext; // jlksjflkdsjaf.png - } - - // ���hashcode���ɶ���Ŀ¼ - public static String generateRandomDir(String uuidFileName) { - int hashCode = uuidFileName.hashCode(); - // һ��Ŀ¼ - int d1 = hashCode & 0xf; - // ����Ŀ¼ - int d2 = (hashCode >> 4) & 0xf; - return "/" + d1 + "/" + d2; // /1/5 - } -} diff --git a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/fileupload/Uploadify.java b/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/fileupload/Uploadify.java deleted file mode 100644 index e11807a10e..0000000000 --- a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/fileupload/Uploadify.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.jun.plugin.file.fileupload; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Iterator; -import java.util.List; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.fileupload.disk.DiskFileItem; -import org.apache.commons.fileupload.disk.DiskFileItemFactory; -import org.apache.commons.fileupload.servlet.ServletFileUpload; -import org.apache.commons.fileupload.util.Streams; - -public class Uploadify extends HttpServlet{ - private static final long serialVersionUID = 1L; - - /** - * 实现多文件的同时上传 - */ - public void doGet(HttpServletRequest request, - HttpServletResponse response) throws ServletException, IOException { - - //设置接收的编码格�? - request.setCharacterEncoding("UTF-8"); - Date date = new Date();//获取当前时间 - SimpleDateFormat sdfFileName = new SimpleDateFormat("yyyyMMddHHmmss"); - SimpleDateFormat sdfFolder = new SimpleDateFormat("yyMM"); - String newfileName = sdfFileName.format(date);//文件名称 - String fileRealPath = "";//文件存放真实地址 - - String fileRealResistPath = "";//文件存放真实相对路径 - - //名称 界面编码 必须 和request 保存�?�?..否则乱码 - String name = request.getParameter("name"); - - - String firstFileName=""; - // 获得容器中上传文件夹�?在的物理路径 - String savePath = this.getServletConfig().getServletContext().getRealPath("/") + "uploads\\" + newfileName +"\\"; - System.out.println("路径" + savePath+"; name:"+name); - File file = new File(savePath); - if (!file.isDirectory()) { - file.mkdirs(); - } - - try { - DiskFileItemFactory fac = new DiskFileItemFactory(); - ServletFileUpload upload = new ServletFileUpload(fac); - upload.setHeaderEncoding("UTF-8"); - // 获取多个上传文件 - List fileList = fileList = upload.parseRequest(request); - // 遍历上传文件写入磁盘 - Iterator it = fileList.iterator(); - while (it.hasNext()) { - Object obit = it.next(); - if(obit instanceof DiskFileItem){ - System.out.println("xxxxxxxxxxxxx"); - DiskFileItem item = (DiskFileItem) obit; - - // 如果item是文件上传表单域 - // 获得文件名及路径 - String fileName = item.getName(); - if (fileName != null) { - firstFileName=item.getName().substring(item.getName().lastIndexOf("\\")+1); - String formatName = firstFileName.substring(firstFileName.lastIndexOf("."));//获取文件后缀�? - fileRealPath = savePath + newfileName+ formatName;//文件存放真实地址 - - BufferedInputStream in = new BufferedInputStream(item.getInputStream());// 获得文件输入�? - BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(new File(fileRealPath)));// 获得文件输出�? - Streams.copy(in, outStream, true);// �?始把文件写到你指定的上传文件�? - //上传成功,则插入数据�? - if (new File(fileRealPath).exists()) { - //虚拟路径赋�?? - fileRealResistPath=sdfFolder.format(date)+"/"+fileRealPath.substring(fileRealPath.lastIndexOf("\\")+1); - //保存到数据库 - System.out.println("保存到数据库:"); - System.out.println("name:"+name); - System.out.println("虚拟路径:"+fileRealResistPath); - } - - } - } - } - } catch (org.apache.commons.fileupload.FileUploadException ex) { - ex.printStackTrace(); - System.out.println("没有上传文件"); - return; - } - response.getWriter().write("1"); - - } - - public void doPost(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - doGet(req, resp); - } -} \ No newline at end of file diff --git "a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/\345\244\232\347\272\277\347\250\213\344\270\213\350\275\275Demo.java" "b/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/\345\244\232\347\272\277\347\250\213\344\270\213\350\275\275Demo.java" deleted file mode 100644 index 1325989878..0000000000 --- "a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/\345\244\232\347\272\277\347\250\213\344\270\213\350\275\275Demo.java" +++ /dev/null @@ -1,116 +0,0 @@ -package com.jun.plugin.file; - -/** - * 说明: - * 每一个线程下载的位置计算方式: - * 开始位置: - * (线程id - 1)*每一块大小 - * 结束位置: - * (线程id*每一块大小) - 1 - * ---注意有时候不一定能够整除,所以最后一个线程的结束位置应该是文件的末尾 - * - * 步骤: - * 1.本地创建一个大小跟服务器文件相同的临时文件 - * 2.计算分配几个线程去下载服务器上的资源,知道每个线程下载文件的位置 - * 3.开启三个线程,每一个线程下载对应位置的文件 - * 4.如果所有的线程,都把自己的数据下载完毕后,服务器上的资源都被下载到本地了 - */ -import java.io.InputStream; -import java.io.RandomAccessFile; -import java.net.HttpURLConnection; -import java.net.URL; - -public class 多线程下载Demo { - public static String path = "http://static.csdn.net/public/common/toolbar/css/index.css"; - public static int threadCount = 10; - public static long startTime; - public static void main(String[] args) throws Exception{ - startTime = System.currentTimeMillis(); - //1.连接服务器,获取一个文件,获取文件的长度,在本地创建一个跟服务器一样大小的临时文件 - URL url = new URL(path); - HttpURLConnection conn = (HttpURLConnection)url.openConnection(); - conn.setConnectTimeout(5000); - conn.setRequestMethod("GET"); - int code = conn.getResponseCode(); - if (code == 200) { - //服务器端返回的数据的长度,实际上就是文件的长度 - int length = conn.getContentLength(); - System.out.println("文件总长度:"+length); - //在客户端本地创建出来一个大小跟服务器端一样大小的临时文件 - RandomAccessFile raf = new RandomAccessFile("index.css", "rwd"); - //指定创建的这个文件的长度 - raf.setLength(length); - raf.close(); - //假设是3个线程去下载资源。 - //平均每一个线程下载的文件大小. - int blockSize = length / threadCount; - for (int threadId = 1; threadId <= threadCount; threadId++) { - //第一个线程下载的开始位置 - int startIndex = (threadId - 1) * blockSize; - int endIndex = threadId * blockSize - 1; - if (threadId == threadCount) {//最后一个线程下载的长度要稍微长一点 - endIndex = length; - } - System.out.println("线程:"+threadId+"下载:---"+startIndex+"--->"+endIndex); - new DownLoadThread(path, threadId, startIndex, endIndex).start(); - } - }else { - System.out.printf("服务器错误!"); - } - } - - /** - * 下载文件的子线程 每一个线程下载对应位置的文件 - * @author jie - * - */ - public static class DownLoadThread extends Thread{ - private int threadId; - private int startIndex; - private int endIndex; - /** - * @param path 下载文件在服务器上的路径 - * @param threadId 线程Id - * @param startIndex 线程下载的开始位置 - * @param endIndex 线程下载的结束位置 - */ - public DownLoadThread(String path, int threadId, int startIndex, int endIndex) { - super(); - this.threadId = threadId; - this.startIndex = startIndex; - this.endIndex = endIndex; - } - - @Override - public void run() { - try { - URL url = new URL(path); - HttpURLConnection conn = (HttpURLConnection)url.openConnection(); - conn.setConnectTimeout(5000); - conn.setRequestMethod("GET"); - //重要:请求服务器下载部分文件 指定文件的位置 - conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex); - //从服务器请求全部资源返回200 ok如果从服务器请求部分资源 返回 206 ok - int code = conn.getResponseCode(); - System.out.println("code:"+code); - InputStream is = conn.getInputStream();//已经设置了请求的位置,返回的是当前位置对应的文件的输入流 - RandomAccessFile raf = new RandomAccessFile("index.css", "rwd"); - //随机写文件的时候从哪个位置开始写 - raf.seek(startIndex);//定位文件 - - int len = 0; - byte[] buffer = new byte[1024]; - while ((len = is.read(buffer)) != -1) { - raf.write(buffer, 0, len); - } - is.close(); - raf.close(); - System.out.println("线程:"+threadId+"下载完毕"); - System.out.println((System.currentTimeMillis()-startTime)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - } -} \ No newline at end of file diff --git "a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/\346\226\255\347\202\271\344\270\213\350\275\275Demo.java" "b/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/\346\226\255\347\202\271\344\270\213\350\275\275Demo.java" deleted file mode 100644 index ea1367f2b3..0000000000 --- "a/jun_java_plugins/jun_fileupload/src/main/java/com/jun/plugin/file/\346\226\255\347\202\271\344\270\213\350\275\275Demo.java" +++ /dev/null @@ -1,151 +0,0 @@ -package com.jun.plugin.file; - -/** - * 说明: - * 每一个线程下载的位置计算方式: - * 开始位置: - * (线程id - 1)*每一块大小 - * 结束位置: - * (线程id*每一块大小) - 1 - * ---注意有时候不一定能够整除,所以最后一个线程的结束位置应该是文件的末尾 - * - * 步骤: - * 1.本地创建一个大小跟服务器文件相同的临时文件 - * 2.计算分配几个线程去下载服务器上的资源,知道每个线程下载文件的位置 - * 3.开启三个线程,每一个线程下载对应位置的文件 - * 4.如果所有的线程,都把自己的数据下载完毕后,服务器上的资源都被下载到本地了 - * - * 断点下载: - * 1.使用文件记录每一个线程的下载长度 - * 2.每一个下载开始之前,读取文件,如果文件存在并且长度大于0,则取出长度 - * 3.将每一个线程的起始位置+已经下载的长度 - * 4.所有的线程下载完毕后,删除保存下载长度的文件 - */ -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.io.RandomAccessFile; -import java.net.HttpURLConnection; -import java.net.URL; - -public class 断点下载Demo { - public static String path = "http://softdownload.hao123.com/hao123-soft-online-bcs/soft/Y/2013-07-18_YoudaoDict_baidu.alading.exe";//"http://softdownload.hao123.com/hao123-soft-online-bcs/soft/Y/2013-07-18_YoudaoDict_baidu.alading.exe"; - public static int threadCount = 10; - public static int runningThread = 10; - public static void main(String[] args) throws Exception{ - //1.连接服务器,获取一个文件,获取文件的长度,在本地创建一个跟服务器一样大小的临时文件 - URL url = new URL(path); - HttpURLConnection conn = (HttpURLConnection)url.openConnection(); - conn.setConnectTimeout(5000); - conn.setRequestMethod("GET"); - int code = conn.getResponseCode(); - if (code == 200) { - //服务器端返回的数据的长度,实际上就是文件的长度 - int length = conn.getContentLength(); - System.out.println("文件总长度:"+length); - //在客户端本地创建出来一个大小跟服务器端一样大小的临时文件 - RandomAccessFile raf = new RandomAccessFile("setup.exe", "rwd"); - //指定创建的这个文件的长度 - raf.setLength(length); - raf.close(); - //假设是3个线程去下载资源。 - //平均每一个线程下载的文件大小. - int blockSize = length / threadCount; - for (int threadId = 1; threadId <= threadCount; threadId++) { - //第一个线程下载的开始位置 - int startIndex = (threadId - 1) * blockSize; - int endIndex = threadId * blockSize - 1; - if (threadId == threadCount) {//最后一个线程下载的长度要稍微长一点 - endIndex = length; - } - System.out.println("线程:"+threadId+"下载:---"+startIndex+"--->"+endIndex); - new DownLoadThread(path, threadId, startIndex, endIndex).start(); - } - - }else { - System.out.printf("服务器错误!"); - } - } - - /** - * 下载文件的子线程 每一个线程下载对应位置的文件 - * @author jie - * - */ - public static class DownLoadThread extends Thread{ - private int threadId; - private int startIndex; - private int endIndex; - /** - * @param path 下载文件在服务器上的路径 - * @param threadId 线程Id - * @param startIndex 线程下载的开始位置 - * @param endIndex 线程下载的结束位置 - */ - public DownLoadThread(String path, int threadId, int startIndex, int endIndex) { - super(); - this.threadId = threadId; - this.startIndex = startIndex; - this.endIndex = endIndex; - } - - @Override - public void run() { - try { - //检查是否存在记录下载长度的文件,如果存在读取这个文件 - File tmp_file = new File(threadId+".txt"); - if (tmp_file.exists() && tmp_file.length() > 0) { - FileInputStream fio = new FileInputStream(tmp_file); - byte[] temp = new byte[1024]; - int len = fio.read(temp); - String downloadlen = new String(temp, 0, len); - int downloadInt = Integer.parseInt(downloadlen); - startIndex = downloadInt;//修改下载的真实的开始位置 - System.out.println("线程:"+threadId+"真实的下载位置:"+startIndex+"--->"+endIndex); - fio.close(); - } - - - URL url = new URL(path); - HttpURLConnection conn = (HttpURLConnection)url.openConnection(); - conn.setConnectTimeout(5000); - conn.setRequestMethod("GET"); - //重要:请求服务器下载部分文件 指定文件的位置 - conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex); - //从服务器请求全部资源返回200 ok如果从服务器请求部分资源 返回 206 ok - int code = conn.getResponseCode(); - System.out.println("code:"+code); - InputStream is = conn.getInputStream();//已经设置了请求的位置,返回的是当前位置对应的文件的输入流 - RandomAccessFile raf = new RandomAccessFile("setup.exe", "rwd"); - //随机写文件的时候从哪个位置开始写 - raf.seek(startIndex);//定位文件 - - int len = 0; - byte[] buffer = new byte[1024]; - int total = 0;//已经下载的数据长度 - while ((len = is.read(buffer)) != -1) { - RandomAccessFile file = new RandomAccessFile(threadId+".txt", "rwd"); - raf.write(buffer, 0, len); - total += len; - file.write((""+(total+startIndex)).getBytes()); - file.close(); - } - is.close(); - raf.close(); - System.out.println("线程:"+threadId+"下载完毕"); - } catch (Exception e) { - e.printStackTrace(); - }finally{ - runningThread--; - if (runningThread == 0) {//所有的线程执行完毕 - for (int i = 1; i <= threadCount; i++) { - File file = new File(i+".txt"); - file.delete(); - } - System.out.println("文件全部下载完毕!"); - } - } - } - - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_freemarker/pom.xml b/jun_java_plugins/jun_freemarker/pom.xml deleted file mode 100644 index 58bbad921c..0000000000 --- a/jun_java_plugins/jun_freemarker/pom.xml +++ /dev/null @@ -1,65 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_freemarker - 1.0 - war - - - - UTF-8 - - - - - - - org.freemarker - freemarker - 2.3.30 - - - org.springframework - spring-context-support - 4.1.4.RELEASE - - - - - - - mysql - mysql-connector-java - 5.1.40 - - - junit - junit - 4.13 - - - org.slf4j - slf4j-api - 1.7.30 - - - org.slf4j - slf4j-log4j12 - 1.7.30 - - - - javax.servlet - javax.servlet-api - 3.1.0 - provided - - - - jun_freemarker - - diff --git a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemark/code/conf/PropertiesConfig.java b/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemark/code/conf/PropertiesConfig.java deleted file mode 100644 index 941a4c24de..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemark/code/conf/PropertiesConfig.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.jun.plugin.freemark.code.conf; - -import java.io.InputStream; -import java.util.HashMap; -import java.util.Properties; - -/** - * 读取*.properties配置文件 - */ -public class PropertiesConfig { - - // 配置文件的map key:propertiesName value:PropertiesUtil对象 - private static HashMap propertiesMap = new HashMap(); - - // 属性文件 - private Properties properties; - - private PropertiesConfig() { - - } - - public synchronized static PropertiesConfig getInstance(String propertiesName) { - - PropertiesConfig configUtil = propertiesMap.get(propertiesName); - - if (configUtil == null) { - configUtil = new PropertiesConfig(); - configUtil.analysisXml(propertiesName); - propertiesMap.put(propertiesName, configUtil); - } - - return configUtil; - } - - private void analysisXml(String propertiesName) { - InputStream ins = getClass().getResourceAsStream(propertiesName); - properties = new Properties(); - try { - properties.load(ins); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public String getProperty(String key) { - return properties.getProperty(key); - } - -} diff --git a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemark/code/conf/PropertiesService.java b/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemark/code/conf/PropertiesService.java deleted file mode 100644 index 4d828302b6..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemark/code/conf/PropertiesService.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.jun.plugin.freemark.code.conf; - -/** - * properties服务类 - */ -public class PropertiesService { - - /** - * application配置文件 - * - * @return - */ - public static PropertiesConfig getApplicationConfig() { - return PropertiesConfig.getInstance("/application.properties"); - } -} diff --git a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemark/code/create/CreateJava.java b/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemark/code/create/CreateJava.java deleted file mode 100644 index 5f3d14c07b..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemark/code/create/CreateJava.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.jun.plugin.freemark.code.create; - -import java.io.BufferedWriter; -import java.io.FileNotFoundException; -import java.io.FileWriter; -import java.io.IOException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.jun.plugin.freemark.code.entity.Columns; -import com.jun.plugin.freemark.code.entity.Table; -import com.jun.plugin.freemark.code.sql.SelectTableSql; - -/** - * 编写一个代码生成的小程序 - * - * @author shichenyang - * - */ -public class CreateJava { - - public static Map map=new HashMap(); - - static{ - map.put("VARCHAR", "String"); - map.put("DECIMAL", "Double"); - map.put("DATE", "Date"); - } - public static void main(String[] args) { - SelectTableSql updateSql = new SelectTableSql(); - List tables=null; - try { - tables = updateSql.getSchema(); - } catch (Exception e1) { - e1.printStackTrace(); - } - - - for (Table table : tables) { - StringBuffer java = new StringBuffer(); - String tableName=table.getTableName().substring(0, 1).toUpperCase()+table.getTableName().substring(1); - java.append("package com.yang.model;\n\n"); - java.append("import java.util.Date;\n\n"); - java.append("public class " + tableName + "{\n"); - // 循环一下列信息 - for (Columns item : table.getList()) { - java.append(" //" + item.getREMARKS()+"\n");// 加上注释 - // COLUMN_TYPE字段类型,COLUMN_NAME字段名称 - java.append(" private " + map.get(item.getColumnType()) + " " - + item.getColumnName() + ";\n"); - - } - java.append("\n"); - // 循环一下列信息 - for (Columns item : table.getList()) { - String name = item.getColumnName(); - // 拼接一下get方法 - java.append(" public " + map.get(item.getColumnType()) + " get" - + name.substring(0, 1).toUpperCase() - + name.substring(1) + "(){\n"); - java.append(" return " + name + ";\n"); - java.append(" }\n"); - - // 拼接一下set方法 - java.append(" public void" + " set" - + name.substring(0, 1).toUpperCase() - + name.substring(1) + "(" + map.get(item.getColumnType()) + " " - + name + "){\n"); - java.append(" this. " + name + "=" + name + ";\n"); - java.append(" }\n"); - } - - java.append("}\n"); - - BufferedWriter writer = null; - try { - writer = new BufferedWriter(new FileWriter("D:\\" - + tableName + ".java")); - writer.write(java.toString()); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } finally { - try { - writer.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - } - -} diff --git a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemark/code/entity/Columns.java b/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemark/code/entity/Columns.java deleted file mode 100644 index 130630d4c6..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemark/code/entity/Columns.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.jun.plugin.freemark.code.entity; -/** - * 实体类 - * @author shichenyang89@gmail.com - * - */ -public class Columns { - //列名 - private String columnName; - //列类型 - private String columnType; - //备注 - private String REMARKS; - //大小 - private int datasize; - private int digits; - //是否为空 - private String nullable; - public String getColumnName() { - return columnName; - } - public void setColumnName(String columnName) { - this.columnName = columnName; - } - public String getColumnType() { - return columnType; - } - public void setColumnType(String columnType) { - this.columnType = columnType; - } - public String getREMARKS() { - return REMARKS; - } - public void setREMARKS(String rEMARKS) { - REMARKS = rEMARKS; - } - public int getDatasize() { - return datasize; - } - public void setDatasize(int datasize) { - this.datasize = datasize; - } - public int getDigits() { - return digits; - } - public void setDigits(int digits) { - this.digits = digits; - } - public String getNullable() { - return nullable; - } - public void setNullable(String nullable) { - this.nullable = nullable; - } - -} diff --git a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemark/code/entity/Table.java b/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemark/code/entity/Table.java deleted file mode 100644 index fc7fda14a2..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemark/code/entity/Table.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.jun.plugin.freemark.code.entity; - -import java.util.ArrayList; -import java.util.List; -/** - * 实体类 - * @author shichenyang89@gmail.com - * - */ -public class Table { - //表名称 - private String tableName; - //表含义 - private String tableRemarks; - //列集合 - private List list=new ArrayList(); - public String getTableName() { - return tableName; - } - public void setTableName(String tableName) { - this.tableName = tableName; - } - public String getTableRemarks() { - return tableRemarks; - } - public void setTableRemarks(String tableRemarks) { - this.tableRemarks = tableRemarks; - } - public List getList() { - return list; - } - public void setList(List list) { - this.list = list; - } - - - -} diff --git a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemark/code/fm/FreeMarker.java b/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemark/code/fm/FreeMarker.java deleted file mode 100644 index f21b37d3b2..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemark/code/fm/FreeMarker.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.jun.plugin.freemark.code.fm; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileOutputStream; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.text.SimpleDateFormat; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.log4j.Logger; - - -import freemarker.template.Configuration; -import freemarker.template.Template; - -/** - * 生成表设计 - * @author shichenyang89@gmail.com - * - */ -public class FreeMarker { - SimpleDateFormat format=new SimpleDateFormat(); - - //日志对象 - private static Logger logger=Logger.getLogger(FreeMarker.class); - private Configuration configuration = null; - - public static void main(String[] args) throws Exception { - logger.debug("开始生成表"); -// new FreeMarker().create(); - logger.debug("生成结束"); - } - - @SuppressWarnings("deprecation") - public FreeMarker() { - configuration = new Configuration(); - configuration.setDefaultEncoding("utf-8"); - } - - /** - * 生成表设计 - * @throws Exception - */ -// public void create() throws Exception { -// Map map = new HashMap(); -// -// SelectTableSql updateSql = new SelectTableSql(); -// //第一步,加载模板 -// configuration.setClassForTemplateLoading(this.getClass(), "/"); -// Template template = configuration.getTemplate("info.ftl"); -// //设置文件输出位置 -// File outFile = new File("D:/outFile.doc"); -// -// //如果文件输出位置不存在,先进行创建 -// if (!outFile.getParentFile().exists()) { -// outFile.getParentFile().mkdirs(); -// } -// -// //增加输出流 -// Writer out = new BufferedWriter(new OutputStreamWriter( -// new FileOutputStream(outFile))); -// //第二步,获取数据库数据 -// List
tables = updateSql.getSchema(); -// map.put("tables", tables); -// //最后一步,调用freemaker引擎方法 -// template.process(map, out); -// } - -} diff --git a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemark/code/sql/SelectTableSql.java b/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemark/code/sql/SelectTableSql.java deleted file mode 100644 index e7e7dc80d4..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemark/code/sql/SelectTableSql.java +++ /dev/null @@ -1,144 +0,0 @@ -package com.jun.plugin.freemark.code.sql; - -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.DriverManager; -import java.sql.ResultSet; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import com.jun.plugin.freemark.code.conf.PropertiesConfig; -import com.jun.plugin.freemark.code.conf.PropertiesService; -import com.jun.plugin.freemark.code.entity.Columns; -import com.jun.plugin.freemark.code.entity.Table; -/** - * 查询数据库表信息 - * @author shichenyang89@gmail.com - * - */ -public class SelectTableSql { - private String name; - private int age; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - - private static Connection getConnection = null; - - /** - * 获取数据库连接 - * - * @param driver 驱动 - * @param pwd 密码 - * @param user 用户 - * @param url 连接字符串 - * @return 连接 - */ - public static Connection getConnections() { - try { - PropertiesConfig config = PropertiesService.getApplicationConfig(); - Properties props = new Properties(); - //针对于oracle数据库做特殊处理 - if(config.getProperty("database.name").equals("oracle")){ - props.put("remarksReporting", "true"); - } - props.put("user", config.getProperty("jdbc.username")); - props.put("password", config.getProperty("jdbc.password")); - Class.forName(config.getProperty("jdbc.driver")); - getConnection = DriverManager.getConnection(config.getProperty("jdbc.url"), props); - } catch (Exception e) { - e.printStackTrace(); - } - return getConnection; - } - - /** - * 获取数据库信息 - * @return - * @throws Exception - */ - public List
getSchema() throws Exception { -// String schema; - getConnection=getConnections(); - DatabaseMetaData metaData= getConnection.getMetaData();//获得元数据 - //下面这一行,获得数据库所有表信息 - ResultSet result= metaData.getTables(getConnection.getCatalog(), "root", null, new String[]{"TABLE"}); - List
list=new ArrayList
(); - while (result.next()) {// 判断有没有下一行 - //获得表名 - String tableNmae=result.getString("TABLE_NAME"); - //获得表的注释 - String tableRemarks=result.getString("REMARKS"); - - list.add(crateTbale(tableNmae,tableRemarks)); - //这个是我自己生成表的前缀 - /*if(tableNmae.length()>=8){ - String doc=tableNmae.substring(0,8); - if("Y_DOCTOR".equals(doc)){ - list.add(crateTbale(tableNmae,tableRemarks)); - } - }*/ - } -// schema = getConnection.getMetaData().getUserName(); -// if ((schema == null) || (schema.length() == 0)) { -// throw new Exception("ORACLE数据库模式不允许为空"); -// } - return list; - - } - - /** - * 根据表名进行查找列 - * @param tableName - * @param tableRemarks - * @return - * @throws Exception - */ - public Table crateTbale(String tableName,String tableRemarks) throws Exception { - ResultSet result = null;// 查询数据库 - //数据库元数据 - DatabaseMetaData metaData= getConnection.getMetaData(); - //根据表名获得列信息 - result= metaData.getColumns(null,"%", tableName, "%"); - //自己编写的实体类 - Table table=new Table(); - table.setTableName(tableName); - table.setTableRemarks(tableRemarks); - List list=new ArrayList(); - //对列信息进行循环 - while(result.next()) { - //创建一个列的实体类 - Columns columns=new Columns(); - String columnName = result.getString("COLUMN_NAME"); - String columnType = result.getString("TYPE_NAME"); - String REMARKS=result.getString("REMARKS"); - int datasize = result.getInt("COLUMN_SIZE"); - int digits = result.getInt("DECIMAL_DIGITS"); - int nullable = result.getInt("NULLABLE"); - String nullable2=nullable==0?"非空":"可以为空"; - columns.setColumnName(columnName); - columns.setColumnType(columnType); - columns.setDatasize(datasize); - columns.setDigits(digits); - columns.setNullable(nullable2); - columns.setREMARKS(REMARKS); - list.add(columns); - } - table.setList(list); - return table; - } -} diff --git a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemark/demo/User.java b/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemark/demo/User.java deleted file mode 100644 index 123d6d3360..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemark/demo/User.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.jun.plugin.freemark.demo; - -public class User { - - private Integer id; - private String name; - - public User() { - } - - public User(Integer id, String name) { - this.id = id; - this.name = name; - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Override - public String toString() { - return "User [id=" + id + ", name=" + name + "]"; - } - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemark/view/FreeMarkerView.java b/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemark/view/FreeMarkerView.java deleted file mode 100644 index 8acf6ddd12..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemark/view/FreeMarkerView.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.jun.plugin.freemark.view; - - -import java.io.IOException; -import java.io.Writer; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import freemarker.template.Configuration; -import freemarker.template.Template; -import freemarker.template.TemplateException; - -@SuppressWarnings("serial") -public class FreeMarkerView extends HttpServlet { - - public FreeMarkerView() { - super(); - } - - // 负责管理FreeMarker模板的Configuration实例 - private Configuration cfg = null; - - public void init() throws ServletException { - // 创建一个FreeMarker实例 - cfg = new Configuration(); - // 指定FreeMarker模板文件的位置 - cfg.setServletContextForTemplateLoading(getServletContext(), "/WEB-INF/templates"); - } - - public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - doPost(request, response); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - // 建立数据模型 - Map root = new HashMap(); - root.put("message", "hello world"); - root.put("name", "屌丝"); - // root.put("personList", list); - - // 获取模板文件 - Template t = cfg.getTemplate("test.ftl"); - - // 开始准备生成输出 - // - 使用模板文件的Charset作为本页面的charset - // - 使用text/html MIME-type - response.setContentType("text/html; charset=" + t.getEncoding()); - Writer out = response.getWriter(); - // 合并数据模型和模板,并将结果输出到out中 - try { - t.process(root, out); // 往模板里写数据 - } catch (TemplateException e) { - e.printStackTrace(); - } - } - - public void destroy() { - super.destroy(); - } -} diff --git a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/ClientTest.java b/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/ClientTest.java deleted file mode 100644 index 3a86dff23e..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/ClientTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.jun.plugin.freemarker; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -/** - * - * 客户端测试模板输入类 - * @author hailang - * @date 2009-7-9 下午04:11:20 - * @version 1.0 - */ -public class ClientTest { - - public static List initUserList(){ - List list=new ArrayList(); - User user1=new User(); - user1.setUserName("张三"); - user1.setUserPassword("123"); - user1.setAge(20); - - - User user2=new User(); - user2.setUserName("李四"); - user2.setUserPassword("123"); - user2.setAge(22); - - User user3=new User(); - user3.setUserName("王五"); - user3.setUserPassword("123"); - user3.setAge(21); - - list.add(user1); - list.add(user2); - list.add(user3); - - return list; - - } - - - - public static void main(String[] args) { - - Map root=new HashMap(); - List list=ClientTest.initUserList(); - - root.put("userList",list); - -// FreeMarkerUtil.analysisTemplate("user.ftl", "UTF-8", root); - - - } -} diff --git a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/Example.java b/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/Example.java deleted file mode 100644 index 6240c0d86d..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/Example.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.jun.plugin.freemarker; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -import freemarker.template.Configuration; -import freemarker.template.DefaultObjectWrapper; -import freemarker.template.Template; - -public class Example { - - private static String FILE_DIR = "c:\\sample\\freemarker\\"; - - public static void main(String[] args) { - - File f = new File(FILE_DIR); - if (!f.isDirectory()) { - f.mkdirs(); - } - - Example t = new Example(); - - //计算式 - t.process("T101.ftl"); - - //输出一个值 - HashMap t2root = new HashMap(); - t2root.put("user", "RenSanNing"); - t.process("T102.ftl", t2root); - - //输出一个列表 - Map t3root = new HashMap(); - List menu = new ArrayList(); - menu.add(new Food("iText in Action", 98)); - menu.add(new Food("iBATIS in Action", 118)); - menu.add(new Food("Lucene in Action", 69)); - t3root.put("menu", menu); - t.process("T103.ftl", t3root); - - //逻辑判断(IF,SWITCH) - Map t4root = new HashMap(); - t4root.put("x", 2); - t4root.put("y", "medium"); - t.process("T104.ftl", t4root); - - //自定义函数 - t.process("T105.ftl"); - - //定义变量 - t.process("T106.ftl"); - - //定义宏macro - t.process("T107.ftl"); - - //include - t.process("T108.ftl"); - - //名字空间 - t.process("T109.ftl"); - - //自定义指令Directive - Map t10root = new HashMap(); - t10root.put("systemdate", new SystemDateDirective()); - t10root.put("text_cut", new TextCutDirective()); - t.process("T110.ftl", t10root); - - } - - public void process(String template, Map data){ - try { - Configuration cfg = new Configuration(); - cfg.setDirectoryForTemplateLoading(new File("ftl")); - cfg.setObjectWrapper(new DefaultObjectWrapper()); - - //设置字符集 - cfg.setDefaultEncoding("UTF-8"); - - //设置尖括号语法和方括号语法,默认是自动检测语法 - // 自动 AUTO_DETECT_TAG_SYNTAX - // 尖括号 ANGLE_BRACKET_TAG_SYNTAX - // 方括号 SQUARE_BRACKET_TAG_SYNTAX - cfg.setTagSyntax(Configuration.AUTO_DETECT_TAG_SYNTAX); - - Writer out = new OutputStreamWriter(new FileOutputStream(FILE_DIR + template + ".txt"),"UTF-8"); - Template temp = cfg.getTemplate(template); - temp.process(data, out); - out.flush(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public void process(String template) { - process(template, null); - } - -} diff --git a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/Food.java b/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/Food.java deleted file mode 100644 index 5a96317d0b..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/Food.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.jun.plugin.freemarker; - -public class Food { - private String name; - private int price; - public Food(String name, int price) { - this.name = name; - this.price = price; - } - public String getName() { - return name; - } - public int getPrice() { - return price; - } -} diff --git a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/FreeMarkerView.java b/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/FreeMarkerView.java deleted file mode 100644 index ecc3774772..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/FreeMarkerView.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.jun.plugin.freemarker; - -import java.io.IOException; -import java.io.Writer; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import freemarker.template.Configuration; -import freemarker.template.Template; -import freemarker.template.TemplateException; - -@SuppressWarnings("serial") -public class FreeMarkerView extends HttpServlet { - - public FreeMarkerView() { - super(); - } - - // 负责管理FreeMarker模板的Configuration实例 - private Configuration cfg = null; - - public void init() throws ServletException { - // 创建一个FreeMarker实例 - cfg = new Configuration(); - // 指定FreeMarker模板文件的位置 - cfg.setServletContextForTemplateLoading(getServletContext(), "/WEB-INF/templates"); - } - - public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - doPost(request, response); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - // 建立数据模型 - Map root = new HashMap(); - root.put("message", "hello world"); - root.put("name", "屌丝"); - // root.put("personList", list); - - // 获取模板文件 - Template t = cfg.getTemplate("test.ftl"); - - // 开始准备生成输出 - // - 使用模板文件的Charset作为本页面的charset - // - 使用text/html MIME-type - response.setContentType("text/html; charset=" + t.getEncoding()); - Writer out = response.getWriter(); - // 合并数据模型和模板,并将结果输出到out中 - try { - t.process(root, out); // 往模板里写数据 - } catch (TemplateException e) { - e.printStackTrace(); - } - } - - public void destroy() { - super.destroy(); - } -} diff --git a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/FreemarkerTest.java b/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/FreemarkerTest.java deleted file mode 100644 index c4279d29c5..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/FreemarkerTest.java +++ /dev/null @@ -1,189 +0,0 @@ -package com.jun.plugin.freemarker; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.Test; - -import freemarker.template.Configuration; -import freemarker.template.Template; -import freemarker.template.TemplateExceptionHandler; - -public class FreemarkerTest{ - - static String dir = "D:/workspace/workspace_jun_eclipse/jun_base/src_freemarker/com/jun/freemarker/"; - @Test - public void testFreemarker01() throws Exception{ - - - Configuration cfg = new Configuration(); - - //��ʲô�ط�����ģ���ļ� - cfg.setDirectoryForTemplateLoading(new File(dir)); - - //����ģ�� - Template template = cfg.getTemplate("test01.ftl"); - - //�������� - Map root = new HashMap(); - root.put("strvalue", "�������"); - - //������� - PrintWriter out - = new PrintWriter( - new BufferedWriter( - new FileWriter(dir+"\\test01_out.txt") - ) - ); - - //����ģ�壬����� - template.process(root, out); - - } - - //���ڿ�ֵ��������� - public void testFreemarker02() throws Exception{ - -// String dir = "D:\\share\\JavaProjects\\oa\\freemarker\\src\\com\\bjsxt\\freemarker"; - - Configuration cfg = new Configuration(); - - //��ʲô�ط�����ģ���ļ� - cfg.setDirectoryForTemplateLoading(new File(dir)); - - //�����쳣 - cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER); - - //����ģ�� - Template template = cfg.getTemplate("test02.ftl"); - - //�������� - Map root = new HashMap(); - //root.put("strvalue", "�������"); - - //������� - PrintWriter out - = new PrintWriter( - new BufferedWriter( - new FileWriter(dir+"\\test02_out.txt") - ) - ); - - //����ģ�壬����� - template.process(root, out); - - } - - //���������� - public void testFreemarker03() throws Exception{ - -// String dir = "D:\\share\\JavaProjects\\oa\\freemarker\\src\\com\\bjsxt\\freemarker"; - - Configuration cfg = new Configuration(); - - //��ʲô�ط�����ģ���ļ� - cfg.setDirectoryForTemplateLoading(new File(dir)); - - //�����쳣 - cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER); - - //����ģ�� - Template template = cfg.getTemplate("test03.ftl"); - - //�������� - Map root = new HashMap(); - - List list = new ArrayList(); - for(int i=0; i<10; i++){ - list.add("listvalue"+i); - } - root.put("listvalue", list); - - //������� - PrintWriter out - = new PrintWriter( - new BufferedWriter( - new FileWriter(dir+"\\test03_out.txt") - ) - ); - - //����ģ�壬����� - template.process(root, out); - - } - - //freemarker �궨�� - public void testFreemarker04() throws Exception{ - -// String dir = "D:\\share\\JavaProjects\\oa\\freemarker\\src\\com\\bjsxt\\freemarker"; - - Configuration cfg = new Configuration(); - - //��ʲô�ط�����ģ���ļ� - cfg.setDirectoryForTemplateLoading(new File(dir)); - - //�����쳣 - cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER); - - //����ģ�� - Template template = cfg.getTemplate("test04.ftl"); - - //�������� - Map root = new HashMap(); - root.put("name", "����"); - - //������� - PrintWriter out - = new PrintWriter( - new BufferedWriter( - new FileWriter(dir+"\\test04_out.txt") - ) - ); - - //����ģ�壬����� - template.process(root, out); - - } - - //freemarker auto-import���Ե���ʾ - public void testFreemarker05() throws Exception{ - -// String dir = "D:\\share\\JavaProjects\\oa\\freemarker\\src\\com\\bjsxt\\freemarker"; - - Configuration cfg = new Configuration(); - - //��ʲô�ط�����ģ���ļ� - cfg.setDirectoryForTemplateLoading(new File(dir)); - - //�����쳣 - cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER); - - //�Զ���������ԣ��Զ�import������ģ���ļ� - cfg.addAutoImport("my", "common.ftl"); - - //����ģ�� - Template template = cfg.getTemplate("test05.ftl"); - - //�������� - Map root = new HashMap(); - root.put("name", "����"); - - //������� - PrintWriter out - = new PrintWriter( - new BufferedWriter( - new FileWriter(dir+"\\test05_out.txt") - ) - ); - - //����ģ�壬����� - template.process(root, out); - - } -} diff --git a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/SystemDateDirective.java b/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/SystemDateDirective.java deleted file mode 100644 index 453889dde1..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/SystemDateDirective.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.jun.plugin.freemarker; - -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Map; - -import freemarker.core.Environment; -import freemarker.template.TemplateDirectiveBody; -import freemarker.template.TemplateDirectiveModel; -import freemarker.template.TemplateException; -import freemarker.template.TemplateModel; - -public class SystemDateDirective implements TemplateDirectiveModel { - - public void execute(Environment env, Map params, TemplateModel[] loopVars, - TemplateDirectiveBody body) throws TemplateException, IOException { - Calendar cal = Calendar.getInstance(); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); - env.getOut().append(sdf.format(cal.getTime())); - } - -} diff --git a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/TextCutDirective.java b/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/TextCutDirective.java deleted file mode 100644 index 5386c5e715..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/TextCutDirective.java +++ /dev/null @@ -1,112 +0,0 @@ -package com.jun.plugin.freemarker; - -import java.io.IOException; -import java.io.Writer; -import java.util.Map; - -import freemarker.core.Environment; -import freemarker.template.TemplateDirectiveBody; -import freemarker.template.TemplateDirectiveModel; -import freemarker.template.TemplateException; -import freemarker.template.TemplateModel; -import freemarker.template.TemplateNumberModel; -import freemarker.template.TemplateScalarModel; - -public class TextCutDirective implements TemplateDirectiveModel { - public static final String PARAM_S = "s"; - public static final String PARAM_LEN = "len"; - public static final String PARAM_APPEND = "append"; - - @SuppressWarnings("unchecked") - public void execute(Environment env, Map params, TemplateModel[] loopVars, - TemplateDirectiveBody body) throws TemplateException, IOException { - String s = getString(PARAM_S, params); - Integer len = getInt(PARAM_LEN, params); - String append = getString(PARAM_APPEND, params); - if (s != null) { - Writer out = env.getOut(); - if (len != null) { - out.append(textCut(s, len, append)); - } else { - out.append(s); - } - } - } - - private String getString(String name, - Map params) throws TemplateException { - TemplateModel model = params.get(name); - if (model == null) { - return null; - } - if (model instanceof TemplateScalarModel) { - return ((TemplateScalarModel) model).getAsString(); - } else if ((model instanceof TemplateNumberModel)) { - return ((TemplateNumberModel) model).getAsNumber().toString(); - } else { - return ""; - } - } - - private Integer getInt(String name, Map params) - throws TemplateException { - TemplateModel model = params.get(name); - if (model == null) { - return null; - } - if (model instanceof TemplateScalarModel) { - String s = ((TemplateScalarModel) model).getAsString(); - if (s == null || "".equals(s)) { - return null; - } - try { - return Integer.parseInt(s); - } catch (NumberFormatException e) { - return null; - } - } else if (model instanceof TemplateNumberModel) { - return ((TemplateNumberModel) model).getAsNumber().intValue(); - } else { - return null; - } - } - - private String textCut(String s, int len, String append) { - if (s == null) { - return null; - } - int slen = s.length(); - if (slen <= len) { - return s; - } - // 最大计数(如果全是英文) - int maxCount = len * 2; - int count = 0; - int i = 0; - for (; count < maxCount && i < slen; i++) { - if (s.codePointAt(i) < 256) { - count++; - } else { - count += 2; - } - } - if (i < slen) { - if (count > maxCount) { - i--; - } - if (!(append == null || "".equals(append))) { - if (s.codePointAt(i - 1) < 256) { - i -= 2; - } else { - i--; - } - return s.substring(0, i) + append; - } else { - return s.substring(0, i); - } - } else { - return s; - } - } - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/User.java b/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/User.java deleted file mode 100644 index 21bc326223..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/User.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.jun.plugin.freemarker; - -/** - * - * 用户信息 - * @author hailang - * @date 2009-9-9 上午09:13:51 - * @version 1.0 - */ -public class User { - private String userName; - private String userPassword; - private Integer age; - - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - - public String getUserPassword() { - return userPassword; - } - - public void setUserPassword(String userPassword) { - this.userPassword = userPassword; - } - - public Integer getAge() { - return age; - } - - public void setAge(Integer age) { - this.age = age; - } - -} diff --git a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/test01.ftl b/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/test01.ftl deleted file mode 100644 index e3c56ef5f3..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/test01.ftl +++ /dev/null @@ -1 +0,0 @@ -һԳ${strvalue} \ No newline at end of file diff --git a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/test01_out.txt b/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/test01_out.txt deleted file mode 100644 index 2a2b38b7f5..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/test01_out.txt +++ /dev/null @@ -1 +0,0 @@ -��һ�����Գ���������� \ No newline at end of file diff --git a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/test02_out.txt b/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/test02_out.txt deleted file mode 100644 index 13dcf4f728..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/test02_out.txt +++ /dev/null @@ -1,2 +0,0 @@ -��һ�����Գ��� -��������.... \ No newline at end of file diff --git a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/test03_out.txt b/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/test03_out.txt deleted file mode 100644 index 6c80ad8ae3..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/test03_out.txt +++ /dev/null @@ -1,12 +0,0 @@ -listvalue: - - listvalue0 [0] - listvalue1 [1] - listvalue2 [2] - listvalue3 [3] - listvalue4 [4] - listvalue5 [5] - listvalue6 [6] - listvalue7 [7] - listvalue8 [8] - listvalue9 [9] diff --git a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/test04.ftl b/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/test04.ftl deleted file mode 100644 index 5addc3f185..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/test04.ftl +++ /dev/null @@ -1,6 +0,0 @@ -<#macro greet p> - Hello,${p} - - -<@greet p=""/> -<@greet p="${name}"/> \ No newline at end of file diff --git a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/test04_out.txt b/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/test04_out.txt deleted file mode 100644 index e1067d969e..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/test04_out.txt +++ /dev/null @@ -1,3 +0,0 @@ - - Hello,���� - Hello,���� diff --git a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/test05_out.txt b/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/test05_out.txt deleted file mode 100644 index e0311eeede..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/java/com/jun/plugin/freemarker/test05_out.txt +++ /dev/null @@ -1,2 +0,0 @@ - Hello,���� - Hello,���� diff --git a/jun_java_plugins/jun_freemarker/src/main/resources/application.properties b/jun_java_plugins/jun_freemarker/src/main/resources/application.properties deleted file mode 100644 index f4b364302b..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/resources/application.properties +++ /dev/null @@ -1,11 +0,0 @@ -#mysql database setting -jdbc.driver=com.mysql.jdbc.Driver -jdbc.url=jdbc\:mysql\://localhost\:3306/uu?useUnicode\=true&characterEncoding\=UTF-8&zeroDateTimeBehavior\=convertToNull -jdbc.username=root -jdbc.password=root - -#dbcp settings -dbcp.maxIdle=2 -dbcp.maxActive=10 -dbcp.defaultAutoCommit=true -database.name=null diff --git a/jun_java_plugins/jun_freemarker/src/main/resources/info.ftl b/jun_java_plugins/jun_freemarker/src/main/resources/info.ftl deleted file mode 100644 index bda0cddb80..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/resources/info.ftl +++ /dev/null @@ -1,1171 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <#list tables as t> - - - - - - ${t_index+1}. - - - ${t.tableName} - - - ${t.tableRemarks} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 序号 - - - - - - - - - - - - - - - - - - 列名 - - - - - - - - - - - - - - - - - - 注释 - - - - - - - - - - - - - - - - - - 类型 - - - - - - - - - - - - - - - - - - 是否为空 - - - - - - - - - - - - - - - - - <#list t.list as p> - - - - - - - - - - - - - - - - ${p_index+1} - - - - - - - - - - - - - - - - - - ${p.columnName} - - - - - - - - - - - - - - - - - - ${p.REMARKS} - - - - - - - - - - - - - - - - - - ${p.columnType} - - - - - - - - - - - - - - - - - - ${p.nullable} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 史晨阳 - - - 史晨阳 - 2 - 2017-06-06T01:11:00Z - 2017-06-06T01:11:00Z - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1 - 1 - 13 - 75 - Microsoft Office Word - 0 - 1 - 1 - false - - false - 87 - false - false - 15.0000 - - - - diff --git a/jun_java_plugins/jun_freemarker/src/main/resources/log4j.properties b/jun_java_plugins/jun_freemarker/src/main/resources/log4j.properties deleted file mode 100644 index 2bfa2aec48..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/resources/log4j.properties +++ /dev/null @@ -1,24 +0,0 @@ -### 设置### -log4j.rootLogger = debug,stdout,D,E - -### 输出信息到控制抬 ### -log4j.appender.stdout = org.apache.log4j.ConsoleAppender -log4j.appender.stdout.Target = System.out -log4j.appender.stdout.layout = org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n - -### 输出DEBUG 级别以上的日志到=E://logs/error.log ### -log4j.appender.D = org.apache.log4j.DailyRollingFileAppender -log4j.appender.D.File = debug.log -log4j.appender.D.Append = true -log4j.appender.D.Threshold = DEBUG -log4j.appender.D.layout = org.apache.log4j.PatternLayout -log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n - -### 输出ERROR 级别以上的日志到=E://logs/error.log ### -log4j.appender.E = org.apache.log4j.DailyRollingFileAppender -log4j.appender.E.File =error.log -log4j.appender.E.Append = true -log4j.appender.E.Threshold = ERROR -log4j.appender.E.layout = org.apache.log4j.PatternLayout -log4j.appender.E.layout.ConversionPattern =%-d{yyyy-MM-dd HH\:mm\:ss} [ %t\:%r ] - [ %p ] %m%n \ No newline at end of file diff --git a/jun_java_plugins/jun_freemarker/src/main/resources/templates/common.ftl b/jun_java_plugins/jun_freemarker/src/main/resources/templates/common.ftl deleted file mode 100644 index ba12e110a1..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/resources/templates/common.ftl +++ /dev/null @@ -1,3 +0,0 @@ -<#macro greet p> - Hello,${p} - \ No newline at end of file diff --git a/jun_java_plugins/jun_freemarker/src/main/resources/templates/test02.ftl b/jun_java_plugins/jun_freemarker/src/main/resources/templates/test02.ftl deleted file mode 100644 index d506360f40..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/resources/templates/test02.ftl +++ /dev/null @@ -1,2 +0,0 @@ -һԳ${strvalue} -.... \ No newline at end of file diff --git a/jun_java_plugins/jun_freemarker/src/main/resources/templates/test03.ftl b/jun_java_plugins/jun_freemarker/src/main/resources/templates/test03.ftl deleted file mode 100644 index 31654e3fcc..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/resources/templates/test03.ftl +++ /dev/null @@ -1,5 +0,0 @@ -listvalue: - -<#list listvalue as v> - ${v} [${v_index}] - \ No newline at end of file diff --git a/jun_java_plugins/jun_freemarker/src/main/resources/templates/user.ftl b/jun_java_plugins/jun_freemarker/src/main/resources/templates/user.ftl deleted file mode 100644 index 837357d684..0000000000 --- a/jun_java_plugins/jun_freemarker/src/main/resources/templates/user.ftl +++ /dev/null @@ -1,60 +0,0 @@ -<#--Freemarker遍历list--> -简单遍历list: -<#list userList as user> - 用户名:${user.userName} - 密 码:${user.userPassword} - 年 龄: ${user.age} - - - -<#--Freemarker遍历list并应用list隐含变量item_index--> -item_index使用: -<#list userList as user> -第${user_index+1}个用户 - 用户名:${user.userName} - 密 码:${user.userPassword} - 年 龄: ${user.age} - -<#--Freemarker遍历list并应用list隐含变量item_has_next--> -item_has_next,size使用: -<#list userList as user> - - 用户名:${user.userName} - 密 码:${user.userPassword} - 年 龄: ${user.age} - <#if !user_has_next> - 共有${userList?size}最后一个用户是:${user.userName} - - -<#--Freemarker遍历list并按用户年龄升序排序--> - -按用户年龄升序排序: -<#list userList?sort_by("age") as user> - - 用户名:${user.userName} - 密 码:${user.userPassword} - 年 龄: ${user.age} - - -<#--Freemarker遍历list并按用户年龄降序排序--> - -按用户年龄降序排序: -<#list userList?sort_by("age")?reverse as user> - - 用户名:${user.userName} - 密 码:${user.userPassword} - 年 龄: ${user.age} - - -<#--Freemarker遍历list当用户年龄大于21岁时,停止输出--> -list中应用break: -<#list userList?sort_by("age")?reverse as user> - - 用户名:${user.userName} - 密 码:${user.userPassword} - 年 龄: ${user.age} - <#if (user.age>21) > - <#break> - - - diff --git a/jun_java_plugins/jun_guava/.gitignore b/jun_java_plugins/jun_guava/.gitignore deleted file mode 100644 index 4d7b35bc18..0000000000 --- a/jun_java_plugins/jun_guava/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -.project -.classpath -.settings -target diff --git a/jun_java_plugins/jun_guava/README.txt b/jun_java_plugins/jun_guava/README.txt deleted file mode 100644 index bc95ced16e..0000000000 --- a/jun_java_plugins/jun_guava/README.txt +++ /dev/null @@ -1,11 +0,0 @@ -This is a pet project demonstrating some of the basic usage in the Google Guava library: - -> http://code.google.com/p/guava-libraries/ - -The best way to try them out for yourself is to: - 1) Clone the project - 2) Run mvn eclipse:eclipse - 3) Import into Eclipse - 4) Explore and run the different test-classes in src/test/java. - -You can also find slides with the examples here: http://blog.tfnico.com/2010/06/google-guava-taking-over-for-google.html diff --git a/jun_java_plugins/jun_guava/doc/basic-utilities-defaults.md b/jun_java_plugins/jun_guava/doc/basic-utilities-defaults.md deleted file mode 100644 index 20d1155a04..0000000000 --- a/jun_java_plugins/jun_guava/doc/basic-utilities-defaults.md +++ /dev/null @@ -1,20 +0,0 @@ -默认值(Defaults) -=== -Defaults类提供Java各原生类型的默认值 - -com.google.common.base.Defaults.defaultValue(Class type) - -```java -boolean.class //返回false -char.class //返回'\0' -byte.class //返回(byte)0 -short.class //返回(short)0 -int.class //返回0 -long.class //返回0L -float.class //返回0f -double.class //返回0d -non-primitive types //返回null -``` - ------- -[返回目录](/README.md) diff --git a/jun_java_plugins/jun_guava/doc/basic-utilities-object-methods.md b/jun_java_plugins/jun_guava/doc/basic-utilities-object-methods.md deleted file mode 100644 index d12530e2d5..0000000000 --- a/jun_java_plugins/jun_guava/doc/basic-utilities-object-methods.md +++ /dev/null @@ -1,61 +0,0 @@ -常用的对象方法(Objects) -=== -Objects提供了Java对象的equals、hashCode、toString等方法 - -#### equals -覆写equals方法时, 减少了null判断和分支处理 - -```java -Objects.equal("a", "a"); // returns true -Objects.equal(null, "a"); // returns false -Objects.equal("a", null); // returns false -Objects.equal(null, null); // returns true -``` - -#### hashCode -更方便地完成多个属性的hash - -```java -Objects.hashCode(Object...) -Objects.hashCode(field1, field2, ..., fieldn) -``` - -#### toString -对象的toString方法更多是为了更好的可读性, ToStringHelper可以通过链式更方便地将对象的各属性都加入 - -```java -Objects.toStringHelper(Persion.class) - .add("name", this.name) - .add("age", this.age) - .toString(); -``` - -> Intellij Idea中可以安装*Guava equals, hashCode and toString generator*插件来快速生成这三个方法 - - -#### compare/compareTo -compareTo是java.lang.Comparable接口中的方法 - -guava提供了所有原始类型的对比工具 -```java -Ints.compare(int a, int b) -Longs.compare(long a, long b) -Shorts.compare(short a, short b) -Doubles.compare(double a, double b) -Floats.compare(float a, floab b) -Booleans.compare(boolean a, boolean b) -Chars.compare(char a, char b) -``` - -同时,guava还提供了链式对比的工具ComparisonChain -```java -ComparisonChain.start() - .compare(this.aString, that.aString) - .compare(this.anInt, that.anInt) - .compare(this.anEnum, that.anEnum, Ordering.natural().nullsLast()) - .result(); -``` -ComparisonChain是一个lazy的比较过程, 当比较结果为0的时候, 即相等的时候, 会继续比较下去, 出现非0的情况, 就会忽略后面的比较 - ------- -[返回目录](/README.md) diff --git a/jun_java_plugins/jun_guava/doc/basic-utilities-ordering.md b/jun_java_plugins/jun_guava/doc/basic-utilities-ordering.md deleted file mode 100644 index 8633311b6c..0000000000 --- a/jun_java_plugins/jun_guava/doc/basic-utilities-ordering.md +++ /dev/null @@ -1,37 +0,0 @@ -犀利的比较器(Ordering) -=== -Ordering是Guava类库提供的一个犀利强大的比较器工具,Guava的Ordering和JDK Comparator相比功能更强。它非常容易扩展,可以轻松构造复杂的comparator,然后用在容器的比较、排序等操作中。 - -#### 常用静态方法 - -```java - -Ordering.natural(); // 使用Comparable类型的自然顺序, 例如:整数从小到大,字符串是按字典顺序; -Ordering.usingToString(); // 使用toString()返回的字符串按字典顺序进行排序; -Ordering.from(Comparator); // 将Comparator转换为Ordering -new Ordering(){ // 或者直接构建一个Ordering对象,并实现compare方法 - public int compare(T left, T right){} -} -``` - - -#### 实例方法(支持链式) -com.google.common.collect.Ordering - -```java -reverse(); //返回与当前Ordering相反的排序 -nullsFirst(); //返回一个将null放在non-null元素之前的Ordering,其他的和原始的Ordering一样 -nullsLast(); //返回一个将null放在non-null元素之后的Ordering,其他的和原始的Ordering一样 -compound(Comparator); //返回一个使用Comparator的Ordering,Comparator作为第二排序元素 -lexicographical(); //返回一个按照字典元素迭代的Ordering -onResultOf(Function); //将function应用在各个元素上之后, 在使用原始ordering进行排序 -greatestOf(Iterable iterable, int k); //返回指定的前k个可迭代的最大的元素,按照当前Ordering从最大到最小的顺序 -leastOf(Iterable iterable, int k); //返回指定的前k个可迭代的最小的元素,按照当前Ordering从最小到最大的顺序 -isOrdered(Iterable); //是否有序(前面的元素可以大于或等于后面的元素),Iterable不能少于2个元素 -isStrictlyOrdered(Iterable); //是否严格有序(前面的元素必须大于后面的元素),Iterable不能少于两个元素 -sortedCopy(Iterable); //返回指定的元素作为一个列表的排序副本 - -``` - ------- -[返回目录](/README.md) diff --git a/jun_java_plugins/jun_guava/doc/basic-utilities-preconditions.md b/jun_java_plugins/jun_guava/doc/basic-utilities-preconditions.md deleted file mode 100644 index c56b902ff7..0000000000 --- a/jun_java_plugins/jun_guava/doc/basic-utilities-preconditions.md +++ /dev/null @@ -1,49 +0,0 @@ -优雅的参数检查(Preconditions) -=== -#### 问题 -对外接口方法参数过多时,需对参数进行必要的检查,将预期之外的请求快速驳回。 - -```java -public boolean someMethod(int arg1, String arg2, String arg3, Object arg4){ - if( arg1>0 && isNotEmpty(arg2) && isNotEmpty(arg3) && arg4!=null){ - return false; // maybe需要将具体的错误类型告诉调用方 - } - ... -} - -``` - -#### 方案 -com.google.common.base.Preconditions - -```java -// 检查boolean是否为真 -// 失败时抛出 IllegalArgumentException -Preconditions.checkArgument(boolean expression, String errMsg, Object... errMsgArgs) - -// 检查value是否为null -// 失败时抛出 NullPointerException -Preconditions.checkNotNull(T reference, String errMsg, Object... errMsgArgs) - -// 检查对象的一些状态, 不依赖方法参数(相比checkArgument, 在某些情况下更有语义...) -// 失败时抛出 IllegalStateException -Preconditions.checkState(boolean expression, String errMsg, Object... errMsgArgs) - -// 检查index是否在合法范围[0, size)(不包含size) -// 失败时抛出 IndexOutOfBoundsException -Preconditions.checkElementIndex(int index, int size, String desc) - -// 检查位置是否在合法范围[0, size](包含size) -// 失败时抛出 IndexOutOfBoundsException -Preconditions.checkPositionIndex(int index, int size, String desc) - -// 检查[start, end)是一个长度为size的集合合法的子集范围 -// 失败时抛出 IndexOutOfBoundsException -Preconditions.checkPositionIndexs(int start, int index, int size) - -``` - -建议通过静态方式引入com.google.common.base.Preconditions.* - ------- -[返回目录](/README.md) diff --git a/jun_java_plugins/jun_guava/doc/basic-utilities-throwables.md b/jun_java_plugins/jun_guava/doc/basic-utilities-throwables.md deleted file mode 100644 index 26b6b7a75e..0000000000 --- a/jun_java_plugins/jun_guava/doc/basic-utilities-throwables.md +++ /dev/null @@ -1,29 +0,0 @@ -简化异常处理(Throwables) -=== -Guava提供了一个异常处理工具类, 可以简单地捕获和重新抛出多个异常 - -#### 常用方法 - -```java -// 把throwable包装成RuntimeException,用该方法保证异常传递,抛出一个RuntimeException异常 -RuntimeException propagate(Throwable); - -// 当且仅当它是一个X的实例时,传递throwable -void propagateIfInstanceOf(Throwable, Class) throws X; - -// 当且仅当它是一个RuntimeException和Error时,传递throwable -void propagateIfPossible(Throwable); - -// 当且仅当它是一个RuntimeException和Error时,或者是一个X的实例时,传递throwable -void propagateIfPossible(Throwable, Class) throws X; -``` - -#### 异常链处理 -```java -Throwable getRootCause(Throwable) -List getCausalChain(Throwable) -String getStackTraceAsString(Throwable) -``` - ------- -[返回目录](/README.md) diff --git a/jun_java_plugins/jun_guava/doc/basic-utilities-using-avoiding-null.md b/jun_java_plugins/jun_guava/doc/basic-utilities-using-avoiding-null.md deleted file mode 100644 index 23c0f1e811..0000000000 --- a/jun_java_plugins/jun_guava/doc/basic-utilities-using-avoiding-null.md +++ /dev/null @@ -1,43 +0,0 @@ -使用和避免null -=== - - -null本身不是对象,也不是Objcet的实例 - -#### 问题: -null代表不确定的对象, 是一个很模糊的概念, 容易产生二义性 - -Map.get(key)若返回value值为null,其代表的含义可能是该键指向的value值是null,亦或者该键在map中并不存在 - -#### 优点: -从内存消耗和效率方面,null更加廉价 - -#### 优化: Optional -com.google.common.base.Optional - -```java -Optional possbile = Optional.formNullable(T); //将一个T的实例转换为Optional对象(T可以为空) -boolean present = possible.isPresent(); //若Optional包含的T实例不为null,则返回true;若T实例为null,返回false -T t = possible.get(); //返回Optional包含的T实例,该T实例必须不为空;否则,抛出一个IllegalStateException异常 -``` - -构建一个Optional对象 - -```java -Optional.of(T); //将一个T的实例转换为Optional对象(T不可以为空) -Optional.absent(); //获得一个Optional对象,其内部包含了空值 -Optional.fromNullable(T); //将一个T的实例转换为Optional对象,T的实例可以不为空,也可以为空 - //Optional.fromNullable(null) 等同于 Optional.absent() -``` - -Optional实例方法 - -```java -boolean isPresent(); //若Optional包含的T实例不为null, 返回true; 否则, 返回false -T get(); //若Optional包含的T实例不为null, 返回T; 否则, 抛出IllegalStateException -T or(T); //若Optional包含的T实例不为null, 返回T; 否则, 返回参数输入的T实例 -T orNull(); //若Optional包含的T实例不为null, 返回T; 否则, 返回null -``` - ------- -[返回目录](/README.md) \ No newline at end of file diff --git a/jun_java_plugins/jun_guava/doc/caches.md b/jun_java_plugins/jun_guava/doc/caches.md deleted file mode 100644 index 83531cfff3..0000000000 --- a/jun_java_plugins/jun_guava/doc/caches.md +++ /dev/null @@ -1,190 +0,0 @@ -缓存 -=== - -### 什么是缓存 -缓存你懂的,memcached用过没?ehcache用过没?内存Map总该用过吧... - -当计算或检索一个值的代价很高,并且对同样的输入需要不止一次获取值的时候,就应当考虑使用缓存。这下懂了吧 - -换句话说,缓存就是以空间换时间 - -### 问题 -内存Map会一直保存所有添加的元素, 直到显示地移除, 所以会一直占用内存 -而Guava Cache为了限制内存使用,通常都设定为自动回收元素。 - -由于存放于内存中,Guava Cache不适合存放过大的数据,数据量较大时,可以尝试使用 Memcached 等 - -### 主要流程 -get-if-absent-compute -如果有缓存则返回;否则运算、缓存、然后返回 - -### 缓存加载 -当缓存不存在时,guava提供了多种方式来加载数据: CacheLoader、Callable、显示插入. - -###### CacheLoader - -LoadingCache是一种基于CacheLoader的缓存实现. - -```java -LoadingCache graphs = CacheBuilder.newBuilder() - .maximumSize(1000) - .expireAfterWrite(10, TimeUnit.MINUTES) - .build( - new CacheLoader() { - public Graph load(Key key) throws AnyException { - return createExpensiveGraph(key); - } - }); - -... -try { - return graphs.get(key); -} catch (ExecutionException e) { - throw new OtherException(e.getCause()); -} -``` -使用LoadingCache.get(K)方法可以获取缓存中对应的值,如果没有缓存,则会使用CacheLoader原子地加载新值. - -###### Callable - -所有类型的Guava Cache, 不管有没有自动加载功能, 都支持get(K, Callable)方法。 -get(K, Callable)方法尝试返回缓存中对应的值; 如果值不存在,则使用Callable运算,并把结果加入缓存中。 - -```java -Cache cache = CacheBuilder.newBuilder() - .maximumSize(1000) - .build(); // 看,木有CacheLoader -... -try { - cache.get(key, new Callable() { - @Override - public Value call() throws AnyException { - // 缓存不存在,就会调用call()方法计算, 并把结果加入缓存 - return doThingsTheHardWay(key); - } - }); -} catch (ExecutionException e) { - throw new OtherException(e.getCause()); -} -``` -这种方式简便地实现了"get-if-absent-compute"模式 - -###### 显式插入 - -使用cache.put(key, value)方法可以直接向缓存中插入值, 该方法会直接覆盖掉给定键之前映射的值. - - -### 缓存回收 -由于guava缓存是将数据存放于内存中,所以确定一定以及肯定没有足够的内存存放所有的数据 -guava提供了三种基本的缓存回收方式: 基于容量回收、定时回收和基于引用回收。 - -###### 基于容量回收(Size-based Eviction) - -构建Cache时,可以通过CacheBuilder.maximumSize(long)来指定缓存的容量. -在缓存容量达到指定容量时(maybe达到之前), 会尝试回收最近没有使用或总体上很少使用的缓存项. - -另外,可以通过CacheBuilder.weight(Weigher), 来指定权重函数, 权重函数将在缓存创建时计算 - -```java -LoadingCache graphs = CacheBuilder.newBuilder() - .maximumWeight(100000) - .weigher(new Weigher() { - public int weigh(Key k, Graph g) { - return g.vertices().size(); - } - }) - .build( - new CacheLoader() { - public Graph load(Key key) { // no checked exception - return createExpensiveGraph(key); - } - }); -``` - -###### 定时回收(Timed Eviction) - -CacheBuilder提供两种定时回收的方式: - -* expireAfterAccess(long, TimeUnit): 缓存在给定时间内没有被读/写访问过, 则回收. 回收顺序与基于容量回收的一样 -* expireAfterWrite(long, TimeUnit): 缓存在给定时间内没有被写访问(创建/覆盖), 则回收. - -###### 基于引用回收(Reference-based Eviction) - -如果使用week references的键/值、soft references的值,则缓存允许被垃圾回收: - -* CacheBuilder.weakKeys() -* CacheBuilder.weakValues() -* CacheBuilder.softValues() - -###### 显式移除 - -可以通过以下接口,在任何时间清除缓存 - -* Cache.invalidate(key): 单个清除 -* Cache.invalidateAll(keys): 批量清除 -* Cache.invalidateAll(): 清除所有缓存项 - -###### 移除监听器 - -CacheBuilder.removalListener(RemovalListener) -添加一个监听器,在缓存项被移除时,进行额外操作. - -```java -RemovalListener removalListener = new RemovalListener() { - - // 缓存项被移除时,RemovalListener会获取移除通知[RemovalNotification] - // 其中包含移除原因[RemovalCause]、键和值 - public void onRemoval(RemovalNotification removal) { - removal.getKey(); // 被移除的Key - removal.getValue(); // 被移除的Value - removal.getCause(); // 被移除的原因: EXPLICIT、REPLACED、COLLECTED、EXPIRED、SIZE - } -}; - -return CacheBuilder.newBuilder() - .expireAfterWrite(2, TimeUnit.MINUTES) - .removalListener(removalListener) - .build(loader); -``` - -用RemovalListeners.asynchronous(RemovalListener, Executor)把监听器装饰为异步操作 - -###### 缓存清理的时间点 - -使用CacheBuilder构建的缓存,不会“自动”执行清理和回收工作. -guava并没有建立独立线程来完成清理工作, 而是在写操作时顺带做少量的维护工作. -使用者可以建立自己的独立线程, 来主动清理缓存, 只需要调用Cache.cleanUp()就可以了 - -###### 刷新 - -LoadingCache.referesh(K) 刷新表示为键加载新值, 可以异步完成 -刷新和回收不一样,刷新时,缓存仍然可以向其他线程返回旧值,而回收时,读取线程必须等待新值加载完成. -如果刷新失败(抛出异常),缓存将保留旧值 - -CacheLoader.reload(K, V)可以扩展刷新时的行为 -CacheBuilder.refreshAfterWrite(long, TimeUnit)可以为缓存增加自动定时刷新功能 - -### 其他特性 - -###### 统计 -CacheBuilder.recordStats() 开启Guava Cache的统计功能。 -Cache.stats() 返回CacheStats对象 - -CacheStatus提供如下统计信息: -CacheStats.hitRate() 缓存命中率 -CacheStats.hitCount() 缓存命中数量 -CacheStats.averageLoadPenalty() 加载新值的平均时间,单位为纳秒 -CacheStats.evictionCount() 缓存项被回收的总数,不包括显式清除 -... - -###### Map视图 - -cache.asMap() 提供了缓存的ConcurrentMap形式 - -* asMap()包含当前所有加载到缓存的项 -* asMap().get(key)实质上等同于cache.getIfPresent(key),而且不会引起缓存项的加载 -* Cache.asMap().get(Object)方法和Cache.asMap().put(K, V)方法会重置相关缓存项的访问时间 - - ------- -[返回目录](/README.md) diff --git a/jun_java_plugins/jun_guava/doc/collections-extension-utilities.md b/jun_java_plugins/jun_guava/doc/collections-extension-utilities.md deleted file mode 100644 index 11b4636acd..0000000000 --- a/jun_java_plugins/jun_guava/doc/collections-extension-utilities.md +++ /dev/null @@ -1,81 +0,0 @@ -集合扩展工具类 -=== -有时候你需要实现自己的集合扩展。也许你想要在元素被添加到列表时增加特定的行为,或者你想实现一个Iterable,其底层实际上是遍历数据库查询的结果集。Guava提供了若干工具方法,以便让类似的工作变得更简单。 - - -#### Forwarding Decorators -针对所有类型的集合接口,Guava都提供了Forwarding抽象类以简化*装饰者模式*的使用。 -Forwarding抽象类定义了一个抽象方法:delegate(),你可以覆盖这个方法来返回被装饰对象。所有其他方法都会直接委托给delegate()。 -通过创建ForwardingXXX的子类并实现delegate()方法,可以选择性地覆盖子类的方法来增加装饰功能,而不需要自己委托每个方法。 -此外,很多集合方法都对应一个”标准方法[standardxxx]“实现,可以用来恢复被装饰对象的默认行为,比如standardAdd - -示例: -```java -class AddLoggingList extends ForwardingList { - final List delegate; // backing list - @Override - protected List delegate() { - return delegate; - } - @Override - public void add(int index, E elem) { - log(index, elem); - super.add(index, elem); - } - @Override - public boolean add(E elem) { - return standardAdd(elem); // implements in terms of add(int, E) - } - @Override - public boolean addAll(Collection c) { - return standardAddAll(c); // implements in terms of add - } -} - -``` - -目前提供了Forwarding包装类的接口有: -ForwardingCollection、ForwardingList、ForwardingSet、ForwardingSortedSet、ForwardingMap、ForwardingSortedMap、ForwardingConcurrentMap、ForwardingMapEntry、ForwardingQueue、ForwardingIterator、ForwardingListIterator、ForwardingMultiset、ForwardingMultimap、ForwardingListMultimap、ForwardingSetMultimap - -#### PeekingIterator -Iterators提供一个Iterators.peekingIterator(Iterator)方法,来把Iterator包装为PeekingIterator,这是Iterator的子类,它能让你提前查看下一次调用next()返回的元素 -注意:Iterators.peekingIterator返回的PeekingIterator不支持在peek()操作之后调用remove()方法。 - -示例:复制一个List,并去除连续的重复元素。 -```java -List result = Lists.newArrayList(); -PeekingIterator iter = Iterators.peekingIterator(source.iterator()); -while (iter.hasNext()) { - E current = iter.next(); - while (iter.hasNext() && iter.peek().equals(current)) { - // skip this duplicate element - iter.next(); - } - result.add(current); -} - -``` - -##### AbstractIterator - -AbstractIterator可以让你更方便地实现自己的Iterator - -```java -public static Iterator skipNulls(final Iterator in) { - return new AbstractIterator() { - protected String computeNext() { - while (in.hasNext()) { - String s = in.next(); - if (s != null) { - return s; - } - } - return endOfData(); - } - }; -} - -``` - ------- -[返回目录](/README.md) diff --git a/jun_java_plugins/jun_guava/doc/collections-immutable-collections.md b/jun_java_plugins/jun_guava/doc/collections-immutable-collections.md deleted file mode 100644 index d83fcfed2e..0000000000 --- a/jun_java_plugins/jun_guava/doc/collections-immutable-collections.md +++ /dev/null @@ -1,144 +0,0 @@ -不可变集合(Immutable collections) -=== -不可变集合是不可被修改的, 集合的数据项是在创建的时候提供, 并且在整个生命周期中都不可改变. - -Immutable对象有以下的优点: - -* 对不可靠的客户代码库来说,它使用安全,可以在未受信任的类库中安全的使用这些对象 -* 线程安全的:immutable对象在多线程下安全,没有竞态条件 -* 不需要支持可变性, 可以尽量节省空间和时间的开销. 所有的不可变集合实现都比可变集合更加有效的利用内存 (analysis) -* 可以被使用为一个常量,并且期望在未来也是保持不变的 - -Immutable对象是一个很好的防御编程(defensive programming)的技术实践 - -#### 问题 -JDK自带的Collections.unmodifiableXXX实现的不是真正的不可变集合,当原始集合修改后,不可变集合也发生变化。 - -```java - List lists = Lists.newArrayList("aa", "bb", "cc"); - - List unmodifiedLists = Collections.unmodifiableList(lists); - assertEquals(3, unmodifiedLists.size()); - - lists.add("dd"); - assertEquals(4, unmodifiedLists.size()); -``` - -JDK自带的Collections.unmodifiableXXX实现的不可变集合存在问题: - -* 它不安全: 如果有对象reference原始的被封装的集合类,这些方法返回的集合也就不是正真的不可改变 -* 效率低: 因为它返回的数据结构本质仍旧是原来的集合类,所以它的操作开销,包括并发下修改检查,hash table里的额外数据空间都和原来的集合是一样的。 - - -#### 方案 -com.google.common.collect.ImmutableXXX - -##### 创建Immutable集合的方法 -```java -ImmutableSet.copyOf(set); // 使用copyOf方法 -ImmutableSet.of("a", "b", "c"); // 使用of方法 -ImmutableMap.of("a", 1, "b", 2); // 使用of方法 -ImmutableSet.builder() // 使用builder - .add(new Color(0, 255, 255)) - .add(new Color(0, 191, 255)) - .build(); -``` - -##### 智能的copyOf方法 -一般来说,ImmutableXXX.copyOf(ImmutableCollection)会避免线性复杂度的拷贝操作: - -* 这个操作有可能就利用了被封装数据结构的常数复杂度的操作。但例如ImmutableSet.copyOf(list)不能在常数复杂度下实现。 -* 这样不会导致内存泄漏-例如,你有个ImmutableList imInfolist,然后你显式操作ImmutableList.copyOf(imInfolist.subList(0, 10))。这样的操作可以避免意外持有不再需要的在hugeList里元素的reference。 -* 它不会改变集合的语意-像ImmutableSet.copyOf(myImmutableSortedSet)这样的显式拷贝操作,因为在ImmutableSet里的hashCode()和equals()的含义和基于comparator的ImmutableSortedSet是不同的。 - -这些特性有助于最优化防御性编程的性能开销 - -##### asList方法 -所有的immutable集合都以asList()的形式提供了ImmutableList视图(view). -比如,你把数据放在ImmutableSortedSet,你就可以调用sortedSet.asList().get(k)来取得第k个元素的集合。 -返回的ImmutableList常常是个常数复杂度的视图,而不是一个真的拷贝。 - -##### guava中的不可变集合 - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
可变类型集合来源Guava中的不可变集合
Collection JDKImmutableCollection
ListJDKImmutableList
SetJDKImmutableSet
SortedSet/NavigableSetJDKImmutableSortedSet
MapJDKImmutableMap
SortedMapJDKImmutableSortedMap
MultisetGuavaImmutableMultiset
SortedMultisetGuavaImmutableSortedMultiset
MultimapGuavaImmutableMultimap
ListMultimapGuavaImmutableListMultimap
SetMultimapGuavaImmutableSetMultimap
BiMapGuavaImmutableBiMap
ClassToInstanceMapGuavaImmutableClassToInstanceMap
TableGuavaImmutableTable
- ------- -[返回目录](/README.md) diff --git a/jun_java_plugins/jun_guava/doc/collections-new-collection-types.md b/jun_java_plugins/jun_guava/doc/collections-new-collection-types.md deleted file mode 100644 index a7edf4c5a7..0000000000 --- a/jun_java_plugins/jun_guava/doc/collections-new-collection-types.md +++ /dev/null @@ -1,238 +0,0 @@ -Guava新增集合类型 -=== -Guava新增了一些JDK中没有的,但是被广泛使用到的新集合类型 - -* [Multiset](#multiset) -* [SortedMultiset](#sortedmultiset) -* [MultiMap](#multimap) -* [BiMap](#bimap) -* [Table](#table) -* [ClassToInstanceMap](#classtoinstancemap) -* [RangeSet](#rangeset) - -

Multiset

- -Multiset和Set的区别就是可以保存多个相同的对象。 -Multiset占据了List和Set之间的一个灰色地带:允许重复,但是不保证顺序。 -常见使用场景:Multiset有一个有用的功能,就是跟踪每种对象的数量,所以你可以用来进行数字统计。 - -Multiset接口定义的接口主要有: - -* add(E element): 向其中添加单个元素 -* add(E element,int occurrences): 向其中添加指定个数的元素 -* count(Object element): 返回给定参数元素的个数 -* remove(E element): 移除一个元素,其count值 会响应减少 -* remove(E element,int occurrences): 移除相应个数的元素 -* elementSet(): 将不同的元素放入一个Set中 -* entrySet(): 类似与Map.entrySet 返回Set。包含的Entry支持使用getElement()和getCount() -* setCount(E element ,int count): 设定某一个元素的重复次数 -* setCount(E element,int oldCount,int newCount): 将符合原有重复个数的元素修改为新的重复次数 -* retainAll(Collection c): 保留出现在给定集合参数的所有的元素 -* removeAll(Collectionc): 去除出现给给定集合参数的所有的元素 - -Guava提供了很多和JDK中的Map对应的Multiset的实现 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Map对应的MultiSet支持null值
HashMapHashMultiset
TreeMapTreeMultiSet
LinkedHashMapLinkedHashMultiset
ConcurrentHashMapConcurrentHashMultiset
ImmutableMapImmutableMultiset
- -

SortedMultiset

- -SortedMultiset是Multiset 接口的变种,它支持高效地获取指定范围的子集。 -比如,你可以用 latencies.subMultiset(0,BoundType.CLOSED, 100, BoundType.OPEN).size()来统计你的站点中延迟在100毫秒以内的访问,然后把这个值和latencies.size()相比,以获取这个延迟水平在总体访问中的比例。 - -TreeMultiset实现SortedMultiset接口。 - -

MultiMap

- -经常会遇到这种结构 Map>或Map> -Multimap可以很容易地把一个键映射到多个值。换句话说,Multimap是把键映射到任意多个值的一种方式。 - -可以用两种方式思考Multimap的概念: - -* "键-单个值映射"的集合: a->1, a->2, a->4, b->3, c->5 -* "键-值集合映射"的映射: a->[1,2,4], b->3, c->5 - -一般情况下都会使用ListMultimap或SetMultimap接口,它们分别把键映射到List或Set。 -Multimap.get(key)以集合形式返回键所对应的值视图, 即使没有任何对应的值,也会返回空集合。 -对值视图集合进行的修改最终都会反映到底层的Multimap。 - -##### 修改Multimap的方法有: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
方法签名描述等价于
put(K, V)添加键到单个值的映射multimap.get(key).add(value)
putAll(K, Iterable)依次添加键到多个值的映射Iterables.addAll(multimap.get(key), values)
remove(K, V)移除键到值的映射;如果有这样的键值并成功移除,返回true。multimap.get(key).remove(value)
removeAll(K)清除键对应的所有值,返回的集合包含所有之前映射到K的值,但修改这个集合就不会影响Multimap了。multimap.get(key).clear()
replaceValues(K, Iterable)清除键对应的所有值,并重新把key关联到Iterable中的每个元素。返回的集合包含所有之前映射到K的值。multimap.get(key).clear(); Iterables.addAll(multimap.get(key), values)
- -##### Multimap不是Map -Multimap不是Map> - -* Multimap.get(key)总是返回非null、但是可能空的集合。这并不意味着Multimap为相应的键花费内存创建了集合,而只是提供一个集合视图方便你为键增加映射值 -* 如果你更喜欢像Map那样,为Multimap中没有的键返回null,请使用asMap()视图获取一个Map> -* 当且仅当有值映射到键时,Multimap.containsKey(key)才会返回true -* Multimap.entries()返回Multimap中所有”键-单个值映射”——包括重复键。如果你想要得到所有”键-值集合映射”,请使用asMap().entrySet()。 -* Multimap.size()返回所有”键-单个值映射”的个数,而非不同键的个数。要得到不同键的个数,请改用Multimap.keySet().size()。 - -

BiMap

- -BiMap提供了key和value双向关联的数据结构。 - -* 可以用inverse()反转BiMap的键值映射, 反转的map不是新的map对象,它实现了一种视图关联,这样你对于反转后的map的所有操作都会影响原先的map对象 -* 保证值是唯一的,因此 values()返回Set而不是普通的Collection -* 如果你想把键映射到已经存在的值,会抛出IllegalArgumentException异常, 使用BiMap.forcePut(key, value)可强制替换 - -```java -BiMap logfileMap = HashBiMap.create(); -BiMap filelogMap = logfileMap.inverse(); -``` - -

Table

- -当我们需要多个索引的数据结构的时候,通常情况下,我们只能用这种丑陋的Map>来实现。为此Guava提供了一个新的集合类型-Table集合类型,来支持这种数据结构的使用场景。 - -##### Table的视图 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
视图描述
rowMap()用Map>表现Table
rowKeySet()rowKeySet()返回”行”的集合Set
row(r) 用Map返回给定”行”的所有列,对这个map进行的写操作也将写入Table中。
columnMap()用Map>表现Table
columnKeySet()columnKeySet()返回”列”的集合Set
column(r) 用Map返回给定”列”的所有行,对这个map进行的写操作也将写入Table中。
cellSet()用元素类型为Table.Cell的Set表现Table。Cell类似于Map.Entry,但它是用行和列两个键区分的。
-注: 基于列的访问会比基于的行访问稍微低效点 - -Table有如下实现 - - - - - - - - - - - - - - - - - - - - - -
实现描述
HashBasedTable本质上用HashMap>实现
TreeBasedTable本质上用TreeMap>实现
ImmutableTable本质上用ImmutableMap>实现;注:ImmutableTable对稀疏或密集的数据集都有优化。
ArrayTable要求在构造时就指定行和列的大小,本质上由一个二维数组实现,以提升访问速度和密集Table的内存利用率。
- -

ClassToInstanceMap

- -ClassToInstanceMap\ 相当于 Map, B>, 它的键是类型,而值是符合键所指类型的对象。 -ClassToInstanceMap额外声明了两个方法:T getInstance(Class) 和T putInstance(Class, T),从而避免强制类型转换,同时保证了类型安全。 - - -

RangeSet

- -RangeSet描述了一组不相连的、非空的区间。当把一个区间添加到可变的RangeSet时,所有相连的区间会被合并,空区间会被忽略。 -例如: -```java -RangeSet rangeSet = TreeRangeSet.create(); -rangeSet.add(Range.closed(1, 10)); // {[1, 10]} -rangeSet.add(Range.closedOpen(11, 15)); // 不相连的区间: {[1, 10], [11, 15)} -rangeSet.add(Range.closedOpen(15, 20)); // 相连的区间; {[1, 10], [11, 20)} -rangeSet.add(Range.openClosed(0, 0)); // 空区间; {[1, 10], [11, 20)} -rangeSet.remove(Range.open(5, 10)); // 分割[1, 10]; {[1, 5], [10, 10], [11, 20)} -``` - -RangeMap描述了"不相交的、非空的区间"到特定值的映射。和RangeSet不同,RangeMap不会合并相邻的映射,即便相邻的区间映射到相同的值。例如: -```java -RangeMap rangeMap = TreeRangeMap.create(); -rangeMap.put(Range.closed(1, 10), "foo"); // {[1, 10] => "foo"} -rangeMap.put(Range.open(3, 6), "bar"); // {[1, 3] => "foo", (3, 6) => "bar", [6, 10] => "foo"} -rangeMap.put(Range.open(10, 20), "foo"); // {[1, 3] => "foo", (3, 6) => "bar", [6, 10] => "foo", (10, 20) => "foo"} -rangeMap.remove(Range.closed(5, 11)); // {[1, 3] => "foo", (3, 5) => "bar", (11, 20) => "foo"} -``` - ------- -[返回目录](/README.md) \ No newline at end of file diff --git a/jun_java_plugins/jun_guava/doc/collections-utility-classes.md b/jun_java_plugins/jun_guava/doc/collections-utility-classes.md deleted file mode 100644 index da1eba60be..0000000000 --- a/jun_java_plugins/jun_guava/doc/collections-utility-classes.md +++ /dev/null @@ -1,294 +0,0 @@ -强大的集合工具类 -=== -Guava提供了很多类似java.util.Collections的静态工具类 - -Guava中工具类与集合的对应关系如下: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
集合接口来自于JDK/Guava对应的Guava工具类
CollectionJDKCollections2
ListJDKLists
SetJDKSets
SortedSetJDKSets
MapJDKMaps
SortedMapJDKMaps
QueueJDKQueues
MultisetGuavaMultisets
MultimapGuavaMultimaps
BiMapGuavaMaps
TableGuavaTables
- - -* [静态工厂方法](#static-constructor) -* [Iterables](#iterables) -* [Lists](#lists) -* [Sets](#sets) -* [Maps](#maps) -* [Multisets](#multisets) -* [Multimaps](#multimaps) -* [Tables](#tables) - -

Static Constructor

- -JDK7之前构造一个集合 -> List list = new ArrayList(); - -Guava提供了能够推断泛型的静态工厂方法 -> List list = Lists.newArrayList(); -> List theseElements = Lists.newArrayList("alpha", "beta", "gamma"); //可以直接初始化的静态构造方法 -> List exactly100 = Lists.newArrayListWithCapacity(100); //更具可读性的工厂方法 -> List approx100 = Lists.newArrayListWithExpectedSize(100); //更具可读性的工厂方法 -> Set set = Sets.newHashSet(); -> Set approx100Set = Sets.newHashSetWithExpectedSize(100); - -

Iterables

- -相比于Collection, Guava更偏向于提供Iterable类型, 原因就不写了,网上可以找到 -大部分的方法都在Iterators和FluentIterable中, 后者提供了很多链式操作 - -Iterators常用方法 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
方法描述参考
concat(Iterable)串联多个iterables的懒加载视图concat(Iterable...)
frequency(Iterable, Object)返回对象在iterable中出现的次数Collections.frequency(Collection, Object)
partition(Iterable, int)把iterable按指定大小分割,得到的子集都不能进行修改操作Lists.partition(List, int); paddedPartition(Iterable, int)
getFirst(Iterable, T default)返回iterable的第一个元素,若iterable为空则返回默认值Iterable.iterator().next(); FluentIterable.first()
getLast(Iterable)返回iterable的最后一个元素,若iterable为空则抛出NoSuchElementExceptiongetLast(Iterable, T default); FluentIterable.last()
elementsEqual(Iterable, Iterable)如果两个iterable中的所有元素相等且顺序一致,返回trueList.equals(Object)
unmodifiableIterable(Iterable)返回iterable的不可变视图Collections.unmodifiableCollection(Collection)
limit(Iterable, int)返回一个尽可能达到指定个数的iterableFluentIterable.limit(int)
getOnlyElement(Iterable)获取iterable中唯一的元素,如果iterable为空或有多个元素,则失败getOnlyElement(Iterable, T default)
- -Iterators中也有很多和Collections相似的工具方法,比如addAll、removeAll、retainAll、contains、size、isEmpty等 - -

Lists

- -```java -// 静态工厂方法 -Lists.newArrayList(); -Lists.newArrayList(1, 2, 3); -Lists.newArrayList(Sets.newHashSet(1, 2, 3)); -Lists.newArrayListWithCapacity(10); -Lists.newArrayListWithExpectedSize(10); - -Lists.newLinkedList(); -Lists.newLinkedList(Sets.newHashSet(1, 2, 3)); - -// 其他工具方法 -Lists.partition(Lists.newArrayList(1, 2, 3, 4, 5), 2); -Lists.reverse(Lists.newArrayList(1, 2, 3, 4, 5)); -``` - -

Sets

- -```java -// 静态工厂方法 -Sets.newHashSet(); -Sets.newHashSet(1, 2, 3); -Sets.newHashSetWithExpectedSize(10); -Sets.newHashSet(Lists.newArrayList(1, 2, 3)); - -Sets.newLinkedHashSet(); -Sets.newLinkedHashSetWithExpectedSize(10); -Sets.newLinkedHashSet(Lists.newArrayList(1, 2, 3)); - -Sets.newTreeSet(); -Sets.newTreeSet(Lists.newArrayList(1, 2, 3)); -Sets.newTreeSet(Ordering.natural()); - -// 集合运算(返回SetView) -Sets.union(Sets.newHashSet(1, 2, 3), Sets.newHashSet(4, 5, 6)); // 取并集[1,2,3,4,5,6] -Sets.intersection(Sets.newHashSet(1, 2, 3), Sets.newHashSet(3, 4, 5)); // 取交集[3] -Sets.difference(Sets.newHashSet(1, 2, 3), Sets.newHashSet(3, 4, 5)); // 只在set1, 不在set2[1,2] -Sets.symmetricDifference(Sets.newHashSet(1, 2, 3), Sets.newHashSet(3, 4, 5)); // 交集取反[1,2,4,5] - -// 其他工具方法 -Sets.cartesianProduct(Lists.newArrayList(Sets.newHashSet(1, 2), Sets.newHashSet(3, 4))); // 返回所有集合的笛卡尔积 -Sets.powerSet(Sets.newHashSet(1, 2, 3)); // 返回给定集合的所有子集 -``` - -

Maps

- -Maps除了类似Lists、Sets一样提供基本的静态工厂方法外,还提供了很多其他有意思的方法 - -#### uniqueIndex - -场景:有一组对象,它们在某个属性上分别有独一无二的值,而我们希望能够按照这个属性值查找对象 - -> Maps.uniqueIndex(Iterable,Function) -> 这个方法返回一个Map,键为Function返回的属性值,值为Iterable中相应的元素,因此我们可以反复用这个Map进行查找操作。 - -示例: -```java -ImmutableMap stringsByIndex = Maps.uniqueIndex(strings, new Function () { - public Integer apply(String string) { - return string.length(); - } -}); - -``` -如果索引值不是独一无二的,请参见下面的Multimaps.index方法。 - -#### difference - -Maps.difference(Map, Map)用来比较两个Map以获取所有不同点, 该方法返回MapDifference对象 - -```java -Map left = ImmutableMap.of("a", 1, "b", 2, "c", 3); -Map right = ImmutableMap.of("b", 2, "c", 4, "d", 5); -MapDifference diff = Maps.difference(left, right); - -diff.entriesInCommon(); // {"b" => 2}, 两个Map中都有的映射项,包括键与值 -diff.entriesDiffering(); // {"c" => (3, 4)}, 键相同但是值不同的映射项。 - // 返回的Map的值类型为MapDifference.ValueDifference,以表示左右两个不同的值 -diff.entriesOnlyOnLeft(); // {"a" => 1}, 键只存在于左边Map的映射项 -diff.entriesOnlyOnRight(); // {"d" => 5}, 键只存在于右边Map的映射项 - -``` - -

Multisets

- -```java -containsOccurrences(Multiset sup, Multiset sub); //对任意o,如果sub.count(o)<=super.count(o),返回true -removeOccurrences(Multiset removeFrom, Multiset toRemove); //对toRemove中的重复元素,仅在removeFrom中删除相同个数 -retainOccurrences(Multiset removeFrom, Multiset toRetain); //修改removeFrom,以保证任意o都符合removeFrom.count(o)<=toRetain.count(o) -intersection(Multiset, Multiset); //返回两个multiset的交集 -copyHighestCountFirst(Multiset); //返回Multiset的不可变拷贝,并将元素按重复出现的次数做降序排列 -unmodifiableMultiset(Multiset); //返回Multiset的只读视图 -unmodifiableSortedMultiset(SortedMultiset); //返回SortedMultiset的只读视图 - -``` - -

Multimaps

- -#### index -作为Maps.uniqueIndex的兄弟方法,Multimaps.index(Iterable, Function)通常针对的场景是:有一组对象,它们有共同的特定属性,我们希望按照这个属性的值查询对象,但属性值不一定是独一无二的。 - -#### invertFrom -鉴于Multimap可以把多个键映射到同一个值,也可以把一个键映射到多个值,反转Multimap也会很有用。Guava 提供了invertFrom(Multimap toInvert, Multimap dest)做这个操作,并且你可以自由选择反转后的Multimap实现。 -> TreeMultimap inverse = Multimaps.invertFrom(multimap, TreeMultimap.create()); - -#### forMap -forMap方法把Map包装成SetMultimap, 与Multimaps.invertFrom结合使用,可以把多对一的Map反转为一对多的Multimap。 -```java -Map map = ImmutableMap.of("a", 1, "b", 1, "c", 2); -SetMultimap multimap = Multimaps.forMap(map); -// multimap maps ["a" => {1}, "b" => {1}, "c" => {2}] -Multimap inverse = Multimaps.invertFrom(multimap, HashMultimap. create()); -// inverse maps [1 => {"a", "b"}, 2 => {"c"}] - -``` - -

Tables

- -#### customTable - -Tables.newCustomTable(Map, Supplier)允许你指定Table用什么样的map实现行和列。 -```java -// use LinkedHashMaps instead of HashMaps -Table table = Tables.newCustomTable( - Maps.>newLinkedHashMap(), - new Supplier> () { - public Map get() { - return Maps.newLinkedHashMap(); - } - } -); - -``` - -#### transpose - -transpose(Table)方法允许你把Table转置成Table。例如,如果你在用Table构建加权有向图,这个方法就可以把有向图反转。 - ------- -[返回目录](/README.md) \ No newline at end of file diff --git a/jun_java_plugins/jun_guava/doc/concurrency-listenablefuture.md b/jun_java_plugins/jun_guava/doc/concurrency-listenablefuture.md deleted file mode 100644 index 07d09746e0..0000000000 --- a/jun_java_plugins/jun_guava/doc/concurrency-listenablefuture.md +++ /dev/null @@ -1,93 +0,0 @@ -并发编程之ListenableFuture -=== - -### 背景 -在并发编程方面,JDK提供了Future, 但是使用起来不是很方便,guava提供了ListenableFuture以简化并发的编写. -ListenableFuture继承自Future. - -### 接口 - -```java -interface ListenableFuture extends Future -void addListener(Runnable listener, Executor executor) -``` - -传统的Future: 通过异步的方式计算返回结果,Future是运行中的多线程的一个引用句柄. -ListenableFuture: 允许注册回调方法, 在运算(多线程执行)完成的时候,使用指定的Executor执行指定的Runnable. - -### 添加回调 - -guava提供了以下几种方式添加回调 - -* ListenableFuture接口上的addLister(Runnbale, Executor) -* Futures.addCallback(ListenableFuture, FutureCallback, Executor) -* Futures.addCallback(ListenableFuture, FutureCallback) // 这种情况默认使用MoreExecutors.sameThreadExecutor()线程池 - -FutureCallback采用轻量级的设计, 只需要实现以下两个方法 - -* onSuccess(V) // 在Future成功的时候执行 -* onFailure(Throwable) // 在Future失败的时候执行 - -### 创建ListenableFuture - -传统JDK中创建Future的方式: - -```java -Executors.newFixedThreadPool(10).submit(Callable); -``` - -guava中创建ListenableFuture的方式: - -```java -MoreExecutors.listeningDecorator(ExecutorService).submit(Callable); -``` - -完整的ListenableFuture使用示例: - -```java -// 创建ListeningExecutorService -ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10)); - -// 添加执行操作 -ListenableFuture explosion = service.submit(new Callable() { - public Explosion call() { - return pushBigRedButton(); - } -}); - -// 添加回调 -Futures.addCallback(explosion, new FutureCallback() { - // 操作执行完成后,执行onSuccess - public void onSuccess(Explosion explosion) { - walkAwayFrom(explosion); - } - public void onFailure(Throwable thrown) { - battleArchNemesis(); // escaped the explosion! - } -}); -``` - -当然,还有其他方式来创建,比如: - -```java -// 类似JDK的FutureTask模式 -ListenableFutureTask.create(Callable); - -// 将其他API提供的Future转换为ListenableFuture -JdkFutureAdapters.listenInPoolThread(Future); -``` - -### 使用 - -guava还提供了一些支持链式操作的API - -```java -Futures.transform(ListenableFuture, AsyncFunction, Executor); -Futures.transform(ListenableFuture, Function, Executor); -Futures.allAsList(Iterable>); -Futures.successfulAsList(Iterable>); -``` - - ------- -[返回目录](/README.md) \ No newline at end of file diff --git a/jun_java_plugins/jun_guava/doc/concurrency-service.md b/jun_java_plugins/jun_guava/doc/concurrency-service.md deleted file mode 100644 index cffcf21c74..0000000000 --- a/jun_java_plugins/jun_guava/doc/concurrency-service.md +++ /dev/null @@ -1,5 +0,0 @@ -并发编程之Service框架 -=== - ------- -[返回目录](/README.md) \ No newline at end of file diff --git a/jun_java_plugins/jun_guava/doc/eventbus.md b/jun_java_plugins/jun_guava/doc/eventbus.md deleted file mode 100644 index e1f31f19ef..0000000000 --- a/jun_java_plugins/jun_guava/doc/eventbus.md +++ /dev/null @@ -1,164 +0,0 @@ -事件总线EventBus -=== - -### 背景 - -JDK中通过Observer接口和Observable类实现观察者模式, Observer对象是观察者,Observable对象是被观察者. - -实现一个简单的观察者模式有以下几步: - -1. 创建被观察者, 继承自java.util.Observable类 -2. 创建观察者, 实现java.util.Observer接口 -3. 在观察者中实现void update(java.util.Observable observable, java.lang.Object o)方法 -4. 在被观察者对象上添加观察者Observable.addObserver(observer) -5. 当被观察事件发生时,执行以下代码 -6. setChanged(); // 内部标志,注明数据发生了变化 -7. notifyObservers(); // 调用观察者对象列表中所有的Observer的update()方法, 通知它们数据变化了 - -这种方式是通过发布者和订阅者之间的显式注册实现的. -guava的EventBus就是为了取代这种显示注册方式,使组件间有更好的解耦. -EventBus不适用于进程间通信。 - -### 示例 - -消息封装类: 任意的Java对象均可 -```java -public class LogEvent { - - private String log; - - // setter、getter -} -``` - -消息接收类: 任意的Java对象均可, 只需要在接收方法上添加注解@Subscribe即可 -```java -public class LogEventListener { - - @Subscribe - public void listen(LogEvent log) { - // handle log - } - -} -``` - -消息发布 -```java -// 事件总线 -EventBus eventBus = new EventBus(); -// 事件监听者 -LogEventListener logEventListener = new LogEventListener(); -// 注册监听 -eventBus.register(logEventListener) -// 发布消息 -eventBus.post(new LogEvent("测试")); -``` - -### 解析 - -EventBus中主要包括以下几个角色: - -* 事件: 可以向事件总线发布的消息 -* 监听者: 提供一个处理方法, 通过参数声明希望接受和处理事件对象,实现自己的处理逻辑 -* 事件总线: 可以理解为消息传输的渠道,所有在当前事件总线上注册了的监听者都会收到来自于当前事件总线、与监听者所声明的期望类型一致(支持继承关系)的消息 - -同步发布事件: EventBus.post(Object) -异步发布事件: AsyncEventBus.post(Object) - -guava并未将EventBus设计为单例, 所以可以根据实际情况使用 - -### DeadEvent - -EventBus会将所有发布后,没有监听者处理的事件包装为DeadEvent, 可以通过监听该类型的消息来检测哪些消息未指明监听者 - -### 监听多个消息 -EventBus中,可以支持同一个监听者监听多个消息,只需要在每个订阅消息的方法上加上@Subscribe注解即可 - -```java - @Subscribe - public void listenInteger(Integer event) { - lastInteger = event; - System.out.println("event Integer:"+lastInteger); - } - - @Subscribe - public void listenLong(Long event) { - lastLong = event; - System.out.println("event Long:"+lastLong); - } -``` - -### 单例使用 - -在简单情况下,可以将EventBus声明为全局唯一的单例, 并可以通过Spring完成自动注册, 这样将进一步简化使用 - -示例: - -EventBus工厂 -```java -public class EventBusFactory { - - private static final EventBusFactory factory = new EventBusFactory(); - - private final EventBus eventBus; - - private EventBusFactory() { - eventBus = new AsyncEventBus("AsyncEventBus", Executors.newFixedThreadPool(5)); - } - - public static final EventBusFactory getDefault() { - return factory; - } - - public EventBus eventBus() { - return eventBus; - } - -} -``` - -通过spring自动注册 -```java -@Service -public class EventBusPostProcessor implements BeanPostProcessor { - - @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { - return bean; - } - - @Override - public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { - // for each method in the bean - Method[] methods = bean.getClass().getMethods(); - for (Method method : methods) { - // check the annotations on that method - Annotation[] annotations = method.getAnnotations(); - for (Annotation annotation : annotations) { - // if it contains the Subscribe annotation - if (annotation.annotationType().equals(Subscribe.class)) { - // 检查到bean声明了Guava EventBus Subscribe注解, 则自动注册到全局的EventBus上 - EventBusFactory.getDefault().eventBus().register(bean); - LOGGER.info("Bean " + beanName + " was subscribed to EventBus"); - // we only need to register once - return bean; - } - } - } - - return bean; - } - -} -``` - -发布消息 -```java -EventBusFactory.getDefault().eventBus().post(new LogEvent(log)); -``` - -通过这种方式,只需要编写监听者即可,无需关心注册 - ------- -[返回目录](/README.md) \ No newline at end of file diff --git a/jun_java_plugins/jun_guava/doc/functional-idioms.md b/jun_java_plugins/jun_guava/doc/functional-idioms.md deleted file mode 100644 index c8df3071b5..0000000000 --- a/jun_java_plugins/jun_guava/doc/functional-idioms.md +++ /dev/null @@ -1,62 +0,0 @@ -函数式 -=== - -### 注意!注意!注意! - -Java中一切皆对象,唯函数不算! -Java 7以前, Java中只能通过笨拙冗长的匿名类来达到近似函数式编程的效果。 (Java 8引入了Lambda表达式) - -> 过度使用Guava函数式编程会导致冗长、混乱、可读性差而且低效的代码。 -> 如果你想通过函数式风格达成一行代码,致使这行代码长到荒唐,Guava团队会泪流满面。 -> 请务必确保,当使用Guava函数式的时候,用传统的命令式做同样的事情不会更具可读性。 -> 总之,不要盲目使用函数式!!! - -比较一下这种场景: - -函数式 -```java -Function lengthFunction = new Function() { - public Integer apply(String string) { - return string.length(); - } -}; -Predicate allCaps = new Predicate() { - public boolean apply(String string) { - return CharMatcher.JAVA_UPPER_CASE.matchesAllOf(string); - } -}; -Multiset lengths = HashMultiset.create( - Iterables.transform(Iterables.filter(strings, allCaps), lengthFunction)); -``` - -函数式2 -```java -Multiset lengths = HashMultiset.create( - FluentIterable.from(strings) - .filter(new Predicate() { - public boolean apply(String string) { - return CharMatcher.JAVA_UPPER_CASE.matchesAllOf(string); - } - }) - .transform(new Function() { - public Integer apply(String string) { - return string.length(); - } - })); -``` - -命令式 -```java -Multiset lengths = HashMultiset.create(); -for (String string : strings) { - if (CharMatcher.JAVA_UPPER_CASE.matchesAllOf(string)) { - lengths.add(string.length()); - } -} -``` - -### Functions[函数]和Predicates[断言] - - ------- -[返回目录](/README.md) diff --git a/jun_java_plugins/jun_guava/doc/hash.md b/jun_java_plugins/jun_guava/doc/hash.md deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/jun_java_plugins/jun_guava/doc/io.md b/jun_java_plugins/jun_guava/doc/io.md deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/jun_java_plugins/jun_guava/doc/math.md b/jun_java_plugins/jun_guava/doc/math.md deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/jun_java_plugins/jun_guava/doc/networking.md b/jun_java_plugins/jun_guava/doc/networking.md deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/jun_java_plugins/jun_guava/doc/primitives.md b/jun_java_plugins/jun_guava/doc/primitives.md deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/jun_java_plugins/jun_guava/doc/ranges.md b/jun_java_plugins/jun_guava/doc/ranges.md deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/jun_java_plugins/jun_guava/doc/reflection.md b/jun_java_plugins/jun_guava/doc/reflection.md deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/jun_java_plugins/jun_guava/doc/strings.md b/jun_java_plugins/jun_guava/doc/strings.md deleted file mode 100644 index 4a38bb3498..0000000000 --- a/jun_java_plugins/jun_guava/doc/strings.md +++ /dev/null @@ -1,15 +0,0 @@ -字符串工具类 -=== - -### 连接器(Joiner) - -### 拆分器(Splitter) - -### 字符串匹配(CharMatcher) - -### 字符集(Charsets) - -### 大小写格式(CaseFormat) - ------- -[返回目录](/README.md) \ No newline at end of file diff --git a/jun_java_plugins/jun_guava/guava.md b/jun_java_plugins/jun_guava/guava.md deleted file mode 100644 index 7325a5d0a6..0000000000 --- a/jun_java_plugins/jun_guava/guava.md +++ /dev/null @@ -1,29 +0,0 @@ - -        ImmutableList list = ImmutableList.of("1", "2"); -        List lists = Lists.newArrayList("abc","abcd","123"); -        System.err.println(Joiner.on(",").join(lists)); -        Map map = Maps.newHashMap(); -        Set set = Sets.newHashSet("1", "2"); -        ImmutableMap map2 = ImmutableMap.of("key1", "value1", "key2", "value2"); -        System.err.println(Joiner.on(",").withKeyValueSeparator("=").join(map2)); -//        System.err.println(map2.get("key2")); -//        map.forEach((key,value)->{System.out.println(key+""+value);}); -        -        Multimap m = ArrayListMultimap.create(); -        m.put("a", "1"); -        m.put("a", "2"); -        m.forEach((key,value)->{System.out.println(key+"-"+value);}); -//        System.err.println(m.get("a")); -        -        Stopwatch sw = Stopwatch.createStarted(); -        String str = "1-2-3-4-5-6"; -        System.err.println(Splitter.on("-").splitToList(str)); -        String str2 = "xiaoming=11,xiaohong=23"; -        System.err.println(Splitter.on(",").withKeyValueSeparator("=").split(str2)); -        Strings.isNullOrEmpty(""); -//        List list = Splitter.on("-").splitToList(str); -        long time = sw.elapsed(TimeUnit.MILLISECONDS); -        System.err.println(time); -        Thread.currentThread().sleep(500); -        time = sw.elapsed(TimeUnit.MILLISECONDS); -        System.err.println(time); \ No newline at end of file diff --git a/jun_java_plugins/jun_guava/pom.xml b/jun_java_plugins/jun_guava/pom.xml deleted file mode 100644 index 97856a801b..0000000000 --- a/jun_java_plugins/jun_guava/pom.xml +++ /dev/null @@ -1,77 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_guava - 1.0 - jar - - - UTF-8 - 1.8 - 1.8 - - - - - - - - - junit - junit - 4.8.1 - test - - - com.google.guava - guava - 16.0.1 - - - - javax.servlet - javax.servlet-api - 3.1.0 - provided - - - mysql - mysql-connector-java - 5.1.40 - - - - - - - jdk-1.8 - - true - 1.8 - - - 1.8 - 1.8 - 1.8 - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.0 - - 1.8 - 1.8 - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_guava/src/main/java/com/jun/plugin/guava/GuavaCollections2.java b/jun_java_plugins/jun_guava/src/main/java/com/jun/plugin/guava/GuavaCollections2.java deleted file mode 100644 index 633e78c070..0000000000 --- a/jun_java_plugins/jun_guava/src/main/java/com/jun/plugin/guava/GuavaCollections2.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.jun.plugin.guava; - -import static java.lang.System.out; - -import com.google.common.base.Predicates; -import com.google.common.collect.Collections2; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; - -/** - * Class whose sole reason for existence is to demonstrate Guava's Collections2 - * class. - * - * @author Dustin - * @see http://marxsoftware.blogspot.com/2011/10/filtering-and-transforming-java.html - */ -public class GuavaCollections2 { - - /** - * Provides a Set of Strings. - * - * @return Set of strings representing some programming languages. - */ - private static Set buildSetStrings() { - final Set strings = new HashSet(); - strings.add("Java"); - strings.add("Groovy"); - strings.add("Jython"); - strings.add("JRuby"); - strings.add("Python"); - strings.add("Ruby"); - strings.add("Perl"); - strings.add("C"); - strings.add("C++"); - strings.add("C#"); - strings.add("Pascal"); - strings.add("Fortran"); - strings.add("Cobol"); - strings.add("Scala"); - strings.add("Clojure"); - strings.add("Basic"); - strings.add("PHP"); - strings.add("Flex/ActionScript"); - strings.add("JOVIAL"); - return strings; - } - - /** - * Demonstrate Guava's Collections2.filter method. Filter String beginning - * with letter 'J'. - */ - public static void demonstrateFilter() { - printHeader("Collections2.filter(Collection,Predicate): 'J' Languages"); - final Set strings = buildSetStrings(); - out.println("\nOriginal Strings (pre-filter):\n\t" + strings); - final Collection filteredStrings = Collections2.filter(strings, - Predicates.containsPattern("^J")); - out.println("\nFiltered Strings:\n\t" + filteredStrings); - out.println("\nOriginal Strings (post-filter):\n\t" + strings); - } - - /** - * Demonstrate Guava's Collections2.transform method. Transform input - * collection's entries to uppercase form. - */ - public static void demonstrateTransform() { - printHeader("Collections2.transform(Collection,Function): Uppercase"); - final Set strings = buildSetStrings(); - out.println("\nOriginal Strings (pre-transform):\n\t" + strings); - final Collection transformedStrings = Collections2.transform( - strings, new UpperCaseFunction()); - out.println("\nTransformed Strings:\n\t" + transformedStrings); - out.println("\nOriginal Strings (post-transform):\n\t" + strings); - } - - /** - * Print a separation header including the provided text. - * - * @param headerText - * Text to be included in separation header. - */ - private static void printHeader(final String headerText) { - out.println("\n=========================================================="); - out.println("== " + headerText); - out.println("=========================================================="); - } - - /** - * Main function for demonstrating Guava's Collections2 class. - * - * @param arguments - */ - public static void main(final String[] arguments) { - demonstrateFilter(); - demonstrateTransform(); - } - -} diff --git a/jun_java_plugins/jun_guava/src/main/java/com/jun/plugin/guava/UpperCaseFunction.java b/jun_java_plugins/jun_guava/src/main/java/com/jun/plugin/guava/UpperCaseFunction.java deleted file mode 100644 index 5938204594..0000000000 --- a/jun_java_plugins/jun_guava/src/main/java/com/jun/plugin/guava/UpperCaseFunction.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.jun.plugin.guava; - -import com.google.common.base.Function; - -/** - * Simple Guava Function that converts provided object's toString() - * representation to upper case. - * - * @author Dustin - */ -public class UpperCaseFunction implements Function { - public Object apply(Object f) { - return f.toString().toUpperCase(); - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/BaseTest.java b/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/BaseTest.java deleted file mode 100644 index 5fcb129b66..0000000000 --- a/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/BaseTest.java +++ /dev/null @@ -1,245 +0,0 @@ -package com.jun.plugin.guava; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.nio.charset.Charset; -import java.util.Arrays; - -import org.junit.Test; - -import com.google.common.base.Charsets; -import com.google.common.base.Defaults; -import com.google.common.base.Function; -import com.google.common.base.Functions; -import com.google.common.base.Joiner; -import com.google.common.base.Objects; -import com.google.common.base.Preconditions; -import com.google.common.base.Predicate; -import com.google.common.base.Predicates; -import com.google.common.base.Splitter; -import com.google.common.base.Strings; -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; - -public class BaseTest { - - @Test - public void charSetsAndDefaults() { - // Here's some charsets - Charset utf8 = Charsets.UTF_8; - assertTrue(utf8.canEncode()); - - // Primitive defaults: - Integer defaultValue = Defaults.defaultValue(int.class); - assertEquals(0, defaultValue.intValue()); - } - - - @Test - public void joinSomeStrings() { - ImmutableSet strings = ImmutableSet.of("A", "B", "C"); - - String joined = Joiner.on(":").join(strings); - assertEquals("A:B:C", joined); - } - - @Test - public void splitSomeStrings() { - String string = "A:B:C"; - - String[] parts = string.split(":"); // the old way - String backTogether = Joiner.on(":").join(parts); - assertEquals(string, backTogether); - - String gorbleString = ": A::: B : C :::"; - Iterable gorbleParts = Splitter.on(":").omitEmptyStrings() - .trimResults().split(gorbleString); - String gorbleBackTogether = Joiner.on(":").join(gorbleParts); - assertEquals(string, gorbleBackTogether); // A:B:C - } - - @Test - public void moreFunWithStrings() { - assertNull(Strings.emptyToNull("")); - assertEquals("", Strings.nullToEmpty(null)); - assertTrue(Strings.isNullOrEmpty("")); // About the only thing we ever - // used in commons-lang? :) - assertEquals("oioioi", Strings.repeat("oi", 3)); - - String a = "Too short "; - String b = a + " "; - assertEquals("Too short ", - Strings.padEnd("Too short", a.length(), ' ')); - assertFalse("Too short " - .equals(Strings.padEnd(b, a.length(), ' '))); - - assertEquals(a, Strings.commonPrefix(a, b)); - assertEquals(" ", Strings.commonSuffix(a, b)); - } - - // Some customers - Customer bob = new Customer(1, "Bob"); - Customer lisa = new Customer(2, "Lisa"); - Customer stephen = new Customer(3, "Stephen"); - Customer ken = new Customer(null, "Ken"); - - @Test - public void toStringsAndHashcodes() { - Object[] bobAndLisa = new Object[] { bob, lisa }; - - // Make some hashcode! - int hashCode = Objects.hashCode(bob, lisa); - - assertEquals(Arrays.hashCode(bobAndLisa), hashCode); - - // Build toString method - String string = Objects.toStringHelper(bob).add("name", bob.getName()) - .add("id", bob.getId()).toString(); - assertEquals("Customer{name=Bob, id=1}", string); - } - - @Test(expected = NullPointerException.class) - public void needAnIntegerWhichIsNeverNull() { - Integer defaultId = 0; - Integer kensId = ken.getId() != null ? ken.getId() : defaultId; - assertEquals(kensId, defaultId); - // this one does not throw! - - int kensId2 = Objects.firstNonNull(ken.getId(), null); - assertEquals(0, kensId2); - // But the above does! That means that at least one parameter of - // Objects.firstNonNull should be nonNull - } - - @Test(expected = IllegalArgumentException.class) - public void somePreconditions() { - // Pretend this is a constructor: - Preconditions.checkNotNull(lisa.getId()); // Will not throw NPE - assertEquals(Preconditions.checkNotNull(lisa.getId()), - Integer.valueOf(2)); - - Preconditions.checkState(!lisa.isSick()); // Will throw - // IllegalStateException - Preconditions.checkArgument(lisa.getAddress() != null, - "We couldn't find the description for customer with id %s", - lisa.getId()); - } - - @Test - public void someFunctions() { - assertEquals("Bob (id 1)", bob.toString()); - - Function toStringFunction = Functions - .toStringFunction(); - assertEquals("Bob (id 1)", toStringFunction.apply(bob)); - } - - @Test - public void fancierFunctions() { - Function isCustomerWithOddId = new Function() { - public Boolean apply(Customer customer) { - return customer.getId().intValue() % 2 != 0; - } - }; - - assertTrue(isCustomerWithOddId.apply(bob)); - assertFalse(isCustomerWithOddId.apply(lisa)); - - // Functions are great for higher-order functions, like - // project/transform, and fold - } - - @Test - public void somePredicates() { - ImmutableSet customers = ImmutableSet.of(bob, lisa, stephen); - - Predicate itsBob = Predicates.equalTo(bob); - Predicate itsLisa = Predicates.equalTo(lisa); - Predicate bobOrLisa = Predicates.or(itsBob, itsLisa); - - // Predicates are great to pass in to higher-order functions like - // filter/search - Iterable filtered = Iterables.filter(customers, bobOrLisa); - assertEquals(2, ImmutableSet.copyOf(filtered).size()); - assertEquals(ImmutableSet.of(bob, lisa), ImmutableSet.copyOf(filtered)); - } - -} - -class Customer { - - private Integer id; - private String name; - - public Customer(Integer id, String name) { - this.id = id; - this.name = name; - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof Customer)) { - return false; - } - - Customer that = (Customer) obj; - return Objects.equal(id, that.getId()) - && Objects.equal(name, that.getName()); - - } - - @Override - public int hashCode() { - return Objects.hashCode(id, name); - } - - @Override - public String toString() { - return name + " (id " + id + ")"; - } - - public Integer getId() { - return id; - } - - public boolean isSick() { - return false; - } - - public String getAddress() { - return null; - } - - public String getName() { - return name; - } -} - -class Ingredients { - -} - -class Cake { - Cake(Ingredients ingredients) { - - } -} - -class IngredientsFactory implements Supplier { - - private int counter; - - public Ingredients get() { - counter++; - return new Ingredients(); - } - - int getNumberOfIngredientsUsed() { - return counter; - } - -} diff --git a/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/CollectionTest.java b/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/CollectionTest.java deleted file mode 100644 index 3e471f40c3..0000000000 --- a/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/CollectionTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.jun.plugin.guava; - -import static org.junit.Assert.assertEquals; - -import java.util.HashSet; -import java.util.Set; - -import org.junit.Test; - -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Sets; - -public class CollectionTest { - - // Some customers - Customer bob = new Customer(1, "Bob"); - Customer lisa = new Customer(2, "Lisa"); - Customer stephen = new Customer(3, "Stephen"); - Customer ken = new Customer(null, "Ken"); - - @Test - public void someSets() { - ImmutableSet customers1 = ImmutableSet.of(bob, lisa, stephen); - ImmutableSet customers2 = ImmutableSet.of(stephen, ken); - - assertEquals(4, Sets.union(customers1, customers2).size()); - - assertEquals(ImmutableSet.of(stephen), - Sets.intersection(customers1, customers2)); - } - - - @Test - public void some() { - // TODO: Add more collections demos - } - -} diff --git a/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/ConcurrencyTest.java b/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/ConcurrencyTest.java deleted file mode 100644 index 0278c6873e..0000000000 --- a/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/ConcurrencyTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.jun.plugin.guava; - -import static org.junit.Assert.*; - -import org.junit.Test; - -import com.google.common.util.concurrent.MoreExecutors; - - -public class ConcurrencyTest { - - @Test - public void showOffSomeFancyThreadStuff(){ - //TODO: I'm not really good with concurrency, so my examples won't make it justice, I'm afraid. - - } -} diff --git a/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/IoTest.java b/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/IoTest.java deleted file mode 100644 index b25da609de..0000000000 --- a/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/IoTest.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.jun.plugin.guava; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintStream; -import java.net.URL; -import java.util.List; - -import org.junit.Test; - -import com.google.common.base.Charsets; -import com.google.common.base.Preconditions; -import com.google.common.base.Throwables; -import com.google.common.io.Closeables; -import com.google.common.io.Files; -import com.google.common.io.Flushables; -import com.google.common.io.Resources; - -public class IoTest { - - @Test - public void messAroundWithFile() { - File file = new File("woop.txt"); - try { - Files.touch(file); - - Files.write("Hey sailor!\n hello li", file, Charsets.UTF_8); - - // Breakpoint here.. have a look at the file.. - - Files.toByteArray(file); - Files.newInputStreamSupplier(file); - assertEquals("Hey sailor!", - Files.readFirstLine(file, Charsets.UTF_8)); - assertEquals("Hey sailor!\n hello li", Files.toString(file, Charsets.UTF_8)); - List lines = Files.readLines(file, Charsets.UTF_8); - assertEquals("Hey sailor!", lines.get(0)); - assertEquals(" hello li", lines.get(1)); - - assertEquals("txt", Files.getFileExtension(file.getName())); - file.delete(); - // guava has abandoned this method -// Files.deleteRecursively(file); - - } catch (IOException e) { - Throwables.propagate(e); - } - } - - @Test - public void classPathResources() { - // This: - Resources.getResource("com/tfnico/examples/guava/BaseTest.class"); - - // instead of this: - String location = "com/tfnico/examples/guava/BaseTest.class"; - URL resource2 = this.getClass().getClassLoader().getResource(location); - Preconditions.checkArgument(resource2 != null, "resource %s not found", - location); - } - -} diff --git a/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/NetTest.java b/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/NetTest.java deleted file mode 100644 index 14e968c35c..0000000000 --- a/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/NetTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.jun.plugin.guava; - -import java.net.InetAddress; -import java.net.UnknownHostException; - -import org.junit.Test; - -import com.google.common.base.Throwables; -import com.google.common.net.InetAddresses; - - -public class NetTest { - - @Test - public void iNetAddressIsFixed() - { - try { - - /** - * Unlike InetAddress.getByName(), - * the methods of this class never cause DNS services to be accessed. - * For this reason, you should prefer these methods as much as possible - * over their JDK equivalents whenever you are expecting to handle only - * IP address string literals -- there is no blocking DNS penalty for - * a malformed string. - */ - InetAddresses.forString("0.0.0.0"); - - //Instead of this... - InetAddress.getByName("0.0.0.0"); - - } catch (UnknownHostException e) { - Throwables.propagate(e); - } - } - - - - - -} diff --git a/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/NewStuffInR08Test.java b/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/NewStuffInR08Test.java deleted file mode 100644 index 8a24519b01..0000000000 --- a/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/NewStuffInR08Test.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.jun.plugin.guava; - -import static com.google.common.collect.Collections2.filter; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import java.util.Collection; -import java.util.SortedMap; -import java.util.TreeMap; - -import org.junit.Test; - -import com.google.common.base.Ascii; -import com.google.common.base.CharMatcher; -import com.google.common.base.Function; -import com.google.common.base.Supplier; -import com.google.common.base.Suppliers; -import com.google.common.collect.Collections2; -import com.google.common.collect.ImmutableList; - - -public class NewStuffInR08Test { - - @Test - public void makeALineBreakWithAscii(){ - System.out.print("Carriage return:"); - System.out.print(new String(new byte[] {Ascii.CR} )); - System.out.print("Second line!"); - } - - @Test - public void filterVowelsInSomeChars() { - CharMatcher vowelMatcher = CharMatcher.anyOf("aeiouy"); - assertTrue(vowelMatcher.matches('a')); - - ImmutableList someChars = ImmutableList.of('a','b','c','d','e'); - Collection filter = filter(someChars, vowelMatcher); - - ImmutableList result = ImmutableList.of('a','e'); - assertThat(charArray(filter), is(charArray(result))); - } - - @Test - public void makeAnIngredientsFromEachSupplier(){ - Supplier factory1 = new IngredientsFactory(); - Supplier factory2 = new IngredientsFactory(); - - Function, Ingredients> supplierFunction = Suppliers.supplierFunction(); - - ImmutableList> twoFactories = ImmutableList.of(factory1,factory2); - Collection twoIngredients = Collections2.transform(twoFactories, supplierFunction); - } - - @Test - public void filterAwayNullMapValues() { - SortedMap map = new TreeMap(); - map.put("1","one"); - map.put("2","two"); - map.put("3",null); - map.put("4","four"); - -// SortedMap filtered = Collections2.filter(map, Predicates.notNull()); -// assertThat(filtered.size(), is(3)); //null entry for "3" is gone! - } - - - - static Character[] charArray(Collection filter) { - return filter.toArray(new Character[0]); - } - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/basicutilities/DefaultsTest.java b/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/basicutilities/DefaultsTest.java deleted file mode 100644 index 6d83a0652d..0000000000 --- a/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/basicutilities/DefaultsTest.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.jun.plugin.guava.basicutilities; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import org.junit.Test; - -import com.google.common.base.Defaults; - -/** - * @author tiantiangao - */ -public class DefaultsTest { - - @Test - public void testGetDefaultValue() { - assertEquals(false, Defaults.defaultValue(boolean.class).booleanValue()); - assertEquals('\0', Defaults.defaultValue(char.class).charValue()); - assertEquals(0, Defaults.defaultValue(byte.class).byteValue()); - assertEquals(0, Defaults.defaultValue(short.class).shortValue()); - assertEquals(0, Defaults.defaultValue(int.class).intValue()); - assertEquals(0, Defaults.defaultValue(long.class).longValue()); - assertEquals((Float) 0.0f, (Float) Defaults.defaultValue(float.class).floatValue()); - assertEquals((Double) 0.0d, (Double) Defaults.defaultValue(double.class).doubleValue()); - assertNull(Defaults.defaultValue(void.class)); - assertNull(Defaults.defaultValue(String.class)); - } -} diff --git a/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/basicutilities/ObjectsTest.java b/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/basicutilities/ObjectsTest.java deleted file mode 100644 index c382c7eb38..0000000000 --- a/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/basicutilities/ObjectsTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.jun.plugin.guava.basicutilities; - -import static org.junit.Assert.*; - -import org.junit.Test; - -import com.google.common.base.Objects; -import com.google.common.collect.ComparisonChain; -import com.google.common.primitives.Ints; - -/** - * - * @author tiantiangao - */ -public class ObjectsTest { - - @Test - public void test() { - testEquals(); - testHashCode(); - testToString(); - testCompare(); - } - - private void testEquals() { - assertTrue(Objects.equal("a", "a")); - assertFalse(Objects.equal("a", null)); - assertFalse(Objects.equal(null, "a")); - assertTrue(Objects.equal(null, null)); - } - - private void testHashCode() { - assertNotSame(Objects.hashCode("a", "b", "c"), Objects.hashCode("c", "b", "a")); - } - - private void testToString() { - assertEquals("Object{name=test, age=18}", - Objects.toStringHelper(Object.class).add("name", "test").add("age", 18).toString()); - } - - private void testCompare() { - assertEquals(-1, Ints.compare(1, 2)); - assertEquals(1, Ints.compare(2, 1)); - assertEquals(0, Ints.compare(1, 1)); - - assertEquals(1, ComparisonChain.start().compare(1, 1).compare("aString", "aString").compare(true, false).result()); - } -} diff --git a/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/basicutilities/OptionalTest.java b/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/basicutilities/OptionalTest.java deleted file mode 100644 index 7ef3b80521..0000000000 --- a/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/basicutilities/OptionalTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.jun.plugin.guava.basicutilities; - -import static org.junit.Assert.*; - -import org.junit.Test; - -import com.google.common.base.Optional; - -/** - * @author tiantiangao - */ -public class OptionalTest { - - @Test - public void test() { - testNotNullValue(); - testNullValue(); - } - - private void testNotNullValue() { - Optional possible = Optional.fromNullable(6); - assertTrue(possible.isPresent()); - assertEquals(6, possible.get().intValue()); - assertEquals(6, possible.or(1).intValue()); - assertEquals(6, possible.orNull().intValue()); - } - - private void testNullValue() { - Optional absent = Optional.fromNullable(null); - assertFalse(absent.isPresent()); - try { - absent.get(); - fail(); - } catch (IllegalStateException e) { - assertTrue(true); - } - assertEquals(1, absent.or(1).intValue()); - assertNull(absent.orNull()); - } -} diff --git a/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/basicutilities/OrderingTest.java b/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/basicutilities/OrderingTest.java deleted file mode 100644 index 3219f86923..0000000000 --- a/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/basicutilities/OrderingTest.java +++ /dev/null @@ -1,162 +0,0 @@ -package com.jun.plugin.guava.basicutilities; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -import org.junit.Test; - -import com.google.common.base.Function; -import com.google.common.collect.Lists; -import com.google.common.collect.Ordering; - -/** - * @author tiantiangao - */ -public class OrderingTest { - - @Test - public void test() { - testNatural(); - testFrom(); - testReverse(); - testNullFirst(); - testNullLast(); - testCompound(); - testOnResultOf(); - testGreatestOf(); - testLeastOf(); - testIsOrdered(); - testIsStrictlyOrdered(); - testSortedCopy(); - } - - private void testNatural() { - // test int order - List unorderedIntList = Lists.newArrayList(5, 3, 2, 4, 1); - List orderedIntList = Lists.newArrayList(1, 2, 3, 4, 5); - Collections.sort(unorderedIntList, Ordering.natural()); - assertTrue(orderedIntList.equals(unorderedIntList)); - - // test string order - List unorderedStringList = Lists.newArrayList("Test", "Jerry", "Rock", "Ohaha", "Yeah"); - List orderedStringList = Lists.newArrayList("Jerry", "Ohaha", "Rock", "Test", "Yeah"); - Collections.sort(unorderedStringList, Ordering.natural()); - assertTrue(orderedStringList.equals(unorderedStringList)); - } - - private void testFrom() { - List unorderedIntList = Lists.newArrayList(5, 3, 2, 4, 1); - List orderedIntList = Lists.newArrayList(1, 2, 3, 4, 5); - Collections.sort(unorderedIntList, Ordering.from(new Comparator() { - @Override - public int compare(Integer i1, Integer i2) { - return i1.compareTo(i2); - } - })); - assertTrue(orderedIntList.equals(unorderedIntList)); - } - - private void testReverse() { - List unorderedIntList = Lists.newArrayList(5, 3, 2, 4, 1); - List orderedIntList = Lists.newArrayList(5, 4, 3, 2, 1); - Collections.sort(unorderedIntList, Ordering.natural().reverse()); - assertTrue(orderedIntList.equals(unorderedIntList)); - } - - private void testNullFirst() { - List unorderedIntList = Lists.newArrayList(5, 3, null, 4, 1); - List orderedIntList = Lists.newArrayList(null, 1, 3, 4, 5); - Collections.sort(unorderedIntList, Ordering.natural().nullsFirst()); - assertTrue(orderedIntList.equals(unorderedIntList)); - } - - private void testNullLast() { - List unorderedIntList = Lists.newArrayList(5, 3, null, 4, 1); - List orderedIntList = Lists.newArrayList(1, 3, 4, 5, null); - Collections.sort(unorderedIntList, Ordering.natural().nullsLast()); - assertTrue(orderedIntList.equals(unorderedIntList)); - } - - private void testCompound() { - List unorderedStringList = Lists.newArrayList("Oest", "Jerry", "Jock", "Ohaha", "Yeah"); - List orderedStringList = Lists.newArrayList("Jock", "Jerry", "Ohaha", "Oest", "Yeah"); - - Ordering firstLetterOrdering = Ordering.from(new Comparator() { - @Override - public int compare(String s1, String s2) { - return s1.substring(0, 1).compareTo(s2.substring(0, 1)); - } - }); - Collections.sort(unorderedStringList, firstLetterOrdering.compound(new Comparator() { - @Override - public int compare(String s1, String s2) { - return s2.substring(1, s2.length()).compareTo(s1.substring(1, s1.length())); - } - })); - assertTrue(orderedStringList.equals(unorderedStringList)); - } - - private void testOnResultOf() { - List unorderedStringList = Lists.newArrayList("Oest", "Jarry", "Jock", "Ohaha", "Ybah"); - List orderedStringList = Lists.newArrayList("Jarry", "Ybah", "Oest", "Ohaha", "Jock"); - - Ordering secondLetterOrdering = Ordering.natural().onResultOf(new Function() { - @Override - public String apply(String input) { - // 去除首字母 - return input.substring(1, input.length()); - } - }); - - Collections.sort(unorderedStringList, secondLetterOrdering); - assertTrue(orderedStringList.equals(unorderedStringList)); - } - - private void testGreatestOf() { - List unorderList = Lists.newArrayList(5, 3, 2, 4, 1); - List orderList = Lists.newArrayList(5, 4); - assertTrue(orderList.equals(Ordering.natural().greatestOf(unorderList, 2))); - - orderList = Lists.newArrayList(5, 4, 3, 2, 1); - assertTrue(orderList.equals(Ordering.natural().greatestOf(unorderList, 8))); - } - - private void testLeastOf() { - List unorderList = Lists.newArrayList(5, 3, 2, 4, 1); - List orderList = Lists.newArrayList(1, 2); - assertTrue(orderList.equals(Ordering.natural().leastOf(unorderList, 2))); - - orderList = Lists.newArrayList(1, 2, 3, 4, 5); - assertTrue(orderList.equals(Ordering.natural().leastOf(unorderList, 8))); - } - - private void testIsOrdered() { - // 大于可通过 - List orderList = Lists.newArrayList(1, 2, 3, 4, 5); - assertTrue(Ordering.natural().isOrdered(orderList)); - - // 大于或等于也可通过 - orderList = Lists.newArrayList(1, 2, 2, 4, 5); - assertTrue(Ordering.natural().isOrdered(orderList)); - } - - private void testIsStrictlyOrdered() { - // 大于可通过 - List orderList = Lists.newArrayList(1, 2, 3, 4, 5); - assertTrue(Ordering.natural().isStrictlyOrdered(orderList)); - - // 大于或等于不可通过 - orderList = Lists.newArrayList(1, 2, 2, 4, 5); - assertFalse(Ordering.natural().isStrictlyOrdered(orderList)); - } - - private void testSortedCopy() { - List unorderList = Lists.newArrayList(5, 3, 2, 4, 1); - List orderList = Lists.newArrayList(1, 2, 3, 4, 5); - assertTrue(orderList.equals(Ordering.natural().sortedCopy(unorderList))); - } -} diff --git a/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/basicutilities/PreconditionsTest.java b/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/basicutilities/PreconditionsTest.java deleted file mode 100644 index 2199e2fd4d..0000000000 --- a/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/basicutilities/PreconditionsTest.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.jun.plugin.guava.basicutilities; - -import static com.google.common.base.Preconditions.*; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.ArrayList; - -import org.junit.Test; - -import com.google.common.collect.Lists; - -/** - * - * @author tiantiangao - */ -public class PreconditionsTest { - - @Test - public void test() { - testCheckArgument(); - testCheckNotNull(); - testCheckState(); - testCheckElementIndex(); - testCheckPositionIndex(); - testCheckPositionIndexs(); - } - - private void testCheckArgument() { - int i = 1; - checkArgument(i > 0, "参数是%s, 参数必须为正整数", i); - - try { - i = -1; - checkArgument(-1 > 0, "参数是%s, 参数必须为正整数", -1); - fail(); - } catch (IllegalArgumentException e) { - assertTrue(true); - } - } - - private void testCheckNotNull() { - Object value = new Object(); - - checkNotNull(value, "参数是null"); - - try { - value = null; - checkNotNull(value, "参数是null"); - fail(); - } catch (NullPointerException e) { - assertTrue(true); - } - } - - private void testCheckState() { - ArrayList list = Lists.newArrayList(1, 2, 3, 4, 5); - checkState(list.size() < 6, "集体长度应该小于5"); - - list.add(6); - try { - checkState(list.size() < 6, "集体长度应该小于5"); - fail(); - } catch (Exception e) { - assertTrue(true); - } - } - - private void testCheckElementIndex() { - ArrayList list = Lists.newArrayList(1, 2, 3); - // [0, size) - checkElementIndex(list.size(), 4); - - try { - checkElementIndex(list.size(), 3); - fail(); - } catch (Exception e) { - assertTrue(true); - } - } - - private void testCheckPositionIndex() { - ArrayList list = Lists.newArrayList(1, 2, 3); - // [0, size] - checkPositionIndex(list.size(), 3); - - try { - checkPositionIndex(list.size(), 2); - fail(); - } catch (Exception e) { - assertTrue(true); - } - } - - private void testCheckPositionIndexs() { - ArrayList list = Lists.newArrayList(1, 2, 3, 4, 5); - checkPositionIndexes(4, 5, list.size()); - - try { - checkPositionIndexes(5, 6, list.size()); - fail(); - } catch (Exception e) { - assertTrue(true); - } - } -} diff --git a/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/basicutilities/ThrowablesTest.java b/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/basicutilities/ThrowablesTest.java deleted file mode 100644 index 8b3475be7e..0000000000 --- a/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/basicutilities/ThrowablesTest.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.jun.plugin.guava.basicutilities; - -import static org.junit.Assert.*; - -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.net.URL; -import java.util.Arrays; - -import org.junit.Test; - -import com.google.common.base.Throwables; - -/** - * @author tiantiangao - */ -public class ThrowablesTest { - - @Test - public void test() { - testPropagate(); - testPropagateIfInstanceOf(); - testPropagateIfPossible(); - testGetRootCause(); - testGetStackTraceAsString(); - testGetCausalChain(); - } - - private void testPropagate() { - try { - URL url = new URL("http://www.dianping.com"); - InputStream in = url.openStream(); - in.close(); - } catch (Exception e) { - throw Throwables.propagate(e); - } - } - - private void testPropagateIfInstanceOf() { - try { - throw new NumberFormatException("a"); - } catch (Throwable t) { - try { - Throwables.propagateIfInstanceOf(t, NumberFormatException.class); - fail(); - } catch (Throwable t2) { - assertTrue(true); - } - } - } - - private void testPropagateIfPossible() { - try { - throw new NumberFormatException(); - } catch (Throwable t) { - try { - Throwables.propagateIfPossible(t, Exception.class); - fail(); - } catch (Throwable t1) { - assertTrue(true); - } - } - } - - private void testGetRootCause() { - Exception e = new NumberFormatException("a"); - assertEquals(e, Throwables.getRootCause(e)); - - IllegalArgumentException e2 = new IllegalArgumentException(e); - assertEquals(e, Throwables.getRootCause(e2)); - } - - private void testGetStackTraceAsString() { - try { - Integer.parseInt("a"); - fail(); - } catch (Exception e) { - assertTrue(Throwables.getStackTraceAsString(e).startsWith( - "java.lang.NumberFormatException: For input string: \"a\"")); - } - } - - private void testGetCausalChain() { - FileNotFoundException fnfe = new FileNotFoundException(); - IllegalArgumentException iae = new IllegalArgumentException(fnfe); - RuntimeException re = new RuntimeException(iae); - IllegalStateException ex = new IllegalStateException(re); - - assertEquals(Arrays.asList(ex, re, iae, fnfe), Throwables.getCausalChain(ex)); - try { - Throwables.getCausalChain(null); - fail("Should have throw NPE"); - } catch (NullPointerException expected) { - } - } -} diff --git a/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/collections/CollectionUtilitiesTest.java b/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/collections/CollectionUtilitiesTest.java deleted file mode 100644 index 4246eaf3f0..0000000000 --- a/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/collections/CollectionUtilitiesTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.jun.plugin.guava.collections; - -import com.google.common.collect.Lists; -import com.google.common.collect.Ordering; -import com.google.common.collect.Sets; -import org.junit.Test; - -/** - * @author tiantiangao - */ -public class CollectionUtilitiesTest { - - @Test - public void test() { - testLists(); - testSets(); - } - - private void testLists() { - Lists.newArrayList(); - Lists.newArrayList(1, 2, 3); - Lists.newArrayList(Sets.newHashSet(1, 2, 3)); - Lists.newArrayListWithCapacity(10); - Lists.newArrayListWithExpectedSize(10); - - Lists.newLinkedList(); - Lists.newLinkedList(Sets.newHashSet(1, 2, 3)); - - Lists.partition(Lists.newArrayList(1, 2, 3, 4, 5), 2); - Lists.reverse(Lists.newArrayList(1, 2, 3, 4, 5)); - } - - private void testSets() { - // 静态工厂方法 - Sets.newHashSet(); - Sets.newHashSet(1, 2, 3); - Sets.newHashSetWithExpectedSize(10); - Sets.newHashSet(Lists.newArrayList(1, 2, 3)); - - Sets.newLinkedHashSet(); - Sets.newLinkedHashSetWithExpectedSize(10); - Sets.newLinkedHashSet(Lists.newArrayList(1, 2, 3)); - - Sets.newTreeSet(); - Sets.newTreeSet(Lists.newArrayList(1, 2, 3)); - Sets.newTreeSet(Ordering.natural()); - - // 集合运算(返回SetView) - Sets.union(Sets.newHashSet(1, 2, 3), Sets.newHashSet(4, 5, 6)).toString(); // 取并集[1,2,3,4,5] - Sets.intersection(Sets.newHashSet(1, 2, 3), Sets.newHashSet(3, 4, 5)); // 取交集[3] - Sets.difference(Sets.newHashSet(1, 2, 3), Sets.newHashSet(3, 4, 5)); // 只在set1, 不在set2[1,2] - Sets.symmetricDifference(Sets.newHashSet(1, 2, 3), Sets.newHashSet(3, 4, 5)); // 交集取反[1,2,4,5] - - // 其他工具方法 - Sets.cartesianProduct(Lists.newArrayList(Sets.newHashSet(1, 2), Sets.newHashSet(3, 4))); // 返回所有集合的笛卡尔积 - Sets.powerSet(Sets.newHashSet(1, 2, 3)); // 返回给定集合的所有子集 - } -} diff --git a/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/collections/ImmutableCollectionsTest.java b/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/collections/ImmutableCollectionsTest.java deleted file mode 100644 index ffeaf7b6d6..0000000000 --- a/jun_java_plugins/jun_guava/src/test/java/com/jun/plugin/guava/collections/ImmutableCollectionsTest.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.jun.plugin.guava.collections; - -import com.google.common.collect.*; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -/** - * @author tiantiangao - */ -public class ImmutableCollectionsTest { - - @Test - public void test() { - testJDKUnmodifiedList(); - testCreate(); - testAsList(); - testImmutableXXX(); - } - - private void testJDKUnmodifiedList() { - List lists = Lists.newArrayList("aa", "bb", "cc"); - - List unmodifiedLists = Collections.unmodifiableList(lists); - assertEquals(3, unmodifiedLists.size()); - - lists.add("dd"); - assertEquals(4, unmodifiedLists.size()); - } - - private void testCreate() { - testCopyOf(); - testOf(); - testBuilder(); - } - - private void testCopyOf() { - ArrayList list = Lists.newArrayList(1, 2, 3); - ImmutableList unmodifiedList = ImmutableList.copyOf(list); - assertEquals(3, unmodifiedList.size()); - - list.add(4); - assertEquals(3, unmodifiedList.size()); - } - - private void testOf() { - assertEquals(4, ImmutableList.of(1, 2, 3, 4).size()); - assertEquals(4, ImmutableSet.of(1, 2, 3, 4).size()); - assertEquals(4, ImmutableMap.of("aa", 1, "bb", 2, "cc", 3, "dd", 4).entrySet().size()); - assertEquals(4, (Object) ImmutableMap.of("aa", 1, "bb", 2, "cc", 3, "dd", 4).get("dd")); - } - - private void testBuilder() { - ImmutableMap map = ImmutableMap.builder().put("aaa", 1).put("bbb", 2).put("ccc", 3).build(); - assertEquals(3, map.size()); - assertEquals(1, map.get("aaa")); - assertEquals(2, map.get("bbb")); - assertEquals(3, map.get("ccc")); - } - - private void testAsList() { - ImmutableSortedSet iset = ImmutableSortedSet.of(5, 2, 3, 4, 1); - ImmutableList ilist = iset.asList(); - - List list = Lists.newArrayList(1, 2, 3, 4, 5); - assertEquals(list, ilist); - } - - private void testImmutableXXX() { - assertEquals(5, ImmutableList.of(1, 2, 3, 4, 5).size()); - assertEquals(5, ImmutableSet.of(1, 2, 3, 4, 5).size()); - assertEquals(5, ImmutableSortedSet.of(1, 2, 3, 4, 5).size()); - assertEquals(3, ImmutableMap.of(1, 2, 3, 4, 5, 6).size()); - assertEquals(3, ImmutableSortedMap.of(1, 2, 3, 4, 5, 6).size()); - assertEquals(9, ImmutableMultiset.of(1, 1, 2, 2, 3, 3, 4, 5, 6).size()); - assertEquals(6, ImmutableMultiset.of(1, 1, 2, 2, 3, 3, 4, 5, 6).elementSet().size()); - assertEquals(2, ImmutableMultiset.of(1, 1, 2, 2, 3, 3, 4, 5, 6).count(1)); - } -} diff --git a/jun_java_plugins/jun_guice/.gitignore b/jun_java_plugins/jun_guice/.gitignore deleted file mode 100644 index 9c300cc65f..0000000000 --- a/jun_java_plugins/jun_guice/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -/target/ -# Compiled class file -*.class - -# Log file -*.log - -# BlueJ files -*.ctxt - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ - -# Package Files # -*.jar -*.war -*.nar -*.ear -*.zip -*.tar.gz -*.rar - -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* \ No newline at end of file diff --git a/jun_java_plugins/jun_guice/README.md b/jun_java_plugins/jun_guice/README.md deleted file mode 100644 index 6243bc7553..0000000000 --- a/jun_java_plugins/jun_guice/README.md +++ /dev/null @@ -1,4 +0,0 @@ - ###guice - - ####demo for google light ioc framework guice - diff --git a/jun_java_plugins/jun_guice/pom.xml b/jun_java_plugins/jun_guice/pom.xml deleted file mode 100644 index f3d487686a..0000000000 --- a/jun_java_plugins/jun_guice/pom.xml +++ /dev/null @@ -1,89 +0,0 @@ - - 4.0.0 - io.github.wujun728 - jun_guice - 1.0 - jar - - - UTF-8 - 4.11 - 1.10.8 - 1.3 - 18.0 - 2.6 - 2.4 - 1.7.7 - 2.13 - 2.6 - 4.0-beta5 - 1.2.17 - 1.7.5 - - - - - com.google.guava - guava - ${guava.version} - - - com.google.inject - guice - ${guice.version} - - - com.google.inject.extensions - guice-multibindings - ${guice.version} - - - junit - junit - ${junit.version} - test - - - org.hamcrest - hamcrest-all - ${hamcrest.version} - test - - - - org.mockito - mockito-all - ${mockito.version} - test - - - commons-lang - commons-lang - ${commons-lang.version} - - - commons-io - commons-io - ${commons-io.version} - - - org.slf4j - slf4j-api - ${slf4j.version} - - - org.slf4j - slf4j-log4j12 - ${slf4j-log4j12.version} - test - - - log4j - log4j - ${log4j.version} - test - - - diff --git a/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/app/AppModule.java b/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/app/AppModule.java deleted file mode 100644 index d27b6659cb..0000000000 --- a/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/app/AppModule.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.jun.plugin.guice.app; - -import com.google.common.collect.ImmutableList; -import com.google.inject.*; -import com.google.inject.multibindings.Multibinder; -import com.google.inject.name.Named; -import com.google.inject.name.Names; -import com.jun.plugin.guice.item.ItemService; -import com.jun.plugin.guice.item.ItemServiceImpl1; -import com.jun.plugin.guice.item.ItemServiceImpl2; -import com.jun.plugin.guice.named.NamedService; -import com.jun.plugin.guice.named.NamedServiceImpl1; -import com.jun.plugin.guice.named.NamedServiceImpl2; -import com.jun.plugin.guice.order.OrderService; -import com.jun.plugin.guice.order.OrderServiceImpl; -import com.jun.plugin.guice.price.PriceService; -import com.jun.plugin.guice.runtime.RuntimeService; -import com.jun.plugin.guice.runtime.RuntimeServiceImpl; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.List; - -import static com.google.common.collect.ImmutableList.of; -import static com.google.inject.Scopes.SINGLETON; -import static com.google.inject.matcher.Matchers.any; -import static com.jun.plugin.guice.app.ExceptionMethodInterceptor.exception; - -/** - * *************************************** - * * - * Auth: green gerong * - * Date: 2014 * - * blog: http://greengerong.github.io/ * - * github: https://github.com/greengerong * - * * - * **************************************** - */ -public class AppModule extends AbstractModule { - private static final Logger LOGGER = LoggerFactory.getLogger(AppModule.class); - private final RuntimeServiceImpl runtimeService; - - public AppModule(RuntimeServiceImpl runtimeService) { - this.runtimeService = runtimeService; - } - - @Override - public void configure() { - final Binder binder = binder(); - if (LOGGER.isDebugEnabled()) { - binder.bindInterceptor(any(), any(), exception()); - } - //TODO: bind interface - binder.bind(OrderService.class).to(OrderServiceImpl.class).in(SINGLETON); - //TODO: bind self class(without interface or base class) - binder.bind(PriceService.class).in(Scopes.SINGLETON); - - //TODO: Multibinder - final Multibinder itemServiceMultibinder = Multibinder.newSetBinder(binder, ItemService.class); - itemServiceMultibinder.addBinding().to(ItemServiceImpl1.class); - itemServiceMultibinder.addBinding().to(ItemServiceImpl2.class); - - //TODO: bind instance not class. - binder.bind(RuntimeService.class).toInstance(runtimeService); - - //TODO: bind named instance; - binder.bind(NamedService.class).annotatedWith(Names.named("impl1")).to(NamedServiceImpl1.class); - binder.bind(NamedService.class).annotatedWith(Names.named("impl2")).to(NamedServiceImpl2.class); - } - - @Provides - public List getAllItemServices(@Named("impl1") NamedService nameService1, - @Named("impl2") NamedService nameService2) { - return of(nameService1, nameService2); - } - - -} diff --git a/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/app/ExceptionMethodInterceptor.java b/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/app/ExceptionMethodInterceptor.java deleted file mode 100644 index f25010d3cb..0000000000 --- a/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/app/ExceptionMethodInterceptor.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.jun.plugin.guice.app; - -import com.google.common.base.Joiner; -import com.google.common.collect.Lists; -import org.aopalliance.intercept.MethodInterceptor; -import org.aopalliance.intercept.MethodInvocation; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.List; - -/** - * *************************************** - * * - * Auth: green gerong * - * Date: 2014 * - * blog: http://greengerong.github.io/ * - * github: https://github.com/greengerong * - * * - * **************************************** - */ -public class ExceptionMethodInterceptor implements MethodInterceptor { - private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionMethodInterceptor.class); - - private ExceptionMethodInterceptor() { - } - - public static ExceptionMethodInterceptor exception() { - return new ExceptionMethodInterceptor(); - } - - @Override - public Object invoke(MethodInvocation methodInvocation) throws Throwable { - final String methodName = getMethodName(methodInvocation); - try { - LOGGER.debug(String.format("method(%s) call with: %s.", methodName, getArgs(methodInvocation))); - final Object result = methodInvocation.proceed(); - LOGGER.debug(String.format("method(%s) return with: %s.", methodName, result)); - return result; - } catch (Exception e) { - LOGGER.error(String.format("method(%s) error with: %s.", methodName, e.getCause()), e); - throw e; - } - - } - - private Object getArgs(MethodInvocation methodInvocation) { - final List args = Lists.newArrayList(); - if (methodInvocation.getArguments() != null) { - for (int i = 0; i < methodInvocation.getArguments().length; i++) { - final Object arg = methodInvocation.getArguments()[i]; - args.add(arg == null ? "null" : arg.toString()); - } - } - return Joiner.on(",").join(args); - } - - private String getMethodName(MethodInvocation methodInvocation) { - return String.format("%s-(%s)", methodInvocation.getMethod().getDeclaringClass().getName(), methodInvocation.getMethod()); - } -} diff --git a/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/item/Item.java b/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/item/Item.java deleted file mode 100644 index 4e6fce11bf..0000000000 --- a/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/item/Item.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.jun.plugin.guice.item; - -/** - * *************************************** - * * - * Auth: green gerong * - * Date: 2014 * - * blog: http://greengerong.github.io/ * - * github: https://github.com/greengerong * - * * - * **************************************** - */ -public class Item { -} diff --git a/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/item/ItemService.java b/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/item/ItemService.java deleted file mode 100644 index 9d55dc2af0..0000000000 --- a/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/item/ItemService.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.jun.plugin.guice.item; - -/** - * *************************************** - * * - * Auth: green gerong * - * Date: 2014 * - * blog: http://greengerong.github.io/ * - * github: https://github.com/greengerong * - * * - * **************************************** - */ -public interface ItemService { - Item get(int id); -} diff --git a/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/item/ItemServiceImpl1.java b/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/item/ItemServiceImpl1.java deleted file mode 100644 index 515d21b645..0000000000 --- a/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/item/ItemServiceImpl1.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.jun.plugin.guice.item; - -import com.google.inject.name.Named; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * *************************************** - * * - * Auth: green gerong * - * Date: 2014 * - * blog: http://greengerong.github.io/ * - * github: https://github.com/greengerong * - * * - * **************************************** - */ -public class ItemServiceImpl1 implements ItemService { - private static final Logger LOGGER = LoggerFactory.getLogger(ItemServiceImpl1.class); - - @Override - public Item get(int id) { - return null; - } -} diff --git a/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/item/ItemServiceImpl2.java b/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/item/ItemServiceImpl2.java deleted file mode 100644 index 52432e8efb..0000000000 --- a/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/item/ItemServiceImpl2.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.jun.plugin.guice.item; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * *************************************** - * * - * Auth: green gerong * - * Date: 2014 * - * blog: http://greengerong.github.io/ * - * github: https://github.com/greengerong * - * * - * **************************************** - */ -public class ItemServiceImpl2 implements ItemService { - private static final Logger LOGGER = LoggerFactory.getLogger(ItemServiceImpl1.class); - - @Override - public Item get(int id) { - return null; - } -} diff --git a/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/named/NamedService.java b/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/named/NamedService.java deleted file mode 100644 index c35feaa375..0000000000 --- a/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/named/NamedService.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.jun.plugin.guice.named; - -/** - * *************************************** - * * - * Auth: green gerong * - * Date: 2014 * - * blog: http://greengerong.github.io/ * - * github: https://github.com/greengerong * - * * - * **************************************** - */ -public class NamedService { -} diff --git a/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/named/NamedServiceImpl1.java b/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/named/NamedServiceImpl1.java deleted file mode 100644 index b57dc9ea1b..0000000000 --- a/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/named/NamedServiceImpl1.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.jun.plugin.guice.named; - -/** - * *************************************** - * * - * Auth: green gerong * - * Date: 2014 * - * blog: http://greengerong.github.io/ * - * github: https://github.com/greengerong * - * * - * **************************************** - */ -public class NamedServiceImpl1 extends NamedService { -} diff --git a/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/named/NamedServiceImpl2.java b/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/named/NamedServiceImpl2.java deleted file mode 100644 index b911678893..0000000000 --- a/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/named/NamedServiceImpl2.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.jun.plugin.guice.named; - -/** - * *************************************** - * * - * Auth: green gerong * - * Date: 2014 * - * blog: http://greengerong.github.io/ * - * github: https://github.com/greengerong * - * * - * **************************************** - */ -public class NamedServiceImpl2 extends NamedService { -} diff --git a/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/order/Order.java b/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/order/Order.java deleted file mode 100644 index 8b16ad3976..0000000000 --- a/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/order/Order.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.jun.plugin.guice.order; - -import java.util.Date; - -/** - * *************************************** - * * - * Auth: green gerong * - * Date: 2014 * - * blog: http://greengerong.github.io/ * - * github: https://github.com/greengerong * - * * - * **************************************** - */ -public class Order { - private int id; - private String customer; - private Date createDate; - - public Order(int id) { - this.id = id; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getCustomer() { - return customer; - } - - public void setCustomer(String customer) { - this.customer = customer; - } - - public Date getCreateDate() { - return createDate; - } - - public void setCreateDate(Date createDate) { - this.createDate = createDate; - } - - @Override - public String toString() { - return String.format("Order{id=%d, customer='%s', createDate=%s}", id, customer, createDate); - } -} diff --git a/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/order/OrderService.java b/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/order/OrderService.java deleted file mode 100644 index 25c096038d..0000000000 --- a/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/order/OrderService.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.jun.plugin.guice.order; - - -public interface OrderService { - - void add(Order order); - - void remove(Order order); - - Order get(int id); -} diff --git a/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/order/OrderServiceImpl.java b/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/order/OrderServiceImpl.java deleted file mode 100644 index e5fc65f288..0000000000 --- a/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/order/OrderServiceImpl.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.jun.plugin.guice.order; - -import com.google.inject.Inject; -import com.jun.plugin.guice.item.ItemService; -import com.jun.plugin.guice.price.PriceService; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Set; - -/** - * *************************************** - * * - * Auth: green gerong * - * Date: 2014 * - * blog: http://greengerong.github.io/ * - * github: https://github.com/greengerong * - * * - * **************************************** - */ -public class OrderServiceImpl implements OrderService { - private static final Logger LOGGER = LoggerFactory.getLogger(OrderServiceImpl.class); - private Set itemServices; - private PriceService priceService; - - public OrderServiceImpl() { - } - - @Inject - public OrderServiceImpl(Set itemServices, PriceService priceService) { - this.itemServices = itemServices; - this.priceService = priceService; - } - - @Override - public void add(Order order) { - for (ItemService item : itemServices) { - item.get(0); - } - priceService.getPrice(); - } - - @Override - public void remove(Order order) { - } - - @Override - public Order get(int id) { - for (ItemService item : itemServices) { - item.get(id); - } - return new Order(id); - } - - public Set getItemServices() { - return itemServices; - } - - public PriceService getPriceService() { - return priceService; - } -} diff --git a/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/price/PriceService.java b/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/price/PriceService.java deleted file mode 100644 index 411d1cdbb3..0000000000 --- a/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/price/PriceService.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.jun.plugin.guice.price; - -/** - * *************************************** - * * - * Auth: green gerong * - * Date: 2014 * - * blog: http://greengerong.github.io/ * - * github: https://github.com/greengerong * - * * - * **************************************** - */ -public class PriceService { - - public String getPrice() { - return "price"; - } -} diff --git a/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/runtime/RuntimeService.java b/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/runtime/RuntimeService.java deleted file mode 100644 index 9c0e4c5612..0000000000 --- a/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/runtime/RuntimeService.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.jun.plugin.guice.runtime; - -/** - * *************************************** - * * - * Auth: green gerong * - * Date: 2014 * - * blog: http://greengerong.github.io/ * - * github: https://github.com/greengerong * - * * - * **************************************** - */ -public class RuntimeService { -} diff --git a/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/runtime/RuntimeServiceImpl.java b/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/runtime/RuntimeServiceImpl.java deleted file mode 100644 index 1a48dcd836..0000000000 --- a/jun_java_plugins/jun_guice/src/main/java/com/jun/plugin/guice/runtime/RuntimeServiceImpl.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.jun.plugin.guice.runtime; - -/** - * *************************************** - * * - * Auth: green gerong * - * Date: 2014 * - * blog: http://greengerong.github.io/ * - * github: https://github.com/greengerong * - * * - * **************************************** - */ -public class RuntimeServiceImpl extends RuntimeService { -} diff --git a/jun_java_plugins/jun_guice/src/test/java/com/jun/plugin/guice/AppModuleTest.java b/jun_java_plugins/jun_guice/src/test/java/com/jun/plugin/guice/AppModuleTest.java deleted file mode 100644 index 374d0c473c..0000000000 --- a/jun_java_plugins/jun_guice/src/test/java/com/jun/plugin/guice/AppModuleTest.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.jun.plugin.guice; - -import com.google.common.collect.Lists; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.jun.plugin.guice.app.AppModule; -import com.jun.plugin.guice.item.ItemService; -import com.jun.plugin.guice.item.ItemServiceImpl1; -import com.jun.plugin.guice.item.ItemServiceImpl2; -import com.jun.plugin.guice.named.NamedService; -import com.jun.plugin.guice.order.Order; -import com.jun.plugin.guice.order.OrderService; -import com.jun.plugin.guice.order.OrderServiceImpl; -import com.jun.plugin.guice.price.PriceService; -import com.jun.plugin.guice.runtime.RuntimeService; -import com.jun.plugin.guice.runtime.RuntimeServiceImpl; - -import org.junit.Before; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.sameInstance; -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; - -public class AppModuleTest { - - private Injector injector; - - @Before - public void setUp() throws Exception { - injector = Guice.createInjector(new AppModule(new RuntimeServiceImpl())); - } - - @Test - public void should_get_order_service_from_guice_module() throws Exception { - //given - //when - final OrderService instance = injector.getInstance(OrderService.class); - //then - assertThat(instance, is(instanceOf(OrderServiceImpl.class))); - final List itemServices = Lists.newArrayList(((OrderServiceImpl) instance).getItemServices()); - assertThat(itemServices.get(0), is(instanceOf(ItemServiceImpl1.class))); - assertThat(itemServices.get(1), is(instanceOf(ItemServiceImpl2.class))); - assertThat(((OrderServiceImpl) instance).getPriceService(), is(instanceOf(PriceService.class))); - instance.add(new Order(100)); - } - - @Test - public void should_get_all_item_service() throws Exception { - //given - - //when - final List instance = Lists.newArrayList( - injector.getInstance(new Key>() { - }) - ); - //then - assertThat(instance.size(), is(2)); - assertThat(instance.get(0), is(instanceOf(ItemServiceImpl1.class))); - assertThat(instance.get(1), is(instanceOf(ItemServiceImpl2.class))); - } - - @Test - public void should_register_service_runtime() throws Exception { - //given - - //when - final RuntimeService instance = injector.getInstance(RuntimeService.class); - //then - - assertThat(instance, is(instanceOf(RuntimeServiceImpl.class))); - } - - @Test - public void should_be_singleton_for_one_without_interface_bean() throws Exception { - //given - - //when - final PriceService first = injector.getInstance(PriceService.class); - final PriceService second = injector.getInstance(PriceService.class); - //then - - assertThat(first, is(sameInstance(second))); - } - - @Test - public void should_get_named_service_with_Provides_bean() throws Exception { - //given - - //when - final List namedServices = injector.getInstance(new Key>() { - }); - //then - - assertThat(namedServices.size(), is(2)); - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_guice/src/test/resources/log4j.properties b/jun_java_plugins/jun_guice/src/test/resources/log4j.properties deleted file mode 100644 index 8bf4b8db7e..0000000000 --- a/jun_java_plugins/jun_guice/src/test/resources/log4j.properties +++ /dev/null @@ -1,63 +0,0 @@ -#log4j.rootLogger=CONSOLE,FILE -log4j.rootLogger=DEBUG,CONSOLE -log4j.addivity.org.apache=true - - -# 应用于控制台 -log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender -log4j.appender.CONSOLE.Threshold=DEBUG -log4j.appender.CONSOLE.Target=System.out -log4j.appender.CONSOLE.Encoding=GBK -log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout -log4j.appender.CONSOLE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n - -# 每天新建日志 -log4j.appender.A1=org.apache.log4j.DailyRollingFileAppender -log4j.appender.A1.File=/Users/zxgerong/project/opensource/java/guice-demo/target/log -log4j.appender.A1.Encoding=GBK -log4j.appender.A1.Threshold=DEBUG -log4j.appender.A1.DatePattern='.'yyyy-MM-dd -log4j.appender.A1.layout=org.apache.log4j.PatternLayout -log4j.appender.A1.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L : %m%n - -#应用于文件 -log4j.appender.FILE=org.apache.log4j.FileAppender -log4j.appender.FILE.File=C:/log4j/file.log -log4j.appender.FILE.Append=false -log4j.appender.FILE.Encoding=GBK -log4j.appender.FILE.layout=org.apache.log4j.PatternLayout -log4j.appender.FILE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n - -# 应用于文件回滚 -log4j.appender.ROLLING_FILE=org.apache.log4j.RollingFileAppender -log4j.appender.ROLLING_FILE.Threshold=ERROR -log4j.appender.ROLLING_FILE.File=rolling.log -log4j.appender.ROLLING_FILE.Append=true -log4j.appender.CONSOLE_FILE.Encoding=GBK -log4j.appender.ROLLING_FILE.MaxFileSize=10KB -log4j.appender.ROLLING_FILE.MaxBackupIndex=1 -log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout -log4j.appender.ROLLING_FILE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n - -#应用于socket -log4j.appender.SOCKET=org.apache.log4j.RollingFileAppender -log4j.appender.SOCKET.RemoteHost=localhost -log4j.appender.SOCKET.Port=5001 -log4j.appender.SOCKET.LocationInfo=true -# Set up for Log Facter 5 -log4j.appender.SOCKET.layout=org.apache.log4j.PatternLayout -log4j.appender.SOCET.layout.ConversionPattern=[start]%d{DATE}[DATE]%n%p[PRIORITY]%n%x[NDC]%n%t[THREAD]%n%c[CATEGORY]%n%m[MESSAGE]%n%n -# Log Factor 5 Appender -log4j.appender.LF5_APPENDER=org.apache.log4j.lf5.LF5Appender -log4j.appender.LF5_APPENDER.MaxNumberOfRecords=2000 - -# 发送日志给邮件 -log4j.appender.MAIL=org.apache.log4j.net.SMTPAppender -log4j.appender.MAIL.Threshold=FATAL -log4j.appender.MAIL.BufferSize=10 -log4j.appender.MAIL.From= -log4j.appender.MAIL.SMTPHost=www.wusetu.com -log4j.appender.MAIL.Subject=Log4J Message -log4j.appender.MAIL.To= -log4j.appender.MAIL.layout=org.apache.log4j.PatternLayout -log4j.appender.MAIL.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n diff --git a/jun_java_plugins/jun_gzip/jun_compress_client/pom.xml b/jun_java_plugins/jun_gzip/jun_compress_client/pom.xml deleted file mode 100644 index ca55fffc55..0000000000 --- a/jun_java_plugins/jun_gzip/jun_compress_client/pom.xml +++ /dev/null @@ -1,59 +0,0 @@ - - - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 2.2.6.RELEASE - - - - io.github.wujun728 - jun_compress_client - 1.0 - - - 1.8 - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-test - test - - - org.junit.vintage - junit-vintage-engine - - - - - org.apache.httpcomponents - httpclient - 4.5.10 - - - - com.alibaba - druid - 1.2.4 - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - diff --git a/jun_java_plugins/jun_gzip/jun_compress_client/src/test/java/Base64Utils.java b/jun_java_plugins/jun_gzip/jun_compress_client/src/test/java/Base64Utils.java deleted file mode 100644 index fba8293edd..0000000000 --- a/jun_java_plugins/jun_gzip/jun_compress_client/src/test/java/Base64Utils.java +++ /dev/null @@ -1,193 +0,0 @@ -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Base64; -public class Base64Utils { - - private static Base64Utils utils = null; - - private Base64Utils() { - - } - - public static Base64Utils getInstance() { - if (utils == null) { - synchronized (Base64Utils.class) { - if (utils == null) { - utils = new Base64Utils(); - } - } - } - return utils; - } - - /** - * 返回文件大小 - * - * @param inFile - * @return - */ - public int getFileSize(File inFile) { - InputStream in = null; - - try { - in = new FileInputStream(inFile); - // 文件长度 - int len = in.available(); - return len; - } catch (Exception e) { - // TODO: handle exception - } finally { - try { - in.close(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - return -1; - } - - /** - * 将文件转化为base64 - * - * @param inFile - * @return - */ - public String file2Base64(File inFile) { - - // 将文件转化为字节码 - byte[] bytes = copyFile2Byte(inFile); - if (bytes == null) { - return null; - } - - // base64,将字节码转化为base64的字符串 - String result = Base64.getEncoder().encodeToString(bytes); - return result; - } - - /** - * 将文件转化为字节码 - * - * @param inFile - * @return - */ - private byte[] copyFile2Byte(File inFile) { - InputStream in = null; - - try { - in = new FileInputStream(inFile); - // 文件长度 - int len = in.available(); - - // 定义数组 - byte[] bytes = new byte[len]; - - // 读取到数组里面 - in.read(bytes); - return bytes; - } catch (Exception e) { - e.printStackTrace(); - return null; - } finally { - try { - if (in != null) { - in.close(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - /** - * 将字符串转化为文件 - * - * @param strBase64 base64 编码的文件 - * @param outFile 输出的目标文件地址 - */ - public boolean base64ToFile(String strBase64, File outFile) { - try { - // 解码,然后将字节转换为文件 - byte[] bytes = Base64.getDecoder().decode(strBase64); // 将字符串转换为byte数组 - return copyByte2File(bytes, outFile); - } catch (Exception ioe) { - ioe.printStackTrace(); - return false; - } - } - - /** - * 将字节码转化为文件 - * - * @param bytes - * @param file - */ - private boolean copyByte2File(byte[] bytes, File file) { - FileOutputStream out = null; - try { - // 转化为输入流 - ByteArrayInputStream in = new ByteArrayInputStream(bytes); - - // 写出文件 - byte[] buffer = new byte[1024]; - - out = new FileOutputStream(file); - - // 写文件 - int len = 0; - while ((len = in.read(buffer)) != -1) { - out.write(buffer, 0, len); // 文件写操作 - } - return true; - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } finally { - try { - if (out != null) { - out.close(); - } - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - return false; - } - - /** - * 将base64转换为输入流 - * - * @param base64 - * @return - */ - public ByteArrayInputStream base64ToInputStream(String base64) { - try { - // 将字符串转换为byte数组 - byte[] bytes = Base64.getDecoder().decode(base64); - ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); - - return inputStream; - - } catch (Exception e) { - e.printStackTrace(); - } - - return null; - } - - - public static void main(String[] args) { - File file = new File("C:\\Users\\test\\Desktop\\base64-master\\123.JPG"); - File fileNew = new File("C:\\Users\\test\\Desktop\\base64-master\\123-copy.JPG"); - System.out.println(Base64Utils.getInstance().file2Base64(file)); - String fileStr = Base64Utils.getInstance().file2Base64(file); - System.out.println(Base64Utils.getInstance().base64ToFile(fileStr, fileNew)); - } -} - \ No newline at end of file diff --git a/jun_java_plugins/jun_gzip/jun_compress_client/src/test/java/GzipTest.java b/jun_java_plugins/jun_gzip/jun_compress_client/src/test/java/GzipTest.java deleted file mode 100644 index 0fc7b64d22..0000000000 --- a/jun_java_plugins/jun_gzip/jun_compress_client/src/test/java/GzipTest.java +++ /dev/null @@ -1,52 +0,0 @@ - - -import java.io.IOException; - -import com.jun.plugin.gzip.compressclient.compress.CompressUtils; -import com.jun.plugin.gzip.compressclient.encrypt.AESUtils; - -/** - * - * @author Wujun - * - */ -public class GzipTest { - - public static void main(String [] args){ - String content=" "; - System.out.println("Step1 压缩前长度:" + content.length()); - try{ - // 压缩 - String afterCompressStr = CompressUtils.compress(content); - System.out.println("Step2 压缩后长度:" + afterCompressStr.length()); - - // 加密 - String afterEncryptStr = AESUtils.encrypt(afterCompressStr); - System.out.println("Step3 先压缩后加密的长度:" + afterEncryptStr.length()); - System.out.println("Step3 先压缩后加密的content:" + afterEncryptStr); - - // 先加密后压缩 - String _afterEncryptStr = AESUtils.encrypt(content); - System.out.println("先加密的长度:" +_afterEncryptStr); - String _afterCompressStr = CompressUtils.compress(_afterEncryptStr); - System.out.println("先加密后压缩的长度:" + _afterCompressStr.length()); - - // 解密 - String afterEncryptStrVal=afterEncryptStr; -// String afterEncryptStrVal="abcde"; - String afterDecryptStr = AESUtils.decrypt(afterEncryptStrVal); - System.out.println("Step4 解密:" + afterDecryptStr.length()); - - - // 解压缩 - String afterDecryptContent = CompressUtils.decompressToStr(afterDecryptStr); - System.out.println("Step5 解压缩:" + afterDecryptContent.length()); - System.out.println("Step5 解压缩:" + afterDecryptContent); - - - - }catch (IOException e){ - System.out.println(e.getMessage()); - } - } -} diff --git a/jun_java_plugins/jun_gzip/jun_compress_client/src/test/java/SplitUtil.java b/jun_java_plugins/jun_gzip/jun_compress_client/src/test/java/SplitUtil.java deleted file mode 100644 index 684fd8fe18..0000000000 --- a/jun_java_plugins/jun_gzip/jun_compress_client/src/test/java/SplitUtil.java +++ /dev/null @@ -1,111 +0,0 @@ -import java.util.ArrayList; -import java.util.List; - -public class SplitUtil { - - public static void main(String[] args) { - String content="854ad05a51616c372058622b9d7144b2be4215583cc0f2200451f951a93eb74809780b1fe29f3e8e09eef565ff65a4166730" + - "d5f0b7bff0149dfeda5aaf7835a41c5b05d50817484803684c2ac95c1113aa5f00bb2ab23d1accff478545d43c3318dc2474" + - "3954f0b165f9787710f5363471675f5a1a264f49332e8c235929ae04af97f4172b1c9c11109ce19c4e5251005475ff8f0751" + - "1eff29fb469fc9ae8708f27a2bb4d9c1cd6c0ae2523f21c4859fec3a05edf7cc16eae196c79ec51954a493e7cbc48d2bccb5" + - "7a3f3ea8c4c94ea58606863d4dd604173090a302fb163ad8554ffcd9e6c40b062002e96614d1018f652dc3ec0ec837509d4b" + - "d2b0b2995f281cb938c233afdc4c3ac97932cf69725b05da0a38de624269794d279301dfed12110f2aa5e09906eac17ffe9b" + - "e1b1e08bef74de49a8fdd0ecd4d34fcb06957694ed656f92cc52db876f36c164505e3975ea827404b8df817f7a166257a784" + - "3b1e5c2f503a5bef2f43e9f960f0aaae39c0d680ab48791c952d30974ae64f5955bd03c864084942c690944696b383e8c53f" + - "a132bedc000f082cac3948f957976567e7bd8f700d66780e018a7e610d19008f80d302f4a639723b83494c2425498803cc31" + - "15e90dd604222bc7356bd6e189e1200cad6586e043fc4525c7a94c359e4b8f31238db96c70a51aade677f743fd44ad4dfd4f" + - "11237347b7e07241f7003753632ae95871923a10ebe555c07397d201862d606fdbaede9f2ec8b87e14df25b53dbdd162e43d" + - "bf2f35b118db4df7e5f6b0cd52a473520800802e519e23fb1cafd199959678c6b57699ae0bc23af69c248d0391f99593bf55" + - "34308b850c1ae4923c42e6deec8bc19b4caeac789e6264ad83ed1602488553495c449c8895276713d21ab9dc3cd60550d4ab" + - "4fad148b18b2ba5a6743bc5c2dd95e7f5b96d9c6fbed54a515a37a7a8664674b28d01d76727058e580eb4c12f84ae576cc1b" + - "816891505707346638a1ba8d8d929f837c6a8b998caa870e4f1d24557cd7ac1500f5b07758b5ec754a214a5a98cb1c44add0" + - "aed64195dcc28e10a8574d2072c9165a67550b0f193788c3714153408b62836f56db9ffdd690ba80403be974a93161c60a99" + - "f1a050b8966c068ca451301b17e4482470ba26d43fde708850c14d8f7891efe464420354e235dc4cff714798829b70fd8f42" + - "00b41871144a7a417ae395b046092faa19efeba7373e0449745f049fee7836eb34e46f9ab657dc366357721102f6fd95bb0e" + - "ded99a1224545e75e831abeabe0d6923612be30e29405dbde57904b3c6042d4853057868c7dae68efd989e1c58c9e155765c" + - "6a3be50c183d772eb6d61191114116094c76c23b73b2c79c00bc2a079698de6f1cc643e521cbe1c352068987531d55279cad" + - "3dc97c672cea81874f1f644bab5b5a02598c147a58989d4bd17ca9e24650ec089aeab282150f4c13292a573faf9e9e12a171" + - "69bde6c143a842f1f587c794c1c201a76d9943c1b0031dcff42a938840199bafe9ec5125a7ba16f275309b0244b396509c0e" + - "87a608a985ff2660c0527f85f07b70f169976ab42a654c816293998968d35bf8ebd5e8bd1f3c2f01ae6be6c0afaa974c8b0d" + - "9004227375089e14802f31b6750814a072c1d23e8d06b9e38e616bd4f37509c6542ad36d4322bb435a848ca4ccee3245ec0f" + - "cc1b3c5679cde7f0cf2c733598b6b9529bf3259e2fa8798d1825bdf3183e141688111e4add57814915bd9297c6a98d141b00" + - "43beea0cfc469c1f4af905e1dd1e1d45f79283eb21b36b44431fec60034ffe97c8fe02880cfd6038f822696bded8e39c2829" + - "80c09e7a1dc105bf65398cdbb878a73122d3b96ebc76674c830a3914e90b3351fc6001730ee481df60ce7091f98e3210e88b" + - "244192a0680e71325862d4fa67bf6633b9035ca145305fe8bba7231c84c4503e66768a80426de7b5b00ce94215da0661d464" + - "17d4f9fa461590ac2f3de6799aaf053857c6cfaa731303cdbd7402fed1e467ea8b95e21c7e75c62e0ed5c187b23b9af0333b" + - "ae7dcb266bf99776d8caed8123c949ba248e794a4c49cc785a803ad3a0aae4e35000aa3cb0d2bc469af1ab96f5b5e0c6016b" + - "55b97f5ef0b6e39cc392ed781f348ed8bc9765329ea69bd354b2950d99377769f1c555720fa03648f98cae95993df4b00539" + - "b3d964efff0da0e00d7c9454dc27985d33843064bffc4f6e22d4de6ab5ce22a395a434a37179a2941b49e5767f2bcbe9a1a3" + - "b17368a1386f888d40fb15dfc9bcdc5fed4729d1cf4e2b9627225b8fbbd71e6aa8b243a57247eaa06effd97670a9b3fab4a2" + - "3b11719e103b4ced57cc6ea1b3a1d36f76ca84312c8bfb58972358b68e680c2d0f17325af1958de4e3403eba558f39c48eb1" + - "83c1634cbe36dc61f810918681ef91fdf8cdb36935aa9d8ff46c71e4187fcc66091d61f89ff1364a4601d16b7154c2f7ffdd" + - "ef4ff4673cdf1d25ea907a8300073499793f1da3f3b952eba9eb3e56a03413e0952568eb7381d5fa1586bd2f2030b6f4c246" + - "48894b0f38be1042ad8a92375e1ab70d7d55e4c053c11c29966dcb4cde684fe37f3e7b2857403299f9d300c0b3cb547d1882" + - "b3b33df13e4c9dff3fc9d68d2c7f47ca53d1244c93279fb2befc3db94eed8ba3cdfab3060b3587f2174136084c6d8e41a9e0" + - "36222138a4d176d1e2ca8710e30f6a2dcf37e388"; - SplitUtil.getStrList(content, 100).forEach(str->{ - System.out.println(str); - }); - } - - /** - * 把原始字符串分割成指定长度的字符串列表 - * - * @param inputString - * 原始字符串 - * @param length - * 指定长度 - * @return - */ - public static List getStrList(String inputString, int length) { - int size = inputString.length() / length; - if (inputString.length() % length != 0) { - size += 1; - } - return getStrList(inputString, length, size); - } - - /** - * 把原始字符串分割成指定长度的字符串列表 - * - * @param inputString - * 原始字符串 - * @param length - * 指定长度 - * @param size - * 指定列表大小 - * @return - */ - public static List getStrList(String inputString, int length, - int size) { - List list = new ArrayList(); - for (int index = 0; index < size; index++) { - String childStr = substring(inputString, index * length, - (index + 1) * length); - list.add(childStr); - } - return list; - } - - /** - * 分割字符串,如果开始位置大于字符串长度,返回空 - * - * @param str - * 原始字符串 - * @param f - * 开始位置 - * @param t - * 结束位置 - * @return - */ - public static String substring(String str, int f, int t) { - if (f > str.length()) - return null; - if (t > str.length()) { - return str.substring(f, str.length()); - } else { - return str.substring(f, t); - } - } - -} diff --git a/jun_java_plugins/jun_gzip/jun_springboot_server/pom.xml b/jun_java_plugins/jun_gzip/jun_springboot_server/pom.xml deleted file mode 100644 index 1a0386981e..0000000000 --- a/jun_java_plugins/jun_gzip/jun_springboot_server/pom.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 2.2.6.RELEASE - - - io.github.wujun728 - jun_springboot_server - 1.0 - - - 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/jun_java_plugins/jun_gzip/pom.xml b/jun_java_plugins/jun_gzip/pom.xml deleted file mode 100644 index 2821194ecd..0000000000 --- a/jun_java_plugins/jun_gzip/pom.xml +++ /dev/null @@ -1,93 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_gzip - 1.0 - pom - - - jun_compress_client - jun_springboot_server - - - - - - - - - - - - src/main/resources - true - - - - - src/test/resources - true - - - - - org.apache.maven.plugins - maven-resources-plugin - 2.4 - - ${project.encoding} - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.0.2 - - ${java.src.version} - ${java.target.version} - ${project.encoding} - - - - org.apache.maven.plugins - maven-eclipse-plugin - 2.6 - - ${basedir} - - http://svn.apache.org/repos/asf/maven/plugins/trunk/maven-eclipse-plugin/src/optional/eclipse-config/maven-styles.xml - - true - false - - - - org.apache.maven.plugins - maven-source-plugin - 2.2.1 - - - attach-sources - - jar - - - - - - org.apache.maven.plugins - maven-deploy-plugin - 2.7 - - true - - - - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_hibernate/.keep b/jun_java_plugins/jun_hibernate/.keep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/jun_java_plugins/jun_hibernate/pom.xml b/jun_java_plugins/jun_hibernate/pom.xml deleted file mode 100644 index 4321055792..0000000000 --- a/jun_java_plugins/jun_hibernate/pom.xml +++ /dev/null @@ -1,120 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_hibernate - 1.0 - jar - - jun_hibernate - - - UTF-8 - 1.8 - 1.8 - - - - - junit - junit - 4.12 - test - - - org.hibernate - hibernate-core - 5.4.17.Final - - - mysql - mysql-connector-java - 5.1.48 - - - org.springframework - spring-orm - 4.3.6.RELEASE - - - org.aspectj - aspectjweaver - 1.8.9 - - - org.springframework - spring-test - 4.3.6.RELEASE - - - org.springframework - spring-context - 4.3.6.RELEASE - - - commons-dbcp - commons-dbcp - 1.4 - - - com.alibaba - druid - 1.2.3 - - - com.oracle - ojdbc6 - 11.2.0.3 - - - - - - - - - - maven-clean-plugin - 3.1.0 - - - - maven-resources-plugin - 3.0.2 - - - maven-compiler-plugin - 3.8.0 - - - maven-surefire-plugin - 2.22.1 - - - maven-jar-plugin - 3.0.2 - - - maven-install-plugin - 2.5.2 - - - maven-deploy-plugin - 2.8.2 - - - - maven-site-plugin - 3.7.1 - - - maven-project-info-reports-plugin - 3.0.0 - - - - - diff --git a/jun_java_plugins/jun_hibernate/src/main/java/com/jun/plugin/hibernate/App.java b/jun_java_plugins/jun_hibernate/src/main/java/com/jun/plugin/hibernate/App.java deleted file mode 100644 index 7415159560..0000000000 --- a/jun_java_plugins/jun_hibernate/src/main/java/com/jun/plugin/hibernate/App.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.jun.plugin.hibernate; - -/** - * Hello world! - * - */ -public class App -{ - public static void main( String[] args ) - { - System.out.println( "Hello World!" ); - } -} diff --git a/jun_java_plugins/jun_hibernate/src/main/java/com/jun/plugin/hibernate/dao/IEmpDao.java b/jun_java_plugins/jun_hibernate/src/main/java/com/jun/plugin/hibernate/dao/IEmpDao.java deleted file mode 100644 index a006962d4f..0000000000 --- a/jun_java_plugins/jun_hibernate/src/main/java/com/jun/plugin/hibernate/dao/IEmpDao.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jun.plugin.hibernate.dao; - -import java.util.List; - -import com.jun.plugin.hibernate.modal.EmpEntity; - -public interface IEmpDao { - - int count(); - - EmpEntity findByid(Short empno); - - List findList(Integer pageNo,Integer pageSize); - - int addEmp(EmpEntity e); - - int updateEmp(EmpEntity e); - - int removeEmp(Short empno); - -} diff --git a/jun_java_plugins/jun_hibernate/src/main/java/com/jun/plugin/hibernate/dao/impl/EmpDao.java b/jun_java_plugins/jun_hibernate/src/main/java/com/jun/plugin/hibernate/dao/impl/EmpDao.java deleted file mode 100644 index c632b94b54..0000000000 --- a/jun_java_plugins/jun_hibernate/src/main/java/com/jun/plugin/hibernate/dao/impl/EmpDao.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.jun.plugin.hibernate.dao.impl; - -import org.hibernate.HibernateException; -import org.hibernate.Session; -import org.hibernate.query.Query; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.orm.hibernate5.HibernateCallback; -import org.springframework.orm.hibernate5.HibernateTemplate; -import org.springframework.stereotype.Repository; - -import com.jun.plugin.hibernate.dao.IEmpDao; -import com.jun.plugin.hibernate.modal.EmpEntity; - -import java.util.List; - - -@Repository -public class EmpDao implements IEmpDao { - - - @Autowired - private HibernateTemplate hibernateTemplate; - - @Override - public int count() { - Integer cnt = hibernateTemplate.execute(new HibernateCallback() { - @Override - public Integer doInHibernate(Session session) throws HibernateException { - String hql = "select count(e.empno) from EmpEntity e"; - Query query = session.createQuery(hql); - Long sum = (Long) query.uniqueResult(); - return sum.intValue(); - } - }); - return cnt; - } - - @Override - public EmpEntity findByid(Short empno) { - return hibernateTemplate.get(EmpEntity.class,empno); - } - - @Override - public List findList(Integer pageNo, Integer pageSize) { - List empList = hibernateTemplate.execute(new HibernateCallback>() { - @Override - public List doInHibernate(Session session) throws HibernateException { - String hql = "from EmpEntity "; - Query query = session.createQuery(hql); - query.setFirstResult((pageNo-1)*pageSize);//从第几页开始 - query.setMaxResults(pageSize);//获取多少页 - List result = query.list(); - return result; - } - }); - return empList; - } - - @Override - public int addEmp(EmpEntity e) { - hibernateTemplate.save(e); - return 1; - } - - @Override - public int updateEmp(EmpEntity e) { - hibernateTemplate.update(e); - return 1; - } - - @Override - public int removeEmp(Short empno) { - EmpEntity e = new EmpEntity(); - e.setEmpno(empno); - hibernateTemplate.delete(e); - return 1; - } -} diff --git a/jun_java_plugins/jun_hibernate/src/main/java/com/jun/plugin/hibernate/modal/DeptEntity.java b/jun_java_plugins/jun_hibernate/src/main/java/com/jun/plugin/hibernate/modal/DeptEntity.java deleted file mode 100644 index 4c5cfed39a..0000000000 --- a/jun_java_plugins/jun_hibernate/src/main/java/com/jun/plugin/hibernate/modal/DeptEntity.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.jun.plugin.hibernate.modal; - -import java.util.Objects; - -public class DeptEntity { - private Byte deptno; - private String deptName; - private String loc; - - public Byte getDeptno() { - return deptno; - } - - public void setDeptno(Byte deptno) { - this.deptno = deptno; - } - - public String getDeptName() { - return deptName; - } - - public void setDeptName(String deptName) { - this.deptName = deptName; - } - - public String getLoc() { - return loc; - } - - public void setLoc(String loc) { - this.loc = loc; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - DeptEntity that = (DeptEntity) o; - return Objects.equals(deptno, that.deptno) && - Objects.equals(deptName, that.deptName) && - Objects.equals(loc, that.loc); - } - - @Override - public int hashCode() { - return Objects.hash(deptno, deptName, loc); - } -} diff --git a/jun_java_plugins/jun_hibernate/src/main/java/com/jun/plugin/hibernate/modal/EmpEntity.java b/jun_java_plugins/jun_hibernate/src/main/java/com/jun/plugin/hibernate/modal/EmpEntity.java deleted file mode 100644 index 2fdbbd644c..0000000000 --- a/jun_java_plugins/jun_hibernate/src/main/java/com/jun/plugin/hibernate/modal/EmpEntity.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.jun.plugin.hibernate.modal; - -import java.util.Date; -import java.util.Objects; - -public class EmpEntity { - private Short empno; - private String empName; - private String job; - private Long mgr; - private Date hiredate; - private Long sal; - private Double comm; - - public Short getEmpno() { - return empno; - } - - public void setEmpno(Short empno) { - this.empno = empno; - } - - public String getEmpName() { - return empName; - } - - public void setEmpName(String empName) { - this.empName = empName; - } - - public String getJob() { - return job; - } - - public void setJob(String job) { - this.job = job; - } - - public Long getMgr() { - return mgr; - } - - public void setMgr(Long mgr) { - this.mgr = mgr; - } - - public Date getHiredate() { - return hiredate; - } - - public void setHiredate(Date hiredate) { - this.hiredate = hiredate; - } - - public Long getSal() { - return sal; - } - - public void setSal(Long sal) { - this.sal = sal; - } - - public Double getComm() { - return comm; - } - - public void setComm(Double comm) { - this.comm = comm; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - EmpEntity empEntity = (EmpEntity) o; - return Objects.equals(empno, empEntity.empno) && - Objects.equals(empName, empEntity.empName) && - Objects.equals(job, empEntity.job) && - Objects.equals(mgr, empEntity.mgr) && - Objects.equals(hiredate, empEntity.hiredate) && - Objects.equals(sal, empEntity.sal) && - Objects.equals(comm, empEntity.comm); - } - - @Override - public int hashCode() { - return Objects.hash(empno, empName, job, mgr, hiredate, sal, comm); - } -} diff --git a/jun_java_plugins/jun_hibernate/src/main/java/com/jun/plugin/hibernate/service/IEmpService.java b/jun_java_plugins/jun_hibernate/src/main/java/com/jun/plugin/hibernate/service/IEmpService.java deleted file mode 100644 index 7b8616cf2f..0000000000 --- a/jun_java_plugins/jun_hibernate/src/main/java/com/jun/plugin/hibernate/service/IEmpService.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jun.plugin.hibernate.service; - -import java.util.List; - -import com.jun.plugin.hibernate.modal.EmpEntity; - -public interface IEmpService { - - int count(); - - EmpEntity findByid(Short empno); - - List findList(Integer pageNo, Integer pageSize); - - int addEmp(EmpEntity e); - - int updateEmp(EmpEntity e); - - int removeEmp(Short empno); - -} diff --git a/jun_java_plugins/jun_hibernate/src/main/java/com/jun/plugin/hibernate/service/impl/EmpService.java b/jun_java_plugins/jun_hibernate/src/main/java/com/jun/plugin/hibernate/service/impl/EmpService.java deleted file mode 100644 index d7ae4d51f9..0000000000 --- a/jun_java_plugins/jun_hibernate/src/main/java/com/jun/plugin/hibernate/service/impl/EmpService.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.jun.plugin.hibernate.service.impl; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import com.jun.plugin.hibernate.dao.IEmpDao; -import com.jun.plugin.hibernate.modal.EmpEntity; -import com.jun.plugin.hibernate.service.IEmpService; - -import java.util.List; - -@Service -public class EmpService implements IEmpService { - - @Autowired - private IEmpDao empDao; - - @Override - public int count() { - return empDao.count(); - } - - @Override - public EmpEntity findByid(Short empno) { - return empDao.findByid(empno); - } - - @Override - public List findList(Integer pageNo, Integer pageSize) { - return empDao.findList(pageNo,pageSize); - } - - @Override - public int addEmp(EmpEntity e) { - return empDao.addEmp(e); - } - - @Override - public int updateEmp(EmpEntity e) { - return empDao.updateEmp(e); - } - - @Override - public int removeEmp(Short empno) { - return empDao.removeEmp(empno); - } -} diff --git a/jun_java_plugins/jun_hibernate/src/main/resources/hbm/DeptEntity.hbm.xml b/jun_java_plugins/jun_hibernate/src/main/resources/hbm/DeptEntity.hbm.xml deleted file mode 100644 index 4b196e82e8..0000000000 --- a/jun_java_plugins/jun_hibernate/src/main/resources/hbm/DeptEntity.hbm.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_hibernate/src/main/resources/hbm/EmpEntity.hbm.xml b/jun_java_plugins/jun_hibernate/src/main/resources/hbm/EmpEntity.hbm.xml deleted file mode 100644 index 27d2fa073c..0000000000 --- a/jun_java_plugins/jun_hibernate/src/main/resources/hbm/EmpEntity.hbm.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_hibernate/src/main/resources/hibernate.cfg.xml b/jun_java_plugins/jun_hibernate/src/main/resources/hibernate.cfg.xml deleted file mode 100644 index df176ffb94..0000000000 --- a/jun_java_plugins/jun_hibernate/src/main/resources/hibernate.cfg.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - jdbc:oracle:thin:@localhost:1521:orcl - oracle.jdbc.OracleDriver - scott - orcl - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_hibernate/src/main/resources/spring-core.xml b/jun_java_plugins/jun_hibernate/src/main/resources/spring-core.xml deleted file mode 100644 index 3f7d29fd94..0000000000 --- a/jun_java_plugins/jun_hibernate/src/main/resources/spring-core.xml +++ /dev/null @@ -1,58 +0,0 @@ - - - - - - - - - - - - - - - - - - - org.hibernate.dialect.Oracle10gDialect - - true - true - update - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_hibernate/src/test/java/com/jun/plugin/hibernate/AppTest.java b/jun_java_plugins/jun_hibernate/src/test/java/com/jun/plugin/hibernate/AppTest.java deleted file mode 100644 index 348681d7bc..0000000000 --- a/jun_java_plugins/jun_hibernate/src/test/java/com/jun/plugin/hibernate/AppTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.jun.plugin.hibernate; - -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -/** - * Unit test for simple App. - */ -public class AppTest -{ - /** - * Rigorous Test :-) - */ - @Test - public void shouldAnswerWithTrue() - { - assertTrue( true ); - } -} diff --git a/jun_java_plugins/jun_hibernate/src/test/java/com/jun/plugin/hibernate/test1.java b/jun_java_plugins/jun_hibernate/src/test/java/com/jun/plugin/hibernate/test1.java deleted file mode 100644 index 75ac9ba0ba..0000000000 --- a/jun_java_plugins/jun_hibernate/src/test/java/com/jun/plugin/hibernate/test1.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.jun.plugin.hibernate; - -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.Transaction; -import org.hibernate.cfg.Configuration; -import org.hibernate.query.Query; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.jun.plugin.hibernate.modal.EmpEntity; - -import java.util.List; - -public class test1 { - - - private Session ss; - - @Before - public void beforeRun(){ - // 加载配置 初始化框架 - Configuration config = new Configuration().configure(); - // 获取会话工厂 - SessionFactory sf = config.buildSessionFactory(); - // 获取Session - ss = sf.openSession(); - } - - @Test - public void fun1(){ - - EmpEntity e = ss.get(EmpEntity.class,new Short("7369")); - System.out.println(e.getEmpName()); - - } - - @Test - public void fun2(){ - EmpEntity e = new EmpEntity(); - e.setEmpName("员工A"); - e.setEmpno(new Short("8080")); - Transaction tc = ss.beginTransaction(); - ss.save(e); - tc.commit(); - } - - @Test - public void fun3(){ - EmpEntity e = new EmpEntity(); - e.setEmpName("员工B"); - e.setEmpno(new Short("8080")); - Transaction tc = ss.beginTransaction(); - try { - ss.update(e); - tc.commit(); - } catch (Exception exception) { - exception.printStackTrace(); - tc.rollback(); - } - } - - @Test - public void fun4(){ - String hql = "from EmpEntity"; - Query query = ss.createQuery(hql); - List empList = query.list(); - for(EmpEntity e : empList){ - System.out.println(e.getEmpName()); - } - } - - @After - public void afterRun(){ - // 关闭Session - ss.close(); - } -} diff --git a/jun_java_plugins/jun_hibernate/src/test/java/com/jun/plugin/hibernate/test2.java b/jun_java_plugins/jun_hibernate/src/test/java/com/jun/plugin/hibernate/test2.java deleted file mode 100644 index a53722bc5c..0000000000 --- a/jun_java_plugins/jun_hibernate/src/test/java/com/jun/plugin/hibernate/test2.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.jun.plugin.hibernate; - - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.jun.plugin.hibernate.modal.EmpEntity; -import com.jun.plugin.hibernate.service.IEmpService; - -import java.util.List; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:spring-core.xml") -public class test2 { - - @Autowired - private IEmpService empService; - - @Test - public void fun1(){ - Integer count = empService.count(); - System.out.println(count); - } - - @Test - public void fun2(){ - List emps = empService.findList(2,5); - System.out.println(emps.size()); - } - - - @Test - public void fun3(){ - EmpEntity e = new EmpEntity(); - e.setEmpName("员工BBB"); - e.setEmpno(new Short("8081")); - empService.addEmp(e); - } - - @Test - public void fun5(){ - EmpEntity e = new EmpEntity(); - e.setEmpno(new Short("8081")); - e.setEmpName("admin123"); - empService.updateEmp(e); - } - -} diff --git a/jun_java_plugins/jun_httpclient/README.md b/jun_java_plugins/jun_httpclient/README.md deleted file mode 100644 index ef1042f0d1..0000000000 --- a/jun_java_plugins/jun_httpclient/README.md +++ /dev/null @@ -1,200 +0,0 @@ -# httpclientutil - -该项目基于HttpClient-4.4.1封装的一个工具类,支持插件式配置Header、插件式配置httpclient对象,这样就可以方便地自定义header信息、配置ssl、配置proxy等。 - -## Maven坐标: -``` - - - com.arronlong - httpclientutil - 1.0.4 - -``` - -## 简单Demo -在test包里还有各种测试[demo](http://mfxuan.free.800m.net/demo.png),各测试类的源码在src/test/java/com/httpclient/test包路径下。 -``` -public static void main(String[] args) throws HttpProcessException, FileNotFoundException { - String url = "https://github.com/Arronlong/httpclientutil"; - - //最简单的使用: - String html = HttpClientUtil.get(HttpConfig.custom().url(url)); - System.out.println(html); - - //--------------------------------- - // 【详细说明】 - //-------------------------------- - - //插件式配置Header(各种header信息、自定义header) - Header[] headers = HttpHeader.custom() - .userAgent("javacl") - .other("customer", "自定义") - .build(); - - //插件式配置生成HttpClient时所需参数(超时、连接池、ssl、重试) - HCB hcb = HCB.custom() - .timeout(1000) //超时 - .pool(100, 10) //启用连接池,每个路由最大创建10个链接,总连接数限制为100个 - .sslpv(SSLProtocolVersion.TLSv1_2) //设置ssl版本号,默认SSLv3,也可以调用sslpv("TLSv1.2") - .ssl() //https,支持自定义ssl证书路径和密码,ssl(String keyStorePath, String keyStorepass) - .retry(5) //重试5次 - ; - - HttpClient client = hcb.build(); - - Map map = new HashMap(); - map.put("key1", "value1"); - map.put("key2", "value2"); - - //插件式配置请求参数(网址、请求参数、编码、client) - HttpConfig config = HttpConfig.custom() - .headers(headers) //设置headers,不需要时则无需设置 - .url(url) //设置请求的url - .map(map) //设置请求参数,没有则无需设置 - .encoding("utf-8") //设置请求和返回编码,默认就是Charset.defaultCharset() - .client(client) //如果只是简单使用,无需设置,会自动获取默认的一个client对象 - //.inenc("utf-8") //设置请求编码,如果请求返回一直,不需要再单独设置 - //.inenc("utf-8") //设置返回编码,如果请求返回一直,不需要再单独设置 - //.json("json字符串") //json方式请求的话,就不用设置map方法,当然二者可以共用。 - //.context(HttpCookies.custom().getContext()) //设置cookie,用于完成携带cookie的操作 - //.out(new FileOutputStream("保存地址")) //下载的话,设置这个方法,否则不要设置 - //.files(new String[]{"d:/1.txt","d:/2.txt"}) //上传的话,传递文件路径,一般还需map配置,设置服务器保存路径 - ; - - - //使用方式: - String result1 = HttpClientUtil.get(config); //get请求 - String result2 = HttpClientUtil.post(config); //post请求 - System.out.println(result1); - System.out.println(result2); - - //HttpClientUtil.down(config); //下载,需要调用config.out(fileOutputStream对象) - //HttpClientUtil.upload(config); //上传,需要调用config.files(文件路径数组) - - //如果指向看是否访问正常 - //String result3 = HttpClientUtil.head(config); // 返回Http协议号+状态码 - //int statusCode = HttpClientUtil.status(config);//返回状态码 - - //[新增方法]sendAndGetResp,可以返回原生的HttpResponse对象, - //同时返回常用的几类对象:result、header、StatusLine、StatusCode - HttpResult respResult = HttpClientUtil.sendAndGetResp(config); - System.out.println("返回结果:\n"+respResult.getResult()); - System.out.println("返回resp-header:"+respResult.getRespHeaders());//可以遍历 - System.out.println("返回具体resp-header:"+respResult.getHeaders("Date")); - System.out.println("返回StatusLine对象:"+respResult.getStatusLine()); - System.out.println("返回StatusCode:"+respResult.getStatusCode()); - System.out.println("返回HttpResponse对象)(可自行处理):"+respResult.getResp()); -} -``` - -![image](http://box.kancloud.cn/cover_2016-01-11_5693502e2de2_800x1068.jpg?imageMogr2/thumbnail/346x462!/interlace/1/quality/100)| 专栏创建者:[xiaoxian8023](http://blog.csdn.net/xiaoxian8023)
创建时间:2015-11-16
文章数:17篇
[RSS订阅](http://blog.csdn.net/xiaoxian8023/rss/list)

[轻松把玩HttpClient](http://blog.csdn.net/column/details/httpclient-arron.html)
介绍如何使用HttpClient,通过一些简单示例,来帮助初学者快速入手。
同时提供了一个非常强大的工具类,比现在网络上分享的都强大:
支持插件式设置header、代理、ssl等配置信息,支持携带Cookie的操作,支持http的各种方法,支持上传、下载等功能。 ----|--- - - ---- - -# 最新更新文章 -## ![image](http://static.blog.csdn.net/images/icon-zhuanjia.gif "专家") [轻松把玩HttpClient之封装HttpClient工具类(九),添加多文件上传功能](http://blog.csdn.net/xiaoxian8023/article/details/53065507) -``` -在Git上有人给我提Issue,说怎么上传文件,其实我一开始就想上这个功能,不过这半年比较忙,所以一直耽搁了。 -这次正好没什么任务了,赶紧完成这个功能。毕竟作为一款工具类,有基本的请求和下载功能,就差上... -``` -## ![image](http://static.blog.csdn.net/images/icon-zhuanjia.gif "专家") [轻松把玩HttpClient之封装HttpClient工具类(八),优化启用Http连接池策略](http://blog.csdn.net/xiaoxian8023/article/details/53064210) -``` -写了HttpClient工具类后,有人一直在问我怎么启用http连接池,其实我没考虑过这个问题难过。 -不过闲暇的时候,突然间想起了这个问题,就想把这个问题搞一搞。 -``` -## ![image](http://static.blog.csdn.net/images/icon-zhuanjia.gif "专家") [轻松把玩HttpClient之封装HttpClient工具类(七),新增验证码识别功能](http://blog.csdn.net/xiaoxian8023/article/details/51606865) -``` -这个HttpClientUtil工具类分享在GitHub上已经半年多的时间了,并且得到了不小的关注,有25颗star,被fork了38次。 -有了大家的鼓励,工具类一直也在完善中。最近比较忙,两个多月前的修改在今天刚修改测试完成,今天再次分享给大家。 -验证码识别这项技术并不是本工具类的功能,而是通过一个开源的api来识别验证码的。 -这里做了一个简单的封装,主要是用来解决登陆时的验证码的问题。... -``` -## ![image](http://static.blog.csdn.net/images/icon-zhuanjia.gif "专家") [轻松把玩HttpClient之封装HttpClient工具类(六),封装输入参数,简化工具类](http://blog.csdn.net/xiaoxian8023/article/details/50768320) -``` -在写这个工具类的时候发现传入的参数太多,以至于方法泛滥,只一个send方法就有30多个, -所以对工具类进行了优化,把输入参数封装在一个对象里,这样以后再扩展输入参数,直接修改这个类就ok了。 -``` -## ![image](http://static.blog.csdn.net/images/icon-zhuanjia.gif "专家") [轻松把玩HttpClient之封装HttpClient工具类(五),携带Cookie的请求](http://blog.csdn.net/xiaoxian8023/article/details/50474987) -``` -最近更新了一下HttpClientUtil工具类代码,主要是添加了一个参数HttpContext,这个是用来干嘛的呢? -其实是用来保存和传递Cookie所需要的。因为我们有很多时候都需要登录,然后才能请求一些想要的数据。 -而在这以前使用HttpClientUtil工具类,还不能办到。现在更新了以后,终于可以了。 -先说一下思路:本次的demo,就是获取csdn中的c币,要想获取c币,必须先登... -``` -## ![image](http://static.blog.csdn.net/images/icon-zhuanjia.gif "专家") [轻松把玩HttpAsyncClient之模拟post请求示例](http://blog.csdn.net/xiaoxian8023/article/details/49949813) -``` -如果看到过我前些天写过的《轻松把玩HttpClient之模拟post请求示例》这篇文章,你再看本文就是小菜一碟了,如果你顺便懂一些NIO,基本上是毫无压力了。 -因为HttpAsyncClient相对于HttpClient,就多了一个NIO,这也是为什么支持异步的原因。 -不过我有一个疑问,虽说NIO是同步非阻塞IO,但是HttpAsyncClient提供了回调的机制, -这点儿跟netty很像,所以可以模拟... -``` -## ![image](http://static.blog.csdn.net/images/icon-zhuanjia.gif "专家") [轻松把玩HttpClient之封装HttpClient工具类(四),单线程调用及多线程批量调用测试](http://blog.csdn.net/xiaoxian8023/article/details/49910885) -``` -本文主要来分享一下该工具类的测试结果。工具类的整体源码不再单独分享,源码基本上都已经在文章中了。 -开始我们的测试。单线程调用测试: - public static void testOne() throws HttpProcessException{ - - System.out.println("--------简单方式调用(默认post)--------"); - String url = "http://... -``` -## ![image](http://static.blog.csdn.net/images/icon-zhuanjia.gif "专家") [轻松把玩HttpClient之封装HttpClient工具类(三),插件式配置Header](http://blog.csdn.net/xiaoxian8023/article/details/49910127) -``` -上篇文章介绍了插件式配置HttpClient,本文将介绍插件式配置Header。为什么要配置header在前面已经提到了,还里再简单说一下, -要使用HttpClient模拟请求,去访问各种接口或者网站资源,都有可能有各种限制, -比如说java客户端模拟访问csdn博客,就必须设置User-Agent,否则就报错了。 -还有各种其他情况,必须的设置一些特定的Header,才能请求成功,或者才能不出问题。好了... -``` -## ![image](http://static.blog.csdn.net/images/icon-zhuanjia.gif "专家") [轻松把玩HttpClient之封装HttpClient工具类(二),插件式配置HttpClient对象](http://blog.csdn.net/xiaoxian8023/article/details/49909359) -``` -上一篇文章中,简单分享一下封装HttpClient工具类的思路及部分代码,本文将分享如何实现插件式配置HttpClient对象。 -如果你看过我前面的几篇关于HttpClient的文章或者官网示例,应该都知道HttpClient对象在创建时,都可以设置各种参数, -但是却没有简单的进行封装,比如对我来说比较重要的3个: -代理、ssl(包含绕过证书验证和自定义证书验证)、超时。还需要自己写。 -所以这里我就简单封... -``` -## ![image](http://static.blog.csdn.net/images/icon-zhuanjia.gif "专家") [轻松把玩HttpClient之封装HttpClient工具类(一)(现有网上分享中的最强大的工具类)](http://blog.csdn.net/xiaoxian8023/article/details/49883113) -``` -搜了一下网络上别人封装的HttpClient,大部分特别简单,有一些看起来比较高级,但是用起来都不怎么好用。 -调用关系不清楚,结构有点混乱。所以也就萌生了自己封装HttpClient工具类的想法。 -要做就做最好的,本工具类支持插件式配置Header、插件式配置httpclient对象, -这样就可以方便地自定义header信息、配置ssl、配置proxy等。是不是觉得说的有点悬乎了,那就先看看调用吧:... -``` -## ![image](http://static.blog.csdn.net/images/icon-zhuanjia.gif "专家") [轻松把玩HttpClient之设置代理,可以访问FaceBook](http://blog.csdn.net/xiaoxian8023/article/details/49867257) -``` -前面的文章介绍了一些HttpClient的简单示例,本文继续采用示例的方式来演示HttpClient的功能。 -在项目中我们可能会遇到这样的情况:为了保证系统的安全性,只允许使用特定的代理才可以访问, -而与这些系统使用HttpClient进行交互时,只能为其配置代理。 -这里我们使用gogent代理访问脸书来模拟这种情况。现在在浏览器上访问是可以访问的:... -``` -## ![image](http://static.blog.csdn.net/images/icon-zhuanjia.gif "专家") [轻松把玩HttpClient之配置ssl,采用设置信任自签名证书实现https](http://blog.csdn.net/xiaoxian8023/article/details/49866397) -``` -在上篇文章《HttpClient配置ssl实现https简单示例——绕过证书验证》中简单分享了一下如何绕过证书验证。 -如果你想用httpclient访问一个网站,但是对方的证书没有通过ca认证或者其他问题导致证书不被信任, -比如12306的证书就是这样的。所以对于这样的情况,你只能是选择绕过证书验证的方案了。 -但是,如果是自己用jdk或者其他工具生成的证书,还是希望用其他方式认证自签名的证书,这篇文... -``` -## ![image](http://static.blog.csdn.net/images/icon-zhuanjia.gif "专家") [轻松把玩HttpClient之配置ssl,采用绕过证书验证实现https](http://blog.csdn.net/xiaoxian8023/article/details/49865335) -``` -上篇文章说道httpclient不能直接访问https的资源,这次就来模拟一下环境,然后配置https测试一下。 -在前面的文章中,分享了一篇自己生成并在tomcat中配置ssl的文章《Tomcat配置SSL》,大家可以据此来在本地配置https。 -我已经配置好了,效果是这样滴: -可以看到已经信任该证书(显示浅绿色小锁),浏览器可以正常访问。现在我们用代码测试一下: -``` -## ![image](http://static.blog.csdn.net/images/icon-zhuanjia.gif "专家") [轻松把玩HttpClient之模拟post请求示例](http://blog.csdn.net/xiaoxian8023/article/details/49863967) -``` -HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。 -许多需要后台模拟请求的系统或者框架都用的是httpclient。所以作为一个java开发人员,有必要学一学。 -本文提供了一个简单的demo,供初学者参考。 -``` -## ![image](http://static.blog.csdn.net/images/icon-zhuanjia.gif "专家") [简单的利用UrlConnection,后台模拟http请求](http://blog.csdn.net/xiaoxian8023/article/details/49785417) -``` -这两天在整理看httpclient,然后想自己用UrlConnection后台模拟实现Http请求,于是一个简单的小例子就新鲜出炉了(支持代理哦): - public class SimpleHttpTest { - - public static String send(String urlStr, Map map,String encoding){ - String body=""; - Strin... -``` diff --git a/jun_java_plugins/jun_httpclient/pom.xml b/jun_java_plugins/jun_httpclient/pom.xml deleted file mode 100644 index 30ec216669..0000000000 --- a/jun_java_plugins/jun_httpclient/pom.xml +++ /dev/null @@ -1,117 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_httpclient - 1.0 - war - - - UTF-8 - - - - - - org.apache.commons - commons-lang3 - 3.8 - - - - org.apache.httpcomponents - httpasyncclient - 4.1 - - - - log4j - log4j - 1.2.17 - - - - - junit - junit - 4.1 - test - - - - org.apache.httpcomponents - httpclient - 4.5.2 - - - - org.apache.httpcomponents - httpmime - 4.5 - - - - commons-io - commons-io - 2.6 - - - - - - - - - mysql - mysql-connector-java - 5.1.40 - - - - - org.slf4j - slf4j-api - 1.7.30 - - - org.slf4j - slf4j-log4j12 - 1.7.30 - - - commons-lang - commons-lang - 2.6 - - - net.sf.json-lib - json-lib - 2.4 - jdk15 - - - xerces - xercesImpl - 2.12.0 - - - - jun_httpclient - - diff --git a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/base/HttpDownload.java b/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/base/HttpDownload.java deleted file mode 100644 index 8b482669c7..0000000000 --- a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/base/HttpDownload.java +++ /dev/null @@ -1,111 +0,0 @@ -// This file is commented out — file download utility using deprecated DefaultHttpClient. -// See jun_httpclient base package for maintained HTTP download functionality. -/* -package com.jun.plugin.httpclient.base; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.InputStream; - -import org.apache.http.Header; -import org.apache.http.HeaderElement; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.NameValuePair; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.DefaultHttpClient; - -public class HttpDownload { - - public static final int cache = 10 * 1024; - public static final boolean isWindows; - public static final String splash; - public static final String root; - static { - if (System.getProperty("os.name") != null && System.getProperty("os.name").toLowerCase().contains("windows")) { - isWindows = true; - splash = "\\"; - root = "D:"; - } else { - isWindows = false; - splash = "/"; - root = "/search"; - } - } - - public static String download(String url) { - return download(url, null); - } - - public static String download(String url, String filepath) { - try { - HttpClient client = new DefaultHttpClient(); - HttpGet httpget = new HttpGet(url); - HttpResponse response = client.execute(httpget); - HttpEntity entity = response.getEntity(); - InputStream is = entity.getContent(); - if (filepath == null) - filepath = getFilePath(response); - File file = new File(filepath); - file.getParentFile().mkdirs(); - FileOutputStream fileout = new FileOutputStream(file); - byte[] buffer = new byte[cache]; - int ch = 0; - while ((ch = is.read(buffer)) != -1) { - fileout.write(buffer, 0, ch); - } - is.close(); - fileout.flush(); - fileout.close(); - if (file.length() < 255) { - file.delete(); - } - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static String getFilePath(HttpResponse response) { - String filepath = root + splash; - String filename = getFileName(response); - if (filename != null) { - filepath += filename; - } else { - filepath += getRandomFileName(); - } - return filepath; - } - - public static String getFileName(HttpResponse response) { - Header contentHeader = response.getFirstHeader("Content-Disposition"); - String filename = null; - if (contentHeader != null) { - HeaderElement[] values = contentHeader.getElements(); - if (values.length == 1) { - NameValuePair param = values[0].getParameterByName("filename"); - if (param != null) { - try { - filename = param.getValue(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - } - return filename; - } - - public static String getRandomFileName() { - return String.valueOf(System.currentTimeMillis()); - } - - public static void outHeaders(HttpResponse response) { - Header[] headers = response.getAllHeaders(); - for (int i = 0; i < headers.length; i++) { - System.out.println(headers[i]); - } - } -} -*/ diff --git a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/HttpClientUtil.java b/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/HttpClientUtil.java deleted file mode 100644 index fdd71bf1de..0000000000 --- a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/HttpClientUtil.java +++ /dev/null @@ -1,594 +0,0 @@ -package com.jun.plugin.httpclient.httpclientutil; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.apache.http.Header; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.NameValuePair; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpHead; -import org.apache.http.client.methods.HttpOptions; -import org.apache.http.client.methods.HttpPatch; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.client.methods.HttpTrace; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.EntityUtils; - -import com.jun.plugin.httpclient.httpclientutil.builder.HCB; -import com.jun.plugin.httpclient.httpclientutil.common.HttpConfig; -import com.jun.plugin.httpclient.httpclientutil.common.HttpMethods; -import com.jun.plugin.httpclient.httpclientutil.common.HttpResult; -import com.jun.plugin.httpclient.httpclientutil.common.Utils; -import com.jun.plugin.httpclient.httpclientutil.exception.HttpProcessException; - -/** - * 使用HttpClient模拟发送(http/https)请求 - * - * @author arron - * @version 1.0 - */ -public class HttpClientUtil{ - - //默认采用的http协议的HttpClient对象 - private static HttpClient client4HTTP; - - //默认采用的https协议的HttpClient对象 - private static HttpClient client4HTTPS; - - static{ - try { - client4HTTP = HCB.custom().build(); - client4HTTPS = HCB.custom().ssl().build(); - } catch (HttpProcessException e) { - Utils.errorException("创建https协议的HttpClient对象出错:{}", e); - } - } - - /** - * 判定是否开启连接池、及url是http还是https
- * 如果已开启连接池,则自动调用build方法,从连接池中获取client对象
- * 否则,直接返回相应的默认client对象
- * - * @param config 请求参数配置 - * @throws HttpProcessException http处理异常 - */ - private static void create(HttpConfig config) throws HttpProcessException { - if(config.client()==null){//如果为空,设为默认client对象 - if(config.url().toLowerCase().startsWith("https://")){ - config.client(client4HTTPS); - }else{ - config.client(client4HTTP); - } - } - } - - //-----------华----丽----分----割----线-------------- - //-----------华----丽----分----割----线-------------- - //-----------华----丽----分----割----线-------------- - - /** - * 以Get方式,请求资源或服务 - * - * @param client client对象 - * @param url 资源地址 - * @param headers 请求头信息 - * @param context http上下文,用于cookie操作 - * @param encoding 编码 - * @return 返回处理结果 - * @throws HttpProcessException http处理异常 - */ - public static String get(HttpClient client, String url, Header[] headers, HttpContext context, String encoding) throws HttpProcessException { - return get(HttpConfig.custom().client(client).url(url).headers(headers).context(context).encoding(encoding)); - } - /** - * 以Get方式,请求资源或服务 - * - * @param config 请求参数配置 - * @return 返回结果 - * @throws HttpProcessException http处理异常 - */ - public static String get(HttpConfig config) throws HttpProcessException { - return send(config.method(HttpMethods.GET)); - } - - /** - * 以Post方式,请求资源或服务 - * - * @param client client对象 - * @param url 资源地址 - * @param headers 请求头信息 - * @param parasMap 请求参数 - * @param context http上下文,用于cookie操作 - * @param encoding 编码 - * @return 返回处理结果 - * @throws HttpProcessException http处理异常 - */ - public static String post(HttpClient client, String url, Header[] headers, MapparasMap, HttpContext context, String encoding) throws HttpProcessException { - return post(HttpConfig.custom().client(client).url(url).headers(headers).map(parasMap).context(context).encoding(encoding)); - } - /** - * 以Post方式,请求资源或服务 - * - * @param config 请求参数配置 - * @return 返回处理结果 - * @throws HttpProcessException http处理异常 - */ - public static String post(HttpConfig config) throws HttpProcessException { - return send(config.method(HttpMethods.POST)); - } - - /** - * 以Put方式,请求资源或服务 - * - * @param client client对象 - * @param url 资源地址 - * @param parasMap 请求参数 - * @param headers 请求头信息 - * @param context http上下文,用于cookie操作 - * @param encoding 编码 - * @return 返回处理结果 - * @throws HttpProcessException http处理异常 - */ - public static String put(HttpClient client, String url, MapparasMap,Header[] headers, HttpContext context,String encoding) throws HttpProcessException { - return put(HttpConfig.custom().client(client).url(url).headers(headers).map(parasMap).context(context).encoding(encoding)); - } - /** - * 以Put方式,请求资源或服务 - * - * @param config 请求参数配置 - * @return 返回处理结果 - * @throws HttpProcessException http处理异常 - */ - public static String put(HttpConfig config) throws HttpProcessException { - return send(config.method(HttpMethods.PUT)); - } - - /** - * 以Delete方式,请求资源或服务 - * - * @param client client对象 - * @param url 资源地址 - * @param headers 请求头信息 - * @param context http上下文,用于cookie操作 - * @param encoding 编码 - * @return 返回处理结果 - * @throws HttpProcessException http处理异常 - */ - public static String delete(HttpClient client, String url, Header[] headers, HttpContext context,String encoding) throws HttpProcessException { - return delete(HttpConfig.custom().client(client).url(url).headers(headers).context(context).encoding(encoding)); - } - /** - * 以Delete方式,请求资源或服务 - * - * @param config 请求参数配置 - * @return 返回处理结果 - * @throws HttpProcessException http处理异常 - */ - public static String delete(HttpConfig config) throws HttpProcessException { - return send(config.method(HttpMethods.DELETE)); - } - - /** - * 以Patch方式,请求资源或服务 - * - * @param client client对象 - * @param url 资源地址 - * @param parasMap 请求参数 - * @param headers 请求头信息 - * @param context http上下文,用于cookie操作 - * @param encoding 编码 - * @return 返回处理结果 - * @throws HttpProcessException http处理异常 - */ - public static String patch(HttpClient client, String url, MapparasMap, Header[] headers, HttpContext context,String encoding) throws HttpProcessException { - return patch(HttpConfig.custom().client(client).url(url).headers(headers).map(parasMap).context(context).encoding(encoding)); - } - /** - * 以Patch方式,请求资源或服务 - * - * @param config 请求参数配置 - * @return 返回处理结果 - * @throws HttpProcessException http处理异常 - */ - public static String patch(HttpConfig config) throws HttpProcessException { - return send(config.method(HttpMethods.PATCH)); - } - - /** - * 以Head方式,请求资源或服务 - * - * @param client client对象 - * @param url 资源地址 - * @param headers 请求头信息 - * @param context http上下文,用于cookie操作 - * @param encoding 编码 - * @return 返回处理结果 - * @throws HttpProcessException http处理异常 - */ - public static String head(HttpClient client, String url, Header[] headers, HttpContext context,String encoding) throws HttpProcessException { - return head(HttpConfig.custom().client(client).url(url).headers(headers).context(context).encoding(encoding)); - } - /** - * 以Head方式,请求资源或服务 - * - * @param config 请求参数配置 - * @return 返回处理结果 - * @throws HttpProcessException http处理异常 - */ - public static String head(HttpConfig config) throws HttpProcessException { - return send(config.method(HttpMethods.HEAD)); - } - - /** - * 以Options方式,请求资源或服务 - * - * @param client client对象 - * @param url 资源地址 - * @param headers 请求头信息 - * @param context http上下文,用于cookie操作 - * @param encoding 编码 - * @return 返回处理结果 - * @throws HttpProcessException http处理异常 - */ - public static String options(HttpClient client, String url, Header[] headers, HttpContext context,String encoding) throws HttpProcessException { - return options(HttpConfig.custom().client(client).url(url).headers(headers).context(context).encoding(encoding)); - } - /** - * 以Options方式,请求资源或服务 - * - * @param config 请求参数配置 - * @return 返回处理结果 - * @throws HttpProcessException http处理异常 - */ - public static String options(HttpConfig config) throws HttpProcessException { - return send(config.method(HttpMethods.OPTIONS)); - } - - /** - * 以Trace方式,请求资源或服务 - * - * @param client client对象 - * @param url 资源地址 - * @param headers 请求头信息 - * @param context http上下文,用于cookie操作 - * @param encoding 编码 - * @return 返回处理结果 - * @throws HttpProcessException http处理异常 - */ - public static String trace(HttpClient client, String url, Header[] headers, HttpContext context, String encoding) throws HttpProcessException { - return trace(HttpConfig.custom().client(client).url(url).headers(headers).context(context).encoding(encoding)); - } - /** - * 以Trace方式,请求资源或服务 - * - * @param config 请求参数配置 - * @return 返回处理结果 - * @throws HttpProcessException http处理异常 - */ - public static String trace(HttpConfig config) throws HttpProcessException { - return send(config.method(HttpMethods.TRACE)); - } - - /** - * 下载文件 - * - * @param client client对象 - * @param url 资源地址 - * @param headers 请求头信息 - * @param context http上下文,用于cookie操作 - * @param out 输出流 - * @return 返回处理结果 - * @throws HttpProcessException http处理异常 - */ - public static OutputStream down(HttpClient client, String url, Header[] headers, HttpContext context, OutputStream out) throws HttpProcessException { - return down(HttpConfig.custom().client(client).url(url).headers(headers).context(context).out(out)); - } - - /** - * 下载文件 - * - * @param config 请求参数配置 - * @return 返回处理结果 - * @throws HttpProcessException http处理异常 - */ - public static OutputStream down(HttpConfig config) throws HttpProcessException { - if(config.method() == null) { - config.method(HttpMethods.GET); - } - return fmt2Stream(execute(config), config.out()); - } - - /** - * 上传文件 - * - * @param client client对象 - * @param url 资源地址 - * @param headers 请求头信息 - * @param context http上下文,用于cookie操作 - * @return 返回处理结果 - * @throws HttpProcessException http处理异常 - */ - public static String upload(HttpClient client, String url, Header[] headers, HttpContext context) throws HttpProcessException { - return upload(HttpConfig.custom().client(client).url(url).headers(headers).context(context)); - } - - /** - * 上传文件 - * - * @param config 请求参数配置 - * @return 返回处理结果 - * @throws HttpProcessException http处理异常 - */ - public static String upload(HttpConfig config) throws HttpProcessException { - if(config.method() != HttpMethods.POST && config.method() != HttpMethods.PUT){ - config.method(HttpMethods.POST); - } - return send(config); - } - - /** - * 查看资源链接情况,返回状态码 - * - * @param client client对象 - * @param url 资源地址 - * @param headers 请求头信息 - * @param context http上下文,用于cookie操作 - * @return 返回处理结果 - * @throws HttpProcessException http处理异常 - */ - public static int status(HttpClient client, String url, Header[] headers, HttpContext context, HttpMethods method) throws HttpProcessException { - return status(HttpConfig.custom().client(client).url(url).headers(headers).context(context).method(method)); - } - - /** - * 查看资源链接情况,返回状态码 - * - * @param config 请求参数配置 - * @return 返回处理结果 - * @throws HttpProcessException http处理异常 - */ - public static int status(HttpConfig config) throws HttpProcessException { - return fmt2Int(execute(config)); - } - - //-----------华----丽----分----割----线-------------- - //-----------华----丽----分----割----线-------------- - //-----------华----丽----分----割----线-------------- - - /** - * 请求资源或服务 - * - * @param config 请求参数配置 - * @return 返回处理结果 - * @throws HttpProcessException http处理异常 - */ - public static String send(HttpConfig config) throws HttpProcessException { - return fmt2String(execute(config), config.outenc()); - } - - /** - * 请求资源或服务,返回HttpResult对象 - * - * @param config 请求参数配置 - * @return 返回HttpResult处理结果 - * @throws HttpProcessException http处理异常 - */ - public static HttpResult sendAndGetResp(HttpConfig config) throws HttpProcessException { - Header[] reqHeaders = config.headers(); - //执行结果 - HttpResponse resp = execute(config); - - HttpResult result = new HttpResult(resp); - result.setResult(fmt2String(resp, config.outenc())); - result.setReqHeaders(reqHeaders); - - return result; - } - - /** - * 请求资源或服务 - * - * @param config 请求参数配置 - * @return 返回HttpResponse对象 - * @throws HttpProcessException http处理异常 - */ - private static HttpResponse execute(HttpConfig config) throws HttpProcessException { - create(config);//获取链接 - HttpResponse resp = null; - - try { - //创建请求对象 - HttpRequestBase request = getRequest(config.url(), config.method()); - - //设置超时 - request.setConfig(config.requestConfig()); - - //设置header信息 - request.setHeaders(config.headers()); - - //判断是否支持设置entity(仅HttpPost、HttpPut、HttpPatch支持) - if(HttpEntityEnclosingRequestBase.class.isAssignableFrom(request.getClass())){ - List nvps = new ArrayList(); - - if(request.getClass()==HttpGet.class) { - //检测url中是否存在参数 - //注:只有get请求,才自动截取url中的参数,post等其他方式,不再截取 - config.url(Utils.checkHasParas(config.url(), nvps, config.inenc())); - } - - //装填参数 - HttpEntity entity = Utils.map2HttpEntity(nvps, config.map(), config.inenc()); - - //设置参数到请求对象中 - ((HttpEntityEnclosingRequestBase)request).setEntity(entity); - - Utils.info("请求地址:"+config.url()); - if(nvps.size()>0){ - Utils.info("请求参数:"+nvps.toString()); - } - if(config.json()!=null){ - Utils.info("请求参数:"+config.json()); - } - }else{ - int idx = config.url().indexOf("?"); - Utils.info("请求地址:"+config.url().substring(0, (idx>0 ? idx : config.url().length()))); - if(idx>0){ - Utils.info("请求参数:"+config.url().substring(idx+1)); - } - } - //执行请求操作,并拿到结果(同步阻塞) - resp = (config.context()==null)?config.client().execute(request) : config.client().execute(request, config.context()) ; - - if(config.isReturnRespHeaders()){ - //获取所有response的header信息 - config.headers(resp.getAllHeaders()); - } - - //获取结果实体 - return resp; - - } catch (IOException e) { - throw new HttpProcessException(e); - } - } - - //-----------华----丽----分----割----线-------------- - //-----------华----丽----分----割----线-------------- - //-----------华----丽----分----割----线-------------- - - /** - * 转化为字符串 - * - * @param resp 响应对象 - * @param encoding 编码 - * @return 返回处理结果 - * @throws HttpProcessException http处理异常 - */ - private static String fmt2String(HttpResponse resp, String encoding) throws HttpProcessException { - String body = ""; - try { - if (resp.getEntity() != null) { - // 按指定编码转换结果实体为String类型 - body = EntityUtils.toString(resp.getEntity(), encoding); - Utils.info(body); - }else{//有可能是head请求 - body =resp.getStatusLine().toString(); - } - EntityUtils.consume(resp.getEntity()); - } catch (IOException e) { - throw new HttpProcessException(e); - }finally{ - close(resp); - } - return body; - } - - /** - * 转化为数字 - * - * @param resp 响应对象 - * @return 返回处理结果 - * @throws HttpProcessException http处理异常 - */ - private static int fmt2Int(HttpResponse resp) throws HttpProcessException { - int statusCode; - try { - statusCode = resp.getStatusLine().getStatusCode(); - EntityUtils.consume(resp.getEntity()); - } catch (IOException e) { - throw new HttpProcessException(e); - }finally{ - close(resp); - } - return statusCode; - } - - /** - * 转化为流 - * - * @param resp 响应对象 - * @param out 输出流 - * @return 返回输出流 - * @throws HttpProcessException http处理异常 - */ - public static OutputStream fmt2Stream(HttpResponse resp, OutputStream out) throws HttpProcessException { - try { - resp.getEntity().writeTo(out); - EntityUtils.consume(resp.getEntity()); - } catch (IOException e) { - throw new HttpProcessException(e); - }finally{ - close(resp); - } - return out; - } - - /** - * 根据请求方法名,获取request对象 - * - * @param url 资源地址 - * @param method 请求方式 - * @return 返回Http处理request基类 - */ - private static HttpRequestBase getRequest(String url, HttpMethods method) { - HttpRequestBase request = null; - switch (method.getCode()) { - case 0:// HttpGet - request = new HttpGet(url); - break; - case 1:// HttpPost - request = new HttpPost(url); - break; - case 2:// HttpHead - request = new HttpHead(url); - break; - case 3:// HttpPut - request = new HttpPut(url); - break; - case 4:// HttpDelete - request = new HttpDelete(url); - break; - case 5:// HttpTrace - request = new HttpTrace(url); - break; - case 6:// HttpPatch - request = new HttpPatch(url); - break; - case 7:// HttpOptions - request = new HttpOptions(url); - break; - default: - request = new HttpPost(url); - break; - } - return request; - } - - /** - * 尝试关闭response - * - * @param resp HttpResponse对象 - */ - private static void close(HttpResponse resp) { - try { - if(resp == null) return; - //如果CloseableHttpResponse 是resp的父类,则支持关闭 - if(CloseableHttpResponse.class.isAssignableFrom(resp.getClass())){ - ((CloseableHttpResponse)resp).close(); - } - } catch (IOException e) { - Utils.exception(e); - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/builder/HCB.java b/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/builder/HCB.java deleted file mode 100644 index 949795bf14..0000000000 --- a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/builder/HCB.java +++ /dev/null @@ -1,243 +0,0 @@ -package com.jun.plugin.httpclient.httpclientutil.builder; - -import java.io.IOException; -import java.io.InterruptedIOException; -import java.net.UnknownHostException; - -import javax.net.ssl.SSLException; -import javax.net.ssl.SSLHandshakeException; - -import org.apache.http.HttpEntityEnclosingRequest; -import org.apache.http.HttpHost; -import org.apache.http.HttpRequest; -import org.apache.http.NoHttpResponseException; -import org.apache.http.client.HttpRequestRetryHandler; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.config.Registry; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.conn.ConnectTimeoutException; -import org.apache.http.conn.socket.ConnectionSocketFactory; -import org.apache.http.conn.socket.PlainConnectionSocketFactory; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.DefaultProxyRoutePlanner; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.http.protocol.HttpContext; - -import com.jun.plugin.httpclient.httpclientutil.common.SSLs; -import com.jun.plugin.httpclient.httpclientutil.common.SSLs.SSLProtocolVersion; -import com.jun.plugin.httpclient.httpclientutil.exception.HttpProcessException; - -/** - * httpclient创建者 - * - * @author arron - * @version 1.0 - */ -public class HCB extends HttpClientBuilder{ - - public boolean isSetPool=false;//记录是否设置了连接池 - private SSLProtocolVersion sslpv=SSLProtocolVersion.SSLv3;//ssl 协议版本 - - //用于配置ssl - private SSLs ssls = SSLs.getInstance(); - - private HCB(){} - public static HCB custom(){ - return new HCB(); - } - - /** - * 设置超时时间 - * - * @param timeout 超市时间,单位-毫秒 - * @return 返回当前对象 - */ - @Deprecated - public HCB timeout(int timeout){ - return timeout(timeout, true); - } - - /** - * 设置超时时间以及是否允许网页重定向(自动跳转 302) - * - * @param timeout 超时时间,单位-毫秒 - * @param redirectEnable 自动跳转 - * @return 返回当前对象 - */ - @Deprecated - public HCB timeout(int timeout, boolean redirectEnable){ - // 配置请求的超时设置 - RequestConfig config = RequestConfig.custom() - .setConnectionRequestTimeout(timeout) - .setConnectTimeout(timeout) - .setSocketTimeout(timeout) - .setRedirectsEnabled(redirectEnable) - .build(); - return (HCB) this.setDefaultRequestConfig(config); - } - - /** - * 设置ssl安全链接 - * - * @return 返回当前对象 - * @throws HttpProcessException http处理异常 - */ - public HCB ssl() throws HttpProcessException { -// if(isSetPool){//如果已经设置过线程池,那肯定也就是https链接了 -// if(isNewSSL){ -// throw new HttpProcessException("请先设置ssl,后设置pool"); -// } -// return this; -// } -// Registry socketFactoryRegistry = RegistryBuilder -// . create() -// .register("http", PlainConnectionSocketFactory.INSTANCE) -// .register("https", ssls.getSSLCONNSF()).build(); -// //设置连接池大小 -// PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); -// return (HCB) this.setConnectionManager(connManager); - return (HCB) this.setSSLSocketFactory(ssls.getSSLCONNSF(sslpv)); - } - - - /** - * 设置自定义sslcontext - * - * @param keyStorePath 密钥库路径 - * @return 返回当前对象 - * @throws HttpProcessException http处理异常 - */ - public HCB ssl(String keyStorePath) throws HttpProcessException{ - return ssl(keyStorePath,"nopassword"); - } - /** - * 设置自定义sslcontext - * - * @param keyStorePath 密钥库路径 - * @param keyStorepass 密钥库密码 - * @return 返回当前对象 - * @throws HttpProcessException http处理异常 - */ - public HCB ssl(String keyStorePath, String keyStorepass) throws HttpProcessException{ - this.ssls = SSLs.custom().customSSL(keyStorePath, keyStorepass); -// this.isNewSSL=true; - return ssl(); - } - - - /** - * 设置连接池(默认开启https) - * - * @param maxTotal 最大连接数 - * @param defaultMaxPerRoute 每个路由默认连接数 - * @return 返回当前对象 - * @throws HttpProcessException http处理异常 - */ - public HCB pool(int maxTotal, int defaultMaxPerRoute) throws HttpProcessException{ - Registry socketFactoryRegistry = RegistryBuilder - . create() - .register("http", PlainConnectionSocketFactory.INSTANCE) - .register("https", ssls.getSSLCONNSF(sslpv)).build(); - //设置连接池大小 - PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); - connManager.setMaxTotal(maxTotal);// Increase max total connection to $maxTotal - connManager.setDefaultMaxPerRoute(defaultMaxPerRoute);// Increase default max connection per route to $defaultMaxPerRoute - //connManager.setMaxPerRoute(route, max);// Increase max connections for $route(eg:localhost:80) to 50 - isSetPool=true; - return (HCB) this.setConnectionManager(connManager); - } - - /** - * 设置代理 - * - * @param hostOrIP 代理host或者ip - * @param port 代理端口 - * @return 返回当前对象 - */ - public HCB proxy(String hostOrIP, int port){ - // 依次是代理地址,代理端口号,协议类型 - HttpHost proxy = new HttpHost(hostOrIP, port, "http"); - DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); - return (HCB) this.setRoutePlanner(routePlanner); - } - - /** - * 重试(如果请求是幂等的,就再次尝试) - * - * @param tryTimes 重试次数 - * @return 返回当前对象 - */ - public HCB retry(final int tryTimes){ - return retry(tryTimes, false); - } - - /** - * 重试(如果请求是幂等的,就再次尝试) - * - * @param tryTimes 重试次数 - * @param retryWhenInterruptedIO 连接拒绝时,是否重试 - * @return 返回当前对象 - */ - public HCB retry(final int tryTimes, final boolean retryWhenInterruptedIO){ - // 请求重试处理 - HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() { - public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { - if (executionCount >= tryTimes) {// 如果已经重试了n次,就放弃 - return false; - } - if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试 - return true; - } - if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常 - return false; - } - if (exception instanceof InterruptedIOException) {// 超时 - //return false; - return retryWhenInterruptedIO; - } - if (exception instanceof UnknownHostException) {// 目标服务器不可达 - return true; - } - if (exception instanceof ConnectTimeoutException) {// 连接被拒绝 - return false; - } - if (exception instanceof SSLException) {// SSL握手异常 - return false; - } - - HttpClientContext clientContext = HttpClientContext .adapt(context); - HttpRequest request = clientContext.getRequest(); - // 如果请求是幂等的,就再次尝试 - if (!(request instanceof HttpEntityEnclosingRequest)) { - return true; - } - return false; - } - }; - this.setRetryHandler(httpRequestRetryHandler); - return this; - } - - /** - * 设置ssl版本
- * 如果您想要设置ssl版本,必须先调用此方法,再调用ssl方法
- * 仅支持 SSLv3,TSLv1,TSLv1.1,TSLv1.2
- * @param sslpv 版本号 - * @return 返回当前对象 - */ - public HCB sslpv(String sslpv){ - return sslpv(SSLProtocolVersion.find(sslpv)); - } - /** - * 设置ssl版本
- * 如果您想要设置ssl版本,必须先调用此方法,再调用ssl方法
- * 仅支持 SSLv3,TSLv1,TSLv1.1,TSLv1.2
- * @param sslpv 版本号 - * @return 返回当前对象 - */ - public HCB sslpv(SSLProtocolVersion sslpv){ - this.sslpv = sslpv; - return this; - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/HttpConfig.java b/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/HttpConfig.java deleted file mode 100644 index 2baed982fd..0000000000 --- a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/HttpConfig.java +++ /dev/null @@ -1,387 +0,0 @@ -package com.jun.plugin.httpclient.httpclientutil.common; - -import java.io.OutputStream; -import java.nio.charset.Charset; -import java.util.HashMap; -import java.util.Map; - -import org.apache.http.Header; -import org.apache.http.client.HttpClient; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.protocol.HttpContext; - -//import com.tgb.ccl.http.exception.HttpProcessException; -//import com.tgb.ccl.http.httpclient.builder.HCB; - -/** - * 请求配置类 - * - * @author arron - * @version 1.0 - */ -public class HttpConfig { - - private HttpConfig(){}; - - /** - * 获取实例 - * @return 返回当前对象 - */ - public static HttpConfig custom(){ - return new HttpConfig(); - } - - /** - * HttpClient对象 - */ - private HttpClient client; - - /** - * Header头信息 - */ - private Header[] headers; - - /** - * 是否返回response的headers - */ - private boolean isReturnRespHeaders; - - /** - * 请求方法 - */ - private HttpMethods method=HttpMethods.GET; - - /** - * 请求方法名称 - */ - private String methodName; - - /** - * 用于cookie操作 - */ - private HttpContext context; - - /** - * 传递参数 - */ -// private Map map; - - /** - * 以json格式作为输入参数 - */ - private String json; - - /** - * 输入输出编码 - */ - private String encoding=Charset.defaultCharset().displayName(); - - /** - * 输入编码 - */ - private String inenc; - - /** - * 输出编码 - */ - private String outenc; - - /** - * 设置RequestConfig - */ - private RequestConfig requestConfig; - - /** - * 解决多线程下载时,strean被close的问题 - */ - private static final ThreadLocal outs = new ThreadLocal(); - - /** - * 解决多线程处理时,url被覆盖问题 - */ - private static final ThreadLocal urls = new ThreadLocal(); - - /** - * 解决多线程处理时,url被覆盖问题 - */ - private static final ThreadLocal> maps = new ThreadLocal>(); - - /** - * @param client HttpClient对象 - * @return 返回当前对象 - */ - public HttpConfig client(HttpClient client) { - this.client = client; - return this; - } - - /** - * @param url 资源url - * @return 返回当前对象 - */ - public HttpConfig url(String url) { - urls.set(url); - return this; - } - - /** - * @param headers Header头信息 - * @return 返回当前对象 - */ - public HttpConfig headers(Header[] headers) { - this.headers = headers; - return this; - } - - /** - * Header头信息(是否返回response中的headers) - * - * @param headers Header头信息 - * @param isReturnRespHeaders 是否返回response中的headers - * @return 返回当前对象 - */ - public HttpConfig headers(Header[] headers, boolean isReturnRespHeaders) { - this.headers = headers; - this.isReturnRespHeaders=isReturnRespHeaders; - return this; - } - - /** - * @param method 请求方法 - * @return 返回当前对象 - */ - public HttpConfig method(HttpMethods method) { - this.method = method; - return this; - } - - /** - * @param methodName 请求方法 - * @return 返回当前对象 - */ - public HttpConfig methodName(String methodName) { - this.methodName = methodName; - return this; - } - - /** - * @param context cookie操作相关 - * @return 返回当前对象 - */ - public HttpConfig context(HttpContext context) { - this.context = context; - return this; - } - - /** - * @param map 传递参数 - * @return 返回当前对象 - */ - public HttpConfig map(Map map) { -// synchronized (getClass()) { -// if(this.map==null || map==null){ -// this.map = map; -// }else { -// this.map.putAll(map);; -// } -// } - Map m = maps.get(); - if(m==null || m==null || map==null){ - m = map; - }else { - m.putAll(map); - } - maps.set(m); - return this; - } - - /** - * @param json 以json格式字符串作为参数 - * @return 返回当前对象 - */ - public HttpConfig json(String json) { - this.json = json; - Map map = new HashMap(); - map.put(Utils.ENTITY_JSON, json); - maps.set(map); - return this; - } - - /** - * @param filePaths 待上传文件所在路径 - * @return 返回当前对象 - */ - public HttpConfig files(String[] filePaths) { - return files(filePaths, "file"); - } - /** - * 上传文件时用到 - * @param filePaths 待上传文件所在路径 - * @param inputName 即file input 标签的name值,默认为file - * @return 返回当前对象 - */ - public HttpConfig files(String[] filePaths, String inputName) { - return files(filePaths, inputName, false); - } - /** - * 上传文件时用到 - * @param filePaths 待上传文件所在路径 - * @param inputName 即file input 标签的name值,默认为file - * @param forceRemoveContentTypeChraset 是否强制一处content-type中设置的编码类型 - * @return 返回当前对象 - */ - public HttpConfig files(String[] filePaths, String inputName, boolean forceRemoveContentTypeChraset) { -// synchronized (getClass()) { -// if(this.map==null){ -// this.map= new HashMap(); -// } -// } -// map.put(Utils.ENTITY_MULTIPART, filePaths); -// map.put(Utils.ENTITY_MULTIPART+".name", inputName); -// map.put(Utils.ENTITY_MULTIPART+".rmCharset", forceRemoveContentTypeChraset); - - Map m = maps.get(); - if(m==null || m==null){ - m = new HashMap(); - } - m.put(Utils.ENTITY_MULTIPART, filePaths); - m.put(Utils.ENTITY_MULTIPART+".name", inputName); - m.put(Utils.ENTITY_MULTIPART+".rmCharset", forceRemoveContentTypeChraset); - maps.set(m); - return this; - } - - /** - * @param encoding 输入输出编码 - * @return 返回当前对象 - */ - public HttpConfig encoding(String encoding) { - //设置输入输出 - inenc(encoding); - outenc(encoding); - this.encoding = encoding; - return this; - } - - /** - * @param inenc 输入编码 - * @return 返回当前对象 - */ - public HttpConfig inenc(String inenc) { - this.inenc = inenc; - return this; - } - - /** - * @param outenc 输出编码 - * @return 返回当前对象 - */ - public HttpConfig outenc(String outenc) { - this.outenc = outenc; - return this; - } - - /** - * @param out 输出流对象 - * @return 返回当前对象 - */ - public HttpConfig out(OutputStream out) { - outs.set(out); - return this; - } - - /** - * 设置超时时间 - * - * @param timeout 超市时间,单位-毫秒 - * @return 返回当前对象 - */ - public HttpConfig timeout(int timeout){ - return timeout(timeout, true); - } - - /** - * 设置超时时间以及是否允许网页重定向(自动跳转 302) - * - * @param timeout 超时时间,单位-毫秒 - * @param redirectEnable 自动跳转 - * @return 返回当前对象 - */ - public HttpConfig timeout(int timeout, boolean redirectEnable){ - // 配置请求的超时设置 - RequestConfig config = RequestConfig.custom() - .setConnectionRequestTimeout(timeout) - .setConnectTimeout(timeout) - .setSocketTimeout(timeout) - .setRedirectsEnabled(redirectEnable) - .build(); - return timeout(config); - } - - /** - * 设置代理、超时时间、允许网页重定向等 - * - * @param requestConfig 超时时间,单位-毫秒 - * @return 返回当前对象 - */ - public HttpConfig timeout(RequestConfig requestConfig){ - this.requestConfig = requestConfig; - return this; - } - - public HttpClient client() { - return client; - } - - public Header[] headers() { - return headers; - } - public boolean isReturnRespHeaders() { - return isReturnRespHeaders; - } - - public String url() { - return urls.get(); - } - - public HttpMethods method() { - return method; - } - - public String methodName() { - return methodName; - } - - public HttpContext context() { - return context; - } - - public Map map() { -// return map; - return maps.get(); - } - - public String json() { - return json; - } - - public String encoding() { - return encoding; - } - - public String inenc() { - return inenc == null ? encoding : inenc; - } - - public String outenc() { - return outenc == null ? encoding : outenc; - } - - public OutputStream out() { - return outs.get(); - } - - public RequestConfig requestConfig() { - return requestConfig; - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/HttpCookies.java b/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/HttpCookies.java deleted file mode 100644 index a725653424..0000000000 --- a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/HttpCookies.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.jun.plugin.httpclient.httpclientutil.common; - -import org.apache.http.client.CookieStore; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.impl.client.BasicCookieStore; - -/** - * 封装Cookie - * - * @author arron - * @version 1.0 - */ -public class HttpCookies { - - /** - * 使用httpcontext,用于设置和携带Cookie - */ - private HttpClientContext context ; - - /** - * 储存Cookie - */ - private CookieStore cookieStore; - - public static HttpCookies custom(){ - return new HttpCookies(); - } - - private HttpCookies(){ - this.context = new HttpClientContext(); - this.cookieStore = new BasicCookieStore(); - this.context.setCookieStore(cookieStore); - } - - public HttpClientContext getContext() { - return context; - } - - public HttpCookies setContext(HttpClientContext context) { - this.context = context; - return this; - } - - public CookieStore getCookieStore() { - return cookieStore; - } - - public HttpCookies setCookieStore(CookieStore cookieStore) { - this.cookieStore = cookieStore; - return this; - } - - -} diff --git a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/HttpHeader.java b/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/HttpHeader.java deleted file mode 100644 index b4e36e136a..0000000000 --- a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/HttpHeader.java +++ /dev/null @@ -1,651 +0,0 @@ -package com.jun.plugin.httpclient.httpclientutil.common; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.http.Consts; -import org.apache.http.Header; -import org.apache.http.message.BasicHeader; - -/** - * 创建HttpReqHead - * - * @author arron - * @version 1.0 - */ -public class HttpHeader { - - private HttpHeader() {}; - - public static HttpHeader custom() { - return new HttpHeader(); - } - - //记录head头信息 - private Map headerMaps = new HashMap(); - - /** - * 自定义header头信息 - * - * @param key header-key - * @param value header-value - * @return 返回当前对象 - */ - public HttpHeader other(String key, String value) { - headerMaps.put(key, new BasicHeader(key, value)); - return this; - } - /** - * 指定客户端能够接收的内容类型 - * 例如:Accept: text/plain, text/html - * - * @param accept accept - * @return 返回当前对象 - */ - public HttpHeader accept(String accept) { - headerMaps.put(HttpReqHead.ACCEPT, - new BasicHeader(HttpReqHead.ACCEPT, accept)); - return this; - } - - /** - * 浏览器可以接受的字符编码集 - * 例如:Accept-Charset: iso-8859-5 - * - * @param acceptCharset accept-charset - * @return 返回当前对象 - */ - public HttpHeader acceptCharset(String acceptCharset) { - headerMaps.put(HttpReqHead.ACCEPT_CHARSET, - new BasicHeader(HttpReqHead.ACCEPT_CHARSET, acceptCharset)); - return this; - } - - /** - * 指定浏览器可以支持的web服务器返回内容压缩编码类型 - * 例如:Accept-Encoding: compress, gzip - * - * @param acceptEncoding accept-encoding - * @return 返回当前对象 - */ - public HttpHeader acceptEncoding(String acceptEncoding) { - headerMaps.put(HttpReqHead.ACCEPT_ENCODING, - new BasicHeader(HttpReqHead.ACCEPT_ENCODING, acceptEncoding)); - return this; - } - - /** - * 浏览器可接受的语言 - * 例如:Accept-Language: en,zh - * - * @param acceptLanguage accept-language - * @return 返回当前对象 - */ - public HttpHeader acceptLanguage(String acceptLanguage) { - headerMaps.put(HttpReqHead.ACCEPT_LANGUAGE, - new BasicHeader(HttpReqHead.ACCEPT_LANGUAGE, acceptLanguage)); - return this; - } - - /** - * 可以请求网页实体的一个或者多个子范围字段 - * 例如:Accept-Ranges: bytes - * - * @param acceptRanges accept-ranges - * @return 返回当前对象 - */ - public HttpHeader acceptRanges(String acceptRanges) { - headerMaps.put(HttpReqHead.ACCEPT_RANGES, - new BasicHeader(HttpReqHead.ACCEPT_RANGES, acceptRanges)); - return this; - } - - /** - * HTTP授权的授权证书 - * 例如:Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== - * - * @param authorization authorization - * @return 返回当前对象 - */ - public HttpHeader authorization(String authorization) { - headerMaps.put(HttpReqHead.AUTHORIZATION, - new BasicHeader(HttpReqHead.AUTHORIZATION, authorization)); - return this; - } - - /** - * 指定请求和响应遵循的缓存机制 - * 例如:Cache-Control: no-cache - * - * @param cacheControl cache-control - * @return 返回当前对象 - */ - public HttpHeader cacheControl(String cacheControl) { - headerMaps.put(HttpReqHead.CACHE_CONTROL, - new BasicHeader(HttpReqHead.CACHE_CONTROL, cacheControl)); - return this; - } - - /** - * 表示是否需要持久连接(HTTP 1.1默认进行持久连接) - * 例如:Connection: close 短链接; Connection: keep-alive 长连接 - * - * @param connection connection - * @return 返回当前对象 - */ - public HttpHeader connection(String connection) { - headerMaps.put(HttpReqHead.CONNECTION, - new BasicHeader(HttpReqHead.CONNECTION, connection)); - return this; - } - - /** - * HTTP请求发送时,会把保存在该请求域名下的所有cookie值一起发送给web服务器 - * 例如:Cookie: $Version=1; Skin=new; - * - * @param cookie cookie - * @return 返回当前对象 - */ - public HttpHeader cookie(String cookie) { - headerMaps.put(HttpReqHead.COOKIE, - new BasicHeader(HttpReqHead.COOKIE, cookie)); - return this; - } - - /** - * 请求内容长度 - * 例如:Content-Length: 348 - * - * @param contentLength content-length - * @return 返回当前对象 - */ - public HttpHeader contentLength(String contentLength) { - headerMaps.put(HttpReqHead.CONTENT_LENGTH, - new BasicHeader(HttpReqHead.CONTENT_LENGTH, contentLength)); - return this; - } - - /** - * 请求的与实体对应的MIME信息 - * 例如:Content-Type: application/x-www-form-urlencoded - * - * @param contentType content-type - * @return 返回当前对象 - */ - public HttpHeader contentType(String contentType) { - headerMaps.put(HttpReqHead.CONTENT_TYPE, - new BasicHeader(HttpReqHead.CONTENT_TYPE, contentType)); - return this; - } - - /** - * 请求发送的日期和时间 - * 例如:Date: Tue, 15 Nov 2010 08:12:31 GMT - * - * @param date date - * @return 返回当前对象 - */ - public HttpHeader date(String date) { - headerMaps.put(HttpReqHead.DATE, - new BasicHeader(HttpReqHead.DATE, date)); - return this; - } - - /** - * 请求的特定的服务器行为 - * 例如:Expect: 100-continue - * - * @param expect expect - * @return 返回当前对象 - */ - public HttpHeader expect(String expect) { - headerMaps.put(HttpReqHead.EXPECT, - new BasicHeader(HttpReqHead.EXPECT, expect)); - return this; - } - - /** - * 发出请求的用户的Email - * 例如:From: user@email.com - * - * @param from from - * @return 返回当前对象 - */ - public HttpHeader from(String from) { - headerMaps.put(HttpReqHead.FROM, - new BasicHeader(HttpReqHead.FROM, from)); - return this; - } - - /** - * 指定请求的服务器的域名和端口号 - * 例如:Host: blog.csdn.net - * - * @param host host - * @return 返回当前对象 - */ - public HttpHeader host(String host) { - headerMaps.put(HttpReqHead.HOST, - new BasicHeader(HttpReqHead.HOST, host)); - return this; - } - - /** - * 只有请求内容与实体相匹配才有效 - * 例如:If-Match: “737060cd8c284d8af7ad3082f209582d” - * - * @param ifMatch if-match - * @return 返回当前对象 - */ - public HttpHeader ifMatch(String ifMatch) { - headerMaps.put(HttpReqHead.IF_MATCH, - new BasicHeader(HttpReqHead.IF_MATCH, ifMatch)); - return this; - } - - /** - * 如果请求的部分在指定时间之后被修改则请求成功,未被修改则返回304代码 - * 例如:If-Modified-Since: Sat, 29 Oct 2010 19:43:31 GMT - * - * @param ifModifiedSince if-modified-Since - * @return 返回当前对象 - */ - public HttpHeader ifModifiedSince(String ifModifiedSince) { - headerMaps.put(HttpReqHead.IF_MODIFIED_SINCE, - new BasicHeader(HttpReqHead.IF_MODIFIED_SINCE, ifModifiedSince)); - return this; - } - - /** - * 如果内容未改变返回304代码,参数为服务器先前发送的Etag,与服务器回应的Etag比较判断是否改变 - * 例如:If-None-Match: “737060cd8c284d8af7ad3082f209582d” - * - * @param ifNoneMatch if-none-match - * @return 返回当前对象 - */ - public HttpHeader ifNoneMatch(String ifNoneMatch) { - headerMaps.put(HttpReqHead.IF_NONE_MATCH, - new BasicHeader(HttpReqHead.IF_NONE_MATCH, ifNoneMatch)); - return this; - } - - /** - * 如果实体未改变,服务器发送客户端丢失的部分,否则发送整个实体。参数也为Etag - * 例如:If-Range: “737060cd8c284d8af7ad3082f209582d” - * - * @param ifRange if-range - * @return 返回当前对象 - */ - public HttpHeader ifRange(String ifRange) { - headerMaps.put(HttpReqHead.IF_RANGE, - new BasicHeader(HttpReqHead.IF_RANGE, ifRange)); - return this; - } - - /** - * 只在实体在指定时间之后未被修改才请求成功 - * 例如:If-Unmodified-Since: Sat, 29 Oct 2010 19:43:31 GMT - * - * @param ifUnmodifiedSince if-unmodified-since - * @return 返回当前对象 - */ - public HttpHeader ifUnmodifiedSince(String ifUnmodifiedSince) { - headerMaps.put(HttpReqHead.IF_UNMODIFIED_SINCE, - new BasicHeader(HttpReqHead.IF_UNMODIFIED_SINCE, ifUnmodifiedSince)); - return this; - } - - /** - * 限制信息通过代理和网关传送的时间 - * 例如:Max-Forwards: 10 - * - * @param maxForwards max-forwards - * @return 返回当前对象 - */ - public HttpHeader maxForwards(String maxForwards) { - headerMaps.put(HttpReqHead.MAX_FORWARDS, - new BasicHeader(HttpReqHead.MAX_FORWARDS, maxForwards)); - return this; - } - - /** - * 用来包含实现特定的指令 - * 例如:Pragma: no-cache - * - * @param pragma pragma - * @return 返回当前对象 - */ - public HttpHeader pragma(String pragma) { - headerMaps.put(HttpReqHead.PRAGMA, - new BasicHeader(HttpReqHead.PRAGMA, pragma)); - return this; - } - - /** - * 连接到代理的授权证书 - * 例如:Proxy-Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== - * - * @param proxyAuthorization proxy-authorization - * @return 返回当前对象 - */ - public HttpHeader proxyAuthorization(String proxyAuthorization) { - headerMaps.put(HttpReqHead.PROXY_AUTHORIZATION, - new BasicHeader(HttpReqHead.PROXY_AUTHORIZATION, proxyAuthorization)); - return this; - } - - /** - * 只请求实体的一部分,指定范围 - * 例如:Range: bytes=500-999 - * - * @param range range - * @return 返回当前对象 - */ - public HttpHeader range(String range) { - headerMaps.put(HttpReqHead.RANGE, - new BasicHeader(HttpReqHead.RANGE, range)); - return this; - } - - /** - * 先前网页的地址,当前请求网页紧随其后,即来路 - * 例如:Referer: http://www.zcmhi.com/archives/71.html - * - * @param referer referer - * @return 返回当前对象 - */ - public HttpHeader referer(String referer) { - headerMaps.put(HttpReqHead.REFERER, - new BasicHeader(HttpReqHead.REFERER, referer)); - return this; - } - - /** - * 客户端愿意接受的传输编码,并通知服务器接受接受尾加头信息 - * 例如:TE: trailers,deflate;q=0.5 - * - * @param te te - * @return 返回当前对象 - */ - public HttpHeader te(String te) { - headerMaps.put(HttpReqHead.TE, - new BasicHeader(HttpReqHead.TE, te)); - return this; - } - - /** - * 向服务器指定某种传输协议以便服务器进行转换(如果支持) - * 例如:Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11 - * - * @param upgrade upgrade - * @return 返回当前对象 - */ - public HttpHeader upgrade(String upgrade) { - headerMaps.put(HttpReqHead.UPGRADE, - new BasicHeader(HttpReqHead.UPGRADE, upgrade)); - return this; - } - - /** - * User-Agent的内容包含发出请求的用户信息 - * - * @param userAgent user-agent - * @return 返回当前对象 - */ - public HttpHeader userAgent(String userAgent) { - headerMaps.put(HttpReqHead.USER_AGENT, - new BasicHeader(HttpReqHead.USER_AGENT, userAgent)); - return this; - } - - /** - * 关于消息实体的警告信息 - * 例如:Warn: 199 Miscellaneous warning - * - * @param warning warning - * @return 返回当前对象 - */ - public HttpHeader warning(String warning) { - headerMaps.put(HttpReqHead.WARNING, - new BasicHeader(HttpReqHead.WARNING, warning)); - return this; - } - - /** - * 通知中间网关或代理服务器地址,通信协议 - * 例如:Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1) - * - * @param via via - * @return 返回当前对象 - */ - public HttpHeader via(String via) { - headerMaps.put(HttpReqHead.VIA, - new BasicHeader(HttpReqHead.VIA, via)); - return this; - } - - /** - * 设置此HTTP连接的持续时间(超时时间) - * 例如:Keep-Alive: 300 - * - * @param keepAlive keep-alive - * @return 返回当前对象 - - */ - public HttpHeader keepAlive(String keepAlive) { - headerMaps.put(HttpReqHead.KEEP_ALIVE, - new BasicHeader(HttpReqHead.KEEP_ALIVE, keepAlive)); - return this; - } - - public String accept() { - return get(HttpReqHead.ACCEPT); - } - - public String acceptCharset() { - return get(HttpReqHead.ACCEPT_CHARSET); - } - - public String acceptEncoding() { - return get(HttpReqHead.ACCEPT_ENCODING); - } - - public String acceptLanguage() { - return get(HttpReqHead.ACCEPT_LANGUAGE); - } - - public String acceptRanges() { - return get(HttpReqHead.ACCEPT_RANGES); - } - - public String authorization() { - return get(HttpReqHead.AUTHORIZATION); - } - - public String cacheControl() { - return get(HttpReqHead.CACHE_CONTROL); - } - - public String connection() { - return get(HttpReqHead.CONNECTION); - } - - public String cookie() { - return get(HttpReqHead.COOKIE); - } - - public String contentLength() { - return get(HttpReqHead.CONTENT_LENGTH); - } - - public String contentType() { - return get(HttpReqHead.CONTENT_TYPE); - } - - public String date() { - return get(HttpReqHead.DATE); - } - - public String expect() { - return get(HttpReqHead.EXPECT); - } - - public String from() { - return get(HttpReqHead.FROM); - } - - public String host() { - return get(HttpReqHead.HOST); - } - - public String ifMatch() { - return get(HttpReqHead.IF_MATCH); - } - - public String ifModifiedSince() { - return get(HttpReqHead.IF_MODIFIED_SINCE); - } - - public String ifNoneMatch() { - return get(HttpReqHead.IF_NONE_MATCH); - } - - public String ifRange() { - return get(HttpReqHead.IF_RANGE); - } - - public String ifUnmodifiedSince() { - return get(HttpReqHead.IF_UNMODIFIED_SINCE); - } - - public String maxForwards() { - return get(HttpReqHead.MAX_FORWARDS); - } - - public String pragma() { - return get(HttpReqHead.PRAGMA); - } - - public String proxyAuthorization() { - return get(HttpReqHead.PROXY_AUTHORIZATION); - } - - public String referer() { - return get(HttpReqHead.REFERER); - } - - public String te() { - return get(HttpReqHead.TE); - } - - public String upgrade() { - return get(HttpReqHead.UPGRADE); - } - - public String userAgent() { - return get(HttpReqHead.USER_AGENT); - } - - public String via() { - return get(HttpReqHead.VIA); - } - - public String warning() { - return get(HttpReqHead.WARNING); - } - - public String keepAlive() { - return get(HttpReqHead.KEEP_ALIVE); - } - - - /** - * 获取head信息 - * - * @return - */ - private String get(String headName) { - if (headerMaps.containsKey(headName)) { - return headerMaps.get(headName).getValue(); - } - return null; - } - - /** - * 返回header头信息 - * - * @return 返回构建的header头信息数组 - */ - public Header[] build() { - Header[] headers = new Header[headerMaps.size()]; - int i = 0; - for (Header header : headerMaps.values()) { - headers[i] = header; - i++; - } - headerMaps.clear(); - headerMaps = null; - return headers; - } - - /** - * Http头信息 - * - * @author arron - * @date 2015年11月9日 上午11:29:04 - * @version 1.0 - */ - private static class HttpReqHead { - public static final String ACCEPT = "Accept"; - public static final String ACCEPT_CHARSET = "Accept-Charset"; - public static final String ACCEPT_ENCODING = "Accept-Encoding"; - public static final String ACCEPT_LANGUAGE = "Accept-Language"; - public static final String ACCEPT_RANGES = "Accept-Ranges"; - public static final String AUTHORIZATION = "Authorization"; - public static final String CACHE_CONTROL = "Cache-Control"; - public static final String CONNECTION = "Connection"; - public static final String COOKIE = "Cookie"; - public static final String CONTENT_LENGTH = "Content-Length"; - public static final String CONTENT_TYPE = "Content-Type"; - public static final String DATE= "Date"; - public static final String EXPECT = "Expect"; - public static final String FROM = "From"; - public static final String HOST = "Host"; - public static final String IF_MATCH = "If-Match "; - public static final String IF_MODIFIED_SINCE = "If-Modified-Since"; - public static final String IF_NONE_MATCH = "If-None-Match"; - public static final String IF_RANGE = "If-Range"; - public static final String IF_UNMODIFIED_SINCE = "If-Unmodified-Since"; - public static final String KEEP_ALIVE = "Keep-Alive"; - public static final String MAX_FORWARDS = "Max-Forwards"; - public static final String PRAGMA = "Pragma"; - public static final String PROXY_AUTHORIZATION = "Proxy-Authorization"; - public static final String RANGE = "Range"; - public static final String REFERER = "Referer"; - public static final String TE = "TE"; - public static final String UPGRADE = "Upgrade"; - public static final String USER_AGENT = "User-Agent"; - public static final String VIA = "Via"; - public static final String WARNING = "Warning"; - } - - /** - * 常用头信息配置 - * - * @author arron - * @version 1.0 - */ - public static class Headers{ - public static final String APP_FORM_URLENCODED="application/x-www-form-urlencoded"; - public static final String TEXT_PLAIN="text/plain"; - public static final String TEXT_HTML="text/html"; - public static final String TEXT_XML="text/xml"; - public static final String TEXT_JSON="text/json"; - public static final String CONTENT_CHARSET_ISO_8859_1 = Consts.ISO_8859_1.name(); - public static final String CONTENT_CHARSET_UTF8 = Consts.UTF_8.name(); - public static final String DEF_PROTOCOL_CHARSET = Consts.ASCII.name(); - public static final String CONN_CLOSE = "close"; - public static final String KEEP_ALIVE = "keep-alive"; - public static final String EXPECT_CONTINUE = "100-continue"; - } -} diff --git a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/HttpMethods.java b/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/HttpMethods.java deleted file mode 100644 index f9b881a7cf..0000000000 --- a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/HttpMethods.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.jun.plugin.httpclient.httpclientutil.common; - - /** - * 枚举HttpMethods方法 - * - * @author arron - * @version 1.0 - */ - public enum HttpMethods{ - - /** - * 求获取Request-URI所标识的资源 - */ - GET(0, "GET"), - - /** - * 向指定资源提交数据进行处理请求(例如提交表单或者上传文件)。数据被包含在请求体中。 - * POST请求可能会导致新的资源的建立和/或已有资源的修改 - */ - POST(1, "POST"), - - /** - * 向服务器索要与GET请求相一致的响应,只不过响应体将不会被返回。 - * 这一方法可以在不必传输整个响应内容的情况下,就可以获取包含在响应消息头中的元信息 - * 只获取响应信息报头 - */ - HEAD(2, "HEAD"), - - /** - * 向指定资源位置上传其最新内容(全部更新,操作幂等) - */ - PUT (3, "PUT"), - - /** - * 请求服务器删除Request-URI所标识的资源 - */ - DELETE (4, "DELETE"), - - /** - * 请求服务器回送收到的请求信息,主要用于测试或诊断 - */ - TRACE(5, "TRACE"), - - /** - * 向指定资源位置上传其最新内容(部分更新,非幂等) - */ - PATCH (6, "PATCH"), - - /** - * 返回服务器针对特定资源所支持的HTTP请求方法。 - * 也可以利用向Web服务器发送'*'的请求来测试服务器的功能性 - */ - OPTIONS (7, "OPTIONS"), - -// /** -// * HTTP/1.1协议中预留给能够将连接改为管道方式的代理服务器 -// */ -// CONNECT(99, "CONNECT"), - ; - - private int code; - private String name; - - private HttpMethods(int code, String name){ - this.code = code; - this.name = name; - } - public String getName() { - return name; - } - public int getCode() { - return code; - } - } \ No newline at end of file diff --git a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/HttpResult.java b/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/HttpResult.java deleted file mode 100644 index 88575d18eb..0000000000 --- a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/HttpResult.java +++ /dev/null @@ -1,128 +0,0 @@ -package com.jun.plugin.httpclient.httpclientutil.common; - -import java.io.Serializable; - -import org.apache.http.Header; -import org.apache.http.HttpResponse; -import org.apache.http.ProtocolVersion; -import org.apache.http.StatusLine; - -/** - * 请求结果 - * - * @author arron - * @version 1.1 - */ -public class HttpResult implements Serializable{ - private static final long serialVersionUID = -6368281080581808792L; - - /** - * 执行结果-body - */ - private String result; - - /** - * 状态码-statusCode - */ - private int statusCode; - - /** - * 状态行-StatusLine - */ - private StatusLine statusLine; - - /** - * 请求头信息 - */ - private Header[] reqHeaders; - - /** - * 响应头信息 - */ - private Header[] respHeaders; - - /** - * 协议版本 - */ - private ProtocolVersion protocolVersion; - - /** - * HttpResponse结果对象 - */ - private HttpResponse resp; - - public HttpResult(HttpResponse resp) { - this.statusLine = resp.getStatusLine(); - this.respHeaders = resp.getAllHeaders(); - this.protocolVersion = resp.getProtocolVersion(); - this.statusCode = resp.getStatusLine().getStatusCode(); - this.resp = resp; - } - - /** - * 从返回的头信息中查询指定头信息 - * - * @param name 头信息名称 - * @return - */ - public Header getHeaders(final String name) { - Header[] headers = this.resp.getHeaders(name); - return headers!=null && headers.length>0?headers[0]:null; - } - - public String getResult() { - return result; - } - - public void setResult(String result) { - this.result = result; - } - - public int getStatusCode() { - return statusCode; - } - - public void setStatusCode(int statusCode) { - this.statusCode = statusCode; - } - - public StatusLine getStatusLine() { - return statusLine; - } - - public void setStatusLine(StatusLine statusLine) { - this.statusLine = statusLine; - } - - public Header[] getReqHeaders() { - return reqHeaders; - } - - public void setReqHeaders(Header[] reqHeaders) { - this.reqHeaders = reqHeaders; - } - - public Header[] getRespHeaders() { - return respHeaders; - } - - public void setRespHeaders(Header[] respHeaders) { - this.respHeaders = respHeaders; - } - - public ProtocolVersion getProtocolVersion() { - return protocolVersion; - } - - public void setProtocolVersion(ProtocolVersion protocolVersion) { - this.protocolVersion = protocolVersion; - } - - public HttpResponse getResp() { - return resp; - } - - public void setResp(HttpResponse resp) { - this.resp = resp; - } -} diff --git a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/SSLs.java b/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/SSLs.java deleted file mode 100644 index 81ff91ced2..0000000000 --- a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/SSLs.java +++ /dev/null @@ -1,190 +0,0 @@ -package com.jun.plugin.httpclient.httpclientutil.common; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.security.KeyManagementException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; - -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.conn.ssl.TrustSelfSignedStrategy; -import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy; -import org.apache.http.ssl.SSLContexts; - -import com.jun.plugin.httpclient.httpclientutil.exception.HttpProcessException; - -/** - * 设置ssl - * - * @author arron - * @version 1.0 - */ -public class SSLs { - - private static final SSLHandler simpleVerifier = new SSLHandler(); - private static SSLSocketFactory sslFactory ; - private static SSLConnectionSocketFactory sslConnFactory ; - private static SSLIOSessionStrategy sslIOSessionStrategy ; - private static SSLs sslutil = new SSLs(); - private SSLContext sc; - - public static SSLs getInstance(){ - return sslutil; - } - public static SSLs custom(){ - return new SSLs(); - } - - // 重写X509TrustManager类的三个方法,信任服务器证书 - private static class SSLHandler implements X509TrustManager, HostnameVerifier{ - - @Override - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return new java.security.cert.X509Certificate[]{}; - //return null; - } - - @Override - public void checkServerTrusted(java.security.cert.X509Certificate[] chain, - String authType) throws java.security.cert.CertificateException { - } - - @Override - public void checkClientTrusted(java.security.cert.X509Certificate[] chain, - String authType) throws java.security.cert.CertificateException { - } - - @Override - public boolean verify(String paramString, SSLSession paramSSLSession) { - return true; - } - }; - - // 信任主机 - public static HostnameVerifier getVerifier() { - return simpleVerifier; - } - - public synchronized SSLSocketFactory getSSLSF(SSLProtocolVersion sslpv) throws HttpProcessException { - if (sslFactory != null) - return sslFactory; - try { - SSLContext sc = getSSLContext(sslpv); - sc.init(null, new TrustManager[] { simpleVerifier }, null); - sslFactory = sc.getSocketFactory(); - } catch (KeyManagementException e) { - throw new HttpProcessException(e); - } - return sslFactory; - } - - public synchronized SSLConnectionSocketFactory getSSLCONNSF(SSLProtocolVersion sslpv) throws HttpProcessException { - if (sslConnFactory != null) - return sslConnFactory; - try { - SSLContext sc = getSSLContext(sslpv); -// sc.init(null, new TrustManager[] { simpleVerifier }, null); - sc.init(null, new TrustManager[] { simpleVerifier }, new java.security.SecureRandom()); - sslConnFactory = new SSLConnectionSocketFactory(sc, simpleVerifier); - } catch (KeyManagementException e) { - throw new HttpProcessException(e); - } - return sslConnFactory; - } - - public synchronized SSLIOSessionStrategy getSSLIOSS(SSLProtocolVersion sslpv) throws HttpProcessException { - if (sslIOSessionStrategy != null) - return sslIOSessionStrategy; - try { - SSLContext sc = getSSLContext(sslpv); -// sc.init(null, new TrustManager[] { simpleVerifier }, null); - sc.init(null, new TrustManager[] { simpleVerifier }, new java.security.SecureRandom()); - sslIOSessionStrategy = new SSLIOSessionStrategy(sc, simpleVerifier); - } catch (KeyManagementException e) { - throw new HttpProcessException(e); - } - return sslIOSessionStrategy; - } - - public SSLs customSSL(String keyStorePath, String keyStorepass) throws HttpProcessException{ - FileInputStream instream =null; - KeyStore trustStore = null; - try { - trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); - instream = new FileInputStream(new File(keyStorePath)); - trustStore.load(instream, keyStorepass.toCharArray()); - // 相信自己的CA和所有自签名的证书 - sc= SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()) .build(); - } catch (KeyManagementException e) { - throw new HttpProcessException(e); - } catch (KeyStoreException e) { - throw new HttpProcessException(e); - } catch (FileNotFoundException e) { - throw new HttpProcessException(e); - } catch (NoSuchAlgorithmException e) { - throw new HttpProcessException(e); - } catch (CertificateException e) { - throw new HttpProcessException(e); - } catch (IOException e) { - throw new HttpProcessException(e); - }finally{ - try { - instream.close(); - } catch (IOException e) {} - } - return this; - } - - public SSLContext getSSLContext(SSLProtocolVersion sslpv) throws HttpProcessException{ - try { - if(sc==null){ - sc = SSLContext.getInstance(sslpv.getName()); - } - return sc; - } catch (NoSuchAlgorithmException e) { - throw new HttpProcessException(e); - } - } - - /** - * The SSL protocol version (SSLv3, TLSv1, TLSv1.1, TLSv1.2) - * - * @author arron - * @version 1.0 - */ - public static enum SSLProtocolVersion{ - SSL("SSL"), - SSLv3("SSLv3"), - TLSv1("TLSv1"), - TLSv1_1("TLSv1.1"), - TLSv1_2("TLSv1.2"), - ; - private String name; - private SSLProtocolVersion(String name){ - this.name = name; - } - public String getName(){ - return this.name; - } - public static SSLProtocolVersion find(String name){ - for (SSLProtocolVersion pv : SSLProtocolVersion.values()) { - if(pv.getName().toUpperCase().equals(name.toUpperCase())){ - return pv; - } - } - throw new RuntimeException("未支持当前ssl版本号:"+name); - } - - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/Utils.java b/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/Utils.java deleted file mode 100644 index f4e5e717f9..0000000000 --- a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/Utils.java +++ /dev/null @@ -1,304 +0,0 @@ -package com.jun.plugin.httpclient.httpclientutil.common; - -import java.io.File; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.nio.charset.Charset; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import org.apache.http.HttpEntity; -import org.apache.http.NameValuePair; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.entity.ByteArrayEntity; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.FileEntity; -import org.apache.http.entity.StringEntity; -import org.apache.http.entity.mime.HttpMultipartMode; -import org.apache.http.entity.mime.MultipartEntityBuilder; -import org.apache.http.message.BasicHeader; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.protocol.HTTP; -import org.apache.log4j.Logger; - -/** - * 工具类 - * - * 用于设定参数特定类型 - * 启用bebug模式,打印消息 - * - * @author arron - * @version 1.0 - */ -public class Utils { - - //传入参数特定类型 - public static final String ENTITY_STRING="$ENTITY_STRING$"; - public static final String ENTITY_JSON="$ENTITY_JSON$"; - public static final String ENTITY_FILE="$ENTITY_FILEE$"; - public static final String ENTITY_BYTES="$ENTITY_BYTES$"; - public static final String ENTITY_INPUTSTREAM="$ENTITY_INPUTSTREAM$"; - public static final String ENTITY_SERIALIZABLE="$ENTITY_SERIALIZABLE$"; - public static final String ENTITY_MULTIPART="$ENTITY_MULTIPART$"; - private static final List SPECIAL_ENTITIY = Arrays.asList(ENTITY_STRING, ENTITY_JSON, ENTITY_BYTES, ENTITY_FILE, ENTITY_INPUTSTREAM, ENTITY_SERIALIZABLE, ENTITY_MULTIPART); - - /** - * 是否开启debug, - */ - private static boolean debug = false; - private static final Logger logger = Logger.getLogger("HttpClient(异步)工具类"); - - /** - * 检测url是否含有参数,如果有,则把参数加到参数列表中 - * - * @param url 资源地址 - * @param nvps 参数列表 - * @param encoding 编码 - * @return 返回去掉参数的url - * @throws UnsupportedEncodingException 不支持的编码异常 - */ - public static String checkHasParas(String url, List nvps, String encoding) throws UnsupportedEncodingException { - // 检测url中是否存在参数 - if (url.contains("?") && url.indexOf("?") < url.indexOf("=")) { - Map map = buildParas(url.substring(url.indexOf("?") + 1)); - map2HttpEntity(nvps, map, encoding); - url = url.substring(0, url.indexOf("?")); - } - return url; - } - - /** - * - * 参数转换,将map中的参数,转到参数列表中 - * - * @param nvps 参数列表 - * @param map 参数列表(map) - * @param encoding 编码 - * @return 返回HttpEntity - * @throws UnsupportedEncodingException 不支持的编码异常 - */ - public static HttpEntity map2HttpEntity(List nvps, Map map, String encoding) throws UnsupportedEncodingException { - HttpEntity entity = null; - if(map!=null && map.size()>0){ - boolean isSpecial = false; - // 拼接参数 - for (Entry entry : map.entrySet()) { - if(SPECIAL_ENTITIY.contains(entry.getKey())){//判断是否在之中 - isSpecial = true; - if(ENTITY_STRING.equals(entry.getKey())){//string - entity = new StringEntity(String.valueOf(entry.getValue()), encoding); - break; - }else if(ENTITY_JSON.equals(entry.getKey())){//json - entity = new StringEntity(String.valueOf(entry.getValue()), encoding); - String contentType = "application/json"; - if (encoding != null) { - contentType += ";charset=" + encoding; - } - ((StringEntity) entity).setContentType(contentType); - break; - }else if(ENTITY_BYTES.equals(entry.getKey())){//file - entity = new ByteArrayEntity((byte[])entry.getValue()); - break; - }else if(ENTITY_FILE.equals(entry.getKey())){//file - if(File.class.isAssignableFrom(entry.getValue().getClass())){ - entity = new FileEntity((File)entry.getValue(), ContentType.APPLICATION_OCTET_STREAM); - }else if(entry.getValue().getClass()==String.class){ - entity = new FileEntity(new File((String) entry.getValue()), ContentType.create("text/plain", "UTF-8")); - } - break; - }else if(ENTITY_INPUTSTREAM.equals(entry.getKey())){//inputstream -// entity = new InputStreamEntity(); - break; - }else if(ENTITY_SERIALIZABLE.equals(entry.getKey())){//serializeable -// entity = new SerializableEntity() - break; - }else if(ENTITY_MULTIPART.equals(entry.getKey())){//MultipartEntityBuilder - File[] files = null; - if(File.class.isAssignableFrom(entry.getValue().getClass().getComponentType())){ - files=(File[])entry.getValue(); - }else if(entry.getValue().getClass().getComponentType()==String.class){ - String[] names = (String[]) entry.getValue(); - files = new File[names.length]; - for (int i = 0; i < names.length; i++) { - files[i] = new File(names[i]); - } - } - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setCharset(Charset.forName(encoding));// 设置请求的编码格式 - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);// 设置浏览器兼容模式 - int count = 0; - for (File file : files) { -// //把文件转换成流对象FileBody -// FileBody fileBody = new FileBody(file); -// builder.addPart(String.valueOf(map.get(ENTITY_MULTIPART+".name")) + count++, fileBody); - builder.addBinaryBody(String.valueOf(map.get(ENTITY_MULTIPART+".name")) + count++,file); - } - boolean forceRemoveContentTypeCharset = (Boolean)map.get(ENTITY_MULTIPART+".rmCharset"); - Map m = new HashMap(); - m.putAll(map); - m.remove(ENTITY_MULTIPART); - m.remove(ENTITY_MULTIPART+".name"); - m.remove(ENTITY_MULTIPART+".rmCharset"); - Iterator> iterator = m.entrySet().iterator(); - // 发送的数据 - while (iterator.hasNext()) { - Entry e = iterator.next(); - builder.addTextBody(e.getKey(), String.valueOf(e.getValue()), ContentType.create("text/plain", encoding)); - } - entity = builder.build();// 生成 HTTP POST 实体 - - //强制去除contentType中的编码设置,否则,在某些情况下会导致上传失败 - if(forceRemoveContentTypeCharset){ - removeContentTypeCharset(encoding, entity); - } - break; - }else { - nvps.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue()))); - } - }else{ - nvps.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue()))); - } - } - if(!isSpecial) { - entity = new UrlEncodedFormEntity(nvps, encoding); - } - } - return entity; - } - - /** - * 移除content-type中的charset - * - * @param encoding 编码 - * @param entity 请求参数及数据信息 - */ - private static void removeContentTypeCharset(String encoding, HttpEntity entity) { - try { - Class clazz = entity.getClass(); - Field field = clazz.getDeclaredField("contentType"); - field.setAccessible(true); //将字段的访问权限设为true:即去除private修饰符的影响 - if(Modifier.isFinal(field.getModifiers())){ - Field modifiersField = Field.class.getDeclaredField("modifiers"); //去除final修饰符的影响,将字段设为可修改的 - modifiersField.setAccessible(true); - modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); - } - BasicHeader o = (BasicHeader) field.get(entity); - field.set(entity, new BasicHeader(HTTP.CONTENT_TYPE, o.getValue().replace("; charset="+encoding,""))); - } catch (NoSuchFieldException e) { - Utils.exception(e); - } catch (SecurityException e) { - Utils.exception(e); - } catch (IllegalArgumentException e) { - Utils.exception(e); - } catch (IllegalAccessException e) { - Utils.exception(e); - } - } - - - /** - * 生成参数 - * 参数格式:k1=v1&k2=v2 - * - * @param paras 参数列表 - * @return 返回参数列表(map) - */ - public static Map buildParas(String paras){ - String[] p = paras.split("&"); - String[][] ps = new String[p.length][2]; - int pos = 0; - for (int i = 0; i < p.length; i++) { - pos = p[i].indexOf("="); - ps[i][0]=p[i].substring(0,pos); - ps[i][1]=p[i].substring(pos+1); - pos = 0; - } - return buildParas(ps); - } - - /** - * 生成参数 - * 参数类型:{{"k1","v1"},{"k2","v2"}} - * - * @param paras 参数列表 - * @return 返回参数列表(map) - */ - public static Map buildParas(String[][] paras){ - // 创建参数队列 - Map map = new HashMap(); - for (String[] para: paras) { - map.put(para[0], para[1]); - } - return map; - } - - /** - * 打印消息 - * - * @param msg 消息 - */ - public static void info(String msg){ - if(debug){ - logger.info(msg); - } - } - - /** - * 打印消息和异常堆栈 - * - * @param msg 异常消息 - * @param t 异常 - */ - public static void infoException(String msg, Throwable t){ - if(debug){ - logger.info(msg, t); - } - } - - /** - * 打印错误消息 - * - * @param msg 异常消息 - */ - public static void error(String msg){ - logger.error(msg); - } - - /** - * 打印错误消息和异常堆栈 - * - * @param msg 异常消息 - * @param t 异常 - */ - public static void errorException(String msg, Throwable t){ - logger.error(msg, t); - } - - /** - * 打印异常堆栈 - * - * @param t 异常 - */ - public static void exception(Throwable t){ - logger.error(t); - } - - /** - * 开启打印日志 - */ - public static void debug() { - debug(true); - } - /** - * 开启或关闭打印日志 - * @param debug 是否开启debug - */ - public static void debug(boolean debug) { - Utils.debug = debug; - } -} diff --git a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/util/OCR.java b/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/util/OCR.java deleted file mode 100644 index d4683f6461..0000000000 --- a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/util/OCR.java +++ /dev/null @@ -1,205 +0,0 @@ -package com.jun.plugin.httpclient.httpclientutil.common.util; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import org.apache.http.Header; -import org.apache.http.client.HttpClient; - -import com.jun.plugin.httpclient.httpclientutil.HttpClientUtil; -import com.jun.plugin.httpclient.httpclientutil.builder.HCB; -import com.jun.plugin.httpclient.httpclientutil.common.HttpConfig; -import com.jun.plugin.httpclient.httpclientutil.common.HttpHeader; -import com.jun.plugin.httpclient.httpclientutil.common.Utils; -import com.jun.plugin.httpclient.httpclientutil.exception.HttpProcessException; - -/** - * 识别验证码 - * - * @author arron - * @version 1.0 - */ -public class OCR { - - /** - * 接口说明: - * https://github.com/AvensLab/OcrKing/blob/master/线上识别http接口说明.txt - */ - private static final String apiUrl = "http://lab.ocrking.com/ok.html"; - private static final String apiKey = PropertiesUtil.getProperty("OCR.key"); - private static HttpClient client =null; //=HCB.custom().proxy("127.0.0.1", 8888).build(); - - public static void enableCatch(){ - client =HCB.custom().proxy("127.0.0.1", 8888).build(); - } - public static void unEnableCatch(){ - client =null; - } - - //获取固定参数 - private static Map getParaMap(){ - //加载所有参数 - Map map = new HashMap(); - map.put("service", "OcrKingForCaptcha"); - map.put("language", "eng"); - map.put("charset", "7");//7-数字大写小写,5-数字大写字母 - map.put("type", "http://www.unknown.com"); - map.put("apiKey", apiKey); - return map; - } - - /** - * 识别本地校验码(英文:字母+大小写) - * - * @param filePath 验证码地址 - * @return 返回识别的验证码结果 - */ - public static String ocrCode(String filePath){ - return ocrCode(filePath, 0); - } - /** - * 识别本地校验码(英文:字母+大小写) - * - * @param imgFilePath 验证码地址 - * @param limitCodeLen 验证码长度(如果结果与设定长度不一致,则返回获取失败的提示) - * @return 返回识别的验证码结果 - */ - public static String ocrCode(String imgFilePath, int limitCodeLen){ - //读取文件 - File f = new File(imgFilePath); - if(!f.exists()){ - return "Error:文件不存在!"; - } - - String html; - try { - html = HttpClientUtil.upload(HttpConfig.custom().client(client).url(apiUrl).files(new String[]{imgFilePath},"ocrfile",true).map(getParaMap())); - //System.out.println(html); - String[] results = StringUtil.regex("([^<]*)\\s*([^<]*)", html); - if(results.length>0){ - //System.out.println(results[0]); - if(Boolean.parseBoolean(results[1])){ - if(limitCodeLen<=0 || limitCodeLen==results[0].length()){//不判断长度或者长度一致时,直接返回 - return results[0]; - }else{ - return "Error:获取失败! 原因:识别结果长度为:"+results[0].length()+"(期望长度:"+limitCodeLen+")"; - } - }else{ - return "Error:获取失败! 原因:"+results[0]; - } - } - } catch (HttpProcessException e) { - Utils.exception(e); - } - - return "Error:获取失败!"; - } - - - - /** - * 直接获取网络验证码(验证码不刷新) - * - * @param imgUrl 验证码地址 - * @return 返回识别的验证码结果 - */ - public static String ocrCode4Net(String imgUrl){ - return ocrCode4Net(imgUrl, 0); - } - /** - * 直接获取网络验证码(验证码不刷新) - * - * @param imgUrl 验证码地址 - * @param limitCodeLen 验证码长度 - * @return 返回识别的验证码结果 - */ - public static String ocrCode4Net(String imgUrl, int limitCodeLen){ - Map map = getParaMap(); - map.put("url", imgUrl); - - Header[] headers = HttpHeader.custom().userAgent("Mozilla/5.0 (Windows NT 5.1; zh-CN; rv:1.9.1.3) Gecko/20100101 Firefox/8.0").build(); - - try { - String html = HttpClientUtil.post(HttpConfig.custom().client(client).url(apiUrl).headers(headers).map(map)); - //System.out.println(html); - String[] results = StringUtil.regex("([^<]*)\\s*([^<]*)", html); - if(results.length>0){ - //System.out.println(results[0]); - if(Boolean.parseBoolean(results[1])){ - if(limitCodeLen<=0 || limitCodeLen==results[0].length()){//不判断长度或者长度一致时,直接返回 - return results[0]; - }else{ - return "Error:获取失败! 原因:识别结果长度为:"+results[0].length()+"(期望长度:"+limitCodeLen+")"; - } - }else{ - return "Error:获取失败! 原因:"+results[0]; - } - } - } catch (HttpProcessException e) { - Utils.exception(e); - } - - return "Error:获取失败!"; - } - - - /** - * 直接获取网络验证码(通过获取图片流,然后识别验证码) - * - * @param config HttpConfig对象(设置cookie) - * @param savePath 图片保存的完整路径(值为null时,不保存),如:c:/1.png - * @return 返回识别的验证码结果 - */ - public static String ocrCode4Net(HttpConfig config, String savePath){ - return ocrCode4Net(config, savePath, 0); - } - /** - * 直接获取网络验证码(通过获取图片流,然后识别验证码) - * - * @param config HttpConfig对象(设置cookie) - * @param savePath 图片保存的完整路径(值为null时,不保存),如:c:/1.png - * @param limitCodeLen 验证码长度 - * @return 返回识别的验证码结果 - */ - @SuppressWarnings("resource") - public static String ocrCode4Net(HttpConfig config, String savePath, int limitCodeLen){ - if(savePath==null || savePath.equals("")){//如果不保存图片,则直接使用图片地址的方式获取验证码 - return ocrCode4Net(config.url(), limitCodeLen); - } - - //下载图片 - ByteArrayOutputStream out = new ByteArrayOutputStream(); - try { - out = (ByteArrayOutputStream) HttpClientUtil.down(config.client(client).out(out)); - //本地测试,可以保存一下图片,方便核验 - FileOutputStream fos = new FileOutputStream(savePath); - fos.write(out.toByteArray()); - - return ocrCode(savePath, limitCodeLen); - } catch (HttpProcessException e) { - Utils.exception(e); - } catch (IOException e) { - Utils.exception(e); - } - - return "Error:获取失败!"; - } - - public static void main(String[] args) throws HttpProcessException, IOException { - String filePath="C:/Users/160049/Desktop/中国.png"; - String url = "http://file.ocrking.net:6080/small/20161104/w4fCjnzCl8KTwphpwqnCv2bCn8Kp/66fcff8d-61b1-49d6-bbfe-7428cf7accdf_debug.png?e9gFvJmkLbmgsZNTUCCNkjfi8J0Wbpn1CZHeP98eT1kxZ0ISBDt8Ql6h6zQ79pJg"; - String url2 = "http://59.41.9.91/GZCX/WebUI/Content/Handler/ValidateCode.ashx?0.3271647585525703"; - String code1 = ocrCode(filePath, 5); - String code2 = ocrCode4Net(url,5); - String code3 = ocrCode4Net(HttpConfig.custom().url(url2), System.getProperty("user.dir")+System.getProperty("file.separator")+"123.png", 5); - System.out.println(code1); - System.out.println(code2); - System.out.println(code3); - System.out.println("----"); - - } -} diff --git a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/util/OldOCR.java b/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/util/OldOCR.java deleted file mode 100644 index 744fe872ba..0000000000 --- a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/util/OldOCR.java +++ /dev/null @@ -1,292 +0,0 @@ -package com.jun.plugin.httpclient.httpclientutil.common.util; - -import java.io.BufferedInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - -import org.apache.http.Header; -import org.apache.http.client.HttpClient; - -import com.jun.plugin.httpclient.httpclientutil.HttpClientUtil; -import com.jun.plugin.httpclient.httpclientutil.builder.HCB; -import com.jun.plugin.httpclient.httpclientutil.common.HttpConfig; -import com.jun.plugin.httpclient.httpclientutil.common.HttpHeader; -import com.jun.plugin.httpclient.httpclientutil.common.Utils; -import com.jun.plugin.httpclient.httpclientutil.exception.HttpProcessException; - -/** - * 识别验证码,自拼接http报文信息 - * - * @author arron - * @version 1.0 - */ -public class OldOCR { - - /** - * 接口说明: - * https://github.com/AvensLab/OcrKing/blob/master/线上识别http接口说明.txt - */ - private static final String apiUrl = "http://lab.ocrking.com/ok.html"; - private static final String apiKey = PropertiesUtil.getProperty("OCR.key"); - private static final String boundary = "----------------------------OcrKing_Client_Aven_s_Lab"; - private static final String end="\r\n--" + boundary + "--\r\n"; - private static final Header[] headers = HttpHeader.custom() - .accept("text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2") - .userAgent("Mozilla/5.0 (Windows NT 5.1; zh-CN; rv:1.9.1.3) Gecko/20100101 Firefox/8.0") - .contentType("multipart/form-data; boundary="+boundary) - .referer("http://lab.ocrking.com/?javaclient0.1)") - .build(); - private static final Map map = getParaMap(); - private static HttpClient client =null; //=HCB.custom().proxy("127.0.0.1", 8888).build(); - - public static void enableCatch(){ - client =HCB.custom().proxy("127.0.0.1", 8888).build(); - } - public static void unEnableCatch(){ - client =null; - } - - //获取固定参数 - private static Map getParaMap(){ - //加载所有参数 - Map map = new HashMap(); - map.put("service", "OcrKingForCaptcha"); - map.put("language", "eng"); - map.put("charset", "7");//7-数字大写小写,5-数字大写字母 - map.put("type", "http://www.unknown.com"); - map.put("apiKey", apiKey); - return map; - } - - - /** - * 识别本地校验码(英文:字母+大小写) - * - * @param filePath 验证码地址 - * @return 返回识别的验证码结果 - */ - public static String ocrCode(String filePath){ - return ocrCode(filePath, 0); - } - /** - * 识别本地校验码(英文:字母+大小写) - * - * @param imgFilePath 验证码地址 - * @param limitCodeLen 验证码长度(如果结果与设定长度不一致,则返回获取失败的提示) - * @return 返回识别的验证码结果 - */ - @SuppressWarnings("resource") - public static String ocrCode(String imgFilePath, int limitCodeLen){ - byte[] data = null; - String fileName = imgFilePath.replaceAll("[^/]*/|[^\\\\]*\\\\", ""); - - StringBuffer strBuf = new StringBuffer(); - for (Entry entry : map.entrySet()) { - strBuf.append("\r\n").append("--").append(boundary).append("\r\n"); - strBuf.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n"); - strBuf.append(entry.getValue()); - } - strBuf.append("\r\n").append("--").append(boundary).append("\r\n"); - strBuf.append("Content-Disposition: form-data; name=\"ocrfile\"; filename=\"" + fileName + "\"\r\n"); - strBuf.append("Content-Type:application/octet-stream\r\n\r\n"); - - //读取文件 - File f = new File(imgFilePath); - if(!f.exists()){ - return "Error:文件不存在!"; - } - - //内容长度=参数长度+文件长度+结尾字符串长度 - ByteArrayOutputStream bos = new ByteArrayOutputStream(strBuf.length()+(int)f.length()+end.length()); - try { - bos.write(strBuf.toString().getBytes());//转化参数内容 - BufferedInputStream in = new BufferedInputStream(new FileInputStream(f)); - int buf_size = 1024; - int len = 0; - byte[] buf = new byte[buf_size]; - while (-1 != (len = in.read(buf, 0, buf_size))) { - bos.write(buf, 0, len); - } - bos.write(end.getBytes()); - data= bos.toByteArray(); - } catch (IOException e) { - Utils.exception(e); - } - - Map m = new HashMap(); - m.put(Utils.ENTITY_BYTES, data); - - String html; - try { - html = HttpClientUtil.post(HttpConfig.custom().client(client).url(apiUrl).headers(headers).map(m)); - //System.out.println(html); - String[] results = StringUtil.regex("([^<]*)\\s*([^<]*)", html); - if(results.length>0){ - //System.out.println(results[0]); - if(Boolean.parseBoolean(results[1])){ - if(limitCodeLen<=0 || limitCodeLen==results[0].length()){//不判断长度或者长度一致时,直接返回 - return results[0]; - }else{ - return "Error:获取失败! 原因:识别结果长度为:"+results[0].length()+"(期望长度:"+limitCodeLen+")"; - } - }else{ - return "Error:获取失败! 原因:"+results[0]; - } - } - } catch (HttpProcessException e) { - Utils.exception(e); - } - - return "Error:获取失败!"; - } - - - - /** - * 直接获取网络验证码(验证码不刷新) - * - * @param imgUrl 验证码地址 - * @return 返回识别的验证码结果 - */ - public static String ocrCode4Net(String imgUrl){ - return ocrCode4Net(imgUrl, 0); - } - /** - * 直接获取网络验证码(验证码不刷新) - * - * @param imgUrl 验证码地址 - * @param limitCodeLen 验证码长度 - * @return 返回识别的验证码结果 - */ - public static String ocrCode4Net(String imgUrl, int limitCodeLen){ - Map map = getParaMap(); - map.put("url", imgUrl); - - Header[] headers = HttpHeader.custom().userAgent("Mozilla/5.0 (Windows NT 5.1; zh-CN; rv:1.9.1.3) Gecko/20100101 Firefox/8.0").build(); - - try { - String html = HttpClientUtil.post(HttpConfig.custom().client(client).url(apiUrl).headers(headers).map(map)); - //System.out.println(html); - String[] results = StringUtil.regex("([^<]*)\\s*([^<]*)", html); - if(results.length>0){ - //System.out.println(results[0]); - if(Boolean.parseBoolean(results[1])){ - if(limitCodeLen<=0 || limitCodeLen==results[0].length()){//不判断长度或者长度一致时,直接返回 - return results[0]; - }else{ - return "Error:获取失败! 原因:识别结果长度为:"+results[0].length()+"(期望长度:"+limitCodeLen+")"; - } - }else{ - return "Error:获取失败! 原因:"+results[0]; - } - } - } catch (HttpProcessException e) { - Utils.exception(e); - } - - return "Error:获取失败!"; - } - - - /** - * 直接获取网络验证码(通过获取图片流,然后识别验证码) - * - * @param config HttpConfig对象(设置cookie) - * @param savePath 图片保存的完整路径(值为null时,不保存),如:c:/1.png - * @return 返回识别的验证码结果 - */ - public static String ocrCode4Net(HttpConfig config, String savePath){ - return ocrCode4Net(config, savePath, 0); - } - /** - * 直接获取网络验证码(通过获取图片流,然后识别验证码) - * - * @param config HttpConfig对象(设置cookie) - * @param savePath 图片保存的完整路径(值为null时,不保存),如:c:/1.png - * @param limitCodeLen 验证码长度 - * @return 返回识别的验证码结果 - */ - @SuppressWarnings("resource") - public static String ocrCode4Net(HttpConfig config, String savePath, int limitCodeLen){ - if(savePath==null || savePath.equals("")){//如果不保存图片,则直接使用图片地址的方式获取验证码 - return ocrCode4Net(config.url(), limitCodeLen); - } - - byte[] data = null; - - StringBuffer strBuf = new StringBuffer(); - for (Entry entry : map.entrySet()) { - strBuf.append("\r\n").append("--").append(boundary).append("\r\n"); - strBuf.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n"); - strBuf.append(entry.getValue()); - } - strBuf.append("\r\n").append("--").append(boundary).append("\r\n"); - strBuf.append("Content-Disposition: form-data; name=\"ocrfile\"; filename=\"" + "aaa" + "\"\r\n"); - strBuf.append("Content-Type:application/octet-stream\r\n\r\n"); - - //下载图片 - ByteArrayOutputStream out = new ByteArrayOutputStream(); - try { - out = (ByteArrayOutputStream) HttpClientUtil.down(config.client(client).out(out)); - //本地测试,可以保存一下图片,方便核验 - FileOutputStream fos = new FileOutputStream(savePath); - fos.write(out.toByteArray()); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(out.size()+strBuf.length()+end.length()); - bos.write(strBuf.toString().getBytes()); - bos.write(out.toByteArray()); - bos.write(end.getBytes()); - data= bos.toByteArray(); - } catch (HttpProcessException e) { - Utils.exception(e); - } catch (IOException e) { - Utils.exception(e); - } - - Map m = new HashMap(); - m.put(Utils.ENTITY_BYTES, data); - - String html; - try { - html = HttpClientUtil.post(config.client(client).url(apiUrl).headers(headers).map(m)); - //System.out.println(html); - String[] results = StringUtil.regex("([^<]*)\\s*([^<]*)", html); - if(results.length>0){ - //System.out.println(results[0]); - if(Boolean.parseBoolean(results[1])){ - if(limitCodeLen<=0 || limitCodeLen==results[0].length()){//不判断长度或者长度一致时,直接返回 - return results[0]; - }else{ - return "Error:获取失败! 原因:识别结果长度为:"+results[0].length()+"(期望长度:"+limitCodeLen+")"; - } - }else{ - return "Error:获取失败! 原因:"+results[0]; - } - } - } catch (HttpProcessException e) { - Utils.exception(e); - } - - return "Error:获取失败!"; - } - - public static void main(String[] args) throws HttpProcessException, IOException { -// enableCatch(); - String filePath="C:/Users/160049/Desktop/中国.png"; - String url = "http://file.ocrking.net:6080/small/20161104/w4fCjnzCl8KTwphpwqnCv2bCn8Kp/66fcff8d-61b1-49d6-bbfe-7428cf7accdf_debug.png?e9gFvJmkLbmgsZNTUCCNkjfi8J0Wbpn1CZHeP98eT1kxZ0ISBDt8Ql6h6zQ79pJg"; - String url2 = "http://59.41.9.91/GZCX/WebUI/Content/Handler/ValidateCode.ashx?0.3271647585525703"; - String code1 = ocrCode(filePath, 5); - String code2 = ocrCode4Net(url,5); - String code3 = ocrCode4Net(HttpConfig.custom().url(url2), System.getProperty("user.dir")+System.getProperty("file.separator")+"123.png", 5); - System.out.println(code1); - System.out.println(code2); - System.out.println(code3); - System.out.println("----"); - } -} diff --git a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/util/PropertiesUtil.java b/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/util/PropertiesUtil.java deleted file mode 100644 index 360abe36ef..0000000000 --- a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/util/PropertiesUtil.java +++ /dev/null @@ -1,104 +0,0 @@ -/********************************************************* - * 2012-2013 (c) IHARM Corporation. All rights reserved. * - *********************************************************/ -package com.jun.plugin.httpclient.httpclientutil.common.util; - -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -/** - * 最简单的属性文件读取工具类 - * - * @author arron - * @version 1.0 - */ -public class PropertiesUtil { - - /** - * 默认属性集合(文件在Constants中配置) - */ - protected static Properties defaultProp = null; - /** - * 所有读取过的属性集合 - * 文件名 - 属性集合 - */ - protected static Map allProps = new HashMap(); - - // 初始化默认的属性集合 - static { - if (defaultProp == null) { - defaultProp = loadProperties("config.properties"); - allProps.put("config.properties", defaultProp); - } - } - - /** - * 读取属性文件,并将读出来的属性集合添加到【allProps】当中 - * 如果该属性文件之前已读取过,则直接从【allProps】获得 - * - * @param fileName 属性文件名 - * @return 属性 - */ - public static Properties getProperties(String fileName) { - if (fileName==null || "".equals(fileName)) { - return defaultProp; - } else { - Properties prop = allProps.get(fileName); - if(prop == null) { - prop = loadProperties(fileName); - allProps.put(fileName, prop); - } - - return prop; - } - } - - /** - * 解析属性文件,将文件中的所有属性都读取到【Properties】当中 - * - * @param fileName 属性文件名 - * @return 属性 - */ - protected static Properties loadProperties (String fileName) { - Properties prop = new Properties(); - InputStream ins = null; - ins = PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName); - if (ins == null) { - System.err.println("Can not find the resource!"); - } else { - try { - prop.load(ins); - } catch (IOException e) { - System.err.println("An error occurred when reading from the input stream, "+e.getMessage()); - } catch (IllegalArgumentException e) { - System.err.println("The input stream contains a malformed Unicode escape sequence, "+e.getMessage()); - } - } - return prop; - } - - /** - * 从指定的属性文件中获取某一属性值 - * 如果属性文件不存在该属性则返回 null - * - * @param fileName 属性文件 - * @param name 属性名称 - * @return 属性值 - */ - public static String getProperty(String fileName, String name){ - return getProperties(fileName).getProperty(name); - } - - /** - * 从默认的属性文件中获取某一属性值 - * 如果属性文件不存在该属性则返回 null - * @param name 属性名称 - * @return 属性值 - */ - public static String getProperty(String name){ - return getProperties(null).getProperty(name); - } -} diff --git a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/util/StringUtil.java b/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/util/StringUtil.java deleted file mode 100644 index 66db72f561..0000000000 --- a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/common/util/StringUtil.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.jun.plugin.httpclient.httpclientutil.common.util; - -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * 字符串简易工具类 - * - * @author arron - * @version 1.0 - */ -public class StringUtil { - - /** - * 通过正则表达式获取内容 - * - * @param regex 正则表达式 - * @param from 原字符串 - * @return 返回匹配结果 - */ - public static String[] regex(String regex, String from){ - Pattern pattern = Pattern.compile(regex); - Matcher matcher = pattern.matcher(from); - List results = new ArrayList(); - while(matcher.find()){ - for (int i = 0; i < matcher.groupCount(); i++) { - results.add(matcher.group(i+1)); - } - } - return results.toArray(new String[]{}); - } -} diff --git a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/evictor/NIdleConnectionEvictor.java b/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/evictor/NIdleConnectionEvictor.java deleted file mode 100644 index e9b2f1645e..0000000000 --- a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/evictor/NIdleConnectionEvictor.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.jun.plugin.httpclient.httpclientutil.evictor; - -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; - -import org.apache.http.nio.conn.NHttpClientConnectionManager; -import org.apache.http.util.Args; - -/** - * This class maintains a background thread to enforce an eviction policy for expired / idle - * persistent connections kept alive in the connection pool. - * - */ -public final class NIdleConnectionEvictor { - - private NHttpClientConnectionManager connMgr; - private final ThreadFactory threadFactory; - private final Thread thread; - private final long sleepTimeMs; - private final long maxIdleTimeMs; - - @SuppressWarnings("unused") - private volatile Exception exception; - - public NIdleConnectionEvictor( - final NHttpClientConnectionManager connMgr, - final ThreadFactory threadFactory, - final long sleepTime, final TimeUnit sleepTimeUnit, - final long maxIdleTime, final TimeUnit maxIdleTimeUnit) { - //this.connMgr = Args.notNull(connMgr, "Connection manager"); - this.connMgr = connMgr; - this.threadFactory = threadFactory != null ? threadFactory : new DefaultThreadFactory(); - this.sleepTimeMs = sleepTimeUnit != null ? sleepTimeUnit.toMillis(sleepTime) : sleepTime; - this.maxIdleTimeMs = maxIdleTimeUnit != null ? maxIdleTimeUnit.toMillis(maxIdleTime) : maxIdleTime; - this.thread = this.threadFactory.newThread(new Runnable() { - @Override - public void run() { - try { - while (!Thread.currentThread().isInterrupted()) { - Thread.sleep(sleepTimeMs); - connMgr.closeExpiredConnections(); - if (maxIdleTimeMs > 0) { - connMgr.closeIdleConnections(maxIdleTimeMs, TimeUnit.MILLISECONDS); - } - } - } catch (Exception ex) { - exception = ex; - } - - } - }); - } - - public NIdleConnectionEvictor( - final NHttpClientConnectionManager connMgr, - final long sleepTime, final TimeUnit sleepTimeUnit, - final long maxIdleTime, final TimeUnit maxIdleTimeUnit) { - this(connMgr, null, sleepTime, sleepTimeUnit, maxIdleTime, maxIdleTimeUnit); - } - - public NIdleConnectionEvictor( - final NHttpClientConnectionManager connMgr, - final long maxIdleTime, final TimeUnit maxIdleTimeUnit) { - this(connMgr, null, - maxIdleTime > 0 ? maxIdleTime : 5, maxIdleTimeUnit != null ? maxIdleTimeUnit : TimeUnit.SECONDS, - maxIdleTime, maxIdleTimeUnit); - } - - public NIdleConnectionEvictor( - final long maxIdleTime, final TimeUnit maxIdleTimeUnit) { - this(null, null, - maxIdleTime > 0 ? maxIdleTime : 5, maxIdleTimeUnit != null ? maxIdleTimeUnit : TimeUnit.SECONDS, - maxIdleTime, maxIdleTimeUnit); - } - - public NIdleConnectionEvictor setConnMgr(final NHttpClientConnectionManager connMgr){ - this.connMgr = Args.notNull(connMgr, "Connection manager"); - return this; - } - - public void start() { - Args.notNull(connMgr, "Connection manager"); - thread.start(); - } - - public void shutdown() { - thread.interrupt(); - } - - public boolean isRunning() { - return thread.isAlive(); - } - - public void awaitTermination(final long time, final TimeUnit tunit) throws InterruptedException { - thread.join((tunit != null ? tunit : TimeUnit.MILLISECONDS).toMillis(time)); - } - - public void await() { - try { - shutdown(); - thread.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - static class DefaultThreadFactory implements ThreadFactory { - - @Override - public Thread newThread(final Runnable r) { - final Thread t = new Thread(r, "Connection evictor"); - t.setDaemon(true); - return t; - } - - }; - - -} diff --git a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/exception/HttpProcessException.java b/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/exception/HttpProcessException.java deleted file mode 100644 index 78e47c46a8..0000000000 --- a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/httpclient/httpclientutil/exception/HttpProcessException.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.jun.plugin.httpclient.httpclientutil.exception; - - -/** - * - * @author arron - * @version 1.0 - */ -public class HttpProcessException extends Exception { - private static final long serialVersionUID = -2749168865492921426L; - - public HttpProcessException(Exception e){ - super(e); - } - - /** - * @param msg 消息 - */ - public HttpProcessException(String msg) { - super(msg); - } - - /** - * @param message 异常消息 - * @param e 异常 - */ - public HttpProcessException(String message, Exception e) { - super(message, e); - } - -} diff --git a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/okhttp/GetRequest.java b/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/okhttp/GetRequest.java deleted file mode 100644 index 321f90c0a6..0000000000 --- a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/okhttp/GetRequest.java +++ /dev/null @@ -1,32 +0,0 @@ -// This file is commented out — OkHttp wrapper moved to jun_okhttp module. -/* -package com.jun.plugin.okhttp; - -import java.util.Map; - -import okhttp3.Request; -import okhttp3.RequestBody; - -/** - * - * @author Wujun - * - * / -public class GetRequest extends OkHttpRequest { - // - public GetRequest(String url, Object tag, Map params, - Map headers, int id) { - super(url,tag,params,headers,null,null,id); - } - - @Override - protected RequestBody buildRequestBody() { - return null; - } - - @Override - protected Request buildRequest(RequestBody requestBody) { - return builder.get().build(); - } -} -*/ diff --git a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/okhttp/PostRequest.java b/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/okhttp/PostRequest.java deleted file mode 100644 index 6352ab5fd4..0000000000 --- a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/okhttp/PostRequest.java +++ /dev/null @@ -1,100 +0,0 @@ -// This file is commented out — OkHttp wrapper moved to jun_okhttp module. -/* -package com.jun.plugin.okhttp; - -import java.io.UnsupportedEncodingException; -import java.net.FileNameMap; -import java.net.URLConnection; -import java.net.URLEncoder; -import java.util.List; -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import okhttp3.FormBody; -import okhttp3.Headers; -import okhttp3.MediaType; -import okhttp3.MultipartBody; -import okhttp3.Request; -import okhttp3.RequestBody; - -/** - * - * @author Wujun - * - * / -public class PostRequest extends OkHttpRequest { - // - public static Logger logger = LoggerFactory.getLogger(PostRequest.class); - // - public PostRequest(String url, Object tag, Map params, - Map headers,List fileInfos,String postBody,int id) { - super(url, tag, params, headers, fileInfos,postBody,id); - } - - @Override - protected RequestBody buildRequestBody() { - if(postBody!=null&&postBody.length()>0){ - MediaType MEDIA_TYPE_PLAIN = MediaType.parse("text/plain;charset=utf-8"); - return RequestBody.create(MEDIA_TYPE_PLAIN,postBody); - } - else if (fileInfos == null || fileInfos.isEmpty()) { - FormBody.Builder builder = new FormBody.Builder(); - addParams(builder); - FormBody formBody = builder.build(); - return formBody; - } else{ - MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM); - addParams(builder); - fileInfos.forEach(fileInfo -> { - RequestBody fileBody = RequestBody.create(MediaType.parse(getMimeType(fileInfo.fileName)), - fileInfo.fileContent); - builder.addFormDataPart(fileInfo.partName, fileInfo.fileName, fileBody); - }); - return builder.build(); - } - } - - @Override - protected Request buildRequest(RequestBody requestBody) { - return builder.post(requestBody).build(); - } - - private void addParams(FormBody.Builder builder) { - if (params!= null) { - params.forEach((k,v)->builder.add(k,v)); - } - } - // - private void addParams(MultipartBody.Builder builder) { - if (params != null && !params.isEmpty()) { - params.forEach((k,v)->{ - builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + k + "\""), - RequestBody.create(null,v)); - }); - } - } - - // - public static class FileInfo { - public String partName; - public String fileName; - public byte[] fileContent; - } - // - public static String getMimeType(String path) { - FileNameMap fileNameMap = URLConnection.getFileNameMap(); - String contentTypeFor = null; - try { - contentTypeFor = fileNameMap.getContentTypeFor(URLEncoder.encode(path, "UTF-8")); - } catch (UnsupportedEncodingException e) { - logger.error(e.getMessage(),e); - } - if (contentTypeFor == null) { - contentTypeFor = "application/octet-stream"; - } - return contentTypeFor; - } -} -*/ diff --git a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/okhttp/Response.java b/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/okhttp/Response.java deleted file mode 100644 index 87d158822a..0000000000 --- a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/okhttp/Response.java +++ /dev/null @@ -1,136 +0,0 @@ -// This file is commented out — OkHttp wrapper moved to jun_okhttp module. -/* -package com.jun.plugin.okhttp; - -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -import okhttp3.Handshake; -import okhttp3.Headers; -import okhttp3.Protocol; -import okhttp3.Request; -import okhttp3.ResponseBody; - -/** - * - * @author Wujun - * - * / -public class Response { - // - public okhttp3.Response response; - // - public Response(okhttp3.Response response){ - this.response=response; - } - // - public Request request() { - return response.request(); - } - - /** - * Returns the HTTP protocol, such as {@link Protocol#HTTP_1_1} or - * {@link Protocol#HTTP_1_0}. - * / - public Protocol protocol() { - return response.protocol(); - } - - /** Returns the HTTP status code. * / - public int code() { - return response.code(); - } - - /** - * Returns true if the code is in [200..300), which means the request was - * successfully received, understood, and accepted. - * / - public boolean isSuccessful() { - return response.isSuccessful(); - } - - /** Returns the HTTP status message or null if it is unknown. * / - public String message() { - return response.message(); - } - - /** - * Returns the TLS handshake of the connection that carried this response, - * or null if the response was received without TLS. - * / - public Handshake handshake() { - return response.handshake(); - } - - public List headers(String name) { - return response.headers(name); - } - - public String header(String name) { - return response.header(name, null); - } - - public String header(String name, String defaultValue) { - return response.header(name, defaultValue); - } - - public Headers headers() { - return response.headers(); - } - - /** - * Peeks up to {@code byteCount} bytes from the response body and returns - * them as a new response body. If fewer than {@code byteCount} bytes are in - * the response body, the full response body is returned. If more than - * {@code byteCount} bytes are in the response body, the returned value will - * be truncated to {@code byteCount} bytes. - * - *

- * It is an error to call this method after the body has been consumed. - * - *

- * Warning: this method loads the requested bytes into - * memory. Most applications should set a modest limit on {@code byteCount}, - * such as 1 MiB. - * / - public ResponseBody peekBody(long byteCount) throws IOException { - return response.peekBody(byteCount); - } - - /** - * Never {@code null}, must be closed after consumption, can be consumed - * only once. - * / - public ResponseBody body() { - return response.body(); - } - - // - /** - * Returns the response as a string decoded with the charset of the - * Content-Type header. If that header is either absent or lacks a charset, - * this will attempt to decode the response body as UTF-8. - * / - public final String string() throws IOException { - return body().string(); - } - // - /** - * Returns the response as a string decoded with the charset of the - * Content-Type header. If that header is either absent or lacks a charset, - * this will attempt to decode the response body as UTF-8. - * / - public final String string(String charset) throws IOException { - return new String(body().bytes(),charset); - } - // - public final byte[] bytes() throws IOException { - return body().bytes(); - } - // - public final InputStream byteStream() { - return body().source().inputStream(); - } -} -*/ diff --git a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/okhttp/callback/Callback.java b/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/okhttp/callback/Callback.java deleted file mode 100644 index 2b827092ef..0000000000 --- a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/okhttp/callback/Callback.java +++ /dev/null @@ -1,19 +0,0 @@ -// This file is commented out — OkHttp wrapper moved to jun_okhttp module. -/* -package com.jun.plugin.okhttp.callback; - -import com.jun.plugin.okhttp.Response; - -import okhttp3.Call; - -/** - * - * @author Wujun - * / -public abstract class Callback{ - // - public abstract void onFailure(Call call,Exception e,int id); - // - public abstract void onResponse(Call call,Response response, int id); -} -*/ diff --git a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/okhttp/callback/StringCallback.java b/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/okhttp/callback/StringCallback.java deleted file mode 100644 index 31dae8fa65..0000000000 --- a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/okhttp/callback/StringCallback.java +++ /dev/null @@ -1,31 +0,0 @@ -// This file is commented out — OkHttp wrapper moved to jun_okhttp module. -/* -package com.jun.plugin.okhttp.callback; - -import java.io.IOException; - -import com.jun.plugin.okhttp.Response; - -import okhttp3.Call; - -/** - * - * @author Wujun - * - * / -public abstract class StringCallback extends Callback{ - // - @Override - public void onResponse(Call call, Response response, int id) { - try { - onSuccess(call,response.body().string(),id); - } catch (IOException e) { - e.printStackTrace(); - } - } - // - public void onSuccess(Call call,String response,int id) { - - } -} -*/ diff --git a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/okhttp/interceptor/DownloadFileProgressListener.java b/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/okhttp/interceptor/DownloadFileProgressListener.java deleted file mode 100644 index 5c5f028e73..0000000000 --- a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/okhttp/interceptor/DownloadFileProgressListener.java +++ /dev/null @@ -1,13 +0,0 @@ -// This file is commented out — OkHttp wrapper moved to jun_okhttp module. -/* -package com.jun.plugin.okhttp.interceptor; - -/** - * - * @author Wujun - * - * / -public interface DownloadFileProgressListener { - void updateProgress(long downloadLenth, long totalLength, boolean done); -} -*/ diff --git a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/okhttp/util/FileUtil.java b/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/okhttp/util/FileUtil.java deleted file mode 100644 index 14106290e0..0000000000 --- a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/okhttp/util/FileUtil.java +++ /dev/null @@ -1,186 +0,0 @@ -// This file is commented out — OkHttp wrapper moved to jun_okhttp module. -/* -package com.jun.plugin.okhttp.util; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.util.Enumeration; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; -/** - * - * @author Wujun - * - * / -public class FileUtil { - // - private static final int BUFFER = 2048; - - private FileUtil() { - } - // - public static void unzip(String file, String destFolder) throws IOException { - BufferedOutputStream dest = null; - BufferedInputStream is = null; - ZipEntry entry; - ZipFile zipfile = new ZipFile(file); - Enumeration e = zipfile.entries(); - while (e.hasMoreElements()) { - entry = (ZipEntry) e.nextElement(); - if (entry.isDirectory()) { - File f = new File(destFolder, entry.getName()); - f.mkdirs(); - } else { - InputStream iis = zipfile.getInputStream(entry); - is = new BufferedInputStream(iis); - int count; - byte data[] = new byte[BUFFER]; - File theFile = new File(destFolder, entry.getName()); - FileOutputStream fos = new FileOutputStream(theFile); - dest = new BufferedOutputStream(fos, BUFFER); - while ((count = is.read(data, 0, BUFFER)) != -1) { - dest.write(data, 0, count); - } - dest.flush(); - dest.close(); - is.close(); - iis.close(); - } - } - zipfile.close(); - } - - // - public static void copyFile(String sourceURL, String destFilePath) - throws Exception { - File destFile = new File(destFilePath); - URL url = new URL(sourceURL); - FileOutputStream fos = new FileOutputStream(destFile); - InputStream is = url.openStream(); - byte[] buffer = new byte[4096]; - int n = 0; - while (-1 != (n = is.read(buffer))) { - fos.write(buffer, 0, n); - } - IOUtil.closeQuietly(is); - IOUtil.closeQuietly(fos); - } - - // - public static File createEmptyDir(String path) { - File tempDir = new File(path); - if (tempDir.exists() && !tempDir.isDirectory()) { - throw new RuntimeException("file:" + path + " already exists."); - } - if (tempDir.exists()) { - if (!deleteDirectory(tempDir)) { - throw new RuntimeException("can not delete old dir:" + path); - } - } - if (!tempDir.mkdirs()) { - throw new RuntimeException("can not create dir:" + path); - } - return tempDir; - } - - // - public static File createTemporaryDirectory(String prefix) { - File tempDir = null; - try { - tempDir = File.createTempFile(prefix, ""); - } catch (IOException e) { - throw new RuntimeException("could not create temporary file " - + prefix, e); - } - boolean success = tempDir.delete(); - if (!success) { - throw new RuntimeException("could not delete temporary file " - + tempDir); - } - success = tempDir.mkdir(); - if (!success) { - throw new RuntimeException("could not create temporary directory " - + tempDir); - } - return tempDir; - } - - public static boolean deleteDirectory(File directory) { - if (directory.exists()) { - File[] files = directory.listFiles(); - for (File file : files) { - if (file.isDirectory()) { - deleteDirectory(file); - } else { - // noinspection ResultOfMethodCallIgnored - file.delete(); - } - } - } - return (directory.delete()); - } - - /** - * get content from file - * - * @param filePath - * @return - * @throws IOException - * / - public static byte[] getBytes(String filePath) throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - IOUtil.copy(new FileInputStream(filePath), bos); - return bos.toByteArray(); - } - - /** - * get content from file - * - * @param filePath - * @return - * @throws IOException - * / - public static String getContent(String filePath) throws IOException { - return getContent(new File(filePath)); - } - - /** - * get content from file - * - * @param filePath - * @return - * @throws IOException - * / - public static String getContent(File file) throws IOException { - return new String(Files.readAllBytes(file.toPath()), - StandardCharsets.UTF_8); - } - - // - public static void saveContent(String content, File file) - throws IOException { - try (FileOutputStream fos = new FileOutputStream(file); - ByteArrayInputStream bis = new ByteArrayInputStream( - content.getBytes())) { - IOUtil.copy(bis, fos); - } - } - - public static void saveContent(byte bb[], File file) throws IOException { - try (FileOutputStream fos = new FileOutputStream(file); - ByteArrayInputStream bis = new ByteArrayInputStream(bb)) { - IOUtil.copy(bis, fos); - } - } -} -*/ diff --git a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/okhttp/util/IOUtil.java b/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/okhttp/util/IOUtil.java deleted file mode 100644 index f744ecc1f5..0000000000 --- a/jun_java_plugins/jun_httpclient/src/main/java/com/jun/plugin/okhttp/util/IOUtil.java +++ /dev/null @@ -1,302 +0,0 @@ -// This file is commented out — OkHttp wrapper moved to jun_okhttp module. -/* -package com.jun.plugin.okhttp.util; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.BufferedReader; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.Reader; -import java.io.StringWriter; -import java.io.Writer; -import java.net.URL; -import java.net.URLConnection; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Enumeration; -import java.util.List; -import java.util.function.BiConsumer; -import java.util.zip.DataFormatException; -import java.util.zip.Deflater; -import java.util.zip.Inflater; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * @author Wujun - * - * / -public class IOUtil { - private static Logger logger = LoggerFactory.getLogger(IOUtil.class); - private static final int CACHE_SIZE = 512; - - // - // - public static byte[] compress(byte[] inputs) { - if (inputs.length == 0) { - return inputs; - } - Deflater deflater = new Deflater(Deflater.BEST_SPEED); - deflater.setInput(inputs); - deflater.finish(); - byte outputs[] = new byte[0]; - try(ByteArrayOutputStream stream = new ByteArrayOutputStream(inputs.length);){ - byte[] bytes = new byte[CACHE_SIZE]; - int value; - while (!deflater.finished()) { - value = deflater.deflate(bytes); - stream.write(bytes, 0, value); - } - outputs = stream.toByteArray(); - deflater.end(); - } catch (IOException e) { - logger.error(e.getMessage(), e); - } - return outputs; - } - - // - // - public static byte[] decompress(byte[] input) { - if (input.length == 0) { - return input; - } - Inflater decompressor = new Inflater(); - decompressor.setInput(input); - ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length); - byte[] buf = new byte[CACHE_SIZE]; - try { - while (!decompressor.finished()) { - int count = decompressor.inflate(buf); - bos.write(buf, 0, count); - } - } catch (DataFormatException e) { - return input; - } finally { - try { - decompressor.end(); - bos.close(); - } catch (IOException e) { - logger.error(e.getMessage(), e); - } - } - byte[] decompressedData = bos.toByteArray(); - return decompressedData; - } - - // - /** - * / - public static void closeQuietly(OutputStream output) { - try { - if (output != null) { - output.flush(); - output.close(); - } - } catch (IOException ioe) { - logger.error(ioe.getMessage(), ioe); - } - } - - // - /** - * / - public static void closeQuietly(InputStream input) { - try { - if (input != null) { - input.close(); - } - } catch (IOException ioe) { - logger.error(ioe.getMessage(), ioe); - } - } - - // - /** - * copy inputstream data to output stream - * / - public static long copy(InputStream input, OutputStream output) - throws IOException { - byte[] buffer = new byte[4096]; - long count = 0; - int n = 0; - while (-1 != (n = input.read(buffer))) { - output.write(buffer, 0, n); - count += n; - } - return count; - } - - /** - * - * @param file - * @return - * @throws IOException - * / - public static String getContent(InputStream in) throws IOException { - try (InputStreamReader isr = new InputStreamReader(in); - BufferedReader br = new BufferedReader(isr);) { - StringBuilder sb = new StringBuilder(); - String s = null; - while ((s = br.readLine()) != null) { - sb.append(s).append("\n"); - } - return sb.toString(); - } - } - // - public static ListgetContentList(InputStream inStream)throws IOException{ - ListinputLines=new ArrayList(); - BufferedReader br = new BufferedReader(new InputStreamReader(inStream)); - String line = null; - while ((line = br.readLine()) != null) { - inputLines.add(line); - } - return inputLines; - } - // - public static void unzip(File file, File destFolder) throws IOException { - final int BUFFER=2048; - BufferedOutputStream dest = null; - BufferedInputStream is = null; - ZipEntry entry; - ZipFile zipfile = new ZipFile(file); - Enumeration e = zipfile.entries(); - while (e.hasMoreElements()) { - entry = (ZipEntry) e.nextElement(); - if (entry.isDirectory()) { - File f = new File(destFolder, entry.getName()); - f.mkdirs(); - } else { - InputStream iis=zipfile.getInputStream(entry); - is = new BufferedInputStream(iis); - int count; - byte data[] = new byte[BUFFER]; - File theFile = new File(destFolder, entry.getName()); - FileOutputStream fos = new FileOutputStream(theFile); - dest = new BufferedOutputStream(fos, BUFFER); - while ((count = is.read(data, 0, BUFFER)) != -1) { - dest.write(data, 0, count); - } - dest.flush(); - dest.close(); - is.close(); - iis.close(); - } - } - zipfile.close(); - } - /** - * copy file from source file to dest file - * / - public static void copyFile(File sourceFile,File destFile)throws Exception{ - copy(new FileInputStream(sourceFile),new FileOutputStream(destFile)); - } - /** - * copy file from source url to destfile - * / - public static void copyFile( - String sourceURL, - String destFilePath, - BiConsumerprogress) - throws Exception { - File destFile = new File(destFilePath); - URL url = new URL(sourceURL); - FileOutputStream fos = new FileOutputStream(destFile); - URLConnection connection=url.openConnection(); - long contentLength=connection.getContentLength(); - long currentLength=0; - InputStream is = connection.getInputStream(); - byte[] buffer = new byte[4096]; - int n = 0; - while (-1 != (n = is.read(buffer))) { - currentLength+=n; - fos.write(buffer, 0, n); - if(progress!=null){ - progress.accept(contentLength,currentLength); - } - } - IOUtil.closeQuietly(is); - IOUtil.closeQuietly(fos); - } - /** - * if we use file.delete to delete a none empty directory,delete action will - * fail,we need to delete all file under this directory first. - * / - public static boolean deleteDirectory(File directory) { - if(!directory.exists()){ - return true; - } - Arrays.asList(directory.listFiles()).forEach(file->{ - if (file.isDirectory()) { - deleteDirectory(file); - } else { - file.delete(); - } - }); - return (directory.delete()); - } - - /** - *convert input stream to byte array - * / - public static byte[] toByteArray(InputStream input) throws IOException { - ByteArrayOutputStream os = new ByteArrayOutputStream(); - byte[] buf = new byte[1024]; - for (int n = input.read(buf); n != -1; n = input.read(buf)) { - os.write(buf, 0, n); - } - return os.toByteArray(); - } - - /** - * convert inputstream to string - * / - public static String toString(InputStream input) throws IOException { - StringWriter sw = new StringWriter(); - copy(input, sw); - return sw.toString(); - } - /** - * copy input stream to writer - * / - public static void copy(InputStream input, Writer output) - throws IOException { - InputStreamReader in = new InputStreamReader(input); // NOSONAR - copy(in, output); - } - /** - *copy input reader to output writer - * / - public static int copy(Reader input, Writer output) throws IOException { - long count = copyLarge(input, output); - if (count > Integer.MAX_VALUE) { - return -1; - } - return (int) count; - } - // - public static long copyLarge(Reader input, Writer output) - throws IOException { - char[] buffer = new char[1024 * 4]; - long count = 0; - int n = 0; - while (-1 != (n = input.read(buffer))) { - output.write(buffer, 0, n); - count += n; - } - return count; - } -} -*/ diff --git a/jun_java_plugins/jun_httpclient/src/main/java/config.properties b/jun_java_plugins/jun_httpclient/src/main/java/config.properties deleted file mode 100644 index fee29c7bed..0000000000 --- a/jun_java_plugins/jun_httpclient/src/main/java/config.properties +++ /dev/null @@ -1,32 +0,0 @@ -#\u6253\u5f00\u4e0b\u9762\u8fd9\u4e2a\u9875\u9762\uff0c\u8fdb\u9a8c\u8bc1\u7801\u5f00\u53d1\u8005\u7684\u7fa4\uff0c\u7fa4\u6587\u4ef6\u91cc\u6709\u83b7\u53d6apiKey\u7684\u65b9\u6cd5 -#https:github.com/AvensLab/OcrKing/blob/master/%E7%BA%BF%E4%B8%8A%E8%AF%86%E5%88%ABhttp%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E.txt -# -#\u4e00\u4e0b\u5185\u5bb9\u5c31\u662fapiKey\u83b7\u53d6\u65b9\u6cd5\uff1a -# -#\u672c\u8bc6\u522b\u670d\u52a1\u4e3a\u514d\u8d39\uff0c\u6ca1\u6709apiKey \u8bf7\u4ee5 apiKey \u4e3a\u6807\u9898 -#!!!!\u4e00\u5b9a\u8981\u4ee5 apiKey (\u6216key \u4e8c\u9009\u4e00\u5373\u53ef) \u4e3a\u6807\u9898!!!! -# -#\u6b63\u6587\u5185\u5bb9\u8bf7\u6309\u4ee5\u4e0b\u683c\u5f0f\u5199 -#\u4f7f\u7528\u8bc6\u522b\u63a5\u53e3\u5927\u81f4\u7528\u9014 \u4f7f\u7528\u73af\u5883 \u5f00\u53d1\u5de5\u5177\u6216\u8bed\u8a00 \u7528\u6237\u7c7b\u578b \u4eba\u7fa4\u6570\u91cf\u8303\u56f4 -#\u4ee5\u4e0b\u5185\u5bb9\u4ec5\u4f9b\u53c2\u8003\uff0c\u8bf7\u6309\u5b9e\u9645\u60c5\u51b5\u4fee\u6539\uff0c -# -#\u7528\u9014\uff1a\u6587\u6863\u7535\u5b50\u5316\uff0c\u81ea\u52a8\u767b\u5f55\uff0c\u626b\u4e8c\u7ef4\u7801..... -#\u73af\u5883\uff1aPC\uff0cAPP\uff0cWEB -#\u5de5\u5177\u6216\u8bed\u8a00: eclipse,VS,ZS c++,c#,java,php,python,js ..... -#\u7c7b\u578b\uff1a\u4e2a\u4eba\uff0c\u516c\u53f8\uff0c\u5f00\u6e90\uff0c\u514d\u8d39 -#\u4eba\u7fa4\u6570\u91cf\uff1a0-10,10-50,50-100,100+ ..... -# -# -#\u865a\u6784\u7f16\u9020\u6216\u4e0d\u7b26\u5408\u8981\u6c42\u7684\u4e0d\u4f1a\u56de\u590d -#\u65e0\u610f\u601d\u7684\u4e71\u8f93\u5165\u4f1a\u8fdb\u5165\u5783\u573e\u7bb1 -#\u53ef\u80fd\u4f1a\u6709\u5ef6\u8fdf\uff0c\u8bf7\u5306\u591a\u6b21\u91cd\u590d\u53d1\u9001\uff0c -#\u591a\u6b21\u53d1\u9001\u7cfb\u7edf\u53ef\u80fd\u4f1a\u5224\u65ad\u4e3a\u5783\u573e\u4fe1\u4ef6 -# -#\u53d1\u90ae\u4ef6\u5230 ok\uff08@\uff09ocrking.com \u83b7\u53d6 -#!!!!\u90ae\u4ef6\u5730\u5740\u8bf7\u53bb\u6389\u4e24\u4fa7\u62ec\u53f7!!!! -#\u4ec5\u63a5\u53d7\u4ee5\u4e0b\u540e\u7f00\u7684\u90ae\u7bb1 qq.com/163.com/sina.com/126.com -# /outlook.com/gmail.com/live.com/139.com/wo.com.cn/189.com -#\u56de\u53d1\u7684apiKey\u5b57\u4e32\u533a\u5206\u5927\u5c0f\u5199 - -#\u683c\u5f0f\u5982\u4e0b\uff1a -OCR.key=1a8085d1b4e993649f2SvMv6S33ZzHfUb7OTVlT048KA9t0GcT1fSaumUsi9UYSb6kX6t3IlnbA diff --git a/jun_java_plugins/jun_httpclient/src/main/resources/log4j.properties b/jun_java_plugins/jun_httpclient/src/main/resources/log4j.properties deleted file mode 100644 index b34924db06..0000000000 --- a/jun_java_plugins/jun_httpclient/src/main/resources/log4j.properties +++ /dev/null @@ -1,29 +0,0 @@ -### \u8bbe\u7f6e Logger \u8f93\u51fa\u7ea7\u522b\u548c\u8f93\u51fa\u76ee\u7684\u5730 ### - -log4j.rootLogger=INFO,stdout,logfile - -### \u628a\u65e5\u5fd7\u4fe1\u606f\u8f93\u51fa\u5230\u63a7\u5236\u53f0 ### - -log4j.appender.INFO=org.apache.log4j.ConsoleAppender -log4j.appender.INFO.layout=org.apache.log4j.PatternLayout -log4j.appender.INFO.layout.ConversionPattern=[%-5p] %L method:%l - %m%n - -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -#log4j.appender.stdout.Target=System.err -log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout -#log4j.appender.stdout.layout.ConversionPattern=[%-5p] %L method:%l - %m%n - -### \u628a\u65e5\u5fd7\u4fe1\u606f\u8f93\u51fa\u5230\u6587\u4ef6 jbit.log ### - -#log4j.appender.logfile=org.apache.log4j.FileAppender -log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender - -log4j.appender.logfile.File=/logs/httpclient/httputil.log - -log4j.appender.logfile.DatePattern='.'yyyy-MM-dd - -log4j.appender.logfile.layout=org.apache.log4j.PatternLayout - -#log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %F %p %m%n -log4j.appender.logfile.layout.ConversionPattern=[%-5p] %L-%d{yyyy-MM-dd HH:mm:ss,SSS} method:%l - %m%n - diff --git a/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/Demo.java b/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/Demo.java deleted file mode 100644 index 1c87519ddd..0000000000 --- a/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/Demo.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.jun.plugin.httpclient.httpclientutil.test; - -import java.io.FileNotFoundException; -import java.util.HashMap; -import java.util.Map; - -import org.apache.http.Header; -import org.apache.http.client.HttpClient; - -import com.jun.plugin.httpclient.httpclientutil.HttpClientUtil; -import com.jun.plugin.httpclient.httpclientutil.builder.HCB; -import com.jun.plugin.httpclient.httpclientutil.common.HttpConfig; -import com.jun.plugin.httpclient.httpclientutil.common.HttpHeader; -import com.jun.plugin.httpclient.httpclientutil.common.HttpResult; -import com.jun.plugin.httpclient.httpclientutil.common.SSLs.SSLProtocolVersion; -import com.jun.plugin.httpclient.httpclientutil.exception.HttpProcessException; - -/** - * 使用简单介绍 - * - * @author arron - * @date 2016年11月7日 下午2:36:16 - * @version 1.0 - */ -public class Demo { - - public static void main(String[] args) throws HttpProcessException, FileNotFoundException { - String url = "https://github.com/Arronlong/httpclientutil"; - - //最简单的使用: - String html = HttpClientUtil.get(HttpConfig.custom().url(url).client(HCB.custom().sslpv(SSLProtocolVersion.TLSv1_2).ssl().build())); - System.out.println(html); - - //--------------------------------- - // 【详细说明】 - //-------------------------------- - - //插件式配置Header(各种header信息、自定义header) - Header[] headers = HttpHeader.custom() - .userAgent("javacl") - .other("customer", "自定义") - .build(); - - //插件式配置生成HttpClient时所需参数(超时、连接池、ssl、重试) - HCB hcb = HCB.custom() - //.timeout(1000) //超时 - .pool(100, 10) //启用连接池,每个路由最大创建10个链接,总连接数限制为100个 - .sslpv(SSLProtocolVersion.TLSv1_2) //可设置ssl版本号,默认SSLv3,用于ssl,也可以调用sslpv("TLSv1.2") - .ssl() //https,支持自定义ssl证书路径和密码,ssl(String keyStorePath, String keyStorepass) - .retry(5) //重试5次 - ; - - HttpClient client = hcb.build(); - - Map map = new HashMap(); - map.put("key1", "value1"); - map.put("key2", "value2"); - - //插件式配置请求参数(网址、请求参数、编码、client) - HttpConfig config = HttpConfig.custom() - .headers(headers) //设置headers,不需要时则无需设置 - .timeout(1000) //超时 - .url(url) //设置请求的url - .map(map) //设置请求参数,没有则无需设置 - .encoding("utf-8") //设置请求和返回编码,默认就是Charset.defaultCharset() - .client(client) //如果只是简单使用,无需设置,会自动获取默认的一个client对象 - //.inenc("utf-8") //设置请求编码,如果请求返回一直,不需要再单独设置 - //.inenc("utf-8") //设置返回编码,如果请求返回一直,不需要再单独设置 - //.json("json字符串") //json方式请求的话,就不用设置map方法,当然二者可以共用。 - //.context(HttpCookies.custom().getContext()) //设置cookie,用于完成携带cookie的操作 - //.out(new FileOutputStream("保存地址")) //下载的话,设置这个方法,否则不要设置 - //.files(new String[]{"d:/1.txt","d:/2.txt"}) //上传的话,传递文件路径,一般还需map配置,设置服务器保存路径 - ; - - - //使用方式: - String result1 = HttpClientUtil.get(config); //get请求 - String result2 = HttpClientUtil.post(config); //post请求 - System.out.println(result1); - System.out.println(result2); - - //HttpClientUtil.down(config); //下载,需要调用config.out(fileOutputStream对象) - //HttpClientUtil.upload(config); //上传,需要调用config.files(文件路径数组) - - //如果指向看是否访问正常 - //String result3 = HttpClientUtil.head(config); // 返回Http协议号+状态码 - //int statusCode = HttpClientUtil.status(config);//返回状态码 - - //[新增方法]sendAndGetResp,可以返回原生的HttpResponse对象, - //同时返回常用的几类对象:result、header、StatusLine、StatusCode - HttpResult respResult = HttpClientUtil.sendAndGetResp(config); - System.out.println("返回结果:\n"+respResult.getResult()); - System.out.println("返回resp-header:"+respResult.getRespHeaders());//可以遍历 - System.out.println("返回具体resp-header:"+respResult.getHeaders("Date")); - System.out.println("返回StatusLine对象:"+respResult.getStatusLine()); - System.out.println("返回StatusCode:"+respResult.getStatusCode()); - System.out.println("返回HttpResponse对象)(可自行处理):"+respResult.getResp()); - - } -} diff --git a/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/HttpClientTest.java b/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/HttpClientTest.java deleted file mode 100644 index e4579d98bc..0000000000 --- a/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/HttpClientTest.java +++ /dev/null @@ -1,198 +0,0 @@ -package com.jun.plugin.httpclient.httpclientutil.test; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import org.apache.http.Header; -import org.apache.http.client.HttpClient; - -import com.jun.plugin.httpclient.httpclientutil.HttpClientUtil; -import com.jun.plugin.httpclient.httpclientutil.builder.HCB; -import com.jun.plugin.httpclient.httpclientutil.common.HttpConfig; -import com.jun.plugin.httpclient.httpclientutil.common.HttpHeader; -import com.jun.plugin.httpclient.httpclientutil.exception.HttpProcessException; - -/** - * - * @author arron - * @date 2015年11月1日 下午2:23:18 - * @version 1.0 - */ -public class HttpClientTest { - - public static void testOne() throws HttpProcessException{ - - System.out.println("--------简单方式调用(默认post)--------"); - String url = "http://tool.oschina.net/"; - HttpConfig config = HttpConfig.custom(); - //简单调用 - String resp = HttpClientUtil.get(config.url(url)); - - System.out.println("请求结果内容长度:"+ resp.length()); - - System.out.println("\n#################################\n"); - - System.out.println("--------加入header设置--------"); - url="http://blog.csdn.net/xiaoxian8023"; - //设置header信息 - Header[] headers=HttpHeader.custom().userAgent("Mozilla/5.0").build(); - //执行请求 - resp = HttpClientUtil.get(config.headers(headers)); - System.out.println("请求结果内容长度:"+ resp.length()); - - System.out.println("\n#################################\n"); - - System.out.println("--------代理设置(绕过证书验证)-------"); - url="https://www.facebook.com/"; - HttpClient client= HCB.custom().timeout(10000).proxy("127.0.0.1", 8087).ssl().build();//采用默认方式(绕过证书验证) - //执行请求 - resp = HttpClientUtil.get(config.client(client)); - System.out.println("请求结果内容长度:"+ resp.length()); - - System.out.println("\n#################################\n"); - -// System.out.println("--------代理设置(自签名证书验证)+header+get方式-------"); -// url = "https://sso.tgb.com:8443/cas/login"; -// client= HCB.custom().timeout(10000).ssl("D:\\keys\\wsriakey","tomcat").build(); -// headers=HttpHeader.custom().keepAlive("false").connection("close").contentType(Headers.APP_FORM_URLENCODED).build(); -// //执行请求 -// resp = CopyOfHttpClientUtil.get(config.method(HttpMethods.GET)); -// System.out.println("请求结果内容长度:"+ resp.length()); - try { - System.out.println("--------下载测试-------"); - url="http://ss.bdimg.com/static/superman/img/logo/logo_white_fe6da1ec.png"; - FileOutputStream out = new FileOutputStream(new File("d://aaa//000.png")); - HttpClientUtil.down(HttpConfig.custom().url(url).out(out)); - out.flush(); - out.close(); - System.out.println("--------下载测试+代理-------"); - - out = new FileOutputStream(new File("d://aaa//001.png")); - HttpClientUtil.down(HttpConfig.custom().client(client).url(url).out(out)); - out.flush(); - out.close(); - } catch (IOException e) { - e.printStackTrace(); - } - - System.out.println("\n#################################\n"); - } - - - - public static void testMutilTask() throws HttpProcessException{ - // URL列表数组 - String[] urls = { - "http://blog.csdn.net/xiaoxian8023/article/details/49883113", - "http://blog.csdn.net/xiaoxian8023/article/details/49909359", - "http://blog.csdn.net/xiaoxian8023/article/details/49910127", - "http://blog.csdn.net/xiaoxian8023/article/details/49910885", - -// "http://blog.csdn.net/xiaoxian8023/article/details/49862725", -// "http://blog.csdn.net/xiaoxian8023/article/details/49834643", -// "http://blog.csdn.net/xiaoxian8023/article/details/49834615", -// "http://blog.csdn.net/xiaoxian8023/article/details/49834589", -// "http://blog.csdn.net/xiaoxian8023/article/details/49785417", -// -// "http://blog.csdn.net/xiaoxian8023/article/details/48679609", -// "http://blog.csdn.net/xiaoxian8023/article/details/48681987", -// "http://blog.csdn.net/xiaoxian8023/article/details/48710653", -// "http://blog.csdn.net/xiaoxian8023/article/details/48729479", -// "http://blog.csdn.net/xiaoxian8023/article/details/48733249", -// -// "http://blog.csdn.net/xiaoxian8023/article/details/48806871", -// "http://blog.csdn.net/xiaoxian8023/article/details/48826857", -// "http://blog.csdn.net/xiaoxian8023/article/details/49663643", -// "http://blog.csdn.net/xiaoxian8023/article/details/49619777", -// "http://blog.csdn.net/xiaoxian8023/article/details/47335659", -// -// "http://blog.csdn.net/xiaoxian8023/article/details/47301245", -// "http://blog.csdn.net/xiaoxian8023/article/details/47057573", -// "http://blog.csdn.net/xiaoxian8023/article/details/45601347", -// "http://blog.csdn.net/xiaoxian8023/article/details/45569441", -// "http://blog.csdn.net/xiaoxian8023/article/details/43312929", - }; - String[] imgurls ={"http://ss.bdimg.com/static/superman/img/logo/logo_white_fe6da1ec.png", - "https://scontent-hkg3-1.xx.fbcdn.net/hphotos-xaf1/t39.2365-6/11057093_824152007634067_1766252919_n.png"}; - // 设置header信息 - Header[] headers = HttpHeader.custom().userAgent("Mozilla/5.0").from("http://blog.csdn.net/newest.html").build(); - HttpClient client= HCB.custom().timeout(10000).proxy("127.0.0.1", 8087).ssl().build();//采用默认方式(绕过证书验证) - - long start = System.currentTimeMillis(); - try { - int pagecount = urls.length; - ExecutorService executors = Executors.newFixedThreadPool(pagecount); - CountDownLatch countDownLatch = new CountDownLatch(pagecount*10); - for(int i = 0; i< pagecount*10;i++){ - FileOutputStream out = new FileOutputStream(new File("d://aaa//"+(i+1)+".png")); - //启动线程抓取 - executors.execute(new GetRunnable(countDownLatch).setConfig(HttpConfig.custom().headers(headers).url(urls[i%pagecount]))); - executors.execute(new GetRunnable(countDownLatch).setConfig(HttpConfig.custom().client(client).headers(headers).url(imgurls[i%2]).out(out))); - } - countDownLatch.await(); - executors.shutdown(); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (InterruptedException e) { - e.printStackTrace(); - } finally { - System.out.println("线程" + Thread.currentThread().getName() + ", 所有线程已完成,开始进入下一步!"); - } - - long end = System.currentTimeMillis(); - System.out.println("总耗时(毫秒): -> " + (end - start)); - //(7715+7705+7616)/3= 23 036/3= 7 678.66---150=51.2 - //(9564+8250+8038+7604+8401)/5=41 857/5=8 371.4--150 - //(9803+8244+8188+8378+8188)/5=42 801/5= 8 560.2---150 - } - - static class GetRunnable implements Runnable { - private CountDownLatch countDownLatch; - private HttpConfig config = null; - - public GetRunnable setConfig(HttpConfig config){ - this.config = config; - return this; - } - - public GetRunnable(CountDownLatch countDownLatch){ - this.countDownLatch = countDownLatch; - } - @Override - public void run() { - try { - if(config.out()==null){ - String response = null; - response = HttpClientUtil.get(config); - System.out.println(Thread.currentThread().getName()+"--获取内容长度:"+response.length()); - }else{ - HttpClientUtil.down(config); - try { - config.out().flush(); - config.out().close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } catch (HttpProcessException e) { - e.printStackTrace(); - } finally { - countDownLatch.countDown(); - } - } - } - - public static void main(String[] args) throws Exception { - File file = new File("d://aaa"); - if(!file.exists() && file.isDirectory()){ - file.mkdir(); - } -// testOne(); - testMutilTask(); - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/SimpleHttpClientDemo.java b/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/SimpleHttpClientDemo.java deleted file mode 100644 index ae8264d3ef..0000000000 --- a/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/SimpleHttpClientDemo.java +++ /dev/null @@ -1,231 +0,0 @@ -package com.jun.plugin.httpclient.httpclientutil.test; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.security.KeyManagementException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpHost; -import org.apache.http.NameValuePair; -import org.apache.http.ParseException; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.config.Registry; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.conn.socket.ConnectionSocketFactory; -import org.apache.http.conn.socket.PlainConnectionSocketFactory; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.conn.ssl.TrustSelfSignedStrategy; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.conn.DefaultProxyRoutePlanner; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.ssl.SSLContexts; -import org.apache.http.util.EntityUtils; - -/** - * 简单httpclient实例 - * - * @author arron - * @date 2015年11月11日 下午6:36:49 - * @version 1.0 - */ -public class SimpleHttpClientDemo { - - /** - * 设置信任自定义的证书 - * - * @param keyStorePath 密钥库路径 - * @param keyStorepass 密钥库密码 - * @return - */ - public static SSLContext custom(String keyStorePath, String keyStorepass) { - SSLContext sc = null; - FileInputStream instream = null; - KeyStore trustStore = null; - try { - trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); - instream = new FileInputStream(new File(keyStorePath)); - trustStore.load(instream, keyStorepass.toCharArray()); - // 相信自己的CA和所有自签名的证书 - sc = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build(); - } catch (KeyManagementException e) { - e.printStackTrace(); - } catch (KeyStoreException e) { - e.printStackTrace(); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (NoSuchAlgorithmException e) { - e.printStackTrace(); - } catch (CertificateException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); -// } catch (KeyStoreException | NoSuchAlgorithmException| CertificateException | IOException | KeyManagementException e) { -// e.printStackTrace(); - } finally { - try { - instream.close(); - } catch (IOException e) { - } - } - return sc; - } - - /** - * 绕过验证 - * - * @return - * @throws NoSuchAlgorithmException - * @throws KeyManagementException - */ - public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException { - SSLContext sc = SSLContext.getInstance("SSLv3"); - - // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法 - X509TrustManager trustManager = new X509TrustManager() { - @Override - public void checkClientTrusted( - java.security.cert.X509Certificate[] paramArrayOfX509Certificate, - String paramString) throws CertificateException { - } - - @Override - public void checkServerTrusted( - java.security.cert.X509Certificate[] paramArrayOfX509Certificate, - String paramString) throws CertificateException { - } - - @Override - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return null; - } - }; - - sc.init(null, new TrustManager[] { trustManager }, null); - return sc; - } - - /** - * 设置代理 - * @param builder - * @param hostOrIP - * @param port - */ - public static HttpClientBuilder proxy(String hostOrIP, int port){ - // 依次是代理地址,代理端口号,协议类型 - HttpHost proxy = new HttpHost(hostOrIP, port, "http"); - DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); - return HttpClients.custom().setRoutePlanner(routePlanner); - } - - /** - * 模拟请求 - * - * @param url 资源地址 - * @param map 参数列表 - * @param encoding 编码 - * @return - * @throws NoSuchAlgorithmException - * @throws KeyManagementException - * @throws IOException - * @throws ClientProtocolException - */ - public static String send(String url, Map map,String encoding) throws KeyManagementException, NoSuchAlgorithmException, ClientProtocolException, IOException { - String body = ""; - - //绕过证书验证,处理https请求 - SSLContext sslcontext = createIgnoreVerifySSL(); - - // 设置协议http和https对应的处理socket链接工厂的对象 - Registry socketFactoryRegistry = RegistryBuilder.create() - .register("http", PlainConnectionSocketFactory.INSTANCE) - .register("https", new SSLConnectionSocketFactory(sslcontext)) - .build(); - PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); - - //创建自定义的httpclient对象 -// CloseableHttpClient client = proxy("127.0.0.1", 8087).setConnectionManager(connManager).build(); - CloseableHttpClient client = HttpClients.createDefault(); - - //创建post方式请求对象 - HttpPost httpPost = new HttpPost(url); - - //装填参数 - List nvps = new ArrayList(); - if(map!=null){ - for (Entry entry : map.entrySet()) { - nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); - } - } - //设置参数到请求对象中 - httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding)); - - System.out.println("请求地址:"+url); - System.out.println("请求参数:"+nvps.toString()); - - //设置header信息 - //指定报文头【Content-type】、【User-Agent】 - httpPost.setHeader("Content-type", "application/x-www-form-urlencoded"); - httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); - - //执行请求操作,并拿到结果(同步阻塞) - CloseableHttpResponse response = client.execute(httpPost); - //获取结果实体 - HttpEntity entity = response.getEntity(); - if (entity != null) { - //按指定编码转换结果实体为String类型 - body = EntityUtils.toString(entity, encoding); - } - EntityUtils.consume(entity); - //释放链接 - response.close(); - return body; - } - -// public static void main(String[] args) throws ParseException, IOException, KeyManagementException, NoSuchAlgorithmException, HttpProcessException { -// String url = "https://www.facebook.com/"; -// String body = send(url, null, "utf-8"); -// System.out.println("交易响应结果"); -// System.out.println(body); -// } -// - - public static void main(String[] args) throws ParseException, IOException, KeyManagementException, NoSuchAlgorithmException { - String url = "http://php.weather.sina.com.cn/iframe/index/w_cl.php"; - Map map = new HashMap(); - map.put("code", "js"); - map.put("day", "0"); - map.put("city", "上海"); - map.put("dfc", "1"); - map.put("charset", "utf-8"); - String body = send(url, map, "utf-8"); - System.out.println("交易响应结果:"); - System.out.println(body); - System.out.println("-----------------------------------"); - - map.put("city", "北京"); - body = send(url, map, "utf-8"); - System.out.println("交易响应结果:"); - System.out.println(body); - } -} diff --git a/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/TestCookie.java b/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/TestCookie.java deleted file mode 100644 index 321628f023..0000000000 --- a/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/TestCookie.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.jun.plugin.httpclient.httpclientutil.test; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.http.Header; -import org.apache.http.client.CookieStore; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.impl.client.BasicCookieStore; - -import com.jun.plugin.httpclient.httpclientutil.HttpClientUtil; -import com.jun.plugin.httpclient.httpclientutil.common.HttpConfig; -import com.jun.plugin.httpclient.httpclientutil.common.HttpHeader; -import com.jun.plugin.httpclient.httpclientutil.exception.HttpProcessException; - -/** - * 测试携带cookie的操作 - * - * @author arron - * @date 2016年1月7日 上午10:09:53 - * @version 1.0 - */ -public class TestCookie { - - public static void main(String[] args) throws HttpProcessException { - //登录地址 - String loginUrl = "https://passport.csdn.net/account/login"; - //C币查询 - String scoreUrl = "http://my.csdn.net/my/score"; - - //定义cookie存储 - HttpClientContext context = new HttpClientContext(); - CookieStore cookieStore = new BasicCookieStore(); - context.setCookieStore(cookieStore); - HttpConfig config =HttpConfig.custom().url(loginUrl).context(context); - //获取参数 - String loginform = HttpClientUtil.get(config);//可以用.send(config)代替,但是推荐使用明确的get方法 - //System.out.println(loginform); - System.out.println("获取登录所需参数"); - String lt = regex("\"lt\" value=\"([^\"]*)\"", loginform)[0]; - String execution = regex("\"execution\" value=\"([^\"]*)\"", loginform)[0]; - String _eventId = regex("\"_eventId\" value=\"([^\"]*)\"", loginform)[0]; - - //组装参数 - Map map = new HashMap(); - map.put("username", "用户名"); - map.put("password", "密码"); - map.put("lt", lt); - map.put("execution", execution); - map.put("_eventId", _eventId); - - //发送登录请求 - String result = HttpClientUtil.post(config.map(map));//可以用.send(config.method(HttpMethods.POST).map(map))代替,但是推荐使用明确的post方法 - //System.out.println(result); - if(result.contains("帐号登录")){//如果有帐号登录,则说明未登录成功 - String errmsg = regex("\"error-message\">([^<]*)<", result)[0]; - System.err.println("登录失败:"+errmsg); - return; - } - System.out.println("----登录成功----"); - -// //打印参数,可以看到cookie里已经有值了。 -// cookieStore = context.getCookieStore(); -// for (Cookie cookie : cookieStore.getCookies()) { -// System.out.println(cookie.getName()+"--"+cookie.getValue()); -// } - - //访问积分管理页面 - Header[] headers = HttpHeader.custom().userAgent("User-Agent: Mozilla/5.0").build(); - result = HttpClientUtil.post(config.url(scoreUrl).headers(headers));//可以用.send(config.url(scoreUrl).headers(headers))代替,但是推荐使用明确的post方法 - //获取C币 - String score = regex("\"last-img\">([^<]*)<", result)[0]; - System.out.println("您当前有C币:"+score); - - } - - - /** - * 通过正则表达式获取内容 - * - * @param regex 正则表达式 - * @param from 原字符串 - * @return - */ - public static String[] regex(String regex, String from){ - Pattern pattern = Pattern.compile(regex); - Matcher matcher = pattern.matcher(from); - List results = new ArrayList(); - while(matcher.find()){ - for (int i = 0; i < matcher.groupCount(); i++) { - results.add(matcher.group(i+1)); - } - } - return results.toArray(new String[]{}); - } -} diff --git a/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/TestCookieWithHttpCookies.java b/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/TestCookieWithHttpCookies.java deleted file mode 100644 index 05c8351e92..0000000000 --- a/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/TestCookieWithHttpCookies.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.jun.plugin.httpclient.httpclientutil.test; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.http.Header; -import org.apache.http.cookie.Cookie; - -import com.jun.plugin.httpclient.httpclientutil.HttpClientUtil; -import com.jun.plugin.httpclient.httpclientutil.common.HttpConfig; -import com.jun.plugin.httpclient.httpclientutil.common.HttpCookies; -import com.jun.plugin.httpclient.httpclientutil.common.HttpHeader; -import com.jun.plugin.httpclient.httpclientutil.exception.HttpProcessException; - -/** - * 测试携带cookie的操作(使用HttpCookies) - * - * @author arron - * @date 2016年1月12日 下午2:15:17 - * @version 1.0 - */ -public class TestCookieWithHttpCookies { - - public static void main(String[] args) throws HttpProcessException { - //登录地址 - String loginUrl = "https://passport.csdn.net/account/login"; - //C币查询 - String scoreUrl = "http://my.csdn.net/my/score"; - - HttpCookies cookies = HttpCookies.custom(); - HttpConfig config =HttpConfig.custom().url(loginUrl).context(cookies.getContext()); - //获取参数 - String loginform = HttpClientUtil.get(config);//可以用.send(config)代替,但是推荐使用明确的get方法 - //System.out.println(loginform); - -// //打印参数,可以看到cookie里已经有值了。 -// for (Cookie cookie : cookies.getCookieStore().getCookies()) { -// System.out.println(cookie.getName()+"--"+cookie.getValue()); -// } - - System.out.println("获取登录所需参数"); - String lt = regex("\"lt\" value=\"([^\"]*)\"", loginform)[0]; - String execution = regex("\"execution\" value=\"([^\"]*)\"", loginform)[0]; - String _eventId = regex("\"_eventId\" value=\"([^\"]*)\"", loginform)[0]; - - //组装参数 - Map map = new HashMap(); - map.put("username", "用户名"); - map.put("password", "密码"); - map.put("lt", lt); - map.put("execution", execution); - map.put("_eventId", _eventId); - - //发送登录请求 - String result = HttpClientUtil.post(config.map(map));//可以用.send(config.method(HttpMethods.POST).map(map))代替,但是推荐使用明确的post方法 - //System.out.println(result); - if(result.contains("帐号登录")){//如果有帐号登录,则说明未登录成功 - String errmsg = regex("\"error-message\">([^<]*)<", result)[0]; - System.err.println("登录失败:"+errmsg); - return; - } - System.out.println("----登录成功----"); - -// //打印参数,可以看到cookie里已经有值了。 - for (Cookie cookie : cookies.getCookieStore().getCookies()) { - System.out.println(cookie.getName()+"--"+cookie.getValue()); - } - - //访问积分管理页面 - Header[] headers = HttpHeader.custom().userAgent("User-Agent: Mozilla/5.0").build(); - result = HttpClientUtil.post(config.url(scoreUrl).headers(headers));//可以用.send(config.url(scoreUrl).headers(headers))代替,但是推荐使用明确的post方法 - //获取C币 - String score = regex("\"last-img\">([^<]*)<", result)[0]; - System.out.println("您当前有C币:"+score); - - } - - - /** - * 通过正则表达式获取内容 - * - * @param regex 正则表达式 - * @param from 原字符串 - * @return - */ - public static String[] regex(String regex, String from){ - Pattern pattern = Pattern.compile(regex); - Matcher matcher = pattern.matcher(from); - List results = new ArrayList(); - while(matcher.find()){ - for (int i = 0; i < matcher.groupCount(); i++) { - results.add(matcher.group(i+1)); - } - } - return results.toArray(new String[]{}); - } -} diff --git a/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/TestDownLoadImg.java b/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/TestDownLoadImg.java deleted file mode 100644 index 1bee1c2628..0000000000 --- a/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/TestDownLoadImg.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.jun.plugin.httpclient.httpclientutil.test; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; - -import com.jun.plugin.httpclient.httpclientutil.HttpClientUtil; -import com.jun.plugin.httpclient.httpclientutil.common.HttpConfig; -import com.jun.plugin.httpclient.httpclientutil.exception.HttpProcessException; - -/** - * 下载demo - * - * @author arron - * @date 2016年6月7日 上午10:29:30 - * @version 1.0 - */ -public class TestDownLoadImg { - - public static void main(String[] args) throws FileNotFoundException, HttpProcessException{ - String imgUrl = "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/logo_white_fe6da1ec.png"; //百度logo - File file = new File("c:/baidu.png"); - HttpClientUtil.down(HttpConfig.custom().url(imgUrl).out(new FileOutputStream(file))); - if (file.exists()) { - System.out.println("图片下载成功了!存放在:" + file.getPath()); - } - - String mp3Url="http://win.web.rh01.sycdn.kuwo.cn/resource/n1/24/6/707126989.mp3"; //四叶草-好想你 - file = new File("c:/好想你.mp3"); - HttpClientUtil.down(HttpConfig.custom().url(mp3Url).out(new FileOutputStream(file))); - if (file.exists()) { - System.out.println("mp3下载成功了!存放在:" + file.getPath()); - } - } -} diff --git a/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/TestHttpPool.java b/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/TestHttpPool.java deleted file mode 100644 index 4c3a0c53bf..0000000000 --- a/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/TestHttpPool.java +++ /dev/null @@ -1,199 +0,0 @@ -package com.jun.plugin.httpclient.httpclientutil.test; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import org.apache.http.Header; -import org.apache.http.client.HttpClient; - -import com.jun.plugin.httpclient.httpclientutil.HttpClientUtil; -import com.jun.plugin.httpclient.httpclientutil.builder.HCB; -import com.jun.plugin.httpclient.httpclientutil.common.HttpConfig; -import com.jun.plugin.httpclient.httpclientutil.common.HttpHeader; -import com.jun.plugin.httpclient.httpclientutil.exception.HttpProcessException; - -/** - * 测试启用http连接池 - * - * @author arron - * @date 2016年11月7日 下午1:08:07 - * @version 1.0 - */ -public class TestHttpPool { - - // 设置header信息 - private static final Header[] headers = HttpHeader.custom().userAgent("Mozilla/5.0").from("http://blog.csdn.net/newest.html").build(); - - // URL列表数组,GET请求 - private static final String[] urls = { - "http://blog.csdn.net/xiaoxian8023/article/details/49883113", - "http://blog.csdn.net/xiaoxian8023/article/details/49909359", - "http://blog.csdn.net/xiaoxian8023/article/details/49910127", - "http://www.baidu.com/", - "http://126.com", - }; - - // 图片URL列表数组,Down操作 - private static final String[] imgurls ={ - "http://ss.bdimg.com/static/superman/img/logo/logo_white_fe6da1ec.png", - "https://images.gitbook.cn/Fi7WlXOsPSUP17_WDlo7Nv7cjOx5" - }; - - private static String filePath = "d://aaa//"; - - private static StringBuffer buf=new StringBuffer(); - - //多线程get请求 - public static void testMultiGet(HttpConfig cfg, int count) throws HttpProcessException{ - try { - int pagecount = urls.length; - ExecutorService executors = Executors.newFixedThreadPool(pagecount); - CountDownLatch countDownLatch = new CountDownLatch(count); - //启动线程抓取 - for(int i = 0; i< count;i++){ - executors.execute(new GetRunnable(countDownLatch,cfg, urls[i%pagecount])); - } - countDownLatch.await(); - executors.shutdown(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - //多线程下载 - public static void testMultiDown(HttpConfig cfg, int count) throws HttpProcessException{ - try { - int pagecount = imgurls.length; - ExecutorService executors = Executors.newFixedThreadPool(pagecount); - CountDownLatch countDownLatch = new CountDownLatch(count); - //启动线程抓取 - for(int i = 0; i< count;i++){ - executors.execute(new GetRunnable(countDownLatch, cfg, imgurls[i%2], new FileOutputStream(new File(filePath+(i+1)+".png")))); - } - countDownLatch.await(); - executors.shutdown(); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - static class GetRunnable implements Runnable { - private CountDownLatch countDownLatch; - private HttpConfig config = null; - private FileOutputStream out = null; - private String url = null; - - public GetRunnable(CountDownLatch countDownLatch,HttpConfig config, String url){ - this(countDownLatch, config, url, null); - } - public GetRunnable(CountDownLatch countDownLatch,HttpConfig config, String url, FileOutputStream out){ - this.countDownLatch = countDownLatch; - this.config = config; - this.out = out; - this.url = url; - } - - @Override - public void run() { - try { - config.out(out); - config.url(url); - if(config.out()==null){ - String response = null; - response = HttpClientUtil.get(config); - System.out.println(config.url()); - System.out.println(Thread.currentThread().getName()+"--获取内容长度:"+response.length()); - response = null; - - }else{ - HttpClientUtil.down(config); - try { - config.out().flush(); - config.out().close(); - } catch (IOException e) { - e.printStackTrace(); - } - System.out.println(Thread.currentThread().getName()+"--下载完毕"); - } - } catch (HttpProcessException e) { - e.printStackTrace(); - } finally { - countDownLatch.countDown(); - } - } - } - - /** - * 测试启用http连接池,get100次,down20次的执行时间 - * @throws HttpProcessException - */ - private static void testByPool(int getCount, int downCount) throws HttpProcessException { - long start = System.currentTimeMillis(); - - HCB hcb= HCB.custom().pool(100, 10).ssl(); - if(getCount>0){ - HttpConfig cfg3 = HttpConfig.custom().client(hcb.build()).headers(headers);//使用一个client对象 - testMultiGet(cfg3, getCount); - } - if(downCount>0){ - HttpConfig cfg4 = HttpConfig.custom().client(hcb.build()).timeout(10000); - File file = new File(filePath); - if(!file.exists()){ - file.mkdirs(); - } - testMultiDown(cfg4, downCount); - } - - System.out.println("-----所有线程已完成!------"); - long end = System.currentTimeMillis(); - System.out.println("总耗时(毫秒): -> " + (end - start)); - buf.append("\t").append((end-start)); - } - - /** - * 快速测试pool的应用(通过运行httpConn.bat监控http连接数,查看是否启用连接池) - * - * @throws HttpProcessException - */ - public static void testquickConcurrent() throws HttpProcessException{ - //--------------------------- - //--- 期望结果: - // 由于urls中有3个域名,所以会为每个域名最多建立20个http链接, - // 通过上面的监控,应该会看到http连接数会增加3-20=60个左右 - //--------------------------- - - HttpClient client= HCB.custom().pool(100, 20).timeout(10000).build();//最多创建20个http链接 - final HttpConfig cfg = HttpConfig.custom().client(client).headers(headers);//为每次请求创建一个实例化对象 - for (int i = 0; i < 100; i++) { - new Thread(new Runnable() { - @Override - public void run() { - try { - int idx = ((int) (Math.random() * 10)) % 5; - HttpClientUtil.get(cfg.url(urls[idx])); - System.out.println("---idx="+idx); - } catch (HttpProcessException e) { - } - } - }).start(); - } - } - - public static void main(String[] args) throws Exception { - //以下测试通过使用线程池和未启用线程池2个方式测试http连接池 - //通过监控http链接查看连接池是否有效,脚本文件是httpConn.bat - - //未启用线程池,直接启用100个线程,通过监控http连接数,查看连接池是否跟配置的一致 - testquickConcurrent(); - - //启用连接池,访问500次(线程数=urls的元素个数),测试连接池 - testByPool(500, 100); - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/TestHttpResult.java b/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/TestHttpResult.java deleted file mode 100644 index f18b8ec513..0000000000 --- a/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/TestHttpResult.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.jun.plugin.httpclient.httpclientutil.test; - -import org.apache.http.client.config.RequestConfig; - -import com.jun.plugin.httpclient.httpclientutil.HttpClientUtil; -import com.jun.plugin.httpclient.httpclientutil.common.HttpConfig; -import com.jun.plugin.httpclient.httpclientutil.common.HttpHeader; -import com.jun.plugin.httpclient.httpclientutil.common.HttpResult; -import com.jun.plugin.httpclient.httpclientutil.exception.HttpProcessException; - -public class TestHttpResult { - - public static void main(String[] args) throws HttpProcessException { - - final String url = "http://jd.com/?"+Math.random(); -// final String url2 = "https://www.facebook.com/?"+Math.random(); - // 配置请求的超时设置 - int timeout=1000*7; - RequestConfig requestConfig = RequestConfig.custom() - .setConnectionRequestTimeout(timeout) - .setConnectTimeout(timeout) - .setSocketTimeout(timeout) - .build(); - final HttpConfig config = HttpConfig.custom().headers(HttpHeader.custom().build(), true); - config.timeout(requestConfig); -// new Thread(new Runnable() { -// @Override -// public void run() { -// long t1 = System.currentTimeMillis(); -// try { -// HttpClientUtil.get(config.url(url)); -// long t2 = System.currentTimeMillis(); -// System.err.println("2耗费:"+(t2-t1)); -// HttpClientUtil.get(config.url(url2)); -// long t3 = System.currentTimeMillis(); -// System.err.println("3耗费:"+(t3-t1)); -// } catch (HttpProcessException e) { -//// e.printStackTrace(); -// System.err.println(e.getMessage()); -// } finally { -// System.err.println("===finally==="); -// } -// } -// }).start(); -// new Thread(new Runnable() { -// @Override -// public void run() { -// long t1 = System.currentTimeMillis(); -// try { -// HttpClientUtil.get(config.url(url)); -// long t2 = System.currentTimeMillis(); -// System.err.println("2耗费:"+(t2-t1)); -// HttpClientUtil.get(config.url(url2)); -// long t3 = System.currentTimeMillis(); -// System.err.println("3耗费:"+(t3-t1)); -// } catch (HttpProcessException e) { -//// e.printStackTrace(); -// System.err.println(e.getMessage()); -// } finally { -// System.err.println("===finally==="); -// } -// } -// }).start(); -// String result = HttpClientUtil.get(config); -// System.out.println(result); -// for (Header header : config.headers()) { -// System.out.println(header); -// } - - //测试HttpResult返回方式 - - long t1 = System.currentTimeMillis(); - - HttpResult result = HttpClientUtil.sendAndGetResp(config.url(url)); - - long t2 = System.currentTimeMillis(); - System.out.println("返回结果(内容太长,仅打印字节数):"+result.getResult().length()); - System.out.println("状态码:"+result.getStatusCode()); - System.out.println("使用协议:"+result.getProtocolVersion()); - System.out.println("----------"); - System.out.println("耗时:"+(t2-t1)); - } - -} diff --git a/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/TestUpload.java b/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/TestUpload.java deleted file mode 100644 index f26845b424..0000000000 --- a/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/TestUpload.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.jun.plugin.httpclient.httpclientutil.test; - -import java.util.HashMap; -import java.util.Map; - -import com.jun.plugin.httpclient.httpclientutil.HttpClientUtil; -import com.jun.plugin.httpclient.httpclientutil.common.HttpConfig; -import com.jun.plugin.httpclient.httpclientutil.common.HttpCookies; -import com.jun.plugin.httpclient.httpclientutil.common.Utils; -import com.jun.plugin.httpclient.httpclientutil.exception.HttpProcessException; - -/** - * 上传功能测试 - * - * @author arron - * @date 2016年11月2日 下午1:17:17 - * @version 1.0 - */ -public class TestUpload { - - public static void main(String[] args) throws HttpProcessException { - //登录后,为上传做准备 - HttpConfig config = prepareUpload(); - - String url= "http://test.free.800m.net:8080/up.php?action=upsave";//上传地址 -// String[] filePaths = {"D:\\中国.txt","D:\\111.txt","C:\\Users\\160049\\Desktop\\中国.png"};//待上传的文件路径 - String[] filePaths = {"D:\\中国支付清算系统总体架构图-无文字版.png"};//待上传的文件路径 - - Map map = new HashMap(); - map.put("path", "./tomcat/vhost/test/ROOT/");//指定其他参数 - config.url(url) //设定上传地址 - .encoding("GB2312") //设定编码,否则可能会引起中文乱码或导致上传失败 - .files(filePaths,"myfile",true)//.files(filePaths),如果服务器端有验证input 的name值,则请传递第二个参数,如果上传失败,则尝试第三个参数设置为true - .map(map);//其他需要提交的参数 - - Utils.debug();//开启打印日志,调用 Utils.debug(false);关闭打印日志 - String r = HttpClientUtil.upload(config);//上传 - System.out.println(r); - - } - - /** - * 登录,并上传文件 - * - * @return - * @throws HttpProcessException - */ - private static HttpConfig prepareUpload() throws HttpProcessException { - String url ="http://test.free.800m.net:8080/"; - String loginUrl = url+"login.php"; - String indexUrl = url+"index.php"; - HttpCookies cookies = HttpCookies.custom(); - //启用cookie,用于登录后的操作 - HttpConfig config = HttpConfig.custom().context(cookies.getContext()); - Map map = new HashMap(); - map.put("user_name", "test"); - map.put("user_pass", "800m.net"); - map.put("action", "login"); - String loginResult = HttpClientUtil.post(config.url(loginUrl).map(map)); - - System.out.println("是否登录成功:"+loginResult.contains("成功")); - //打开主页 - HttpClientUtil.get(config.map(null).url(indexUrl)); - - return config; - } - -} diff --git a/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/TestVerifyCode.java b/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/TestVerifyCode.java deleted file mode 100644 index dc95a9a07e..0000000000 --- a/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/TestVerifyCode.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.jun.plugin.httpclient.httpclientutil.test; - -import org.apache.http.Header; - -import com.jun.plugin.httpclient.httpclientutil.HttpClientUtil; -import com.jun.plugin.httpclient.httpclientutil.common.HttpConfig; -import com.jun.plugin.httpclient.httpclientutil.common.HttpCookies; -import com.jun.plugin.httpclient.httpclientutil.common.HttpHeader; -import com.jun.plugin.httpclient.httpclientutil.common.util.OCR; -import com.jun.plugin.httpclient.httpclientutil.exception.HttpProcessException; - -/** - * 识别验证码demo - * - * @author arron - * @date 2016年6月7日 上午10:51:51 - * @version 1.0 - */ -public class TestVerifyCode { - - public static void main(String[] args) throws InterruptedException, HttpProcessException { - String qq = "123456789";//qq号 - String imgUrl = "http://qqxoo.com/include/vdimgvt.php?t="+Math.random(); //获取验证码图片地址 - String verifyUrl = "http://qqxoo.com/include/vdcheck.php"; - String saveCodePath = "C:/1.png";//保存验证码图片路径 - - Header[] headers = HttpHeader.custom().referer("http://qqxoo.com/main.html?qqid="+qq).build();//设置referer,是为了获取对应qq号的验证码,否则报错 - HttpConfig config = HttpConfig.custom().headers(headers).context(HttpCookies.custom().getContext());//必须设置context,是为了携带cookie进行操作 - - String result =null;//识别结果 - - do { - if(result!=null){ - System.err.println("校验失败!稍等片刻后继续识别"); - Thread.sleep((int)(Math.random()*10)*100); - } - - //获取验证码 - //OCR.debug(); //开始Fiddler4抓包(127.0.0.1:8888) - String code = OCR.ocrCode4Net(config.url(imgUrl), saveCodePath); - - while(code.length()!=5){//如果识别的验证码位数不等于5,则重新识别 - if(code.contains("亲,apiKey已经过期或错误,请重新获取")){ - System.err.println(code); - return; - } - code = OCR.ocrCode4Net(config.url(imgUrl), saveCodePath); - } - - System.out.println("本地识别的验证码为:"+code); - System.out.println("验证码已保存到:"+saveCodePath); - - System.out.println("开始校验验证码是否正确"); - //开始验证识别的验证码是否正确 - result = HttpClientUtil.get(config.url(verifyUrl+"?vc="+code+"&qqid="+qq)); - - } while (!result.contains("succeed")); - - System.out.println("识别验证码成功!反馈信息如下:\n" + result); - } -} diff --git a/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/httpConn.bat b/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/httpConn.bat deleted file mode 100644 index 0c3ee60732..0000000000 --- a/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/httpclientutil/test/httpConn.bat +++ /dev/null @@ -1,5 +0,0 @@ -@echo off -:count -echo|set /p="Num of HTTP Connections(port:80): " & netstat -na |findstr "ESTABLISHED" | find /C ":80" -timeout 2 > nul -GOTO count \ No newline at end of file diff --git a/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/test/HttpClientTest.java b/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/test/HttpClientTest.java deleted file mode 100644 index 147c5f90e5..0000000000 --- a/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/httpclient/test/HttpClientTest.java +++ /dev/null @@ -1,265 +0,0 @@ -package com.jun.plugin.httpclient.test; - - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.security.KeyManagementException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; -import java.util.ArrayList; -import java.util.List; - -import javax.net.ssl.SSLContext; - -import org.apache.http.HttpEntity; -import org.apache.http.ParseException; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.conn.ssl.SSLContexts; -import org.apache.http.conn.ssl.TrustSelfSignedStrategy; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.mime.MultipartEntityBuilder; -import org.apache.http.entity.mime.content.FileBody; -import org.apache.http.entity.mime.content.StringBody; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.util.EntityUtils; -import org.junit.Test; - -public class HttpClientTest { - - @Test - public void jUnitTest() { - get(); - } - - /** - * HttpClient SSL - */ - @SuppressWarnings("deprecation") -public void ssl() { - CloseableHttpClient httpclient = null; - try { - KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); - FileInputStream instream = new FileInputStream(new File("d:\\tomcat.keystore")); - try { - //keyStore d:\\tomcat.keystore - trustStore.load(instream, "123456".toCharArray()); - } catch (CertificateException e) { - e.printStackTrace(); - } finally { - try { - instream.close(); - } catch (Exception ignore) { - } - } - SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build(); - SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, - SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); - httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); - // ����http����(get��ʽ) - HttpGet httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action"); - System.out.println("executing request" + httpget.getRequestLine()); - CloseableHttpResponse response = httpclient.execute(httpget); - try { - HttpEntity entity = response.getEntity(); - System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); - if (entity != null) { - System.out.println("Response content length: " + entity.getContentLength()); - System.out.println(EntityUtils.toString(entity)); - EntityUtils.consume(entity); - } - } finally { - response.close(); - } - } catch (ParseException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } catch (KeyManagementException e) { - e.printStackTrace(); - } catch (NoSuchAlgorithmException e) { - e.printStackTrace(); - } catch (KeyStoreException e) { - e.printStackTrace(); - } finally { - if (httpclient != null) { - try { - httpclient.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - } - - /** - *HttpClient post - */ - @SuppressWarnings({ "unchecked", "rawtypes" }) -public void postForm() { - CloseableHttpClient httpclient = HttpClients.createDefault(); - HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action"); - List formparams = new ArrayList(); - formparams.add(new BasicNameValuePair("username", "admin")); - formparams.add(new BasicNameValuePair("password", "123456")); - UrlEncodedFormEntity uefEntity; - try { - uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8"); - httppost.setEntity(uefEntity); - System.out.println("executing request " + httppost.getURI()); - CloseableHttpResponse response = httpclient.execute(httppost); - try { - HttpEntity entity = response.getEntity(); - if (entity != null) { - System.out.println("--------------------------------------"); - System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8")); - System.out.println("--------------------------------------"); - } - } finally { - response.close(); - } - } catch (ClientProtocolException e) { - e.printStackTrace(); - } catch (UnsupportedEncodingException e1) { - e1.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } finally { - // �ر�����,�ͷ���Դ - try { - httpclient.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - /** - *HttpClient post - */ - public void post() { - CloseableHttpClient httpclient = HttpClients.createDefault(); - HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action"); - List formparams = new ArrayList(); - formparams.add(new BasicNameValuePair("type", "house")); - UrlEncodedFormEntity uefEntity; - try { - uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8"); - httppost.setEntity(uefEntity); - System.out.println("executing request " + httppost.getURI()); - CloseableHttpResponse response = httpclient.execute(httppost); - try { - HttpEntity entity = response.getEntity(); - if (entity != null) { - System.out.println("--------------------------------------"); - System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8")); - System.out.println("--------------------------------------"); - } - } finally { - response.close(); - } - } catch (ClientProtocolException e) { - e.printStackTrace(); - } catch (UnsupportedEncodingException e1) { - e1.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } finally { - // �ر�����,�ͷ���Դ - try { - httpclient.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - /** - * HttpClient get - */ - public void get() { - CloseableHttpClient httpclient = HttpClients.createDefault(); - try { - HttpGet httpget = new HttpGet("http://www.baidu.com/"); - System.out.println("executing request " + httpget.getURI()); - CloseableHttpResponse response = httpclient.execute(httpget); - try { - HttpEntity entity = response.getEntity(); - System.out.println("--------------------------------------"); - System.out.println(response.getStatusLine()); - if (entity != null) { - System.out.println("Response content length: " + entity.getContentLength()); - System.out.println("Response content: " + EntityUtils.toString(entity)); - } - System.out.println("------------------------------------"); - } finally { - response.close(); - } - } catch (ClientProtocolException e) { - e.printStackTrace(); - } catch (ParseException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } finally { - // �ر�����,�ͷ���Դ - try { - httpclient.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - /** - *HttpClient upload - */ - public void upload() { - CloseableHttpClient httpclient = HttpClients.createDefault(); - try { - HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action"); - - FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg")); - StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN); - - HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build(); - - httppost.setEntity(reqEntity); - - System.out.println("executing request " + httppost.getRequestLine()); - CloseableHttpResponse response = httpclient.execute(httppost); - try { - System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); - HttpEntity resEntity = response.getEntity(); - if (resEntity != null) { - System.out.println("Response content length: " + resEntity.getContentLength()); - } - EntityUtils.consume(resEntity); - } finally { - response.close(); - } - } catch (ClientProtocolException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } finally { - try { - httpclient.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/okhttp/test/URLUtil.java b/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/okhttp/test/URLUtil.java deleted file mode 100644 index d855be334c..0000000000 --- a/jun_java_plugins/jun_httpclient/src/test/java/com/jun/plugin/okhttp/test/URLUtil.java +++ /dev/null @@ -1,103 +0,0 @@ -// This file is commented out — OkHttp wrapper moved to jun_okhttp module. -/* -package com.jun.plugin.okhttp.test; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.util.Map; - -import javax.net.ssl.SSLContext; - -import com.jun.plugin.okhttp.FastHttpClient; -import com.jun.plugin.okhttp.Response; - - -/** - * - * @author Wujun - * - * / -public class URLUtil { - // - public static String httpGet(String url) throws Exception { - Response response = FastHttpClient.get(). - url(url). - build(). - execute(); - return response.body().string(); - } - // - public static String httpsGet(String url) throws Exception { - Response response = FastHttpClient.get(). - url(url). - build(). - execute(); - return response.body().string(); - } - // - public static String httpsGet(String url,SSLContext sslContext) throws Exception { - Response response = FastHttpClient.get(). - url(url). - build(). - sslContext(sslContext). - execute(); - return response.body().string(); - } - // - public static String httpPost(String url,Map paramMap) throws MalformedURLException, IOException{ - Response response = FastHttpClient.post(). - url(url). - addParams(paramMap). - build(). - execute(); - return response.body().string(); - } - // - public static String httpPostWithBody(String url,String body) throws MalformedURLException, IOException{ - Response response = FastHttpClient.post(). - url(url). - body(body). - build(). - execute(); - return response.body().string(); - } - // - public static String httpsPost(String url) throws MalformedURLException, IOException{ - return httpsPost(url, null, null); - } - // - public static String httpsPost(String url,Map paramMap) throws MalformedURLException, IOException{ - return httpsPost(url, paramMap, null); - } - // - public static String httpsPost(String url,Map paramMap,SSLContext sslContext) throws MalformedURLException, IOException{ - Response response = FastHttpClient.post(). - url(url). - addParams(paramMap). - build(). - sslContext(sslContext). - execute(); - return response.body().string(); - } - // - public static String httpsPostWithBody(String url,String body) throws MalformedURLException, IOException{ - return httpsPostWithBody(url, body, null); - } - // - public static String httpsPostWithBody(String url,String body,SSLContext sslContext) throws MalformedURLException, IOException{ - Response response = FastHttpClient.post(). - url(url). - body(body). - build(). - sslContext(sslContext). - execute(); - return response.body().string(); - } - // - public static void main(String[] args) throws Exception { - System.out.println(URLUtil.httpGet("http://sz.bendibao.com/news/2016923/781534.htm")); - System.out.println(URLUtil.httpsGet("https://kyfw.12306.cn/otn/")); - System.out.println(URLUtil.httpsPost("https://skydu.cn")); - } -} -*/ diff --git a/jun_java_plugins/jun_j2cache/README.md b/jun_java_plugins/jun_j2cache/README.md deleted file mode 100644 index 2eb688f7fc..0000000000 --- a/jun_java_plugins/jun_j2cache/README.md +++ /dev/null @@ -1,22 +0,0 @@ -#oschina-j2cache -## 说明 -目前一级缓存用的是ehcache,二级使用redis;集群同步工具使用jgroups或redis pub sub; -## 计划 -下一步会改为模块化工程,使用时按需加载; -包括 : -

    -
  • 一二级缓存自定义
  • -
  • 序列化工具自定义
  • -
- -## 使用说明 -在src/test/resources目录下有个spring-cache-test.xml文件,演示了在spring项目中如何使用oschina-j2cache;对于可以使用的配置项也有相应的文本注释 -
-* 属性说明:
-* useCluster                - 是否为集群,默认true
-* cacheBroadcast            - 集群模式下个节点数据同步的机制,可选择为:REDIS_PUBSUB/JGROUPS_MULTICAST
-* openSecondCache           - 是否启用二级缓存,默认false
-* cache_jgroup_conf_file    - 使用jgroups实现ehcache集群
-* cache_ehcache_conf_file   - 一级缓存ehcache配置文件
-* cache_redis_conf_file     - 二级缓存redis配置文件
-
\ No newline at end of file diff --git a/jun_java_plugins/jun_j2cache/pom.xml b/jun_java_plugins/jun_j2cache/pom.xml deleted file mode 100644 index 02368c965c..0000000000 --- a/jun_java_plugins/jun_j2cache/pom.xml +++ /dev/null @@ -1,164 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_j2cache - 1.0 - jar - - - UTF-8 - 1.8 - - 4.11 - - 4.2.3.RELEASE - 2.8.0 - 2.10.0 - 3.6.1.Final - 2.4 - 2.43 - 1.1.2 - - 1.1.2 - 1.7.7 - - - - - - - de.ruedigermoeller - fst - ${fst.version} - - - org.xerial.snappy - snappy-java - ${snappy-java.version} - - - org.jgroups - jgroups - ${jgroups.version} - - - - redis.clients - jedis - ${jedis.verion} - - - net.sf.ehcache - ehcache - ${ehcache.version} - - - - org.springframework - spring-beans - ${spring.version} - - - - commons-io - commons-io - ${commons-io.version} - - - - - org.slf4j - slf4j-api - ${slf4j-api.version} - - - ch.qos.logback - logback-classic - ${logback.version} - - - - org.slf4j - log4j-over-slf4j - ${slf4j-api.version} - runtime - - - - org.slf4j - jcl-over-slf4j - ${slf4j-api.version} - runtime - - - - org.slf4j - jul-to-slf4j - ${slf4j-api.version} - runtime - - - - - - junit - junit - ${junit.version} - test - - - org.springframework - spring-context - ${spring.version} - test - - - org.springframework - spring-test - ${spring.version} - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - true - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.1 - - ${java.version} - ${java.version} - true - - - - org.apache.maven.plugins - maven-install-plugin - 2.4 - - - org.apache.maven.plugins - maven-jar-plugin - 2.4 - - - - true - - - - - - - - \ No newline at end of file diff --git "a/jun_java_plugins/jun_j2cache/spring boot \344\275\277\347\224\250spring cache \346\225\264\345\220\210\345\244\232\347\272\247\347\274\223\345\255\230(EhCache,Redis).md" "b/jun_java_plugins/jun_j2cache/spring boot \344\275\277\347\224\250spring cache \346\225\264\345\220\210\345\244\232\347\272\247\347\274\223\345\255\230(EhCache,Redis).md" deleted file mode 100644 index b213b58c76..0000000000 --- "a/jun_java_plugins/jun_j2cache/spring boot \344\275\277\347\224\250spring cache \346\225\264\345\220\210\345\244\232\347\272\247\347\274\223\345\255\230(EhCache,Redis).md" +++ /dev/null @@ -1,549 +0,0 @@ -spring boot 使用spring cache 整合多级缓存(EhCache,Redis) - - -spring boot spring cache实现多级缓存, 只是按照自己的思想实现,若有读者有更好的解决思路,欢迎指点 -spring cache实现多级缓存的思路如下: -添加自定义的CacheManager,自定义的Cache,在Cache里实现多级缓存的操作(增删查) -配置类如下注意红色标记的部分: - -package com.zyc.zspringboot.config; - -import com.zyc.zspringboot.cache.MyCacheManager; -import com.zyc.zspringboot.cache.MyCacheTemplate; -import com.zyc.zspringboot.cache.MyRedisCache; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.cache.CacheManager; -import org.springframework.cache.annotation.EnableCaching; -import org.springframework.cache.ehcache.EhCacheCacheManager; -import org.springframework.cache.ehcache.EhCacheManagerFactoryBean; -import org.springframework.context.annotation.AdviceMode; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Primary; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; -import org.springframework.data.redis.cache.RedisCacheManager; -import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer; -import org.springframework.data.redis.serializer.RedisSerializer; -import org.springframework.data.redis.serializer.StringRedisSerializer; -import redis.clients.jedis.JedisPoolConfig; -import java.util.ArrayList; -import java.util.List; - -/** - * ClassName: RedisConfig - * - * @author zyc-admin - * @date 2018年1月23日 - * @Description: - */ -@Configuration -@EnableCaching(mode = AdviceMode.PROXY) -// model属性默认proxy -// mode属性,可以选择值proxy和aspectj。默认使用proxy。当mode为proxy时, -// 只有缓存方法在外部被调用的时候才会生效。这也就意味着如果一个缓存方法在一个对 -// 象的内部被调用SpringCache是不会发生作用的。而mode为aspectj时,就不会有 -// 这种问题了。另外使用proxy的时候,只有public方法上的@Cacheable才会发生作用。 -// 如果想非public上的方法也可以使用那么就把mode改成aspectj。 -@ConfigurationProperties(prefix = "spring.redis") -// 使用@ConfigurationProperties 需要实现属性的getter setter方法, -// 1.5之前版本需要在启动类上使用@EnableConfigurationProperties进行激活,1.5之后直接在配置类上使用@Component, -// 由于本类使用@Configuration注解包含了@Component就不用在声明@Component, -// 这样就可以直接在其他类中使用@Autowired直接把此类注入进来 -// extends CachingConfigurerSupport -public class RedisConfig { - - private String hostName; - - private int port; - - private int timeOut; - - private int maxIdle;// 最大空闲连接数, 默认8个 - - private int maxWaitMillis;// 获取连接时的最大等待毫秒数 - - private boolean testOnBorrow;// 在获取连接的时候检查有效性, 默认false - - private boolean testWhileIdle;// 空闲是否检查是否有效,默认为false - - public String getHostName() { - return hostName; - } - - public void setHostName(String hostName) { - this.hostName = hostName; - } - - public int getPort() { - return port; - } - - public void setPort(int port) { - this.port = port; - } - - public int getTimeOut() { - return timeOut; - } - - public void setTimeOut(int timeOut) { - this.timeOut = timeOut; - } - - public int getMaxIdle() { - return maxIdle; - } - - public void setMaxIdle(int maxIdle) { - this.maxIdle = maxIdle; - } - - public int getMaxWaitMillis() { - return maxWaitMillis; - } - - public void setMaxWaitMillis(int maxWaitMillis) { - this.maxWaitMillis = maxWaitMillis; - } - - public boolean isTestOnBorrow() { - return testOnBorrow; - } - - public void setTestOnBorrow(boolean testOnBorrow) { - this.testOnBorrow = testOnBorrow; - } - - public boolean isTestWhileIdle() { - return testWhileIdle; - } - - public void setTestWhileIdle(boolean testWhileIdle) { - this.testWhileIdle = testWhileIdle; - } - - - @Bean("jedisPoolConfig") - public JedisPoolConfig jedisPoolConfig() { - JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); - jedisPoolConfig.setMaxIdle(maxIdle); - jedisPoolConfig.setMaxWaitMillis(maxWaitMillis); - jedisPoolConfig.setTestOnBorrow(true); - jedisPoolConfig.setTestWhileIdle(false); - return jedisPoolConfig; - } - - @Bean - public JedisConnectionFactory redisConnectionFactory( - JedisPoolConfig jedisPoolConfig) { - // 如果集群使用new JedisConnectionFactory(new - // RedisClusterConfiguration()),集群配置在RedisClusterConfiguration,这里省略具体配置 - JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory(); - redisConnectionFactory.setPoolConfig(jedisPoolConfig); - - redisConnectionFactory.setHostName(hostName); - redisConnectionFactory.setPort(port); - redisConnectionFactory.setTimeout(timeOut); - return redisConnectionFactory; - } - - /** - * RedisTemplate配置 - * - * @param redisConnectionFactory - * @return RedisTemplate - */ - @Bean - public RedisTemplate redisTemplate( - JedisConnectionFactory redisConnectionFactory) { - RedisTemplate redisTemplate = new RedisTemplate<>(); - redisTemplate.setConnectionFactory(redisConnectionFactory); - RedisSerializer redisSerializer = new StringRedisSerializer(); - redisTemplate.setKeySerializer(redisSerializer); - // Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new - // Jackson2JsonRedisSerializer( - // Object.class); - // ObjectMapper om = new ObjectMapper(); - // om.setVisibility(PropertyAccessor.ALL, - // JsonAutoDetect.Visibility.ANY); - // om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); - // jackson2JsonRedisSerializer.setObjectMapper(om); - // redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); - JdkSerializationRedisSerializer jdkSerializationRedisSerializer = new JdkSerializationRedisSerializer(); - redisTemplate.setValueSerializer(jdkSerializationRedisSerializer); - return redisTemplate; - } - - /** - * redis缓存管理器 - * @param redisTemplate - * @return - */ - @Bean - public RedisCacheManager redisCacheManager(RedisTemplate redisTemplate) { - RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate); - // Number of seconds before expiration. Defaults to unlimited (0) - cacheManager.setDefaultExpiration(120); //设置key-value超时时间 - List cacheNames = new ArrayList<>(); - cacheNames.add("myRedis"); - cacheNames.add("j2CacheRedis"); - cacheManager.setCacheNames(cacheNames); - return cacheManager; - } - - /** - * spring cache整合(EhCache,Redis)二级缓存具体Cache - * @param redisCacheManager - * @param redisTemplate - * @return - */ - @Bean - public MyCacheTemplate myCacheTemplate(RedisCacheManager redisCacheManager,RedisTemplate redisTemplate){ - MyCacheTemplate myCacheTemplate=new MyCacheTemplate(); - myCacheTemplate.setRedisCacheManager(redisCacheManager); - myCacheTemplate.setRedisTemplate(redisTemplate); - myCacheTemplate.setName("j2CacheRedis"); - return myCacheTemplate; - } - /** - * 自定义redis缓存 - * @param redisCacheManager - * @param redisTemplate - * @return - */ - @Bean - public MyRedisCache myRedisCache(RedisCacheManager redisCacheManager,RedisTemplate redisTemplate){ - MyRedisCache myRedisCache=new MyRedisCache(); - //自定义属性配置缓存名称 - myRedisCache.setName("myRedis"); - //redis缓存管理器 - myRedisCache.setRedisCacheManager(redisCacheManager); - //redisTemplate 实例 - myRedisCache.setRedisTemplate(redisTemplate); - return myRedisCache; - } - - /** - * spring cache 统一缓存管理器 - * @param myCacheTemplate - * @param myRedisCache - * @return - */ - @Bean - @Primary - public CacheManager cacheManager(MyCacheTemplate myCacheTemplate,MyRedisCache myRedisCache){ - MyCacheManager cacheManager=new MyCacheManager(); - cacheManager.setMyCacheTemplate(myCacheTemplate); - cacheManager.setMyRedisCache(myRedisCache); - return cacheManager; - } - - // 整合ehcache - @Bean - public EhCacheCacheManager ehCacheCacheManager() { - EhCacheCacheManager ehCacheCacheManager = new EhCacheCacheManager(ehCacheManagerFactoryBean().getObject()); - return ehCacheCacheManager; - } - - - - @Bean - public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() { - EhCacheManagerFactoryBean cacheManagerFactoryBean = new - EhCacheManagerFactoryBean(); - //这里暂时借用shiro的ehcache配置文件 - Resource r=new ClassPathResource("ehcache-shiro.xml"); - cacheManagerFactoryBean.setConfigLocation(r); - cacheManagerFactoryBean.setShared(true); - return cacheManagerFactoryBean; - } - -} -自定义CacheManager如下: - -package com.zyc.zspringboot.cache; - -import org.springframework.cache.Cache; -import org.springframework.cache.CacheManager; -import java.util.Collection; - -/** - * @author zyc-admin - * @data 2018-03-20 10:12 - **/ -public class MyCacheManager implements CacheManager { - - private MyCacheTemplate myCacheTemplate; - - private MyRedisCache myRedisCache; - - public MyRedisCache getMyRedisCache() { - return myRedisCache; - } - - public void setMyRedisCache(MyRedisCache myRedisCache) { - this.myRedisCache = myRedisCache; - } - - public MyCacheTemplate getMyCacheTemplate() { - return myCacheTemplate; - } - - public void setMyCacheTemplate(MyCacheTemplate myCacheTemplate) { - this.myCacheTemplate = myCacheTemplate; - } - - @Override - public Cache getCache(String name) { - //多级缓存实现 - if(name.equals(myCacheTemplate.getName())){ - return myCacheTemplate; - } - - return null; - } - - @Override - public Collection getCacheNames() { - - return null; - } -} -自定义Cache实现: - -package com.zyc.zspringboot.cache; - -import net.sf.ehcache.CacheManager; -import net.sf.ehcache.Element; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.cache.Cache; -import org.springframework.cache.support.SimpleValueWrapper; -import org.springframework.data.redis.cache.RedisCacheElement; -import org.springframework.data.redis.cache.RedisCacheKey; -import org.springframework.data.redis.cache.RedisCacheManager; -import org.springframework.data.redis.core.RedisTemplate; -import java.util.concurrent.Callable; - -/** - * @author zyc-admin - * @data 2018-03-19 17:15 - **/ -public class MyCacheTemplate implements Cache { - - private static final Logger logger= LoggerFactory.getLogger(MyCacheTemplate.class); - - private CacheManager ehCacheManager; - - private RedisCacheManager redisCacheManager; - - private RedisTemplate redisTemplate; - - public CacheManager getEhCacheManager() { - return ehCacheManager; - } - - public void setEhCacheManager(CacheManager ehCacheManager) { - this.ehCacheManager = ehCacheManager; - } - - public RedisCacheManager getRedisCacheManager() { - return redisCacheManager; - } - - public void setRedisCacheManager(RedisCacheManager redisCacheManager) { - this.redisCacheManager = redisCacheManager; - } - - public RedisTemplate getRedisTemplate() { - return redisTemplate; - } - - public void setRedisTemplate(RedisTemplate redisTemplate) { - this.redisTemplate = redisTemplate; - } - - private String name; - - @Override - public String getName() { - return name; - } - //自己添加set方法,实现Cache本身无此方法 - public void setName(String name){ - this.name=name; - } - - @Override - public Object getNativeCache() { - return null; - } - - @Override - public ValueWrapper get(Object key) { - ehCacheManager=CacheManager.getCacheManager("ec"); - if(ehCacheManager!=null){ - net.sf.ehcache.Cache myEhcache = ehCacheManager.getCache(getName()); - logger.info("取数据ehcache库===key:{}",key); - if(myEhcache.get(key)!=null){ - ValueWrapper v=new SimpleValueWrapper(myEhcache.get(key).getObjectValue()); - return v; - } - } - Cache myRedis = redisCacheManager.getCache(getName()); - if(myRedis!=null){ - logger.info("取数据reids库===key:{}",key); - if(myRedis.get(key)!=null){ - RedisCacheElement vr=new RedisCacheElement(new RedisCacheKey(key),myRedis.get(key).get()); - return vr; - } - } - - - return null; - } - - @Override - public T get(Object key, Class type) { - System.out.println(key+"======================="+type); - return null; - } - - @Override - public T get(Object key, Callable valueLoader) { - return null; - } - - @Override - public void put(Object key, Object value) { - ehCacheManager=CacheManager.getCacheManager("ec"); - if(ehCacheManager!=null){ - net.sf.ehcache.Cache myEhcache = ehCacheManager.getCache(getName()); - Element e=new Element(key,value); - logger.info("插入ehcache库===key:{},value:{}",key,value); - myEhcache.put(e); - } - Cache myRedis = redisCacheManager.getCache(getName()); - if(myRedis!=null){ - logger.info("插入reids库===key:{},value:{}",key,value); - myRedis.put(key,value); - } - System.out.println("cha ru key "+ key); - - } - - @Override - public ValueWrapper putIfAbsent(Object key, Object value) { - return null; - } - - @Override - public void evict(Object key) { - Cache myRedis = redisCacheManager.getCache(getName()); - if(myRedis!=null){ - logger.info("删除reids库===key:{}",key); - myRedis.evict(key); - } - ehCacheManager=CacheManager.getCacheManager("ec"); - if(ehCacheManager!=null){ - net.sf.ehcache.Cache myEhcache = ehCacheManager.getCache(getName()); - logger.info("删除ehcache库===key:{}",key); - if(myEhcache.isKeyInCache(key)){ - myEhcache.remove(key); - } - - } - - System.out.println("删除 key "+ key); - } - - @Override - public void clear() { - Cache myRedis = redisCacheManager.getCache(getName()); - myRedis.clear(); - ehCacheManager=CacheManager.getCacheManager("ec"); - if(ehCacheManager!=null) { - net.sf.ehcache.Cache myEhcache = ehCacheManager.getCache(getName()); - myEhcache.removeAll(); - } - } -} -使用spring cache 注解使用缓存如下:(在首次调用这个方法时,自定义缓存的put,get方法总是打印2次插入数据,2次取数据,暂时不知道什么原因,若有哪位大神知道,欢迎评论指点。) - -@Cacheable(value = "j2CacheRedis", key = "'role:id:'+#id",unless ="#result == null") - //@Log(value = "获取数据并存入缓存") - public Role getRole(String id) { - // TODO Auto-generated method stub - return roleDao.getRole(id); - } -application.properties配置文件如下 - -#redis ------start------- -spring.redis.hostName=127.0.0.1 -spring.redis.port=63791 -spring.redis.timeOut=1000 -spring.redis.maxIdle=10 -spring.redis.maxWaitMillis=15000 -spring.redis.testOnBorrow=true -spring.redis.testWhileIdle=false -ecache-shiro.xml配置文件如下(因本项目使用了shiro,所以Ehcache使用shiro的缓存配置文件) - - - - - - - - - - - - -整合过程遇到的问题: -1 创建cacheManager bean时失败 -解决方法:可能你配置了多个cacheManager,确保不重名,在自定义的那个cacheManager上添加 @Primary注解 -自定义的CacheManager 要实现CacheManager接口, -注意不要继承org.springframework.cache.support.AbstractCacheManager这个类来实现自己CacheManager -2 创建EhCacheCacheManager失败 -解决方法:查看你的EhCacheCacheManager是否和shiro的EhCache缓存有冲突, -EhCache 2.5版本之上,jvm里面一般只能存在EhCache实例。 -3 内部方法调用带有spring cache注解的方法 缓存失效 -解决方法:spring cache 依赖于aop,使用AopContext.currentProxy().你的方法, -使用之前需先暴露代理对象添加注解 @EnableAspectJAutoProxy(exposeProxy=true,proxyTargetClass=true) -exposeProxy:暴露代理对象,proxyTargetClass强制使用cglib代理 -———————————————— -版权声明:本文为CSDN博主「啊大海全是水」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 -原文链接:https://blog.csdn.net/zhaoyachao123/article/details/79657358 \ No newline at end of file diff --git a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/broadcast/Command.java b/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/broadcast/Command.java deleted file mode 100644 index 0744677f9c..0000000000 --- a/jun_java_plugins/jun_j2cache/src/main/java/net/oschina/j2cache/broadcast/Command.java +++ /dev/null @@ -1,113 +0,0 @@ -package net.oschina.j2cache.broadcast; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.nio.charset.Charset; - -/** - * 广播消息命令封装 - *

<规则:/P> - *

    - *
  • 第 1 个字节为命令代码,长度为1byte [OPT]
  • - *
  • 第 2至3 个字节为缓存region长度,长度为2 [R_LEN]
  • - *
  • 第 4至N 为region值,长度为N-4 [R_LEN]
  • - *
  • 第 N+1至N+2 为key长度,长度为2 [K_LEN]
  • - *
  • 第 N+3至M 为key内容容,长度为M-(N+3)
  • - *
- * - * @author FY - */ -public class Command { - private static final Logger logger = LoggerFactory.getLogger(Command.class); - private static final Charset UTF_8 = Charset.forName("UTF-8"); - - private final byte operator; - private final String region; - private final String key; - - public Command(byte operator, String region, Object key) { - this.operator = operator; - this.region = region; - this.key = String.valueOf(key); - } - - public byte getOperator() { - return operator; - } - - public String getRegion() { - return region; - } - - public Object getKey() { - return key; - } - - // ----------------------------------------------------------------------- - - /** - * 转换为传输buff - * @return {@link byte} - */ - public byte[] toBuff() { - byte[] kBuff = key.getBytes(UTF_8); - byte[] rBytes = region.getBytes(UTF_8); - - int rLen = rBytes.length; - int kLen = kBuff.length; - - byte[] buff = new byte[5 + rLen + kLen]; - int idx = 0; - - buff[idx] = operator; - - buff[++idx] = (byte) (rLen >> 8); - buff[++idx] = (byte) (rLen & 0xFF); - System.arraycopy(rBytes, 0, buff, ++idx, rLen); - idx += rLen; - - buff[idx++] = (byte) (kLen >> 8); - buff[idx++] = (byte) (kLen & 0xFF); - System.arraycopy(kBuff, 0, buff, idx, kLen); - - return buff; - } - - /** - * 接收到广播消息后,解析为{@link Command}对象 - * @param buff 消息buff数据 - * @return {@link Command} - */ - public static Command parse(byte[] buff) { - Command cmd = null; - - try { - int idx = 0; - byte operator = buff[idx]; // 取得操作KEY, 如:{@see CacheCustoms#OPT_DELTED_KEY} - - int rLen = buff[++idx] << 8; - rLen += buff[++idx]; - - if (rLen > 0) { - String region = new String(buff, ++idx, rLen, UTF_8); - idx += rLen; - - int kLen = buff[idx++] << 8; - kLen += buff[idx++]; - - if (kLen > 0) { - byte[] kBuff = new byte[kLen]; - System.arraycopy(buff, idx, kBuff, 0, kLen); - Object key = new String(kBuff, UTF_8); - cmd = new Command(operator, region, key); - } - } - - } catch (Exception e) { - logger.error("解析缓存JGroup广播事件消息为Command对象失败.", e); - } - - return cmd; - } -} diff --git a/jun_java_plugins/jun_jar2maven/README.md b/jun_java_plugins/jun_jar2maven/README.md deleted file mode 100644 index 7ba390d232..0000000000 --- a/jun_java_plugins/jun_jar2maven/README.md +++ /dev/null @@ -1,33 +0,0 @@ -# jarToMaven - -#### 介绍 -jar包转成maven项目的pom.xml格式 -将网上的代码整理一番,供网友直接下载运行 - - -#### 软件架构 -软件架构说明 - - -#### 安装教程 - -1. 运行pom.xml把需要的jar包下载下来。 -2. 运行里面唯一的java文件。 -3. 控制台输出结果,红色内容为未找到该jar所对应的格式,需要自己上网找替代版本或pom.xml配置本地jar包 - -#### 软件运行环境说明 - -1. Eclipse -2. jdk1.7 -3. 联网 - -#### 参与贡献 - -1. Fork 本仓库 -2. 新建 Feat_xxx 分支 -3. 提交代码 -4. 新建 Pull Request - - -#### 码云特技 - diff --git a/jun_java_plugins/jun_jar2maven/pom.xml b/jun_java_plugins/jun_jar2maven/pom.xml deleted file mode 100644 index 553831f6d5..0000000000 --- a/jun_java_plugins/jun_jar2maven/pom.xml +++ /dev/null @@ -1,53 +0,0 @@ - - 4.0.0 - io.github.wujun728 - jun_jar2maven - 1.0 - - UTF-8 - false - - - - - - javax.servlet - javax.servlet-api - 3.1.0 - provided - - - org.jsoup - jsoup - 1.8.3 - - - dom4j - dom4j - 1.6 - - - com.alibaba - fastjson - 1.2.25.sec10 - - - - - - src/main/java - - - maven-compiler-plugin - 3.5.1 - - 1.7 - 1.7 - - - - - - diff --git a/jun_java_plugins/jun_java_compiler/.gitignore b/jun_java_plugins/jun_java_compiler/.gitignore deleted file mode 100644 index 08a6861f18..0000000000 --- a/jun_java_plugins/jun_java_compiler/.gitignore +++ /dev/null @@ -1,279 +0,0 @@ -# Java.gitignore ############################################################## - -*.class - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ - -# Package Files # -*.jar -*.war -*.ear - -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* - -# Maven.gitignore ############################################################# - -target/ -pom.xml.tag -pom.xml.releaseBackup -pom.xml.versionsBackup -pom.xml.next -release.properties -dependency-reduced-pom.xml -buildNumber.properties -.mvn/timing.properties - -# Eclipse.gitignore ########################################################### - -*.pydevproject -.metadata -.gradle -bin/ -tmp/ -*.tmp -*.bak -*.swp -*~.nib -local.properties -.settings/ -.loadpath - -# Eclipse Core -.project - -# External tool builders -.externalToolBuilders/ -.recommenders/ - -# Locally stored "Eclipse launch configurations" -*.launch - -# CDT-specific -.cproject - -# JDT-specific (Eclipse Java Development Tools) -.classpath - -# Java annotation processor (APT) -.factorypath - -# PDT-specific -.buildpath - -# sbteclipse plugin -.target - -# TeXlipse plugin -.texlipse - -# NetBeans.gitignore ########################################################## - -nbproject/private/ -build/ -nbbuild/ -dist/ -nbdist/ -nbactions.xml -nb-configuration.xml -.nb-gradle/ - -# JetBrains.gitignore ######################################################### - -# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio - -*.iml - -## Directory-based project format: -.idea/ -# if you remove the above rule, at least ignore the following: - -# model.User-specific stuff: -# .idea/workspace.xml -# .idea/tasks.xml -# .idea/dictionaries - -# Sensitive or high-churn files: -# .idea/dataSources.ids -# .idea/dataSources.xml -# .idea/sqlDataSources.xml -# .idea/dynamic.xml -# .idea/uiDesigner.xml - -# Gradle: -# .idea/gradle.xml -# .idea/libraries - -# Mongo Explorer plugin: -# .idea/mongoSettings.xml - -## File-based project format: -*.ipr -*.iws - -## Plugin-specific files: - -# IntelliJ -/out/ - -# mpeltonen/sbt-idea plugin -.idea_modules/ - -# JIRA plugin -atlassian-ide-plugin.xml - -# Crashlytics plugin (for Android Studio and IntelliJ) -com_crashlytics_export_strings.xml -crashlytics.properties -crashlytics-build.properties - -# SublimeText.gitignore ####################################################### - -# cache files for sublime text -*.tmlanguage.cache -*.tmPreferences.cache -*.stTheme.cache - -# workspace files are user-specific -*.sublime-workspace - -# project files should be checked into the repository, unless a significant -# proportion of contributors will probably not be using SublimeText -# *.sublime-project - -# sftp configuration file -sftp-config.json - -# Vim.gitignore ############################################################### - -[._]*.s[a-w][a-z] -[._]s[a-w][a-z] -*.un~ -Session.vim -.netrwhist -*~ - -# Emacs.gitignore ############################################################# - -# -*- mode: gitignore; -*- -*~ -\#*\# -/.emacs.desktop -/.emacs.desktop.lock -*.elc -auto-save-list -tramp -.\#* - -# Org-mode -.org-id-locations -*_archive - -# flymake-mode -*_flymake.* - -# eshell files -/eshell/history -/eshell/lastdir - -# elpa packages -/elpa/ - -# reftex files -*.rel - -# AUCTeX auto folder -/auto/ - -# cask packages -.cask/ - -# Python ignore ############################################################### - -*.py[cod] - -# C extensions -*.so - -# Packages -*.egg -*.egg-info -dist -build -eggs -parts -bin -var -sdist -develop-eggs -.installed.cfg -lib -lib64 -__pycache__ - -# Installer logs -pip-log.txt - -# Unit test / coverage reports -.coverage -.tox -nosetests.xml - -# OSX.gitignore ############################################################### - -.DS_Store -.AppleDouble -.LSOverride - -# Icon must end with two \r -Icon - -# Thumbnails -._* - -# Files that might appear in the root of a volume -.DocumentRevisions-V100 -.fseventsd -.Spotlight-V100 -.TemporaryItems -.Trashes -.VolumeIcon.icns - -# Directories potentially created on remote AFP share -.AppleDB -.AppleDesktop -Network Trash Folder -Temporary Items -.apdisk - -# Windows.gitignore ########################################################### - -# Windows image file caches -Thumbs.db -ehthumbs.db - -# Folder config file -Desktop.ini - -# Recycle Bin used on file shares -$RECYCLE.BIN/ - -# Windows Installer files -*.cab -*.msi -*.msm -*.msp - -# Windows shortcuts -*.lnk - -# Linux.gitignore ############################################################# - -*~ - -# KDE directory preferences -.directory - -# Linux trash folder which might appear on any partition or disk -.Trash-* diff --git a/jun_java_plugins/jun_java_compiler/.travis.yml b/jun_java_plugins/jun_java_compiler/.travis.yml deleted file mode 100644 index 19932b5447..0000000000 --- a/jun_java_plugins/jun_java_compiler/.travis.yml +++ /dev/null @@ -1,7 +0,0 @@ -language: java - -jdk: - - oraclejdk7 - -install: mvn install -DskipTests=true -Dgpg.skip=true - diff --git a/jun_java_plugins/jun_java_compiler/README.md b/jun_java_plugins/jun_java_compiler/README.md deleted file mode 100644 index f67afcbad4..0000000000 --- a/jun_java_plugins/jun_java_compiler/README.md +++ /dev/null @@ -1,62 +0,0 @@ -# compiler - -Compile Java code in memory using Java 6 compiler API. - -[![Build Status](https://travis-ci.org/michaelliao/compiler.svg?branch=master)](https://travis-ci.org/michaelliao/compiler) - -### Why compiler API? - -You can use compiler API to compile generated Java source code and load the compiled classes on-the-fly. - -For example, generate proxy classes using compiler API instead of CGLIB or Javassist. - -### How to use this compiler? - -Step 1: add maven dependency: - -``` - - com.itranswarp - compiler - 1.0 - -``` - -Step 2: compile string and load class: - -``` -public class Main { - - public static void main(String[] args) { - JavaStringCompiler compiler = new JavaStringCompiler(); - Map results = compiler.compile("UserProxy.java", JAVA_SOURCE_CODE); - Class clazz = compiler.loadClass("on.the.fly.UserProxy", results); - // try instance: - model.User user = (model.User) clazz.newInstance(); - } - - static final String JAVA_SOURCE_CODE = "/* a single java source file */ " - + "package on.the.fly; " - + "public class UserProxy extends test.model.User { " - + " boolean _dirty = false; " - + " public void setId(String id) { " - + " super.setId(id); " - + " setDirty(true); " - + " } " - + " public void setName(String name) { " - + " super.setName(name); " - + " setDirty(true); " - + " } " - + " public void setCreated(long created) { " - + " super.setCreated(created); " - + " setDirty(true); " - + " } " - + " public void setDirty(boolean dirty) { " - + " this._dirty = dirty; " - + " } " - + " public boolean isDirty() { " - + " return this._dirty; " - + " } " - + "} "; -} -``` diff --git a/jun_java_plugins/jun_java_compiler/pom.xml b/jun_java_plugins/jun_java_compiler/pom.xml deleted file mode 100644 index 293d8fdadc..0000000000 --- a/jun_java_plugins/jun_java_compiler/pom.xml +++ /dev/null @@ -1,127 +0,0 @@ - - 4.0.0 - - io.github.wujun728 - 1.0 - jun_java_compiler - jar - - - - UTF-8 - - 1.0 - - yyyyMMdd_HHmmss - - 2.1.1 - 4.12 - - - - - org.eclipse.persistence - javax.persistence - ${jpa.version} - test - - - junit - junit - ${junit.version} - test - - - - - - - org.apache.maven.plugins - maven-jar-plugin - 2.6 - - - - jar - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.2 - - 1.7 - 1.7 - -verbose - - - - org.apache.maven.plugins - maven-source-plugin - 2.2.1 - - - attach-sources - - jar-no-fork - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.9.1 - - - attach-javadocs - - jar - - - - - - - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.3 - true - - ossrh - https://oss.sonatype.org/ - true - - - - - - - - ossrh - https://oss.sonatype.org/content/repositories/snapshots - - - - ossrh - Nexus Release Repository - http://oss.sonatype.org/service/local/staging/deploy/maven2/ - - - diff --git a/jun_java_plugins/jun_java_compiler/src/main/java/com/jun/plugin/compiler/JavaStringCompiler.java b/jun_java_plugins/jun_java_compiler/src/main/java/com/jun/plugin/compiler/JavaStringCompiler.java deleted file mode 100644 index 72eca71744..0000000000 --- a/jun_java_plugins/jun_java_compiler/src/main/java/com/jun/plugin/compiler/JavaStringCompiler.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.jun.plugin.compiler; - -import java.io.IOException; -import java.util.Arrays; -import java.util.Map; - -import javax.tools.JavaCompiler; -import javax.tools.JavaFileObject; -import javax.tools.StandardJavaFileManager; -import javax.tools.ToolProvider; -import javax.tools.JavaCompiler.CompilationTask; - -/** - * In-memory compile Java source code as String. - * - * @author michael - */ -public class JavaStringCompiler { - - JavaCompiler compiler; - StandardJavaFileManager stdManager; - - public JavaStringCompiler() { - this.compiler = ToolProvider.getSystemJavaCompiler(); - this.stdManager = compiler.getStandardFileManager(null, null, null); - } - - /** - * Compile a Java source file in memory. - * - * @param fileName - * Java file name, e.g. "Test.java" - * @param source - * The source code as String. - * @return The compiled results as Map that contains class name as key, - * class binary as value. - * @throws IOException - * If compile error. - */ - public Map compile(String fileName, String source) throws IOException { - try (MemoryJavaFileManager manager = new MemoryJavaFileManager(stdManager)) { - JavaFileObject javaFileObject = manager.makeStringSource(fileName, source); - CompilationTask task = compiler.getTask(null, manager, null, null, null, Arrays.asList(javaFileObject)); - Boolean result = task.call(); - if (result == null || !result.booleanValue()) { - throw new RuntimeException("Compilation failed."); - } - return manager.getClassBytes(); - } - } - - /** - * Load class from compiled classes. - * - * @param name - * Full class name. - * @param classBytes - * Compiled results as a Map. - * @return The Class instance. - * @throws ClassNotFoundException - * If class not found. - * @throws IOException - * If load error. - */ - public Class loadClass(String name, Map classBytes) throws ClassNotFoundException, IOException { - try (MemoryClassLoader classLoader = new MemoryClassLoader(classBytes)) { - return classLoader.loadClass(name); - } - } -} diff --git a/jun_java_plugins/jun_java_compiler/src/main/java/com/jun/plugin/compiler/MemoryClassLoader.java b/jun_java_plugins/jun_java_compiler/src/main/java/com/jun/plugin/compiler/MemoryClassLoader.java deleted file mode 100644 index 6321dd1369..0000000000 --- a/jun_java_plugins/jun_java_compiler/src/main/java/com/jun/plugin/compiler/MemoryClassLoader.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.jun.plugin.compiler; - -import java.net.URL; -import java.net.URLClassLoader; -import java.util.HashMap; -import java.util.Map; - -/** - * Load class from byte[] which is compiled in memory. - * - * @author michael - */ -class MemoryClassLoader extends URLClassLoader { - - // class name to class bytes: - Map classBytes = new HashMap(); - - public MemoryClassLoader(Map classBytes) { - super(new URL[0], MemoryClassLoader.class.getClassLoader()); - this.classBytes.putAll(classBytes); - } - - @Override - protected Class findClass(String name) throws ClassNotFoundException { - byte[] buf = classBytes.get(name); - if (buf == null) { - return super.findClass(name); - } - classBytes.remove(name); - return defineClass(name, buf, 0, buf.length); - } - -} diff --git a/jun_java_plugins/jun_java_compiler/src/main/java/com/jun/plugin/compiler/MemoryJavaFileManager.java b/jun_java_plugins/jun_java_compiler/src/main/java/com/jun/plugin/compiler/MemoryJavaFileManager.java deleted file mode 100644 index 518984c760..0000000000 --- a/jun_java_plugins/jun_java_compiler/src/main/java/com/jun/plugin/compiler/MemoryJavaFileManager.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.jun.plugin.compiler; - -import java.io.ByteArrayOutputStream; -import java.io.FilterOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.net.URI; -import java.nio.CharBuffer; -import java.util.HashMap; -import java.util.Map; - -import javax.tools.FileObject; -import javax.tools.ForwardingJavaFileManager; -import javax.tools.JavaFileManager; -import javax.tools.JavaFileObject; -import javax.tools.JavaFileObject.Kind; -import javax.tools.SimpleJavaFileObject; - -/** - * In-memory java file manager. - * - * @author michael - */ -class MemoryJavaFileManager extends ForwardingJavaFileManager { - - // compiled classes in bytes: - final Map classBytes = new HashMap(); - - MemoryJavaFileManager(JavaFileManager fileManager) { - super(fileManager); - } - - public Map getClassBytes() { - return new HashMap(this.classBytes); - } - - @Override - public void flush() throws IOException { - } - - @Override - public void close() throws IOException { - classBytes.clear(); - } - - @Override - public JavaFileObject getJavaFileForOutput(JavaFileManager.Location location, String className, Kind kind, - FileObject sibling) throws IOException { - if (kind == Kind.CLASS) { - return new MemoryOutputJavaFileObject(className); - } else { - return super.getJavaFileForOutput(location, className, kind, sibling); - } - } - - JavaFileObject makeStringSource(String name, String code) { - return new MemoryInputJavaFileObject(name, code); - } - - static class MemoryInputJavaFileObject extends SimpleJavaFileObject { - - final String code; - - MemoryInputJavaFileObject(String name, String code) { - super(URI.create("string:///" + name), Kind.SOURCE); - this.code = code; - } - - @Override - public CharBuffer getCharContent(boolean ignoreEncodingErrors) { - return CharBuffer.wrap(code); - } - } - - class MemoryOutputJavaFileObject extends SimpleJavaFileObject { - final String name; - - MemoryOutputJavaFileObject(String name) { - super(URI.create("string:///" + name), Kind.CLASS); - this.name = name; - } - - @Override - public OutputStream openOutputStream() { - return new FilterOutputStream(new ByteArrayOutputStream()) { - @Override - public void close() throws IOException { - out.close(); - ByteArrayOutputStream bos = (ByteArrayOutputStream) out; - classBytes.put(name, bos.toByteArray()); - } - }; - } - - } -} diff --git a/jun_java_plugins/jun_java_compiler/src/test/java/com/jun/plugin/compiler/JavaStringCompilerTest.java b/jun_java_plugins/jun_java_compiler/src/test/java/com/jun/plugin/compiler/JavaStringCompilerTest.java deleted file mode 100644 index 14dea9b104..0000000000 --- a/jun_java_plugins/jun_java_compiler/src/test/java/com/jun/plugin/compiler/JavaStringCompilerTest.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.jun.plugin.compiler; - -import static org.junit.Assert.*; - -import java.lang.reflect.Method; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; - -import com.jun.plugin.compiler.JavaStringCompiler; -import com.jun.plugin.on.the.fly.BeanProxy; -import com.jun.plugin.on.the.fly.User; - -public class JavaStringCompilerTest { - - JavaStringCompiler compiler; - - @Before - public void setUp() throws Exception { - compiler = new JavaStringCompiler(); - } - - static final String SINGLE_JAVA = "/* a single java class to one file */ " - + "package on.the.fly; " - + "import com.itranswarp.on.the.fly.*; " - + "public class UserProxy extends User implements BeanProxy { " - + " boolean _dirty = false; " - + " public void setId(String id) { " - + " super.setId(id); " - + " setDirty(true); " - + " } " - + " public void setName(String name) { " - + " super.setName(name); " - + " setDirty(true); " - + " } " - + " public void setCreated(long created) { " - + " super.setCreated(created); " - + " setDirty(true); " - + " } " - + " public void setDirty(boolean dirty) { " - + " this._dirty = dirty; " - + " } " - + " public boolean isDirty() { " - + " return this._dirty; " - + " } " - + "} "; - - @Test - public void testCompileSingleClass() throws Exception { - Map results = compiler.compile("UserProxy.java", SINGLE_JAVA); - assertEquals(1, results.size()); - assertTrue(results.containsKey("on.the.fly.UserProxy")); - Class clazz = compiler.loadClass("on.the.fly.UserProxy", results); - // get method: - Method setId = clazz.getMethod("setId", String.class); - Method setName = clazz.getMethod("setName", String.class); - Method setCreated = clazz.getMethod("setCreated", long.class); - // try instance: - Object obj = clazz.newInstance(); - // get as proxy: - BeanProxy proxy = (BeanProxy) obj; - assertFalse(proxy.isDirty()); - // set: - setId.invoke(obj, "A-123"); - setName.invoke(obj, "Fly"); - setCreated.invoke(obj, 123000999); - // get as user: - User user = (User) obj; - assertEquals("A-123", user.getId()); - assertEquals("Fly", user.getName()); - assertEquals(123000999, user.getCreated()); - assertTrue(proxy.isDirty()); - } - - static final String MULTIPLE_JAVA = "/* a single class to many files */ " - + "package on.the.fly; " - + "import java.util.*; " - + "public class Multiple { " - + " List list = new ArrayList(); " - + " public void add(String name) { " - + " Bird bird = new Bird(); " - + " bird.name = name; " - + " this.list.add(bird); " - + " } " - + " public Bird getFirstBird() { " - + " return this.list.get(0); " - + " } " - + " public static class StaticBird { " - + " public int weight = 100; " - + " } " - + " class NestedBird { " - + " NestedBird() { " - + " System.out.println(list.size() + \" birds...\"); " - + " } " - + " } " - + "} " - + "/* package level */ " - + "class Bird { " - + " String name = null; " - + "} "; - - @Test - public void testCompileMultipleClasses() throws Exception { - Map results = compiler.compile("Multiple.java", MULTIPLE_JAVA); - assertEquals(4, results.size()); - assertTrue(results.containsKey("on.the.fly.Multiple")); - assertTrue(results.containsKey("on.the.fly.Multiple$StaticBird")); - assertTrue(results.containsKey("on.the.fly.Multiple$NestedBird")); - assertTrue(results.containsKey("on.the.fly.Bird")); - Class clzMul = compiler.loadClass("on.the.fly.Multiple", results); - // try instance: - Object obj = clzMul.newInstance(); - assertNotNull(obj); - } -} diff --git a/jun_java_plugins/jun_java_compiler/src/test/java/com/jun/plugin/on/the/fly/BeanProxy.java b/jun_java_plugins/jun_java_compiler/src/test/java/com/jun/plugin/on/the/fly/BeanProxy.java deleted file mode 100644 index 0dd0a54a44..0000000000 --- a/jun_java_plugins/jun_java_compiler/src/test/java/com/jun/plugin/on/the/fly/BeanProxy.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.jun.plugin.on.the.fly; - -/** - * Sample interface. - * - * @author michael - */ -public interface BeanProxy { - - void setDirty(boolean dirty); - - boolean isDirty(); - -} diff --git a/jun_java_plugins/jun_java_compiler/src/test/java/com/jun/plugin/on/the/fly/User.java b/jun_java_plugins/jun_java_compiler/src/test/java/com/jun/plugin/on/the/fly/User.java deleted file mode 100644 index 3c23410120..0000000000 --- a/jun_java_plugins/jun_java_compiler/src/test/java/com/jun/plugin/on/the/fly/User.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.jun.plugin.on.the.fly; - -/** - * Sample class as JavaBean. - * - * @author michael - */ -public class User { - - private String id; - private String name; - private long created; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public long getCreated() { - return created; - } - - public void setCreated(long created) { - this.created = created; - } - -} diff --git a/jun_java_plugins/jun_javase/pom.xml b/jun_java_plugins/jun_javase/pom.xml deleted file mode 100644 index c7470e4a51..0000000000 --- a/jun_java_plugins/jun_javase/pom.xml +++ /dev/null @@ -1,23 +0,0 @@ - - 4.0.0 - - io.github.wujun728 - jun_javase - 1.0 - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.1 - - 8 - 8 - UTF-8 - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/JDBCTest/ConnTest.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/JDBCTest/ConnTest.java deleted file mode 100644 index 17cc928ada..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/JDBCTest/ConnTest.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.jun.plugin.javase.JDBCTest; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; - -public class ConnTest { - public static void main(String[] args) { - Connection conn=null; - PreparedStatement stat=null; -// PreparedStatement - ResultSet rs=null;//������ݿ���������ʱ�� - try { - Class.forName("com.mysql.jdbc.Driver");//�������ݿ������� - } catch (ClassNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - try { - conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/db_food", "root","root"); - //����DriverManager���е�getConnection()����������ָ�����ݿ������ - - //����Connection�ӿ��е�createStatement()��������Statement����Statement��������ã��Ѿ��������ӵĻ����ϣ�����sql��� - String sql="insert into t_food(name,price) values (?,?)"; - stat=conn.prepareStatement(sql); - //�༭sql��� - rs=stat.executeQuery(sql); - //����Statement�еķ���executeQuery()ִ��sql��䣬�����ص����Ľ�� - while(rs.next()){ - Food food=new Food(); - food.setName(rs.getString("name")); - food.setPrice(rs.getInt("price")); - System.out.println(food.getName()+","+food.getPrice()); - } - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - try { - rs.close(); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - try { - stat.close(); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - try { - conn.close(); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/JDBCTest/Food.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/JDBCTest/Food.java deleted file mode 100644 index 5a52c61650..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/JDBCTest/Food.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.jun.plugin.javase.JDBCTest; - -public class Food { - private int id; - private String name; - private int price; - public int getId() { - return id; - } - public void setId(int id) { - this.id = id; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public int getPrice() { - return price; - } - public void setPrice(int price) { - this.price = price; - } - @Override - public String toString() { - return "Food [id=" + id + ", name=" + name + ", price=" + price + "]"; - } - public Food() { - super(); - } - - - - - -}//�ϸ�����javaBeen��ʽ������ܴ������ݿ� diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/SevDay/BubbleSort.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/SevDay/BubbleSort.java deleted file mode 100644 index 28fabefa3b..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/SevDay/BubbleSort.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.jun.plugin.javase.SevDay; - -import com.jun.plugin.javase.fiveday.Test; - -public class BubbleSort { - public static void main(String[] args) { - int[] arr={10,32,67,5,78,43}; - - /*bubbleSort(arr); - bubbleSortT(arr); - bubbleSorts(arr); - selectSort(arr); - selectSortT(arr); - reverse(arr);*/ - selectSorts(arr); - } - - - static void bubbleSort(int[] array){ - for(int i=0;iarray[j+1]){ - int temp=array[j]; - array[j]=array[j+1]; - array[j+1]=temp; - } - } - } - printArrays(array); - } - - static void bubbleSortT(int[] array){ - for(int i=array.length-1;i>=0;i--){ - for(int j=array.length-i-1;j>=1;j--){ - if(array[j]=0;i--){ - for(int j=0;jarray[j+1]){ - int temp=array[j]; - array[j]=array[j+1]; - array[j+1]=temp; - } - } - } - printArrays(array); - } - - static void selectSort(int[] array){ - for(int i=0;iarray[j]){ - int temp=array[i]; - array[i]=array[j]; - array[j]=temp; - } - } - } - printArrays(array); - } - - static void selectSortT(int[] array){ - for(int i=array.length-1;i>=0;i--){ - for(int j=i-1;j>=0;j--){ - if(array[j]>array[i]){ - int temp=array[i]; - array[i]=array[j]; - array[j]=temp; - } - } - } - printArrays(array); - } - - static void selectSorts(int[] array){ - for(int i=0;ii;j--){ - if(array[j]arr[j]){ - num=arr[j]; - index=j; - } - } - if(index!=i){ - int temp=arr[i]; - arr[i]=arr[index]; - arr[index]=temp; - } - } - CommonMethod.printArrays(arr); - //ͨ�������±�������������*/ - - int[] arr={12,21,15,3,4,13,43}; - CommonMethod.bubbleSort(arr); - CommonMethod.printArrays(arr); - int n=12; - int index=0; - for(int i=0;i=arr[i]&&n=arr[arr.length-1]){ - System.out.println("���������������ֵ"+arr[arr.length-1]+"֮��"); - index=arr.length; - break; - } - else if(narr[mid]){ - min=mid+1; - }else if(keymax){ - return -1; - } - mid=(min+max)/2; - - } - return mid; - }//���ֲ��ҡ���һ�γ��ֵ��±� - - - static int halfSearch_2(int[] arr,int key){ - int min,max,mid; - min=0; - max=arr.length-1; - while(min<=max){ - mid=(min+max)/2; - if(key>arr[mid]){ - min=mid+1; - }else if(keymap=new HashMap(); - Emp emp=new Emp("351","����"); - Emp emp2=new Emp("350","����"); - Emp emp3=new Emp("315","����"); - Emp emp4=new Emp("355","����"); - Emp emp5=new Emp("305","�Ŷ�"); - - map.put(emp4.getE_id(), emp4.getE_name()); - map.put(emp2.getE_id(), emp2.getE_name()); - map.put(emp3.getE_id(), emp3.getE_name()); - map.put(emp.getE_id(), emp.getE_name()); - map.put(emp5.getE_id(), emp5.getE_name()); - - Set set=map.keySet(); - Iterator it=set.iterator(); - while(it.hasNext()){ - String str=(String)it.next(); - String name=(String)map.get(str); - System.out.println(str+" "+name); - } - System.out.println("---------"); - TreeMaptreemap=new TreeMap(); - treemap.putAll(map); -// Set sett=treemap.keySet(); -// Iterator iter=sett.iterator(); - Iteratoriter=treemap.keySet().iterator(); - while(iter.hasNext()){ - String str=(String)iter.next(); - String name=(String)treemap.get(str); - System.out.println(str+" "+name); - } - } -} - -class Emp{ - private String e_id; - private String e_name; - Emp(String e_id,String e_name){ - this.e_id=e_id; - this.e_name=e_name; - } - public String getE_id() { - return e_id; - } - public void setE_id(String e_id) { - this.e_id = e_id; - } - public String getE_name() { - return e_name; - } - public void setE_name(String e_name) { - this.e_name = e_name; - } - -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/collectionn/SetTest.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/collectionn/SetTest.java deleted file mode 100644 index c90023f240..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/collectionn/SetTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.jun.plugin.javase.collectionn; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.TreeSet; - -public class SetTest { - public static void main(String[] args) { - HashSet hs=new HashSet(); - hs.add(new Person1("zs",21)); - hs.add(new Person1("ls",22)); - hs.add(new Person1("ww",23)); - Iterator it=hs.iterator(); - while(it.hasNext()){ - System.out.println(it.next()); - } - - System.out.println("-----------"); - - TreeSet ts=new TreeSet(); - ts.add(new Person1("zs",21)); - ts.add(new Person1("ls",19)); - ts.add(new Person1("ww",3)); - Iterator iter=ts.iterator(); - while(iter.hasNext()){ - System.out.println(iter.next()); - } - - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/collectionn/StringTest.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/collectionn/StringTest.java deleted file mode 100644 index f60e8bf7ee..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/collectionn/StringTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.jun.plugin.javase.collectionn; - -import java.util.HashMap; - -public class StringTest { - public static void main(String[] args) { - HashMap hashmap=new HashMap(); - String str="ababdcdacbfxsrvfgr"; - for(int i=0;i map=new TreeMap(); - for(int i=0;i='a'&&Character.toLowerCase(ch[i])<='z')){ - continue; - } - Integer value=map.get(ch[i]); - int count=1; - if(value!=null){ - count=value+1; - } - map.put(ch[i], count); - } - return mapToString(map); - } - - public static String mapToString(Mapmap){ - StringBuilder sb=new StringBuilder(); - Iteratorit=map.keySet().iterator(); - while(it.hasNext()){ - Character key=it.next(); - Integer value=map.get(key); - sb.append(key+"("+value+")"+","); - } - return sb.toString(); - } - -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/collectionn/Test1.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/collectionn/Test1.java deleted file mode 100644 index 8bf6cf7daf..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/collectionn/Test1.java +++ /dev/null @@ -1,105 +0,0 @@ -package com.jun.plugin.javase.collectionn; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; -import java.util.TreeSet; - -public class Test1 { - public static void main(String[] args) { -// ArrayList - /*Collection list=new ArrayList (); - Collection list1=new ArrayList (); - list.add("a"); - list.add("b"); - list.add("c"); - list.add("d"); - list1.add("c"); - list1.add("d"); - list1.add("e"); - list1.add("f");*/ -// list.removeAll(list1);//���� -// list.retainAll(list1);//���� -// list.clear(); -// System.out.println(list.hashCode()); - /*Iterator iter=list.iterator(); - while(iter.hasNext()){ - System.out.println(iter.next()); - } - System.out.println("--------"); - Iterator it=list1.iterator(); - while(it.hasNext()){ - System.out.println(it.next()); - }*/ - - -// LinkedList - /*List linked=new LinkedList(); - String[] s1={"q","w","e"}; - String[] s2={"p","o","i","h"}; - linked.add(s1); - linked.add(s2); - for(int j=0;jit=linked.iterator(); - while(it.hasNext()){ - String[] str=(String[])it.next(); - for(int i=0;i=0){ - flag=index; - } - else{ - flag=-index-1; - } - //System.out.println(index); - int[] arrNew=new int[arr.length+1]; - for(int i=0;i<=arrNew.length-1;i++){ - if(iarr[j+1]){ - int temp=arr[j]; - arr[j]=arr[j+1]; - arr[j+1]=temp; - } - } - } - printArrays(arr); - - System.out.println("========ѡ������=========="); - int[] arr2={12,55,39,6,7,65,0,3}; - for(int i=0;iarr2[j]){ - int temp=arr2[i]; - arr2[i]=arr2[j]; - arr2[j]=temp; - } - } - } - printArrays(arr2); - System.out.println("========����=========="); - for(int i=2;i<100;i++){ - boolean flag=true; - for(int j=2;j2){ - return fn(n-1)+fn(n-2); - } - else{ - return 1; - } - } -} - - - - diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/day9/Array.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/day9/Array.java deleted file mode 100644 index b92edee327..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/day9/Array.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.jun.plugin.javase.day9; - -import java.util.Arrays; - -public class Array { - public static void main(String[] args) { - /*String[][] arr={{"12345","kdsjf","skfj"},{"16723","ksjfdks"},{"1237986","dsk"},{"12678653","saie"}}; - - for(int i=0;i=0;i--){ - for(int j=0;j<=arrNew.length;j++){ - System.out.print(arrNew[i][j]+" "); - } - System.out.println(); - }*/ - - - - } - -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/Action.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/Action.java deleted file mode 100644 index 2e951acb93..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/Action.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.jun.plugin.javase.enums; - -public enum Action { - TURN_LEFT, TURN_RIGHT, SHOOT -} \ No newline at end of file diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/DetailActioin2.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/DetailActioin2.java deleted file mode 100644 index 6d7c77b530..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/DetailActioin2.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.jun.plugin.javase.enums; - -/** - * 枚举类型既然是类,那么也就可以有构造函数。只不过不得有公开(Public)的构造函数,这是为了避免直接对枚举类型实例化。 - */ -public enum DetailActioin2 { - TURN_LEFT("向左转"), TURN_RIGHT("向右转"), SHOOT("射击"); - - private String description; - - // 不公开的构造函数 - private DetailActioin2(String description) { - this.description = description; - } - - public String getDescription() { - return description; - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/DetailAction.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/DetailAction.java deleted file mode 100644 index fcde38b0ab..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/DetailAction.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.jun.plugin.javase.enums; - -/** - *定义枚举类型其实就是在定义一个类,只不过很多细节由编译器帮你补齐了,所以,某种程度上enum关键词的作用就像是class或interface. - - 当使用enum定义枚举类型时,实际上所定义出来的类型是继承自java.lang.Enum类。而每个被枚举的成员其实就是定义的枚举类型的一个实例, - 它们都被默认为final。无法改变常数名称所设定的值,它们也是public和static的成员,这与接口中的常量限制相同。可以通过类名称直接使用它们。 - 如1中所定义的枚举类型Action,TURN_LEFT,TURN_RIGHT,SHOOT都是Action的一个对象实例。因为是对象,所以,对象上自然有一些方法可以调用。 - 如从Object继承焉的toString()方法被重新定义了,可以让你直接取得枚举值的字符串描述;values()方法可以让您取得所有的枚举成员实例, - 并以数组方式返回。您可以使用这两个方法来简单的将Action的枚举成员显示出来。静态valueOf()方法可以让您将指定的字符串尝试转换为枚举类型。 - 可以用compareTo()方法来比较两个枚举对象在枚举时的顺序。-1之前,0位置相同,1之后。 - - 对于每个枚举成员,使用ordinal()方法,依枚举顺序得到位置索引,默认以0开始。 - - * @author Wujun - * @since 2013年9月9日 下午5:24:43 - */ -public enum DetailAction { - TURN_LEFT, TURN_RIGHT, SHOOT; - - public String getDescription() { - switch (this.ordinal()) { - case 0: - return "向左转"; - case 1: - return "向右转"; - case 2: - return "射击"; - default: - return null; - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/DetailActionDemo.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/DetailActionDemo.java deleted file mode 100644 index 8a656622eb..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/DetailActionDemo.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jun.plugin.javase.enums; - -public class DetailActionDemo { - public static void main(String[] args) { - for (DetailAction action : DetailAction.values()) { - System.out.printf("%s: %s%n", action, action.getDescription()); - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/EnumDemo.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/EnumDemo.java deleted file mode 100644 index 9cae1b1f43..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/EnumDemo.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jun.plugin.javase.enums; - -public class EnumDemo { - public static void main(String[] args) { - doAction(Action.TURN_RIGHT); - } - - public static void doAction(Action action) { - switch (action) { - case TURN_LEFT: - System.out.println("向左转"); - break; - case TURN_RIGHT: - System.out.println("向右转"); - break; - case SHOOT: - System.out.println("射击"); - break; - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/EnumDemo2.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/EnumDemo2.java deleted file mode 100644 index 15320607c4..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/EnumDemo2.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.jun.plugin.javase.enums; - -public class EnumDemo2 { - private enum InnerAction { - TURN_LEFT, TURN_RIGHT, SHOOT - }; - - public static void main(String[] args) { - doAction(InnerAction.TURN_RIGHT); - } - - public static void doAction(InnerAction action) { - switch (action) { - case TURN_LEFT: - System.out.println("向左转"); - break; - case TURN_RIGHT: - System.out.println("向右转"); - break; - case SHOOT: - System.out.println("射击"); - break; - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/IDescription.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/IDescription.java deleted file mode 100644 index 62a424e14a..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/IDescription.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.jun.plugin.javase.enums; - -public interface IDescription { - public String getDescription(); -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/MoreAction.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/MoreAction.java deleted file mode 100644 index 0bfd52d622..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/MoreAction.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.jun.plugin.javase.enums; - -public enum MoreAction implements IDescription { - TURN_LEFT { - // 实现接口上的方法 - public String getDescription() { - return "向左转"; - } - - }, // 注意这里的枚举值分隔使用, - - TURN_RIGHT { - // 实现接口上的方法 - public String getDescription() { - return "向右转"; - } - }, // 注意这里的枚举值分隔使用, - - SHOOT { - // 实现接口上的方法 - public String getDescription() { - return "射击"; - } - }; // 注意这里的枚举值结束使用; -} \ No newline at end of file diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/MoreAction2.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/MoreAction2.java deleted file mode 100644 index 590d928091..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/MoreAction2.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.jun.plugin.javase.enums; - -public enum MoreAction2 { - TURN_LEFT { - // 实现抽象方法 - public String getDescription() { - return "向左转"; - } - }, // 记得这里的枚举值分隔使用, - - TURN_RIGHT { - // 实现抽象方法 - public String getDescription() { - return "向右转"; - } - }, - - SHOOT { - // 实现抽象方法 - public String getDescription() { - return "射击"; - } - }; // 记得这里的枚举值结束使用; - - // 声明抽象方法 - public abstract String getDescription(); -} \ No newline at end of file diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/MoreActionDemo.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/MoreActionDemo.java deleted file mode 100644 index efc8dca886..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/MoreActionDemo.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jun.plugin.javase.enums; - -public class MoreActionDemo { - public static void main(String[] args) { - for (MoreAction action : MoreAction.values()) { - System.out.printf("%s: %s%n", action, action.getDescription()); - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/MoreActionDemo2.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/MoreActionDemo2.java deleted file mode 100644 index 9d234b2c04..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/MoreActionDemo2.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jun.plugin.javase.enums; - -public class MoreActionDemo2 { - public static void main(String[] args) { - for (MoreAction2 action : MoreAction2.values()) { - System.out.printf("%s: %s%n", action, action.getDescription()); - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/Singleton.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/Singleton.java deleted file mode 100644 index b395974142..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/enums/Singleton.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.jun.plugin.javase.enums; - -public class Singleton { - // 构造函数私有,只限内部调用 - private Singleton() { - }; - - private static Singleton instance = null; - - public static synchronized Singleton getInstance() { - if (instance == null) - instance = new Singleton(); - return instance; - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/fiveday/Array.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/fiveday/Array.java deleted file mode 100644 index 614002ad31..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/fiveday/Array.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.jun.plugin.javase.fiveday; - -public class Array { - public static void main(String[] args) { - - /*int[] arr=new int[5]; - System.out.print("["); - for(int i=0;iarr[j]){ - int temp=arr[i]; - arr[i]=arr[j]; - arr[j]=temp; - } - count++; - } - } - printArrays(arr); - System.out.println(count);*/ - - int[] arr2={12,4,65,87,45,23,2,9,56,3}; - for(int i=0;i=arr.length){ - throw new ArrayIndexOutOfBoundsException("�����±�Խ��"+index); - } - if(index<0){ - throw new FushuException1(index); - } - return arr[index]; - } -} - - - -class FushuException1 extends RuntimeException{ - FushuException1(int index){ - super("�±겻��Ϊ����"+index); - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/ExceptionWork.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/ExceptionWork.java deleted file mode 100644 index 54df517d16..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/ExceptionWork.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.jun.plugin.javase.object; - -public class ExceptionWork { - public static void main(String[] args) { - Computer c1=new Computer(1); - Teacher t1=new Teacher(); - t1.lession(c1); - } -} -class Teacher{ - void lession(Computer comp){ - try{ - comp.run(); - System.out.println("��ʼ�Ͽ�"); - System.exit(0); - }catch(BlueScreen e){ - e.printStackTrace(); - }catch(Crashed e){ - e.printStackTrace(); - }finally{ - System.out.println("���Ի��ˣ�����ϰ"); - } - } - -} -class Computer{ - private int condition=0; - Computer(int condition){ - this.condition=condition; - } - - void setCondition(int condition){ - this.condition=condition; - } - void run(){ - if(condition==0){ - throw new Crashed("����������"); - } - if(condition==1){ - throw new BlueScreen("����������"); - } - if(condition>1){ - System.out.println("������������"); - } - } -} -class BlueScreen extends RuntimeException{ - BlueScreen(String msg){ - super(msg); - } -} -class Crashed extends RuntimeException{ - Crashed(String msg){ - super(msg); - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/ExceptionWork11.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/ExceptionWork11.java deleted file mode 100644 index cbc35d02b5..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/ExceptionWork11.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.jun.plugin.javase.object; - -public class ExceptionWork11 { - public static void main(String[] args) { - Teacher1 t1=new Teacher1("����"); - try{ - t1.prelect(); - }catch(NoPlanException2 e){ - e.printStackTrace(); - System.out.println(e.toString()); - } - } -} - -class Teacher1{ - private String name; - private Computer1 comp; - Teacher1(String name){ - this.name=name; - comp=new Computer1(); - } - public void prelect()throws NoPlanException2{ - try{ - comp.run(); - System.out.println(name+"���Ͽ�"); - }catch(LanPingException2 e){ - System.out.println(e.toString()); - e.printStackTrace(); - comp.reset(); - prelect(); - }catch(MaoYanException2 e){ - e.printStackTrace(); - test(); - throw new NoPlanException2("�γ��޷�����"); - } - } - public void test(){ - System.out.println("����ϰ"); - } -} -class Computer1{ - private int state; - Computer1(){ - - } - public void run() throws LanPingException2,MaoYanException2{ - state=(int)(Math.random()*3+1); - if(state==1) - throw new LanPingException2("������"); - if(state==2) - throw new MaoYanException2("ð����"); - System.out.println("��������"); - } - public void reset(){ - state=0; - System.out.println("��������"); - } -} -class LanPingException2 extends Exception{ - LanPingException2(String msg){ - super(msg); - } -} -class MaoYanException2 extends Exception{ - MaoYanException2(String msg){ - super(msg); - } -} -class NoPlanException2 extends Exception{ - NoPlanException2(String msg){ - super(msg); - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/ExtendsKey.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/ExtendsKey.java deleted file mode 100644 index 31d4dab6e8..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/ExtendsKey.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.jun.plugin.javase.object; - -public class ExtendsKey { - public static void main(String[] args) { -// Son s=new Son(); - - Father f2=new Father(); - - } -} - - -class Father{ - - static Father f1=new Father(); - - Father(){ - System.out.println("���캯��"); - System.out.println(f1); - } - void show(){ - - } -} -/*class Son extends Father{ - int num=8; - Son(){ - System.out.println(num); - num=10; - System.out.println(num); - } - void show(){ - System.out.println("Son����"+"========="+num); - } -}*/ - - diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/Homework.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/Homework.java deleted file mode 100644 index c4e884c2d9..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/Homework.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.jun.plugin.javase.object; - -public class Homework { - public static void main(String[] args) { - new Son("С��",11); - } -} -class Grandpa{ - String name; - int age; - static Son s1=new Son("С��",12); - static Son s2=new Son("С��",12); - static{ - System.out.println("����үү�ľ�̬��"); - } - { - System.out.println("����үү�Ĺ�������"); - } - Grandpa(String name,int age){ - System.out.println("����үү�Ĺ��캯��"); - this.name=name; - this.age=age; - } -} -class Father11 extends Grandpa{ - static Son s1=new Son("С��",12); - static Son s2=new Son("С��",12); - static { - System.out.println("���Ǹ��׵ľ�̬��"); - } - { - System.out.println("���Ǹ��׵Ĺ�������"); - } - Father11(String name,int age){ - super(name,age); - System.out.println("���Ǹ��׵Ĺ��캯��"); - } -} -class Son extends Father11{ - int number=10; - static { - System.out.println("���Ƕ��ӵľ�̬��"); - } - { - System.out.println(number); - System.out.println("���Ƕ��ӵĹ�������"); - } - Son(String name,int age){ - super(name,age); - System.out.println("���Ƕ��ӵĹ��캯��"); - } -} -/*ÿʵ����һ�ζ���ÿ��һ�ι��캯���������������������࣬�ӻ��࿪ʼִ��һ�ι��캯������̬��Ա�ڼ������ʱ���Ѿ�������ϣ� -�˺��ټ��أ����캯��ÿnewһ�ζ���ִ��һ�Σ���������͹��캯�����ǺͶ�����صģ���̬��Ա������أ��ȼ��������е��ִࣨ�����еľ�̬���򣬴Ӹ����ӣ�����Ϊ��Ա������ֵ -���ʵ��������ִ�й����͹��캯�����Ӹ����ӣ�;��̬��Աִֻ��һ��*/ diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/InnerClass.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/InnerClass.java deleted file mode 100644 index ad2fa38c88..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/InnerClass.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.jun.plugin.javase.object; - -public class InnerClass { - public static void main(String[] args) { - /*Outer.Inner o=new Outer().new Inner();//��Ա�ڲ��ࡪ���ڲ��಻��static������ʹ�ô˷������� - o.show(); - Outer o1=new Outer(); - o1.showInner();//�����ڲ���ı���*/ - - - /*Outer.Inner in=new Outer.Inner();//��Ա�ڲ��ࡪ�����ڲ��౻static������ʹ�ô˷������� - in.show();*/ - - //Object o=new Outer().method();//�ֲ��ڲ��� - //System.out.println(o);//�ֲ��ڲ����еķ����ͱ�������������ڸ÷��������ڲ����� - Outer.Inner o1=new Outer().new Inner(); - } -} -class Outer{ - int number=5; - class Inner{ - int number=6; - void show(){ - int number=7; - System.out.println("-----------"+number); - } - } - /* - void showInner(){ - Inner a1=new Inner(); - a1.show();//6 - System.out.println(a1.number);//7 - }*/ - - static{ - System.out.println("�����ⲿ��ľ�̬��"); - } - Outer(){ - System.out.println("�����ⲿ��Ĺ��캯��"); - } - - Object method(){ - class Inner{ - int a=12; - /*static{ - System.out.println("�����ڲ���ľ�̬��"); - }*/ - Inner(){ - System.out.println("�����ڲ���Ĺ��캯��"+"-------a="+a); - } - void show(){ - System.out.println("�ⲿ���еı���number�ǣ�"+number); - System.out.println("�ֲ��ڲ���ķ���"); - } - } - Inner in=new Inner(); - in.show(); - return in; - } -} -//�ڲ���ļ���˳������: - - - diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/InnerClass2.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/InnerClass2.java deleted file mode 100644 index 3bb2187cf1..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/InnerClass2.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.jun.plugin.javase.object; - -public class InnerClass2 { - public static void main(String[] args) { - new Demo11(){ - void show(){ - System.out.println("��д�����෽��"); - } - void show1(){ - System.out.println("������з���"); - } - }.show1(); - } -} -abstract class Demo11{ - abstract void show(); -} -class Outer1{ - void Method(){ - /*new Demo11(){ - void show(){ - System.out.println("��д�����෽��"); - } - void show1(){ - System.out.println("������з���"); - } - }.show1();//���ø������֣���������ʵ��������ȿ��Է��ʸ��෽����Ҳ���Է������෽��������ת�ͣ���̬�� - */ - - /*Demo11 d=new Demo11(){ - void show(){ - System.out.println("��д�����෽��"); - } - void show1(){ - System.out.println("������з���"); - } - };//����һ��������ʵ���������������з���show1�ᱨ�� - d.show(); - d.show1();*/ - } -} - - - diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/IntegerDemo.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/IntegerDemo.java deleted file mode 100644 index 451e7d847a..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/IntegerDemo.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jun.plugin.javase.object; - -public class IntegerDemo { - int a; - Integer b; - void show(){ - System.out.println("a��"+a); - System.out.println("b��"+b); - } - public static void main(String[] args) { - byte b=5; - Byte bb=b; - bb=b; - b=bb; - System.out.println(b+"---------"+bb); - System.out.println(b==bb); - new IntegerDemo().show(); - - - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/Interface.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/Interface.java deleted file mode 100644 index 0b6e310455..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/Interface.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.jun.plugin.javase.object; - -public class Interface { - public static void main(String[] args) { - //useUSB(new Mouse());//��̬�У�ʹ��һ���������ݴ������IJ�ͬ��ʵ�ֲ�ͬ�ķ�����������ʱ�ĸ�ʽ���������ģ�������ij������Ϊ��������ij������ - //Mouse m1=new Mouse(); - //m1.print(); - - new USB(){ - public void print(){ - System.out.println(1); - } - }.print();//ʹ�������ڲ��࣬����ע�Ͳ��ֵȼ� - } - - public static void useUSB(USB u){} -} - -interface USB{ - int a=15; - void print(); -} -/*class Mouse implements USB{ - void show(){ - System.out.println(a); - } - public void print(){ - System.out.println(a); - } -}*/ - diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/Person3.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/Person3.java deleted file mode 100644 index 27f9b7e96b..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/Person3.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.jun.plugin.javase.object; - -import java.util.Arrays; - -public class Person3 { - String name; - int age; - static String contry; - static{ - contry="cq"; - System.out.println("���Ǿ�̬����"); - } - { - System.out.println("���ǹ�������"); - } - Person3(){ - - } - Person3(String name,int age){ - System.out.println("���ǹ��캯��"); - //contry="cd"; - this.name=name; - this.age=age; - } - public void pop(){ - System.out.println(name+","+age+","+contry); - } - public static void speak(){ - System.out.println(contry); - System.out.println("���Ǿ�̬����"); - } - - public String toString() { - return "Person3 [name=" + name + ", age=" + age + "]"; - } - - - public static void main(String[] args) { - System.out.println("========"); - Person3 p1=new Person3("����",20); - p1.pop(); - Person3 p2=new Person3("����",22); - Person3 p3=new Person3("����",22); - p2.pop(); - - - Person3 []arr={p1,p2,p3}; - System.out.println(Arrays.toString(arr)); - - - } - -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/Rectangle.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/Rectangle.java deleted file mode 100644 index 9f5ce86a54..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/Rectangle.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.jun.plugin.javase.object; - -public class Rectangle { - int a; - int b; - - public Rectangle(){ - this.a=5; - this.b=6; - } - - public int area(){ - return a*b; - } - - public static void main(String[] args) { - Rectangle test=new Rectangle(); - System.out.println("������"+test.area()); - - Trectangle test2=new Trectangle(); - test2.a=12; - test2.b=1; - System.out.println("������"+test2.area()); - } -} - - - -class Trectangle extends Rectangle{ - public Trectangle(){ - super();//ֻ���������๹�췽����ĵ�һ�� - super.area(); - } - - public int area(){ - return a*b*10; - } -} - diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/StaticKey.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/StaticKey.java deleted file mode 100644 index a5ce5d4787..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/StaticKey.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.jun.plugin.javase.object; - -public class StaticKey { - public static void main(String[] args) { - System.out.println("============"); - Person1 p1=new Person1("����",22); - //Person1 p2=new Person1("����",21); - //Person1 p3=new Person1("������",23); - p1.pop(); - //p1.speak();//������ʾ�̬����,���׻�����̬��Ա�ͷǾ�̬��Ա��������ʹ�� - //p2.pop(); - //p3.pop(); - Person1.speak();//�������ʾ�̬����,��speak����δ��static���Σ�����ʹ���������� - /*System.out.println("�������:"+p1.contry); - System.out.println("�����:"+Person1.contry);*/ - - - - } -} - -class Person1{ - String name; - int age=40; - static String contry="CN"; - static{ - contry="cq"; - System.out.println("���Ǿ�̬����"); - } - Person1(){ - - } - Person1(String name,int age){ - System.out.println("���ǹ��캯��"); - contry="cd"; - this.name=name; - this.age=age; - } - public void pop(){ - System.out.println(name+","+age+","+contry); - } - public static void speak(){ - //System.out.println(contry); - System.out.println("���Ǿ�̬����"); - } -} - -//ִ��˳�򣺾�̬���򡪡����캯��������̬���������캯���;�̬������ִ��˳��һ���������ݴ�������͵��þ�̬������˳��ͬ����ͬ diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/SuperKey.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/SuperKey.java deleted file mode 100644 index 8b36553e84..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/SuperKey.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.jun.plugin.javase.object; - -public class SuperKey { - public static void main(String[] args) { - ChildClass cc=new ChildClass(); - cc.f(); - } -} -class FatherClass{ - public int value; - public void f(){ - value=10; - System.out.println("����ֵ"+this.value); - } -} -class ChildClass extends FatherClass{ - public int value;//���˼̳и����value�����Լ����ⶨ����һ��value�� - public void f(){ - super.f();//ʹ��������еĸ�������Լ������Լ���f�������ı��������ࣩ��ֵ; - value=200; - System.out.println("����ֵ"+this.value); - System.out.println(value); - System.out.println(super.value);//�Ӹ���̳�����value��ֵ�� - } -} - -/* -superָ���࣬�Ǹ�������� -thisָ�����࣬�����������,ֻ�����ڷǾ�̬�������� -��new����һ������ʱ�������������һ��this�����ã�ָ������� -���new�����Ķ���ʱһ���������Ļ�����ô�������������滹����һ��super���ã�ָ��ǰ����ĸ����� -*/ - - - - - - - - - diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/Test.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/Test.java deleted file mode 100644 index 9634bce467..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/Test.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.jun.plugin.javase.object; - -public class Test { - private String name; - public void setName(String name){ - this.name=name; - } - public void getName(){ - System.out.println("���õ�������"+name); - } - public static void main(String[] args) { - Test test=new Test(); - test.setName("java"); - test.getName(); - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/Test111.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/Test111.java deleted file mode 100644 index 8dd45c6a10..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/Test111.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.jun.plugin.javase.object; - -public class Test111 { - public void test(Bird bird){ - System.out.println(bird.getName()+"�ܹ���"+bird.fly()+"��"); - } - - public static void main(String[] args) { - Test111 test=new Test111(); - test.test(new Bird(){ - public int fly(){ - return 1000; - } - public String getName(){ - return "����"; - } - }); - } -} - - -abstract class Bird { - private String name; - public String getName(){ - return name; - } - public void setName(String name){ - this.name=name; - } - public abstract int fly(); -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/Test2.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/Test2.java deleted file mode 100644 index dad63a8ddb..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/Test2.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.jun.plugin.javase.object; - -import java.util.Arrays; - -public class Test2 { - public static void main(String[] args) { - int a=3; - int b=4; - change(a,b);//��ջ����ִ����ϡ�����ջ - System.out.println("a:"+a); - System.out.println("b:"+b);//���ݵ�ֵ����Ӱ��ԭֵ - - int[] count={1,2,3,4,5}; - change(count);//����counts��count����һ����ַ��ͬʱָ����еĶ��󣬣��ı�������һ����ֵ����һ��Ҳ��ı䣻 - System.out.println("���÷���֮������飺"+Arrays.toString(count));//���õ�ֵ�ı���ԭֵ - } - static void change(int i,int j){ - int temp=i; - i=j; - j=temp; - } - - public static void change(int[] counts){ - counts[0]=6; - System.out.println("count�ĵ�һ������Ԫ���ǣ�"+counts[0]); - } -} -/*��Java�в������ݶ����и����ģ�����˵��ֵ���ݣ������ǽ���������һ���ٽ��д��ݣ������������͵�ֵ�Ǹ��ƣ����������ݽ��в�������˲���ı�ԭֵ�� -��һ�ֽ����ǣ������������ʹ洢��ջ�У������÷�������ʱ������ջ�����ܸı�ԭֵ���Ҳ���ԭֵ���� -����Ĵ����Ǵ��ݵ�ַ���Ƕ�������ã�������ַָ����ڴ��е�ͬһ�����ݣ��ı�������һ���������������仯��*/ - - diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/Test3.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/Test3.java deleted file mode 100644 index 0ab494f133..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/Test3.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.jun.plugin.javase.object; - - - -public class Test3 { - static void show(){ - System.out.println(1); - } - void show(int n){ - - } -} -class TestF extends Test3{ - static void show(){ - System.out.println(2); - }//�����˸��෽������������д???static���εij�Ա���ڷ������У�����ʵ���������ԲŻ������ظ����˵��??? - void show(int n){ - System.out.println(n); - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/Test4.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/Test4.java deleted file mode 100644 index d82b67d5fa..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/Test4.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.jun.plugin.javase.object; - -public class Test4 { - public static void main(String[] args) { - Animal a1=new Cat();//����ת�� - a1.eat(); - - //a1.catchMouse();���� - /*Cat c1=(Cat) a1;//����ת�� - c1.catchMouse();*/ - - /*Dog d1=(Dog)a1; - d1.lookHome();//ͬ�������벻����ִ�б���*/ - - if(a1 instanceof Dog){ - System.out.println(1); - } - - - } -} -abstract class Animal{ - abstract void eat(); -} - -class Cat extends Animal{ - void eat(){ - System.out.println("����"); - } - void catchMouse(){ - System.out.println("ץ����"); - } -} - -class Dog extends Animal{ - void eat(){ - System.out.println("�й�ͷ"); - } - void lookHome(){ - System.out.println("����"); - } -} - -class Pig extends Animal{ - void eat(){ - System.out.println("������"); - } - void gongdi(){ - System.out.println("����"); - } -} - diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/Test6.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/Test6.java deleted file mode 100644 index 2446b7814c..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/Test6.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.jun.plugin.javase.object; - -public class Test6 { - public static void main(String[] args) { - - Outer2.Inner2 o1=new Outer2().new Inner2();//ע�Ͳ����뱾����ͬ�� - o1.show(); - - } -} -class Outer2{ - /*Inner2 in=new Inner2(); - void print(){ - in.show(); - }*/ - - class Inner2{ - int n=12; - void show(){ - System.out.println(n); - } - } -} - - diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/TransferProperty.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/TransferProperty.java deleted file mode 100644 index 01b31133f3..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/TransferProperty.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.jun.plugin.javase.object; - -public class TransferProperty { - int i=47; - public void call(){ - System.out.println("����call��������"); - for(int i=0;i<3;i++){ - System.out.print(i+""); - if(i==2){ - System.out.print("\n"); - } - } - } - public TransferProperty(){ - - } - public static void main(String[] args){ - TransferProperty t1=new TransferProperty(); - TransferProperty t2=new TransferProperty(); - t2.i=60; - System.out.println("��һ��ʵ��������ñ���i�Ľ����"+t1.i++); - t1.call(); - System.out.println("�ڶ���ʵ��������ñ���i�Ľ����"+t2.i); - t2.call(); - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/TryCatch.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/TryCatch.java deleted file mode 100644 index 8c7c130889..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/TryCatch.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.jun.plugin.javase.object; - -public class TryCatch { - public static void main(String[] args) { - int[] arr=new int[3]; - try{ - System.out.println("--------"); - method(arr,-1); - return; - }catch(Exception e){ - e.printStackTrace(); - System.out.println("========="); - //return; -// System.exit(0); - }finally{ - System.out.println("����"); - } - System.out.println("over"); - } - - public static int method(int[] arr,int index){ - if(arr==null){ - throw new NullPointerException("����Ϊ��"); - } - if(index>=arr.length){ - throw new ArrayIndexOutOfBoundsException("�����±�Խ��"+index); - } - if(index<0){ - throw new FushuException(index); - } - return arr[index]; - } -} - -class FushuException extends RuntimeException{ - FushuException(int index){ - super("�±겻��Ϊ����"+index); - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test/Coder.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test/Coder.java deleted file mode 100644 index da3d8cda86..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test/Coder.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.jun.plugin.javase.object.test; - -public class Coder extends Person{ - private String yuyan; - Coder(String name,int age,String yuyan){ - super(name,age); - this.yuyan=yuyan; - } - - void setYuyan(String yuyan){ - this.yuyan=yuyan; - } - String getYuyan(){ - return yuyan; - } - void show(){ - System.out.println("����:"+getName()+","+"����:"+getAge()+","+"����:"+yuyan); - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test/Coffee.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test/Coffee.java deleted file mode 100644 index 93895f31e3..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test/Coffee.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.jun.plugin.javase.object.test; - -public class Coffee extends Drink { - - Coffee(String taste,String capacity,int price){ - super(taste,capacity,price); - } - void showName(){ - System.out.println("����"); - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test/Interface.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test/Interface.java deleted file mode 100644 index 28f1d683ab..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test/Interface.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.jun.plugin.javase.object.test; - -public class Interface { - public static void main(String[] args) { - - - } -} - -interface calculate{ - long fact(int m); - long intPower(int m,int n); - boolean findFactor(int m,int n); -} - -class Intrtface2 implements calculate { - - public long fact(int m){ - if(m<=1){ - return 1; - } - else{ - return m*fact(m-1); - } - } - public long intPower(int m,int n){ - int temp=m; - for(int i=1;i100) - return true; - return false; - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test/Manager.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test/Manager.java deleted file mode 100644 index 94f08c26f9..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test/Manager.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.jun.plugin.javase.object.test; - -public class Manager extends Empolyee{ - private double bonus; - public Manager(String name, String Id, double salary,double bonus) { - super(name, Id, salary); - this.bonus=bonus; - } - - public double getBonus() { - return bonus; - } - - public void setBonus(double bonus) { - this.bonus = bonus; - } - - void work() { - System.out.println("mananger..."); - } - -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test/Milk.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test/Milk.java deleted file mode 100644 index bd4180bd5c..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test/Milk.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.jun.plugin.javase.object.test; - -public class Milk extends Drink{ - - Milk(String taste,String capacity,int price){ - super(taste,capacity,price); - } - - void showName(){ - System.out.println("ţ��"); - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test/Person.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test/Person.java deleted file mode 100644 index 13ec17bfb5..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test/Person.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.jun.plugin.javase.object.test; - -public class Person { - private String name; - private int age; - Person(String name,int age){ - this.name=name; - this.age=age; - } - - void setName(String name){ - this.name=name; - } - String getName(){ - return name; - } - void setAge(int age){ - this.age=age; - } - int getAge(){ - return age; - } - void show(){ - System.out.println(name+","+age); - } - -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test/Student.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test/Student.java deleted file mode 100644 index c3913ba1ec..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test/Student.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.jun.plugin.javase.object.test; - -public class Student { - private String name; - private int age; - private String sex; - private String dept; - - Student(String name,int age){ - this.name=name; - this.age=age; - this.sex="��"; - this.dept="Computer Science"; - } - Student(String name,int age,String sex,String dept){ - this.name=name; - this.age=age; - this.sex=sex; - this.dept=dept; - } - void setName(String name){ - this.name=name; - } - String getName(){ - return name; - } - void setAge(int age){ - this.age=age; - } - int getAge(){ - return age; - } - void setSex(String sex){ - this.sex=sex; - } - String getSex(){ - return sex; - } - void setDept(String dept){ - this.dept=dept; - } - String getDept(){ - return dept; - } - void introduce(Student s1){ - if(s1.getSex()==null||s1.getDept()==null){ - s1.setSex("��"); - s1.setDept("Computer Science"); - } - System.out.println("�ҽ�"+getName()+","+getAge()+"��,�Ա�:"+getSex()+",רҵ:"+getDept()); - } - public String toString() { - return "Student [name=" + name + ", age=" + age + ", sex=" + sex+ ", dept=" + dept + "]"; - } - -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test/Tea.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test/Tea.java deleted file mode 100644 index a394fdb284..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test/Tea.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.jun.plugin.javase.object.test; - -public class Tea extends Drink { - - Tea(String taste,String capacity,int price){ - super(taste,capacity,price); - } - void showName(){ - System.out.println("��"); - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test/Test.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test/Test.java deleted file mode 100644 index aaf2290311..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test/Test.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.jun.plugin.javase.object.test; - - -public class Test { - public static void main(String[] args) { - /*Person p1=new Person("����",21); - p1.show(); - Worker w1=new Worker("����",20,9999); - w1.show(); - Student s1=new Student("����",14,1406101010); - s1.show(); - Coder c1=new Coder("Ǯ��",27,"java"); - c1.show();*/ -// Person p1=null; - /*Person[] arr2=new Person[10]; - for(int i=0;i<10;i++){ - Person p1=new Person("����"+(i+1)+"��",21+i); - arr2[i]=p1; - } - for(int i=0;istuArr[j].getAge()){ - Student temp=stuArr[i]; - stuArr[i]=stuArr[j]; - stuArr[j]=temp; - } - } - System.out.println(stuArr[i].toString()); - }*/ - - /*int[] arr={1,3,2,5,2,7,1,8}; - System.out.println(getElement(arr,7));*/ - - int[] arr2={1,2,3,4,5,6,1}; - System.out.println(getElement(arr2,2)); - - } - - static int getElement(int[] arr,int index){ - if(arr==null){ - throw new NullPointerException("����Ϊ��"); - } - if(index>=arr.length){ - throw new ArrayIndexOutOfBoundsException("�����±�Խ��"+index); - } - return arr[index]; - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test/Triangle.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test/Triangle.java deleted file mode 100644 index b11d21515a..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test/Triangle.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.jun.plugin.javase.object.test; - -public class Triangle extends Shape { - private int longA; - private int wideB; - private int heightC; - - Triangle(int longA,int wideB,int heightC){ - this.longA=longA; - this.wideB=wideB; - this.heightC=heightC; - isTriangle(); - } - boolean isTriangle() { - if((this.longA+this.wideB>this.heightC&&this.longA+this.heightC>this.wideB&&this.wideB+this.heightC>this.longA)&&(this.longA-this.wideB list=new ArrayList(); - list.add("a"); - list.add("b"); - list.add("c"); - int i=(int)(Math.random()*list.size()); - System.out.println("�����������е�Ԫ����"+list.get(i)); - list.remove(2); - System.out.println("ȥ������Ϊ2��Ԫ�غ�"); - for(int j=0;j { - String name; - long id; - public SetUpdateStu(String name,long id){ - this.id=id; - this.name=name; - } - public int compareTo(Object o){ - SetUpdateStu upstu=(SetUpdateStu)o; - int result=id>upstu.id?1:(id==upstu.id?0:-1); - return result; - } - public String getName(){ - return name; - } - public void setName(String name){ - this.name=name; - } - public long getId(){ - return id; - } - public void setId(long id){ - this.id=id; - } - - public static void main(String[] args) { - SetUpdateStu stu1=new SetUpdateStu("��ͬѧ",01011); - SetUpdateStu stu2=new SetUpdateStu("��ͬѧ",01012); - SetUpdateStu stu3=new SetUpdateStu("��ͬѧ",01013); - SetUpdateStu stu4=new SetUpdateStu("��ͬѧ",01014); - TreeSettree=new TreeSet(); - tree.add(stu1); - tree.add(stu2); - tree.add(stu3); - tree.add(stu4); - Iteratorit=tree.iterator(); - System.out.println("�����е�����Ԫ��"); - while(it.hasNext()){ - SetUpdateStu stu=(SetUpdateStu)it.next(); - System.out.println(stu.getId()+" "+stu.getName()); - } - it=tree.headSet(stu2).iterator(); - System.out.println("��ȡǰ�沿�ֵļ���"); - while(it.hasNext()){ - SetUpdateStu stu=(SetUpdateStu)it.next(); - System.out.println(stu.getId()+" "+stu.getName()); - } - it=tree.subSet(stu2,stu3).iterator(); - System.out.println("��ȡ�м䲿�ֵļ���"); - while(it.hasNext()){ - SetUpdateStu stu=(SetUpdateStu)it.next(); - System.out.println(stu.getId()+" "+stu.getName()); - } - - /*long a=01011; - System.out.println((int)a);*/ - - } - -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test2/ThreadTest.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test2/ThreadTest.java deleted file mode 100644 index 06552dee2e..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test2/ThreadTest.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.jun.plugin.javase.object.test2; - -public class ThreadTest{ - public static void main(String[] args) { - ThreadDemo t1=new ThreadDemo(); - ThreadDemo t2=new ThreadDemo(); - t1.start(); -// t2.start(); - for(int i=0;i<10;i++){ - int[] arr=new int[3]; - //System.out.println(arr[9]); - System.out.println(i+Thread.currentThread().getName()); - } - } -} - -class ThreadDemo extends Thread{ -// private String name="������"; -// ThreadDemo(String name){ -// this.name=name; -// super(name); -// } - public void run(){ - int[] arr=new int[3]; - //System.out.println(arr[3]);ִ���쳣���̲߳���Ӱ�쵽�����̣߳��統ǰ�̺߳�main�߳� - for(int i=0;i<10;i++){ - System.out.println(getName()+"-------"+i+"-------"+Thread.currentThread().getName()); - } - } -} - diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test2/ThreadTest1.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test2/ThreadTest1.java deleted file mode 100644 index 14251900c5..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test2/ThreadTest1.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.jun.plugin.javase.object.test2; -/*package com.ky26.object.test2; - -public class ThreadTest1 { - public static void main(String[] args) { - - Ticket t1=new Ticket(); - Ticket t2=new Ticket(); - Ticket t3=new Ticket(); - Ticket t4=new Ticket(); - t1.start(); - t2.start(); - t3.start(); - t4.start(); - - TicketImpl ticket=new TicketImpl(); - Thread t11=new Thread(ticket); - Thread t22=new Thread(ticket); - t11.start(); - t22.start(); - } -} -class Ticket extends Thread{ - private int num=100; - public void run(){ - while(true){ - if(num>0){ - System.out.println(Thread.currentThread().getName()+"---sale---"+num--); - } - } - } -}//���ַ�ʽʵ�ֶ��߳� -class TicketImpl implements Runnable{ - private int num=100; - boolean flag=true; - public void run(){ - while(true){ - if(flag){ - synchronized(""){ - if(num>0){ - try{ - Thread.sleep(10); - }catch(Exception e){ - e.printStackTrace(); - } - System.out.println(Thread.currentThread().getName()+"---object---"+num--); - } - } - } - else{ - show(); - } - } - } - public synchronized void show(){ - if(num>0){ - try{ - Thread.sleep(10); - }catch(Exception e){ - e.printStackTrace(); - } - System.out.println(Thread.currentThread().getName()+"---function---"+num--); - } - } -} -*/ \ No newline at end of file diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test2/ThreadTest4.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test2/ThreadTest4.java deleted file mode 100644 index eac41e134f..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test2/ThreadTest4.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.jun.plugin.javase.object.test2; - -public class ThreadTest4 { -public static void main(String[] args) { - /*TicketImpl ticket=new TicketImpl(); - System.out.println("ticket"+ticket); - Thread t1=new Thread(ticket); - Thread t2=new Thread(ticket); - t1.start(); - try { - Thread.sleep(10); - } catch (InterruptedException e) { - e.printStackTrace(); - } - ticket.flag=false; - t2.start();*///����ʾ�� - - Test1 a=new Test1(true); - Test1 b=new Test1(false); - Thread t1=new Thread(a); - Thread t2=new Thread(b); - t1.start(); - t2.start(); - new String("aaa"); - - - } -} - -class Test1 implements Runnable{ - private boolean flag; - Test1(boolean flag){ - this.flag=flag; - } - @Override - public void run() { - // TODO Auto-generated method stub - if(flag){ -// while(true){ - synchronized (MyLock.locka) { - System.out.println(Thread.currentThread().getName()+"if locka..."); - synchronized (MyLock.lockb) { - System.out.println(Thread.currentThread().getName()+"if lockb..."); - } - } -// } - }else{ -// while(true){ - synchronized (MyLock.lockb) { - System.out.println(Thread.currentThread().getName()+"else lockb..."); - synchronized (MyLock.locka) { - System.out.println(Thread.currentThread().getName()+"else locka..."); - } - } -// } - } - } -} -class MyLock{ - public static final Object locka=new Object(); - public static final Object lockb=new Object(); -} - - -/*class TicketImpl implements Runnable{ - private static int num=1000; - Object obj=new Object(); - boolean flag=true; - public void run(){ - if(flag){ - while(true){ - synchronized(obj){ - show(); - } - } - }else{ - while(true){ - show(); - } - } - } - public synchronized void show(){ - synchronized (obj) { - if(num>0){ - try { - Thread.sleep(10); - } catch (InterruptedException e) { - e.printStackTrace(); - } - System.out.println(Thread.currentThread().getName()+"---fun---num="+num--); - } - } - } -}*/ diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test2/_IntegerDemo.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test2/_IntegerDemo.java deleted file mode 100644 index 2b56e41022..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/object/test2/_IntegerDemo.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.jun.plugin.javase.object.test2; - -public class _IntegerDemo { - public static void main(String[] args) { - int a=12; - Integer b; - b=a; - a=b;//����һ����ʽ�ͱ���ʽ����λ�ûᱨ�� - System.out.println(b==a); - System.out.println(Integer.toString(a)); - - String str=Integer.toString(456); - String str1=Integer.toBinaryString(456); - String str2=Integer.toHexString(456); - String str3=Integer.toOctalString(456); - System.out.println("ʮ����"+str); - System.out.println("������"+str1); - System.out.println("ʮ������"+str2); - System.out.println("�˽���"+str3); - - String strArr[]={"12","22","32","42"}; - int sum=0; - for(int i=0;i=1;i--){ - j=(j+1)*2; - System.out.println(j); - }*/ - System.out.println(getNum(1)); - } - - static int getNum(int n){ - if(n==10){ - return 1; - } - else{ - return (getNum(n+1)+1)*2; - } - } -} -//i��������j����ʣ�������������ÿ���һ���һ�������һ��ʣһ��->��һ���*2+1����ǰһ�� diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/oneday/HomeWork.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/oneday/HomeWork.java deleted file mode 100644 index 1fe9bb5818..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/oneday/HomeWork.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.jun.plugin.javase.oneday; - -public class HomeWork { - public static void main(String[] args) { - for(int man=0;man<=12;man++){ - for(int woman=0;woman<=18;woman++){ - for(int child=0;child<=36-man-woman;child++){ - if(3*man+2*woman+child/2==36&&man+woman+child==36&&child%2==0){ - System.out.println("����"+man+"Ů��"+woman+"С��"+child); - } - } - } - } - System.out.println(); - - int count=0; - for(int cock=0;cock<=20;cock++){ - for(int hen=0;hen<=33;hen++){ - for(int chick=0;chick<=200;chick++){ - if(cock*5+hen*3+chick/2==100&&cock+hen+chick==100&&chick%2==0){ - System.out.println("����"+cock+"ĸ��"+hen+"С��"+chick); - } - } - } - count++; - } - System.out.println("���д���Ϊ"+count); - System.out.println(); - /* - int a=378; - System.out.println(a/100+" "+a/10%10+" "+a%10);*/ - - - for(int i=100;i<1000;i++){ - int a=i/100; - int b=i/10%10; - int c=i%10; - if(a*a*a+b*b*b+c*c*c==i){ - System.out.println("ˮ�ɻ���"+i); - } - } - - - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/oneday/Shop.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/oneday/Shop.java deleted file mode 100644 index 033c168c7e..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/oneday/Shop.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.jun.plugin.javase.oneday; - -public class Shop { - public static void main(String[] args){ - String name="��ˢ"; - int price=12,amount=2; - - System.out.println("��Ʒ��"+" "+"����"+" "+"����"+" "+"�ܼ�"); - System.out.println(name+" "+price+" "+amount+" "+price*amount); - - /*System.out.println("��ˢ"+" "+"10Ԫ"+" "+"1"+" "+"10Ԫ"); - System.out.println("����"+" "+"20"+" "+"2"+" "+"40Ԫ"); - System.out.println("ë��"+" "+"20"+" "+"1"+" "+"20");*/ - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/oneday/Star.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/oneday/Star.java deleted file mode 100644 index 0b651621cb..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/oneday/Star.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.jun.plugin.javase.oneday; - -public class Star { - public static void main(String[] args) { - for(int i=0;i<6;i++){ - for(int j=0;j<6;j++){ - System.out.print("*"); - } - System.out.println(); - } - - - for(int i=1;i<=6;i++){ - for(int j=1;j<=6-i;j++){ - System.out.print(" "); - }//����ո� - for(int k=1;k<=6;k++){ - System.out.print("*"); - }//������� - System.out.println(); - } -// j<=6-i��ʼ�Ŀո��������һ�п�5�����ڶ��п�4���������п�3�����Դ����� - - for(int i=0;i<5;i++){ - for(int j=0;j<=5-i;j++){ - System.out.print(" "); - } - - for(int k=0;k<=i*2;k++){ - System.out.print("*"); - } - System.out.println(); - } - - for(int i=0;i<=5;i++){ - for(int j=0;j<=5-i;j++){ - System.out.print("*"); - } - - for(int k=0;k<=i;k++){ - System.out.print(" "); - } - System.out.println(); - - } - - - for(int i=0;i<=3;i++){ - for(int j=0;j<=i;j++){ - for(int k=0;k<=j;k++){ - for(int m=0;m<=k;m++){ - for(int n=0;n<=m;n++){ - System.out.print("$"); - } - } - } - } - System.out.println(" "); - } - - - for(int i=0;i<=5;i++){ - for(int j=0;j<=5-i;j++){ - System.out.print(" "); - } - for(int k=0;k<=i*2;k++){ - System.out.print("*"); - } - System.out.println(" "); - } - for(int i=0;i<=4;i++){ - for(int j=0;j<=i+1;j++){ - System.out.print(" "); - } - for(int k=8;k>=i*2;k--){ - System.out.print("*"); - } - System.out.println(" "); - } - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/oneday/Sum.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/oneday/Sum.java deleted file mode 100644 index 8687153160..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/oneday/Sum.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.jun.plugin.javase.oneday; - -public class Sum { - public static void main(String[] args){ - int a=120; - int b=180; - -// System.out.println(a>b?"a��":"b��"); - - if(a>b){ - System.out.println("a��"); - } - else{ - System.out.println("b��"); - } - } - -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/oneday/Sum2.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/oneday/Sum2.java deleted file mode 100644 index ca8db261db..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/oneday/Sum2.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.jun.plugin.javase.oneday; - -import java.util.Scanner; - -public class Sum2 { - public static void main(String[] args) { - - /*Scanner scan=new Scanner(System.in); - System.out.println("���������֣�"); - int week=scan.nextInt();*/ - int week=5; - - /*if(week==1){ - System.out.println("����һ"); - } - else if(week==2){ - System.out.println("���ڶ�"); - } - else if(week==3){ - System.out.println("������"); - } - else if(week==4){ - System.out.println("������"); - } - else if(week==5){ - System.out.println("������"); - } - else if(week==6){ - System.out.println("������"); - } - else { - System.out.println("������"); - }*/ - - switch (week){ - case 1: - System.out.println("����1"); - break; - case 2: - System.out.println("����2"); - break; - case 3: - System.out.println("����3"); - break; - case 4: - System.out.println("����4"); - break; - case 5: - System.out.println("����5"); - break; - case 6: - System.out.println("����6"); - break; - case 7: - System.out.println("������"); - } - - int x=1; - int sum=0; - while(x<=100){ - sum+=x; - x++; - } - System.out.println(sum); - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/reflectTest/Example_01.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/reflectTest/Example_01.java deleted file mode 100644 index cdd3a8633d..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/reflectTest/Example_01.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.jun.plugin.javase.reflectTest; - -public class Example_01 { - public static void main(String[] args) { - - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/reflectTest/ReflectTest.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/reflectTest/ReflectTest.java deleted file mode 100644 index 59af93b17b..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/reflectTest/ReflectTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.jun.plugin.javase.reflectTest; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; - -public class ReflectTest { - public static void main(String[] args) { - try { - Class cls=Class.forName("com.yc.reflectTest.User"); - Field[] field=cls.getDeclaredFields(); - for(Field f:field){ - System.out.println(f); - } - System.out.println("------------"); - Method[] method=cls.getDeclaredMethods(); - for(Method m:method){ - System.out.println(m); - } - } catch (ClassNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/reflectTest/User.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/reflectTest/User.java deleted file mode 100644 index 76186b8ff1..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/reflectTest/User.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.jun.plugin.javase.reflectTest; - -public class User { - private int age; - private String name; - private String sex; - int hight; - int weight; - public int getAge() { - return age; - } - public void setAge(int age) { - this.age = age; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public String getSex() { - return sex; - } - public void setSex(String sex) { - this.sex = sex; - } - public int getHight() { - return hight; - } - public void setHight(int hight) { - this.hight = hight; - } - public int getWeight() { - return weight; - } - public void setWeight(int weight) { - this.weight = weight; - } - public User() { - super(); - } - public User(int age, String name, String sex, int hight, int weight) { - super(); - this.age = age; - this.name = name; - this.sex = sex; - this.hight = hight; - this.weight = weight; - } - @Override - public String toString() { - return "User [age=" + age + ", name=" + name + ", sex=" + sex - + ", hight=" + hight + ", weight=" + weight + "]"; - } - - -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/sixday/Array.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/sixday/Array.java deleted file mode 100644 index 3d15fa77f9..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/sixday/Array.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.jun.plugin.javase.sixday; - -import java.util.Arrays; - -public class Array { - public static void main(String[] args) { - int[] arr={2,45,21,6,8,94,100,8,4,123,54,76,90}; - int l=arr.length; - int[] arr1=Arrays.copyOfRange(arr,0,l); - - int temp=0; - for(int i=0;iarr[i+1]){ - temp=arr[i]; - arr[i]=arr[i+1]; - arr[i+1]=temp; - } - } - - for(int j=0;jmax){ - max=arr[i]; - } - } - for(int i=0;ii;j--){ - if(arr1[j]max){ - max=array[i]; - } - } - for(int i=0;i1){ - if(isIn[index]){ - countNum++; - if(countNum==3){ - countNum = 0; - isIn[index] = false; - inCount--; - } - } - index++; - if(index==n) - index = 0; - } - for(int i=0;iarray[j+1]){ - int temp=array[j]; - array[j]=array[j+1]; - array[j+1]=temp; - } - - } - } - printArrays(array); - } - -/* public void showArray(int[] array){ - for(int i:array){ - System.out.print("<"+i); - } - System.out.println(); - }*/ - - static long factorial(int n){ - if(n==1){ - return 1; - } - else{ - return n*factorial(n-1); - } - } - - static void isPalin(int number){ - int[] array=new int[5]; - for(int i=0;i=0;j--){ - if(j==0){ - System.out.print(a[j]); - } - else{ - System.out.print(a[j]+","); - } - } - } - - static void printArrays(int[] array){ - System.out.print("["); - for(int i=0;i0){ - String temp=arr[i]; - arr[i]=arr[j]; - arr[j]=temp; - } - } - } - for(int i=0;i=90?"����":(n>=60?"����":"������")); - - - System.out.println("=======a+aa+aaa+...��ֵ========"); - int dig=7,amou=5,sum=0,m=7;//mΪ�̶�������ֵ��amou����Ҫ�󵽵����ֳ��� - for(int i=1;i<=amou;i++){ - sum+=dig; - dig=dig*10+m; - System.out.println(sum); - } - - - System.out.println("=======���ڵݹ顪���׳�========"); - System.out.println(factorial(5)); - - - System.out.println("=======do-while========"); - int b=100; - do{ - System.out.print(","+b); - b--; - }while(b>=60);//ִ�����֮������while�е��������ٴ�ִ����䣬������������ѭ�� - - - /*System.out.println("=======���Լ������С������======="); - int a=40,b=60; - int max=a>b?a:b; - int min=2; - int mul=1; - for(int i=1;i<=max;i++){ - if(a%min==0&&b%min==0){ - a=a/min; - b=b/min; - mul*=min; - } - else{ - min++; - } - } - System.out.println("���Լ����"+mul); - System.out.print("��С��������"+mul*a*b);*/ - - - /*System.out.println("=======���Լ������С������-��������======="); - System.out.println("���Լ��"+mul(40,60)); - System.out.println("���Լ��"+mul(40,10,60)); - - System.out.println("=======��������������======"); - int count=0; - for(int i=1;i<5;i++){ - for(int j=1;j<5;j++){ - for(int k=1;k<5;k++){ - if(i!=j&&i!=k&&j!=k){ - System.out.print(i*100+j*10+k+","); - count++; - } - } - } - } - System.out.println(); - System.out.println("��"+count+"��");*/ - - - - /*double m=1,n=2,sum=0; - for(int i=0;i<20;i++){ - double j=m; - double k=n; - sum=sum+(n/m); - n=k+j; - m=k; - } - System.out.println(sum);//2/1��3/2��5/3��8/5��13/8��21/13...*/ - - /*long sum=0; - for(int i=1;i<=20;i++){ - sum+=factorial(i); - } - System.out.println(sum);//1+2!+3!+...+20!*/ - - - /*System.out.println("======������ֵ��������������������Ӧ�±�====="); - int[] arr={12,21,15,3,4,13,43}; - CommonMethod.bubbleSort(arr); - CommonMethod.printArrays(arr); - int n=12; - int index=0; - for(int i=0;i=arr[i]&&n=arr[arr.length-1]){ - index=arr.length; - break; - } - else if(n2){ - return sum(n-1)+sum(n-2); - } - else{ - return 1; - } - } - - static long factorial(int n){ - if(n<=1){ - return 1; - } - else{ - return n*factorial(n-1); - } - } - - static int mul(int m,int n){ - int max=m>n?m:n; - int min=2; - int mul=1; - for(int i=1;i<=max;i++){ - if(m%min==0&&n%min==0){ - m=m/min; - n=n/min; - mul*=min; - } - else{ - min++; - } - } - return (mul*m*n); - } - - static int mul(int m,int n,int k){ - int temp=m>n?m:n; - int max=temp>k?temp:k; - int min=2; - int mul=1; - for(int i=1;i<=max;i++){ - if(m%min==0&&n%min==0&&k%min==0){ - m=m/min; - n=n/min; - k=k/min; - mul*=min; - } - else{ - min++; - } - } - return (mul*m*n*k); - } - - - - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/threeday/Area.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/threeday/Area.java deleted file mode 100644 index 409887684a..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/threeday/Area.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.jun.plugin.javase.threeday; - -//import java.util.Scanner; - -public class Area { - public static void main(String[] args) { - - System.out.println("Բ�������"+area(4)); - System.out.println("�����ε������"+area(4,5)); - - - - - double x=area(3,4,5); - if(x!=0){ - System.out.println("�����ε�����ǣ�"+x); - } - else{ - System.out.println("����������"); - } - - - } - - - - static double area(int r){ - return Math.PI*(r*r); - } - static int area(int a,int b){ - return a*b; - } - static double area(int a,int b,int c){ - double p=(a+b+c)/2; - - if(a+b<=c||a+c<=b||b+c<=a||a-b>=c||a-c>=b||b-c>=a){ - return 0; - } - else{ - return Math.sqrt(p*(p-a)*(p-b)*(p-c)); - } - } - - -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/threeday/HomeWork.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/threeday/HomeWork.java deleted file mode 100644 index 8e493a5eb9..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/threeday/HomeWork.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.jun.plugin.javase.threeday; - -public class HomeWork { - public static void main(String[] args) { - for(int i=0;i<=5;i++){ - for(int j=0;j<5-i;j++){ - System.out.print("*"); - } - System.out.println(); - } - - for(int i=1;i<=5;i++){ - for(int j=0;j<=5-i;j++){ - System.out.print(6-i); - } - System.out.println(); - } - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/threeday/Mouth.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/threeday/Mouth.java deleted file mode 100644 index 5b05ba3e92..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/threeday/Mouth.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.jun.plugin.javase.threeday; - -public class Mouth { - public static void main(String[] args) { - int mouth=4; - - - if(mouth==3||mouth==4||mouth==5){ - System.out.println("����"); - } - else if(mouth==6||mouth==7||mouth==8){ - System.out.println("�ļ�"); - } - else if(mouth==9||mouth==10||mouth==11){ - System.out.println("�^"); - } - else if(mouth==12||mouth==1||mouth==2){ - System.out.println("����"); - } - else{ - System.out.println("������1-12֮����·�"); - } - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/threeday/Test.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/threeday/Test.java deleted file mode 100644 index 82ab001bf1..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/threeday/Test.java +++ /dev/null @@ -1,269 +0,0 @@ -package com.jun.plugin.javase.threeday; - -import java.util.Scanner; - -public class Test { - public static void main(String[] args) { - Scanner scan=new Scanner(System.in); - - /*int n=-3; - int c=0; - String s=""; - while(n!=0){ - c+=n&1; - s=(n&1)+s; - n=n>>>1; - } - System.out.print("�����Ķ������ǣ�"+s);//���һ�����Ķ����ƣ��������� - System.out.println(); - System.out.println("1�ĸ����ǣ�"+c);//���1�ĸ��� -*/ - - /*System.out.println("test"); - System.out.println(5>>1);//5���ɶ����ƣ�����һλ����λ��0�����õ���������תΪʮ���� - System.out.println(-5>>1); - System.out.println(5>>>1); - System.out.println(-5>>>1);*/ - - - /*int m=12; - String s=""; - while(m!=0){ - s=(m&1)+s; - m=m>>>1; - } - System.out.println(s);*/ - - /*int a=3,b=5; - a=a^b; - b=a^b; - System.out.println(b);*/ - /*System.out.println(a); - b=a^b; - System.out.println(b); - a=a^b; - System.out.println(a); - System.out.println(b);*/ - - /*double a=3,b=4,c=5; - double s=(a+b+c)/2; - System.out.println(Math.sqrt(s*(s-a)*(s-b)*(s-c))); - - for(int i=0;i<=10;i++){ - for(int j=0;j<=10;j++){ - System.out.println(i+"====="+j); - if(j==5){ - System.out.println(i+"-----"+j); - continue; - } - } - }*/ - - /*int x=0; - for(System.out.println("a");x<3;System.out.println("b")){ - for(System.out.println("M");x<3;System.out.println("N")){ - for(System.out.println("K");x<3;System.out.println("H")){ - System.out.println("X"); - x++; - } - } - }*/ - - /* int m=0; - for(int i=0;i<=9;i++){ - for(int j=0;j<=i;j++){ - for(int k=0;k<=j;k++){ - System.out.println(k); - m++; - } - } - } - System.out.println(m);*/ - - - - /*int a=10; - int b=100; - int m=0; - System.out.println(m=(a>b?a:b));*/ - - /*int a=23,b=0; - - for(int i=0;i<=a+1;i++){ - a=a/2; - b=a%2; - System.out.println(a+","+b); - }*/ - - /*int num=23; - int count=0; - for(int i=0;i<=num;i++){ - num=num>>1; - if(num>>1!=0){ - count++; - } - } - - System.out.println(count);*/ - - /*int n=-1; - int count = 0; - int com = 1; - while(com <= n){ - if((n&com) != 0) - count++; - com = com<<1; - } - System.out.println(count); - - System.out.println((-5)%2);*/ - - - /*int a=-3; - int count=0; - while(a!=0){ - if((a&1)!=0){ - count++; - } - a=a>>>1; - } - System.out.println(count); - - System.out.println(a&1);*/ - - - /*int n=-1; - int c=0; - int c1=0; - while(n != 0){ - if((n&1)==1){ - ++c; - }else{ - c1++; - } - n>>>=1; - } - System.out.println("1�ĸ���Ϊ"+c+"----"+"0�ĸ���Ϊ"+c1);*/ - - /*int n=23;//10111 - int c=0; - while(n != 0){ - if(n%2 !=0){ - c++; - } - n/=2; - } - System.out.println(c);//ֻ�����������Ķ������м���1 -*/ - - - /*if(a%2==0){ - b++; - } - else{ - c++; - } - - System.out.println(b); - System.out.println(c);*/ - -/* for(int i=2;i<=100;i++){ - boolean t=true; - for(int j=2;j0){ - t=n%10; - if (t==0) - nn=0; - else - nn=nn*10+t; - n/=10; - } - - System.out.println(nn); - - - - int te=0,newN=1,old=1; - for(int i=0;i<10;i++){ - te=newN; - newN=old+newN; - old=te; - - System.out.print(" "+newN); - }//���1 1 2 3 5 8 -*/ - - - /*System.out.print("������ֵ��"); - int n =scan.nextInt(); - if(n>9){ - System.out.println("��������"); - return; - } - System.out.print("�������ۼ�������"); - int c =scan.nextInt(); - int sum=0; - int d=n; - for(int i=1;i<=c;i++){ - System.out.print(n+"+"); - sum=sum+n; - n=n*10+d; - } - System.out.print("="+sum); - System.out.println();*///�ۼ� - - - System.out.print("�����������"); - int count =scan.nextInt(); - double height=100,sumHeight=100; - for(int i=1;i=c||a-c>=b||b-c>=a){ - System.out.println("����������"); - } - else{ - System.out.println("���Ϊ"+Math.sqrt(p*(p-a)*(p-b)*(p-c))); - } - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/threeday/work.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/threeday/work.java deleted file mode 100644 index 7103723838..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/threeday/work.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.jun.plugin.javase.threeday; - -import java.util.Scanner; - -public class work { - public static void main(String[] args) { - Scanner scan=new Scanner(System.in); -// ��ϰ�����������������ʽ�� -// 8 /** -// * ***** -// * **** -// * *** -// * ** -// * * -// */ -// /** -// * 55555 -// * 4444 -// * 333 -// * 22 -// * 1 -// */ - /* - - System.out.print("���������:"); - int m=scan.nextInt(); - for(int i=1;i<=m;i++){ - for(int j=i;j<=m;j++){ - System.out.print("*"); -// System.out.print(6-i); - } - System.out.println(); - } - for(int k=1;k<=m;k++){ - for(int n=m;n>=k;n--){ - System.out.print(m+1-k); - } - System.out.println(); - } - */ - - //��s=a+aa+aaa+aaaa...��ֵ������a��һ�����֡�����������Ϊ1234=1+11+111+1111�����������ʽ������������������һ������a����ֵ��С����һ�������ۼӵ����� -// Scanner scan=new Scanner(System.in); - - /*System.out.print("������a��ֵ��"); - int a =scan.nextInt(); - System.out.print("�������ۼ�������"); - int count =scan.nextInt(); - int n=0; - int sum=0; - String string=""; - for(int i=1;i<=count;i++){ - n=n*10+a; - if(i Math.sqrt(i)) - if(number!=i){ - string=string+i+"*"; - }else if(number==i){ - string=string+i; - } - break; - } - } - number=number/i; - }while(number!=1) ; - System.out.println(n+"="+string);*/ - - } - -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/twoday/HomeWork.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/twoday/HomeWork.java deleted file mode 100644 index 3982a84ee7..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/twoday/HomeWork.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.jun.plugin.javase.twoday; - -import java.util.Scanner; - -public class HomeWork { - public static void main(String[] args) { - - int m=(int)(Math.random()*100); -// System.out.println(m); - while(true){ - Scanner scan=new Scanner(System.in); - System.out.println("���������֣�"); - int a=scan.nextInt(); - - if(a>m){ - System.out.println("�������"); - } - else if(a==m){ - System.out.println("�����"); - break; - } - else{ - System.out.println("����С��"); - } - } - - - - - - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/twoday/Practice.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/twoday/Practice.java deleted file mode 100644 index 85cb7c2307..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/twoday/Practice.java +++ /dev/null @@ -1,125 +0,0 @@ -package com.jun.plugin.javase.twoday; -import java.util.Scanner; - -public class Practice { - public static void main(String[] args) { - - - /*char c1=0+'0'; - char c2=0+'A'; - char c3=0+'a'; - System.out.println(c1+" "+c2+" "+c3);*/ - - /*for(int i=0;i<=61;i++){ - if(i<10){ - System.out.print((char)(i+'0')); - if(i==9){ - System.out.println(); - } - } - else if(i<36){ - System.out.print((char)((i-10)+'A')); - if(i==35){ - System.out.println(); - } - } - else { - System.out.print((char)((i-36)+'a')); - } - }*/ - - /*int a=5,b=2,c=9; - - int temp=a>b?a:b; - - int max=temp>c?temp:c; - - System.out.println(max);*/ - - - /*Scanner scana=new Scanner(System.in); - System.out.println("����������a��"); - int a=scana.nextInt(); - - Scanner scanb=new Scanner(System.in); - System.out.println("����������b��"); - int b=scanb.nextInt(); - - Scanner scanc=new Scanner(System.in); - System.out.println("����������c��"); - int c=scanc.nextInt(); - - int t=a>b?a:b; - int m=t>c?t:c; - System.out.println(m);*/ - - /*int a=1,b; - b=(a++)+(++a)+(a++)+a; - System.out.println(a+","+b);*/ - - - int day=46; - -// System.out.println("����"+day%7); - - while(day<=7){ - System.out.println("����"+day); - break; - } - - while(day>7){ - int m=day/7; - int n=day%7; - System.out.println("��"+m+"��"+","+"����"+n); - break; - } - - int a=10; - char d=(char)a; -// byte e=(byte)129;���-127 -// char e='��'ֻ�ܴ��һ������; - char b='A'; - int c=(int)b;//ת��֮����ʾA��ASCII�� - System.out.println(d); - - - - /*while(day%7==0){ - System.out.println("������"); - break; - } - while(day%7==1){ - System.out.println("����1"); - break; - } - while(day%7==2){ - System.out.println("����2"); - break; - } - while(day%7==3){ - System.out.println("����3"); - break; - } - while(day%7==4){ - System.out.println("����4"); - break; - } - while(day%7==5){ - System.out.println("����5"); - break; - } - while(day%7==6){ - System.out.println("����6"); - break; - }*/ - - - /*System.out.println(com(9,6,4)); */ - } - - /*static int com(int a,int b,int c){ - int t=a>b?a:b; - int m=t>c?t:c; - return m; - }*/ -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/twoday/Star.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/twoday/Star.java deleted file mode 100644 index 3ebbc686f0..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/twoday/Star.java +++ /dev/null @@ -1,136 +0,0 @@ -package com.jun.plugin.javase.twoday; - -public class Star { - public static void main(String[] args) { - for(int i=0;i<5;i++){ - for(int j=0;j<=i;j++){ - System.out.print("*"); - } - System.out.println(" "); - } - System.out.println("======================="); - - for(int i=0;i<=5;i++){ - for(int j=0;j<5-i;j++){ - System.out.print(" "); - } - for(int k=0;k=i*2;k--){ - System.out.print("*"); - } - System.out.println(" "); - } - - System.out.println("======================="); - for(int i=1;i<=4;i++){ - for(int j=1;j<=4-i;j++){ - System.out.print(" "); - } - for(int k=1;k<=i*2-1;k++){ - System.out.print("#"); - } - System.out.println(); - } - for(int i=1;i<=3;i++){ - for(int j=1;j<=i;j++){ - System.out.print(" "); - } - for(int k=5;k>=i*2-1;k--){ - System.out.print("#"); - } - System.out.println(" "); - } - - System.out.println("======================="); - - for(int i=1;i<=5;i++){ - for(int j=0;j<=i;j++){ - System.out.print(" "); - } - for(int k=0;k<5-i;k++){ - System.out.print("*"); - } - System.out.println(); - } - - System.out.println("======================="); - - for(int i=0;i<=5;i++){ - for(int j=0;j<=i;j++){ - System.out.print(" "); - } - for(int k=0;k<11-2*i;k++){ - System.out.print("*"); - } - System.out.println(); - } - - - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/twoday/Sum.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/twoday/Sum.java deleted file mode 100644 index 0516acb818..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/twoday/Sum.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.jun.plugin.javase.twoday; - -public class Sum { - public static void main(String[] args) { - - double sum = 0; - for(int i=1; i<=100; i++){ - sum += 1.0/i;//��Χ����뷶ΧС�����㣬��ΧС���Զ�תΪ��Χ��ģ�double>int - } - System.out.println("sum = " + sum); - - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/twoday/Test.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/twoday/Test.java deleted file mode 100644 index 7f7954edb6..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/twoday/Test.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.jun.plugin.javase.twoday; - -public class Test { - public static void main(String[] args) { - System.out.println(1.0/5); - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/DiceTest.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/DiceTest.java deleted file mode 100644 index f84061c527..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/DiceTest.java +++ /dev/null @@ -1,23 +0,0 @@ - package com.jun.plugin.javase.winterHomeWork; - -public class DiceTest { - public static void main(String[] args) { - Dice d1=new Dice(); - int a=d1.throwDice(); - int b=d1.throwDice(); - if(a+b==7) { - System.out.println("��Ӯ��"); - } - else { - System.out.println("������"); - } - } -} -class Dice{ - private int count; - public int throwDice() { - this.count=(int)(Math.random()*6+1); - System.out.println(this.count); - return count; - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Exercise5/StudentTest.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Exercise5/StudentTest.java deleted file mode 100644 index cb04be7a58..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Exercise5/StudentTest.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.jun.plugin.javase.winterHomeWork.Exercise5; - -public class StudentTest { - public static void main(String[] args) { - Student s1=new Student(); - Student s2=new Student(); - Student s3=new Student(); - Student.showCount(); - Student s4=new Student(1,"zs","nv","5��"); - Student s5=new Student(2,"zs","nv","6��"); - Student s6=new Student(3,"zs","nv","7��"); - Student.showCount(); - s1.show(); - s2.show(); - s3.show(); - s4.show(); - s5.show(); - s6.show(); - } -} -class Student{ - private int sno; - private String name; - private String sex; - private String clazz; - static int count; - Student(){ - count++; - } - Student(int sno,String name,String sex,String clazz){ - this.sno=sno; - this.name=name; - this.sex=sex; - this.clazz=clazz; - count++; - } - public int getSno() { - return sno; - } - public void setSno(int sno) { - this.sno = sno; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public String getSex() { - return sex; - } - public void setSex(String sex) { - this.sex = sex; - } - public String getClazz() { - return clazz; - } - public void setClazz(String clazz) { - this.clazz = clazz; - } - public void show() { - System.out.println("ѧ��:"+getSno()+"������:"+getName()+"���Ա�:"+getSex()+"���༶:"+getClazz()); - } - public static void showCount() { - System.out.println("�Ѿ�����"+Student.count+"������"); - } - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Exercise5/TeacherTest.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Exercise5/TeacherTest.java deleted file mode 100644 index a1776f4468..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Exercise5/TeacherTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.jun.plugin.javase.winterHomeWork.Exercise5; - -public class TeacherTest { - public static void main(String[] args) { - Teacher.setCoefficient(1.2); - Teacher t1=new Teacher(10); - Teacher t2=new Teacher(20); - System.out.println(t1.courseCompute()); - System.out.println(t2.courseCompute()); - } -} -class Teacher{ - private double amount; - private static double coefficient; - Teacher(){ - - } - Teacher(double amount){ - this.amount = amount; - } - public double getAmount() { - return amount; - } - public void setAmount(double amount) { - this.amount = amount; - } - public static double getCoefficient() { - return coefficient; - } - public static void setCoefficient(double coefficient) { - Teacher.coefficient = coefficient; - } - double courseCompute() { - return (getAmount()*getCoefficient()); - } - -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Exercise6/AnimalTest.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Exercise6/AnimalTest.java deleted file mode 100644 index fc21bbf1c6..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Exercise6/AnimalTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.jun.plugin.javase.winterHomeWork.Exercise6; - -public class AnimalTest { - public static void main(String[] args) { - Rabbit r1=new Rabbit(); - r1.eat(); - r1.sleep(); - Tiger t1=new Tiger(); - t1.eat(); - t1.sleep(); - } -} -class Animal{ - public void eat(){ - - } - public void sleep() { - System.out.println("˯����"); - } -} -class Rabbit extends Animal{ - public void eat(){ - System.out.println("�ҳԲ�"); - } -} -class Tiger extends Animal{ - public void eat(){ - System.out.println("�ҳ���"); - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Exercise6/FamilyTest.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Exercise6/FamilyTest.java deleted file mode 100644 index 4f6b3dc0e2..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Exercise6/FamilyTest.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.jun.plugin.javase.winterHomeWork.Exercise6; - -public class FamilyTest { - -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Exercise6/InstrumentTest.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Exercise6/InstrumentTest.java deleted file mode 100644 index bba8789d49..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Exercise6/InstrumentTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.jun.plugin.javase.winterHomeWork.Exercise6; - -public class InstrumentTest { - public static void main(String[] args) { - - } -} -class Instrument{ - void play(){ - - } -} -class Piano extends Instrument{ - void play(){ - System.out.println("���ٵ���"); - } -} -class Violin extends Instrument{ - void play(){ - System.out.println("С���ٵ���"); - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Exercise7/BiologicalTest.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Exercise7/BiologicalTest.java deleted file mode 100644 index d5e3ec3eee..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Exercise7/BiologicalTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.jun.plugin.javase.winterHomeWork.Exercise7; - -public class BiologicalTest { - -} -interface Biological{ - public abstract void breathe(); -} -interface Animal extends Biological{ - public abstract void sleep(); - public abstract void eat(); -} -interface People extends Animal{ - public abstract void thinking(); - public abstract void study(); -} - -class Person implements People{ - - public void sleep() { - System.out.println("����˯��"); - } - - public void eat() { - System.out.println("���ܳԷ�"); - } - - public void breathe() { - System.out.println("���ܺ���"); - } - - public void thinking() { - System.out.println("����˼��"); - } - - public void study() { - System.out.println("����ѧϰ"); - } - -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Exercise8/ExceptionTest.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Exercise8/ExceptionTest.java deleted file mode 100644 index d65b1ec2ad..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Exercise8/ExceptionTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.jun.plugin.javase.winterHomeWork.Exercise8; - -public class ExceptionTest { - public static void main(String[] args) throws MyException { - threwException(); - } - static void threwException() throws MyException{ - int num=(int)(Math.random()*100); - if(num>50) { - System.out.println(num); - throw new MyException("��ֵ����50"); - } - else { - System.out.println(num); - System.out.println("����С��50�����׳��쳣"); - } - } -} -class MyException extends Exception{ - public MyException(String ExceptionMes){ - super(ExceptionMes); - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Exercise8/RiverTest.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Exercise8/RiverTest.java deleted file mode 100644 index fc21bea9f4..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Exercise8/RiverTest.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.jun.plugin.javase.winterHomeWork.Exercise8; - -public class RiverTest { - public static void main(String[] args) { - Changjiang c1=new Changjiang(); - c1.setWarning(100); - c1.setWaterline(110); - /*try { - c1.flow(); - } catch (ChangjiangException e) { - e.printStackTrace(); - }*/ - Huanghe h1=new Huanghe(); - h1.setWarning(100); - h1.setWaterline(110); - /*try { - h1.flow(); - } catch (HuangheException e) { - e.printStackTrace(); - }*/ - - Admin a1=new Admin(); - a1.watch(h1); - a1.watch(c1); - } -} -abstract class River { - static int warning; - static int waterline; - - public static int getWarning() { - return warning; - } - public static void setWarning(int warning) { - River.warning = warning; - } - public static int getWaterline() { - return waterline; - } - public static void setWaterline(int waterline) { - River.waterline = waterline; - } - public abstract void flow() throws HuangheException,ChangjiangException; -} -class Changjiang extends River{ - public void flow() throws ChangjiangException{ - if(getWaterline()>getWarning()+9){ - throw new ChangjiangException("����������"); - } - else { - System.out.println("�����������·�ԶӰ�̿վ���Ω�����������"); - } - } -} -class Huanghe extends River{ - public void flow() throws HuangheException{ - if(getWaterline()>getWarning()+5){ - throw new HuangheException("�ƺӾ�����"); - } - else { - System.out.println("�ƺ��������ƺ�֮ˮ������"); - } - } -} -class Admin{ - void watch(River river) { - try { - river.flow(); - System.out.println("ˮλ����"); - }catch(ChangjiangException e) { - e.printStackTrace(); - System.out.println("����������"); - drain(); - }catch(HuangheException e) { - e.printStackTrace(); - System.out.println("�ƺӾ�����"); - drain(); - } - } - void drain() { - System.out.println("���ˮ"); - } -} -class HuangheException extends Exception{ - HuangheException(String mes){ - super(mes); - } -} -class ChangjiangException extends Exception{ - ChangjiangException(String mes){ - super(mes); - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Exercise9/StringTest2.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Exercise9/StringTest2.java deleted file mode 100644 index 467f91ae51..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Exercise9/StringTest2.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.jun.plugin.javase.winterHomeWork.Exercise9; - -import java.util.Scanner; - -public class StringTest2 { - public static void main(String[] args) { - Scanner scan=new Scanner(System.in); - System.out.println("��������ĸ��"); - String name=scan.next(); - checkString(name); - } - static void checkString(String name) { - System.out.println("���������ĸ���ǣ�"+name); - String rege="[a-zA-Z]+"; - String reget="\\p{Upper}+[a-zA-Z]*"; - if(!name.matches(rege)) { - System.out.println("����������������ĸ����"); - } - else if(!name.matches(reget)){ - System.out.println("��һ����ĸ���Ǵ�д��ĸ"); - } - else if(name.matches(rege)&&name.matches(reget)) { - char[] arr=name.toCharArray(); - int count=0; - for(int i=0;inum) { - System.out.println("�´��ˣ����²�"); - }else if(number=0;i--) { - ss+=s.substring(i, i+1); - } - System.out.println(ss); - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Exercise9/WorkSystemTest.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Exercise9/WorkSystemTest.java deleted file mode 100644 index 8b3e9b9fa2..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Exercise9/WorkSystemTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.jun.plugin.javase.winterHomeWork.Exercise9; - -import java.util.Scanner; - -public class WorkSystemTest { - public static void main(String[] args) { - Scanner scan=new Scanner(System.in); - System.out.println("�������ļ���"); - String name=scan.next(); - checkName(name); - Scanner scant=new Scanner(System.in); - System.out.println("����������"); - String email=scant.next(); - checkemail(email); - } - static void checkName(String name) { - String rege=".+\\.java"; - if(name.matches(rege)) { - System.out.println("���ύ���ļ��ǣ�"+name); - }else { - System.out.println("�ļ�����׺����,��ȷ�Ϻ��ύ"); - } - } - static void checkemail(String email) { - String rege=".+@[a-zA-Z]+\\.com"; - if(email.matches(rege)) { - System.out.println("��������ǣ�"+email); - }else { - System.out.println("�����ַ����"); - } - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/GoodsTest.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/GoodsTest.java deleted file mode 100644 index f96a1b0cc9..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/GoodsTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.jun.plugin.javase.winterHomeWork; - -public class GoodsTest { - public static void main(String[] args) { - Goods g1=new Goods(1,"����",23,"����"); - Goods g2=new Goods(2,"����",24,"����"); - Goods g3=new Goods(3,"����",21,"����"); - Goods g4=new Goods(4,"����",29,"����"); - Goods g5=new Goods(5,"����",5,"����"); - Goods g6=new Goods(6,"����",3,"����"); - Goods g7=new Goods(7,"����",67,"����"); - Goods g8=new Goods(8,"����",23,"����"); - Goods g9=new Goods(9,"����",13,"����"); - Goods g10=new Goods(10,"����",88,"����"); - Goods[] arr= {g1,g2,g3,g4,g5,g6,g7,g8,g9,g10}; - Goods.printArr(Goods.sortGoods(arr)); - - } -} -class Goods{ - private int id; - private String name; - private int price; - private String place; - Goods(){ - - } - Goods(int id,String name,int price,String place){ - this.id=id; - this.name=name; - this.price=price; - this.place=place; - } - int getPrice() { - return this.price; - } - int getId() { - return this.id; - } - String getName() { - return this.name; - } - String getPlace() { - return this.place; - } - - public static Goods[] sortGoods(Goods[] arr) { - for(int i=0;iarr[j].getPrice()) { - Goods temp=arr[i]; - arr[i]=arr[j]; - arr[j]=temp; - } - } - } - return arr; - } - - - static void printArr(Goods[] array) { - System.out.print("{"); - for(int i=0;i=25) { - return true; - } - else { - return false; - } - } -} diff --git a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Test.java b/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Test.java deleted file mode 100644 index b798a4f42b..0000000000 --- a/jun_java_plugins/jun_javase/src/main/java/com/jun/plugin/javase/winterHomeWork/Test.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.jun.plugin.javase.winterHomeWork; - -public class Test { - public static void main(String[] args) { - int[] arr={1,2,3,4,5,6,7,8,9}; - int number=(int)(Math.random()*8+1); - boolean flag=false; - for(int i=0;i - - 4.0.0 - io.github.wujun728 - jun_jbpm - 1.0 - war - - - UTF-8 - - - - - junit - junit - 3.8.1 - test - - - - - mysql - mysql-connector-java - 5.1.40 - - - - jun_jbpm - - diff --git a/jun_java_plugins/jun_jbpm/src/main/java/jbpm.cfg.xml b/jun_java_plugins/jun_jbpm/src/main/java/jbpm.cfg.xml deleted file mode 100644 index ff26254d61..0000000000 --- a/jun_java_plugins/jun_jbpm/src/main/java/jbpm.cfg.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/jun_java_plugins/jun_jbpm/src/main/java/jbpm.hibernate.cfg.xml b/jun_java_plugins/jun_jbpm/src/main/java/jbpm.hibernate.cfg.xml deleted file mode 100644 index ff9fc634bd..0000000000 --- a/jun_java_plugins/jun_jbpm/src/main/java/jbpm.hibernate.cfg.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - org.hibernate.dialect.MySQL5InnoDBDialect - com.mysql.jdbc.Driver - jdbc:mysql:///jbpm4?useUnicode=true&characterEncoding=utf8 - root - mysqladmin - create-drop - true - - - - - - - - - diff --git a/jun_java_plugins/jun_jbpm/src/main/java/jbpm.mail.properties b/jun_java_plugins/jun_jbpm/src/main/java/jbpm.mail.properties deleted file mode 100644 index 320c113180..0000000000 --- a/jun_java_plugins/jun_jbpm/src/main/java/jbpm.mail.properties +++ /dev/null @@ -1,3 +0,0 @@ -mail.smtp.host localhost -mail.smtp.port 2525 -mail.from noreply@jbpm.org \ No newline at end of file diff --git a/jun_java_plugins/jun_jbpm/src/main/java/jbpm.mail.templates.xml b/jun_java_plugins/jun_jbpm/src/main/java/jbpm.mail.templates.xml deleted file mode 100644 index edb07661fe..0000000000 --- a/jun_java_plugins/jun_jbpm/src/main/java/jbpm.mail.templates.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - ${task.name} - - - - - - ${task.name} - - - - - - - - rectify ${newspaper} - ${newspaper} ${date} ${details} - - - - - diff --git a/jun_java_plugins/jun_jbpm/src/main/java/leave.jpdl.xml b/jun_java_plugins/jun_jbpm/src/main/java/leave.jpdl.xml deleted file mode 100644 index a979a3912b..0000000000 --- a/jun_java_plugins/jun_jbpm/src/main/java/leave.jpdl.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_jbpm/src/main/java/leave.png b/jun_java_plugins/jun_jbpm/src/main/java/leave.png deleted file mode 100644 index ebbb8b3375..0000000000 Binary files a/jun_java_plugins/jun_jbpm/src/main/java/leave.png and /dev/null differ diff --git a/jun_java_plugins/jun_jbpm/src/main/java/leave.zip b/jun_java_plugins/jun_jbpm/src/main/java/leave.zip deleted file mode 100644 index 0386bafb8d..0000000000 Binary files a/jun_java_plugins/jun_jbpm/src/main/java/leave.zip and /dev/null differ diff --git a/jun_java_plugins/jun_jbpm/src/main/java/logging.properties b/jun_java_plugins/jun_jbpm/src/main/java/logging.properties deleted file mode 100644 index 6672c9f3eb..0000000000 --- a/jun_java_plugins/jun_jbpm/src/main/java/logging.properties +++ /dev/null @@ -1,18 +0,0 @@ -handlers= java.util.logging.ConsoleHandler -redirect.commons.logging = enabled - -java.util.logging.ConsoleHandler.level = FINEST -java.util.logging.ConsoleHandler.formatter = org.jbpm.internal.log.LogFormatter - -org.jbpm.level=FINE -# org.jbpm.pvm.internal.tx.level=FINE -# org.jbpm.pvm.internal.wire.level=FINE -# org.jbpm.pvm.internal.util.level=FINE - -org.hibernate.level=INFO -org.hibernate.cfg.SettingsFactory.level=SEVERE -org.hibernate.cfg.HbmBinder.level=SEVERE -org.hibernate.SQL.level=FINEST -org.hibernate.type.level=FINEST -# org.hibernate.tool.hbm2ddl.SchemaExport.level=FINEST -# org.hibernate.transaction.level=FINEST \ No newline at end of file diff --git a/jun_java_plugins/jun_jbpm/src/main/webapp/boss.jsp b/jun_java_plugins/jun_jbpm/src/main/webapp/boss.jsp deleted file mode 100644 index 29cc7a88dd..0000000000 --- a/jun_java_plugins/jun_jbpm/src/main/webapp/boss.jsp +++ /dev/null @@ -1,29 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=UTF-8" - pageEncoding="UTF-8"%> -<%@page import="org.jbpm.api.*,org.jbpm.api.task.*" %> -<% - ProcessEngine processEngine = Configuration.getProcessEngine(); - TaskService taskService = processEngine.getTaskService(); - String taskId = request.getParameter("id"); - Task task = taskService.getTask(taskId); -%> - - - - -Insert title here - - -
- 老板审核 -
- - 申请人:<%=taskService.getVariable(taskId, "owner") %>
- 请假时间:<%=taskService.getVariable(taskId, "day") %>
- 请假原因:<%=taskService.getVariable(taskId, "reason") %>
- -
-
- - - \ No newline at end of file diff --git a/jun_java_plugins/jun_jbpm/src/main/webapp/checkLogin.jsp b/jun_java_plugins/jun_jbpm/src/main/webapp/checkLogin.jsp deleted file mode 100644 index 36705940e2..0000000000 --- a/jun_java_plugins/jun_jbpm/src/main/webapp/checkLogin.jsp +++ /dev/null @@ -1,5 +0,0 @@ -<% - if (session.getAttribute("username") == null) { - response.sendRedirect("login.jsp"); - } -%> \ No newline at end of file diff --git a/jun_java_plugins/jun_jbpm/src/main/webapp/deploy.jsp b/jun_java_plugins/jun_jbpm/src/main/webapp/deploy.jsp deleted file mode 100644 index 96f6fbb68f..0000000000 --- a/jun_java_plugins/jun_jbpm/src/main/webapp/deploy.jsp +++ /dev/null @@ -1,13 +0,0 @@ -<%@page import="java.util.*,org.jbpm.api.*,java.util.zip.*"%> -<% - ProcessEngine processEngine = Configuration.getProcessEngine(); - RepositoryService repositoryService = processEngine - .getRepositoryService(); - - //repositoryService.createDeployment().addResourceFromClasspath("leave.jpdl.xml").deploy(); - ZipInputStream zis = new ZipInputStream(this.getClass() - .getResourceAsStream("/leave.zip")); - repositoryService.createDeployment() - .addResourcesFromZipInputStream(zis).deploy(); - response.sendRedirect("index.jsp"); -%> \ No newline at end of file diff --git a/jun_java_plugins/jun_jbpm/src/main/webapp/doLogin.jsp b/jun_java_plugins/jun_jbpm/src/main/webapp/doLogin.jsp deleted file mode 100644 index 85896b099a..0000000000 --- a/jun_java_plugins/jun_jbpm/src/main/webapp/doLogin.jsp +++ /dev/null @@ -1,5 +0,0 @@ - -<% - session.setAttribute("username", request.getParameter("username")); - response.sendRedirect("index.jsp"); -%> \ No newline at end of file diff --git a/jun_java_plugins/jun_jbpm/src/main/webapp/index.jsp b/jun_java_plugins/jun_jbpm/src/main/webapp/index.jsp deleted file mode 100644 index 5b993736f0..0000000000 --- a/jun_java_plugins/jun_jbpm/src/main/webapp/index.jsp +++ /dev/null @@ -1,105 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=UTF-8"%> -<%@include file="/checkLogin.jsp" %> -<%@page import="java.util.*,org.jbpm.api.*,org.jbpm.api.task.*" %> -<% -ProcessEngine processEngine = Configuration.getProcessEngine(); -RepositoryService repositoryService = processEngine.getRepositoryService(); -ExecutionService executionService = processEngine.getExecutionService(); -TaskService taskService = processEngine.getTaskService(); - -String username = (String) session.getAttribute("username"); - -List pdList = repositoryService.createProcessDefinitionQuery().list(); -List piList = executionService.createProcessInstanceQuery().list(); -List taskList = taskService.findPersonalTasks(username); -%> - - - - - index - - - 发布新流程 [username: <%=username %>]登陆 - - - - - - - - - - - - -<% - for (ProcessDefinition pd : pdList) { -%> - - - - - - -<% - } -%> - -
流程定义
idnameversion 
<%=pd.getId() %><%=pd.getName() %><%=pd.getVersion() %> - remove -  |  - start -
- - - - - - - - - - - - -<% - for (ProcessInstance pi : piList) { -%> - - - - - - -<% - } -%> - -
流程实例
idactivitystate 
<%=pi.getId() %><%=pi.findActiveActivityNames() %><%=pi.getState() %>view
- - - - - - - - - - - -<% - for (Task task : taskList) { -%> - - - - - -<% - } -%> - -
待办任务
idname 
<%=task.getId() %><%=task.getName() %>view
- - diff --git a/jun_java_plugins/jun_jbpm/src/main/webapp/leave.png b/jun_java_plugins/jun_jbpm/src/main/webapp/leave.png deleted file mode 100644 index ebbb8b3375..0000000000 Binary files a/jun_java_plugins/jun_jbpm/src/main/webapp/leave.png and /dev/null differ diff --git a/jun_java_plugins/jun_jbpm/src/main/webapp/login.jsp b/jun_java_plugins/jun_jbpm/src/main/webapp/login.jsp deleted file mode 100644 index 21da94abfe..0000000000 --- a/jun_java_plugins/jun_jbpm/src/main/webapp/login.jsp +++ /dev/null @@ -1,19 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=UTF-8" - pageEncoding="UTF-8"%> - - - - -Insert title here - - -
- 登陆 -
- 用户名:
- -
-
- - - \ No newline at end of file diff --git a/jun_java_plugins/jun_jbpm/src/main/webapp/manager.jsp b/jun_java_plugins/jun_jbpm/src/main/webapp/manager.jsp deleted file mode 100644 index 4224ac4372..0000000000 --- a/jun_java_plugins/jun_jbpm/src/main/webapp/manager.jsp +++ /dev/null @@ -1,29 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=UTF-8" - pageEncoding="UTF-8"%> -<%@page import="org.jbpm.api.*,org.jbpm.api.task.*" %> -<% - ProcessEngine processEngine = Configuration.getProcessEngine(); - TaskService taskService = processEngine.getTaskService(); - String taskId = request.getParameter("id"); - Task task = taskService.getTask(taskId); -%> - - - - -Insert title here - - -
- 经理审核 -
- - 申请人:<%=taskService.getVariable(taskId, "owner") %>
- 请假时间:<%=taskService.getVariable(taskId, "day") %>
- 请假原因:<%=taskService.getVariable(taskId, "reason") %>
- -
-
- - - \ No newline at end of file diff --git a/jun_java_plugins/jun_jbpm/src/main/webapp/pic.jsp b/jun_java_plugins/jun_jbpm/src/main/webapp/pic.jsp deleted file mode 100644 index e54f175578..0000000000 --- a/jun_java_plugins/jun_jbpm/src/main/webapp/pic.jsp +++ /dev/null @@ -1,22 +0,0 @@ -<%@page import="org.jbpm.api.*,java.io.*"%> -<% - ProcessEngine processEngine = Configuration.getProcessEngine(); - RepositoryService repositoryService = processEngine - .getRepositoryService(); - ExecutionService executionService = processEngine - .getExecutionService(); - String id = request.getParameter("id"); - ProcessInstance processInstance = executionService - .findProcessInstanceById(id); - String processDefinitionId = processInstance - .getProcessDefinitionId(); - ProcessDefinition processDefinition = repositoryService - .createProcessDefinitionQuery().processDefinitionId( - processDefinitionId).uniqueResult(); - InputStream inputStream = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(),"leave.png"); - byte[] b = new byte[1024]; - int len = -1; - while ((len = inputStream.read(b, 0, 1024)) != -1) { - response.getOutputStream().write(b, 0, len); - } -%> \ No newline at end of file diff --git a/jun_java_plugins/jun_jbpm/src/main/webapp/remove.jsp b/jun_java_plugins/jun_jbpm/src/main/webapp/remove.jsp deleted file mode 100644 index 91abf852ae..0000000000 --- a/jun_java_plugins/jun_jbpm/src/main/webapp/remove.jsp +++ /dev/null @@ -1,8 +0,0 @@ -<%@page import="java.util.*,org.jbpm.api.*" %> -<% - ProcessEngine processEngine = Configuration.getProcessEngine(); - RepositoryService repositoryService = processEngine.getRepositoryService(); - - repositoryService.deleteDeploymentCascade(request.getParameter("id")); - response.sendRedirect("index.jsp"); -%> \ No newline at end of file diff --git a/jun_java_plugins/jun_jbpm/src/main/webapp/request.jsp b/jun_java_plugins/jun_jbpm/src/main/webapp/request.jsp deleted file mode 100644 index 74b70be62b..0000000000 --- a/jun_java_plugins/jun_jbpm/src/main/webapp/request.jsp +++ /dev/null @@ -1,22 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=UTF-8" - pageEncoding="UTF-8"%> - - - - -Insert title here - - -
- 申请 -
- - 申请人:
- 请假时间:
- 请假原因:
- -
-
- - - \ No newline at end of file diff --git a/jun_java_plugins/jun_jbpm/src/main/webapp/start.jsp b/jun_java_plugins/jun_jbpm/src/main/webapp/start.jsp deleted file mode 100644 index 92eaf839f3..0000000000 --- a/jun_java_plugins/jun_jbpm/src/main/webapp/start.jsp +++ /dev/null @@ -1,11 +0,0 @@ -<%@page import="java.util.*,org.jbpm.api.*,java.util.*"%> -<% - ProcessEngine processEngine = Configuration.getProcessEngine(); - ExecutionService executionService = processEngine - .getExecutionService(); - Map map = new HashMap(); - map.put("owner", session.getAttribute("username")); - executionService.startProcessInstanceById(request - .getParameter("id"), map); - response.sendRedirect("index.jsp"); -%> \ No newline at end of file diff --git a/jun_java_plugins/jun_jbpm/src/main/webapp/submit.jsp b/jun_java_plugins/jun_jbpm/src/main/webapp/submit.jsp deleted file mode 100644 index 3a5f7e584d..0000000000 --- a/jun_java_plugins/jun_jbpm/src/main/webapp/submit.jsp +++ /dev/null @@ -1,16 +0,0 @@ -<%@page import="java.util.*,org.jbpm.api.*"%> -<% - ProcessEngine processEngine = Configuration.getProcessEngine(); - TaskService taskService = processEngine.getTaskService(); - - String taskId = request.getParameter("taskId"); - String owner = request.getParameter("owner"); - int day = Integer.parseInt(request.getParameter("day")); - String reason = request.getParameter("reason"); - - Map map = new HashMap(); - map.put("day", day); - map.put("reason", reason); - taskService.completeTask(taskId, map); - response.sendRedirect("index.jsp"); -%> \ No newline at end of file diff --git a/jun_java_plugins/jun_jbpm/src/main/webapp/submit_boss.jsp b/jun_java_plugins/jun_jbpm/src/main/webapp/submit_boss.jsp deleted file mode 100644 index cd485127d5..0000000000 --- a/jun_java_plugins/jun_jbpm/src/main/webapp/submit_boss.jsp +++ /dev/null @@ -1,9 +0,0 @@ -<%@page import="java.util.*,org.jbpm.api.*"%> -<% - ProcessEngine processEngine = Configuration.getProcessEngine(); - TaskService taskService = processEngine.getTaskService(); - - String taskId = request.getParameter("taskId"); - taskService.completeTask(taskId); - response.sendRedirect("index.jsp"); -%> \ No newline at end of file diff --git a/jun_java_plugins/jun_jbpm/src/main/webapp/submit_manager.jsp b/jun_java_plugins/jun_jbpm/src/main/webapp/submit_manager.jsp deleted file mode 100644 index ddc4e6f9c0..0000000000 --- a/jun_java_plugins/jun_jbpm/src/main/webapp/submit_manager.jsp +++ /dev/null @@ -1,12 +0,0 @@ -<%@page contentType="text/html;charset=UTF-8" %> -<%@page import="java.util.*,org.jbpm.api.*"%> -<% - ProcessEngine processEngine = Configuration.getProcessEngine(); - TaskService taskService = processEngine.getTaskService(); - - String taskId = request.getParameter("taskId"); - String result = request.getParameter("result"); - result = new String(result.getBytes("ISO-8859-1"), "UTF-8"); - taskService.completeTask(taskId, result); - response.sendRedirect("index.jsp"); -%> \ No newline at end of file diff --git a/jun_java_plugins/jun_jbpm/src/main/webapp/view.jsp b/jun_java_plugins/jun_jbpm/src/main/webapp/view.jsp deleted file mode 100644 index c192c077b5..0000000000 --- a/jun_java_plugins/jun_jbpm/src/main/webapp/view.jsp +++ /dev/null @@ -1,24 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=UTF-8" - pageEncoding="UTF-8"%> -<%@page import="org.jbpm.api.*,java.util.*,org.jbpm.api.model.*" %> -<% - String id = request.getParameter("id"); - ProcessEngine processEngine = Configuration.getProcessEngine(); - RepositoryService repositoryService = processEngine.getRepositoryService(); - ExecutionService executionService = processEngine.getExecutionService(); - ProcessInstance processInstance = executionService.findProcessInstanceById(id); - Set activityNames = processInstance.findActiveActivityNames(); - - ActivityCoordinates ac = repositoryService.getActivityCoordinates(processInstance.getProcessDefinitionId(),activityNames.iterator().next()); -%> - - - - -Insert title here - - - -
- - \ No newline at end of file diff --git a/jun_java_plugins/jun_jdbc/pom.xml b/jun_java_plugins/jun_jdbc/pom.xml deleted file mode 100644 index 1f39807019..0000000000 --- a/jun_java_plugins/jun_jdbc/pom.xml +++ /dev/null @@ -1,88 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_jdbc - 1.0 - war - - - UTF-8 - 1.8 - 1.8 - - - - - io.github.wujun728 - jun_datasource - 1.0 - - - - commons-beanutils - commons-beanutils - 1.9.4 - - - org.apache.commons - commons-collections4 - 4.4 - - - commons-logging - commons-logging - 1.2 - - - log4j - log4j - 1.2.17 - - - - - junit - junit - 4.13 - test - - - - - - mysql - mysql-connector-java - 5.1.40 - - - - com.oracle - ojdbc6 - 11.2.0.3 - - - - - - jun_jdbc - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.0 - - 1.8 - 1.8 - - - - - diff --git a/jun_java_plugins/jun_jdbc/src/main/java/c3p0-config.xml b/jun_java_plugins/jun_jdbc/src/main/java/c3p0-config.xml deleted file mode 100644 index 2fd4117b80..0000000000 --- a/jun_java_plugins/jun_jdbc/src/main/java/c3p0-config.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - jdbc:mysql://localhost:3306/test1 - com.mysql.jdbc.Driver - root - 1234 - - 3 - - 10 - - 2 - - 10 - - - - jdbc:mysql://localhost:3306/test2 - com.mysql.jdbc.Driver - root - 1234 - 3 - 10 - 2 - 10 - - - diff --git a/jun_java_plugins/jun_jdbc/src/main/java/com/jun/plugin/jdbc/bean/User.java b/jun_java_plugins/jun_jdbc/src/main/java/com/jun/plugin/jdbc/bean/User.java deleted file mode 100644 index 4d28bcd60f..0000000000 --- a/jun_java_plugins/jun_jdbc/src/main/java/com/jun/plugin/jdbc/bean/User.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.jun.plugin.jdbc.bean; - -public class User { - private int id; - private String name; - private String pass; - private String gender; - private int age; - public int getId() { - return id; - } - public void setId(int id) { - this.id = id; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public String getPass() { - return pass; - } - public void setPass(String pass) { - this.pass = pass; - } - public String getGender() { - return gender; - } - public void setGender(String gender) { - this.gender = gender; - } - public int getAge() { - return age; - } - public void setAge(int age) { - this.age = age; - } - public User() { - super(); - // TODO Auto-generated constructor stub - } - public User(int id, String name, String pass, String gender, int age) { - super(); - this.id = id; - this.name = name; - this.pass = pass; - this.gender = gender; - this.age = age; - } - @Override - public String toString() { - return "User [id=" + id + ", name=" + name + ", pass=" + pass - + ", gender=" + gender + ", age=" + age + "]"; - } - - - -} diff --git a/jun_java_plugins/jun_jdbc/src/main/java/com/jun/plugin/jdbc/jdbc/ResultHandler.java b/jun_java_plugins/jun_jdbc/src/main/java/com/jun/plugin/jdbc/jdbc/ResultHandler.java deleted file mode 100644 index b6b5960b56..0000000000 --- a/jun_java_plugins/jun_jdbc/src/main/java/com/jun/plugin/jdbc/jdbc/ResultHandler.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.jun.plugin.jdbc.jdbc; - -import java.sql.SQLException; - -/** - * 结果的处理 - * - * @author Wujun - * - */ -public interface ResultHandler{ - - T doHandle(DataRow rs) throws SQLException; -} diff --git a/jun_java_plugins/jun_jdbc/src/main/java/com/jun/plugin/jdbc/jdbc/test/Test.java b/jun_java_plugins/jun_jdbc/src/main/java/com/jun/plugin/jdbc/jdbc/test/Test.java deleted file mode 100644 index e33759d750..0000000000 --- a/jun_java_plugins/jun_jdbc/src/main/java/com/jun/plugin/jdbc/jdbc/test/Test.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.jun.plugin.jdbc.jdbc.test; - -import java.sql.*; -import java.util.List; - -public class Test { - - public static void main(String[] args) { - try { - MemberDbControl mdb = new MemberDbControl(); - Member m = new Member(); - m.setBirthDay(new java.util.Date()); - m.setCountNum(100); - m.setGender("女"); - m.setUname("王八"); - m.setMno("m111100"); - m.setTelephone("13838388383"); - int rs = mdb.addMember(m); - System.out.println(rs > 0 ? "创建成功!" : "操作失败!"); - - List members = mdb.findAll(); - if (members.isEmpty()) { - System.out.println("没有查询到数据"); - } else { - for (Member member : members) { - member.print(); - } - } - System.out.println(); - // 查询积分大于等于400分的会员 - members = mdb.findMemerByCountNum(400); - if (members.isEmpty()) { - System.out.println("没有查询到数据"); - } else { - for (Member member : members) { - member.print(); - } - } - // 把所有会员的积分归零 - mdb.clearCountNum(); - - m = mdb.getMemberById(1); - System.out.println(m.getUname()); - - System.out.println("总会员数:"+mdb.getTotalMemeber()); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } catch (SQLException e) { - e.printStackTrace(); - } - } -} diff --git a/jun_java_plugins/jun_jdbc/src/main/java/com/jun/plugin/jdbc/jdbc2/JdbcUtil.java b/jun_java_plugins/jun_jdbc/src/main/java/com/jun/plugin/jdbc/jdbc2/JdbcUtil.java deleted file mode 100644 index b39e7e01b9..0000000000 --- a/jun_java_plugins/jun_jdbc/src/main/java/com/jun/plugin/jdbc/jdbc2/JdbcUtil.java +++ /dev/null @@ -1,1234 +0,0 @@ -package com.jun.plugin.jdbc.jdbc2; - -import java.io.IOException; -import java.io.InputStream; -import java.sql.Blob; -import java.sql.Clob; -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.Driver; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Properties; - -import org.apache.log4j.Logger; - -import com.jun.plugin.datasource.DataSourceUtil; - -public final class JdbcUtil { - - private static String DBDRIVER = ""; - private static String DBURL = ""; - private static String DBUSER = ""; - private static String DBPASSWORD = ""; - - private static Connection conn = null; - private static ResultSet rs = null; - private static Statement stmt = null; - private static PreparedStatement prepareStmt = null; - - private static Logger logger = Logger.getLogger(JdbcUtil.class);// 这种情况下默认使用logger打印,如是只打印到自定义的logger就获取自定义的logger的名称 - - static { - Properties props = new Properties(); - InputStream is = JdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"); - try { - props.load(is); - DBDRIVER = props.getProperty("jdbc.driver"); - DBURL = props.getProperty("jdbc.url"); - DBUSER = props.getProperty("jdbc.username"); - DBPASSWORD = props.getProperty("jdbc.password"); - Class.forName(DBDRIVER); -// dataSource = DruidDataSourceFactory.createDataSource(props); -// if (dataSource != null) { -// conn = dataSource.getConnection(); -// } - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * 取一个数据库中所有表的信息 - * - * @throws SQLException - */ - public static void getDatabaseMetaDataInfo() throws SQLException { - Connection conn = JdbcUtil.getConnection(); - logger.info("###### DatabaseMetaData关于数据库的整体综合信息===="); - java.sql.DatabaseMetaData dbmd = conn.getMetaData(); - logger.info("数据库产品名: " + dbmd.getDatabaseProductName()); - logger.info("数据库是否支持事务: " + dbmd.supportsTransactions()); - logger.info("数据库产品的版本号:" + dbmd.getDatabaseProductVersion()); - logger.info("数据库的默认事务隔离级别:" + dbmd.getDefaultTransactionIsolation()); - logger.info("支持批量更新:" + dbmd.supportsBatchUpdates()); - logger.info("DBMS 的 URL:" + dbmd.getURL()); - logger.info("数据库的已知的用户名称:" + dbmd.getUserName()); - logger.info("数据库是否处于只读模式:" + dbmd.isReadOnly()); - logger.info("数据库是否支持为列提供别名:" + dbmd.supportsColumnAliasing()); - logger.info("是否支持指定 LIKE 转义子句:" + dbmd.supportsLikeEscapeClause()); - logger.info("是否为外连接提供受限制的支持:" + dbmd.supportsLimitedOuterJoins()); - logger.info("是否允许一次打开多个事务:" + dbmd.supportsMultipleTransactions()); - logger.info("是否支持 EXISTS 表达式中的子查询:" + dbmd.supportsSubqueriesInExists()); - logger.info("是否支持 IN 表达式中的子查询:" + dbmd.supportsSubqueriesInIns()); - logger.info("是否支持给定事务隔离级别:" + dbmd.supportsTransactionIsolationLevel(1)); - logger.info("此数据库是否支持事务:" + dbmd.supportsTransactions()); - logger.info("此数据库是否支持 SQL UNION:" + dbmd.supportsUnion()); - logger.info("此数据库是否支持 SQL UNION ALL:" + dbmd.supportsUnionAll()); - logger.info("此数据库是否为每个表使用一个文件:" + dbmd.usesLocalFilePerTable()); - logger.info("此数据库是否将表存储在本地文件中:" + dbmd.usesLocalFiles()); - logger.info("底层数据库的主版本号:" + dbmd.getDatabaseMajorVersion()); - logger.info("底层数据库的次版本号:" + dbmd.getDatabaseMinorVersion()); - logger.info("JDBC 驱动程序的主版本号:" + dbmd.getJDBCMajorVersion()); - logger.info("JDBC 驱动程序的次版本号:" + dbmd.getJDBCMinorVersion()); - logger.info("JDBC 驱动程序的名称:" + dbmd.getDriverName()); - logger.info("JDBC 驱动程序的 String 形式的版本号:" + dbmd.getDriverVersion()); - logger.info("可以在不带引号的标识符名称中使用的所有“额外”字符:" + dbmd.getExtraNameCharacters()); - logger.info("用于引用 SQL 标识符的字符串:" + dbmd.getIdentifierQuoteString()); - logger.info("允许用于类别名称的最大字符数:" + dbmd.getMaxCatalogNameLength()); - logger.info("允许用于列名称的最大字符数:" + dbmd.getMaxColumnNameLength()); - logger.info("允许在 GROUP BY 子句中使用的最大列数:" + dbmd.getMaxColumnsInGroupBy()); - logger.info("允许在 SELECT 列表中使用的最大列数:" + dbmd.getMaxColumnsInSelect()); - logger.info("允许在表中使用的最大列数:" + dbmd.getMaxColumnsInTable()); - logger.info("数据库的并发连接的可能最大数:" + dbmd.getMaxConnections()); - logger.info("允许用于游标名称的最大字符数:" + dbmd.getMaxCursorNameLength()); - logger.info("在同一时间内可处于开放状态的最大活动语句数:" + dbmd.getMaxStatements()); - // 获取所有表 new String[]{"TABLE"} - // String[] type = {"TABLE","VIEW"} null - logger.info("###### 获取表的信息"); - ResultSet tSet = dbmd.getTables(null, "%", "%", new String[] { "TABLE", "VIEW" }); - while (tSet.next()) { - logger.info(tSet.getRow() + "_表类别:" + tSet.getString("TABLE_CAT") + "_表模式:" + tSet.getString("TABLE_SCHEM") - + "_表名称:" + tSet.getString("TABLE_NAME") + "_表类型:" + tSet.getString("TABLE_TYPE") - // +"\n_表的解释性注释:"+tSet.getString("REMARKS")+"_类型的类别:"+tSet.getString("TYPE_CAT") - // +"\n_类型模式:"+tSet.getString("TYPE_SCHEM")+"_类型名称:"+tSet.getString("TYPE_NAME") - // +"\n_有类型表的指定'identifier'列的名称:"+tSet.getString("SELF_REFERENCING_COL_NAME") - // +"\n_指定在 SELF_REFERENCING_COL_NAME - // 中创建值的方式:"+tSet.getString("REF_GENERATION") - ); - // 2_表类别:MANOR_表模式:PUBLIC_表名称:SYS_RESOURCE_表类型:TABLE - String tableName = tSet.getString(3); - String sql = "select * from " + tableName; - ResultSet rsSet = conn.createStatement().executeQuery(sql); - ResultSetMetaData rsData = rsSet.getMetaData(); - for (int i = 1; i < rsData.getColumnCount(); i++) { - logger.info("==列的信息:获取SQL语句的列名:" + rsData.getColumnName(i) + "(" + rsData.getColumnLabel(i) + "," - + rsData.getColumnType(i) + "," + rsData.getColumnClassName(i) + ")" + " 列宽" - + rsData.getPrecision(i) + " 大小写敏感" + rsData.isCaseSensitive(i) + " isReadOnly:" - + rsData.isReadOnly(i)); - // ==列的信息:获取SQL语句的列名:LIMITLEVER(LIMITLEVER,5,java.lang.Short) - // 列宽5 大小写敏感true isReadOnly:false - } - } - tSet.close(); - logger.info("###### 获取当前数据库所支持的SQL数据类型"); - - ResultSet tableType = dbmd.getTypeInfo(); - while (tableType.next()) { - logger.info("数据类型名:" + tableType.getString(1) + ",短整型的数:" + tableType.getString(2) + ",整型的数:" - + tableType.getString(3) + ",最小精度:" + tableType.getString(14) + ",最大精度:" + tableType.getString(15)); - // 数据类型名:TIMESTAMP,短整型的数:93,整型的数:23,最小精度:0,最大精度:10 - // 数据类型名:VARCHAR,短整型的数:12,整型的数:2147483647,最小精度:0,最大精度:0 - } - logger.info("###### 表的主键列信息"); - ResultSet primaryKey = dbmd.getPrimaryKeys("MANOR", "PUBLIC", "SYS_ROLE_RES"); - while (primaryKey.next()) { - logger.info("表名:" + primaryKey.getString("TABLE_NAME") + ",列名:" + primaryKey.getString("COLUMN_NAME") - + " 主键名:" + primaryKey.getString("PK_NAME")); - // 表名:SYS_ROLE_RES,列名:SYS_RES_ID 主键名:CONSTRAINT_9 - // 表名:SYS_ROLE_RES,列名:SYS_ROLE_ID 主键名:CONSTRAINT_9 - } - logger.info("###### 表的外键列信息"); - ResultSet foreinKey = dbmd.getImportedKeys("MANOR", "PUBLIC", "SYS_ROLE_RES"); - while (foreinKey.next()) { - logger.info("主键名:" + foreinKey.getString("PK_NAME") + ",外键名:" + foreinKey.getString("FKCOLUMN_NAME") - + ",主键表名:" + foreinKey.getString("PKTABLE_NAME") + ",外键表名:" + foreinKey.getString("FKTABLE_NAME") - + ",外键列名:" + foreinKey.getString("PKCOLUMN_NAME") + ",外键序号:" + foreinKey.getString("KEY_SEQ")); - // 主键名:PRIMARY_KEY_95,外键名:SYS_RES_ID,主键表名:SYS_RESOURCE,外键表名:SYS_ROLE_RES,外键列名:ID,外键序号:1 - // 主键名:PRIMARY_KEY_A,外键名:SYS_ROLE_ID,主键表名:SYS_ROLE,外键表名:SYS_ROLE_RES,外键列名:ID,外键序号:1 - } - logger.info("###### 获取数据库中允许存在的表类型"); - ResultSet tableTypes = dbmd.getTableTypes(); - while (tableTypes.next()) { - logger.info("类型名:" + tableTypes.getString(1)); - /** - * H2 类型名:SYSTEM TABLE 类型名:TABLE 类型名:TABLE LINK 类型名:VIEW - */ - } - // 此外还可以获取索引等的信息 - conn.close(); - } - - /** - * PreparedStatement 信息 ResultSetMetaData 信息 - * - * @throws SQLException - */ - public static void getDBParameterMetaData() throws SQLException { - Connection conn = JdbcUtil.getConnection(); // id,name - PreparedStatement pre = conn.prepareStatement("SELECT * FROM SYS_APPTYPE where id = ?"); - pre.setInt(1, 3); - java.sql.ParameterMetaData pmd = pre.getParameterMetaData(); - logger.info("参数的个数:" + pmd.getParameterCount()); - logger.info("获取指定参数的 SQL 类型:" + pmd.getParameterType(1)); - logger.info("culomn的参数类型:" + pmd.getParameterTypeName(1)); - logger.info("Java 类的完全限定名称:" + pmd.getParameterClassName(1)); - logger.info("获取指定参数的模式:" + pmd.getParameterMode(1)); - logger.info("获取指定参数的指定列大小:" + pmd.getPrecision(1)); - logger.info("获取指定参数的小数点右边的位数:" + pmd.getScale(1)); - logger.info("是否允许在指定参数中使用 null 值:" + pmd.isNullable(1)); - logger.info("指定参数的值是否可以是带符号的数字:" + pmd.isSigned(1)); - // 获取结果集元数据 - ResultSet rs = pre.executeQuery(); - while (rs.next()) { - logger.info(rs.getString(1) + "___" + rs.getString(2)); - } - rs.close(); - } - - /** - * 获取所有Driver信息 - */ - public static void getAllDriverMsg() { - Enumeration drivers = DriverManager.getDrivers(); - while (drivers.hasMoreElements()) { - Driver d = (Driver) drivers.nextElement(); - logger.info(d.getClass().getName() + "_" + d.getMajorVersion()); - } - } - - @SuppressWarnings("rawtypes") - public static List execute(String Sql) throws Exception { - PreparedStatement psmt = null; - if (Sql.toUpperCase().startsWith("SELECT")) { - psmt = conn.prepareStatement(Sql); - ResultSet res = psmt.executeQuery(); - if (res.next()) { - String.valueOf(res.getObject(1)); - } - } else if (Sql.toUpperCase().startsWith("INSERT")) { - psmt = conn.prepareStatement(Sql, Statement.RETURN_GENERATED_KEYS); - psmt.executeUpdate(); - ResultSet res = psmt.getGeneratedKeys(); - if (res.next()) { - String.valueOf(res.getObject(1)); - } - } else if (Sql.toUpperCase().startsWith("UPDATE")) { - psmt = conn.prepareStatement(Sql, Statement.RETURN_GENERATED_KEYS); - psmt.executeUpdate(); - ResultSet res = psmt.getGeneratedKeys(); - if (res.next()) { - String.valueOf(res.getObject(1)); - } - } - return null; - } - - public int executeUpdateDeleteInsert(String sql) { - int i = 0; - try { - // Connection c = getConnection(); - Statement state = conn.createStatement(); - i = state.executeUpdate(sql); - } catch (Exception ex) { - ex.printStackTrace(); - } - return i; - } - - public static String repeatSql(String Table_name, Map repeatParams) { - StringBuffer sql = new StringBuffer("select 1"); - sql.append(" from ").append(Table_name).append(" where 1 = 1"); - for (String key : repeatParams.keySet()) { - if (repeatParams.get(key) instanceof CharSequence || repeatParams.get(key) instanceof Timestamp) { - sql.append(" and ").append(key).append(" = '").append(repeatParams.get(key)).append("'"); - } else { - sql.append(" and ").append(key).append(" = ").append(repeatParams.get(key)); - } - } - return sql.toString(); - } - - @SuppressWarnings("unused") - public static String getUpdateSql(String Table_name, Map params, Map repeatParams) { - StringBuffer mapping = new StringBuffer(); - StringBuffer conditions = new StringBuffer(); - for (Entry entry : params.entrySet()) { - mapping.append(entry.getKey()).append(" = "); - if (entry.getValue() instanceof CharSequence || entry.getValue() instanceof Timestamp) { - mapping.append("'" + entry.getValue() + "' ,"); - } else { - mapping.append(entry.getValue() + " ,"); - } - } - for (Entry entry : repeatParams.entrySet()) { - conditions.append(" and ").append(entry.getKey()).append(" = "); - if (entry.getValue() instanceof CharSequence || entry.getValue() instanceof Timestamp) { - conditions.append("'" + entry.getValue() + "'"); - } else { - conditions.append(entry.getValue()); - } - } - if (mapping.length() > 0) { - mapping.deleteCharAt(mapping.length() - 1); - } - StringBuffer sql = new StringBuffer("update "); - sql.append(Table_name); - sql.append(" set "); - sql.append(mapping); - sql.append(" where 1 = 1"); - sql.append(conditions); - return sql.toString(); - } - - @SuppressWarnings("unused") - public static String getInsertSql(String Table_name, Map params) { - if (params == null || params.size() <= 0) { - return null; - } - StringBuffer keys = new StringBuffer(); - StringBuffer values = new StringBuffer(); - for (Entry entry : params.entrySet()) { - keys.append(entry.getKey() + ","); - if (entry.getValue() instanceof CharSequence || entry.getValue() instanceof Timestamp) { - values.append("'" + entry.getValue() + "',"); - } else { - values.append(entry.getValue() + ","); - } - } - if (keys.length() > 0) { - keys.deleteCharAt(keys.length() - 1); - } - if (values.length() > 0) { - values.deleteCharAt(values.length() - 1); - } - StringBuffer sql = new StringBuffer("insert into "); - sql.append(Table_name); - sql.append(" (" + keys); - sql.append(") values ("); - sql.append(values + ")"); - return sql.toString(); - } - - @SuppressWarnings("unused") - public static String getQuerySql(String Table_name, Map params) { - StringBuffer sql = new StringBuffer("select "); - sql.append("").append(" from ").append(Table_name).append(" where 1 = 1"); - for (String key : params.keySet()) { - if (params.get(key) instanceof CharSequence || params.get(key) instanceof Timestamp) { - sql.append(" and ").append(key).append(" = '").append(params.get(key)).append("'"); - } else { - sql.append(" and ").append(key).append(" = ").append(params.get(key)); - } - } - return sql.toString(); - } - - public Connection getJdbcConnection() throws SQLException, IOException, Exception { - Properties props = new Properties(); - // String fileName = "e:\Database.Property"; - // FileInputStream in = new FileInputStream(fileName); - InputStream in = getClass().getResourceAsStream("jdbc.properties"); - props.load(in); - String drivers = props.getProperty("jdbc.drivers"); - if (drivers != null) { - System.setProperty("jdbc.drives", drivers); - } - String url = props.getProperty("jdbc.url"); - String username = props.getProperty("jdbc.username"); - String password = props.getProperty("jdbc.password"); - Class.forName(drivers); - return DriverManager.getConnection(url, username, password); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public static List query(String strSql) throws SQLException { - rs = stmt.executeQuery(strSql); - List results = new LinkedList(); - int rowNum = 0; - for (; rs.next(); results.add(mapRow(rs, rowNum++))) - ; - return results; - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public static List queryByRow(ResultSet rs, int rowsExpected) throws SQLException { - List results = ((List) (rowsExpected <= 0 ? ((List) (new LinkedList())) - : ((List) (new ArrayList(rowsExpected))))); - int rowNum = 0; - for (; rs.next(); results.add(mapRow(rs, rowNum++))) - ; - return results; - } - - public static List extractData(ResultSet rs) throws SQLException { - List results = new LinkedList(); - int rowNum = 0; - for (; rs.next(); results.add(mapRow(rs, rowNum++))) - ; - return results; - } - - public static List extractData(ResultSet rs, int rowsExpected) throws SQLException { - List results = ((List) (rowsExpected <= 0 ? ((List) (new LinkedList())) - : ((List) (new ArrayList(rowsExpected))))); - int rowNum = 0; - for (; rs.next(); results.add(mapRow(rs, rowNum++))) - ; - return results; - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public static Object mapRow(ResultSet rs, int rowNum) throws SQLException { - ResultSetMetaData rsmd = rs.getMetaData(); - int columnCount = rsmd.getColumnCount(); - Map mapOfColValues = new HashMap(columnCount); - for (int i = 1; i <= columnCount; i++) { - String key = rsmd.getColumnName(i); - Object obj = getResultSetValue(rs, i); - mapOfColValues.put(key, obj); - } - return mapOfColValues; - } - - public static Object getResultSetValue(ResultSet rs, int index) throws SQLException { - Object obj = rs.getObject(index); - if (obj instanceof Blob) - obj = rs.getBytes(index); - else if (obj instanceof Clob) - obj = rs.getString(index); - else if (obj != null && obj.getClass().getName().startsWith("oracle.sql.TIMESTAMP")) - obj = rs.getTimestamp(index); - else if (obj != null && obj.getClass().getName().startsWith("oracle.sql.DATE")) { - String metaDataClassName = rs.getMetaData().getColumnClassName(index); - if ("java.sql.Timestamp".equals(metaDataClassName) || "oracle.sql.TIMESTAMP".equals(metaDataClassName)) - obj = rs.getTimestamp(index); - else - obj = rs.getDate(index); - } else if (obj != null && (obj instanceof Date) - && "java.sql.Timestamp".equals(rs.getMetaData().getColumnClassName(index))) - obj = rs.getTimestamp(index); - return obj; - } - - // ResultSet rs = null; - // 执行查询语句的方法 - public static ResultSet executeQuery(String sql) { - try { - conn = DriverManager.getConnection(DBURL, DBUSER, DBPASSWORD); // 建立与数据库服务器的连接 - Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - rs = stmt.executeQuery(sql);// 执行指定的数据查询语句 - } catch (SQLException ex) { - ex.printStackTrace(); - } - return rs; - } - - // 执行增、删改语句的方法 - public int executeUpdate(String sql) { - int result = 0; - try { - conn = DriverManager.getConnection(DBURL, DBUSER, DBPASSWORD); - Statement stmt = conn.createStatement(); - result = stmt.executeUpdate(sql);// 执行指定的数据操作语句 - } catch (SQLException ex) { - System.err.println(ex.getMessage()); - } - return result; - } - - public void create(String sql) { - Connection conn = null; - Statement stmt = null; - ResultSet rs = null; - try { - conn = JdbcUtil.getConnection(); - stmt = conn.createStatement(); - int i = stmt.executeUpdate(sql); - System.out.println(i > 0 ? "sucess" : "faild"); - } catch (Exception e) { - e.printStackTrace(); - } finally { - JdbcUtil.close(); - } - } - - public void update(String sql) { - Connection conn = null; - Statement stmt = null; - ResultSet rs = null; - try { - conn = JdbcUtil.getConnection(); - stmt = conn.createStatement(); - int i = stmt.executeUpdate(sql); - System.out.println(i > 0 ? "sucess" : "faild"); - } catch (Exception e) { - e.printStackTrace(); - } finally { - JdbcUtil.close(); - } - } - - public void delete(String sql) { - Connection conn = null; - Statement stmt = null; - ResultSet rs = null; - try { - conn = JdbcUtil.getConnection(); - stmt = conn.createStatement(); - int i = stmt.executeUpdate(sql); - System.out.println(i > 0 ? "sucess" : "faild"); - } catch (Exception e) { - e.printStackTrace(); - } finally { - JdbcUtil.close(); - } - } - - public void init() { - try { - // 1.ע���� - Class.forName("oracle.jdbc.driver.OracleDriver"); - // 2.ͨ���������������� - // ��ʽ:jdbc:oracle:thin:@:<�˿ں�,Ĭ����1521>: - String url = "jdbc:oracle:thin:@192.168.0.26:1521:tarena"; - String dbUsername = "openlab"; - String dbPassword = "open123"; - conn = DriverManager.getConnection(url, dbUsername, dbPassword); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public static void close() { - try { - if (rs != null) - rs.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - try { - if (prepareStmt != null) - prepareStmt.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - try { - if (conn != null) - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - public void update() { - init(); - try { - String sql = "update mydepttemp " + "set loc = ? " + "where deptno = ?"; - prepareStmt = conn.prepareStatement(sql); - prepareStmt.setString(1, "���"); - prepareStmt.setInt(2, 10); - - int n = prepareStmt.executeUpdate(); - System.out.println(n + "����¼���޸�"); - System.out.println((n > 0) ? "OK" : "error"); - - } catch (SQLException e) { - e.printStackTrace(); - } finally { - close(); - } - } - - public void insert() { - init(); - try { - - String sql = "insert into dept " + "values(?, ?, ?)"; - prepareStmt = conn.prepareStatement(sql); - prepareStmt.setInt(1, 10); - prepareStmt.setString(2, "market"); - prepareStmt.setString(3, "beijing"); - - int n = prepareStmt.executeUpdate(); - - System.out.println((n == 1) ? "OK" : "error"); - - } catch (SQLException e) { - e.printStackTrace(); - } finally { - close(); - } - } - - /** - * 得到连接对象 - */ - public static Connection getConnection() { - Connection conn = null; - try { - conn = DriverManager.getConnection(DBURL, DBUSER, DBPASSWORD); - } catch (SQLException e) { - e.printStackTrace(); - } - return conn; - } - - // 通用的增删改方法 - public static boolean update(String sql, Object[] params) throws Exception { - Connection conn = null; - PreparedStatement pstmt = null; - ResultSet rs = null; - try { - conn = getConnection(); - conn.setAutoCommit(false);// 将事物默认提交设置为flase - pstmt = conn.prepareStatement(sql); - for (int i = 0; params != null && i < params.length; i++) - pstmt.setObject(i + 1, params[i]);// 通过setObject设置参数所对应的值。sql语句的参数用?占位 - int num = pstmt.executeUpdate();// executeUpdate会返回影响结果的条数 - conn.commit(); - conn.setAutoCommit(false); - if (num > 0) - return true; - return false; - } catch (SQLException e) { - if (conn != null) { - try { - conn.rollback(); - } catch (SQLException e1) { - throw new Exception(e1); - } - } - throw new Exception(e); - } - } - - /** - * @author - * @throws SQLException - * @since - * @throws @description 对数据进行批量添加,当数据量大于100时,则整除1000时提交一次,wbs里存放的是批量数值数组的集合 - */ - public static boolean updateBatch(String sql, List wbs) throws Exception, SQLException { - logger.info("批量添加开始"); - Calendar calendar = Calendar.getInstance(); - long startTime = calendar.getTimeInMillis(); - calendar = null; - Connection conn = null; - PreparedStatement pstmt = null; - ResultSet rs = null; - int count = 0; - boolean flag = false; - try { - conn = getConnection(); - conn.setAutoCommit(false); - pstmt = conn.prepareStatement(sql); - for (Iterator it = wbs.iterator(); it.hasNext();) { - Object[] params = (Object[]) it.next(); - count++; - for (int i = 0; params != null && i < params.length; i++) { - pstmt.setObject(i + 1, params[i]); - } - pstmt.addBatch();// 将一批参数添加到pstmt对象的批处理命令 - if (count % 100 == 0) { - pstmt.executeBatch(); - conn.commit();// 当数量到100时提交 - flag = true; - } - } - pstmt.executeBatch(); - conn.commit(); - conn.setAutoCommit(true); - flag = true; - if (flag) { - logger.info("批量添加结束"); - Calendar calendarOld = Calendar.getInstance(); - long endTime = calendarOld.getTimeInMillis(); - // logger.info("批量添加共耗时:"+(endTime-startTime)+"ms"); - logger.info("批量添加共耗时:" + (endTime - startTime) + "ms"); - return true; - } - logger.info("批量添加失败"); - return false; - } catch (SQLException e) { - if (conn != null) { - try { - conn.rollback(); - } catch (SQLException e1) { - throw new Exception(e); - } - } - throw new Exception(e); - } - } - - /** - * 此处返回的是插入数据后生成的主键 - * - * @param sql - * @param params - * @return - * @throws SQLException - */ - public static int insert(String sql, Object[] params) throws Exception, SQLException { - Connection conn = null; - PreparedStatement pstmt = null; - ResultSet rs = null; - try { - conn = getConnection(); - pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); - for (int i = 0; params != null && i < params.length; i++) - pstmt.setObject(i + 1, params[i]); - pstmt.executeUpdate(); - rs = pstmt.getGeneratedKeys();// 获取刚刚插入的主键rs - rs.next();// 获取刚刚获取的主键 - int key = rs.getInt(1); - if (key > 0) { - return key; - } else { - return 0; - } - } catch (SQLException e) { - throw new Exception(e); - } - } - - public static PreparedStatement getPs(Connection conn2, String sql) { - PreparedStatement ps = null; - try { - ps = conn.prepareStatement(sql); - } catch (SQLException e) { - e.printStackTrace(); - } - return ps; - } - - /** - * - * @Discription 执行有参数,无返回值的存储过程 - * @return void - * @param conn - * @throws Exception - */ - - /** - * @说明 执行一条SQL - */ - @SuppressWarnings("unchecked") - public static List excuteQuery(String sql) { - Connection conn = null; - PreparedStatement psta = null; - ResultSet resultSet = null; - List relist = new ArrayList(); // 总数据 - Object[] objects = null; // 每行数据 - try { - conn = DataSourceUtil.getConn(); // 得到链接 - if (null != conn) { - psta = conn.prepareStatement(sql); - resultSet = psta.executeQuery(); // 执行查询,返回结果接集合 - int count = resultSet.getMetaData().getColumnCount(); // 一共有多少列数据 - // 循环行 - while (resultSet.next()) { - objects = new Object[count]; - // 数据集索引从 1 开始,而数组存放时是从 0 开始 - for (int i = 1; i <= count; i++) { - objects[i - 1] = resultSet.getObject(i); - } - relist.add(objects); - } - } - } catch (Exception e) { - e.printStackTrace(); - relist = null; - } finally { - try { - if (null != resultSet) - resultSet.close(); - if (null != psta) - psta.close(); - if (null != conn) - conn.close(); - } catch (Exception e2) { - - } - } - return relist; - } - - /******************************************************************************************************/ - /******************************************************************************************************/ - /******************************************************************************************************/ - /******************************************************************************************************/ - - public static List extractData1(ResultSet rs) throws SQLException { - List results = new LinkedList(); - int rowNum = 0; - for (; rs.next(); results.add(mapRow(rs, rowNum++))) - ; - return results; - } - - public static List extractData1(ResultSet rs, int rowsExpected) throws SQLException { - List results = ((List) (rowsExpected <= 0 ? ((List) (new LinkedList())) - : ((List) (new ArrayList(rowsExpected))))); - int rowNum = 0; - for (; rs.next(); results.add(mapRow(rs, rowNum++))) - ; - return results; - } - - public static Object mapRow1(ResultSet rs, int rowNum) throws SQLException { - ResultSetMetaData rsmd = rs.getMetaData(); - int columnCount = rsmd.getColumnCount(); - Map mapOfColValues = new HashMap(columnCount); - for (int i = 1; i <= columnCount; i++) { - String key = getColumnKey(rsmd.getColumnName(i)); - Object obj = getColumnValue(rs, i); - mapOfColValues.put(key, obj); - } - - return mapOfColValues; - } - - public static String getColumnKey(String columnName) { - return columnName; - } - - public static Object getColumnValue(ResultSet rs, int index) throws SQLException { - return getResultSetValue(rs, index); - } - - public static Object getResultSetValue1(ResultSet rs, int index) throws SQLException { - Object obj = rs.getObject(index); - if (obj instanceof Blob) - obj = rs.getBytes(index); - else if (obj instanceof Clob) - obj = rs.getString(index); - else if (obj != null && obj.getClass().getName().startsWith("oracle.sql.TIMESTAMP")) - obj = rs.getTimestamp(index); - else if (obj != null && obj.getClass().getName().startsWith("oracle.sql.DATE")) { - String metaDataClassName = rs.getMetaData().getColumnClassName(index); - if ("java.sql.Timestamp".equals(metaDataClassName) || "oracle.sql.TIMESTAMP".equals(metaDataClassName)) - obj = rs.getTimestamp(index); - else - obj = rs.getDate(index); - } else if (obj != null && (obj instanceof Date) - && "java.sql.Timestamp".equals(rs.getMetaData().getColumnClassName(index))) - obj = rs.getTimestamp(index); - return obj; - } - - public static int getRow(String sql) { - int i = 0; - conn = JdbcUtil.getConnection(); - PreparedStatement ps = null; - ResultSet rs = null; - try { - ps = conn.prepareStatement("SELECT COUNT(*) FROM " + sql, ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); - rs = ps.executeQuery(); - if (rs.next()) { - i = rs.getInt(1); - } - } catch (SQLException e) { - System.out.println(e.getMessage()); - i = 0; - } finally { - System.out.println("SELECT COUNT(*) FROM " + sql); - try { - rs.close(); - ps.close(); - } catch (SQLException e) { - } - } - return i; - } - - /** - * @Description: JDBC操作元数据示例-- DatabaseMetaData接口 - * @version V1.0 - */ - // *************************************************************** - // 获得驱动 - private static String DRIVER = "oracle.jdbc.driver.OracleDriver"; - // 获得url - private static String URL = "jdbc:oracle:thin:@localhost:test"; - // 获得连接数据库的用户名 - private static String USER = "root"; - // 获得连接数据库的密码 - private static String PASS = "root"; - static { - try { - // 初始化JDBC驱动并让驱动加载到jvm中 - Class.forName(DRIVER); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } - } - - /* - * public static Connection getConnection(){ Connection conn = null; try { - * //连接数据库 - * - * - * 设置可获取REMARK备注信息 Properties props =new Properties(); - * props.put("remarksReporting","true"); props.put("user", USER); - * props.put("password", PASS); conn =DriverManager.getConnection(URL,props); - * - * // conn = DriverManager.getConnection(URL,USER,PASS); conn = - * JdbcUtil.getConnection(); conn.setAutoCommit(true); } catch (SQLException e) - * { e.printStackTrace(); } return conn; } - */ - - // 关闭连接 - public static void close(Object o) { - if (o == null) { - return; - } - if (o instanceof ResultSet) { - try { - ((ResultSet) o).close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } else if (o instanceof Statement) { - try { - ((Statement) o).close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } else if (o instanceof Connection) { - Connection c = (Connection) o; - try { - if (!c.isClosed()) { - c.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - } - - public static void close(ResultSet rs, Statement stmt, Connection conn) { - close(rs); - close(stmt); - close(conn); - } - - public static void close(ResultSet rs, Connection conn) { - close(rs); - close(conn); - } - - /** - * @Description: 获取数据库相关信息 @author: chenzw @CreateTime: 2014-1-27 - * 下午5:09:12 @throws - */ - public static void getDataBaseInfo() { - Connection conn = getConnection(); - ResultSet rs = null; - try { - DatabaseMetaData dbmd = conn.getMetaData(); - System.out.println("数据库已知的用户: " + dbmd.getUserName()); - System.out.println("数据库的系统函数的逗号分隔列表: " + dbmd.getSystemFunctions()); - System.out.println("数据库的时间和日期函数的逗号分隔列表: " + dbmd.getTimeDateFunctions()); - System.out.println("数据库的字符串函数的逗号分隔列表: " + dbmd.getStringFunctions()); - System.out.println("数据库供应商用于 'schema' 的首选术语: " + dbmd.getSchemaTerm()); - System.out.println("数据库URL: " + dbmd.getURL()); - System.out.println("是否允许只读:" + dbmd.isReadOnly()); - System.out.println("数据库的产品名称:" + dbmd.getDatabaseProductName()); - System.out.println("数据库的版本:" + dbmd.getDatabaseProductVersion()); - System.out.println("驱动程序的名称:" + dbmd.getDriverName()); - System.out.println("驱动程序的版本:" + dbmd.getDriverVersion()); - - System.out.println("数据库中使用的表类型"); - rs = dbmd.getTableTypes(); - while (rs.next()) { - System.out.println(rs.getString("TABLE_TYPE")); - } - } catch (SQLException e) { - e.printStackTrace(); - } finally { - JdbcUtil.close(rs, conn); - } - } - - /** - * @Description:获得数据库中所有Schemas(对应于oracle中的Tablespace) @author: - * chenzw @CreateTime: 2014-1-27 下午5:10:35 @throws - */ - public static void getSchemasInfo() { - Connection conn = getConnection(); - ResultSet rs = null; - try { - DatabaseMetaData dbmd = conn.getMetaData(); - rs = dbmd.getSchemas(); - while (rs.next()) { - String tableSchem = rs.getString("TABLE_SCHEM"); - System.out.println(tableSchem); - } - } catch (SQLException e) { - e.printStackTrace(); - } finally { - JdbcUtil.close(rs, conn); - } - } - - /** - * @Description: 获取数据库中所有的表信息 @author: chenzw @CreateTime: 2014-1-27 - * 下午5:08:28 @throws - */ - public static void getTablesList() { - Connection conn = getConnection(); - ResultSet rs = null; - try { - /** - * 设置连接属性,使得可获取到表的REMARK(备注) - */ -// ((OracleConnection)conn).setRemarksReporting(true); - DatabaseMetaData dbmd = conn.getMetaData(); - String[] types = { "TABLE" }; - rs = dbmd.getTables(null, null, "%", types); - while (rs.next()) { - String tableName = rs.getString("TABLE_NAME"); // 表名 - String tableType = rs.getString("TABLE_TYPE"); // 表类型 - String remarks = rs.getString("REMARKS"); // 表备注 - System.out.println(tableName + " - " + tableType + " - " + remarks); - } - } catch (SQLException e) { - e.printStackTrace(); - } finally { - JdbcUtil.close(rs, conn); - } - } - - /** - * @Description: 获取某表信息 @author: chenzw @CreateTime: 2014-1-27 下午3:26:30 @throws - */ - public static void getTablesInfo() { - Connection conn = getConnection(); - ResultSet rs = null; - try { - /** - * 设置连接属性,使得可获取到表的REMARK(备注) - */ -// ((OracleConnection)conn).setRemarksReporting(true); - DatabaseMetaData dbmd = conn.getMetaData(); - /** - * 获取给定类别中使用的表的描述。 方法原型:ResultSet getTables(String catalog,String - * schemaPattern,String tableNamePattern,String[] types); catalog - - * 表所在的类别名称;""表示获取没有类别的列,null表示获取所有类别的列。 schema - - * 表所在的模式名称(oracle中对应于Tablespace);""表示获取没有模式的列,null标识获取所有模式的列; - * 可包含单字符通配符("_"),或多字符通配符("%"); tableNamePattern - - * 表名称;可包含单字符通配符("_"),或多字符通配符("%"); types - 表类型数组; "TABLE"、"VIEW"、"SYSTEM - * TABLE"、"GLOBAL TEMPORARY"、"LOCAL TEMPORARY"、"ALIAS" 和 - * "SYNONYM";null表示包含所有的表类型;可包含单字符通配符("_"),或多字符通配符("%"); - */ - rs = dbmd.getTables(null, null, "CUST_INTER_TF_SERVICE_REQ", new String[] { "TABLE", "VIEW" }); - - while (rs.next()) { - String tableCat = rs.getString("TABLE_CAT"); // 表类别(可为null) - String tableSchemaName = rs.getString("TABLE_SCHEM");// 表模式(可能为空),在oracle中获取的是命名空间,其它数据库未知 - String tableName = rs.getString("TABLE_NAME"); // 表名 - String tableType = rs.getString("TABLE_TYPE"); // 表类型,典型的类型是 "TABLE"、"VIEW"、"SYSTEM TABLE"、"GLOBAL - // TEMPORARY"、"LOCAL TEMPORARY"、"ALIAS" 和 "SYNONYM"。 - String remarks = rs.getString("REMARKS"); // 表备注 - - System.out.println( - tableCat + " - " + tableSchemaName + " - " + tableName + " - " + tableType + " - " + remarks); - } - } catch (Exception ex) { - ex.printStackTrace(); - } finally { - JdbcUtil.close(rs, conn); - } - } - - /** - * @Description: 获取表主键信息 @author: chenzw @CreateTime: 2014-1-27 - * 下午5:12:53 @throws - */ - public static void getPrimaryKeysInfo() { - Connection conn = getConnection(); - ResultSet rs = null; - try { - DatabaseMetaData dbmd = conn.getMetaData(); - /** - * 获取对给定表的主键列的描述 方法原型:ResultSet getPrimaryKeys(String catalog,String - * schema,String table); catalog - 表所在的类别名称;""表示获取没有类别的列,null表示获取所有类别的列。 schema - * - 表所在的模式名称(oracle中对应于Tablespace);""表示获取没有模式的列,null标识获取所有模式的列; - * 可包含单字符通配符("_"),或多字符通配符("%"); table - 表名称;可包含单字符通配符("_"),或多字符通配符("%"); - */ -// rs = dbmd.getPrimaryKeys(null, null, "CUST_INTER_TF_SERVICE_REQ"); - rs = dbmd.getPrimaryKeys(null, null, "sys_fileupload"); - - while (rs.next()) { - String tableCat = rs.getString("TABLE_CAT"); // 表类别(可为null) - String tableSchemaName = rs.getString("TABLE_SCHEM");// 表模式(可能为空),在oracle中获取的是命名空间,其它数据库未知 - String tableName = rs.getString("TABLE_NAME"); // 表名 - String columnName = rs.getString("COLUMN_NAME");// 列名 - short keySeq = rs.getShort("KEY_SEQ");// 序列号(主键内值1表示第一列的主键,值2代表主键内的第二列) - String pkName = rs.getString("PK_NAME"); // 主键名称 - - System.out.println(tableCat + " - " + tableSchemaName + " - " + tableName + " - " + columnName + " - " - + keySeq + " - " + pkName); - } - } catch (SQLException e) { - e.printStackTrace(); - } finally { - JdbcUtil.close(rs, conn); - } - } - - /** - * @Description: 获取表索引信息 @author: chenzw @CreateTime: 2014-1-27 - * 下午5:12:04 @throws - */ - public static void getIndexInfo() { - Connection conn = getConnection(); - ResultSet rs = null; - try { - DatabaseMetaData dbmd = conn.getMetaData(); - /** - * 获取给定表的索引和统计信息的描述 方法原型:ResultSet getIndexInfo(String catalog,String - * schema,String table,boolean unique,boolean approximate) catalog - - * 表所在的类别名称;""表示获取没有类别的列,null表示获取所有类别的列。 schema - - * 表所在的模式名称(oracle中对应于Tablespace);""表示获取没有模式的列,null标识获取所有模式的列; - * 可包含单字符通配符("_"),或多字符通配符("%"); table - 表名称;可包含单字符通配符("_"),或多字符通配符("%"); unique - * - 该参数为 true时,仅返回唯一值的索引; 该参数为 false时,返回所有索引; approximate - - * 该参数为true时,允许结果是接近的数据值或这些数据值以外的值;该参数为 false时,要求结果是精确结果; - */ - rs = dbmd.getIndexInfo(null, null, "CUST_INTER_TF_SERVICE_REQ", false, true); - while (rs.next()) { - String tableCat = rs.getString("TABLE_CAT"); // 表类别(可为null) - String tableSchemaName = rs.getString("TABLE_SCHEM");// 表模式(可能为空),在oracle中获取的是命名空间,其它数据库未知 - String tableName = rs.getString("TABLE_NAME"); // 表名 - boolean nonUnique = rs.getBoolean("NON_UNIQUE");// 索引值是否可以不唯一,TYPE为 tableIndexStatistic时索引值为 false; - String indexQualifier = rs.getString("INDEX_QUALIFIER");// 索引类别(可能为空),TYPE为 tableIndexStatistic 时索引类别为 - // null; - String indexName = rs.getString("INDEX_NAME");// 索引的名称 ;TYPE为 tableIndexStatistic 时索引名称为 null; - /** - * 索引类型: tableIndexStatistic - 此标识与表的索引描述一起返回的表统计信息 tableIndexClustered - 此为集群索引 - * tableIndexHashed - 此为散列索引 tableIndexOther - 此为某种其他样式的索引 - */ - short type = rs.getShort("TYPE");// 索引类型; - short ordinalPosition = rs.getShort("ORDINAL_POSITION");// 在索引列顺序号;TYPE为 tableIndexStatistic 时该序列号为零; - String columnName = rs.getString("COLUMN_NAME");// 列名;TYPE为 tableIndexStatistic时列名称为 null; - String ascOrDesc = rs.getString("ASC_OR_DESC");// 列排序顺序:升序还是降序[A:升序; B:降序];如果排序序列不受支持,可能为 null;TYPE为 - // tableIndexStatistic时排序序列为 null; - int cardinality = rs.getInt("CARDINALITY"); // 基数;TYPE为 tableIndexStatistic 时,它是表中的行数;否则,它是索引中唯一值的数量。 - int pages = rs.getInt("PAGES"); // TYPE为 tableIndexStatisic时,它是用于表的页数,否则它是用于当前索引的页数。 - String filterCondition = rs.getString("FILTER_CONDITION"); // 过滤器条件,如果有的话(可能为 null)。 - - System.out.println(tableCat + " - " + tableSchemaName + " - " + tableName + " - " + nonUnique + " - " - + indexQualifier + " - " + indexName + " - " + type + " - " + ordinalPosition + " - " - + columnName + " - " + ascOrDesc + " - " + cardinality + " - " + pages + " - " - + filterCondition); - } - } catch (SQLException e) { - e.printStackTrace(); - } finally { - JdbcUtil.close(rs, conn); - } - } - - /** - * @Description: 获取表中列值信息 @author: chenzw @CreateTime: 2014-1-27 - * 下午2:55:56 @throws - */ - public static void getColumnsInfo() { - Connection conn = getConnection(); - ResultSet rs = null; - - try { - /** - * 设置连接属性,使得可获取到列的REMARK(备注) - */ -// ((OracleConnection)conn).setRemarksReporting(true); - DatabaseMetaData dbmd = conn.getMetaData(); - /** - * 获取可在指定类别中使用的表列的描述。 方法原型:ResultSet getColumns(String catalog,String - * schemaPattern,String tableNamePattern,String columnNamePattern) catalog - - * 表所在的类别名称;""表示获取没有类别的列,null表示获取所有类别的列。 schema - - * 表所在的模式名称(oracle中对应于Tablespace);""表示获取没有模式的列,null标识获取所有模式的列; - * 可包含单字符通配符("_"),或多字符通配符("%"); tableNamePattern - - * 表名称;可包含单字符通配符("_"),或多字符通配符("%"); columnNamePattern - 列名称; - * ""表示获取列名为""的列(当然获取不到);null表示获取所有的列;可包含单字符通配符("_"),或多字符通配符("%"); - */ - rs = dbmd.getColumns(null, null, "sys_fileupload", null); - - while (rs.next()) { - String tableCat = rs.getString("TABLE_CAT"); // 表类别(可能为空) - String tableSchemaName = rs.getString("TABLE_SCHEM"); // 表模式(可能为空),在oracle中获取的是命名空间,其它数据库未知 - String tableName_ = rs.getString("TABLE_NAME"); // 表名 - String columnName = rs.getString("COLUMN_NAME"); // 列名 - int dataType = rs.getInt("DATA_TYPE"); // 对应的java.sql.Types的SQL类型(列类型ID) - String dataTypeName = rs.getString("TYPE_NAME"); // java.sql.Types类型名称(列类型名称) - int columnSize = rs.getInt("COLUMN_SIZE"); // 列大小 - int decimalDigits = rs.getInt("DECIMAL_DIGITS"); // 小数位数 - int numPrecRadix = rs.getInt("NUM_PREC_RADIX"); // 基数(通常是10或2) --未知 - /** - * 0 (columnNoNulls) - 该列不允许为空 1 (columnNullable) - 该列允许为空 2 - * (columnNullableUnknown) - 不确定该列是否为空 - */ - int nullAble = rs.getInt("NULLABLE"); // 是否允许为null - String remarks = rs.getString("REMARKS"); // 列描述 - String columnDef = rs.getString("COLUMN_DEF"); // 默认值 - int charOctetLength = rs.getInt("CHAR_OCTET_LENGTH"); // 对于 char 类型,该长度是列中的最大字节数 - int ordinalPosition = rs.getInt("ORDINAL_POSITION"); // 表中列的索引(从1开始) - /** - * ISO规则用来确定某一列的是否可为空(等同于NULLABLE的值:[ 0:'YES'; 1:'NO'; 2:''; ]) YES -- 该列可以有空值; - * NO -- 该列不能为空; 空字符串--- 不知道该列是否可为空 - */ - String isNullAble = rs.getString("IS_NULLABLE"); - - /** - * 指示此列是否是自动递增 YES -- 该列是自动递增的 NO -- 该列不是自动递增 空字串--- 不能确定该列是否自动递增 - */ - // String isAutoincrement = rs.getString("IS_AUTOINCREMENT"); //该参数测试报错 - - System.out.println(tableCat + " - " + tableSchemaName + " - " + tableName_ + " - " + columnName + " - " - + dataType + " - " + dataTypeName + " - " + columnSize + " - " + decimalDigits + " - " - + numPrecRadix + " - " + nullAble + " - " + remarks + " - " + columnDef + " - " - + charOctetLength + " - " + ordinalPosition + " - " + isNullAble); - - } - } catch (SQLException ex) { - ex.printStackTrace(); - } finally { - JdbcUtil.close(rs, conn); - } - } - - /** - * @Description: TODO @author: chenzw @CreateTime: 2014-1-17 下午2:47:45 @param - * args @throws - */ - public static void main(String[] args) { - getDataBaseInfo(); // 获取数据库信息 - getSchemasInfo(); // 获取数据库所有Schema - getTablesList(); // 获取某用户下所有的表 - getTablesInfo(); // 获取表信息 - getPrimaryKeysInfo(); // 获取表主键信息 - getIndexInfo(); // 获取表索引信息 - getColumnsInfo(); // 获取表中列值信息 - } - -} diff --git a/jun_java_plugins/jun_jdbc/src/main/resources/log4j.properties b/jun_java_plugins/jun_jdbc/src/main/resources/log4j.properties deleted file mode 100644 index d9538089b1..0000000000 --- a/jun_java_plugins/jun_jdbc/src/main/resources/log4j.properties +++ /dev/null @@ -1,6 +0,0 @@ -#debug < info < warn < error < fatal -log4j.rootLogger=debug,Console - -log4j.appender.Console=org.apache.log4j.ConsoleAppender -log4j.appender.Console.layout=org.apache.log4j.PatternLayout -log4j.appender.Console.layout.ConversionPattern=%d %-5p %c(%L) %n\u4FE1\u606F\: %m%n diff --git a/jun_java_plugins/jun_jdbc/src/test/java/SQL.sql b/jun_java_plugins/jun_jdbc/src/test/java/SQL.sql deleted file mode 100644 index fffd06531d..0000000000 --- a/jun_java_plugins/jun_jdbc/src/test/java/SQL.sql +++ /dev/null @@ -1,10 +0,0 @@ -DELIMITER && -CREATE PROCEDURE pro_getBookNameById(IN bookId INT,OUT bN VARCHAR(20)) - BEGIN - SELECT bookName INTO bn FROM t_book WHERE id=bookId; - END -&& -DELIMITER ; - -CALL pro_getBookNameById(10,@bookName); -SELECT @bookName; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap02/sec03/Demo1.java b/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap02/sec03/Demo1.java deleted file mode 100644 index 8f2c1819b2..0000000000 --- a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap02/sec03/Demo1.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.jun.plugin.jdbc.chap02.sec03; - -public class Demo1 { - - private static String jdbcName="com.mysql.jdbc.Driver"; - - public static void main(String[] args) { - try { - Class.forName(jdbcName); - System.out.println("���������ɹ���"); - } catch (ClassNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - System.out.println("��������ʧ�ܣ�"); - } - } -} diff --git a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap02/sec04/Demo1.java b/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap02/sec04/Demo1.java deleted file mode 100644 index c68b64449a..0000000000 --- a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap02/sec04/Demo1.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.jun.plugin.jdbc.chap02.sec04; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -public class Demo1 { - - // ���ݿ��ַ - private static String dbUrl="jdbc:mysql://localhost:3306/db_book"; - // �û��� - private static String dbUserName="root"; - // ���� - private static String dbPassword="123456"; - // �������� - private static String jdbcName="com.mysql.jdbc.Driver"; - - public static void main(String[] args) { - try { - Class.forName(jdbcName); - System.out.println("���������ɹ���"); - } catch (ClassNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - System.out.println("��������ʧ�ܣ�"); - } - Connection con=null; - try { - // ��ȡ���ݿ����� - con=DriverManager.getConnection(dbUrl, dbUserName, dbPassword); - System.out.println("��ȡ���ݿ����ӳɹ���"); - System.out.println("�������ݿ������"); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - }finally{ - try { - con.close(); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } -} diff --git a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap03/sec02/Demo1.java b/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap03/sec02/Demo1.java deleted file mode 100644 index 5b90fd4beb..0000000000 --- a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap03/sec02/Demo1.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.jun.plugin.jdbc.chap03.sec02; - -import java.sql.Connection; -import java.sql.Statement; - -import com.jun.plugin.jdbc.util.DbUtil; - -public class Demo1 { - - public static void main(String[] args) throws Exception{ - DbUtil dbUtil=new DbUtil(); - String sql="insert into t_book values(null,'javaţ��',888,'B��',1)"; - Connection con=dbUtil.getCon(); //��ȡ�������� - Statement stmt=con.createStatement(); // ��ȡStatement - int result=stmt.executeUpdate(sql); - System.out.println("�����Ľ����"+result+"����"); - stmt.close(); // �ر�statement - con.close(); // �ر����� - } -} diff --git a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap03/sec02/Demo2.java b/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap03/sec02/Demo2.java deleted file mode 100644 index af731af630..0000000000 --- a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap03/sec02/Demo2.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.jun.plugin.jdbc.chap03.sec02; - -import java.sql.Connection; -import java.sql.Statement; - -import com.jun.plugin.jdbc.model.Book; -import com.jun.plugin.jdbc.util.DbUtil; - -public class Demo2 { - - private static DbUtil dbUtil=new DbUtil(); - - /** - * ���ͼ��2 - * @param book - * @return - * @throws Exception - */ - private static int addBook2(Book book)throws Exception{ - Connection con=dbUtil.getCon(); // ��ȡ���� - String sql="insert into t_book values(null,'"+book.getBookName()+"',"+book.getPrice()+",'"+book.getAuthor()+"',"+book.getBookTypeId()+")"; - Statement stmt=con.createStatement(); // ����Statement - int result=stmt.executeUpdate(sql); - dbUtil.close(stmt, con); // �ر�Statement������ - return result; - } - - /** - * ���ͼ�� - * @param bookName - * @param price - * @param author - * @param bookTypeId - * @return - * @throws Exception - */ - private static int addBook(String bookName,float price,String author,int bookTypeId)throws Exception{ - Connection con=dbUtil.getCon(); // ��ȡ���� - String sql="insert into t_book values(null,'"+bookName+"',"+price+",'"+author+"',"+bookTypeId+")"; - Statement stmt=con.createStatement(); // ����Statement - int result=stmt.executeUpdate(sql); - dbUtil.close(stmt, con); // �ر�Statement������ - return result; - } - - public static void main(String[] args) throws Exception{ - /*int result=addBook("Javaţţ", 121, "ţ��", 1); - if(result==1){ - System.out.println("��ӳɹ���"); - }else{ - System.out.println("���ʧ�ܣ�"); - }*/ - // ����ע�� ctrl+shift+/ - Book book=new Book("Javaţţ2", 1212, "ţ��2", 2); - int result=addBook2(book); - if(result==1){ - System.out.println("��ӳɹ���"); - }else{ - System.out.println("���ʧ�ܣ�"); - } - } -} diff --git a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap03/sec03/Demo1.java b/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap03/sec03/Demo1.java deleted file mode 100644 index cba5ac7fa6..0000000000 --- a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap03/sec03/Demo1.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.jun.plugin.jdbc.chap03.sec03; - -import java.sql.Connection; -import java.sql.Statement; - -import com.jun.plugin.jdbc.model.Book; -import com.jun.plugin.jdbc.util.DbUtil; - -public class Demo1 { - - private static DbUtil dbUtil = new DbUtil(); - - /** - * ����ͼ�� - * @param book - * @return - * @throws Exception - */ - private static int updateBook(Book book) throws Exception { - Connection con = dbUtil.getCon(); // ��ȡ���� - String sql = "update t_book set bookName='" + book.getBookName() - + "',price=" + book.getPrice() + ",author='" + book.getAuthor() - + "',bookTypeId=" + book.getBookTypeId() + " where id=" - + book.getId(); // ctrl+a ȫѡ ctrl+shift+F ��ʽ������ - Statement stmt = con.createStatement(); // ����Statement - int result = stmt.executeUpdate(sql); - dbUtil.close(stmt, con); // �ر�Statement������ - return result; - } - - public static void main(String[] args) throws Exception{ - Book book=new Book(3,"Javaţţ2222", 121, "ţ��222", 1); - int result=updateBook(book); - if(result==1){ - System.out.println("���³ɹ���"); - }else{ - System.out.println("���°ܣ�"); - } - - } -} diff --git a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap03/sec04/Demo1.java b/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap03/sec04/Demo1.java deleted file mode 100644 index 5ce89c45c0..0000000000 --- a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap03/sec04/Demo1.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.jun.plugin.jdbc.chap03.sec04; - -import java.sql.Connection; -import java.sql.Statement; - -import com.jun.plugin.jdbc.util.DbUtil; - -public class Demo1 { - - private static DbUtil dbUtil=new DbUtil(); - - /** - * ɾ��ͼ�� - * @param id - * @return - * @throws Exception - */ - private static int deleteBook(int id)throws Exception{ - Connection con = dbUtil.getCon(); // ��ȡ���� - String sql ="delete from t_book where id="+id; - Statement stmt = con.createStatement(); // ����Statement - int result = stmt.executeUpdate(sql); - dbUtil.close(stmt, con); // �ر�Statement������ - return result; - } - - public static void main(String[] args) throws Exception{ - int result=deleteBook(3); - if(result==1){ - System.out.println("ɾ���ɹ���"); - }else{ - System.out.println("ɾ��ʧ�ܣ�"); - } - } -} diff --git a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap04/sec02/Demo1.java b/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap04/sec02/Demo1.java deleted file mode 100644 index bbb6d5b9a6..0000000000 --- a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap04/sec02/Demo1.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.jun.plugin.jdbc.chap04.sec02; - -import java.sql.Connection; -import java.sql.PreparedStatement; - -import com.jun.plugin.jdbc.model.Book; -import com.jun.plugin.jdbc.util.DbUtil; - -public class Demo1 { - - private static DbUtil dbUtil=new DbUtil(); - - /** - * ���ͼ�� - * @param book - * @return - * @throws Exception - */ - private static int addBook(Book book)throws Exception{ - Connection con=dbUtil.getCon(); // ��ȡ���� - String sql="insert into t_book values(null,?,?,?,?)"; - PreparedStatement pstmt=con.prepareStatement(sql); - pstmt.setString(1, book.getBookName()); // ����һ��������ֵ - pstmt.setFloat(2, book.getPrice()); // ���ڶ���������ֵ - pstmt.setString(3, book.getAuthor()); // ��������������ֵ - pstmt.setInt(4, book.getBookTypeId()); // �����ĸ�������ֵ - int result=pstmt.executeUpdate(); - dbUtil.close(pstmt, con); - return result; - } - - public static void main(String[] args) throws Exception{ - Book book=new Book("Java���2", 1, "���", 1); - int result=addBook(book); - if(result==1){ - System.out.println("��ӳɹ���"); - }else{ - System.out.println("���ʧ�ܣ�"); - } - } -} diff --git a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap04/sec03/Demo1.java b/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap04/sec03/Demo1.java deleted file mode 100644 index 23cf9998bb..0000000000 --- a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap04/sec03/Demo1.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.jun.plugin.jdbc.chap04.sec03; - -import java.sql.Connection; -import java.sql.PreparedStatement; - -import com.jun.plugin.jdbc.model.Book; -import com.jun.plugin.jdbc.util.DbUtil; - -public class Demo1 { - - private static DbUtil dbUtil=new DbUtil(); - - /** - * ����ͼ�� - * @param book - * @return - * @throws Exception - */ - private static int updateBook(Book book)throws Exception{ - Connection con=dbUtil.getCon(); - String sql="update t_book set bookName=?,price=?,author=?,bookTypeId=? where id=?"; - PreparedStatement pstmt=con.prepareStatement(sql); - pstmt.setString(1, book.getBookName()); - pstmt.setFloat(2, book.getPrice()); - pstmt.setString(3, book.getAuthor()); - pstmt.setInt(4, book.getBookTypeId()); - pstmt.setInt(5, book.getId()); - int result=pstmt.executeUpdate(); - dbUtil.close(pstmt, con); - return result; - } - - public static void main(String[] args) throws Exception{ - Book book=new Book(12,"K2", 2, "K", 2); - int result=updateBook(book); - if(result==1){ - System.out.println("���³ɹ���"); - }else{ - System.out.println("����ʧ�ܣ�"); - } - } -} diff --git a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap04/sec04/Demo1.java b/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap04/sec04/Demo1.java deleted file mode 100644 index fb17822334..0000000000 --- a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap04/sec04/Demo1.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.jun.plugin.jdbc.chap04.sec04; - -import java.sql.Connection; -import java.sql.PreparedStatement; - -import com.jun.plugin.jdbc.util.DbUtil; - -public class Demo1 { - - private static DbUtil dbUtil=new DbUtil(); - - /** - * ɾ��ͼ�� - * @param id - * @return - * @throws Exception - */ - private static int deleteBook(int id)throws Exception{ - Connection con=dbUtil.getCon(); - String sql="delete from t_book where id=?"; - PreparedStatement pstmt=con.prepareStatement(sql); - pstmt.setInt(1, id); - int result=pstmt.executeUpdate(); - dbUtil.close(pstmt, con); - return result; - } - - public static void main(String[] args)throws Exception { - int result=deleteBook(12); - if(result==1){ - System.out.println("ɾ���ɹ���"); - }else{ - System.out.println("ɾ��ʧ�ܣ�"); - } - } -} diff --git a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap05/sec02/Demo1.java b/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap05/sec02/Demo1.java deleted file mode 100644 index 6ef4de166e..0000000000 --- a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap05/sec02/Demo1.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.jun.plugin.jdbc.chap05.sec02; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.util.ArrayList; -import java.util.List; - -import com.jun.plugin.jdbc.model.Book; -import com.jun.plugin.jdbc.util.DbUtil; - -public class Demo1 { - - private static DbUtil dbUtil = new DbUtil(); - - /** - * ������ѯ��� - * @throws Exception - */ - private static void listBook() throws Exception { - Connection con = dbUtil.getCon(); // ��ȡ���� - String sql = "select * from t_book"; - PreparedStatement pstmt = con.prepareStatement(sql); - ResultSet rs = pstmt.executeQuery(); // ���ؽ����ResultSet - while (rs.next()) { - int id = rs.getInt(1); // ��ȡ��һ���е�ֵ ���id - String bookName = rs.getString(2); // ��ȡ�ڶ����е�ֵ ͼ������ bookName - float price = rs.getFloat(3); // ��ȡ�����е�ֵ ͼ��۸� price - String author = rs.getString(4); // ��ȡ�����е�ֵ ͼ������ author - int bookTypeId = rs.getInt(5); // ��ȡ�����е�ֵ ͼ�����id - System.out.println("ͼ���ţ�" + id + " ͼ�����ƣ�" + bookName + " ͼ��۸�" - + price + " ͼ�����ߣ�" + author + " ͼ�����id��" + bookTypeId); - System.out - .println("======================================================================="); - - } - } - - /** - * ������ѯ��� - * @throws Exception - */ - private static void listBook2() throws Exception { - Connection con = dbUtil.getCon(); // ��ȡ���� - String sql = "select * from t_book"; - PreparedStatement pstmt = con.prepareStatement(sql); - ResultSet rs = pstmt.executeQuery(); // ���ؽ����ResultSet - while (rs.next()) { - int id = rs.getInt("id"); // ��ȡ��һ���е�ֵ ���id - String bookName = rs.getString("bookName"); // ��ȡ�ڶ����е�ֵ ͼ������ bookName - float price = rs.getFloat("price"); // ��ȡ�����е�ֵ ͼ��۸� price - String author = rs.getString("author"); // ��ȡ�����е�ֵ ͼ������ author - int bookTypeId = rs.getInt("bookTypeId"); // ��ȡ�����е�ֵ ͼ�����id - System.out.println("ͼ���ţ�" + id + " ͼ�����ƣ�" + bookName + " ͼ��۸�" - + price + " ͼ�����ߣ�" + author + " ͼ�����id��" + bookTypeId); - System.out - .println("======================================================================="); - - } - } - - private static List listBook3()throws Exception{ - List bookList=new ArrayList(); - Connection con = dbUtil.getCon(); // ��ȡ���� - String sql = "select * from t_book"; - PreparedStatement pstmt = con.prepareStatement(sql); - ResultSet rs = pstmt.executeQuery(); // ���ؽ����ResultSet - while (rs.next()) { - int id = rs.getInt("id"); // ��ȡ��һ���е�ֵ ���id - String bookName = rs.getString("bookName"); // ��ȡ�ڶ����е�ֵ ͼ������ bookName - float price = rs.getFloat("price"); // ��ȡ�����е�ֵ ͼ��۸� price - String author = rs.getString("author"); // ��ȡ�����е�ֵ ͼ������ author - int bookTypeId = rs.getInt("bookTypeId"); // ��ȡ�����е�ֵ ͼ�����id - Book book=new Book(id, bookName, price, author, bookTypeId); - bookList.add(book); - } - return bookList; - } - - public static void main(String[] args) throws Exception { - // listBook(); - // listBook2(); - List bookList=listBook3(); - for (Book book : bookList) { - System.out.println(book); - } - } -} diff --git a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap06/sec01/Demo1.java b/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap06/sec01/Demo1.java deleted file mode 100644 index 2db4b49c2c..0000000000 --- a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap06/sec01/Demo1.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.jun.plugin.jdbc.chap06.sec01; - -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.sql.Clob; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; - -import com.jun.plugin.jdbc.model.Book; -import com.jun.plugin.jdbc.util.DbUtil; - -public class Demo1 { - -private static DbUtil dbUtil=new DbUtil(); - - /** - * ���ͼ�� - * @param book - * @return - * @throws Exception - */ - private static int addBook(Book book)throws Exception{ - Connection con=dbUtil.getCon(); // ��ȡ���� - String sql="insert into t_book values(null,?,?,?,?,?)"; - PreparedStatement pstmt=con.prepareStatement(sql); - pstmt.setString(1, book.getBookName()); // ����һ��������ֵ - pstmt.setFloat(2, book.getPrice()); // ���ڶ���������ֵ - pstmt.setString(3, book.getAuthor()); // ��������������ֵ - pstmt.setInt(4, book.getBookTypeId()); // �����ĸ�������ֵ - File context=book.getContext(); // ��ȡ�ļ� - InputStream inputStream=new FileInputStream(context); - pstmt.setAsciiStream(5, inputStream,context.length()); // �������������ֵ - int result=pstmt.executeUpdate(); - dbUtil.close(pstmt, con); - return result; - } - - public static void getBook(int id)throws Exception{ - Connection con=dbUtil.getCon(); - String sql="select * from t_book where id=?"; - PreparedStatement pstmt=con.prepareStatement(sql); - pstmt.setInt(1, id); - ResultSet rs=pstmt.executeQuery(); - if(rs.next()){ - String bookName=rs.getString("bookName"); - float price=rs.getFloat("price"); - String author=rs.getString("author"); - int bookTypeId=rs.getInt("bookTypeId"); - Clob c=rs.getClob("context"); - String context=c.getSubString(1, (int)c.length()); - System.out.println("ͼ�����ƣ�"+bookName); - System.out.println("ͼ��۸�:"+price); - System.out.println("ͼ�����ߣ�"+author); - System.out.println("ͼ������ID��"+bookTypeId); - System.out.println("ͼ�����ݣ�"+context); - } - dbUtil.close(pstmt, con); - } - - public static void main(String[] args)throws Exception { - /*File context=new File("c:/helloWorld.txt"); - Book book=new Book("helloWorld", 100, "С��", 1,context); - int result=addBook(book); - if(result==1){ - System.out.println("��ӳɹ���"); - }else{ - System.out.println("���ʧ�ܣ�"); - }*/ - getBook(16); - } -} diff --git a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap06/sec02/Demo1.java b/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap06/sec02/Demo1.java deleted file mode 100644 index d0c2413af2..0000000000 --- a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap06/sec02/Demo1.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.jun.plugin.jdbc.chap06.sec02; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.sql.Blob; -import java.sql.Clob; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; - -import com.jun.plugin.jdbc.model.Book; -import com.jun.plugin.jdbc.util.DbUtil; - -public class Demo1 { - -private static DbUtil dbUtil=new DbUtil(); - - /** - * ���ͼ�� - * @param book - * @return - * @throws Exception - */ - private static int addBook(Book book)throws Exception{ - Connection con=dbUtil.getCon(); // ��ȡ���� - String sql="insert into t_book values(null,?,?,?,?,?,?)"; - PreparedStatement pstmt=con.prepareStatement(sql); - pstmt.setString(1, book.getBookName()); // ����һ��������ֵ - pstmt.setFloat(2, book.getPrice()); // ���ڶ���������ֵ - pstmt.setString(3, book.getAuthor()); // ��������������ֵ - pstmt.setInt(4, book.getBookTypeId()); // �����ĸ�������ֵ - File context=book.getContext(); // ��ȡ�ļ� - InputStream inputStream=new FileInputStream(context); - pstmt.setAsciiStream(5, inputStream,context.length()); // �������������ֵ - - File pic=book.getPic(); // ��ȡͼƬ�ļ� - InputStream inputStream2=new FileInputStream(pic); - pstmt.setBinaryStream(6, inputStream2, pic.length()); // ��������������ֵ - int result=pstmt.executeUpdate(); - dbUtil.close(pstmt, con); - return result; - } - - public static void getBook(int id)throws Exception{ - Connection con=dbUtil.getCon(); - String sql="select * from t_book where id=?"; - PreparedStatement pstmt=con.prepareStatement(sql); - pstmt.setInt(1, id); - ResultSet rs=pstmt.executeQuery(); - if(rs.next()){ - String bookName=rs.getString("bookName"); - float price=rs.getFloat("price"); - String author=rs.getString("author"); - int bookTypeId=rs.getInt("bookTypeId"); - Clob c=rs.getClob("context"); - String context=c.getSubString(1, (int)c.length()); - Blob b=rs.getBlob("pic"); - FileOutputStream out=new FileOutputStream(new File("d:/pic2.jpg")); - out.write(b.getBytes(1, (int)b.length())); - out.close(); - System.out.println("ͼ�����ƣ�"+bookName); - System.out.println("ͼ��۸�:"+price); - System.out.println("ͼ�����ߣ�"+author); - System.out.println("ͼ������ID��"+bookTypeId); - System.out.println("ͼ�����ݣ�"+context); - } - dbUtil.close(pstmt, con); - } - - public static void main(String[] args)throws Exception { - /*File context=new File("c:/helloWorld.txt"); - File pic=new File("c:/pic1.jpg"); - Book book=new Book("helloWorld", 100, "С��", 1,context,pic); - int result=addBook(book); - if(result==1){ - System.out.println("��ӳɹ���"); - }else{ - System.out.println("���ʧ�ܣ�"); - }*/ - getBook(18); - } -} diff --git a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap07/sec02/Demo1.java b/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap07/sec02/Demo1.java deleted file mode 100644 index 9a14eb903e..0000000000 --- a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap07/sec02/Demo1.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.jun.plugin.jdbc.chap07.sec02; - -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.Types; - -import com.jun.plugin.jdbc.util.DbUtil; - -public class Demo1 { - - private static DbUtil dbUtil=new DbUtil(); - - /** - * ���ô洢���̣�ͨ��id��ѯbookName - * @param id - * @return - * @throws Exception - */ - private static String getBookNameById(int id)throws Exception{ - Connection con=dbUtil.getCon(); // ��ȡ���ݿ����� - String sql="{CALL pro_getBookNameById(?,?)}"; - CallableStatement cstmt=con.prepareCall(sql); - cstmt.setInt(1, id); // ���õ�һ������ - cstmt.registerOutParameter(2, Types.VARCHAR); // ���÷������� - cstmt.execute(); - String bookName=cstmt.getString("bN"); // ��ȡ����ֵ - dbUtil.close(cstmt, con); - return bookName; - } - - public static void main(String[] args) throws Exception{ - System.out.println("ͼ�������ǣ�"+getBookNameById(11)); - } -} diff --git a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap08/sec01/Demo1.java b/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap08/sec01/Demo1.java deleted file mode 100644 index 28c0ee7d87..0000000000 --- a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap08/sec01/Demo1.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.jun.plugin.jdbc.chap08.sec01; - -import java.sql.Connection; -import java.sql.DatabaseMetaData; - -import com.jun.plugin.jdbc.util.DbUtil; - -public class Demo1 { - - public static void main(String[] args)throws Exception { - DbUtil dbUtil=new DbUtil(); - Connection con=dbUtil.getCon(); - DatabaseMetaData dmd=con.getMetaData(); // ��ȡԪ���� - System.out.println("���ݿ����ƣ�"+dmd.getDatabaseProductName()); - System.out.println("���ݿ�汾��"+dmd.getDriverMajorVersion()+"."+dmd.getDriverMinorVersion()); - - } -} diff --git a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap08/sec02/Demo2.java b/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap08/sec02/Demo2.java deleted file mode 100644 index 53888dae99..0000000000 --- a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap08/sec02/Demo2.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.jun.plugin.jdbc.chap08.sec02; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSetMetaData; - -import com.jun.plugin.jdbc.util.DbUtil; - -public class Demo2 { - - public static void main(String[] args) throws Exception{ - DbUtil dbUtil=new DbUtil(); - Connection con=dbUtil.getCon(); - String sql="select * from t_book"; - PreparedStatement pstmt=con.prepareStatement(sql); - ResultSetMetaData rsmd=pstmt.getMetaData(); - int num=rsmd.getColumnCount(); // ��ȡԪ�����е����� - System.out.println("����"+num+"��"); - for(int i=1;i<=num;i++){ - System.out.println(rsmd.getColumnName(i)+","+rsmd.getColumnTypeName(i)); - } - } -} diff --git a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap09/sec03/Demo1.java b/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap09/sec03/Demo1.java deleted file mode 100644 index 1eb276cc1b..0000000000 --- a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap09/sec03/Demo1.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.jun.plugin.jdbc.chap09.sec03; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; - -import com.jun.plugin.jdbc.util.DbUtil; - -public class Demo1 { - - private static DbUtil dbUtil=new DbUtil(); - - /** - * ת�� - * @param con - * @param accountName - * @param account - * @throws Exception - */ - private static void outCount(Connection con,String accountName,int account)throws Exception{ - String sql="update t_account set accountBalance=accountBalance-? where accountName=?"; - PreparedStatement pstmt=con.prepareStatement(sql); - pstmt.setInt(1, account); - pstmt.setString(2, accountName); - pstmt.executeUpdate(); - } - - /** - * ת�� - * @param con - * @param accountName - * @param account - * @throws Exception - */ - private static void inCount(Connection con,String accountName,int account)throws Exception{ - String sql="update t_account set account=accountBalance+? where accountName=?"; - PreparedStatement pstmt=con.prepareStatement(sql); - pstmt.setInt(1, account); - pstmt.setString(2, accountName); - pstmt.executeUpdate(); - } - - - public static void main(String[] args) { - Connection con=null; - try { - con=dbUtil.getCon(); - con.setAutoCommit(false); // ȡ���Զ��ύ - System.out.println("������ʼ������ת�ˣ�"); - int account=500; - outCount(con, "����", account); - inCount(con, "����", account); - System.out.println("ת�˳ɹ���"); - } catch (Exception e) { - try { - con.rollback(); // �ع� - } catch (SQLException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - // TODO Auto-generated catch block - e.printStackTrace(); - }finally{ - try { - con.commit(); // �ύ���� - con.close(); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } -} diff --git a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap09/sec04/Demo1.java b/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap09/sec04/Demo1.java deleted file mode 100644 index 09d7201557..0000000000 --- a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/chap09/sec04/Demo1.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.jun.plugin.jdbc.chap09.sec04; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.sql.Savepoint; - -import com.jun.plugin.jdbc.util.DbUtil; - -public class Demo1 { - - private static DbUtil dbUtil=new DbUtil(); - - /** - * ת�� - * @param con - * @param accountName - * @param account - * @throws Exception - */ - private static void outCount(Connection con,String accountName,int account)throws Exception{ - String sql="update t_account set accountBalance=accountBalance-? where accountName=?"; - PreparedStatement pstmt=con.prepareStatement(sql); - pstmt.setInt(1, account); - pstmt.setString(2, accountName); - pstmt.executeUpdate(); - } - - /** - * ת�� - * @param con - * @param accountName - * @param account - * @throws Exception - */ - private static void inCount(Connection con,String accountName,int account)throws Exception{ - String sql="update t_account set account=accountBalance+? where accountName=?"; - PreparedStatement pstmt=con.prepareStatement(sql); - pstmt.setInt(1, account); - pstmt.setString(2, accountName); - pstmt.executeUpdate(); - } - - - public static void main(String[] args) { - Connection con=null; - Savepoint sp=null; - try { - con=dbUtil.getCon(); - con.setAutoCommit(false); // ȡ���Զ��ύ - System.out.println("������ʼ������ת�ˣ�"); - int account=500; - outCount(con, "����", account); - sp=con.setSavepoint(); // ����һ������� - inCount(con, "����", account); - System.out.println("ת�˳ɹ���"); - } catch (Exception e) { - try { - con.rollback(sp); // �ع���sp����� - } catch (SQLException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - // TODO Auto-generated catch block - e.printStackTrace(); - }finally{ - try { - con.commit(); // �ύ���� - con.close(); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } -} diff --git a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/model/Book.java b/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/model/Book.java deleted file mode 100644 index 47e38d1b07..0000000000 --- a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/model/Book.java +++ /dev/null @@ -1,113 +0,0 @@ -package com.jun.plugin.jdbc.model; - -import java.io.File; - -/** - * ͼ��ģ�� - * @author caofeng - * - */ -public class Book { - - private int id; - private String bookName; - private float price; - private String author; - private int bookTypeId; - private File context; - private File pic; - - - - public Book(int id, String bookName, float price, String author, - int bookTypeId) { - super(); - this.id = id; - this.bookName = bookName; - this.price = price; - this.author = author; - this.bookTypeId = bookTypeId; - } - public Book(String bookName, float price, String author, int bookTypeId) { - super(); - this.bookName = bookName; - this.price = price; - this.author = author; - this.bookTypeId = bookTypeId; - } - - - public Book(String bookName, float price, String author, int bookTypeId, - File context) { - super(); - this.bookName = bookName; - this.price = price; - this.author = author; - this.bookTypeId = bookTypeId; - this.context = context; - } - - - public Book(String bookName, float price, String author, int bookTypeId, - File context, File pic) { - super(); - this.bookName = bookName; - this.price = price; - this.author = author; - this.bookTypeId = bookTypeId; - this.context = context; - this.pic = pic; - } - public int getId() { - return id; - } - public void setId(int id) { - this.id = id; - } - public String getBookName() { - return bookName; - } - public void setBookName(String bookName) { - this.bookName = bookName; - } - public float getPrice() { - return price; - } - public void setPrice(float price) { - this.price = price; - } - public String getAuthor() { - return author; - } - public void setAuthor(String author) { - this.author = author; - } - public int getBookTypeId() { - return bookTypeId; - } - public void setBookTypeId(int bookTypeId) { - this.bookTypeId = bookTypeId; - } - - - public File getContext() { - return context; - } - public void setContext(File context) { - this.context = context; - } - - - public File getPic() { - return pic; - } - public void setPic(File pic) { - this.pic = pic; - } - @Override - public String toString() { - return "["+this.id+","+this.bookName+","+this.price+","+this.author+","+this.bookTypeId+"]"; - } - - -} diff --git a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/util/DbUtil.java b/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/util/DbUtil.java deleted file mode 100644 index 1d895ec07f..0000000000 --- a/jun_java_plugins/jun_jdbc/src/test/java/com/jun/plugin/jdbc/util/DbUtil.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.jun.plugin.jdbc.util; - -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.Statement; - -import com.mysql.jdbc.PreparedStatement; - -public class DbUtil { - - // ���ݿ��ַ - private static String dbUrl="jdbc:mysql://localhost:3306/db_bank"; - // �û��� - private static String dbUserName="root"; - // ���� - private static String dbPassword="123456"; - // �������� - private static String jdbcName="com.mysql.jdbc.Driver"; - - /** - * ��ȡ���ݿ����� - * @return - * @throws Exception - */ - public Connection getCon()throws Exception{ - Class.forName(jdbcName); - Connection con=DriverManager.getConnection(dbUrl, dbUserName, dbPassword); - return con; - } - - /** - * �ر����� - * @param con - * @throws Exception - */ - public void close(Statement stmt,Connection con)throws Exception{ - if(stmt!=null){ - stmt.close(); - if(con!=null){ - con.close(); - } - } - } - - /** - * �ر����� - * @param con - * @throws Exception - */ - public void close(PreparedStatement pstmt,Connection con)throws Exception{ - if(pstmt!=null){ - pstmt.close(); - if(con!=null){ - con.close(); - } - } - } - - /** - * �ر����� - * @param con - * @throws Exception - */ - public void close(CallableStatement cstmt,Connection con)throws Exception{ - if(cstmt!=null){ - cstmt.close(); - if(con!=null){ - con.close(); - } - } - } -} diff --git a/jun_java_plugins/jun_jdbc/src/test/java/db_bank.sql b/jun_java_plugins/jun_jdbc/src/test/java/db_bank.sql deleted file mode 100644 index 67792cc391..0000000000 --- a/jun_java_plugins/jun_jdbc/src/test/java/db_bank.sql +++ /dev/null @@ -1,37 +0,0 @@ -/* -SQLyog 企业版 - MySQL GUI v8.14 -MySQL - 5.1.49-community : Database - db_bank -********************************************************************* -*/ - -/*!40101 SET NAMES utf8 */; - -/*!40101 SET SQL_MODE=''*/; - -/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; -/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; -/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; -/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -CREATE DATABASE /*!32312 IF NOT EXISTS*/`db_bank` /*!40100 DEFAULT CHARACTER SET utf8 */; - -USE `db_bank`; - -/*Table structure for table `t_account` */ - -DROP TABLE IF EXISTS `t_account`; - -CREATE TABLE `t_account` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `accountName` varchar(20) DEFAULT NULL, - `accountBalance` int(11) DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; - -/*Data for the table `t_account` */ - -insert into `t_account`(`id`,`accountName`,`accountBalance`) values (1,'张三',500),(2,'李四',1000); - -/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; -/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; -/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; -/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; diff --git a/jun_java_plugins/jun_jdk/README.md b/jun_java_plugins/jun_jdk/README.md deleted file mode 100644 index 99b2c838f3..0000000000 --- a/jun_java_plugins/jun_jdk/README.md +++ /dev/null @@ -1,106 +0,0 @@ -
- -[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](http://github.com/hhyo/archery/blob/master/LICENSE) -[![996.icu](https://img.shields.io/badge/link-996.icu-red.svg)](https://996.icu) - -
- -## java-study - -**介绍** - -[java-study](https://github.com/xuwujing/java-study) 是本人学习Java过程中记录的一些代码!从Java基础的数据类型、jdk1.8的使用、IO、集合、线程等等技术以及一些常用框架,netty、mina、springboot、kafka、storm、zookeeper、es、redis、hbase、hive等等。 - -**使用** - -下载: - - git clone https://github.com/xuwujing/java-study - -然后使用maven方式导入IDE中运行main方法即可。 - -## 项目结构 - - com.pancm.arithmetic - 一些算法相关类 - com.pancm.basics - 一些Java基础相关类 主要是三大特性、修饰符、io、集合、反射、克隆等等相关代码 - com.pancm.bigdata - 大数据相关的类 主要是hbase、storm、zookeeper等等相关的代码 - com.pancm.commons - 一些第三方工具类的测试用例 主要是apache commons、apache lang、google common、google guava、joda等等一些工具包测试使用代码 - com.pancm.design - 设计模式相关的示例类 包含常用的23种设计模式 - com.pancm.elasticsearch - elasticsearch相关使用的测试用例,包括索引mapping的创建、全文检索、聚合查询等等 - com.pancm.jdk8 - jdk1.8相关的类 主要是lambda、stream以及LocalDateTime等等测试代码 - com.pancm.mq - 一些消息中间件的类,主要包含kafka、rabbitmq相关的测试代码 - com.pancm.nio - 一些nio框架,主要是netty和mina - com.pancm.others - 一些不知道怎么定义的测试类,Jsoup(爬虫)、logback、lombok等等测试代码 - com.pancm.pojo - 实体相关类 - com.pancm.question - 一些面试可能会问的问题的类 - com.pancm.redis - redis相关使用的类 - com.pancm.sql - 一些数据库相关的类 - com.pancm.thread - 一些线程相关的类 从基本的使用到各种并发的测试类 - com.pancm.utils - 一些常用的工具类 主要是Json数据转换,日期转换,二维码图片生成工具类,常用的AES、MD5、BASE64等等编码解码工具类,redis、kafka、zookeeper等等工具类 - -## 相关文章 - -这里介绍的文章主要是本人写的一些博客。博客主要发布在[个人博客](http://www.panchengming.com)、[CSDN](https://blog.csdn.net/qazwsxpcm)、[博客园](https://www.cnblogs.com/xuwujing/)等,但是由于个人博客在github上,访问可能较慢,CSDN目前观感体验不好,所以以下链接主要就在博客园中了。 - -**Java基础相关:** - -- [基本数据类型](https://www.cnblogs.com/xuwujing/p/8597557.html) -- [修饰符和String](https://www.cnblogs.com/xuwujing/p/8638329.html) -- [封装、继承和多态](https://www.cnblogs.com/xuwujing/p/8681123.html) -- [集合List、Map和Set](https://www.cnblogs.com/xuwujing/p/8886821.html) -- [多线程](https://www.cnblogs.com/xuwujing/p/9102870.html) -- [IO流](https://www.cnblogs.com/xuwujing/p/9191546.html) -- [总结篇](https://www.cnblogs.com/xuwujing/p/9236376.html) - -**设计模式:** - -- [单例模式](https://www.cnblogs.com/xuwujing/p/9277266.html) -- [工厂方法和抽象工厂模式](https://www.cnblogs.com/xuwujing/p/9363142.html) -- [建造者模式和原型模式](https://www.cnblogs.com/xuwujing/p/9496346.html) -- [适配器模式和桥接模式](https://www.cnblogs.com/xuwujing/p/9520851.html) -- [外观模式和装饰器模式](https://www.cnblogs.com/xuwujing/p/9545272.html) -- [组合模式和过滤器模式](https://www.cnblogs.com/xuwujing/p/9630850.html) -- [享元模式和代理模式](https://www.cnblogs.com/xuwujing/p/9704228.html) -- [责任链模式和命令模式](https://www.cnblogs.com/xuwujing/p/9794886.html) -- [解释器模式和迭代器模式](https://www.cnblogs.com/xuwujing/p/9873514.html) -- [访问者模式和中介者模式](https://www.cnblogs.com/xuwujing/p/9911997.html) -- [策略模式和模板方法模式](https://www.cnblogs.com/xuwujing/p/9954263.html) -- [观察者模式和空对象模式](https://www.cnblogs.com/xuwujing/p/10036204.html) -- [总结篇](https://www.cnblogs.com/xuwujing/p/10134494.html) - -**JAVA进阶相关:** - -- [JDK1.8的Lambda、Stream和日期的使用详解](https://www.cnblogs.com/xuwujing/p/10145691.html) - - -**大数据相关:** -- [大数据学习系列之三 ----- HBase Java Api 图文详解](https://www.cnblogs.com/xuwujing/p/8039175.html) -- [Kafka 使用Java实现数据的生产和消费demo](https://www.cnblogs.com/xuwujing/p/8371127.html) -- [关于Kafka 的 consumer 消费者手动提交详解](https://www.cnblogs.com/xuwujing/p/8432984.html) -- [Storm 入门的Demo教程](https://www.cnblogs.com/xuwujing/p/8584684.html) - - -**ElasticSearch相关:** -- [ElasticSearch实战系列一: ElasticSearch集群+Kinaba安装教程](https://www.cnblogs.com/xuwujing/p/11385255.html) -- [ElasticSearch实战系列二: ElasticSearch的DSL语句使用教程---图文详解](https://www.cnblogs.com/xuwujing/p/11567053.html) -- [ElasticSearch实战系列三: ElasticSearch的JAVA API使用教程](https://www.cnblogs.com/xuwujing/p/11645630.html) -- [ElasticSearch实战系列四: ElasticSearch理论知识介绍](https://www.cnblogs.com/xuwujing/p/12093933.html) - - - -**其他博客:** - -- [两年JAVA程序员的面试总结](https://www.cnblogs.com/xuwujing/p/7613084.html) -- [一个两年java程序猿的2017个人总结](https://www.cnblogs.com/xuwujing/p/8158716.html) -- [写了一年的博客,我收获了什么](https://www.cnblogs.com/xuwujing/p/8747769.html) -- [给刚工作不久的程序猿同学的一封信](https://www.cnblogs.com/xuwujing/p/9665966.html) -- [一个平凡但不平庸的程序猿2018个人总结](https://www.cnblogs.com/xuwujing/p/9665966.html) -- [个人收集的资源分享](https://www.cnblogs.com/xuwujing/p/10393111.html) -- [一个毕业三年的程序猿对于提升自我的一些建议](https://www.cnblogs.com/xuwujing/p/11735726.html) -- [认清自我,不在迷茫!2019个人年终总结!](https://www.cnblogs.com/xuwujing/p/12174112.html) - -## 其他 - -在这些代码中,虽然大部分都是自己写的,但是也有不少是在学习过程中从网上或书上直接摘抄的,当时有些并未标明出处,现在由于忘了出处,有些代码并未标明,若有冒犯,请见谅! - -Thanks to [Jetbrains](https://www.jetbrains.com/?from=java-study) for IDE support! \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/pom.xml b/jun_java_plugins/jun_jdk/pom.xml deleted file mode 100644 index 5cb3ee4985..0000000000 --- a/jun_java_plugins/jun_jdk/pom.xml +++ /dev/null @@ -1,401 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_jdk - 1.0 - jar - - - UTF-8 - - - - - - com.google.guava - guava - 29.0-jre - - - - mysql - mysql-connector-java - 5.1.40 - - - cglib - cglib - 3.1 - - - - - junit - junit - 4.12 - - - - - - - - - org.slf4j - slf4j-api - 1.7.25 - - - - - ch.qos.logback - logback-classic - 1.2.3 - - - - ch.qos.logback - logback-core - 1.2.3 - - - - - - - - com.fasterxml.jackson.jaxrs - jackson-jaxrs-json-provider - 2.9.6 - - - - - com.google.code.gson - gson - 2.8.5 - - - - - com.alibaba - fastjson - 1.2.49 - - - - commons-codec - commons-codec - 1.11 - - - - - - commons-lang - commons-lang - 2.6 - - - - org.apache.commons - commons-lang3 - 3.7 - - - - - org.apache.commons - commons-compress - 1.18 - - - - - - - - - - - - - - com.github.pagehelper - pagehelper - 4.1.0 - - - - - org.projectlombok - lombok - 1.18.20 - - - - - com.geccocrawler - gecco - 1.2.8 - - - - - - com.google.protobuf - protobuf-java - 3.5.1 - - - - - - - - org.springframework - spring-beans - 5.2.1.RELEASE - - - - - - - - - - - - - - - - - - - - org.xerial - sqlite-jdbc - 3.20.1 - - - - - com.microsoft.sqlserver - sqljdbc4 - 4.0 - - - - - - - - - - - io.netty - netty-all - 4.1.42.Final - - - - - org.apache.mina - mina-core - 2.0.16 - - - - - com.github.kevinsawicki - http-request - 6.0 - - - - - - - - - - - - - com.rabbitmq - amqp-client - 4.3.0 - - - - - org.apache.kafka - kafka_2.12 - 1.0.0 - - - org.apache.zookeeper - zookeeper - - - org.slf4j - slf4j-log4j12 - - - log4j - log4j - - - - - - - org.apache.kafka - kafka-clients - 1.0.0 - - - - org.apache.kafka - kafka-streams - 1.0.0 - - - - - - - - - - org.apache.zookeeper - zookeeper - 3.4.10 - - - org.slf4j - slf4j-log4j12 - - - log4j - log4j - - - - - - - com.101tec - zkclient - 0.10 - - - - - org.apache.hbase - hbase-client - 2.1.4 - - - org.apache.hbase - hbase-common - 2.1.4 - - - - org.apache.storm - storm-core - 1.2.2 - provided - - - - org.apache.storm - storm-kafka - 1.2.2 - provided - - - - - - - - - org.elasticsearch.client - elasticsearch-rest-high-level-client - 6.6.1 - - - - - io.searchbox - jest - 6.3.1 - - - - - - jun_jdk - - diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/App.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/App.java deleted file mode 100644 index c666f0340d..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/App.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.jun.plugin; - -/** - * Hello world! - * - */ -public class App -{ - public static void main( String[] args ) - { - System.out.println( "Hello World!" ); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/arithmetic/PatternMatchingTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/arithmetic/PatternMatchingTest.java deleted file mode 100644 index 102bd06aa5..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/arithmetic/PatternMatchingTest.java +++ /dev/null @@ -1,163 +0,0 @@ -package com.jun.plugin.arithmetic; - -import java.util.Scanner; - -/** - * @Title: PatternMatchingTest - * @Description: 模式匹配算法 - * 来源:http://www.cnblogs.com/jiaohanhan/p/6654874.html - * @Version:1.0.0 - * @author pancm - * @date 2018年9月14日 - */ -public class PatternMatchingTest { - - - - /** - * 暴力匹配 - *  时间复杂度为O(n*m);n为主串长度,m为模式串长度 -   算法的基本思想: -      从主串的起始位置(或指定位置)开始与模式串的第一个字符比较,若相等,则继续逐个比较后续字符; - 否则从主串的下一个字符再重新和模式串的字符比较。 - 依次类推,直到模式串成功匹配,返回主串中第一次出现模式串字符的位置,或者模式串匹配不成功,这里约定返回-1; - * @param source - * @param pattern - * @return - */ - public static int bruteForceStringMatch(String source, String pattern) { - int slen = source.length(); - int plen = pattern.length(); - char[] s = source.toCharArray(); - char[] p = pattern.toCharArray(); - int i = 0; - int j = 0; - - if (slen < plen) - return -1; // 如果主串长度小于模式串,直接返回-1,匹配失败 - else { - while (i < slen && j < plen) { - if (s[i] == p[j]) // 如果i,j位置上的字符匹配成功就继续向后匹配 - { - ++i; - ++j; - } else { - i = i - (j - 1); // i回溯到主串上一次开始匹配下一个位置的地方 - j = 0; // j重置,模式串从开始再次进行匹配 - } - } - if (j == plen) // 匹配成功 - return i - j; - else - return -1; // 匹配失败 - } - } - - - - - - /** - * KMP算法 -   KMP算法是D.E.Knuth、V.R.Pratt和J.H.Morris同时发现,所以命名为KMP算法。 -   此算法可以在O(n+m)的时间数量级上完成串的模式匹配。 -   主要就是改进了暴力匹配中i回溯的操作,KMP算法中当一趟匹配过程中出现字符比较不等时, - 不直接回溯i,而是利用已经得到的“部分匹配”的结果将模式串向右移动(j-next[k])的距离。 - - * @param source - * @param pattern - * @return - */ - public static int kmpStringMatch(String source, String pattern) - { - int i = 0; - int j = 0; - char[] s = source.toCharArray(); - char[] p = pattern.toCharArray(); - int slen = s.length; - int plen = p.length; - int[] next = getNext(p); - while(i < slen && j < plen) - { - if(j == -1 || s[i] == p[j]) - { - ++i; - ++j; - } - else - { - //如果j != -1且当前字符匹配失败,则令i不变, - //j = next[j],即让pattern模式串右移j - next[j]个单位 - j = next[j]; - } - } - - - if(j == plen) - return i - j; - else - return -1; - } - - - /** - * 关于next[k]数组的计算引出的两种办法,一种是递归,一种对递归优化,第一种对应的就是KMP算法,第二种就是优化的KMP算法。 - next函数值仅取决于模式串本身而和主串无关。 - 有很多讲next函数值计算办法的资料,在此我想用一种直观的比较容易理解的办法来表达。 - 举个栗子:现在有一个模式串abab - - 模式串的各个字串  前缀 后缀 最大公共元素长度 - a null null 0 - ab a b 0 - aba a,ab a,ba 1 - abab a,ab,aba b,ab,bab 2 - * @param p - * @return - */ - private static int[] getNext(char[] p) - { - /** - * 已知next[j] = k, 利用递归的思想求出next[j+1]的值 - * 1.如果p[j] = p[k],则next[j+1] = next[k] + 1; - * 2.如果p[j] != p[k],则令k = next[k],如果此时p[j] == p[k],则next[j+1] = k+1 - * 如果不相等,则继续递归前缀索引,令k=next[k],继续判断,直至k=-1(即k=next[0])或者p[j]=p[k]为止 - */ - int plen = p.length; - int[] next = new int[plen]; - int k = -1; - int j = 0; - next[0] = -1; //这里采用-1做标识 - while(j < plen -1) - { - if(k == -1 || p[j] == p[k]) - { - ++k; - ++j; - next[j] = k; - } - else - { - k = next[k]; - } - } - System.out.println("next函数值:"); - for(int ii = 0;ii执行耗时 : "+(System.currentTimeMillis()-a)+"毫秒 "); -// int[] p=sort(t); -// for(int i=0,j=p.length;i执行耗时 : "+(System.currentTimeMillis()-a)+"毫秒 "); - } - - /** - * 插入排序 升序 - * 插入排序是循环数组,然后将前一位的数字和后一位的进行比较,将数值大的向后移一位 - * @param a - * @return - */ - public static int[] ps(int[] a){ - for(int i=1,j=a.length;i=0;k--){ - if(a[k]>t){ - a[k+1]=a[k]; - }else{ - break; - } - } - a[k+1]=t; - } - return a; - } - - /** - * 插入排序 降序 - * 插入排序是循环数组,然后将前一位的数字和后一位的进行比较,将数值大的向后移一位 - * @param a - * @return - */ - public static int[] crps(int[] a){ - for(int i=1,j=a.length;i=0;k--){ - if(a[k]m[j]){ - int tmp=m[i]; - m[i]=m[j]; - m[j]=tmp; - } - } - } - return m; - } - - /** - * 冒泡排序 倒序 - * 冒泡排序 是双重循环数组,前一位和后一位进行比较,若前一位大于后一位,就交换位置 - */ - public static int[] mpdx(int[] a){ - for(int i=0;i= left; j--) { - a[j+1] = a[j]; - } - if(left != i){ - a[left] = temp; - } - } - return a; - } - - /** - * 快速排序 - * @param a - */ - private static void quick(int[] a) { - if(a.length>0){ - quickSort(a,0,a.length-1); - } - } - - private static void quickSort(int[] a, int low, int high) { - if(low=temp){ - high--; - } - a[low] = a[high]; - while(low 1 && !result) { - result = true; - duplication[0] = numbers[i]; - } - } - return result; - } - - /** - * 先排序,然后找到排序后数组中第一个重复的数字(主要就是练习一下快排) - * @param numbers - * @param length - * @param duplication - * @return - */ - public boolean sortThenFindFirstDuplicateNumber(int[] numbers, int length, int[] duplication) { - if (numbers == null) { - return false; - } - quickSort(numbers, 0, length-1); - int temp = numbers[0]; - boolean result = false; - - for (int i = 1; i < length; i++) { - if (numbers[i] == temp) { - result = true; - duplication[0] = temp; - break; - } - temp = numbers[i]; - } - return result; - } - - /** - * 将值为 i 的元素调整到下标为 i 的位置,如果该位置上的数已经等于 i 了,就说明 i 已经重复了 - * @param numbers - * @param length - * @param duplication - * @return - */ - public static boolean jz(int[] numbers, int length, int[] duplication) { - for (int i = 0; i < length; i++) { - //第 i 个位置上的数 numbers[i] 若不与下标 i 相等,就把 numbers[i] 放到下标为 numbers[i] 的位置 - while (numbers[i] != i) { - //在交换位置之前还要检查 numbers[i] 位置上的数字是否已经是 numbers[i],如果是就已经找到了重复的数字 - if (numbers[numbers[i]] == numbers[i]) { - duplication[0] = numbers[i]; - //注意这里不是 break - return true; - } - - //交换下标为 i、numbers[i] 两个位置上的数字(保证下标为 numbers[i] 的位置,放置的数字是 numbers[i]) - swap(numbers, i, numbers[i]); - } - } - return false; - } - - /** - * 交换下标为 i、j 的两个数 - * @param numbers - * @param i - * @param j - */ - public static void swap(int[] numbers, int i, int j) { - int swap = numbers[i]; - numbers[i] = numbers[j]; - numbers[j] = swap; - } - - /** - * 快排 - * @param array - * @param length - */ - @SuppressWarnings("all") - public static void quickSort(int[] array, int low, int high) { - //这里必须首先限制 low temp && h > l) { - h--; - } - array[l] = array[h]; - while (array[l] <= temp && l < h) { - l++; - } - array[h] = array[l]; - } - array[l] = temp; - quickSort(array, low, h-1); - quickSort(array, l+1, high); - } - } - - public static void main(String[] args) { - int[] result = new int[1]; - jz(new int[]{2,4,2,1,4}, 5, result); - System.out.println(result[0]); -// int[] d = new int[1]; -// jz(new int[]{2,1,3,0,4}, 5, d); -// int[] array = new int[]{1,4,4,4,12,78,8,45,67,39,20,90,65,34,34,6,7,88,9,1,-3,-88,-2}; - int[] array = new int[]{2,4,3,1,4}; - quickSort(array, 0, array.length-1); - for (int i = 0; i < array.length; i++) { - System.out.println(array[i]); - } - - } - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/arithmetic/jzoffer/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/arithmetic/jzoffer/package-info.java deleted file mode 100644 index 20b85a10b1..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/arithmetic/jzoffer/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -/** - * @description: 剑指 Offer 中的题目 - * @author: Zhoust - * @date: 2019/04/28 10:57 - * @version: V1.0 - */ -package com.jun.plugin.arithmetic.jzoffer; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/arithmetic/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/arithmetic/package-info.java deleted file mode 100644 index d6b9da5e30..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/arithmetic/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: 算法相关类 -* @Version:1.0.0 -* @author pancm -* @date 2018年9月14日 -*/ -package com.jun.plugin.arithmetic; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/AbstractTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/AbstractTest.java deleted file mode 100644 index 86ea5e5545..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/AbstractTest.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.jun.plugin.basics; - -/** - * @author pancm - * @Data 2017-6-1 - * @Description abstract 抽象类测试 - */ -public class AbstractTest { - public static void main(String[] args) { - // 这句会报错,因为抽象类不能实例化 - // Animal a=new Animal(); - Animal a = new Dog(); - a.show(); - - E p = new F(); - p.show(); - E q = new G(); - q.show(); - - /* - * - * 1、抽象类和抽象方法都需要被abstract修饰。抽象方法一定要定义在抽象类中。 - * - * 2、抽象类不可以创建实例,原因:调用抽象方法没有意义。 - * - * 3、只有覆盖了抽象类中所有的抽象方法后,其子类才可以实例化。否则该子类还是一个抽象类。 - * - * 之所以继承,更多的是在思想,是面对共性类型操作会更简单。 - * - */ - } -} - -abstract class Animal { - abstract void show(); - - public void print() { - System.out.println("Animal"); - } -} - -class Dog extends Animal { - @Override - void show() { - System.out.println("This is Dog!"); - } -} - -abstract class E { - public abstract void show(); -} - -class F extends E { - public void show() { - System.out.print("test all FFFF \n"); - } -} - -class G extends E { - public void show() { - System.out.print("test all GGGG \n"); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/CalculateTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/CalculateTest.java deleted file mode 100644 index cf958e3ad0..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/CalculateTest.java +++ /dev/null @@ -1,220 +0,0 @@ -package com.jun.plugin.basics; - -import java.math.BigInteger; - -/** - * @Title: CalculateTest - * @Description: 运算符相关类 - * @Version:1.0.0 - * @author pancm - * @date 2018年10月18日 - */ -public class CalculateTest { - - public static void main(String[] args) { - //自增运算符测试 - test1(); - //运算符优先级测试 - test2(); - //位运算符 - test3(); - //赋值运算符 - test4(); - } - - private static void test4() { - int a = 4; - a *= 5; - int b = 6; - b %=3; - int c = 9; - c |= a; - int d = 8; - d <<=2; - int e = 17; - e &=9; - int f = 16; - f ^=2; - System.out.println("赋值运算符测试开始"); - System.out.println(a); - System.out.println(b); - System.out.println(c); - System.out.println(d); - System.out.println(e); - System.out.println(f); - System.out.println("赋值运算符测试结束"); - - - - /* - - 操作符 描述 例子 - = 简单的赋值运算符,将右操作数的值赋给左侧操作数 C = A + B将把A + B得到的值赋给C - + = 加和赋值操作符,它把左操作数和右操作数相加赋值给左操作数 C + = A等价于C = C + A - - = 减和赋值操作符,它把左操作数和右操作数相减赋值给左操作数 C - = A等价于C = C - - A - * = 乘和赋值操作符,它把左操作数和右操作数相乘赋值给左操作数 C * = A等价于C = C * A - / = 除和赋值操作符,它把左操作数和右操作数相除赋值给左操作数 C / = A等价于C = C / A - (%)= 取模和赋值操作符,它把左操作数和右操作数取模后赋值给左操作数 C%= A等价于C = C%A - << = 左移位赋值运算符 C << = 2等价于C = C << 2 - >> = 右移位赋值运算符 C >> = 2等价于C = C >> 2 - &= 按位与赋值运算符 C&= 2等价于C = C&2 - ^ = 按位异或赋值操作符 C ^ = 2等价于C = C ^ 2 - | = 按位或赋值操作符 C | = 2等价于C = C | 2 - - */ - } - - private static void test3() { - int a = 64>>>2; - int b = 2<<2; - int c = a&b; - int d = b|c; - int e = ~a; - int f = 60^13; - System.out.println("位运算符测试开始"); - System.out.println(a); - System.out.println(b); - System.out.println(c); - System.out.println(d); - System.out.println(e); - System.out.println(f); - System.out.println("位运算符测试结束"); - - /* - * - 十进制 - A = 60,B = 13 - 二进制 - A = 0011 1100 - B = 0000 1101 - - 操作符 描述 例子 - & 如果相对应位都是1,则结果为1,否则为0 (A&B),得到12,即0000 1100 - | 如果相对应位都是0,则结果为0,否则为1 (A | B)得到61,即 0011 1101 - ^ 如果相对应位值相同,则结果为0,否则为1 (A ^ B)得到49,即 0011 0001 - 〜 按位取反运算符翻转操作数的每一位,即0变成1,1变成0。 (〜A)得到-61,即1100 0011 - << 按位左移运算符。左操作数按位左移右操作数指定的位数。 A << 2得到240,即 1111 0000 - >> 按位右移运算符。左操作数按位右移右操作数指定的位数。 A >> 2得到15即 1111 - >>> 按位右移补零操作符。左操作数的值按右操作数指定的位数右移,移动得到的空位以零填充。 A>>>2得到15即0000 1111 - */ - - } - - //运算符优先级测试 - private static void test2() { - int a = 2+3*4/2 + (5+4)*2; - int b = 2>>3+4/2-1; - int c = a++*3-b--; - int d = (a>c?4:5) + 4%2 << 3; - System.out.println("运算符优先级测试开始"); - System.out.println(a); - System.out.println(b); - System.out.println(c); - System.out.println(d); - System.out.println("运算符优先级测试结束"); - /* - * 最高优先级的运算符在的表的最上面,最低优先级的在表的底部。 - 类别 操作符 关联性 - 后缀 () [] . (点操作符) 左到右 - 一元 + + - !〜 从右到左 - 乘性 * /% 左到右 - 加性 + - 左到右 - 移位 >> >>> << 左到右 - 关系 >> = << = 左到右 - 相等 == != 左到右 - 按位与 & 左到右 - 按位异或 ^ 左到右 - 按位或 | 左到右 - 逻辑与 && 左到右 - 逻辑或 | | 左到右 - 条件 ?: 从右到左 - 赋值 = + = - = * = / =%= >> = << =&= ^ = | = 从右到左 - 逗号 , 左到右 - */ - - } - - private static void test1() { - int a=1,z=1; - int b = a++; - int c = ++a; - int x = 2*++a; - int y = 2*b++; - System.out.println("自增运算符测试开始"); - System.out.println(a); - System.out.println(b); - System.out.println(c); - System.out.println(z++); - System.out.println(++z); - System.out.println(x); - System.out.println(y); - System.out.println("自增加运算符测试结束"); - - } - - - - - private static void test10() { - int i = 16; - // 16转换的二进制数据 - int j = 10000; - // 8转换的二进制数据 - int k = 1000; - // 4转换的二进制数据 - int m = 100; - // 32转换的二进制数据 - int n = 100000; - System.out.println("--" + (j & i)); - System.out.println("--" + (k & i)); - System.out.println("--" + (m & i)); - System.out.println("--" + (n & i)); - System.out.println("--" + decimal2Binary(i)); - System.out.println("--" + biannary2Decimal(n)); - //十进制转二进制 - System.out.println("--" + Integer.toBinaryString(i)); - /* - * 1. BigInteger的构造函数 - BigInteger(String src)默认参数字符串为10进制数值 - BigInteger(String src, int x)第2个参数x是指定第一个参数src的进制类型 - 2. toString方法 - toString()默认把数值按10进制数值转化为字符串。 - toString(int x)把数值按参数x的进制转化为字符串 - */ - System.out.println("--" + new BigInteger(String.valueOf(i)).toString(2)); - //二进制转十进制 - System.out.println("--" + new BigInteger(String.valueOf(j),2).toString()); - } - - /** - * 十进制转二进制 - */ - public static String decimal2Binary(int de) { - String numstr = ""; - while (de > 0) { - int res = de % 2; // 除2 取余数作为二进制数 - numstr = res + numstr; - de = de / 2; - } - return numstr; - } - - /** - * 将二进制转换为10进制 - * @param bi :待转换的二进制 - * @return - */ - public static Integer biannary2Decimal(int bi) { - String binStr = bi + ""; - Integer sum = 0; - int len = binStr.length(); - for (int i = 1; i <= len; i++) { - // 第i位 的数字为: - int dt = Integer.parseInt(binStr.substring(i - 1, i)); - sum += (int) Math.pow(2, len - i) * dt; - } - return sum; - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/CloneTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/CloneTest.java deleted file mode 100644 index 73d02c12b7..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/CloneTest.java +++ /dev/null @@ -1,224 +0,0 @@ -package com.jun.plugin.basics; - -/** - * -* @Title: CloneTest -* @Description: 克隆测试 -* @Version:1.0.0 -* @author pancm -* @date 2017-7-24 - */ -public class CloneTest { - public static void main(String args[]) { - - /* - * 浅拷贝1 - */ - Student stu1 = new Student(); - stu1.setNumber(12345); - Student stu2 = (Student)stu1.clone(); - - System.out.println("学生1:" + stu1.getNumber()); //12345 - System.out.println("学生2:" + stu2.getNumber()); //12345 - - stu2.setNumber(54321); - //说明拷贝成功 - System.out.println("学生1:" + stu1.getNumber()); //12345 - System.out.println("学生2:" + stu2.getNumber()); //54321 - - System.out.println(stu1==stu2);//false - - - /* - * 浅拷贝2 - * 是浅复制只是复制了addr变量的引用,并没有真正的开辟另一块空间,将值复制后再将引用返回给新对象。 - 所以,为了达到真正的复制对象,而不是纯粹引用复制。 - */ - Address addr = new Address(); - addr.setAdd("杭州市"); - Student2 student1 = new Student2(); - student1.setNumber(123); - student1.setAddr(addr); - Student2 student2 = (Student2)stu1.clone(); - - //学生1:123,地址:杭州市 - System.out.println("学生1:" + student1.getNumber() + ",地址:" + student1.getAddr().getAdd()); - //学生2:123,地址:杭州市 - System.out.println("学生2:" + student2.getNumber() + ",地址:" + student2.getAddr().getAdd()); - - addr.setAdd("深圳市"); - //学生1:123,地址:深圳市 - System.out.println("学生1:" + student1.getNumber() + ",地址:" + student1.getAddr().getAdd()); - //学生1:123,地址:深圳市 - System.out.println("学生2:" + student2.getNumber() + ",地址:" + student2.getAddr().getAdd()); - - - /* - * 浅克隆3 - * 是浅复制只是复制了addr变量的引用,并没有真正的开辟另一块空间,将值复制后再将引用返回给新对象。 - 所以,为了达到真正的复制对象,而不是纯粹引用复制。 - */ - Address3 addr3 = new Address3(); - addr.setAdd("杭州市"); - Student3 st1 = new Student3(); - st1.setNumber(123); - st1.setAddr(addr3); - Student3 st2 = (Student3)stu1.clone(); - - //学生1:123,地址:杭州市 - System.out.println("学生1:" + st1.getNumber() + ",地址:" + st1.getAddr().getAdd()); - //学生2:123,地址:杭州市 - System.out.println("学生2:" + st2.getNumber() + ",地址:" + st2.getAddr().getAdd()); - - addr3.setAdd("武汉市"); - //学生1:123,地址:武汉市 - System.out.println("学生1:" + st1.getNumber() + ",地址:" + st1.getAddr().getAdd()); - //学生1:123,地址:杭州市 - System.out.println("学生2:" + st2.getNumber() + ",地址:" + st2.getAddr().getAdd()); - - - } -} - - -/* - * 浅克隆1 - */ -//被复制的类需要实现Cloneable接口 重写Object方法 -class Student implements Cloneable{ - private int number; - - public int getNumber() { - return number; - } - - public void setNumber(int number) { - this.number = number; - } - - @Override - public Object clone() { - Student stu = null; - try{ - stu = (Student)super.clone(); - }catch(CloneNotSupportedException e) { - e.printStackTrace(); - } - return stu; - } -} - - - -/* - * 浅克隆2 - */ -//该对象不继承Cloneable -class Address { - private String add; - - public String getAdd() { - return add; - } - - public void setAdd(String add) { - this.add = add; - } -} - -//此对象依旧继承 Cloneable -class Student2 implements Cloneable{ - private int number; - - private Address addr; - - public Address getAddr() { - return addr; - } - - public void setAddr(Address addr) { - this.addr = addr; - } - - public int getNumber() { - return number; - } - - public void setNumber(int number) { - this.number = number; - } - - @Override - public Object clone() { - Student2 stu = null; - try{ - stu = (Student2)super.clone(); - }catch(CloneNotSupportedException e) { - e.printStackTrace(); - } - return stu; - } -} - - -/* - * 浅克隆3 - */ -//该对象继承Cloneable -class Address3 implements Cloneable { - private String add; - public String getAdd() { - return add; - } - - public void setAdd(String add) { - this.add = add; - } - - @Override - public Object clone(){ - Address3 addr=null; - try{ - addr=(Address3)super.clone(); - }catch(CloneNotSupportedException e){ - e.printStackTrace(); - } - return addr; - } -} - -//此对象依旧继承 Cloneable -class Student3 implements Cloneable{ - private int number; - - private Address3 addr; - - public Address3 getAddr() { - return addr; - } - - public void setAddr(Address3 addr) { - this.addr = addr; - } - - public int getNumber() { - return number; - } - - public void setNumber(int number) { - this.number = number; - } - - @Override - public Object clone() { - Student3 stu = null; - try{ - stu = (Student3)super.clone(); //浅复制 - }catch(CloneNotSupportedException e) { - e.printStackTrace(); - } - stu.addr = (Address3)addr.clone(); //深度复制 - return stu; - } -} - diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/ExtendTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/ExtendTest.java deleted file mode 100644 index 1666daad47..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/ExtendTest.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.jun.plugin.basics; - - -/** - * -* @Title: ExtendTest -* @Description: -* 继承测试 -* @Version:1.0.0 -* @author pancm -* @date 2018年3月27日 - */ -public class ExtendTest { - - public static void main(String[] args) { - Cat1 cat=new Cat1(); - Dog1 dog=new Dog1(); - cat.eat(); - cat.sleep("cat"); - cat.climbTree(); - dog.eat("dog"); - dog.sleep("dog"); - } -} - -class Animal1{ - public void eat(String name){ - System.out.println(name+"正在吃东西..."); - } - public void sleep(String name){ - System.out.println(name+"正在睡觉..."); - } -} - -class Cat1 extends Animal1{ - private String name="Cat"; - public void eat(){ - super.eat(name); - System.out.println(name+"吃完了"); - } - public void sleep(){ - this.sleep(name); - } - - public void sleep(String name){ - System.out.println(name+"刚刚睡觉!"); - } - - public void climbTree(){ - System.out.println(name+"正在爬树!"); - } -} - -class Dog1 extends Animal1{ - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/ExtendsTest2.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/ExtendsTest2.java deleted file mode 100644 index ff7ff3de71..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/ExtendsTest2.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.jun.plugin.basics; - -/** - * -* @Title: ExtendsTest2 -* @Description: 继承测试 经典题 -* @Version:1.0.0 -* @author pancm -* @date 2017年6月2日 - */ -public class ExtendsTest2 { - public static void main(String[] args) { - A a1 = new A(); - A a2 = new B(); - B b = new B(); - C c = new C(); - D d = new D(); - - System.out.println("1--" + a1.show(b)); //A and A - System.out.println("2--" + a1.show(c)); //A and A - System.out.println("3--" + a1.show(d)); //A and D - System.out.println("4--" + a2.show(b)); //B and A - System.out.println("5--" + a2.show(c)); //B and A - System.out.println("6--" + a2.show(d)); //A and D - System.out.println("7--" + b.show(b)); //B and B - System.out.println("8--" + b.show(c)); //B and B - System.out.println("9--" + b.show(d)); //A and D - } -} - -class A { - public String show(D obj) { - return ("A and D"); - } - - public String show(A obj) { - return ("A and A"); - } - -} - - class B extends A{ - public String show(B obj){ - return ("B and B"); - } - - public String show(A obj){ - return ("B and A"); - } -} - - class C extends B{ - -} - - class D extends B{ - -} - diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/FinalTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/FinalTest.java deleted file mode 100644 index 6f9e816469..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/FinalTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.jun.plugin.basics; - -import java.util.Date; - - -/** - * -* Title: FinalTest -* Description: -* final测试 -* Version:1.0.0 -* @author pancm -* @date 2018年3月21日 - */ -public class FinalTest{ - //定义一个final修饰的变量 - public static final String name="xuwujing"; - - public static void main(String[] args) { - //这句会报错 因为该变量已经被final修饰了 -// name="张三"; - } - //类加上final之后,该类是无法被继承的 - final class Test2{ - } - //这句会报错,因为Test2是被final修饰的类 -// class Test3 extends Test2{ -// } - - class Test4{ - //定义一个被final修饰的方法 - final Date getTime(){ - return new Date(); - } - } - - class Test5 extends Test4{ - //这句会报错,因为final方法是不能被子类修改的。 -// Date getTime(){ -// return new Date(); -// } - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/ForTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/ForTest.java deleted file mode 100644 index 0e7d8c4926..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/ForTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.jun.plugin.basics; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -/** - * -* @Title: ForTest -* @Description: 循环测试 -* @Version:1.0.0 -* @author pancm -* @date 2017年9月29日 - */ -public class ForTest { - public static void main(String[] args) { - /* - * 阿里巴巴开发手册中的遍历移除测试 - */ - iteratorTest(); - forEachTest(); - } - private static void forEachTest(){ - List list = new ArrayList(); - list.add("1"); - list.add("2"); - System.out.println("list1:"+list); - for (String item : list) { - //如果是1就不会出现 - if ("2".equals(item)) { - list.remove(item); - //加上break就不会抛异常 -// break; - } - } - System.out.println("list2:"+list); - } - private static void iteratorTest(){ - List list = new ArrayList(); - list.add("1"); - list.add("2"); - System.out.println("list3:"+list); - Iterator iterator = list.iterator(); - while (iterator.hasNext()) { - String item = iterator.next(); - if ("2".equals(item)) { - iterator.remove(); - } - } - System.out.println("list4:"+list); - } - - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/IoTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/IoTest.java deleted file mode 100644 index d17176bc17..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/IoTest.java +++ /dev/null @@ -1,235 +0,0 @@ -package com.jun.plugin.basics; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.util.Properties; - -/** -* @Title: IoTest -* @Description: -* io字符流和字节流测试 -* @Version:1.0.0 -* @author pancm -* @date 2018年6月11日 -*/ -public class IoTest { - - public static void main(String[] args) { - try { -// test(); -// test2(); -// test3(); -// test4(); - test5(); -// test6(); -// test7(); - - } catch (IOException e) { - e.printStackTrace(); - } - } - - - - - - /** - * 字符流 - * @throws IOException - */ - private static void test() throws IOException { - String str; - // 使用 System.in 创建 BufferedReader - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - System.out.println("输入字符, 输入 'quit' 退出。"); - // 读取字符 - do { - str=br.readLine(); - System.out.println("您输入的字符是:"+str); - } while(!str.equals("quit")); - br.close(); - } - - /** - * 字节流 - * 创建一个文件并新增一条记录 - * @throws IOException - */ - private static void test2() throws IOException { - String path="E:/test/hello.txt"; - String str="hello world"; - //创建一个文件并向文件中写数据 需要文件夹存在 - OutputStream output = new FileOutputStream(path); - output.write(str.getBytes()); - output.close(); - } - - /** - * 写入和读取文件 - * @throws IOException - */ - private static void test3() throws IOException { - //创建要操作的文件路径和名称 - String path ="E:/test/hello.txt"; - String str="你好!"; - FileWriter fw = new FileWriter(path); - BufferedWriter bw=new BufferedWriter(fw); - bw.write(str); - bw.close(); - fw.close(); - - FileReader fr = new FileReader(path); - BufferedReader br=new BufferedReader(fr); - StringBuffer sb=new StringBuffer(); - while(br.ready()){ - sb.append((char)br.read()); - } - System.out.println("输出:"+sb.toString()); - br.close(); - fr.close(); - } - - - - - /** - * 字节流 - * 创建一个文件并读取记录 防止乱码 - * @throws IOException - */ - private static void test4() throws IOException { - String path="E:/test/hello.txt"; - String path2="E:/test/你好.txt"; - String str="你好!"; - //从文件读取数据 - InputStream input = new FileInputStream(path); - InputStreamReader reader = new InputStreamReader(input, "UTF-8"); - StringBuffer sb=new StringBuffer(); - while(reader.ready()){ - sb.append((char)reader.read()); - } - - input.close(); - reader.close(); - - //创建一个文件并向文件中写数据 - OutputStream output = new FileOutputStream(path2); - OutputStreamWriter writer = new OutputStreamWriter(output, "UTF-8"); - writer.write(sb+str); - - writer.close(); - output.close(); - - //从文件读取数据 - InputStream input2 = new FileInputStream(path2); - InputStreamReader reader2 = new InputStreamReader(input2, "UTF-8"); - StringBuffer sb2=new StringBuffer(); - while(reader2.ready()){ - sb2.append((char)reader2.read()); - } - System.out.println("输出:"+sb2); - input2.close(); - reader2.close(); - } - - - - /** - * 字符流 - * 写入和读取文件 - * @throws IOException - */ - private static void test6() throws IOException { - //创建要操作的文件路径和名称 - //其中,File.separator表示系统相关的分隔符,Linux下为:/ Windows下为:\\ - String path ="E:/test2/hello.txt"; - String str="hello world"; - FileWriter fw = new FileWriter(path); - //以path为路径创建一个新的FileWriter对象 - //如果需要追加数据,而不是覆盖,则使用FileWriter(path,true)构造方法 - //将字符串写入到流中,\r\n表示换行想有好的 - fw.write(str); - fw.close(); - - FileReader fr = new FileReader(path); - StringBuffer sb=new StringBuffer(); - while(fr.ready()){ - sb.append((char)fr.read()); - } - System.out.println("输出:"+sb.toString()); - fr.close(); - } - - - /** - * 字符流 - * 写入和读取文件 - * @throws IOException - */ - private static void test7() throws IOException { - //创建要操作的文件路径和名称 - String path ="E:/test2/hello.txt"; - Properties prop=new Properties(); - prop.setProperty("name", "zz"); - FileWriter fw = new FileWriter(path); - BufferedWriter bw=new BufferedWriter(fw); - bw.write(prop.toString()); - bw.close(); - fw.close(); - - FileReader fr = new FileReader(path); - BufferedReader br=new BufferedReader(fr); - StringBuffer sb=new StringBuffer(); - while(br.ready()){ - sb.append((char)br.read()); - } - System.out.println("输出:"+sb.toString()); - br.close(); - fr.close(); - } - - - - /** - * 新建文件夹和文件 - * @throws IOException - */ - private static void test5() throws IOException { - String path="E:/test/test2"; - String path2="E:/test/test3/test3"; - String path3="E:/test/test2/test2.txt"; - File f = new File(path); - File f2 = new File(path2); - File f3 = new File(path3); - System.out.println(f.exists()); - //创建文件夹 - System.out.println("="+f.mkdir()); - //创建文件夹和所有父文件夹 - System.out.println("=="+f2.mkdirs()); - //创建一个文本 - System.out.println("==="+f3.createNewFile()); - //获取名称 - System.out.println("==="+f3.getName()); - //获取父级名称 - System.out.println("==="+f3.getParent()); - //获取当前路径 - System.out.println("==="+f3.getPath()); - //判断是否是目录 - System.out.println("=="+f2.isDirectory()); - System.out.println("==="+f3.isDirectory()); - //删除该文件 - System.out.println("==="+f3.delete()); - - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/ListTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/ListTest.java deleted file mode 100644 index 4fa41b383b..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/ListTest.java +++ /dev/null @@ -1,295 +0,0 @@ -package com.jun.plugin.basics; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Vector; -import java.util.stream.Collectors; - -/** - * -* @Title: ListTest -* @Description:关于list测试 -* @Version:1.0.0 -* @author pancm -* @date 2017年10月13日 - */ -public class ListTest { - - private final static int count=50000; - - private static ArrayList arrayList = new ArrayList<>(); - private static LinkedList linkedList = new LinkedList<>(); - private static Vector vector = new Vector<>(); - - - public static void main(String[] args) { -// test1(); -// test2(); - test3(); -// test4(); -// test5(); - - - Vector v=new Vector<>(); - } - - - /** - * 遍历方法 - */ - private static void test1() { - List list=new ArrayList(); - list.add("a"); - list.add("b"); - list.add("c"); - - System.out.println("list截取:"+list.subList(0, 1)); - System.out.println("list截取:"+list.subList(1, 3)); - - - //第一种使用 - for(int i=0;i iterator=list.iterator(); - while(iterator.hasNext())//判断下一个元素之后有值 - { - System.out.println(iterator.next()); - } - } - - /** - * 数组变化遍历 - */ - private static void test2() { - - List list1 = new ArrayList(); - list1.add("1"); - list1.add("2"); - System.out.println("list1遍历之前:"+list1); - Iterator iterator = list1.iterator(); - while (iterator.hasNext()) { - String item = iterator.next(); - if ("2".equals(item)) { - iterator.remove(); - } - } - System.out.println("list1遍历之后:"+list1); - - List list = new ArrayList(); - list.add("1"); - list.add("2"); - System.out.println("list遍历之前:"+list); - for (String item : list) { - if ("2".equals(item)) { - list.remove(item); - //如果这里不适用break的话,会直接报错的 - break; - } - } - System.out.println("list遍历之后:"+list); - - - } - - - /** - * 常用方法 - */ - private static void test3() { - List list=initData(100); - System.out.println("list:"+list); - System.out.println("removeList:"+removeList(list,10,20)); - list.subList(10, 20).clear(); - System.out.println("subList:"+list); - - List ls1=new ArrayList(); - List ls2=new ArrayList(); - ls1.add("a"); - ls1.add("b"); - ls1.add("c"); - ls2.add("a"); - ls2.add("b"); - ls2.add("c"); - ls2.add("e"); -// System.out.println("合集:"+addAll(ls1,ls2)); -// System.out.println("交集 :"+retainAll(ls1,ls2)); - System.out.println("差集 :"+removeAll(ls2,ls1)); -// System.out.println("并集 :"+andAll(ls1,ls2)); - - } - - private static void test4() { - LinkedList list=new LinkedList(); - list.add(3); - list.add(5); - list.add(4); - System.out.println(list); - list.addFirst(2); - list.addLast(4); - System.out.println(list); - - LinkedList list2=new LinkedList(); - list2.add(1); - list2.add(2); - list2.add(4); - list2.add(4); - list2.add(6); - list2.add(6); - list2.add(5); - System.out.println("去重之前:"+list2); - //jdk1.8去重 - List newList = list2.stream().distinct().collect(Collectors.toList()); - System.out.println("去重之后:"+newList); - - } - - private static void test5() { - insertList(arrayList); - insertList(linkedList); - insertList(vector); - - System.out.println("--------------------"); - - readList(arrayList); - readList(linkedList); - readList(vector); - - System.out.println("--------------------"); - - delList(arrayList); - delList(linkedList); - delList(vector); - - } - - - private static void insertList(List list){ - long start=System.currentTimeMillis(); - Object o = new Object(); - for(int i=0;i removeList(List list,int s,int d){ - for(int i=0,j=list.size();i=s&&i initData(int j){ - List list=new ArrayList(); - for(int i=1;i<=j;i++){ - list.add(i); - } - return list; - } - - /** - * 数组合集 - * @param ls1 - * @param ls2 - * @return - */ - private static List addAll(List ls1,Listls2){ - ls1.addAll(ls2); - return ls1; - } - - /** - * 数组交集 (retainAll 会删除 ls1在ls2中没有的元素) - * @param ls1 - * @param ls2 - * @return - */ - private static List retainAll(List ls1,Listls2){ - System.out.println("ls1:"+ls1+";ls2:"+ls2); - ls1.retainAll(ls2); - return ls1; - } - - /** - * 差集 (删除ls2中没有ls1中的元素) - * @param ls1 - * @param ls2 - * @return - */ - private static List removeAll(List ls1,Listls2){ - System.out.println("ls1:"+ls1+";ls2:"+ls2); - ls1.removeAll(ls2); - return ls1; - } - - /** - * 无重复的并集 (ls1和ls2中并集,并无重复) - * @param ls1 - * @param ls2 - * @return - */ - private static List andAll(List ls1,Listls2){ - //删除在ls1中出现的元素 - ls2.removeAll(ls1); - //将剩余的ls2中的元素添加到ls1中 - ls1.addAll(ls2); - System.out.println(ls1+";ls2:"+ls2); - return ls1; - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/MapTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/MapTest.java deleted file mode 100644 index 190befb2fa..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/MapTest.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.jun.plugin.basics; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; -import java.util.TreeMap; - -/** - * -* Title: MapTest -* Description:集合map测试 -* Version:1.0.0 -* @author pancm -* @date 2017年11月16日 - */ -public class MapTest { - private static Map map = new HashMap(); - - public static Map getHashMap(){ - if(map == null || map.isEmpty()){ - map = new HashMap(); - } - return map; - } - - public static void main(String[] args) { - //普通的HashMap -// Map map=mapTest.getHashMap(); -// map.put("a", "1"); -// map.put("b", "1"); -// map.put("c", "e"); -// System.out.println(map.toString()); -// Map map1=mapTest.getHashMap(); -// System.out.println("-----"+map1.get("a")); - - //上锁的HashMap -// Map sMap=Collections.synchronizedMap(new HashMap()); - -// getMap1(); - - test1(); - test2(); - } - - - - private static void test1() { - Map map = new HashMap(); - map.put("1", "value1"); - map.put("2", "value2"); - map.put("3", "value3"); - //第一种:普遍使用,二次取值 - System.out.println("通过Map.keySet遍历key和value:"); - for (String key : map.keySet()) { - System.out.println("key= "+ key + " and value= " + map.get(key)); - } - - //第二种 使用迭代器Iterator进行遍历 - System.out.println("通过Map.entrySet使用iterator遍历key和value:"); - Iterator> it = map.entrySet().iterator(); - while (it.hasNext()) { - Map.Entry entry = it.next(); - System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue()); - } - - //第三种:使用entrySet遍历 推荐,尤其是容量大时 - System.out.println("通过Map.entrySet遍历key和value"); - for (Map.Entry entry : map.entrySet()) { - System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue()); - } - } - - private static void test2() { - Map hashMap=new HashMap(); - hashMap.put("a", 1); - hashMap.put("c", 3); - hashMap.put("b", 2); - System.out.println("HashMap:"+hashMap); - - Map treeMap=new TreeMap(); - treeMap.put("a", 1); - treeMap.put("c", 3); - treeMap.put("b", 2); - System.out.println("TreeMap:"+treeMap); - - } - - - - - - @SuppressWarnings("unused") - private static void getMap1(){ - Map map1 =new HashMap(); - Map map2 =new HashMap(); - map1.put(1, 1); - map1.put(2, 2); - map1.put(3, 3); - map2.put(11, 11); - map2.put(22, 22); - map2.put(33, 33); - Map> map3 =new HashMap>(); - map3.put(1, map1); - map3.put(2, map2); - - System.out.println("map3:"+map3); - StringBuffer sb=new StringBuffer(); - for(Entry> entry:map3.entrySet()){ - sb.append(entry.getKey()); - sb.append(":"); - Map map4=entry.getValue(); - for(Entry entry1:map4.entrySet()){ - sb.append(entry1.getKey()); - sb.append("_"); - sb.append(entry1.getValue()); - sb.append(","); - } - - } - sb.deleteCharAt(sb.lastIndexOf(",")); - System.out.println("sb:"+sb); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/PackagingTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/PackagingTest.java deleted file mode 100644 index 0fbac9709c..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/PackagingTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.jun.plugin.basics; - -/** - * -* @Title: PackagingTest -* @Description: -* 封装 -* @Version:1.0.0 -* @author pancm -* @date 2018年3月27日 - */ -public class PackagingTest { - - public static void main(String[] args) { - User9 user=new User9(); - //这里会报错,因为id和name是私有的,用于保护该数据 -// user.id=10; -// user.name="张三"; - user.setId(1); - user.setName("张三"); - System.out.println(user.getId()); - System.out.println(user.getName()); - } - -} - -class User9{ - private int id; - private String name; - public int getId() { - return id; - } - public void setId(int id) { - this.id = id; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/PolymorphicTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/PolymorphicTest.java deleted file mode 100644 index 5ec0064c68..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/PolymorphicTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.jun.plugin.basics; - -/** - * - * @Title: PolymorphicTest - * @Description: 多态测试 - * @Version:1.0.0 - * @author pancm - * @date 2018年3月27日 - */ -public class PolymorphicTest { - - public static void main(String[] args) { - Animal2 animal = new Cat2(); - animal.eat(); - } -} - -class Animal2 { - private String name = "Animal"; - - public void eat() { - System.out.println(name + "正在吃东西..."); - sleep(); - } - - public void sleep() { - System.out.println(name + "正在睡觉..."); - } -} - -class Cat2 extends Animal2 { - private String name = "Cat"; - - public void eat(String name) { - System.out.println(name + "吃完了"); - sleep(); - } - - public void sleep() { - System.out.println(name + "正在睡觉"); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/ReflectTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/ReflectTest.java deleted file mode 100644 index 2df7965bcf..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/ReflectTest.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.jun.plugin.basics; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Member; -import java.lang.reflect.Method; - - -/** - * -* Title: ReflectTest -* Description: -* 反射测试 -* -* 反射技术可以对一个类进行解剖。 -  优点:大大的增强了程序的扩展性。 -* Version:1.0.0 -* @author pancm -* @date 2018年2月9日 - */ -public class ReflectTest { - - public static void main(String[] args) throws Exception { - Class clazz = User.class;//获得User的类名,返回reflect.User - Object obj = create(clazz);//创建User的一个对象 - System.out.println(obj);//输出对象,会调用对象的toString方法 - System.out.println("---------"); - invoke1(obj, "getMessage");//调用User对象的getMessage方法 - } - /* - **根据类名,new一个对象,并返回*/ - static Object create(Class clazz) throws Exception { - //如果clazz含有无参数的构造方法,可以如下方式实例化 - //clazz.newInstance(); - //根据类名和参数(类型、个数),找到相应的构造方法-下面创建构造方法参数为String的构造方法 - Constructor con=clazz.getConstructor(String.class); - //实例化对象 - Object obj=con.newInstance("哈哈"); - //返回对象 - return obj; - } - /* - **根据对象,方法名(字符串),来调用方法*/ - static void invoke1(Object obj, String methodName)throws Exception{ - //getDeclaredMethods可以获取类本身(不包括父类)所有方法的名字(包括私有方法)**一般不用这种方法,私有的属性一般不能修改 - Method[] ms = obj.getClass().getDeclaredMethods(); - //getMethods可以获取类本身,以及父类的方法的名字,但不包括私有的方法 - ms = obj.getClass().getMethods(); - for (Method m : ms) { - //如果方法名字匹配,则反射调用方法 - if (methodName.equals(m.getName())) - m.invoke(obj, null); - } - /* - **防止方法重载,可用下面的方式(可以指明参数)--与上面的for循环(无法防止方法重载)一个效果 - **Method m = obj.getClass().getMethod(methodName, null); - **m.invoke(obj, null); - */ - } - - /* - **根据类名获取类的属性(一般不直接操作属性)*/ - static void field(Class clazz) throws Exception { - Field[] fs = clazz.getDeclaredFields(); - //fs = clazz.getFields(); - for (Field f : fs) - System.out.println(f.getName()); - } - /* - **根据类名获取类的注解*/ - static void annon(Class clazz) throws Exception { - Annotation[] as = clazz.getAnnotations(); - for (Annotation a : as) - System.out.println(((Member) a).getName()); - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/ReflectTest2.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/ReflectTest2.java deleted file mode 100644 index 0fe1e1aace..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/ReflectTest2.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.jun.plugin.basics; - -import java.lang.reflect.Method; - -/** - * -* Title: ReflectTest2 -* Description: -* 反射测试 -*  反射的基本步骤: -1、获得class对象,就是获取到指定的名称的字节码文件对象。 -2、实例化对象,获得类的属性、方法或构造函数。 -3、访问属性、调用方法、调用构造函数创建对象。 -* Version:1.0.0 -* @author pancm -* @date 2018年2月28日 - */ -public class ReflectTest2 { - - public static void main(String[] args) throws ReflectiveOperationException { - method_1(); - method_2(); - method_3(); - method_4(); - } - - /** - * 获取该类中的所有方法 - */ - private static void method_1() throws ReflectiveOperationException { - //指定类和路径 - Class clazz=Class.forName("com.pancm.test.reflectTest.User"); -// Class clazz=User.class; - //获取的是该类中的公有方法和父类中的公有方法。 - Method[] methods=clazz.getMethods(); - //获取本类中的方法,包含私有方法。 - methods=clazz.getDeclaredMethods(); - for(Method me:methods){ - System.out.println("方法:"+me); - } - } - - /** - * 获取指定方法 - */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - private static void method_2() throws ReflectiveOperationException { - //指定类和路径 - Class clazz=Class.forName("com.pancm.test.reflectTest.User"); - //获取的指定名称的方法 - //如果带有入参,则指定入参类型 - Method method=clazz.getMethod("getMessage2",int.class); - //初始化 - Object obj=clazz.newInstance(); - //执行该方法 - method.invoke(obj, 11); - } - - - /** - * 获取私有的方法 - */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - private static void method_3() throws ReflectiveOperationException { - //指定类和路径 - Class clazz=Class.forName("com.pancm.test.reflectTest.User"); - //获取私有的方法,必须要使用getDeclaredMethod - Method method=clazz.getDeclaredMethod("getMessage3", null); - //私有方法不能直接访问,因为权限不够。非要访问,可以通过暴力的方式。 - method.setAccessible(true); - } - - - /** - * 获取静态方法 - */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - private static void method_4() throws ReflectiveOperationException { - //指定类和路径 - Class clazz=Class.forName("com.pancm.test.reflectTest.User"); - //获取私有的方法,必须要使用getDeclaredMethod - Method method=clazz.getMethod("getMessage4",String.class); - System.out.println(); - method.invoke(null, "测试"); - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/ServletTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/ServletTest.java deleted file mode 100644 index c723d845e6..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/ServletTest.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.jun.plugin.basics; - -import java.io.IOException; -import java.io.PrintWriter; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * -* Title: ServletTest -* Description: -* 部署在tomcat之后,在web.xml添加: -* - testServlet - com.pancm.test.servletTest.testServlet - - - - testServlet - /test.do - - 然后启动tomcat,在浏览器输入 ip:端口/项目名/设置的地址 - 就可以访问了 -* Version:1.0.0 -* @author pancm -* @date 2018年3月20日 - */ -public class ServletTest extends HttpServlet { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * 返回结果 - */ - private String result = null; - - private long count=1; - - /** - * - */ - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - doPost(req, resp); - } - - /** - * - */ - @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - System.out.println("============"); - System.out.println(req.getParameter("param")); - PrintWriter printWriter=resp.getWriter(); - result = "这是第"+count+"次响应!"; - try { - resp.setCharacterEncoding("utf-8"); - count++; - printWriter.print(result); - } catch (Exception e) { - result="第"+count+"次请求错误!"; - printWriter.print(result); - }finally{ - req=null; - printWriter=null; - resp=null; - } - } - - @Override - public void destroy() { - super.destroy(); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/SetTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/SetTest.java deleted file mode 100644 index c89ce76293..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/SetTest.java +++ /dev/null @@ -1,311 +0,0 @@ -package com.jun.plugin.basics; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; -import java.util.TreeSet; - -/** - * -* @Title: setTest -* @Description: 重写set中的equals和hashcode -* @Version:1.0.0 -* @author panchengming -* @date 2017年9月17日 - */ -public class SetTest { - - - public static void main(String[] args) { - Set hashSet = new HashSet(); - Set treeSet = new TreeSet(); - Set linkedSet = new LinkedHashSet(); - - - set(); - hashSetTest(); - treeSet1(); - treeSet2(); - } - - /** - * set去重 - */ - public static void set(){ - // 初始化list - List list = new ArrayList(); - list.add("Jhon"); - list.add("Jency"); - list.add("Mike"); - list.add("Dmitri"); - list.add("Mike"); - // 利用set不允许元素重复的性质去掉相同的元素 - Set set = new HashSet(); - for (int i = 0; i < list.size(); i++) { - String items = list.get(i); - System.out.println("items:"+items); - if (!set.add(items)) { - // 打印重复的元素 - System.out.println("重复的数据: " + items); - } - } - System.out.println("list:"+list); - } - - /** - * 使用hashSet去重 - */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - public static void hashSetTest(){ - HashSet hs = new HashSet(); - // TreeMap tm=new TreeMap(); - hs.add(new AA("ABC", 20)); - hs.add(new AA("BCD", 20)); - hs.add(new AA("CDE", 20)); - hs.add(new AA("ABC", 20)); - hs.add(new AA("BCD", 20)); - Iterator it = hs.iterator(); //定义迭代器 - while (it.hasNext()) { - Object next = it.next(); - System.out.println("排序之前:"+next); -// Entry me=(Entry) it.next(); -// tm.put(me.getKey(), me.getValue()); - } -// System.out.println("TreeMap排序之后:"+tm); - } - - /** - * 一,让容器自身具备比较性,自定义比较器。 - 需求:当元素自身不具备比较性,或者元素自身具备的比较性不是所需的。 - 那么这时只能让容器自身具备。 - 定义一个类实现Comparator 接口,覆盖compare方法。 - 并将该接口的子类对象作为参数传递给TreeSet集合的构造函数。 - 当Comparable比较方式,及Comparator比较方式同时存在,以Comparator - 比较方式为主 - */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - public static void treeSet1(){ - TreeSet ts = new TreeSet(new MyComparator()); - ts.add(new Book("think in java", 100)); - ts.add(new Book("java 核心技术", 75)); - ts.add(new Book("现代操作系统", 50)); - ts.add(new Book("java就业教程", 35)); - ts.add(new Book("think in java", 100)); - ts.add(new Book("ccc in java", 100)); - - System.out.println("treeSet1:"+ts); - } - - - /** - * - 二,让元素自身具备比较性。 - 也就是元素需要实现Comparable接口,覆盖compareTo 方法。 - 这种方式也作为元素的自然排序,也可称为默认排序。 - 年龄按照搜要条件,年龄相同再比姓名。 - */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - public static void treeSet2(){ - TreeSet ts = new TreeSet(); - ts.add(new Person("aa", 20, "男")); - ts.add(new Person("bb", 18, "女")); - ts.add(new Person("cc", 17, "男")); - ts.add(new Person("dd", 17, "女")); - ts.add(new Person("dd", 15, "女")); - ts.add(new Person("dd", 15, "女")); - - System.out.println("treeSet2:"+ts); - System.out.println(ts.size()); // 5 - } - -} - - - - class AA{ - private String name; - private int age; - - public AA(String name, int age) { - this.name=name; - this.age=age; - } - - AA() { - - } - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - - //重写hashCode - @Override - public int hashCode() { - System.out.println("hashCode:" + this.name); - return this.name.hashCode() + age * 37; - } - - //重写equals - @Override - public boolean equals(Object obj) { - if (obj instanceof AA) { - AA a = (AA) obj; - return this.name.equals(a.name) && this.age == a.age; - } else { - return false; - } - } - - @Override - public String toString() { - return "姓名:" + this.name + " 年龄:" + this.age; - } - } - -@SuppressWarnings("rawtypes") -class Person implements Comparable { - private String name; - private int age; - private String gender; //性别 - - public Person() { - } - - public Person(String name, int age, String gender) { - - this.name = name; - this.age = age; - this.gender = gender; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - - public String getGender() { - return gender; - } - - public void setGender(String gender) { - this.gender = gender; - } - - @Override - public int hashCode() { - return name.hashCode() + age * 37; - } - - public boolean equals(Object obj) { - System.err.println(this + "equals :" + obj); - if (!(obj instanceof Person)) { - return false; - } - Person p = (Person) obj; - return this.name.equals(p.name) && this.age == p.age; - - } - - public String toString() { - return "Person [name=" + name + ", age=" + age + ", gender=" + gender - + "]"; - } - - @Override - public int compareTo(Object obj) { - Person p = (Person) obj; - System.out.println(this+" compareTo:"+p); - if (this.age > p.age) { - return 1; - } - if (this.age < p.age) { - return -1; - } - return this.name.compareTo(p.name); - } - } - - -@SuppressWarnings("rawtypes") -class MyComparator implements Comparator { - - public int compare(Object o1, Object o2) { - Book b1 = (Book) o1; - Book b2 = (Book) o2; - System.out.println(b1+" comparator "+b2); - if (b1.getPrice() > b2.getPrice()) { - return 1; - } - if (b1.getPrice() < b2.getPrice()) { - return -1; - } - return b1.getName().compareTo(b2.getName()); - } - -} - -class Book { - private String name; - private double price; - - public Book() { - - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public double getPrice() { - return price; - } - - public void setPrice(double price) { - this.price = price; - } - - public Book(String name, double price) { - - this.name = name; - this.price = price; - } - - @Override - public String toString() { - return "Book [name=" + name + ", price=" + price + "]"; - } - -} - - diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/SocketTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/SocketTest.java deleted file mode 100644 index 9247ecd9a2..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/SocketTest.java +++ /dev/null @@ -1,186 +0,0 @@ -package com.jun.plugin.basics; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.net.InetSocketAddress; -import java.net.ServerSocket; -import java.net.Socket; -import java.nio.ByteBuffer; -import java.nio.channels.SelectionKey; -import java.nio.channels.Selector; -import java.nio.channels.ServerSocketChannel; -import java.nio.channels.SocketChannel; -import java.nio.charset.Charset; -import java.util.Iterator; -import java.util.Set; - -/** - * - * @Title: SocketTest - * @Description:Socket测试 - * @Version:1.0.0 - * @author pancm - * @date 2017年11月16日 - */ -public class SocketTest { - /** 端口 */ - private static final int portNumber = 6789; - - private static String request = null; - private static String response = null; - - public static void main(String[] args) { - request = "Hello"; - socketTest(request); - - } - - /** - * socket简单连接测试 - * - * @param request - */ - private static void socketTest(String request) { - try { - // 创建一个新的 ServerSocket, 用 以监听指定端口上的连接请求 - ServerSocket serverSocket = new ServerSocket(portNumber); - // 对 accept()方法的调用将被阻塞,直到一个连接建立 - Socket clientSocket = serverSocket.accept(); - // 这些流对象都派生于该套接字的流对象 - BufferedReader in = new BufferedReader(new InputStreamReader( - clientSocket.getInputStream())); - PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), - true); - // 循环处理开始 - while ((request = in.readLine()) != null) { - // 如果客户端发送了“Done”,则退出处理循环 - if ("Done".equals(request)) { - break; - } - // 请求被传递给服务器的处理方法 - response = processRequest(request); - System.out.println("response:" + response); - // 服务器的响应被发送给了客户端 - out.println(response); - } - } catch (IOException e) { - e.printStackTrace(); - - } - } - - private static String processRequest(String request) { - return "hi"; - } - - /** - * socket简单并发测试 - * @param port - * @throws IOException - */ - public void serve(int port) throws IOException { - // 将服务器绑定到指定端口 - final ServerSocket socket = new ServerSocket(port); - try { - for (;;) { - // 接受连接 - final Socket clientSocket = socket.accept(); - System.out.println("Accepted connection from " + clientSocket); - // 创建一个新的线程来处理该连接 - new Thread(new Runnable() { - @Override - public void run() { - OutputStream out; - try { - out = clientSocket.getOutputStream(); - // 将消息写给已连接的客户端 - out.write("Hi!\r\n".getBytes(Charset - .forName("UTF-8"))); - out.flush(); - clientSocket.close(); - } catch (IOException e) { - e.printStackTrace(); - } finally { - try { - clientSocket.close(); - } catch (IOException ex) { - // ignore on close - } - } - } - }).start(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - /** - * socket 实现非阻塞 I/O - * @param port - * @throws IOException - */ - public void serve1(int port) throws IOException { - ServerSocketChannel serverChannel = ServerSocketChannel.open(); - serverChannel.configureBlocking(false); - ServerSocket ssocket = serverChannel.socket(); - InetSocketAddress address = new InetSocketAddress(port); - ssocket.bind(address); - //打开Selector来处理Channel - Selector selector = Selector.open(); - //将ServerSocket 注册到Selector以接受连接 - serverChannel.register(selector, SelectionKey.OP_ACCEPT); - final ByteBuffer msg = ByteBuffer.wrap("Hi!\r\n".getBytes()); - for (;;) { - try { - //等待需要处理的新事件; 阻 塞 将一直持续到下一个传入事件 - selector.select(); - } catch (IOException ex) { - ex.printStackTrace(); - break; - } - //获取所有接收事件的Selection-Key实例 - Set readyKeys = selector.selectedKeys(); - Iterator iterator = readyKeys.iterator(); - while (iterator.hasNext()) { - SelectionKey key = iterator.next(); - iterator.remove(); - try { - //检查事件是否是一个新的已经就绪可以被接受的连接 - if (key.isAcceptable()) { - ServerSocketChannel server = (ServerSocketChannel) key.channel(); - SocketChannel client = server.accept(); - client.configureBlocking(false); - //接受客户端,并将它注册到选择器 - client.register(selector, SelectionKey.OP_WRITE - | SelectionKey.OP_READ, msg.duplicate()); - System.out.println("Accepted connection from " + client); - } - //检查套接字是否已经准备好写数据 - if (key.isWritable()) { - SocketChannel client = (SocketChannel) key.channel(); - ByteBuffer buffer = (ByteBuffer) key.attachment(); - //将数据写到已连接的客户端 - while (buffer.hasRemaining()) { - if (client.write(buffer) == 0) { - break; - } - } - client.close(); - } - } catch (IOException ex) { - key.cancel(); - try { - key.channel().close(); - } catch (IOException cex) { - // ignore on close - } - } - } - } - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/StaticTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/StaticTest.java deleted file mode 100644 index 4bf1c88fe0..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/StaticTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.jun.plugin.basics; - -/** - * - * @Title: StaticTest - * @Description: 构造块和静态方法测试 - * @Version:1.0.0 - * @author Administrator - * @date 2017-8-14 - */ -public class StaticTest { - public static StaticTest t1 = new StaticTest(); - public static StaticTest t2 = new StaticTest(); - { - System.out.println("构造块"); - } - static { - System.out.println("静态块"); - } - - public static void main(String[] args) { - StaticTest t = new StaticTest(); // 构造块 构造块 静态块 构造块 - - - // new HelloA(); extends HelloA - new HelloB(); //3 - /* - * 总结:创建对象时构造器的调用顺序是:先初始化静态成员,然后调用父类构造器,再初始化非静态成员,最后调用自身构造器。 - */ - - /* - * 总结 开始时JVM加载B.class,对所有的静态成员进行声明,t1 t2被初始化为默认值,为null, 又因为t1 - * t2需要被显式初始化,所以对t1进行显式初始化,初始化代码块→构造函数(没有就是调用默认的构造函数), - * 咦!静态代码块咋不初始化?因为在开始时已经对static部分进行了初始化,虽然只对static变量进行了初始化, - * 但在初始化t1时也不会再执行static块了,因为JVM认为这是第二次加载类B了,所以static会在t1初始化时被忽略掉, - * 所以直接初始化非static部分,也就是构造块部分(输出''构造块'')接着构造函数(无输出)。 - * 接着对t2进行初始化过程同t1相同(输出'构造块'),此时就对所有的static变量都完成了初始化, - * 接着就执行static块部分(输出'静态块'),接着执行,main方法,同样也,new了对象, 调用构造函数输出('构造块') - * - */ - - } - -} - -class HelloA { - private int i=10; - public HelloA() { - System.out.println("HelloA"); //5 - } - - { System.out.println("I'm A class"); } //4 - - static { System.out.println("static A"); } //1 - -} - class HelloB extends HelloA{ - private int j=12; - public HelloB() { - System.out.println("HelloB"); //7 - } - - { System.out.println("I'm B class"); } //6 - - static { System.out.println("static B"); } //2 - - - - - -} - diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/StringTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/StringTest.java deleted file mode 100644 index a83c3757d8..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/StringTest.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.jun.plugin.basics; - -/** -* Title: test1 -* Description: string相关问题 -* Version:1.0.0 -* @author pancm -* @date 2017-7-21 - */ -public class StringTest { - public static void main(String[] args) { - - String hello="hello"; - //有15种构造方法,有两种是过时的,其中包含char[],byte[],int[],String,StringBuffer,StringBuilder。 - String newHello=new String("hello"); - char []cHello ={'h','e','l','l','o'}; - String str=new String(cHello); - System.out.println(hello+","+newHello+","+str); - test1(); - test3(); - - System.out.println("=="+"-2".indexOf("-1")); - System.out.println("=="+"-1".indexOf("-1")); - System.out.println("=="+"0".indexOf("-1")); - System.out.println("=="+"1".indexOf("-1")); - String string = null; - System.out.println(""+string); - System.out.println((""+string)); - System.out.println(string+""); - System.out.println(string+"1"); - } - - - - - - private static void test1(){ - String str="Hello World"; - String str1=""; - StringBuffer sbr=new StringBuffer(str); - StringBuilder sbd=new StringBuilder(str); - long start=System.currentTimeMillis(); - for(int i=0;i<10000;i++){ - str1+=str; - } - System.out.println("String累加用时:"+(System.currentTimeMillis()-start)+"ms"); - long start2=System.currentTimeMillis(); - for(int i=0;i<10000;i++){ - sbr.append(str); - } - System.out.println("StringBuffer累加用时:"+(System.currentTimeMillis()-start2)+"ms"); - long start3=System.currentTimeMillis(); - for(int i=0;i<10000;i++){ - sbd.append(str); - } - System.out.println("StringBuilder累加用时:"+(System.currentTimeMillis()-start3)+"ms"); - } - - - private static void test3() { - - String s1 = "test"; - String s2 = new String("test"); - String s3 = "te"; - String s4 = "st"; - String s5 = "te" + "st"; - String s6 = s3 + s4; - String s7 = new String(s1); - // 引用地址不同 equals相同 - System.out.println(s1 == s2); //false - // s5 在编译之前就可以确认s5=Programming 因此相等 - System.out.println(s1 == s5); //true - //字符串常量池的原则 这时 s6 的值是在运行时得到的,它会重新构造字符串对象 所以为false - System.out.println(s1 == s6); //false - System.out.println(s7==s1); //false - System.out.println(s7.equals(s1)); //true - - - String ab="ab"; - String c="c"; - String ab_c=ab+c; - String ab_c1="ab"+"c"; - String abc="abc"; - /** - * 优先级问题 - */ - System.out.println(ab_c == abc + " : " + ab_c.equals(abc));//false - /** - * 字符串常量池的原则 这时 ab_c 的值是在运行时得到的,它会重新构造字符串对象 所以为false - */ - System.out.println((ab_c == abc) + " : " + ab_c.equals(abc));//false : true - /** - * 这条语言在编译时,可以确定 ab_c1 = "abc",因此它与 abc = "abc" 指向同一对象 所以为true - */ - System.out.println((ab_c1 == abc) + " : " + ab_c1.equals(abc));//true : true - - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/SuperTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/SuperTest.java deleted file mode 100644 index 6b97fea38f..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/SuperTest.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.jun.plugin.basics; - -/** - * -* @Title: SuperTest -* @Description: super测试 -* @Version:1.0.0 -* @author pancm -* @date 2017-5-24 - */ -public class SuperTest extends Person8 { - SuperTest() { - super(); // 调用父类构造函数(1) - prt("A chinese.");// (4) - } - - SuperTest(String name) { - super(name);// 调用父类具有相同形参的构造函数(2) 调用了Person中的Person(String name)方法 - prt("his name is:" + name); - } - - SuperTest(String name, int age) { - this(name);// 调用当前具有相同形参的构造函数(3) 调用了SuperTest(String name) - prt("his age is:" + age); - } - - public static void main(String[] args) { - SuperTest cn = new SuperTest(); // A Person. A chinese. - cn = new SuperTest("kevin"); //A person name is:kevin his name is:kevin - cn = new SuperTest("kevin", 22);//A person name is:kevin his name is:kevin his age is:22 - } -} - - -class Person8 { - - public static void prt(String s) { - System.out.println(s); - } - - Person8() { - prt("A Person."); - } - - Person8(String name) { - prt("A person name is:" + name); - - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/User.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/User.java deleted file mode 100644 index d78b680c0e..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/User.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.jun.plugin.basics; - -/** - * -* @Title: User -* @Description: -* 反射测试实体类 -* Version:1.0.0 -* @author pancm -* @date 2018年2月9日 - */ -public class User { - private String name; - - //构造方法1(默认构造方法)*********************** - public User(){ - - } - //构造方法2 - public User(String name){ - this.name=name; - } - //******自定义方法************* - public void getMessage(){ - System.out.print("反射测试"); - } - - //******自定义方法2************* - public String getMessage2(int num){ - String str=num+"反射测试!"; - System.out.print(str); - return str; - } - - //******自定义方法3************* - private String getMessage3(){ - String str="这是一个私有的方法!"; - System.out.print(str); - return str; - } - - - //******自定义方法4************* - public static String getMessage4(String s){ - String str=s+"这是一个静态的方法!"; - System.out.print(str); - return str; - } - - //******重写toString方法,在测试的时候会用到***** - @Override - public String toString() { - return "name:"+this.name; - } - //************************** - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/package-info.java deleted file mode 100644 index fe9141e2c8..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/basics/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: Java 基础知识的相关代码 -* @Version:1.0.0 -* @author pancm -* @date 2018年9月20日 -*/ -package com.jun.plugin.basics; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/hbase/HBaseUtil.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/hbase/HBaseUtil.java deleted file mode 100644 index ca6db2f4cb..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/hbase/HBaseUtil.java +++ /dev/null @@ -1,396 +0,0 @@ -package com.jun.plugin.bigdata.hbase; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.hadoop.conf.Configuration; -import org.apache.hadoop.hbase.Cell; -import org.apache.hadoop.hbase.CellUtil; -import org.apache.hadoop.hbase.HBaseConfiguration; -import org.apache.hadoop.hbase.HColumnDescriptor; -import org.apache.hadoop.hbase.HTableDescriptor; -import org.apache.hadoop.hbase.TableName; -import org.apache.hadoop.hbase.client.Admin; -import org.apache.hadoop.hbase.client.Connection; -import org.apache.hadoop.hbase.client.ConnectionFactory; -import org.apache.hadoop.hbase.client.Delete; -import org.apache.hadoop.hbase.client.Get; -import org.apache.hadoop.hbase.client.Put; -import org.apache.hadoop.hbase.client.Result; -import org.apache.hadoop.hbase.client.ResultScanner; -import org.apache.hadoop.hbase.client.Scan; -import org.apache.hadoop.hbase.client.Table; -import org.apache.hadoop.hbase.util.Bytes; - -import com.alibaba.fastjson.JSONObject; - -/** - * - * Title: HBaseUtil - * Description: HBase工具类 - * Version:1.0.0 - * @author pancm - * @date 2017年12月6日 - */ -public class HBaseUtil { - /** hadoop 连接 */ - private static Configuration conf = null; - /** hbase 连接 */ - private static Connection con = null; - /** 会话 */ - private static Admin admin = null; - - private static String ip ="master"; - private static String port ="2181"; - private static String port1 ="9001"; - - // 初始化连接 - static { - // 获得配制文件对象 - conf = HBaseConfiguration.create(); - // 设置配置参数 - conf.set("hbase.zookeeper.quorum", ip); - conf.set("hbase.zookeeper.property.clientPort", port); - //如果hbase是集群,这个必须加上 - //这个ip和端口是在hadoop/mapred-site.xml配置文件配置的 - conf.set("hbase.master", ip+":"+port1); - } - - - /** - * 获取连接 - * - * @return - */ - public synchronized static Connection getConnection() { - try { - if (null == con || con.isClosed()) { - // 获得连接对象 - con = ConnectionFactory.createConnection(conf); - } - } catch (IOException e) { - System.out.println("获取连接失败!"); - e.printStackTrace(); - } - - return con; - } - - /** - * 连接关闭 - */ - public static void close() { - try { - if (admin != null) { - admin.close(); - } - if (con != null) { - con.close(); - } - } catch (IOException e) { - System.out.println("连接关闭失败!"); - e.printStackTrace(); - } - } - - /** - * 创建表 - * - * @param tableName - * 表名 - * @param columnFamily - * 列族 - */ - public static void creatTable(String tableName, String[] columnFamily) { - if(null==tableName||tableName.length()==0){ - return; - } - if(null==columnFamily||columnFamily.length==0){ - return; - } - // 创建表名对象 - TableName tn = TableName.valueOf(tableName); - // a.判断数据库是否存在 - try { - // 获取会话 - admin = getConnection().getAdmin(); - if (admin.tableExists(tn)) { - System.out.println(tableName + " 表存在,删除表...."); - // 先使表设置为不可编辑 - admin.disableTable(tn); - // 删除表 - admin.deleteTable(tn); - System.out.println("表删除成功....."); - } - // 创建表结构对象 - HTableDescriptor htd = new HTableDescriptor(tn); - for (String str : columnFamily) { - // 创建列族结构对象 - HColumnDescriptor hcd = new HColumnDescriptor(str); - htd.addFamily(hcd); - } - // 创建表 - admin.createTable(htd); - System.out.println(tableName + " 表创建成功!"); - } catch (IOException e) { - e.printStackTrace(); - } finally { - close(); - } - } - - /** - * 数据单条插入或更新 - * - * @param tableName - * 表名 - * @param rowKey - * 行健 (主键) - * @param family - * 列族 - * @param qualifier - * 列 - * @param value - * 存入的值 - * @return - */ - public static void insert(String tableName, String rowKey, String family, - String qualifier, String value) { - Table t = null; - try { - t = getConnection().getTable(TableName.valueOf(tableName)); - Put put = new Put(Bytes.toBytes(rowKey)); - put.addColumn(Bytes.toBytes(family), Bytes.toBytes(qualifier), - Bytes.toBytes(value)); - t.put(put); - System.out.println(tableName + " 更新成功!"); - } catch (IOException e) { - System.out.println(tableName + " 更新失败!"); - e.printStackTrace(); - } finally { - close(); - } - } - - /** - * 数据批量插入或更新 - * - * @param tableName - * 表名 - * @param list - * hbase的数据 - * @return - */ - public static void insertBatch(String tableName, List list) { - if (null == tableName ||tableName.length()==0) { - return; - } - if( null == list || list.size() == 0){ - return; - } - Table t = null; - Put put = null; - JSONObject json = null; - List puts = new ArrayList(); - try { - t = getConnection().getTable(TableName.valueOf(tableName)); - for (int i = 0, j = list.size(); i < j; i++) { - json = (JSONObject) list.get(i); - put = new Put(Bytes.toBytes(json.getString("rowKey"))); - put.addColumn(Bytes.toBytes(json.getString("family")), - Bytes.toBytes(json.getString("qualifier")), - Bytes.toBytes(json.getString("value"))); - puts.add(put); - } - t.put(puts); - System.out.println(tableName + " 更新成功!"); - } catch (IOException e) { - System.out.println(tableName + " 更新失败!"); - e.printStackTrace(); - } finally { - close(); - } - } - - /** - * 数据删除 - * @param tableName 表名 - * @param rowKey 行健 - * @return - */ - public static void delete(String tableName, String rowKey) { - delete(tableName,rowKey,"",""); - } - - /** - * 数据删除 - * @param tableName 表名 - * @param rowKey 行健 - * @param family 列族 - * @return - */ - public static void delete(String tableName, String rowKey, String family) { - delete(tableName,rowKey,family,""); - } - - /** - * 数据删除 - * @param tableName 表名 - * @param rowKey 行健 - * @param family 列族 - * @param qualifier 列 - * @return - */ - public static void delete(String tableName, String rowKey, String family, - String qualifier) { - if (null == tableName ||tableName.length()==0) { - return; - } - if( null == rowKey || rowKey.length() == 0){ - return; - } - Table t = null; - try { - t = getConnection().getTable(TableName.valueOf(tableName)); - Delete del = new Delete(Bytes.toBytes(rowKey)); - // 如果列族不为空 - if (null != family && family.length() > 0) { - // 如果列不为空 - if (null != qualifier && qualifier.length() > 0) { - del.addColumn(Bytes.toBytes(family), - Bytes.toBytes(qualifier)); - } else { - del.addFamily(Bytes.toBytes(family)); - } - } - t.delete(del); - } catch (IOException e) { - System.out.println("删除失败!"); - e.printStackTrace(); - } finally { - close(); - } - } - - /** - * 查询该表中的所有数据 - * - * @param tableName - * 表名 - */ - public static void select(String tableName) { - if(null==tableName||tableName.length()==0){ - return; - } - Table t = null; - List> list=new ArrayList>(); - try { - t = getConnection().getTable(TableName.valueOf(tableName)); - // 读取操作 - Scan scan = new Scan(); - // 得到扫描的结果集 - ResultScanner rs = t.getScanner(scan); - if (null == rs ) { - return; - } - for (Result result : rs) { - // 得到单元格集合 - List cs = result.listCells(); - if (null == cs || cs.size() == 0) { - continue; - } - for (Cell cell : cs) { - Map map=new HashMap(); - map.put("rowKey", Bytes.toString(CellUtil.cloneRow(cell)));// 取行健 - map.put("timestamp", cell.getTimestamp());// 取到时间戳 - map.put("family", Bytes.toString(CellUtil.cloneFamily(cell)));// 取到列族 - map.put("qualifier", Bytes.toString(CellUtil.cloneQualifier(cell)));// 取到列 - map.put("value", Bytes.toString(CellUtil.cloneValue(cell)));// 取到值 - list.add(map); - } - } - System.out.println("查询的数据:"+list); - } catch (IOException e) { - System.out.println("查询失败!"); - e.printStackTrace(); - } finally { - close(); - } - } - - /** - * 根据表名和行健查询 - * @param tableName - * @param rowKey - */ - public static void select(String tableName, String rowKey) { - select(tableName,rowKey,"",""); - } - - /** - * 根据表名、行健和列族查询 - * @param tableName - * @param rowKey - * @param family - */ - public static void select(String tableName, String rowKey, String family) { - select(tableName,rowKey,family,""); - } - - /** - * 根据条件明细查询 - * - * @param tableName - * 表名 - * @param rowKey - * 行健 (主键) - * @param family - * 列族 - * @param qualifier - * 列 - */ - public static void select(String tableName, String rowKey, String family, - String qualifier) { - Table t = null; - List> list=new ArrayList>(); - try { - t = getConnection().getTable(TableName.valueOf(tableName)); - // 通过HBase中的 get来进行查询 - Get get = new Get(Bytes.toBytes(rowKey)); - // 如果列族不为空 - if (null != family && family.length() > 0) { - // 如果列不为空 - if (null != qualifier && qualifier.length() > 0) { - get.addColumn(Bytes.toBytes(family), - Bytes.toBytes(qualifier)); - } else { - get.addFamily(Bytes.toBytes(family)); - } - } - Result r = t.get(get); - List cs = r.listCells(); - if (null == cs || cs.size() == 0) { - return; - } - for (Cell cell : cs) { - Map map=new HashMap(); - map.put("rowKey", Bytes.toString(CellUtil.cloneRow(cell)));// 取行健 - map.put("timestamp", cell.getTimestamp());// 取到时间戳 - map.put("family", Bytes.toString(CellUtil.cloneFamily(cell)));// 取到列族 - map.put("qualifier", Bytes.toString(CellUtil.cloneQualifier(cell)));// 取到列 - map.put("value", Bytes.toString(CellUtil.cloneValue(cell)));// 取到值 - list.add(map); - } - System.out.println("查询的数据:"+list); - } catch (IOException e) { - System.out.println("查询失败!"); - e.printStackTrace(); - } finally { - close(); - } - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/hbase/HbaseTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/hbase/HbaseTest.java deleted file mode 100644 index 89d66f5eb0..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/hbase/HbaseTest.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.jun.plugin.bigdata.hbase; - -import java.util.ArrayList; -import java.util.List; - -import com.alibaba.fastjson.JSONObject; -/** - * -* Title: hbaseTest -* Description: HBase 相关测试 -* Version:1.0.0 -* @author pancm -* @date 2017年11月23日 - */ -public class HbaseTest { - - public static void main(String[] args) { - test(); - } - - /** - * 一些测试 - */ - private static void test() { - String tableName1="t_student",tableName2="t_student_info"; - String []columnFamily1={"st1","st2"}; - String []columnFamily2={"stf1","stf2"}; - HBaseUtil.creatTable(tableName1, columnFamily1); - HBaseUtil.creatTable(tableName2, columnFamily2); - - HBaseUtil.insert(tableName1, "1001", columnFamily1[0], "name", "zhangsan"); - HBaseUtil.insert(tableName1, "1002", columnFamily1[0], "name", "lisi"); - HBaseUtil.insert(tableName1, "1001", columnFamily1[1], "age", "18"); - HBaseUtil.insert(tableName1, "1002", columnFamily1[1], "age", "20"); - - HBaseUtil.insert(tableName2, "1001", columnFamily2[0], "phone", "123456"); - HBaseUtil.insert(tableName2, "1002", columnFamily2[0], "phone", "234567"); - HBaseUtil.insert(tableName2, "1001", columnFamily2[1], "mail", "123@163.com"); - HBaseUtil.insert(tableName2, "1002", columnFamily2[1], "mail", "234@163.com"); - - HBaseUtil.select(tableName1); //查询该表所有数据 - HBaseUtil.select(tableName1, "1001"); //根据表名和行健查询 - HBaseUtil.select(tableName2, "1002",columnFamily2[0]); //根据表名、行健和列族查询 - HBaseUtil.select(tableName2, "1002",columnFamily2[1],"mail"); //根据表名、行健、列族、和列查询 - - HBaseUtil.select(tableName1, "1002"); //根据表名和行健查询 - HBaseUtil.delete(tableName1, "1002", columnFamily1[0]);//删除数据 - HBaseUtil.select(tableName1, "1002"); //根据表名和行健查询 - - } - - - - - - - /** - * 批量测试方法 - * @param tableName 表名 - * @param family 列族 - * @param qualifier 列 - * @param value 值 - * @param k 次数 - */ - public static void insterTest(String tableName,String family,String qualifier,String value, int k){ - List list =new ArrayList<>(); - for(int i=1;i<=k;i++){ - JSONObject json =new JSONObject(); - json.put("rowKey", i); //行健 - json.put("family", family); //列族 - json.put("qualifier", qualifier); //列 - if("t_student".equals(tableName)){ //如果是t_student 姓名则加上编号 - json.put("value", value+i); //值 - }else if("".equals(value)){ //如果为空,则是年龄 - json.put("value", i); //值 - }else{ //否则就是性别 - json.put("value", value); //值 - } - - list.add(json); - } - HBaseUtil.insertBatch(tableName,list); - } - - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/hbase/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/hbase/package-info.java deleted file mode 100644 index b99212d5ce..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/hbase/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: hbase相关的代码 -* @Version:1.0.0 -* @author pancm -* @date 2018年9月21日 -*/ -package com.jun.plugin.bigdata.hbase; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/package-info.java deleted file mode 100644 index d0dbf180a2..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: 大数据相关代码 -* @Version:1.0.0 -* @author pancm -* @date 2018年9月20日 -*/ -package com.jun.plugin.bigdata; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example/WordCountApp.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example/WordCountApp.java deleted file mode 100644 index d428406ed3..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example/WordCountApp.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.jun.plugin.bigdata.storm.example; - -import org.apache.storm.Config; -import org.apache.storm.LocalCluster; -import org.apache.storm.StormSubmitter; -import org.apache.storm.generated.AlreadyAliveException; -import org.apache.storm.generated.AuthorizationException; -import org.apache.storm.generated.InvalidTopologyException; -import org.apache.storm.generated.StormTopology; -import org.apache.storm.topology.TopologyBuilder; -import org.apache.storm.tuple.Fields; - - - -/** - * -* Title: WordCountApp -* Description: 测试storm本地模式 统计words单次个数 -* 源代码地址:http://www.tianshouzhi.com/api/tutorials/storm/54 -* Version:1.0.0 -* @author pancm -* @date 2017年12月28日 - */ -public class WordCountApp { - public static void main(String[] args) throws InterruptedException, AlreadyAliveException, InvalidTopologyException { - //定义拓扑 - TopologyBuilder builder = new TopologyBuilder(); - builder.setSpout("word-reader" , new WordReader()); - builder.setBolt("word-normalizer" , new WordNormalizer()).shuffleGrouping("word-reader" ); - builder.setBolt("word-counter" , new WordCounter()).fieldsGrouping("word-normalizer" , new Fields("word")); - StormTopology topology = builder.createTopology(); - //配置 - - Config conf = new Config(); - String fileName ="words.txt" ; - conf.put("fileName" , fileName ); - conf.setDebug(false); - - //运行拓扑 - System.out.println("开始..."); - if(args !=null&&args.length>0){ //有参数时,表示向集群提交作业,并把第一个参数当做topology名称 - System.out.println("远程模式"); - try { - StormSubmitter.submitTopology(args[0], conf, topology); - } catch (AuthorizationException e) { - e.printStackTrace(); - } - } else{//没有参数时,本地提交 - //启动本地模式 - System.out.println("本地模式"); - LocalCluster cluster = new LocalCluster(); - cluster.submitTopology("Getting-Started-Topologie" , conf , topology ); - Thread.sleep(5000); - //关闭本地集群 - cluster.shutdown(); - } - System.out.println("结束"); - - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example/WordCounter.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example/WordCounter.java deleted file mode 100644 index 82479dc1f3..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example/WordCounter.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.jun.plugin.bigdata.storm.example; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.storm.task.OutputCollector; -import org.apache.storm.task.TopologyContext; -import org.apache.storm.topology.IRichBolt; -import org.apache.storm.topology.OutputFieldsDeclarer; -import org.apache.storm.tuple.Tuple; - -/** - * -* Title: WordCounter -* Description: 该类主要用于统计 -* Version:1.0.0 -* @author pancm -* @date 2017年12月28日 - */ -public class WordCounter implements IRichBolt { - /** - * - */ - private static final long serialVersionUID = 1L; - Integer id; - String name; - Map counters; - private OutputCollector collector; - - /** - * 当Bolt销毁时,我们会显示单词数量 - */ - @Override - public void cleanup() { - System.out.println("开始显示单词数量..."); - for (Map.Entry entry : counters.entrySet()) { - System.out.println(entry.getKey() + ": " + entry.getValue()); - } - System.out.println("WordCounter.cleanup()"); - } - - /** - * 为每个单词计数 - */ - @Override - public void execute(Tuple input) { - System.out.println("WordCounter.execute()"); - String str = input.getString(0); - /** - * 如果单词尚不存在于map,我们就创建一个,如果已在,我们就为它加1 - */ - if (!counters.containsKey(str)) { - counters.put(str, 1); - } else { - Integer c = counters.get(str) + 1; - counters.put(str, c); - } - // 对元组作为应答 - collector.ack(input); - } - - /** - * 初始化 - */ - @Override - public void prepare(Map stormConf, TopologyContext context, - OutputCollector collector) { - this.counters = new HashMap(); - this.collector = collector; - this.name = context.getThisComponentId(); - this.id = context.getThisTaskId(); - } - - @Override - public void declareOutputFields(OutputFieldsDeclarer declarer) { - System.out.println("WordCounter.declareOutputFields()"); - } - - @Override - public Map getComponentConfiguration() { - System.out.println("WordCounter.getComponentConfiguration()"); - return null; - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example/WordNormalizer.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example/WordNormalizer.java deleted file mode 100644 index 4d84d3d059..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example/WordNormalizer.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.jun.plugin.bigdata.storm.example; - -import java.util.Map; - -import org.apache.storm.task.OutputCollector; -import org.apache.storm.task.TopologyContext; -import org.apache.storm.topology.IRichBolt; -import org.apache.storm.topology.OutputFieldsDeclarer; -import org.apache.storm.tuple.Fields; -import org.apache.storm.tuple.Tuple; -import org.apache.storm.tuple.Values; - - -/** - * -* Title: WordNormalizer -* Description:该类主要用于格式化数据 -* Version:1.0.0 -* @author pancm -* @date 2017年12月28日 - */ -public class WordNormalizer implements IRichBolt { - /** - * - */ - private static final long serialVersionUID = 3644849073824009317L; - private OutputCollector collector; - private static int count=1; - - /** - * *bolt*从单词文件接收到文本行,并标准化它。 文本行会全部转化成小写,并切分它,从中得到所有单词。 - */ - public void execute(Tuple input) { - System.out.println("WordNormalizer.execute()执行次数:"+count); - String sentence = input.getString(0); - String[] words = sentence.split(" "); - for (String word : words) { - word = word.trim(); - if (!word.isEmpty()) { - word = word.toLowerCase(); - /* //发布这个单词 */ - collector.emit(input, new Values(word)); - } - } - // 对元组做出应答 - collector.ack(input); - count++; - } - - public void prepare(Map stormConf, TopologyContext context, - OutputCollector collector) { - System.out.println("WordNormalizer.prepare()"); - this.collector = collector; - } - - /** - * 这个*bolt*只会发布“word”域 - */ - public void declareOutputFields(OutputFieldsDeclarer declarer) { - System.out.println("WordNormalizer.declareOutputFields()"); - declarer.declare(new Fields("word")); - } - - @Override - public Map getComponentConfiguration() { - System.out.println("WordNormalizer.getComponentConfiguration()"); - return null; - } - - public void cleanup() { - System.out.println("WordNormalizer.cleanup()"); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example/WordReader.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example/WordReader.java deleted file mode 100644 index 47fd582d4e..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example/WordReader.java +++ /dev/null @@ -1,129 +0,0 @@ -package com.jun.plugin.bigdata.storm.example; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.Map; - -import org.apache.storm.spout.SpoutOutputCollector; -import org.apache.storm.task.TopologyContext; -import org.apache.storm.topology.IRichSpout; -import org.apache.storm.topology.OutputFieldsDeclarer; -import org.apache.storm.tuple.Fields; -import org.apache.storm.tuple.Values; - - -/** - * -* Title: WordReader -* Description: 该类主要用于从外部数据源words.txt中获取数据 -* Version:1.0.0 -* @author pancm -* @date 2017年12月28日 - */ -public class WordReader implements IRichSpout { - /** - * - */ - private static final long serialVersionUID = 6146631397258548505L; - private SpoutOutputCollector collector; - private FileReader fileReader; - BufferedReader reader; - private boolean completed = false; - - /** - * 这个方法做的惟一一件事情就是分发文件中的文本行 - */ - public void nextTuple() { - /** - * 这个方法会不断的被调用,直到整个文件都读完了,我们将等待并返回。 - */ - if (completed) { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - // 什么也不做 - } - return; - } - String str; - - try { - int i = 0; - // 读所有文本行 - while ((str = reader.readLine()) != null) { - System.out.println("WordReader.nextTuple(),emits time:" + i++); - /** - * 按行发布一个新值 - */ - this.collector.emit(new Values(str), str); - } - } catch (Exception e) { - throw new RuntimeException("Error reading tuple", e); - } finally { - completed = true; - } - } - - /** - * - * 当Spout被创建之后,这个方法会被掉用 - */ - public void open(Map conf, TopologyContext context, - SpoutOutputCollector collector) { - - System.out.println("WordReader.open(Map conf, TopologyContext context, SpoutOutputCollector collector)"); - String fileName = conf.get("fileName").toString(); - InputStream inputStream = WordReader.class.getClassLoader() - .getResourceAsStream(fileName); - reader = new BufferedReader(new InputStreamReader(inputStream)); - this.collector = collector; - } - - /** - * 声明数据格式,即输出的一个Tuple中,包含几个字段 - */ - public void declareOutputFields(OutputFieldsDeclarer declarer) { - System.out - .println("WordReader.declareOutputFields(OutputFieldsDeclarer declarer)"); - declarer.declare(new Fields("line")); - } - - @Override - public void activate() { - System.out.println("WordReader.activate()"); - } - - @Override - public void deactivate() { - System.out.println("WordReader.deactivate()"); - } - - @Override - public Map getComponentConfiguration() { - System.out.println("WordReader.getComponentConfiguration()"); - return null; - } - - /** - * 当一个Tuple处理成功时,会调用这个方法 - */ - public void ack(Object msgId) { - System.out.println("WordReader.ack(Object msgId):" + msgId); - } - - /** - * 当Topology停止时,会调用这个方法 - */ - public void close() { - System.out.println("WordReader.close()"); - } - - /** - * 当一个Tuple处理失败时,会调用这个方法 - */ - public void fail(Object msgId) { - System.out.println("WordReader.fail(Object msgId):" + msgId); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example/package-info.java deleted file mode 100644 index e32cca3249..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example/package-info.java +++ /dev/null @@ -1,11 +0,0 @@ -/** - * - */ -/** - * Title: package-info - * Description: - * Version:1.0.0 - * @author pancm - * @date 2017年12月28日 - */ -package com.jun.plugin.bigdata.storm.example; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example1/ReportBolt.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example1/ReportBolt.java deleted file mode 100644 index 5be035ad2e..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example1/ReportBolt.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.jun.plugin.bigdata.storm.example1; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import org.apache.storm.task.OutputCollector; -import org.apache.storm.task.TopologyContext; -import org.apache.storm.topology.OutputFieldsDeclarer; -import org.apache.storm.topology.base.BaseRichBolt; -import org.apache.storm.tuple.Tuple; - - - -/** - * 生成一份报告 - * @author soul - * - */ -public class ReportBolt extends BaseRichBolt { - - private HashMap counts = null;//保存单词和对应的计数 - - public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) { - // TODO Auto-generated method stub - - this.counts = new HashMap(); - } - - public void execute(Tuple input) { - // TODO Auto-generated method stub - - String word = input.getStringByField("word"); - Long count = input.getLongByField("count"); - this.counts.put(word, count); - - //实时输出 - System.out.println("结果:"+this.counts); - } - - public void declareOutputFields(OutputFieldsDeclarer declarer) { - // TODO Auto-generated method stub - //这里是末端bolt,不需要发射数据流,这里无需定义 - } - - /** - * cleanup是IBolt接口中定义 - * Storm在终止一个bolt之前会调用这个方法 - * 本例我们利用cleanup()方法在topology关闭时输出最终的计数结果 - * 通常情况下,cleanup()方法用来释放bolt占用的资源,如打开的文件句柄或数据库连接 - * 但是当Storm拓扑在一个集群上运行,IBolt.cleanup()方法不能保证执行(这里是开发模式,生产环境不要这样做)。 - */ - public void cleanup(){ - System.out.println("---------- FINAL COUNTS -----------"); - - ArrayList keys = new ArrayList(); - keys.addAll(this.counts.keySet()); - Collections.sort(keys); - for(String key : keys){ - System.out.println(key + " : " + this.counts.get(key)); - } - System.out.println("----------------------------"); - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example1/SentenceSpout.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example1/SentenceSpout.java deleted file mode 100644 index 9afa0178fa..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example1/SentenceSpout.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.jun.plugin.bigdata.storm.example1; - -import java.util.Map; - -import org.apache.storm.spout.SpoutOutputCollector; -import org.apache.storm.task.TopologyContext; -import org.apache.storm.topology.OutputFieldsDeclarer; -import org.apache.storm.topology.base.BaseRichSpout; -import org.apache.storm.tuple.Fields; -import org.apache.storm.tuple.Values; -import org.apache.storm.utils.Utils; - - - -/** - * 向后端发射tuple数据流 - * @author soul - * - */ -public class SentenceSpout extends BaseRichSpout { - - //BaseRichSpout是ISpout接口和IComponent接口的简单实现,接口对用不到的方法提供了默认的实现 - - /** - * - */ - private static final long serialVersionUID = 1L; - private SpoutOutputCollector collector; - private String[] sentences = { - "my name is soul", - "im a boy", - "i have a dog", - "my dog has fleas", - "my girl friend is beautiful" - }; - - private int index=0; - - /** - * open()方法中是ISpout接口中定义,在Spout组件初始化时被调用。 - * open()接受三个参数:一个包含Storm配置的Map,一个TopologyContext对象,提供了topology中组件的信息,SpoutOutputCollector对象提供发射tuple的方法。 - * 在这个例子中,我们不需要执行初始化,只是简单的存储在一个SpoutOutputCollector实例变量。 - */ - public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) { - // TODO Auto-generated method stub - this.collector = collector; - } - - /** - * nextTuple()方法是任何Spout实现的核心。 - * Storm调用这个方法,向输出的collector发出tuple。 - * 在这里,我们只是发出当前索引的句子,并增加该索引准备发射下一个句子。 - */ - public void nextTuple() { - //collector.emit(new Values("hello world this is a test")); - - // TODO Auto-generated method stub - this.collector.emit(new Values(sentences[index])); - index++; - if (index>=sentences.length) { - index=0; - } - Utils.sleep(1); - } - - /** - * declareOutputFields是在IComponent接口中定义的,所有Storm的组件(spout和bolt)都必须实现这个接口 - * 用于告诉Storm流组件将会发出那些数据流,每个流的tuple将包含的字段 - */ - public void declareOutputFields(OutputFieldsDeclarer declarer) { - // TODO Auto-generated method stub - - declarer.declare(new Fields("sentence"));//告诉组件发出数据流包含sentence字段 - - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example1/SplitSentenceBolt.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example1/SplitSentenceBolt.java deleted file mode 100644 index e79595e5c2..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example1/SplitSentenceBolt.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.jun.plugin.bigdata.storm.example1; - -import java.util.Map; - -import org.apache.storm.task.OutputCollector; -import org.apache.storm.task.TopologyContext; -import org.apache.storm.topology.OutputFieldsDeclarer; -import org.apache.storm.topology.base.BaseRichBolt; -import org.apache.storm.tuple.Fields; -import org.apache.storm.tuple.Tuple; -import org.apache.storm.tuple.Values; - - - -/** - * 订阅sentence spout发射的tuple流,实现分割单词 - * @author soul - * - */ -public class SplitSentenceBolt extends BaseRichBolt { - //BaseRichBolt是IComponent和IBolt接口的实现 - //继承这个类,就不用去实现本例不关心的方法 - - /** - * - */ - private static final long serialVersionUID = 1L; - private OutputCollector collector; - - /** - * prepare()方法类似于ISpout 的open()方法。 - * 这个方法在blot初始化时调用,可以用来准备bolt用到的资源,比如数据库连接。 - * 本例子和SentenceSpout类一样,SplitSentenceBolt类不需要太多额外的初始化, - * 所以prepare()方法只保存OutputCollector对象的引用。 - */ - public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) { - // TODO Auto-generated method stub - this.collector=collector; - - } - - /** - * SplitSentenceBolt核心功能是在类IBolt定义execute()方法,这个方法是IBolt接口中定义。 - * 每次Bolt从流接收一个订阅的tuple,都会调用这个方法。 - * 本例中,收到的元组中查找“sentence”的值, - * 并将该值拆分成单个的词,然后按单词发出新的tuple。 - */ - public void execute(Tuple input) { - // TODO Auto-generated method stub - String sentence = input.getStringByField("sentence"); - String[] words = sentence.split(" "); - for (String word : words) { - this.collector.emit(new Values(word));//向下一个bolt发射数据 - } - } - - /** - * plitSentenceBolt类定义一个元组流,每个包含一个字段(“word”)。 - */ - public void declareOutputFields(OutputFieldsDeclarer declarer) { - // TODO Auto-generated method stub - declarer.declare(new Fields("word")); - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example1/WordCountApp.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example1/WordCountApp.java deleted file mode 100644 index 744e692bf0..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example1/WordCountApp.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.jun.plugin.bigdata.storm.example1; - - - -import org.apache.storm.Config; -import org.apache.storm.LocalCluster; -import org.apache.storm.topology.TopologyBuilder; -import org.apache.storm.tuple.Fields; -import org.apache.storm.utils.Utils; - -/** - * 实现单词计数topology - * - */ -public class WordCountApp -{ - private static final String SENTENCE_SPOUT_ID = "sentence-spout"; - private static final String SPLIT_BOLT_ID = "split-bolt"; - private static final String COUNT_BOLT_ID = "count-bolt"; - private static final String REPORT_BOLT_ID = "report-bolt"; - private static final String TOPOLOGY_NAME = "word-count-topology"; - - public static void main( String[] args ) //throws Exception - { - //System.out.println( "Hello World!" ); - //实例化spout和bolt - - SentenceSpout spout = new SentenceSpout(); - SplitSentenceBolt splitBolt = new SplitSentenceBolt(); - WordCountBolt countBolt = new WordCountBolt(); - ReportBolt reportBolt = new ReportBolt(); - - TopologyBuilder builder = new TopologyBuilder();//创建了一个TopologyBuilder实例 - - //TopologyBuilder提供流式风格的API来定义topology组件之间的数据流 - - //builder.setSpout(SENTENCE_SPOUT_ID, spout);//注册一个sentence spout - - //设置两个Executeor(线程),默认一个 - builder.setSpout(SENTENCE_SPOUT_ID, spout,2); - - // SentenceSpout --> SplitSentenceBolt - - //注册一个bolt并订阅sentence发射出的数据流,shuffleGrouping方法告诉Storm要将SentenceSpout发射的tuple随机均匀的分发给SplitSentenceBolt的实例 - //builder.setBolt(SPLIT_BOLT_ID, splitBolt).shuffleGrouping(SENTENCE_SPOUT_ID); - - //SplitSentenceBolt单词分割器设置4个Task,2个Executeor(线程) - builder.setBolt(SPLIT_BOLT_ID, splitBolt,2).setNumTasks(4).shuffleGrouping(SENTENCE_SPOUT_ID); - - // SplitSentenceBolt --> WordCountBolt - - //fieldsGrouping将含有特定数据的tuple路由到特殊的bolt实例中 - //这里fieldsGrouping()方法保证所有“word”字段相同的tuuple会被路由到同一个WordCountBolt实例中 - //builder.setBolt(COUNT_BOLT_ID, countBolt).fieldsGrouping( SPLIT_BOLT_ID, new Fields("word")); - - //WordCountBolt单词计数器设置4个Executeor(线程) - builder.setBolt(COUNT_BOLT_ID, countBolt,4).fieldsGrouping( SPLIT_BOLT_ID, new Fields("word")); - - // WordCountBolt --> ReportBolt - - //globalGrouping是把WordCountBolt发射的所有tuple路由到唯一的ReportBolt - builder.setBolt(REPORT_BOLT_ID, reportBolt).globalGrouping(COUNT_BOLT_ID); - - - Config config = new Config();//Config类是一个HashMap的子类,用来配置topology运行时的行为 - //设置worker数量 - //config.setNumWorkers(2); - //本地提交 - LocalCluster cluster = new LocalCluster(); - - cluster.submitTopology(TOPOLOGY_NAME, config, builder.createTopology()); - - Utils.sleep(10000); - cluster.killTopology(TOPOLOGY_NAME); - cluster.shutdown(); - - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example1/WordCountBolt.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example1/WordCountBolt.java deleted file mode 100644 index eef8e845fc..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example1/WordCountBolt.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.jun.plugin.bigdata.storm.example1; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.storm.task.OutputCollector; -import org.apache.storm.task.TopologyContext; -import org.apache.storm.topology.OutputFieldsDeclarer; -import org.apache.storm.topology.base.BaseRichBolt; -import org.apache.storm.tuple.Fields; -import org.apache.storm.tuple.Tuple; -import org.apache.storm.tuple.Values; - - - -/** - * 订阅 split sentence bolt的输出流,实现单词计数,并发送当前计数给下一个bolt - * @author soul - * - */ -public class WordCountBolt extends BaseRichBolt { - /** - * - */ - private static final long serialVersionUID = 1L; - private OutputCollector collector; - //存储单词和对应的计数 - private HashMap counts = null;//注:不可序列化对象需在prepare中实例化 - - /** - * 大部分实例变量通常是在prepare()中进行实例化,这个设计模式是由topology的部署方式决定的 - * 因为在部署拓扑时,组件spout和bolt是在网络上发送的序列化的实例变量。 - * 如果spout或bolt有任何non-serializable实例变量在序列化之前被实例化(例如,在构造函数中创建) - * 会抛出NotSerializableException并且拓扑将无法发布。 - * 本例中因为HashMap 是可序列化的,所以可以安全地在构造函数中实例化。 - * 但是,通常情况下最好是在构造函数中对基本数据类型和可序列化的对象进行复制和实例化 - * 而在prepare()方法中对不可序列化的对象进行实例化。 - */ - public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) { - // TODO Auto-generated method stub - this.collector = collector; - this.counts = new HashMap(); - } - - /** - * 在execute()方法中,我们查找的收到的单词的计数(如果不存在,初始化为0) - * 然后增加计数并存储,发出一个新的词和当前计数组成的二元组。 - * 发射计数作为流允许拓扑的其他bolt订阅和执行额外的处理。 - */ - public void execute(Tuple input) { - // TODO Auto-generated method stub - - String word = input.getStringByField("word"); - Long count = this.counts.get(word); - if (count == null) { - count = 0L;//如果不存在,初始化为0 - } - count++;//增加计数 - this.counts.put(word, count);//存储计数 - this.collector.emit(new Values(word,count)); - } - - /** - * - */ - public void declareOutputFields(OutputFieldsDeclarer declarer) { - // TODO Auto-generated method stub - //声明一个输出流,其中tuple包括了单词和对应的计数,向后发射 - //其他bolt可以订阅这个数据流进一步处理 - declarer.declare(new Fields("word","count")); - } - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example1/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example1/package-info.java deleted file mode 100644 index a6327047ea..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/example1/package-info.java +++ /dev/null @@ -1,11 +0,0 @@ -/** - * - */ -/** - * Title: package-info - * Description: - * Version:1.0.0 - * @author pancm - * @date 2017年12月29日 - */ -package com.jun.plugin.bigdata.storm.example1; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/one/WordCountApp.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/one/WordCountApp.java deleted file mode 100644 index 17cca29277..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/one/WordCountApp.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.jun.plugin.bigdata.storm.one; - -import org.apache.storm.Config; -import org.apache.storm.LocalCluster; -import org.apache.storm.StormSubmitter; -import org.apache.storm.generated.AlreadyAliveException; -import org.apache.storm.generated.AuthorizationException; -import org.apache.storm.generated.InvalidTopologyException; -import org.apache.storm.generated.StormTopology; -import org.apache.storm.topology.TopologyBuilder; -import org.apache.storm.tuple.Fields; - - - -/** - * -* Title: WordCountApp -* Description: 测试storm本地模式 统计words单次个数 -* 源代码地址:http://www.tianshouzhi.com/api/tutorials/storm/54 -* Version:1.0.0 -* @author pancm -* @date 2017年12月28日 - */ -public class WordCountApp { - public static void main(String[] args) throws InterruptedException, AlreadyAliveException, InvalidTopologyException { - //定义拓扑 - TopologyBuilder builder = new TopologyBuilder(); - builder.setSpout("word-reader" , new WordReader()); - builder.setBolt("word-normalizer" , new WordNormalizer()).shuffleGrouping("word-reader" ); - builder.setBolt("word-counter" , new WordCounter()).fieldsGrouping("word-normalizer" , new Fields("word")); - StormTopology topology = builder.createTopology(); - //配置 - - Config conf = new Config(); - String fileName ="words.txt" ; - conf.put("fileName" , fileName ); - conf.setDebug(false); - - //运行拓扑 - System.out.println("开始..."); - if(args !=null&&args.length>0){ //有参数时,表示向集群提交作业,并把第一个参数当做topology名称 - System.out.println("远程模式"); - try { - StormSubmitter.submitTopology(args[0], conf, topology); - } catch (AuthorizationException e) { - e.printStackTrace(); - } - } else{//没有参数时,本地提交 - //启动本地模式 - System.out.println("本地模式"); - LocalCluster cluster = new LocalCluster(); - cluster.submitTopology("Getting-Started-Topologie" , conf , topology ); - Thread.sleep(5000); - //关闭本地集群 - cluster.shutdown(); - } - System.out.println("结束"); - - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/one/WordCounter.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/one/WordCounter.java deleted file mode 100644 index b6cffa6809..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/one/WordCounter.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.jun.plugin.bigdata.storm.one; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.storm.task.OutputCollector; -import org.apache.storm.task.TopologyContext; -import org.apache.storm.topology.IRichBolt; -import org.apache.storm.topology.OutputFieldsDeclarer; -import org.apache.storm.tuple.Tuple; - -/** - * -* Title: WordCounter -* Description: 该类主要用于统计 -* Version:1.0.0 -* @author pancm -* @date 2017年12月28日 - */ -public class WordCounter implements IRichBolt { - /** - * - */ - private static final long serialVersionUID = 1L; - Integer id; - String name; - Map counters; - private OutputCollector collector; - - /** - * 当Bolt销毁时,我们会显示单词数量 - */ - @Override - public void cleanup() { - System.out.println("开始显示单词数量..."); - for (Map.Entry entry : counters.entrySet()) { - System.out.println(entry.getKey() + ": " + entry.getValue()); - } - System.out.println("WordCounter.cleanup()"); - } - - /** - * 为每个单词计数 - */ - @Override - public void execute(Tuple input) { - System.out.println("WordCounter.execute()"); - String str = input.getString(0); - /** - * 如果单词尚不存在于map,我们就创建一个,如果已在,我们就为它加1 - */ - if (!counters.containsKey(str)) { - counters.put(str, 1); - } else { - Integer c = counters.get(str) + 1; - counters.put(str, c); - } - // 对元组作为应答 - collector.ack(input); - } - - /** - * 初始化 - */ - @Override - public void prepare(Map stormConf, TopologyContext context, - OutputCollector collector) { - this.counters = new HashMap(); - this.collector = collector; - this.name = context.getThisComponentId(); - this.id = context.getThisTaskId(); - } - - @Override - public void declareOutputFields(OutputFieldsDeclarer declarer) { - System.out.println("WordCounter.declareOutputFields()"); - } - - @Override - public Map getComponentConfiguration() { - System.out.println("WordCounter.getComponentConfiguration()"); - return null; - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/one/WordNormalizer.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/one/WordNormalizer.java deleted file mode 100644 index cf14845cc5..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/one/WordNormalizer.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.jun.plugin.bigdata.storm.one; - -import java.util.Map; - -import org.apache.storm.task.OutputCollector; -import org.apache.storm.task.TopologyContext; -import org.apache.storm.topology.IRichBolt; -import org.apache.storm.topology.OutputFieldsDeclarer; -import org.apache.storm.tuple.Fields; -import org.apache.storm.tuple.Tuple; -import org.apache.storm.tuple.Values; - - -/** - * -* Title: WordNormalizer -* Description:该类主要用于格式化数据 -* Version:1.0.0 -* @author pancm -* @date 2017年12月28日 - */ -public class WordNormalizer implements IRichBolt { - /** - * - */ - private static final long serialVersionUID = 3644849073824009317L; - private OutputCollector collector; - - /** - * *bolt*从单词文件接收到文本行,并标准化它。 文本行会全部转化成小写,并切分它,从中得到所有单词。 - */ - public void execute(Tuple input) { - System.out.println("WordNormalizer.execute()"); - String sentence = input.getString(0); - String[] words = sentence.split(" "); - for (String word : words) { - word = word.trim(); - if (!word.isEmpty()) { - word = word.toLowerCase(); - /* //发布这个单词 */ - collector.emit(input, new Values(word)); - } - } - // 对元组做出应答 - collector.ack(input); - } - - public void prepare(Map stormConf, TopologyContext context, - OutputCollector collector) { - System.out.println("WordNormalizer.prepare()"); - this.collector = collector; - } - - /** - * 这个*bolt*只会发布“word”域 - */ - public void declareOutputFields(OutputFieldsDeclarer declarer) { - System.out.println("WordNormalizer.declareOutputFields()"); - declarer.declare(new Fields("word")); - } - - @Override - public Map getComponentConfiguration() { - System.out.println("WordNormalizer.getComponentConfiguration()"); - return null; - } - - public void cleanup() { - System.out.println("WordNormalizer.cleanup()"); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/one/WordReader.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/one/WordReader.java deleted file mode 100644 index e151b1b9c8..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/one/WordReader.java +++ /dev/null @@ -1,130 +0,0 @@ -package com.jun.plugin.bigdata.storm.one; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.Map; - -import org.apache.storm.spout.SpoutOutputCollector; -import org.apache.storm.task.TopologyContext; -import org.apache.storm.topology.IRichSpout; -import org.apache.storm.topology.OutputFieldsDeclarer; -import org.apache.storm.tuple.Fields; -import org.apache.storm.tuple.Values; - - -/** - * -* Title: WordReader -* Description: 该类主要用于从外部数据源words.txt中获取数据 -* Version:1.0.0 -* @author pancm -* @date 2017年12月28日 - */ -public class WordReader implements IRichSpout { - /** - * - */ - private static final long serialVersionUID = 6146631397258548505L; - private SpoutOutputCollector collector; - private FileReader fileReader; - BufferedReader reader; - private boolean completed = false; - - /** - * 这个方法做的惟一一件事情就是分发文件中的文本行 - */ - public void nextTuple() { - /** - * 这个方法会不断的被调用,直到整个文件都读完了,我们将等待并返回。 - */ - if (completed) { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - // 什么也不做 - } - return; - } - String str; - - try { - int i = 0; - // 读所有文本行 - while ((str = reader.readLine()) != null) { - System.out.println("WordReader.nextTuple(),emits time:" + i++); - /** - * 按行发布一个新值 - */ - this.collector.emit(new Values(str), str); - } - } catch (Exception e) { - throw new RuntimeException("Error reading tuple", e); - } finally { - completed = true; - } - } - - /** - * - * 当Spout被创建之后,这个方法会被掉用 - */ - public void open(Map conf, TopologyContext context, - SpoutOutputCollector collector) { - - System.out - .println("WordReader.open(Map conf, TopologyContext context, SpoutOutputCollector collector)"); - String fileName = conf.get("fileName").toString(); - InputStream inputStream = WordReader.class.getClassLoader() - .getResourceAsStream(fileName); - reader = new BufferedReader(new InputStreamReader(inputStream)); - this.collector = collector; - } - - /** - * 声明数据格式,即输出的一个Tuple中,包含几个字段 - */ - public void declareOutputFields(OutputFieldsDeclarer declarer) { - System.out - .println("WordReader.declareOutputFields(OutputFieldsDeclarer declarer)"); - declarer.declare(new Fields("line")); - } - - @Override - public void activate() { - System.out.println("WordReader.activate()"); - } - - @Override - public void deactivate() { - System.out.println("WordReader.deactivate()"); - } - - @Override - public Map getComponentConfiguration() { - System.out.println("WordReader.getComponentConfiguration()"); - return null; - } - - /** - * 当一个Tuple处理成功时,会调用这个方法 - */ - public void ack(Object msgId) { - System.out.println("WordReader.ack(Object msgId):" + msgId); - } - - /** - * 当Topology停止时,会调用这个方法 - */ - public void close() { - System.out.println("WordReader.close()"); - } - - /** - * 当一个Tuple处理失败时,会调用这个方法 - */ - public void fail(Object msgId) { - System.out.println("WordReader.fail(Object msgId):" + msgId); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/one/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/one/package-info.java deleted file mode 100644 index 9b461222af..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/one/package-info.java +++ /dev/null @@ -1,11 +0,0 @@ -/** - * - */ -/** - * Title: package-info - * Description: - * Version:1.0.0 - * @author pancm - * @date 2017年12月28日 - */ -package com.jun.plugin.bigdata.storm.one; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/package-info.java deleted file mode 100644 index 0018a60a46..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/package-info.java +++ /dev/null @@ -1,11 +0,0 @@ -/** - * - */ -/** - * Title: package-info - * Description: strom相关代码 - * Version:1.0.0 - * @author pancm - * @date 2018年1月11日 - */ -package com.jun.plugin.bigdata.storm; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/test/App.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/test/App.java deleted file mode 100644 index 71807ea5be..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/test/App.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.jun.plugin.bigdata.storm.test; - -import org.apache.storm.Config; -import org.apache.storm.LocalCluster; -import org.apache.storm.StormSubmitter; -import org.apache.storm.topology.TopologyBuilder; - -/** - * -* Title: App -* Description: -* storm测试 -* Version:1.0.0 -* @author pancm -* @date 2018年3月6日 - */ -public class App { - - private static final String str1="test1"; - private static final String str2="test2"; - - public static void main(String[] args) { - // TODO Auto-generated method stub - //定义一个拓扑 - TopologyBuilder builder=new TopologyBuilder(); - builder.setSpout(str1, new TestSpout()); - builder.setBolt(str2, new TestBolt()).shuffleGrouping(str1); - Config conf = new Config(); - conf.put("test", "test"); - try{ - //运行拓扑 - if(args !=null&&args.length>0){ //有参数时,表示向集群提交作业,并把第一个参数当做topology名称 - System.out.println("远程模式"); - StormSubmitter.submitTopology(args[0], conf, builder.createTopology()); - } else{//没有参数时,本地提交 - //启动本地模式 - System.out.println("本地模式"); - LocalCluster cluster = new LocalCluster(); - cluster.submitTopology("111" ,conf, builder.createTopology() ); -// Thread.sleep(2000); -// //关闭本地集群 -// cluster.shutdown(); - } - }catch (Exception e){ - e.printStackTrace(); - } - - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/test/TestBolt.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/test/TestBolt.java deleted file mode 100644 index 1ed6b78f18..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/test/TestBolt.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.jun.plugin.bigdata.storm.test; - -import java.util.Map; - -import org.apache.storm.task.OutputCollector; -import org.apache.storm.task.TopologyContext; -import org.apache.storm.topology.OutputFieldsDeclarer; -import org.apache.storm.topology.base.BaseRichBolt; -import org.apache.storm.tuple.Tuple; - -/** - * -* Title: TestBolt -* Description: -* 用于处理消息 -* Version:1.0.0 -* @author pancm -* @date 2018年3月6日 - */ -public class TestBolt extends BaseRichBolt{ - - /** - * - */ - private static final long serialVersionUID = 4743224635827696343L; - - private OutputCollector collector; - private long count=1; - /** - * 在Bolt启动前执行,提供Bolt启动环境配置的入口 - * 一般对于不可序列化的对象进行实例化。 - * 注:如果是可以序列化的对象,那么最好是使用构造函数。 - */ - @Override - public void prepare(Map map, TopologyContext arg1, OutputCollector collector) { - System.out.println("prepare:"+map.get("test")); - this.collector=collector; - } - - /** - * execute()方法是Bolt实现的核心。 - * 也就是执行方法,每次Bolt从流接收一个订阅的tuple,都会调用这个方法。 - */ - @Override - public void execute(Tuple tuple) { - /** - * 接受消息可以使用这两种方式进行接收。 - * 个人推荐第二种。 - */ -// String msg=tuple.getString(0); - String msg=tuple.getStringByField("test"); - //这里我们就不做消息的处理,只打印 - System.out.println("Bolt第"+count+"接受的消息:"+msg); - count++; - /** - * - * 没次调用处理一个输入的tuple,所有的tuple都必须在一定时间内应答。 - * 可以是ack或者fail。否则,spout就会重发tuple。 - * 如果继承的是IRichBolt,则需要手动ack。 - * 这里就不用了,BaseRichBolt会自动帮我们应答。 - */ -// collector.ack(tuple); - } - - /** - * 声明数据格式 - */ - @Override - public void declareOutputFields(OutputFieldsDeclarer arg0) { - - } - - /** - * cleanup是IBolt接口中定义,用于释放bolt占用的资源。 - * Storm在终止一个bolt之前会调用这个方法。 - */ - @Override - public void cleanup() { - System.out.println("资源释放"); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/test/TestSpout.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/test/TestSpout.java deleted file mode 100644 index 94f35419d4..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/test/TestSpout.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.jun.plugin.bigdata.storm.test; - -import java.util.Map; - -import org.apache.storm.spout.SpoutOutputCollector; -import org.apache.storm.task.TopologyContext; -import org.apache.storm.topology.OutputFieldsDeclarer; -import org.apache.storm.topology.base.BaseRichSpout; -import org.apache.storm.tuple.Fields; -import org.apache.storm.tuple.Values; - -/** - * -* Title: TestSpout -* Description: -* Spout 发射器 -* 用于向Bolt发送消息 -* Version:1.0.0 -* @author pancm -* @date 2018年3月6日 - */ -public class TestSpout extends BaseRichSpout{ - - private static final long serialVersionUID = 225243592780939490L; - - private SpoutOutputCollector collector; - private String message="这是个测试消息!"; - private static final String field="test"; - private long count=1; - - - /** - * open()方法中是在ISpout接口中定义,在Spout组件初始化时被调用。 - * 有三个参数: - * 1.Storm配置的Map; - * 2.topology中组件的信息; - * 3.发射tuple的方法; - */ - @Override - public void open(Map map, TopologyContext arg1, SpoutOutputCollector collector) { - System.out.println("open:"+map.get("test")); - this.collector = collector; - } - - /** - * nextTuple()方法是Spout实现的核心。 - * 也就是主要执行方法,用于输出信息,通过collector.emit方法发射。 - */ - @Override - public void nextTuple() { - if(count<=2){ - System.out.println("第"+count+"次开始发送数据..."); - this.collector.emit(new Values(message)); - } - count++; - } - - - /** - * declareOutputFields是在IComponent接口中定义,用于声明数据格式。 - * 即输出的一个Tuple中,包含几个字段。 - */ - @Override - public void declareOutputFields(OutputFieldsDeclarer declarer) { - System.out.println("定义格式..."); - declarer.declare(new Fields(field)); - } - - /** - * 当一个Tuple处理成功时,会调用这个方法 - */ - @Override - public void ack(Object obj) { - System.out.println("ack:"+obj); - } - - /** - * 当Topology停止时,会调用这个方法 - */ - @Override - public void close() { - System.out.println("关闭..."); - } - - /** - * 当一个Tuple处理失败时,会调用这个方法 - */ - @Override - public void fail(Object obj) { - System.out.println("失败:"+obj); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/test/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/test/package-info.java deleted file mode 100644 index 1fc1724537..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/test/package-info.java +++ /dev/null @@ -1,11 +0,0 @@ -/** - * - */ -/** - * Title: package-info - * Description: - * Version:1.0.0 - * @author pancm - * @date 2018年3月15日 - */ -package com.jun.plugin.bigdata.storm.test; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/test2/App.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/test2/App.java deleted file mode 100644 index ad4d034b8d..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/test2/App.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.jun.plugin.bigdata.storm.test2; - -import org.apache.storm.Config; -import org.apache.storm.LocalCluster; -import org.apache.storm.StormSubmitter; -import org.apache.storm.topology.TopologyBuilder; -import org.apache.storm.tuple.Fields; - -/** - * -* Title: App -* Description: -* storm测试 -* Version:1.0.0 -* @author pancm -* @date 2018年3月6日 - */ -public class App { - - private static final String test_spout="test_spout"; - private static final String test_bolt="test_bolt"; - private static final String test2_bolt="test2_bolt"; - - public static void main(String[] args) { - //定义一个拓扑 - TopologyBuilder builder=new TopologyBuilder(); - //设置两个Executeor(线程),默认一个 - builder.setSpout(test_spout, new TestSpout(),2); - //shuffleGrouping:表示是随机分组 - //设置两个Executeor(线程),和两个task - builder.setBolt(test_bolt, new TestBolt(),2).setNumTasks(2).shuffleGrouping(test_spout); - //fieldsGrouping:表示是按字段分组 - //设置两个Executeor(线程),和两个task - builder.setBolt(test2_bolt, new Test2Bolt(),2).setNumTasks(2).fieldsGrouping(test_bolt, new Fields("count")); - Config conf = new Config(); - conf.put("test", "test"); - try{ - //运行拓扑 - if(args !=null&&args.length>0){ //有参数时,表示向集群提交作业,并把第一个参数当做topology名称 - System.out.println("运行远程模式"); - StormSubmitter.submitTopology(args[0], conf, builder.createTopology()); - } else{//没有参数时,本地提交 - //启动本地模式 - System.out.println("运行本地模式"); - LocalCluster cluster = new LocalCluster(); - cluster.submitTopology("Word-counts" ,conf, builder.createTopology() ); - Thread.sleep(20000); -// //关闭本地集群 - cluster.shutdown(); - } - }catch (Exception e){ - e.printStackTrace(); - } - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/test2/Test2Bolt.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/test2/Test2Bolt.java deleted file mode 100644 index 99acd9759c..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/test2/Test2Bolt.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.jun.plugin.bigdata.storm.test2; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.storm.task.OutputCollector; -import org.apache.storm.task.TopologyContext; -import org.apache.storm.topology.OutputFieldsDeclarer; -import org.apache.storm.topology.base.BaseRichBolt; -import org.apache.storm.tuple.Tuple; - -/** - * -* Title: Test2Bolt -* Description: -* 统计单词出现的次数 -* Version:1.0.0 -* @author pancm -* @date 2018年3月16日 - */ -public class Test2Bolt extends BaseRichBolt{ - - /** - * - */ - private static final long serialVersionUID = 4743224635827696343L; - - - /** - * 保存单词和对应的计数 - */ - private HashMap counts = null; - - private long count=1; - /** - * 在Bolt启动前执行,提供Bolt启动环境配置的入口 - * 一般对于不可序列化的对象进行实例化。 - * 注:如果是可以序列化的对象,那么最好是使用构造函数。 - */ - @Override - public void prepare(Map map, TopologyContext arg1, OutputCollector collector) { - System.out.println("prepare:"+map.get("test")); - this.counts=new HashMap(); - } - - /** - * execute()方法是Bolt实现的核心。 - * 也就是执行方法,每次Bolt从流接收一个订阅的tuple,都会调用这个方法。 - * - */ - @Override - public void execute(Tuple tuple) { - String msg=tuple.getStringByField("count"); - System.out.println("第"+count+"次统计单词出现的次数"); - /** - * 如果不包含该单词,说明在该map是第一次出现 - * 否则进行加1 - */ - if (!counts.containsKey(msg)) { - counts.put(msg, 1); - } else { - counts.put(msg, counts.get(msg)+1); - } - count++; - } - - - /** - * cleanup是IBolt接口中定义,用于释放bolt占用的资源。 - * Storm在终止一个bolt之前会调用这个方法。 - */ - @Override - public void cleanup() { - System.out.println("===========开始显示单词数量============"); - for (Map.Entry entry : counts.entrySet()) { - System.out.println(entry.getKey() + ": " + entry.getValue()); - } - System.out.println("===========结束============"); - System.out.println("Test2Bolt的资源释放"); - } - - /** - * 声明数据格式 - */ - @Override - public void declareOutputFields(OutputFieldsDeclarer arg0) { - - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/test2/TestBolt.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/test2/TestBolt.java deleted file mode 100644 index fe86a500dc..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/test2/TestBolt.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.jun.plugin.bigdata.storm.test2; - -import java.util.Map; - -import org.apache.storm.task.OutputCollector; -import org.apache.storm.task.TopologyContext; -import org.apache.storm.topology.OutputFieldsDeclarer; -import org.apache.storm.topology.base.BaseRichBolt; -import org.apache.storm.tuple.Fields; -import org.apache.storm.tuple.Tuple; -import org.apache.storm.tuple.Values; - - -/** - * -* Title: TestBolt -* Description: -* 对单词进行分割 -* Version:1.0.0 -* @author pancm -* @date 2018年3月16日 - */ -public class TestBolt extends BaseRichBolt{ - - /** - * - */ - private static final long serialVersionUID = 4743224635827696343L; - - private OutputCollector collector; - - /** - * 在Bolt启动前执行,提供Bolt启动环境配置的入口 - * 一般对于不可序列化的对象进行实例化。 - * 注:如果是可以序列化的对象,那么最好是使用构造函数。 - */ - @Override - public void prepare(Map map, TopologyContext arg1, OutputCollector collector) { - System.out.println("prepare:"+map.get("test")); - this.collector=collector; - } - - /** - * execute()方法是Bolt实现的核心。 - * 也就是执行方法,每次Bolt从流接收一个订阅的tuple,都会调用这个方法。 - */ - @Override - public void execute(Tuple tuple) { - String msg=tuple.getStringByField("word"); - System.out.println("开始分割单词:"+msg); - String[] words = msg.toLowerCase().split(" "); - for (String word : words) { - this.collector.emit(new Values(word));//向下一个bolt发射数据 - } - - } - - /** - * 声明数据格式 - */ - @Override - public void declareOutputFields(OutputFieldsDeclarer declarer) { - declarer.declare(new Fields("count")); - } - - /** - * cleanup是IBolt接口中定义,用于释放bolt占用的资源。 - * Storm在终止一个bolt之前会调用这个方法。 - */ - @Override - public void cleanup() { - System.out.println("TestBolt的资源释放"); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/test2/TestSpout.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/test2/TestSpout.java deleted file mode 100644 index a5fe90dd82..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/test2/TestSpout.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.jun.plugin.bigdata.storm.test2; - -import java.util.Map; - -import org.apache.storm.spout.SpoutOutputCollector; -import org.apache.storm.task.TopologyContext; -import org.apache.storm.topology.OutputFieldsDeclarer; -import org.apache.storm.topology.base.BaseRichSpout; -import org.apache.storm.tuple.Fields; -import org.apache.storm.tuple.Values; - -/** - * -* Title: TestSpout -* Description: -* 发送信息 -* Version:1.0.0 -* @author pancm -* @date 2018年3月6日 - */ -public class TestSpout extends BaseRichSpout{ - - private static final long serialVersionUID = 225243592780939490L; - - private SpoutOutputCollector collector; - private static final String field="word"; - private int count=1; - private String[] message = { - "My nickname is xuwujing", - "My blog address is http://www.panchengming.com/", - "My interest is playing games" - }; - - /** - * open()方法中是在ISpout接口中定义,在Spout组件初始化时被调用。 - * 有三个参数: - * 1.Storm配置的Map; - * 2.topology中组件的信息; - * 3.发射tuple的方法; - */ - @Override - public void open(Map map, TopologyContext arg1, SpoutOutputCollector collector) { - System.out.println("open:"+map.get("test")); - this.collector = collector; - } - - /** - * nextTuple()方法是Spout实现的核心。 - * 也就是主要执行方法,用于输出信息,通过collector.emit方法发射。 - */ - @Override - public void nextTuple() { - - if(count<=message.length){ - System.out.println("第"+count +"次开始发送数据..."); - this.collector.emit(new Values(message[count-1])); - } - count++; - } - - - /** - * declareOutputFields是在IComponent接口中定义,用于声明数据格式。 - * 即输出的一个Tuple中,包含几个字段。 - */ - @Override - public void declareOutputFields(OutputFieldsDeclarer declarer) { - System.out.println("定义格式..."); - declarer.declare(new Fields(field)); - } - - /** - * 当一个Tuple处理成功时,会调用这个方法 - */ - @Override - public void ack(Object obj) { - System.out.println("ack:"+obj); - } - - /** - * 当Topology停止时,会调用这个方法 - */ - @Override - public void close() { - System.out.println("关闭..."); - } - - /** - * 当一个Tuple处理失败时,会调用这个方法 - */ - @Override - public void fail(Object obj) { - System.out.println("失败:"+obj); - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/test2/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/test2/package-info.java deleted file mode 100644 index 04c2d75138..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/storm/test2/package-info.java +++ /dev/null @@ -1,11 +0,0 @@ -/** - * - */ -/** - * Title: package-info - * Description: - * Version:1.0.0 - * @author pancm - * @date 2018年3月15日 - */ -package com.jun.plugin.bigdata.storm.test2; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/zookeeper/ZookeeperTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/zookeeper/ZookeeperTest.java deleted file mode 100644 index 095d853229..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/zookeeper/ZookeeperTest.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.jun.plugin.bigdata.zookeeper; - -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.WatchedEvent; -import org.apache.zookeeper.Watcher; -import org.apache.zookeeper.ZooDefs.Ids; -import org.apache.zookeeper.ZooKeeper; - -/** - * -* @Title: ZookeeperTest -* @Description: -* zookeeper测试 -* @Version:1.0.0 -* @author pancm -* @date 2018年4月28日 - */ -public class ZookeeperTest { - private static String url="master:2181"; - private static ZooKeeper zk; - private static int CONNECTION_TIMEOUT=30000; - - public static void main(String[] args) throws Exception { - // 创建一个与服务器的连接 - zk = new ZooKeeper(url , - CONNECTION_TIMEOUT, new Watcher() { - // 监控所有被触发的事件 - public void process(WatchedEvent event) { - System.out.println(event.getPath()+"已经触发了" + event.getType() + "事件!"); - } - }); - - /* - * 创建一个给定的目录节点 path, 并给它设置数据, - * CreateMode 标识有四种形式的目录节点,分别是 - * PERSISTENT:持久化目录节点,这个目录节点存储的数据不会丢失; - * PERSISTENT_SEQUENTIAL:顺序自动编号的目录节点,这种目录节点会根据当前已近存在的节点数自动加 1, - * 然后返回给客户端已经成功创建的目录节点名; - * EPHEMERAL:临时目录节点,一旦创建这个节点的客户端与服务器端口也就是 session 超时,这种节点会被自动删除; - * EPHEMERAL_SEQUENTIAL:临时自动编号节点 - */ - - // 创建一个父级目录节点 - if(zk.exists("/test", true)==null){ - //参数说明:目录,参数,参数权限,节点类型 - zk.create("/test", "data1".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); - } - if(zk.exists("/test/test1", true)==null){ - // 创建一个子目录节点 - zk.create("/test/test1", "data2".getBytes(), Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT); - } - - System.out.println("="+new String(zk.getData("/test",false,null))); - // 取出子目录节点列表 - System.out.println("=="+zk.getChildren("/test",true)); - - if(zk.exists("/test/test1", true)!=null){ - // 修改子目录节点数据 - zk.setData("/test/test1","testOne".getBytes(),-1); - } - System.out.println("目录节点状态:["+zk.exists("/test",true)+"]"); - if(zk.exists("/test/test1", true)!=null){ - // 创建另外一个子目录节点 - zk.create("/test/test2", "test2".getBytes(), Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT); - } - System.out.println("==="+new String(zk.getData("/test/test2",true,null))); - - /* - * 删除 path 对应的目录节点,version 为 -1 可以匹配任何版本,也就删除了这个目录节点所有数据 - */ - // 删除子目录节点 - zk.delete("/test/test2",-1); - zk.delete("/test/test1",-1); - - // 删除父目录节点 - zk.delete("/test",-1); - // 关闭连接 - zk.close(); - } - - - - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/zookeeper/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/zookeeper/package-info.java deleted file mode 100644 index 5dc5b95932..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/bigdata/zookeeper/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: zookeeper相关代码 -* @Version:1.0.0 -* @author pancm -* @date 2018年4月28日 -*/ -package com.jun.plugin.bigdata.zookeeper; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/code/MapCodeTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/code/MapCodeTest.java deleted file mode 100644 index e98bac5157..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/code/MapCodeTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.jun.plugin.code; - -import java.util.HashMap; -import java.util.Map; - -/** -* @Title: MapCodeTest -* @Description: Map源码学习相关类 -* @Version:1.0.0 -* @author pancm -* @date 2018年11月29日 -*/ -public class MapCodeTest { - - /** - * @param args - */ - public static void main(String[] args) { - test1(); - } - - - /** - * - */ - private static void test1() { - Map map =new HashMap<>(); - map.put("1", 1); - map.put("2", 2); - } -} - - diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/code/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/code/package-info.java deleted file mode 100644 index afee21651b..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/code/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: 源码相关类 -* @Version:1.0.0 -* @author pancm -* @date 2018年11月29日 -*/ -package com.jun.plugin.code; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/commons/apache/CommonsTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/commons/apache/CommonsTest.java deleted file mode 100644 index daca88a9d7..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/commons/apache/CommonsTest.java +++ /dev/null @@ -1,132 +0,0 @@ -package com.jun.plugin.commons.apache; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.apache.commons.collections.Bag; -import org.apache.commons.collections.BidiMap; -import org.apache.commons.collections.Factory; -import org.apache.commons.collections.HashBag; -import org.apache.commons.collections.bidimap.TreeBidiMap; -import org.apache.commons.collections.list.LazyList; -import org.apache.commons.lang.RandomStringUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.WordUtils; - -/** - * -* Title: langTest -* Description: Apache commons工具包测试 -* Version:1.0.0 -* @author pancm -* @date 2017年10月30日 - */ -public class CommonsTest { - - public static void main(String[] args) { - stringTest(); - otherTest(); - } - - /** - * StringUtils 相关测试 - */ - private static void stringTest(){ - /* - * 空指针判断 - */ - String str=""; - String str2=null; - String str3=" "; - System.out.println(":"+StringUtils.isEmpty(str)); //:true - System.out.println("null:"+StringUtils.isEmpty(str2)); //null:true - System.out.println(" :"+StringUtils.isEmpty(str3)); // :false - - /* - * 判断是否为数字 - */ - String str4="123"; - String str5="12 3"; - String str6="123QD#"; - System.out.println("str4:"+StringUtils.isNumeric(str4));//str4:true - System.out.println("str5:"+StringUtils.isNumeric(str5));//str5:false - System.out.println("str6:"+StringUtils.isNumeric(str6));//str6:false - - /* - * 统计子字符串出现的次数 - */ - String str7="abcdefgfedccfg"; - String str8="ac"; - String str9="c"; - System.out.println("count:"+StringUtils.countMatches(str7, str8));//count:0 - System.out.println("count:"+StringUtils.countMatches(str7, str9));//count:3 - - } - - /** - * 其他的测试 - */ - private static void otherTest(){ - System.out.println("十位数字随机数:"+RandomStringUtils.randomNumeric(10)); //0534110685 - System.out.println("十位字母随机数:"+RandomStringUtils.randomAlphabetic(10)); //jLWiHdQhHg - System.out.println("十位ASCII随机数:"+RandomStringUtils.randomAscii(10)); //8&[bxy%h_- - String str="hello world,why are you so happy"; - System.out.println("首字符大写:"+WordUtils.capitalize(str)); //:Hello World,why Are You So Happy - } - - /** - * Bag 测试 - * 主要测试重复元素的统计 - */ - @SuppressWarnings("deprecation") - private static void bagTest(){ - //定义4种球 - Bag box=new HashBag(Arrays.asList("red","blue","black","green")); - System.out.println("box.getCount():"+box.getCount("red"));//box.getCount():1 - box.add("red", 5);//红色的球增加五个 - System.out.println("box.size():"+box.size()); //box.size():9 - System.out.println("box.getCount():"+box.getCount("red"));//box.getCount():6 - } - - /** - * Lazy测试 - * 需要该元素的时候,才会生成 - */ - @SuppressWarnings("unchecked") - private static void lazyTest(){ - List lazy=LazyList.decorate(new ArrayList<>(), new Factory() { - @Override - public Object create() { - return "Hello"; - } - }); - //访问了第三个元素,此时0和1位null - //get几就增加了几加一 , 输出依旧是 Hello - String str=lazy.get(2); - System.out.println("str:"+str);//str:Hello - //加入的第四个元素 - lazy.add("world"); - //元素总个为4个 - System.out.println("lazy.size():"+lazy.size());//lazy.size():4 - } - - /** - * 双向Map - * 唯一的key和map,可以通过键或值来操作 - * 比如删除、查询等 - */ - private static void bidimapTest(){ - BidiMap map=new TreeBidiMap(); - map.put(1, "a"); - map.put(2, "b"); - map.put(3, "c"); - System.out.println("map:"+map); //map:{1=a, 2=b, 3=c} - System.out.println("map.get():"+map.get(2)); //map.get():b - System.out.println("map.getKey():"+map.getKey("a")); //map.getKey():1 - System.out.println("map.removeValue():"+map.removeValue("c")); //map.removeValue():3 - System.out.println("map:"+map); //map:{1=a, 2=b} - } - - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/commons/apache/CompressTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/commons/apache/CompressTest.java deleted file mode 100644 index 4bcbd3557f..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/commons/apache/CompressTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * - */ -package com.jun.plugin.commons.apache; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; - -import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; -import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; - -/** -* @Title: compressTest -* @Description: -* 压缩测试 -* @Version:1.0.0 -* @author pancm -* @date 2018年5月14日 -*/ -public class CompressTest { - - /** - * @param args - */ - public static void main(String[] args) { - test(); - } - - /** - * 压缩文件测试 - */ - private static void test() { - - // 创建压缩对象 - ZipArchiveEntry entry = new ZipArchiveEntry("CompressTest"); - // 要压缩的文件 - File f = new File("d:\\user.txt"); - FileInputStream fis; - try { - fis = new FileInputStream(f); - // 输出的对象 压缩的文件 - ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(new File("d:\\user.zip")); - zipOutput.putArchiveEntry(entry); - int i = 0, j; - while ((j = fis.read()) != -1) { - zipOutput.write(j); - i++; - } - System.out.println("压缩成功!遍历了:" + i + "次"); - zipOutput.closeArchiveEntry(); - zipOutput.close(); - fis.close(); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/commons/apache/LangTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/commons/apache/LangTest.java deleted file mode 100644 index 21dd1e959b..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/commons/apache/LangTest.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * - */ -package com.jun.plugin.commons.apache; - -import org.apache.commons.lang.StringEscapeUtils; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.ClassUtils; -import org.apache.commons.lang3.RandomStringUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.math.NumberUtils; - -/** - * @Title: LangTest - * @Description: - * @Version:1.0.0 - * @author pancm - * @date 2018年5月14日 - */ -public class LangTest { - - /** - * @param args - */ - public static void main(String[] args) { - test(); - } - - public static void test() { - // 1 合并两个数组: org.apache.commons.lang. ArrayUtils - String[] s1 = new String[] { "1", "2", "3" }; - String[] s2 = new String[] { "a", "b", "c" }; - String[] s = (String[]) ArrayUtils.addAll(s1, s2); - for (int i = 0; i < s.length; i++) { - System.out.println(s[i]); - } - String str = ArrayUtils.toString(s); - str = str.substring(1, str.length() - 1); - System.out.println(str + ">>" + str.length()); - - System.out.println("测试截取:" + StringUtils.substringAfter("SELECT * FROM PERSON ", "FROM")); - // 3 判断该字符串是不是为数字(0~9)组成,如果是,返回true 但该方法不识别有小数点和 请注意。 - System.out.println("数字判断:" + StringUtils.isNumeric("454534")); - System.out.println("取得类名:" + ClassUtils.getShortClassName(LangTest.class)); - System.out.println("获取包名:" + ClassUtils.getPackageName(LangTest.class)); - - System.out.println("是否是数字:" + NumberUtils.isCreatable("123")); - System.out.println("随机数字和字母:" + RandomStringUtils.randomAlphanumeric(5)); - System.out.println("<>进行转义" + StringEscapeUtils.escapeHtml("")); - - System.out.println("是否是null字符 :" + StringUtils.isBlank(null)); - System.out.println("是否是空字符 :" + StringUtils.isBlank("")); - System.out.println("是否是空格字符 :" + StringUtils.isBlank(" ")); - System.out.println("分割数组:" + StringUtils.join(s1, ",")); - System.out.println("添加某个字符,使其长度等于所设置的:" + StringUtils.rightPad("abc", 6, 'T')); - System.out.println("首字母大写:" + StringUtils.capitalize("abc")); - System.out.println("去掉空格:" + StringUtils.deleteWhitespace(" ab c ")); - System.out.println("是否包含该字符:" + StringUtils.contains("abc", "ba")); - System.out.println("表示左边的字符:" + StringUtils.left("abc", 2)); - } - - - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/commons/apache/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/commons/apache/package-info.java deleted file mode 100644 index 1720c95562..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/commons/apache/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: apache相关的工具类 -* @Version:1.0.0 -* @author pancm -* @date 2018年9月20日 -*/ -package com.jun.plugin.commons.apache; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/commons/google/GoogleTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/commons/google/GoogleTest.java deleted file mode 100644 index 5240412d5b..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/commons/google/GoogleTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * - */ -package com.jun.plugin.commons.google; - -import java.util.ArrayList; -import java.util.List; - -import com.google.common.base.Function; -import com.google.common.collect.Lists; -import com.jun.plugin.pojo.User; - -/** -* @Title: googleTest -* @Description: -* @Version:1.0.0 -* @author pancm -* @date 2018年5月14日 -*/ -public class GoogleTest { - - /** - * @param args - */ - public static void main(String[] args) { - test(); - } - - /** - * 数组里所有对象的某个属性的值改变 - */ - private static void test(){ - List userList=new ArrayList<>(); - User user=new User(); - user.setId(1); - user.setName("张三"); - userList.add(user); - User user2=new User(); - user2.setId(2); - user2.setName("李四"); - userList.add(user2); - System.out.println("更改之前的数据:"+userList); - userList=Lists.transform(userList,new Function() { - @Override - public User apply(User user) { - user.setName("王五"); - return user; - } - }); - System.out.println("更改之后的数据:"+userList); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/commons/google/GuavaTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/commons/google/GuavaTest.java deleted file mode 100644 index a165572572..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/commons/google/GuavaTest.java +++ /dev/null @@ -1,154 +0,0 @@ -package com.jun.plugin.commons.google; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.google.common.base.Joiner; -import com.google.common.base.Predicate; -import com.google.common.base.Splitter; -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.HashBasedTable; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Maps; -import com.google.common.collect.Multimap; -import com.google.common.collect.Table; -import com.google.common.primitives.Ints; - -/** - * -* Title: guavaTest -* Description:谷歌 guava 工具包测试 -* Version:1.0.0 -* @author pancm -* @date 2017年10月30日 - */ -public class GuavaTest { - - public static void main(String[] args) { - noChangeList(); - one2MoreMap(); - more2One(); - filtedMap(); - joiner(); - splitter(); - integer(); - } - - /** - * 不可变集合测试 - */ - private static void noChangeList(){ - ImmutableList list=ImmutableList.of("A","B","C"); - ImmutableMap map=ImmutableMap.of(1,"壹",2,"贰",3,"叁"); - System.out.println("ImmutableList:"+list); //ImmutableList:[A, B, C] - System.out.println("ImmutableMap:"+map); //ImmutableMap:{1=壹, 2=贰, 3=叁} - - //下面运行直接报错,因为这是不可变集合 -// list.add("D"); -// map.put(4, "肆"); - } - - /** - * map中多个键的测试 - * 例如:一个人多个电话 - */ - private static void one2MoreMap(){ - Multimap map= ArrayListMultimap.create(); - map.put("路人甲", "123"); - map.put("路人甲", "234"); - map.put("路人乙", "567"); - map.put("路人乙", "890"); - System.out.println("Multimap:"+map); //Multimap:{路人乙=[567, 890], 路人甲=[123, 234]} - System.out.println("get:"+map.get("路人乙")); //get:[567, 890] - } - - /** - * 多个键值对一个值 - * 例如:坐标 - */ - private static void more2One(){ - Table table=HashBasedTable.create(); - table.put(22.54, 114.01, "深圳"); - table.put(39.96, 116.40, "北京"); - System.out.println("Table:"+table); //Table:{22.54={114.01=深圳}, 39.96={116.4=北京}} - System.out.println("Table.get:"+table.get(22.54, 114.01));//Table.get:深圳 - } - - /** - * Map的过滤 - * 例如:查找该集合中大于20岁的人 - */ - private static void filtedMap(){ - Map map=new HashMap(); - map.put("张三", 19); - map.put("李四", 20); - map.put("王五", 21); - Map filtedmap =Maps.filterValues(map, - new Predicate(){ - @Override - public boolean apply(Integer age) { - return age>20; - } - }); - System.out.println("Map:"+map); //Map:{张三=19, 李四=20, 王五=21} - System.out.println("filtedmap:"+filtedmap);//filtedmap:{王五=21} - } - - /** - * Joiner连接测试 - * 不局限于连接String,如果是null,会直接跳过 - * - */ - private static void joiner(){ - //设置连接符 - //如:设置为 "和",拼接 “你”,“我” 就变成了“你和我” - Joiner joiner=Joiner.on(","); - String str=joiner.skipNulls().join("你好","java"); - Map map=new HashMap(); - map.put("张三", "你好"); - map.put("李四", "嗨"); - //设置键值的连接符以及键与值之间的连接符 - String str1=Joiner.on(",").withKeyValueSeparator(":").join(map); - System.out.println("Joiner: "+str); //Joiner: 你好,java - System.out.println("Joiner: "+str1); //Joiner: 张三:你好,李四:嗨 - } - - /** - * Splitter拆分测试 - */ - private static void splitter(){ - String str="你好,java"; - //按字符分割 - for(String s:Splitter.on(",").split(str)){ - System.out.println("s:"+s); - } - //按固定长度分割 - for(String d:Splitter.fixedLength(2).split(str)){ - System.out.println("d:"+d); - } - } - - /** - * 基本类型测试 - */ - private static void integer(){ - int []ints={1,4,3,2}; - //找到里面的最大值 - System.out.println("max:"+Ints.max(ints)); //max:4 - - List list=new ArrayList(); - list.add(1); - list.add(3); - list.add(6); - //包装类型集合转变为基本类型集合 - int []arr=Ints.toArray(list); - for(int i=0,j=arr.length;i commands = new ArrayList(); - - - //添加这个命令 - public void setCommand(Command command) { - //设置执行命令的 - if(command.toString().indexOf("WangTeacher")>-1) { - System.out.println("不执行 WangTeacher 的命令!"); - }else { - commands.add(command); - } - } - - //执行这个命令 - public void executeCommand(String name) { - commands.forEach(command->{ - command.execute(name); - }); - } - - //撤销这个命令 - public void undoCommand(Command command) { - commands.remove(command); - System.out.println("撤销该命令!"); - } - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/command/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/command/package-info.java deleted file mode 100644 index 2ed8c17b05..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/command/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: 命令模式 -* @Version:1.0.0 -* @author pancm -* @date 2018年8月8日 -*/ -package com.jun.plugin.design.command; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/composite/CompositeTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/composite/CompositeTest.java deleted file mode 100644 index 1a5c400117..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/composite/CompositeTest.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.jun.plugin.design.composite; - -import java.util.ArrayList; -import java.util.List; - -/** -* @Title: CompositeTest -* @Description: 组合模式 -* 将对象组合成树形结构以表示"部分-整体"的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。 -* @Version:1.0.0 -* @author pancm -* @date 2018年8月8日 -*/ -public class CompositeTest { - - public static void main(String[] args) { - /* - * 建立一个学生类,包含学生姓名和职位 - * - */ - Student studentLeader=new Student("小明","学生会主席"); - - Student committeeMember=new Student("小刚","学生会委员"); - - Student student=new Student("小红","学生"); - - committeeMember.add(student); - studentLeader.add(committeeMember); - - System.out.println("-"+studentLeader); - studentLeader.get().forEach(sl->{ - System.out.println("--"+sl); - sl.get().forEach(cm->{ - System.out.println("---"+cm); - }); - }); - - /* - * -Student [name=小明, position=学生会主席] - --Student [name=小刚, position=学生会委员] - ---Student [name=小红, position=学生] - */ - } - -} - -class Student{ - private String name; - - private String position; - - private List students; - - public Student(String name, String position) { - this.name = name; - this.position = position; - students=new ArrayList(); - } - - - public void add(Student student){ - students.add(student); - } - - public void remove(Student student){ - students.remove(student); - } - - public List get(){ - return students; - } - - - /** - * - */ - @Override - public String toString() { - return "Student [name=" + name + ", position=" + position + "]"; - } - - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/composite/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/composite/package-info.java deleted file mode 100644 index 5611f3203f..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/composite/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: 组合模式 -* @Version:1.0.0 -* @author pancm -* @date 2018年8月8日 -*/ -package com.jun.plugin.design.composite; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/decorator/DecoratorTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/decorator/DecoratorTest.java deleted file mode 100644 index fe537e59a9..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/decorator/DecoratorTest.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.jun.plugin.design.decorator; - -/** -* @Title: DecoratorTest -* @Description: 装饰器模式 -* 动态地给一个对象添加一些额外的职责。就增加功能来说,装饰器模式相比生成子类更为灵活。 -* 比如一个人,可以穿不同的装饰,外套、T恤、短裤、西服等等 -* 人是不变的 -Component抽象构件角色:真实对象和装饰对象有相同的接口。这样,客户端对象就能够以与真实对象相同的方式同装饰对象交互。 -ConcreteComponent具体构件角色(真实对象):io流中的FileInputStream、    FileOutputStream -Decorator装饰角色:持有一个抽象构件的引用。装饰对象接受所有客户端的请求,并把这些请求转发给真实的对象。这样,就能在真实对象调用前后增加新的功能。 -ConcreteDecorator具体装饰角色:负责给构件对象增加新的责任。 -* @Version:1.0.0 -* @author pancm -* @date 2018年8月8日 -*/ -public class DecoratorTest { - public static void main(String[] args) { - //组装模型 - Model gundam=new GUNDAM(); - Model mrgu=new MrGu(); - gundam.assemble(); - mrgu.assemble(); - - //组装模型并添加武器 - Model gModel=new LightSaber(new GUNDAM()); - gModel.assemble(); - Model mModel=new RocketLauncher(new MrGu()); - mModel.assemble(); - - /* - * - 组装一个高达模型 - 组装一个扎古模型 - 组装一个高达模型 - 添加光剑 - 组装一个扎古模型 - 添加火箭筒 - */ - } -} - - -interface Model{ - void assemble(); -} - -class GUNDAM implements Model{ - @Override - public void assemble() { - System.out.println("组装一个高达模型"); - } -} - -class MrGu implements Model{ - @Override - public void assemble() { - System.out.println("组装一个扎古模型"); - } -} - -//添加额外的功能 -//装饰器 -abstract class AddExtra implements Model{ - protected Model model; - - public AddExtra(Model model){ - this.model=model; - } - public void assemble(){ - model.assemble(); - } -} - -//添加光剑 -class LightSaber extends AddExtra{ - - public LightSaber(Model model) { - super(model); - } - - public void assemble(){ - model.assemble(); - addLightSaber(); - } - public void addLightSaber(){ - System.out.println("添加光剑"); - } -} - - -//添加火箭筒 -class RocketLauncher extends AddExtra{ - - public RocketLauncher(Model model) { - super(model); - } - - public void assemble(){ - model.assemble(); - addRocketLauncher(); - } - public void addRocketLauncher(){ - System.out.println("添加火箭筒"); - } -} - - - - - diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/decorator/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/decorator/package-info.java deleted file mode 100644 index c7faf61c3b..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/decorator/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: 装饰器模式 -* @Version:1.0.0 -* @author pancm -* @date 2018年8月8日 -*/ -package com.jun.plugin.design.decorator; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/facade/FacadeTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/facade/FacadeTest.java deleted file mode 100644 index c8aacd0c77..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/facade/FacadeTest.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.jun.plugin.design.facade; - -/** -* @Title: FacadeTest -* @Description: -* 外观模式测试代码 -* -* 为子系统中的一组接口提供一个一致的界面,外观模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。 -* -* 比如windows开机:启动CPU、启动内存、启动硬盘 -* windows关机:关闭硬盘、关闭内存、关闭CPU -* -* @Version:1.0.0 -* @author pancm -* @date 2018年8月8日 -*/ -public class FacadeTest { - - public static void main(String[] args) { - - /* - * 对外提供 一个界面 - * 游戏装在电脑上,想玩游戏就在电脑启动游戏就可以了 - */ - Computer computer=new Computer(); - computer.playDNF(); - computer.playLOL(); - computer.playWOW(); - } -} - -interface Game{ - void play(); -} - -class DNF implements Game{ - - @Override - public void play() { - System.out.println("正在玩DNF..."); - } -} - -class LOL implements Game{ - @Override - public void play() { - System.out.println("正在玩LOL..."); - } -} - -class WOW implements Game{ - @Override - public void play() { - System.out.println("正在玩WOW..."); - } -} - -class Computer{ - - private Game dnf; - private Game lol; - private Game wow; - - public Computer() { - dnf=new DNF(); - lol=new LOL(); - wow=new WOW(); - } - - public void playDNF(){ - dnf.play(); - } - - public void playLOL(){ - lol.play(); - } - - public void playWOW(){ - wow.play(); - } - - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/facade/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/facade/package-info.java deleted file mode 100644 index 3da7a510ea..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/facade/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: 外观模式 -* @Version:1.0.0 -* @author pancm -* @date 2018年8月8日 -*/ -package com.jun.plugin.design.facade; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/factory/FactoryTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/factory/FactoryTest.java deleted file mode 100644 index 0631682705..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/factory/FactoryTest.java +++ /dev/null @@ -1,171 +0,0 @@ -package com.jun.plugin.design.factory; - -/** -* @Title: FactorymTest -* @Description: -* 简单工厂模式测试 -* @Version:1.0.0 -* @author pancm -* @date 2018年7月23日 -*/ -public class FactoryTest { - private static final String LOL="LOL"; - private static final String DNF="DNF"; - /** - * @param args - */ - public static void main(String[] args) { - /** - * 简单工厂模式 - * 根据条件决定一个接口由哪个具体产品类来实现 - * 优点: - * 缺点:扩展性差 - */ - Game game= ComputerFactory.playGame(LOL); - Game game2= ComputerFactory.playGame(DNF); - game.play(); - game2.play(); - - /** - * 工厂方法模式 - * - * 优点:扩展性高 - * 缺点:增加了复杂度 - */ - Game game3=new LOLFactory().playGame(); - Game game4=new DNFFactory().playGame(); - Game game5=new WOWFactory().playGame(); - game3.play(); - game4.play(); - game5.play(); - - - /** - * 抽象工厂模式 - * - * 优点: - * - */ - ComputerFactory3 cf3=new PVPFactory(); - cf3.playGame().play(); - cf3.playGame2().play(); - ComputerFactory3 cf4=new PVEFactory(); - cf4.playGame().play(); - cf4.playGame2().play(); - - - } - - - - -} - -/** - * 定义一个接口 - */ -interface Game{ - void play(); -} - -/** - * 定义一个实现类 - */ -class LOL implements Game{ - @Override - public void play() { - System.out.println("正在玩LOL..."); - } -} - -class DNF implements Game{ - @Override - public void play() { - System.out.println("正在玩DNF..."); - } -} - -class WOW implements Game{ - @Override - public void play() { - System.out.println("正在玩WOW..."); - } -} - -/** - * 定义一个电脑 - */ -class ComputerFactory{ - private static final String LOL="LOL"; - private static final String DNF="DNF"; - //玩游戏 - public static Game playGame(String game){ - if(LOL.equalsIgnoreCase(game)){ - return new LOL(); - }else if(DNF.equalsIgnoreCase(game)){ - return new DNF(); - } - return null; - } -} - -interface ComputerFactory2{ - Game playGame(); -} - -class LOLFactory implements ComputerFactory2{ - @Override - public Game playGame() { - return new LOL(); - } -} - -class DNFFactory implements ComputerFactory2{ - @Override - public Game playGame() { - return new DNF(); - } -} - -class WOWFactory implements ComputerFactory2{ - @Override - public Game playGame() { - return new WOW(); - } -} - -interface ComputerFactory3{ - Game playGame(); - - Game playGame2(); -} - -class PVPFactory implements ComputerFactory3{ - - @Override - public Game playGame() { - return new LOL(); - } - - @Override - public Game playGame2() { - return new WOW(); - } - -} - -class PVEFactory implements ComputerFactory3{ - - @Override - public Game playGame() { - return new DNF(); - } - - @Override - public Game playGame2() { - return new WOW(); - } - -} - - diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/factory/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/factory/package-info.java deleted file mode 100644 index 46f7191fd2..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/factory/package-info.java +++ /dev/null @@ -1,11 +0,0 @@ -/** - * - */ -/** - * Title: package-info - * Description: 工厂测试 - * Version:1.0.0 - * @author pancm - * @date 2017年10月13日 - */ -package com.jun.plugin.design.factory; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/filter/FilterTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/filter/FilterTest.java deleted file mode 100644 index 159ff6621a..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/filter/FilterTest.java +++ /dev/null @@ -1,181 +0,0 @@ -package com.jun.plugin.design.filter; - -import java.util.ArrayList; -import java.util.List; - -/** -* @Title: FilterTest -* @Description: 过滤器模式 -* 过滤器模式(Filter Pattern)或标准模式(Criteria Pattern)是一种设计模式, -* 这种模式允许开发人员使用不同的标准来过滤一组对象,通过逻辑运算以解耦的方式把它们连接起来。 -* 这种类型的设计模式属于结构型模式,它结合多个标准来获得单一标准。 -* @Version:1.0.0 -* @author pancm -* @date 2018年8月8日 -*/ -public class FilterTest { - - public static void main(String[] args) { - /* - * 1.创建学生,有姓名、性别、年级这三个属性 - * 2.根据这三个属性进行过滤分组 - * - */ - List list=new ArrayList(); - list.add(new Student("小明", "male", 1)); - list.add(new Student("小红", "female", 2)); - list.add(new Student("小刚", "male", 2)); - list.add(new Student("小霞", "female", 3)); - list.add(new Student("小智", "male", 3)); - list.add(new Student("虚无境", "male", 1)); - - - FilterinGrule male = new MaleStudents(); - FilterinGrule female = new FemaleStudents(); - FilterinGrule secondGrade = new SecondGrade(); - FilterinGrule secondGradeMale = new And(secondGrade, male); - FilterinGrule secondGradeOrFemale = new Or(secondGrade, female); - - System.out.println("男生:"+male.filter(list)); - System.out.println("女生:"+female.filter(list)); - System.out.println("二年级学生:"+secondGrade.filter(list)); - System.out.println("二年级男生:"+secondGradeMale.filter(list)); - System.out.println("二年级的学生或女生:"+secondGradeOrFemale.filter(list)); - - /* - * - 男生:[Student [name=小明, gender=male, grade=1], Student [name=小刚, gender=male, grade=2], Student [name=小智, gender=male, grade=3], Student [name=虚无境, gender=male, grade=1]] - 女生:[Student [name=小红, gender=female, grade=2], Student [name=小霞, gender=female, grade=3]] - 二年级学生:[Student [name=小红, gender=female, grade=2], Student [name=小刚, gender=male, grade=2]] - 二年级男生:[Student [name=小刚, gender=male, grade=2]] - 二年级的学生或女生:[Student [name=小红, gender=female, grade=2], Student [name=小刚, gender=male, grade=2], Student [name=小霞, gender=female, grade=3]] - */ - - } -} - -class Student{ - private String name; - private String gender; - private Integer grade; - public Student(String name, String gender, Integer grade) { - super(); - this.name = name; - this.gender = gender; - this.grade = grade; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getGender() { - return gender; - } - - public void setGender(String gender) { - this.gender = gender; - } - - public Integer getGrade() { - return grade; - } - - public void setGrade(Integer grade) { - this.grade = grade; - } - - @Override - public String toString() { - return "Student [name=" + name + ", gender=" + gender + ", grade=" + grade + "]"; - } -} - -interface FilterinGrule { - List filter(List students); -} - -class MaleStudents implements FilterinGrule{ - @Override - public List filter(List students) { - List maleStudents = new ArrayList(); - students.forEach(student->{ - if(student.getGender().equalsIgnoreCase("male")){ - maleStudents.add(student); - } - }); - return maleStudents; - } -} - -class FemaleStudents implements FilterinGrule{ - @Override - public List filter(List students) { - List femaleStudents = new ArrayList(); - students.forEach(student->{ - if(student.getGender().equalsIgnoreCase("female")){ - femaleStudents.add(student); - } - }); - return femaleStudents; - } -} - -class SecondGrade implements FilterinGrule{ - @Override - public List filter(List students) { - List secondGradeStudents = new ArrayList(); - students.forEach(student->{ - if(student.getGrade() == 2){ - secondGradeStudents.add(student); - } - }); - - return secondGradeStudents; - } -} - - -class And implements FilterinGrule{ - private FilterinGrule filter; - private FilterinGrule filter2; - - public And(FilterinGrule filter,FilterinGrule filter2) { - this.filter=filter; - this.filter2=filter2; - } - - @Override - public List filter(List students) { - List students2=filter.filter(students); - return filter2.filter(students2); - } -} - -class Or implements FilterinGrule{ - private FilterinGrule filter; - private FilterinGrule filter2; - - public Or(FilterinGrule filter,FilterinGrule filter2) { - this.filter=filter; - this.filter2=filter2; - } - - @Override - public List filter(List students) { - List students1=filter.filter(students); - List students2=filter2.filter(students); - students2.forEach(student->{ - if(!students1.contains(student)){ - students1.add(student); - } - }); - return students1; - } -} - - diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/filter/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/filter/package-info.java deleted file mode 100644 index e97c3d8273..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/filter/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: 过滤器模式 -* @Version:1.0.0 -* @author pancm -* @date 2018年8月8日 -*/ -package com.jun.plugin.design.filter; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/flyweight/FlyweightTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/flyweight/FlyweightTest.java deleted file mode 100644 index 0ec2b165ba..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/flyweight/FlyweightTest.java +++ /dev/null @@ -1,118 +0,0 @@ -package com.jun.plugin.design.flyweight; - -import java.util.HashMap; -import java.util.Map; - -/** - * @Title: FlyweightTest - * @Description: 享元模式 - * 在有大量对象时,有可能会造成内存溢出,我们把其中共同的部分抽象出来,如果有相同的业务请求,直接返回在内存中已有的对象, - * 避免重新创建。 - * 应用实例: 1、JAVA 中的 String,如果有则返回,如果没有则创建一个字符串保存在字符串缓存池里面。 - * 2、数据库的数据池。 - * 主要目的就是复用 - * @Version:1.0.0 - * @author pancm - * @date 2018年8月8日 - */ -public class FlyweightTest { - - public static void main(String[] args) { - /* - * 享元模式的角色: Flyweight: 抽象享元类。所有具体享元类的超类或者接口,通过这个接口,Flyweight可以接受并作用于外部专题 - * ConcreteFlyweight: 具体享元类。指定内部状态,为内部状态增加存储空间。 - * UnsharedConcreteFlyweight: 非共享具体享元类。指出那些不需要共享的Flyweight子类。 - * FlyweightFactory: - * 享元工厂类。用来创建并管理Flyweight对象,它主要用来确保合理地共享Flyweight,当用户请求一个Flyweight时, - * FlyweightFactory就会提供一个已经创建的Flyweight对象或者新建一个(如果不存在)。 - * - * 享元模式的核心在于享元工厂类,享元工厂类的作用在于提供一个用于存储享元对象的享元池,用户需要对象时,首先从享元池中获取,如果享元池中不存在 - * ,则创建一个新的享元对象返回给用户,并在享元池中保存该新增对象。 - * - * 享元模式的目的是共享,避免多次创建耗费资源,单例模式的目的是限制创建多个对象以避免冲突等,所以即使都是一个对象,目的也不同。 - */ - - String names[] = { "张三", "李四", "王五", "虚无境" }; - for (int i = 0; i < 8; i++) { - Penil penil = PenFactory.get(names[i>3?i-4:i]); - penil.setSomething("画了一条鱼"); - penil.write(); - } - /* - * - * 张三 第:1次创建 - 张三 用于铅笔 画了一条鱼 - 李四 第:1次创建 - 李四 用于铅笔 画了一条鱼 - 王五 第:1次创建 - 王五 用于铅笔 画了一条鱼 - 虚无境 第:1次创建 - 虚无境 用于铅笔 画了一条鱼 - 张三 用于铅笔 画了一条鱼 - 李四 用于铅笔 画了一条鱼 - 王五 用于铅笔 画了一条鱼 - 虚无境 用于铅笔 画了一条鱼 - - */ - } -} - -/* - * 创建一支笔的接口 - */ -interface Pen { - void write(); -} - -/* - * 创建一支铅笔 - */ -class Penil implements Pen { - private String name; - private String something; - private int i; - - public Penil(String name) { - this.name = name; - i++; - System.out.println(name+" 第:"+i+"次创建"); - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getSomething() { - return something; - } - - public void setSomething(String something) { - this.something = something; - } - - @Override - public void write() { - System.out.println(name+" 用于铅笔 "+something); - } -} - -/* - * 创建一个工厂 - * 核心 - */ -class PenFactory { - private static final Map map = new HashMap(); - - public static Penil get(String name) { - Penil penil = map.get(name); - if (penil == null) { - penil = new Penil(name); - map.put(name, penil); - } - return penil; - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/flyweight/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/flyweight/package-info.java deleted file mode 100644 index bf216b8e3f..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/flyweight/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: 享元模式 -* @Version:1.0.0 -* @author pancm -* @date 2018年8月8日 -*/ -package com.jun.plugin.design.flyweight; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/interpreter/InterpreterTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/interpreter/InterpreterTest.java deleted file mode 100644 index fc0d9ae7b7..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/interpreter/InterpreterTest.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.jun.plugin.design.interpreter; - -/** -* @Title: InterpreterTest -* @Description: 解释器模式 -解释器模式(Interpreter Pattern)是类的行为模式。给定一个语言之后,解释器模式可以定义出其文法的一种表示,并同时提供一个解释器。客户端可以使用这个解释器来解释这个语言中的句子。 -* 比如正则表达式 -* @Version:1.0.0 -* @author pancm -* @date 2018年8月8日 -*/ -public class InterpreterTest { - - /** - * @param args - */ - public static void main(String[] args) { - - - - String word = "好好学习,天天向上!"; - Expreeion expreeion =new BaiduExpreeion(); - Expreeion expreeion2 =new YouDaoExpreeion(); - Expreeion expreeion3 =new XuWuJingExpreeion(); - expreeion.interpert(word); - expreeion2.interpert(word); - expreeion3.interpert(word); - - - /* - 输出结果: - 百度翻译:好好学习,天天向上! 的英文是 Study hard and keep up! - 有道翻译:好好学习,天天向上! 的英文是 study hard and make progress every day! - xuwujing翻译:好好学习,天天向上! 的英文是 Good good study, day day up! - - */ - - /* - - 应用实例:编译器、运算表达式计算。 - - 优点: 1、可扩展性比较好,灵活。 2、增加了新的解释表达式的方式。 3、易于实现简单文法。 - - 缺点: 1、可利用场景比较少。 2、对于复杂的文法比较难维护。 3、解释器模式会引起类膨胀。 4、解释器模式采用递归调用方法。 - - 使用场景: 1、可以将一个需要解释执行的语言中的句子表示为一个抽象语法树。 2、一些重复出现的问题可以用一种简单的语言来进行表达。 3、一个简单语法需要解释的场景。 - - */ - - } - -} - - - -/* - * 定义一个表达式,有一个解释的方法 - */ -interface Expreeion{ - void interpert(String word); -} - -class BaiduExpreeion implements Expreeion{ - String str ="好好学习,天天向上!"; - @Override - public void interpert(String word) { - //如果是这句就翻译 - if(str.equals(word)) { - System.out.println("百度翻译:"+word+" 的英文是 Study hard and keep up!"); - } - } -} - -class YouDaoExpreeion implements Expreeion{ - String str ="好好学习,天天向上!"; - @Override - public void interpert(String word) { - //如果是这句就翻译 - if(str.equals(word)) { - System.out.println("有道翻译:"+word+" 的英文是 study hard and make progress every day!"); - } - } -} - -class XuWuJingExpreeion implements Expreeion{ - String str ="好好学习,天天向上!"; - @Override - public void interpert(String word) { - //如果是这句就翻译 - if(str.equals(word)) { - System.out.println("xuwujing翻译:"+word+" 的英文是 Good good study, day day up!"); - } - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/interpreter/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/interpreter/package-info.java deleted file mode 100644 index a7e1feb0d9..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/interpreter/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: 解释器模式 -* @Version:1.0.0 -* @author pancm -* @date 2018年8月8日 -*/ -package com.jun.plugin.design.interpreter; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/iterator/IteratorTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/iterator/IteratorTest.java deleted file mode 100644 index ef0af39e6a..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/iterator/IteratorTest.java +++ /dev/null @@ -1,135 +0,0 @@ -package com.jun.plugin.design.iterator; - -import java.util.ArrayList; -import java.util.List; - -/** - * @Title: IteratorTest - * @Description: 迭代器模式 迭代器模式(Iterator Pattern)是 Java 和 .Net - * 编程环境中非常常用的设计模式。这种模式用于顺序访问集合对象的元素,不需要知道集合对象的底层表示。 迭代器模式属于行为型模式。 - * 提供一种方法顺序访问一个聚合对象中各个元素, 而又无须暴露该对象的内部表示。 - * @Version:1.0.0 - * @author pancm - * @date 2018年8月8日 - */ -public class IteratorTest { - - public static void main(String[] args) { - - - MyIterable myIterable = new ListContainer(); - myIterable.add("1"); - myIterable.add("zhangsan"); - myIterable.add("2"); - myIterable.add("lisi"); - myIterable.add("3"); - myIterable.add("xuwujing"); - - MyIterator myIterator = myIterable.getIterator(); - while (myIterator.hasNext()){ - String str = myIterator.next(); - System.out.println(str); - } - - /* - 输出结果: - 1 - zhangsan - 2 - lisi - 3 - xuwujing - * - */ - - - /* - * - * 优点: 1、它支持以不同的方式遍历一个聚合对象。 2、迭代器简化了聚合类。 3、在同一个聚合上可以有多个遍历。 - * 4、在迭代器模式中,增加新的聚合类和迭代器类都很方便,无须修改原有代码。 - * - * 缺点:由于迭代器模式将存储数据和遍历数据的职责分离,增加新的聚合类需要对应增加新的迭代器类,类的个数成对增加,这在一定程度上增加了系统的复杂性。 - * - * 使用场景: 1、访问一个聚合对象的内容而无须暴露它的内部表示。 2、需要为聚合对象提供多种遍历方式。 3、为遍历不同的聚合结构提供一个统一的接口。 - * - * 注意事项:迭代器模式就是分离了集合对象的遍历行为,抽象出一个迭代器类来负责,这样既可以做到不暴露集合的内部结构,又可让外部代码透明地访问集合内部的数据。 - * - - 适用 - 访问一个聚集对象的内容而无需暴露它的内部表示; - 支持对聚集对象的多种遍历(如: 不光可以正向遍历, 还可以反向遍历容器元素.); - 为遍历不同的聚合结构提供一个统一的接口(即: 支持多态迭代). - Iterator使用场景不必多言, 由于Java已经将其固化到语言中,因此开发中天天都在使用: - - 当需要访问一个聚集对象, 且不需要了解其内部实现的时, 就应该考虑使用迭代器模式. - 当需要对聚集有多种方式遍历时, 可以考虑使用迭代器模式. - - */ - } - -} - - -/* - * 定义一个Iterator - */ -interface MyIterator { - //判断是否还有下一个 - boolean hasNext(); - //返回信息 - String next(); -} - -/* - * 定义一个Iterable - */ -interface MyIterable{ - MyIterator getIterator(); - - void add(String str); - - String get(int index); -} - - - -class ListContainer implements MyIterable { - - private List list =new ArrayList<>(); - - - @Override - public MyIterator getIterator() { - return new ListIterator(); - } - - @Override - public void add(String str) { - list.add(str); - } - - @Override - public String get(int index) { - return list.get(index); - } - - - class ListIterator implements MyIterator{ - int index; - @Override - public boolean hasNext() { - return index < list.size(); - } - - @Override - public String next() { - if (this.hasNext()) { - return list.get(index++); - } - return null; - } - } - -} - - diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/iterator/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/iterator/package-info.java deleted file mode 100644 index 27341f7bfa..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/iterator/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: 迭代器模式 -* @Version:1.0.0 -* @author pancm -* @date 2018年8月8日 -*/ -package com.jun.plugin.design.iterator; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/mediator/MediatorTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/mediator/MediatorTest.java deleted file mode 100644 index 076fb2e415..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/mediator/MediatorTest.java +++ /dev/null @@ -1,125 +0,0 @@ -package com.jun.plugin.design.mediator; - -/** - * @Title: MediatorTest - * @Description: 中介者模式 中介者模式(Mediator Pattern)是用来降低多个对象和类之间的通信复杂性。 - * 这种模式提供了一个中介类,该类通常处理不同类之间的通信,并支持松耦合,使代码易于维护。中介者模式属于行为型模式。 - * 用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。 - * @Version:1.0.0 - * @author pancm - * @date 2018年8月8日 - */ -public class MediatorTest { - - public static void main(String[] args) { - - - /* - * 基本角色 - 抽象中介者(Mediator): 。定义了同事对象到中介者对象之间的接口。 - 具体中介者(ConcreteMediator): 实现抽象中介者的方法,它需要知道所有的具体同事类,同时需要从具体的同事类那里接收信息,并且向具体的同事类发送信息。 - 抽象同事类(Colleague): 定义了中介者对象的接口,它只知道中介者而不知道其他的同事对象。 - 具体同事类(ConcreteColleague) : 每个具体同事类都只需要知道自己的行为即可,但是他们都需要认识中介者。 - * - */ - - JavaQQqun jq = new JavaQQqun(); - - ZhangSan zs = new ZhangSan("张三", jq); - XuWuJing xwj = new XuWuJing("xuwujing", jq); - jq.setZs(zs); - jq.setXwj(xwj); - zs.exchange("大家好!我是张三!"); - xwj.exchange("欢迎你!张三!"); - - - /* - * 优点: 1、降低了类的复杂度,将一对多转化成了一对一。 2、各个类之间的解耦。 3、符合迪米特原则。 - 缺点:中介者会庞大,变得复杂难以维护。 - */ - - } - -} - - - -//定义一个中介者 QQ群 -interface QQqun { - //提供一个交流的方法 - void exchange(Person person,String message); -} - -//定义一个抽象同事类 -abstract class Person{ - protected String name; - protected QQqun qun; - - Person(String name,QQqun qun){ - this.name = name; - this.qun = qun; - } -} - -class ZhangSan extends Person{ - - ZhangSan(String name, QQqun qun) { - super(name, qun); - } - - void exchange(String message){ - qun.exchange(this,message); - } - - void talk(String message){ - System.out.println(name +"说:" + message); - } -} - -class XuWuJing extends Person{ - - XuWuJing(String name, QQqun qun) { - super(name, qun); - } - - void exchange(String message){ - qun.exchange(this,message); - } - - void talk(String message){ - System.out.println(name +"回应:" + message); - } -} - -//定义一个JavaQQ群 -class JavaQQqun implements QQqun{ - private ZhangSan zs; - private XuWuJing xwj; - - public ZhangSan getZs() { - return zs; - } - - public void setZs(ZhangSan zs) { - this.zs = zs; - } - - public XuWuJing getXwj() { - return xwj; - } - - - public void setXwj(XuWuJing xwj) { - this.xwj = xwj; - } - - - @Override - public void exchange(Person person, String message) { - if(zs.equals(person)){ - zs.talk(message); - }else if(xwj.equals(person)){ - xwj.talk(message); - } - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/mediator/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/mediator/package-info.java deleted file mode 100644 index bd69ee2343..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/mediator/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: 中介者模式 -* @Version:1.0.0 -* @author pancm -* @date 2018年8月8日 -*/ -package com.jun.plugin.design.mediator; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/memento/MementoTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/memento/MementoTest.java deleted file mode 100644 index 9af061648c..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/memento/MementoTest.java +++ /dev/null @@ -1,192 +0,0 @@ -package com.jun.plugin.design.memento; - -/** - * @Title: MementoTest - * @Description: 备忘录模式 - 备忘录模式(Memento Pattern)保存一个对象的某个状态,以便在适当的时候恢复对象。备忘录模式属于行为型模式。 -核心: 在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。 - * @Version:1.0.0 - * @author pancm - * @date 2018年10月29日 - */ -public class MementoTest { - - /** - * @param args - */ - public static void main(String[] args) { - - /* - * 基本使用 - 基本角色:备忘录(Memento)角色、发起人(Originator)角色、负责人(Caretaker)角色。 - 1.备忘录(Memento):主要的功能是包含要被恢复的对象的状态。 - 2.发起人(Originator):在创建的时候,会在备忘录对象中存储状态。 - 3.负责人(Caretaker):主要是负责从备忘录对象中恢复对象的状态。 - */ - /* - * 使用 - * 常见场景就是游戏存档,电脑中的 Ctrl+Z撤销功能 - */ - int level = 1; - int life = 100; - //创建一个玩家 - Player player =new Player(level, life); - System.out.println("玩家xuwujing进入游戏!"); - //状态 - player.getStatus(); - //进行练级 - player.leveling(); - GameSavePage savePage =new GameSavePage(); - //状态 - player.getStatus(); - System.out.println("玩家xuwujing正在存档..."); - //第一次存档 - savePage.setSm(player.saveStateToMemento()); - System.out.println("玩家xuwujing存档成功!"); - System.out.println("玩家xuwujing挑战新手村的BOSS!"); - boolean flag=player.challengeBOSS(); - if(flag) { - System.out.println("玩家xuwujing挑战BOSS成功!"); - return; - } - System.out.println("玩家xuwujing挑战BOSS失败!游戏结束!开始读取存档..."); - savePage.getSm(); - System.out.println("玩家xuwujing读取存档成功!"); - //进行练级 - player.leveling(); - //状态 - player.getStatus(); - System.out.println("玩家xuwujing挑战新手村的BOSS!"); - flag=player.challengeBOSS(); - if(flag) { - System.out.println("玩家xuwujing挑战BOSS成功!"); - return; - } - - /* - - 玩家xuwujing进入游戏! - 玩家xuwujing当前信息: - 人物等级:1,人物生命:100 - 恭喜玩家xuwujing升级!等级提升了1,生命提升了10! - 玩家xuwujing当前信息: - 人物等级:2,人物生命:110 - 玩家xuwujing正在存档... - 玩家xuwujing存档成功! - 玩家xuwujing挑战新手村的BOSS! - 玩家xuwujing挑战BOSS失败!游戏结束!开始读取存档... - 玩家xuwujing读取存档成功! - 恭喜玩家xuwujing升级!等级提升了1,生命提升了10! - 玩家xuwujing当前信息: - 人物等级:3,人物生命:120 - 玩家xuwujing挑战新手村的BOSS! - 玩家xuwujing挑战BOSS成功! - - */ - - - - /* - * 优点: - 1、给用户提供了一种可以恢复状态的机制,可以使用户能够比较方便地回到某个历史的状态。 - 2、实现了信息的封装,使得用户不需要关心状态的保存细节。 - 缺点: - 消耗资源。如果类的成员变量过多,势必会占用比较大的资源,而且每一次保存都会消耗一定的内存。 - 使用场景: - 1、需要保存/恢复数据的相关状态场景。 - 2、提供一个可回滚的操作。 - 注意事项:为了节约内存,可使用原型模式+备忘录模式。 - */ - - } -} - - - -//创建一个存档 信息(备忘录) -class SaveMsg{ - //存档等级 - private int level; - //存档时的生命值 - private int life; - - - public SaveMsg( int level, int life) { - super(); - this.level = level; - this.life = life; - } - - public int getLevel() { - return level; - } - public void setLevel(int level) { - this.level = level; - } - public int getLife() { - return life; - } - public void setLife(int life) { - this.life = life; - } -} - -//设置一个玩家(发起者) -class Player { - //等级 - private int level; - //生命值 - private int life; - - public Player( int level, int life) { - super(); - this.level = level; - this.life = life; - } - //保存信息 - public SaveMsg saveStateToMemento() { - return new SaveMsg(level,life); - } - - //恢复信息 - public void getStateFromMemento(SaveMsg sm) { - this.level = sm.getLevel(); - this.life = sm.getLife(); - } - - //获取当前状态 - public void getStatus() { - System.out.println("玩家xuwujing当前信息:"); - System.out.println("人物等级:"+level+",人物生命:"+life); - } - - //练级 - public void leveling() { - this.level = this.level+1; - this.life = this.life+10; - System.out.println("恭喜玩家xuwujing升级!等级提升了1,生命提升了10!"); - } - - //挑战BOSS - public boolean challengeBOSS() { - //设置条件 - return this.level>2&&this.life>100; - } -} - - -//设置一个游戏存档页(负责人) -class GameSavePage{ - private SaveMsg sm; - - public SaveMsg getSm() { - return sm; - } - public void setSm(SaveMsg sm) { - this.sm = sm; - } - -} - - - diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/memento/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/memento/package-info.java deleted file mode 100644 index d455ecd9c3..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/memento/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: 备忘录模式 -* @Version:1.0.0 -* @author pancm -* @date 2018年8月8日 -*/ -package com.jun.plugin.design.memento; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/nullobject/NullObjectTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/nullobject/NullObjectTest.java deleted file mode 100644 index b3bfa2bbeb..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/nullobject/NullObjectTest.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.jun.plugin.design.nullobject; - -/** - * @Title: NullObjectTest - * @Description: 空对象模式 一个空对象取代 NULL 对象实例的检查。Null 对象不是检查空值,而是反应一个不做任何动作的关系。 这样的 - * Null 对象也可以在数据不可用的时候提供默认的行为。 - * 核心: 其主要目的是在进行调用是不返回Null,而是返回一个空对象,防止空指针异常。 - * - * @Version:1.0.0 - * @author pancm - * @date 2018年8月8日 - */ -public class NullObjectTest { - - /** - * @param args - */ - public static void main(String[] args) { - - /* - * - */ - - AbstractUser au1 = UserFactory.getUser("wangwu"); - AbstractUser au2 = UserFactory.getUser("xuwujing"); - - System.out.println(au1.isNull()); - System.out.println(au1.getName()); - System.out.println(au2.isNull()); - System.out.println(au2.getName()); - - /* - * - * 优点: - 1 .可以加强系统的稳固性,能有效防止空指针报错对整个系统的影响。 - 2 .不依赖客户端便可以保证系统的稳定性。 - - 缺点: - 1.需要编写较多的代码来实现空值的判断,从某种方面来说不划算。 - - 使用场景: - 需要大量对空值进行判断的时候。 - - * - */ - } - -} - -//定义一个抽象类 -interface AbstractUser { - String getName(); - - boolean isNull(); -} - -//实际用户 -class RealUser implements AbstractUser { - private String name; - - public RealUser(String name) { - this.name = name; - } - - @Override - public String getName() { - return name; - } - - @Override - public boolean isNull() { - return false; - } -} - -class NullUser implements AbstractUser { - - @Override - public String getName() { - return "user is not exist"; - } - - @Override - public boolean isNull() { - return true; - } -} - -//定义一个工厂 -class UserFactory { - - public static final String[] names = { "zhangsan", "lisi", "xuwujing" }; - - public static AbstractUser getUser(String name) { - for (int i = 0; i < names.length; i++) { - if (names[i].equalsIgnoreCase(name)) { - return new RealUser(name); - } - } - return new NullUser(); - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/nullobject/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/nullobject/package-info.java deleted file mode 100644 index e577da99b5..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/nullobject/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: 空对象模式 -* @Version:1.0.0 -* @author pancm -* @date 2018年8月8日 -*/ -package com.jun.plugin.design.nullobject; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/observer/ObserverTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/observer/ObserverTest.java deleted file mode 100644 index 3771dcef01..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/observer/ObserverTest.java +++ /dev/null @@ -1,185 +0,0 @@ -package com.jun.plugin.design.observer; - -import java.util.ArrayList; -import java.util.List; - -/** - * @Title: ObserverTest - * @Description: 观察者模式 当对象间存在一对多关系时,则使用观察者模式(Observer - * Pattern)。比如,当一个对象被修改时,则会自动通知它的依赖对象。观察者模式属于行为型模式。 - 观察者模式是对象的行为模式,又叫发布-订阅(Publish/Subscribe)模式、模型-视图(Model/View)模式、源-监听器(Source/Listener)模式或从属者(Dependents)模式。 -观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态上发生变化时,会通知所有观察者对象,使它们能够自动更新自己。 - * 核心:定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。 - * @Version:1.0.0 - * @author pancm - * @date 2018年8月8日 - */ -public class ObserverTest { - - public static void main(String[] args) { - - /* - * 基本使用 - * - 基本角色 - 1.抽象主题角色(Subject):它把所有观察者对象的引用保存到一个聚集里,每个主题都可以有任何数量的观察者。抽象主题提供一个接口,可以增加和删除观察者对象。 - 2.具体主题角色(ConcreteSubject):将有关状态存入具体观察者对象;在具体主题内部状态改变时,给所有登记过的观察者发出通知。 - 3.抽象观察者角色(Observer):为所有的具体观察者定义一个接口,在得到主题通知时更新自己。 - 4.具体观察者角色(ConcreteObserver):实现抽象观察者角色所要求的更新接口,以便使本身的状态与主题状态协调。 - - * - */ - - - /* - 比如,订阅番剧,番剧更新则通知订阅的人。 - xuwujing订阅了 <冰菓>和番剧,当番剧更新的时候,他们就会收到通知! - 如果他们取消了该番剧的订阅,那么他就不会收到该番剧的通知了。 - */ - String name1 ="张三"; - String name2 ="xuwujing"; - String bingguo = "冰菓"; - String fate = "fate/zero"; - BangumiSubject bs1 = new Bangumi(bingguo); - BangumiSubject bs2 = new Bangumi(fate); - - UserObserver uo1 = new User(name1); - UserObserver uo2 = new User(name2); - - //进行订阅 - bs1.toThem(uo1); - bs1.toThem(uo2); - bs2.toThem(uo1); - bs2.toThem(uo2); - //进行通知 - bs1.notifyUser(); - bs2.notifyUser(); - - //取消订阅 - bs1.callOff(uo1); - bs2.callOff(uo2); - //进行通知 - bs1.notifyUser(); - bs2.notifyUser(); - - /* - 输出结果: - 用户张三订阅了冰菓! - 用户xuwujing订阅了冰菓! - 用户张三订阅了fate/zero! - 用户xuwujing订阅了fate/zero! - 冰菓更新了!开始通知订阅该番剧的用户! - 张三订阅的番剧: 冰菓更新啦! - xuwujing订阅的番剧: 冰菓更新啦! - fate/zero更新了!开始通知订阅该番剧的用户! - 张三订阅的番剧: fate/zero更新啦! - xuwujing订阅的番剧: fate/zero更新啦! - 用户张三取消订阅冰菓! - 用户xuwujing取消订阅fate/zero! - 冰菓更新了!开始通知订阅该番剧的用户! - xuwujing订阅的番剧: 冰菓更新啦! - fate/zero更新了!开始通知订阅该番剧的用户! - 张三订阅的番剧: fate/zero更新啦! - */ - - /* - * - 优点: 1、解除耦合,让耦合的双方都依赖于抽象,从而使得各自的变换都不会影响另一边的变换。 - 缺点: 1、如果一个被观察者对象有很多的直接和间接的观察者的话,将所有的观察者都通知到会花费很多时间。 - 2、如果在观察者和观察目标之间有循环依赖的话,观察目标会触发它们之间进行循环调用,可能导致系统崩溃。 - 3、观察者模式没有相应的机制让观察者知道所观察的目标对象是怎么发生变化的,而仅仅只是知道观察目标发生了变化。 - - 使用场景: - - 1. 需要关联行为的场景; - 2. 事件需要创建一个触发链的场景,比如监控; - 3.跨系统的消息交换场景,比如消息队列、事件总线的处理机制。 - - 注意事项: - 1、JAVA中已经有了对观察者模式的支持类。 - 2、避免循环引用。 - 3、如果顺序执行,某一观察者错误会导致系统卡壳,一般采用异步方式。 - * - */ - } - -} - - - -//定义一个抽象主题, 将观察者(订阅者)聚集起来,可以进行新增、删除和通知。 -//这里就可以当做番剧 -interface BangumiSubject{ - //追番 - void toThem(UserObserver user); - //取消追番 - void callOff(UserObserver user); - //通知 - void notifyUser(); -} - - -//定义一个抽象观察者,在得到通知时进行更新 -//这里就可以当做是用户 -interface UserObserver{ - //更新通知 - void update(String bangumi); - //得到用户名称 - String getName(); -} - -//定义一个具体主题,实现了抽象主题(BangumiSubject)接口的方法 -//同时通过一个List集合保存观察者的信息,当需要通知观察者的时候,遍历通知即可。 -class Bangumi implements BangumiSubject { - - - private List list; - private String anime; - public Bangumi(String anime) { - this.anime = anime; - list = new ArrayList(); - } - - @Override - public void toThem(UserObserver user) { - System.out.println("用户"+user.getName()+"订阅了"+anime+"!"); - list.add(user); - } - - @Override - public void callOff(UserObserver user) { - if(!list.isEmpty()) { - System.out.println("用户"+user.getName()+"取消订阅"+anime+"!"); - list.remove(user); - } - } - - @Override - public void notifyUser() { - System.out.println(anime+"更新了!开始通知订阅该番剧的用户!"); - list.forEach(user-> - user.update(anime) - ); - } - -} - - -//定义了一个具体观察者,实现抽象观察者(UserObserver)接口的方法 -class User implements UserObserver{ - private String name; - public User(String name){ - this.name = name; - } - - @Override - public void update(String bangumi) { - System.out.println(name+"订阅的番剧: " + bangumi+"更新啦!"); - } - - @Override - public String getName() { - return name; - } -} - diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/observer/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/observer/package-info.java deleted file mode 100644 index de382d9cb6..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/observer/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: 观察者模式 -* @Version:1.0.0 -* @author pancm -* @date 2018年8月8日 -*/ -package com.jun.plugin.design.observer; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/package-info.java deleted file mode 100644 index 3060cf2842..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/package-info.java +++ /dev/null @@ -1,60 +0,0 @@ -/** -* @Title: package-info -* @Description: 设计模式相关测试代码 -设计模式有23种类型。按照主要分类可以分为三大类: - -一、创建型模式 - -这些设计模式提供了一种在创建对象的同时隐藏创建逻辑的方式,而不是使用 new运算符直接实例化对象。这使得程序在判断针对某个给定实例需要创建哪些对象时更加灵活。 - -单例模式 -工厂模式 -抽象工厂模式 -建造者模式 -原型模式 -二、结构型模式 - -这些设计模式关注类和对象的组合。继承的概念被用来组合接口和定义组合对象获得新功能的方式。 - -适配器模式 -桥接模式 -过滤器模式 -组合模式 -装饰器模式 -外观模式 -享元模式 -代理模式 -三、行为型模式 - -这些设计模式特别关注对象之间的通信。 - -责任链模式 -命令模式 -解释器模式 -迭代器模式 -中介者模式 -备忘录模式 -观察者模式 -状态模式 -空对象模式 -策略模式 -模板模式 -访问者模式 - - -设计模式的原则 -设计模式的六大原则 -开闭原则:对扩展开放,对修改关闭。 -里氏代换原则:对开闭原则的补充。任何基类可以出现的地方,子类一定可以出现。LSP 是继承复用的基石,只有当派生类可以替换掉基类,且软件单位的功能不受到影响时,基类才能真正被复用,而派生类也能够在基类的基础上增加新的行为。 -依赖倒转原则:针对接口编程,依赖于抽象而不依赖于具体。 -接口隔离原则:尽量使用多个隔离的接口,为了降低类之间的耦合度。 -迪米特法则:一个实体应当尽量少地与其他实体之间发生相互作用,使得系统功能模块相对独立。 -合成复用原则:尽量使用合成/聚合的方式,而不是使用继承。 - - - -* @Version:1.0.0 -* @author pancm -* @date 2018年7月7日 -*/ -package com.jun.plugin.design; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/prototype/PrototypeTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/prototype/PrototypeTest.java deleted file mode 100644 index 6a1cf82f0b..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/prototype/PrototypeTest.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.jun.plugin.design.prototype; - -/** - * @Title: PrototypeTest - * @Description: 原型模式 - * 用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。 - * 所谓原型模式,就是java中的克隆技术,以某个对象为原型。复制出新的对象。显然新的对象具备原型对象的特点。 - * 1、实现克隆操作,在 JAVA 继承 Cloneable,重写 clone()。 - * 2、原型模式同样用于隔离类对象的使用者和具体类型(易变类)之间的耦合关系,它同样要求这些"易变类"拥有稳定的接口。 - * - * @Version:1.0.0 - * @author pancm - * @date 2018年8月13日 - */ -public class PrototypeTest { - - public static void main(String[] args) { - Mail mail=new Mail(); - mail.setMsg("生日快乐!"); - Mail mail2=(Mail) mail.clone(); - System.out.println("小明:"+mail.getMsg()); - System.out.println("小红:"+mail2.getMsg()); - } -} - -/** - * @Title: - * @Description: 定义一个原型的邮件信息 - * @Version:1.0.0 - * @author pancm - * @date 2018年8月15日 - */ - class Mail implements Cloneable { - protected String msg; - - public String getMsg() { - return msg; - } - - public void setMsg(String msg) { - this.msg = msg; - } - - - public Object clone() { - Object clone = null; - try { - clone = super.clone(); - } catch (CloneNotSupportedException e) { - e.printStackTrace(); - } - return clone; - } - void sendMail() { - } -} - -class BirthdayMail extends Mail { - - public BirthdayMail() { - msg = "生日快乐!"; - } - - @Override - void sendMail() { - System.out.println(msg); - } -} - - - diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/prototype/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/prototype/package-info.java deleted file mode 100644 index 753c521fce..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/prototype/package-info.java +++ /dev/null @@ -1,10 +0,0 @@ - -/** -* @Title: package-info -* @Description: -* 原型模式 -* @Version:1.0.0 -* @author pancm -* @date 2018年8月7日 -*/ -package com.jun.plugin.design.prototype; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/proxy/ProxyTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/proxy/ProxyTest.java deleted file mode 100644 index 5e8af2e9c5..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/proxy/ProxyTest.java +++ /dev/null @@ -1,134 +0,0 @@ -package com.jun.plugin.design.proxy; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; - -/** - * @Title: ProxyTest - * @Description:代理模式 在代理模式中,一个类代表另一个类的功能。这种类型的设计模式属于结构型模式。 - * 在代理模式中,我们创建具有现有对象的对象,以便向外界提供功能接口。 - * - * 应用实例: 1、Windows 里面的快捷方式。 2、spring aop。 3、支票。 - * @Version:1.0.0 - * @author pancm - * @date 2018年8月8日 - */ -public class ProxyTest { - - public static void main(String[] args) { - - /* - * - * - * 一个是真正的你要访问的对象(目标类),一个是代理对象,真正对象与代理 对象实现同一个接口,先访问代理类再访问真正要访问的对象。 - * 代理模式分为静态代理、动态代理。 - * 静态代理是由程序员创建或工具生成代理类的源码,再编译代理类。所谓静态也就是在程序运行前就已经存在代理类的字节码文件, - * 代理类和委托类的关系在运行前就确定了。 动态代理是在实现阶段不用关心代理类,而在运行阶段才指定哪一个对象。 - * - * 组成: 抽象角色:通过接口或抽象类声明真实角色实现的业务方法。 - * 代理角色:实现抽象角色,是真实角色的代理,通过真实角色的业务逻辑方法来实现抽象方法,并可以附加自己的操作。 - * 真实角色:实现抽象角色,定义真实角色所要实现的业务逻辑,供代理角色调用。 - - * JDK对动态代理提供了以下支持: - java.lang.reflect.Proxy 动态生成代理类和对象 - java.lang.reflect.InvocationHandler - 可以通过invoke方法实现对真实角色的代理访问; - 每次通过Proxy生成代理类对象时都要指定对象的处理器对象. - - * 优点: 1、职责清晰。 2、高扩展性。 3、智能化。 - * 缺点: - * 1、由于在客户端和真实主题之间增加了代理对象,因此有些类型的代理模式可能会造成请求的处理速度变慢。 - * 2、实现代理模式需要额外的工作,有些代理模式的实现非常复杂。 - * - * 注意事项: 1、和适配器模式的区别:适配器模式主要改变所考虑对象的接口,而代理模式不能改变所代理类的接口。 - * 2、和装饰器模式的区别:装饰器模式为了增强功能,而代理模式是为了加以控制。 - */ - - /* - * <大话设计模式>中的追求者、代理者 张三想买东西,可以自己买,但是此时李四正好在商场,于是便让李四帮忙(代理)买了。 - */ - - /* - * 静态代理 - */ - - String name = "李四"; - Shopping shopping = new ProxyPerson(new ExecutePerson(name)); - shopping.buyFood(); - - /* - * 动态代理 - */ - Shopping shopping2 = (Shopping) Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{Shopping.class}, new ProxyPerson2(new ExecutePerson(name))); - shopping2.buyFood(); - - /* - * 核心就是在不影响之前的功能下进行扩展 - */ - } -} - -/* - * - */ -interface Shopping { - void buyFood(); -} - -/* - * 定义一个需要买东西的人 - */ -class ExecutePerson implements Shopping { - - private String name; - - public ExecutePerson(String name) { - this.name = name; - } - - @Override - public void buyFood() { - System.out.println(name + " 买东西"); - } -} - -/* - * 静态代理 - * 定义一个可以帮买东西的人 - */ -class ProxyPerson implements Shopping { - private ExecutePerson ep; - - public ProxyPerson(ExecutePerson ep) { - this.ep = ep; - } - - @Override - public void buyFood() { - ep.buyFood(); - } -} - -/* - * 动态代理 - * 定义一个可以帮买东西的人 - */ -class ProxyPerson2 implements InvocationHandler { - private Shopping shopping; - - private final String methodName = "buyFood"; - - public ProxyPerson2(Shopping shopping) { - this.shopping = shopping; - } - - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - Object result = null; - if (methodName.equals(method.getName())) { - result = method.invoke(shopping, args); - } - return result; - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/proxy/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/proxy/package-info.java deleted file mode 100644 index 625478f60e..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/proxy/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: 代理模式 -* @Version:1.0.0 -* @author pancm -* @date 2018年8月8日 -*/ -package com.jun.plugin.design.proxy; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/responsibility/ResponsibilityTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/responsibility/ResponsibilityTest.java deleted file mode 100644 index 748845f936..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/responsibility/ResponsibilityTest.java +++ /dev/null @@ -1,157 +0,0 @@ -package com.jun.plugin.design.responsibility; - -/** - * @Title: ResponsibilityTest - * @Description: 责任链模式 - 顾名思义,责任链模式(Chain of Responsibility Pattern)为请求创建了一个接收者对象的链。 - 这种模式给予请求的类型,对请求的发送者和接收者进行解耦。这种类型的设计模式属于行为型模式。 - 在这种模式中,通常每个接收者都包含对另一个接收者的引用。如果一个对象不能处理该请求,那么它会把相同的请求传给下一个接收者,依此类推。 - * @Version:1.0.0 - * @author pancm - * @date 2018年8月8日 - */ -public class ResponsibilityTest { - - public static void main(String[] args) { - - - /* - * 通过条件判断是否能够处理,符合就行处理,否则就转交给下一个进行处理 - * - */ - String name = "xuwujing"; - String something = "去聚餐"; - String something2 = "去旅游"; - Learder learder1 =new Supervisor(name, something); - Learder learder2 =new BranchManager(name, something); - Learder learder3 =new GeneralManager(name, something); - learder1.setLearder(learder2); - learder2.setLearder(learder3); - learder1.handler(1); - - Learder learder4 =new Supervisor(name, something2); - Learder learder5 =new BranchManager(name, something2); - Learder learder6 =new GeneralManager(name, something2); - learder4.setLearder(learder5); - learder5.setLearder(learder6); - learder4.handler(0); - - - - } - -} - -// 定义一个抽象类 -abstract class Handler { - protected Handler successor; - - /** * 示意处理请求的方法,虽然这个示意方法是没有传入参数的 但实际是可以传入参数的,根据具体需要来选择是否传递参数 */ - public abstract void handleRequest(); - - /** * 取值方法 */ - public Handler getSuccessor() { - return successor; - } - - /** * 赋值方法,设置后继的责任对象 */ - public void setSuccessor(Handler successor) { - this.successor = successor; - } - -} - -// 具体的业务 -class ConcreteHandler extends Handler { - @Override - public void handleRequest() { - /** * 判断是否有后继的责任对象 如果有,就转发请求给后继的责任对象 如果没有,则处理请求 */ - if (getSuccessor() != null) { - System.out.println("放过请求"); - getSuccessor().handleRequest(); - } else { - System.out.println("处理请求"); - } - } -} - - -abstract class Learder{ - - - protected Learder learder; - - protected void setLearder(Learder learder){ - this.learder=learder; - } - - protected Learder getLearder(){ - return learder; - } - - abstract void handler(int level); -} - -//主管 -class Supervisor extends Learder{ - private String name; - private String something; - public Supervisor(String name,String something) { - this.name=name; - this.something=something; - } - - @Override - void handler(int level) { - //如果级别在自己的处理范围之内 - if(level>1){ - System.out.println("主管处理了 "+name+"所述的<"+something+">事情!"); - }else{ - System.out.println("主管未能处理 "+name+"所述的<"+something+">事情!转交给上级!"); - getLearder().handler(level); - } - } -} - -//部门经理 -class BranchManager extends Learder{ - private String name; - private String something; - public BranchManager(String name,String something) { - this.name=name; - this.something=something; - } - - @Override - void handler(int level) { - //如果级别在自己的处理范围之内 - if(level>0){ - System.out.println("部门经理处理了 "+name+"所述的<"+something+">事情!"); - }else{ - System.out.println("部门经理未能处理 "+name+"所述的<"+something+">事情!转交给上级!"); - getLearder().handler(level); - } - } -} - -//总经理 -class GeneralManager extends Learder{ - private String name; - private String something; - public GeneralManager(String name,String something) { - this.name=name; - this.something=something; - } - - @Override - void handler(int level) { - //如果级别在自己的处理范围之内 - if(level>-1){ - System.out.println("总经理处理了 "+name+"所述的<"+something+">事情!"); - }else{ - System.out.println("总经理未能处理 "+name+"所述的<"+something+">事情!转交给上级!"); - getLearder().handler(level); - } - } -} - diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/responsibility/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/responsibility/package-info.java deleted file mode 100644 index 52ca40176f..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/responsibility/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: 责任链模式 -* @Version:1.0.0 -* @author pancm -* @date 2018年8月8日 -*/ -package com.jun.plugin.design.responsibility; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/singleton/SingletonTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/singleton/SingletonTest.java deleted file mode 100644 index e0ef41f938..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/singleton/SingletonTest.java +++ /dev/null @@ -1,145 +0,0 @@ -package com.jun.plugin.design.singleton; -/** - * @author ZERO - * @Data 2017-6-7 下午4:08:26 - * @Description - */ - -/** - * 方法一 - * 单例模式的实现:饿汉式,线程安全 但效率比较低 - * - * 方法一就是传说的中的饿汉模式 - * 优点是:写起来比较简单,而且不存在多线程同步问题,避免了synchronized所造成的性能问题; - * 缺点是:当类SingletonTest被加载的时候,会初始化static的instance,静态变量被创建并分配内存空间, - * 从这以后,这个static的instance对象便一直占着这段内存(即便你还没有用到这个实例), - * 当类被卸载时,静态变量被摧毁,并释放所占有的内存,因此在某些特定条件下会耗费内存。 - * - */ - class SingletonTest1 { - - // 定义一个私有的构造方法 - private SingletonTest1() { - } - - // 将自身的实例对象设置为一个属性,并加上Static和final修饰符 - private static final SingletonTest1 instance = new SingletonTest1(); - - // 静态方法返回该类的实例 - public static SingletonTest1 getInstance() { - return instance; - } -} - - - /** - * 方法二 - * 单例模式的实现:饱汉式,非线程安全 - * 方法二就是传说的中的饱汉模式 - * 优点是:写起来比较简单,当类SingletonTest被加载的时候,静态变量static的instance未被创建并分配内存空间, - * 当getInstance方法第一次被调用时,初始化instance变量,并分配内存,因此在某些特定条件下会节约了内存; - * 缺点是:并发环境下很可能出现多个SingletonTest实例。 - */ - class SingletonTest2 { - // 定义私有构造方法(防止通过 new SingletonTest()去实例化) - private SingletonTest2() { - } - - // 定义一个SingletonTest类型的变量(不初始化,注意这里没有使用final关键字) - private static SingletonTest2 instance; - - // 定义一个静态的方法(调用时再初始化SingletonTest,但是多线程访问时,可能造成重复初始化问题) - public static SingletonTest2 getInstance() { - if (instance == null) { - instance = new SingletonTest2(); - } - return instance; - } - } - - - /** - *方法三 - * 单例模式的实现:饱汉式,线程安全简单实现 - * 方法三为方法二的简单优化 - * 优点是:使用synchronized关键字避免多线程访问时,出现多个SingletonTest实例。 - * 缺点是:同步方法频繁调用时,效率略低 - */ - class SingletonTest3 { - // 定义私有构造方法(防止通过 new SingletonTest()去实例化) - private SingletonTest3() { - } - // 定义一个SingletonTest类型的变量(不初始化,注意这里没有使用final关键字) - private static SingletonTest3 instance; - - // 定义一个静态的方法(调用时再初始化SingletonTest,使用synchronized 避免多线程访问时,可能造成重的复初始化问题) - public static synchronized SingletonTest3 getInstance() { - if (instance == null) { - instance = new SingletonTest3(); - } - return instance; - } - } - - - /** - * 方法四 - * 静态内部类 - * 这种写法仍然使用JVM本身机制保证了线程安全问题;由于SingletonTest5是私有的, 除了getInstance()之外没有办法访问它, - * 因此它是懒汉式的;同时读取实例的时候不会进行同步,没有性能缺陷;也不依赖JDK版本。 - */ - class SingletonTest4 { - private SingletonTest4(){ - } - private static class SingletonTest5{ - private static SingletonTest4 instance = new SingletonTest4(); - } - public static final SingletonTest4 getInstance(){ - return SingletonTest5.instance; - } - } - - - /** - * 方法五 双重锁 - * 单例模式最优方案 - * 线程安全 并且效率高 - * 方法四为单例模式的最佳实现。内存占用低,效率高,线程安全,多线程操作原子性。 - */ - class SingletonTest6 { - // 定义一个私有构造方法 - private SingletonTest6() { - } - //定义一个静态私有变量(不初始化,不使用final关键字,使用volatile保证了多线程访问时instance变量的可见性,避免了instance初始化时其他变量属性还没赋值完时,被另外线程调用) - private static volatile SingletonTest6 instance; - //定义一个共有的静态方法,返回该类型实例 - public static SingletonTest6 getIstance() { - // 对象实例化时与否判断(不使用同步代码块,instance不等于null时,直接返回对象,提高运行效率) - if (instance == null) { - //同步代码块(对象未初始化时,使用同步代码块,保证多线程访问时对象在第一次创建后,不再重复被创建) - synchronized (SingletonTest6.class) { - //未初始化,则初始instance变量 - if (instance == null) { - instance = new SingletonTest6(); - } - } - } - return instance; - } - } - - /** - * 方法六,枚举单例模式 - * 1.从Java1.5开始支持; - * 2.无偿提供序列化机制; - * 3.绝对防止多次实例化,即使在面对复杂的序列化或者反射攻击的时候; - * 自由序列化,线程安全,保证单例 - */ - enum SingletonTest7{ - INSTANCE; - } - - public class SingletonTest { - public static void main(String[] args) { - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/singleton/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/singleton/package-info.java deleted file mode 100644 index c32d8058d9..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/singleton/package-info.java +++ /dev/null @@ -1,11 +0,0 @@ -/** - * - */ -/** - * Title: package-info - * Description: 单例模式测试 - * Version:1.0.0 - * @author pancm - * @date 2017年11月7日 - */ -package com.jun.plugin.design.singleton; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/state/StateTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/state/StateTest.java deleted file mode 100644 index 4e3e7b2aa2..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/state/StateTest.java +++ /dev/null @@ -1,122 +0,0 @@ -package com.jun.plugin.design.state; - -/** - * @Title: StateTest - * @Description: 状态模式 在状态模式(State Pattern)中,类的行为是基于它的状态改变的。这种类型的设计模式属于行为型模式。 - * 在状态模式中,我们创建表示各种状态的对象和一个行为随着状态对象改变而改变的 context 对象。 - * 允许对象在内部状态发生改变时改变它的行为,对象看起来好像修改了它的类。 - * 状态模式主要解决的是当控制一个对象状态转换的条件表达式过于复杂是的情况。把状态的判断逻辑转移到表示不同状态一系列类中,可以把复杂的判断简单化。 - * @Version:1.0.0 - * @author pancm - * @date 2018年8月8日 - */ -public class StateTest { - - /** - * @param args - */ - public static void main(String[] args) { - - /* - - 例子: 经典的Tcp的状态有 创建、监听、关闭这三个状态。 - - 基本角色: - 环境角色(Context):它定义了客户程序需要的接口并维护一个具体状态角色的实例,将与状态相关的操作委托给当前的Concrete State对象来处理。 -   抽象状态角色(State):定义一个接口以封装使用上下文环境的的一个特定状态相关的行为。 -   具体状态角色(Concrete State):实现抽象状态定义的接口。 - * - */ - - Headset hs = new Headset(new PlayState()); - //第一次播放音乐 - hs.press(); - //第二次暂停音乐 - hs.press(); - //第三次播放音乐 - hs.press(); - - /* - * 优点: - * 1、封装了转换规则。 - * 2、枚举可能的状态,在枚举状态之前需要确定状态种类。 - * 3、将所有与某个状态有关的行为放到一个类中,并且可以方便地增加新的状态,只需要改变对象状态即可改变对象的行为。 - * 4、允许状态转换逻辑与状态对象合成一体,而不是某一个巨大的条件语句块。 - * 5、可以让多个环境对象共享一个状态对象,从而减少系统中对象的个数。 - * 缺点: - * 1、状态模式的使用必然会增加系统类和对象的个数。 - * 2、状态模式的结构与实现都较为复杂,如果使用不当将导致程序结构和代码的混乱。 - * 3、状态模式对"开闭原则"的支持并不太好,对于可以切换状态的状态模式,增加新的状态类需要修改那些负责状态转换的源代码, - * 否则无法切换到新增状态,而且修改某个状态类的行为也需修改对应类的源代码。 - * 使用场景: - * 1、行为随状态改变而改变的场景。 - * 2、条件、分支语句的代替者。 - 和策略模式比较: - 相同: - 1.它们很容易添加新的状态或策略,而且不需要修改使用它们的Context对象。 - 2.它们都符合OCP原则,在状态模式和策略模式中,Context对象对修改是关闭的,添加新的状态或策略,都不需要修改Context。 - 3.它们都会初始化。 - 4.它们都依赖子类去实现相关行为。 - - 区别: - 1.状态模式的行为是平行性的,不可相互替换的; - 2.而策略模式的行为是平等性的,是可以相互替换的。 - 3.最重要的一个不同之处是,策略模式的改变由客户端完成; - 4.而状态模式的改变,由环境角色或状态自己 - - * 注意事项:在行为受状态约束的时候使用状态模式,而且状态不超过 5 个。 - */ - } - -} - - - -//定义一个音乐状态 -interface MusicState{ - void press(); -} - -class PlayState implements MusicState{ - - @Override - public void press() { - System.out.println("播放音乐!"); - } -} - -class PauseState implements MusicState{ - - @Override - public void press() { - System.out.println("暂停音乐!"); - } -} - - - - -//定义一个耳机 -class Headset{ - private MusicState state; - private int i; - public Headset(MusicState state){ - this.state=state; - } - public void press() { - if((i&1)==0) { - this.state=new PlayState(); - }else { - this.state=new PauseState(); - } - this.state.press(); - i++; - } - public MusicState getState() { - return state; - } - public void setState(MusicState state) { - this.state = state; - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/state/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/state/package-info.java deleted file mode 100644 index 5df503f22f..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/state/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: 状态模式 -* @Version:1.0.0 -* @author pancm -* @date 2018年8月8日 -*/ -package com.jun.plugin.design.state; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/strategy/StrategyTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/strategy/StrategyTest.java deleted file mode 100644 index 32d4ae8df5..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/strategy/StrategyTest.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.jun.plugin.design.strategy; - -/** - * @Title: StrategyTest - * @Description: 策略模式 在策略模式(CalculateStrategy Pattern)中,一个类的行为或其算法可以在运行时更改。 - * 这种类型的设计模式属于行为型模式。 在策略模式中,我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的 context - * 对象。 策略对象改变 context 对象的执行算法。 - * @Version:1.0.0 - * @author pancm - * @date 2018年8月8日 - */ -public class StrategyTest { - - public static void main(String[] args) { - - /* - * 基本使用 - * - 角色 - 1,环境角色(Context):持有一个策略类的引用,提供给客户端使用。 - -    2,抽象策略角色(Strategy):这是一个抽象角色,通常由一个接口或抽象类实现。此角色给出所有的具体策略类所需的接口。 - -    3,具体策略角色(ConcreteStrategy):包装了相关的算法或行为。 - * - */ - - /* - * 计算加减乘除 - */ - int a=4,b=2; - CalculatorContext context = new CalculatorContext(new OperationAdd()); - System.out.println("a + b = "+context.executeStrategy(a, b)); - - CalculatorContext context2 = new CalculatorContext(new OperationSub()); - System.out.println("a - b = "+context2.executeStrategy(a, b)); - - CalculatorContext context3 = new CalculatorContext(new OperationMul()); - System.out.println("a * b = "+context3.executeStrategy(a, b)); - - CalculatorContext context4 = new CalculatorContext(new OperationDiv()); - System.out.println("a / b = "+context4.executeStrategy(a, b)); - - - /* - a + b = 6 - a - b = 2 - a * b = 8 - a / b = 2 - */ - - - /* - 优点: 1、扩展性好,可以在不修改对象结构的情况下,为新的算法进行添加新的类进行实现; - 2、灵活性好,可以对算法进行自由切换; - - 缺点: 1、使用策略类变多,会增加系统的复杂度。 - 2、客户端必须知道所有的策略类才能进行调用 - - 使用场景: 1、如果在一个系统里面有许多类,它们之间的区别仅在于它们的行为,那么使用策略模式可以动态地让一个对象在许多行为中选择一种行为。 - 2、一个系统需要动态地在几种算法中选择一种。 - 3、如果一个对象有很多的行为,如果不用恰当的模式,这些行为就只好使用多重的条件选择语句来实现。 - - */ - } -} - -//定义一个策略 -interface CalculateStrategy { - int doOperation(int num1, int num2); -} - -//定义一个加法 -class OperationAdd implements CalculateStrategy { - @Override - public int doOperation(int num1, int num2) { - return num1 + num2; - } -} - -//定义一个减法 -class OperationSub implements CalculateStrategy { - @Override - public int doOperation(int num1, int num2) { - return num1 - num2; - } -} - -//定义一个乘法 -class OperationMul implements CalculateStrategy { - @Override - public int doOperation(int num1, int num2) { - return num1 * num2; - } -} - -//定义一个除法 -class OperationDiv implements CalculateStrategy { - @Override - public int doOperation(int num1, int num2) { - return num1 / num2; - } -} - -//定义一个环境 -class CalculatorContext { - private CalculateStrategy strategy; - - public CalculatorContext(CalculateStrategy strategy) { - this.strategy = strategy; - } - - public int executeStrategy(int num1, int num2) { - return strategy.doOperation(num1, num2); - } -} - - - diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/strategy/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/strategy/package-info.java deleted file mode 100644 index 966acb5ef5..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/strategy/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: 策略模式 -* @Version:1.0.0 -* @author pancm -* @date 2018年8月8日 -*/ -package com.jun.plugin.design.strategy; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/template/TemplateTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/template/TemplateTest.java deleted file mode 100644 index 7a1099df6e..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/template/TemplateTest.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.jun.plugin.design.template; - -/** - * @Title: TemplateTest - * @Description: 模板模式(Template Pattern)中,一个抽象类公开定义了执行它的方法的方式/模板。 - * 它的子类可以按需要重写方法实现,但调用将以抽象类中定义的方式进行。 这种类型的设计模式属于行为型模式。 - * 定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。 - * 模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。 - * @Version:1.0.0 - * @author pancm - * @date 2018年8月8日 - */ -public class TemplateTest { - - public static void main(String[] args) { - - /* - * 基本使用 - Java 中的 Servlet就是经典的模板模式的使用。HttpService类提供了一个service()方法, - 这个方法调用七个do方法中的一个或几个,完成对客户端调用的响应。这些do方法需要由HttpServlet的具体子类提供 - - - 基本角色 -  抽象模板(Abstract Template)角色有如下责任: -   1.定义了一个或多个抽象操作,以便让子类实现。这些抽象操作叫做基本操作,它们是一个顶级逻辑的组成步骤。 -   2.定义并实现了一个模板方法。这个模板方法一般是一个具体方法,它给出了一个顶级逻辑的骨架,而逻辑的组成步骤在相应的抽象操作中,推迟到子类实现。顶级逻辑也有可能调用一些具体方法。 -  具体模板(Concrete Template)角色又如下责任: -   1.实现父类所定义的一个或多个抽象方法,它们是一个顶级逻辑的组成步骤。 -   2.每一个抽象模板角色都可以有任意多个具体模板角色与之对应,而每一个具体模板角色都可以给出这些抽象方法(也就是顶级逻辑的组成步骤)的不同实现,从而使得顶级逻辑的实现各不相同。 - - */ - Game game = new ContraGame(); - game.play(); - System.out.println(); - game = new TMNTGame(); - game.play(); - - /* - * 优点: - * 1、封装不变部分,扩展可变部分。 - * 2、提取公共代码,便于维护。 - * 3、行为由父类控制,子类实现。 - * 缺点:每一个不同的实现都需要一个子类来实现,导致类的个数增加,使得系统更加庞大。 - * 使用场景: - * 1、有多个子类共有的方法,且逻辑相同。 - * 2、重要的、复杂的方法,可以考虑作为模板方法。 - * 注意事项:为防止恶意操作,一般模板方法都加上 final 关键词。 - * - */ - - } - -} - - - -//定义一个玩游戏的步骤 -abstract class Game{ - - //启动游戏 - protected abstract void runGame(); - //选择人物 - protected void choosePerson() {}; - //开始玩游戏 - protected abstract void startPlayGame(); - //结束游戏 - protected abstract void endPlayGame(); - - //模板方法 - public final void play() { - runGame(); - choosePerson(); - startPlayGame(); - endPlayGame(); - } - -} - -//魂斗罗游戏 -class ContraGame extends Game{ - - @Override - protected void runGame() { - System.out.println("启动魂斗罗II..."); - } - - @Override - protected void startPlayGame() { - System.out.println("1P正在使用S弹打aircraft..."); - } - - @Override - protected void endPlayGame() { - System.out.println("1P被流弹打死了,游戏结束!"); - } -} - -//忍者神龟游戏 -class TMNTGame extends Game{ - - @Override - protected void runGame() { - System.out.println("启动忍者神龟III..."); - } - - @Override - protected void choosePerson() { - System.out.println("1P选择了Raph !"); - } - - @Override - protected void startPlayGame() { - System.out.println("Raph正在使用绝技 “火箭头槌” "); - } - - @Override - protected void endPlayGame() { - System.out.println("Raph 掉进井盖里死了,游戏结束了! "); - } -} - diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/template/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/template/package-info.java deleted file mode 100644 index e42e3cde74..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/template/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: 模板模式 -* @Version:1.0.0 -* @author pancm -* @date 2018年8月8日 -*/ -package com.jun.plugin.design.template; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/visitor/VisitorTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/visitor/VisitorTest.java deleted file mode 100644 index 084d5c410a..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/visitor/VisitorTest.java +++ /dev/null @@ -1,150 +0,0 @@ -package com.jun.plugin.design.visitor; - -import java.util.ArrayList; -import java.util.List; - -/** - * @Title: VisitorTest - * @Description: 访问者模式 - * 访问者模式(VisitorPattern)是对象的行为模式。访问者模式的目的是封装一些施加于某种数据结构元素之上的操作。一旦这些操作需要修改的话,接受这个操作的数据结构则可以保持不变。 - * 核心:主要将数据结构与数据操作分离。 - * @Version:1.0.0 - * @author pancm - * @date 2018年8月8日 - */ -public class VisitorTest { - - public static void main(String[] args) { - - /* - * 基本角色: 1 抽象访问者(Visitor)角色:声明了一个或者多个方法操作,形成所有的具体访问者角色必须实现的接口。 - * - * 2 具体访问者(ConcreteVisitor)角色:实现抽象访问者所声明的接口,也就是抽象访问者所声明的各个访问操作。 - * - * 3 抽象节点(Node)角色:声明一个接受操作,接受一个访问者对象作为一个参数。 - * - * 4 具体节点(ConcreteNode)角色:实现了抽象节点所规定的接受操作。 - * - * 5 结构对象(ObjectStructure)角色:有如下的责任,可以遍历结构中的所有元素;如果需要,提供一个高层次的接口让访问者对象可以访问每一个元素; - - * - */ - - // 创建一个结构对象 - ObjectStructure os = new ObjectStructure(); - // 给结构增加一个节点 - os.add(new Games()); - // 给结构增加一个节点 - os.add(new Photos()); - // 创建一个访问者 - Visitor visitor = new ZhangSan(); - os.action(visitor); - - /* - * 优点: 1、扩展性好,可以在不修改对象结构中的元素的情况下,为对象结构中的元素添加新的功能。 - * 2、符合单一职责原则,通过访问者将无关的行为分离,使职责单一。 - * - * 缺点: 1、违反了迪米特原则,因为具体元素对访问者公布细节。 2、违反了依赖倒置原则,依赖了具体类,没有依赖抽象。 - * 3、对象结构变化困难,若对象结构发生了改变,访问者的接口和访问者的实现也都要发生相应的改变。 - * - * - * 使用场景: 1、对象结构中对象对应的类很少改变,但经常需要在此对象结构上定义新的操作。 - * 2、需要对一个对象结构中的对象进行很多不同的并且不相关的操作,而需要避免让这些操作"污染"这些对象的类,也不希望在增加新操作时修改这些类。 - * 注意事项:访问者可以对功能进行统一,可以做报表、UI、拦截器与过滤器。 - * - */ - } - -} - -/* - * 定义一个抽象的角色(游客) - */ -interface Visitor { - // 可以玩游戏 - void visit(Games games); - - // 可以查看图片 - void visit(Photos photos); -} - -class ZhangSan implements Visitor { - @Override - public void visit(Games games) { - games.play(); - } - - @Override - public void visit(Photos photos) { - photos.watch(); - } -} - -/* - * - */ -class LiSi implements Visitor { - @Override - public void visit(Games games) { - games.play(); - } - - @Override - public void visit(Photos photos) { - photos.watch(); - } -} - -/* - * 定义个接受者 - */ -interface Computer { - void accept(Visitor visitor); -} - -class Games implements Computer { - @Override - public void accept(Visitor visitor) { - visitor.visit(this); - } - - public void play() { - System.out.println("play lol"); - } -} - -class Photos implements Computer { - @Override - public void accept(Visitor visitor) { - visitor.visit(this); - } - - public void watch() { - System.out.println("watch scenery photo"); - } -} - -/* - * 结构对象角色 - */ -class ObjectStructure { - - private List computers = new ArrayList(); - - /** - * 执行方法操作 - */ - public void action(Visitor visitor) { - computers.forEach(c -> { - c.accept(visitor); - }); - - } - - /** - * 添加一个新元素 - */ - public void add(Computer computer) { - computers.add(computer); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/visitor/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/visitor/package-info.java deleted file mode 100644 index 4e15ba9ef5..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/design/visitor/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: 访问者模式 -* @Version:1.0.0 -* @author pancm -* @date 2018年8月8日 -*/ -package com.jun.plugin.design.visitor; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/dynamicProxy/app/MainTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/dynamicProxy/app/MainTest.java deleted file mode 100644 index 2d3ac08703..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/dynamicProxy/app/MainTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.jun.plugin.dynamicProxy.app; - -import java.lang.reflect.Proxy; - -import com.jun.plugin.dynamicProxy.bean.LogHandler; -import com.jun.plugin.dynamicProxy.bean.LogInterceptor; -import com.jun.plugin.dynamicProxy.bean.Manager; -import com.jun.plugin.dynamicProxy.bean.Student; -import com.jun.plugin.dynamicProxy.bean.SubStudent; -import com.jun.plugin.dynamicProxy.bean.SumTeacher; -import com.jun.plugin.dynamicProxy.bean.Teacher; -import com.jun.plugin.dynamicProxy.preson.Preson; -import com.jun.plugin.dynamicProxy.proxy.CglibProxy; -import com.jun.plugin.dynamicProxy.proxy.JdkProxy; - -import net.sf.cglib.proxy.Enhancer; - -public class MainTest { - - public static void main(String[] args) { - //静态代理 - Preson p = new Student(); - Preson p1 = new SubStudent(); - Preson p2 = new Teacher(); - Preson p3 = new SumTeacher(new Teacher()); - Preson p4 = new SumTeacher(new Student()); - - p.goToSchool(); - p1.goToSchool(); - p2.goToSchool(); - p3.goToSchool(); - p4.goToSchool(); - - System.out.println("===========jdk动态代理============"); - //jdk实现 - Student s = new Student(); - LogHandler logHandler = new LogHandler(s); - Class sc = s.getClass(); - Preson proxyStudent = (Preson) Proxy.newProxyInstance(sc.getClassLoader(),sc.getInterfaces(), logHandler); - proxyStudent.goToSchool(); - //实现方法2 - Preson stu = (Preson) new JdkProxy().getInstance(new Student()); - stu.goToSchool(); - - System.out.println("===========cglib动态代理============"); - - //cglib实现动态代理,需提前导入cglib jar包 - //Enhancer是CGLib的字节码增强器,可以方便的对类进行扩展,内部调用GeneratorStrategy.generate方法生成代理类的字节码,通过以下方式可以生成class文件。 - Enhancer enhancer = new Enhancer(); - //继承代理类 - enhancer.setSuperclass(Manager.class); - enhancer.setCallback(new LogInterceptor()); - //通过字节码技术动态创建子类实例 - Manager m = (Manager) enhancer.create(); - m.goToSchool(); - //实现方法2 - Manager instance = (Manager) new CglibProxy().getInstance(new Manager()); - instance.goToSchool(); - - } - - - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/dynamicProxy/bean/Manager.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/dynamicProxy/bean/Manager.java deleted file mode 100644 index 6fdc8210db..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/dynamicProxy/bean/Manager.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.jun.plugin.dynamicProxy.bean; - - -public class Manager { - public void goToSchool() { - - System.out.println("我是现在,住在学校"); - - } - - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/dynamicProxy/bean/Student.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/dynamicProxy/bean/Student.java deleted file mode 100644 index 7e6e75ec83..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/dynamicProxy/bean/Student.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.jun.plugin.dynamicProxy.bean; - -import com.jun.plugin.dynamicProxy.preson.Preson; - -public class Student implements Preson { - private String name; - public Student() { - super(); - // TODO Auto-generated constructor stub - } - - - public Student(String name) { - super(); - this.name = name; - } - - - @Override - public void goToSchool() { - - System.out.println("坐车去学校"); - - } - - @Override - public void eat() { - - System.out.println(name+"我吃大饭堂,好难吃!"); - - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/dynamicProxy/bean/Teacher.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/dynamicProxy/bean/Teacher.java deleted file mode 100644 index d2b8178329..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/dynamicProxy/bean/Teacher.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jun.plugin.dynamicProxy.bean; - -import com.jun.plugin.dynamicProxy.preson.Preson; - -public class Teacher implements Preson { - - @Override - public void goToSchool() { - - System.out.println("开车去学校"); - - } - - @Override - public void eat() { - - System.out.println("我吃小堂,味道还不错哦"); - - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/dynamicProxy/preson/Preson.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/dynamicProxy/preson/Preson.java deleted file mode 100644 index 99142454e8..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/dynamicProxy/preson/Preson.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.jun.plugin.dynamicProxy.preson; - -public interface Preson { - public void goToSchool(); - public void eat(); -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/elasticsearch/EsAggregationSearchTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/elasticsearch/EsAggregationSearchTest.java deleted file mode 100644 index 5b92d5a386..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/elasticsearch/EsAggregationSearchTest.java +++ /dev/null @@ -1,482 +0,0 @@ -package com.jun.plugin.elasticsearch; - -import org.apache.http.HttpHost; -import org.elasticsearch.action.admin.indices.alias.Alias; -import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; -import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; -import org.elasticsearch.action.admin.indices.get.GetIndexRequest; -import org.elasticsearch.action.bulk.BulkRequest; -import org.elasticsearch.action.search.SearchRequest; -import org.elasticsearch.action.search.SearchResponse; -import org.elasticsearch.action.update.UpdateRequest; -import org.elasticsearch.client.RequestOptions; -import org.elasticsearch.client.RestClient; -import org.elasticsearch.client.RestClientBuilder; -import org.elasticsearch.client.RestHighLevelClient; -import org.elasticsearch.common.xcontent.XContentType; -import org.elasticsearch.rest.RestStatus; -import org.elasticsearch.search.aggregations.Aggregation; -import org.elasticsearch.search.aggregations.AggregationBuilder; -import org.elasticsearch.search.aggregations.AggregationBuilders; -import org.elasticsearch.search.aggregations.Aggregations; -import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval; -import org.elasticsearch.search.aggregations.bucket.terms.Terms; -import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder; -import org.elasticsearch.search.aggregations.metrics.avg.Avg; -import org.elasticsearch.search.aggregations.metrics.max.Max; -import org.elasticsearch.search.aggregations.metrics.min.Min; -import org.elasticsearch.search.aggregations.metrics.sum.Sum; -import org.elasticsearch.search.aggregations.metrics.tophits.TopHits; -import org.elasticsearch.search.builder.SearchSourceBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.BeanUtils; - -import java.io.IOException; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * @author pancm - * @Title: pancm_project - * @Description:ES聚合查询测试用例 - * @Version:1.0.0 - * @Since:jdk1.8 - * @date 2019/4/2 - */ -public class EsAggregationSearchTest { - - - - private static String elasticIp = "192.169.0.23"; - private static int elasticPort = 9200; - private static Logger logger = LoggerFactory.getLogger(EsHighLevelRestSearchTest.class); - - private static RestHighLevelClient client = null; - - /** - * @param args - */ - public static void main(String[] args) { - - try { - init(); - createIndex(); - bulk(); - groupbySearch(); - avgSearch(); - maxSearch(); - sumSearch(); - avgGroupSearch(); - maxGroupSearch(); - sumGroupSearch(); - topSearch(); - } catch (Exception e) { - e.printStackTrace(); - }finally { - close(); - } - - } - - - /* - * 初始化服务 - */ - private static void init() { - RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(elasticIp, elasticPort)); - client = new RestHighLevelClient(restClientBuilder); - } - - /* - * 关闭服务 - */ - private static void close() { - if (client != null) { - try { - client.close(); - } catch (IOException e) { - e.printStackTrace(); - }finally{ - client=null; - } - } - } - - /** - * 创建索引 - * - * @throws IOException - */ - private static void createIndex() throws IOException { - - // 类型 - String type = "_doc"; - String index = "student"; - // setting 的值 - Map setmapping = new HashMap<>(); - // 分区数、副本数、缓存刷新时间 - setmapping.put("number_of_shards", 10); - setmapping.put("number_of_replicas", 1); - setmapping.put("refresh_interval", "5s"); - Map keyword = new HashMap<>(); - //设置类型 - keyword.put("type", "keyword"); - Map lon = new HashMap<>(); - //设置类型 - lon.put("type", "long"); - Map date = new HashMap<>(); - //设置类型 - date.put("type", "date"); - date.put("format", "yyyy-MM-dd"); - - Map date2 = new HashMap<>(); - //设置类型 - date2.put("type", "date"); - date2.put("format", "yyyy-MM-dd HH:mm:ss.SSS"); - Map jsonMap2 = new HashMap<>(); - Map properties = new HashMap<>(); - //设置字段message信息 - properties.put("uid", lon); - properties.put("grade", lon); - properties.put("class", lon); - properties.put("age", lon); - properties.put("name", keyword); - properties.put("createtm", date); - properties.put("updatetm", date2); - Map mapping = new HashMap<>(); - mapping.put("properties", properties); - jsonMap2.put(type, mapping); - - GetIndexRequest getRequest = new GetIndexRequest(); - getRequest.indices(index); - getRequest.types(type); - getRequest.local(false); - getRequest.humanReadable(true); - boolean exists2 = client.indices().exists(getRequest, RequestOptions.DEFAULT); - //如果存在就不创建了 - if(exists2) { - System.out.println(index+"索引库已经存在!"); - return; - } - // 开始创建库 - CreateIndexRequest request = new CreateIndexRequest(index); - try { - // 加载数据类型 - request.settings(setmapping); - //设置mapping参数 - request.mapping(type, jsonMap2); - //设置别名 - request.alias(new Alias("pancm_alias")); - CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT); - boolean falg = createIndexResponse.isAcknowledged(); - if(falg){ - System.out.println("创建索引库:"+index+"成功!" ); - } - } catch (IOException e) { - e.printStackTrace(); - } - - } - - - - /** - * 批量操作示例 - * - * @throws InterruptedException - */ - private static void bulk() throws IOException{ - // 类型 - String type = "_doc"; - String index = "student"; - - BulkRequest request = new BulkRequest(); - int k =10; - List> mapList = new ArrayList<>(); - LocalDateTime ldt = LocalDateTime.now(); - for (int i = 1; i <=k ; i++) { - Map map = new HashMap<>(); - map.put("uid",i); - map.put("age",i); - map.put("name","虚无境"+(i%3)); - map.put("class",i%10); - map.put("grade",400+i); - map.put("createtm",ldt.plusDays(i).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); - map.put("updatetm",ldt.plusDays(i).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"))); - if(i==5){ - map.put("updatetm","2019-11-31 21:04:55.268"); - } - mapList.add(map); - } - - - for (int i = 0; i map = mapList.get(i); - String id = map.get("uid").toString(); - // 可以进行修改/删除/新增 操作 - //docAsUpsert 为true表示存在更新,不存在插入,为false表示不存在就是不做更新 - request.add(new UpdateRequest(index, type, id).doc(map, XContentType.JSON).docAsUpsert(true).retryOnConflict(5)); - } - - client.bulk(request, RequestOptions.DEFAULT); - System.out.println("批量执行成功!"); - } - - /** - * @Author pancm - * @Description 多个聚合条件测试 - * SQL: select age, name, count(*) as count1 from student group by age, name; - * @Date 2019/7/3 - * @Param [] - * @return void - **/ - private static void groupbySearch() throws IOException{ - String buk="group"; - AggregationBuilder aggregation = AggregationBuilders.terms("age").field("age"); - AggregationBuilder aggregation2 = AggregationBuilders.terms("name").field("name"); - //根据创建时间按天分组 - AggregationBuilder aggregation3 = AggregationBuilders.dateHistogram("createtm") - .field("createtm") - .format("yyyy-MM-dd") - .dateHistogramInterval(DateHistogramInterval.DAY); - - aggregation2.subAggregation(aggregation3); - aggregation.subAggregation(aggregation2); - agg(aggregation,buk); - } - - /** - * @Author pancm - * @Description 平均聚合查询测试用例 - * @Date 2019/4/1 - * @Param [] - * @return void - **/ - private static void avgSearch() throws IOException { - - String buk="t_grade_avg"; - //直接求平均数 - AggregationBuilder aggregation = AggregationBuilders.avg(buk).field("grade"); - logger.info("求班级的平均分数:"); - agg(aggregation,buk); - - } - - private static void maxSearch() throws IOException{ - String buk="t_grade"; - AggregationBuilder aggregation = AggregationBuilders.max(buk).field("grade"); - logger.info("求班级的最分数:"); - agg(aggregation,buk); - } - - private static void sumSearch() throws IOException{ - String buk="t_grade"; - AggregationBuilder aggregation = AggregationBuilders.sum(buk).field("grade"); - logger.info("求班级的总分数:"); - agg(aggregation,buk); - } - - /** - * @Author pancm - * @Description 平均聚合查询测试用例 - * @Date 2019/4/1 - * @Param [] - * @return void - **/ - private static void avgGroupSearch() throws IOException { - - - String agg="t_class_avg"; - String buk="t_grade"; - //terms 就是分组统计 根据student的grade成绩进行分组并创建一个新的聚合 - TermsAggregationBuilder aggregation = AggregationBuilders.terms(agg).field("class"); - aggregation.subAggregation(AggregationBuilders.avg(buk).field("grade")); - - logger.info("根据班级求平均分数:"); - agg(aggregation,agg,buk); - - } - - - private static void maxGroupSearch() throws IOException{ - - String agg="t_class_max"; - String buk="t_grade"; - //terms 就是分组统计 根据student的grade成绩进行分组并创建一个新的聚合 - TermsAggregationBuilder aggregation = AggregationBuilders.terms(agg).field("class"); - aggregation.subAggregation(AggregationBuilders.max(buk).field("grade")); - logger.info("根据班级求最大分数:"); - agg(aggregation,agg,buk); - } - - - private static void sumGroupSearch() throws IOException{ - String agg="t_class_sum"; - String buk="t_grade"; - //terms 就是分组统计 根据student的grade成绩进行分组并创建一个新的聚合 - TermsAggregationBuilder aggregation = AggregationBuilders.terms(agg).field("class"); - aggregation.subAggregation(AggregationBuilders.sum(buk).field("grade")); - - logger.info("根据班级求总分:"); - agg(aggregation,agg,buk); - } - - - protected static void agg(AggregationBuilder aggregation, String buk) throws IOException{ - SearchResponse searchResponse = search(aggregation); - if(RestStatus.OK.equals(searchResponse.status())) { - // 获取聚合结果 - Aggregations aggregations = searchResponse.getAggregations(); - - if(buk.contains("avg")){ - //取子聚合 - Avg ba = aggregations.get(buk); - logger.info(buk+":" + ba.getValue()); - logger.info("------------------------------------"); - }else if(buk.contains("max")){ - //取子聚合 - Max ba = aggregations.get(buk); - logger.info(buk+":" + ba.getValue()); - logger.info("------------------------------------"); - - }else if(buk.contains("min")){ - //取子聚合 - Min ba = aggregations.get(buk); - logger.info(buk+":" + ba.getValue()); - logger.info("------------------------------------"); - }else if(buk.contains("sum")){ - //取子聚合 - Sum ba = aggregations.get(buk); - logger.info(buk+":" + ba.getValue()); - logger.info("------------------------------------"); - }else if(buk.contains("top")){ - //取子聚合TopHits - TopHits ba = aggregations.get(buk); - logger.info(buk+":" + ba.getHits().totalHits); - logger.info("------------------------------------"); - }else if (buk.contains("group")){ - Map map = new HashMap<>(); - List> list = new ArrayList<>(); - agg(map,list,aggregations); - logger.info("聚合查询结果:"+list); - logger.info("------------------------------------"); - } - - } - } - - private static void agg(Map map, List> list, Aggregations aggregations) { - aggregations.forEach(aggregation -> { - String name = aggregation.getName(); - Terms genders = aggregations.get(name); - for (Terms.Bucket entry : genders.getBuckets()) { - String key = entry.getKey().toString(); - long t = entry.getDocCount(); - map.put(name,key); - map.put(name+"_"+"count",t); - - //判断里面是否还有嵌套的数据 - List list2 = entry.getAggregations().asList(); - if (list2.isEmpty()) { - Map map2 = new HashMap<>(); - BeanUtils.copyProperties(map,map2); - list.add(map2); - }else{ - agg(map, list, entry.getAggregations()); - } - } - }); - } - - - - private static SearchResponse search(AggregationBuilder aggregation) throws IOException { - SearchRequest searchRequest = new SearchRequest(); - searchRequest.indices("student"); - searchRequest.types("_doc"); - SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); - //不需要解释 - searchSourceBuilder.explain(false); - //不需要原始数据 - searchSourceBuilder.fetchSource(false); - //不需要版本号 - searchSourceBuilder.version(false); - searchSourceBuilder.aggregation(aggregation); - logger.info("查询的语句:"+searchSourceBuilder.toString()); - searchRequest.source(searchSourceBuilder); - // 同步查询 - SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); - return searchResponse; - } - - /** - * @Author pancm - * @Description 进行聚合 - * @Date 2019/4/2 - * @Param [] - * @return void - **/ - protected static void agg(AggregationBuilder aggregation, String agg, String buk) throws IOException{ - - // 同步查询 - SearchResponse searchResponse = search(aggregation); - - //4、处理响应 - //搜索结果状态信息 - if(RestStatus.OK.equals(searchResponse.status())) { - // 获取聚合结果 - Aggregations aggregations = searchResponse.getAggregations(); - - - //分组 - Terms byAgeAggregation = aggregations.get(agg); - logger.info(agg+" 结果"); - logger.info("name: " + byAgeAggregation.getName()); - logger.info("type: " + byAgeAggregation.getType()); - logger.info("sumOfOtherDocCounts: " + byAgeAggregation.getSumOfOtherDocCounts()); - - logger.info("------------------------------------"); - for(Terms.Bucket buck : byAgeAggregation.getBuckets()) { - logger.info("key: " + buck.getKeyAsNumber()); - logger.info("docCount: " + buck.getDocCount()); - logger.info("docCountError: " + buck.getDocCountError()); - - - if(agg.contains("avg")){ - //取子聚合 - Avg ba = buck.getAggregations().get(buk); - logger.info(buk+":" + ba.getValue()); - logger.info("------------------------------------"); - }else if(agg.contains("max")){ - //取子聚合 - Max ba = buck.getAggregations().get(buk); - logger.info(buk+":" + ba.getValue()); - logger.info("------------------------------------"); - - }else if(agg.contains("min")){ - //取子聚合 - Min ba = buck.getAggregations().get(buk); - logger.info(buk+":" + ba.getValue()); - logger.info("------------------------------------"); - }else if(agg.contains("sum")){ - //取子聚合 - Sum ba = buck.getAggregations().get(buk); - logger.info(buk+":" + ba.getValue()); - logger.info("------------------------------------"); - } - } - } - } - - private static void topSearch() throws IOException{ - - - } - - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/elasticsearch/EsHighLevelRestSearchTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/elasticsearch/EsHighLevelRestSearchTest.java deleted file mode 100644 index 55d521d787..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/elasticsearch/EsHighLevelRestSearchTest.java +++ /dev/null @@ -1,613 +0,0 @@ -package com.jun.plugin.elasticsearch; - -import org.apache.http.HttpHost; -import org.elasticsearch.action.search.SearchRequest; -import org.elasticsearch.action.search.SearchResponse; -import org.elasticsearch.action.search.ShardSearchFailure; -import org.elasticsearch.action.support.IndicesOptions; -import org.elasticsearch.client.RequestOptions; -import org.elasticsearch.client.RestClient; -import org.elasticsearch.client.RestClientBuilder; -import org.elasticsearch.client.RestHighLevelClient; -import org.elasticsearch.common.unit.Fuzziness; -import org.elasticsearch.common.unit.TimeValue; -import org.elasticsearch.index.query.BoolQueryBuilder; -import org.elasticsearch.index.query.MatchQueryBuilder; -import org.elasticsearch.index.query.QueryBuilders; -import org.elasticsearch.rest.RestStatus; -import org.elasticsearch.search.SearchHits; -import org.elasticsearch.search.aggregations.Aggregation; -import org.elasticsearch.search.aggregations.AggregationBuilders; -import org.elasticsearch.search.aggregations.Aggregations; -import org.elasticsearch.search.aggregations.bucket.terms.Terms; -import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket; -import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder; -import org.elasticsearch.search.aggregations.metrics.avg.Avg; -import org.elasticsearch.search.builder.SearchSourceBuilder; -import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder; -import org.elasticsearch.search.suggest.Suggest; -import org.elasticsearch.search.suggest.SuggestBuilder; -import org.elasticsearch.search.suggest.SuggestBuilders; -import org.elasticsearch.search.suggest.SuggestionBuilder; -import org.elasticsearch.search.suggest.term.TermSuggestion; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.TimeUnit; - - -/** - * @author pancm - * @Title: EsHighLevelRestSearchTest - * @Description: Java High Level REST Client Es高级客户端查询使用使用教程 (Search查询使用教程) - * 官方文档地址: - * https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high.html - * @Version:1.0.0 - * @date 2019年3月12日 - */ -public class EsHighLevelRestSearchTest { - - private static String elasticIp = "192.169.0.23"; - private static int elasticPort = 9200; - private static Logger logger = LoggerFactory.getLogger(EsHighLevelRestSearchTest.class); - - private static RestHighLevelClient client = null; - - /** - * @param args - */ - public static void main(String[] args) { - - try { - init(); - allSearch(); - //普通查询 - genSearch(); - orSearch(); - likeSearch(); -// inSearch(); - existSearch(); - rangeSearch(); - regexpSearch(); - boolSearch(); -// search(); -// search2(); - - } catch (Exception e) { - e.printStackTrace(); - } finally { - close(); - } - - /** - * test1 - *{ - * "settings" : { - * "number_of_shards" : 10, - * "refresh_interval" : "1s" - * }, - * "mappings" : { - * "_doc" : { - * "properties" : { - * "uid" : { "type" : "long" }, - * "phone" : { "type" : "long" }, - * "userid" : { "type" : "keyword" }, - * - * "message" : { "type" : "keyword" }, - * "msgcode" : { "type" : "long" }, - * "price" : { "type" : "double","index": "false" }, - * "sendtime" : { - * "type" : "date", - * "format" : "yyyy-MM-dd HH:mm:ss.SSS" - * }, - * "sendtime2" : { - * "type" : "date", - * "format" : "yyyy-MM-dd HH:mm:ss.SSS" - * }, - * "sendtm" : { "type" : "long" }, - * "sendtm2" : { "type" : "long" } - * } - * } - * } - * } - */ - - } - - - /** - * @Author pancm - * @Description 组合查询 - * @Date 2019/9/30 - * @Param [] - * @return void - **/ - private static void boolSearch() throws IOException{ - String type = "_doc"; - String index = "test1"; - // 查询指定的索引库 - SearchRequest searchRequest = new SearchRequest(index); - searchRequest.types(type); - SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); - BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder(); - boolQueryBuilder.must(QueryBuilders.termQuery("uid",12345)); - boolQueryBuilder.must(QueryBuilders.termQuery("msgcode",1)); - // 设置查询条件 - sourceBuilder.query(boolQueryBuilder); - searchRequest.source(sourceBuilder); - System.out.println("组合查询的DSL语句:"+sourceBuilder.toString()); - // 同步查询 - SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); - // 结果 - searchResponse.getHits().forEach(hit -> { - String string = hit.getSourceAsString(); - System.out.println("组合查询的String结果:" + string); - }); - System.out.println("\n=================\n"); - } - - /** - * @Author pancm - * @Description 正则查询 - * @Date 2019/9/30 - * @Param [] - * @return void - **/ - private static void regexpSearch() throws IOException{ - String type = "_doc"; - String index = "test1"; - // 查询指定的索引库 - SearchRequest searchRequest = new SearchRequest(index); - searchRequest.types(type); - SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); - // 设置查询条件 - sourceBuilder.query(QueryBuilders.regexpQuery("message","xu[0-9]")); - searchRequest.source(sourceBuilder); - System.out.println("正则查询的DSL语句:"+sourceBuilder.toString()); - // 同步查询 - SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); - // 结果 - searchResponse.getHits().forEach(hit -> { - Map map = hit.getSourceAsMap(); - String string = hit.getSourceAsString(); - System.out.println("正则查询的Map结果:" + map); - System.out.println("正则查询的String结果:" + string); - }); - - System.out.println("\n=================\n"); - } - - /** - * @Author pancm - * @Description 范围查询 - * @Date 2019/9/30 - * @Param [] - * @return void - **/ - private static void rangeSearch() throws IOException{ - String type = "_doc"; - String index = "test1"; - SearchRequest searchRequest = new SearchRequest(index); - searchRequest.types(type); - SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); - - // 设置查询条件 - sourceBuilder.query(QueryBuilders.rangeQuery("sendtime").gte("2019-01-01 00:00:00").lte("2019-12-31 23:59:59")); - searchRequest.source(sourceBuilder); - System.out.println("范围查询的DSL语句:"+sourceBuilder.toString()); - // 同步查询 - SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); - // 结果 - searchResponse.getHits().forEach(hit -> { - String string = hit.getSourceAsString(); - System.out.println("范围查询的String结果:" + string); - }); - System.out.println("\n=================\n"); - } - - /** - * @return void - * @Author pancm - * @Description exist查询 - * @Date 2019/9/17 - * @Param [] - **/ - private static void existSearch() throws IOException { - String type = "_doc"; - String index = "test1"; - // 查询指定的索引库 - SearchRequest searchRequest = new SearchRequest(index); - searchRequest.types(type); - SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); - - // 设置查询条件 - sourceBuilder.query(QueryBuilders.existsQuery("msgcode")); - searchRequest.source(sourceBuilder); - System.out.println("存在查询的DSL语句:"+sourceBuilder.toString()); - // 同步查询 - SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); - // 结果 - searchResponse.getHits().forEach(hit -> { - Map map = hit.getSourceAsMap(); - String string = hit.getSourceAsString(); - System.out.println("存在查询的Map结果:" + map); - System.out.println("存在查询的String结果:" + string); - }); - System.out.println("\n=================\n"); - } - - /** - * @return void - * @Author pancm - * @Description in查询 - * @Date 2019/9/16 - * @Param [] - **/ - private static void inSearch() throws IOException { - String type = "_doc"; - String index = "test1"; - // 查询指定的索引库 - SearchRequest searchRequest = new SearchRequest(index,type); - SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); - /** - * SELECT * FROM p_test where uid in (1,2) - * */ - // 设置查询条件 -// sourceBuilder.query(QueryBuilders.termsQuery("uid", 1, 2)); - searchRequest.source(sourceBuilder); - System.out.println("in查询的DSL语句:"+sourceBuilder.toString()); - // 同步查询 - SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); - // 结果 - searchResponse.getHits().forEach(hit -> { - Map map = hit.getSourceAsMap(); - String string = hit.getSourceAsString(); - System.out.println("in查询的Map结果:" + map); - System.out.println("in查询的String结果:" + string); - }); - - System.out.println("\n=================\n"); - } - - /** - * @return void - * @Author pancm - * @Description 模糊查询 - * @Date 2019/9/12 - * @Param [] - **/ - private static void likeSearch() throws IOException { - String type = "_doc"; - String index = "test1"; - SearchRequest searchRequest = new SearchRequest(); - searchRequest.indices(index); - searchRequest.types(type); - SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); - BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder(); - /** - * SELECT * FROM p_test where message like '%xu%'; - * */ - boolQueryBuilder.must(QueryBuilders.wildcardQuery("message", "*xu*")); - searchSourceBuilder.query(boolQueryBuilder); - System.out.println("模糊查询语句:" + searchSourceBuilder.toString()); - searchRequest.source(searchSourceBuilder); - // 同步查询 - SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); - searchResponse.getHits().forEach(documentFields -> { - System.out.println("模糊查询结果:" + documentFields.getSourceAsMap()); - }); - System.out.println("\n=================\n"); - } - - - /** - * @return void - * @Author pancm - * @Description 普通查询 - * @Date 2019/9/12 - * @Param [] - **/ - private static void genSearch() throws IOException { - String type = "_doc"; - String index = "test1"; - // 查询指定的索引库 - SearchRequest searchRequest = new SearchRequest(index); - searchRequest.types(type); - SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); - // 设置查询条件 - sourceBuilder.query(QueryBuilders.termQuery("uid", "1234")); - // 设置起止和结束 - sourceBuilder.from(0); - sourceBuilder.size(5); - sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS)); - // 设置路由 -// searchRequest.routing("routing"); - // 设置索引库表达式 - searchRequest.indicesOptions(IndicesOptions.lenientExpandOpen()); - // 查询选择本地分片,默认是集群分片 - searchRequest.preference("_local"); - - // 排序 - // 根据默认值进行降序排序 -// sourceBuilder.sort(new ScoreSortBuilder().order(SortOrder.DESC)); - // 根据字段进行升序排序 -// sourceBuilder.sort(new FieldSortBuilder("id").order(SortOrder.ASC)); - - // 关闭suorce查询 -// sourceBuilder.fetchSource(false); - - String[] includeFields = new String[]{"title", "user", "innerObject.*"}; - String[] excludeFields = new String[]{"_type"}; - // 包含或排除字段 -// sourceBuilder.fetchSource(includeFields, excludeFields); - - searchRequest.source(sourceBuilder); - System.out.println("普通查询的DSL语句:"+sourceBuilder.toString()); - // 同步查询 - SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); - - // HTTP状态代码、执行时间或请求是否提前终止或超时 - RestStatus status = searchResponse.status(); - TimeValue took = searchResponse.getTook(); - Boolean terminatedEarly = searchResponse.isTerminatedEarly(); - boolean timedOut = searchResponse.isTimedOut(); - - // 供关于受搜索影响的切分总数的统计信息,以及成功和失败的切分 - int totalShards = searchResponse.getTotalShards(); - int successfulShards = searchResponse.getSuccessfulShards(); - int failedShards = searchResponse.getFailedShards(); - // 失败的原因 - for (ShardSearchFailure failure : searchResponse.getShardFailures()) { - // failures should be handled here - } - // 结果 - searchResponse.getHits().forEach(hit -> { - Map map = hit.getSourceAsMap(); - System.out.println("普通查询的结果:" + map); - }); - System.out.println("\n=================\n"); - } - - private static void allSearch() throws IOException { - /* - * 查询集群所有的索引 - * - */ - SearchRequest searchRequestAll = new SearchRequest(); - SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); - searchSourceBuilder.query(QueryBuilders.matchAllQuery()); - searchRequestAll.source(searchSourceBuilder); - // 同步查询 - SearchResponse searchResponseAll = client.search(searchRequestAll, RequestOptions.DEFAULT); - System.out.println("所有查询总数:" + searchResponseAll.getHits().getTotalHits()); - } - - /** - * @return void - * @Author pancm - * @Description 或查询 - * @Date 2019/9/6 - * @Param [] - **/ - private static void orSearch() throws IOException { - SearchRequest searchRequest = new SearchRequest(); - searchRequest.indices("test1"); - searchRequest.types("_doc"); - SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); - BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder(); - BoolQueryBuilder boolQueryBuilder2 = new BoolQueryBuilder(); - /** - * SELECT * FROM test1 where (uid = 1234 or uid =12345) and phone = 12345678909 - * */ - boolQueryBuilder2.should(QueryBuilders.termQuery("uid", 1234)); - boolQueryBuilder2.should(QueryBuilders.termQuery("uid", 12345)); - boolQueryBuilder.must(boolQueryBuilder2); - boolQueryBuilder.must(QueryBuilders.termQuery("phone", "12345678909")); - searchSourceBuilder.query(boolQueryBuilder); - System.out.println("或查询语句:" + searchSourceBuilder.toString()); - searchRequest.source(searchSourceBuilder); - // 同步查询 - SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); - searchResponse.getHits().forEach(documentFields -> { - System.out.println("或查询结果:" + documentFields.getSourceAsMap()); - }); - System.out.println("\n=================\n"); - } - - /* - * 初始化服务 - */ - private static void init() { - RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(elasticIp, elasticPort)); - client = new RestHighLevelClient(restClientBuilder); - - } - - /* - * 关闭服务 - */ - private static void close() { - if (client != null) { - try { - client.close(); - } catch (IOException e) { - e.printStackTrace(); - } finally { - client = null; - } - } - } - - - /** - * search查询使用示例 - * - * @throws IOException - */ - private static void search() throws IOException { - - - - /* - * 全文查询使用示例 - */ - // 查询指定的索引库 - SearchRequest searchRequest = new SearchRequest("user"); - SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); - // 搜索字段user为pancm的数据 - MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("user", "pancm"); - - // 设置模糊查询 - matchQueryBuilder.fuzziness(Fuzziness.AUTO); - // 设置前缀长度 - matchQueryBuilder.prefixLength(3); - // 设置最大扩展选项来控制查询的模糊过程 - matchQueryBuilder.maxExpansions(10); - - /* - * QueryBuilder也可以 - */ - -// QueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("user", "kimchy") -// .fuzziness(Fuzziness.AUTO) -// .prefixLength(3) -// .maxExpansions(10); - - SearchSourceBuilder searchSourceBuilder2 = new SearchSourceBuilder(); - searchSourceBuilder2.query(matchQueryBuilder); - - SearchRequest searchRequest2 = new SearchRequest(); - searchRequest2.source(searchSourceBuilder2); - // 同步查询 - SearchResponse searchResponse2 = client.search(searchRequest, RequestOptions.DEFAULT); - - SearchHits hits = searchResponse2.getHits(); - //总条数和分值 - long totalHits = hits.getTotalHits(); - float maxScore = hits.getMaxScore(); - - - hits.forEach(hit -> { - - String index = hit.getIndex(); - String type = hit.getType(); - String id = hit.getId(); - float score = hit.getScore(); - - - Map sourceAsMap = hit.getSourceAsMap(); - String string = hit.getSourceAsString(); - System.out.println("Match查询的Map结果:" + sourceAsMap); - System.out.println("Match查询的String结果:" + string); - - String documentTitle = (String) sourceAsMap.get("title"); -// List users = (List) sourceAsMap.get("user"); - Map innerObject = - (Map) sourceAsMap.get("innerObject"); - }); - - - System.out.println("\n=================\n"); - - /* - * 高亮查询 - */ - - SearchSourceBuilder searchSourceBuilder3 = new SearchSourceBuilder(); - HighlightBuilder highlightBuilder = new HighlightBuilder(); - HighlightBuilder.Field highlightTitle = new HighlightBuilder.Field("title"); - // 设置字段高亮字体 - highlightTitle.highlighterType("user"); - highlightBuilder.field(highlightTitle); - HighlightBuilder.Field highlightUser = new HighlightBuilder.Field("user"); - highlightBuilder.field(highlightUser); - searchSourceBuilder3.highlighter(highlightBuilder); - - SearchRequest searchRequest3 = new SearchRequest(); - searchRequest3.source(searchSourceBuilder3); - - // 同步查询 - SearchResponse searchResponse3 = client.search(searchRequest3, RequestOptions.DEFAULT); - - searchResponse3.getHits().forEach(hit -> { - - Map map = hit.getSourceAsMap(); - String string = hit.getSourceAsString(); - System.out.println("Highlight查询的Map结果:" + map); - System.out.println("Highlight查询的String结果:" + string); - }); - - System.out.println("\n=================\n"); - - /** - * 聚合查询 - */ - - SearchSourceBuilder searchSourceBuilder4 = new SearchSourceBuilder(); - - //terms 就是分组统计 根据user进行分组并创建一个新的聚合user_ - TermsAggregationBuilder aggregation = AggregationBuilders.terms("user_").field("user"); - aggregation.subAggregation(AggregationBuilders.avg("average_age").field("age")); - searchSourceBuilder4.aggregation(aggregation); - - SearchRequest searchRequest4 = new SearchRequest(); - searchRequest4.source(searchSourceBuilder4); - - // 同步查询 - SearchResponse searchResponse4 = client.search(searchRequest4, RequestOptions.DEFAULT); - //聚合查询返回条件 - Aggregations aggregations = searchResponse4.getAggregations(); - System.out.println("聚合查询"); - for (Aggregation agg : aggregations) { - String type = agg.getType(); - String name = agg.getName(); - - Terms terms = (Terms) aggregations.get(name); - for (Bucket bucket : terms.getBuckets()) { - System.out.println("条数:" + bucket.getDocCount()); - System.out.println("key:" + bucket.getKey()); - System.out.println("num:" + bucket.getKeyAsNumber()); - Avg avg = bucket.getAggregations().get("average_age"); - System.out.println("value:" + avg.getValue()); - } - if (type.equals(TermsAggregationBuilder.NAME)) { - Bucket elasticBucket = ((Terms) agg).getBucketByKey("average_age"); - long numberOfDocs = elasticBucket.getDocCount(); - System.out.println("条数:" + numberOfDocs); - } - } - - - - - - /* - * 建议查询 - */ - SearchSourceBuilder searchSourceBuilder5 = new SearchSourceBuilder(); - SuggestionBuilder termSuggestionBuilder = SuggestBuilders.termSuggestion("user").text("pancm"); - SuggestBuilder suggestBuilder = new SuggestBuilder(); - suggestBuilder.addSuggestion("suggest_user", termSuggestionBuilder); - searchSourceBuilder5.suggest(suggestBuilder); - - SearchRequest searchRequest5 = new SearchRequest(); - searchRequest5.source(searchSourceBuilder5); - - // 同步查询 - SearchResponse searchResponse5 = client.search(searchRequest5, RequestOptions.DEFAULT); - - Suggest suggest = searchResponse5.getSuggest(); - TermSuggestion termSuggestion = suggest.getSuggestion("suggest_user"); - for (TermSuggestion.Entry entry : termSuggestion.getEntries()) { - for (TermSuggestion.Entry.Option option : entry) { - String suggestText = option.getText().string(); - System.out.println("返回结果:" + suggestText); - } - } - - } - - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/elasticsearch/EsHighLevelRestTest1.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/elasticsearch/EsHighLevelRestTest1.java deleted file mode 100644 index 6a47f6fbe0..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/elasticsearch/EsHighLevelRestTest1.java +++ /dev/null @@ -1,650 +0,0 @@ -package com.jun.plugin.elasticsearch; - -import org.apache.http.HttpHost; -import org.elasticsearch.ElasticsearchException; -import org.elasticsearch.action.ActionListener; -import org.elasticsearch.action.DocWriteRequest; -import org.elasticsearch.action.DocWriteResponse; -import org.elasticsearch.action.admin.indices.alias.Alias; -import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; -import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; -import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; -import org.elasticsearch.action.admin.indices.get.GetIndexRequest; -import org.elasticsearch.action.bulk.*; -import org.elasticsearch.action.delete.DeleteRequest; -import org.elasticsearch.action.delete.DeleteResponse; -import org.elasticsearch.action.get.GetRequest; -import org.elasticsearch.action.get.GetResponse; -import org.elasticsearch.action.index.IndexRequest; -import org.elasticsearch.action.index.IndexResponse; -import org.elasticsearch.action.support.IndicesOptions; -import org.elasticsearch.action.support.WriteRequest; -import org.elasticsearch.action.support.replication.ReplicationResponse; -import org.elasticsearch.action.update.UpdateRequest; -import org.elasticsearch.action.update.UpdateResponse; -import org.elasticsearch.client.RequestOptions; -import org.elasticsearch.client.RestClient; -import org.elasticsearch.client.RestHighLevelClient; -import org.elasticsearch.common.unit.ByteSizeUnit; -import org.elasticsearch.common.unit.ByteSizeValue; -import org.elasticsearch.common.unit.TimeValue; -import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.common.xcontent.XContentFactory; -import org.elasticsearch.common.xcontent.XContentType; -import org.elasticsearch.index.query.BoolQueryBuilder; -import org.elasticsearch.index.query.QueryBuilders; -import org.elasticsearch.index.query.TermQueryBuilder; -import org.elasticsearch.index.reindex.BulkByScrollResponse; -import org.elasticsearch.index.reindex.DeleteByQueryRequest; -import org.elasticsearch.index.reindex.ScrollableHitSource; -import org.elasticsearch.index.reindex.UpdateByQueryRequest; -import org.elasticsearch.rest.RestStatus; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import java.util.function.BiConsumer; - -/** - * @Title: EsHighLevelRestTest1 - * @Description: Java High Level REST Client Es高级客户端使用教程一 (基本CRUD使用) 官方文档地址: - * https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high.html - * @since jdk 1.8 - * @Version:1.0.0 - * @author pancm - * @date 2019年3月5日 - */ -public class EsHighLevelRestTest1 { - - private static String elasticIp = "192.169.0.23"; - private static int elasticPort = 9200; - - private static Logger logger = LoggerFactory.getLogger(EsHighLevelRestTest1.class); - - private static RestHighLevelClient client = null; - - public static void main(String[] args) { - try { - init(); - createIndex(); - insert(); - queryById(); - exists(); - update(); -// deleteByQuery(); -// deleteIndex(); -// delete(); -// bulk(); - close(); - } catch (Exception e) { - e.printStackTrace(); - } - - } - - private static void insert() throws IOException { - String index = "test1"; - String type = "_doc"; - // 唯一编号 - String id = "1"; - IndexRequest request = new IndexRequest(index, type, id); - /* - * 第一种方式,通过jsonString进行创建 - */ - // json - String jsonString = "{" + "\"uid\":\"1234\","+ "\"phone\":\"12345678909\","+ "\"msgcode\":\"1\"," + "\"sendtime\":\"2019-03-14 01:57:04\"," - + "\"message\":\"xuwujing study Elasticsearch\"" + "}"; - request.source(jsonString, XContentType.JSON); - - /* - * 第二种方式,通过map创建,,会自动转换成json的数据 - */ - Map jsonMap = new HashMap<>(); - jsonMap.put("uid", 1234); - jsonMap.put("phone", 12345678909L); - jsonMap.put("msgcode", 1); - jsonMap.put("sendtime", "2019-03-14 01:57:04"); - jsonMap.put("message", "xuwujing study Elasticsearch"); - request.source(jsonMap); - - /* - * 第三种方式 : 通过XContentBuilder对象进行创建 - */ - - XContentBuilder builder = XContentFactory.jsonBuilder(); - builder.startObject(); - { - builder.field("uid", 1234); - builder.field("phone", 12345678909L); - builder.field("msgcode", 1); - builder.timeField("sendtime", "2019-03-14 01:57:04"); - builder.field("message", "xuwujing study Elasticsearch"); - } - builder.endObject(); - request.source(builder); - - IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT); - - //如果是200则表示成功,否则就是失败 - if(200 == indexResponse.status().getStatus()){ - - } - - // 对响应结果进行处理 - String index1 = indexResponse.getIndex(); - String type1 = indexResponse.getType(); - String id1 = indexResponse.getId(); - long version = indexResponse.getVersion(); - // 如果是新增/修改的话的话 - if (indexResponse.getResult() == DocWriteResponse.Result.CREATED) { - - } else if (indexResponse.getResult() == DocWriteResponse.Result.UPDATED) { - - } - ReplicationResponse.ShardInfo shardInfo = indexResponse.getShardInfo(); - if (shardInfo.getTotal() != shardInfo.getSuccessful()) { - - } - if (shardInfo.getFailed() > 0) { - for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) { - String reason = failure.reason(); - } - } - } - - /* - * 初始化服务 - */ - private static void init() { - - client = new RestHighLevelClient(RestClient.builder(new HttpHost(elasticIp, elasticPort))); - - } - - /* - * 关闭服务 - */ - private static void close() { - if (client != null) { - try { - client.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - /** - * 创建索引 - * - * @throws IOException - */ - private static void createIndex() throws IOException { - - // 类型 - String type = "_doc"; - String index = "test1"; - // setting 的值 - Map setmapping = new HashMap<>(); - // 分区数、副本数、缓存刷新时间 - setmapping.put("number_of_shards", 10); - setmapping.put("number_of_replicas", 1); - setmapping.put("refresh_interval", "5s"); - Map keyword = new HashMap<>(); - //设置类型 - keyword.put("type", "keyword"); - Map lon = new HashMap<>(); - //设置类型 - lon.put("type", "long"); - Map date = new HashMap<>(); - //设置类型 - date.put("type", "date"); - date.put("format", "yyyy-MM-dd HH:mm:ss"); - - Map jsonMap2 = new HashMap<>(); - Map properties = new HashMap<>(); - //设置字段message信息 - properties.put("uid", lon); - properties.put("phone", lon); - properties.put("msgcode", lon); - properties.put("message", keyword); - properties.put("sendtime", date); - Map mapping = new HashMap<>(); - mapping.put("properties", properties); - jsonMap2.put(type, mapping); - - GetIndexRequest getRequest = new GetIndexRequest(); - getRequest.indices(index); - getRequest.types(type); - getRequest.local(false); - getRequest.humanReadable(true); - boolean exists2 = client.indices().exists(getRequest, RequestOptions.DEFAULT); - //如果存在就不创建了 - if(exists2) { - System.out.println(index+"索引库已经存在!"); - return; - } - // 开始创建库 - CreateIndexRequest request = new CreateIndexRequest(index); - try { - // 加载数据类型 - request.settings(setmapping); - //设置mapping参数 - request.mapping(type, jsonMap2); - //设置别名 - request.alias(new Alias("pancm_alias")); - CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT); - boolean falg = createIndexResponse.isAcknowledged(); - if(falg){ - System.out.println("创建索引库:"+index+"成功!" ); - } - } catch (IOException e) { - e.printStackTrace(); - } - - } - - - /** - * 删除索引 - * - * @throws IOException - */ - private static void deleteIndex() throws IOException { - String index = "userindex"; - DeleteIndexRequest request = new DeleteIndexRequest(index); - // 同步删除 - client.indices().delete(request,RequestOptions.DEFAULT); - System.out.println("删除索引库成功!"+index); - - } - - /** - * 查询数据 - * - * @throws IOException - */ - private static void queryById() { - String type = "_doc"; - String index = "test1"; - // 唯一编号 - String id = "1"; - // 创建查询请求 - GetRequest getRequest = new GetRequest(index, type, id); - - GetResponse getResponse = null; - try { - getResponse = client.get(getRequest, RequestOptions.DEFAULT); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (ElasticsearchException e) { - // 如果是索引不存在 - if (e.status() == RestStatus.NOT_FOUND) { - System.out.println("该索引库不存在!" + index); - } - - } - // 如果存在该数据则返回对应的结果 - if (getResponse.isExists()) { - long version = getResponse.getVersion(); - String sourceAsString = getResponse.getSourceAsString(); - Map sourceAsMap = getResponse.getSourceAsMap(); - byte[] sourceAsBytes = getResponse.getSourceAsBytes(); - System.out.println("查询返回结果String:" + sourceAsString); - System.out.println("查询返回结果Map:" + sourceAsMap); - } else { - System.out.println("没有找到该数据!"); - } - } - - /** - * 是否存在 - * - * @throws IOException - */ - private static void exists() throws IOException { - String type = "_doc"; - String index = "test1"; - // 唯一编号 - String id = "1"; - // 创建查询请求 - GetRequest getRequest = new GetRequest(index, type, id); - - - boolean exists = client.exists(getRequest, RequestOptions.DEFAULT); - - ActionListener listener = new ActionListener() { - @Override - public void onResponse(Boolean exists) { - System.out.println("==" + exists); - } - - @Override - public void onFailure(Exception e) { - System.out.println("失败的原因:" + e.getMessage()); - } - }; - // 进行异步监听 -// client.existsAsync(getRequest, RequestOptions.DEFAULT, listener); - - System.out.println("数据是否存在:" + exists); - } - - /** - * 更新操作 - * - * @throws IOException - */ - private static void update() throws IOException { - String type = "_doc"; - String index = "test1"; - // 唯一编号 - String id = "1"; - UpdateRequest upateRequest = new UpdateRequest(); - upateRequest.id(id); - upateRequest.index(index); - upateRequest.type(type); - - // 依旧可以使用Map这种集合作为更新条件 - Map jsonMap = new HashMap<>(); - jsonMap.put("uid", 12345); - jsonMap.put("phone", 123456789019L); - jsonMap.put("msgcode", 2); - jsonMap.put("sendtime", "2019-03-14 01:57:04"); - jsonMap.put("message", "xuwujing study Elasticsearch"); - upateRequest.doc(jsonMap); - // upsert 方法表示如果数据不存在,那么就新增一条 - upateRequest.docAsUpsert(true); - client.update(upateRequest, RequestOptions.DEFAULT); - System.out.println("更新成功!"); - - } - - - - /** - * 根据查询条件更新 - * - * @throws IOException - */ - private static void updateByQuery() throws IOException { - String type = "_doc"; - String index = "test1"; - // - UpdateByQueryRequest request = new UpdateByQueryRequest(index,type); - // 设置查询条件 - request.setQuery(new TermQueryBuilder("user", "pancm")); - BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder(); - - // 设置复制文档的数量 - request.setSize(10); - // 设置一次批量处理的条数,默认是1000 - request.setBatchSize(100); - //设置超时时间 - request.setTimeout(TimeValue.timeValueMinutes(2)); - //索引选项 - request.setIndicesOptions(IndicesOptions.LENIENT_EXPAND_OPEN); - - // 同步执行 - BulkByScrollResponse bulkResponse = client.updateByQuery(request, RequestOptions.DEFAULT); - - // 异步执行 -// client.updateByQueryAsync(request, RequestOptions.DEFAULT, listener); - - // 返回结果 - TimeValue timeTaken = bulkResponse.getTook(); - boolean timedOut = bulkResponse.isTimedOut(); - long totalDocs = bulkResponse.getTotal(); - long updatedDocs = bulkResponse.getUpdated(); - long deletedDocs = bulkResponse.getDeleted(); - long batches = bulkResponse.getBatches(); - long noops = bulkResponse.getNoops(); - long versionConflicts = bulkResponse.getVersionConflicts(); - long bulkRetries = bulkResponse.getBulkRetries(); - long searchRetries = bulkResponse.getSearchRetries(); - TimeValue throttledMillis = bulkResponse.getStatus().getThrottled(); - TimeValue throttledUntilMillis = bulkResponse.getStatus().getThrottledUntil(); - List searchFailures = bulkResponse.getSearchFailures(); - List bulkFailures = bulkResponse.getBulkFailures(); - System.out.println("查询更新总共花费了:" + timeTaken.getMillis() + " 毫秒,总条数:" + totalDocs + ",更新数:" + updatedDocs); - - } - - /** - * 删除 - * - * @throws IOException - * - */ - private static void delete() throws IOException { - - String type = "_doc"; - String index = "test1"; - // 唯一编号 - String id = "1"; - DeleteRequest deleteRequest = new DeleteRequest(); - deleteRequest.id(id); - deleteRequest.index(index); - deleteRequest.type(type); - // 设置超时时间 - deleteRequest.timeout(TimeValue.timeValueMinutes(2)); - // 设置刷新策略"wait_for" - // 保持此请求打开,直到刷新使此请求的内容可以搜索为止。此刷新策略与高索引和搜索吞吐量兼容,但它会导致请求等待响应,直到发生刷新 - deleteRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL); - // 同步删除 - DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT); - - /* - * 异步删除操作 - */ - - // 进行监听 - ActionListener listener = new ActionListener() { - @Override - public void onResponse(DeleteResponse deleteResponse) { - System.out.println("响应:" + deleteResponse); - } - - @Override - public void onFailure(Exception e) { - System.out.println("删除监听异常:" + e.getMessage()); - } - }; - - // 异步删除 -// client.deleteAsync(deleteRequest, RequestOptions.DEFAULT, listener); - - ReplicationResponse.ShardInfo shardInfo = deleteResponse.getShardInfo(); - // 如果处理成功碎片的数量少于总碎片的情况,说明还在处理或者处理发生异常 - if (shardInfo.getTotal() != shardInfo.getSuccessful()) { - System.out.println("需要处理的碎片总量:" + shardInfo.getTotal()); - System.out.println("处理成功的碎片总量:" + shardInfo.getSuccessful()); - } - - if (shardInfo.getFailed() > 0) { - for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) { - String reason = failure.reason(); - } - } - System.out.println("删除成功!"); - } - - - /** - * 根据查询条件删除 - * - * @throws IOException - */ - private static void deleteByQuery() throws IOException { - String type = "_doc"; - String index = "test1"; - DeleteByQueryRequest request = new DeleteByQueryRequest(index,type); - // 设置查询条件 - request.setQuery(QueryBuilders.termQuery("uid",1234)); - // 同步执行 - BulkByScrollResponse bulkResponse = client.deleteByQuery(request, RequestOptions.DEFAULT); - - // 异步执行 -// client.updateByQueryAsync(request, RequestOptions.DEFAULT, listener); - - // 返回结果 - TimeValue timeTaken = bulkResponse.getTook(); - boolean timedOut = bulkResponse.isTimedOut(); - long totalDocs = bulkResponse.getTotal(); - long updatedDocs = bulkResponse.getUpdated(); - long deletedDocs = bulkResponse.getDeleted(); - long batches = bulkResponse.getBatches(); - long noops = bulkResponse.getNoops(); - long versionConflicts = bulkResponse.getVersionConflicts(); - long bulkRetries = bulkResponse.getBulkRetries(); - long searchRetries = bulkResponse.getSearchRetries(); - TimeValue throttledMillis = bulkResponse.getStatus().getThrottled(); - TimeValue throttledUntilMillis = bulkResponse.getStatus().getThrottledUntil(); - List searchFailures = bulkResponse.getSearchFailures(); - List bulkFailures = bulkResponse.getBulkFailures(); - System.out.println("查询更新总共花费了:" + timeTaken.getMillis() + " 毫秒,总条数:" + totalDocs + ",更新数:" + updatedDocs); - - } - - /** - * 批量操作示例 - * - * @throws InterruptedException - */ - private static void bulk() throws IOException, InterruptedException { - String index = "estest"; - String type = "estest"; - - BulkRequest request = new BulkRequest(); - // 批量新增,存在会直接覆盖 - request.add(new IndexRequest(index, type, "1").source(XContentType.JSON, "field", "foo")); - request.add(new IndexRequest(index, type, "2").source(XContentType.JSON, "field", "bar")); - request.add(new IndexRequest(index, type, "3").source(XContentType.JSON, "field", "baz")); - - // 可以进行修改/删除/新增 操作 - //docAsUpsert 为true表示存在更新,不存在插入,为false表示不存在就是不做更新 - request.add(new UpdateRequest(index, type, "2").doc(XContentType.JSON, "field", "test").docAsUpsert(true)); - request.add(new DeleteRequest(index, type, "3")); - request.add(new IndexRequest(index, type, "4").source(XContentType.JSON, "field", "baz")); - - BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT); - - - ActionListener listener3 = new ActionListener() { - @Override - public void onResponse(BulkResponse response) { - System.out.println("===="+response.buildFailureMessage()); - } - - @Override - public void onFailure(Exception e) { - System.out.println("====---"+e.getMessage()); - } - }; - - client.bulkAsync(request, RequestOptions.DEFAULT,listener3); - - // 可以快速检查一个或多个操作是否失败 true是有至少一个失败! - if (bulkResponse.hasFailures()) { - System.out.println("有一个操作失败!"); - } - - // 对处理结果进行遍历操作并根据不同的操作进行处理 - for (BulkItemResponse bulkItemResponse : bulkResponse) { - DocWriteResponse itemResponse = bulkItemResponse.getResponse(); - - // 操作失败的进行处理 - if (bulkItemResponse.isFailed()) { - BulkItemResponse.Failure failure = bulkItemResponse.getFailure(); - - } - - if (bulkItemResponse.getOpType() == DocWriteRequest.OpType.INDEX - || bulkItemResponse.getOpType() == DocWriteRequest.OpType.CREATE) { - IndexResponse indexResponse = (IndexResponse) itemResponse; - System.out.println("新增失败!"+indexResponse.toString()); - - } else if (bulkItemResponse.getOpType() == DocWriteRequest.OpType.UPDATE) { - UpdateResponse updateResponse = (UpdateResponse) itemResponse; - System.out.println("更新失败!"+updateResponse.toString()); - - } else if (bulkItemResponse.getOpType() == DocWriteRequest.OpType.DELETE) { - DeleteResponse deleteResponse = (DeleteResponse) itemResponse; - System.out.println("删除失败!"+deleteResponse.toString()); - - } - } - - System.out.println("批量执行成功!"); - - /* - * 批量执行处理器相关示例代码 - */ - - // 批量处理器的监听器设置 - - BulkProcessor.Listener listener = new BulkProcessor.Listener() { - - // 在执行BulkRequest的每次执行之前调用,这个方法允许知道将要在BulkRequest中执行的操作的数量 - @Override - public void beforeBulk(long executionId, BulkRequest request) { - int numberOfActions = request.numberOfActions(); - logger.debug("Executing bulk [{}] with {} requests", executionId, numberOfActions); - } - - // 在每次执行BulkRequest之后调用,这个方法允许知道BulkResponse是否包含错误 - @Override - public void afterBulk(long executionId, BulkRequest request, BulkResponse response) { - if (response.hasFailures()) { - logger.warn("Bulk [{}] executed with failures", executionId); - } else { - logger.debug("Bulk [{}] completed in {} milliseconds", executionId, response.getTook().getMillis()); - } - } - - // 如果BulkRequest失败,则调用该方法,该方法允许知道失败 - @Override - public void afterBulk(long executionId, BulkRequest request, Throwable failure) { - logger.error("Failed to execute bulk", failure); - } - }; - - BiConsumer> bulkConsumer = (request2, bulkListener) -> client - .bulkAsync(request, RequestOptions.DEFAULT, bulkListener); - // 创建一个批量执行的处理器 - BulkProcessor bulkProcessor = BulkProcessor.builder(bulkConsumer, listener).build(); - BulkProcessor.Builder builder = BulkProcessor.builder(bulkConsumer, listener); - // 根据当前添加的操作数量设置刷新新批量请求的时间(默认为1000,使用-1禁用它) - builder.setBulkActions(500); - // 根据当前添加的操作大小设置刷新新批量请求的时间(默认为5Mb,使用-1禁用) - builder.setBulkSize(new ByteSizeValue(1L, ByteSizeUnit.MB)); - // 设置允许执行的并发请求数量(默认为1,使用0只允许执行单个请求) - builder.setConcurrentRequests(0); - // 设置刷新间隔如果间隔通过,则刷新任何挂起的BulkRequest(默认为未设置) - builder.setFlushInterval(TimeValue.timeValueSeconds(10L)); - // 设置一个常量后退策略,该策略最初等待1秒并重试最多3次。 - builder.setBackoffPolicy(BackoffPolicy.constantBackoff(TimeValue.timeValueSeconds(1L), 3)); - - IndexRequest one = new IndexRequest(index, type, "1").source(XContentType.JSON, "title", - "In which order are my Elasticsearch queries executed?"); - IndexRequest two = new IndexRequest(index, type, "2").source(XContentType.JSON, "title", - "Current status and upcoming changes in Elasticsearch"); - IndexRequest three = new IndexRequest(index, type, "3").source(XContentType.JSON, "title", - "The Future of Federated Search in Elasticsearch"); - bulkProcessor.add(one); - bulkProcessor.add(two); - bulkProcessor.add(three); - - // 如果所有大容量请求都已完成,则该方法返回true;如果在所有大容量请求完成之前的等待时间已经过去,则返回false - boolean terminated = bulkProcessor.awaitClose(30L, TimeUnit.SECONDS); - - System.out.println("请求的响应结果:" + terminated); - - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/elasticsearch/EsHighLevelRestTest2.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/elasticsearch/EsHighLevelRestTest2.java deleted file mode 100644 index ed4ce8ad83..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/elasticsearch/EsHighLevelRestTest2.java +++ /dev/null @@ -1,292 +0,0 @@ -package com.jun.plugin.elasticsearch; - -import org.apache.http.HttpHost; -import org.elasticsearch.action.ActionListener; -import org.elasticsearch.action.admin.cluster.node.tasks.list.ListTasksResponse; -import org.elasticsearch.action.bulk.BulkItemResponse; -import org.elasticsearch.action.get.GetResponse; -import org.elasticsearch.action.get.MultiGetItemResponse; -import org.elasticsearch.action.get.MultiGetRequest; -import org.elasticsearch.action.get.MultiGetResponse; -import org.elasticsearch.action.support.IndicesOptions; -import org.elasticsearch.client.RequestOptions; -import org.elasticsearch.client.RestClient; -import org.elasticsearch.client.RestHighLevelClient; -import org.elasticsearch.client.RethrottleRequest; -import org.elasticsearch.common.unit.TimeValue; -import org.elasticsearch.index.query.TermQueryBuilder; -import org.elasticsearch.index.reindex.BulkByScrollResponse; -import org.elasticsearch.index.reindex.DeleteByQueryRequest; -import org.elasticsearch.index.reindex.ReindexRequest; -import org.elasticsearch.index.reindex.ScrollableHitSource; -import org.elasticsearch.tasks.TaskId; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.List; -import java.util.Map; - -import static org.junit.Assert.assertNull; - -/** - * @Title: EsHighLevelRestTest2 - * @Description: Java High Level REST Client Es高级客户端使用教程二 (关于组合使用) - * @since jdk 1.8 - * @Version:1.0.0 - * @author pancm - * @date 2019年3月11日 - */ -public class EsHighLevelRestTest2 { - - private static String elasticIp = "192.169.0.23"; - private static int elasticPort = 9200; - - private static Logger logger = LoggerFactory.getLogger(EsHighLevelRestTest2.class); - - private static RestHighLevelClient client = null; - - /** - * @param args - */ - public static void main(String[] args) { - try { - init(); - multiGet(); - reindex(); - deleteByQuery(); - rethrottleByQuery(); - close(); - } catch (Exception e) { - e.printStackTrace(); - } - - } - - /* - * 初始化服务 - */ - private static void init() { - client = new RestHighLevelClient(RestClient.builder(new HttpHost(elasticIp, elasticPort, "http"))); - - } - - /* - * 关闭服务 - */ - private static void close() { - if (client != null) { - try { - client.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - /** - * 多查询使用 - * - * @throws IOException - */ - private static void multiGet() throws IOException { - - MultiGetRequest request = new MultiGetRequest(); - request.add(new MultiGetRequest.Item("estest", "estest", "1")); - request.add(new MultiGetRequest.Item("user", "userindex", "2")); - // 禁用源检索,默认启用 -// request.add(new MultiGetRequest.Item("user", "userindex", "2").fetchSourceContext(FetchSourceContext.DO_NOT_FETCH_SOURCE)); - - // 同步构建 - MultiGetResponse response = client.mget(request, RequestOptions.DEFAULT); - - // 异步构建 -// MultiGetResponse response2 = client.mgetAsync(request, RequestOptions.DEFAULT, listener); - - /* - * 返回的MultiGetResponse包含在' getResponses中的MultiGetItemResponse的列表,其顺序与请求它们的顺序相同。 - * 如果成功,MultiGetItemResponse包含GetResponse或MultiGetResponse。如果失败了就失败。 - * 成功看起来就像一个正常的GetResponse - */ - - for (MultiGetItemResponse item : response.getResponses()) { - assertNull(item.getFailure()); - GetResponse get = item.getResponse(); - String index = item.getIndex(); - String type = item.getType(); - String id = item.getId(); - // 如果请求存在 - if (get.isExists()) { - long version = get.getVersion(); - String sourceAsString = get.getSourceAsString(); - Map sourceAsMap = get.getSourceAsMap(); - byte[] sourceAsBytes = get.getSourceAsBytes(); - System.out.println("查询的结果:" + sourceAsMap); - } else { - System.out.println("没有找到该文档!"); - } - - } - - } - - /** - * 索引复制 - * - * @throws IOException - */ - private static void reindex() throws IOException { - // 创建索引复制请求并进行索引复制 - ReindexRequest request = new ReindexRequest(); - // 需要复制的索引 - request.setSourceIndices("user"); - // 复制的目标索引 - request.setDestIndex("dest_test"); - - // 表示如果在复制索引的时候有缺失的文档的话会进行创建,默认是index - request.setDestOpType("create"); - // 如果在复制的过程中发现版本冲突,那么会继续进行复制 - request.setConflicts("proceed"); - - // 只复制文档类型为 userindex 的数据 - request.setSourceDocTypes("userindex"); - // 只复制 pancm 用户的数据 - request.setSourceQuery(new TermQueryBuilder("user", "pancm")); - // 设置复制文档的数量 - request.setSize(10); - // 设置一次批量处理的条数,默认是1000 - request.setSourceBatchSize(100); - - // 进行排序 -// request.addSortField("postDate", SortOrder.DESC); - - // 指定切片大小 - request.setSlices(2); - - //设置超时时间 - request.setTimeout(TimeValue.timeValueMinutes(2)); - //允许刷新 - request.setRefresh(true); - - // 同步执行 - BulkByScrollResponse bulkResponse = client.reindex(request, RequestOptions.DEFAULT); - - // 异步执行 -// client.reindexAsync(request, RequestOptions.DEFAULT, listener); - - // 响应结果处理 - - TimeValue timeTaken = bulkResponse.getTook(); - boolean timedOut = bulkResponse.isTimedOut(); - long totalDocs = bulkResponse.getTotal(); - long updatedDocs = bulkResponse.getUpdated(); - long createdDocs = bulkResponse.getCreated(); - long deletedDocs = bulkResponse.getDeleted(); - long batches = bulkResponse.getBatches(); - long noops = bulkResponse.getNoops(); - long versionConflicts = bulkResponse.getVersionConflicts(); - long bulkRetries = bulkResponse.getBulkRetries(); - long searchRetries = bulkResponse.getSearchRetries(); - TimeValue throttledMillis = bulkResponse.getStatus().getThrottled(); - TimeValue throttledUntilMillis = bulkResponse.getStatus().getThrottledUntil(); - List searchFailures = bulkResponse.getSearchFailures(); - List bulkFailures = bulkResponse.getBulkFailures(); - - System.out.println("索引复制总共花费了:" + timeTaken.getMillis() + " 毫秒,总条数:" + totalDocs + ",创建数:" + createdDocs - + ",更新数:" + updatedDocs); - } - - - - - - /** - * 根据查询条件删除 - * @throws IOException - */ - private static void deleteByQuery() throws IOException { - // - DeleteByQueryRequest request = new DeleteByQueryRequest("user"); - - // 设置查询条件 - request.setQuery(new TermQueryBuilder("user", "pancm")); - - // 设置复制文档的数量 - request.setSize(10); - // 设置一次批量处理的条数,默认是1000 - request.setBatchSize(100); - //设置路由 - request.setRouting("=cat"); - //设置超时时间 - request.setTimeout(TimeValue.timeValueMinutes(2)); - //允许刷新 - request.setRefresh(true); - //索引选项 - request.setIndicesOptions(IndicesOptions.LENIENT_EXPAND_OPEN); - - // 同步执行 - BulkByScrollResponse bulkResponse = client.deleteByQuery(request, RequestOptions.DEFAULT); - - // 异步执行 -// client.updateByQueryAsync(request, RequestOptions.DEFAULT, listener); - - // 返回结果 - TimeValue timeTaken = bulkResponse.getTook(); - boolean timedOut = bulkResponse.isTimedOut(); - long totalDocs = bulkResponse.getTotal(); - long deletedDocs = bulkResponse.getDeleted(); - long batches = bulkResponse.getBatches(); - long noops = bulkResponse.getNoops(); - long versionConflicts = bulkResponse.getVersionConflicts(); - long bulkRetries = bulkResponse.getBulkRetries(); - long searchRetries = bulkResponse.getSearchRetries(); - TimeValue throttledMillis = bulkResponse.getStatus().getThrottled(); - TimeValue throttledUntilMillis = bulkResponse.getStatus().getThrottledUntil(); - List searchFailures = bulkResponse.getSearchFailures(); - List bulkFailures = bulkResponse.getBulkFailures(); - System.out.println("查询更新总共花费了:" + timeTaken.getMillis() + " 毫秒,总条数:" + totalDocs + ",删除数:" + deletedDocs); - - } - - - /** - * 用于更改正在运行的重索引、逐查询更新或逐查询删除任务的当前节流,或完全禁用任务的节流。 - * @throws IOException - */ - private static void rethrottleByQuery() throws IOException { - TaskId taskId=new TaskId("1"); - //用于更改正在运行的重索引、逐查询更新或逐查询删除任务的当前节流,或完全禁用任务的节流。 - //并且将请求将任务的节流更改为每秒100个请求 - RethrottleRequest request = new RethrottleRequest(taskId,100.0f); - - // 同步设置需要更改的流 -// client.reindexRethrottle(request, RequestOptions.DEFAULT); -// client.updateByQueryRethrottle(request, RequestOptions.DEFAULT); -// client.deleteByQueryRethrottle(request, RequestOptions.DEFAULT); - - - ActionListener listener = new ActionListener() { - @Override - public void onResponse(ListTasksResponse response) { - System.out.println("===="+response.getTasks().toString()); - } - - @Override - public void onFailure(Exception e) { - System.out.println("====---"+e.getMessage()); - } - }; - - // 异步设置要更改的流 - client.reindexRethrottleAsync(request, RequestOptions.DEFAULT, listener); - client.updateByQueryRethrottleAsync(request, RequestOptions.DEFAULT, listener); - client.deleteByQueryRethrottleAsync(request, RequestOptions.DEFAULT, listener); - - System.out.println("已成功设置!"); - - } - - - - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/elasticsearch/EsUtil.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/elasticsearch/EsUtil.java deleted file mode 100644 index 05260c64eb..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/elasticsearch/EsUtil.java +++ /dev/null @@ -1,1043 +0,0 @@ -package com.jun.plugin.elasticsearch; - - -import org.apache.http.HttpHost; -import org.elasticsearch.action.admin.indices.alias.Alias; -import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; -import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; -import org.elasticsearch.action.admin.indices.get.GetIndexRequest; -import org.elasticsearch.action.bulk.BulkRequest; -import org.elasticsearch.action.bulk.BulkResponse; -import org.elasticsearch.action.delete.DeleteRequest; -import org.elasticsearch.action.get.GetRequest; -import org.elasticsearch.action.get.GetResponse; -import org.elasticsearch.action.index.IndexRequest; -import org.elasticsearch.action.search.SearchRequest; -import org.elasticsearch.action.search.SearchResponse; -import org.elasticsearch.action.support.IndicesOptions; -import org.elasticsearch.client.RequestOptions; -import org.elasticsearch.client.RestClient; -import org.elasticsearch.client.RestClientBuilder; -import org.elasticsearch.client.RestHighLevelClient; -import org.elasticsearch.common.unit.TimeValue; -import org.elasticsearch.common.xcontent.XContentType; -import org.elasticsearch.index.query.QueryBuilder; -import org.elasticsearch.index.query.QueryBuilders; -import org.elasticsearch.index.query.TermQueryBuilder; -import org.elasticsearch.index.reindex.BulkByScrollResponse; -import org.elasticsearch.index.reindex.DeleteByQueryRequest; -import org.elasticsearch.index.reindex.ReindexRequest; -import org.elasticsearch.index.reindex.UpdateByQueryRequest; -import org.elasticsearch.search.builder.SearchSourceBuilder; -import org.elasticsearch.search.sort.FieldSortBuilder; -import org.elasticsearch.search.sort.ScoreSortBuilder; -import org.elasticsearch.search.sort.SortOrder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.io.Serializable; -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - - -/** - * @author pancm - * @Title: EsUtil - * @Description: ES的工具类 - * @Version:1.0.0 - * @date 2019年3月19日 - */ -public final class EsUtil { - private static Logger logger = LoggerFactory.getLogger(EsHighLevelRestSearchTest.class); - - private EsUtil() { - - } - - - /** - * @param args - * @throws IOException - */ - public static void main(String[] args) { - - try { - - EsUtil.build("192.169.0.23:9200"); - System.out.println("ES连接初始化成功!"); -// createIndexTest(); -// System.out.println("ES索引库创建成功!"); - String index = "student"; - String type = "_doc"; - List> list = new ArrayList<>(); - for (int i = 0; i < 10; i++) { - Map map = new HashMap<>(); - map.put("id", i); - map.put("name", "张三" + i); - map.put("age", 10 + i); - list.add(map); - } - EsUtil.setIsAutoClose(false); - saveBulk(list, index, type, "id"); - System.out.println("批量写入成功!"); - System.out.println("查询的结果1:" + queryById(index, type, "1")); - QueryBuilder queryBuilder = new TermQueryBuilder("name", "xuwujing"); - System.out.println("更新的结果:" + updateByQuery(index, type, queryBuilder)); - System.out.println("查询的结果2:" + queryById(index, type, "1")); - QueryBuilder queryBuilder3 = QueryBuilders.matchAllQuery(); - System.out.println("查询的结果3:" + query(index, type, queryBuilder3)); - QueryBuilder queryBuilder4 = QueryBuilders.rangeQuery("age").from(15); - QueryBuilder queryBuilder5 = QueryBuilders.rangeQuery("id").from(5); - System.out.println("查询的结果4:" + query(index, type, queryBuilder4,queryBuilder5)); - EsQueryCondition esQueryCondition = new EsQueryCondition(); - esQueryCondition.setCloseSource(true); - esQueryCondition.setIndex(1); - esQueryCondition.setPagesize(3); - esQueryCondition.setOrder("desc"); - esQueryCondition.setOrderField(new String[]{"age"}); - String [] incStrings = new String[]{"age","name"}; - esQueryCondition.setIncludeFields(incStrings); - esQueryCondition.setExcludeFields(new String[]{"id"}); - System.out.println("查询的结果5:" + query(index, type,esQueryCondition, queryBuilder4)); - - - // TODO: - - } catch (IOException e) { - e.printStackTrace(); - - } finally { - // TODO: handle finally clause - try { - close(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - - private static void createIndexTest() throws IOException { - // setting 的值 - Map setmapping = new HashMap<>(); - - // 分区数、路由分片数、副本数、缓存刷新时间 - setmapping.put("number_of_shards", 12); - setmapping.put("number_of_routing_shards", 24); - setmapping.put("number_of_replicas", 1); - setmapping.put("refresh_interval", "5s"); - - String index = "test5"; - String type = "test5"; - String alias = "test"; - - Map jsonMap2 = new HashMap<>(); - Map message = new HashMap<>(); - // 设置类型 - message.put("type", "text"); - Map properties = new HashMap<>(); - // 设置字段message信息 - properties.put("msg", message); - Map mapping = new HashMap<>(); - mapping.put("properties", properties); - jsonMap2.put(type, mapping); - - String mappings = jsonMap2.toString(); - - EsBasicModelConfig esBasicModelConfig = new EsBasicModelConfig(); - esBasicModelConfig.setIndex(index); - esBasicModelConfig.setType(type); - esBasicModelConfig.setMappings(mappings); - esBasicModelConfig.setSettings(setmapping); - esBasicModelConfig.setAlias(alias); - - EsUtil.creatIndex(esBasicModelConfig); - } - - - /** - * 创建链接 - * - * @param nodes - * @return - */ - public static void build(String... nodes) { - Objects.requireNonNull(nodes, "hosts can not null"); - ArrayList ahosts = new ArrayList(); - for (String host : nodes) { - IpHandler addr = new IpHandler(); - addr.IpPortFromUrl(host); - ahosts.add(new HttpHost(addr.getIp(), addr.getPort())); - } - httpHosts = ahosts.toArray(new HttpHost[0]); - init(); - } - - - /** - * @return boolean - * @Author pancm - * @Description //创建索引库(指定Mpping类型) - * @Date 2019/3/21 - * @Param [esBasicModelConfig] - **/ - public static boolean creatIndex(EsBasicModelConfig esBasicModelConfig) throws IOException { - boolean falg = true; - Objects.requireNonNull(esBasicModelConfig, "esBasicModelConfig is not null"); - String type = Objects.requireNonNull(esBasicModelConfig.getType(), "type is not null"); - String index = Objects.requireNonNull(esBasicModelConfig.getIndex(), "index is not null"); - if (exitsIndex(index)) { - logger.warn("索引库{}已经存在!无需在进行创建!", index); - return true; - } - String mapping = esBasicModelConfig.getMappings(); - Map setting = esBasicModelConfig.getSettings(); - String alias = esBasicModelConfig.getAlias(); - // 开始创建库 - CreateIndexRequest request = new CreateIndexRequest(index); - try { - if (Objects.nonNull(mapping)) { - // 加载数据类型 - request.mapping(type, mapping); - } - if (Objects.nonNull(setting)) { - // 分片数 - request.settings(setting); - } - if (Objects.nonNull(alias)) { - // 别名 - request.alias(new Alias(alias)); - } - - CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT); - falg = createIndexResponse.isAcknowledged(); - } catch (IOException e) { - throw e; - } finally { - if (isAutoClose) { - close(); - } - } - return falg; - - } - - - /** - * 判断索引库是否存在 - * - * @param index - * @return - * @throws IOException - */ - public static boolean exitsIndex(String index) throws IOException { - try { - GetIndexRequest getRequest = new GetIndexRequest(); - getRequest.indices(index); - getRequest.local(false); - getRequest.humanReadable(true); - return client.indices().exists(getRequest, RequestOptions.DEFAULT); - } finally { - if (isAutoClose) { - close(); - } - } - } - - - /** - * @return boolean - * @Author pancm - * @Description 单条新增/更新数据 - * @Date 2019/6/5 - * @Param [mapList, index, type] - **/ - public static boolean save(Map map, String index, String type) throws IOException { - List> mapList = new ArrayList<>(); - mapList.add(map); - return saveBulk(mapList, index, type, null); - } - - /** - * @return boolean - * @Author pancm - * @Description 批量新增/更新数据 - * @Date 2019/6/5 - * @Param [mapList, index, type] - **/ - public static boolean saveBulk(List> mapList, String index, String type) throws IOException { - return saveBulk(mapList, index, type, null); - } - - /** - * @return boolean - * @Author pancm - * @Description 批量新增/更新数据 - * @Date 2019/3/21 - * @Param [mapList:存储参数, index:索引库名, type:索引库类型,key:存储的主键,为空表示使用ES主键] - **/ - public static boolean saveBulk(List> mapList, String index, String type, String key) throws IOException { - - if (mapList == null || mapList.size() == 0) { - return true; - } - if (index == null || index.trim().length() == 0 || type == null || type.trim().length() == 0) { - return false; - } - try { - BulkRequest request = new BulkRequest(); - mapList.forEach(map -> { - if (key != null) { - String id = map.get(key) + ""; - if (id == null || id.trim().length() == 0) { - request.add(new IndexRequest(index, type).source(map, XContentType.JSON)); - } else { - request.add(new IndexRequest(index, type, id).source(map, XContentType.JSON)); - } - } else { - request.add(new IndexRequest(index, type).source(map, XContentType.JSON)); - } - }); - - BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT); - //说明至少有一个失败了,这里就直接返回false - if (bulkResponse.hasFailures()) { - return false; - } - - return true; - } finally { - if (isAutoClose) { - close(); - } - } - } - - - /** - * @return boolean - * @Author pancm - * @Description //删除数据 - * 根据ID进行单条删除 - * @Date 2019/3/21 - * @Param [] - **/ - public static boolean deleteById(String index, String type, String id) throws IOException { - if (index == null || type == null || id == null) { - return true; - } - try { - DeleteRequest deleteRequest = new DeleteRequest(); - deleteRequest.id(id); - deleteRequest.index(index); - deleteRequest.type(type); - // 同步删除 - client.delete(deleteRequest, RequestOptions.DEFAULT); - } finally { - if (isAutoClose) { - close(); - } - } - return true; - } - - - /** - * @return boolean - * @Author pancm - * @Description //批量删除数据 - * 根据ID进行批量删除 - * @Date 2019/3/21 - * @Param [] - **/ - public static boolean deleteByIds(String index, String type, Set ids) throws IOException { - if (index == null || type == null || ids == null) { - return true; - } - try { - BulkRequest requestBulk = new BulkRequest(); - ids.forEach(id -> { - DeleteRequest deleteRequest = new DeleteRequest(index, type, id); - requestBulk.add(deleteRequest); - }); - // 同步删除 - client.bulk(requestBulk, RequestOptions.DEFAULT); - } finally { - if (isAutoClose) { - close(); - } - } - return false; - } - - /** - * @return boolean - * @Author pancm - * @Description 根据id查询 - * @Date 2019/3/21 - * @Param [] - **/ - public static Map queryById(String index, String type, String id) throws IOException { - if (index == null || type == null) { - return null; - } - Map map = new HashMap<>(); - try { - GetRequest request = new GetRequest(); - request.index(index); - request.type(type); - request.id(id); - GetResponse getResponse = client.get(request, RequestOptions.DEFAULT); - // 如果存在该数据则返回对应的结果 - if (getResponse.isExists()) { - map = getResponse.getSourceAsMap(); - } - } finally { - if (isAutoClose) { - close(); - } - } - return map; - } - - - public static List> query(String index, String type, QueryBuilder... queryBuilders) throws IOException { - return query(index, type, null , queryBuilders); - } - - /** - * @return boolean - * @Author pancm - * @Description 根据条件查询 - * @Date 2019/3/21 - * @Param [] - **/ - public static List> query(String index, String type, EsQueryCondition esQueryCondition, QueryBuilder... queryBuilders) throws IOException { - if (index == null || type == null) { - return null; - } - List> list = new ArrayList<>(); - try { - // 查询指定的索引库 - SearchRequest searchRequest = new SearchRequest(index); - searchRequest.types(type); - SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); - - if (esQueryCondition != null) { - Integer form = esQueryCondition.getIndex(); - Integer pagesize = esQueryCondition.getPagesize(); - if (form != null && form > 0 && pagesize != null && pagesize > 0) { - form = (form - 1) * pagesize; - pagesize = form + pagesize; - // 设置起止和结束 - sourceBuilder.from(form); - sourceBuilder.size(pagesize); - } - String routing = esQueryCondition.getRouting(); - if (routing != null && routing.length() > 0) { - // 设置路由 - searchRequest.routing(routing); - } - - // 设置索引库表达式 - searchRequest.indicesOptions(IndicesOptions.lenientExpandOpen()); - - //设置排序 - String order = esQueryCondition.getOrder(); - if (order != null) { - String[] orderField = esQueryCondition.getOrderField(); - SortOrder order2 = order.equals(SortOrder.DESC) ? SortOrder.DESC : SortOrder.ASC; - //如果设置了排序字段则用排序的字段进行排序,否则就默认排序 - if (orderField != null) { - for (String field : orderField) { - sourceBuilder.sort(new FieldSortBuilder(field).order(order2)); - } - } else { - sourceBuilder.sort(new ScoreSortBuilder().order(order2)); - } - } - String[] includeFields = esQueryCondition.getIncludeFields(); - String[] excludeFields = esQueryCondition.getExcludeFields(); - if (includeFields != null && includeFields.length > 0 && excludeFields != null && excludeFields.length > 0) { - sourceBuilder.fetchSource(includeFields, excludeFields); - } - sourceBuilder.fetchSource(esQueryCondition.isCloseSource()); - } - //设置条件 - if (queryBuilders != null) { - for (QueryBuilder queryBuilder : queryBuilders) { - sourceBuilder.query(queryBuilder); - } - } - - searchRequest.source(sourceBuilder); - // 同步查询 - SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); - - if(queryBuilders != null|| (esQueryCondition != null && esQueryCondition.isQueryData())){ - // 结果 - searchResponse.getHits().forEach(hit -> { - Map map = hit.getSourceAsMap(); - list.add(map); - }); - } - - if(esQueryCondition != null && esQueryCondition.isNeedTotal()){ - Map mapTotal = new HashMap<>(); - mapTotal.put("total", searchResponse.getHits().getTotalHits()); - list.add(mapTotal); - } - - } finally { - if (isAutoClose) { - close(); - } - } - return list; - } - - - /** - * @return boolean - * @Author pancm - * @Description 根据条件更新 - * @Date 2019/3/21 - * @Param [] - **/ - public static Map updateByQuery(String index, String type, QueryBuilder... queryBuilders) throws IOException { - if (index == null || type == null) { - return null; - } - Map map = new HashMap<>(); - try { - UpdateByQueryRequest request = new UpdateByQueryRequest(); - request.indices(index); - request.setDocTypes(type); - - if (queryBuilders != null) { - for (QueryBuilder queryBuilder : queryBuilders) { - request.setQuery(queryBuilder); - } - } - // 同步执行 - BulkByScrollResponse bulkResponse = client.updateByQuery(request, RequestOptions.DEFAULT); - - // 响应结果处理 - map.put("time", bulkResponse.getTook().getMillis()); - map.put("total", bulkResponse.getTotal()); - - } finally { - if (isAutoClose) { - close(); - } - } - return map; - } - - /** - * @return Map - * @Author pancm - * @Description //根据条件删除数据 - * @Date 2019/3/21 - * @Param [] - **/ - public static Map deleteByQuery(String index, String type, QueryBuilder[] queryBuilders) throws IOException { - if (index == null || type == null || queryBuilders == null) { - return null; - } - Map map = new HashMap<>(); - try { - DeleteByQueryRequest request = new DeleteByQueryRequest(index, type); - if (queryBuilders != null) { - for (QueryBuilder queryBuilder : queryBuilders) { - request.setQuery(queryBuilder); - } - } - // 同步执行 - BulkByScrollResponse bulkResponse = client.deleteByQuery(request, RequestOptions.DEFAULT); - // 响应结果处理 - map.put("time", bulkResponse.getTook().getMillis()); - map.put("total", bulkResponse.getTotal()); - - } finally { - if (isAutoClose) { - close(); - } - } - return map; - } - - - /** - * @return Map - * @Author pancm - * @Description //重索引 - * @Date 2019/3/21 - * @Param [] - **/ - public static Map reindexByQuery(String index, String destIndex, QueryBuilder[] queryBuilders) throws IOException { - if (index == null || destIndex == null) { - return null; - } - Map map = new HashMap<>(); - try { - // 创建索引复制请求并进行索引复制 - ReindexRequest request = new ReindexRequest(); - // 需要复制的索引 - request.setSourceIndices(index); - /* 复制的目标索引 */ - request.setDestIndex(destIndex); - if (queryBuilders != null) { - for (QueryBuilder queryBuilder : queryBuilders) { - request.setSourceQuery(queryBuilder); - } - } - // 表示如果在复制索引的时候有缺失的文档的话会进行创建,默认是index - request.setDestOpType("create"); - // 如果在复制的过程中发现版本冲突,那么会继续进行复制 - request.setConflicts("proceed"); - - - // 设置复制文档的数量 - // request.setSize(10); - // 设置一次批量处理的条数,默认是1000 - // request.setSourceBatchSize(10000); - - //设置超时时间 - request.setTimeout(TimeValue.timeValueMinutes(2)); - // 同步执行 - BulkByScrollResponse bulkResponse = client.reindex(request, RequestOptions.DEFAULT); - - // 响应结果处理 - map.put("time", bulkResponse.getTook().getMillis()); - map.put("total", bulkResponse.getTotal()); - map.put("createdDocs", bulkResponse.getCreated()); - map.put("updatedDocs", bulkResponse.getUpdated()); - - } finally { - if (isAutoClose) { - close(); - } - } - return map; - } - - - /* - * 初始化服务 - */ - private static void init() { - if (client == null) { - synchronized (EsUtil.class) { - if (client == null) { - RestClientBuilder restClientBuilder = RestClient.builder(httpHosts); - client = new RestHighLevelClient(restClientBuilder); - } - } - } - - } - - /* - * 关闭服务 - */ - private static void close() throws IOException { - if (client != null) { - try { - client.close(); - setIsAutoClose(true); - } catch (IOException e) { - throw e; - } - } - } - - public static boolean isIsAutoClose() { - return isAutoClose; - } - - public static void setIsAutoClose(boolean isAutoClose) { - EsUtil.isAutoClose = isAutoClose; - } - - - private static String[] elasticIps; - private static int elasticPort; - private static HttpHost[] httpHosts; - private static volatile RestHighLevelClient client = null; - /** - * 是否自动关闭连接 - */ - private static boolean isAutoClose = true; - - private static final String COMMA_SIGN = ","; - - -} - -/** - * @Author pancm - * @Description 查询条件的类 - * @Date 2019/6/19 - * @Param - * @return - **/ -class EsQueryCondition implements Serializable { - private static final long serialVersionUID = 1L; - - /** - * 下标和条数 都为null或小于0表示不分页 - */ - private Integer index; - private Integer pagesize; - - /** - * 排序规则 asc:升序,desc:降序,为空表示不排序 - */ - private String order; - /** - * 排序字段 - */ - private String[] orderField; - - /** - * 路由 为空表示不设置 - */ - private String routing; - - /** - * 返回的字段 - */ - private String[] includeFields; - /** - * 排除的字段 - */ - private String[] excludeFields; - - /** - * 是否关闭source查询 - */ - private boolean isCloseSource; - - /** 是否需要查询数据 */ - private boolean isQueryData = true; - - /** 是否需要 返回总数 */ - private boolean isNeedTotal = true; - - - public boolean isQueryData() { - return isQueryData; - } - - public void setQueryData(boolean queryData) { - isQueryData = queryData; - } - - public boolean isNeedTotal() { - return isNeedTotal; - } - - public void setNeedTotal(boolean needTotal) { - isNeedTotal = needTotal; - } - - public boolean isCloseSource() { - return isCloseSource; - } - - public void setCloseSource(boolean closeSource) { - isCloseSource = closeSource; - } - - public String[] getIncludeFields() { - return includeFields; - } - - public void setIncludeFields(String[] includeFields) { - this.includeFields = includeFields; - } - - public String[] getExcludeFields() { - return excludeFields; - } - - public void setExcludeFields(String[] excludeFields) { - this.excludeFields = excludeFields; - } - - public Integer getIndex() { - return index; - } - - public void setIndex(Integer index) { - this.index = index; - } - - public Integer getPagesize() { - return pagesize; - } - - public void setPagesize(Integer pagesize) { - this.pagesize = pagesize; - } - - public String getOrder() { - return order; - } - - public void setOrder(String order) { - this.order = order; - } - - public String getRouting() { - return routing; - } - - public void setRouting(String routing) { - this.routing = routing; - } - - public String[] getOrderField() { - return orderField; - } - - public void setOrderField(String[] orderField) { - this.orderField = orderField; - } -} - - -/* - * ES的mapping创建的基础类 - */ -class EsBasicModelConfig implements Serializable { - private static final long serialVersionUID = 1L; - /*** 索引库 ***/ - private String index; - private String type; - private Map settings; - private String mappings; - private String alias; - - public EsBasicModelConfig() { - } - - public EsBasicModelConfig(String index, String type) { - this.index = index; - this.type = type; - } - - public String getIndex() { - return index; - } - - public void setIndex(String index) { - this.index = index; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public Map getSettings() { - return settings; - } - - public void setSettings(Map settings) { - this.settings = settings; - } - - public void setSettings(SettingEntity settings) { - this.settings = Objects.requireNonNull(settings, "setting can not null").toDSL(); - } - - public String getMappings() { - return mappings; - } - - public void setMappings(String mappings) { - this.mappings = mappings; - } - - public String getAlias() { - return alias; - } - - public void setAlias(String alias) { - this.alias = alias; - } - - @Override - public String toString() { - return "EsBasicModelConfig [index=" + index + ", type=" + type + ", settings=" + settings + ", mappings=" - + mappings + "]"; - } - -} - -/* - * setting 实体类的配置 - */ -class SettingEntity implements Serializable { - /** - * @Fields serialVersionUID : TODO - */ - private static final long serialVersionUID = 1L; - // 默认分片数 - private int numberOfShards = 5; - // 分片路由数 - private int number_of_routing_shards = 30; - // 副本数 - private int numberOfReplicas = 1; - /***** 刷新频率 单位:秒 *********/ - private int refreshInterval = 5; - /** - * 查询最大返回的时间 - */ - private int maxResultWindow = 10000; - - public SettingEntity(int numberOfShards, int numberOfReplicas, int refreshInterval) { - this.numberOfShards = numberOfShards; - this.numberOfReplicas = numberOfReplicas; - this.refreshInterval = refreshInterval; - } - - public SettingEntity(int numberOfShards, int numberOfReplicas, int refreshInterval, int number_of_routing_shards, - int maxResultWindow, String alias) { - this.numberOfShards = numberOfShards; - this.numberOfReplicas = numberOfReplicas; - this.refreshInterval = refreshInterval; - this.number_of_routing_shards = number_of_routing_shards; - this.maxResultWindow = maxResultWindow; - } - - public SettingEntity() { - - } - - public int getNumberOfShards() { - return numberOfShards; - } - - /** - * 分片数 - * - * @param numberOfShards 默认5 - */ - public void setNumberOfShards(int numberOfShards) { - this.numberOfShards = numberOfShards; - } - - public int getNumberOfReplicas() { - return numberOfReplicas; - } - - /** - * 副本数 - * - * @param numberOfReplicas 默认1 - */ - public void setNumberOfReplicas(int numberOfReplicas) { - this.numberOfReplicas = numberOfReplicas; - } - - public int getRefreshInterval() { - return refreshInterval; - } - - public int getNumber_of_routing_shards() { - return number_of_routing_shards; - } - - public void setNumber_of_routing_shards(int number_of_routing_shards) { - this.number_of_routing_shards = number_of_routing_shards; - } - - public int getMaxResultWindow() { - return maxResultWindow; - } - - public void setMaxResultWindow(int maxResultWindow) { - this.maxResultWindow = maxResultWindow; - } - - /** - * 刷新频率 单位:秒 - * - * @param refreshInterval 默认5秒 设置为-1为无限刷新 - */ - public void setRefreshInterval(int refreshInterval) { - if (refreshInterval < -1) { - refreshInterval = -1; - } - this.refreshInterval = refreshInterval; - } - - public Map toDSL() { - Map json = new HashMap<>(); - json.put("number_of_shards", numberOfShards); - json.put("number_of_routing_shards", number_of_routing_shards); - json.put("number_of_replicas", numberOfReplicas); - json.put("refresh_interval", refreshInterval + "s"); - json.put("max_result_window", maxResultWindow); - return json; - } - - @Override - public String toString() { - return "SettingEntity [numberOfShards=" + numberOfShards + ", numberOfReplicas=" + numberOfReplicas - + ", refreshInterval=" + refreshInterval + ", maxResultWindow=" + maxResultWindow + "]"; - } - -} - -class IpHandler { - - private String ip; - private Integer port; - private static Pattern p = Pattern.compile("(?<=//|)((\\w)+\\.)+\\w+(:\\d{0,5})?"); - - /** - * 冒号 - */ - private static final String COMMA_COLON = ":"; - - /** - * 从url中分析出hostIP:PORT
- * - * @param url - */ - public void IpPortFromUrl(String url) { - - String host = ""; - - Matcher matcher = p.matcher(url); - if (matcher.find()) { - host = matcher.group(); - } - // 如果 - if (host.contains(COMMA_COLON) == false) { - this.ip = host; - this.port = 80; - } else { - String[] ipPortArr = host.split(COMMA_COLON); - this.ip = ipPortArr[0]; - this.port = Integer.valueOf(ipPortArr[1].trim()); - } - } - - public String getIp() { - return ip; - } - - public Integer getPort() { - return port; - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/elasticsearch/JestTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/elasticsearch/JestTest.java deleted file mode 100644 index e361fdb10b..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/elasticsearch/JestTest.java +++ /dev/null @@ -1,370 +0,0 @@ -package com.jun.plugin.elasticsearch; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -import org.elasticsearch.index.query.QueryBuilders; -import org.elasticsearch.search.builder.SearchSourceBuilder; - -import io.searchbox.client.JestClient; -import io.searchbox.client.JestClientFactory; -import io.searchbox.client.JestResult; -import io.searchbox.client.config.HttpClientConfig; -import io.searchbox.core.Bulk; -import io.searchbox.core.BulkResult; -import io.searchbox.core.Delete; -import io.searchbox.core.DocumentResult; -import io.searchbox.core.Index; -import io.searchbox.core.Search; -import io.searchbox.indices.CreateIndex; -import io.searchbox.indices.DeleteIndex; -import io.searchbox.indices.mapping.GetMapping; -import io.searchbox.indices.mapping.PutMapping; - -/** - * -* @Title: JestTest -* @Description: es 的 Jest 测试类 -* @Version:1.0.0 -* @author pancm -* @date 2019年2月28日 - */ -public class JestTest { - private static JestClient jestClient; - private static String indexName = "userindex"; - private static String typeName = "user"; - private static String elasticIps="http://127.0.0.1:9200"; - - - public static void main(String[] args) throws Exception { - jestClient = getJestClient(); - insertBatch(); - serach1(); - serach2(); - serach3(); - jestClient.close(); - - } - - private static JestClient getJestClient() { - JestClientFactory factory = new JestClientFactory(); - factory.setHttpClientConfig(new HttpClientConfig.Builder(elasticIps).connTimeout(60000).readTimeout(60000).multiThreaded(true).build()); - return factory.getObject(); - } - - public static void insertBatch() { - List objs = new ArrayList(); - objs.add(new User(1L, "张三", 20, "张三是个Java开发工程师","2018-4-25 11:07:42")); - objs.add(new User(2L, "李四", 24, "李四是个测试工程师","1980-2-15 19:01:32")); - objs.add(new User(3L, "王五", 25, "王五是个运维工程师","2016-8-21 06:11:32")); - boolean result = false; - try { - result = insertBatch(jestClient,indexName, typeName,objs); - } catch (Exception e) { - e.printStackTrace(); - } - System.out.println("批量新增:"+result); - } - - - /** - * 全文搜索 - */ - public static void serach1() { - String query ="工程师"; - try { - SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); - searchSourceBuilder.query(QueryBuilders.queryStringQuery(query)); - //分页设置 - searchSourceBuilder.from(0).size(2); - System.out.println("全文搜索查询语句:"+searchSourceBuilder.toString()); - System.out.println("全文搜索返回结果:"+search(jestClient,indexName, typeName, searchSourceBuilder.toString())); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * 精确搜索 - */ - public static void serach2() { - try { - SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); - searchSourceBuilder.query(QueryBuilders.termQuery("age", 24)); - System.out.println("精确搜索查询语句:"+searchSourceBuilder.toString()); - System.out.println("精确搜索返回结果:"+search(jestClient,indexName, typeName, searchSourceBuilder.toString())); - } catch (Exception e) { - e.printStackTrace(); - } - } - - - /** - * 区间搜索 - */ - public static void serach3() { - String createtm="createtm"; - String from="2016-8-21 06:11:32"; - String to="2018-8-21 06:11:32"; - - try { - SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); - searchSourceBuilder.query(QueryBuilders.rangeQuery(createtm).gte(from).lte(to)); - System.out.println("区间搜索语句:"+searchSourceBuilder.toString()); - System.out.println("区间搜索返回结果:"+search(jestClient,indexName, typeName, searchSourceBuilder.toString())); - } catch (Exception e) { - e.printStackTrace(); - } - } - - - /** - * 创建索引 - * @param indexName - * @return - * @throws Exception - */ - public boolean createIndex(JestClient jestClient,String indexName) throws Exception { - JestResult jr = jestClient.execute(new CreateIndex.Builder(indexName).build()); - return jr.isSucceeded(); - } - - /** - * 新增数据 - * @param indexName - * @param typeName - * @param source - * @return - * @throws Exception - */ - public boolean insert(JestClient jestClient,String indexName, String typeName, String source) throws Exception { - PutMapping putMapping = new PutMapping.Builder(indexName, typeName, source).build(); - JestResult jr = jestClient.execute(putMapping); - return jr.isSucceeded(); - } - - - /** - * 查询数据 - * @param indexName - * @param typeName - * @return - * @throws Exception - */ - public static String getIndexMapping(JestClient jestClient,String indexName, String typeName) throws Exception { - GetMapping getMapping = new GetMapping.Builder().addIndex(indexName).addType(typeName).build(); - JestResult jr =jestClient.execute(getMapping); - return jr.getJsonString(); - } - - - - /** - * 批量新增数据 - * @param indexName - * @param typeName - * @param objs - * @return - * @throws Exception - */ - public static boolean insertBatch(JestClient jestClient,String indexName, String typeName, List objs) throws Exception { - Bulk.Builder bulk = new Bulk.Builder().defaultIndex(indexName).defaultType(typeName); - for (Object obj : objs) { - Index index = new Index.Builder(obj).build(); - bulk.addAction(index); - } - BulkResult br = jestClient.execute(bulk.build()); - return br.isSucceeded(); - } - - /** - * 全文搜索 - * @param indexName - * @param typeName - * @param query - * @return - * @throws Exception - */ - public static String search(JestClient jestClient,String indexName, String typeName, String query) throws Exception { - Search search = new Search.Builder(query) - .addIndex(indexName) - .addType(typeName) - .build(); - JestResult jr = jestClient.execute(search); -// System.out.println("--"+jr.getJsonString()); -// System.out.println("--"+jr.getSourceAsObject(User.class)); - return jr.getSourceAsString(); - } - - - - - - /** - * 删除索引 - * @param indexName - * @return - * @throws Exception - */ - public boolean delete(JestClient jestClient,String indexName) throws Exception { - JestResult jr = jestClient.execute(new DeleteIndex.Builder(indexName).build()); - return jr.isSucceeded(); - } - - /** - * 删除数据 - * @param indexName - * @param typeName - * @param id - * @return - * @throws Exception - */ - public boolean delete(JestClient jestClient,String indexName, String typeName, String id) throws Exception { - DocumentResult dr = jestClient.execute(new Delete.Builder(id).index(indexName).type(typeName).build()); - return dr.isSucceeded(); - } - -} - - - class User implements Serializable{ - /** - * - */ - private static final long serialVersionUID = 1L; - /** 编号 */ - private Long id; - /** 姓名 */ - private String name; - - /** 年龄 */ - private Integer age; - - /** 描述 */ - private String description; - - /** 创建时间 */ - private String createtm; - - - public User(){ - } - - - - - public User(Long id, String name, Integer age, String description, String createtm) { - super(); - this.id = id; - this.name = name; - this.age = age; - this.description = description; - this.createtm = createtm; - } - - - - - /** - * 获取编号 - * @return id - */ - public Long getId() { - return id; - } - - - /** - * 设置编号 - * @param Long id - */ - public void setId(Long id) { - this.id = id; - } - - - /** - * 获取姓名 - * @return name - */ - public String getName() { - return name; - } - - - /** - * 设置姓名 - * @param String name - */ - public void setName(String name) { - this.name = name; - } - - - /** - * 获取年龄 - * @return age - */ - public Integer getAge() { - return age; - } - - - /** - * 设置年龄 - * @param Integer age - */ - public void setAge(Integer age) { - this.age = age; - } - - - /** - * 获取描述 - * @return description - */ - public String getDescription() { - return description; - } - - - /** - * 设置描述 - * @param String description - */ - public void setDescription(String description) { - this.description = description; - } - - - /** - * 获取创建时间 - * @return createtm - */ - public String getCreatetm() { - return createtm; - } - - - /** - * 设置创建时间 - * @param String createtm - */ - public void setCreatetm(String createtm) { - this.createtm = createtm; - } - - - - - @Override - public String toString() { - return "User [id=" + id + ", name=" + name + ", age=" + age + ", description=" + description + ", createtm=" - + createtm + "]"; - } - - - -} - diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/elasticsearch/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/elasticsearch/package-info.java deleted file mode 100644 index 80336222a4..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/elasticsearch/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: es 相关测试类 -* @Version:1.0.0 -* @author pancm -* @date 2019年2月28日 -*/ -package com.jun.plugin.elasticsearch; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/annotation/AnnotationDefineForTestFunction.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/annotation/AnnotationDefineForTestFunction.java deleted file mode 100644 index 02394dc06e..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/annotation/AnnotationDefineForTestFunction.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.jun.plugin.javase.annotation; - -import java.lang.annotation.*; - -/** - * 定义annotation - * - */ -// 加载在VM中,在运行时进行映射 -@Retention(RetentionPolicy.RUNTIME) -// 限定此annotation只能标示方法 -@Target(ElementType.METHOD) -public @interface AnnotationDefineForTestFunction { -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/annotation/RequestForEnhancement.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/annotation/RequestForEnhancement.java deleted file mode 100644 index 0901f6dec7..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/annotation/RequestForEnhancement.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.jun.plugin.javase.annotation; - -public @interface RequestForEnhancement { - int id(); - - String synopsis(); - - String engineer() default "[unassigned]"; - - String date() default "[unimplemented]"; -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/annotation/UsingAnnotation.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/annotation/UsingAnnotation.java deleted file mode 100644 index 684ee70ff6..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/annotation/UsingAnnotation.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.jun.plugin.javase.annotation; - -import java.lang.reflect.Method; - -/** - * 一个实例程序应用前面定义的Annotation:AnnotationDefineForTestFunction - * - * @author Wujun - * - */ -public class UsingAnnotation { - @AnnotationDefineForTestFunction - public static void method01() { - } - - public static void method02() { - } - - @AnnotationDefineForTestFunction - public static void method03() { - throw new RuntimeException("method03"); - } - - public static void method04() { - throw new RuntimeException("method04"); - } - - public static void main(String[] argv) throws Exception { - int passed = 0, failed = 0; - // 被检测的类名 - String className = "com.ketayao.learn.javase.annotation.UsingAnnotation"; - // 逐个检查此类的方法,当其方法使用annotation声明时调用此方法 - for (Method m : Class.forName(className).getMethods()) { - if (m.isAnnotationPresent(AnnotationDefineForTestFunction.class)) { - try { - m.invoke(null); - passed++; - } catch (Throwable ex) { - System.out.printf("测试 %s 失败: %s %n", m, ex.getCause()); - failed++; - } - } - } - System.out.printf("测试结果:通过: %d, 失败: %d%n", passed, failed); - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/annotation/UsingBuiltInAnnotation.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/annotation/UsingBuiltInAnnotation.java deleted file mode 100644 index ca3e511724..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/annotation/UsingBuiltInAnnotation.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.jun.plugin.javase.annotation; - -import java.util.List; - -public class UsingBuiltInAnnotation { - // 食物类 - class Food { - } - - // 干草类 - class Hay extends Food { - } - - // 动物类 - class Animal { - Food getFood() { - return null; - } - - // 使用Annotation声明Deprecated方法 - @Deprecated - void deprecatedMethod() { - } - } - - // 马类-继承动物类 - class Horse extends Animal { - // 使用Annotation声明覆盖方法 - @Override - Hay getFood() { - return new Hay(); - } - - // 使用Annotation声明禁止警告 - @SuppressWarnings({ "deprecation", "unchecked" }) - void callDeprecatedMethod(List horseGroup) { - Animal an = new Animal(); - an.deprecatedMethod(); - horseGroup.add(an); - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/Action.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/Action.java deleted file mode 100644 index 2e951acb93..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/Action.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.jun.plugin.javase.enums; - -public enum Action { - TURN_LEFT, TURN_RIGHT, SHOOT -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/DetailActioin2.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/DetailActioin2.java deleted file mode 100644 index 6d7c77b530..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/DetailActioin2.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.jun.plugin.javase.enums; - -/** - * 枚举类型既然是类,那么也就可以有构造函数。只不过不得有公开(Public)的构造函数,这是为了避免直接对枚举类型实例化。 - */ -public enum DetailActioin2 { - TURN_LEFT("向左转"), TURN_RIGHT("向右转"), SHOOT("射击"); - - private String description; - - // 不公开的构造函数 - private DetailActioin2(String description) { - this.description = description; - } - - public String getDescription() { - return description; - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/DetailAction.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/DetailAction.java deleted file mode 100644 index fcde38b0ab..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/DetailAction.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.jun.plugin.javase.enums; - -/** - *定义枚举类型其实就是在定义一个类,只不过很多细节由编译器帮你补齐了,所以,某种程度上enum关键词的作用就像是class或interface. - - 当使用enum定义枚举类型时,实际上所定义出来的类型是继承自java.lang.Enum类。而每个被枚举的成员其实就是定义的枚举类型的一个实例, - 它们都被默认为final。无法改变常数名称所设定的值,它们也是public和static的成员,这与接口中的常量限制相同。可以通过类名称直接使用它们。 - 如1中所定义的枚举类型Action,TURN_LEFT,TURN_RIGHT,SHOOT都是Action的一个对象实例。因为是对象,所以,对象上自然有一些方法可以调用。 - 如从Object继承焉的toString()方法被重新定义了,可以让你直接取得枚举值的字符串描述;values()方法可以让您取得所有的枚举成员实例, - 并以数组方式返回。您可以使用这两个方法来简单的将Action的枚举成员显示出来。静态valueOf()方法可以让您将指定的字符串尝试转换为枚举类型。 - 可以用compareTo()方法来比较两个枚举对象在枚举时的顺序。-1之前,0位置相同,1之后。 - - 对于每个枚举成员,使用ordinal()方法,依枚举顺序得到位置索引,默认以0开始。 - - * @author Wujun - * @since 2013年9月9日 下午5:24:43 - */ -public enum DetailAction { - TURN_LEFT, TURN_RIGHT, SHOOT; - - public String getDescription() { - switch (this.ordinal()) { - case 0: - return "向左转"; - case 1: - return "向右转"; - case 2: - return "射击"; - default: - return null; - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/DetailActionDemo.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/DetailActionDemo.java deleted file mode 100644 index 8a656622eb..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/DetailActionDemo.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jun.plugin.javase.enums; - -public class DetailActionDemo { - public static void main(String[] args) { - for (DetailAction action : DetailAction.values()) { - System.out.printf("%s: %s%n", action, action.getDescription()); - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/EnumDemo.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/EnumDemo.java deleted file mode 100644 index 9cae1b1f43..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/EnumDemo.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jun.plugin.javase.enums; - -public class EnumDemo { - public static void main(String[] args) { - doAction(Action.TURN_RIGHT); - } - - public static void doAction(Action action) { - switch (action) { - case TURN_LEFT: - System.out.println("向左转"); - break; - case TURN_RIGHT: - System.out.println("向右转"); - break; - case SHOOT: - System.out.println("射击"); - break; - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/EnumDemo2.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/EnumDemo2.java deleted file mode 100644 index 15320607c4..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/EnumDemo2.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.jun.plugin.javase.enums; - -public class EnumDemo2 { - private enum InnerAction { - TURN_LEFT, TURN_RIGHT, SHOOT - }; - - public static void main(String[] args) { - doAction(InnerAction.TURN_RIGHT); - } - - public static void doAction(InnerAction action) { - switch (action) { - case TURN_LEFT: - System.out.println("向左转"); - break; - case TURN_RIGHT: - System.out.println("向右转"); - break; - case SHOOT: - System.out.println("射击"); - break; - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/IDescription.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/IDescription.java deleted file mode 100644 index 62a424e14a..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/IDescription.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.jun.plugin.javase.enums; - -public interface IDescription { - public String getDescription(); -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/MoreAction.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/MoreAction.java deleted file mode 100644 index 0bfd52d622..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/MoreAction.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.jun.plugin.javase.enums; - -public enum MoreAction implements IDescription { - TURN_LEFT { - // 实现接口上的方法 - public String getDescription() { - return "向左转"; - } - - }, // 注意这里的枚举值分隔使用, - - TURN_RIGHT { - // 实现接口上的方法 - public String getDescription() { - return "向右转"; - } - }, // 注意这里的枚举值分隔使用, - - SHOOT { - // 实现接口上的方法 - public String getDescription() { - return "射击"; - } - }; // 注意这里的枚举值结束使用; -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/MoreAction2.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/MoreAction2.java deleted file mode 100644 index 590d928091..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/MoreAction2.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.jun.plugin.javase.enums; - -public enum MoreAction2 { - TURN_LEFT { - // 实现抽象方法 - public String getDescription() { - return "向左转"; - } - }, // 记得这里的枚举值分隔使用, - - TURN_RIGHT { - // 实现抽象方法 - public String getDescription() { - return "向右转"; - } - }, - - SHOOT { - // 实现抽象方法 - public String getDescription() { - return "射击"; - } - }; // 记得这里的枚举值结束使用; - - // 声明抽象方法 - public abstract String getDescription(); -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/MoreActionDemo.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/MoreActionDemo.java deleted file mode 100644 index efc8dca886..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/MoreActionDemo.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jun.plugin.javase.enums; - -public class MoreActionDemo { - public static void main(String[] args) { - for (MoreAction action : MoreAction.values()) { - System.out.printf("%s: %s%n", action, action.getDescription()); - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/MoreActionDemo2.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/MoreActionDemo2.java deleted file mode 100644 index 9d234b2c04..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/MoreActionDemo2.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jun.plugin.javase.enums; - -public class MoreActionDemo2 { - public static void main(String[] args) { - for (MoreAction2 action : MoreAction2.values()) { - System.out.printf("%s: %s%n", action, action.getDescription()); - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/Singleton.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/Singleton.java deleted file mode 100644 index b395974142..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/javase/enums/Singleton.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.jun.plugin.javase.enums; - -public class Singleton { - // 构造函数私有,只限内部调用 - private Singleton() { - }; - - private static Singleton instance = null; - - public static synchronized Singleton getInstance() { - if (instance == null) - instance = new Singleton(); - return instance; - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/ActiveObject/Sample/Main.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/ActiveObject/Sample/Main.java deleted file mode 100644 index 621ba00940..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/ActiveObject/Sample/Main.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.jun.plugin.jdk.ActiveObject.Sample; - -import com.jun.plugin.jdk.ActiveObject.Sample.activeobject.ActiveObject; -import com.jun.plugin.jdk.ActiveObject.Sample.activeobject.ActiveObjectFactory; - -public class Main { - public static void main(String[] args) { - ActiveObject activeObject = ActiveObjectFactory.createActiveObject(); - new MakerClientThread("Alice", activeObject).start(); - new MakerClientThread("Bobby", activeObject).start(); - new DisplayClientThread("Chris", activeObject).start(); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/ActiveObject/Sample/activeobject/ActiveObject.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/ActiveObject/Sample/activeobject/ActiveObject.java deleted file mode 100644 index df74c40610..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/ActiveObject/Sample/activeobject/ActiveObject.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.jun.plugin.jdk.ActiveObject.Sample.activeobject; - -public interface ActiveObject { - public abstract Result makeString(int count, char fillchar); - public abstract void displayString(String string); -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/ActiveObject/Sample/activeobject/Proxy.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/ActiveObject/Sample/activeobject/Proxy.java deleted file mode 100644 index eb8f2d0d16..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/ActiveObject/Sample/activeobject/Proxy.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.jun.plugin.jdk.ActiveObject.Sample.activeobject; - -class Proxy implements ActiveObject { - private final SchedulerThread scheduler; - private final Servant servant; - public Proxy(SchedulerThread scheduler, Servant servant) { - this.scheduler = scheduler; - this.servant = servant; - } - public Result makeString(int count, char fillchar) { - FutureResult future = new FutureResult(); - scheduler.invoke(new MakeStringRequest(servant, future, count, fillchar)); - return future; - } - public void displayString(String string) { - scheduler.invoke(new DisplayStringRequest(servant, string)); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/ActiveObject/Sample/activeobject/Result.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/ActiveObject/Sample/activeobject/Result.java deleted file mode 100644 index 1e3401e095..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/ActiveObject/Sample/activeobject/Result.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.jun.plugin.jdk.ActiveObject.Sample.activeobject; - -public abstract class Result { - public abstract Object getResultValue(); -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/annotation/AnnotationDefineForTestFunction.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/annotation/AnnotationDefineForTestFunction.java deleted file mode 100644 index d08a150eef..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/annotation/AnnotationDefineForTestFunction.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.jun.plugin.jdk.annotation; - -import java.lang.annotation.*; - -/** - * 定义annotation - * - */ -// 加载在VM中,在运行时进行映射 -@Retention(RetentionPolicy.RUNTIME) -// 限定此annotation只能标示方法 -@Target(ElementType.METHOD) -public @interface AnnotationDefineForTestFunction { -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/annotation/RequestForEnhancement.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/annotation/RequestForEnhancement.java deleted file mode 100644 index 2f975e541d..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/annotation/RequestForEnhancement.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.jun.plugin.jdk.annotation; - -public @interface RequestForEnhancement { - int id(); - - String synopsis(); - - String engineer() default "[unassigned]"; - - String date() default "[unimplemented]"; -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/annotation/UsingAnnotation.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/annotation/UsingAnnotation.java deleted file mode 100644 index cec2561974..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/annotation/UsingAnnotation.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.jun.plugin.jdk.annotation; - -import java.lang.reflect.Method; - -/** - * 一个实例程序应用前面定义的Annotation:AnnotationDefineForTestFunction - * - * @author Wujun - * - */ -public class UsingAnnotation { - @AnnotationDefineForTestFunction - public static void method01() { - } - - public static void method02() { - } - - @AnnotationDefineForTestFunction - public static void method03() { - throw new RuntimeException("method03"); - } - - public static void method04() { - throw new RuntimeException("method04"); - } - - public static void main(String[] argv) throws Exception { - int passed = 0, failed = 0; - // 被检测的类名 - String className = "com.ketayao.learn.javase.annotation.UsingAnnotation"; - // 逐个检查此类的方法,当其方法使用annotation声明时调用此方法 - for (Method m : Class.forName(className).getMethods()) { - if (m.isAnnotationPresent(AnnotationDefineForTestFunction.class)) { - try { - m.invoke(null); - passed++; - } catch (Throwable ex) { - System.out.printf("测试 %s 失败: %s %n", m, ex.getCause()); - failed++; - } - } - } - System.out.printf("测试结果:通过: %d, 失败: %d%n", passed, failed); - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/annotation/UsingBuiltInAnnotation.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/annotation/UsingBuiltInAnnotation.java deleted file mode 100644 index c0fd6cedde..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/annotation/UsingBuiltInAnnotation.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.jun.plugin.jdk.annotation; - -import java.util.List; - -public class UsingBuiltInAnnotation { - // 食物类 - class Food { - } - - // 干草类 - class Hay extends Food { - } - - // 动物类 - class Animal { - Food getFood() { - return null; - } - - // 使用Annotation声明Deprecated方法 - @Deprecated - void deprecatedMethod() { - } - } - - // 马类-继承动物类 - class Horse extends Animal { - // 使用Annotation声明覆盖方法 - @Override - Hay getFood() { - return new Hay(); - } - - // 使用Annotation声明禁止警告 - @SuppressWarnings({ "deprecation", "unchecked" }) - void callDeprecatedMethod(List horseGroup) { - Animal an = new Animal(); - an.deprecatedMethod(); - horseGroup.add(an); - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/Action.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/Action.java deleted file mode 100644 index c5b5422b48..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/Action.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.jun.plugin.jdk.enums; - -public enum Action { - TURN_LEFT, TURN_RIGHT, SHOOT -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/DetailActioin2.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/DetailActioin2.java deleted file mode 100644 index f82c2cd9ba..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/DetailActioin2.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.jun.plugin.jdk.enums; - -/** - * 枚举类型既然是类,那么也就可以有构造函数。只不过不得有公开(Public)的构造函数,这是为了避免直接对枚举类型实例化。 - */ -public enum DetailActioin2 { - TURN_LEFT("向左转"), TURN_RIGHT("向右转"), SHOOT("射击"); - - private String description; - - // 不公开的构造函数 - private DetailActioin2(String description) { - this.description = description; - } - - public String getDescription() { - return description; - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/DetailAction.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/DetailAction.java deleted file mode 100644 index 6d516adae5..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/DetailAction.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.jun.plugin.jdk.enums; - -/** - *定义枚举类型其实就是在定义一个类,只不过很多细节由编译器帮你补齐了,所以,某种程度上enum关键词的作用就像是class或interface. - - 当使用enum定义枚举类型时,实际上所定义出来的类型是继承自java.lang.Enum类。而每个被枚举的成员其实就是定义的枚举类型的一个实例, - 它们都被默认为final。无法改变常数名称所设定的值,它们也是public和static的成员,这与接口中的常量限制相同。可以通过类名称直接使用它们。 - 如1中所定义的枚举类型Action,TURN_LEFT,TURN_RIGHT,SHOOT都是Action的一个对象实例。因为是对象,所以,对象上自然有一些方法可以调用。 - 如从Object继承焉的toString()方法被重新定义了,可以让你直接取得枚举值的字符串描述;values()方法可以让您取得所有的枚举成员实例, - 并以数组方式返回。您可以使用这两个方法来简单的将Action的枚举成员显示出来。静态valueOf()方法可以让您将指定的字符串尝试转换为枚举类型。 - 可以用compareTo()方法来比较两个枚举对象在枚举时的顺序。-1之前,0位置相同,1之后。 - - 对于每个枚举成员,使用ordinal()方法,依枚举顺序得到位置索引,默认以0开始。 - - * @author Wujun - * @since 2013年9月9日 下午5:24:43 - */ -public enum DetailAction { - TURN_LEFT, TURN_RIGHT, SHOOT; - - public String getDescription() { - switch (this.ordinal()) { - case 0: - return "向左转"; - case 1: - return "向右转"; - case 2: - return "射击"; - default: - return null; - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/DetailActionDemo.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/DetailActionDemo.java deleted file mode 100644 index 14cec9fd0a..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/DetailActionDemo.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jun.plugin.jdk.enums; - -public class DetailActionDemo { - public static void main(String[] args) { - for (DetailAction action : DetailAction.values()) { - System.out.printf("%s: %s%n", action, action.getDescription()); - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/EnumDemo.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/EnumDemo.java deleted file mode 100644 index 8e50c88b3b..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/EnumDemo.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jun.plugin.jdk.enums; - -public class EnumDemo { - public static void main(String[] args) { - doAction(Action.TURN_RIGHT); - } - - public static void doAction(Action action) { - switch (action) { - case TURN_LEFT: - System.out.println("向左转"); - break; - case TURN_RIGHT: - System.out.println("向右转"); - break; - case SHOOT: - System.out.println("射击"); - break; - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/EnumDemo2.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/EnumDemo2.java deleted file mode 100644 index 5d271c3d32..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/EnumDemo2.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.jun.plugin.jdk.enums; - -public class EnumDemo2 { - private enum InnerAction { - TURN_LEFT, TURN_RIGHT, SHOOT - }; - - public static void main(String[] args) { - doAction(InnerAction.TURN_RIGHT); - } - - public static void doAction(InnerAction action) { - switch (action) { - case TURN_LEFT: - System.out.println("向左转"); - break; - case TURN_RIGHT: - System.out.println("向右转"); - break; - case SHOOT: - System.out.println("射击"); - break; - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/IDescription.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/IDescription.java deleted file mode 100644 index 79c5f71b1e..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/IDescription.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.jun.plugin.jdk.enums; - -public interface IDescription { - public String getDescription(); -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/MoreAction.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/MoreAction.java deleted file mode 100644 index ca33aa333b..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/MoreAction.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.jun.plugin.jdk.enums; - -public enum MoreAction implements IDescription { - TURN_LEFT { - // 实现接口上的方法 - public String getDescription() { - return "向左转"; - } - - }, // 注意这里的枚举值分隔使用, - - TURN_RIGHT { - // 实现接口上的方法 - public String getDescription() { - return "向右转"; - } - }, // 注意这里的枚举值分隔使用, - - SHOOT { - // 实现接口上的方法 - public String getDescription() { - return "射击"; - } - }; // 注意这里的枚举值结束使用; -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/MoreAction2.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/MoreAction2.java deleted file mode 100644 index 47a121e49b..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/MoreAction2.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.jun.plugin.jdk.enums; - -public enum MoreAction2 { - TURN_LEFT { - // 实现抽象方法 - public String getDescription() { - return "向左转"; - } - }, // 记得这里的枚举值分隔使用, - - TURN_RIGHT { - // 实现抽象方法 - public String getDescription() { - return "向右转"; - } - }, - - SHOOT { - // 实现抽象方法 - public String getDescription() { - return "射击"; - } - }; // 记得这里的枚举值结束使用; - - // 声明抽象方法 - public abstract String getDescription(); -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/MoreActionDemo.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/MoreActionDemo.java deleted file mode 100644 index 3868166e2b..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/MoreActionDemo.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jun.plugin.jdk.enums; - -public class MoreActionDemo { - public static void main(String[] args) { - for (MoreAction action : MoreAction.values()) { - System.out.printf("%s: %s%n", action, action.getDescription()); - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/MoreActionDemo2.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/MoreActionDemo2.java deleted file mode 100644 index e2ff76c0a4..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/MoreActionDemo2.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jun.plugin.jdk.enums; - -public class MoreActionDemo2 { - public static void main(String[] args) { - for (MoreAction2 action : MoreAction2.values()) { - System.out.printf("%s: %s%n", action, action.getDescription()); - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/Singleton.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/Singleton.java deleted file mode 100644 index aac1c63e2d..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/enums/Singleton.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.jun.plugin.jdk.enums; - -public class Singleton { - // 构造函数私有,只限内部调用 - private Singleton() { - }; - - private static Singleton instance = null; - - public static synchronized Singleton getInstance() { - if (instance == null) - instance = new Singleton(); - return instance; - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/sort/BubbleSort.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/sort/BubbleSort.java deleted file mode 100644 index 855ce0e2ba..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/sort/BubbleSort.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.jun.plugin.jdk.sort; - -/** - * 冒泡排序: -标准的冒泡排序过程如下: -首先比较 a[1]与 a[2]的值,若 a[1]大于 a[2]则交换两者的值,否则不变。 -再比较 a[2]与 a[3]的值,若 a[2]大于 a[3]则交换两者的值,否则不变。 -再比较 a[3]与 a[4],以此类推,最后比较 a[n-1]与 a[n]的值。 -这样处理一轮后,a[n]的值一定是这组数据中最大的。 -再对 a[1]~a[n-1]以相同方法处理一轮。 -共处理 n-1 轮后 a[1]、a[2]、……a[n]就以升序排列了。 -过程举例: -初始元素序列: 8 3 2 5 9 3* 6 -第一趟排序: 3 2 5 8 3* 6 【 9 】 -第二趟排序: 2 3 5 3* 6 【8 9 】 -第三趟排序: 2 3 3* 5 【 6 8 9 】 -第四趟排序: 2 3 3* 【5 6 8 9 】 -第五趟排序: 2 3 【3* 5 6 8 9 】 -第六趟排序: 2 【3 3* 5 6 8 9 】 - * @author Wujun - * @since 2014年1月23日 下午3:38:49 - */ -public class BubbleSort extends Sort{ - - /** - * @param args - */ - public static void main(String[] args) { - new BubbleSort().sort(array); - } - - public void execute(int[] array) { - - for (int i = 0; i < array.length - 1; i++) { - for (int j = i + 1; j < array.length; j++) { - if (array[i] > array[j]) { - int array_j = array[j]; - array[j] = array[i]; - array[i] = array_j; - } - } - } - - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/sort/InsertionSort.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/sort/InsertionSort.java deleted file mode 100644 index 40cbdfbbf9..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/sort/InsertionSort.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.jun.plugin.jdk.sort; - -/** - * 直接插入排序 -算法描述: -每步将一个待排序元素,插入到前面已经排好序的一组元素的适当位置上,直到全部 -元素插入为止。 - -过程举例: -初始元素序列: 【8 】 3 2 5 9 3* 6 -第一趟排序: 【3 8】 2 5 9 3* 6 -第二趟排序: 【2 3 8】 5 9 3* 6 -第三趟排序: 【2 3 5 8】 9 3* 6 -第四趟排序: 【2 3 5 8 9】 3* 6 -第五趟排序: 【2 3 3* 5 8 9】 6 -第六趟排序: 【2 3 3* 5 6 8 9】 - * @author Wujun - * @since 2014年1月23日 下午4:45:59 - */ -public class InsertionSort extends Sort { - public static void main(String[] args) { - new InsertionSort().sort(array); - } - - /* (non-Javadoc) - * @see sort.Sort#execute(int[]) - */ - @Override - public void execute(int[] array) { - for (int i = 1; i < array.length; i++) { - for (int j = 0; j < i; j++) { - if (array[j] > array[i]) { - int small = array[i]; - array[i] = array[j]; - array[j] = small; - } - } - } - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/sort/SelectionSort.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/sort/SelectionSort.java deleted file mode 100644 index 3d4c1cc30e..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/sort/SelectionSort.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.jun.plugin.jdk.sort; - -/** - * 直接选择排序 -算法描述: -首先找出最大的元素,将其与 a[n-1]位置交换; -然后在余下的 n-1 个元素中寻找最大的元素,将其与 a[n-2]位置交换, -如此进行下去直至 n 个元素排序完毕。 - -过程举例: -初始元素序列: 8 3 2 5 9 3* 6 -第一趟排序: 8 3 2 5 6 3* 【9 】 -第二趟排序: 3* 3 2 5 6 【 8 9 】 -第三趟排序: 3* 3 2 5 【6 8 9 】 -第四趟排序: 3* 3 2 【5 6 8 9 】 -第五趟排序: 2 3 【3* 5 6 8 9 】 -第六趟排序: 2 【 3 3* 5 6 8 9 】 - * @author Wujun - * @since 2014年1月23日 下午3:49:15 - */ -public class SelectionSort extends Sort { - - /** - * @param args - */ - public static void main(String[] args) { - new SelectionSort().sort(array); - } - - /* (non-Javadoc) - * @see sort.Sort#execute(int[]) - */ - @Override - public void execute(int[] array) { - for (int i = 0; i < array.length - 1; i++) { - int k = i; - for (int j = i + 1; j < array.length; j++) { - if (array[k] > array[j]) { - k = j; - } - } - - int small = array[k]; - array[k] = array[i]; - array[i] = small; - } - - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/sort/ShellSort.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/sort/ShellSort.java deleted file mode 100644 index cfe027c4d9..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/sort/ShellSort.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.jun.plugin.jdk.sort; - -/** - * 希尔排序 -希尔排序(Shell Sort)是插入排序的一种。是针对直接插入排序算法的改进。该方法又称缩 -小增量排序,因 DL.Shell 于 1959 年提出而得名。 -希尔排序属于插入类排序,是将整个无序列分割成若干小的子序列分别进行插入排序 - -算法描述: -先取一个正整数 d1 0) { -// for (i = k; i < array.length; i++) { -// t = array[i]; -// for (j = i - k; j >= 0 && array[j] > t; j -= k) -// array[j + k] = array[j]; -// array[j + k] = t; -// } -// k /= 2; -// System.out.println(k + "--"); -// print(array); -// } - - - int d = array.length / 2; - while (d > 0) { - System.out.println(d + "--"); - for (int i = d; i < array.length; i++) { - int t = array[i]; - int j; - for (j = i - d; j >= 0 && array[j] > t; j -= d) { - array[j + d] = array[j]; - } - - array[j + d] = t; - } - print(array); - d /= 2; - } - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/sort/Sort.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/sort/Sort.java deleted file mode 100644 index 99596190f5..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk/sort/Sort.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.jun.plugin.jdk.sort; - -/** - * 常见排序算法 - -排序是计算机内经常进行的一种操作,其目的是将一组“无序”的记录序列调整为“有序”的记 -录序列。 - -排序分内排序和外排序。 -内排序:指在排序期间数据对象全部存放在内存的排序。 -外排序:指在排序期间全部对象个数太多,不能同时存放在内存,必须根据排序过程的要求, -不断在内、外存之间移动的排序。 - -内排序的方法有许多种,按所用策略不同,可归纳为五类:插入排序、选择排序、交 -换排序、归并排序和分配排序。 -插入排序主要包括直接插入排序和希尔排序两种; -选择排序主要包括直接选择排序和堆排序; -交换排序主要包括冒泡排序和快速排序; -归并排序主要包括二路归并(常用的归并排序)和自然归并。 -分配排序主要包括箱排序和基数排序。 - -稳定排序:假设在待排序的文件中,存在两个或两个以上的记录具有相同的关键字, -在用某种排序法排序后,若这些相同关键字的元素的相对次序仍然不变,则这种排序 -方法是稳定的。 -其中冒泡,插入,基数,归并属于稳定排序; -选择,快速,希尔,堆属于不稳定排序。 - -时间复杂度是衡量算法好坏的最重要的标志。 -排序的时间复杂度与算法执行中的数据比较次数与数据移动次数密切相关。 - -以下给出介绍简单的排序方法:插入排序,选择排序,冒泡排序。 -三种算法的时间复杂度都是 n 2 级的。 - * @author Wujun - * @since 2014年1月23日 下午3:43:34 - */ -public abstract class Sort { - protected static int[] array = {34, 6, 32, 1, 90, 11}; - - public void print(int[] array) { - StringBuilder builder = new StringBuilder(); - for (int i = 0; i < array.length; i++) { - builder.append(array[i] + ","); - } - - if (builder.length() > 0) { - System.out.println(builder.substring(0, builder.length() - 1)); - } else { - System.out.println(builder.toString()); - } - } - - public void sort(int[] array) { - execute(array); - print(array); - } - - public abstract void execute(int[] array); -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk8/LambdaTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk8/LambdaTest.java deleted file mode 100644 index 68907b19f6..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk8/LambdaTest.java +++ /dev/null @@ -1,165 +0,0 @@ -package com.jun.plugin.jdk8; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.alibaba.fastjson.JSON; - -/** - * @Title: lambdaTest - * @Description: 拉姆达表达式 - * - * @Version:1.0.0 - * @author pancm - * @date 2018年8月28日 - */ -public class LambdaTest { - - /** - * @param args - */ - public static void main(String[] args) { - test1(); - test2(); - } - - private static void test1() { - - Map map = new HashMap<>(); - map.put("a", "a"); - map.put("b", "b"); - map.put("c", "c"); - map.put("d", "d"); - - System.out.println("map普通方式遍历:"); - for (String key : map.keySet()) { - System.out.println("k=" + key + ",v=" + map.get(key)); - } - - System.out.println("map拉姆达表达式遍历:"); - map.forEach((k, v) -> { - System.out.println("k=" + k + ",v=" + v); - }); - - - - List list = new ArrayList(); - list.add("a"); - list.add("bb"); - list.add("ccc"); - list.add("dddd"); - System.out.println("list拉姆达表达式遍历:"); - list.forEach(v -> { - System.out.println(v); - }); - System.out.println("list双冒号运算符遍历:"); - list.forEach(System.out::println); - - } - - private static void test2() { - List list = new ArrayList(); - List list2 = new ArrayList(); - list.add(new User(1, "张三")); - list.add(new User(2, "李四")); - list.add(new User(3, "王五")); - list.add(new User(4, "赵六")); - System.out.println("list:" + list); - list.forEach(v -> { - if (v.getId() > 2) { - list2.add(v); - } - }); - System.out.println("list2:" + list2); - } - - //使用普通的方式创建 - Runnable r1 = new Runnable() { - @Override - public void run() { - System.out.println("普通方式创建!"); - } - }; - - //使用拉姆达方式创建 - Runnable r2 = ()-> System.out.println("拉姆达方式创建!"); - - -} - -class User { - - /** 编号 */ - private int id; - /** 姓名 */ - private String name; - - public User() { - } - - /** - * 构造方法 - * - * @param id 编号 - * @param name 姓名 - */ - public User(int id, String name) { - super(); - this.id = id; - this.name = name; - } - - /** - * 获取编号 - * - * @return id - */ - public int getId() { - return id; - } - - /** - * 设置编号 - * - * @param id - */ - public void setId(int id) { - this.id = id; - } - - /** - * 获取姓名 - * - * @return name - */ - public String getName() { - System.out.println("姓名:" + name); - return name; - } - - /** - * 设置姓名 - * - * @param name - */ - public void setName(String name) { - this.name = name; - } - - @SuppressWarnings("rawtypes") - public Map toMap() { - return JSON.parseObject(toString(), HashMap.class); - } - - /** - * - */ - @Override - public String toString() { - return "{\"id\":\"" + id + "\",\"name\":\"" + name + "\"}"; - } - - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk8/LocalDateTimeTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk8/LocalDateTimeTest.java deleted file mode 100644 index 1482e9cd86..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk8/LocalDateTimeTest.java +++ /dev/null @@ -1,228 +0,0 @@ -package com.jun.plugin.jdk8; - -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.Month; -import java.time.Period; -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.time.temporal.ChronoUnit; - -/** -* @Title: timeTest -* @Description: -* 时间测试 -* @Version:1.0.0 -* @author pancm -* @date 2018年6月21日 -*/ -public class LocalDateTimeTest { - - /** - * @param args - */ - public static void main(String[] args) { - - - /* - - 新版API中java.time包里的一些关键类: - - Instant:瞬时实例。 - LocalDate:本地日期,不包含具体时间 例如:2014-01-14 可以用来记录生日、纪念日、加盟日等。 - LocalTime:本地时间,不包含日期。 - LocalDateTime:组合了日期和时间,但不包含时差和时区信息。 - ZonedDateTime:最完整的日期时间,包含时区和相对UTC或格林威治的时差。 - - - Java 8日期时间API 使用说明: - - 1)提供了javax.time.ZoneId 获取时区。 - - 2)提供了LocalDate和LocalTime类。 - - 3)Java 8 的所有日期和时间API都是不可变类并且线程安全,而现有的Date和Calendar API中的java.util.Date和SimpleDateFormat是非线程安全的。 - - 4)主包是 java.time,包含了表示日期、时间、时间间隔的一些类。里面有两个子包java.time.format用于格式化, java.time.temporal用于更底层的操作。 - - 5)时区代表了地球上某个区域内普遍使用的标准时间。每个时区都有一个代号,格式通常由区域/城市构成(Asia/Tokyo),在加上与格林威治或 UTC的时差。例如:东京的时差是+09:00。 - - 6)OffsetDateTime类实际上组合了LocalDateTime类和ZoneOffset类。用来表示包含和格林威治或UTC时差的完整日期(年、月、日)和时间(时、分、秒、纳秒)信息。 - - 7)DateTimeFormatter 类用来格式化和解析时间。与SimpleDateFormat不同,这个类不可变并且线程安全,需要时可以给静态常量赋值。 DateTimeFormatter类提供了大量的内置格式化工具,同时也允许你自定义。在转换方面也提供了parse()将字符串解析成日期,如果解析出错会抛出DateTimeParseException。DateTimeFormatter类同时还有format()用来格式化日期,如果出错会抛出DateTimeException异常。 - - 8)再补充一点,日期格式“MMM d yyyy”和“MMM dd yyyy”有一些微妙的不同,第一个格式可以解析“Jan 2 2014”和“Jan 14 2014”,而第二个在解析“Jan 2 2014”就会抛异常,因为第二个格式里要求日必须是两位的。如果想修正,你必须在日期只有个位数时在前面补零,就是说“Jan 2 2014”应该写成 “Jan 02 2014”。 - - */ - - - test1(); - test2(); - test3(); - test4(); - } - - - - - /** - * - */ - private static void test1(){ - - /* - * 获取当前时间 - */ - //本地日期,不包括时分秒 - LocalDate nowDate = LocalDate.now(); - //本地日期,包括时分秒 - LocalDateTime nowDateTime = LocalDateTime.now(); - System.out.println("当前时间:"+nowDate); - System.out.println("当前时间:"+nowDateTime); - // 当前时间:2018-12-19 - // 当前时间:2018-12-19T15:24:35.822 - - /* - * 格式化时间 - */ - LocalDate ld=LocalDate.parse("2017-11-17"); - LocalDate ld2=LocalDate.parse("2018-01-05"); - - /** - * 创建指定日期 - */ - LocalDate ld3=LocalDate.of(2017, Month.NOVEMBER, 17); - LocalDate ld4=LocalDate.of(2018, 02, 11); - //jdk1.8的类,用于比较时间 - //可以得到相差年、月、日 - Period p=Period.between(ld, ld2); - System.out.println("相差年: "+p.getYears()+" 相差月 :"+p.getMonths() +" 相差天:"+p.getDays()); - // 相差年: 0 相差月 :1 相差天:19 - - System.out.println("增加2个月: "+ld.plusMonths(2)); - Period p2=Period.between(ld3, ld4); - System.out.println("相差年: "+p2.getYears()+" 相差月 :"+p2.getMonths() +" 相差天:"+p2.getDays()+"--"+p2.toTotalMonths()); - //相差年: 0 相差月 :2 相差天:25 - } - - /** - * 时间测试 - */ - private static void test2(){ -// String time="2018-06-29 09:19:45.498"; - String time2="2018-01-04T09:19:29.499"; - //格式化时间 - LocalDateTime ldt2=LocalDateTime.parse(time2); - //获取当前的时间,包括毫秒 - LocalDateTime ldt = LocalDateTime.now(); - System.out.println("当前年:"+ldt.getYear()); //2018 - System.out.println("当前年份天数:"+ldt.getDayOfYear());//172 - System.out.println("当前月:"+ldt.getMonthValue()); - System.out.println("当前时:"+ldt.getHour()); - System.out.println("当前分:"+ldt.getMinute()); - System.out.println("当前时间:"+ldt.toString()); - // 当前年:2018 - // 当前年份天数:353 - // 当前月:12 - // 当前时:15 - // 当前分:24 - // 当前时间:2018-12-19T15:24:35.833 - - - System.out.println("格式化时间: "+ ldt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"))); - //格式化时间:2018-12-19 15:37:47.119 - - System.out.println("后5天时间:"+ldt.plusDays(5)); - System.out.println("前5天时间并格式化:"+ldt.minusDays(5).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); //2018-06-16 - System.out.println("前一个月的时间:"+ldt2.minusMonths(1).format(DateTimeFormatter.ofPattern("yyyyMM"))); //2018-06-16 - System.out.println("后一个月的时间:"+ldt2.plusMonths(1)); //2018-06-16 - System.out.println("指定2099年的当前时间:"+ldt.withYear(2099)); //2099-06-21T15:07:39.506 - // 后5天时间:2018-12-24T15:50:37.508 - // 前5天时间并格式化:2018-12-14 - // 前一个月的时间:201712 - // 后一个月的时间:2018-02-04T09:19:29.499 - // 指定2099年的当前时间:2099-12-19T15:50:37.508 - - System.out.println("得到的时间:"+ldt2.toString()); - System.out.println("格式化时间:"+ldt2.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); - - - /* - * - 通过 Clock时钟类用于获取当时的时间戳,或当前时区下的日期时间信息。 - */ - Clock clock = Clock.systemUTC(); - System.out.println("当前时间戳 : " + clock.millis()); - Clock clock2 = Clock.system(ZoneId.of("Asia/Shanghai")); - System.out.println("亚洲上海此时的时间戳:"+clock2.millis()); - Clock clock3 = Clock.system(ZoneId.of("America/New_York")); - System.out.println("美国纽约此时的时间戳:"+clock3.millis()); - // 当前时间戳 : 1545209277657 - // 亚洲上海此时的时间戳:1545209277657 - // 美国纽约此时的时间戳:1545209277658 - - /* - * 时区计算 - */ - ZoneId zoneId= ZoneId.of("America/New_York"); - ZonedDateTime dateTime=ZonedDateTime.now(zoneId); - System.out.println("美国纽约此时的时间 : " + dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"))); - System.out.println("美国纽约此时的时间 和时区: " + dateTime); - // 美国纽约此时的时间 : 2018-12-19 03:52:22.494 - // 美国纽约此时的时间 和时区: 2018-12-19T03:52:22.494-05:00[America/New_York] - - /** - * - * 时间比较 - */ - LocalDateTime ldt4 = LocalDateTime.now(); - LocalDateTime ldt5 = ldt4.plusMinutes(10); - System.out.println("当前时间是否大于:"+ldt4.isAfter(ldt5)); - System.out.println("当前时间是否小于"+ldt4.isBefore(ldt5)); - // false - // true - } - - - /** - * - */ - private static void test3(){ - /* - * Duration 这个类以秒和纳秒为单位建模时间的数量或数量 - */ - Instant inst1 = Instant.now(); - System.out.println("当前时间戳: " + inst1); - Instant inst2 = inst1.plus(Duration.ofSeconds(10)); - System.out.println("增加之后的时间 : " + inst2); - System.out.println("相差毫秒 : " + Duration.between(inst1, inst2).toMillis()); - System.out.println("相毫秒 : " + Duration.between(inst1, inst2).getSeconds()); - // 当前时间戳 : 2018-12-19T08:14:21.675Z - // 增加之后的时间 : 2018-12-19T08:14:31.675Z - // 相差毫秒 : 10000 - // 相毫秒 : 10 - - } - - - /** - * 单个时间单位内测量一段时间 - */ - private static void test4(){ - /* - * ChronoUnit 日期周期单位的标准集合。 - */ - LocalDate startDate = LocalDate.of(2017, 11, 17); - LocalDate endDate = LocalDate.of(2018, 01, 05); - System.out.println("相差月份:"+ChronoUnit.MONTHS.between(startDate, endDate)); - System.out.println("两月之间的相差的天数 : " + ChronoUnit.DAYS.between(startDate, endDate)); - // 相差月份:1 - // 两天之间的差在天数 : 49 - } - - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk8/StreamTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk8/StreamTest.java deleted file mode 100644 index a60d59018a..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk8/StreamTest.java +++ /dev/null @@ -1,558 +0,0 @@ -package com.jun.plugin.jdk8; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.IntSummaryStatistics; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Random; -import java.util.Set; -import java.util.Stack; -import java.util.function.Supplier; -import java.util.stream.Collectors; -import java.util.stream.IntStream; -import java.util.stream.Stream; - - - -/** - * @Title: StreamTest - * @Description: Stream测试用例 流的操作类型分为两种: - * - * Intermediate:一个流可以后面跟随零个或多个 intermediate - * 操作。其目的主要是打开流,做出某种程度的数据映射/过滤,然后返回一个新的流,交给下一个操作使用。 - * 这类操作都是惰性化的(lazy),就是说,仅仅调用到这类方法,并没有真正开始流的遍历。 Terminal:一个流只能有一个 - * terminal 操作,当这个操作执行后,流就被使用“光”了,无法再被操作。 所以这必定是流的最后一个操作。 Terminal - * 操作的执行,才会真正开始流的遍历,并且会生成一个结果,或者一个 side effect。 - * @Version:1.0.0 - * @author pancm - * @date 2018年9月3日 - */ -public class StreamTest { - - /** - * @param args - */ - public static void main(String[] args) { - test1(); - test2(); - test3(); - test4(); - - /* - * Stream 的特性可以归纳为: - 不是数据结构 - 它没有内部存储,它只是用操作管道从 source(数据结构、数组、generator function、IO channel)抓取数据。 - 它也绝不修改自己所封装的底层数据结构的数据。例如 Stream 的 filter 操作会产生一个不包含被过滤元素的新 Stream,而不是从 source 删除那些元素。 - 所有 Stream 的操作必须以 lambda 表达式为参数 - 不支持索引访问 - 你可以请求第一个元素,但无法请求第二个,第三个,或最后一个。不过请参阅下一项。 - 很容易生成数组或者 List - 惰性化 - 很多 Stream 操作是向后延迟的,一直到它弄清楚了最后需要多少数据才会开始。 - Intermediate 操作永远是惰性化的。 - 并行能力 - 当一个 Stream 是并行化的,就不需要再写多线程代码,所有对它的操作会自动并行进行的。 - 可以是无限的 - 集合有固定大小,Stream 则不必。limit(n) 和 findFirst() 这类的 short-circuiting 操作可以对无限的 Stream 进行运算并很快完成。 - */ - } - - /** - * 简单实用 - */ - private static void test1() { - /* - * 普通的方式过滤 - */ - List list = Arrays.asList("张三", "李四", "王五", "xuwujing"); - System.out.println("过滤之前:" + list); - List result = new ArrayList<>(); - for (String str : list) { - if (!"李四".equals(str)) { - result.add(str); - } - } - System.out.println("过滤之后:" + result); - - /* - * stream 过滤 - */ - List result2 = list.stream().filter(str -> !"李四".equals(str)).collect(Collectors.toList()); - System.out.println("stream 过滤之后:" + result2); - // 另一种方式输出 - result2.forEach(System.out::println); - - // 使用stream.filter ()过滤一列表,并.findAny().orElse - // 遍历该list,查询数据,如果查不到,就返回 找不到! - String result3 = list.stream().filter(str -> "李四".equals(str)).findAny().orElse("找不到!"); - String result4 = list.stream().filter(str -> "李二".equals(str)).findAny().orElse("找不到!"); - - System.out.println("stream 过滤之后 2:" + result3); - System.out.println("stream 过滤之后 3:" + result4); - //stream 过滤之后 2:李四 - //stream 过滤之后 3:找不到! - } - - /** - * 基本使用 - */ - @SuppressWarnings({ "unchecked", "rawtypes", "unused" }) - private static void test2() { - - /* - * 构造流的几种方式 - */ - Stream stream = Stream.of("a", "b", "c"); - String[] strArray = new String[] { "a", "b", "c" }; - stream = Stream.of(strArray); - stream = Arrays.stream(strArray); - List list = Arrays.asList(strArray); - stream = list.stream(); - - /* - * 流之间的相互转化 一个 Stream 只可以使用一次,这段代码为了简洁而重复使用了数次,因此会抛出异常 - */ - try { - Stream stream2 = Stream.of("a", "b", "c"); - // 转换成 Array - String[] strArray1 = stream2.toArray(String[]::new); - - // 转换成 Collection - List list1 = stream2.collect(Collectors.toList()); - List list2 = stream2.collect(Collectors.toCollection(ArrayList::new)); - Set set1 = stream2.collect(Collectors.toSet()); - Stack stack1 = stream2.collect(Collectors.toCollection(Stack::new)); - - // 转换成 String - String str = stream.collect(Collectors.joining()).toString(); - } catch (Exception e) { - e.printStackTrace(); - } - - /* - * 汇总操作 - */ - List lists = new ArrayList(); - lists.add(new User(6, "张三")); - lists.add(new User(2, "李四")); - lists.add(new User(3, "王五")); - lists.add(new User(1, "张三")); - // 计算这个list中出现 "张三" id的值 - int sum = lists.stream().filter(u -> "张三".equals(u.getName())).mapToInt(u -> u.getId()).sum(); - - System.out.println("计算结果:" + sum); - // 7 - - /* - * 数值类型的流 包括IntStream, LongStream和DoubleStream - */ - System.out.println("遍历输出该数组的数据:"); - IntStream.of(new int[] { 1, 2, 3, 4 }).forEach(System.out::println); - System.out.println("查询范围在 2-3(2<=i<3)之间的数据:"); - IntStream.range(2, 3).forEach(System.out::println); - System.out.println("查询范围在2-3(2<=i<=3)之间的数据:"); - IntStream.rangeClosed(2, 3).forEach(System.out::println); - - /* stream中的 map使用 */ - - /* - * 转换大写 - */ - List list3 = Arrays.asList("zhangSan", "liSi", "wangWu"); - System.out.println("转换之前的数据:" + list3); - List list4 = list3.stream().map(String::toUpperCase).collect(Collectors.toList()); - System.out.println("转换之后的数据:" + list4); - // 转换之后的数据:[ZHANGSAN, LISI,WANGWU] - - /* - * 转换数据类型 - */ - List list31 = Arrays.asList("1", "2", "3"); - System.out.println("转换之前的数据:" + list31); - List list41 = list31.stream().map(Integer::valueOf).collect(Collectors.toList()); - System.out.println("转换之后的数据:" + list41); - // [1, 2, 3] - - - /* - * 转换数据类型 - * 对象转map - */ - List list32 = new ArrayList(); - for(int i=1;i<=10;i++){ - list32.add(new User(i,"张三"+i)); - } - - System.out.println("转换之前的数据:" + list32);// 转换之前的数据:[1, 2, 3] - List list42 = list32.stream().map(User::toMap).collect(Collectors.toList()); - System.out.println("转换之后的数据:" + list42); // [1, 2, 3] - - - /* - * 获取平方 - */ - List list5 = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 }); - List list6 = list5.stream().map(n -> n * n).collect(Collectors.toList()); - System.out.println("平方的数据:" + list6); - // [1, 4, 9, 16, 25] - - /* - * flatMap 一对多 得到多个数组里面的数字 - */ - Stream> inputStream = Stream.of(Arrays.asList(1), Arrays.asList(2, 3), Arrays.asList(4, 5, 6)); - Stream outputStream = inputStream.flatMap((childList) -> childList.stream()); - System.out.println("打印 stream中的数字:"); - outputStream.forEach(System.out::println); - - /* - * 得到一段句子中的单词 - */ - String worlds = "The way of the future"; - List list7 = new ArrayList<>(); - list7.add(worlds); - List list8 = list7.stream().flatMap(str -> Stream.of(str.split(" "))) - .filter(world -> world.length() > 0).collect(Collectors.toList()); - System.out.println("单词:"); - list8.forEach(System.out::println); - // 单词: - // The - // way - // of - // the - // future - - /* - * peek 对每个元素执行操作并返回一个新的 Stream - */ - System.out.println("peek使用:"); - Stream.of("one", "two", "three", "four").filter(e -> e.length() > 3).peek(e -> System.out.println("转换之前: " + e)) - .map(String::toUpperCase).peek(e -> System.out.println("转换之后: " + e)).collect(Collectors.toList()); - - // 转换之前: three - // 转换之后: THREE - // 转换之前: four - // 转换之后: FOUR - - - - /* - * limit 和 skip limit 返回 Stream 的前面 n 个元素;skip 则是扔掉前 n 个元素(它是由一个叫 - * subStream 的方法改名而来)。 - */ - - //limit 简单使用 - Random rd = new Random(); - System.out.println("取到的前三条数据:"); - rd.ints().limit(3).forEach(System.out::println); - // 取到的前三条数据: - // 1167267754 - // -1164558977 - // 1977868798 - - List list9 = new ArrayList(); - for (int i = 1; i < 4; i++) { - User user = new User(i, "pancm" + i); - list9.add(user); - } - System.out.println("截取之前的数据:"); - // 取前3条数据,但是扔掉了前面的2条,可以理解为拿到的数据为 2<=i<3 (i 是数值下标) - List list10 = list9.stream().map(User::getName).limit(3).skip(2).collect(Collectors.toList()); - System.out.println("截取之后的数据:" + list10); - // 截取之前的数据: - // 姓名:pancm1 - // 姓名:pancm2 - // 姓名:pancm3 - // 截取之后的数据:[pancm3] - - - /* - * sort 进行排序 先获取在排序效率更高 - */ - - Random rd2 = new Random(); - System.out.println("取到的前三条数据然后进行排序:"); - rd2.ints().limit(3).sorted().forEach(System.out::println); - // 取到的前三条数据然后进行排序: - // -2043456377 - // -1778595703 - // 1013369565 - - //普通的排序取值 - List list11 = list9.stream().sorted((u1, u2) -> u1.getName().compareTo(u2.getName())).limit(3) - .collect(Collectors.toList()); - System.out.println("排序之后的数据:" + list11); - //优化排序取值 - List list12 = list9.stream().limit(3).sorted((u1, u2) -> u1.getName().compareTo(u2.getName())) - .collect(Collectors.toList()); - System.out.println("优化排序之后的数据:" + list12); - //排序之后的数据:[{"id":1,"name":"pancm1"}, {"id":2,"name":"pancm2"}, {"id":3,"name":"pancm3"}] - //优化排序之后的数据:[{"id":1,"name":"pancm1"}, {"id":2,"name":"pancm2"}, {"id":3,"name":"pancm3"}] - - /* - * min/max/distinct - * 最大,最小和去重 - */ - - List list13 = Arrays.asList("zhangsan","lisi","wangwu","xuwujing"); - int maxLines = list13.stream().mapToInt(String::length).max().getAsInt(); - int minLines = list13.stream().mapToInt(String::length).min().getAsInt(); - System.out.println("最长字符的长度:" + maxLines+",最短字符的长度:"+minLines); - //最长字符的长度:8,最短字符的长度:4 - - String lines = "good good study day day up"; - List list14 = new ArrayList(); - list14.add(lines); - List words = list14.stream().flatMap(line -> Stream.of(line.split(" "))).filter(word -> word.length() > 0) - .map(String::toLowerCase).distinct().sorted().collect(Collectors.toList()); - System.out.println("去重复之后:" + words); - //去重复之后:[day, good, study, up] - - /* - * Match 匹配 - * - * allMatch:Stream 中全部元素符合则返回 true ; - * anyMatch:Stream 中只要有一个元素符合则返回 true; - * noneMatch:Stream 中没有一个元素符合则返回 true。 - */ - - boolean all = lists.stream().allMatch(u -> u.getId() > 3); - System.out.println("是否都大于3:" + all); - boolean any = lists.stream().anyMatch(u -> u.getId() > 3); - System.out.println("是否有一个大于3:" + any); - boolean none = lists.stream().noneMatch(u -> u.getId() > 3); - System.out.println("是否没有一个大于3的:" + none); - // 是否都大于3:false - // 是否有一个大于3:true - // 是否没有一个大于3的:false - - /* - * 生成随机数 通过实现 Supplier 接口,你可以自己来控制流的生成。这种情形通常用于随机数、常量的 - * Stream,或者需要前后元素间维持着某种状态信息的 Stream。 把 Supplier 实例传递给 Stream.generate() - * 生成的 Stream,默认是串行(相对 parallel 而言)但无序的(相对 ordered 而言)。 - * 由于它是无限的,在管道中,必须利用 limit 之类的操作限制 Stream 大小。 - */ - Random seed = new Random(); - seed.ints().limit(3).forEach(System.out::println); - Supplier random = seed::nextInt; - System.out.println("生成5个随机数:"); - Stream.generate(random).limit(3).forEach(System.out::println); - System.out.println("生成5正整数的随机数:"); - IntStream.generate(() -> (int) (System.nanoTime() % 100)).limit(3).forEach(System.out::println); - System.out.println("生成5个随机数:"); - - - /* - 并行(parallel)程序 - parallelStream 是流并行处理程序的代替方法。 - */ - List strings = Arrays.asList("a", "", "c", "", "e","", " "); - // 获取空字符串的数量 - long count = strings.parallelStream().filter(string -> string.isEmpty()).count(); - System.out.println("空字符串的个数:"+count); - - - /* - * 合并字符串 - */ - List filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList()); - System.out.println("筛选列表: " + filtered); - String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", ")); - System.out.println("合并字符串: " + mergedString); - // 筛选列表: [a, c, e, ] - // 合并字符串: a, c, e, - - } - - /** - * 一些关联使用 - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - private static void test3() { - - /* - * Optional - */ - String strA = " abcd ", strB = null; - System.out.println("数据校验开始..."); - print(strA); - print(""); - print(strB); - getLength(strA); - getLength(""); - getLength(strB); - System.out.println("数据校验结束..."); - - /* - * reduce 主要作用是把 Stream 元素组合起来。 - */ - // 字符串连接,concat = "ABCD" - String concat = Stream.of("A", "B", "C", "D").reduce("", String::concat); - System.out.println("字符串拼接:" + concat); - //字符串拼接:ABCD - // 求最小值 - double minValue = Stream.of(-4.0, 1.0, 3.0, -2.0).reduce(Double.MAX_VALUE, Double::min); - System.out.println("最小值:" + minValue); - //最小值:-4.0 - - - // 求和, 无起始值 - int sumValue = Stream.of(1, 2, 3, 4).reduce(Integer::sum).get(); - System.out.println("有无起始值求和:" + sumValue); - // 求和, 有起始值 - sumValue = Stream.of(1, 2, 3, 4).reduce(1, Integer::sum); - System.out.println("有起始值求和:" + sumValue); - // 有无起始值求和:10 - // 有起始值求和:11 - - - // 过滤,字符串连接,concat = "ace" - concat = Stream.of("a", "B", "c", "D", "e", "F").filter(x -> x.compareTo("Z") > 0).reduce("", String::concat); - System.out.println("过滤和字符串连接:" + concat); - //过滤和字符串连接:ace - - - - /* - * iterate iterate 跟 reduce 操作很像,接受一个种子值,和一个 UnaryOperator(例如 f)。 - * 然后种子值成为 Stream 的第一个元素,f(seed) 为第二个,f(f(seed)) 第三个,以此类推。 在 iterate - * 时候管道必须有 limit 这样的操作来限制 Stream 大小。 - */ - System.out.println("从2开始生成一个等差队列:"); - Stream.iterate(2, n -> n + 2).limit(5).forEach(x -> System.out.print(x + " ")); - // 从2开始生成一个等差队列: - // 2 4 6 8 10 - - - System.out.println("\n"); - /* - * 分组排序 groupingBy/partitioningBy - */ - // 通过id进行排序 - System.out.println("通过id进行分组排序:"); - Map> personGroups = Stream.generate(new UserSupplier2()).limit(5) - .collect(Collectors.groupingBy(User::getId)); - Iterator it = personGroups.entrySet().iterator(); - while (it.hasNext()) { - Map.Entry> persons = (Map.Entry) it.next(); - System.out.println("id " + persons.getKey() + " = " + persons.getValue()); - } - - // 通过id进行分组排序: - // id 10 = [{"id":10,"name":"pancm1"}] - // id 11 = [{"id":11,"name":"pancm3"}, {"id":11,"name":"pancm6"}, {"id":11,"name":"pancm4"}, {"id":11,"name":"pancm7"}] - - - - //通过年龄排序 - System.out.println("通过年龄进行分区排序:"); - Map> children = Stream.generate(new UserSupplier3()).limit(5) - .collect(Collectors.partitioningBy(p -> p.getId() < 18)); - - System.out.println("小孩: " + children.get(true)); - System.out.println("成年人: " + children.get(false)); - - // 通过年龄进行分区排序: - // 小孩: [{"id":16,"name":"pancm7"}, {"id":17,"name":"pancm2"}] - // 成年人: [{"id":18,"name":"pancm4"}, {"id":19,"name":"pancm9"}, {"id":20,"name":"pancm6"}] - - - - /* - * IntSummaryStatistics 用于收集统计信息(如count、min、max、sum和average)的状态对象。 - */ - List numbers = Arrays.asList(1, 5, 7, 3, 9); - IntSummaryStatistics stats = numbers.stream().mapToInt((x) -> x).summaryStatistics(); - - System.out.println("列表中最大的数 : " + stats.getMax()); - System.out.println("列表中最小的数 : " + stats.getMin()); - System.out.println("所有数之和 : " + stats.getSum()); - System.out.println("平均数 : " + stats.getAverage()); - - // 列表中最大的数 : 9 - // 列表中最小的数 : 1 - // 所有数之和 : 25 - // 平均数 : 5.0 - - } - - /** - * 自定义流 - */ - private static void test4() { - - /* - * 自定义一个流 然后进行输出 - */ - System.out.println("自定义一个流进行计算输出:"); - Stream.generate(new UserSupplier()).limit(2).forEach(u -> System.out.println(u.getId() + ", " + u.getName())); - - //第一次: - //自定义一个流进行计算输出: - //10, pancm7 - //11, pancm6 - - //第二次: - //自定义一个流进行计算输出: - //10, pancm4 - //11, pancm2 - - //第三次: - //自定义一个流进行计算输出: - //10, pancm4 - //11, pancm8 - } - - public static void print(String text) { - // jdk1.8之前的写法 - // if (text != null) { - // System.out.println(text); - // } - // jdk1.8的写法 - Optional.ofNullable(text).ifPresent(System.out::println); - } - - public static void getLength(String text) { - // jdk1.8之前的写法 - // return if (text != null) ? text.length() : -1; - // jdk1.8的写法 - int i = Optional.ofNullable(text).map(String::length).orElse(-1); - System.out.println("数据:" + i); - }; -} - -class UserSupplier implements Supplier { - private int index = 10; - private Random random = new Random(); - - @Override - public User get() { - return new User(index++, "pancm" + random.nextInt(10)); - } -} - -class UserSupplier2 implements Supplier { - private int index = 10; - private Random random = new Random(); - - @Override - public User get() { - return new User(index % 2 == 0 ? index++ : index, "pancm" + random.nextInt(10)); - } -} - -class UserSupplier3 implements Supplier { - private int index = 16; - private Random random = new Random(); - - @Override - public User get() { - return new User(index++, "pancm" + random.nextInt(10)); - } -} - - - - diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk8/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk8/package-info.java deleted file mode 100644 index 24dd9309f4..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/jdk8/package-info.java +++ /dev/null @@ -1,12 +0,0 @@ -/** - * - */ -/** -* @Title: package-info -* @Description: -* jdk1.8测试用例 -* @Version:1.0.0 -* @author pancm -* @date 2018年5月14日 -*/ -package com.jun.plugin.jdk8; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/KafkaProducerTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/KafkaProducerTest.java deleted file mode 100644 index 03c69f1c3c..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/KafkaProducerTest.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.jun.plugin.mq.kafka; - -import java.util.Properties; - -import org.apache.kafka.clients.producer.KafkaProducer; -import org.apache.kafka.clients.producer.ProducerRecord; -import org.apache.kafka.common.serialization.StringSerializer; - -/** - * -* Title: kafkaTest -* Description: -* kafka测试 -* Version:1.0.0 -* @author pancm -* @date 2018年1月11日 - */ -public class KafkaProducerTest { - - private static KafkaProducer producer; - private final String topic; - private int k=10; - - /** - * @param topic 消息名称 - * @param - */ - public KafkaProducerTest(String topic) { - Properties props = new Properties(); - props.put("bootstrap.servers", "master:9092,slave1:9092,slave2:9092"); - props.put("acks", "all"); - props.put("retries", 0); - props.put("batch.size", 16384); - props.put("linger.ms", 1); - props.put("buffer.memory", 33554432); - props.put("key.serializer", StringSerializer.class.getName()); - props.put("value.serializer", StringSerializer.class.getName()); - this.producer = new KafkaProducer(props); - this.topic = topic; - } - - - private void start(){ - int messageNo = 0; - try { - while (true) { - String messageStr = "insert into t_user(name,age) values ('李四',"+messageNo*10+1+")" ; -// StringBuffer sb=new StringBuffer(); -// for(int i=1;i<=k;i++){ -// int count=k*messageNo+i; -// messageStr="insert into t_user(id,name,age) values ("+count+",'李四',"+count+10+")" ; -// sb.append(messageStr); -// sb.append(";"); -// } -// sb.deleteCharAt(sb.lastIndexOf(";")); -// producer.send(new ProducerRecord(topic, "Message", sb.toString())); - producer.send(new ProducerRecord(topic, "Message", messageStr)); - messageNo++; - //生产了100条就打印 - if(messageNo%100==0){ - System.out.println("Send:" + messageStr); - } - //生产100条就退出 - if(messageNo%100==0){ - System.out.println("成功发送了"+messageNo+"条"); - break; - } -// Utils.sleep(1); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - producer.close(); - } - } - - - public static void main(String[] args) { - KafkaProducerTest test =new KafkaProducerTest("INSERT_TOPIC11"); - test.start(); - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/examples/Consumer.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/examples/Consumer.java deleted file mode 100644 index a06cad54cf..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/examples/Consumer.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.jun.plugin.mq.kafka.examples; - -import java.util.Arrays; -import java.util.Properties; - -import org.apache.kafka.clients.consumer.ConsumerRecord; -import org.apache.kafka.clients.consumer.ConsumerRecords; -import org.apache.kafka.clients.consumer.KafkaConsumer; -import org.apache.kafka.common.serialization.StringDeserializer; - -/** - * -* Title: Consumer -* Description: kafka消费者 -* Version:1.0.0 -* @author pancm -* @date 2017年12月29日 - */ -public class Consumer extends Thread { - - private final KafkaConsumer consumer; - private final String topic; - private static final String GROUPID = "test-consumer-group"; - - public Consumer(String kafkaStr, String topic) { - Properties props = new Properties(); - props.put("bootstrap.servers", kafkaStr); - props.put("group.id", GROUPID); - props.put("enable.auto.commit", "true"); - props.put("auto.commit.interval.ms", "1000"); - props.put("session.timeout.ms", "30000"); - props.put("key.deserializer", StringDeserializer.class.getName()); - props.put("value.deserializer", StringDeserializer.class.getName()); - this.consumer = new KafkaConsumer(props); - this.topic = topic; - } - - @Override - public void run() { - this.consumer.subscribe(Arrays.asList(topic)); - int messageNo = 1; - System.out.println("消费开始---------"); - try { - while (true) { - ConsumerRecords records = consumer.poll(100); - for (ConsumerRecord record : records) { - //消费100条就打印 - //打印的数据不一定是这个规律的 - if(messageNo%100==0){ - System.out.println("receive: key = " + record.key() + ", value = " + record.value()); - } - } - //当消费了1000条就退出 - if(messageNo%1000==0){ - break; - } - messageNo++; - } - } finally { - consumer.close(); - } - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/examples/DataProducer.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/examples/DataProducer.java deleted file mode 100644 index b7c1fe7855..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/examples/DataProducer.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.jun.plugin.mq.kafka.examples; - -import java.util.Properties; -import java.util.Random; - -import org.apache.kafka.clients.producer.KafkaProducer; -import org.apache.kafka.clients.producer.Producer; -import org.apache.kafka.clients.producer.ProducerRecord; - -public class DataProducer { - private static Random random = new Random(93285); - private static Producer producer; - - public static void main(String args[]) { - Properties props = new Properties(); - props.put("bootstrap.servers", "192.168.125.172:9092"); - props.put("acks", "all"); - props.put("retries", 0); - props.put("batch.size", 16384); - props.put("linger.ms", 1); - props.put("buffer.memory", 33554432); - props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); - props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); - producer = new KafkaProducer<>(props); - int count = 0; - long startTime = System.nanoTime(); // 获取开始时间 - int tdata = 0; - double hdata = 0.0; - while (true) { - int choise = 0 + random.nextInt(10000); - switch (choise) { - case 0: - tdata = createRandom(-30, -20); - hdata = createRandom(0.0, 4.9); - break; - case 9999: - tdata = createRandom(60, 70); - hdata = createRandom(96.0, 100.0); - break; - default: - tdata = createRandom(-19, 59); - hdata = createRandom(5.0, 95.9); - break; - } - producer.send(new ProducerRecord(args[0], "temper:" + tdata + "," + "humi:" + hdata)); - long endTime = System.nanoTime(); - count++; - int a = (int) ((endTime - startTime) * Math.pow(10, -9)); - if (a == 1) { - System.out.println(args[0] + "每秒发送:" + count + "条数据"); - count = 0; - startTime = System.nanoTime(); - } - } - - } - - private static int createRandom(int min, int max) { - return min + random.nextInt(max - min); - } - - private static double createRandom(double min, double max) { - if (min == 0) { - return max - random.nextDouble(); - } - return max - random.nextDouble() * min; - - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/examples/KafkaProducerConsumerDemo.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/examples/KafkaProducerConsumerDemo.java deleted file mode 100644 index 5fcd0a118b..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/examples/KafkaProducerConsumerDemo.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.jun.plugin.mq.kafka.examples; - -public class KafkaProducerConsumerDemo { - - public static final String KAFKASTR = "master:9092"; - - public static void main(String[] args) { - new Producer(KAFKASTR, "pcm_test1").start(); // args[0] 为要发送的 topic -// new Consumer(KAFKASTR, "pcm_test1").start(); // args[0] 为要接收的 topic - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/examples/Producer.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/examples/Producer.java deleted file mode 100644 index c324aa862d..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/examples/Producer.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.jun.plugin.mq.kafka.examples; - -import java.util.Properties; - -import org.apache.kafka.clients.producer.KafkaProducer; -import org.apache.kafka.clients.producer.ProducerRecord; -import org.apache.kafka.common.serialization.StringSerializer; - -/** - * -* Title: Producer -* Description: kafka生产者 由于生产消息 -* Version:1.0.0 -* @author pancm -* @date 2017年12月29日 - */ -public class Producer extends Thread { - - private final KafkaProducer producer; - private final String topic; - - /** - * - * @param kafkaStr kafka地址 - * @param topic 消息名称 - * @param - */ - public Producer(String kafkaStr, String topic) { - Properties props = new Properties(); - props.put("bootstrap.servers", kafkaStr); - props.put("acks", "all"); - props.put("retries", 0); - props.put("batch.size", 16384); - props.put("linger.ms", 1); - props.put("buffer.memory", 33554432); - props.put("key.serializer", StringSerializer.class.getName()); - props.put("value.serializer", StringSerializer.class.getName()); - this.producer = new KafkaProducer(props); - this.topic = topic; - } - - @Override - public void run() { - int messageNo = 1; - try { - while (true) { - String messageStr = "Message_" + messageNo; - //生产了100条就打印 - if(messageNo%100==0){ - System.out.println("Send:" + messageStr); - } - //生产1000条就退出 -// if(messageNo%1000==0){ -// break; -// } - producer.send(new ProducerRecord(topic, "Message", messageStr)); - messageNo++; - sleep(10); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - producer.close(); - } - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/examples/WordCountDemo.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/examples/WordCountDemo.java deleted file mode 100644 index 2013d6b35c..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/examples/WordCountDemo.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.jun.plugin.mq.kafka.examples; - -import java.util.Arrays; -import java.util.Locale; -import java.util.Properties; -import java.util.concurrent.CountDownLatch; - -import org.apache.kafka.clients.consumer.ConsumerConfig; -import org.apache.kafka.common.serialization.Serdes; -import org.apache.kafka.streams.KafkaStreams; -import org.apache.kafka.streams.StreamsBuilder; -import org.apache.kafka.streams.StreamsConfig; -import org.apache.kafka.streams.kstream.KStream; -import org.apache.kafka.streams.kstream.KTable; -import org.apache.kafka.streams.kstream.KeyValueMapper; -import org.apache.kafka.streams.kstream.Produced; -import org.apache.kafka.streams.kstream.ValueMapper; - -/** - * Demonstrates, using the high-level KStream DSL, how to implement the WordCount program - * that computes a simple word occurrence histogram from an input text. - * - * In this example, the input stream reads from a topic named "streams-plaintext-input", where the values of messages - * represent lines of text; and the histogram output is written to topic "streams-wordcount-output" where each record - * is an updated count of a single word. - * - * Before running this example you must create the input topic and the output topic (e.g. via - * bin/kafka-topics.sh --create ...), and write some data to the input topic (e.g. via - * bin/kafka-console-producer.sh). Otherwise you won't see any data arriving in the output topic. - */ -public class WordCountDemo { - - public static void main(String[] args) throws Exception { - Properties props = new Properties(); - props.put(StreamsConfig.APPLICATION_ID_CONFIG, "streams-wordcount"); - props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "192.169.0.23:9092"); - props.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 0); - props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName()); - props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName()); - - // setting offset reset to earliest so that we can re-run the demo code with the same pre-loaded data - // Note: To re-run the demo, you need to use the offset reset tool: - // https://cwiki.apache.org/confluence/display/KAFKA/Kafka+Streams+Application+Reset+Tool - props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); - - StreamsBuilder builder = new StreamsBuilder(); - - KStream source = builder.stream("streams-plaintext-input"); - - KTable counts = source - .flatMapValues(new ValueMapper>() { - @Override - public Iterable apply(String value) { - return Arrays.asList(value.toLowerCase(Locale.getDefault()).split(" ")); - } - }) - .groupBy(new KeyValueMapper() { - @Override - public String apply(String key, String value) { - return value; - } - }) - .count(); - - // need to override value serde to Long type - counts.toStream().to("streams-wordcount-output", Produced.with(Serdes.String(), Serdes.Long())); - - final KafkaStreams streams = new KafkaStreams(builder.build(), props); - final CountDownLatch latch = new CountDownLatch(1); - - // attach shutdown handler to catch control-c - Runtime.getRuntime().addShutdownHook(new Thread("streams-wordcount-shutdown-hook") { - @Override - public void run() { - streams.close(); - latch.countDown(); - } - }); - - try { - streams.start(); - latch.await(); - } catch (Throwable e) { - System.exit(1); - } - System.exit(0); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/examples/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/examples/package-info.java deleted file mode 100644 index c7d64f2178..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/examples/package-info.java +++ /dev/null @@ -1,11 +0,0 @@ -/** - * - */ -/** - * Title: package-info - * Description: - * Version:1.0.0 - * @author pancm - * @date 2017年12月29日 - */ -package com.jun.plugin.mq.kafka.examples; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/others/TestConsumer.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/others/TestConsumer.java deleted file mode 100644 index c851f94533..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/others/TestConsumer.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.jun.plugin.mq.kafka.others; - -import java.util.Arrays; -import java.util.Properties; - -import org.apache.kafka.clients.consumer.ConsumerRecord; -import org.apache.kafka.clients.consumer.ConsumerRecords; -import org.apache.kafka.clients.consumer.KafkaConsumer; - -public class TestConsumer { - - public static void main(String[] args) { - Properties props = new Properties(); - - props.put("bootstrap.servers", "192.169.0.23:9092"); - System.out.println("this is the group part test 1"); - //消费者的组id - props.put("group.id", "GroupA");//这里是GroupA或者GroupB - - props.put("enable.auto.commit", "true"); - props.put("auto.commit.interval.ms", "1000"); - - //从poll(拉)的回话处理时长 - props.put("session.timeout.ms", "30000"); - //poll的数量限制 - //props.put("max.poll.records", "100"); - - props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); - - props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); - - KafkaConsumer consumer = new KafkaConsumer(props); - //订阅主题列表topic - consumer.subscribe(Arrays.asList("foo")); - while (true) { - ConsumerRecords records =consumer.poll(100); - for (ConsumerRecord record : records) - // 正常这里应该使用线程池处理,不应该在这里处理 - System.out.printf("offset = %d, key = %s, value = %s", record.offset(), record.key(), record.value()+"\n"); - } - } - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/others/TestProducer.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/others/TestProducer.java deleted file mode 100644 index 1899c621b5..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/others/TestProducer.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.jun.plugin.mq.kafka.others; - -import java.util.Properties; - -import org.apache.kafka.clients.producer.KafkaProducer; -import org.apache.kafka.clients.producer.Producer; -import org.apache.kafka.clients.producer.ProducerRecord; - -public class TestProducer { - public static void main(String[] args) { - System.out.println("开始..."); - Properties props = new Properties(); - props.put("bootstrap.servers", "192.169.0.23:9092"); - //The "all" setting we have specified will result in blocking on the full commit of the record, the slowest but most durable setting. - //“所有”设置将导致记录的完整提交阻塞,最慢的,但最持久的设置。 - props.put("acks", "all"); - //如果请求失败,生产者也会自动重试,即使设置成0 the producer can automatically retry. - props.put("retries", 0); - - //The producer maintains buffers of unsent records for each partition. - props.put("batch.size", 16384); - //默认立即发送,这里这是延时毫秒数 - props.put("linger.ms", 1); - //生产者缓冲大小,当缓冲区耗尽后,额外的发送调用将被阻塞。时间超过max.block.ms将抛出TimeoutException - props.put("buffer.memory", 33554432); - //The key.serializer and value.serializer instruct how to turn the key and value objects the user provides with their ProducerRecord into bytes. - props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); - props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); - - //创建kafka的生产者类 - Producer producer = new KafkaProducer(props); - long startTime=System.currentTimeMillis(); - producer.send(new ProducerRecord("test1",1,startTime,"a","b")); - producer.close(); - //生产者的主要方法 - // close();//Close this producer. - // close(long timeout, TimeUnit timeUnit); //This method waits up to timeout for the producer to complete the sending of all incomplete requests. - // flush() ;所有缓存记录被立刻发送 -// for(int i = 0; i < 100; i++){ -// //这里平均写入4个分区 -// producer.send(new ProducerRecord("foo",i%4, Integer.toString(i), Integer.toString(i))); -// producer.close(); -// } - System.out.println("结束"); - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/others/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/others/package-info.java deleted file mode 100644 index d7d4108f28..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/others/package-info.java +++ /dev/null @@ -1,11 +0,0 @@ -/** - * - */ -/** - * Title: package-info - * Description: - * Version:1.0.0 - * @author pancm - * @date 2017年12月29日 - */ -package com.jun.plugin.mq.kafka.others; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/package-info.java deleted file mode 100644 index bfaf18e805..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** - * Title: package-info - * Description: kafka的相关代码 - * Version:1.0.0 - * @author pancm - * @date 2018年1月11日 - */ -package com.jun.plugin.mq.kafka; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/test1/KafkaConsumerTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/test1/KafkaConsumerTest.java deleted file mode 100644 index e07652db44..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/test1/KafkaConsumerTest.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.jun.plugin.mq.kafka.test1; - -import java.util.Arrays; -import java.util.Properties; - -import org.apache.kafka.clients.consumer.ConsumerRecord; -import org.apache.kafka.clients.consumer.ConsumerRecords; -import org.apache.kafka.clients.consumer.KafkaConsumer; -import org.apache.kafka.common.serialization.StringDeserializer; - - -/** - * -* Title: KafkaConsumerTest -* Description: -* kafka消费者 demo -* Version:1.0.0 -* @author pancm -* @date 2018年1月26日 - */ -public class KafkaConsumerTest implements Runnable { - - private final KafkaConsumer consumer; - private ConsumerRecords msgList; - private String topic; - private static final String GROUPID = "groupA"; - - - - public KafkaConsumerTest(String topicName) { - Properties props = new Properties(); - //kafka消费的的地址 - props.put("bootstrap.servers", "master:9092,slave1:9092,slave2:9092"); - //组名 不同组名可以重复消费 - props.put("group.id", GROUPID); - //是否自动提交 - props.put("enable.auto.commit", "true"); - //从poll(拉)的回话处理时长 - props.put("auto.commit.interval.ms", "1000"); - //超时时间 - props.put("session.timeout.ms", "30000"); - //一次最大拉取的条数 - props.put("max.poll.records", 1000); -// earliest当各分区下有已提交的offset时,从提交的offset开始消费;无提交的offset时,从头开始消费 -// latest -// 当各分区下有已提交的offset时,从提交的offset开始消费;无提交的offset时,消费新产生的该分区下的数据 -// none -// topic各分区都存在已提交的offset时,从offset后开始消费;只要有一个分区不存在已提交的offset,则抛出异常 - props.put("auto.offset.reset", "earliest"); - //序列化 - props.put("key.deserializer", StringDeserializer.class.getName()); - props.put("value.deserializer", StringDeserializer.class.getName()); - this.consumer = new KafkaConsumer(props); - this.topic = topicName; - //订阅主题列表topic - this.consumer.subscribe(Arrays.asList(topic)); - - } - - @Override - public void run() { - int messageNo = 1; - System.out.println("---------开始消费---------"); - try { - for (;;) { - msgList = consumer.poll(100); - if(null!=msgList&&msgList.count()>0){ - for (ConsumerRecord record : msgList) { - //消费100条就打印 ,但打印的数据不一定是这个规律的 - if(messageNo%100==0){ - System.out.println(messageNo+"=======receive: key = " + record.key() + ", value = " + record.value()+" offset==="+record.offset()); - } - //当消费了1000条就退出 - if(messageNo%1000==0){ - break; - } - messageNo++; - } - }else{ - Thread.sleep(1000); - } - } - } catch (InterruptedException e) { - e.printStackTrace(); - } finally { - consumer.close(); - } - } - - public static void main(String args[]) { - KafkaConsumerTest test1 = new KafkaConsumerTest("KAFKA_TEST"); - Thread thread1 = new Thread(test1); - thread1.start(); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/test1/KafkaProducerTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/test1/KafkaProducerTest.java deleted file mode 100644 index 8b42e775aa..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/test1/KafkaProducerTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.jun.plugin.mq.kafka.test1; - -import java.util.Properties; - -import org.apache.kafka.clients.producer.KafkaProducer; -import org.apache.kafka.clients.producer.ProducerRecord; -import org.apache.kafka.common.serialization.StringSerializer; - - -/** - * -* Title: KafkaProducerTest -* Description: -* kafka 生产者demo -* Version:1.0.0 -* @author pancm -* @date 2018年1月26日 - */ -public class KafkaProducerTest implements Runnable { - - private final KafkaProducer producer; - private final String topic; - - - public KafkaProducerTest(String topicName) { - Properties props = new Properties(); - props.put("bootstrap.servers", "master:9092,slave1:9092,slave2:9092"); - //acks=0:如果设置为0,生产者不会等待kafka的响应。 - //acks=1:这个配置意味着kafka会把这条消息写到本地日志文件中,但是不会等待集群中其他机器的成功响应。 - //acks=all:这个配置意味着leader会等待所有的follower同步完成。这个确保消息不会丢失,除非kafka集群中所有机器挂掉。这是最强的可用性保证。 - props.put("acks", "all"); - //配置为大于0的值的话,客户端会在消息发送失败时重新发送。 - props.put("retries", 0); - //当多条消息需要发送到同一个分区时,生产者会尝试合并网络请求。这会提高client和生产者的效率 - props.put("batch.size", 16384); - props.put("key.serializer", StringSerializer.class.getName()); - props.put("value.serializer", StringSerializer.class.getName()); - this.producer = new KafkaProducer(props); - this.topic = topicName; - } - - @Override - public void run() { - int messageNo = 1; - try { - for(;;) { - String messageStr="你好,这是第"+messageNo+"条数据"; - producer.send(new ProducerRecord(topic, "Message", messageStr)); - //生产了100条就打印 - if(messageNo%100==0){ - System.out.println("发送的信息:" + messageStr); - } - //生产1000条就退出 - if(messageNo%1000==0){ - System.out.println("成功发送了"+messageNo+"条"); - break; - } - messageNo++; -// Utils.sleep(1); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - producer.close(); - } - } - - public static void main(String args[]) { - KafkaProducerTest test = new KafkaProducerTest("KAFKA_TEST"); - Thread thread = new Thread(test); - thread.start(); - } - - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/test1/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/test1/package-info.java deleted file mode 100644 index b4315b8d68..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/test1/package-info.java +++ /dev/null @@ -1,12 +0,0 @@ -/** - * - */ -/** - * Title: package-info - * Description: - * kafka demo - * Version:1.0.0 - * @author pancm - * @date 2018年2月9日 - */ -package com.jun.plugin.mq.kafka.test1; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/test2/KafkaConsumerTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/test2/KafkaConsumerTest.java deleted file mode 100644 index 2c46488e98..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/test2/KafkaConsumerTest.java +++ /dev/null @@ -1,112 +0,0 @@ -package com.jun.plugin.mq.kafka.test2; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Properties; - -import org.apache.kafka.clients.consumer.ConsumerRecord; -import org.apache.kafka.clients.consumer.ConsumerRecords; -import org.apache.kafka.clients.consumer.KafkaConsumer; -import org.apache.kafka.common.serialization.StringDeserializer; - - -/** - * -* Title: KafkaConsumerTest -* Description: -* kafka消费者 demo -* 手动提交测试 -* Version:1.0.0 -* @author pancm -* @date 2018年1月26日 - */ -public class KafkaConsumerTest implements Runnable { - - private KafkaConsumer consumer; - private ConsumerRecords msgList; - private String topic; - private static final String GROUPID = "groupE4"; - - - - public KafkaConsumerTest(String topicName) { - this.topic = topicName; - init(); - } - - @Override - public void run() { - System.out.println("---------开始消费---------"); - int messageNo = 1; - List list=new ArrayList(); - List list2=new ArrayList(); - try { - for (;;) { - msgList = consumer.poll(100); - if(null!=msgList&&msgList.count()>0){ - for (ConsumerRecord record : msgList) { - if(messageNo%10==0){ - System.out.println(messageNo+"=======receive: key = " + record.key() + ", value = " + record.value()+" offset==="+record.offset()); - } - list.add(record.value()); - list2.add(record.offset()); - messageNo++; - } - if(list.size()==50){ - // 手动提交 - consumer.commitSync(); - System.out.println("成功提交"+list.size()+"条,此时的offset为:"+list2.get(49)); - }else if(list.size()>50){ - consumer.close(); - init(); - list.clear(); - list2.clear(); - } - }else{ - Thread.sleep(1000); - } - } - } catch (InterruptedException e) { - e.printStackTrace(); - } finally { - consumer.close(); - } - } - - private void init() { - Properties props = new Properties(); - //kafka消费的的地址 - props.put("bootstrap.servers", "master:9092,slave1:9092,slave2:9092"); - //组名 不同组名可以重复消费 - props.put("group.id", GROUPID); - //是否自动提交 - props.put("enable.auto.commit", "false"); - //超时时间 - props.put("session.timeout.ms", "30000"); - //一次最大拉取的条数 - props.put("max.poll.records", 10); -// earliest当各分区下有已提交的offset时,从提交的offset开始消费;无提交的offset时,从头开始消费 -// latest -// 当各分区下有已提交的offset时,从提交的offset开始消费;无提交的offset时,消费新产生的该分区下的数据 -// none -// topic各分区都存在已提交的offset时,从offset后开始消费;只要有一个分区不存在已提交的offset,则抛出异常 - props.put("auto.offset.reset", "earliest"); - //序列化 - props.put("key.deserializer", StringDeserializer.class.getName()); - props.put("value.deserializer", StringDeserializer.class.getName()); - this.consumer = new KafkaConsumer(props); - //订阅主题列表topic - this.consumer.subscribe(Arrays.asList(topic)); - - System.out.println("初始化!"); - } - - - - public static void main(String args[]) { - KafkaConsumerTest test1 = new KafkaConsumerTest("KAFKA_TEST2"); - Thread thread1 = new Thread(test1); - thread1.start(); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/test2/KafkaProducerTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/test2/KafkaProducerTest.java deleted file mode 100644 index 74976d45da..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/test2/KafkaProducerTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.jun.plugin.mq.kafka.test2; - -import java.util.Properties; - -import org.apache.kafka.clients.producer.KafkaProducer; -import org.apache.kafka.clients.producer.ProducerRecord; -import org.apache.kafka.common.serialization.StringSerializer; - - -/** - * -* Title: KafkaProducerTest -* Description: -* kafka 生产者demo -* Version:1.0.0 -* @author pancm -* @date 2018年1月26日 - */ -public class KafkaProducerTest implements Runnable { - - private final KafkaProducer producer; - private final String topic; - - - public KafkaProducerTest(String topicName) { - Properties props = new Properties(); - props.put("bootstrap.servers", "master:9092,slave1:9092,slave2:9092"); - //acks=0:如果设置为0,生产者不会等待kafka的响应。 - //acks=1:这个配置意味着kafka会把这条消息写到本地日志文件中,但是不会等待集群中其他机器的成功响应。 - //acks=all:这个配置意味着leader会等待所有的follower同步完成。这个确保消息不会丢失,除非kafka集群中所有机器挂掉。这是最强的可用性保证。 - props.put("acks", "all"); - //配置为大于0的值的话,客户端会在消息发送失败时重新发送。 - props.put("retries", 0); - //当多条消息需要发送到同一个分区时,生产者会尝试合并网络请求。这会提高client和生产者的效率 - props.put("batch.size", 16384); - props.put("key.serializer", StringSerializer.class.getName()); - props.put("value.serializer", StringSerializer.class.getName()); - this.producer = new KafkaProducer(props); - this.topic = topicName; - } - - @Override - public void run() { - int messageNo = 1; - try { - for(;;) { - String messageStr="你好,这是第"+messageNo+"条数据"; - producer.send(new ProducerRecord(topic, "Message", messageStr)); - //生产了10条就打印 - if(messageNo%10==0){ - System.out.println("发送的信息:" + messageStr); - } - //生产100条就退出 - if(messageNo%100==0){ - System.out.println("成功发送了"+messageNo+"条"); - break; - } - messageNo++; -// Utils.sleep(1); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - producer.close(); - } - } - - public static void main(String args[]) { - KafkaProducerTest test = new KafkaProducerTest("KAFKA_TEST2"); - Thread thread = new Thread(test); - thread.start(); - } - - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/test2/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/test2/package-info.java deleted file mode 100644 index 20031c525f..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/test2/package-info.java +++ /dev/null @@ -1,12 +0,0 @@ -/** - * - */ -/** - * Title: package-info - * Description: - * kafka消费者 - * Version:1.0.0 - * @author pancm - * @date 2018年2月9日 - */ -package com.jun.plugin.mq.kafka.test2; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/test3/KafkaConsumerTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/test3/KafkaConsumerTest.java deleted file mode 100644 index 7320c6321f..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/test3/KafkaConsumerTest.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.jun.plugin.mq.kafka.test3; - -import java.util.Arrays; -import java.util.Properties; - -import org.apache.kafka.clients.consumer.ConsumerRecord; -import org.apache.kafka.clients.consumer.ConsumerRecords; -import org.apache.kafka.clients.consumer.KafkaConsumer; -import org.apache.kafka.common.serialization.StringDeserializer; - -/** - * -* Title: KafkaConsumerTest -* Description: -* kafka消费者 -* Version:1.0.0 -* @author pancm -* @date 2017年12月29日 - */ -public class KafkaConsumerTest extends Thread { - - private final KafkaConsumer consumer; - private ConsumerRecords msgList; - private final String topic; - private static final String GROUPID = "groupA1"; - private final String servers="master:9092,slave1:9092,slave2:9092"; - - public KafkaConsumerTest(String topicName) { - Properties props = new Properties(); - //kafka消费的的地址 - props.put("bootstrap.servers", servers); - //组名 不同组名可以重复消费 - props.put("group.id", GROUPID); - //是否自动提交 - props.put("enable.auto.commit", "false"); - //从poll(拉)的回话处理时长 - props.put("auto.commit.interval.ms", "1000"); - //超时时间 - props.put("session.timeout.ms", "30000"); - props.put("max.poll.records", "1000"); -// earliest当各分区下有已提交的offset时,从提交的offset开始消费;无提交的offset时,从头开始消费 -// latest -// 当各分区下有已提交的offset时,从提交的offset开始消费;无提交的offset时,消费新产生的该分区下的数据 -// none -// topic各分区都存在已提交的offset时,从offset后开始消费;只要有一个分区不存在已提交的offset,则抛出异常 - props.put("auto.offset.reset", "earliest"); - //序列化 - props.put("key.deserializer", StringDeserializer.class.getName()); - props.put("value.deserializer", StringDeserializer.class.getName()); - this.consumer = new KafkaConsumer(props); - this.topic = topicName; - //订阅者主题 - this.consumer.subscribe(Arrays.asList(topic)); - } - - @Override - public void run() { - - int messageNo = 0; - System.out.println("---------开始消费---------"); - try { - for (;;) { - msgList = consumer.poll(100); - if(null!=msgList&&msgList.count()>0){ -// System.out.println("msgList:"+msgList.count()); - for (ConsumerRecord record : msgList) { - //消费100条就打印 ,但打印的数据不一定是这个规律的 - if(messageNo%100==0){ - System.out.println(topic+" "+ "=======receive: key = " + record.key() + ", value = " + record.value()+" offset==="+record.offset()); -// consumer.commitAsync(); - } - -// if(messageNo==101){ -// System.out.println("=======receive: key = " + record.key() + ", value = " + record.value()+" offset==="+record.offset()); -// break; -// } -// //当消费了1000条就退出 -// if(messageNo%1000==0){ -// break; -// } - } - messageNo++; - }else{ - Thread.sleep(1000); - System.out.println("休眠中..."); - } - } - } catch (InterruptedException e) { - e.printStackTrace(); - } finally { - consumer.close(); - } - } - - public static void main(String args[]) { - KafkaConsumerTest test1 = new KafkaConsumerTest("TEST_INSERT"); - KafkaConsumerTest test2 = new KafkaConsumerTest("1001_INSERT"); - KafkaConsumerTest test3 = new KafkaConsumerTest("1002_INSERT"); - Thread thread1 = new Thread(test1); - Thread thread2 = new Thread(test2); - Thread thread3 = new Thread(test3); - thread1.start(); -// thread2.start(); -// thread3.start(); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/test3/KafkaConsumerTest3.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/test3/KafkaConsumerTest3.java deleted file mode 100644 index 8495cc8858..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/test3/KafkaConsumerTest3.java +++ /dev/null @@ -1,132 +0,0 @@ -package com.jun.plugin.mq.kafka.test3; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.ConcurrentHashMap; - -import org.apache.kafka.clients.consumer.ConsumerRecord; -import org.apache.kafka.clients.consumer.ConsumerRecords; -import org.apache.kafka.clients.consumer.KafkaConsumer; -import org.apache.kafka.common.TopicPartition; -import org.apache.kafka.common.serialization.StringDeserializer; - - -/** - * -* Title: KafkaConsumerTest -* Description: -* kafka消费者 demo -* 手动提交测试 指定分区和offset -* Version:1.0.0 -* @author pancm -* @date 2018年1月26日 - */ -public class KafkaConsumerTest3 implements Runnable { - - private KafkaConsumer consumer; - private ConsumerRecords msgList; - private String topic; - private static final String GROUPID = "groupF"; - - /**用于存放 分区所对应的offset */ - private ConcurrentHashMap map=new ConcurrentHashMap(); - - /**分区编号 */ - private int partId=0; - /**分区个数 */ - private int partSize=1; - private long offset=-1L; - - /**初始化标志*/ - private boolean flag = true; - - public KafkaConsumerTest3(String topicName) { - this.topic = topicName; - init(); - } - - @Override - public void run() { - System.out.println("---------开始消费---------"); - int messageNo = 1; - List list=new ArrayList(); - List list2=new ArrayList(); - TopicPartition p = new TopicPartition(topic,0); - consumer.assign(Arrays.asList(p)); - //指定分区和offset进行消费 - consumer.seek(p, 0); - try { - for (;;) { - msgList = consumer.poll(100); - if(null!=msgList&&msgList.count()>0){ - int tmpPartId=0; - for (ConsumerRecord record : msgList) { - if(messageNo%10==0){ - System.out.println(messageNo+"=======receive: partId ="+tmpPartId +", key = " + record.key() + ", value = " + record.value()+" offset==="+record.offset()); - } - } - // 手动提交 -// consumer.commitSync(); - }else{ - Thread.sleep(1000); - System.out.println("..."); - } - } - } catch (InterruptedException e) { - e.printStackTrace(); - } finally { - consumer.close(); - } - } - - private void saveOffset(int partId,long offset) { - map.put(partId, offset); - } - - - private long getOffset(int partId) { - return map.containsKey(partId)?map.get(partId):offset; - } - - private void init() { - Properties props = new Properties(); - //kafka消费的的地址 - props.put("bootstrap.servers", "master:9092,slave1:9092,slave2:9092"); - //组名 不同组名可以重复消费 - props.put("group.id", GROUPID); - //是否自动提交 - props.put("enable.auto.commit", "false"); - //超时时间 - props.put("session.timeout.ms", "30000"); - //一次最大拉取的条数 - props.put("max.poll.records", 10); -// earliest当各分区下有已提交的offset时,从提交的offset开始消费;无提交的offset时,从头开始消费 -// latest -// 当各分区下有已提交的offset时,从提交的offset开始消费;无提交的offset时,消费新产生的该分区下的数据 -// none -// topic各分区都存在已提交的offset时,从offset后开始消费;只要有一个分区不存在已提交的offset,则抛出异常 - props.put("auto.offset.reset", "earliest"); - //序列化 - props.put("key.deserializer", StringDeserializer.class.getName()); - props.put("value.deserializer", StringDeserializer.class.getName()); - this.consumer = new KafkaConsumer(props); - //订阅主题列表topic -// this.consumer.subscribe(Arrays.asList(topic)); - - if(consumer.partitionsFor(topic)!=null){ - this.partSize = consumer.partitionsFor(topic).size(); - } - - System.out.println("初始化!"); - } - - - - public static void main(String args[]) { - KafkaConsumerTest3 test1 = new KafkaConsumerTest3("TEST_INSERT"); - Thread thread1 = new Thread(test1); - thread1.start(); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/test3/KafkaProducerTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/test3/KafkaProducerTest.java deleted file mode 100644 index 89aaa42b34..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/test3/KafkaProducerTest.java +++ /dev/null @@ -1,128 +0,0 @@ -package com.jun.plugin.mq.kafka.test3; - -import java.util.Properties; - -import org.apache.kafka.clients.producer.KafkaProducer; -import org.apache.kafka.clients.producer.ProducerRecord; -import org.apache.kafka.common.serialization.StringSerializer; - -import com.alibaba.fastjson.JSONObject; - -/** - * -* Title: KafkaProducerTest -* Description: kafka生产者的消息测试 -* Version:1.0.0 -* @author pancm -* @date 2018年1月9日 - */ -public class KafkaProducerTest implements Runnable { - - private final KafkaProducer producer; - private final String topic; - private int k=10; - private final String servers="master:9092,slave1:9092,slave2:9092"; - /** - * @param topic 消息名称 - * @param - */ - public KafkaProducerTest(String topicName) { - Properties props = new Properties(); - props.put("bootstrap.servers", servers); - //acks=0:如果设置为0,生产者不会等待kafka的响应。 - //acks=1:这个配置意味着kafka会把这条消息写到本地日志文件中,但是不会等待集群中其他机器的成功响应。 - //acks=all:这个配置意味着leader会等待所有的follower同步完成。这个确保消息不会丢失,除非kafka集群中所有机器挂掉。这是最强的可用性保证。 - props.put("acks", "all"); - //配置为大于0的值的话,客户端会在消息发送失败时重新发送。 - props.put("retries", 0); - //当多条消息需要发送到同一个分区时,生产者会尝试合并网络请求。这会提高client和生产者的效率 - props.put("batch.size", 16384); - props.put("linger.ms", 1); - props.put("buffer.memory", 33554432); - props.put("key.serializer", StringSerializer.class.getName()); - props.put("value.serializer", StringSerializer.class.getName()); - this.producer = new KafkaProducer(props); - this.topic = topicName; - } - - @Override - public void run() { - int messageNo = 0; - long k=0L; - try { - while (true) { - JSONObject json=new JSONObject(); - k=239386111508899430L+messageNo; - String messageStr="INSERT INTO MT_TASK_HH ( ECID , PTMSGID , USERID , DTTYPE , " - + "MSGTYPE , USERUID , SPMSGID , ERRORCODE , RECVMTTIME , SENDTIME , RECVTIME , " - + "PHONE , SPGATESEND , SPNUMBER , MOBILEAREA , MOBILETYPE , MOBILECOUNTRY , " - + "NEXTGATETYPE , GATEIDBIND , SPGATEBIND , CPNOBIND , CPNO , ORDERCPNO , PROTYPE , " - + "RCHGTYPE , SVRTYPE , FEEFLAG , RETFLAG , PASSTHROUGH , JTYPE , SENDSTATUS , " - + "SENDLEVEL , SENDRESULT , RESENDCNT , TPUDHI , TPPID , PKTOTAL , PKNUMBER , MSGFMT ," - + " LONGMSGSEQ , SENDERRCODE , GATEIDSEND , SPID , PACKNUM , PACKPOS , NETERRCNT , " - + " ERRRESENDCNT , ERRORCODE2 , RPTEXFLAG , SENDFLAG , SUPPSNDCNT , SENDRPTTIME , " - + "TRANSMTTIME , MTSUBMITTIME , TRANSRPTTIME , MTSENDTIME , SUBMITTIME , DONETIME , " - + " PUSHRPTTIME , PRETRANSMTTM , ENDTRANSRPTTM , SUBMITDATE , DONEDATE , JPTCODE , " - + "PTCODE , LOGINUID , DESTUID , USERMSGID , SUPPMSGID , PREGATENO , LOCALGATENO , " - + " NEXTGATENO , SRCGATENO , NETWORKCODE , NETWORKID , CHARGETYPE , PRICE , CUSTID , " - + " USEREXDATA , USERSVRTYPE , SEQID , AGENTLOGINUID , MSGSRCIP , TMPLID , SPTMPLID ," - + " MSGTYPE1 , ACCTTYPE , PTRCHGID , CHARGOBJ , CHGRADE , VALIDTM , ERRORCODE3 , " - + " ERRORCODE4 , FIRSTDOWNTM , ENDDOWNTM , RDNRPTOKTM , RDNTRANSRPTTM , RECVRDNRPTTM , " - + " MESSAGE ) VALUES ('101034', '"+k+"', 'qian01', '1', '1', " - + "'100032', '2393861115088994305', 'DELIVRD', '2018-02-02 14:11:16', " - + "'2018-02-02 14:09:49', '2018-02-02 14:09:49', '13475676880', '2017022701', " - + "'20170227011', '30', '0', '86', '0', '901', '2017022701', '1', '', '', '0', " - + "'1', '', '2', '1', '0', '0', '0', '3', '0', '0', '0', '0', '1', '1', '0', '0', '0', " - + "'901', 'qianzi', '1', '1', '0', '0', 'DELIVRD', '0', '0', '0', '2018-02-02 14:11:16', " - + "'2018-02-02 14:09:49', '2018-02-02 14:09:49', '2018-02-02 14:11:16', " - + "'2018-02-02 14:09:49', '2018-02-02 14:11:49', '2018-02-02 14:11:49', " - + "'2018-02-02 14:11:16', '2018-02-02 14:11:16', '2018-02-02 14:09:49', '1802021411', " - + "'1802021411', '1050973', '16', '105692', '104473', '0', '0', '0', '2397', '0', '0', " - + "'0', '0', '0', '0.000000', '', '', '', '128', '105692', '192.169.1.32:2232', '0', ''," - + " '0', '0', '0', '0', '0', '4', '', '', '2000-01-01 00:00:00', '2000-01-01 00:00:00', " - + "'2000-01-01 00:00:00', '2000-01-01 00:00:00', '2000-01-01 00:00:00', 'AGEAcwBkAGEAcwBkAGEAcwBkAGEAcwBkAGEAcwBkAFsAbwBlAGUAcgBd');"; - -// String messageStr="222222222222222222222222222222222222222222222222222222222222222222"; - json.put("SQL", messageStr); - json.put("TIME", System.currentTimeMillis()); - json.put("PTMSGID", messageNo); - - producer.send(new ProducerRecord(topic, "Message"+messageNo, json.toJSONString())); - messageNo++; - //生产了100条就打印 - if(messageNo%10000==0){ -// System.out.println("Send:" + messageStr); - } - //生产100条就退出 - if(messageNo%500000==0){ - System.out.println(topic+"成功发送了"+messageNo+"条"); - break; - } -// Utils.sleep(1); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - producer.close(); - } - } - - public static void main(String args[]) { - KafkaProducerTest test = new KafkaProducerTest("1002_INSERT"); - KafkaProducerTest test1 = new KafkaProducerTest("1005_INSERT"); - KafkaProducerTest test2 = new KafkaProducerTest("1001_INSERT"); - KafkaProducerTest testd = new KafkaProducerTest("TEST_INSERT1"); - Thread thread = new Thread(test); - Thread thread1 = new Thread(test1); - Thread thread2 = new Thread(test2); - Thread threadD = new Thread(testd); - thread.start(); -// Utils.sleep(100); -// thread1.start(); -// Utils.sleep(100); -// thread2.start(); -// threadD.start(); - } - - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/test3/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/test3/package-info.java deleted file mode 100644 index 916176b983..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/kafka/test3/package-info.java +++ /dev/null @@ -1,11 +0,0 @@ -/** - * - */ -/** - * Title: package-info - * Description: - * Version:1.0.0 - * @author pancm - * @date 2018年3月15日 - */ -package com.jun.plugin.mq.kafka.test3; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/package-info.java deleted file mode 100644 index f19606a703..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: 消息中间件的一些类 -* @Version:1.0.0 -* @author pancm -* @date 2018年9月20日 -*/ -package com.jun.plugin.mq; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/rabbitmq/demo/C.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/rabbitmq/demo/C.java deleted file mode 100644 index 9b87ed25e3..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/rabbitmq/demo/C.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.jun.plugin.mq.rabbitmq.demo; - -import java.io.IOException; - -import com.rabbitmq.client.AMQP; -import com.rabbitmq.client.Channel; -import com.rabbitmq.client.Connection; -import com.rabbitmq.client.ConnectionFactory; -import com.rabbitmq.client.Consumer; -import com.rabbitmq.client.DefaultConsumer; -import com.rabbitmq.client.Envelope; - - -//消费者 -public class C { - - private final static String QUEUE_NAME = "RabbitMQ_Hello"; //消息队列名 - - public static void main(String[] argv) throws Exception { - // 创建连接工厂 - ConnectionFactory factory = new ConnectionFactory(); -// 设置RabbitMQ地址 - factory.setHost("127.0.0.1"); -// 创建一个新的连接 - Connection connection = factory.newConnection(); -// 创建一个频道 - Channel channel = connection.createChannel(); -// 声明要关注的队列 -- 在RabbitMQ中,队列声明是幂等性的(一个幂等操作的特点是其任意多次执行所产生的影响均与一次执行的影响相同),也就是说,如果不存在,就创建,如果存在,不会对已经存在的队列产生任何影响。 - channel.queueDeclare(QUEUE_NAME, false, false, false, null); - System.out.println("C [*] Waiting for messages. To exit press CTRL+C"); -// DefaultConsumer类实现了Consumer接口,通过传入一个频道,告诉服务器我们需要那个频道的消息,如果频道中有消息,就会执行回调函数handleDelivery - Consumer consumer = new DefaultConsumer(channel) { - @Override - public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { - String message = new String(body, "UTF-8"); - System.out.println("C [x] Received '" + message + "'"); - } - }; -// 自动回复队列应答 -- RabbitMQ中的消息确认机制 - channel.basicConsume(QUEUE_NAME, true, consumer); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/rabbitmq/demo/RabbitConsumer.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/rabbitmq/demo/RabbitConsumer.java deleted file mode 100644 index e9f9c47f25..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/rabbitmq/demo/RabbitConsumer.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.jun.plugin.mq.rabbitmq.demo; - -import com.rabbitmq.client.Channel; -import com.rabbitmq.client.Connection; -import com.rabbitmq.client.ConnectionFactory; -import com.rabbitmq.client.QueueingConsumer; - -//消费者 -public class RabbitConsumer { - - private final static String QUEUE_NAME = "RabbitMQ_Hello"; //消息队列名 - - public static void main(String[] argv) throws Exception { - - ConnectionFactory factory = new ConnectionFactory(); - factory.setHost("127.0.0.1"); - // 打开连接和创建频道,与发送端一样 - Connection connection = factory.newConnection(); - Channel channel = connection.createChannel(); - // 声明队列,主要为了防止消息接收者先运行此程序,队列还不存在时创建队列。 - channel.queueDeclare(QUEUE_NAME, false, false, false, null); - System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); - // 创建队列消费者 - QueueingConsumer consumer = new QueueingConsumer(channel); - // 指定消费队列 - channel.basicConsume(QUEUE_NAME, true, consumer); - while (true) { //消费者程序运行开着 如果生产者新增了数据会自动获取 - Thread.sleep(500); - // nextDelivery是一个阻塞方法(内部实现其实是阻塞队列的take方法) - QueueingConsumer.Delivery delivery = consumer.nextDelivery(); - String message = new String(delivery.getBody()); - System.out.println("'[x] Received '" + message ); - } - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/rabbitmq/demo/RabbitProducer.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/rabbitmq/demo/RabbitProducer.java deleted file mode 100644 index a2e9c86ec5..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/rabbitmq/demo/RabbitProducer.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.jun.plugin.mq.rabbitmq.demo; - -import java.util.HashMap; -import java.util.Map; - -import com.alibaba.fastjson.JSON; -import com.rabbitmq.client.Channel; -import com.rabbitmq.client.Connection; -import com.rabbitmq.client.ConnectionFactory; - -//生产者 -public class RabbitProducer { - private final static String QUEUE_NAME = "RabbitMQ_Hello"; //消息队列名 - - public static void main(String[] argv) throws Exception { - //创建连接连接到RabbitMQ - ConnectionFactory factory = new ConnectionFactory(); - // 设置ip - factory.setHost("127.0.0.1"); - /* //设置端口 - factory.setPort(15672); - //设置用户名 - factory.setUsername("guest"); - //设置密码 - factory.setPassword("guest"); - //设置url(包括ip、端口、用户名、密码) - factory.setUri("amqp://guest:guest@localhost:15672"); - */ - // 创建一个连接 - Connection connection = factory.newConnection(); - // 创建一个频道 - Channel channel = connection.createChannel(); - // 指定一个队列 - channel.queueDeclare(QUEUE_NAME, false, false, false, null); - Map map=new HashMap(); - map.put("java", "hello"); - map.put("RabbitMQ", "Hello"); - //发送的消息 - String message = JSON.toJSONString(map); - // 往队列中发出一条消息 - channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); - System.out.println(" [x] Sent '" + message + "'"); - // 关闭频道和连接 - channel.close(); - connection.close(); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/rabbitmq/one2more/NewTask.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/rabbitmq/one2more/NewTask.java deleted file mode 100644 index c84c777cfb..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/rabbitmq/one2more/NewTask.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.jun.plugin.mq.rabbitmq.one2more; - -import java.util.HashMap; -import java.util.Map; - -import com.rabbitmq.client.Channel; -import com.rabbitmq.client.Connection; -import com.rabbitmq.client.ConnectionFactory; -import com.rabbitmq.client.MessageProperties; - -//生产者 ( Producer:数据的发送方) -//单发送多接收 Worker.java和NewTask.java -public class NewTask { - - private static final String TASK_QUEUE_NAME = "task_queue"; - - public static void main(String[] argv) throws Exception { - // 创建工厂类 - ConnectionFactory factory = new ConnectionFactory(); - //factory.setHost("localhost"); - factory.setUri("amqp://guest:guest@172.26.129.3:5672"); - Connection connection = factory.newConnection(); - Channel channel = connection.createChannel(); - - channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null); - Map map=new HashMap(); - map.put("aa", 11); - map.put("bb", 22); - map.put("cc", 33); - String message = getMessage(argv); - - channel.basicPublish("", TASK_QUEUE_NAME, - MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes()); - System.out.println(" [x] Sent '" + message + "'"); - - channel.close(); - connection.close(); - } - - private static String getMessage(String[] strings) { - if (strings.length < 1) { - return "Hello!"; - } - return joinStrings(strings, " "); - } - - private static String joinStrings(String[] strings, String delimiter) { - int length = strings.length; - if (length == 0) { - return ""; - } - StringBuilder words = new StringBuilder(strings[0]); - for (int i = 1; i < length; i++) { - words.append(delimiter).append(strings[i]); - } - return words.toString(); - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/rabbitmq/one2more/Worker.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/rabbitmq/one2more/Worker.java deleted file mode 100644 index 8a469baacb..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/rabbitmq/one2more/Worker.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.jun.plugin.mq.rabbitmq.one2more; -import com.rabbitmq.client.Channel; -import com.rabbitmq.client.Connection; -import com.rabbitmq.client.ConnectionFactory; -import com.rabbitmq.client.QueueingConsumer; - //消费者 (Consumer:数据的接收方) - //单发送多接收 Worker.java和NewTask.java -public class Worker { - - private static final String TASK_QUEUE_NAME = "task_queue"; -// private static final String TASK_QUEUE_NAME = "tsk.hybris.productbrand.tsk"; - - public static void main(String[] argv) throws Exception { - - ConnectionFactory factory = new ConnectionFactory(); - //factory.setHost("localhost"); - factory.setUri("amqp://guest:guest@172.26.129.3:5672"); - Connection connection = factory.newConnection(); - Channel channel = connection.createChannel(); - - channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);//queue的持久化需要在声明时指定durable=True - System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); - //保证在接收端一个消息没有处理完时不会接收另一个消息 - channel.basicQos(1); - // channel.basicQos(0, 1, false); //这样RabbitMQ就会使得每个Consumer在同一个时间点最多处理一个Message。换句话说,在接收到该Consumer的ack前,他它不会将新的Message分发给它。 - - QueueingConsumer consumer = new QueueingConsumer(channel); - channel.basicConsume(TASK_QUEUE_NAME, false, consumer); - - while (true) { - QueueingConsumer.Delivery delivery = consumer.nextDelivery(); - String message = new String(delivery.getBody()); - - System.out.println(" [x] Received '" + message + "'"); - doWork(message); - System.out.println(" [x] Done"); - - channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); - } - } - - private static void doWork(String task) throws InterruptedException { - for (char ch: task.toCharArray()) { - if (ch == '.') { - Thread.sleep(1000); - } - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/rabbitmq/one2one/ClientReceive1.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/rabbitmq/one2one/ClientReceive1.java deleted file mode 100644 index 90daadfe70..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/rabbitmq/one2one/ClientReceive1.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.jun.plugin.mq.rabbitmq.one2one; -import java.net.URISyntaxException; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.util.concurrent.TimeoutException; - -import com.rabbitmq.client.Channel; -import com.rabbitmq.client.Connection; -import com.rabbitmq.client.ConnectionFactory; -import com.rabbitmq.client.QueueingConsumer; -public class ClientReceive1 { - public static final String queue_name="my_queue"; - public static final boolean autoAck=false; - public static final boolean durable=true; - public static void main(String[] args) - throws java.io.IOException,java.lang.InterruptedException, TimeoutException, KeyManagementException, NoSuchAlgorithmException, URISyntaxException{ - ConnectionFactory factory=new ConnectionFactory(); -// factory.setHost("localhost"); -// factory.setVirtualHost("my_mq"); -// factory.setUsername("zhxia"); -// factory.setPassword("123456"); - factory.setUri("amqp://guest:guest@172.26.129.3:5672");//获取url - Connection connection=factory.newConnection(); - Channel channel=connection.createChannel(); - channel.queueDeclare(queue_name, durable, false, false, null); - System.out.println("Wait for message"); - channel.basicQos(1); //消息分发处理 - QueueingConsumer consumer=new QueueingConsumer(channel); - channel.basicConsume(queue_name, autoAck, consumer); - while(true){ - Thread.sleep(500); - QueueingConsumer.Delivery deliver=consumer.nextDelivery(); - String message=new String(deliver.getBody()); - System.out.println("Message received:"+message); - channel.basicAck(deliver.getEnvelope().getDeliveryTag(), false); - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/rabbitmq/one2one/ClientSend1.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/rabbitmq/one2one/ClientSend1.java deleted file mode 100644 index a58904e15f..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/rabbitmq/one2one/ClientSend1.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.jun.plugin.mq.rabbitmq.one2one; -import java.net.URISyntaxException; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.util.concurrent.TimeoutException; - -import com.rabbitmq.client.Channel; -import com.rabbitmq.client.Connection; -import com.rabbitmq.client.ConnectionFactory; -import com.rabbitmq.client.MessageProperties; -public class ClientSend1 { - public static final String queue_name="my_queue"; - public static final boolean durable=true; //消息队列持久化 - public static void main(String[] args) - throws java.io.IOException, TimeoutException, KeyManagementException, NoSuchAlgorithmException, URISyntaxException{ - ConnectionFactory factory=new ConnectionFactory(); //创建连接工厂 -// factory.setHost("localhost"); -// factory.setVirtualHost("my_mq"); -// factory.setUsername("zhxia"); -// factory.setPassword("123456"); - factory.setUri("amqp://guest:guest@172.26.129.3:5672");//获取url - Connection connection=factory.newConnection(); //创建连接 - Channel channel=connection.createChannel();//创建信道 - channel.queueDeclare(queue_name, durable, false, false, null); //声明消息队列,且为可持久化的 - String message="Hello world"+Math.random(); - //将队列设置为持久化之后,还需要将消息也设为可持久化的,MessageProperties.PERSISTENT_TEXT_PLAIN - channel.basicPublish("", queue_name, MessageProperties.PERSISTENT_TEXT_PLAIN,message.getBytes()); - System.out.println("Send message:"+message); - channel.close(); - connection.close(); - } - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/rabbitmq/one2one/Recv.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/rabbitmq/one2one/Recv.java deleted file mode 100644 index 5c6295862f..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/rabbitmq/one2one/Recv.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.jun.plugin.mq.rabbitmq.one2one; -import java.util.ArrayList; -import java.util.List; - -import com.rabbitmq.client.Channel; -import com.rabbitmq.client.Connection; -import com.rabbitmq.client.ConnectionFactory; -import com.rabbitmq.client.QueueingConsumer; - - -//消费者 (Consumer:数据的接收方) -//单发送单接收 Send.java和Recv.java类 -public class Recv { - - private final static String QUEUE_NAME = "header_exchange"; - - public static void main(String[] argv) throws Exception { - - ConnectionFactory factory = new ConnectionFactory(); - // factory.setHost("localhost"); - // factory.setHost("127.0.0.1"); - factory.setUri("amqp://guest:guest@172.26.129.3:5672");//获取url - // 打开连接和创建频道,与发送端一样 - Connection connection = factory.newConnection(); - Channel channel = connection.createChannel(); - // 声明队列,主要为了防止消息接收者先运行此程序,队列还不存在时创建队列。 - channel.queueDeclare(QUEUE_NAME, false, false, false, null); - System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); - // 创建队列消费者 - QueueingConsumer consumer = new QueueingConsumer(channel); - // 指定消费队列 - channel.basicConsume(QUEUE_NAME, true, consumer); - while (true) { //消费者程序运行开着 如果生产者新增了数据会自动获取 - Thread.sleep(500); - List aa=new ArrayList(); - // nextDelivery是一个阻塞方法(内部实现其实是阻塞队列的take方法) - QueueingConsumer.Delivery delivery = consumer.nextDelivery(); - String message = new String(delivery.getBody()); - aa.add(message); - System.out.println("你好吗!"+" [x] Received '" + message + "'"+aa); - } - - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/rabbitmq/one2one/Send.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/rabbitmq/one2one/Send.java deleted file mode 100644 index 34f4679f7f..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/rabbitmq/one2one/Send.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.jun.plugin.mq.rabbitmq.one2one; -import java.util.HashMap; -import java.util.Map; - -import com.alibaba.fastjson.JSON; -import com.rabbitmq.client.Channel; -//生产者 ( Producer:数据的发送方) -//单发送单接收 //单发送单接收 Send.java和Recv.java类 -import com.rabbitmq.client.Connection; -import com.rabbitmq.client.ConnectionFactory; - -public class Send { - - private final static String QUEUE_NAME = "header_exchange"; //消息队列名 - - public static void main(String[] argv) throws Exception { - Map map=new HashMap(); - map.put("aa", 11); - map.put("bb", 22); - map.put("cc", 33); - map.put("dd", 44); - map.put("ff", 1); - System.out.println("你好啊!"); - //创建连接连接到MabbitMQ - ConnectionFactory factory = new ConnectionFactory(); - // 设置MabbitMQ所在主机ip或者主机名 - // factory.setHost("localhost"); - //factory.setHost("127.0.0.1"); - - factory.setUri("amqp://guest:guest@172.26.129.3:5672");//获取url - // 创建一个连接 - Connection connection = factory.newConnection(); - // 创建一个频道 - Channel channel = connection.createChannel(); - // 指定一个队列 - channel.queueDeclare(QUEUE_NAME, false, false, false, null); - //发送的消息 - String message = JSON.toJSONString(map); - // 往队列中发出一条消息 - channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); //发送 - System.out.println(" [x] Sent '" + message + "'"); - // 关闭频道和连接 - channel.close(); - connection.close(); - - - - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/rabbitmq/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/rabbitmq/package-info.java deleted file mode 100644 index fdc61b7dbf..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/mq/rabbitmq/package-info.java +++ /dev/null @@ -1,11 +0,0 @@ -/** - * - */ -/** - * Title: package-info - * Description: rabbitMq 消息队列测试 - * Version:1.0.0 - * @author pancm - * @date 2017年11月7日 - */ -package com.jun.plugin.mq.rabbitmq; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/ClientTestServer.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/ClientTestServer.java deleted file mode 100644 index 30150bc92a..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/ClientTestServer.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.jun.plugin.nio.mina; - -import java.net.InetSocketAddress; -import java.util.Arrays; -import java.util.HashMap; - -import org.apache.mina.core.future.ConnectFuture; -import org.apache.mina.core.service.IoConnector; -import org.apache.mina.core.session.IoSession; -import org.apache.mina.filter.codec.ProtocolCodecFilter; -import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory; -import org.apache.mina.transport.socket.nio.NioSocketConnector; - -import com.jun.plugin.nio.mina.demo.MinaClientHandler; - - -/** - * @author ZERO - * @Data 2017-5-12 上午10:25:57 - * @Description - */ -public class ClientTestServer { - - public IoConnector creatClient(){ - IoConnector connector=new NioSocketConnector(); - connector.setConnectTimeoutMillis(30000); - connector.getFilterChain().addLast("codec", - new ProtocolCodecFilter(new ObjectSerializationCodecFactory())); - connector.setHandler(new MinaClientHandler()); - return connector; - } - public IoSession getIOSession(IoConnector connector){ - ConnectFuture future = connector.connect(new InetSocketAddress("192.168.2.55", 1255)); - // 等待是否连接成功,相当于是转异步执行为同步执行。 - future.awaitUninterruptibly(); - // 连接成功后获取会话对象。 如果没有上面的等待, 由于connect()方法是异步的, session可能会无法获取。 - IoSession session = null; - try{ - session = future.getSession(); - }catch(Exception e){ - e.printStackTrace(); - } - return session; - } - public void sendMsg(IoSession session,String msg){ - - HashMap sy=new HashMap(); - sy.put("channel", "android"); - sy.put("deviceId", "12-ab"); - sy.put("device", "1456"); - sy.put("appVersion", "Version 1.5.1"); - sy.put("account", "This is test message"); - - sy.put("ss","client_bind"); - // logger.info("SentBody:"+sy); - // session.setAttribute("account","hello world"); - session.write(sy);// 发送消息 - } - public static void main(String[] args) { - for(int i=0;i<4000;i++){ - ClientTestServer client = new ClientTestServer(); - IoConnector connector = client.creatClient(); - IoSession session = client.getIOSession(connector); - client.sendMsg(session,Arrays.toString(new byte[1000])+":"+System.currentTimeMillis()); - } - - } - - } diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo/MinaClient.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo/MinaClient.java deleted file mode 100644 index 2c23044510..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo/MinaClient.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.jun.plugin.nio.mina.demo; - -import java.net.InetSocketAddress; -import java.util.HashMap; - -import org.apache.log4j.Logger; -import org.apache.mina.core.future.ConnectFuture; -import org.apache.mina.core.service.IoConnector; -import org.apache.mina.core.session.IoSession; -import org.apache.mina.filter.codec.ProtocolCodecFilter; -import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory; -import org.apache.mina.transport.socket.nio.NioSocketConnector; - - -/** - * @author ZERO - * @version 2017-3-27 下午5:59:54 - * mina 客户端 - */ -public class MinaClient { - private static Logger logger = Logger.getLogger(MinaClient.class); - private static String HOST = "127.0.0.1"; - private static int PORT = 1255; - private static IoConnector connector=new NioSocketConnector(); - private static IoSession session; - public static IoConnector getConnector() { - return connector; - } - - public static void setConnector(IoConnector connector) { - MinaClient.connector = connector; - } - - /* - * 测试服务端与客户端程序! - a. 启动服务端,然后再启动客户端 - b. 服务端接收消息并处理成功; - */ - @SuppressWarnings("deprecation") - public static void main(String[] args) { - // 设置链接超时时间 - connector.setConnectTimeout(30000); - // 添加过滤器 可序列话的对象 - connector.getFilterChain().addLast( - "codec", - new ProtocolCodecFilter(new ObjectSerializationCodecFactory())); - // 添加业务逻辑处理器类 - connector.setHandler(new MinaClientHandler()); - ConnectFuture future = connector.connect(new InetSocketAddress( - HOST, PORT));// 创建连接 - future.awaitUninterruptibly();// 等待连接创建完成 - session = future.getSession();// 获得session - - bindstart(); - pushstart(); - } - - public static void bindstart(){ - logger.info("客户端绑定服务端"); - // 创建一个非阻塞的客户端程序 - - try { - - HashMap sy=new HashMap(); - sy.put("channel", "xiaoai"); - sy.put("deviceId", "12-ab"); - sy.put("device", "1456"); - sy.put("appVersion", "Version 1.5.1"); - sy.put("account", "0030000100009702"); - - sy.put("client_bind","client_bind"); - logger.info("SentBody:"+sy); - // session.setAttribute("account","hello world"); - session.write(sy);// 发送消息 - logger.info("终端与服务端建立连接成功...发送的消息为:"+sy); - } catch (Exception e) { - e.printStackTrace(); - logger.error("客户端链接异常...", e); - } -// session.getCloseFuture().awaitUninterruptibly();// 等待连接断开 -// connector.dispose(); - } - - public static void pushstart(){ - logger.info("客户端请求服务端推送"); - // 创建一个非阻塞的客户端程序 - // IoConnector connector = new NioSocketConnector(); - // 设置链接超时时间 - try { - HashMap sy=new HashMap(); - sy.put("closeTV", "closeTV"); - sy.put("account", "0030000100009702"); //账号 - - sy.put("put","client_online"); - logger.info("SentBody:"+sy.toString()); - // session.setAttribute("account","hello world"); - session.write(sy);// 发送消息 - logger.info("客户端与服务端建立连接成功...发送的消息为:"+sy); - } catch (Exception e) { - e.printStackTrace(); - logger.error("客户端链接异常...", e); - } -// session.getCloseFuture().awaitUninterruptibly();// 等待连接断开 -// connector.dispose(); - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo/MinaClientHandler.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo/MinaClientHandler.java deleted file mode 100644 index 66d9ee1d02..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo/MinaClientHandler.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.jun.plugin.nio.mina.demo; - -import org.apache.log4j.Logger; -import org.apache.mina.core.service.IoHandlerAdapter; -import org.apache.mina.core.session.IoSession; - - -/** - * @author ZERO - * @version 2017-3-27 ??6:01:31 - * 客户端handle - */ -public class MinaClientHandler extends IoHandlerAdapter { - private static Logger logger = Logger.getLogger(MinaClientHandler.class); - - @Override - public void messageReceived(IoSession session, Object message) - throws Exception { - String msg = message.toString(); - logger.info("客户端接收的数据:" + msg); - // if(msg.equals(XiaoaiConstant.CMD_HEARTBEAT_REQUEST)){ - logger.warn("成功收到心跳包"); - // session.write(XiaoaiConstant.CMD_HEARTBEAT_RESPONSE); - // } - - } - - @Override - public void exceptionCaught(IoSession session, Throwable cause) - throws Exception { - logger.error("发生错误...", cause); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo/MinaServer.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo/MinaServer.java deleted file mode 100644 index b43b0a3dd8..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo/MinaServer.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.jun.plugin.nio.mina.demo; - -import java.net.InetSocketAddress; - -import org.apache.log4j.Logger; -import org.apache.mina.core.service.IoAcceptor; -import org.apache.mina.core.session.IdleStatus; -import org.apache.mina.filter.codec.ProtocolCodecFilter; -import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory; -import org.apache.mina.transport.socket.nio.NioSocketAcceptor; - - -/** - * @author ZERO: - * @version 2017-3-27 下午3:20:11 - * 创建服务端 - */ -public class MinaServer { - //记录日志 - public static Logger logger=Logger.getLogger(MinaServer.class); - private static int PORT=3333; - - /* 启动此类 提示服务端运行成功后 - * Windows 命令 输入 telnet 127.0.0.1 3305 - * 然后输入消息 message - * 消息为bye的时候关闭连接 - * */ - public static void main(String[] args) { - IoAcceptor ia=null; - try{ - //创建一个非堵塞的server端Socket - ia=new NioSocketAcceptor(); - //创建 协议编码解码过滤器ProtocolCodecFilter -// ProtocolCodecFilter pf=new ProtocolCodecFilter(new TextLineCodecFactory(Charset -// .forName("UTF-8"), -// LineDelimiter.WINDOWS.getValue(), -// LineDelimiter.WINDOWS.getValue())); - //设置端口 - InetSocketAddress pt=new InetSocketAddress(PORT); - // 设置过滤器(使用Mina提供的文本换行符编解码器) - ia.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory())); - //设置读取数据的缓存区大小 - ia.getSessionConfig().setReadBufferSize(2048); - //读写通道10秒内无操作进入空闲状态 - ia.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10); - //绑定逻辑处理器 - ia.setHandler(new MinaServerHandler()); - //绑定端口 - ia.bind(pt); - logger.info("服务端启动成功...端口号为:"+PORT); - - }catch(Exception e){ - logger.error("服务器的异常..."+e); - e.printStackTrace(); - } - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo/MinaServerHandler.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo/MinaServerHandler.java deleted file mode 100644 index 7c527f408d..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo/MinaServerHandler.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.jun.plugin.nio.mina.demo; - -import java.net.InetSocketAddress; -import java.util.Date; - -import org.apache.log4j.Logger; -import org.apache.mina.core.service.IoHandlerAdapter; -import org.apache.mina.core.session.IdleStatus; -import org.apache.mina.core.session.IoSession; - - -/** - * @author ZERO: - * @version 2017-3-27 下午3:59:33 - * 业务逻辑实现 - */ -public class MinaServerHandler extends IoHandlerAdapter { - public static Logger logger=Logger.getLogger(MinaServerHandler.class); - - @Override - public void sessionCreated(IoSession iosession) throws Exception{ - InetSocketAddress sa=(InetSocketAddress)iosession.getRemoteAddress(); - String address=sa.getAddress().getHostAddress(); //访问的ip - logger.info("服务端与客户端创建连接..."+"访问的IP:"+address); - } - - - @Override - public void sessionOpened(IoSession iosession) throws Exception{ - logger.info("服务端与客户端连接打开..."); - } - - @Override - public void messageReceived(IoSession session,Object message) throws Exception{ - String msg=message.toString(); - logger.info("服务端收到的数据为:"+msg); - if("bye".equals(msg)){ //服务端断开的条件 - session.close(); - } - Date date=new Date(); - session.write(date); //返回给服务端数据 - } - - @Override - public void messageSent(IoSession session, Object message) throws Exception { -// session.close(); //发送成功后主动断开与客户端的连接 - logger.info("服务端发送信息成功..."); - } - - @Override - public void sessionClosed(IoSession session) throws Exception { - } - - @Override - public void sessionIdle(IoSession session, IdleStatus status) - throws Exception { - logger.info("服务端进入空闲状态..."); - } - - @Override - public void exceptionCaught(IoSession session, Throwable cause) - throws Exception { - logger.error("服务端发送异常...", cause); - } - - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo1/MinaClient.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo1/MinaClient.java deleted file mode 100644 index 13099da102..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo1/MinaClient.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.jun.plugin.nio.mina.demo1; - -import java.net.InetSocketAddress; -import java.nio.charset.Charset; - -import org.apache.log4j.Logger; -import org.apache.mina.core.future.ConnectFuture; -import org.apache.mina.core.service.IoConnector; -import org.apache.mina.core.session.IoSession; -import org.apache.mina.filter.codec.ProtocolCodecFilter; -import org.apache.mina.transport.socket.nio.NioSocketConnector; - -/** - * @author ZERO - * @version 2017-3-27 下午5:59:54 - * mina 客户端 - */ -public class MinaClient { - private static Logger logger = Logger.getLogger(MinaClient.class); - private static String HOST = "127.0.0.1"; - private static int PORT = 3305; - - /* - * 测试服务端与客户端程序! - a. 启动服务端,然后再启动客户端(客户端发送的消息是"why are you so diao ") - b. 服务端接收消息并处理成功; - */ - public static void main(String[] args) { - // 创建一个非阻塞的客户端程序 - IoConnector connector = new NioSocketConnector(); - // 设置链接超时时间 - connector.setConnectTimeout(30000); - ProtocolCodecFilter pf=new ProtocolCodecFilter((new MyTextLineCodecFactory(Charset .forName("utf-8"), "\r\n"))); - // 添加过滤器 - connector.getFilterChain().addLast("codec", pf); - // 添加业务逻辑处理器类 - connector.setHandler(new MinaClientHandler()); - IoSession session = null; - try { - ConnectFuture future = connector.connect(new InetSocketAddress( - HOST, PORT));// 创建连接 - future.awaitUninterruptibly();// 等待连接创建完成 - session = future.getSession();// 获得session - String msg="hello \r\n"; - session.write(msg);// 发送消息 - logger.info("客户端与服务端建立连接成功...发送的消息为:"+msg); - } catch (Exception e) { - e.printStackTrace(); - logger.error("客户端链接异常...", e); - } - session.getCloseFuture().awaitUninterruptibly();// 等待连接断开 - connector.dispose(); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo1/MinaClientHandler.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo1/MinaClientHandler.java deleted file mode 100644 index 9fe3f85a27..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo1/MinaClientHandler.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.jun.plugin.nio.mina.demo1; - -import org.apache.log4j.Logger; -import org.apache.mina.core.service.IoHandlerAdapter; -import org.apache.mina.core.session.IoSession; - -/** - * @author ZERO - * @version 2017-3-27 下午6:01:31 - * 业务逻辑过滤器代码 - */ -public class MinaClientHandler extends IoHandlerAdapter { - private static Logger logger = Logger.getLogger(MinaClientHandler.class); - - @Override - public void messageReceived(IoSession session, Object message) - throws Exception { - String msg = message.toString(); - logger.info("客户端接收到的信息为:" + msg); - } - - @Override - public void exceptionCaught(IoSession session, Throwable cause) - throws Exception { - logger.error("客户端发生异常...", cause); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo1/MinaServer.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo1/MinaServer.java deleted file mode 100644 index 9d8fdc8bcf..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo1/MinaServer.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.jun.plugin.nio.mina.demo1; - -import java.net.InetSocketAddress; -import java.nio.charset.Charset; - -import org.apache.log4j.Logger; -import org.apache.mina.core.service.IoAcceptor; -import org.apache.mina.core.session.IdleStatus; -import org.apache.mina.filter.codec.ProtocolCodecFilter; -import org.apache.mina.transport.socket.nio.NioSocketAcceptor; - - - - - - -/** - * @author ZERO: - * @version 2017-3-28 上午10:20:11 - * 创建服务端 - */ -public class MinaServer { - //记录日志 - public static Logger logger=Logger.getLogger(MinaServer.class); - private static int PORT=3305; - - /* 启动此类 提示服务端运行成功后 - * Windows 命令 输入 telnet 127.0.0.1 3305 - * 然后输入消息 message - * 消息为bye的时候关闭连接 - * */ - public static void main(String[] args) { - new MinaServer().start(); - } - - public void start() { - IoAcceptor ia=null; - try{ - //创建一个非堵塞的server端Socket - ia=new NioSocketAcceptor(); - //创建 自定义协议编码解码过滤器ProtocolCodecFilter - ProtocolCodecFilter pf=new ProtocolCodecFilter((new MyTextLineCodecFactory(Charset .forName("utf-8"), "\r\n"))); - //设置端口 - InetSocketAddress pt=new InetSocketAddress(PORT); - // 设置过滤器(使用Mina提供的文本换行符编解码器) - ia.getFilterChain().addLast("codec", pf); - //设置读取数据的缓存区大小 - ia.getSessionConfig().setReadBufferSize(2048); - //读写通道10秒内无操作进入空闲状态 - ia.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10); - //绑定逻辑处理器 - ia.setHandler(new MinaServerHandler()); - //绑定端口 - ia.bind(pt); - logger.info("服务端启动成功...端口号为:"+PORT); - - }catch(Exception e){ - logger.error("服务器的异常..."+e); - e.printStackTrace(); - } - - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo1/MinaServerHandler.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo1/MinaServerHandler.java deleted file mode 100644 index 3dd01f347d..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo1/MinaServerHandler.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.jun.plugin.nio.mina.demo1; - -import java.util.Date; - -import org.apache.log4j.Logger; -import org.apache.mina.core.service.IoHandlerAdapter; -import org.apache.mina.core.session.IdleStatus; -import org.apache.mina.core.session.IoSession; - - -/** - * @author ZERO: - * @version 2017-3-27 下午3:59:33 - * 业务逻辑实现 - */ -public class MinaServerHandler extends IoHandlerAdapter { - public static Logger logger=Logger.getLogger(MinaServerHandler.class); - - @Override - public void sessionCreated(IoSession session) throws Exception{ - logger.info("服务端与客户端创建连接..."); - super.sessionCreated(session); - } - - - @Override - public void sessionOpened(IoSession session) throws Exception{ - logger.info("服务端与客户端连接打开..."); - super.sessionOpened(session); - } - - @Override - public void messageReceived(IoSession session,Object message) throws Exception{ - String msg=message.toString(); - logger.info("服务端收到的数据为:"+msg); - if("bye".equals(msg)){ //服务端断开的条件 - session.close(); - } - Date date=new Date(); - String mg="Come on:"+date; - logger.info("服务端返回给客户端的数据:"+mg); - session.write(mg); //返回给服务端数据 - } - - @Override - public void messageSent(IoSession session, Object message) throws Exception { - logger.info("服务端发送数据 = "+message); -// session.close(); //发送成功后主动断开与客户端的连接 实现短连接 - logger.info("服务端发送信息成功..."); - } - - @Override - public void sessionClosed(IoSession session) throws Exception { - logger.info("断开连接"); - super.sessionClosed(session); - } - - @Override - public void sessionIdle(IoSession session, IdleStatus status) - throws Exception { - logger.info("服务端进入空闲状态..."); - super.sessionIdle(session, status); - } - - @Override - public void exceptionCaught(IoSession session, Throwable cause) - throws Exception { - logger.error("服务端发送异常...", cause); - super.exceptionCaught(session, cause); - } - - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo1/MyTextLineCodecDecoder.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo1/MyTextLineCodecDecoder.java deleted file mode 100644 index df89cc0a05..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo1/MyTextLineCodecDecoder.java +++ /dev/null @@ -1,206 +0,0 @@ -package com.jun.plugin.nio.mina.demo1; - -import java.nio.charset.CharacterCodingException; -import java.nio.charset.Charset; -import java.nio.charset.CharsetDecoder; - -import org.apache.log4j.Logger; -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.session.IoSession; -import org.apache.mina.filter.codec.ProtocolDecoder; -import org.apache.mina.filter.codec.ProtocolDecoderOutput; - -/** - * @author ZERO - * @version 2017-3-28 上午10:44:55 - * 设置编码解码器 - */ - -public class MyTextLineCodecDecoder implements ProtocolDecoder { - private static Logger logger = Logger.getLogger(MyTextLineCodecDecoder.class); - - private Charset charset; // 编码格式 - - private String delimiter; // 文本分隔符 - private IoBuffer delimBuf; // 文本分割符匹配的变量 - - // 定义常量值,作为每个IoSession中保存解码任务的key值 - private static String CONTEXT = MyTextLineCodecDecoder.class.getName() + ".context"; - - public MyTextLineCodecDecoder(Charset charset,String delimiter){ - this.charset=charset; - this.delimiter=delimiter; - } - - - @Override - public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) - throws Exception { - Context ctx = getContext(session); - if (delimiter == null || "".equals(delimiter)) { - // 如果文本换行符未指定,使用默认值 - delimiter = "\r\n"; - } - - if (charset == null) { - charset = Charset.forName("utf-8"); - } - decodeNormal(ctx, in, out); - - } - - private void decodeNormal(Context ctx, IoBuffer in, ProtocolDecoderOutput out) throws CharacterCodingException { - - // 取出未完成任务中已经匹配的文本换行符的个数 - int matchCount = ctx.getMatchCount(); - - // 设置匹配文本换行符的IoBuffer变量 - if (delimBuf == null) { - IoBuffer tmp = IoBuffer.allocate(2).setAutoExpand(true); - tmp.putString(delimiter, charset.newEncoder()); - tmp.flip(); - delimBuf = tmp; - } - - //解码的IoBuffer中数据的原始信息 - int oldPos = in.position(); //输出值为0 - int oldLimit = in.limit(); //输出值为1 - - logger.info("******************************************************************************"); - logger.info("开始进入解码方法-----------------------------------------------------------------"); - logger.info(""); - logger.info("init Start--------------------------------------------------------------------"); - logger.info("in.postion() = "+oldPos); - logger.info("in.Limit() = "+oldLimit); - logger.info("in.capacity() = "+in.capacity()); - logger.info("matchCount = "+matchCount); - logger.info("init End---------------------------------------------------------------------"); - logger.info(""); - - //变量解码的IoBuffer - while (in.hasRemaining()) { - - byte b = in.get(); - logger.info(""); - logger.info("输入进来的字符为 = "+(char)b+",对应的ascii值 = "+b); - logger.info("in.position() = "+in.position()+",in.limit() = "+in.limit()); - logger.info(""); - - //当b的ascii值为13,10 即为\r,\n时,会进入下述if语句 - if (delimBuf.get(matchCount) == b) { - - // b='\r'时,matchCount=1, b='\n'时,matchCount=2 - matchCount++; - - logger.info("matchCount = "+matchCount); - //当前匹配到字节个数与文本换行符字节个数相同,即 b='\n'时 - //此时matchCount=2, delimBuf.limit()=2 - - if (matchCount == delimBuf.limit()) { - - // 获得当前匹配到的position(position前所有数据有效) - int pos = in.position(); //值为2 - logger.info("pos = "+pos); - - in.limit(pos); //值为2 - // position回到原始位置 - in.position(oldPos); //值为0 - - // 追加到Context对象未完成数据后面 - ctx.append(in); //将 \r\n这两个字符添加到 ctx.getBuf()中 - - // in中匹配结束后剩余数据 - in.limit(oldLimit); //值为2 - in.position(pos); //值为2 - - IoBuffer buf = ctx.getBuf(); //此时是得到 he\r\n - buf.flip(); //此时 buf.position=0,buf.limit()=4 - - buf.limit(buf.limit() - matchCount); //4-2 = 2 - try{ - // 输出解码内容 ,即 he - out.write(buf.getString(ctx.getDecoder())); - } - finally { - buf.clear(); // 释放缓存空间 - } - - matchCount = 0; - - } - }else { //h字符,e字符时,均会进入 此else逻辑判断中 - - //把in中未解码内容放回buf中 - //下面会在 输入的字符不是 \r\n时会需要保存使用 - in.position(oldPos); - ctx.append(in); - ctx.setMatchCount(matchCount); - } - } - } - - // 从IoSession中获取Context对象 - private Context getContext(IoSession session) { - Context ctx; - ctx = (Context) session.getAttribute(CONTEXT); - - if (ctx == null) { - ctx = new Context(); - session.setAttribute(CONTEXT, ctx); - } - return ctx; - } - - public void dispose(IoSession arg0) throws Exception { - // TODO Auto-generated method stub - - } - - public void finishDecode(IoSession arg0, ProtocolDecoderOutput arg1) - throws Exception { - // TODO Auto-generated method stub - } - - - // 内部类,保存IoSession解码时未完成的任务 - private class Context { - - private CharsetDecoder decoder; - private IoBuffer buf; - // 保存真实解码内容 - private int matchCount = 0; // 匹配到的文本换行符个数 - private Context() { - decoder = charset.newDecoder(); - buf = IoBuffer.allocate(80).setAutoExpand(true); - } - - // 重置 - public void reset() { - matchCount = 0; - decoder.reset(); - } - - // 追加数据 - public void append(IoBuffer in) { - getBuf().put(in); - } - - public CharsetDecoder getDecoder() { - return decoder; - } - - public IoBuffer getBuf() { - return buf; - } - - public int getMatchCount() { - return matchCount; - } - - public void setMatchCount(int matchCount) { - this.matchCount = matchCount; - } - } - - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo1/MyTextLineCodecEncoder.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo1/MyTextLineCodecEncoder.java deleted file mode 100644 index 46ae9218f7..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo1/MyTextLineCodecEncoder.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.jun.plugin.nio.mina.demo1; - -import java.nio.charset.Charset; - -import org.apache.log4j.Logger; -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.session.IoSession; -import org.apache.mina.filter.codec.ProtocolEncoder; -import org.apache.mina.filter.codec.ProtocolEncoderOutput; - -/** - * @author ZERO - * @version 2017-3-28 上午11:30:55 - * 设置编码构造器 - */ -public class MyTextLineCodecEncoder implements ProtocolEncoder{ - - private static Logger logger = Logger.getLogger(MyTextLineCodecEncoder.class); - - private Charset charset; // 编码格式 - private String delimiter; // 文本分隔符 - public MyTextLineCodecEncoder(Charset charset, String delimiter) { - this.charset = charset; - this.delimiter = delimiter; - } - - public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception { - logger.info("开始进入编码方法-----------------------------------------------------------------"); - // 如果文本换行符未指定,使用默认值 - if (delimiter == null || "".equals(delimiter)) { - delimiter = "\r\n"; - } - - if (charset == null) { - charset = Charset.forName("utf-8"); - } - - String value = message.toString(); - IoBuffer buf = IoBuffer.allocate(value.length()).setAutoExpand(true); - //真实数据 - buf.putString(value, charset.newEncoder()); - //文本换行符 - buf.putString(delimiter, charset.newEncoder()); - buf.flip(); - out.write(buf); - } - - public void dispose(IoSession session) throws Exception {} - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo1/MyTextLineCodecFactory.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo1/MyTextLineCodecFactory.java deleted file mode 100644 index 6ba004bbef..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/demo1/MyTextLineCodecFactory.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.jun.plugin.nio.mina.demo1; - -import java.nio.charset.Charset; - -import org.apache.mina.core.session.IoSession; -import org.apache.mina.filter.codec.ProtocolCodecFactory; -import org.apache.mina.filter.codec.ProtocolDecoder; -import org.apache.mina.filter.codec.ProtocolEncoder; - -/** - * @author ZERO - * @version 2017-3-28 上午11:39:50 - * 编码格式工厂 - */ -public class MyTextLineCodecFactory implements ProtocolCodecFactory { - - private Charset charset; // 编码格式 - private String delimiter; // 文本分隔符 - public MyTextLineCodecFactory(Charset charset, String delimiter) { - this.charset = charset; - this.delimiter = delimiter; - } - - - public ProtocolDecoder getDecoder(IoSession session) throws Exception { - return new MyTextLineCodecDecoder(charset, delimiter); - } - - - public ProtocolEncoder getEncoder(IoSession session) throws Exception { - return new MyTextLineCodecEncoder(charset, delimiter); - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/package-info.java deleted file mode 100644 index 0a03c90c25..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/mina/package-info.java +++ /dev/null @@ -1,11 +0,0 @@ -/** - * - */ -/** - * Title: package-info - * Description: Mina测试 - * Version:1.0.0 - * @author pancm - * @date 2017-3-27 - */ -package com.jun.plugin.nio.mina; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo/NettyClient.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo/NettyClient.java deleted file mode 100644 index bbce19e63d..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo/NettyClient.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.jun.plugin.nio.netty.demo; - - -import java.io.IOException; - -import io.netty.bootstrap.Bootstrap; -import io.netty.channel.Channel; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.nio.NioSocketChannel; -/** - * -* Title: NettyClient -* Description: Netty客户端 -* Version:1.0.0 -* @author Administrator -* @date 2017-8-31 - */ -public class NettyClient { - - public static String host = "127.0.0.1"; //ip地址 - public static int port = 6789; //端口 - /// 通过nio方式来接收连接和处理连接 - private static EventLoopGroup group = new NioEventLoopGroup(); - private static Bootstrap b = new Bootstrap(); - private static Channel ch; - - /** - * Netty创建全部都是实现自AbstractBootstrap。 - * 客户端的是Bootstrap,服务端的则是 ServerBootstrap。 - **/ - public static void main(String[] args) throws InterruptedException, IOException { - System.out.println("客户端成功启动..."); - b.group(group); - b.channel(NioSocketChannel.class); - b.handler(new NettyClientFilter()); - // 连接服务端 - ch = b.connect(host, port).sync().channel(); - star(); - } - - public static void star() throws IOException{ - String str="Hello Netty"; - ch.writeAndFlush(str); -// ch.writeAndFlush(str+ "\r\n"); - System.out.println("客户端发送数据:"+str); - } - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo/NettyClientFilter.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo/NettyClientFilter.java deleted file mode 100644 index 111f208054..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo/NettyClientFilter.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.jun.plugin.nio.netty.demo; - - -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.socket.SocketChannel; -import io.netty.handler.codec.string.StringDecoder; -import io.netty.handler.codec.string.StringEncoder; -/** - * -* Title: NettyClientFilter -* Description: Netty客户端 过滤器 -* Version:1.0.0 -* @author Administrator -* @date 2017-8-31 - */ -public class NettyClientFilter extends ChannelInitializer { - - @Override - protected void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline ph = ch.pipeline(); - /* - * 解码和编码,应和服务端一致 - * */ -// ph.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter())); - ph.addLast("decoder", new StringDecoder()); - ph.addLast("encoder", new StringEncoder()); - ph.addLast("handler", new NettyClientHandler()); //客户端的逻辑 - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo/NettyClientHandler.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo/NettyClientHandler.java deleted file mode 100644 index b906f3bfe5..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo/NettyClientHandler.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.jun.plugin.nio.netty.demo; - -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.SimpleChannelInboundHandler; - -/** - * -* Title: NettyClientHandler -* Description: 客户端业务逻辑实现 -* Version:1.0.0 -* @author Administrator -* @date 2017-8-31 - */ -public class NettyClientHandler extends SimpleChannelInboundHandler { - - @Override - protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { - System.out.println("客户端接受的消息: " + msg); - } - - // - @Override - public void channelActive(ChannelHandlerContext ctx) throws Exception { - System.out.println("正在连接... "); - super.channelActive(ctx); - } - - @Override - public void channelInactive(ChannelHandlerContext ctx) throws Exception { - System.out.println("连接关闭! "); - super.channelInactive(ctx); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo/NettyServer.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo/NettyServer.java deleted file mode 100644 index 2d049f67d5..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo/NettyServer.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.jun.plugin.nio.netty.demo; - -import io.netty.bootstrap.ServerBootstrap; -import io.netty.channel.ChannelFuture; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.nio.NioServerSocketChannel; - -/** - * -* Title: NettyServer -* Description: Netty服务端 -* Version:1.0.0 -* @author Administrator -* @date 2017-8-31 - */ -public class NettyServer { - private static final int port = 6789; //设置服务端端口 - private static EventLoopGroup group = new NioEventLoopGroup(); // 通过nio方式来接收连接和处理连接 - private static ServerBootstrap b = new ServerBootstrap(); - - /** - * Netty创建全部都是实现自AbstractBootstrap。 - * 客户端的是Bootstrap,服务端的则是 ServerBootstrap。 - **/ - public static void main(String[] args) throws InterruptedException { - try { - b.group(group); - b.channel(NioServerSocketChannel.class); - b.childHandler(new NettyServerFilter()); //设置过滤器 - // 异步地绑定服务器;调用 sync()方法阻塞 等待直到绑定完成 - ChannelFuture f = b.bind(port).sync(); - System.out.println("服务端启动成功,端口是:"+port); - // 获取 Channel 的 CloseFuture,并且阻塞当前线程直到它完成 - f.channel().closeFuture().sync(); - } finally { - group.shutdownGracefully(); //关闭EventLoopGroup,释放掉所有资源包括创建的线程 - } - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo/NettyServerFilter.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo/NettyServerFilter.java deleted file mode 100644 index ea45055626..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo/NettyServerFilter.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.jun.plugin.nio.netty.demo; - - -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.socket.SocketChannel; -import io.netty.handler.codec.string.StringDecoder; -import io.netty.handler.codec.string.StringEncoder; - -/** - * - * Title: HelloServerInitializer - * Description: Netty 服务端过滤器 - * Version:1.0.0 - * @author Administrator - * @date 2017-8-31 - */ -public class NettyServerFilter extends ChannelInitializer { - - @Override - protected void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline ph = ch.pipeline(); - // 以("\n")为结尾分割的 解码器 -// ph.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter())); - // 解码和编码,应和客户端一致 - ph.addLast("decoder", new StringDecoder()); - ph.addLast("encoder", new StringEncoder()); - ph.addLast("handler", new NettyServerHandler());// 服务端业务逻辑 - } - } diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo/NettyServerHandler.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo/NettyServerHandler.java deleted file mode 100644 index 382ce4f011..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo/NettyServerHandler.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.jun.plugin.nio.netty.demo; - -import java.net.InetAddress; -import java.util.Date; - -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.SimpleChannelInboundHandler; - - -/** - * -* Title: HelloServerHandler -* Description: 服务端业务逻辑 -* Version:1.0.0 -* @author Administrator -* @date 2017-8-31 - */ -public class NettyServerHandler extends SimpleChannelInboundHandler { - /* - * 收到消息时,返回信息 - */ - @Override - protected void channelRead0(ChannelHandlerContext ctx, String msg) - throws Exception { - // 收到消息直接打印输出 - System.out.println("服务端接受的消息 : " + msg); - if("quit".equals(msg)){//服务端断开的条件 - ctx.close(); - } - // 返回客户端消息 -// ctx.writeAndFlush("收到消息:"+ msg+",当前的时间是:"+MyTools.getNowTime("")+"\n"); - ctx.writeAndFlush("收到消息:"+ msg+",当前的时间是:"+new Date()); - } - - /* - * 建立连接时,返回消息 - */ - @Override - public void channelActive(ChannelHandlerContext ctx) throws Exception { - System.out.println("连接的客户端地址:" + ctx.channel().remoteAddress()); - ctx.writeAndFlush("客户端"+ InetAddress.getLocalHost().getHostName() + "成功与服务端建立连接! "); - super.channelActive(ctx); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo1/BaseClient1Handler.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo1/BaseClient1Handler.java deleted file mode 100644 index d783ea9487..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo1/BaseClient1Handler.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.jun.plugin.nio.netty.demo1; - -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelInboundHandlerAdapter; - -/** - * -* Title: BaseClient1Handler -* Description: 客户端自定义解码器其一 -* Version:1.0.0 -* @author panchengming -* @date 2017年9月17日 - */ -public class BaseClient1Handler extends ChannelInboundHandlerAdapter{ - @Override - public void channelActive(ChannelHandlerContext ctx) throws Exception { - System.out.println("BaseClient1Handler channelActive"); -// ctx.fireChannelActive(); - } - - @Override - public void channelInactive(ChannelHandlerContext ctx) throws Exception { - System.out.println("BaseClient1Handler channelInactive"); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo1/BaseClient2Handler.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo1/BaseClient2Handler.java deleted file mode 100644 index b250db41a6..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo1/BaseClient2Handler.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.jun.plugin.nio.netty.demo1; - -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelInboundHandlerAdapter; - -/** - * -* Title: BaseClient2Handler -* Description: 客户端自定义解码器其二 -* Version:1.0.0 -* @author panchengming -* @date 2017年9月17日 - */ -public class BaseClient2Handler extends ChannelInboundHandlerAdapter{ - - @Override - public void channelActive(ChannelHandlerContext ctx) throws Exception { - System.out.println("BaseClient2Handler Active"); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo1/NettyClient.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo1/NettyClient.java deleted file mode 100644 index c3fdf4b7cc..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo1/NettyClient.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.jun.plugin.nio.netty.demo1; - -import io.netty.bootstrap.Bootstrap; -import io.netty.channel.Channel; -import io.netty.channel.ChannelFuture; -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelOption; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.SocketChannel; -import io.netty.channel.socket.nio.NioSocketChannel; -import io.netty.handler.codec.string.StringDecoder; -import io.netty.handler.codec.string.StringEncoder; - - -/** - * -* Title: NettyClient -* Description:Netty客户端 测试 -* Version:1.0.0 -* @author Administrator -* @date 2017-8-31 - */ -public class NettyClient { - private static final int port = 1234; - private static final String host = "127.0.0.1"; - private static EventLoopGroup group = new NioEventLoopGroup(); // 通过nio方式来接收连接和处理连接 - private static Bootstrap b = new Bootstrap(); - private static Channel ch ; - /** - * Netty创建全部都是实现自AbstractBootstrap。 - * 客户端的是Bootstrap,服务端的则是 ServerBootstrap。 - **/ - public static void main(String[] args) throws Exception { - try{ - b.group(group) - .channel(NioSocketChannel.class) - .option(ChannelOption.TCP_NODELAY, true) - .handler(new ChannelInitializer() { - @Override - public void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline p = ch.pipeline(); - p.addLast("decoder", new StringDecoder()); - p.addLast("encoder", new StringEncoder()); - p.addLast(new BaseClient1Handler()); - p.addLast(new BaseClient2Handler()); - } - }); - - ChannelFuture future = b.connect(host, port).sync(); // 连接服务端 - System.out.println("客户端连接成功!"); - future.channel().writeAndFlush("Hello Netty Server ,I am a common client");//发送消息 - future.channel().closeFuture().sync(); //关闭 - } finally { - group.shutdownGracefully(); //释放资源 - } - - // start(); - } - - public static void start() throws Exception { - System.out.println("客户端像服务端发送数据"); - try { - String str="Hello Netty"; - ch.writeAndFlush(str+"\r\n");//发送消息 - System.out.println("客户端发送的消息:"+str); - ch.closeFuture().sync(); // 应用程序会一直等待,直到channel关闭 - } finally { - // group.shutdownGracefully().sync(); //关闭EventLoopGroup,释放掉所有资源包括创建的线程 - } - } - - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo1/NettyClientHandler.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo1/NettyClientHandler.java deleted file mode 100644 index 728c15e28c..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo1/NettyClientHandler.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.jun.plugin.nio.netty.demo1; - -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.SimpleChannelInboundHandler; - -/** - * -* Title: NettyClientHandler -* Description:客户端业务逻辑 -* Version:1.0.0 -* @author Administrator -* @date 2017-8-31 - */ -public class NettyClientHandler extends SimpleChannelInboundHandler { - - @Override - protected void channelRead0(ChannelHandlerContext chc, String str) - throws Exception { - // TODO Auto-generated method stub - System.out.println("消息为:"+str); - - } - - @Override - public void channelActive(ChannelHandlerContext chc) throws Exception { - System.out.println("正在连接..."); - super.channelActive(chc); - } - - @Override - public void channelInactive(ChannelHandlerContext chc) throws Exception { - System.out.println("连接关闭"); - super.channelInactive(chc); - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo1/NettyServer.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo1/NettyServer.java deleted file mode 100644 index d1a0f9c3db..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo1/NettyServer.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.jun.plugin.nio.netty.demo1; - -import io.netty.bootstrap.ServerBootstrap; -import io.netty.channel.ChannelFuture; -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.SocketChannel; -import io.netty.channel.socket.nio.NioServerSocketChannel; -import io.netty.handler.codec.string.StringDecoder; -import io.netty.handler.codec.string.StringEncoder; - - - - - -/** - * -* Title: NettyServer -* Description: Netty服务端 测试自定义channelhandler -* Version:1.0.0 -* @author Administrator -* @date 2017-8-31 - */ - -public class NettyServer { - private static final int port = 1234; - public static void main(String[] args) { - System.out.println("开始运行..."); - try { - start(); - } catch (InterruptedException e) { - System.out.println("运行异常..."); - e.printStackTrace(); - } - } - - /** - * Netty创建全部都是实现自AbstractBootstrap。 - * 客户端的是Bootstrap,服务端的则是 ServerBootstrap。 - **/ - public static void start() throws InterruptedException { - ServerBootstrap sb = new ServerBootstrap();// 引导辅助程序 - EventLoopGroup group = new NioEventLoopGroup();// 通过nio方式来接收连接和处理连接 - try { - sb.group(group); // 通过nio方式来接收连接和处理连接 - sb.channel(NioServerSocketChannel.class);// 设置nio类型的channel - sb.childHandler(new ChannelInitializer() {//有连接到达时会创建一个channel - protected void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline p = ch.pipeline(); - - // 字符串解码 和 编码 - p.addLast("decoder", new StringDecoder()); - p.addLast("encoder", new StringEncoder()); - // 在channel队列中添加一个handler来处理业务 - p.addLast("handler", new NettyServerHandler()); - // 以("\n")为结尾分割的 解码器 - // cp.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter())); - } - }); - ChannelFuture f = sb.bind(port).sync();// 配置完成,开始绑定server,通过调用sync同步方法阻塞直到绑定成功 - System.out.println("服务端已启动... 端口是:"+port); - f.channel().closeFuture().sync();// 应用程序会一直等待,直到channel关闭 - } catch (Exception e) { - e.printStackTrace(); - } finally { - // group.shutdownGracefully().sync();//关闭EventLoopGroup,释放掉所有资源包括创建的线程 - } - - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo1/NettyServerHandler.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo1/NettyServerHandler.java deleted file mode 100644 index 3e3d5c996e..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo1/NettyServerHandler.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.jun.plugin.nio.netty.demo1; - -import java.net.InetAddress; - -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.SimpleChannelInboundHandler; - -/** - * -* Title: NettyServerHandler -* Description:Netty服务端业务逻辑实现 -* Version:1.0.0 -* @author Administrator -* @date 2017-8-31 - */ - - -public class NettyServerHandler extends SimpleChannelInboundHandler { - - @Override - protected void channelRead0(ChannelHandlerContext ctx, String msg) - throws Exception { - // 收到消息直接打印输出 - System.out.println(ctx.channel().remoteAddress() + " Say : " + msg); - - // 返回客户端消息 - 我已经接收到了你的消息 - ctx.writeAndFlush("Received your message !\n"); - } - - /* - * - * 覆盖 channelActive 方法 在channel被启用的时候触发 (在建立连接的时候) - * - * channelActive 和 channelInActive 在后面的内容中讲述,这里先不做详细的描述 - */ - @Override - public void channelActive(ChannelHandlerContext ctx) throws Exception { - - System.out.println("连接的客户端地址:" + ctx.channel().remoteAddress()); - ctx.writeAndFlush("客户端"+ InetAddress.getLocalHost().getHostName() + "成功与服务端建立连接! \n"); - super.channelActive(ctx); - } - -} - - - -/** - * Sharable表示此对象在channel间共享 - * handler类是我们的具体业务类 - * */ -/*@Sharable//注解@Sharable可以让它在channels间共享 -public class NettyServerHandler extends ChannelInboundHandlerAdapter { - public void channelRead(ChannelHandlerContext ctx, Object msg) { - System.out.println("服务端接受的数据为:" + msg); - if("quit".equals(msg)){ //服务端断开的条件 - ctx.close(); - } - Date date=new Date(); - ctx.write(date);//回写数据 - } - public void channelReadComplete(ChannelHandlerContext ctx) { - System.out.println("1111"); - ctx.writeAndFlush(Unpooled.EMPTY_BUFFER) //flush掉所有写回的数据 - .addListener(ChannelFutureListener.CLOSE); //当flush完成后关闭channel - } - public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause) { - System.out.println("2222"); - cause.printStackTrace();//捕捉异常信息 - ctx.close();//出现异常时关闭channel - } -}*/ diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo2/NettyClientDemo2.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo2/NettyClientDemo2.java deleted file mode 100644 index 66226217b2..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo2/NettyClientDemo2.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.jun.plugin.nio.netty.demo2; - -import java.io.IOException; - -import io.netty.bootstrap.Bootstrap; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; -import io.netty.channel.Channel; -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelOption; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.SocketChannel; -import io.netty.channel.socket.nio.NioSocketChannel; -import io.netty.handler.codec.string.StringDecoder; - -/** - * -* Title: NettyClientDemo2 -* Description: Netty客户端 用于测试粘包、拆包 -* Version:1.0.0 -* @author pancm -* @date 2017年9月20日 - */ -public class NettyClientDemo2 { - public static String host = "127.0.0.1"; //ip地址 - public static int port = 2345; //端口 - /// 通过nio方式来接收连接和处理连接 - private static EventLoopGroup group = new NioEventLoopGroup(); - private static Bootstrap b = new Bootstrap(); - private static Channel ch; - - /** - * Netty创建全部都是实现自AbstractBootstrap。 - * 客户端的是Bootstrap,服务端的则是ServerBootstrap。 - **/ - public static void main(String[] args) throws InterruptedException, IOException { - b.group(group) - .channel(NioSocketChannel.class) - .option(ChannelOption.TCP_NODELAY,true) - .handler(new ChannelInitializer() { - @Override - public void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline p = ch.pipeline(); - p.addLast(new StringDecoder()); //绑定解码器 - p.addLast(new NettyClientHandlerDemo2()); //绑定自定义业务 - } - }); - // 连接服务端 - ch = b.connect(host, port).sync().channel(); - System.out.println("客户端成功启动..."); - // star(); - } - - public static void star() throws IOException{ - String str="你好 Netty!"; - byte[] by=str.getBytes(); - ByteBuf message = Unpooled.buffer(by.length); ; - message.writeBytes(by); - ch.writeAndFlush(message); - System.out.println("客户端发送数据:"+str); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo2/NettyClientHandlerDemo2.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo2/NettyClientHandlerDemo2.java deleted file mode 100644 index a09d5a430d..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo2/NettyClientHandlerDemo2.java +++ /dev/null @@ -1,136 +0,0 @@ -package com.jun.plugin.nio.netty.demo2; - -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelInboundHandlerAdapter; - -/** - * -* Title: NettyClientHandlerDemo2 -* Description: Netty客户端业务逻辑处理 -* Version:1.0.0 -* @author pancm -* @date 2017年9月20日 - */ -public class NettyClientHandlerDemo2 extends ChannelInboundHandlerAdapter{ - - private byte[] req; - - private int counter; - - public NettyClientHandlerDemo2() { -// req = ("书到用时方恨少,事非经过不知难!").getBytes(); - - //用于测试字节解码器 LineBasedFrameDecoder(2048) - req = ("春江潮水连海平,海上明月共潮生。" - +" 滟滟随波千万里,何处春江无月明! " - +" 江流宛转绕芳甸,月照花林皆似霰;" - +" 空里流霜不觉飞,汀上白沙看不见。" - +" 江天一色无纤尘,皎皎空中孤月轮。" - +" 江畔何人初见月?江月何年初照人?" - +" 人生代代无穷已,江月年年望相似。" - +" 不知江月待何人,但见长江送流水。" - +" 白云一片去悠悠,青枫浦上不胜愁。" - +" 谁家今夜扁舟子?何处相思明月楼?" - +" 可怜楼上月徘徊,应照离人妆镜台。" - +" 玉户帘中卷不去,捣衣砧上拂还来。" - +" 此时相望不相闻,愿逐月华流照君。" - +" 鸿雁长飞光不度,鱼龙潜跃水成文。" - +" 昨夜闲潭梦落花,可怜春半不还家。" - +" 江水流春去欲尽,江潭落月复西斜。" - +" 斜月沉沉藏海雾,碣石潇湘无限路。" - +" 不知乘月几人归,落月摇情满江树。" - +" 噫吁嚱,危乎高哉!蜀道之难,难于上青天!蚕丛及鱼凫,开国何茫然!尔来四万八千岁,不与秦塞通人烟。" - +" 西当太白有鸟道,可以横绝峨眉巅。地崩山摧壮士死,然后天梯石栈相钩连。上有六龙回日之高标,下有冲波逆折之回川。" - +" 黄鹤之飞尚不得过,猿猱欲度愁攀援。青泥何盘盘,百步九折萦岩峦。扪参历井仰胁息,以手抚膺坐长叹。" - +" 问君西游何时还?畏途巉岩不可攀。但见悲鸟号古木,雄飞雌从绕林间。又闻子规啼夜月,愁空山。" - +" 蜀道之难,难于上青天,使人听此凋朱颜!连峰去天不盈尺,枯松倒挂倚绝壁。飞湍瀑流争喧豗,砯崖转石万壑雷。" - +" 其险也如此,嗟尔远道之人胡为乎来哉!剑阁峥嵘而崔嵬,一夫当关,万夫莫开。" - +" 所守或匪亲,化为狼与豺。朝避猛虎,夕避长蛇;磨牙吮血,杀人如麻。锦城虽云乐,不如早还家。" - +" 蜀道之难,难于上青天,侧身西望长咨嗟!"+System.getProperty("line.separator")).getBytes(); - - //用于测试 固定字符切分解码器 DelimiterBasedFrameDecoder(1024,Unpooled.copiedBuffer("~_~".getBytes()) - /* req = ("春江潮水连海平,海上明月共潮生。" - +" 滟滟随波千万里,何处春江无月明! " - +" 江流宛转绕芳甸,月照花林皆似霰;" - +" 空里流霜不觉飞,汀上白沙看不见。" - +" 江天一色无纤尘,皎皎空中孤月轮。" - +" 江畔何人初见月?江月何年初照人?" - +" 人生代代无穷已,江月年年望相似。~_~" - +" 不知江月待何人,但见长江送流水。" - +" 白云一片去悠悠,青枫浦上不胜愁。" - +" 谁家今夜扁舟子?何处相思明月楼?" - +" 可怜楼上月徘徊,应照离人妆镜台。" - +" 玉户帘中卷不去,捣衣砧上拂还来。" - +" 此时相望不相闻,愿逐月华流照君。~_~" - +" 鸿雁长飞光不度,鱼龙潜跃水成文。" - +" 昨夜闲潭梦落花,可怜春半不还家。" - +" 江水流春去欲尽,江潭落月复西斜。" - +" 斜月沉沉藏海雾,碣石潇湘无限路。" - +" 不知乘月几人归,落月摇情满江树。~_~" - +" 噫吁嚱,危乎高哉!蜀道之难,难于上青天!蚕丛及鱼凫,开国何茫然!尔来四万八千岁,不与秦塞通人烟。" - +" 西当太白有鸟道,可以横绝峨眉巅。地崩山摧壮士死,然后天梯石栈相钩连。~_~ 上有六龙回日之高标,下有冲波逆折之回川。" - +" 黄鹤之飞尚不得过,猿猱欲度愁攀援。~_~ 青泥何盘盘,百步九折萦岩峦。扪参历井仰胁息,以手抚膺坐长叹。" - +" 问君西游何时还?畏途巉岩不可攀。但见悲鸟号古木,雄飞雌从绕林间。又闻子规啼夜月,愁空山。" - +" 蜀道之难,难于上青天,使人听此凋朱颜!连峰去天不盈尺,枯松倒挂倚绝壁。~_~ 飞湍瀑流争喧豗,砯崖转石万壑雷。" - +" 其险也如此,嗟尔远道之人胡为乎来哉!剑阁峥嵘而崔嵬,一夫当关,万夫莫开。" - +" 所守或匪亲,化为狼与豺。朝避猛虎,夕避长蛇;磨牙吮血,杀人如麻。锦城虽云乐,不如早还家。" - +" 蜀道之难,难于上青天,侧身西望长咨嗟!"+System.getProperty("line.separator")).getBytes(); */ - - - - - /* req = ("AAAAAAAAAAAAAAAA" - +" BBBBBBBBBBBBBBBB " - +" CCCCCCCCCCCCCCCCC" - +" DDDDDDDDDDDDD" - +" EEEEEEEEEEEEEE" - +" FFFFFFFFFFFFFF" - +" GGGGGGGGGGGG ~_~" - +" HHHHHHHHHHHHHHHH" - +" IIIIIIIIIIIIII" - +" JJJJJJJJJJJJJJJJJJJ" - +" KKKKKKKKKKKKKKKKK" - +" LLLLLLLLLLLLLLLLL" - +" MMMMMMMMMMMMMMMMMM ~_~" - +" NNNNNNNNNNNNNNNN" - +" OOOOOOOOOOOOOOOOOOOO" - +" PPPPPPPPPPPPPP" - +" QQQQQQQQQQQQQQQQQQQQ" - +" RRRRRRRRRRRRRR ~_~" - +" SSSSSSSSSSSSSSSSS" - +" TTTTTT ~_~ TTTTTTT"+System.getProperty("line.separator")).getBytes(); */ - - //System.getProperty("line.separator") 结束标记 - } - - @Override - public void channelActive(ChannelHandlerContext ctx) throws Exception { - ByteBuf message = null; - //会发生粘包现象 -// for (int i = 0; i < 100; i++) { -// message = Unpooled.buffer(req.length); -// message.writeBytes(req); -// ctx.writeAndFlush(message); -// } - message = Unpooled.buffer(req.length); - message.writeBytes(req); - ctx.writeAndFlush(message); - System.out.println("一次发送消息过多,发送拆包现象! "); - } - - @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) - throws Exception { - String buf = (String) msg; - System.out.println("现在 : " + buf + " ; 条数是 : "+ ++counter); - } - - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { - ctx.close(); - } - - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo2/NettyServerDemo2.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo2/NettyServerDemo2.java deleted file mode 100644 index ec030f4d79..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo2/NettyServerDemo2.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.jun.plugin.nio.netty.demo2; - -import java.net.InetSocketAddress; - -import io.netty.bootstrap.ServerBootstrap; -import io.netty.channel.ChannelFuture; -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelOption; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.SocketChannel; -import io.netty.channel.socket.nio.NioServerSocketChannel; -import io.netty.handler.codec.LineBasedFrameDecoder; -import io.netty.handler.codec.string.StringDecoder; - -/** - * -* Title: NettyServerDemo2 -* Description: Netty服务端 用于测试粘包、拆包 -* Version:1.0.0 -* @author pancm -* @date 2017年9月20日 - */ -public class NettyServerDemo2 { - private final static int port=2345; - - public void start(){ - EventLoopGroup bossGroup = new NioEventLoopGroup(1); - EventLoopGroup workerGroup = new NioEventLoopGroup(); - try { - ServerBootstrap sbs = new ServerBootstrap().group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).localAddress(new InetSocketAddress(port)) - .childHandler(new ChannelInitializer() { - protected void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline p = ch.pipeline(); - - p.addLast(new LineBasedFrameDecoder(2048)); //字节解码器 ,其中2048是规定一行数据最大的字节数。 用于解决拆包问题 -// p.addLast(new FixedLengthFrameDecoder(100)); //定长数据帧的解码器 ,每帧数据100个字节就切分一次。 用于解决粘包问题 -// p.addLast(new DelimiterBasedFrameDecoder(1024,Unpooled.copiedBuffer("~_~".getBytes()))); //固定字符切分解码器 ,会以"~_~"为分隔符。 注意此方法要放到StringDecoder()上面 - p.addLast(new StringDecoder()); //设置解码器 - p.addLast(new NettyServerHandlerDemo2()); //绑定自定义事物 - }; - - }).option(ChannelOption.SO_BACKLOG, 128) - .childOption(ChannelOption.SO_KEEPALIVE, true); - // 绑定端口,开始接收进来的连接 - ChannelFuture future = sbs.bind(port).sync(); - - System.out.println("服务端启动成功,端口为 :" + port ); - future.channel().closeFuture().sync(); - } catch (Exception e) { - bossGroup.shutdownGracefully(); //关闭EventLoopGroup,释放掉所有资源包括创建的线程 - workerGroup.shutdownGracefully(); //关闭EventLoopGroup,释放掉所有资源包括创建的线程 - } - } - - public static void main(String[] args) throws Exception { - new NettyServerDemo2().start(); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo2/NettyServerHandlerDemo2.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo2/NettyServerHandlerDemo2.java deleted file mode 100644 index 75fcb4295b..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo2/NettyServerHandlerDemo2.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.jun.plugin.nio.netty.demo2; - -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelInboundHandlerAdapter; - -/** - * -* Title: NettyServerHandlerDemo2 -* Description: Netty服务端业务逻辑处理 用于测试粘包、拆包 -* Version:1.0.0 -* @author pancm -* @date 2017年9月20日 - */ -public class NettyServerHandlerDemo2 extends ChannelInboundHandlerAdapter{ - - - private int counter; - - @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { - - String body = (String)msg; - System.out.println("接受的数据是: " + body + ";条数是: " + ++counter); - } - - - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - cause.printStackTrace(); - ctx.close(); - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo3/NettyClientDemo3.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo3/NettyClientDemo3.java deleted file mode 100644 index a76e9877a2..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo3/NettyClientDemo3.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.jun.plugin.nio.netty.demo3; - -import java.io.IOException; - -import io.netty.bootstrap.Bootstrap; -import io.netty.channel.Channel; -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelOption; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.SocketChannel; -import io.netty.channel.socket.nio.NioSocketChannel; - -/** - * -* Title: NettyClientDemo3 -* Description: Netty客户端 测试自定义解码器 -* Version:1.0.0 -* @author pancm -* @date 2017年9月21日 - */ -public class NettyClientDemo3 { - public static String host = "127.0.0.1"; //ip地址 - public static int port = 3456; //端口 - /// 通过nio方式来接收连接和处理连接 - private static EventLoopGroup group = new NioEventLoopGroup(); - private static Bootstrap b = new Bootstrap(); - private static Channel ch=null; - - /** - * Netty创建全部都是实现自AbstractBootstrap。 - * 客户端的是Bootstrap,服务端的则是ServerBootstrap。 - **/ - public static void main(String[] args) throws InterruptedException, IOException { - b.group(group) - .channel(NioSocketChannel.class) - .option(ChannelOption.TCP_NODELAY,true) - .handler(new ChannelInitializer() { - @Override - public void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline p = ch.pipeline(); - p.addLast(new NettyEncoder()); //绑定自定义编码器 - p.addLast(new NettyClientHandlerDemo3()); //绑定自定义业务 - } - }); - // 连接服务端 - ch = b.connect(host, port).sync().channel(); - System.out.println("客户端成功启动..."); - star(); - } - - public static void star() throws IOException{ - String str="你好,Netty"; - NettyMsg customMsg = new NettyMsg((byte)0xAB, (byte)0xCD, str.length(), str); - ch.writeAndFlush(customMsg); - System.out.println("客户端发送数据:"+customMsg); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo3/NettyClientHandlerDemo3.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo3/NettyClientHandlerDemo3.java deleted file mode 100644 index 9e47efeeec..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo3/NettyClientHandlerDemo3.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.jun.plugin.nio.netty.demo3; - -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelInboundHandlerAdapter; - -/** - * -* Description: -* Version:1.0.0 -* @author pancm -* @date 2017年9月21日 - */ -public class NettyClientHandlerDemo3 extends ChannelInboundHandlerAdapter { - - /** - * 连接时发送消息 - */ - @Override - public void channelActive(ChannelHandlerContext ctx) throws Exception { - NettyMsg customMsg = new NettyMsg((byte)0xAB, (byte)0xCD, "Hello,Netty".length(), "Hello,Netty"); - ctx.writeAndFlush(customMsg); - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo3/NettyDecoder.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo3/NettyDecoder.java deleted file mode 100644 index 0f7b9dc6e3..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo3/NettyDecoder.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.jun.plugin.nio.netty.demo3; - -import java.util.List; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.ByteToMessageCodec; - -/** - * -* Description: Netty自定义解码器 -* Version:1.0.0 -* @author pancm -* @date 2017年9月21日 - */ -public class NettyDecoder extends ByteToMessageCodec { - - //判断传送客户端传送过来的数据是否按照协议传输,头部信息的大小应该是 byte+byte+int = 1+1+4 = 6 - private static final int HEADER_SIZE = 6; - - /** 类型 系统编号 0xAB 表示A系统,0xBC 表示B系统 */ - private byte type; - - /** 信息标志 0xAB 表示心跳包 0xBC 表示超时包 0xCD 业务信息包 */ - private byte flag; - - /** 主题信息的长度 */ - private int length; - - /** 主题信息 */ - private String body; - - - @Override - protected void encode(ChannelHandlerContext ctx, NettyMsg msg, ByteBuf out) - throws Exception { - System.out.println("msg:"+msg); - if (out == null) { - return ; - } - if (out.readableBytes() < HEADER_SIZE) { - throw new Exception("可读信息段比头部信息都小,你在逗我?"); - } - //注意在读的过程中,readIndex的指针也在移动 - type = out.readByte(); - - flag = out.readByte(); - - length = out.readInt(); - - if (out.readableBytes() < length) { - throw new Exception("body字段你告诉我长度是"+length+",但是真实情况是没有这么多,你又逗我?"); - } - ByteBuf buf = out.readBytes(length); - byte[] req = new byte[buf.readableBytes()]; - buf.readBytes(req); - body = new String(req, "UTF-8"); - NettyMsg customMsg = new NettyMsg(type,flag,length,body); - - } - - @Override - protected void decode(ChannelHandlerContext ctx, ByteBuf in, - List out) throws Exception { - // TODO Auto-generated method stub - - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo3/NettyDecoder2.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo3/NettyDecoder2.java deleted file mode 100644 index 7e5656332f..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo3/NettyDecoder2.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.jun.plugin.nio.netty.demo3; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.LengthFieldBasedFrameDecoder; - -/** - * -* Description: Netty自定义解码器 -* Version:1.0.0 -* @author pancm -* @date 2017年9月21日 - */ -public class NettyDecoder2 extends LengthFieldBasedFrameDecoder { - - //判断传送客户端传送过来的数据是否按照协议传输,头部信息的大小应该是 byte+byte+int = 1+1+4 = 6 - private static final int HEADER_SIZE = 6; - - /** 类型 系统编号 0xAB 表示A系统,0xBC 表示B系统 */ - private byte type; - - /** 信息标志 0xAB 表示心跳包 0xBC 表示超时包 0xCD 业务信息包 */ - private byte flag; - - /** 主题信息的长度 */ - private int length; - - /** 主题信息 */ - private String body; - - /** - * - * @param maxFrameLength 解码时,处理每个帧数据的最大长度 - * @param lengthFieldOffset 该帧数据中,存放该帧数据的长度的数据的起始位置 - * @param lengthFieldLength 记录该帧数据长度的字段本身的长度 - * @param lengthAdjustment 修改帧数据长度字段中定义的值,可以为负数 - * @param initialBytesToStrip 解析的时候需要跳过的字节数 - * @param failFast 为true,当frame长度超过maxFrameLength时立即报TooLongFrameException异常,为false,读取完整个帧再报异常 - */ - public NettyDecoder2(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, - int lengthAdjustment, int initialBytesToStrip, boolean failFast) { - super(maxFrameLength, lengthFieldOffset, lengthFieldLength, - lengthAdjustment, initialBytesToStrip, failFast); - } - - @Override - protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception { - if (in == null) { - return null; - } - if (in.readableBytes() < HEADER_SIZE) { - throw new Exception("可读信息段比头部信息都小,你在逗我?"); - } - - //注意在读的过程中,readIndex的指针也在移动 - type = in.readByte(); - - flag = in.readByte(); - - length = in.readInt(); - - if (in.readableBytes() < length) { - throw new Exception("body字段你告诉我长度是"+length+",但是真实情况是没有这么多,你又逗我?"); - } - ByteBuf buf = in.readBytes(length); - byte[] req = new byte[buf.readableBytes()]; - buf.readBytes(req); - body = new String(req, "UTF-8"); - - NettyMsg customMsg = new NettyMsg(type,flag,length,body); - return customMsg; - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo3/NettyEncoder.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo3/NettyEncoder.java deleted file mode 100644 index fc28b1f794..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo3/NettyEncoder.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.jun.plugin.nio.netty.demo3; - -import java.nio.charset.Charset; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.MessageToByteEncoder; - -/** - * -* Description:Netty自定义编码器 -* Version:1.0.0 -* @author pancm -* @date 2017年9月21日 - */ -public class NettyEncoder extends MessageToByteEncoder { - - @Override - protected void encode(ChannelHandlerContext ctx, NettyMsg msg, ByteBuf out) throws Exception { - if(null == msg){ - throw new Exception("消息不能为空!"); - } - - String body = msg.getBody(); - byte[] bodyBytes = body.getBytes(Charset.forName("utf-8")); - out.writeByte(msg.getType()); - out.writeByte(msg.getFlag()); - out.writeInt(bodyBytes.length); - out.writeBytes(bodyBytes); - - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo3/NettyMsg.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo3/NettyMsg.java deleted file mode 100644 index 4c3889f878..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo3/NettyMsg.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.jun.plugin.nio.netty.demo3; - -/** - * -* Description: Netty 自定义消息 -* Version:1.0.0 -* @author pancm -* @date 2017年9月21日 - */ -public class NettyMsg { - - - /** 类型 系统编号 0xAB 表示A系统,0xBC 表示B系统 */ - private byte type; - - /** 信息标志 0xAB 表示心跳包 0xBC 表示超时包 0xCD 业务信息包 */ - private byte flag; - - /** 主题信息的长度 */ - private int length; - - /** 主题信息 */ - private String body; - - public NettyMsg() { - - } - - - /** - * - * @param type 类型 系统编号 0xAB 表示A系统,0xBC 表示B系统 - * @param flag 信息标志 0xAB 表示心跳包 0xBC 表示超时包 0xCD 业务信息包 - * @param length 主题信息的长度 - * @param body 主题信息 - */ - public NettyMsg(byte type, byte flag, int length, String body) { - this.type = type; - this.flag = flag; - this.length = length; - this.body = body; - } - - public byte getType() { - return type; - } - - public void setType(byte type) { - this.type = type; - } - - public byte getFlag() { - return flag; - } - - public void setFlag(byte flag) { - this.flag = flag; - } - - public int getLength() { - return length; - } - - public void setLength(int length) { - this.length = length; - } - - public String getBody() { - return body; - } - - public void setBody(String body) { - this.body = body; - } - - /** - * 重写toString方法,方便打印日志 - */ - @Override - public String toString() { - return "NettyMsg [type=" + type + ", flag=" + flag + ", length=" - + length + ", body=" + body + "]"; - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo3/NettyServerDemo3.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo3/NettyServerDemo3.java deleted file mode 100644 index d291350bf6..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo3/NettyServerDemo3.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.jun.plugin.nio.netty.demo3; - -import java.net.InetSocketAddress; - -import io.netty.bootstrap.ServerBootstrap; -import io.netty.channel.ChannelFuture; -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelOption; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.SocketChannel; -import io.netty.channel.socket.nio.NioServerSocketChannel; - -/** - * -* Description: Netty 服务端 测试自定义解码器 -* Version:1.0.0 -* @author pancm -* @date 2017年9月21日 - */ -public class NettyServerDemo3 { - - private static final int MAX_FRAME_LENGTH = 1024 * 1024; - private static final int LENGTH_FIELD_LENGTH = 4; - private static final int LENGTH_FIELD_OFFSET = 2; - private static final int LENGTH_ADJUSTMENT = 0; - private static final int INITIAL_BYTES_TO_STRIP = 0; - - private final static int port=3456; - - - public void start(){ - EventLoopGroup bossGroup = new NioEventLoopGroup(1); - EventLoopGroup workerGroup = new NioEventLoopGroup(); - try { - ServerBootstrap sbs = new ServerBootstrap().group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).localAddress(new InetSocketAddress(port)) - .childHandler(new ChannelInitializer() { - - protected void initChannel(SocketChannel ch) throws Exception { - ch.pipeline().addLast(new NettyDecoder2(MAX_FRAME_LENGTH,LENGTH_FIELD_LENGTH,LENGTH_FIELD_OFFSET,LENGTH_ADJUSTMENT,INITIAL_BYTES_TO_STRIP,false)); -// ch.pipeline().addLast(new NettyDecoder(MAX_FRAME_LENGTH,LENGTH_FIELD_LENGTH,LENGTH_FIELD_OFFSET,LENGTH_ADJUSTMENT,INITIAL_BYTES_TO_STRIP,false)); - ch.pipeline().addLast(new NettyServerHandlerDemo3()); - }; - - }).option(ChannelOption.SO_BACKLOG, 128) - .childOption(ChannelOption.SO_KEEPALIVE, true); - // 绑定端口,开始接收进来的连接 - ChannelFuture future = sbs.bind(port).sync(); - - System.out.println("Netty服务端成功启动!端口为: " + port ); - future.channel().closeFuture().sync(); - } catch (Exception e) { - bossGroup.shutdownGracefully(); - workerGroup.shutdownGracefully(); - } - } - - public static void main(String[] args) throws Exception { - new NettyServerDemo3().start(); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo3/NettyServerHandlerDemo3.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo3/NettyServerHandlerDemo3.java deleted file mode 100644 index 7b2e7673c3..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo3/NettyServerHandlerDemo3.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.jun.plugin.nio.netty.demo3; - -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.SimpleChannelInboundHandler; - -/** - * -* Description:服务端业务逻辑处理类 -* Version:1.0.0 -* @author pancm -* @date 2017年9月21日 - */ -public class NettyServerHandlerDemo3 extends SimpleChannelInboundHandler { - - @Override - protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { - if(msg instanceof NettyMsg) { - NettyMsg customMsg = (NettyMsg)msg; - System.out.println("接受的数据:"+ctx.channel().remoteAddress()+" send "+customMsg.getBody()); - } - - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo4/NettyClientDemo4.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo4/NettyClientDemo4.java deleted file mode 100644 index 9be69c72a9..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo4/NettyClientDemo4.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.jun.plugin.nio.netty.demo4; - -import java.io.IOException; - -import io.netty.bootstrap.Bootstrap; -import io.netty.channel.Channel; -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelOption; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.SocketChannel; -import io.netty.channel.socket.nio.NioSocketChannel; -import io.netty.handler.codec.string.StringDecoder; - -/** - * -* Title: NettyClientDemo4 -* Description: Netty客户端 -* Version:1.0.0 -* @author pancm -* @date 2017年9月21日 - */ -public class NettyClientDemo4 { - public static String host = "127.0.0.1"; //ip地址 - public static int port = 4567; //端口 - /// 通过nio方式来接收连接和处理连接 - private static EventLoopGroup group = new NioEventLoopGroup(); - private static Bootstrap b = new Bootstrap(); - private static Channel ch=null; - - /** - * Netty创建全部都是实现自AbstractBootstrap。 - * 客户端的是Bootstrap,服务端的则是ServerBootstrap。 - **/ - public static void main(String[] args) throws InterruptedException, IOException { - b.group(group) - .channel(NioSocketChannel.class) - .option(ChannelOption.TCP_NODELAY,true) - .handler(new ChannelInitializer() { - @Override - public void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline p = ch.pipeline(); - p.addLast(new StringDecoder()); //绑定自定义编码器 - p.addLast(new NettyClientHandlerDemo4()); //绑定自定义业务 - } - }); - // 连接服务端 - ch = b.connect(host, port).sync().channel(); - System.out.println("客户端成功启动..."); - //发送消息 - star(); - } - - public static void star() throws IOException{ - NettySendBody nsb=new NettySendBody(); - nsb.put("Netty","Hello"); - nsb.put("JAVA","从入门到入土"); - nsb.put("SQL","从删库到跑路"); - ch.writeAndFlush(nsb); - System.out.println("客户端发送数据:"+nsb.toString()); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo4/NettyClientHandlerDemo4.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo4/NettyClientHandlerDemo4.java deleted file mode 100644 index c6604313e4..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo4/NettyClientHandlerDemo4.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.jun.plugin.nio.netty.demo4; - -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelInboundHandlerAdapter; - -/** - * -* Description: -* Version:1.0.0 -* @author pancm -* @date 2017年9月21日 - */ -public class NettyClientHandlerDemo4 extends ChannelInboundHandlerAdapter { - - /** - * 连接时发送消息 - */ - @Override - public void channelActive(ChannelHandlerContext ctx) throws Exception { - NettySendBody nst = new NettySendBody(); - nst.put("1111", "2222"); - ctx.writeAndFlush(nst); - System.out.println(nst); - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo4/NettySendBody.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo4/NettySendBody.java deleted file mode 100644 index 7ad92ecd0a..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo4/NettySendBody.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.jun.plugin.nio.netty.demo4; - -import java.io.Serializable; -import java.util.concurrent.ConcurrentHashMap; - -/** - * -* Description: Netty 传输对象 -* Version:1.0.0 -* @author pancm -* @date 2017年9月24日 - */ -public class NettySendBody implements Serializable{ - - /** - * 序列化 - */ - private static final long serialVersionUID = 1L; - - - /** 创建集合 */ - private ConcurrentHashMap data; - /** 时间戳 */ - private long timestamp; - - public NettySendBody() { - data = new ConcurrentHashMap(); - timestamp = System.currentTimeMillis(); //取当前时间 - } - - - public ConcurrentHashMap getData() { - return data; - } - - public void setData(ConcurrentHashMap data) { - this.data = data; - } - - public long getTimestamp() { - return timestamp; - } - - public void setTimestamp(long timestamp) { - this.timestamp = timestamp; - } - - public String get(String k) { - return data.get(k); - } - - public void put(String k, String v) { - data.put(k, v); - } - - - @Override - public String toString() { - StringBuffer buffer = new StringBuffer(); - buffer.append(""); - buffer.append(""); - buffer.append("").append(timestamp).append(""); - buffer.append(""); - for (String key : data.keySet()) { - buffer.append("<" + key + ">").append(data.get(key)).append( - ""); - } - buffer.append(""); - buffer.append(""); - return buffer.toString(); - } - - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo4/NettyServerDemo4.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo4/NettyServerDemo4.java deleted file mode 100644 index 9d15842440..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo4/NettyServerDemo4.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.jun.plugin.nio.netty.demo4; - -import java.net.InetSocketAddress; - -import io.netty.bootstrap.ServerBootstrap; -import io.netty.channel.ChannelFuture; -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelOption; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.SocketChannel; -import io.netty.channel.socket.nio.NioServerSocketChannel; -import io.netty.handler.codec.string.StringDecoder; - -/** - * -* Description: Netty 服务端 测试自定义解码器 -* Version:1.0.0 -* @author pancm -* @date 2017年9月21日 - */ -public class NettyServerDemo4 { - - private final static int port=4567; - - - public void start(){ - EventLoopGroup bossGroup = new NioEventLoopGroup(1); - EventLoopGroup workerGroup = new NioEventLoopGroup(); - try { - ServerBootstrap sbs = new ServerBootstrap().group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).localAddress(new InetSocketAddress(port)) - .childHandler(new ChannelInitializer() { - - protected void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline p = ch.pipeline(); - p.addLast(new StringDecoder()); - p.addLast(new NettyServerHandlerDemo4()); //绑定自定义业务逻辑 - }; - - }).option(ChannelOption.SO_BACKLOG, 128) - .childOption(ChannelOption.SO_KEEPALIVE, true); - // 绑定端口,开始接收进来的连接 - ChannelFuture future = sbs.bind(port).sync(); - - System.out.println("Netty服务端启动成功,端口为: " + port ); - future.channel().closeFuture().sync(); //释放监听 - } catch (Exception e) { - bossGroup.shutdownGracefully(); //释放资源 - workerGroup.shutdownGracefully(); - } - } - - public static void main(String[] args) throws Exception { - new NettyServerDemo4().start(); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo4/NettyServerHandlerDemo4.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo4/NettyServerHandlerDemo4.java deleted file mode 100644 index eb1d53d588..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo4/NettyServerHandlerDemo4.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.jun.plugin.nio.netty.demo4; - -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelInboundHandlerAdapter; - -/** - * -* Description:服务端业务逻辑处理类 -* Version:1.0.0 -* @author pancm -* @date 2017年9月21日 - */ -public class NettyServerHandlerDemo4 extends ChannelInboundHandlerAdapter { - - /** - * 处理业务逻辑消息 - */ - protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { - System.out.println(" ----- "+msg); - if(msg instanceof NettySendBody) { - NettySendBody nsb = (NettySendBody)msg; - System.out.println("服务端接受的消息为:"+nsb.toString()); - NettySendBody nsb1 = new NettySendBody(); - nsb1.put("3333","44444"); - ctx.writeAndFlush(nsb1); - }else{ - System.out.println("收到非法请求"); - } - } - - @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { - System.out.println(" ----- "+msg); - if(msg instanceof NettySendBody) { - NettySendBody nsb = (NettySendBody)msg; - System.out.println("服务端接受的消息为:"+nsb.toString()); - NettySendBody nsb1 = new NettySendBody(); - nsb1.put("3333","44444"); - ctx.writeAndFlush(nsb1); - }else{ - System.out.println("收到非法请求"); - } - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo5/NettyClientDemo5.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo5/NettyClientDemo5.java deleted file mode 100644 index 975ad11631..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo5/NettyClientDemo5.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.jun.plugin.nio.netty.demo5; - -import java.io.IOException; -import java.util.concurrent.TimeUnit; - -import io.netty.bootstrap.Bootstrap; -import io.netty.channel.Channel; -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelOption; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.SocketChannel; -import io.netty.channel.socket.nio.NioSocketChannel; -import io.netty.handler.codec.string.StringDecoder; -import io.netty.handler.codec.string.StringEncoder; -import io.netty.handler.timeout.IdleStateHandler; - -/** - * -* Title: NettyClientDemo5 -* Description: Netty客户端 心跳测试 -* Version:1.0.0 -* @author pancm -* @date 2017年9月21日 - */ -public class NettyClientDemo5 { - public static String host = "127.0.0.1"; //ip地址 - public static int port = 5678; //端口 - /// 通过nio方式来接收连接和处理连接 - private static EventLoopGroup group = new NioEventLoopGroup(); - private static Bootstrap b = new Bootstrap(); - private static Channel ch=null; - - /** - * Netty创建全部都是实现自AbstractBootstrap。 - * 客户端的是Bootstrap,服务端的则是ServerBootstrap。 - **/ - public static void main(String[] args) throws InterruptedException, IOException { - b.group(group) - .channel(NioSocketChannel.class) - .option(ChannelOption.TCP_NODELAY,true) - .handler(new ChannelInitializer() { - @Override - public void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline p = ch.pipeline(); - //入参说明: 读超时时间、写超时时间、所有类型的超时时间、时间格式 - //因为服务端设置的超时时间是5秒,所以设置4秒 - p.addLast( new IdleStateHandler(0, 4, 0, TimeUnit.SECONDS)); - p.addLast( new StringDecoder()); - p.addLast( new StringEncoder()); - p.addLast(new NettyClientHandlerDemo5()); //绑定自定义业务 - } - }); - // 连接服务端 - ch = b.connect(host, port).sync().channel(); - System.out.println("客户端成功启动..."); - //发送消息 -// star(); - } - - public static void star() throws IOException{ - String str="你好啊,Netty服务端"; - ch.writeAndFlush(str); - System.out.println("客户端发送数据:"+str); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo5/NettyClientHandlerDemo5.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo5/NettyClientHandlerDemo5.java deleted file mode 100644 index fe233920df..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo5/NettyClientHandlerDemo5.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.jun.plugin.nio.netty.demo5; - -import com.jun.plugin.utils.MyTools; - -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelInboundHandlerAdapter; -import io.netty.handler.timeout.IdleState; -import io.netty.handler.timeout.IdleStateEvent; -import io.netty.util.CharsetUtil; -import io.netty.util.ReferenceCountUtil; - -/** - * -* Description: Netty业务处理 心跳测试 -* Version:1.0.0 -* @author pancm -* @date 2017年9月21日 - */ -public class NettyClientHandlerDemo5 extends ChannelInboundHandlerAdapter { - - /**心跳命令 */ - private static final ByteBuf HEARTBEAT_SEQUENCE = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer("Heartbeat", - CharsetUtil.UTF_8)); - - private static final int TRY_TIMES = 3; - - private int currentTime = 0; - - /** - * 建立连接时 - */ - @Override - public void channelActive(ChannelHandlerContext ctx) throws Exception { - System.out.println("激活时间是:"+MyTools.getNowTime("")); - ctx.fireChannelActive(); - } - - /** - * 关闭连接时 - */ - @Override - public void channelInactive(ChannelHandlerContext ctx) throws Exception { - System.out.println("停止时间是:"+MyTools.getNowTime("")); - } - - @Override - public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { - System.out.println("循环触发时间:"+MyTools.getNowTime("")); - if (evt instanceof IdleStateEvent) { - IdleStateEvent event = (IdleStateEvent) evt; - System.out.println("event.state():"+event.state()+",IdleState.READER_IDLE:"+IdleState.READER_IDLE); - if (event.state() == IdleState.WRITER_IDLE) { - System.out.println("TRY_TIMES:"+TRY_TIMES); - if(currentTime <= TRY_TIMES){ - System.out.println("currentTime:"+currentTime); - currentTime++; - ctx.channel().writeAndFlush(HEARTBEAT_SEQUENCE.duplicate()); - } - } - } - } - - /** - * 业务逻辑处理 - */ - @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { - System.out.println("接受的消息:"+msg); - String message = (String) msg; - if (message.equals("Heartbeat")) { - ctx.write("成功收到心跳信息"); - ctx.flush(); - } - ReferenceCountUtil.release(msg); - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo5/NettyServerDemo5.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo5/NettyServerDemo5.java deleted file mode 100644 index 681453ac9d..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo5/NettyServerDemo5.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.jun.plugin.nio.netty.demo5; - -import java.net.InetSocketAddress; -import java.util.concurrent.TimeUnit; - -import io.netty.bootstrap.ServerBootstrap; -import io.netty.channel.ChannelFuture; -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelOption; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.SocketChannel; -import io.netty.channel.socket.nio.NioServerSocketChannel; -import io.netty.handler.codec.string.StringDecoder; -import io.netty.handler.codec.string.StringEncoder; -import io.netty.handler.timeout.IdleStateHandler; - -/** - * -* Description: Netty 服务端 测试心跳 -* Version:1.0.0 -* @author pancm -* @date 2017年9月21日 - */ -public class NettyServerDemo5 { - /** 设置端口 */ - private final static int port=5678; - - - public void start(){ - EventLoopGroup bossGroup = new NioEventLoopGroup(1); - EventLoopGroup workerGroup = new NioEventLoopGroup(); - try { - ServerBootstrap sbs = new ServerBootstrap().group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).localAddress(new InetSocketAddress(port)) - .childHandler(new ChannelInitializer() { - - protected void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline p = ch.pipeline(); - //入参说明: 读超时时间、写超时时间、所有类型的超时时间、时间格式 - p.addLast(new IdleStateHandler(5, 0, 0, TimeUnit.SECONDS)); - p.addLast(new StringDecoder()); //String解码器 - p.addLast(new StringEncoder()); //String编码器 - p.addLast(new NettyServerHandlerDemo5()); //绑定自定义业务逻辑 - }; - - }).option(ChannelOption.SO_BACKLOG, 128) - .childOption(ChannelOption.SO_KEEPALIVE, true); - // 绑定端口,开始接收进来的连接 - ChannelFuture future = sbs.bind(port).sync(); - - System.out.println("Netty服务端启动成功,端口为: " + port ); - future.channel().closeFuture().sync(); //释放监听 - } catch (Exception e) { - bossGroup.shutdownGracefully(); //释放资源 - workerGroup.shutdownGracefully(); - } - } - - public static void main(String[] args) throws Exception { - new NettyServerDemo5().start(); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo5/NettyServerHandlerDemo5.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo5/NettyServerHandlerDemo5.java deleted file mode 100644 index c2ba8b88cd..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo5/NettyServerHandlerDemo5.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.jun.plugin.nio.netty.demo5; - -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelInboundHandlerAdapter; -import io.netty.handler.timeout.IdleState; -import io.netty.handler.timeout.IdleStateEvent; - -/** - * -* Description:服务端业务逻辑处理类 -* Version:1.0.0 -* @author pancm -* @date 2017年9月21日 - */ -public class NettyServerHandlerDemo5 extends ChannelInboundHandlerAdapter { - /** 时间 */ - private int loss_connect_time = 0; - /** 发送次数 */ - private int count = 1; - - @Override - public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { - if (evt instanceof IdleStateEvent) { - IdleStateEvent event = (IdleStateEvent) evt; - System.out.println("event.state():"+event.state()+",IdleState.READER_IDLE:"+IdleState.READER_IDLE); - if (event.state() == IdleState.READER_IDLE) { - loss_connect_time++; - System.out.println("5 秒没有接收到客户端的信息了"); - if (loss_connect_time > 2) { - System.out.println("关闭这个不活跃的channel"); - ctx.channel().close(); - } - } - } else { - super.userEventTriggered(ctx, evt); - } - } - - - /** - * 处理业务逻辑 - */ - @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { - System.out.println(" ----- "+msg); - String a="你好啊"+",count:"+count; - ctx.writeAndFlush(a); - count++; - } - - /** - * 异常处理 - */ - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - cause.printStackTrace(); - ctx.close(); - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo6/NettyServer.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo6/NettyServer.java deleted file mode 100644 index 181ffa8607..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo6/NettyServer.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.jun.plugin.nio.netty.demo6; - -import io.netty.bootstrap.ServerBootstrap; -import io.netty.channel.ChannelFuture; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.nio.NioServerSocketChannel; - - -/** - * -* Title: NettyServer -* Description: Netty服务端 Http测试 -* Version:1.0.0 -* @author pancm -* @date 2017年10月26日 - */ -public class NettyServer { - private static final int port = 6789; //设置服务端端口 - private static EventLoopGroup group = new NioEventLoopGroup(); // 通过nio方式来接收连接和处理连接 - private static ServerBootstrap b = new ServerBootstrap(); - - /** - * Netty创建全部都是实现自AbstractBootstrap。 - * 客户端的是Bootstrap,服务端的则是 ServerBootstrap。 - **/ - public static void main(String[] args) throws InterruptedException { - try { - b.group(group); - b.channel(NioServerSocketChannel.class); - b.childHandler(new NettyServerFilter()); //设置过滤器 - // 服务器绑定端口监听 - ChannelFuture f = b.bind(port).sync(); - System.out.println("服务端启动成功,端口是:"+port); - // 监听服务器关闭监听 - f.channel().closeFuture().sync(); - } finally { - group.shutdownGracefully(); //关闭EventLoopGroup,释放掉所有资源包括创建的线程 - } - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo6/NettyServerFilter.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo6/NettyServerFilter.java deleted file mode 100644 index 7a696d926c..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo6/NettyServerFilter.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.jun.plugin.nio.netty.demo6; - - -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.socket.SocketChannel; -import io.netty.handler.codec.http.HttpObjectAggregator; -import io.netty.handler.codec.http.HttpRequestDecoder; -import io.netty.handler.codec.http.HttpResponseEncoder; - - -/** - * -* Title: NettyServerFilter -* Description: Netty 服务端过滤器 -* Version:1.0.0 -* @author pancm -* @date 2017年10月26日 - */ -public class NettyServerFilter extends ChannelInitializer { - - @Override - protected void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline ph = ch.pipeline(); - //处理http服务的关键handler - ph.addLast("encoder",new HttpResponseEncoder()); - ph.addLast("decoder",new HttpRequestDecoder()); - ph.addLast("aggregator", new HttpObjectAggregator(10*1024*1024)); - ph.addLast("handler", new NettyServerHandler());// 服务端业务逻辑 - } - } diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo6/NettyServerHandler.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo6/NettyServerHandler.java deleted file mode 100644 index d5c275c537..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo6/NettyServerHandler.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.jun.plugin.nio.netty.demo6; - -import java.net.InetAddress; - -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; -import io.netty.channel.ChannelFutureListener; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelInboundHandlerAdapter; -import io.netty.handler.codec.http.DefaultFullHttpResponse; -import io.netty.handler.codec.http.FullHttpRequest; -import io.netty.handler.codec.http.FullHttpResponse; -import io.netty.handler.codec.http.HttpHeaderNames; -import io.netty.handler.codec.http.HttpMethod; -import io.netty.handler.codec.http.HttpResponseStatus; -import io.netty.handler.codec.http.HttpVersion; -import io.netty.util.CharsetUtil; - -/** - * -* Title: NettyServerHandler -* Description: 服务端业务逻辑 -* Version:1.0.0 -* @author pancm -* @date 2017年10月26日 - */ -public class NettyServerHandler extends ChannelInboundHandlerAdapter { - private String result=""; - /* - * 收到消息时,返回信息 - */ - @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { - if(! (msg instanceof FullHttpRequest)){ - result="未知请求!"; - send(ctx,result,HttpResponseStatus.BAD_REQUEST); - return; - } - FullHttpRequest httpRequest = (FullHttpRequest)msg; - try{ - String path=httpRequest.uri(); //获取路径 - String body = getBody(httpRequest); //获取参数 - HttpMethod method=httpRequest.method();//获取请求方法 - //如果不是这个路径,就直接返回错误 - if(!"/test".equalsIgnoreCase(path)){ - result="非法请求!"; - send(ctx,result,HttpResponseStatus.BAD_REQUEST); - return; - } - System.out.println("接收到:"+method+" 请求"); - //如果是GET请求 - if(HttpMethod.GET.equals(method)){ - //接受到的消息,做业务逻辑处理... - System.out.println("body:"+body); - result="GET请求"; - send(ctx,result,HttpResponseStatus.OK); - return; - } - //如果是POST请求 - if(HttpMethod.POST.equals(method)){ - //接受到的消息,做业务逻辑处理... - System.out.println("body:"+body); - result="POST请求"; - send(ctx,result,HttpResponseStatus.OK); - return; - } - - //如果是PUT请求 - if(HttpMethod.PUT.equals(method)){ - //接受到的消息,做业务逻辑处理... - System.out.println("body:"+body); - result="PUT请求"; - send(ctx,result,HttpResponseStatus.OK); - return; - } - //如果是DELETE请求 - if(HttpMethod.DELETE.equals(method)){ - //接受到的消息,做业务逻辑处理... - System.out.println("body:"+body); - result="DELETE请求"; - send(ctx,result,HttpResponseStatus.OK); - return; - } - }catch(Exception e){ - System.out.println("处理请求失败!"); - e.printStackTrace(); - }finally{ - //释放请求 - httpRequest.release(); - } - } - - /** - * 获取body参数 - * @param request - * @return - */ - private String getBody(FullHttpRequest request){ - ByteBuf buf = request.content(); - return buf.toString(CharsetUtil.UTF_8); - } - - /** - * 发送的返回值 - * @param ctx 返回 - * @param context 消息 - * @param status 状态 - */ - private void send(ChannelHandlerContext ctx, String context,HttpResponseStatus status) { - FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer(context, CharsetUtil.UTF_8)); - response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); - ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); - } - - /* - * 建立连接时,返回消息 - */ - @Override - public void channelActive(ChannelHandlerContext ctx) throws Exception { - System.out.println("连接的客户端地址:" + ctx.channel().remoteAddress()); - ctx.writeAndFlush("客户端"+ InetAddress.getLocalHost().getHostName() + "成功与服务端建立连接! "); - super.channelActive(ctx); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo6/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo6/package-info.java deleted file mode 100644 index 49fe2ea1e9..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/demo6/package-info.java +++ /dev/null @@ -1,11 +0,0 @@ -/** - * - */ -/** - * Title: package-info - * Description: Http服务测试 - * Version:1.0.0 - * @author pancm - * @date 2017年10月26日 - */ -package com.jun.plugin.nio.netty.demo6; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/package-info.java deleted file mode 100644 index 5a4ca75506..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/netty/package-info.java +++ /dev/null @@ -1,11 +0,0 @@ -/** - * - */ -/** - * Title: package-info - * Description: Netty 测试 - * Version:1.0.0 - * @author pancm - * @date 2017-8-31 - */ -package com.jun.plugin.nio.netty; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/package-info.java deleted file mode 100644 index 8f72244fc2..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/nio/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: nio 相关的代码 -* @Version:1.0.0 -* @author pancm -* @date 2018年9月21日 -*/ -package com.jun.plugin.nio; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/others/JsoupHtml.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/others/JsoupHtml.java deleted file mode 100644 index de488d088b..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/others/JsoupHtml.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.jun.plugin.others; - -import java.io.IOException; - -import org.jsoup.Jsoup; -import org.jsoup.nodes.Document; -import org.jsoup.nodes.Element; -import org.jsoup.select.Elements; - -/** - * -* @Title: JsoupHtml -* @Description: 爬虫测试 -* 使用 jsoup -* @Version:1.0.0 -* @author pancm -* @date 2018年3月21日 - */ -public class JsoupHtml { - - private String url="http://sou.zhaopin.com/jobs/searchresult.ashx?jl="; //智联招聘网站 - private String city="深圳"; //搜索工作的城市 - private String keywords="java"; //搜索工作的关键字 - public JsoupHtml(String city,String keywords){ - this.city=city; - this.keywords =keywords; - - } - - public void getZhiLianWork(){ - try { - for (int i=0;i<10;i++) { - System.out.println("*********开始遍历第"+(i+1)+"页的求职信息*********"); - Document doc = Jsoup.connect(url+city+"&kw="+keywords+"&p="+(i+1)+"&isadv=0").get(); - Element content = doc.getElementById("newlist_list_content_table"); - if(content == null){ - continue; - } - Elements zwmcEls = content.getElementsByClass("zwmc"); - Elements gsmcEls = content.getElementsByClass("gsmc"); - Elements zwyxEls = content.getElementsByClass("zwyx"); - Elements gzddEls = content.getElementsByClass("gzdd"); - Elements gxsjEls = content.getElementsByClass("gxsj"); - for(int j = 0;j当启动和去取消任务时可以控制 2>第一次执行任务时可以指定你想要的delay时间 - * 在实现时,Timer类可以调度任务,TimerTask则是通过在run()方法里实现具体任务。 Timer实例可以调度多任务,它是线程安全的。 - * 当Timer的构造器被调用时,它创建了一个线程,这个线程可以用来调度任务。 下面是代码: - */ - public static void timer2(){ - TimerTask task = new TimerTask() { - @Override - public void run() { - // task to run goes here - System.out.println("timer2 Hello !!!"); - } - }; - Timer timer = new Timer(); - long delay = 0; - long intevalPeriod = 1 * 1000; - // schedules the task to be run in an interval - timer.scheduleAtFixedRate(task, delay, intevalPeriod); - } - - /** - * ScheduledExecutorService是从Java SE5的java.util.concurrent里,做为并发工具类被引进的,这是最理想的定时任务实现方式。 - * 相比于上两个方法,它有以下好处: - * 1>相比于Timer的单线程,它是通过线程池的方式来执行任务的 - * 2>可以很灵活的去设定第一次执行任务delay时间 - * 3>提供了良好的约定,以便设定执行的时间间隔 - * 下面是实现代码,我们通过ScheduledExecutorService#scheduleAtFixedRate展示这个例子,通过代码里参数的控制,首次执行加了delay时间。 - */ - public static void timer3(){ - Runnable runnable = new Runnable() { - public void run() { - // task to run goes here - System.out.println("timer3 Hello !!"); - } - }; - ScheduledExecutorService service = Executors .newSingleThreadScheduledExecutor(); - // 第二个参数为首次执行的延时时间10s,,第三个参数为定时执行的间隔时间 2s - service.scheduleAtFixedRate(runnable, 10, 2, TimeUnit.SECONDS); - } - - - // 设定指定任务task在指定时间time执行 schedule(TimerTask task, Date time) - public static void timer4() { - Timer timer = new Timer(); - timer.schedule(new TimerTask() { - public void run() { - System.out.println("timer1() -------设定要指定任务--------"); - } - }, 2000);// 设定指定的时间time,此处为2000毫秒 - } - - // 设定指定任务task在指定延迟delay后进行固定延迟peroid的执行 - // schedule(TimerTask task, long delay, long period) - public static void timer5() { - Timer timer = new Timer(); - timer.schedule(new TimerTask() { - public void run() { - System.out.println("timer2() -------设定要指定任务--------"); - } - }, 1000, 5000); - } - - // 设定指定任务task在指定延迟delay后进行固定频率peroid的执行。 - // scheduleAtFixedRate(TimerTask task, long delay, long period) - public static void timer6() { - Timer timer = new Timer(); - timer.scheduleAtFixedRate(new TimerTask() { - public void run() { - System.out.println("timer3() -------设定要指定任务--------"); - } - }, 1000, 2000); - } - - // 安排指定的任务task在指定的时间firstTime开始进行重复的固定速率period执行. - // Timer.scheduleAtFixedRate(TimerTask task,Date firstTime,long period) - public static void timer7() { - Calendar calendar = Calendar.getInstance(); - calendar.set(Calendar.HOUR_OF_DAY, 12); // 控制时 - calendar.set(Calendar.MINUTE, 0); // 控制分 - calendar.set(Calendar.SECOND, 0); // 控制秒 - - Date time = calendar.getTime(); // 得出执行任务的时间,此处为今天的12:00:00 - - Timer timer = new Timer(); - timer.scheduleAtFixedRate(new TimerTask() { - public void run() { - System.out.println("timer4() -------设定要指定任务--------"); - } - }, time, 1000 * 60 * 60 * 24);// 这里设定将延时每天固定执行 - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/others/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/others/package-info.java deleted file mode 100644 index f052fe37d3..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/others/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: 一些其他的测试代码 -* @Version:1.0.0 -* @author pancm -* @date 2018年9月21日 -*/ -package com.jun.plugin.others; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/pojo/Student.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/pojo/Student.java deleted file mode 100644 index b8ba44b5a8..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/pojo/Student.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.jun.plugin.pojo; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.ToString; -import lombok.extern.log4j.Log4j; - -/** - * -* Title: Class -* Description: -* 学生信息表 -* Version:1.0.0 -* @author pancm -* @date 2018年1月11日 - */ -/*@Data :注解在类上;提供类所有属性的 getting 和 setting 方法,此外还提供了equals、canEqual、hashCode、toString 方法 -@Setter:注解在属性上;为属性提供 setting 方法 -@Getter:注解在属性上;为属性提供 getting 方法 -@Log4j :注解在类上;为类提供一个 属性名为log 的 log4j 日志对象 -@NoArgsConstructor:注解在类上;为类提供一个无参的构造方法 -@AllArgsConstructor:注解在类上;为类提供一个全参的构造方法*/ -@Data -@Log4j -@NoArgsConstructor -@AllArgsConstructor -@ToString(exclude = {"id","name"}) -@SuppressWarnings("unused") -public class Student { - /** 学生id */ - private int id; - /** 学生姓名 */ - private String name; - /** 班级ID */ - private int classId; -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/pojo/User.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/pojo/User.java deleted file mode 100644 index b7b8c443af..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/pojo/User.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.jun.plugin.pojo; - -import java.util.Map; - -import com.jun.plugin.utils.MyTools; - -/** - * - * @Title: User - * @Description:用户pojo类 - * @Version:1.0.0 - * @author pancm - * @date 2017年9月26日 - */ -public class User { - - /** 编号 */ - private int id; - /** 姓名 */ - private String name; - - public User() { - } - - /** - * 构造方法 - * - * @param id - * 编号 - * @param name - * 姓名 - */ - public User(int id, String name) { - super(); - this.id = id; - this.name = name; - } - - /** - * 获取编号 - * - * @return id - */ - public int getId() { - return id; - } - - /** - * 设置编号 - * - * @param id - */ - public void setId(int id) { - this.id = id; - } - - /** - * 获取姓名 - * - * @return name - */ - public String getName() { - System.out.println("姓名:"+name); - return name; - } - - /** - * 设置姓名 - * - * @param name - */ - public void setName(String name) { - this.name = name; - } - - - @SuppressWarnings("rawtypes") - public Map toMap() { - return MyTools.toMap(toString()); - } - /** - * - */ - @Override - public String toString() { - return MyTools.toString(this); - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/pojo/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/pojo/package-info.java deleted file mode 100644 index f59eadaf09..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/pojo/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** - * @Title: package-info - * @Description: 一些pojo类 - * @Version:1.0.0 - * @author pancm - * @date 2017年11月7日 - */ -package com.jun.plugin.pojo; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/question/QuestionTest1.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/question/QuestionTest1.java deleted file mode 100644 index 1dde9ad7fc..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/question/QuestionTest1.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.jun.plugin.question; - -/** - * @Title: QuestionTest1 - * @Description: - * @Version:1.0.0 - * @author pancm - * @date 2017年7月21日 - */ -public class QuestionTest1 { - - /** - * @param args - */ - public static void main(String[] args) { - - /* - * 在一个二维数组中,每一行都按照从左到右递增的顺序排序, 每一列都按照从上到下递增的顺序排序。请完成一个函数, - * 输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。 - */ - int target = 4; - int target1 = 5; - int target2 = 6; - int[][] array = { { 1, 2, 3, 4 }, { 1, 2, 3, 4, 5 } }; - System.out.println(Find(target, array)); - System.out.println(Find(target1, array)); - System.out.println(Find(target2, array)); - System.out.println(Find2(target, array)); - System.out.println(Find2(target1, array)); - System.out.println(Find2(target2, array)); - - - - } - - /** - * 方法一:最笨的方法,利用双重循环找到 - * - * @param target - * @param array - * @return - */ - public static boolean Find(int target, int[][] array) { - for (int[] i : array) { - for (int j : i) { - if (j == target) { - return true; - } - } - } - return false; - } - - /** - * 方法二: 最优解法。 思路:首先我们选择从左下角开始搜寻, (为什么不从左上角开始搜寻,左上角向右和向下都是递增,那么对于一个点, - * 对于向右和向下会产生一个岔路;如果我们选择从左下脚开始搜寻的话, 如果大于就向右,如果小于就向下)。 - * - * @param target - * @param array - * @return - */ - public static boolean Find2(int target, int[][] array) { - int len = array.length - 1; // 得出二维数组的列长度 - int i = 0; - while ((len > 0) && (i < array[0].length)) { - if (array[len][i] > target) { // 如果左下角的数值大于要找的数字,则向右,否则向下 - len--; - } else if (array[len][i] < target) { - i++; - } else { - return true; - } - } - return false; - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/question/QuestionTest2.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/question/QuestionTest2.java deleted file mode 100644 index 924188e486..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/question/QuestionTest2.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.jun.plugin.question; - -/** - * @Title: QuestionTest1 - * @Description: - * @Version:1.0.0 - * @author pancm - * @date 2017年7月21日 - */ -public class QuestionTest2 { - - /** - * @param args - */ - public static void main(String[] args) { - - /* - * 请实现一个函数,将一个字符串中的空格替换成“%20”。 - * 例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。 - */ - StringBuffer str=new StringBuffer("We Are Happy"); - System.out.println(replaceString(str)); - System.out.println(replaceString2(str)); - - - } - - /** - * 方法一:利用String的replace 直接替换 - * @param str - * @return String - */ - public static String replaceString(StringBuffer str){ - if(str==null){ - return null; - } - return str.toString().replaceAll(" ", "%20"); - } - - /** - * 方法二:利用数组循环取出 - * @param str - * @return - */ - public static String replaceString2(StringBuffer str){ - if(str==null){ - return null; - } - char []c =str.toString().toCharArray(); - StringBuffer sb=new StringBuffer(); - for(int i=0;i list = jedis.lrange("list", 0, 2); - for (int i = 0, j = list.size(); i < j; i++) { - System.out.println("list的输出结果:" + list.get(i)); - } - - jedis.set("rst", "redisStringTest"); - System.out.println("redis 存储的字符串为: " + jedis.get("rst")); - - jedis.sadd("setTest1", "abc"); - jedis.sadd("setTest1", "abcd"); - jedis.sadd("setTest1", "abcde"); - Set keys = jedis.keys("*"); - Iterator it = keys.iterator(); - while (it.hasNext()) { - String key = it.next(); - System.out.println(key); - } - - } - -} -*/ diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/redis/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/redis/package-info.java deleted file mode 100644 index bb88e773e4..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/redis/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: redis 相关代码 -* @Version:1.0.0 -* @author pancm -* @date 2018年9月21日 -*/ -package com.jun.plugin.redis; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/sql/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/sql/package-info.java deleted file mode 100644 index 1b74380462..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/sql/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: 数据库相关的代码 -* @Version:1.0.0 -* @author pancm -* @date 2018年9月21日 -*/ -package com.jun.plugin.sql; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/ThreadPoolTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/ThreadPoolTest.java deleted file mode 100644 index 9a25034fc6..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/ThreadPoolTest.java +++ /dev/null @@ -1,204 +0,0 @@ -package com.jun.plugin.thread; - -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - * -* @Title: ThreadPoolTest -* @Description: -* 线程池测试 -* @Version:1.0.0 -* @author pancm -* @date 2018年3月1日 - */ -public class ThreadPoolTest { - - public static void main(String[] args) { -// cachedThreadPool(); -// fixedThreadPool(); -// newSingleThreadExecutor(); -// newScheduledThreadPool(); -// newScheduledThreadPool2(); - threadPoolExecutor(); - } - - /** - * 创建一个可缓存的线程池,如果当前线程池的规模超出了处理需求,将回收空的线程;当需求增加时,会增加线程数量;线程池规模无限制。 - */ - private static void cachedThreadPool() { - ExecutorService exec=Executors.newCachedThreadPool(); - for(int i=0;i<10;i++){ - exec.execute(new MyThread(String.valueOf(i))); - } - //执行到此处并不会马上关闭线程池,执行完成之后才会关闭 但之后不能再往线程池中加线程,否则会报错 - exec.shutdown(); - System.out.println("运行结束!"); - /** - * 1、主线程的执行与线程池里的线程分开,有可能主线程结束了,但是线程池还在运行 - * 2、放入线程池的线程并不一定会按其放入的先后而顺序执行 - * - */ - } - - /** - * 创建一个固定长度的线程池,当到达线程最大数量时,线程池的规模将不再变化。 - */ - private static void fixedThreadPool() { - ExecutorService exec = Executors.newFixedThreadPool(5); - for(int i = 0; i < 10; i++) { - exec.execute(new MyThread(String.valueOf(i))); - } - exec.shutdown(); //执行到此处并不会马上关闭线程池 - System.out.println("运行结束!"); - /** - * 1线程开始运行,时间2018-03-01 11:50:33 170 - 4线程开始运行,时间2018-03-01 11:50:33 170 - 3线程开始运行,时间2018-03-01 11:50:33 170 - 2线程开始运行,时间2018-03-01 11:50:33 170 - 0线程开始运行,时间2018-03-01 11:50:33 170 - 4线程运行结束,时间2018-03-01 11:50:34 171 - 3线程运行结束,时间2018-03-01 11:50:34 171 - 2线程运行结束,时间2018-03-01 11:50:34 171 - 5线程开始运行,时间2018-03-01 11:50:34 172 - 6线程开始运行,时间2018-03-01 11:50:34 172 - 7线程开始运行,时间2018-03-01 11:50:34 172 - 1线程运行结束,时间2018-03-01 11:50:34 172 - 0线程运行结束,时间2018-03-01 11:50:34 172 - 8线程开始运行,时间2018-03-01 11:50:34 172 - 9线程开始运行,时间2018-03-01 11:50:34 172 - 8线程运行结束,时间2018-03-01 11:50:35 181 - 6线程运行结束,时间2018-03-01 11:50:35 181 - 9线程运行结束,时间2018-03-01 11:50:35 181 - 7线程运行结束,时间2018-03-01 11:50:35 181 - 5线程运行结束,时间2018-03-01 11:50:35 181 - - 结论:1,FixedThreadPool模式会使用一个优先固定数目的线程来处理若干数目的任务。 - 2,FixedThreadPool模式下最多 的线程数目是一定的。 - - */ - } - - /** - * 创建一个单线程的Executor,确保任务对了,串行执行 - */ - private static void newSingleThreadExecutor() { - ExecutorService exec = Executors.newSingleThreadExecutor(); //创建大小为1的固定线程池 - for(int i = 0; i < 10; i++) { - exec.execute(new MyThread(String.valueOf(i))); - } - exec.shutdown(); //执行到此处并不会马上关闭线程池 - System.out.println("运行结束!"); - } - - - /** - * 创建一个固定长度的线程池,而且以延迟或者定时的方式来执行,类似Timer; - */ - private static void newScheduledThreadPool() { - ScheduledThreadPoolExecutor exec = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(10); //创建大小为10的线程池 - for(int i = 0; i < 10; i++) { - exec.schedule(new MyThread(String.valueOf(i)), 2, TimeUnit.SECONDS);//延迟2秒执行 - } - //如果任务都完成了则返回true - while(!exec.isTerminated()){ - //wait for all tasks to finish -// System.out.println("正在运行中..."); - } - System.out.println("运行结束!"); - } - - /** - * 设置固定时间执行 - */ - private static void newScheduledThreadPool2() { - ScheduledThreadPoolExecutor exec = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(10); //创建大小为10的线程池 - long oneDay = 24 * 60 * 60 * 1000; - long initDelay = getTimeMillis("14:08:00") - System.currentTimeMillis(); - initDelay = initDelay > 0 ? initDelay : oneDay + initDelay; - exec.scheduleAtFixedRate(new MyThread(String.valueOf(1)), initDelay, oneDay, TimeUnit.MILLISECONDS); - System.out.println("运行结束!"); - } - - /** - * 获取指定时间对应的毫秒数 - * @param time "HH:mm:ss" - * @return - */ - private static long getTimeMillis(String time) { - try { - DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss"); - DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd"); - Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time); - return curDate.getTime(); - } catch (ParseException e) { - e.printStackTrace(); - } - return 0; - } - - /** - * ThreadPoolExecutor线程池 - */ - private static void threadPoolExecutor() { - int corePoolSize=5; - int maximumPoolSize=10; - long keepAliveTime=2L; - // 线程核心数,最大线程数,线程缓存时间,时间格式,缓存队列 ,线程工厂,拒绝策略 - ThreadPoolExecutor tpx=new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, - TimeUnit.SECONDS, new ArrayBlockingQueue(3), - Executors.defaultThreadFactory(),new ThreadPoolExecutor.DiscardOldestPolicy()); - - for (int i = 1; i <= 10; i++) { - try { - // 产生一个任务,并将其加入到线程池 - String task = "task@ " + i; -// System.out.println("put " + task); - tpx.execute(new MyThread(task)); - // 便于观察,等待一段时间 - Thread.sleep(20); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - - -} - -class MyThread implements Runnable{ - private String name; - public MyThread(String name){ - this.name=name; - } - - @Override - public void run() { - System.out.println(name+ "线程开始运行,时间:" +getNowTime()); - pause(1000); - System.out.println(name+ "线程运行结束,时间:" +getNowTime()); - } - - private void pause(long lo) { - try { - Thread.sleep(lo); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - } - - private String getNowTime(){ - return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS").format(new Date()); - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/concurrent/liveLock/Consumer.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/concurrent/liveLock/Consumer.java deleted file mode 100644 index eab3f2af6e..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/concurrent/liveLock/Consumer.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.jun.plugin.thread.concurrent.liveLock; - -import java.util.Random; - - -public class Consumer implements Runnable { - private Drop drop; - - public Consumer(Drop drop) { - this.drop = drop; - } - public void run() { - Random random = new Random(); -// String message=""; -// do{ -// message= drop.take(); -// System.out.format("MESSAGE RECEIVED: %s%n", message); -// try { -// Thread.sleep(random.nextInt(1000)); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } while(!message.equals("DONE")); - - for (String message = drop.take(); !message.equals("DONE"); message = drop.take()) { - System.out.format("MESSAGE RECEIVED: %s%n", message); - try { - Thread.sleep(random.nextInt(1000)); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/concurrent/liveLock/Drop.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/concurrent/liveLock/Drop.java deleted file mode 100644 index bd9ca0dd22..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/concurrent/liveLock/Drop.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.jun.plugin.thread.concurrent.liveLock; - -/** - * -* Title: Drop -* Description: -* 数据协同 -* Version:1.0.0 -* @author pancm -* @date 2018年3月8日 - */ -public class Drop { - // 发送的消息 - private String message; - //true 表示消费者应该等待生产者发送消息 - // flase 表示生产者应该等待消费者获取消息 - private boolean empty = true; - - public synchronized String take() { - // 等待消息可用 - while (empty) { - try { - wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - // 改变状态 - empty = true; - // 通知消费者状态改变 - notifyAll(); - return message; - } - - public synchronized void put(String message) { - //等待消息被检索到 - while (!empty) { - try { - wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - // 改变状态 - empty = false; - this.message = message; - // 通知消费者状态改变 - notifyAll(); - } - } \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/concurrent/liveLock/Producer.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/concurrent/liveLock/Producer.java deleted file mode 100644 index 15defc1b2a..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/concurrent/liveLock/Producer.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.jun.plugin.thread.concurrent.liveLock; - -import java.util.Random; - -/** - * -* Title: Producer -* Description: -* 消息生产者 -* Version:1.0.0 -* @author pancm -* @date 2018年3月8日 - */ -public class Producer implements Runnable { - private Drop drop; - public Producer(Drop drop) { - this.drop = drop; - } - - public void run() { - String importantInfo[] = { "第一条数据", "第二条数据", "第三条数据", - "第四条数据" }; - Random random = new Random(); - for (int i = 0; i < importantInfo.length; i++) { - drop.put(importantInfo[i]); - try { - Thread.sleep(random.nextInt(1000)); - } catch (InterruptedException e) { - } - } - //表示已经发送完 - drop.put("DONE"); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/concurrent/liveLock/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/concurrent/liveLock/package-info.java deleted file mode 100644 index db1beb1675..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/concurrent/liveLock/package-info.java +++ /dev/null @@ -1,13 +0,0 @@ -/** - * - */ -/** - * Title: package-info - * Description: - * 活锁测试 - * 一个线程常常处于响应另一个线程的动作,如果其他线程也常常处于该线程的动作,那么就可能出现活锁。 - * Version:1.0.0 - * @author pancm - * @date 2018年3月8日 - */ -package com.jun.plugin.thread.concurrent.liveLock; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/concurrent/liveLock/test.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/concurrent/liveLock/test.java deleted file mode 100644 index 51b54e8ee8..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/concurrent/liveLock/test.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jun.plugin.thread.concurrent.liveLock; - - - -/** - * -* Title: -* Description: -* 多线程共享测试 -* Version:1.0.0 -* @author pancm -* @date 2018年3月8日 - */ -public class test{ - - public static void main(String[] args) { - Drop drop=new Drop(); - (new Thread(new Producer(drop))).start(); - (new Thread(new Consumer(drop))).start(); - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/concurrent/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/concurrent/package-info.java deleted file mode 100644 index 73e9a11bf2..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/concurrent/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: 并发相关的测试代码 -* @Version:1.0.0 -* @author pancm -* @date 2018年9月20日 -*/ -package com.jun.plugin.thread.concurrent; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/lock/LockSydTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/lock/LockSydTest.java deleted file mode 100644 index 4c3024cebb..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/lock/LockSydTest.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.jun.plugin.thread.lock; - -import java.util.Calendar; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -/** -* @Title: LockSydTest -* @Description: Lock(显示锁)和synchronized(内部锁) 测试 -* @Version:1.0.0 -* @author pancm -* @date 2017年10月18日 - */ -public class LockSydTest { - - public static void main(String[] args) { - try { - runTasks(lockTest.class); - runTasks(synTest.class); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * 任务执行器 - * @param cl - * @throws Exception - */ - public static void runTasks(Class cl) throws Exception{ - ExecutorService es=Executors.newCachedThreadPool(); //创建一个执行器 - System.out.println("---开始执行---"+cl.getSimpleName()+" 任务"); - //启动三个线程 - for(int i=0;i<3;i++){ - es.submit(cl.newInstance()); - } - //等待足够长的时间,然后关闭执行器 - TimeUnit.SECONDS.sleep(10); - System.out.println("---结束任务---"+cl.getSimpleName()+" 任务执行完毕 \n"); - es.shutdown();//关闭执行器 - - - /* - * 输出结果: - * ---开始执行---lockTest 任务 - 线程名称:pool-1-thread-2,执行时间:35 s - 线程名称:pool-1-thread-3,执行时间:35 s - 线程名称:pool-1-thread-1,执行时间:35 s - ---结束任务---lockTest 任务执行完毕 - - ---开始执行---synTest 任务 - 线程名称:pool-2-thread-1,执行时间:45 s - 线程名称:pool-2-thread-3,执行时间:47 s - 线程名称:pool-2-thread-2,执行时间:49 s - ---结束任务---synTest 任务执行完毕 - * - */ - - /* 总结: - * lock(显示锁) 是对象级别的锁,而synchronized(内部锁)是类级别的锁, - * 也就是说显示锁是跟着对象的,而内部锁是跟随类的。 - * 简单来说的话,把lock定义为多线程类的私有属性是起不到资源互斥作用的, - * 除非把lock定义为所有线程的共享变量。 - * - */ - } -} - -class Task{ - public void doSomething(){ - try{ - Thread.sleep(2000); //等待2秒,此处线程状态转为WAITING - }catch(Exception e){ - - } - StringBuffer sb=new StringBuffer(); - sb.append("线程名称:"+Thread.currentThread().getName()); - sb.append(",执行时间:"+Calendar.getInstance().get(13)+" s"); - System.out.println(sb); - } -} - -/** - * -* Title: lockTest -* Description: Lock(显示锁)测试 -* Version:1.0.0 -* @author pancm -* @date 2017年10月18日 - */ -class lockTest extends Task implements Runnable{ - private final Lock lock=new ReentrantLock(); - @Override - public void run() { - try{ - lock.lock(); - doSomething(); - }catch(Exception e){ - - }finally{ - lock.unlock(); //释放锁 - } - } -} - -/** - * -* Title: lockTest -* Description: synchronized(内部锁)测试 -* Version:1.0.0 -* @author pancm -* @date 2017年10月18日 - */ -class synTest extends Task implements Runnable{ - @Override - public void run() { - synchronized("A"){ - doSomething(); - } - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/lock/LockTest1.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/lock/LockTest1.java deleted file mode 100644 index 8cda44ede3..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/lock/LockTest1.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.jun.plugin.thread.lock; - -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -/** - * -* @Title: LockTest1 -* @Description: Lock(显示锁)和synchronized(内部锁) 测试 -* @Version:1.0.0 -* @author pancm -* @date 2017年10月23日 - */ -public class LockTest1 { - - public static void main(String[] args) { - - } - -} - -class Foo{ - /** 可重入的读写锁 */ - private final ReentrantReadWriteLock rwl=new ReentrantReadWriteLock(); - - /** 读锁 */ - private final Lock r=rwl.readLock(); - - /** 写锁 */ - private final Lock w=rwl.writeLock(); - - - //读操作,可并发执行 - public void read(){ - try{ - r.lock(); - Thread.sleep(1000); - System.out.println("read......"); - }catch(InterruptedException e){ - e.printStackTrace(); - }finally{ - r.unlock(); - } - } - - //写操作,同时值允许一个执行 - public void write(){ - try{ - w.lock(); - Thread.sleep(1000); - System.out.println("write......"); - }catch(InterruptedException e){ - e.printStackTrace(); - }finally{ - w.unlock(); - } - } - - /* - * 1.Lock支持更细粒度的锁控制; - * 2.Lock是无阻塞锁,synchronized是阻塞锁; - * 例:当线程A持有锁的时,线程B也期望获得锁,此时,如果线程是使用的显示锁,则B线程为等待状态(即阻塞); - * 如果使用的是内部锁则为阻塞状态。 - * - * 3.Lock可以实现公平锁,而synchronized只能是非公平锁; - * 非公平锁:当一个线程A持有锁,而线程B、C处于阻塞状态时, 若线程A释放锁,JVM将从线程B、C随机选择一个线程持有锁并使其获得执行权, - * 这叫做非公平锁(因为它抛弃了先来后到的顺序); - * 公平锁:若JVM选择了等待时间最长的一个线程持有锁,则为公平锁(保证每个线程的等待时间均衡)。 - * 需要注意的是,即使是公平锁,JVM也无法做到准确的“公平”,在程序中不能以此作为计算。 - * 显示锁默认是非公平锁,可以在构造函数中增加true来声明公平锁,而synchronized只能是实现非公平锁。 - * - * 4.Lock是代码级,synchronized是JVM级的 - * Lock是通过编码实现的,synchronized是在运行期由JVM解释的,相对来说synchronized的优化可能性更高, - * 毕竟是在最核心部分支持的,Lock的优化则需要用户自行考虑。 - * 灵活、强大选择Lock;快捷、安全选择synchronized。 - * - * - * - * - * - */ - - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/lock/LockTest2.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/lock/LockTest2.java deleted file mode 100644 index facd5acd1a..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/lock/LockTest2.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.jun.plugin.thread.lock; - -import java.util.concurrent.locks.Condition; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -/** - * - * @Title: LockTest2 - * @Description: 显示锁的唤醒测试 - * @Version:1.0.0 - * @author pancm - * @date 2018年2月28日 - */ -public class LockTest2 { - final Lock lock = new ReentrantLock(); - - final Condition notfull = lock.newCondition(); - - final Condition notempty = lock.newCondition(); - - final Object[] items = new Object[100]; - - int putptr, takeptr, count; - - public static void main(String[] args) throws InterruptedException { - LockTest2 lt = new LockTest2(); - Object obj = 2; - lt.put(obj); - lt.take(); - } - - /** - * 而现在锁是指定对象lock。所以查找等待唤醒机制方式需要通过lock接口来完成。 - * 而lock接口中并没有直接操作等待唤醒的方法,而是将这些方式又单独封装到了一个对象中。 - * 这个对象就是condition,将object中的三个方法进行单独的封装。 并提供了功能一致的方法 - * await()、signal()、signalall()体现新版本对象的好处。 - * - * @param x - * @throws InterruptedException - */ - public void put(Object x) throws InterruptedException { - lock.lock(); - try { - while (count == items.length) { - notfull.await(); - } - items[putptr] = x; - - if (++putptr == items.length) { - putptr = 0; - } - ++count; - //唤醒一个等待的线程 - notempty.signal(); - - } finally { - lock.unlock(); - } - } - - private Object take() throws InterruptedException { - lock.lock(); - try { - while (count == 0) { - notempty.await(); - } - Object x = items[takeptr]; - - if (++takeptr == items.length) { - takeptr = 0; - } - --count; - //唤醒一个等待的线程 - notfull.signal(); - return x; - - } finally { - lock.unlock(); - } - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/lock/VolatileTest1.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/lock/VolatileTest1.java deleted file mode 100644 index e06ac75bc0..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/lock/VolatileTest1.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.jun.plugin.thread.lock; - -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -/** - * -* Title: VolatileTest1 -* Description: volatile关键字的测试 -* Version:1.0.0 -* @author pancm -* @date 2017年9月21日 - */ -public class VolatileTest1 { - public volatile int inv = 0; //使用volatile 保证了可见性,其他线程也可以查看更新之后的值 - public int ins = 0; - - public int inl = 0; - Lock lock = new ReentrantLock(); - - public void increase() { - inv++; - } - - public synchronized void insrease() { //使用synchronized,可以保证原子性 - ins++; - } - - public void inlrease(){ //使用loca 也可以保证 - lock.lock(); - try { - inl++; - } finally{ - lock.unlock(); - } - } - - - public static void main(String[] args) { - volatileTs(); - synTs(); - lockTs(); - } - - /** - * 使用 volatile 是无法保证 原子性的 - * 因为 自增操作不是原子性操作 - */ - public static void volatileTs(){ - final VolatileTest1 test = new VolatileTest1(); - for(int i=0;i<10;i++){ - new Thread(){ - @Override - public void run() { - for(int j=0;j<1000;j++) { - test.increase(); - } - }; - }.start(); - } - while(Thread.activeCount()>1) { - Thread.yield(); - } - System.out.println(test.inv); //数据小于 10000 例如:9303,9068 - } - - /** - * 使用synchronized,可以保证原子性 - */ - public static void synTs(){ - final VolatileTest1 test = new VolatileTest1(); - for(int i=0;i<10;i++){ - new Thread(){ - @Override - public void run() { - for(int j=0;j<1000;j++) { - test.insrease(); - } - }; - }.start(); - } - while(Thread.activeCount()>1) { - Thread.yield(); - } - System.out.println(test.ins); // 10000 保证了原子性 - } - - /** - * 使用lock,可以保证原子性 - */ - public static void lockTs(){ - final VolatileTest1 test = new VolatileTest1(); - for(int i=0;i<10;i++){ - new Thread(){ - @Override - public void run() { - for(int j=0;j<1000;j++) { - test.inlrease(); - } - }; - }.start(); - } - while(Thread.activeCount()>1) { - Thread.yield(); - } - System.out.println(test.inl); //10000 保证了原子性 - } - - - } - diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/lock/VolatileTest2.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/lock/VolatileTest2.java deleted file mode 100644 index 95d70b9a51..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/lock/VolatileTest2.java +++ /dev/null @@ -1,112 +0,0 @@ -package com.jun.plugin.thread.lock; - -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -/** - * -* Title: volatileTest1 -* Description: -* volatile关键字的测试 -* Version:1.0.0 -* @author pancm -* @date 2017年9月21日 - */ -public class VolatileTest2 { - public volatile long inv = 0; //使用volatile 保证了可见性,其他线程也可以查看更新之后的值 - public long ins = 0; - - public long inl = 0; - Lock lock = new ReentrantLock(); - - public void increase() { - inv++; - } - - public synchronized void insrease() { //使用synchronized,可以保证原子性 - ins++; - } - - public void inlrease(){ //使用loca 也可以保证 - lock.lock(); - try { - inl++; - } finally{ - lock.unlock(); - } - } - - - public static void main(String[] args) { - volatileTs(); - synTs(); - lockTs(); - } - - /** - * 使用 volatile 是无法保证 原子性的 - * 因为 自增操作不是原子性操作 - */ - public static void volatileTs(){ - final VolatileTest2 test = new VolatileTest2(); - for(int i=0;i<10;i++){ - new Thread(){ - @Override - public void run() { - for(int j=0;j<1000;j++) { - test.increase(); - } - }; - }.start(); - } - while(Thread.activeCount()>1) { - Thread.yield(); - } - System.out.println(test.inv); //数据小于 10000 例如:9303,9068 - } - - /** - * 使用synchronized,可以保证原子性 - */ - public static void synTs(){ - final VolatileTest2 test = new VolatileTest2(); - for(int i=0;i<10;i++){ - new Thread(){ - @Override - public void run() { - for(int j=0;j<1000;j++) { - test.insrease(); - } - }; - }.start(); - } - while(Thread.activeCount()>1) { - Thread.yield(); - } - System.out.println(test.ins); // 10000 保证了原子性 - } - - /** - * 使用lock,可以保证原子性 - */ - public static void lockTs(){ - final VolatileTest2 test = new VolatileTest2(); - for(int i=0;i<10;i++){ - new Thread(){ - @Override - public void run() { - for(int j=0;j<1000;j++) { - test.inlrease(); - } - }; - }.start(); - } - while(Thread.activeCount()>1) { - Thread.yield(); - } - System.out.println(test.inl); //10000 保证了原子性 - } - - - } - diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/lock/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/lock/package-info.java deleted file mode 100644 index e3daa67e4c..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/lock/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** - * @Title: package-info - * @Description: 一些锁的测试代码 - * @Version:1.0.0 - * @author pancm - * @date 2017年11月7日 - */ -package com.jun.plugin.thread.lock; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/package-info.java deleted file mode 100644 index 0d882cd226..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/package-info.java +++ /dev/null @@ -1,9 +0,0 @@ -/** - * @Title: package-info - * @Description: - * 线程相关的测试类 - * Version:1.0.0 - * @author pancm - * @date 2018年3月1日 - */ -package com.jun.plugin.thread; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/JoinTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/JoinTest.java deleted file mode 100644 index b2898e8b66..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/JoinTest.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.jun.plugin.thread.test; - -import java.util.Random; - -/** -* @Title: JoinTest -* @Description: -* join方法测试 -* @Version:1.0.0 -* @author pancm -* @date 2018年5月22日 -*/ -public class JoinTest { - - public static void main(String[] args) { - System.out.println(Thread.currentThread().getName()+ "主线程开始运行!"); - Test2 t1=new Test2("A"); - Test2 t2=new Test2("B"); - t1.start(); - t2.start(); - try { - t1.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - try { - t2.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - System.out.println(Thread.currentThread().getName()+ "主线程运行结束!"); - } - -} - -class Test2 extends Thread{ - public Test2(String name) { - super(name); - } - public void run() { - System.out.println(this.getName() + " 线程运行开始!"); - for (int i = 0; i < 5; i++) { - System.out.println("子线程"+this.getName() + "运行 : " + i); - try { - sleep(new Random().nextInt(10)); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - System.out.println(this.getName() + " 线程运行结束!"); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/MyRunnable.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/MyRunnable.java deleted file mode 100644 index 39ef52704a..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/MyRunnable.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.jun.plugin.thread.test; -/** - * @author ZERO - * @Data 2017-5-24 下午2:29:39 - * @Description - */ -public class MyRunnable implements Runnable{ - private int i = 0; - private boolean stop=false; - public void set(boolean falg) throws InterruptedException{ - if(!falg){ - synchronized (this) { - this.notify(); - stop=true; - System.out.println("启动的线程:"+Thread.currentThread().getId()); - } - } - - } - - @Override - public void run() { - for (;;) { - synchronized (this) { - if(stop){ - try { - this.wait(); - System.out.println("暂停的线程:"+Thread.currentThread().getId()); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - i++; - System.out.println("MyRunnable:"+Thread.currentThread().getName() + "第" + i+ "次"); - try { - Thread.sleep(100); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/MyThread.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/MyThread.java deleted file mode 100644 index bd456db333..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/MyThread.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jun.plugin.thread.test; -/** - * @author ZERO - * @Data 2017-5-24 下午2:20:29 - * @Description - */ -public class MyThread extends Thread{ - - private int i = 0; - - @Override - public void run() { - for (i = 0; i < 10; i++) { - System.out.println("MyThread:"+Thread.currentThread().getName() + "第" + i+ "次"); - } - } - - - - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/NotifyTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/NotifyTest.java deleted file mode 100644 index 17aa2da7bb..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/NotifyTest.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.jun.plugin.thread.test; - -import java.util.Random; - -/** - * @Title: NotifyTest - * @Description: - * wait 和 notify测试 - * @Version:1.0.0 - * @author pancm - * @date 2018年5月22日 - */ -public class NotifyTest { - - public static void main(String[] args) { - Test4 t1 = new Test4("张三"); - Test4 t2 = new Test4("李四"); - t1.start(); - t2.start(); - } -} - -class Test4 extends Thread { - private String name; - public Test4(String name) { - super(name); - this.name=name; - } - - @Override - public void run() { - System.out.println(this.getName() + " 线程运行开始!"); - - for (int i = 0; i < 5; i++) { - System.out.println("子线程" + this.getName() + "运行 : " + i); - try { - sleep(new Random().nextInt(100)); - } catch (InterruptedException e) { - e.printStackTrace(); - } - try { - if("李四".equals(this.getName())){ - this.getName().wait(); - } - } catch (InterruptedException e) { - e.printStackTrace(); - } - this.getName().notify(); - - } - System.out.println(this.getName() + " 线程运行结束!"); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/PriorityTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/PriorityTest.java deleted file mode 100644 index f7d968f825..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/PriorityTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.jun.plugin.thread.test; - -import java.util.Random; - -/** -* @Title: PriorityTest -* @Description: -* 线程优先级测试 -* @Version:1.0.0 -* @author pancm -* @date 2018年5月27日 -*/ -public class PriorityTest { - - public static void main(String[] args) { - Test3 t1 = new Test3("张三"); - Test3 t2 = new Test3("李四"); - t1.setPriority(Thread.MIN_PRIORITY); - t2.setPriority(Thread.MAX_PRIORITY); - t1.start(); - t2.start(); - } -} - -class Test3 extends Thread { - public Test3(String name) { - super(name); - } - @Override - public void run() { - System.out.println(this.getName() + " 线程运行开始!"); - for (int i = 1; i <= 5; i++) { - System.out.println("子线程"+this.getName() + "运行 : " + i); - try { - sleep(new Random().nextInt(10)); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - System.out.println(this.getName() + " 线程运行结束!"); - } -} - diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/Test.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/Test.java deleted file mode 100644 index 7d1db77228..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/Test.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * - */ -package com.jun.plugin.thread.test; - -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.FutureTask; - -/** -* @Title: Test -* @Description: -* @Version:1.0.0 -* @author pancm -* @date 2018年5月17日 -*/ -public class Test { - - public static void main(String[] args) { - ThreadTest threadTest=new ThreadTest(); - threadTest.setPriority(1); - threadTest.start(); - - RunalbeTest runalbeTest=new RunalbeTest(); - Thread thread=new Thread(runalbeTest); - thread.setPriority(10); - thread.start(); - - CallableTest callableTest=new CallableTest(); - FutureTask ft = new FutureTask(callableTest); - Thread thread2=new Thread(ft); - thread2.setPriority(5); - thread2.start(); - try { - System.out.println("返回值:"+ft.get()); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (ExecutionException e) { - e.printStackTrace(); - } - } - -} - - -class ThreadTest extends Thread{ - @Override - public void run() { - for(int i=1;i<5;i++){ - System.out.println("这是一个Thread的线程!"+i); - try { - sleep(50); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - System.out.println("Thread的线程执行完了!"); - - } -} - - -class RunalbeTest implements Runnable{ - @Override - public void run() { - for(int i=1;i<5;i++){ - System.out.println("这是一个Runnable的线程!"+i); - try { - Thread.sleep(50); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - System.out.println("Runnable的线程执行完了!"); - - } -} - - -class CallableTest implements Callable{ - - @Override - public Integer call() throws Exception { - for(int i=1;i<5;i++){ - System.out.println("这是一个Callable的线程!"+i); - try { - Thread.sleep(50); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - System.out.println("Callable的线程执行完了!"); - return 2; - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/Test22.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/Test22.java deleted file mode 100644 index be6e94f415..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/Test22.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.jun.plugin.thread.test; - -import java.util.HashMap; -import java.util.Map; - - -public class Test22 { - - public static void main(String[] args) { - Map map=new HashMap(); - map.put(0, 0); - map.put(1, 1); - for(Integer type:map.keySet()){ - Thread3 t3=new Thread3(type); - t3.start(); - } - } -} - -class Thread3 extends Thread{ - - private int type; - - public Thread3(int type){ - this.type=type; - } - - @Override - public void run() { - if(type==0){ - //连接mysql - System.out.println("线程ID:"+getId()+"连接mysql"); - }else if(type==1){ - //连接oracle - System.out.println("线程ID:"+getId()+"连接oracle"); - } - } - - - - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/TheadTest3.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/TheadTest3.java deleted file mode 100644 index 194efe212c..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/TheadTest3.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.jun.plugin.thread.test; - -public class TheadTest3 { - - public static void main(String[] args) throws InterruptedException { - MyRunnable myRunnable=new MyRunnable(); - for(int i=1;i<=5;i++){ - Thread thread=new Thread(myRunnable); - thread.setName("myRunnable-"+i); - thread.start(); - } - Thread.sleep(2000); - myRunnable.set(true); - Thread.sleep(3000); - myRunnable.set(false); - for(int i=1;i<=5;i++){ - MyThread myThread=new MyThread(); - myThread.setName("myThread-"+i); - myThread.start(); - } - - - System.out.println("结束..."); - } - - - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/ThreadPoolTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/ThreadPoolTest.java deleted file mode 100644 index c74c354df3..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/ThreadPoolTest.java +++ /dev/null @@ -1,204 +0,0 @@ -package com.jun.plugin.thread.test; - -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - * -* @Title: ThreadPoolTest -* @Description: -* 线程池测试 -* @Version:1.0.0 -* @author pancm -* @date 2018年3月1日 - */ -public class ThreadPoolTest { - - public static void main(String[] args) { -// cachedThreadPool(); -// fixedThreadPool(); -// newSingleThreadExecutor(); -// newScheduledThreadPool(); -// newScheduledThreadPool2(); - threadPoolExecutor(); - } - - /** - * 创建一个可缓存的线程池,如果当前线程池的规模超出了处理需求,将回收空的线程;当需求增加时,会增加线程数量;线程池规模无限制。 - */ - private static void cachedThreadPool() { - ExecutorService exec=Executors.newCachedThreadPool(); - for(int i=0;i<10;i++){ - exec.execute(new MyThread2(String.valueOf(i))); - } - //执行到此处并不会马上关闭线程池,执行完成之后才会关闭 但之后不能再往线程池中加线程,否则会报错 - exec.shutdown(); - System.out.println("运行结束!"); - /** - * 1、主线程的执行与线程池里的线程分开,有可能主线程结束了,但是线程池还在运行 - * 2、放入线程池的线程并不一定会按其放入的先后而顺序执行 - * - */ - } - - /** - * 创建一个固定长度的线程池,当到达线程最大数量时,线程池的规模将不再变化。 - */ - private static void fixedThreadPool() { - ExecutorService exec = Executors.newFixedThreadPool(5); - for(int i = 0; i < 10; i++) { - exec.execute(new MyThread2(String.valueOf(i))); - } - exec.shutdown(); //执行到此处并不会马上关闭线程池 - System.out.println("运行结束!"); - /** - * 1线程开始运行,时间2018-03-01 11:50:33 170 - 4线程开始运行,时间2018-03-01 11:50:33 170 - 3线程开始运行,时间2018-03-01 11:50:33 170 - 2线程开始运行,时间2018-03-01 11:50:33 170 - 0线程开始运行,时间2018-03-01 11:50:33 170 - 4线程运行结束,时间2018-03-01 11:50:34 171 - 3线程运行结束,时间2018-03-01 11:50:34 171 - 2线程运行结束,时间2018-03-01 11:50:34 171 - 5线程开始运行,时间2018-03-01 11:50:34 172 - 6线程开始运行,时间2018-03-01 11:50:34 172 - 7线程开始运行,时间2018-03-01 11:50:34 172 - 1线程运行结束,时间2018-03-01 11:50:34 172 - 0线程运行结束,时间2018-03-01 11:50:34 172 - 8线程开始运行,时间2018-03-01 11:50:34 172 - 9线程开始运行,时间2018-03-01 11:50:34 172 - 8线程运行结束,时间2018-03-01 11:50:35 181 - 6线程运行结束,时间2018-03-01 11:50:35 181 - 9线程运行结束,时间2018-03-01 11:50:35 181 - 7线程运行结束,时间2018-03-01 11:50:35 181 - 5线程运行结束,时间2018-03-01 11:50:35 181 - - 结论:1,FixedThreadPool模式会使用一个优先固定数目的线程来处理若干数目的任务。 - 2,FixedThreadPool模式下最多 的线程数目是一定的。 - - */ - } - - /** - * 创建一个单线程的Executor,确保任务对了,串行执行 - */ - private static void newSingleThreadExecutor() { - ExecutorService exec = Executors.newSingleThreadExecutor(); //创建大小为1的固定线程池 - for(int i = 0; i < 10; i++) { - exec.execute(new MyThread2(String.valueOf(i))); - } - exec.shutdown(); //执行到此处并不会马上关闭线程池 - System.out.println("运行结束!"); - } - - - /** - * 创建一个固定长度的线程池,而且以延迟或者定时的方式来执行,类似Timer; - */ - private static void newScheduledThreadPool() { - ScheduledThreadPoolExecutor exec = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(10); //创建大小为10的线程池 - for(int i = 0; i < 10; i++) { - exec.schedule(new MyThread2(String.valueOf(i)), 2, TimeUnit.SECONDS);//延迟2秒执行 - } - //如果任务都完成了则返回true - while(!exec.isTerminated()){ - //wait for all tasks to finish -// System.out.println("正在运行中..."); - } - System.out.println("运行结束!"); - } - - /** - * 设置固定时间执行 - */ - private static void newScheduledThreadPool2() { - ScheduledThreadPoolExecutor exec = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(10); //创建大小为10的线程池 - long oneDay = 24 * 60 * 60 * 1000; - long initDelay = getTimeMillis("14:08:00") - System.currentTimeMillis(); - initDelay = initDelay > 0 ? initDelay : oneDay + initDelay; - exec.scheduleAtFixedRate(new MyThread2(String.valueOf(1)), initDelay, oneDay, TimeUnit.MILLISECONDS); - System.out.println("运行结束!"); - } - - /** - * 获取指定时间对应的毫秒数 - * @param time "HH:mm:ss" - * @return - */ - private static long getTimeMillis(String time) { - try { - DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss"); - DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd"); - Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time); - return curDate.getTime(); - } catch (ParseException e) { - e.printStackTrace(); - } - return 0; - } - - /** - * ThreadPoolExecutor线程池 - */ - private static void threadPoolExecutor() { - int corePoolSize=5; - int maximumPoolSize=10; - long keepAliveTime=2L; - // 线程核心数,最大线程数,线程缓存时间,时间格式,缓存队列 ,线程工厂,拒绝策略 - ThreadPoolExecutor tpx=new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, - TimeUnit.SECONDS, new ArrayBlockingQueue(3), - Executors.defaultThreadFactory(),new ThreadPoolExecutor.DiscardOldestPolicy()); - - for (int i = 1; i <= 10; i++) { - try { - // 产生一个任务,并将其加入到线程池 - String task = "task@ " + i; -// System.out.println("put " + task); - tpx.execute(new MyThread2(task)); - // 便于观察,等待一段时间 - Thread.sleep(20); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - - -} - -class MyThread2 implements Runnable{ - private String name; - public MyThread2(String name){ - this.name=name; - } - - @Override - public void run() { - System.out.println(name+ "线程开始运行,时间:" +getNowTime()); - pause(1000); - System.out.println(name+ "线程运行结束,时间:" +getNowTime()); - } - - private void pause(long lo) { - try { - Thread.sleep(lo); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - } - - private String getNowTime(){ - return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS").format(new Date()); - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/ThreadTest1.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/ThreadTest1.java deleted file mode 100644 index 2d2d9e23b3..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/ThreadTest1.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.jun.plugin.thread.test; -/** - * @author ZERO - * @Data 2017-5-24 下午2:22:41 - * @Description - */ -public class ThreadTest1 { - - public static void main(String[] args) { - myThread(); - System.out.println("\r\n"); - myRunnable(); - } - - - public static void myThread(){ - for (int i = 0; i < 10; i++) { - System.out.println("myThreadTest:"+Thread.currentThread().getName() + " " + i); - if (i == 3) { - Thread myThread1 = new MyThread(); // 创建一个新的线程 myThread1 此线程进入新建状态 - Thread myThread2 = new MyThread(); // 创建一个新的线程 myThread2 此线程进入新建状态 - myThread1.start(); // 调用start()方法使得线程进入就绪状态 - myThread2.start(); // 调用start()方法使得线程进入就绪状态 - } - } - } - - public static void myRunnable(){ - for (int i = 0; i < 10; i++) { - System.out.println("myRunnableTest:"+Thread.currentThread().getName() + " " + i); - if (i == 3) { - Runnable myRunnable = new MyRunnable(); // 创建一个Runnable实现类的对象 - Thread thread1 = new Thread(myRunnable); // 将myRunnable作为Thread target创建新的线程 - Thread thread2 = new Thread(myRunnable); - thread1.start(); // 调用start()方法使得线程进入就绪状态 - thread2.start(); - } - } - } - - -} - - diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/ThreadTest4.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/ThreadTest4.java deleted file mode 100644 index ab34104d9c..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/ThreadTest4.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.jun.plugin.thread.test; - -/** - * -* Title: ThreadTest4 -* Description: -* 死锁测试 -* Version:1.0.0 -* @author pancm -* @date 2018年3月8日 - */ -public class ThreadTest4 { - static class Friend { - private final String name; - - public Friend(String name) { - this.name = name; - } - - public String getName() { - return this.name; - } - - public synchronized void bow(Friend bower) { - System.out.format("%s: %s" + " 早上好!%n", this.name, bower.getName()); - bower.bowBack(this); - } - - public synchronized void bowBack(Friend bower) { - System.out.format("%s: %s" + " 你也是!%n", this.name, bower.getName()); - } - } - - /** - * 两个线程都在等在对方释放资源,但是都不会释放,这就是死锁。 - * @param args - */ - public static void main(String[] args) { - final Friend zhangsan = new Friend("张三"); - final Friend lisi = new Friend("李四"); - new Thread(new Runnable() { - public void run() { - zhangsan.bow(lisi); - } - }).start(); - new Thread(new Runnable() { - public void run() { - lisi.bow(zhangsan); - } - }).start(); - - /** - * 正常的返回结果应该是: - * 张三: 李四 早上好! - 李四: 张三 你也是! - 李四: 张三 早上好! - 张三: 李四 你也是! - * 因为去掉了synchronized同步锁! - * - * 但实际结果是: - * 张三: 李四 早上好! - 李四: 张三 早上好! - * 并且线程不会结束! - */ - - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/ThreadTest5.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/ThreadTest5.java deleted file mode 100644 index 10fe3a1ff2..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/ThreadTest5.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.jun.plugin.thread.test; - -import java.util.Random; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -/** - * -* Title: ThreadTest5 -* Description: -* ThreadTest4 的改进版 -* 通过Lock来实现 -* Version:1.0.0 -* @author pancm -* @date 2018年3月8日 - */ -public class ThreadTest5 { - static class Friend { - private final String name; - private final Lock lock = new ReentrantLock(); - - public Friend(String name) { - this.name = name; - } - - public String getName() { - return this.name; - } - - public boolean impendingBow(Friend bower) { - Boolean myLock = false; - Boolean yourLock = false; - try { - myLock = lock.tryLock(); - yourLock = bower.lock.tryLock(); - } finally { - if (!(myLock && yourLock)) { - if (myLock) { - lock.unlock(); - } - if (yourLock) { - bower.lock.unlock(); - } - } - } - return myLock && yourLock; - } - - public void bow(Friend bower) { - if (impendingBow(bower)) { - try { - System.out.format("%s: %s has" + " bowed to me!%n", this.name, bower.getName()); - bower.bowBack(this); - } finally { - lock.unlock(); - bower.lock.unlock(); - } - } else { - System.out.format( - "%s: %s started" + " to bow to me, but saw that" + " I was already bowing to" + " him.%n", - this.name, bower.getName()); - } - } - - public void bowBack(Friend bower) { - System.out.format("%s: %s has" + " bowed back to me!%n", this.name, bower.getName()); - } - } - - static class BowLoop implements Runnable { - private Friend bower; - private Friend bowee; - - public BowLoop(Friend bower, Friend bowee) { - this.bower = bower; - this.bowee = bowee; - } - - public void run() { - Random random = new Random(); - for (;;) { - try { - Thread.sleep(random.nextInt(10)); - } catch (InterruptedException e) { - } - bowee.bow(bower); - } - } - } - - public static void main(String[] args) { - final Friend alphonse = new Friend("Alphonse"); - final Friend gaston = new Friend("Gaston"); - new Thread(new BowLoop(alphonse, gaston)).start(); - new Thread(new BowLoop(gaston, alphonse)).start(); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/ThreadTest6.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/ThreadTest6.java deleted file mode 100644 index df85f40e26..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/ThreadTest6.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.jun.plugin.thread.test; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** -* @Title: ThreadTest6 -* @Description: -* @Version:1.0.0 -* @author pancm -* @date 2018年7月23日 -*/ -public class ThreadTest6 { - - - /** - * @param args - */ - public static void main(String[] args) { - Map map=new HashMap(); - List l=new ArrayList<>(); - Thread99 t9=new Thread99(); - Thread t=new Thread(t9); - - } -} - - - - -class Thread99 implements Runnable{ - - @Override - public void run() { - System.out.println("===="); - } -} - - - diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/YieldTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/YieldTest.java deleted file mode 100644 index 0aa9c59524..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/YieldTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.jun.plugin.thread.test; - -/** - * @Title: YaildTest - * @Description: 线程中的 Yaild方法测试 - * @Version:1.0.0 - * @author pancm - * @date 2018年5月22日 - */ -public class YieldTest { - public static void main(String[] args) { - Test1 t1 = new Test1("张三"); - Test1 t2 = new Test1("李四"); - - new Thread(t1).start(); - new Thread(t2).start(); - } -} - -class Test1 implements Runnable { - private String name; - public Test1(String name) { - this.name=name; - } - @Override - public void run() { - System.out.println(name + " 线程运行开始!"); - for (int i = 1; i <= 5; i++) { - System.out.println("子线程"+name+ "运行 : " + i); - // 当为3的时候,让出资源 - if (i == 3) { - Thread.yield(); - } - } - System.out.println(name + " 线程运行结束!"); - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/executorTest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/executorTest.java deleted file mode 100644 index 11dfefdfc5..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/executorTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.jun.plugin.thread.test; - -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; - -/** - * -* Title: executorTest -* Description:线程池 -* Version:1.0.0 -* @author pancm -* @date 2017年11月20日 - */ -public class executorTest { - - public static void main(String[] args) { - //创建一个其线程池具有 10 个线程的ScheduledExecutorService - ScheduledExecutorService executor =Executors.newScheduledThreadPool(10); - System.out.println("开始..."); - //创建一个 Runnable,以供调度稍后执行 - ScheduledFuture future = executor.schedule( - new Runnable() { - @Override - public void run() { - System.out.println("30 seconds later"); - } - }, 30, TimeUnit.SECONDS); //调度任务在从现在开始的 60 秒之后执行 - executor.shutdown(); //执行完毕,释放资源 - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/package-info.java deleted file mode 100644 index 883c3f3750..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: 线程相关的一些类 -* @Version:1.0.0 -* @author pancm -* @date 2018年9月20日 -*/ -package com.jun.plugin.thread.test; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/threadMain.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/threadMain.java deleted file mode 100644 index 029d8da302..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/threadMain.java +++ /dev/null @@ -1,203 +0,0 @@ -package com.jun.plugin.thread.test; - -import java.util.Random; - -/** - * @author ZERO - * @Data 2017-5-24 下午5:15:23 - * @Description - * 线程优先级测试 - */ -class Thread1 extends Thread{ - public Thread1(String name) { - super(name); - } - public void run() { - System.out.println(this.getName() + " 线程运行开始!"); - for (int i = 0; i < 5; i++) { - System.out.println("子线程"+this.getName() + "运行 : " + i); - try { - sleep(new Random().nextInt(10)); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - System.out.println(this.getName() + " 线程运行结束!"); - } -} - -/** - * -* Title: ThreadYield -* Description: -* - */ -class ThreadYield extends Thread{ - public ThreadYield(String name) { - super(name); - } - - @Override - public void run() { - for (int i = 1; i <= 10; i++) { - System.out.println("" + this.getName() + "-----" + i); - // 当i为5时,该线程就会把CPU时间让掉,让其他或者自己的线程执行(也就是谁先抢到谁执行) - if (i ==5) { - this.yield(); - } - } - } -} - - - public class threadMain { - - public static void main(String[] args) { -// noJoinThread(); -// joinThread(); -// yieldThread(); - setPriorityThread(); - - - - } - - public static void noJoinThread(){ - System.out.println(Thread.currentThread().getName()+"主线程运行开始!"); - Thread1 mTh1=new Thread1("A"); - Thread1 mTh2=new Thread1("B"); - mTh1.start(); - mTh2.start(); - System.out.println(Thread.currentThread().getName()+ "主线程运行结束!"); - /**输出: - * main主线程运行开始! - main主线程运行结束! - A 线程运行开始! - B 线程运行开始! - 子线程B运行 : 0 - 子线程A运行 : 0 - 子线程A运行 : 1 - 子线程A运行 : 2 - 子线程A运行 : 3 - 子线程A运行 : 4 - A 线程运行结束! - 子线程B运行 : 1 - 子线程B运行 : 2 - 子线程B运行 : 3 - 子线程B运行 : 4 - B 线程运行结束! - - 主线程比子线程先结束。因为子线程花费的大量时间运算,如果防止这种情况发生,那么就需要使用join()方法。 - B线程先运行,但是A线程先结束。说明多线程程序是乱序执行。 - * */ - } - - //join指等待t线程终止 - public static void joinThread(){ - System.out.println(Thread.currentThread().getName()+"主线程运行开始!"); - Thread1 mTh1=new Thread1("A"); - Thread1 mTh2=new Thread1("B"); - mTh1.start(); - mTh2.start(); - try { - mTh1.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - try { - mTh2.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - System.out.println(Thread.currentThread().getName()+ "主线程运行结束!"); - /**输出: - * main主线程运行开始! - A 线程运行开始! - 子线程A运行 : 0 - B 线程运行开始! - 子线程B运行 : 0 - 子线程A运行 : 1 - 子线程A运行 : 2 - 子线程A运行 : 3 - 子线程A运行 : 4 - A 线程运行结束! - 子线程B运行 : 1 - 子线程B运行 : 2 - 子线程B运行 : 3 - 子线程B运行 : 4 - B 线程运行结束! - main主线程运行结束! - - 添加join方法,会使 主线程一定会等子线程都结束了才结束。 - B线程先运行,但是A线程先结束。说明多线程程序是乱序执行。 - * */ - } - - //yield():暂停当前正在执行的线程对象,并执行其他线程。 - public static void yieldThread(){ - ThreadYield yt1 = new ThreadYield("张三"); - ThreadYield yt2 = new ThreadYield("李四"); - yt1.start(); - yt2.start(); - /**输出: - * 张三-----1 - 李四-----1 - 李四-----2 - 李四-----3 - 李四-----4 - 李四-----5 - 张三-----2 - 张三-----3 - 张三-----4 - 张三-----5 - 李四-----6 - 李四-----7 - 李四-----8 - 李四-----9 - 李四-----10 - 张三-----6 - 张三-----7 - 张三-----8 - 张三-----9 - 张三-----10 - - 先乱序执行,当谁到达5的时候,让出CPU资源,让另一个执行。 - - * */ - } - - //setPriority(): 设置线程的优先级。数值在0-10之间, 数值越大,优先级越高 - public static void setPriorityThread(){ - Thread1 t1=new Thread1("A"); - Thread1 t2=new Thread1("B"); -// t1.setPriority(Thread.MAX_PRIORITY); -// t2.setPriority(Thread.MIN_PRIORITY); - t1.setPriority(1); - t2.setPriority(2); - t1.start(); - t2.start(); - - /** - * A 线程运行开始! - 子线程A运行 : 0 - 子线程A运行 : 1 - B 线程运行开始! - 子线程B运行 : 0 - 子线程A运行 : 2 - 子线程B运行 : 1 - 子线程A运行 : 3 - 子线程B运行 : 2 - 子线程A运行 : 4 - 子线程B运行 : 3 - A 线程运行结束! - 子线程B运行 : 4 - B 线程运行结束! - - A线程优先级比B线程高,因此优先执行A线程。所以A线程一定比B线程先执行完。 - */ - - } - - - } - diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/threadPrinter.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/threadPrinter.java deleted file mode 100644 index 25b1f212cf..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/threadPrinter.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.jun.plugin.thread.test; -/** - * @author ZERO - * @Data 2017-5-27 下午4:27:21 - * @Description - * 测试Object notify和wait方法 - */ -public class threadPrinter implements Runnable { - - private String name; - private Object prev; - private Object self; - - private threadPrinter(String name, Object prev, Object self) { - this.name = name; - this.prev = prev; - this.self = self; - } - - @Override - public void run() { - int count = 10; - while (count > 0) { - synchronized (prev) { - synchronized (self) { - System.out.print(name); - count--; - self.notify(); - } - try { - prev.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - } - } - - /** - * 建立三个线程,A线程打印10次A,B线程打印10次B,C线程打印10次C,要求线程同时运行,交替打印10次ABC。 - * 思路: - * 同时运行这三个线程,打印A、B、C,确保线程的执行顺序是ABC,可以加上Thread.sleep()进行简单的控制 - * 在运行A线程的时候,确保上一个线程不在运行,那么先唤醒本线程,然后 使上一个线程进行等待 - * - * @param args - * @throws Exception - */ - public static void main(String[] args) throws Exception { - Object a = new Object(); - Object b = new Object(); - Object c = new Object(); - threadPrinter pa = new threadPrinter("A", c, a); - threadPrinter pb = new threadPrinter("B", a, b); - threadPrinter pc = new threadPrinter("C", b, c); - - - new Thread(pa).start(); - Thread.sleep(100); //确保按顺序A、B、C执行 - new Thread(pb).start(); - Thread.sleep(100); - new Thread(pc).start(); - Thread.sleep(100); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/threadTest2.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/threadTest2.java deleted file mode 100644 index 27c2c34516..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/thread/test/threadTest2.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.jun.plugin.thread.test; - -import org.junit.Test; - -/** - * @author ZERO - * @Data 2017-5-18 上午9:47:55 - * @Description 线程测试 - */ -public class threadTest2 { - - /** - * @param args - */ - public static void main(String[] args) { - - - } - - @Test - public void createThread1(){ - Thread t1 = new Thread(){ - public void run(){ - System.out.println("创建线程的方式1"); - } - }; - t1.start(); - } - - @Test - public void createThread2(){ - Thread t2 = new Thread(new Runnable(){ - @Override - public void run() { - System.out.println("创建线程的方式2"); - } - - }); - t2.start(); - } -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/utils/AESUtil.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/utils/AESUtil.java deleted file mode 100644 index c309be4067..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/utils/AESUtil.java +++ /dev/null @@ -1,142 +0,0 @@ -package com.jun.plugin.utils; - - -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.crypto.Cipher; -import javax.crypto.KeyGenerator; -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; - -import org.apache.commons.codec.binary.Base64; - - -/** - * -* @Title: AESUtil -* @Description: -* AES 加密工具类 -* @Version:1.0.0 -* @author pancm -* @date 2018年4月3日 - */ -public class AESUtil { - - private static final String KEY_ALGORITHM = "AES"; - /** 秘钥 16位*/ - private static final String PASSWORD = "e!@$%s^&*a)_m+s."; - private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";//默认的加密算法 - - - - /** - * AES 加密操作 - * - * @param content 待加密内容 - * @return 返回Base64转码后的加密数据 - */ - public static String encrypt(String content) { - return encrypt(content,PASSWORD); - } - - - /** - * AES 加密操作 - * - * @param content 待加密内容 - * @param password 加密密码 - * @return 返回Base64转码后的加密数据 - */ - public static String encrypt(String content, String password) { - try { - Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器 - - byte[] byteContent = content.getBytes("utf-8"); - - cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(password));// 初始化为加密模式的密码器 - - byte[] result = cipher.doFinal(byteContent);// 加密 - - return Base64.encodeBase64String(result);//通过Base64转码返回 - } catch (Exception ex) { - Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex); - } - - return null; - } - - /** - * AES 解密操作 - * @param content - * @return - */ - public static String decrypt(String content) { - return decrypt(content,PASSWORD); - } - - /** - * AES 解密操作 - * @param content - * @param password - * @return - */ - public static String decrypt(String content, String password) { - - try { - //实例化 - Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM); - - //使用密钥初始化,设置为解密模式 - cipher.init(Cipher.DECRYPT_MODE, getSecretKey(password)); - - //执行操作 - byte[] result = cipher.doFinal(Base64.decodeBase64(content)); - - return new String(result, "utf-8"); - } catch (Exception ex) { - Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex); - } - - return null; - } - - /** - * 生成加密秘钥 - * - * @return - */ - private static SecretKeySpec getSecretKey(final String password) { - //返回生成指定算法密钥生成器的 KeyGenerator 对象 - KeyGenerator kg = null; - - try { - kg = KeyGenerator.getInstance(KEY_ALGORITHM); - - //AES 要求密钥长度为 128 - kg.init(128, new SecureRandom(password.getBytes())); - - //生成一个密钥 - SecretKey secretKey = kg.generateKey(); - - return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 转换为AES专用密钥 - } catch (NoSuchAlgorithmException ex) { - Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex); - } - - return null; - } - - public static void main(String[] args) { - String s = "1234"; - String s1 = AESUtil.encrypt(s, "1234"); - System.out.println("s1:" + s1); - - System.out.println("s2:"+AESUtil.decrypt(s1, "1234")); - - - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/utils/IPWhiteCheck.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/utils/IPWhiteCheck.java deleted file mode 100644 index 10fccf2fcf..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/utils/IPWhiteCheck.java +++ /dev/null @@ -1,243 +0,0 @@ -package com.jun.plugin.utils; - - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.regex.Pattern; - - -/** -* @Title: IPWhiteCheck -* @Description: -* IP白名单工具类 -* @Version:1.0.0 -* @author pancm -* @date 2018年6月25日 -*/ -public class IPWhiteCheck { - - private static String VERTICAL="\\|"; - - // IP的正则 - private static Pattern pattern = Pattern - .compile("(1\\d{1,2}|2[0-4]\\d|25[0-5]|\\d{1,2})\\." - + "(1\\d{1,2}|2[0-4]\\d|25[0-5]|\\d{1,2})\\." - + "(1\\d{1,2}|2[0-4]\\d|25[0-5]|\\d{1,2})\\." - + "(1\\d{1,2}|2[0-4]\\d|25[0-5]|\\d{1,2})"); - - - private static Set getAvaliIpList(String allowIp) { - - Set ipList = new HashSet(); - for (String allow : allowIp.replaceAll("\\s", "").split(";")) { - if (allow.indexOf("*") > -1) { - String[] ips = allow.split("\\."); - String[] from = new String[] { "0", "0", "0", "0" }; - String[] end = new String[] { "255", "255", "255", "255" }; - List tem = new ArrayList(); - for (int i = 0; i < ips.length; i++) - if (ips[i].indexOf("*") > -1) { - tem = complete(ips[i]); - from[i] = null; - end[i] = null; - } else { - from[i] = ips[i]; - end[i] = ips[i]; - } - - StringBuffer fromIP = new StringBuffer(); - StringBuffer endIP = new StringBuffer(); - for (int i = 0; i < 4; i++) - if (from[i] != null) { - fromIP.append(from[i]).append("."); - endIP.append(end[i]).append("."); - } else { - fromIP.append("[*]."); - endIP.append("[*]."); - } - fromIP.deleteCharAt(fromIP.length() - 1); - endIP.deleteCharAt(endIP.length() - 1); - - for (String s : tem) { - String ip = fromIP.toString().replace("[*]", - s.split(";")[0]) - + "-" - + endIP.toString().replace("[*]", s.split(";")[1]); - if (validate(ip)) { - ipList.add(ip); - } - } - } else { - if (validate(allow)) { - ipList.add(allow); - } - } - } - - return ipList; - } - - /** - * 对单个IP节点进行范围限定 - * - * @param arg - * @return 返回限定后的IP范围,格式为List[10;19, 100;199] - */ - private static List complete(String arg) { - List com = new ArrayList(); - if (arg.length() == 1) { - com.add("0;255"); - } else if (arg.length() == 2) { - String s1 = complete(arg, 1); - if (s1 != null) - com.add(s1); - String s2 = complete(arg, 2); - if (s2 != null) - com.add(s2); - } else { - String s1 = complete(arg, 1); - if (s1 != null) - com.add(s1); - } - return com; - } - - private static String complete(String arg, int length) { - String from = ""; - String end = ""; - if (length == 1) { - from = arg.replace("*", "0"); - end = arg.replace("*", "9"); - } else { - from = arg.replace("*", "00"); - end = arg.replace("*", "99"); - } - if (Integer.valueOf(from) > 255) - return null; - if (Integer.valueOf(end) > 255) - end = "255"; - return from + ";" + end; - } - - /** - * 在添加至白名单时进行格式校验 - * @param ip - * @return - */ - private static boolean validate(String ip) { - for (String s : ip.split("-")) - if (!pattern.matcher(s).matches()) { - return false; - } - return true; - } - - /** - * - * checkLoginIP:(根据IP,及可用Ip列表来判断ip是否包含在白名单之中). - * @param ip - * @param ipList - * @return - */ - private static boolean checkLoginIP(String ip, Set ipList) { - if (ipList.isEmpty() || ipList.contains(ip)) - return true; - else { - for (String allow : ipList) { - if (allow.indexOf("-") > -1) { - String[] from = allow.split("-")[0].split("\\."); - String[] end = allow.split("-")[1].split("\\."); - String[] tag = ip.split("\\."); - - // 对IP从左到右进行逐段匹配 - boolean check = true; - for (int i = 0; i < 4; i++) { - int s = Integer.valueOf(from[i]); - int t = Integer.valueOf(tag[i]); - int e = Integer.valueOf(end[i]); - if (!(s <= t && t <= e)) { - check = false; - break; - } - } - if (check) { - return true; - } - } - } - } - return false; - } - - /** - * 根据IP地址,及IP白名单设置规则判断IP是否包含在白名单 - * 例如:ip =192.169.0.10 - * ipWhiteConfig=192.169.0.1-192.169.0.11; - * 则可以通过 - * ip =192.169.1.10 - * ipWhiteConfig=192.169.1.* - * 也可以通过 - * @param ip - * @param ipWhiteConfig - * @return - */ - public static boolean checkLoginIP(String ip,String ipWhiteConfig){ - if(ip==null||ipWhiteConfig==null){ - return false; - } - Set ipList = getAvaliIpList(ipWhiteConfig); - return checkLoginIP(ip, ipList); - } - - /** - * 支持多个 - * 根据IP地址,及IP白名单设置规则判断IP是否包含在白名单 - * 例如:ip =192.169.0.10 - * ipWhiteConfig=192.169.1.*|192.169.0.1-192.169.0.11; - * 则可以通过 - * ip =192.169.0.12 - * ipWhiteConfig=192.169.1.*|192.169.0.1-192.169.0.11 - * 不可以通过 - * @param ip - * @param ipWhiteConfig - * @return - */ - public static boolean checkLoginIPS(String ip,String ipWhiteConfig){ - if(ip==null||ipWhiteConfig==null){ - return false; - } - String []ips=ipWhiteConfig.split(VERTICAL); - boolean falg=false; - for(String i:ips){ - falg=checkLoginIP(ip, i); - if(falg){ - break; - } - } - return falg; - } - - - public static void main(String[] args) { - String ip="192.169.0.10"; - String ipWhiteConfig="192.169.0.1-192.169.0.11"; - String ip2="192.169.0.10"; - String ipWhiteConfig2="192.169.1.*"; - String ipWhiteConfig3="192.169.1.*|192.169.0.1-192.169.0.11"; - String []ips=ipWhiteConfig3.split("\\|"); - boolean falg=false; - for(String i:ips){ - falg=IPWhiteCheck.checkLoginIP(ip2, i); - if(falg){ - break; - } - } - System.out.println("是否通过1:"+falg); - - System.out.println("是否通过2:"+IPWhiteCheck.checkLoginIP(ip, ipWhiteConfig)); - System.out.println("是否通过3:"+IPWhiteCheck.checkLoginIP(ip2, ipWhiteConfig2)); -} - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/utils/KafkaProducerUtil.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/utils/KafkaProducerUtil.java deleted file mode 100644 index 3921835feb..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/utils/KafkaProducerUtil.java +++ /dev/null @@ -1,135 +0,0 @@ -package com.jun.plugin.utils; - -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import org.apache.kafka.clients.producer.KafkaProducer; -import org.apache.kafka.clients.producer.ProducerRecord; -import org.apache.kafka.common.serialization.StringSerializer; - - -/** - * -* @Title: KafkaProducerUtil -* @Description: -* kafka消息生产者 -* @Version:1.0.0 -* @author pancm -* @date 2018年4月2日 - */ -public final class KafkaProducerUtil { - - - /** - * 向kafka发送单条消息 - * @param msg 发送的消息 - * @param url 发送的地址 - * @param topicName 消息名称 - * @return - * @throws Exception - */ - public static boolean sendMessage(String msg,String url,String topicName) { - KafkaProducer producer=null; - boolean flag=false; - try{ - Properties props=init(url); - producer= new KafkaProducer(props); - producer.send(new ProducerRecord(topicName,msg)); - flag=true; - }catch(Exception e){ - e.printStackTrace(); - }finally{ - if(producer!=null){ - producer.close(); - } - } - return flag; - } - - - /** - * 向kafka发送批量消息 - * @param listMsg 发送的消息 - * @param url 发送的地址 - * @param topicName 消息名称 - * @return - * @throws Exception - */ - public static boolean sendMessage(List listMsg,String url,String topicName) { - KafkaProducer producer=null; - boolean flag=false; - try{ - Properties props=init(url); - producer= new KafkaProducer(props); - for(String msg:listMsg){ - producer.send(new ProducerRecord(topicName,msg)); - } - flag=true; - }catch(Exception e){ - e.printStackTrace(); - }finally{ - if(producer!=null){ - producer.close(); - } - } - return flag; - } - - - /** - * 向kafka发送批量消息 - * @param listMsg 发送的消息 - * @param url 发送的地址 - * @param topicName 消息名称 - * @param num 每次发送的条数 - * @return - * @throws Exception - */ - public static boolean sendMessage(List listMsg,String url,String topicName,int num) throws Exception{ - KafkaProducer producer=null; - boolean falg=false; - try{ - Properties props=init(url); - producer= new KafkaProducer(props); - List listMsg2 =new ArrayList(); - for(int i = 1,j = listMsg.size();i<=j;i++){ - listMsg2.add(listMsg.get(i-1)); - if(i%num==0 || i == j){ - producer.send(new ProducerRecord(topicName,listMsg2.toString())); - listMsg2.clear(); - } - } - falg=true; - }catch(Exception e){ - e.printStackTrace(); - }finally{ - if(producer!=null){ - producer.close(); - } - } - return falg; - } - - /** - * 初始化配置 - * @param url kafka地址,多个地址则用‘,’隔开 - * @return - */ - private static Properties init(String url){ - Properties props = new Properties(); - props.put("bootstrap.servers", url); - //acks=0:如果设置为0,生产者不会等待kafka的响应。 - //acks=1:这个配置意味着kafka会把这条消息写到本地日志文件中,但是不会等待集群中其他机器的成功响应。 - //acks=all:这个配置意味着leader会等待所有的follower同步完成。这个确保消息不会丢失,除非kafka集群中所有机器挂掉。这是最强的可用性保证。 - props.put("acks", "all"); - //配置为大于0的值的话,客户端会在消息发送失败时重新发送。 - props.put("retries", 0); - //当多条消息需要发送到同一个分区时,生产者会尝试合并网络请求。这会提高client和生产者的效率 - props.put("batch.size", 16384); - props.put("key.serializer", StringSerializer.class.getName()); - props.put("value.serializer", StringSerializer.class.getName()); - return props; - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/utils/MyHttpRequest.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/utils/MyHttpRequest.java deleted file mode 100644 index e8ce5a1e75..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/utils/MyHttpRequest.java +++ /dev/null @@ -1,210 +0,0 @@ -package com.jun.plugin.utils; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.net.URL; -import java.net.URLConnection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; - -/** - * @author xuwujing - * @Data 2017-5-12 上午11:57:52 - * @Description http请求工具类 - */ -public class MyHttpRequest { - - /** - * 向指定URL发送GET方法的请求 - * - * @param url - * 发送请求的URL - * @param param - * 请求Map参数,请求参数应该是 {"name1":"value1","name2":"value2"}的形式。 - * @param charset - * 发送和接收的格式 - * @return URL 所代表远程资源的响应结果 - */ - @SuppressWarnings("rawtypes") - public static String sendGet(String url, Map map,String charset){ - StringBuffer sb=new StringBuffer(); - //构建请求参数 - if(map!=null&&map.size()>0){ - Iterator it=map.entrySet().iterator(); //定义迭代器 - while(it.hasNext()){ - Map.Entry er= (Entry) it.next(); - sb.append(er.getKey()); - sb.append("="); - sb.append(er.getValue()); - sb.append("&"); - } - } - return sendGet(url,sb.toString(), charset); - } - - - /** - * 向指定URL发送POST方法的请求 - * - * @param url - * 发送请求的URL - * @param param - * 请求Map参数,请求参数应该是 {"name1":"value1","name2":"value2"}的形式。 - * @param charset - * 发送和接收的格式 - * @return URL 所代表远程资源的响应结果 - */ - public static String sendPost(String url, Map map,String charset){ - StringBuffer sb=new StringBuffer(); - //构建请求参数 - if(map!=null&&map.size()>0){ - for (Entry e : map.entrySet()) { - sb.append(e.getKey()); - sb.append("="); - sb.append(e.getValue()); - sb.append("&"); - } - } - return sendPost(url,sb.toString(),charset); - } - - - /** - * 向指定URL发送GET方法的请求 - * - * @param url - * 发送请求的URL - * @param param - * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 - * @param charset - * 发送和接收的格式 - * @return URL 所代表远程资源的响应结果 - */ - public static String sendGet(String url, String param,String charset) { - String result = ""; - String line; - StringBuffer sb=new StringBuffer(); - BufferedReader in = null; - try { - String urlNameString = url + "?" + param; - URL realUrl = new URL(urlNameString); - // 打开和URL之间的连接 - URLConnection conn = realUrl.openConnection(); - // 设置通用的请求属性 设置请求格式 - conn.setRequestProperty("contentType", charset); - conn.setRequestProperty("content-type", "application/x-www-form-urlencoded"); - //设置超时时间 - conn.setConnectTimeout(60); - conn.setReadTimeout(60); - // 建立实际的连接 - conn.connect(); - // 定义 BufferedReader输入流来读取URL的响应,设置接收格式 - in = new BufferedReader(new InputStreamReader( - conn.getInputStream(),charset)); - while ((line = in.readLine()) != null) { - sb.append(line); - } - result=sb.toString(); - } catch (Exception e) { - System.out.println("发送GET请求出现异常!" + e); - e.printStackTrace(); - } - // 使用finally块来关闭输入流 - finally { - try { - if (in != null) { - in.close(); - } - } catch (Exception e2) { - e2.printStackTrace(); - } - } - return result; - } - - /** - * 向指定 URL 发送POST方法的请求 - * - * @param url - * 发送请求的 URL - * @param param - * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 - * @param charset - * 发送和接收的格式 - * @return 所代表远程资源的响应结果 - */ - public static String sendPost(String url, String param,String charset) { - PrintWriter out = null; - BufferedReader in = null; - String result = ""; - String line; - StringBuffer sb=new StringBuffer(); - try { - URL realUrl = new URL(url); - // 打开和URL之间的连接 - URLConnection conn = realUrl.openConnection(); - // 设置通用的请求属性 设置请求格式 - conn.setRequestProperty("contentType", charset); - conn.setRequestProperty("content-type", "application/x-www-form-urlencoded"); - //设置超时时间 - conn.setReadTimeout(60); - conn.setConnectTimeout(60); - // 发送POST请求必须设置如下两行 - conn.setDoOutput(true); - conn.setDoInput(true); - // 建立实际的连接 - conn.connect(); - // 获取URLConnection对象对应的输出流 - out = new PrintWriter(conn.getOutputStream()); - // 发送请求参数 - out.print(param); - // flush输出流的缓冲 - out.flush(); - // 定义BufferedReader输入流来读取URL的响应 设置接收格式 - in = new BufferedReader( - new InputStreamReader(conn.getInputStream(),charset)); - while ((line = in.readLine()) != null) { - sb.append(line); - } - result=sb.toString(); - } catch (Exception e) { - System.out.println("发送 POST请求出现异常!"+e); - e.printStackTrace(); - } - //使用finally块来关闭输出流、输入流 - finally{ - try{ - if(out!=null){ - out.close(); - } - if(in!=null){ - in.close(); - } - } - catch(IOException ex){ - ex.printStackTrace(); - } - } - return result; - } - - public static void main(String[] args) { - String getUrl="http://int.dpool.sina.com.cn/iplookup/iplookup.php"; - String postUrl="http://gc.ditu.aliyun.com/geocoding"; - String param="format=json&ip=218.4.255.255"; - String param1="a=苏州市"; - Map map=new HashMap(); - map.put("format", "json"); - map.put("ip", "218.4.255.255"); - Map map1=new HashMap(); - map1.put("a", "苏州市"); - System.out.println("Get请求1:"+sendGet(getUrl, param,"utf-8")); - System.out.println("Get请求2:"+sendGet(getUrl, map,"utf-8")); - System.out.println("Post请求1:"+sendPost(postUrl, param1,"utf-8")); - System.out.println("Post请求2:"+sendPost(postUrl, map1,"utf-8")); - } - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/utils/MyTools.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/utils/MyTools.java deleted file mode 100644 index 90d291be81..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/utils/MyTools.java +++ /dev/null @@ -1,919 +0,0 @@ -package com.jun.plugin.utils; - -import java.math.BigInteger; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.Period; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Random; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.commons.codec.binary.Base64; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; - -/** - * - * @Title: MyTools - * @Description:常用工具类 - * @Version:1.0.1 - * @author pancm - * @date 2017年9月26日 - */ -public final class MyTools { - /** 时间格式包含毫秒 */ - private static final String sdfm = "yyyy-MM-dd HH:mm:ss SSS"; - /** 普通的时间格式 */ - private static final String sdf = "yyyy-MM-dd HH:mm:ss"; - /** 时间戳格式 */ - private static final String sd = "yyyyMMddHHmmss"; - /** 检查是否为整型 */ - private static Pattern p = Pattern.compile("^\\d+$"); - - /** - * 判断String类型的数据是否为空 null,""," " 为true "A"为false - * - * @return boolean - */ - public static boolean isEmpty(String str) { - return (null == str || str.trim().length() == 0); - } - - /** - * 判断String类型的数据是否为空 null,"", " " 为false "A", 为true - * - * @return boolean - */ - public static boolean isNotEmpty(String str) { - return !isEmpty(str); - } - - /** - * 判断list类型的数据是否为空 null,[] 为 true - * - * @return boolean - */ - public static boolean isEmpty(List list) { - return (null == list || list.size() == 0); - } - - /** - * 判断list类型的数据是否为空 null,[] 为 false - * - * @return boolean - */ - public static boolean isNotEmpty(List list) { - return !isEmpty(list); - } - - /** - * 判断Map类型的数据是否为空 null,[] 为true - * - * @return boolean - */ - public static boolean isEmpty(Map map) { - return (null == map || map.size() == 0); - } - - /** - * 判断map类型的数据是否为空 null,[] 为 false - * - * @return boolean - */ - public static boolean isNotEmpty(Map map) { - return !isEmpty(map); - } - - /** - * 判断JSONObject类型的数据是否为空 null,[] 为true - * - * @return boolean - */ - public static boolean isEmpty(JSONObject json) { - return (null == json || json.size() == 0); - } - - /** - * 判断json类型的数据是否为空 null,[] 为 false - * - * @return boolean - */ - public static boolean isNotEmpty(JSONObject json) { - return !isEmpty(json); - } - - /** - * 字符串反转 如:入参为abc,出参则为cba - * - * @param str - * @return - */ - public static String reverse(String str) { - if (isEmpty(str)) { - return str; - } - return reverse(str.substring(1)) + str.charAt(0); - } - - /** - * 获取当前long类型的的时间 - * - * @return long - */ - public static long getNowLongTime() { - return System.currentTimeMillis(); - } - - /** - * long类型的时间转换成 yyyyMMddHHmmss String类型的时间 - * - * @param lo - * long类型的时间 - * @return - */ - public static String longTime2StringTime(long lo) { - return longTime2StringTime(lo, sd); - } - - /** - * long类型的时间转换成自定义时间格式 - * - * @param lo - * long类型的时间 - * @param format - * 时间格式 - * @return String - */ - public static String longTime2StringTime(long lo, String format) { - return new SimpleDateFormat(format).format(lo); - } - - /** - * String类型的时间转换成 long - * - * @param lo - * @return String - * @throws ParseException - */ - public static long stringTime2LongTime(String time, String format) throws ParseException { - if (isEmpty(format)) { - format = sdf; - } - if (isEmpty(time)) { - time = getNowTime(format); - } - SimpleDateFormat sd = new SimpleDateFormat(format); - Date date = sd.parse(time); - return date.getTime(); - } - - /** - * 格式化时间 - * - * @param format1 - * 之前的 时间格式 - * @param format2 - * 之后的 时间格式 - * @param time - * 时间 - * @return String - * @throws ParseException - */ - public static String formatTime(String format1, String format2, String time) throws ParseException { - SimpleDateFormat d1 = new SimpleDateFormat(format1); - SimpleDateFormat d2 = new SimpleDateFormat(format2); - time = d2.format(d1.parse(time)); - return time; - } - - /** - * 时间补全 例如将2018-04-04补全为2018-04-04 00:00:00.000 - * - * @param time - * 补全的时间 - * @return - */ - public static String complementTime(String time) { - return complementTime(time, sdfm, 1); - - } - - /** - * 时间补全 例如将2018-04-04补全为2018-04-04 00:00:00.000 - * - * @param time - * 补全的时间 - * @param format - * 补全的格式 - * @param type - * 类型 1:起始;2:终止 - * @return - */ - public static String complementTime(String time, String format, int type) { - if (isEmpty(time) || isEmpty(format)) { - return null; - } - int tlen = time.length(); - int flen = format.length(); - int clen = flen - tlen; - if (clen <= 0) { - return time; - } - StringBuffer sb = new StringBuffer(time); - if (clen == 4) { - if (type == 1) { - sb.append(".000"); - } else { - sb.append(".999"); - } - } else if (clen == 9) { - if (type == 1) { - sb.append(" 00:00:00"); - } else { - sb.append(" 23:59:59"); - } - } else if (clen == 13) { - if (type == 1) { - sb.append(" 00:00:00.000"); - } else { - sb.append(" 23:59:59.999"); - } - } - return sb.toString(); - - } - - /** - * 获取当前String类型的的时间 使用默认格式 yyyy-MM-dd HH:mm:ss - * - * @return String - */ - public static String getNowTime() { - return getNowTime(sdf); - } - - /** - * 获取当前String类型的的时间(自定义格式) - * - * @param format - * 时间格式 - * @return String - */ - public static String getNowTime(String format) { - return new SimpleDateFormat(format).format(new Date()); - } - - /** - * 获取当前Timestamp类型的的时间 - * - * @return Timestamp - */ - public static Timestamp getTNowTime() { - return new Timestamp(getNowLongTime()); - } - - /** - * 获取的String类型的当前时间并更改时间 - * - * @param number - * 要更改的的数值 - * @param format - * 更改时间的格式 如yyyy-MM-dd HH:mm:ss - * @param type - * 更改时间的类型 时:h; 分:m ;秒:s - * @return String - */ - public static String changeTime(int number, String format, String type) { - return changeTime(number, format, type, ""); - } - - /** - * 获取的String类型时间并更改时间 - * - * @param number - * 要更改的的数值 - * @param format - * 更改时间的格式 - * @param type - * 更改时间的类型 。时:h; 分:m ;秒:s - * @param time - * 更改的时间 没有则取当前时间 - * @return String - */ - public static String changeTime(int number, String format, String type, String time) { - if (isEmpty(time)) { // 如果没有设置时间则取当前时间 - time = getNowTime(format); - } - SimpleDateFormat format1 = new SimpleDateFormat(format); - Date d = null; - Calendar ca = null; - String backTime = null; - try { - d = format1.parse(time); - ca = Calendar.getInstance(); // 定义一个Calendar 对象 - ca.setTime(d);// 设置时间 - if ("h".equals(type)) { - ca.add(Calendar.HOUR, number);// 改变时 - } else if ("m".equals(type)) { - ca.add(Calendar.MINUTE, number);// 改变分 - } else if ("s".equals(type)) { - ca.add(Calendar.SECOND, number);// 改变秒 - } - backTime = format1.format(ca.getTime()); // 转化为String 的格式 - } catch (Exception e) { - e.printStackTrace(); - } - return backTime; - } - - /** - * 两个日期带时间比较 第二个时间大于第一个则为true,否则为false - * - * @param String - * @return boolean - * @throws ParseException - */ - public static boolean isCompareDay(String time1, String time2, String format) { - if (isEmpty(format)) {// 如果没有设置格式使用默认格式 - format = sdf; - } - SimpleDateFormat s1 = new SimpleDateFormat(format); - Date t1 = null; - Date t2 = null; - try { - t1 = s1.parse(time1); - t2 = s1.parse(time2); - return t2.after(t1);// 当 t2 大于 t1 时,为 true,否则为 false - } catch (ParseException e) { - e.printStackTrace(); - return false; - } - } - - /** - * 获取几天之前的时间 - * - * @since 1.8 - * @param day - * @return - */ - public static String getMinusDays(int day) { - return getMinusDays(day, sdf); - } - - /** - * 获取几天之前的时间 - * - * @since 1.8 - * @param day - * @param format - * @return - */ - public static String getMinusDays(int day, String format) { - return LocalDateTime.now().minusDays(day).format(DateTimeFormatter.ofPattern(format)); - } - - /** - * 获取几天之后的时间 - * - * @since 1.8 - * @param day - * @return - */ - public static String getPlusDays(int day) { - return getPlusDays(day, sdf); - } - - /** - * 获取几天之后的时间 - * - * @since 1.8 - * @param day - * @param format - * @return - */ - public static String getPlusDays(int day, String format) { - return LocalDateTime.now().plusDays(day).format(DateTimeFormatter.ofPattern(format)); - } - - /** - * 获取几天之后的时间 - * - * @since 1.8 - * @param day - * @return - */ - public static String getPlusMonths(int month) { - return getPlusMonths(month, sdf); - } - - /** - * 获取几月之后的时间 - * - * @since 1.8 - * @param day - * @param format - * @return - */ - public static String getPlusMonths(int month, String format) { - return LocalDateTime.now().plusMonths(month).format(DateTimeFormatter.ofPattern(format)); - } - - /** - * 增加月份 - * - * @param time - * 格式为yyyy-MM-dd - * @param month - * 增加月份 - * @return - */ - public static String addPlusMonths(String time, int month) { - return LocalDate.parse(time).plusMonths(month).toString(); - } - - /** - * 时间相比得月份 如果是201711和201801相比,返回的结果是2 前面的时间要小于后面的时间 - * - * @param month - * 格式为yyyyMM - * @param toMonth - * 格式为yyyyMM - * @since jdk 1.8 - * @return - */ - public static int diffMonth(String month, String toMonth) { - int year1 = Integer.parseInt(month.substring(0, 4)); - int month1 = Integer.parseInt(month.substring(4, 6)); - int year2 = Integer.parseInt(month.substring(0, 4)); - int month2 = Integer.parseInt(month.substring(4, 6)); - LocalDate ld1 = LocalDate.of(year1, month1, 01); - LocalDate ld2 = LocalDate.of(year2, month2, 01); - return Period.between(ld1, ld2).getMonths(); - } - - /** - * 判断是否为整型 - * - * @param String - * @return boolean - */ - public static boolean isInteger(String str) { - Matcher m = p.matcher(str); - return m.find(); - } - - /** - * 自定义位数产生随机数字 - * - * @param int - * @return String - */ - public static String random(int count) { - char start = '0'; - char end = '9'; - Random rnd = new Random(); - char[] result = new char[count]; - int len = end - start + 1; - while (count-- > 0) { - result[count] = (char) (rnd.nextInt(len) + start); - } - return new String(result); - } - - /** - * 获取自定义长度的随机数(含字母) - * - * @param len - * 长度 - * @return String - */ - public static String random2(int len) { - int random = Integer.parseInt(random(5)); - Random rd = new Random(random); - final int maxNum = 62; - StringBuffer sb = new StringBuffer(); - int rdGet;// 取得随机数 - char[] str = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', - 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', - 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', - '9' }; - int count = 0; - while (count < len) { - rdGet = Math.abs(rd.nextInt(maxNum));// 生成的数最大为62-1 - if (rdGet >= 0 && rdGet < str.length) { - sb.append(str[rdGet]); - count++; - } - } - return sb.toString(); - } - - /** - * 获取本机ip - * - * @return String - * @throws UnknownHostException - */ - public static String getLocalHostIp() throws UnknownHostException { - return InetAddress.getLocalHost().getHostAddress(); - } - - /** - * Object 转换为 String - * - * @param list - * @return String - */ - public static String toString(Object obj) { - return JSON.toJSONString(obj); - } - - /** - * JSON 转换为 JavaBean - * - * @param json - * @param t - * @return - */ - public static T toBean(JSONObject json, Class t) { - return JSON.toJavaObject(json, t); - } - - /** - * JSON 字符串转换为 JavaBean - * - * @param str - * @param t - * @return - */ - public static T toBean(String str, Class t) { - return JSON.parseObject(str, t); - } - - /** - * JSON 字符串 转换成JSON格式 - * - * @param obj - * @return JSONObject - */ - public static JSONObject toJson(String str) { - if (isEmpty(str)) { - return new JSONObject(); - } - return JSON.parseObject(str); - - } - - /** - * JavaBean 转化为JSON - * - * @param t - * @return - */ - public static JSONObject toJson(Object t) { - if (null == t || "".equals(t)) { - return new JSONObject(); - } - return (JSONObject) JSON.toJSON(t); - } - - /** - * JSON 字符串转换为 HashMap - * - * @param json - * - String - * @return Map - */ - @SuppressWarnings("rawtypes") - public static Map toMap(String json) { - if (isEmpty(json)) { - return new HashMap(); - } - return JSON.parseObject(json, HashMap.class); - } - - /** - * 将map转化为string - * - * @param m - * @return - */ - @SuppressWarnings("rawtypes") - public static String toString(Map m) { - return JSONObject.toJSONString(m); - } - - /** - * String转换为数组 - * - * @param text - * @return - */ - public static Object[] toArray(String text) { - return toArray(text, null); - } - - /** - * String转换为数组 - * - * @param text - * @return - */ - public static Object[] toArray(String text, Class clazz) { - return JSON.parseArray(text, clazz).toArray(); - } - - /** - * name1=value1&name2=value2格式的数据转换成json数据格式 - * - * @param str - * @return - */ - public static JSONObject str2Json(String str) { - if (isEmpty(str)) { - return new JSONObject(); - } - JSONObject json = new JSONObject(); - String[] str1 = str.split("&"); - String str3 = "", str4 = ""; - if (null == str1 || str1.length == 0) { - return new JSONObject(); - } - for (String str2 : str1) { - str3 = str2.substring(0, str2.lastIndexOf("=")); - str4 = str2.substring(str2.lastIndexOf("=") + 1, str2.length()); - json.put(str3, str4); - } - return json; - } - - /** - * json数据格式 转换成name1=value1&name2=value2格式 - * - * @param str - * @return - */ - @SuppressWarnings("rawtypes") - public static String json2Str(JSONObject json) { - if (isEmpty(json)) { - return null; - } - StringBuffer sb = new StringBuffer(); - Iterator it = json.entrySet().iterator(); // 定义迭代器 - while (it.hasNext()) { - Map.Entry er = (Entry) it.next(); - sb.append(er.getKey()); - sb.append("="); - sb.append(er.getValue()); - sb.append("&"); - } - sb.delete(sb.length() - 1, sb.length()); // 去掉最后的& - return sb.toString(); - } - - /** - * 将JDBC查询的数据转换成List类型 - * - * @param ResultSet - * @return List - * @throws SQLException - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - public static List convertList(ResultSet rs) throws SQLException { - if (null == rs) { - return new ArrayList<>(); - } - List list = new ArrayList(); - ResultSetMetaData md = rs.getMetaData(); - int columnCount = md.getColumnCount(); - while (rs.next()) { - JSONObject rowData = new JSONObject(); - for (int i = 1; i <= columnCount; i++) { - rowData.put(md.getColumnName(i), rs.getObject(i)); - } - list.add(rowData); - } - return list; - } - - /** - * MD5加密 - * - * @param message - * @return - */ - public static String md5Encode(String message) { - byte[] secretBytes = null; - try { - secretBytes = MessageDigest.getInstance("md5").digest(message.getBytes()); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException("没有md5这个算法!"); - } - String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字 - // 如果生成数字未满32位,需要前面补0 - int length = 32 - md5code.length(); - for (int i = 0; i < length; i++) { - md5code = "0" + md5code; - } - return md5code; - } - - /** - * base64 加密 - * - * @param str - * @return - */ - public static String base64En(String str) { - Base64 base64 = new Base64(); - byte[] encode = base64.encode(str.getBytes()); - return new String(encode); - } - - /** - * base64解密 - * - * @param encodeStr - * @return - */ - @SuppressWarnings("static-access") - public static String base64De(String encodeStr) { - Base64 base64 = new Base64(); - byte[] decodeStr = base64.decodeBase64(encodeStr); - return new String(decodeStr); - } - - /** - * 十进制转二进制 - * - * @param n - * @return - */ - public static String decToBinary(int n) { - String str = ""; - while (n != 0) { - str = n % 2 + str; - n = n / 2; - } - return str; - } - - /** - * 二进制转十进制 - * - * @param n - * @return - */ - public static int binaryToDec(char[] cs) { - return binaryToDec(cs); - } - - /** - * 二进制转十进制 - * - * @param n - * @return - */ - public static int binaryToDec(String cs) { - return new BigInteger(new String(cs), 2).intValue(); - } - - /** - * 本方法的测试示例 - * - * @param args - */ - @SuppressWarnings({ "rawtypes" }) - public static void main(String[] args) { - /* - * String 和List 空数据判断 - */ - String str1 = ""; - String str2 = " "; - String str3 = null; - String str4 = "a"; - List list = null; - List list2 = new ArrayList(); - List list3 = new ArrayList(); - list3.add("a"); - - System.out.println("str1 :" + isEmpty(str1)); // str1 :true - System.out.println("str2 :" + isEmpty(str2)); // str2 :true - System.out.println("str3 :" + isEmpty(str3)); // str3 :true - System.out.println("str4 :" + isEmpty(str4)); // str4 :false - System.out.println("list :" + isEmpty(list)); // list :true - System.out.println("list2 :" + isEmpty(list2)); // list2 :true - System.out.println("list3 :" + isEmpty(list3)); // list3 :false - - /* - * 时间 - */ - long start = getNowLongTime(); - System.out.println("getNowTime():" + getNowTime()); // getNowTime():2017-09-26 - // 17:46:44 - System.out.println("getNowLongTime():" + getNowLongTime()); // getNowLongTime():1506419204920 - System.out.println("getNowTime(sdfm):" + getNowTime(sdfm)); // getNowTime(sdfm):2017-09-26 - // 17:46:44 - // 920 - System.out.println("当时时间向前推移30秒:" + changeTime(-30, sdf, "s")); // 2017-09-26 - // 17:46:14 - System.out.println("时间比较:" + isCompareDay(getNowTime(sdfm), changeTime(-30, sdf, "s"), "")); // 时间比较:false - System.out.println("getTNowTime():" + getTNowTime()); // getTNowTime():2017-09-26 - // 17:46:44.921 - System.out.println("LongTime2StringTime():" + longTime2StringTime(start, sd)); // LongTime2StringTime():20170926174644 - - /* - * 整型判断 - */ - String st = "258369"; - String st2 = "258369A!@"; - String st3 = "258 369 "; - System.out.println("st:" + isInteger(st)); // st:true - System.out.println("st2:" + isInteger(st2)); // st2:false - System.out.println("st3:" + isInteger(st3)); // st3:false - - /* - * 字符串反转 - */ - String re = "abcdefg"; - System.out.println("字符串反转:" + reverse(re)); // 字符串反转:gfedcba - - /* - * 本机IP - */ - try { - System.out.println("本机IP:" + getLocalHostIp()); // 本机IP:192.168.1.111 - } catch (UnknownHostException e) { - e.printStackTrace(); - } - - /* - * 随机数 - */ - - System.out.println("6位随机数:" + random(6)); // 6位随机数:222488 - System.out.println("10位随机数:" + random2(10)); // 10位随机数:ZwW0pmofjW - - /* - * JSON数据转换 - */ - - String value = "name1=value1&name2=value2&name3=value3"; - JSONObject json = new JSONObject(); - json.put("name1", "value1"); - json.put("name2", "value2"); - json.put("name3", "value3"); - System.out.println("value:" + value); // value:name1=value1&name2=value2&name3=value3 - System.out.println("str2Json:" + str2Json(value)); // str2Json:{"name1":"value1","name2":"value2","name3":"value3"} - System.out.println("json:" + json.toJSONString()); // json:{"name1":"value1","name2":"value2","name3":"value3"} - System.out.println("json2Str:" + json2Str(json)); // json2Str:name3=value3&name1=value1&name2=value2 - - String jsonString = json.toJSONString(); - System.out.println("jsonString:" + jsonString); // {"name1":"value1","name2":"value2","name3":"value3"} - System.out.println("toJson(jsonString):" + toJson(jsonString)); // toJson(jsonString):{"name1":"value1","name2":"value2","name3":"value3"} - - System.out.println("long TO String" + longTime2StringTime(32472115200L)); - System.out.println("long TO String" + longTime2StringTime(1513330097L)); - - String time1 = "2018-04-04"; - String time2 = "2018-04-04 14:48:00"; - String time3 = "2018-04-04 14:48:00.000"; - System.out.println("时间补全:" + complementTime(time1, sdfm, 1)); - System.out.println("时间补全:" + complementTime(time2, sdfm, 2)); - System.out.println("时间补全:" + complementTime(time3, sdfm, 1)); - String time4 = addPlusMonths(time1, 2); - System.out.println("增加之前的数据:" + time1 + "增加月份之后的数据:" + time4); - System.out.println("相差月份:" + diffMonth("201711", "201801")); - - - - int l = 2; - String string = "10101"; - System.out.println(l + " 十进制转二进制: " + decToBinary(l)); - - System.out.println(string + " 二进制转十进制: " + binaryToDec(string)); - - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/utils/QrCodeCreateUtil.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/utils/QrCodeCreateUtil.java deleted file mode 100644 index 332e73a8df..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/utils/QrCodeCreateUtil.java +++ /dev/null @@ -1,77 +0,0 @@ -// This file is commented out — functionality moved to jun_qrcode module. -// See jun_qrcode for QR code generation and reading utilities. -/* -package com.jun.plugin.utils; - -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Hashtable; - -import javax.imageio.ImageIO; - -import com.google.zxing.BarcodeFormat; -import com.google.zxing.BinaryBitmap; -import com.google.zxing.EncodeHintType; -import com.google.zxing.LuminanceSource; -import com.google.zxing.ReaderException; -import com.google.zxing.Result; -import com.google.zxing.WriterException; -import com.google.zxing.client.j2se.BufferedImageLuminanceSource; -import com.google.zxing.common.BitMatrix; -import com.google.zxing.common.HybridBinarizer; -import com.google.zxing.qrcode.QRCodeReader; -import com.google.zxing.qrcode.QRCodeWriter; -import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; - -public class QrCodeCreateUtil { - - public static boolean createQrCode(OutputStream outputStream, String content, int qrCodeSize, String imageFormat) throws WriterException, IOException { - Hashtable hintMap = new Hashtable(); - hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); - QRCodeWriter qrCodeWriter = new QRCodeWriter(); - BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hintMap); - int matrixWidth = byteMatrix.getWidth(); - BufferedImage image = new BufferedImage(matrixWidth - 200, matrixWidth - 200, BufferedImage.TYPE_INT_RGB); - image.createGraphics(); - Graphics2D graphics = (Graphics2D) image.getGraphics(); - graphics.setColor(Color.WHITE); - graphics.fillRect(0, 0, matrixWidth, matrixWidth); - graphics.setColor(Color.BLACK); - for (int i = 0; i < matrixWidth; i++) { - for (int j = 0; j < matrixWidth; j++) { - if (byteMatrix.get(i, j)) { - graphics.fillRect(i - 100, j - 100, 1, 1); - } - } - } - return ImageIO.write(image, imageFormat, outputStream); - } - - public static void readQrCode(InputStream inputStream) throws IOException { - BufferedImage image = ImageIO.read(inputStream); - LuminanceSource source = new BufferedImageLuminanceSource(image); - BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); - QRCodeReader reader = new QRCodeReader(); - Result result = null; - try { - result = reader.decode(bitmap); - } catch (ReaderException e) { - e.printStackTrace(); - } - System.out.println(result.getText()); - } - - public static void main(String[] args) throws IOException, WriterException { - createQrCode(new FileOutputStream(new File("d:\\pancm.jpg")), "http://www.panchengming.com", 900, "JPEG"); - readQrCode(new FileInputStream(new File("d:\\pancm.jpg"))); - } - -} -*/ diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/utils/ZkUtil.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/utils/ZkUtil.java deleted file mode 100644 index ffc5cd8bf4..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/utils/ZkUtil.java +++ /dev/null @@ -1,155 +0,0 @@ -package com.jun.plugin.utils; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.I0Itec.zkclient.ZkClient; -import org.I0Itec.zkclient.exception.ZkException; -import org.I0Itec.zkclient.exception.ZkInterruptedException; -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.WatchedEvent; -import org.apache.zookeeper.Watcher.Event; - -/** - * -* @Title: ZookeeperUtils -* @Description: -* zookeeper的工具类 -* @Version:1.0.0 -* @author pancm -* @date 2018年5月2日 - */ -public class ZkUtil { - - /** - * 斜杠 - */ - private static final String SPRIT ="/"; - /** - * 创建目录并添加参数 - * @param zk - * @param path - * @param data - * @return - */ - public static void create(ZkClient zk,String path,String data) throws ZkInterruptedException, IllegalArgumentException, ZkException, RuntimeException{ - if(!zk.exists(path)){ - zk.create(path,data,CreateMode.PERSISTENT); - } - } - - /** - * 创建目录不添加参数 - * 也可以创建层级目录,格式: /test/test1/test1-1 - * @param zk - * @param path - * @return - */ - public static void create(ZkClient zk,String path) throws ZkInterruptedException, IllegalArgumentException, ZkException, RuntimeException{ - if(!zk.exists(path)){ - zk.createPersistent(path,true); - } - } - - /** - * 更新参数,没有就新增 - * @param zk - * @param path - * @param data - * @return - */ - public static boolean setData(ZkClient zk,String path,String data){ - boolean falg=false; - if(zk.exists(path)){ - zk.writeData(path, data); - falg=true; - } - return falg; - } - - /** - * 获取数据 - * @param zk - * @param path - * @return - */ - public static T getData(ZkClient zk,String path){ - T t=null; - if(zk.exists(path)){ - t=zk.readData(path); - } - return t; - } - - - /** - * 获取子节点 - * @param zk - * @param path - * @return - */ - public static List getChildNode(ZkClient zk,String path){ - List list=null; - if(zk.exists(path)){ - list=zk.getChildren(path); - } - return list; - } - - - /** - * 获取父级目录下的所有数据 - * 注:仅限一级 - * @param zk - * @param path - * @return - */ - public static Map getAll(ZkClient zk,String path){ - List yardList =getChildNode(zk,path); - Map map = new HashMap(); - for(String key : yardList){ - String value = getData(zk,path.concat(SPRIT).concat(key)); - map.put(key, value); - } - return map; - } - - /** - * 删除节点 - * 注:如果是该节点包含子节点,也会一并删除 - * @param zk - * @param path - * @return - */ - public static boolean delete(ZkClient zk,String path){ - return zk.deleteRecursive(path); - } - - public static void close(ZkClient zk){ - if(zk!=null){ - zk.close(); - } - } - - - public void process(WatchedEvent watchedEvent) { - if (watchedEvent.getState() == Event.KeeperState.SyncConnected) { //与zk服务器处于连接状态 - //如果没有就创建 - if(watchedEvent.getType() == Event.EventType.None && null == watchedEvent.getPath()) { - - }else if(watchedEvent.getType() == Event.EventType.NodeCreated) { - System.out.println("监控到了该节点被创建"); - } else if(watchedEvent.getType() == Event.EventType.NodeDataChanged) { - // 节点的子节点列表发生变化 - System.out.println("监控到了该节点更新"); - } else if(watchedEvent.getType() == Event.EventType.NodeChildrenChanged) { - // 节点的数据内容发生变化 - System.out.println("监控到了该节点的子节点更新"); - }else if(watchedEvent.getType() == Event.EventType.NodeDeleted) { - System.out.println("监控到了该节点删除"); - } - } - } - -} diff --git a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/utils/package-info.java b/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/utils/package-info.java deleted file mode 100644 index 5747370324..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/java/com/jun/plugin/utils/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -* @Title: package-info -* @Description: 一些工具类 -* @Version:1.0.0 -* @author pancm -* @date 2018年9月20日 -*/ -package com.jun.plugin.utils; \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/main/resources/logback.xml b/jun_java_plugins/jun_jdk/src/main/resources/logback.xml deleted file mode 100644 index 80db60fde6..0000000000 --- a/jun_java_plugins/jun_jdk/src/main/resources/logback.xml +++ /dev/null @@ -1,85 +0,0 @@ - - - - - - - - - - - %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] [%class:%line] %-5level %logger{50} - %msg%n - - - - - - - ${LOG_HOME}/mylog-%d{yyyy-MM-dd}.%i.txt - - 10MB - 31 - 10GB - - - - %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] [%class:%line] %-5level %logger{50} - %msg%n - - - - - - - - - ${LOG_HOME}/oneInfo/%d{yyyy-MM-dd}/oneInfo.%i.txt - - 10MB - 31 - 10GB - - - - %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] [%class:%line] %-5level %logger{50} - %msg%n - - - - - - - - - ${LOG_HOME}/twoInfo/%d{yyyy-MM-dd}/twoInfo.%i.txt - - 10MB - 31 - 10GB - - - - %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] [%class:%line] %-5level %logger{50} - %msg%n - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_jdk/src/test/java/com/jun/plugin/AppTest.java b/jun_java_plugins/jun_jdk/src/test/java/com/jun/plugin/AppTest.java deleted file mode 100644 index 4175d2d1d4..0000000000 --- a/jun_java_plugins/jun_jdk/src/test/java/com/jun/plugin/AppTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.jun.plugin; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * Unit test for simple App. - */ -public class AppTest - extends TestCase -{ - /** - * Create the test case - * - * @param testName name of the test case - */ - public AppTest( String testName ) - { - super( testName ); - } - - /** - * @return the suite of tests being tested - */ - public static Test suite() - { - return new TestSuite( AppTest.class ); - } - - /** - * Rigourous Test :-) - */ - public void testApp() - { - assertTrue( true ); - } -} diff --git a/jun_java_plugins/jun_jgit/.gitignore b/jun_java_plugins/jun_jgit/.gitignore deleted file mode 100644 index 285b86ba9f..0000000000 --- a/jun_java_plugins/jun_jgit/.gitignore +++ /dev/null @@ -1,26 +0,0 @@ -*.class -target -.classpath -.project -.settings/ -.gradle -/bin/ -/build/ - -### JetBrains template -# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio - -*.iml - -## Directory-based project format: -.idea/ -# if you remove the above rule, at least ignore the following: - -## File-based project format: -*.ipr -*.iws - -## Plugin-specific files: - -# IntelliJ -/out/ diff --git a/jun_java_plugins/jun_jgit/README.md b/jun_java_plugins/jun_jgit/README.md deleted file mode 100644 index c94d9c0a52..0000000000 --- a/jun_java_plugins/jun_jgit/README.md +++ /dev/null @@ -1,185 +0,0 @@ -jgit-cookbook -============= -[![Build Status](https://travis-ci.org/centic9/jgit-cookbook.svg)](https://travis-ci.org/centic9/jgit-cookbook) [![Gradle Status](https://gradleupdate.appspot.com/centic9/jgit-cookbook/status.svg?branch=master)](https://gradleupdate.appspot.com/centic9/jgit-cookbook/status) - -Provides examples and code snippets for the [JGit](https://eclipse.org/jgit/) Java Git implementation. - -The JGit framework is rich and diverse, it has two layers, a low-level _api_ and a higher-level set of _porcelain_ commands. This can be a bit intimidating at first as there are lots of classes, some of which are not relevant for most tasks. - -This project tries to provide a collection of ready-to-run snippets which provide a quick start for building functionality using JGit. - -Please make sure to take a look at the nicely written [introduction](http://www.codeaffine.com/2015/12/15/getting-started-with-jgit/) and also use the existing [JavaDoc](http://download.eclipse.org/jgit/site/5.5.0.201909110433-r/apidocs/) and the [model.User Guide](http://wiki.eclipse.org/JGit/User_Guide) as well, as they are well done and provide detailed information and a general overview of JGit respectively. - -*Note: Please use sites such as http://stackoverflow.com for general questions about JGit usage, not issues in this project. Issues should be used for problems with snippets and suggestions of missing snippets. Snippets from good answers on stackoverflow can then be included here, naturally.* - -#### Getting started - -##### Grab it - - git clone git://github.com/centic9/jgit-cookbook - -##### Build it and create Eclipse project files - -###### When using Maven - - mvn dependency:sources eclipse:eclipse package - -###### When using Gradle - - ./gradlew eclipse check - -#### Run it - - Import the project into your favourite IDE and execute the snippets there. - -#### Currently the following snippets are available - -##### General Repository handling - -* [Open an existing repository](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/OpenRepository.java) -* [Create a new repository](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/CreateNewRepository.java) - -##### Porcelain commands - -* [Initialize a new repository](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/InitRepository.java) -* [Add a new file to the index](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/AddFile.java) -* [Commit a file to an existing repository](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/CommitFile.java) -* [Commit all changes](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/CommitAll.java) -* [List commits (i.e. Log)](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/ShowLog.java) -* [List all tags in a repository](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/ListTags.java) -* [List all branches in a repository](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/ListBranches.java) -* [List all commits in a repository](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/WalkAllCommits.java) -* [List uncommitted changes of a repository](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/ListUncommittedChanges.java) -* [Create and delete branches](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/CreateAndDeleteBranch.java) -* [Create and delete tags](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/CreateAndDeleteTag.java) -* [List all tags applied on a branch](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/ListTagsOnBranch.java) -* [Revert a modified tracked file back to its original state in most recent commit](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/RevertChanges.java) -* [Return diff between two branches](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/ShowBranchDiff.java) -* [Show diff of changes to a file between two revs](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/ShowFileDiff.java) -* [Show diff of changes to all files between two commits](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/ShowChangedFilesBetweenCommits.java) -* [Show diff of changes to a file between two commits when the file has been renamed](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/DiffRenamedFile.java) -* [Show Status](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/ShowStatus.java) -* [Store contents of branch into a compressed file](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/CreateArchive.java) -* [Write contents of branch into a compressed file using a custom archive format](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/CreateCustomFormatArchive.java) -* [Blame, i.e. find out which commit changed specific lines in a file](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/ShowBlame.java) -* [Add and list Notes attached to commits](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/AddAndListNoteOfCommit.java) -* [List available Notes](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/ListNotes.java) -* [Clean all untracked files](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/CleanUntrackedFiles.java) -* [Create, list, apply and drop stashes](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/CreateListApplyAndDropStash.java) -* [Run garbage collection](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/CollectGarbage.java) -* [Blame, i.e. retrieve information who last changed which line in a file](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/BlameFile.java) -* [Merge changes from a branch](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/MergeChanges.java) -* [List changed files between two commits](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/DiffFilesInCommit.java) - -##### Commands working with remote repositories - -* [Clone a remote repository into a new local directory](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/CloneRemoteRepository.java) -* [Iterate remote references in a repository](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/ListRemotes.java) -* [List remote heads/tags without a local clone](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/ListRemoteRepository.java) -* [Fetch from remote repositories](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/FetchRemoteCommits.java) -* [Fetch from remote repositories and use 'prune' to remove outdated remote branches/tags](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/FetchRemoteCommitsWithPrune.java) -* [Fetch from remote repositories via ssh protocol](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/FetchRemoteCommitsWithSshAuth.java) -* [Clone a remote repository via SSH protocol and username/password credentials](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/CloneRemoteRepositoryWithAuthentication.java) -* [Rebase onto an upstream branch](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/RebaseToOriginMaster.java) -* [Using InMemoryRepository to clone a Git repo in-memory and work from there](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/CloneRemoteRepositoryIntoMemoryAndReadFile.java) -* [Checkout a PR from GitHub](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/CheckoutGitHubPullRequest.java) - -##### Low-level API - -* [Get the SHA-1 ref from a name, e.g. refs/heads/master](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/api/GetRefFromName.java) -* [Get the commit-object from a name or a SHA-1](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/api/GetRevCommitFromObjectId.java) -* [Get the commit-message](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/api/GetCommitMessage.java) -* [Get the tree-object from a commit-object, name or SHA-1](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/api/GetRevTreeFromObjectId.java) -* [Read the contents of a file/blob](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/api/ReadBlobContents.java) -* [Get the tag-object from a name or a SHA-1](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/api/ReadTagFromName.java) -* [Resolve complex references, e.g. HEAD^^ to a SHA-1](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/api/ResolveRef.java) -* [Iterate over the commits on a branch](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/api/WalkRev.java) -* [Iterate over a range of commits](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/api/WalkFromToRev.java) -* [Read contents of a specific file from a specific commit](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/api/ReadFileFromCommit.java) -* [List remotes configured for the current repository](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/api/PrintRemotes.java) -* [Print out user information from Git](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/api/ReadUserConfig.java) -* [Read file attributes, e.g. executable state, file or directory, size, ...](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/api/GetFileAttributes.java) -* [Use class BranchTrackingStatus to retrieve number of commits ahead/behind compared to remote branches](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/api/ShowBranchTrackingStatus.java) -* [Check if commits on other branches are merged into a given branch](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/api/CheckMergeStatusOfCommit.java) -* [List files in a directory as-of a specific commit or a tag](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/api/ListFilesOfCommitAndTag.java) -* [Iterate over files of a commit recursively](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/api/WalkTreeRecursive.java) -* [Iterate over files of a commit non-recursively](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/api/WalkTreeNonRecursive.java) -* [Find all commits that are reachable via tags, branches, remotes, HEADs, ...](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/api/WalkAllCommits.java) - -##### GitServlet - -* There is a standalone sub-project in directory [httpserver](https://github.com/centic9/jgit-cookbook/blob/master/httpserver) which -starts up a simple HTTP Git server based on the JGit GitServlet. - -Just import the project in your IDE and start up the `Main` application, see the Comments in the code for more details. - -Another simple way to start the sample-server is to run `./gradlew run` in the httpserver-directory. - -#### Useful code elsewhere - -##### cf-ops-automation-broker - -* Implementation of a simple git server serving anynymous `git:` protocol: https://github.com/orange-cloudfoundry/cf-ops-automation-broker/blob/8bcb286652fae2b8fe2ccc9f67c53cb0272bcbd0/cf-ops-automation-broker-core/src/main/java/com/orange/oss/cloudfoundry/broker/opsautomation/ondemandbroker/git/GitServer.java -* Usage in tests: https://github.com/orange-cloudfoundry/cf-ops-automation-broker/blob/8bcb286652fae2b8fe2ccc9f67c53cb0272bcbd0/cf-ops-automation-bosh-broker/src/test/java/com/orange/oss/cloudfoundry/broker/opsautomation/ondemandbroker/sample/BoshServiceProvisionningTest.java#L134 - -#### Missing snippets - -* Iterate all commits of a repository: https://gerrit.googlesource.com/plugins/branch-network/+log/refs/heads/master/src/main/java/com/googlesource/gerrit/plugins/branchnetwork/data/JGitFacade.java -* Take some of the unit tests as example: https://github.com/eclipse/jgit/tree/master/org.eclipse.jgit.test/tst/org/eclipse/jgit/api -* SubModules: http://stackoverflow.com/questions/13426798/jgit-read-gitmodules http://www.codeaffine.com/2014/04/16/how-to-manage-git-submodules-with-jgit/ https://stackoverflow.com/questions/26090139/jgit-reading-commits-from-a-submodule https://download.eclipse.org/jgit/site/5.5.0.201909110433-r/apidocs/org/eclipse/jgit/submodule/package-frame.html -* Diffing: http://stackoverflow.com/questions/12987364/how-to-diff-with-two-files-by-jgit-without-creating-repo -* Amend a previous commit: http://stackoverflow.com/questions/4772142/jgit-unstaging-files-removing-files-from-the-index-and-ammending-a-commit -* Remove a file from the index: http://stackoverflow.com/questions/4803462/jgit-java-git-library-unstaging-files -* Git repo on Amazon S3: http://stackoverflow.com/questions/8744611/git-repository-on-s3-as-origin-not-as-backup http://stackoverflow.com/questions/7031729/publish-to-s3-using-git http://www.fancybeans.com/blog/2012/08/24/how-to-use-s3-as-a-private-git-repository/ -* CherryPick: http://download.eclipse.org/jgit/site/5.5.0.201909110433-r/apidocs/org/eclipse/jgit/api/CherryPickCommand.html http://stackoverflow.com/questions/18300898/how-to-cherry-pick-a-commit-that-has-more-than-one-parent -* More authentication: http://www.lordofthejars.com/2016/09/authenticating-with-jgit.html -* How to do a shallow clone (i.e. --depth 1) as soon as https://bugs.eclipse.org/bugs/show_bug.cgi?id=475615 is implemented - -#### Support this project - -If you find these snippets useful and would like to support it, you can [Sponsor the author](https://github.com/sponsors/centic9) - -#### Sources - -The following sources were used to build the snippets: - -* [JGit JavaDoc](http://download.eclipse.org/jgit/site/5.5.0.201909110433-r/apidocs/) -* [JGit model.User Guide](http://wiki.eclipse.org/JGit/User_Guide) -* [JGit related questions on stackoverflow](http://stackoverflow.com/questions/tagged/jgit) -* [AlBlue's Blog: Embedding JGit](http://alblue.bandlem.com/2013/11/embedding-jgit.html) -* [JGit main page](http://www.eclipse.org/jgit/) - -#### Other applications using JGit - -* EGit - Git plugin for Eclipse - https://www.eclipse.org/egit/ -* Gerrit - A web-based team code collaboration tool - https://www.gerritcodereview.com -* Gitiles - A simple Git repository browser - http://code.google.com/p/gitiles/ and https://android.googlesource.com -* JGitFS - A userfs implementation which allows to browse branches, tags, committs as a directory structure - https://github.com/centic9/JGitFS -* jgitstats - displays repository stats - https://github.com/selesse/jgitstats -* git-to-solr - Index git history into a Solr repository - https://github.com/arafalov/git-to-solr -* Elegit - GUI client for people who want to learn Git - https://github.com/dmusican/Elegit -* Grgit - A wrapper over JGit that provides a fluent API for interacting with Git repositories in Groovy-based tooling - https://github.com/ajoberstar/grgit -* jgitver A library to calculate a project semver compatible version from a git repository and its content - https://github.com/jgitver/jgitver -* gitective - Investigate Git repositories via filters - https://github.com/kevinsawicki/gitective -* RJGit - A JRuby wrapper around the JGit library - https://github.com/repotag/rjgit -* KGit - A Kotlin Wrapper of JGit - https://github.com/sya-ri/KGit - -Ruby Build - -#### Contribute - -Please note that the list of snippets is not yet complete, probably never will. If you are missing things or have suggestions how to improve or add snippets, please either send pull requests or create [issues](https://github.com/centic9/jgit-cookbook/issues). - -#### Licensing - - Copyright 2013-2020 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/jun_java_plugins/jun_jgit/pom.xml b/jun_java_plugins/jun_jgit/pom.xml deleted file mode 100644 index cac8cc108f..0000000000 --- a/jun_java_plugins/jun_jgit/pom.xml +++ /dev/null @@ -1,74 +0,0 @@ - - 4.0.0 - - io.github.wujun728 - 1.0 - jun_jgit - jar - - - - jgit-repository - https://repo.eclipse.org/content/groups/releases/ - - - - - - - org.eclipse.jgit - org.eclipse.jgit - 5.13.0.202109080827-r - - - org.eclipse.jgit - org.eclipse.jgit.archive - 5.13.0.202109080827-r - - - org.eclipse.jgit - org.eclipse.jgit.ssh.jsch - 5.13.0.202109080827-r - - - - commons-io - commons-io - 2.8.0 - - - org.slf4j - slf4j-simple - 1.7.36 - - - - - - - junit - junit - 4.13.2 - test - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.2 - - 1.8 - 1.8 - - - - - diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/CreateNewRepository.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/CreateNewRepository.java deleted file mode 100644 index 27517447ac..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/CreateNewRepository.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.jun.plugin.jgit; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.File; -import java.io.IOException; - -import org.apache.commons.io.FileUtils; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; - -/** - * Simple snippet which shows how to create a new repository - * - * @author dominik.stadler at gmx.at - */ -public class CreateNewRepository { - - public static void main(String[] args) throws IOException, IllegalStateException, GitAPIException { - // prepare a new folder - File localPath = File.createTempFile("TestGitRepository", ""); - if(!localPath.delete()) { - throw new IOException("Could not delete temporary file " + localPath); - } - - // create the directory - try (Git git = Git.init().setDirectory(localPath).call()) { - System.out.println("Having repository: " + git.getRepository().getDirectory()); - } - - // clean up here to not keep using more and more disk-space for these samples - FileUtils.deleteDirectory(localPath); - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/OpenRepository.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/OpenRepository.java deleted file mode 100644 index 54b1ee5e2d..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/OpenRepository.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.jun.plugin.jgit; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import org.apache.commons.io.FileUtils; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.storage.file.FileRepositoryBuilder; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -import java.io.File; -import java.io.IOException; - -/** - * Simple snippet which shows how to open an existing repository - * - * @author dominik.stadler at gmx.at - */ -public class OpenRepository { - - public static void main(String[] args) throws IOException, GitAPIException { - // first create a test-repository, the return is including the .get directory here! - File repoDir = createSampleGitRepo(); - - // now open the resulting repository with a FileRepositoryBuilder - FileRepositoryBuilder builder = new FileRepositoryBuilder(); - try (Repository repository = builder.setGitDir(repoDir) - .readEnvironment() // scan environment GIT_* variables - .findGitDir() // scan up the file system tree - .build()) { - System.out.println("Having repository: " + repository.getDirectory()); - - // the Ref holds an ObjectId for any type of object (tree, commit, blob, tree) - Ref head = repository.exactRef("refs/heads/master"); - System.out.println("Ref of refs/heads/master: " + head); - } - - // clean up here to not keep using more and more disk-space for these samples - FileUtils.deleteDirectory(repoDir.getParentFile()); - } - - private static File createSampleGitRepo() throws IOException, GitAPIException { - try (Repository repository = CookbookHelper.createNewRepository()) { - System.out.println("Temporary repository at " + repository.getDirectory()); - - // create the file - File myFile = new File(repository.getDirectory().getParent(), "testfile"); - if(!myFile.createNewFile()) { - throw new IOException("Could not create file " + myFile); - } - - // run the add-call - try (Git git = new Git(repository)) { - git.add() - .addFilepattern("testfile") - .call(); - - - // and then commit the changes - git.commit() - .setMessage("Added testfile") - .call(); - } - - System.out.println("Added file " + myFile + " to repository at " + repository.getDirectory()); - - return repository.getDirectory(); - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/CheckMergeStatusOfCommit.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/CheckMergeStatusOfCommit.java deleted file mode 100644 index 1fa4e37708..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/CheckMergeStatusOfCommit.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.jun.plugin.jgit.api; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.IOException; - -import org.eclipse.jgit.lib.ObjectId; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; -import org.eclipse.jgit.revwalk.RevWalk; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -/** - * Snippet which shows how to check if commits are merged into a - * given branch. - * - * See also http://stackoverflow.com/questions/26644919/how-to-determine-with-jgit-which-branches-have-been-merged-to-master - */ -public class CheckMergeStatusOfCommit { - - public static void main(String[] args) throws IOException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - try (RevWalk revWalk = new RevWalk( repository )) { - RevCommit masterHead = revWalk.parseCommit( repository.resolve( "refs/heads/master" )); - - // first a commit that was merged - ObjectId id = repository.resolve("05d18a76875716fbdbd2c200091b40caa06c713d"); - System.out.println("Had id: " + id); - RevCommit otherHead = revWalk.parseCommit( id ); - - if( revWalk.isMergedInto( otherHead, masterHead ) ) { - System.out.println("Commit " + otherHead + " is merged into master"); - } else { - System.out.println("Commit " + otherHead + " is NOT merged into master"); - } - - - // then a commit on a test-branch which is not merged - id = repository.resolve("ae70dd60a7423eb07893d833600f096617f450d2"); - System.out.println("Had id: " + id); - otherHead = revWalk.parseCommit( id ); - - if( revWalk.isMergedInto( otherHead, masterHead ) ) { - System.out.println("Commit " + otherHead + " is merged into master"); - } else { - System.out.println("Commit " + otherHead + " is NOT merged into master"); - } - - // and finally master-HEAD itself - id = repository.resolve("HEAD"); - System.out.println("Had id: " + id); - otherHead = revWalk.parseCommit( id ); - - if( revWalk.isMergedInto( otherHead, masterHead ) ) { - System.out.println("Commit " + otherHead + " is merged into master"); - } else { - System.out.println("Commit " + otherHead + " is NOT merged into master"); - } - - revWalk.dispose(); - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/GetCommitMessage.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/GetCommitMessage.java deleted file mode 100644 index 3cea36217a..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/GetCommitMessage.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.jun.plugin.jgit.api; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.IOException; - -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; -import org.eclipse.jgit.revwalk.RevWalk; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -/** - * Simple snippet which shows how to retrieve the commit-message based on object id. - */ -public class GetCommitMessage { - - public static void main(String[] args) throws IOException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - Ref head = repository.findRef("refs/heads/master"); - System.out.println("Found head: " + head); - - // a RevWalk allows to walk over commits based on some filtering that is defined - try (RevWalk walk = new RevWalk(repository)) { - RevCommit commit = walk.parseCommit(head.getObjectId()); - - System.out.println("\nCommit-Message: " + commit.getFullMessage()); - - walk.dispose(); - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/GetFileAttributes.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/GetFileAttributes.java deleted file mode 100644 index 12c3d2ba49..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/GetFileAttributes.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.jun.plugin.jgit.api; - -import org.eclipse.jgit.lib.*; -import org.eclipse.jgit.revwalk.RevCommit; -import org.eclipse.jgit.revwalk.RevTree; -import org.eclipse.jgit.revwalk.RevWalk; -import org.eclipse.jgit.treewalk.TreeWalk; -import org.eclipse.jgit.treewalk.filter.PathFilter; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -import java.io.IOException; - -/** - * Snippet which shows how to use RevWalk and TreeWalk to read the file - * attributes like execution-bit and type of file/directory/... - * - * @author dominik.stadler at gmx.at - */ -public class GetFileAttributes { - - public static void main(String[] args) throws IOException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - // find the Tree for current HEAD - RevTree tree = getTree(repository); - - printFile(repository, tree); - - printDirectory(repository, tree); - - // there is also FileMode.SYMLINK for symbolic links, but this is not handled here yet - } - } - - private static RevTree getTree(Repository repository) throws IOException { - ObjectId lastCommitId = repository.resolve(Constants.HEAD); - - // a RevWalk allows to walk over commits based on some filtering - try (RevWalk revWalk = new RevWalk(repository)) { - RevCommit commit = revWalk.parseCommit(lastCommitId); - - System.out.println("Time of commit (seconds since epoch): " + commit.getCommitTime()); - - // and using commit's tree find the path - RevTree tree = commit.getTree(); - System.out.println("Having tree: " + tree); - return tree; - } - } - - private static void printFile(Repository repository, RevTree tree) throws IOException { - // now try to find a specific file - try (TreeWalk treeWalk = new TreeWalk(repository)) { - treeWalk.addTree(tree); - treeWalk.setRecursive(false); - treeWalk.setFilter(PathFilter.create("README.md")); - if (!treeWalk.next()) { - throw new IllegalStateException("Did not find expected file 'README.md'"); - } - - // FileMode specifies the type of file, FileMode.REGULAR_FILE for normal file, FileMode.EXECUTABLE_FILE for executable bit - // set - FileMode fileMode = treeWalk.getFileMode(0); - ObjectLoader loader = repository.open(treeWalk.getObjectId(0)); - System.out.println("README.md: " + getFileMode(fileMode) + ", type: " + fileMode.getObjectType() + ", mode: " + fileMode + - " size: " + loader.getSize()); - } - } - - private static void printDirectory(Repository repository, RevTree tree) throws IOException { - // look at directory, this has FileMode.TREE - try (TreeWalk treeWalk = new TreeWalk(repository)) { - treeWalk.addTree(tree); - treeWalk.setRecursive(false); - treeWalk.setFilter(PathFilter.create("src")); - if (!treeWalk.next()) { - throw new IllegalStateException("Did not find expected folder 'src'"); - } - - // FileMode now indicates that this is a directory, i.e. FileMode.TREE.equals(fileMode) holds true - FileMode fileMode = treeWalk.getFileMode(0); - System.out.println("src: " + getFileMode(fileMode) + ", type: " + fileMode.getObjectType() + ", mode: " + fileMode); - } - } - - private static String getFileMode(FileMode fileMode) { - if (fileMode.equals(FileMode.EXECUTABLE_FILE)) { - return "Executable File"; - } else if (fileMode.equals(FileMode.REGULAR_FILE)) { - return "Normal File"; - } else if (fileMode.equals(FileMode.TREE)) { - return "Directory"; - } else if (fileMode.equals(FileMode.SYMLINK)) { - return "Symlink"; - } else { - // there are a few others, see FileMode javadoc for details - throw new IllegalArgumentException("Unknown type of file encountered: " + fileMode); - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/GetRefFromName.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/GetRefFromName.java deleted file mode 100644 index 1311f643b9..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/GetRefFromName.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jun.plugin.jgit.api; - -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -import java.io.IOException; -/** - * Simple snippet which shows how to retrieve a Ref for some reference string. - */ -public class GetRefFromName { - - public static void main(String[] args) throws IOException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - // the Ref holds an ObjectId for any type of object (tree, commit, blob, tree) - Ref head = repository.exactRef("refs/heads/master"); - System.out.println("Ref of refs/heads/master: " + head + ": " + head.getName() + " - " + head.getObjectId().getName()); - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/GetRevCommitFromObjectId.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/GetRevCommitFromObjectId.java deleted file mode 100644 index a0ed6e9791..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/GetRevCommitFromObjectId.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.jun.plugin.jgit.api; - -import org.eclipse.jgit.lib.ObjectId; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; -import org.eclipse.jgit.revwalk.RevWalk; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -import java.io.IOException; - -/** - * Simple snippet which shows how to use RevWalk to iterate over objects - */ -public class GetRevCommitFromObjectId { - - public static void main(String[] args) throws IOException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - Ref head = repository.exactRef("refs/heads/master"); - System.out.println("Found head: " + head); - - // a RevWalk allows to walk over commits based on some filtering that is defined - try (RevWalk walk = new RevWalk(repository)) { - RevCommit commit = walk.parseCommit(head.getObjectId()); - System.out.println("Found Commit: " + commit); - - // You can also get the commit for an (abbreviated) SHA - walk.reset(); - ObjectId id = repository.resolve("38d51408bd"); - RevCommit commitAgain = walk.parseCommit(id); - System.out.println("Found Commit again: " + commitAgain); - - walk.dispose(); - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/GetRevTreeFromObjectId.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/GetRevTreeFromObjectId.java deleted file mode 100644 index 92ed5d28b7..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/GetRevTreeFromObjectId.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.jun.plugin.jgit.api; - -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; -import org.eclipse.jgit.revwalk.RevTree; -import org.eclipse.jgit.revwalk.RevWalk; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -import java.io.IOException; - -/** - * Simple snippet which shows how to use RevWalk to iterate over objects - */ -public class GetRevTreeFromObjectId { - - public static void main(String[] args) throws IOException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - // See e.g. GetRevCommitFromObjectId for how to use a SHA-1 directly - Ref head = repository.findRef("HEAD"); - System.out.println("Ref of HEAD: " + head + ": " + head.getName() + " - " + head.getObjectId().getName()); - - // a RevWalk allows to walk over commits based on some filtering that is defined - try (RevWalk walk = new RevWalk(repository)) { - RevCommit commit = walk.parseCommit(head.getObjectId()); - System.out.println("Commit: " + commit); - - // a commit points to a tree - RevTree tree = walk.parseTree(commit.getTree().getId()); - System.out.println("Found Tree: " + tree); - - walk.dispose(); - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/ListFilesOfCommitAndTag.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/ListFilesOfCommitAndTag.java deleted file mode 100644 index 2a139fb627..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/ListFilesOfCommitAndTag.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.jun.plugin.jgit.api; - -import org.eclipse.jgit.lib.FileMode; -import org.eclipse.jgit.lib.ObjectId; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; -import org.eclipse.jgit.revwalk.RevTree; -import org.eclipse.jgit.revwalk.RevWalk; -import org.eclipse.jgit.treewalk.TreeWalk; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - * Simple snippet which shows how to get a list of files/directories - * based on a specific commit or a tag. - */ -public class ListFilesOfCommitAndTag { - - public static void main(String[] args) throws IOException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - List paths = readElementsAt(repository, "6409ee1597a53c6fbee31edf9cde31dc3afbe20f", "src/main/java/org/dstadler/jgit/porcelain"); - - System.out.println("Had paths for commit: " + paths); - - final ObjectId testbranch = repository.resolve("testbranch"); - paths = readElementsAt(repository, testbranch.getName(), "src/main/java/org/dstadler/jgit/porcelain"); - - System.out.println("Had paths for tag: " + paths); - } - } - - private static List readElementsAt(Repository repository, String commit, String path) throws IOException { - RevCommit revCommit = buildRevCommit(repository, commit); - - // and using commit's tree find the path - RevTree tree = revCommit.getTree(); - //System.out.println("Having tree: " + tree + " for commit " + commit); - - List items = new ArrayList<>(); - - // shortcut for root-path - if(path.isEmpty()) { - try (TreeWalk treeWalk = new TreeWalk(repository)) { - treeWalk.addTree(tree); - treeWalk.setRecursive(false); - treeWalk.setPostOrderTraversal(false); - - while(treeWalk.next()) { - items.add(treeWalk.getPathString()); - } - } - } else { - // now try to find a specific file - try (TreeWalk treeWalk = buildTreeWalk(repository, tree, path)) { - if((treeWalk.getFileMode(0).getBits() & FileMode.TYPE_TREE) == 0) { - throw new IllegalStateException("Tried to read the elements of a non-tree for commit '" + commit + "' and path '" + path + "', had filemode " + treeWalk.getFileMode(0).getBits()); - } - - try (TreeWalk dirWalk = new TreeWalk(repository)) { - dirWalk.addTree(treeWalk.getObjectId(0)); - dirWalk.setRecursive(false); - while(dirWalk.next()) { - items.add(dirWalk.getPathString()); - } - } - } - } - - return items; - } - - private static RevCommit buildRevCommit(Repository repository, String commit) throws IOException { - // a RevWalk allows to walk over commits based on some filtering that is defined - try (RevWalk revWalk = new RevWalk(repository)) { - return revWalk.parseCommit(ObjectId.fromString(commit)); - } - } - - private static TreeWalk buildTreeWalk(Repository repository, RevTree tree, final String path) throws IOException { - TreeWalk treeWalk = TreeWalk.forPath(repository, path, tree); - - if(treeWalk == null) { - throw new FileNotFoundException("Did not find expected file '" + path + "' in tree '" + tree.getName() + "'"); - } - - return treeWalk; - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/PrintRemotes.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/PrintRemotes.java deleted file mode 100644 index d1a7068e29..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/PrintRemotes.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.jun.plugin.jgit.api; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.IOException; -import java.util.Set; - -import org.eclipse.jgit.lib.Config; -import org.eclipse.jgit.lib.Repository; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -/** - * Simple snippet which shows how to retrieve the list of remotes from the configuration - */ -public class PrintRemotes { - - public static void main(String[] args) throws IOException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - Config storedConfig = repository.getConfig(); - Set remotes = storedConfig.getSubsections("remote"); - - for (String remoteName : remotes) { - String url = storedConfig.getString("remote", remoteName, "url"); - System.out.println(remoteName + " " + url); - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/ReadBlobContents.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/ReadBlobContents.java deleted file mode 100644 index 1fceafd941..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/ReadBlobContents.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.jun.plugin.jgit.api; - -import org.eclipse.jgit.lib.ObjectLoader; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; -import org.eclipse.jgit.revwalk.RevTree; -import org.eclipse.jgit.revwalk.RevWalk; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -import java.io.IOException; - -/** - * Simple snippet which shows how to retrieve a Ref for some reference string. - */ -public class ReadBlobContents { - - public static void main(String[] args) throws IOException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - // the Ref holds an ObjectId for any type of object (tree, commit, blob, tree) - Ref head = repository.exactRef("refs/heads/master"); - System.out.println("Ref of refs/heads/master: " + head); - - System.out.println("\nPrint contents of head of master branch, i.e. the latest commit information"); - ObjectLoader loader = repository.open(head.getObjectId()); - loader.copyTo(System.out); - - System.out.println("\nPrint contents of tree of head of master branch, i.e. the latest binary tree information"); - - // a commit points to a tree - try (RevWalk walk = new RevWalk(repository)) { - RevCommit commit = walk.parseCommit(head.getObjectId()); - RevTree tree = walk.parseTree(commit.getTree().getId()); - System.out.println("Found Tree: " + tree); - loader = repository.open(tree.getId()); - loader.copyTo(System.out); - - walk.dispose(); - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/ReadFileFromCommit.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/ReadFileFromCommit.java deleted file mode 100644 index 64ab17d891..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/ReadFileFromCommit.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.jun.plugin.jgit.api; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.IOException; - -import org.eclipse.jgit.lib.Constants; -import org.eclipse.jgit.lib.ObjectId; -import org.eclipse.jgit.lib.ObjectLoader; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; -import org.eclipse.jgit.revwalk.RevTree; -import org.eclipse.jgit.revwalk.RevWalk; -import org.eclipse.jgit.treewalk.TreeWalk; -import org.eclipse.jgit.treewalk.filter.PathFilter; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -/** - * Snippet which shows how to use RevWalk and TreeWalk to read the contents - * of a specific file from a specific commit. - * - * @author dominik.stadler at gmx.at - */ -public class ReadFileFromCommit { - - public static void main(String[] args) throws IOException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - // find the HEAD - ObjectId lastCommitId = repository.resolve(Constants.HEAD); - - // a RevWalk allows to walk over commits based on some filtering that is defined - try (RevWalk revWalk = new RevWalk(repository)) { - RevCommit commit = revWalk.parseCommit(lastCommitId); - // and using commit's tree find the path - RevTree tree = commit.getTree(); - System.out.println("Having tree: " + tree); - - // now try to find a specific file - try (TreeWalk treeWalk = new TreeWalk(repository)) { - treeWalk.addTree(tree); - treeWalk.setRecursive(true); - treeWalk.setFilter(PathFilter.create("README.md")); - if (!treeWalk.next()) { - throw new IllegalStateException("Did not find expected file 'README.md'"); - } - - ObjectId objectId = treeWalk.getObjectId(0); - ObjectLoader loader = repository.open(objectId); - - // and then one can the loader to read the file - loader.copyTo(System.out); - } - - revWalk.dispose(); - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/ReadTagFromName.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/ReadTagFromName.java deleted file mode 100644 index 17880050eb..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/ReadTagFromName.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.jun.plugin.jgit.api; - -import org.eclipse.jgit.lib.ObjectLoader; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevObject; -import org.eclipse.jgit.revwalk.RevWalk; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -import java.io.IOException; - -/** - * Simple snippet which shows how to use RevWalk to read tags - */ -public class ReadTagFromName { - - public static void main(String[] args) throws IOException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - // a RevWalk allows to retrieve information from the repository - try (RevWalk walk = new RevWalk(repository)) { - // a simple tag that is not annotated - Ref simpleTag = repository.findRef("initialtag"); - RevObject any = walk.parseAny(simpleTag.getObjectId()); - System.out.println("Commit: (" + any.getClass() + ")" + any); - - // an annotated tag - Ref annotatedTag = repository.findRef("secondtag"); - any = walk.parseAny(annotatedTag.getObjectId()); - System.out.println("Tag: (" + any.getClass() + ")" + any); - - // finally try to print out the tag-content - System.out.println("\nTag-Content: \n"); - ObjectLoader loader = repository.open(annotatedTag.getObjectId()); - loader.copyTo(System.out); - - walk.dispose(); - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/ReadUserConfig.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/ReadUserConfig.java deleted file mode 100644 index a848773813..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/ReadUserConfig.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.jun.plugin.jgit.api; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.IOException; - -import org.eclipse.jgit.lib.Config; -import org.eclipse.jgit.lib.Repository; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -/** - * Simple snippet which shows how to retrieve the user name and email that is configured in Git. - */ -public class ReadUserConfig { - - public static void main(String[] args) throws IOException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - Config config = repository.getConfig(); - String name = config.getString("user", null, "name"); - String email = config.getString("user", null, "email"); - if (name == null || email == null) { - System.out.println("User identity is unknown!"); - } else { - System.out.println("User identity is " + name + " <" + email + ">"); - } - - String url = config.getString("remote", "origin", "url"); - if (url != null) { - System.out.println("Origin comes from " + url); - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/ResolveRef.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/ResolveRef.java deleted file mode 100644 index e67494db93..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/ResolveRef.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.jun.plugin.jgit.api; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.IOException; - -import org.eclipse.jgit.lib.ObjectId; -import org.eclipse.jgit.lib.Repository; - -import com.jun.plugin.jgit.helper.CookbookHelper; - - - -/** - * Simple snippet which shows how to retrieve an ObjectId for some name. - */ -public class ResolveRef { - - public static void main(String[] args) throws IOException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - // basic syntax is similar to getRef() - ObjectId id = repository.resolve("HEAD"); - System.out.println("ObjectId of HEAD: " + id); - - // however resolve() supports almost all of the git-syntax, where getRef() only works on names - id = repository.resolve("HEAD^1"); - System.out.println("ObjectId of HEAD: " + id); - - id = repository.resolve("b419522521af553ae2752fd1b609f2aa11062243"); - System.out.println("ObjectId of specific commit: " + id); - - id = repository.resolve("05d18a76875716fbdbd2c200091b40caa06c713d"); - System.out.println("ObjectId of merged commit: " + id); - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/ShowBranchTrackingStatus.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/ShowBranchTrackingStatus.java deleted file mode 100644 index f632474258..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/ShowBranchTrackingStatus.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.jun.plugin.jgit.api; - -/* - * Copyright 2013, 2014 Dominik Stadler - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.BranchTrackingStatus; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -/** - * Snippet which shows how to use BranchTrackingStatus to print - * how many commits away the local git repository is from the - * remote branches. - * - * @author dominik.stadler at gmx.at - */ -public class ShowBranchTrackingStatus { - - public static void main(String[] args) throws IOException, GitAPIException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - try (Git git = new Git(repository)) { - List call = git.branchList().call(); - for (Ref ref : call) { - List counts = getCounts(repository, ref.getName()); - System.out.println("For branch: " + ref.getName()); - System.out.println("Commits ahead : " + counts.get(0)); - System.out.println("Commits behind : " + counts.get(1)); - System.out.println(); - } - } - } - } - - private static List getCounts(org.eclipse.jgit.lib.Repository repository, String branchName) throws IOException { - BranchTrackingStatus trackingStatus = BranchTrackingStatus.of(repository, branchName); - List counts = new ArrayList<>(); - if (trackingStatus != null) { - counts.add(trackingStatus.getAheadCount()); - counts.add(trackingStatus.getBehindCount()); - } else { - System.out.println("Returned null, likely no remote tracking of branch " + branchName); - counts.add(0); - counts.add(0); - } - return counts; - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/WalkAllCommits.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/WalkAllCommits.java deleted file mode 100644 index 98ca45d531..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/WalkAllCommits.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.jun.plugin.jgit.api; - -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; -import org.eclipse.jgit.revwalk.RevWalk; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -import java.io.IOException; -import java.util.Collection; - - -/** - * Simple snippet which shows how to use RevWalk to iterate over all commits - * across all branches/tags/remotes in the given repository - * - * See the original discussion at http://stackoverflow.com/a/40803945/411846 - */ -public class WalkAllCommits { - - public static void main(String[] args) throws IOException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - // get a list of all known heads, tags, remotes, ... - Collection allRefs = repository.getAllRefs().values(); - - // a RevWalk allows to walk over commits based on some filtering that is defined - try (RevWalk revWalk = new RevWalk( repository )) { - for( Ref ref : allRefs ) { - revWalk.markStart( revWalk.parseCommit( ref.getObjectId() )); - } - System.out.println("Walking all commits starting with " + allRefs.size() + " refs: " + allRefs); - int count = 0; - for( RevCommit commit : revWalk ) { - System.out.println("Commit: " + commit); - count++; - } - System.out.println("Had " + count + " commits"); - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/WalkFromToRev.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/WalkFromToRev.java deleted file mode 100644 index 50a0ecd92e..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/WalkFromToRev.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.jun.plugin.jgit.api; - -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; -import org.eclipse.jgit.revwalk.RevWalk; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -import java.io.IOException; - - -/** - * Simple snippet which shows how to use RevWalk to iterate over objects - */ -public class WalkFromToRev { - - public static void main(String[] args) throws IOException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - String from = "3408efc41a51555d488d30d8a91ea560c5e13311"; - String to = "7228de6ebe2a3087118562414061af4e189624c0"; - - // a RevWalk allows to walk over commits based on some filtering that is defined - try (RevWalk walk = new RevWalk(repository)) { - RevCommit commit = walk.parseCommit(repository.resolve(to)); - System.out.println("Start-Commit: " + commit); - - System.out.println("Walking all commits starting at " + to + " until we find " + from); - walk.markStart(commit); - int count = 0; - for (RevCommit rev : walk) { - System.out.println("Commit: " + rev); - count++; - - if(rev.getId().getName().equals(from)) { - System.out.println("Found from, stopping walk"); - break; - } - } - System.out.println(count); - - walk.dispose(); - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/WalkRev.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/WalkRev.java deleted file mode 100644 index 560bcb9736..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/WalkRev.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.jun.plugin.jgit.api; - -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; -import org.eclipse.jgit.revwalk.RevWalk; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -import java.io.IOException; - - - -/** - * Simple snippet which shows how to use RevWalk to iterate over objects - */ -public class WalkRev { - - public static void main(String[] args) throws IOException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - Ref head = repository.exactRef("refs/heads/master"); - - // a RevWalk allows to walk over commits based on some filtering that is defined - try (RevWalk walk = new RevWalk(repository)) { - RevCommit commit = walk.parseCommit(head.getObjectId()); - System.out.println("Start-Commit: " + commit); - - System.out.println("Walking all commits starting at HEAD"); - walk.markStart(commit); - int count = 0; - for (RevCommit rev : walk) { - System.out.println("Commit: " + rev); - count++; - } - System.out.println(count); - - walk.dispose(); - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/WalkTreeNonRecursive.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/WalkTreeNonRecursive.java deleted file mode 100644 index fa96e531af..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/WalkTreeNonRecursive.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.jun.plugin.jgit.api; - -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; -import org.eclipse.jgit.revwalk.RevTree; -import org.eclipse.jgit.revwalk.RevWalk; -import org.eclipse.jgit.treewalk.TreeWalk; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -import java.io.IOException; - -/** - * - * Simple snippet which shows how to use RevWalk to iterate over items in a file-tree - * - * See {@link WalkTreeNonRecursive} for a different usage of the {@link TreeWalk} class. - * - * @author dominik.stadler at gmx.at - */ -public class WalkTreeNonRecursive { - - public static void main(String[] args) throws IOException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - Ref head = repository.findRef("HEAD"); - - // a RevWalk allows to walk over commits based on some filtering that is defined - try (RevWalk walk = new RevWalk(repository)) { - RevCommit commit = walk.parseCommit(head.getObjectId()); - RevTree tree = commit.getTree(); - System.out.println("Having tree: " + tree); - - // now use a TreeWalk to iterate over all files in the Tree - // you can set Filters to narrow down the results if needed - try (TreeWalk treeWalk = new TreeWalk(repository)) { - treeWalk.addTree(tree); - // not walk the tree recursively so we only get the elements in the top-level directory - treeWalk.setRecursive(false); - while (treeWalk.next()) { - System.out.println("found: " + treeWalk.getPathString()); - } - } - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/WalkTreeRecursive.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/WalkTreeRecursive.java deleted file mode 100644 index 97703d29d4..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/api/WalkTreeRecursive.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.jun.plugin.jgit.api; - -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; -import org.eclipse.jgit.revwalk.RevTree; -import org.eclipse.jgit.revwalk.RevWalk; -import org.eclipse.jgit.treewalk.TreeWalk; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -import java.io.IOException; - -/** - * Simple snippet which shows how to use RevWalk to iterate over items in a file-tree. - * - * See {@link WalkTreeNonRecursive} for a different usage of the {@link TreeWalk} class. - * - * @author dominik.stadler at gmx.at - */ -public class WalkTreeRecursive { - - public static void main(String[] args) throws IOException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - Ref head = repository.findRef("HEAD"); - - // a RevWalk allows to walk over commits based on some filtering that is defined - try (RevWalk walk = new RevWalk(repository)) { - RevCommit commit = walk.parseCommit(head.getObjectId()); - RevTree tree = commit.getTree(); - System.out.println("Having tree: " + tree); - - // now use a TreeWalk to iterate over all files in the Tree recursively - // you can set Filters to narrow down the results if needed - try (TreeWalk treeWalk = new TreeWalk(repository)) { - treeWalk.addTree(tree); - treeWalk.setRecursive(true); - while (treeWalk.next()) { - System.out.println("found: " + treeWalk.getPathString()); - } - } - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/helper/CookbookHelper.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/helper/CookbookHelper.java deleted file mode 100644 index d59229b109..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/helper/CookbookHelper.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.jun.plugin.jgit.helper; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.File; -import java.io.IOException; - -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.storage.file.FileRepositoryBuilder; - - -public class CookbookHelper { - - public static Repository openJGitCookbookRepository() throws IOException { - FileRepositoryBuilder builder = new FileRepositoryBuilder(); - return builder - .readEnvironment() // scan environment GIT_* variables - .findGitDir() // scan up the file system tree - .build(); - } - - public static Repository createNewRepository() throws IOException { - // prepare a new folder - File localPath = File.createTempFile("TestGitRepository", ""); - if(!localPath.delete()) { - throw new IOException("Could not delete temporary file " + localPath); - } - - // create the directory - Repository repository = FileRepositoryBuilder.create(new File(localPath, ".git")); - repository.create(); - - return repository; - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/AddAndListNoteOfCommit.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/AddAndListNoteOfCommit.java deleted file mode 100644 index 86773067fb..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/AddAndListNoteOfCommit.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.ObjectLoader; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.notes.Note; -import org.eclipse.jgit.revwalk.RevCommit; -import org.eclipse.jgit.revwalk.RevWalk; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -import java.io.IOException; -import java.util.List; - - - -/** - * Simple snippet which shows how to load Notes in a Git repository - * - * @author dominik.stadler at gmx.at - */ -public class AddAndListNoteOfCommit { - - public static void main(String[] args) throws IOException, GitAPIException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - Ref head = repository.exactRef("refs/heads/master"); - System.out.println("Found head: " + head); - - try (RevWalk walk = new RevWalk(repository)) { - RevCommit commit = walk.parseCommit(head.getObjectId()); - System.out.println("Found Commit: " + commit); - - try (Git git = new Git(repository)) { - git.notesAdd().setMessage("some note message").setObjectId(commit).call(); - System.out.println("Added Note to commit " + commit); - - List call = git.notesList().call(); - System.out.println("Listing " + call.size() + " notes"); - for(Note note : call) { - // check if we found the note for this commit - if(!note.getName().equals(head.getObjectId().getName())) { - System.out.println("Note " + note + " did not match commit " + head); - continue; - } - System.out.println("Found note: " + note + " for commit " + head); - - // displaying the contents of the note is done via a simple blob-read - ObjectLoader loader = repository.open(note.getData()); - loader.copyTo(System.out); - } - } - - walk.dispose(); - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/AddFile.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/AddFile.java deleted file mode 100644 index 62c76d0919..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/AddFile.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.File; -import java.io.IOException; - -import org.apache.commons.io.FileUtils; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Repository; - -import com.jun.plugin.jgit.helper.CookbookHelper; - - - -/** - * Simple snippet which shows how to add a file to the index - * - * @author dominik.stadler at gmx.at - */ -public class AddFile { - - public static void main(String[] args) throws IOException, GitAPIException { - final File localPath; - // prepare a new test-repository - try (Repository repository = CookbookHelper.createNewRepository()) { - localPath = repository.getWorkTree(); - - try (Git git = new Git(repository)) { - // create the file - File myFile = new File(repository.getDirectory().getParent(), "testfile"); - if(!myFile.createNewFile()) { - throw new IOException("Could not create file " + myFile); - } - - // run the add-call - git.add() - .addFilepattern("testfile") - .call(); - - System.out.println("Added file " + myFile + " to repository at " + repository.getDirectory()); - } - } - - // clean up here to not keep using more and more disk-space for these samples - FileUtils.deleteDirectory(localPath); - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/BlameFile.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/BlameFile.java deleted file mode 100644 index 44f24669ae..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/BlameFile.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.blame.BlameResult; -import org.eclipse.jgit.diff.RawText; -import org.eclipse.jgit.diff.RawTextComparator; -import org.eclipse.jgit.lib.PersonIdent; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -import java.io.File; -import java.io.IOException; -import java.text.SimpleDateFormat; - -// Simple example that shows how to get the Blame-information for a file -public class BlameFile { - public static void main(String[] args) throws IOException, GitAPIException { - try (Repository repo = CookbookHelper.openJGitCookbookRepository()) { - final String[] list = new File(".").list(); - if (list == null) { - throw new IllegalStateException("Did not find any files at " + new File(".").getAbsolutePath()); - } - - final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("YYYY-MM-dd HH:mm"); - for (String file : list) { - if (new File(file).isDirectory()) { - continue; - } - - System.out.println("Blaming " + file); - final BlameResult result = new Git(repo).blame().setFilePath(file) - .setTextComparator(RawTextComparator.WS_IGNORE_ALL).call(); - final RawText rawText = result.getResultContents(); - for (int i = 0; i < rawText.size(); i++) { - final PersonIdent sourceAuthor = result.getSourceAuthor(i); - final RevCommit sourceCommit = result.getSourceCommit(i); - System.out.println(sourceAuthor.getName() + - (sourceCommit != null ? " - " + DATE_FORMAT.format(((long)sourceCommit.getCommitTime())*1000) + - " - " + sourceCommit.getName() : "") + - ": " + rawText.getString(i)); - } - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CheckoutGitHubPullRequest.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CheckoutGitHubPullRequest.java deleted file mode 100644 index 75181e5e1f..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CheckoutGitHubPullRequest.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import org.apache.commons.io.FileUtils; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.ProgressMonitor; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.revwalk.RevCommit; -import org.eclipse.jgit.transport.FetchResult; -import org.eclipse.jgit.transport.RefSpec; - -import java.io.File; -import java.io.IOException; - - -/** - * Simple snippet which shows how to clone a repository from GitHub and - * then checkout a PR - * - * @author dominik.stadler at gmx.at - */ -public class CheckoutGitHubPullRequest { - - private static final String REMOTE_URL = "https://github.com/github/testrepo.git"; - - public static void main(String[] args) throws IOException, GitAPIException { - // prepare a new folder for the cloned repository - File localPath = File.createTempFile("TestGitRepository", ""); - if(!localPath.delete()) { - throw new IOException("Could not delete temporary file " + localPath); - } - - // then clone - System.out.println("Cloning from " + REMOTE_URL + " to " + localPath); - try (Git result = Git.cloneRepository() - .setURI(REMOTE_URL) - .setDirectory(localPath) - .setProgressMonitor(new SimpleProgressMonitor()) - .call()) { - // Note: the call() returns an opened repository already which needs to be closed to avoid file handle leaks! - System.out.println("Having repository: " + result.getRepository().getDirectory()); - - FetchResult fetchResult = result.fetch() - .setRemote(REMOTE_URL) - .setRefSpecs("+refs/pull/6/head:pr_6") - //.setRefSpecs(new RefSpec("+refs/heads/*:refs/heads/*")) - .call(); - - System.out.println("Result when fetching the PR: " + fetchResult.getMessages()); - - Ref checkoutRef = result.checkout() - .setName("pr_6") - .call(); - - System.out.println("Checked out PR, now printing log, it should include two commits from the PR on top"); - - Iterable logs = result.log() - .call(); - for (RevCommit rev : logs) { - System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); - } - } - - // clean up here to not keep using more and more disk-space for these samples - FileUtils.deleteDirectory(localPath); - } - - private static class SimpleProgressMonitor implements ProgressMonitor { - @Override - public void start(int totalTasks) { - System.out.println("Starting work on " + totalTasks + " tasks"); - } - - @Override - public void beginTask(String title, int totalWork) { - System.out.println("Start " + title + ": " + totalWork); - } - - @Override - public void update(int completed) { - System.out.print(completed + "-"); - } - - @Override - public void endTask() { - System.out.println("Done"); - } - - @Override - public boolean isCancelled() { - return false; - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CleanUntrackedFiles.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CleanUntrackedFiles.java deleted file mode 100644 index de6305acbd..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CleanUntrackedFiles.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.File; -import java.io.IOException; -import java.util.Set; - -import org.apache.commons.io.FileUtils; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Repository; - -import com.jun.plugin.jgit.helper.CookbookHelper; - - - -/** - * Simple snippet which shows how to list all Tags - * - * @author dominik.stadler at gmx.at - */ -public class CleanUntrackedFiles { - - public static void main(String[] args) throws IOException, GitAPIException { - final File localPath; - try (Repository repository = CookbookHelper.createNewRepository()) { - localPath = repository.getWorkTree(); - - System.out.println("Repository at " + repository.getWorkTree()); - - File untrackedFile = File.createTempFile("untracked", ".txt", repository.getWorkTree()); - File untrackedDir = File.createTempFile("untrackedDir", "", repository.getWorkTree()); - if(!untrackedDir.delete()) { - throw new IOException("Could not delete file " + untrackedDir); - } - if(!untrackedDir.mkdirs()) { - throw new IOException("Could not create directory " + untrackedDir); - } - - System.out.println("Untracked exists: " + untrackedFile.exists() + " Dir: " + untrackedDir.exists() + "/" + untrackedDir.isDirectory()); - - try (Git git = new Git(repository)) { - Set removed = git.clean().setCleanDirectories(true).call(); - for(String item : removed) { - System.out.println("Removed: " + item); - } - System.out.println("Removed " + removed.size() + " items"); - } - - System.out.println("Untracked after: " + untrackedFile.exists() + " Dir: " + untrackedDir.exists() + "/" + untrackedDir.isDirectory()); - } - - // clean up here to not keep using more and more disk-space for these samples - FileUtils.deleteDirectory(localPath); - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CloneRemoteRepository.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CloneRemoteRepository.java deleted file mode 100644 index 8cdfeab524..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CloneRemoteRepository.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import org.apache.commons.io.FileUtils; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.ProgressMonitor; - -import java.io.File; -import java.io.IOException; - - -/** - * Simple snippet which shows how to clone a repository from a remote source - * - * @author dominik.stadler at gmx.at - */ -public class CloneRemoteRepository { - - private static final String REMOTE_URL = "https://github.com/github/testrepo.git"; - - public static void main(String[] args) throws IOException, GitAPIException { - // prepare a new folder for the cloned repository - File localPath = File.createTempFile("TestGitRepository", ""); - if(!localPath.delete()) { - throw new IOException("Could not delete temporary file " + localPath); - } - - // then clone - System.out.println("Cloning from " + REMOTE_URL + " to " + localPath); - try (Git result = Git.cloneRepository() - .setURI(REMOTE_URL) - .setDirectory(localPath) - .setProgressMonitor(new SimpleProgressMonitor()) - .call()) { - // Note: the call() returns an opened repository already which needs to be closed to avoid file handle leaks! - System.out.println("Having repository: " + result.getRepository().getDirectory()); - } - - // clean up here to not keep using more and more disk-space for these samples - FileUtils.deleteDirectory(localPath); - } - - private static class SimpleProgressMonitor implements ProgressMonitor { - @Override - public void start(int totalTasks) { - System.out.println("Starting work on " + totalTasks + " tasks"); - } - - @Override - public void beginTask(String title, int totalWork) { - System.out.println("Start " + title + ": " + totalWork); - } - - @Override - public void update(int completed) { - System.out.print(completed + "-"); - } - - @Override - public void endTask() { - System.out.println("Done"); - } - - @Override - public boolean isCancelled() { - return false; - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CloneRemoteRepositoryIntoMemoryAndReadFile.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CloneRemoteRepositoryIntoMemoryAndReadFile.java deleted file mode 100644 index a22348b615..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CloneRemoteRepositoryIntoMemoryAndReadFile.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.internal.storage.dfs.DfsRepositoryDescription; -import org.eclipse.jgit.internal.storage.dfs.InMemoryRepository; -import org.eclipse.jgit.lib.ObjectId; -import org.eclipse.jgit.lib.ObjectLoader; -import org.eclipse.jgit.revwalk.RevCommit; -import org.eclipse.jgit.revwalk.RevTree; -import org.eclipse.jgit.revwalk.RevWalk; -import org.eclipse.jgit.transport.RefSpec; -import org.eclipse.jgit.treewalk.TreeWalk; -import org.eclipse.jgit.treewalk.filter.PathFilter; - -import java.io.IOException; - -/** - * Copyright 2019 Vasyl Khrystiuk https://github.com/msangel - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * http://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -public class CloneRemoteRepositoryIntoMemoryAndReadFile { - private static final String REMOTE_URL = "https://github.com/github/testrepo.git"; - private static final String BRANCH = "master"; - private static final String FILE_TO_READ = "test/alias.c"; - - - public static void main(String[] args) throws IOException, GitAPIException { - DfsRepositoryDescription repoDesc = new DfsRepositoryDescription(); - InMemoryRepository repo = new InMemoryRepository(repoDesc); - Git git = new Git(repo); - git.fetch() - .setRemote(REMOTE_URL) - .setRefSpecs(new RefSpec("+refs/heads/*:refs/heads/*")) - .call(); - repo.getObjectDatabase(); - ObjectId lastCommitId = repo.resolve("refs/heads/" + BRANCH); - RevWalk revWalk = new RevWalk(repo); - RevCommit commit = revWalk.parseCommit(lastCommitId); - RevTree tree = commit.getTree(); - TreeWalk treeWalk = new TreeWalk(repo); - treeWalk.addTree(tree); - treeWalk.setRecursive(true); - treeWalk.setFilter(PathFilter.create(FILE_TO_READ)); - if (!treeWalk.next()) { - return; - } - ObjectId objectId = treeWalk.getObjectId(0); - ObjectLoader loader = repo.open(objectId); - loader.copyTo(System.out); - } - -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CloneRemoteRepositoryWithAuthentication.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CloneRemoteRepositoryWithAuthentication.java deleted file mode 100644 index 894689dc7f..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CloneRemoteRepositoryWithAuthentication.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -/* - Copyright 2015 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import org.apache.commons.io.FileUtils; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.errors.UnsupportedCredentialItem; -import org.eclipse.jgit.transport.CredentialItem; -import org.eclipse.jgit.transport.CredentialsProvider; -import org.eclipse.jgit.transport.URIish; - -import java.io.File; -import java.io.IOException; - - - -/** - * Simple snippet which shows how to clone a repository from a remote source - * via ssh protocol and username/password authentication. - * - * @author dominik.stadler at gmx.at - */ -public class CloneRemoteRepositoryWithAuthentication { - private static final String REMOTE_URL = "ssh://:@:22//"; - - public static void main(String[] args) throws IOException, GitAPIException { - // this is necessary when the remote host does not have a valid certificate, ideally we would install the certificate in the JVM - // instead of this unsecure workaround! - CredentialsProvider allowHosts = new CredentialsProvider() { - - @Override - public boolean supports(CredentialItem... items) { - for(CredentialItem item : items) { - if((item instanceof CredentialItem.YesNoType)) { - return true; - } - } - return false; - } - - @Override - public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem { - for(CredentialItem item : items) { - if(item instanceof CredentialItem.YesNoType) { - ((CredentialItem.YesNoType)item).setValue(true); - return true; - } - } - return false; - } - - @Override - public boolean isInteractive() { - return false; - } - }; - - // prepare a new folder for the cloned repository - File localPath = File.createTempFile("TestGitRepository", ""); - if(!localPath.delete()) { - throw new IOException("Could not delete temporary file " + localPath); - } - - // then clone - System.out.println("Cloning from " + REMOTE_URL + " to " + localPath); - try (Git result = Git.cloneRepository() - .setURI(REMOTE_URL) - .setDirectory(localPath) - .setCredentialsProvider(allowHosts) - .call()) { - // Note: the call() returns an opened repository already which needs to be closed to avoid file handle leaks! - System.out.println("Having repository: " + result.getRepository().getDirectory()); - } - - // clean up here to not keep using more and more disk-space for these samples - FileUtils.deleteDirectory(localPath); - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CollectGarbage.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CollectGarbage.java deleted file mode 100644 index 8e4e52d4f3..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CollectGarbage.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.IOException; -import java.util.Map; -import java.util.Properties; - -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.ProgressMonitor; -import org.eclipse.jgit.lib.Repository; - -import com.jun.plugin.jgit.helper.CookbookHelper; - - - -/** - * Simple snippet which shows how to execute the "gc" command to remove unused - * objects from the .git directory. - * - * @author dominik.stadler at gmx.at - */ -public class CollectGarbage { - - public static void main(String[] args) throws IOException, GitAPIException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - try (Git git = new Git(repository)) { - Properties ret = git.gc(). - setProgressMonitor(new PrintlnProgressMonitor()).call(); - for(Map.Entry entry : ret.entrySet()) { - System.out.println("Ret: " + entry.getKey() + ": " + entry.getValue()); - } - } - } - } - - private static class PrintlnProgressMonitor implements ProgressMonitor { - @Override - public void start(int totalTasks) { - System.out.println("Starting work on " + totalTasks + " tasks"); - } - - @Override - public void beginTask(String title, int totalWork) { - System.out.println("Start " + title + ": " + totalWork); - } - - @Override - public void update(int completed) { - System.out.print(completed); - } - - @Override - public void endTask() { - System.out.println("Done"); - } - - @Override - public boolean isCancelled() { - return false; - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CommitAll.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CommitAll.java deleted file mode 100644 index bdabc030da..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CommitAll.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; - -import org.apache.commons.io.FileUtils; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Repository; - -import com.jun.plugin.jgit.helper.CookbookHelper; - - - -/** - * Simple snippet which shows how to commit all files - * - * @author dominik.stadler@gmx.at - */ -public class CommitAll { - - public static void main(String[] args) throws IOException, GitAPIException { - final File localPath; - // prepare a new test-repository - try (Repository repository = CookbookHelper.createNewRepository()) { - localPath = repository.getWorkTree(); - - try (Git git = new Git(repository)) { - // create the file - File myFile = new File(repository.getDirectory().getParent(), "testfile"); - if(!myFile.createNewFile()) { - throw new IOException("Could not create file " + myFile); - } - - // Stage all files in the repo including new files, excluding deleted files - git.add().addFilepattern(".").call(); - - // Stage all changed files, including deleted files, excluding new files - git.add().addFilepattern(".").setUpdate(true).call(); - - // and then commit the changes. - git.commit() - .setMessage("Commit all changes including additions") - .call(); - - try(PrintWriter writer = new PrintWriter(myFile)) { - writer.append("Hello, world!"); - } - - // Stage all changed files, omitting new files, and commit with one command - git.commit() - .setAll(true) - .setMessage("Commit changes to all files") - .call(); - - - System.out.println("Committed all changes to repository at " + repository.getDirectory()); - } - } - - // clean up here to not keep using more and more disk-space for these samples - FileUtils.deleteDirectory(localPath); - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CommitFile.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CommitFile.java deleted file mode 100644 index 7a7ea93e5d..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CommitFile.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.File; -import java.io.IOException; - -import org.apache.commons.io.FileUtils; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Repository; - -import com.jun.plugin.jgit.helper.CookbookHelper; - - - -/** - * Simple snippet which shows how to commit a file - * - * @author dominik.stadler at gmx.at - */ -public class CommitFile { - - public static void main(String[] args) throws IOException, GitAPIException { - final File localPath; - // prepare a new test-repository - try (Repository repository = CookbookHelper.createNewRepository()) { - localPath = repository.getWorkTree(); - - try (Git git = new Git(repository)) { - // create the file - File myFile = new File(repository.getDirectory().getParent(), "testfile"); - if(!myFile.createNewFile()) { - throw new IOException("Could not create file " + myFile); - } - - // run the add - git.add() - .addFilepattern("testfile") - .call(); - - // and then commit the changes - git.commit() - .setMessage("Added testfile") - .call(); - - System.out.println("Committed file " + myFile + " to repository at " + repository.getDirectory()); - } - } - - // clean up here to not keep using more and more disk-space for these samples - FileUtils.deleteDirectory(localPath); - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CreateAndDeleteBranch.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CreateAndDeleteBranch.java deleted file mode 100644 index 595179b2ff..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CreateAndDeleteBranch.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.IOException; -import java.util.List; - -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; - -import com.jun.plugin.jgit.helper.CookbookHelper; - - - -/** - * Simple snippet which shows how to create and delete branches - * - * @author dominik.stadler at gmx.at - */ -public class CreateAndDeleteBranch { - - public static void main(String[] args) throws IOException, GitAPIException { - // prepare test-repository - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - try (Git git = new Git(repository)) { - List call = git.branchList().call(); - for (Ref ref : call) { - System.out.println("Branch-Before: " + ref + " " + ref.getName() + " " + ref.getObjectId().getName()); - } - - // make sure the branch is not there - List refs = git.branchList().call(); - for(Ref ref : refs) { - System.out.println("Had branch: " + ref.getName()); - if(ref.getName().equals("refs/heads/testbranch")) { - System.out.println("Removing branch before"); - git.branchDelete() - .setBranchNames("testbranch") - .setForce(true) - .call(); - - break; - } - } - - // run the add-call - git.branchCreate() - .setName("testbranch") - .call(); - - call = git.branchList().call(); - for (Ref ref : call) { - System.out.println("Branch-Created: " + ref + " " + ref.getName() + " " + ref.getObjectId().getName()); - } - - // run the delete-call - git.branchDelete() - .setBranchNames("testbranch") - .call(); - - call = git.branchList().call(); - for (Ref ref : call) { - System.out.println("Branch-After: " + ref + " " + ref.getName() + " " + ref.getObjectId().getName()); - } - - // run the add-call with a given starting point - git.branchCreate() - .setName("testbranch") - .setStartPoint("d52a1031cd359a5941d0e047aa7ab82053f7f7c3") - .call(); - - call = git.branchList().call(); - for (Ref ref : call) { - System.out.println("Branch-Created with starting point: " + ref + " " + ref.getName() + " " + ref.getObjectId().getName()); - } - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CreateAndDeleteTag.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CreateAndDeleteTag.java deleted file mode 100644 index 7be685d4e6..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CreateAndDeleteTag.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.IOException; - -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Constants; -import org.eclipse.jgit.lib.ObjectId; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; -import org.eclipse.jgit.revwalk.RevWalk; - -import com.jun.plugin.jgit.helper.CookbookHelper; - - - -/** - * Simple snippet which shows how to create a tag - * - * @author dominik.stadler at gmx.at - */ -public class CreateAndDeleteTag { - - public static void main(String[] args) throws IOException, GitAPIException { - // prepare test-repository - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - try (Git git = new Git(repository)) { - // remove the tag before creating it - git.tagDelete().setTags("tag_for_testing").call(); - - System.out.println("HEAD: " + git.getRepository().resolve(Constants.HEAD)); - - // set it on the current HEAD - Ref tag = git.tag().setName("tag_for_testing").call(); - System.out.println("Created/moved tag " + tag + - (tag.getPeeledObjectId() == null ? "" : ", peeled: " + tag.getPeeledObjectId().getName()) + - " to repository at " + repository.getDirectory()); - - // remove the tag again - git.tagDelete().setTags("tag_for_testing").call(); - - // read some other commit and set the tag on it - System.out.println(); - System.out.println("HEAD^: " + git.getRepository().resolve("HEAD^")); - ObjectId id = repository.resolve("HEAD^"); - try (RevWalk walk = new RevWalk(repository)) { - RevCommit commit = walk.parseCommit(id); - tag = git.tag().setObjectId(commit).setName("tag_for_testing").call(); - System.out.println("Created/moved tag " + tag + - (tag.getPeeledObjectId() == null ? "" : ", peeled: " + tag.getPeeledObjectId().getName()) + - " to repository at " + repository.getDirectory()); - - // remove the tag again - git.tagDelete().setTags("tag_for_testing").call(); - - // create an annotated tag - System.out.println(); - tag = git.tag().setName("tag_for_testing").setAnnotated(true).call(); - System.out.println("Created/moved tag " + tag + - (tag.getPeeledObjectId() == null ? "" : ", peeled: " + tag.getPeeledObjectId().getName()) + - " to repository at " + repository.getDirectory()); - - // remove the tag again - git.tagDelete().setTags("tag_for_testing").call(); - - walk.dispose(); - } - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CreateArchive.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CreateArchive.java deleted file mode 100644 index 5bc58cabe0..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CreateArchive.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -/* - * Copyright 2013, 2014 Dominik Stadler - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.commons.io.FileUtils; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.archive.ArchiveFormats; -import org.eclipse.jgit.lib.Repository; - -import com.jun.plugin.jgit.helper.CookbookHelper; - - - -/** - * Simple snippet which shows how to package the contents of a branch into an archive file - * using a format provided by the org.eclipse.jgit.archive jar. - * - * @author dominik.stadler at gmx.at - */ -public class CreateArchive { - public static void main(String[] args) throws IOException, GitAPIException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - // make the included archive formats known - ArchiveFormats.registerAll(); - try { - write(repository, ".zip", "zip"); - write(repository, ".tar.gz", "tgz"); - write(repository, ".tar.bz2", "tbz2"); - write(repository, ".tar.xz", "txz"); - } finally { - ArchiveFormats.unregisterAll(); - } - } - } - - private static void write(Repository repository, String suffix, String format) throws IOException, GitAPIException { - // this is the file that we write the archive to - File file = File.createTempFile("test", suffix); - try (OutputStream out = new FileOutputStream(file)) { - // finally call the ArchiveCommand to write out using the various supported formats - try (Git git = new Git(repository)) { - git.archive() - .setTree(repository.resolve("master")) - .setFormat(format) - .setOutputStream(out) - .call(); - } - } - - System.out.println("Wrote " + file.length() + " bytes to " + file); - - // clean up here to not keep using more and more disk-space for these samples - FileUtils.forceDelete(file); - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CreateCustomFormatArchive.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CreateCustomFormatArchive.java deleted file mode 100644 index 62b19513e1..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CreateCustomFormatArchive.java +++ /dev/null @@ -1,117 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -/* - * Copyright 2013, 2014 Dominik Stadler - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.Collections; -import java.util.Map; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - -import org.apache.commons.io.FileUtils; -import org.eclipse.jgit.api.ArchiveCommand; -import org.eclipse.jgit.api.ArchiveCommand.Format; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.FileMode; -import org.eclipse.jgit.lib.ObjectId; -import org.eclipse.jgit.lib.ObjectLoader; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; - -import com.jun.plugin.jgit.helper.CookbookHelper; - - -/** - * Simple snippet which shows how to package the contents of a branch into an archive file - * using a custom compression format. - * - * @author dominik.stadler at gmx.at - */ -public class CreateCustomFormatArchive { - - /** - * A simple custom format for Zip-files via ZipOutputStream, - * JGit only has one via commons-compress - */ - private static final class ZipArchiveFormat implements Format { - - @Override - public ZipOutputStream createArchiveOutputStream(OutputStream s) { - return new ZipOutputStream(s); - } - - @Override - public void putEntry(ZipOutputStream out, ObjectId tree, String path, FileMode mode, ObjectLoader loader) throws IOException { - // loader is null for directories... - if (loader != null) { - ZipEntry entry = new ZipEntry(path); - - if (tree instanceof RevCommit) { - long t = ((RevCommit) tree).getCommitTime() * 1000L; - entry.setTime(t); - } - - out.putNextEntry(entry); - out.write(loader.getBytes()); - out.closeEntry(); - } - } - - @Override - public Iterable suffixes() { - return Collections.singleton(".mzip"); - } - - @Override - public ZipOutputStream createArchiveOutputStream(OutputStream s, Map o) { - return new ZipOutputStream(s); - } - } - - public static void main(String[] args) throws IOException, GitAPIException { - File file = File.createTempFile("test", ".mzip"); - - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - // make the archive format known - ArchiveCommand.registerFormat("myzip", new ZipArchiveFormat()); - try { - // this is the file that we write the archive to - try (OutputStream out = new FileOutputStream(file)) { - // finally call the ArchiveCommand to write out using the given format - try (Git git = new Git(repository)) { - git.archive() - .setTree(repository.resolve("master")) - .setFormat("myzip") - .setOutputStream(out) - .call(); - } - } - } finally { - ArchiveCommand.unregisterFormat("myzip"); - } - - System.out.println("Wrote " + file.length() + " bytes to " + file); - } - - // clean up here to not keep using more and more disk-space for these samples - FileUtils.forceDelete(file); - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CreateListApplyAndDropStash.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CreateListApplyAndDropStash.java deleted file mode 100644 index aa77e8ccfc..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/CreateListApplyAndDropStash.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.File; -import java.io.IOException; -import java.util.Collection; - -import org.apache.commons.io.FileUtils; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.ObjectId; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; - -import com.jun.plugin.jgit.helper.CookbookHelper; - - - -/** - * Simple snippet which shows how to use commands for stashing changes. - * - * @author dominik.stadler at gmx.at - */ -public class CreateListApplyAndDropStash { - - public static void main(String[] args) throws IOException, GitAPIException { - final File localPath; - // prepare a new test-repository - try (Repository repository = CookbookHelper.createNewRepository()) { - localPath = repository.getWorkTree(); - - try (Git git = new Git(repository)) { - // create a file - File file1 = new File(repository.getDirectory().getParent(), "testfile"); - FileUtils.writeStringToFile(file1, "some text", "UTF-8"); - File file2 = new File(repository.getDirectory().getParent(), "testfile2"); - FileUtils.writeStringToFile(file2, "some text", "UTF-8"); - - // add and commit the file - git.add() - .addFilepattern("testfile") - .call(); - git.add() - .addFilepattern("testfile2") - .call(); - git.commit() - .setMessage("Added testfiles") - .call(); - - // then modify the file - FileUtils.writeStringToFile(file1, "some more text", "UTF-8", true); - - // push the changes to a new stash - RevCommit stash = git.stashCreate() - .call(); - - System.out.println("Created stash " + stash); - - // then modify the 2nd file - FileUtils.writeStringToFile(file2, "some more text", "UTF-8", true); - - // push the changes to a new stash - stash = git.stashCreate() - .call(); - - System.out.println("Created stash " + stash); - - // list the stashes - Collection stashes = git.stashList().call(); - for(RevCommit rev : stashes) { - System.out.println("Found stash: " + rev + ": " + rev.getFullMessage()); - } - - // drop the 1st stash without applying it - ObjectId call = git.stashDrop().setStashRef(0).call(); - System.out.println("StashDrop returned: " + call); - - ObjectId applied = git.stashApply().setStashRef(stash.getName()).call(); - System.out.println("Applied 2nd stash as: " + applied); - } - } - - // clean up here to not keep using more and more disk-space for these samples - FileUtils.deleteDirectory(localPath); - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/DiffFilesInCommit.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/DiffFilesInCommit.java deleted file mode 100644 index ff967697a1..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/DiffFilesInCommit.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.IOException; -import java.util.List; - -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.diff.DiffEntry; -import org.eclipse.jgit.lib.ObjectReader; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; -import org.eclipse.jgit.revwalk.RevTree; -import org.eclipse.jgit.revwalk.RevWalk; -import org.eclipse.jgit.treewalk.AbstractTreeIterator; -import org.eclipse.jgit.treewalk.CanonicalTreeParser; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -/** - * Simple snippet which shows how to retrieve the diffs - * between two commits - */ -public class DiffFilesInCommit { - - public static void main(String[] args) throws IOException, GitAPIException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - try (Git git = new Git(repository)) { - - // compare older commit with the newer one, showing an addition - // and 2 changes - listDiff(repository, git, - "3cc51d5cfd1dc3e890f9d6ded4698cb0d22e650e", - "19536fe5765ee79489265927a97cb0e19bb93e70"); - - // also the diffing the reverse works and now shows a delete - // instead of the added file - listDiff(repository, git, - "19536fe5765ee79489265927a97cb0e19bb93e70", - "3cc51d5cfd1dc3e890f9d6ded4698cb0d22e650e"); - - // to compare against the "previous" commit, you can use - // the caret-notation - listDiff(repository, git, - "19536fe5765ee79489265927a97cb0e19bb93e70^", - "19536fe5765ee79489265927a97cb0e19bb93e70"); - } - } - } - - private static void listDiff(Repository repository, Git git, String oldCommit, String newCommit) throws GitAPIException, IOException { - final List diffs = git.diff() - .setOldTree(prepareTreeParser(repository, oldCommit)) - .setNewTree(prepareTreeParser(repository, newCommit)) - .call(); - - System.out.println("Found: " + diffs.size() + " differences"); - for (DiffEntry diff : diffs) { - System.out.println("Diff: " + diff.getChangeType() + ": " + - (diff.getOldPath().equals(diff.getNewPath()) ? diff.getNewPath() : diff.getOldPath() + " -> " + diff.getNewPath())); - } - } - - private static AbstractTreeIterator prepareTreeParser(Repository repository, String objectId) throws IOException { - // from the commit we can build the tree which allows us to construct the TreeParser - //noinspection Duplicates - try (RevWalk walk = new RevWalk(repository)) { - RevCommit commit = walk.parseCommit(repository.resolve(objectId)); - RevTree tree = walk.parseTree(commit.getTree().getId()); - - CanonicalTreeParser treeParser = new CanonicalTreeParser(); - try (ObjectReader reader = repository.newObjectReader()) { - treeParser.reset(reader, tree.getId()); - } - - walk.dispose(); - - return treeParser; - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/DiffRenamedFile.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/DiffRenamedFile.java deleted file mode 100644 index b9b81a3bea..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/DiffRenamedFile.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -import java.io.IOException; -import java.util.List; - -import org.eclipse.jgit.annotations.NonNull; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.diff.DiffConfig; -import org.eclipse.jgit.diff.DiffEntry; -import org.eclipse.jgit.diff.DiffFormatter; -import org.eclipse.jgit.lib.Config; -import org.eclipse.jgit.lib.ObjectReader; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.FollowFilter; -import org.eclipse.jgit.revwalk.RevCommit; -import org.eclipse.jgit.revwalk.RevTree; -import org.eclipse.jgit.revwalk.RevWalk; -import org.eclipse.jgit.treewalk.AbstractTreeIterator; -import org.eclipse.jgit.treewalk.CanonicalTreeParser; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -// Simple example that shows how to diff a single file between two commits when -// the file may have been renamed. -public class DiffRenamedFile { - public static void main(String[] args) - throws IOException, GitAPIException { - try (Repository repo = CookbookHelper.openJGitCookbookRepository()) { - runDiff(repo, - "2e1d65e4cf6c5e267e109aa20fd68ae119fa5ec9", - "5a10bd6ee431e362facb03cfe763b9a3d9dfd02d", - "README.md"); - - // try the reverse as well - runDiff(repo, - "5a10bd6ee431e362facb03cfe763b9a3d9dfd02d", - "2e1d65e4cf6c5e267e109aa20fd68ae119fa5ec9", - "README.md"); - - // caret allows to specify "the previous commit" - runDiff(repo, - "7b2e6193a39726510ed9d0f66a779665d0e4ce23^", - "7b2e6193a39726510ed9d0f66a779665d0e4ce23", - "build.gradle"); - } - } - - private static void runDiff(Repository repo, String oldCommit, String newCommit, String path) throws IOException, GitAPIException { - // Diff README.md between two commits. The file is named README.md in - // the new commit (5a10bd6e), but was named "jgit-cookbook README.md" in - // the old commit (2e1d65e4). - DiffEntry diff = diffFile(repo, - oldCommit, - newCommit, - path); - - // Display the diff - System.out.println("Showing diff of " + path); - try (DiffFormatter formatter = new DiffFormatter(System.out)) { - formatter.setRepository(repo); - //noinspection ConstantConditions - formatter.format(diff); - } - } - - private static AbstractTreeIterator prepareTreeParser(Repository repository, String objectId) throws IOException { - // from the commit we can build the tree which allows us to construct the TreeParser - //noinspection Duplicates - try (RevWalk walk = new RevWalk(repository)) { - RevCommit commit = walk.parseCommit(repository.resolve(objectId)); - RevTree tree = walk.parseTree(commit.getTree().getId()); - - CanonicalTreeParser treeParser = new CanonicalTreeParser(); - try (ObjectReader reader = repository.newObjectReader()) { - treeParser.reset(reader, tree.getId()); - } - - walk.dispose(); - - return treeParser; - } - } - - private static @NonNull DiffEntry diffFile(Repository repo, String oldCommit, - String newCommit, String path) throws IOException, GitAPIException { - Config config = new Config(); - config.setBoolean("diff", null, "renames", true); - DiffConfig diffConfig = config.get(DiffConfig.KEY); - try (Git git = new Git(repo)) { - List diffList = git.diff(). - setOldTree(prepareTreeParser(repo, oldCommit)). - setNewTree(prepareTreeParser(repo, newCommit)). - setPathFilter(FollowFilter.create(path, diffConfig)). - call(); - if (diffList.size() == 0) - return null; - if (diffList.size() > 1) - throw new RuntimeException("invalid diff"); - return diffList.get(0); - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/FetchRemoteCommits.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/FetchRemoteCommits.java deleted file mode 100644 index 3ae9b18d1d..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/FetchRemoteCommits.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.IOException; - -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.transport.FetchResult; - -import com.jun.plugin.jgit.helper.CookbookHelper; - - - -/** - * Simple snippet which shows how to fetch commits from a remote Git repository - * - * @author dominik.stadler at gmx.at - */ -public class FetchRemoteCommits { - - public static void main(String[] args) throws IOException, GitAPIException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - System.out.println("Starting fetch"); - try (Git git = new Git(repository)) { - FetchResult result = git.fetch().setCheckFetchedObjects(true).call(); - System.out.println("Messages: " + result.getMessages()); - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/FetchRemoteCommitsWithPrune.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/FetchRemoteCommitsWithPrune.java deleted file mode 100644 index fa011507b1..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/FetchRemoteCommitsWithPrune.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -import java.io.File; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.IOException; -import java.util.List; - -import org.apache.commons.io.FileUtils; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.ListBranchCommand.ListMode; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.transport.FetchResult; - - - -/** - * Simple snippet which shows how to fetch commits from a remote Git repository - * - * @author dominik.stadler at gmx.at - */ -public class FetchRemoteCommitsWithPrune { - - private static final String REMOTE_URL = "https://github.com/github/testrepo.git"; - - public static void main(String[] args) throws IOException, GitAPIException, InterruptedException { - // prepare a new folder for the cloned repository - File localPath = File.createTempFile("TestGitRepository", ""); - if(!localPath.delete()) { - throw new IOException("Could not delete temporary file " + localPath); - } - - // then clone - System.out.println("Cloning from " + REMOTE_URL + " to " + localPath); - try (Git git = Git.cloneRepository() - .setURI(REMOTE_URL) - .setDirectory(localPath) - .call()) { - // Note: the call() returns an opened repository already which needs to be closed to avoid file handle leaks! - System.out.println("Having repository: " + git.getRepository().getDirectory()); - - System.out.println("Starting fetch"); - FetchResult result = git.fetch().setCheckFetchedObjects(true).call(); - System.out.println("Messages: " + result.getMessages()); - - // ensure master/HEAD are still there - System.out.println("Listing local branches:"); - List call = git.branchList().call(); - for (Ref ref : call) { - System.out.println("Branch: " + ref + " " + ref.getName() + " " + ref.getObjectId().getName()); - } - - System.out.println("Now including remote branches:"); - call = git.branchList().setListMode(ListMode.ALL).call(); - for (Ref ref : call) { - System.out.println("Branch: " + ref + " " + ref.getName() + " " + ref.getObjectId().getName()); - } - } - - // clean up here to not keep using more and more disk-space for these samples - try { - FileUtils.deleteDirectory(localPath); - } catch (IOException e) { - System.out.println("Retrying deleting path " + localPath + " once after catching exception"); - e.printStackTrace(); - - Thread.sleep(1000); - - FileUtils.deleteDirectory(localPath); - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/FetchRemoteCommitsWithSshAuth.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/FetchRemoteCommitsWithSshAuth.java deleted file mode 100644 index 66df69de40..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/FetchRemoteCommitsWithSshAuth.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -import com.jcraft.jsch.JSch; -import com.jcraft.jsch.JSchException; -import com.jcraft.jsch.Session; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.LsRemoteCommand; -import org.eclipse.jgit.api.TransportConfigCallback; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.transport.JschConfigSessionFactory; -import org.eclipse.jgit.transport.OpenSshConfig; -import org.eclipse.jgit.transport.SshSessionFactory; -import org.eclipse.jgit.transport.SshTransport; -import org.eclipse.jgit.transport.Transport; -import org.eclipse.jgit.util.FS; - -import java.util.Map; - -/** - * Simple snippet which shows how to fetch commits from a remote Git repository - * via ssh protocol authentication. - * - * You need to provide proper values for the URL of the Git repository and - * the location of the private key file - * - *

- * Created by zhengmaoshao on 2019/4/3 上午12:38 - */ -public class FetchRemoteCommitsWithSshAuth { - private static final String REMOTE_URL = "ssh://@:22//"; - private static final String PRIVATE_KEY = "/path/to/private_key"; - - public static void main(String[] args) throws GitAPIException { - - final SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() { - @Override - protected void configure(OpenSshConfig.Host host, Session session) { - } - - @Override - protected JSch createDefaultJSch(FS fs) throws JSchException { - JSch defaultJSch = super.createDefaultJSch(fs); - defaultJSch.addIdentity(PRIVATE_KEY); - return defaultJSch; - } - }; - - LsRemoteCommand lsRemoteCommand = Git.lsRemoteRepository(); - lsRemoteCommand.setRemote(REMOTE_URL); - lsRemoteCommand.setTransportConfigCallback(new TransportConfigCallback() - { - @Override - public void configure(Transport transport) { - SshTransport sshTransport = (SshTransport) transport; - sshTransport.setSshSessionFactory(sshSessionFactory); - } - }); - - final Map map = lsRemoteCommand.setHeads(true) - .setTags(true) - .callAsMap(); - - for (Map.Entry entry : map.entrySet()) { - System.out.println("Key: " + entry.getKey()/*eg.refs/heads/develop*/ + ", Ref: " + entry.getValue().getObjectId().getName()/*eg.e16c937848d5c1ad50ef163003c7b076103f7e37*/); - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/InitRepository.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/InitRepository.java deleted file mode 100644 index 4d88612e5c..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/InitRepository.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.File; -import java.io.IOException; - -import org.apache.commons.io.FileUtils; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.storage.file.FileRepositoryBuilder; - - - -/** - * Simple snippet which shows how to initialize a new repository - * - * @author dominik.stadler at gmx.at - */ -public class InitRepository { - - public static void main(String[] args) throws IOException, GitAPIException { - // run the init-call - File dir = File.createTempFile("gitinit", ".test"); - if(!dir.delete()) { - throw new IOException("Could not delete file " + dir); - } - - // The Git-object has a static method to initialize a new repository - try (Git git = Git.init() - .setDirectory(dir) - .call()) { - System.out.println("Created a new repository at " + git.getRepository().getDirectory()); - } - - // clean up here to not keep using more and more disk-space for these samples - FileUtils.deleteDirectory(dir); - - dir = File.createTempFile("repoinit", ".test"); - if(!dir.delete()) { - throw new IOException("Could not delete file " + dir); - } - - // you can also create a Repository-object directly from the - try (Repository repository = FileRepositoryBuilder.create(new File(dir.getAbsolutePath(), ".git"))) { - System.out.println("Created a new repository at " + repository.getDirectory()); - } - - // clean up here to not keep using more and more disk-space for these samples - FileUtils.deleteDirectory(dir); - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ListBranches.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ListBranches.java deleted file mode 100644 index f8ef8d0b7f..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ListBranches.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -/* - Copyright 2013, 2014, 2021 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.IOException; -import java.util.List; - -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.ListBranchCommand.ListMode; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -/** - * Simple snippet which shows how to list all Branches in a Git repository - * - * @author dominik.stadler at gmx.at - */ -public class ListBranches { - - public static void main(String[] args) throws IOException, GitAPIException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - try (Git git = new Git(repository)) { - System.out.println("Listing local branches:"); - List call = git.branchList().call(); - for (Ref ref : call) { - System.out.println("Branch: " + ref + " " + ref.getName() + " " + ref.getObjectId().getName()); - } - - System.out.println("Now including remote branches:"); - call = git.branchList().setListMode(ListMode.ALL).call(); - for (Ref ref : call) { - System.out.println("Branch: " + ref + " " + ref.getName() + " " + ref.getObjectId().getName()); - } - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ListNotes.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ListNotes.java deleted file mode 100644 index 5c50b99fe0..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ListNotes.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.IOException; -import java.util.List; - -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.ObjectLoader; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.notes.Note; - -import com.jun.plugin.jgit.helper.CookbookHelper; - - - -/** - * Simple snippet which shows how to load Notes in a Git repository - * - * @author dominik.stadler at gmx.at - */ -public class ListNotes { - - public static void main(String[] args) throws IOException, GitAPIException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - try (Git git = new Git(repository)) { - List call = git.notesList().call(); - System.out.println("Listing " + call.size() + " notes"); - for (Note note : call) { - System.out.println("Note: " + note + " " + note.getName() + " " + note.getData().getName() + "\nContent: "); - - // displaying the contents of the note is done via a simple blob-read - ObjectLoader loader = repository.open(note.getData()); - loader.copyTo(System.out); - } - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ListRemoteRepository.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ListRemoteRepository.java deleted file mode 100644 index a2b81f3a8b..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ListRemoteRepository.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Ref; - -import java.util.Collection; -import java.util.Map; - - -/** - * Simple snippet which shows how to list heads/tags of remote repositories without - * a local repository - * - * @author dominik.stadler at gmx.at - */ -public class ListRemoteRepository { - - private static final String REMOTE_URL = "https://github.com/github/testrepo.git"; - - public static void main(String[] args) throws GitAPIException { - // then clone - System.out.println("Listing remote repository " + REMOTE_URL); - Collection refs = Git.lsRemoteRepository() - .setHeads(true) - .setTags(true) - .setRemote(REMOTE_URL) - .call(); - - for (Ref ref : refs) { - System.out.println("Ref: " + ref); - } - - final Map map = Git.lsRemoteRepository() - .setHeads(true) - .setTags(true) - .setRemote(REMOTE_URL) - .callAsMap(); - - System.out.println("As map"); - for (Map.Entry entry : map.entrySet()) { - System.out.println("Key: " + entry.getKey() + ", Ref: " + entry.getValue()); - } - - refs = Git.lsRemoteRepository() - .setRemote(REMOTE_URL) - .call(); - - System.out.println("All refs"); - for (Ref ref : refs) { - System.out.println("Ref: " + ref); - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ListRemotes.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ListRemotes.java deleted file mode 100644 index 6431fc0db3..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ListRemotes.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.IOException; -import java.util.Collection; - -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -/** - * Snippet which shows how to iterate remotes, i.e. "git ls-remote" - * - * @author dominik.stadler at gmx.at - */ -public class ListRemotes { - - public static void main(String[] args) throws IOException, GitAPIException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - // all refs - try (Git git = new Git(repository)) { - Collection refs = git.lsRemote().call(); - for (Ref ref : refs) { - System.out.println("Ref: " + ref); - } - - // heads only - refs = git.lsRemote().setHeads(true).call(); - for (Ref ref : refs) { - System.out.println("Head: " + ref); - } - - // tags only - refs = git.lsRemote().setTags(true).call(); - for (Ref ref : refs) { - System.out.println("Remote tag: " + ref); - } - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ListTags.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ListTags.java deleted file mode 100644 index ef9701c323..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ListTags.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -/* - Copyright 2013, 2014, 2021 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.IOException; -import java.util.List; - -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.LogCommand; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -/** - * Simple snippet which shows how to list all Tags - * - * @author dominik.stadler at gmx.at - */ -public class ListTags { - - public static void main(String[] args) throws IOException, GitAPIException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - try (Git git = new Git(repository)) { - List call = git.tagList().call(); - for (Ref ref : call) { - System.out.println("Tag: " + ref + " " + ref.getName() + " " + ref.getObjectId().getName() + - (ref.getPeeledObjectId() == null ? "" : ", peeled: " + ref.getPeeledObjectId().getName())); - - // fetch all commits for this tag - LogCommand log = git.log(); - - Ref peeledRef = repository.getRefDatabase().peel(ref); - if(peeledRef.getPeeledObjectId() != null) { - log.add(peeledRef.getPeeledObjectId()); - } else { - log.add(ref.getObjectId()); - } - - Iterable logs = log.call(); - for (RevCommit rev : logs) { - System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); - } - } - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ListTagsOnBranch.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ListTagsOnBranch.java deleted file mode 100644 index 9706aba5b4..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ListTagsOnBranch.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -/* - Copyright 2021 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.ObjectId; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -/** - * A snippet which fetches all the tags of the repository and then walks - * commits on a given branch and prints out whenever a tag is found for - * a commit. - * - * I.e. it prints all tags that are applied to commits on the branch. - * - * @author dominik.stadler at gmx.at - */ -public class ListTagsOnBranch { - - private static final String BRANCH = "remotes/origin/master"; - - public static void main(String[] args) throws IOException, GitAPIException { - long start = System.currentTimeMillis(); - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - try (Git git = new Git(repository)) { - // create a map of commit-refs and corresponding list of tags - Map> tagsMap = git.tagList().call().stream() - .collect(Collectors.groupingBy(ref -> { - if (ref.getPeeledObjectId() == null) { - return ref.getObjectId(); - } else { - return ref.getPeeledObjectId(); - } - }, Collectors.mapping(ref -> ref, Collectors.toList()))); - - Iterable logs = git.log() - .add(repository.resolve(BRANCH)) - .call(); - int count = 0; - - for (RevCommit rev : logs) { - //System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); - count++; - - if (tagsMap.containsKey(rev.getId())) { - System.out.println("Found tags " + tagsMap.get(rev.getId()) + " for " + rev); - } - } - System.out.println("Had " + count + " commits overall on branch " + BRANCH - + ", iteration took " + (System.currentTimeMillis() - start) + "ms"); - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ListUncommittedChanges.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ListUncommittedChanges.java deleted file mode 100644 index d8aa212fa9..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ListUncommittedChanges.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.IOException; -import java.util.Map; -import java.util.Set; - -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.Status; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.IndexDiff.StageState; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -import org.eclipse.jgit.lib.Repository; - - - -/** - * Simple snippet which shows how to list various types of uncommitted changes - * of a Git repository - * - * @author dominik.stadler at gmx.at - */ -public class ListUncommittedChanges { - - public static void main(String[] args) throws IOException, GitAPIException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - System.out.println("Listing uncommitted changes:"); - try (Git git = new Git(repository)) { - Status status = git.status().call(); - Set conflicting = status.getConflicting(); - for(String conflict : conflicting) { - System.out.println("Conflicting: " + conflict); - } - - Set added = status.getAdded(); - for(String add : added) { - System.out.println("Added: " + add); - } - - Set changed = status.getChanged(); - for(String change : changed) { - System.out.println("Change: " + change); - } - - Set missing = status.getMissing(); - for(String miss : missing) { - System.out.println("Missing: " + miss); - } - - Set modified = status.getModified(); - for(String modify : modified) { - System.out.println("Modification: " + modify); - } - - Set removed = status.getRemoved(); - for(String remove : removed) { - System.out.println("Removed: " + remove); - } - - Set uncommittedChanges = status.getUncommittedChanges(); - for(String uncommitted : uncommittedChanges) { - System.out.println("Uncommitted: " + uncommitted); - } - - Set untracked = status.getUntracked(); - for(String untrack : untracked) { - System.out.println("Untracked: " + untrack); - } - - Set untrackedFolders = status.getUntrackedFolders(); - for(String untrack : untrackedFolders) { - System.out.println("Untracked Folder: " + untrack); - } - - Map conflictingStageState = status.getConflictingStageState(); - for(Map.Entry entry : conflictingStageState.entrySet()) { - System.out.println("ConflictingState: " + entry); - } - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/MergeChanges.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/MergeChanges.java deleted file mode 100644 index c1327cbb96..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/MergeChanges.java +++ /dev/null @@ -1,112 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -/* - Copyright 2017 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import org.apache.commons.io.FileUtils; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.MergeCommand; -import org.eclipse.jgit.api.MergeResult; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.ObjectId; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -import java.io.File; -import java.io.IOException; -import java.util.Arrays; -import java.util.Map; - -/** - * Snippet which shows how to merge changes from another branch. - */ -public class MergeChanges { - - public static void main(String[] args) throws IOException, GitAPIException { - final File localPath; - try (Repository repository = CookbookHelper.createNewRepository()) { - localPath = repository.getWorkTree(); - - try (Git git = new Git(repository)) { - // create some commit on master - createCommit(repository, git, "masterFile", "content12"); - - // create branch "changes" - Ref changes = git.branchCreate().setName("changes").call(); - System.out.println("Result of creating the branch: " + changes); - - // now start a change on master - createCommit(repository, git, "sharedFile", "content12"); - - // check out branch "changes" - Ref checkout = git.checkout().setName("changes").call(); - System.out.println("Result of checking out the branch: " + checkout); - - // create some commit on branch "changes", one of them conflicting with the change on master - createCommit(repository, git, "branchFile", "content98"); - createCommit(repository, git, "sharedFile", "content98"); - - // check out "master" - checkout = git.checkout().setName("master").call(); - System.out.println("Result of checking out master: " + checkout); - - // retrieve the objectId of the latest commit on branch - ObjectId mergeBase = repository.resolve("changes"); - - // perform the actual merge, here we disable FastForward to see the - // actual merge-commit even though the merge is trivial - MergeResult merge = git.merge(). - include(mergeBase). - setCommit(true). - setFastForward(MergeCommand.FastForwardMode.NO_FF). - //setSquash(false). - setMessage("Merged changes"). - call(); - System.out.println("Merge-Results for id: " + mergeBase + ": " + merge); - for (Map.Entry entry : merge.getConflicts().entrySet()) { - System.out.println("Key: " + entry.getKey()); - for(int[] arr : entry.getValue()) { - System.out.println("value: " + Arrays.toString(arr)); - } - } - } - - // clean up here to not keep using more and more disk-space for these samples - FileUtils.deleteDirectory(localPath); - } - } - - private static void createCommit(Repository repository, Git git, String fileName, String content) throws IOException, GitAPIException { - // create the file - File myFile = new File(repository.getDirectory().getParent(), fileName); - FileUtils.writeStringToFile(myFile, content, "UTF-8"); - - // run the add - git.add() - .addFilepattern(fileName) - .call(); - - // and then commit the changes - RevCommit revCommit = git.commit() - .setMessage("Added " + fileName) - .call(); - - System.out.println("Committed file " + myFile + " as " + revCommit + " to repository at " + repository.getDirectory()); - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/RebaseToOriginMaster.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/RebaseToOriginMaster.java deleted file mode 100644 index 3c58383b2f..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/RebaseToOriginMaster.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.IOException; -import java.util.List; - -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.RebaseCommand; -import org.eclipse.jgit.api.RebaseCommand.InteractiveHandler; -import org.eclipse.jgit.api.RebaseResult; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.errors.IllegalTodoFileModification; -import org.eclipse.jgit.lib.RebaseTodoLine; -import org.eclipse.jgit.lib.RebaseTodoLine.Action; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.lib.RepositoryState; - -/** - * Snippet which shows how to rebase local changes onto a remote branch. - * - * See also http://stackoverflow.com/questions/22945257/jgit-how-to-squash-commits - * - * @author dominik.stadler at gmx.at - */ -public class RebaseToOriginMaster { - - public static void main(String[] args) throws IOException, GitAPIException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - // all refs - try (Git git = new Git(repository)) { - InteractiveHandler handler = new InteractiveHandler() { - @Override - public void prepareSteps(List steps) { - // the handler receives the list of commits that are rebased, i.e. the ones on the local branch - for(RebaseTodoLine step : steps) { - // for each step, you can decide which action should be taken - // default is PICK - try { - // by selecting "EDIT", the rebase will stop and ask you to edit the commit-contents - step.setAction(Action.EDIT); - } catch (IllegalTodoFileModification e) { - throw new IllegalStateException(e); - } - } - } - - @Override - public String modifyCommitMessage(String oldMessage) { - return oldMessage; - } - }; - - RebaseResult result = git.rebase().setUpstream("origin/master").runInteractively(handler).call(); - System.out.println("Rebase had state: " + result.getStatus() + ": " + result.getConflicts()); - - // because of the "EDIT" in the InteractiveHandler, the rebase was stopped in-between - // now you can adjust the commit and continue rebasing with setOperation(RebaseCommand.Operation.CONTINUE) - // to use the local changes for the commit or setOperation(RebaseCommand.Operation.SKIP) to skip this - // commit (i.e. remove it from the branch!) - - if(!result.getStatus().isSuccessful() && - // sometimes the repository does not need aborting afterwards?! - repository.getRepositoryState() != RepositoryState.SAFE) { - // if rebasing stopped or failed, you can get back to the original state by running it with setOperation(RebaseCommand.Operation.ABORT) - result = git.rebase().setUpstream("origin/master").runInteractively(handler).setOperation(RebaseCommand.Operation.ABORT).call(); - System.out.println("Aborted reabse with state: " + result.getStatus() + ": " + result.getConflicts()); - } - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/RevertChanges.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/RevertChanges.java deleted file mode 100644 index de70c736b1..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/RevertChanges.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -import org.apache.commons.io.FileUtils; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Repository; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -import java.io.File; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardOpenOption; - -/** - * Simple snippet which shows how to set a modified tracked file back to its state - * in the most recent commit. This does not make a new commit that reverts a previous commit; - * this reverts a modified file back to its unmodified state (according to most recent commit) - * - * @author JordanMartinez - */ -public class RevertChanges { - - public static void main(String[] args) throws IOException, GitAPIException { - final File localPath; - try (Repository repository = CookbookHelper.createNewRepository()) { - localPath = repository.getWorkTree(); - - System.out.println("Listing local branches:"); - try (Git git = new Git(repository)) { - // set up a file - String fileName = "temptFile.txt"; - File tempFile = new File(repository.getDirectory().getParentFile(), fileName); - if(!tempFile.createNewFile()) { - throw new IOException("Could not create temporary file " + tempFile); - } - Path tempFilePath = tempFile.toPath(); - - // write some initial text to it - String initialText = "Initial Text"; - System.out.println("Writing text [" + initialText + "] to file [" + tempFile.toString() + "]"); - Files.write(tempFilePath, initialText.getBytes()); - - // add the file and commit it - git.add().addFilepattern(fileName).call(); - git.commit().setMessage("Added untracked file " + fileName + "to repo").call(); - - // modify the file - Files.write(tempFilePath, "Some modifications".getBytes(), StandardOpenOption.APPEND); - - // assert that file's text does not equal initialText - if (initialText.equals(getTextFromFilePath(tempFilePath))) { - throw new IllegalStateException("Modified file's text should not equal " + - "its original state after modification"); - } - - System.out.println("File now has text [" + getTextFromFilePath(tempFilePath) + "]"); - - // revert the changes - git.checkout().addPath(fileName).call(); - - // text should no longer have modifications - if (!initialText.equals(getTextFromFilePath(tempFilePath))) { - throw new IllegalStateException("Reverted file's text should equal its initial text"); - } - - System.out.println("File modifications were reverted. " + - "File now has text [" + getTextFromFilePath(tempFilePath) + "]"); - } - } - - // clean up here to not keep using more and more disk-space for these samples - FileUtils.deleteDirectory(localPath); - } - - private static String getTextFromFilePath(Path file) throws IOException { - byte[] bytes = Files.readAllBytes(file); - CharBuffer chars = Charset.defaultCharset().decode(ByteBuffer.wrap(bytes)); - return chars.toString(); - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/RevertCommit.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/RevertCommit.java deleted file mode 100644 index 265bb2ed17..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/RevertCommit.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -import java.io.File; -import java.io.IOException; - -import org.apache.commons.io.FileUtils; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.RevertCommand; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -/** - * Simple snippet which shows how to revert a previous commit - * - * @author JordanMartinez - */ -public class RevertCommit { - - public static void main(String[] args) throws IOException, GitAPIException { - final File path; - try (Repository repository = CookbookHelper.createNewRepository()) { - try (Git git = new Git(repository)) { - path = repository.getWorkTree(); - System.out.println("Repository at " + path); - - // Create a new file and add it to the index - File newFile = new File(path, "file1.txt"); - FileUtils.writeStringToFile(newFile, "Line 1\r\n", "UTF-8", true); - git.add().addFilepattern("file1.txt").call(); - RevCommit rev1 = git.commit().setAuthor("test", "test@test.com").setMessage("Commit Log 1").call(); - System.out.println("Rev1: " + rev1); - - // commit some changes - FileUtils.writeStringToFile(newFile, "Line 2\r\n", "UTF-8", true); - git.add().addFilepattern("file1.txt").call(); - RevCommit rev2 = git.commit().setAll(true).setAuthor("test", "test@test.com").setMessage("Commit Log 2").call(); - System.out.println("Rev2: " + rev2); - - // commit some changes - FileUtils.writeStringToFile(newFile, "Line 3\r\n", "UTF-8", true); - git.add().addFilepattern("file1.txt").call(); - RevCommit rev3 = git.commit().setAll(true).setAuthor("test", "test@test.com").setMessage("Commit Log 3").call(); - System.out.println("Rev3: " + rev3); - - // print logs - Iterable gitLog = git.log().call(); - for (RevCommit logMessage : gitLog) { - System.out.println("Before revert: " + logMessage.getName() + " - " + logMessage.getFullMessage()); - } - - RevertCommand revertCommand = git.revert(); - // revert to revision 2 - revertCommand.include(rev3); - RevCommit revCommit = revertCommand.call(); - System.out.println("Reverted: " + revCommit); - System.out.println("Reverted refs: " + revertCommand.getRevertedRefs()); - System.out.println("Unmerged paths: " + revertCommand.getUnmergedPaths()); - System.out.println("Failing results: " + revertCommand.getFailingResult()); - - // print logs - gitLog = git.log().call(); - for (RevCommit logMessage : gitLog) { - System.out.println("After revert: " + logMessage.getName() + " - " + logMessage.getFullMessage()); - } - - System.out.println("File contents: " + FileUtils.readFileToString(newFile, "UTF-8")); - } - } - - // clean up here to not keep using more and more disk-space for these samples - FileUtils.deleteDirectory(path); - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ShowBlame.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ShowBlame.java deleted file mode 100644 index 824a5d4d74..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ShowBlame.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -/* - Copyright 2013, 2014, 2017 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.FileInputStream; -import java.io.IOException; - -import org.apache.commons.io.IOUtils; -import org.eclipse.jgit.api.BlameCommand; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.blame.BlameResult; -import org.eclipse.jgit.lib.ObjectId; -import org.eclipse.jgit.lib.ObjectLoader; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; -import org.eclipse.jgit.revwalk.RevTree; -import org.eclipse.jgit.revwalk.RevWalk; -import org.eclipse.jgit.treewalk.TreeWalk; -import org.eclipse.jgit.treewalk.filter.PathFilter; - -import com.jun.plugin.jgit.helper.CookbookHelper; - - - -/** - * Simple snippet which shows how to get a diff showing who - * changed which line in a file. - * - * It uses HEAD~~ to select the version of README.md two commits ago - * and reads the blame information for it. - * - * Then it prints out the number of lines and the actual number of lines in the - * latest/local version of the file. - * - * @author dominik.stadler at gmx.at - */ -public class ShowBlame { - - public static void main(String[] args) throws IOException, GitAPIException { - // prepare a new test-repository - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - BlameCommand blamer = new BlameCommand(repository); - ObjectId commitID = repository.resolve("HEAD~~"); - blamer.setStartCommit(commitID); - blamer.setFilePath("README.md"); - BlameResult blame = blamer.call(); - - // read the number of lines from the given revision, this excludes changes from the last two commits due to the "~~" above - int lines = countLinesOfFileInCommit(repository, commitID, "README.md"); - for (int i = 0; i < lines; i++) { - RevCommit commit = blame.getSourceCommit(i); - System.out.println("Line: " + i + ": " + commit); - } - - final int currentLines; - try (final FileInputStream input = new FileInputStream("README.md")) { - currentLines = IOUtils.readLines(input, "UTF-8").size(); - } - - System.out.println("Displayed commits responsible for " + lines + " lines of README.md, current version has " + currentLines + " lines"); - } - } - - private static int countLinesOfFileInCommit(Repository repository, ObjectId commitID, String name) throws IOException { - try (RevWalk revWalk = new RevWalk(repository)) { - RevCommit commit = revWalk.parseCommit(commitID); - RevTree tree = commit.getTree(); - System.out.println("Having tree: " + tree); - - // now try to find a specific file - try (TreeWalk treeWalk = new TreeWalk(repository)) { - treeWalk.addTree(tree); - treeWalk.setRecursive(true); - treeWalk.setFilter(PathFilter.create(name)); - if (!treeWalk.next()) { - throw new IllegalStateException("Did not find expected file 'README.md'"); - } - - ObjectId objectId = treeWalk.getObjectId(0); - ObjectLoader loader = repository.open(objectId); - - // load the content of the file into a stream - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - loader.copyTo(stream); - - revWalk.dispose(); - - return IOUtils.readLines(new ByteArrayInputStream(stream.toByteArray()), "UTF-8").size(); - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ShowBranchDiff.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ShowBranchDiff.java deleted file mode 100644 index 78a9a71ed7..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ShowBranchDiff.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.diff.DiffEntry; -import org.eclipse.jgit.lib.ObjectReader; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; -import org.eclipse.jgit.revwalk.RevTree; -import org.eclipse.jgit.revwalk.RevWalk; -import org.eclipse.jgit.treewalk.AbstractTreeIterator; -import org.eclipse.jgit.treewalk.CanonicalTreeParser; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -import java.io.IOException; -import java.util.List; - - - -/** - * Simple snippet which shows how to show diffs between branches - * - * @author dominik.stadler at gmx.at - */ -public class ShowBranchDiff { - - public static void main(String[] args) throws IOException, GitAPIException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - try (Git git = new Git(repository)) { - if(repository.exactRef("refs/heads/testbranch") == null) { - // first we need to ensure that the remote branch is visible locally - Ref ref = git.branchCreate().setName("testbranch").setStartPoint("origin/testbranch").call(); - - System.out.println("Created local testbranch with ref: " + ref); - } - - // the diff works on TreeIterators, we prepare two for the two branches - AbstractTreeIterator oldTreeParser = prepareTreeParser(repository, "refs/heads/testbranch"); - AbstractTreeIterator newTreeParser = prepareTreeParser(repository, "refs/heads/master"); - - // then the procelain diff-command returns a list of diff entries - List diff = git.diff().setOldTree(oldTreeParser).setNewTree(newTreeParser).call(); - for (DiffEntry entry : diff) { - System.out.println("Entry: " + entry); - } - } - } - } - - private static AbstractTreeIterator prepareTreeParser(Repository repository, String ref) throws IOException { - // from the commit we can build the tree which allows us to construct the TreeParser - Ref head = repository.exactRef(ref); - try (RevWalk walk = new RevWalk(repository)) { - RevCommit commit = walk.parseCommit(head.getObjectId()); - RevTree tree = walk.parseTree(commit.getTree().getId()); - - CanonicalTreeParser treeParser = new CanonicalTreeParser(); - try (ObjectReader reader = repository.newObjectReader()) { - treeParser.reset(reader, tree.getId()); - } - - walk.dispose(); - - return treeParser; - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ShowChangedFilesBetweenCommits.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ShowChangedFilesBetweenCommits.java deleted file mode 100644 index 273125c6ed..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ShowChangedFilesBetweenCommits.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.IOException; -import java.util.List; - -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.diff.DiffEntry; -import org.eclipse.jgit.lib.ObjectId; -import org.eclipse.jgit.lib.ObjectReader; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.treewalk.CanonicalTreeParser; - -import com.jun.plugin.jgit.helper.CookbookHelper; - - - -/** - * Snippet which shows how to show diffs between two commits. - * - * @author dominik.stadler at gmx.at - */ -public class ShowChangedFilesBetweenCommits { - - public static void main(String[] args) throws IOException, GitAPIException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - // The {tree} will return the underlying tree-id instead of the commit-id itself! - // For a description of what the carets do see e.g. http://www.paulboxley.com/blog/2011/06/git-caret-and-tilde - // This means we are selecting the parent of the parent of the parent of the parent of current HEAD and - // take the tree-ish of it - ObjectId oldHead = repository.resolve("HEAD^^^^{tree}"); - ObjectId head = repository.resolve("HEAD^{tree}"); - - System.out.println("Printing diff between tree: " + oldHead + " and " + head); - - // prepare the two iterators to compute the diff between - try (ObjectReader reader = repository.newObjectReader()) { - CanonicalTreeParser oldTreeIter = new CanonicalTreeParser(); - oldTreeIter.reset(reader, oldHead); - CanonicalTreeParser newTreeIter = new CanonicalTreeParser(); - newTreeIter.reset(reader, head); - - // finally get the list of changed files - try (Git git = new Git(repository)) { - List diffs= git.diff() - .setNewTree(newTreeIter) - .setOldTree(oldTreeIter) - .call(); - for (DiffEntry entry : diffs) { - System.out.println("old: " + entry.getOldPath() + - ", new: " + entry.getNewPath() + - ", entry: " + entry); - } - } - } - } - - System.out.println("Done"); - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ShowFileDiff.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ShowFileDiff.java deleted file mode 100644 index 56fc572777..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ShowFileDiff.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.IOException; -import java.util.List; - -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.diff.DiffEntry; -import org.eclipse.jgit.diff.DiffFormatter; -import org.eclipse.jgit.lib.ObjectId; -import org.eclipse.jgit.lib.ObjectReader; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; -import org.eclipse.jgit.revwalk.RevTree; -import org.eclipse.jgit.revwalk.RevWalk; -import org.eclipse.jgit.treewalk.AbstractTreeIterator; -import org.eclipse.jgit.treewalk.CanonicalTreeParser; -import org.eclipse.jgit.treewalk.filter.PathFilter; - -import com.jun.plugin.jgit.helper.CookbookHelper; - - -/** - * Simple snippet which shows how to show diffs between branches - * - * @author dominik.stadler at gmx.at - */ -public class ShowFileDiff { - - public static void main(String[] args) throws IOException, GitAPIException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - // the diff works on TreeIterators, we prepare two for the two branches - AbstractTreeIterator oldTreeParser = prepareTreeParser(repository, "b97b184b0ce11c0b6a4dcc2b57768ff155cb696b"); - AbstractTreeIterator newTreeParser = prepareTreeParser(repository, "9e0719d7d773b41b49ebf04e6fd7b5c637e96063"); - - // then the porcelain diff-command returns a list of diff entries - try (Git git = new Git(repository)) { - List diff = git.diff(). - setOldTree(oldTreeParser). - setNewTree(newTreeParser). - setPathFilter(PathFilter.create("README.md")). - // to filter on Suffix use the following instead - //setPathFilter(PathSuffixFilter.create(".java")). - call(); - for (DiffEntry entry : diff) { - System.out.println("Entry: " + entry + ", from: " + entry.getOldId() + ", to: " + entry.getNewId()); - try (DiffFormatter formatter = new DiffFormatter(System.out)) { - formatter.setRepository(repository); - formatter.format(entry); - } - } - } - } - } - - private static AbstractTreeIterator prepareTreeParser(Repository repository, String objectId) throws IOException { - // from the commit we can build the tree which allows us to construct the TreeParser - //noinspection Duplicates - try (RevWalk walk = new RevWalk(repository)) { - RevCommit commit = walk.parseCommit(ObjectId.fromString(objectId)); - RevTree tree = walk.parseTree(commit.getTree().getId()); - - CanonicalTreeParser treeParser = new CanonicalTreeParser(); - try (ObjectReader reader = repository.newObjectReader()) { - treeParser.reset(reader, tree.getId()); - } - - walk.dispose(); - - return treeParser; - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ShowLog.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ShowLog.java deleted file mode 100644 index 083790d370..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ShowLog.java +++ /dev/null @@ -1,148 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.IOException; -import java.time.Instant; -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.util.Arrays; -import java.util.stream.Collectors; - -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; - -import com.jun.plugin.jgit.helper.CookbookHelper; - - - -/** - * Simple snippet which shows how to get the commit-ids for a file to provide log information. - * - * @author dominik.stadler at gmx.at - */ -public class ShowLog { - - @SuppressWarnings("unused") - public static void main(String[] args) throws IOException, GitAPIException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - try (Git git = new Git(repository)) { - Iterable logs = git.log() - .call(); - int count = 0; - for (RevCommit rev : logs) { - //System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); - count++; - } - System.out.println("Had " + count + " commits overall on current branch"); - - logs = git.log() - .add(repository.resolve("remotes/origin/testbranch")) - .call(); - count = 0; - for (RevCommit rev : logs) { - System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); - count++; - } - System.out.println("Had " + count + " commits overall on test-branch"); - - logs = git.log() - .not(repository.resolve("master")) - .add(repository.resolve("remotes/origin/testbranch")) - .call(); - count = 0; - for (RevCommit rev : logs) { - System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); - count++; - } - System.out.println("Had " + count + " commits only on test-branch"); - - logs = git.log() - .all() - .call(); - count = 0; - for (RevCommit rev : logs) { - //System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); - count++; - } - System.out.println("Had " + count + " commits overall in repository"); - - logs = git.log() - // for all log.all() - .addPath("README.md") - .call(); - count = 0; - for (RevCommit rev : logs) { - //System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); - count++; - } - System.out.println("Had " + count + " commits on README.md"); - - logs = git.log() - // for all log.all() - .addPath("pom.xml") - .call(); - count = 0; - for (RevCommit rev : logs) { - //System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); - count++; - } - System.out.println("Had " + count + " commits on pom.xml"); - - // then produce a "classic" Git commit log - // see also https://stackoverflow.com/a/69138290/411846 - System.out.println(); - logs = git.log() - .add(repository.resolve("remotes/origin/testbranch")) - .call(); - for (RevCommit rev : logs) { - System.out.println(getConventionalCommitMessage(rev)); - } - } - } - } - - private static String getConventionalCommitMessage(RevCommit commit) { - StringBuilder stringBuilder = new StringBuilder(); - - // Prepare the pieces - final String justTheAuthorNoTime = commit.getAuthorIdent().toExternalString().split(">")[0] + ">"; - final Instant commitInstant = Instant.ofEpochSecond(commit.getCommitTime()); - final ZoneId zoneId = commit.getAuthorIdent().getTimeZone().toZoneId(); - final ZonedDateTime authorDateTime = ZonedDateTime.ofInstant(commitInstant, zoneId); - final String gitDateTimeFormatString = "EEE MMM dd HH:mm:ss yyyy Z"; - final String formattedDate = authorDateTime.format(DateTimeFormatter.ofPattern(gitDateTimeFormatString)); - final String tabbedCommitMessage = - Arrays.stream(commit.getFullMessage() - .split("\\r?\\n")) // split it up by line - .map(s -> "\t" + s + "\n") // add a tab on each line - .collect(Collectors.joining()); // put it back together - - // Put pieces together - stringBuilder - .append("commit ").append(commit.getName()).append("\n") - .append("Author:\t").append(justTheAuthorNoTime).append("\n") - .append("Date:\t").append(formattedDate).append("\n\n") - .append(tabbedCommitMessage); - - return stringBuilder.toString(); - } - -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ShowStatus.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ShowStatus.java deleted file mode 100644 index e389c8247b..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/ShowStatus.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.IOException; - -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.Status; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Repository; - -import com.jun.plugin.jgit.helper.CookbookHelper; - - - -/** - * Simple snippet which prints the Status of a git repository, i.e. modified/added/ - * removed/ignored files, similar to "git status" - * - * @author dominik.stadler at gmx.at - */ -public class ShowStatus { - - public static void main(String[] args) throws IOException, GitAPIException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - try (Git git = new Git(repository)) { - Status status = git.status().call(); - System.out.println("Added: " + status.getAdded()); - System.out.println("Changed: " + status.getChanged()); - System.out.println("Conflicting: " + status.getConflicting()); - System.out.println("ConflictingStageState: " + status.getConflictingStageState()); - System.out.println("IgnoredNotInIndex: " + status.getIgnoredNotInIndex()); - System.out.println("Missing: " + status.getMissing()); - System.out.println("Modified: " + status.getModified()); - System.out.println("Removed: " + status.getRemoved()); - System.out.println("Untracked: " + status.getUntracked()); - System.out.println("UntrackedFolders: " + status.getUntrackedFolders()); - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/WalkAllCommits.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/WalkAllCommits.java deleted file mode 100644 index 21a539e815..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/porcelain/WalkAllCommits.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -import java.io.IOException; - -/** - * Simple snippet which shows how to use RevWalk to quickly iterate over all available commits, - * not just the ones on the current branch - */ -public class WalkAllCommits { - - public static void main(String[] args) throws IOException, GitAPIException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - try (Git git = new Git(repository)) { - // use the following instead to list commits on a specific branch - //ObjectId branchId = repository.resolve("HEAD"); - //Iterable commits = git.log().add(branchId).call(); - - Iterable commits = git.log().all().call(); - int count = 0; - for (RevCommit commit : commits) { - System.out.println("LogCommit: " + commit); - count++; - } - System.out.println(count); - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/unfinished/BrowseTree.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/unfinished/BrowseTree.java deleted file mode 100644 index 138d075f8b..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/unfinished/BrowseTree.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.jun.plugin.jgit.unfinished; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.IOException; - -import org.eclipse.jgit.lib.Constants; -import org.eclipse.jgit.lib.ObjectId; -import org.eclipse.jgit.lib.ObjectLoader; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevWalk; -import org.eclipse.jgit.treewalk.TreeWalk; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -/** - * Simple snippet which shows how to use RevWalk to iterate over items in a file-tree - * - * @author dominik.stadler at gmx.at - */ -public class BrowseTree { - - public static void main(String[] args) throws IOException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - ObjectId revId = repository.resolve(Constants.HEAD); - try (TreeWalk treeWalk = new TreeWalk(repository)) { - try (RevWalk revWalk = new RevWalk(repository)) { - treeWalk.addTree(revWalk.parseTree(revId)); - - while (treeWalk.next()) - { - System.out.println("---------------------------"); - System.out.append("name: ").println(treeWalk.getNameString()); - System.out.append("path: ").println(treeWalk.getPathString()); - - ObjectLoader loader = repository.open(treeWalk.getObjectId(0)); - - System.out.append("directory: ").println(loader.getType() - == Constants.OBJ_TREE); - System.out.append("size: ").println(loader.getSize()); - } - } - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/unfinished/ListChildrenOfCommit.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/unfinished/ListChildrenOfCommit.java deleted file mode 100644 index a2cfaff931..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/unfinished/ListChildrenOfCommit.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.jun.plugin.jgit.unfinished; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.IOException; - -import org.eclipse.jgit.lib.ObjectId; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revplot.PlotCommitList; -import org.eclipse.jgit.revplot.PlotLane; -import org.eclipse.jgit.revplot.PlotWalk; -import org.eclipse.jgit.revwalk.RevCommit; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -/** - * Note: This snippet is not done and likely does not show anything useful yet - * - * Snippet which shows how to use PlotWalk to read from a specific commit. - * - * @author dominik.stadler at gmx.at - */ -public class ListChildrenOfCommit { - - public static void main(String[] args) throws IOException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - try (PlotWalk revWalk = new PlotWalk(repository)) { - ObjectId rootId = repository.resolve("refs/heads/master"); - RevCommit root = revWalk.parseCommit(rootId); - revWalk.markStart(root); - PlotCommitList plotCommitList = new PlotCommitList<>(); - plotCommitList.source(revWalk); - plotCommitList.fillTo(Integer.MAX_VALUE); - - System.out.println("Printing children of commit " + root); - for (RevCommit com : revWalk) { - System.out.println("Child: " + com); - } - - System.out.println("Printing with next()"); - System.out.println("next: " + revWalk.next()); - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/unfinished/ListIndex.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/unfinished/ListIndex.java deleted file mode 100644 index cfdad4da37..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/unfinished/ListIndex.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.jun.plugin.jgit.unfinished; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.IOException; - -import org.eclipse.jgit.dircache.DirCache; -import org.eclipse.jgit.dircache.DirCacheEntry; -import org.eclipse.jgit.lib.Repository; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -/** - * Snippet which shows how to work with the Index - * - * @author dominik.stadler at gmx.at - */ -public class ListIndex { - - public static void main(String[] args) throws IOException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - // DirCache contains all files of the repository - DirCache index = DirCache.read(repository); - System.out.println("DirCache has " + index.getEntryCount() + " items"); - for (int i = 0; i < index.getEntryCount(); i++) { - // the number after the AnyObjectId is the "stage", see the constants in DirCacheEntry - System.out.println("Item " + i + ": " + index.getEntry(i)); - } - - // - System.out.println("Now printing staged items..."); - for (int i = 0; i < index.getEntryCount(); i++) { - DirCacheEntry entry = index.getEntry(i); - if (entry.getStage() != DirCacheEntry.STAGE_0) { - System.out.println("Item " + i + ": " + entry); - } - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/unfinished/ListRefLog.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/unfinished/ListRefLog.java deleted file mode 100644 index 1fada42fa6..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/unfinished/ListRefLog.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.jun.plugin.jgit.unfinished; - -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.ReflogEntry; -import org.eclipse.jgit.lib.Repository; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -import java.io.IOException; -import java.util.Collection; -import java.util.List; - - - -/** - * Note: This snippet is not done and likely does not show anything useful yet - * - * @author dominik.stadler at gmx.at - */ -public class ListRefLog { - - public static void main(String[] args) throws IOException, GitAPIException { - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - try (Git git = new Git(repository)) { - List refs = git.branchList().call(); - for (Ref ref : refs) { - System.out.println("Branch: " + ref + " " + ref.getName() + " " + ref.getObjectId().getName()); - - listReflog(repository, ref); - } - - List call = git.tagList().call(); - for (Ref ref : call) { - System.out.println("Tag: " + ref + " " + ref.getName() + " " + ref.getObjectId().getName()); - - listReflog(repository, ref); - } - } - } - } - - private static void listReflog(Repository repository, Ref ref) throws GitAPIException { - /* - * Ref head = repository.getRef(ref.getName()); - * RevWalk walk = new RevWalk(repository); - * RevCommit commit = walk.parseCommit(head.getObjectId()); - */ - - try (Git git = new Git(repository)) { - Collection call = git.reflog().setRef(ref.getName()).call(); - for (ReflogEntry reflog : call) { - System.out.println("Reflog: " + reflog); - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/unfinished/PullFromRemoteRepository.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/unfinished/PullFromRemoteRepository.java deleted file mode 100644 index d9e0c043a3..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/unfinished/PullFromRemoteRepository.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.jun.plugin.jgit.unfinished; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import org.apache.commons.io.FileUtils; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; - -import java.io.File; -import java.io.IOException; - - - -/** - * Note: This snippet is not done and likely does not show anything useful yet - * - * @author dominik.stadler at gmx.at - */ -public class PullFromRemoteRepository { - - private static final String REMOTE_URL = "https://github.com/github/testrepo.git"; - - public static void main(String[] args) throws IOException, GitAPIException { - // prepare a new folder for the cloned repository - File localPath = File.createTempFile("TestGitRepository", ""); - if(!localPath.delete()) { - throw new IOException("Could not delete temporary file " + localPath); - } - - // then clone - System.out.println("Cloning from " + REMOTE_URL + " to " + localPath); - try (Git result = Git.cloneRepository() - .setURI(REMOTE_URL) - .setDirectory(localPath) - .call()) { - // Note: the call() returns an opened repository already which needs to be closed to avoid file handle leaks! - System.out.println("Having repository: " + result.getRepository().getDirectory()); - try (Git git = new Git(result.getRepository())) { - git.pull() - .call(); - } - - System.out.println("Pulled from remote repository to local repository at " + result.getRepository().getDirectory()); - } - - // clean up here to not keep using more and more disk-space for these samples - FileUtils.deleteDirectory(localPath); - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/unfinished/PullRemoteRepository.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/unfinished/PullRemoteRepository.java deleted file mode 100644 index 6bf3eb4794..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/unfinished/PullRemoteRepository.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.jun.plugin.jgit.unfinished; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import org.apache.commons.io.FileUtils; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.PullResult; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Constants; -import org.eclipse.jgit.lib.Repository; - -import java.io.File; -import java.io.IOException; - - - -/** - * Note: This snippet is not done and likely does not show anything useful yet - * - * Simple snippet which shows how to pull from a remote repository from a remote source - * - * @author dominik.stadler at gmx.at - */ -public class PullRemoteRepository { - - private static final String REMOTE_URL = "https://github.com/github/testrepo.git"; - - public static void main(String[] args) throws IOException, GitAPIException { - final File localPath; - try (Repository repository = cloneRepository()) { - localPath = repository.getWorkTree(); - - System.out.println("Having repository: " + repository.getDirectory() + " with head: " + - repository.findRef(Constants.HEAD) + "/" + repository.resolve("HEAD") + "/" + - repository.resolve("refs/heads/master")); - - // TODO: why do we get null here for HEAD?!? See also - // http://stackoverflow.com/questions/17979660/jgit-pull-noheadexception - - try (Git git = new Git(repository)) { - PullResult call = git.pull().call(); - - System.out.println("Pulled from the remote repository: " + call); - } - } - - // clean up here to not keep using more and more disk-space for these samples - FileUtils.deleteDirectory(localPath); - } - - private static Repository cloneRepository() throws IOException, GitAPIException { - // prepare a new folder for the cloned repository - File localPath = File.createTempFile("TestGitRepository", ""); - if(!localPath.delete()) { - throw new IOException("Could not delete temporary file " + localPath); - } - - // then clone - System.out.println("Cloning from " + REMOTE_URL + " to " + localPath); - try (Git result = Git.cloneRepository() - .setURI(REMOTE_URL) - .setDirectory(localPath) - .call()) { - // Note: the call() returns an opened repository already which needs to be closed to avoid file handle leaks! - return result.getRepository(); - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/unfinished/PushToRemoteRepository.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/unfinished/PushToRemoteRepository.java deleted file mode 100644 index 86449ac1e4..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/unfinished/PushToRemoteRepository.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.jun.plugin.jgit.unfinished; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import org.apache.commons.io.FileUtils; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.storage.file.FileRepositoryBuilder; - -import java.io.File; -import java.io.IOException; - - - -/** - * Note: This snippet is not done and likely does not show anything useful yet - * - * @author dominik.stadler at gmx.at - */ -public class PushToRemoteRepository { - - private static final String REMOTE_URL = "https://github.com/github/testrepo.git"; - - public static void main(String[] args) throws IOException, GitAPIException { - // prepare a new folder for the cloned repository - File localPath = File.createTempFile("TestGitRepository", ""); - if(!localPath.delete()) { - throw new IOException("Could not delete temporary file " + localPath); - } - - // then clone - System.out.println("Cloning from " + REMOTE_URL + " to " + localPath); - try (Git result = Git.cloneRepository() - .setURI(REMOTE_URL) - .setDirectory(localPath) - .call()) { - // prepare a second folder for the 2nd clone - File localPath2 = File.createTempFile("TestGitRepository", ""); - if(!localPath2.delete()) { - throw new IOException("Could not delete temporary file " + localPath2); - } - - // then clone again - System.out.println("Cloning from file://" + localPath + " to " + localPath2); - try (Git result2 = Git.cloneRepository() - .setURI("file://" + localPath) - .setDirectory(localPath2) - .call()) { - System.out.println("Result: " + result2); - - // now open the created repository - FileRepositoryBuilder builder = new FileRepositoryBuilder(); - try (Repository repository = builder.setGitDir(localPath2) - .readEnvironment() // scan environment GIT_* variables - .findGitDir() // scan up the file system tree - .build()) { - try (Git git = new Git(repository)) { - git.push() - .call(); - } - - System.out.println("Pushed from repository: " + repository.getDirectory() + " to remote repository at " + REMOTE_URL); - } - } - } - - // clean up here to not keep using more and more disk-space for these samples - FileUtils.deleteDirectory(localPath); - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/unfinished/TestSubmodules.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/unfinished/TestSubmodules.java deleted file mode 100644 index 0e40101d88..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/unfinished/TestSubmodules.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.jun.plugin.jgit.unfinished; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.File; -import java.io.IOException; - -import org.apache.commons.io.FileUtils; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.storage.file.FileRepositoryBuilder; -import org.eclipse.jgit.submodule.SubmoduleWalk; - - -/** - * Note: This snippet is not done and likely does not show anything useful yet - * - * @author dominik.stadler at gmx.at - */ -public class TestSubmodules { - - public static void main(String[] args) throws IOException, GitAPIException { - File mainRepoDir = createRepository(); - - try (Repository mainRepo = openMainRepo(mainRepoDir)) { - addSubmodule(mainRepo); - - try (Repository subRepo = SubmoduleWalk.getSubmoduleRepository(mainRepo, "testrepo")) { - if (subRepo.isBare()) { - throw new IllegalStateException("Repository at " + subRepo.getDirectory() + " should not be bare"); - } - - System.out.println("Found submodule-repository at: " + subRepo.getDirectory().getAbsolutePath()); - } - } - - System.out.println("All done!"); - - // clean up here to not keep using more and more disk-space for these samples - FileUtils.deleteDirectory(mainRepoDir); - } - - private static void addSubmodule(Repository mainRepo) throws GitAPIException { - System.out.println("Adding submodule"); - try (Git git = new Git(mainRepo)) { - try (Repository subRepoInit = git.submoduleAdd(). - setURI("https://github.com/github/testrepo.git"). - setPath("testrepo"). - call()) { - if(subRepoInit.isBare()) { - throw new IllegalStateException("Repository at " + subRepoInit.getDirectory() + " should not be bare"); - } - } - } - } - - private static Repository openMainRepo(File mainRepoDir) throws IOException { - FileRepositoryBuilder builder = new FileRepositoryBuilder(); - - Repository mainRepo = builder.setGitDir(new File(mainRepoDir.getAbsolutePath(), ".git")) - .readEnvironment() // scan environment GIT_* variables - .findGitDir() // scan up the file system tree - .build(); - - if(mainRepo.isBare()) { - throw new IllegalStateException("Repository at " + mainRepoDir + " should not be bare"); - } - return mainRepo; - } - - private static File createRepository() throws IOException, GitAPIException { - File dir = File.createTempFile("gitinit", ".test"); - if(!dir.delete()) { - throw new IOException("Could not delete temporary file " + dir); - } - - Git.init() - .setDirectory(dir) - .call(); - - try (Repository repository = FileRepositoryBuilder.create(new File(dir.getAbsolutePath(), ".git"))) { - System.out.println("Created a new repository at " + repository.getDirectory()); - } - - return dir; - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/unfinished/TrackMaster.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/unfinished/TrackMaster.java deleted file mode 100644 index 23f164afa3..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/unfinished/TrackMaster.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.jun.plugin.jgit.unfinished; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import org.apache.commons.io.FileUtils; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.storage.file.FileRepositoryBuilder; - -import java.io.File; -import java.io.IOException; - - - -/** - * Note: This snippet is not done and likely does not show anything useful yet - * - * @author dominik.stadler at gmx.at - */ -public class TrackMaster { - - private static final String REMOTE_URL = "https://github.com/github/testrepo.git"; - - public static void main(String[] args) throws IOException, GitAPIException { - // prepare a new folder for the cloned repository - File localPath = File.createTempFile("TestGitRepository", ""); - if(!localPath.delete()) { - throw new IOException("Could not delete temporary file " + localPath); - } - - // then clone - System.out.println("Cloning from " + REMOTE_URL + " to " + localPath); - try (Git result = Git.cloneRepository() - .setURI(REMOTE_URL) - .setDirectory(localPath) - .call()) { - System.out.println("Result: " + result); - - // now open the created repository - FileRepositoryBuilder builder = new FileRepositoryBuilder(); - try (Repository repository = builder.setGitDir(localPath) - .readEnvironment() // scan environment GIT_* variables - .findGitDir() // scan up the file system tree - .build()) { - try (Git git = new Git(repository)) { - git.branchCreate() - .setName("master") - // ?!? .setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM) - .setStartPoint("origin/master") - .setForce(true) - .call(); - } - - System.out.println("Now tracking master in repository at " + repository.getDirectory() + " from origin/master at " + - REMOTE_URL); - } - } - - // clean up here to not keep using more and more disk-space for these samples - FileUtils.deleteDirectory(localPath); - } -} diff --git a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/unfinished/UpdateIndex.java b/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/unfinished/UpdateIndex.java deleted file mode 100644 index 669bce2358..0000000000 --- a/jun_java_plugins/jun_jgit/src/main/java/com/jun/plugin/jgit/unfinished/UpdateIndex.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.jun.plugin.jgit.unfinished; - -/* - Copyright 2013, 2014 Dominik Stadler - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.File; -import java.io.IOException; -import java.util.Date; -import java.util.Set; - -import org.apache.commons.io.FileUtils; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.GitCommand; -import org.eclipse.jgit.api.Status; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.api.errors.JGitInternalException; -import org.eclipse.jgit.dircache.DirCache; -import org.eclipse.jgit.dircache.DirCacheEntry; -import org.eclipse.jgit.errors.NoWorkTreeException; -import org.eclipse.jgit.lib.Repository; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -/** - * Note: This snippet is not done and likely does not show anything useful yet - * - * Snippet which shows how to mark files as assumed-unchanged (git update-index --assume-unchanged) - */ -public class UpdateIndex { - - public static void main(String[] args) throws IOException, GitAPIException { - try (final Repository repo = CookbookHelper.openJGitCookbookRepository()) { - try (final Git git = new Git(repo)) { - final String testFile = "README.md"; - - // Modify the file - FileUtils.write(new File(testFile), new Date().toString(), "UTF-8"); - System.out.println("Modified files: " + getModifiedFiles(git)); - - new AssumeChangedCommand(repo, testFile, true).call(); - System.out.println("Modified files after assume-changed: " + getModifiedFiles(git)); - - new AssumeChangedCommand(repo, testFile, false).call(); - System.out.println("Modified files after no-assume-changed: " + getModifiedFiles(git)); - - git.checkout().addPath(testFile).call(); - System.out.println("Modified files after reset: " + getModifiedFiles(git)); - } - } - } - - private static Set getModifiedFiles(Git git) throws NoWorkTreeException, GitAPIException { - Status status = git.status().call(); - return status.getModified(); - } - - private static class AssumeChangedCommand extends GitCommand { - private final String fileName; - private final boolean assumeUnchanged; - - AssumeChangedCommand(Repository repository, String fileName, boolean assumedUnchanged) { - super(repository); - - this.fileName = fileName; - this.assumeUnchanged = assumedUnchanged; - } - - @Override - public String call() throws GitAPIException { - try { - DirCache index = repo.lockDirCache(); - DirCacheEntry entry = index.getEntry(fileName); - - if (entry != null) { - entry.setAssumeValid(assumeUnchanged); - index.write(); - index.commit(); - return entry.getPathString(); - } - } catch (IOException e) { - throw new JGitInternalException(e.getMessage(), e); - } - - return null; - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/test/java/com/jun/plugin/jgit/JGitBugTest.java b/jun_java_plugins/jun_jgit/src/test/java/com/jun/plugin/jgit/JGitBugTest.java deleted file mode 100644 index 4eea185870..0000000000 --- a/jun_java_plugins/jun_jgit/src/test/java/com/jun/plugin/jgit/JGitBugTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.jun.plugin.jgit; - -import org.eclipse.jgit.lib.ObjectLoader; -import org.eclipse.jgit.lib.ObjectReader; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevWalk; -import org.junit.Test; - -import com.jun.plugin.jgit.helper.CookbookHelper; - -import java.io.IOException; - -import static org.junit.Assert.assertNotNull; - -/** - * Tests which show issues with JGit that we reported upstream. - */ -public class JGitBugTest { - @Test - public void testRevWalkDisposeClosesReader() throws IOException { - try (Repository repo = CookbookHelper.openJGitCookbookRepository()) { - try (ObjectReader reader = repo.newObjectReader()) { - assertNotNull("Need to get back an ObjectReader", reader); - try (RevWalk walk = new RevWalk(reader)) { - walk.dispose(); - - Ref head = repo.exactRef("refs/heads/master"); - System.out.println("Found head: " + head); - assertNotNull("Need to find head on master-branch", head); - - ObjectLoader loader = reader.open(head.getObjectId()); - assertNotNull(loader); - } - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/test/java/com/jun/plugin/jgit/api/ApiTest.java b/jun_java_plugins/jun_jgit/src/test/java/com/jun/plugin/jgit/api/ApiTest.java deleted file mode 100644 index 959bd4fea2..0000000000 --- a/jun_java_plugins/jun_jgit/src/test/java/com/jun/plugin/jgit/api/ApiTest.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.jun.plugin.jgit.api; - -import static org.junit.Assert.assertNotNull; - -import java.io.IOException; - -import org.eclipse.jgit.lib.ObjectId; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; -import org.eclipse.jgit.revwalk.RevWalk; -import org.junit.Test; - -import com.jun.plugin.jgit.api.CheckMergeStatusOfCommit; -import com.jun.plugin.jgit.api.GetCommitMessage; -import com.jun.plugin.jgit.api.GetFileAttributes; -import com.jun.plugin.jgit.api.GetRefFromName; -import com.jun.plugin.jgit.api.GetRevCommitFromObjectId; -import com.jun.plugin.jgit.api.GetRevTreeFromObjectId; -import com.jun.plugin.jgit.api.PrintRemotes; -import com.jun.plugin.jgit.api.ReadBlobContents; -import com.jun.plugin.jgit.api.ReadFileFromCommit; -import com.jun.plugin.jgit.api.ReadTagFromName; -import com.jun.plugin.jgit.api.ReadUserConfig; -import com.jun.plugin.jgit.api.ResolveRef; -import com.jun.plugin.jgit.api.ShowBranchTrackingStatus; -import com.jun.plugin.jgit.api.WalkAllCommits; -import com.jun.plugin.jgit.api.WalkFromToRev; -import com.jun.plugin.jgit.api.WalkRev; -import com.jun.plugin.jgit.api.WalkTreeNonRecursive; -import com.jun.plugin.jgit.api.WalkTreeRecursive; -import com.jun.plugin.jgit.helper.CookbookHelper; - - -public class ApiTest { - @Test - public void runSamples() throws Exception { - // simply call all the samples to see any severe problems with the samples - CheckMergeStatusOfCommit.main(null); - GetCommitMessage.main(null); - GetFileAttributes.main(null); - GetRefFromName.main(null); - GetRevCommitFromObjectId.main(null); - GetRevTreeFromObjectId.main(null); - PrintRemotes.main(null); - ReadBlobContents.main(null); - ReadFileFromCommit.main(null); - ReadTagFromName.main(null); - ReadUserConfig.main(null); - ResolveRef.main(null); - ShowBranchTrackingStatus.main(null); - WalkAllCommits.main(null); - WalkRev.main(null); - WalkFromToRev.main(null); - WalkTreeNonRecursive.main(null); - WalkTreeRecursive.main(null); - } - - @Test - public void testFailure() throws IOException { - // perform a specific check for things that seem to fail in github/travis checking - try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { - try (RevWalk revWalk = new RevWalk( repository )) { - ObjectId resolve = repository.resolve( "refs/heads/master" ); - assertNotNull("Did not find refs/heads/master", resolve); - - RevCommit masterHead = revWalk.parseCommit( resolve); - - // first a commit that was merged - ObjectId id = repository.resolve("05d18a76875716fbdbd2c200091b40caa06c713d"); - System.out.println("Had id: " + id); - assertNotNull("Did not find specific commit", resolve); - - RevCommit otherHead = revWalk.parseCommit( id ); - if( revWalk.isMergedInto( otherHead, masterHead ) ) { - System.out.println("Commit " + otherHead + " is merged into master"); - } else { - System.out.println("Commit " + otherHead + " is NOT merged into master"); - } - } - } - } -} diff --git a/jun_java_plugins/jun_jgit/src/test/java/com/jun/plugin/jgit/porcelain/PorcelainTest.java b/jun_java_plugins/jun_jgit/src/test/java/com/jun/plugin/jgit/porcelain/PorcelainTest.java deleted file mode 100644 index 2806b6d6e4..0000000000 --- a/jun_java_plugins/jun_jgit/src/test/java/com/jun/plugin/jgit/porcelain/PorcelainTest.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.jun.plugin.jgit.porcelain; - -import org.junit.Test; - -import com.jun.plugin.jgit.porcelain.AddAndListNoteOfCommit; -import com.jun.plugin.jgit.porcelain.AddFile; -import com.jun.plugin.jgit.porcelain.BlameFile; -import com.jun.plugin.jgit.porcelain.CheckoutGitHubPullRequest; -import com.jun.plugin.jgit.porcelain.CleanUntrackedFiles; -import com.jun.plugin.jgit.porcelain.CloneRemoteRepository; -import com.jun.plugin.jgit.porcelain.CommitAll; -import com.jun.plugin.jgit.porcelain.CommitFile; -import com.jun.plugin.jgit.porcelain.CreateAndDeleteBranch; -import com.jun.plugin.jgit.porcelain.CreateAndDeleteTag; -import com.jun.plugin.jgit.porcelain.CreateArchive; -import com.jun.plugin.jgit.porcelain.CreateCustomFormatArchive; -import com.jun.plugin.jgit.porcelain.CreateListApplyAndDropStash; -import com.jun.plugin.jgit.porcelain.DiffFilesInCommit; -import com.jun.plugin.jgit.porcelain.DiffRenamedFile; -import com.jun.plugin.jgit.porcelain.FetchRemoteCommits; -import com.jun.plugin.jgit.porcelain.FetchRemoteCommitsWithPrune; -import com.jun.plugin.jgit.porcelain.InitRepository; -import com.jun.plugin.jgit.porcelain.ListBranches; -import com.jun.plugin.jgit.porcelain.ListNotes; -import com.jun.plugin.jgit.porcelain.ListRemoteRepository; -import com.jun.plugin.jgit.porcelain.ListRemotes; -import com.jun.plugin.jgit.porcelain.ListTags; -import com.jun.plugin.jgit.porcelain.ListUncommittedChanges; -import com.jun.plugin.jgit.porcelain.MergeChanges; -import com.jun.plugin.jgit.porcelain.RebaseToOriginMaster; -import com.jun.plugin.jgit.porcelain.RevertChanges; -import com.jun.plugin.jgit.porcelain.RevertCommit; -import com.jun.plugin.jgit.porcelain.ShowBlame; -import com.jun.plugin.jgit.porcelain.ShowBranchDiff; -import com.jun.plugin.jgit.porcelain.ShowChangedFilesBetweenCommits; -import com.jun.plugin.jgit.porcelain.ShowFileDiff; -import com.jun.plugin.jgit.porcelain.ShowLog; -import com.jun.plugin.jgit.porcelain.ShowStatus; -import com.jun.plugin.jgit.porcelain.WalkAllCommits; - - -public class PorcelainTest { - @Test - public void runSamples() throws Exception { - // simply call all the samples to see any severe problems with the samples - AddAndListNoteOfCommit.main(null); - AddFile.main(null); - BlameFile.main(null); - CheckoutGitHubPullRequest.main(null); - CleanUntrackedFiles.main(null); - CloneRemoteRepository.main(null); - // does not run without changes: CloneRemoteRepositoryWithAuthentication.main(null); - // TODO: sometimes fails because there are still files open?!: CollectGarbage.main(null); - CommitAll.main(null); - CommitFile.main(null); - CreateAndDeleteBranch.main(null); - CreateAndDeleteTag.main(null); - CreateArchive.main(null); - CreateCustomFormatArchive.main(null); - CreateListApplyAndDropStash.main(null); - DiffFilesInCommit.main(null); - DiffRenamedFile.main(null); - FetchRemoteCommits.main(null); - FetchRemoteCommitsWithPrune.main(null); - InitRepository.main(null); - ListBranches.main(null); - ListNotes.main(null); - ListRemoteRepository.main(null); - ListRemotes.main(null); - ListTags.main(null); - ListUncommittedChanges.main(null); - MergeChanges.main(null); - RebaseToOriginMaster.main(null); - RevertChanges.main(null); - RevertCommit.main(null); - ShowBlame.main(null); - ShowBranchDiff.main(null); - ShowChangedFilesBetweenCommits.main(null); - ShowFileDiff.main(null); - ShowLog.main(null); - ShowStatus.main(null); - WalkAllCommits.main(null); - } -} diff --git a/jun_java_plugins/jun_json/pom.xml b/jun_java_plugins/jun_json/pom.xml deleted file mode 100644 index 9708cc14bd..0000000000 --- a/jun_java_plugins/jun_json/pom.xml +++ /dev/null @@ -1,63 +0,0 @@ - - 4.0.0 - io.github.wujun728 - jun_json - 1.0 - - - - junit - junit - 4.10 - test - - - - - net.sf.json-lib - json-lib - 2.4 - jdk15 - - - cn.hutool - hutool-all - 5.8.41 - - - com.alibaba.fastjson2 - fastjson2 - 2.0.57 - - - com.google.code.gson - gson - 2.10.1 - - - com.fasterxml.jackson.core - jackson-core - 2.19.2 - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.1 - - 8 - 8 - UTF-8 - - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_json/src/main/java/com/jun/plugin/json/json_lib/JsonUtil.java b/jun_java_plugins/jun_json/src/main/java/com/jun/plugin/json/json_lib/JsonUtil.java deleted file mode 100644 index 3200c724f4..0000000000 --- a/jun_java_plugins/jun_json/src/main/java/com/jun/plugin/json/json_lib/JsonUtil.java +++ /dev/null @@ -1,291 +0,0 @@ -package com.jun.plugin.json.json_lib; - -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import net.sf.json.JSONArray; -import net.sf.json.JSONObject; -import net.sf.json.JsonConfig; -import net.sf.json.util.PropertyFilter; - -public class JsonUtil { - - private static String top = "{"; - private static String top_ = "}"; - - public JsonUtil() { - } - - public static String getJsonByList(List dList) { - String data = ""; - if (dList != null) { - JSONArray ja = JSONArray.fromObject(dList); - data = ja.toString(); - } - return data; - } - - public static String getObjectJsonData(HashMap params) { - StringBuffer data = new StringBuffer(); - int i = 0; - if (params != null) { - data.append(top); - for (Iterator it = params.entrySet().iterator(); it.hasNext();) { - java.util.Map.Entry element = (java.util.Map.Entry) it.next(); - String key = (String) element.getKey(); - List dList = (ArrayList) element.getValue(); - if (i > 0) - data.append(","); - data.append((new StringBuilder()).append("\"").append(key).append("\"").append(":").toString()); - data.append(getJsonByList(dList)); - i++; - } - - data.append(top_); - } - return data.toString(); - } - - public static String getExtGridJsonData(List dList) { - StringBuffer data = new StringBuffer(); - if (dList != null) { - data.append((new StringBuilder()).append("{\"totalCount\":").append(dList.size()).append(", \"Body\":") - .toString()); - data.append(getJsonByList(dList)); - data.append("}"); - } - return data.toString(); - } - - public static String getGridJsonData(int rowNumber, List dList) { - StringBuffer data = new StringBuffer(); - if (dList != null) { - data.append((new StringBuilder()).append("{\"totalCount\":").append(rowNumber).append(", \"Body\":") - .toString()); - data.append(getJsonByList(dList)); - data.append("}"); - } - return data.toString(); - } - - public static String getDefineJsonData(String firstParam, String listParam, String firstValue, List dList) { - StringBuffer data = new StringBuffer(); - if (dList != null) { - data.append((new StringBuilder()).append("{\"").append(firstParam).append("\":").append(firstValue) - .append(", \"").append(listParam).append("\":").toString()); - data.append(getJsonByList(dList)); - data.append("}"); - } - return data.toString(); - } - - public static String getBasetJsonData(List dList) { - StringBuffer data = new StringBuffer(); - if (dList != null) { - JSONArray ja = JSONArray.fromObject(dList); - data.append(ja.toString()); - } - return data.toString(); - } - - public static String getEasyUIJsonData(List dList) { - StringBuffer data = new StringBuffer(); - if (dList != null) - if (dList.size() > 0) { - String total = ((Map) dList.get(0)).get("IRECCOUNT").toString(); - data.append((new StringBuilder()).append("{\"total\": ").append(total).append(", \"rows\": ") - .append(getJsonByList(dList)).append("}").toString()); - } else { - data.append("{\"total\": 0, \"rows\": []}"); - } - System.out.println("json=" + data.toString()); - return data.toString(); - } - - public static String getEasyUIJsonDataV2(List dList, String total) { - StringBuffer data = new StringBuffer(); - if (dList != null) - if (dList.size() > 0) { - // String total = - // StringUtil.toString(((Map)dList.get(0)).get("IRECCOUNT")); - data.append((new StringBuilder()).append("{\"total\": ").append(total).append(", \"rows\": ") - .append(getJsonByList(dList)).append("}").toString()); - } else { - data.append("{\"total\": 0, \"rows\": []}"); - } - System.out.println("total=" + total + "json=" + data.toString()); - return data.toString(); - } - - public static String getJsonDataByObject(Object obj) { - StringBuffer data = new StringBuffer(); - if (obj != null) - data.append(JSONArray.fromObject(obj).toString()); - return data.toString(); - } - - // ************************************************************************************* - // ************************************************************************************* - /** - * List转换成Json字符 - */ - public static String listToJson(List list, final String[] filters) { - if (null == list || list.size() == 0) { - return ""; - } - JSONArray jsonArray = null; - JsonConfig config = new JsonConfig(); - // config.registerJsonValueProcessor(Date.class, new - // DateJsonValueProcessor(Globarle.DEFAULT_DATE_FORMAT)); - if (null != filters && filters.length != 0) { - config.setJsonPropertyFilter(new PropertyFilter() { - public boolean apply(Object source, String name, Object value) { - for (String field : filters) { - if (name.equals(field)) { - return true; - } - if (value instanceof Set && ((Set) value).size() == 0) { - return true; - } - if (value instanceof Object[] && ((Object[]) value).length == 0) { - return true; - } - } - return false; - } - }); - jsonArray = JSONArray.fromObject(list, config); - } else { - jsonArray = JSONArray.fromObject(list, config); - } - return jsonArray.toString(); - } - - /** - * Object转换成Json字符 - * - * @param object - * 源对 - * @param ignorFields - * 忽略属�数 - * @return - */ - public static String objectToJson(Object object, final String[] ignorFields) { - if (null == object) { - return ""; - } - JSONObject jsonObject = null; - if (null != ignorFields && ignorFields.length != 0) { - JsonConfig config = new JsonConfig(); - config.setJsonPropertyFilter(new PropertyFilter() { - public boolean apply(Object source, String name, Object value) { - for (String field : ignorFields) { - if (name.equals(field)) { - return true; - } - if (value instanceof Set && ((Set) value).size() == 0) { - return true; - } - if (value.getClass().isArray() && ((Object[]) value).length == 0) { - return true; - } - } - return false; - } - }); - jsonObject = JSONObject.fromObject(object, config); - } else { - jsonObject = JSONObject.fromObject(object); - } - return jsonObject.toString(); - } - - /** - * 输出Json字符串到客户 - * - * @param jsonModel - * json模型 - * @param response - * 输出对象 - */ - // public static void outputJsonString(, HttpServletResponse response) - // throws IOException { - // StringBuffer sb = new StringBuffer(); - // if (!model.isQueryAction()) { - // sb.append("{").append(model.SUCCESS_FIELD).append(":").append(model.isSuccess()).append(",") - // .append(model.MESSAGE_FIELD).append(":'").append(model.getMessage()).append("'}"); - // } else { - // sb.append("{").append(model.TOTAL_FIELD).append(":").append(model.getTotalCount()).append(",") - // .append(model.ROOT_FIELD).append(":").append(model.getJsonString()).append("}"); - // } - // response.setCharacterEncoding("UTF-8"); - // response.setContentType("application/x-json"); - // // response.setContentType("text/html"); - // response.getWriter().write(sb.toString()); - // } - // ************************************************************************************* - // ************************************************************************************* - // ************************************************************************************* - - /** - * jquery-Treeview树形菜单json数据生成工具 @描述 - * 由于jquery_treeview插件要的json数据属�格式是固定的,无法用json-lib自动生成,除非实体类属�与之对 - * 采用ajax异步加载子节点方式,初始阶段只加载顶级节 生成的json格式如下 { "id":"1", //id "text":"aaa", - * //显示 "value":"1", //提交 "expanded":true, //是否展开 "hasChildren":true, - * //是否有子节点 "ChildNodes":[{},{}], //子节点集 "showcheck":true, //是否显示checkbox - * "complete":false //是否已加载子节点 } - * - * @author Lanxiaowei - * @createTime 2011-9-1 下午08:50:14 - */ - - private Map parseStr(String str) { - Map map = new HashMap(); - for (String strPart : str.split(",")) { - String[] ss = strPart.split(":"); - if (ss == null || ss.length != 2) { - continue; - } - String key = ss[0]; - String value = ss[1].trim(); - if (value.startsWith("'") && value.endsWith("'")) { - map.put(key, value.substring(1, value.length() - 1)); - } else if (value.startsWith("\"") && value.endsWith("\"")) { - map.put(key, value.substring(1, value.length() - 1)); - } else if (value.equals("true") || value.equals("false")) { - map.put(key, Boolean.valueOf(value)); - } else if (value.indexOf(".") == -1) { - try { - int val = Integer.parseInt(value); - map.put(key, val); - } catch (Exception e) { - map.put(key, value); - } - } else { - try { - BigDecimal val = new BigDecimal(value); - map.put(key, val); - } catch (Exception e) { - map.put(key, value); - } - } - } - return map; - } - - // ************************************************************************************* - // ************************************************************************************* - // ************************************************************************************* - // ************************************************************************************* - // ************************************************************************************* - // ************************************************************************************* - // ************************************************************************************* - // ************************************************************************************* - // ************************************************************************************* - -} diff --git a/jun_java_plugins/jun_json/src/test/java/com/jun/plugin/json/json_lib/ComplexJsonParser.java b/jun_java_plugins/jun_json/src/test/java/com/jun/plugin/json/json_lib/ComplexJsonParser.java deleted file mode 100644 index e8564dd817..0000000000 --- a/jun_java_plugins/jun_json/src/test/java/com/jun/plugin/json/json_lib/ComplexJsonParser.java +++ /dev/null @@ -1,153 +0,0 @@ -package com.jun.plugin.json.json_lib; -import cn.hutool.core.util.StrUtil; -import cn.hutool.json.JSONArray; -import cn.hutool.json.JSONObject; -import cn.hutool.json.JSONUtil; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class ComplexJsonParser { - - // 正则:匹配 // 单行注释(需处理换行) - private static final Pattern COMMENT_PATTERN = Pattern.compile("//.*?\\n"); - // 正则:匹配数组中 "}{" 之间缺失的逗号(如 }{ → },{) - private static final Pattern MISSING_COMMA_PATTERN = Pattern.compile("\\}\\s*\\{"); - // 正则:匹配数组中 "key: value" 格式,替换为 {"key": value}(修复 ruleAction) - private static final Pattern ARRAY_KEY_VALUE_PATTERN = Pattern.compile("\"(\\w+)\":\\s*({[^}]+})"); - - /** - * 解析复杂JSON(含自动修复非法JSON逻辑) - */ - public static JSONObject parseComplexJson(String jsonStr) { - JSONObject rootObj = JSONUtil.parseObj(jsonStr); - // 递归处理嵌套JSON字符串(带修复) - parseNestedJsonFieldsWithFix(rootObj); - return rootObj; - } - - /** - * 递归解析 + 预处理修复非法JSON字符串 - */ - private static void parseNestedJsonFieldsWithFix(JSONObject jsonObj) { - if (jsonObj == null || jsonObj.isEmpty()) { - return; - } - - for (String key : jsonObj.keySet()) { - Object value = jsonObj.get(key); - if (value == null || !(value instanceof String)) { - // 非字符串:递归处理JSONObject/JSONArray - if (value instanceof JSONObject) { - parseNestedJsonFieldsWithFix((JSONObject) value); - } else if (value instanceof JSONArray) { - parseNestedJsonArrayWithFix((JSONArray) value); - } - continue; - } - - String strValue = ((String) value).trim(); - // 仅处理疑似JSON的字符串(以{/[开头,以}/]结尾) - if (!((strValue.startsWith("{") && strValue.endsWith("}")) || (strValue.startsWith("[") && strValue.endsWith("]")))) { - continue; - } - - // 步骤1:预处理修复非法JSON - String fixedJson = fixInvalidJson(strValue); - - // 步骤2:尝试解析修复后的JSON - try { - Object parsedObj = JSONUtil.parse(fixedJson); - jsonObj.put(key, parsedObj); - // 递归处理新解析的对象 - if (parsedObj instanceof JSONObject) { - parseNestedJsonFieldsWithFix((JSONObject) parsedObj); - } else if (parsedObj instanceof JSONArray) { - parseNestedJsonArrayWithFix((JSONArray) parsedObj); - } - } catch (Exception e) { - System.out.println("字段[" + key + "]修复后仍解析失败,保留原字符串:" + e.getMessage()); - } - } - } - - /** - * 修复JSONArray中的嵌套字段 - */ - private static void parseNestedJsonArrayWithFix(JSONArray jsonArray) { - if (jsonArray == null || jsonArray.isEmpty()) { - return; - } - for (int i = 0; i < jsonArray.size(); i++) { - Object element = jsonArray.get(i); - if (element instanceof JSONObject) { - parseNestedJsonFieldsWithFix((JSONObject) element); - } else if (element instanceof JSONArray) { - parseNestedJsonArrayWithFix((JSONArray) element); - } else if (element instanceof String) { - String strElement = ((String) element).trim(); - if ((strElement.startsWith("{") && strElement.endsWith("}")) || (strElement.startsWith("[") && strElement.endsWith("]"))) { - String fixed = fixInvalidJson(strElement); - try { - jsonArray.set(i, JSONUtil.parse(fixed)); - } catch (Exception e) { - // 保留原字符串 - } - } - } - } - } - - /** - * 核心:修复非法JSON字符串的常见问题 - */ - private static String fixInvalidJson(String jsonStr) { - if (StrUtil.isBlank(jsonStr)) { - return jsonStr; - } - - String fixed = jsonStr; - // 1. 移除 // 单行注释(JSON不支持注释) - Matcher commentMatcher = COMMENT_PATTERN.matcher(fixed); - fixed = commentMatcher.replaceAll("\n"); - - // 2. 补全数组中缺失的逗号(如 }{ → },{) - Matcher commaMatcher = MISSING_COMMA_PATTERN.matcher(fixed); - fixed = commaMatcher.replaceAll("},{"); - - // 3. 修复数组中的键值对(如 "addEdit": {...} → {"addEdit": {...}}) - Matcher keyValueMatcher = ARRAY_KEY_VALUE_PATTERN.matcher(fixed); - fixed = keyValueMatcher.replaceAll("{\"$1\": $2}"); - - // 4. 移除多余的空白字符(可选) - fixed = fixed.replaceAll("\\r\\n", "").replaceAll("\\t", ""); - - return fixed; - } - - /** - * 美观打印JSON - */ - public static void printHierarchicalJson(JSONObject jsonObj) { - System.out.println("===== 层级展示JSON数据 ====="); - System.out.println(jsonObj.toStringPretty()); - } - - // 测试 - public static void main(String[] args) { - // 替换为你的原始JSON字符串 - String rawJsonStr = "{\n" + - " \"code\": \"0\",\n" + - " \"msg\": \"操作成功\",\n" + - " \"data\": {\n" + - " \"duplicateCondition\": \"{\\r\\n\\t\\t\\\"filterFormula\\\": \\\"1 AND 2\\\",\\r\\n\\t\\t\\\"duplicationConditions\\\": [\\r\\n\\t\\t\\t{\\r\\n\\t\\t\\t\\t\\\"objectCode\\\": \\\"import_export_test_4161\\\",\\r\\n\\t\\t\\t\\t\\\"instanceName\\\": \\\"字段名称1\\\", // 字段名称\\r\\n\\t\\t\\t\\t\\\"instanceCode\\\": \\\"FID_km80kxv5d6\\\",\\r\\n\\t\\t\\t\\t\\\"instanceType\\\": \\\"input\\\", \\r\\n\\t\\t\\t\\t\\\"valueType\\\": \\\"ALL_DATA|NO_NULL_DATA\\\", \\r\\n\\t\\t\\t\\t\\\"checkType\\\": \\\"EQ|KEYWORD_EQ\\\", \\r\\n\\t\\t\\t\\t\\\"sort\\\": 1\\r\\n\\t\\t\\t},\\r\\n\\t\\t\\t {\\r\\n\\t\\t\\t\\t\\\"objectCode\\\": \\\"import_export_test_4161\\\",\\r\\n\\t\\t\\t\\t\\\"instanceName\\\": \\\"字段名称2\\\", // 字段名称\\r\\n\\t\\t\\t\\t\\\"instanceCode\\\": \\\"FID_km80kxv5d6\\\",\\r\\n\\t\\t\\t\\t\\\"instanceType\\\": \\\"input\\\", \\r\\n\\t\\t\\t\\t\\\"valueType\\\": \\\"ALL_DATA|NO_NULL_DATA\\\", \\r\\n\\t\\t\\t\\t\\\"checkType\\\": \\\"EQ|KEYWORD_EQ\\\", \\r\\n\\t\\t\\t\\t\\\"sort\\\": 1\\r\\n\\t\\t\\t}\\r\\n\\t\\t] \\r\\n\\t}\",\n" + - " \"ruleScope\": \"{\\r\\n\\t\\t\\\"filterFormula\\\": \\\"1 AND 2\\\",\\r\\n\\t\\t\\\"duplicationConditions\\\": [\\r\\n\\t\\t\\t{\\r\\n\\t\\t\\t\\t\\\"instanceName\\\": \\\"字段名称1\\\",\\r\\n\\t\\t\\t\\t\\\"valueType\\\": \\\"FIXED_VALUE\\\",\\r\\n\\t\\t\\t\\t\\\"value\\\": \\\"111\\\", \\r\\n\\t\\t\\t\\t\\\"objectCode\\\": \\\"import_export_test_4161\\\",\\r\\n\\t\\t\\t\\t\\\"conditionType\\\": \\\"LIKE\\\",\\r\\n\\t\\t\\t\\t\\\"instanceCode\\\": \\\"FID_kc2zts8ob6\\\",\\r\\n\\t\\t\\t\\t\\\"instanceType\\\": \\\"textarea\\\",\\r\\n\\t\\t\\t\\t\\\"sort\\\": 1\\r\\n\\t\\t\\t}\\r\\n\\t\\t\\t{\\r\\n\\t\\t\\t\\t\\\"instanceName\\\": \\\"字段名称2\\\",\\r\\n\\t\\t\\t\\t\\\"valueType\\\": \\\"FIXED_VALUE\\\",\\r\\n\\t\\t\\t\\t\\\"value\\\": \\\"111\\\", \\r\\n\\t\\t\\t\\t\\\"objectCode\\\": \\\"import_export_test_4161\\\",\\r\\n\\t\\t\\t\\t\\\"conditionType\\\": \\\"LIKE\\\",\\r\\n\\t\\t\\t\\t\\\"instanceCode\\\": \\\"FID_kc2zts8ob6\\\",\\r\\n\\t\\t\\t\\t\\\"instanceType\\\": \\\"textarea\\\",\\r\\n\\t\\t\\t\\t\\\"sort\\\": 2\\r\\n\\t\\t\\t}\\r\\n\\t\\t] \\r\\n\\t}\",\n" + - " \"ruleAction\": \"[\\r\\n \\\"addEdit\\\": \\r\\n { \\r\\n \\\"hitType\\\": \\\"1\\\", \\r\\n\\t\\t\\t\\\"value\\\": \\\"LYT_0001 | 禁止XXX重复\\\" \\r\\n },\\r\\n\\t\\\"service\\\": \\r\\n\\t\\t\\t{ \\r\\n\\t\\t\\t\\t\\\"hitType\\\": \\\"1\\\", \\r\\n\\t\\t\\t}\\r\\n\\t\\\"import\\\": \\r\\n\\t\\t\\t{ \\r\\n\\t\\t\\t\\t\\\"hitType\\\": \\\"1\\\", \\r\\n\\t\\t\\t\\t\\\"value\\\": \\\"禁止XXX重复\\\" \\r\\n\\t\\t\\t} \\t\\t\\r\\n]\"\n" + - " },\n" + - " \"trace-id\": \"metadata1208150203545b9ii\"\n" + - "}"; - - // 解析并打印 - JSONObject fullJsonObj = parseComplexJson(rawJsonStr); - printHierarchicalJson(fullJsonObj); - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_json/src/test/java/com/jun/plugin/json/json_lib/JsonKeyUtils.java b/jun_java_plugins/jun_json/src/test/java/com/jun/plugin/json/json_lib/JsonKeyUtils.java deleted file mode 100644 index ccabfb535c..0000000000 --- a/jun_java_plugins/jun_json/src/test/java/com/jun/plugin/json/json_lib/JsonKeyUtils.java +++ /dev/null @@ -1,141 +0,0 @@ -package com.jun.plugin.json.json_lib; - -import cn.hutool.json.JSONObject; - -public class JsonKeyUtils { - - /** - * 重命名 JSON 中指定路径的 Key(支持全路径+自动清理空对象) - *

- * 路径规则: - * 1. 默认用 "." 分隔路径层级(如 "user.info.oldAge"); - * 2. 若 Key 本身含 ".",请用 "/" 作为路径分隔符(如 "user/info/user.newAge"); - * 3. 自动删除操作后产生的空 JSONObject。 - * - * @param rootObj 根 JSONObject - * @param oldKeyPath 旧 Key 全路径(示例:"user.info.oldAge" 或 "user/info/user.newAge") - * @param newKeyPath 新 Key 全路径(示例:"newAge2" 或 "user.profile.age") - */ - public static void renameJsonKey(JSONObject rootObj, String oldKeyPath, String newKeyPath) { - // 空值校验 - if (rootObj == null || oldKeyPath == null || newKeyPath == null - || oldKeyPath.isEmpty() || newKeyPath.isEmpty()) { - return; - } - - // 自动识别路径分隔符(优先用 /,无则用 .) - String pathSeparator = oldKeyPath.contains("/") || newKeyPath.contains("/") ? "/" : "."; - - // 1. 获取旧路径的值 & 删除旧路径 Key(并清理空父级) - Object oldValue = getValueByFullPath(rootObj, oldKeyPath, pathSeparator); - if (oldValue == null) { - return; // 旧路径无值,直接返回 - } - // 删除旧Key,并递归清理空父级 - removeKeyByFullPathWithClean(rootObj, oldKeyPath, pathSeparator); - - // 2. 将值放入新路径(自动创建不存在的父级 JSONObject) - setValueByFullPath(rootObj, newKeyPath, oldValue, pathSeparator); - } - - /** - * 按全路径获取值(支持自定义分隔符) - */ - private static Object getValueByFullPath(JSONObject rootObj, String fullPath, String separator) { - String[] pathSegments = fullPath.split(escapeSeparator(separator)); - JSONObject currentObj = rootObj; - - for (int i = 0; i < pathSegments.length - 1; i++) { - String segment = pathSegments[i]; - if (!currentObj.containsKey(segment) || !(currentObj.get(segment) instanceof JSONObject)) { - return null; - } - currentObj = currentObj.getJSONObject(segment); - } - - String finalKey = pathSegments[pathSegments.length - 1]; - return currentObj.get(finalKey); - } - - /** - * 按全路径删除 Key + 递归清理空父级 JSONObject - */ - private static void removeKeyByFullPathWithClean(JSONObject rootObj, String fullPath, String separator) { - String[] pathSegments = fullPath.split(escapeSeparator(separator)); - // 保存所有层级的 JSONObject 和对应 Key,用于后续清理空对象 - JSONObject[] layerObjs = new JSONObject[pathSegments.length]; - String[] layerKeys = new String[pathSegments.length]; - - // 1. 遍历定位路径,记录每一层的 JSONObject 和 Key - layerObjs[0] = rootObj; - for (int i = 0; i < pathSegments.length; i++) { - if (i > 0) { - layerObjs[i] = layerObjs[i - 1].getJSONObject(layerKeys[i - 1]); - if (layerObjs[i] == null) { - return; // 路径不存在,直接返回 - } - } - layerKeys[i] = pathSegments[i]; - } - - // 2. 删除最后一级 Key - JSONObject targetObj = layerObjs[pathSegments.length - 1]; - String targetKey = layerKeys[pathSegments.length - 1]; - targetObj.remove(targetKey); - - // 3. 递归向上清理空 JSONObject(从倒数第二层开始) - for (int i = pathSegments.length - 1; i > 0; i--) { - JSONObject parentObj = layerObjs[i - 1]; - String currentKey = layerKeys[i - 1]; - JSONObject currentObj = layerObjs[i]; - - // 若当前 JSONObject 为空,则从父级中删除 - if (currentObj.isEmpty()) { - parentObj.remove(currentKey); - } else { - break; // 非空则停止向上清理 - } - } - } - - /** - * 按全路径设置值(自动创建父级,支持自定义分隔符) - */ - private static void setValueByFullPath(JSONObject rootObj, String fullPath, Object value, String separator) { - String[] pathSegments = fullPath.split(escapeSeparator(separator)); - JSONObject currentObj = rootObj; - - for (int i = 0; i < pathSegments.length - 1; i++) { - String segment = pathSegments[i]; - if (!currentObj.containsKey(segment) || !(currentObj.get(segment) instanceof JSONObject)) { - currentObj.put(segment, new JSONObject()); - } - currentObj = currentObj.getJSONObject(segment); - } - - String finalKey = pathSegments[pathSegments.length - 1]; - currentObj.put(finalKey, value); - } - - /** - * 转义分隔符(避免正则特殊字符报错) - */ - private static String escapeSeparator(String separator) { - return separator.replace(".", "\\.").replace("/", "\\/"); - } - - // 测试示例 - public static void main(String[] args) { - // 测试1:普通全路径替换(清理空对象) - String json1 = "{\"user\":{\"info\":{\"oldAge\":25}}}"; - JSONObject root1 = new JSONObject(json1); - renameJsonKey(root1, "user.info.oldAge", "user.newAge2"); - System.out.println("普通全路径替换(清理空对象后):\n" + root1.toStringPretty()); - - // 测试2:嵌套多层空对象清理 - String json2 = "{\"a\":{\"b\":{\"c\":{\"d\":\"test\"}}}}"; - JSONObject root2 = new JSONObject(json2); - renameJsonKey(root2, "a.b.c.d", "x.y.z"); - System.out.println("\n多层空对象清理:\n" + root2.toStringPretty()); - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_jsoup/doc/htmlcleaner/htmlcleaner.md b/jun_java_plugins/jun_jsoup/doc/htmlcleaner/htmlcleaner.md deleted file mode 100644 index bcb6fec78b..0000000000 --- a/jun_java_plugins/jun_jsoup/doc/htmlcleaner/htmlcleaner.md +++ /dev/null @@ -1,44 +0,0 @@ -htmlcleaner代码学习 ---- -相比Jsoup,htmlcleaner支持XPath进行抽取,也是挺有用的。 - -htmlcleaner托管在sourceforge下[http://htmlcleaner.sourceforge.net/‎](http://htmlcleaner.sourceforge.net/‎ -),由于某种原因,访问sourceforge不是那么顺畅,最后选了这个比较新的github上的fork:[https://github.com/amplafi/htmlcleaner](https://github.com/amplafi/htmlcleaner)。 - -htmlcleaner的包结构与Jsoup还是有些差距,一开始就被一字排开的类给吓到了。 - -htmlcleaner仍然有一套自己的树结构,继承自:`HtmlNode`。但是它提供了到`org.w3c.dom.Document`和`org.jdom2.Document`的转换。 - -`HtmlTokenizer`是词法分析部分,有状态但是没用状态机,而是用了一些基本类型来保存状态,例如: - - public class HtmlTokenizer { - - private BufferedReader _reader; - private char[] _working = new char[WORKING_BUFFER_SIZE]; - - private transient int _pos; - private transient int _len = -1; - private transient int _row = 1; - private transient int _col = 1; - - - private transient StringBuffer _saved = new StringBuffer(512); - - private transient boolean _isLateForDoctype; - private transient DoctypeToken _docType; - private transient TagToken _currentTagToken; - private transient List _tokenList = new ArrayList(); - private transient Set _namespacePrefixes = new HashSet(); - - private boolean _asExpected = true; - - private boolean _isScriptContext; - } - -浓烈的面向过程编程的味道。 - -`Tokenize`之后就是简单的用栈将树组合起来。 - -测试了一下,一个44k的文档,用Jsoup做parse是3.5ms,而htmlcleaner是7.9ms,差距在一倍左右。 - -XPath部分也是云里雾里, \ No newline at end of file diff --git a/jun_java_plugins/jun_jsoup/doc/images/compiler.pages b/jun_java_plugins/jun_jsoup/doc/images/compiler.pages deleted file mode 100644 index 822f8064f6..0000000000 Binary files a/jun_java_plugins/jun_jsoup/doc/images/compiler.pages and /dev/null differ diff --git a/jun_java_plugins/jun_jsoup/doc/images/compiler.png b/jun_java_plugins/jun_jsoup/doc/images/compiler.png deleted file mode 100644 index cc76f9b735..0000000000 Binary files a/jun_java_plugins/jun_jsoup/doc/images/compiler.png and /dev/null differ diff --git a/jun_java_plugins/jun_jsoup/doc/images/hacker.png b/jun_java_plugins/jun_jsoup/doc/images/hacker.png deleted file mode 100644 index 2c5eef0ebd..0000000000 Binary files a/jun_java_plugins/jun_jsoup/doc/images/hacker.png and /dev/null differ diff --git a/jun_java_plugins/jun_jsoup/doc/images/html compiler.png b/jun_java_plugins/jun_jsoup/doc/images/html compiler.png deleted file mode 100644 index 13f9125774..0000000000 Binary files a/jun_java_plugins/jun_jsoup/doc/images/html compiler.png and /dev/null differ diff --git a/jun_java_plugins/jun_jsoup/doc/images/select uml.png b/jun_java_plugins/jun_jsoup/doc/images/select uml.png deleted file mode 100644 index 8a2446cf6c..0000000000 Binary files a/jun_java_plugins/jun_jsoup/doc/images/select uml.png and /dev/null differ diff --git a/jun_java_plugins/jun_jsoup/doc/images/streetfighter.jpg b/jun_java_plugins/jun_jsoup/doc/images/streetfighter.jpg deleted file mode 100644 index 0dc18bb5df..0000000000 Binary files a/jun_java_plugins/jun_jsoup/doc/images/streetfighter.jpg and /dev/null differ diff --git a/jun_java_plugins/jun_jsoup/doc/images/uml.zargo b/jun_java_plugins/jun_jsoup/doc/images/uml.zargo deleted file mode 100644 index 8aa57dbc4e..0000000000 Binary files a/jun_java_plugins/jun_jsoup/doc/images/uml.zargo and /dev/null differ diff --git a/jun_java_plugins/jun_jsoup/doc/images/uml.zargo~ b/jun_java_plugins/jun_jsoup/doc/images/uml.zargo~ deleted file mode 100644 index 5cd48d816f..0000000000 Binary files a/jun_java_plugins/jun_jsoup/doc/images/uml.zargo~ and /dev/null differ diff --git "a/jun_java_plugins/jun_jsoup/doc/images/\347\261\273\345\233\276.png" "b/jun_java_plugins/jun_jsoup/doc/images/\347\261\273\345\233\276.png" deleted file mode 100644 index 6c2c6bc650..0000000000 Binary files "a/jun_java_plugins/jun_jsoup/doc/images/\347\261\273\345\233\276.png" and /dev/null differ diff --git a/jun_java_plugins/jun_jsoup/doc/jsoup.md b/jun_java_plugins/jun_jsoup/doc/jsoup.md deleted file mode 100644 index a209cee72c..0000000000 --- a/jun_java_plugins/jun_jsoup/doc/jsoup.md +++ /dev/null @@ -1,42 +0,0 @@ -Jsoup学习笔记 ------- -**Jsoup**是Java世界的一款HTML解析工具,它支持用CSS Selector方式选择DOM元素,也可过滤HTML文本,防止XSS攻击。 - -学习Jsoup是为了更好的开发我的另一个爬虫框架[webmagic](https://github.com/code4craft/webmagic),为了学的比较详细,就强制自己用很规范的方式写出这部分文章。 - -代码部分来自[https://github.com/jhy/jsoup](https://github.com/jhy/jsoup),添加了一些中文注释以及示例代码。 - ---------------- - -## 提纲 - -1. [概述](https://github.com/code4craft/jsoup-learning/blob/master/blogs/jsoup1.md) - -2. [DOM相关对象](https://github.com/code4craft/jsoup-learning/blob/master/blogs/jsoup2.md) - -3. [Document的输出](https://github.com/code4craft/jsoup-learning/blob/master/blogs/jsoup3.md) - -4. HTML语法分析parser - - 1. [语法分析与状态机基础](https://github.com/code4craft/jsoup-learning/blob/master/blogs/jsoup4.md) - 2. [词法分析Tokenizer](https://github.com/code4craft/jsoup-learning/blob/master/blogs/jsoup5.md) - 3. [语法检查及DOM树构建](https://github.com/code4craft/jsoup-learning/blob/master/blogs/jsoup6.md) - -5. [CSS Selector](https://github.com/code4craft/jsoup-learning/blob/master/blogs/jsoup7.md) - -6. [防御XSS攻击](https://github.com/code4craft/jsoup-learning/blob/master/blogs/jsoup8.md) - -7. [为Jsoup增加XPath选择功能](https://github.com/code4craft/xsoup) - - Jsoup默认没有XPath功能,我写了一个项目[Xsoup](https://github.com/code4craft/xsoup),可以使用XPath来选择HTML文本。Java里较常用的XPath抽取器是HtmlCleaner,Xsoup的性能比它快了一倍。 - -------- - -## 协议: - -相关代码遵循MIT协议。 - -文档遵循CC-BYNC协议。 - -[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/code4craft/jsoup-learning/trend.png)](https://bitdeli.com/free "Bitdeli Badge") - diff --git a/jun_java_plugins/jun_jsoup/doc/jsoup1.md b/jun_java_plugins/jun_jsoup/doc/jsoup1.md deleted file mode 100644 index 538ca4c588..0000000000 --- a/jun_java_plugins/jun_jsoup/doc/jsoup1.md +++ /dev/null @@ -1,87 +0,0 @@ -Jsoup代码解读之一-概述 ------- ->今天看到一个用python写的抽取正文的东东,美滋滋的用Java实现了一番,放到了webmagic里,然后发现Jsoup里已经有了…觉得自己各种不靠谱啊!算了,静下心来学学好东西吧! - -Jsoup是Java世界用作html解析和过滤的不二之选。支持将html解析为DOM树、支持CSS Selector形式选择、支持html过滤,本身还附带了一个Http下载器。 - -## 概述 - -Jsoup的代码相当简洁,Jsoup总共53个类,且没有任何第三方包的依赖,对比最终发行包9.8M的SAXON,实在算得上是短小精悍了。 - -```shell - jsoup - ├── examples #样例,包括一个将html转为纯文本和一个抽取所有链接地址的例子。 - ├── helper #一些工具类,包括读取数据、处理连接以及字符串转换的工具 - ├── nodes #DOM节点定义 - ├── parser #解析html并转换为DOM树 - ├── safety #安全相关,包括白名单及html过滤 - └── select #选择器,支持CSS Selector以及NodeVisitor格式的遍历 -``` - -## 使用 - -Jsoup的入口是`Jsoup`类。examples包里提供了两个例子,解析html后,分别用CSS Selector以及NodeVisitor来操作Dom元素。 - -这里用`ListLinks`里的例子来说明如何调用Jsoup: - -```java - public static void main(String[] args) throws IOException { - Validate.isTrue(args.length == 1, "usage: supply url to fetch"); - String url = args[0]; - print("Fetching %s...", url); - - // 下载url并解析成html DOM结构 - Document doc = Jsoup.connect(url).get(); - // 使用select方法选择元素,参数是CSS Selector表达式 - Elements links = doc.select("a[href]"); - - print("\nLinks: (%d)", links.size()); - for (Element link : links) { - //使用abs:前缀取绝对url地址 - print(" * a: <%s> (%s)", link.attr("abs:href"), trim(link.text(), 35)); - } - } -``` - -Jsoup使用了自己的一套DOM代码体系,这里的Elements、Element等虽然名字和概念都与Java XML API`org.w3c.dom`类似,但并没有代码层面的关系。就是说你想用XML的一套API来操作Jsoup的结果是办不到的,但是正因为如此,才使得Jsoup可以抛弃xml里一些繁琐的API,使得代码更加简单。 - -还有一种方式是通过`NodeVisitor`来遍历DOM树,这个在对整个html做分析和替换时比较有用: - -```java - public interface NodeVisitor { - - //遍历到节点开始时,调用此方法 - public void head(Node node, int depth); - - //遍历到节点结束时(所有子节点都已遍历完),调用此方法 - public void tail(Node node, int depth); - } -``` - -`HtmlToPlainText`的例子说明了如何使用NodeVisitor来遍历DOM树,将html转化为纯文本,并将需要换行的标签替换为换行\\n: - -```java - public static void main(String... args) throws IOException { - Validate.isTrue(args.length == 1, "usage: supply url to fetch"); - String url = args[0]; - - // fetch the specified URL and parse to a HTML DOM - Document doc = Jsoup.connect(url).get(); - - HtmlToPlainText formatter = new HtmlToPlainText(); - String plainText = formatter.getPlainText(doc); - System.out.println(plainText); - } - - public String getPlainText(Element element) { - //自定义一个NodeVisitor - FormattingVisitor - FormattingVisitor formatter = new FormattingVisitor(); - //使用NodeTraversor来装载FormattingVisitor - NodeTraversor traversor = new NodeTraversor(formatter); - //进行遍历 - traversor.traverse(element); - return formatter.toString(); - } -``` - -下一节将从DOM结构开始对Jsoup代码进行分析。 \ No newline at end of file diff --git a/jun_java_plugins/jun_jsoup/doc/jsoup2.md b/jun_java_plugins/jun_jsoup/doc/jsoup2.md deleted file mode 100644 index 90a1269e6a..0000000000 --- a/jun_java_plugins/jun_jsoup/doc/jsoup2.md +++ /dev/null @@ -1,91 +0,0 @@ -Jsoup代码解读之二-DOM相关对象 -------- -之前在文章中说到,Jsoup使用了一套自己的DOM对象体系,和Java XML API互不兼容。这样做的好处是从XML的API里解脱出来,使得代码精炼了很多。这篇文章会说明Jsoup的DOM结构,DOM的遍历方式。在下一篇文章,我会并结合这两个基础,分析一下Jsoup的HTML输出功能。 -## DOM结构相关类 - -我们先来看看nodes包的类图: - -![node类图][1] - -这里可以看到,核心无疑是`Node`类。 - -Node类是一个抽象类,它代表DOM树中的一个节点,它包含: - -* 父节点`parentNode`以及子节点`childNodes`的引用 -* 属性值集合`attributes` -* 页面的uri`baseUri`,用于修正相对地址为绝对地址 -* 在兄弟节点中的位置`siblingIndex`,用于进行DOM操作 - -Node里面包含一些获取属性、父子节点、修改元素的方法,其中比较有意思的是`absUrl()`。我们知道,在很多html页面里,链接会使用相对地址,我们有时会需要将其转变为绝对地址。Jsoup的解决方案是在attr()的参数开始加"abs:",例如attr("abs:href"),而`absUrl()`就是其实现方式。我写的爬虫框架[webmagic](http://www.oschina.net/p/webmagic)里也用到了类似功能,当时是自己手写的,看到Jsoup的实现,才发现自己是白费劲了,代码如下: - -```java - URL base; - try { - try { - base = new URL(baseUri); - } catch (MalformedURLException e) { - // the base is unsuitable, but the attribute may be abs on its own, so try that - URL abs = new URL(relUrl); - return abs.toExternalForm(); - } - // workaround: java resolves '//path/file + ?foo' to '//path/?foo', not '//path/file?foo' as desired - if (relUrl.startsWith("?")) - relUrl = base.getPath() + relUrl; - // java URL自带的相对路径解析 - URL abs = new URL(base, relUrl); - return abs.toExternalForm(); - } catch (MalformedURLException e) { - return ""; - } -``` - -Node还有一个比较值得一提的方法是`abstract String nodeName()`,这个相当于定义了节点的类型名(例如`Document`是'#Document',`Element`则是对应的TagName)。 - -Element也是一个重要的类,它代表的是一个HTML元素。它包含一个字段`tag`和`classNames`。classNames是"class"属性解析出来的集合,因为CSS规范里,"class"属性允许设置多个,并用空格隔开,而在用Selector选择的时候,即使只指定其中一个,也能够选中其中的元素。所以这里就把"class"属性展开了。Element还有选取元素的入口,例如`select`、`getElementByXXX`,这些都用到了select包中的内容,这个留到下篇文章select再说。 - -Document是代表整个文档,它也是一个特殊的Element,即根节点。Document除了Element的内容,还包括一些输出的方法。 - -Document还有一个属性`quirksMode`,大致意思是定义处理非标准HTML的几个级别,这个留到以后分析parser的时候再说。 - -## DOM树的遍历 - -Node还有一些方法,例如`outerHtml()`,用作节点及文档HTML的输出,用到了树的遍历。在DOM树的遍历上,用到了`NodeVisitor`和`NodeTraversor`来对树的进行遍历。`NodeVisitor`在上一篇文章提到过了,head()和tail()分别是遍历开始和结束时的方法,而`NodeTraversor`的核心代码如下: - -```java - public void traverse(Node root) { - Node node = root; - int depth = 0; - - //这里对树进行后序(深度优先)遍历 - while (node != null) { - //开始遍历node - visitor.head(node, depth); - if (node.childNodeSize() > 0) { - node = node.childNode(0); - depth++; - } else { - //没有下一个兄弟节点,退栈 - while (node.nextSibling() == null && depth > 0) { - visitor.tail(node, depth); - node = node.parent(); - depth--; - } - //结束遍历 - visitor.tail(node, depth); - if (node == root) - break; - node = node.nextSibling(); - } - } - } -``` - -这里使用循环+回溯来替换掉了我们常用的递归方式,从而避免了栈溢出的风险。 - -实际上,Jsoup的Selector机制也是基于`NodeVisitor`来实现的,可以说`NodeVisitor`是更加底层和灵活的API。 - -在下一篇博客我会讲讲Document的输出。 - - - - [1]: http://static.oschina.net/uploads/space/2013/0825/221021_wQvT_190591.png \ No newline at end of file diff --git a/jun_java_plugins/jun_jsoup/doc/jsoup3.md b/jun_java_plugins/jun_jsoup/doc/jsoup3.md deleted file mode 100644 index 765a2ca93e..0000000000 --- a/jun_java_plugins/jun_jsoup/doc/jsoup3.md +++ /dev/null @@ -1,138 +0,0 @@ -Jsoup代码解读之三-Document的输出 -------- - -Jsoup官方说明里,一个重要的功能就是***output tidy HTML***。这里我们看看Jsoup是如何输出HTML的。 - -## HTML相关知识 - -分析代码前,我们不妨先想想,"tidy HTML"到底包括哪些东西: - -* 换行,块级标签习惯上都会独占一行 -* 缩进,根据HTML标签嵌套层数,行首缩进会不同 -* 严格的标签闭合,如果是可以自闭合的标签并且没有内容,则进行自闭合 -* HTML实体的转义 - -这里要补充一下HTML标签的知识。HTML Tag可以分为block和inline两类。关于Tag的inline和block的定义可以参考[http://www.w3schools.com/html/html_blocks.asp](http://www.w3schools.com/html/html_blocks.asp),而Jsoup的`Tag`类则是对Java开发者非常好的学习资料。 - -```java - // internal static initialisers: - // prepped from http://www.w3.org/TR/REC-html40/sgml/dtd.html and other sources - //block tags,需要换行 - private static final String[] blockTags = { - "html", "head", "body", "frameset", "script", "noscript", "style", "meta", "link", "title", "frame", - "noframes", "section", "nav", "aside", "hgroup", "header", "footer", "p", "h1", "h2", "h3", "h4", "h5", "h6", - "ul", "ol", "pre", "div", "blockquote", "hr", "address", "figure", "figcaption", "form", "fieldset", "ins", - "del", "s", "dl", "dt", "dd", "li", "table", "caption", "thead", "tfoot", "tbody", "colgroup", "col", "tr", "th", - "td", "video", "audio", "canvas", "details", "menu", "plaintext" - }; - //inline tags,无需换行 - private static final String[] inlineTags = { - "object", "base", "font", "tt", "i", "b", "u", "big", "small", "em", "strong", "dfn", "code", "samp", "kbd", - "var", "cite", "abbr", "time", "acronym", "mark", "ruby", "rt", "rp", "a", "img", "br", "wbr", "map", "q", - "sub", "sup", "bdo", "iframe", "embed", "span", "input", "select", "textarea", "label", "button", "optgroup", - "option", "legend", "datalist", "keygen", "output", "progress", "meter", "area", "param", "source", "track", - "summary", "command", "device" - }; - //emptyTags是不能有内容的标签,这类标签都是可以自闭合的 - private static final String[] emptyTags = { - "meta", "link", "base", "frame", "img", "br", "wbr", "embed", "hr", "input", "keygen", "col", "command", - "device" - }; - private static final String[] formatAsInlineTags = { - "title", "a", "p", "h1", "h2", "h3", "h4", "h5", "h6", "pre", "address", "li", "th", "td", "script", "style", - "ins", "del", "s" - }; - //在这些标签里,需要保留空格 - private static final String[] preserveWhitespaceTags = { - "pre", "plaintext", "title", "textarea" - }; -``` - -另外,Jsoup的`Entities`类里包含了一些HTML实体转义的东西。这些转义的对应数据保存在`entities-full.properties`和`entities-base.properties`里。 - -## Jsoup的格式化实现 - -在Jsoup里,直接调用`Document.toString()`(继承自Element),即可对文档进行输出。另外`OutputSettings`可以控制输出格式,主要是`prettyPrint`(是否重新格式化)、`outline`(是否强制所有标签换行)、`indentAmount`(缩进长度)等。 - -里面的继承和互相调用关系略微复杂,大概是这样子: - -`Document.toString()`=>`Document.outerHtml()`=>`Element.html()`,最终`Element.html()`又会循环调用所有子元素的`outerHtml()`,拼接起来作为输出。 - -```java - private void html(StringBuilder accum) { - for (Node node : childNodes) - node.outerHtml(accum); - } -``` - -而`outerHtml()`会使用一个`OuterHtmlVisitor`对所以子节点做遍历,并拼装起来作为结果。 - -```java - protected void outerHtml(StringBuilder accum) { - new NodeTraversor(new OuterHtmlVisitor(accum, getOutputSettings())).traverse(this); - } -``` - -OuterHtmlVisitor会对所有子节点做遍历,并调用`node.outerHtmlHead()`和`node.outerHtmlTail`两个方法。 - -```java - private static class OuterHtmlVisitor implements NodeVisitor { - private StringBuilder accum; - private Document.OutputSettings out; - - public void head(Node node, int depth) { - node.outerHtmlHead(accum, depth, out); - } - - public void tail(Node node, int depth) { - if (!node.nodeName().equals("#text")) // saves a void hit. - node.outerHtmlTail(accum, depth, out); - } - } -``` - -我们终于找到了真正工作的代码,`node.outerHtmlHead()`和`node.outerHtmlTail`。Jsoup里每种Node的输出方式都不太一样,这里只讲讲两种主要节点:`Element`和`TextNode`。`Element`是格式化的主要对象,它的两个方法代码如下: - -```java - void outerHtmlHead(StringBuilder accum, int depth, Document.OutputSettings out) { - if (accum.length() > 0 && out.prettyPrint() - && (tag.formatAsBlock() || (parent() != null && parent().tag().formatAsBlock()) || out.outline()) ) - //换行并调整缩进 - indent(accum, depth, out); - accum - .append("<") - .append(tagName()); - attributes.html(accum, out); - - if (childNodes.isEmpty() && tag.isSelfClosing()) - accum.append(" />"); - else - accum.append(">"); - } - - void outerHtmlTail(StringBuilder accum, int depth, Document.OutputSettings out) { - if (!(childNodes.isEmpty() && tag.isSelfClosing())) { - if (out.prettyPrint() && (!childNodes.isEmpty() && ( - tag.formatAsBlock() || (out.outline() && (childNodes.size()>1 || (childNodes.size()==1 && !(childNodes.get(0) instanceof TextNode)))) - ))) - //换行并调整缩进 - indent(accum, depth, out); - accum.append(""); - } - } -``` - -而ident方法的代码只有一行: - -```java - protected void indent(StringBuilder accum, int depth, Document.OutputSettings out) { - //out.indentAmount()是缩进长度,默认是1 - accum.append("\n").append(StringUtil.padding(depth * out.indentAmount())); - } -``` - -代码简单明了,就没什么好说的了。值得一提的是,`StringUtil.padding()`方法为了减少字符串生成,把常用的缩进保存到了一个数组中。 - -好了,水了一篇文章,下一篇将比较有技术含量的parser部分。 - -另外,通过本节的学习,我们学到了要把StringBuilder命名为**accum**,而不是**sb**。 \ No newline at end of file diff --git a/jun_java_plugins/jun_jsoup/doc/jsoup4.md b/jun_java_plugins/jun_jsoup/doc/jsoup4.md deleted file mode 100644 index 2794adc706..0000000000 --- a/jun_java_plugins/jun_jsoup/doc/jsoup4.md +++ /dev/null @@ -1,111 +0,0 @@ -Jsoup代码解读之四-parser(上) -------- -作为Java世界最好的HTML 解析库,Jsoup的parser实现非常具有代表性。这部分也是Jsoup最复杂的部分,需要一些数据结构、状态机乃至编译器的知识。好在HTML语法不复杂,解析只是到DOM树为止,所以作为编译器入门倒是挺合适的。这一块不要指望囫囵吞枣,我们还是泡一杯咖啡,细细品味其中的奥妙吧。 - -## 基础知识 - -### 编译器 - -将计算机语言转化为另一种计算机语言(通常是更底层的语言,例如机器码、汇编、或者JVM字节码)的过程就叫做编译(compile)。编译器(Compiler)是计算机科学的一个重要领域,已经有很多年历史了,而最近各种通用语言层出不穷,加上跨语言编译的兴起、DSL概念的流行,都让编译器变成了一个很时髦的东西。 - -编译器领域相关有三本公认的经典书籍,龙书[《Compilers: Principles, Techniques, and Tools 》](http://book.douban.com/subject/1866231/),虎书[《Modern Compiler Implementation in X (X表示各种语言)》](http://book.douban.com/subject/1923484/),鲸书[《Advanced Compiler Design and Implementation》](http://book.douban.com/subject/1821532/)。其中龙书是编译理论方面公认的不二之选,而后面两本则对实践更有指导意义。另外[@装配脑袋](http://www.cnblogs.com/Ninputer)有个很好的编译器入门系列博客:[http://www.cnblogs.com/Ninputer/archive/2011/06/07/2074632.html](http://www.cnblogs.com/Ninputer/archive/2011/06/07/2074632.html) - -编译器的基本流程如下: - -![compiler][1] - -其中词法分析、语法分析、语义分析这部分又叫编译器的前端(front-end),而此后的中间代码生成直到目标生成、优化等属于编译器的后端(back-end)。编译器的前端技术已经很成熟了,也有yacc这样的工具来自动进行词法、语法分析(Java里也有一个类似的工具ANTLR),而后端技术更加复杂,也是目前编译器研究的重点。 - -说了这么多,回到咱们的HTML上来。HTML是一种声明式的语言,可以理解它的最终的输出是浏览器里图形化的页面,而并非可执行的目标语言,因此我将这里的Translate改为了Render。 - -![html compiler][2] - -在Jsoup(包括类似的HTML parser)里,只做了Lex(词法分析)、Parse(语法分析)两步,而HTML parse最终产出结果,就是DOM树。至于HTML的语义解析以及渲染,不妨看看携程UED团队的这篇文章:[《浏览器是怎样工作的:渲染引擎,HTML解析》](http://ued.ctrip.com/blog/?p=3295)。 - -### 状态机 - -Jsoup的词法分析和语法分析都用到了状态机。状态机可以理解为一个特殊的程序模型,例如经常跟我们打交道的正则表达式就是用状态机实现的。 - -它由状态(state)和转移(transition)两部分构成。根据状态转移的可能性,状态机又分为DFA(确定有限状态机)和NFA(非确定有限状态自动机)。这里拿一个最简单的正则表达式"a[b]*"作为例子,我们先把它映射到一个状态机DFA,大概是这样子: - -![state machine][3] - -状态机本身是一个编程模型,这里我们尝试用程序去实现它,那么最直接的方式大概是这样: - -```java - public void process(StringReader reader) throws StringReader.EOFException { - char ch; - switch (state) { - case Init: - ch = reader.read(); - if (ch == 'a') { - state = State.AfterA; - accum.append(ch); - } - break; - case AfterA: - ... - break; - case AfterB: - ... - break; - case Accept: - ... - break; - } - } -``` - -这样写简单的状态机倒没有问题,但是复杂情况下就有点难受了。还有一种标准的状态机解法,先建立状态转移表,然后使用这个表建立状态机。这个方法的问题就是,只能做纯状态转移,无法在代码级别操作输入输出。 - -Jsoup里则使用了状态模式来实现状态机,初次看到时,确实让人眼前一亮。状态模式是设计模式的一种,它将状态和对应的行为绑定在一起。而在状态机的实现过程中,使用它来实现状态转移时的处理再合适不过了。 - -"a[b]*"的例子的状态模式实现如下,这里采用了与Jsoup相同的方式,用到了枚举来实现状态模式: - -```java - public class StateModelABStateMachine implements ABStateMachine { - - State state; - - StringBuilder accum; - - enum State { - Init { - @Override - public void process(StateModelABStateMachine stateModelABStateMachine, StringReader reader) throws StringReader.EOFException { - char ch = reader.read(); - if (ch == 'a') { - stateModelABStateMachine.state = AfterA; - stateModelABStateMachine.accum.append(ch); - } - } - }, - Accept { - ... - }, - AfterA { - ... - }, - AfterB { - ... - }; - - public void process(StateModelABStateMachine stateModelABStateMachine, StringReader reader) throws StringReader.EOFException { - } - } - - public void process(StringReader reader) throws StringReader.EOFException { - state.process(this, reader); - } - } -``` - -本文中提到的几种状态机的完整实现在这个仓库的[https://github.com/code4craft/jsoup-learning/tree/master/src/main/java/us/codecraft/learning/automata](https://github.com/code4craft/jsoup-learning/tree/master/src/main/java/us/codecraft/learning/automata)路径下。 - -下一篇文章将从Jsoup的词法分析器开始来讲状态机的使用。 - - - - [1]: http://static.oschina.net/uploads/space/2013/0828/081055_j2Xy_190591.png - [2]: http://static.oschina.net/uploads/space/2013/0828/103726_uejc_190591.png - [3]: http://static.oschina.net/uploads/space/2013/0828/131113_nyHh_190591.png \ No newline at end of file diff --git a/jun_java_plugins/jun_jsoup/doc/jsoup5.md b/jun_java_plugins/jun_jsoup/doc/jsoup5.md deleted file mode 100644 index a796288e9a..0000000000 --- a/jun_java_plugins/jun_jsoup/doc/jsoup5.md +++ /dev/null @@ -1,108 +0,0 @@ -Jsoup代码解读之五-parser(中) -------- -上一篇文章讲到了状态机和词法分析的基本知识,这一节我们来分析Jsoup是如何进行词法分析的。 - -## 代码结构 - -先介绍以下parser包里的主要类: - -* `Parser` - - Jsoup parser的入口facade,封装了常用的parse静态方法。可以设置`maxErrors`,用于收集错误记录,默认是0,即不收集。与之相关的类有`ParseError`,`ParseErrorList`。基于这个功能,我写了一个[`PageErrorChecker`](https://github.com/code4craft/jsoup-learning/tree/master/src/main/java/us/codecraft/learning/parser)来对页面做语法检查,并输出语法错误。 - -* `Token` - - 保存单个的词法分析结果。Token是一个抽象类,它的实现有`Doctype`,`StartTag`,`EndTag`,`Comment`,`Character`,`EOF`6种,对应6种词法类型。 - -* `Tokeniser` - - 保存词法分析过程的状态及结果。比较重要的两个字段是`state`和`emitPending`,前者保存状态,后者保存输出。其次还有`tagPending`/`doctypePending`/`commentPending`,保存还没有填充完整的Token。 - -* `CharacterReader` - - 对读取字符的逻辑的封装,用于Tokenize时候的字符输入。CharacterReader包含了类似NIO里ByteBuffer的`consume()`、`unconsume()`、`mark()`、`rewindToMark()`,还有高级的`consumeTo()`这样的用法。 - -* `TokeniserState` - - 用枚举实现的词法分析状态机。 - -* `HtmlTreeBuilder` - - 语法分析,通过token构建DOM树的类。 - -* `HtmlTreeBuilderState` - - 语法分析状态机。 - -* `TokenQueue` - - 虽然披了个Token的马甲,其实是在query的时候用到,留到select部分再讲。 - -## 词法分析状态机 - -现在我们来讲讲HTML的词法分析过程。这里借用一下[http://ued.ctrip.com/blog/?p=3295](http://ued.ctrip.com/blog/?p=3295)里的图,图中描述了一个Tag标签的状态转移过程, - -![lexer][1] - -这里忽略了HTML注释、实体以及属性,只保留基本的开始/结束标签,例如下面的HTML: - -

test
- -Jsoup里词法分析比较复杂,我从里面抽取出了对应的部分,就成了我们的miniSoupLexer(这里省略了部分代码,完整代码可以看这里[`MiniSoupTokeniserState`](https://github.com/code4craft/jsoup-learning/blob/master/src/main/java/org/jsoup/parser/MiniSoupTokeniserState.java)): - -```java - enum MiniSoupTokeniserState implements ITokeniserState { - /** - * 什么层级都没有的状态 - * ⬇ - *
test
- * ⬇ - *
test
- */ - Data { - // in data state, gather characters until a character reference or tag is found - public void read(Tokeniser t, CharacterReader r) { - switch (r.current()) { - case '<': - t.advanceTransition(TagOpen); - break; - case eof: - t.emit(new Token.EOF()); - break; - default: - String data = r.consumeToAny('&', '<', nullChar); - t.emit(data); - break; - } - } - }, - /** - * ⬇ - *
test
- */ - TagOpen { - ... - }, - /** - * ⬇ - *
test
- */ - EndTagOpen { - ... - }, - /** - * ⬇ - *
test
- */ - TagName { - ... - }; - - } -``` - -参考这个程序,可以看到Jsoup的词法分析的大致思路。分析器本身的编写是比较繁琐的过程,涉及属性值(区分单双引号)、DocType、注释、HTML实体,以及一些错误情况。不过了解了其思路,代码实现也是按部就班的过程。 - -下一节开始介绍语法分析部分。 - - [1]: http://taligarsiel.com/Projects/image019.png \ No newline at end of file diff --git a/jun_java_plugins/jun_jsoup/doc/jsoup6.md b/jun_java_plugins/jun_jsoup/doc/jsoup6.md deleted file mode 100644 index e84fbe93a3..0000000000 --- a/jun_java_plugins/jun_jsoup/doc/jsoup6.md +++ /dev/null @@ -1,186 +0,0 @@ -Jsoup代码解读之六-parser(下) --------- -最近生活上有点忙,女儿老是半夜不睡,精神状态也不是很好。工作上的事情也谈不上顺心,有很多想法但是没有几个被认可,有些事情也不是说代码写得好就行的。算了,还是端正态度,毕竟资历尚浅,我还是继续我的。 - -读Jsoup源码并非无聊,目的其实是为了将webmagic做的更好一点,毕竟parser也是爬虫的重要组成部分之一。读了代码后,收获也不少,对HTML的知识也更进一步了。 - -## DOM树产生过程 - -这里单独将`TreeBuilder`部分抽出来叫做语法分析过程可能稍微不妥,其实就是根据Token生成DOM树的过程,不过我还是沿用这个编译器里的称呼了。 - -`TreeBuilder`同样是一个facade对象,真正进行语法解析的是以下一段代码: - -```java - protected void runParser() { - while (true) { - Token token = tokeniser.read(); - - process(token); - - if (token.type == Token.TokenType.EOF) - break; - } - } -``` - -`TreeBuilder`有两个子类,`HtmlTreeBuilder`和`XmlTreeBuilder`。`XmlTreeBuilder`自然是构建XML树的类,实现颇为简单,基本上是维护一个栈,并根据不同Token插入节点即可: - -```java - @Override - protected boolean process(Token token) { - // start tag, end tag, doctype, comment, character, eof - switch (token.type) { - case StartTag: - insert(token.asStartTag()); - break; - case EndTag: - popStackToClose(token.asEndTag()); - break; - case Comment: - insert(token.asComment()); - break; - case Character: - insert(token.asCharacter()); - break; - case Doctype: - insert(token.asDoctype()); - break; - case EOF: // could put some normalisation here if desired - break; - default: - Validate.fail("Unexpected token type: " + token.type); - } - return true; - } -``` - -`insertNode`的代码大致是这个样子(为了便于展示,对方法进行了一些整合): - -```java - Element insert(Token.StartTag startTag) { - Tag tag = Tag.valueOf(startTag.name()); - Element el = new Element(tag, baseUri, startTag.attributes); - stack.getLast().appendChild(el); - if (startTag.isSelfClosing()) { - tokeniser.acknowledgeSelfClosingFlag(); - if (!tag.isKnownTag()) // unknown tag, remember this is self closing for output. see above. - tag.setSelfClosing(); - } else { - stack.add(el); - } - return el; - } -``` - -## HTML解析状态机 - -相比`XmlTreeBuilder`,`HtmlTreeBuilder`则实现较为复杂,除了类似的栈结构以外,还用到了`HtmlTreeBuilderState`来构建了一个状态机来分析HTML。这是为什么呢?不妨看看`HtmlTreeBuilderState`到底用到了哪些状态吧(在代码中中用``标明状态): - -```html - - - - - - - - - - - - - - - - - - xxx - - - - - - - -
- -
- -``` - -这里可以看到,HTML标签是有嵌套要求的,例如``,``需要组合``来使用。根据Jsoup的代码,可以发现,`HtmlTreeBuilderState`做了以下一些事情: - -* ### 语法检查 - - 例如`tr`没有嵌套在`table`标签内,则是一个语法错误。当`InBody`状态直接出现以下tag时,则出错。Jsoup里遇到这种错误,会发现这个Token的解析并记录错误,然后继续解析下面内容,并不会直接退出。 - -```java - InBody { - boolean process(Token t, HtmlTreeBuilder tb) { - if (StringUtil.in(name, - "caption", "col", "colgroup", "frame", "head", "tbody", "td", "tfoot", "th", "thead", "tr")) { - tb.error(this); - return false; - } - } -``` - -* ### 标签补全 - - 例如`head`标签没有闭合,就写入了一些只有body内才允许出现的标签,则自动闭合``。`HtmlTreeBuilderState`有的方法`anythingElse()`就提供了自动补全标签,例如`InHead`状态的自动闭合代码如下: - -```java - private boolean anythingElse(Token t, TreeBuilder tb) { - tb.process(new Token.EndTag("head")); - return tb.process(t); - } -``` - -还有一种标签闭合方式,例如下面的代码: - -```java - private void closeCell(HtmlTreeBuilder tb) { - if (tb.inTableScope("td")) - tb.process(new Token.EndTag("td")); - else - tb.process(new Token.EndTag("th")); // only here if th or td in scope - } -``` - -## 实例研究 - -### 缺少标签时,会发生什么事? - -好了,看了这么多parser的源码,不妨回到我们的日常应用上来。我们知道,在页面里多写一个两个未闭合的标签是很正常的事,那么它们会被怎么解析呢? - -就拿`
`标签为例: - -1. 漏写了开始标签,只写了结束标签 - - ```java - case EndTag: - if (StringUtil.in(name,"div","dl", "fieldset", "figcaption", "figure", "footer", "header", "pre", "section", "summary", "ul")) { - if (!tb.inScope(name)) { - tb.error(this); - return false; - } - } - ``` - - 恭喜你,这个`
`会被当做错误处理掉,于是你的页面就毫无疑问的乱掉了!当然,如果单纯多写了一个``,好像也不会有什么影响哦?(记得有人跟我讲过为了防止标签未闭合,而在页面底部多写了几个``的故事) - -2. 写了开始标签,漏写了结束标签 - - 这个情况分析起来更复杂一点。如果是无法在内部嵌套内容的标签,那么在遇到不可接受的标签时,会进行闭合。而`
`标签可以包括大多数标签,这种情况下,其作用域会持续到HTML结束。 - -好了,parser系列算是分析结束了,其间学到不少HTML及状态机内容,但是离实际使用比较远。下面开始select部分,这部分可能对日常使用更有意义一点。 \ No newline at end of file diff --git a/jun_java_plugins/jun_jsoup/doc/jsoup7.md b/jun_java_plugins/jun_jsoup/doc/jsoup7.md deleted file mode 100644 index f7ca599d8f..0000000000 --- a/jun_java_plugins/jun_jsoup/doc/jsoup7.md +++ /dev/null @@ -1,65 +0,0 @@ -Jsoup代码解读之七-实现一个CSS Selector ------ - -![street fighter][1] - -当当当!终于来到了Jsoup的特色:CSS Selector部分。selector也是我写的爬虫框架[webmagic](https://github.com/code4craft/webmagic)开发的一个重点。附上一张street fighter的图,希望以后webmagic也能挑战Jsoup! - -## select机制 - -Jsoup的select包里,类结构如下: - -![uml][2] - -在最开始介绍Jsoup的时候,就已经说过`NodeVisitor`和`Selector`了。`Selector`是select部分的对外facade,而`NodeVisitor`则是遍历树的底层API,CSS Selector也是根据`NodeVisitor`实现的遍历。 - -Jsoup的select核心是`Evaluator`。Selector所传递的表达式,会经过`QueryParser`,最终编译成一个`Evaluator`。`Evaluator`是一个抽象类,它只有一个方法: - -```java - public abstract boolean matches(Element root, Element element); -``` - -注意这里传入了root,是为了某些情况下对树进行遍历时用的。 - -Evaluator的设计简洁明了,所有的Selector表达式单词都会编译到对应的Evaluator。例如`#xx`对应`Id`,`.xx`对应`Class`,`[]`对应`Attribute`。这里补充一下w3c的CSS Selector规范:[http://www.w3.org/TR/CSS2/selector.html](http://www.w3.org/TR/CSS2/selector.html) - -当然,只靠这几个还不够,Jsoup还定义了`CombiningEvaluator`(对Evaluator进行And/Or组合),`StructuralEvaluator`(结合DOM树结构进行筛选)。 - -这里我们可能最关心的是,“div ul li”这样的父子结构是如何实现的。这个的实现方式在`StructuralEvaluator.Parent`中,贴一下代码了: - -```java - static class Parent extends StructuralEvaluator { - public Parent(Evaluator evaluator) { - this.evaluator = evaluator; - } - - public boolean matches(Element root, Element element) { - if (root == element) - return false; - - Element parent = element.parent(); - while (parent != root) { - if (evaluator.matches(root, parent)) - return true; - parent = parent.parent(); - } - return false; - } - } -``` - -这里Parent包含了一个`evaluator`属性,会根据这个evaluator去验证所有父节点。注意Parent是可以嵌套的,所以这个表达式"div ul li"最终会编译成`And(Parent(And(Parent(Tag("div")),Tag("ul")),Tag("li")))`这样的Evaluator组合。 - -select部分比想象的要简单,代码可读性也很高。经过了parser部分的研究,这部分应该算是驾轻就熟了。 - -## 关于webmagic的后续打算 - -webmagic是一个爬虫框架,它的Selector是用于抓取HTML中指定的文本,其机制和Jsoup的Evaluator非常像,只不过webmagic暂时是将Selector封装成较简单的API,而Evaluator直接上了表达式。之前也考虑过自己定制DSL来写一个HTML,现在看了Jsoup的源码,实现能力算是有了,但是引入DSL,实现只是一小部分,如何让DSL易写易懂才是难点。 - -其实看了Jsoup的源码,精细程度上比webmagic要好得多了,基本每个类都对应一个真实的概念抽象,可能以后会在这方面下点工夫。 - -下篇文章将讲最后一部分:白名单及HTML过滤机制。 - -[1]: http://static.oschina.net/uploads/space/2013/0830/180244_r1Vb_190591.jpg - -[2]: http://static.oschina.net/uploads/space/2013/0830/184337_j85b_190591.png \ No newline at end of file diff --git a/jun_java_plugins/jun_jsoup/doc/jsoup8.md b/jun_java_plugins/jun_jsoup/doc/jsoup8.md deleted file mode 100644 index 9aaf26c6ac..0000000000 --- a/jun_java_plugins/jun_jsoup/doc/jsoup8.md +++ /dev/null @@ -1,103 +0,0 @@ -Jsoup代码解读之八-防御XSS攻击 --------- -![hacker][1] - -## 防御XSS攻击的一般原理 - -cleaner是Jsoup的重要功能之一,我们常用它来进行富文本输入中的XSS防御。 - -我们知道,XSS攻击的一般方式是,通过在页面输入中嵌入一段恶意脚本,对输出时的DOM结构进行修改,从而达到执行这段脚本的目的。对于纯文本输入,过滤/转义HTML特殊字符`<`,`>`,`"`,`'`是行之有效的办法,但是如果本身用户输入的就是一段HTML文本(例如博客文章),这种方式就不太有效了。这个时候,就是Jsoup大显身手的时候了。 - -在前面,我们已经知道了,Jsoup里怎么将HTML变成一棵DOM树,怎么对DOM树进行遍历,怎么对DOM文档进行输出,那么其实cleaner的实现方式,也能猜出大概了。使用Jsoup进行XSS防御,大致分为三个步骤: - -1. 将HTML解析为DOM树 - - 这一步可以过滤掉一些企图搞破坏的非闭合标签、非正常语法等。例如一些输入,会尝试用``闭合当前Tag,然后写入攻击脚本。而根据前面对Jsoup的parser的分析,这种时候,这些非闭合标签会被当做错误并丢弃。 - -2. 过滤高风险标签/属性/属性值 - - 高风险标签是指` \ No newline at end of file diff --git a/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/baidu-variant.html b/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/baidu-variant.html deleted file mode 100644 index b89b65c29d..0000000000 --- a/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/baidu-variant.html +++ /dev/null @@ -1 +0,0 @@ -ٶһ£֪ diff --git a/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/google-ipod.html b/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/google-ipod.html deleted file mode 100644 index ba38bb8165..0000000000 --- a/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/google-ipod.html +++ /dev/null @@ -1,10 +0,0 @@ -ipod - Google Search

Advanced Search

 Results 1 - 10 of about 281,000,000 for ipod [definition]. (0.20 seconds) 

Sponsored Links

  1. Buy Ipod

    Ipod at the market's
    lowest price. Deal of a lifetime!
    www.bidrivals.com/au
  2. Ipod Catalogue

    One Stop School Shop Catalogue.
    You Won't Find It Cheaper Anywhere!
    www.Kmart.CatalogueCentral.com.au
  3. Ipod

    We've Reviewed 12 MP3 Players
    Make The Right Decision With CHOICE
    www.CHOICE.com.au/Mp3Players
  4. Cheap Used iPods For Sale

    New & Used iPods For Sale
    in Australia. Grab a Bargain today!
    Apple-Deals.info/iPod
  5. Ipod

    Find amazing bargains for MP3
    players, minidiscs & discmans!
    www.gumtree.com.au

See your ad here »

Sponsored Links

  1. iPod at The Apple® Store

    store.apple.com/au/ipod      New iPod nano, iPod touch, iPod shuffle & iPod classic. Ships free.
    Shop Mac
    Shop iPod
    Shop iPhone
    Back to Uni - Apple Store
  2. Buy iPods

    www.harveynorman.com.au      Get great prices on iPods at A Harvey Norman store near you.

Search Results

  1. News results for ipod


    CES2010: L5 accessory turns iPhone or iPod Touch into universal remote‎ - 6 days ago
    At the Consumer Electronics Show this week, L5 Technology will be showing off a new $49.95 L5 Remote accessory for the iPhone and iPod Touch that allows ...
    San Francisco Chronicle (blog) - 588 related articles »
  2. Apple - Download music and more with iTunes. Play it all on iPod.

    Learn about iPod, Apple TV, and accessories. Download iTunes software free and purchase iTunes Gift Cards. Check out the most popular TV shows, movies, ...
    www.apple.com/itunes/ - Cached - Similar
    More results from apple.com »
  3. Apple - iPod classic - Hold 40000 songs in your pocket.

    With 160GB of storage, iPod classic is the take-everything-everywhere iPod, with space for up to 40000 songs, 200 hours of video, or 25000 photos.
    www.apple.com/ipodclassic/ - Cached - Similar
  4. Shopping results for ipod

    Apple iPod Touch 32 GB (3rd Generation)

    Rated 4.4 out of 5.0

    528 reviews - $270 new, $260 used - 37 stores
    Apple iPod Touch 8 GB (3rd Generation)

    Rated 4.4 out of 5.0

    528 reviews - $173 new, $162 used - 29 stores
    Apple iPod Touch 64 GB (3rd Generation)

    Rated 4.4 out of 5.0

    528 reviews - $349 new, $325 used - 44 stores
  5. iPod - Wikipedia, the free encyclopedia

    The iPod is a portable media player designed and marketed by Apple and launched on October 23, 2001. The product line-up includes the hard drive-based iPod ...
    en.wikipedia.org/wiki/IPod - Cached - Similar
  6. Apple iPod reviews, news and videos - CNET.com

    Check out CNET's iPod coverage for the latest Apple iPod reviews, news and videos of the iPod Nano, iPod Shuffle, iPod Touch, iPod Classic and iPod ...
    www.cnet.com/ipod/ - 22 minutes ago - Cached - Similar
  7. All things iPod, iPhone, iTunes and beyond | iLounge

    Includes news, information, reviews, a discussion forum, and tips and tricks for all iPods and iPhones.
    www.ilounge.com/ - Cached - Similar
  8. Amazon.com: iPod: Electronics

    On September 9, Apple launched a host of new iPods, including 18 nanos that now feature a built-in video camera, FM radio, and pedometer; six shuffles in ...
    www.amazon.com/iPod-Computers/b?ie=UTF8&node... - Cached - Similar
  9. Welcome to the Apple Store - Apple Store (U.S.)

    Shop for Apple computers, compare iPod and iPhone models, and discover Apple and third-party accessories, software, and much more.
    store.apple.com/ - Cached - Similar
  10. Cheap iPods - Best Prices iPod & iPod Touch | Save Money

    Savebuckets has an enormous selection of the latest iPods. Compare prices of new generation iPods: Classic, Nano, Shuffle & Touch.
    www.savebuckets.co.uk › ... › Multi Media Players - Cached - Similar
  11. iPod - Blendtec - Home of mixers, blenders, grain mills and more

    At WillItBlend.com we take everything but the kitchen sink, stick it in a blender, and ask, will it blend?
    www.blendtec.com/willitblend/videos.aspx?type=unsafe...ipod - Cached
  12. iPodLinux :: Home

    6 Mar 2009 ... October 10, 2009. 2:20 pm, The broken dates are now fixed on our website. Forums and Wiki are working as expected again! ...
    ipodlinux.org/ - Cached

\ No newline at end of file diff --git a/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/meta-charset-1.html b/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/meta-charset-1.html deleted file mode 100644 index 19ce3125c8..0000000000 --- a/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/meta-charset-1.html +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/meta-charset-2.html b/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/meta-charset-2.html deleted file mode 100644 index 04334d8472..0000000000 --- a/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/meta-charset-2.html +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/meta-charset-3.html b/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/meta-charset-3.html deleted file mode 100644 index b303a82e1a..0000000000 --- a/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/meta-charset-3.html +++ /dev/null @@ -1,4 +0,0 @@ - - -新 - \ No newline at end of file diff --git a/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/news-com-au-home.html b/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/news-com-au-home.html deleted file mode 100644 index 191a7cb198..0000000000 --- a/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/news-com-au-home.html +++ /dev/null @@ -1,3039 +0,0 @@ - - - - - - News.com.au | News from Australia and around the world online | NewsComAu - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
-
-
-
-
- - - - -
-
Last updated: - - - January 11, 2010 - -
- - - - -
-
-

- Weather: - - - Sydney 21°C - - - 27°C - . - Fine. Increasing sunny periods. -

-
-
- - -
-
-
- -
-
-

news top stories

-
-
-
- -
-
-
- -
-
David Swan
-
-

Love the beast but hate the petrol costs?  Meet the men who were so sick of shelling out at the bowser they chose to spend thousands making their old cars new - kind of.

More
-
-
- -
-
-
- - - -
-
-
-
-
-

- - Bali 'confession' to help mate - -

- Scott Rush and Renae Lawrence -

- - BALI Nine drug mule Renae Lawrence has taken a dramatic step to try to save Scott Rush's life. -

- -
-
-

- - Fire breaks out in 'catastrophic fire zone' - -

- Fire -

- A NEWLY-spotted blaze has led to a state issuing its first code red catastrophic alert. -

- -
-
-

- - Hunger striker 'shrinking away to nothing' - -

- news image spencer 20100108 -

- - A FARMER who hasn't eaten for 50 days has broken down, saying he could do with a "nice bit of steak". -

-

- 33 comments on this story -

- -
-
-

- - Girl weeps blood 'up to 50 times a day' - -

- Twinkle -

- -  A GIRL who bleeds from her eyes and other parts of her body without any injury has left doctors baffled. -

-
-
-

- - Ricki-Lee says women don't relate to Jen - -

- Ricki Lee Coulter -

- - THE singer says there is “a big divide” between the model and the average Australian woman. -

- -
-
-
- -
-
-
- - -
-
-
- -
-
-
- -
-
Lindsay Lohan
-
- -

Lindsay Lohan's car hit a photographer, reports say
- Tila hints at Casey's baby

-
-
- -
-
- -
-
Simon Clausen
-
- -
Meet the geek-turned-property-tycoon building an empire of havens for the super-rich -

 

-
- -

 

-
-
- -
-
- -
-
Victoria Beckham
-
- -

What Posh took home from an $865,000 shopping spree
-Gallery Tila Tequila's celeb catfight

-
-
- -
-
- -
-
White Cockatoo
-
- -

Australia's unofficial top sex tourist destination now comes with a million-dollar price tag

-
-
- -
-
-
- -
-
-
- -
-
- -
-
-
- -
-
-
-
-
More Cities - -
-
-

- - Adelaide - -

-
-
- Showers -
- 24°C - 26°C - Cloudy. Showers. -
-
-
- Mostly sunny -
- Tomorrow - 21°C - 31°C -
- -
-
-

- - Brisbane - -

-
-
- Mostly sunny -
- 21°C - 31°C - Fine. -
-
-
- Showers -
- Tomorrow - 24°C - 31°C -
- -
-
-

- - Cairns - -

-
-
- Showers -
- 24°C - 31°C - Showers. -
-
-
- Sunny -
- Tomorrow - 16°C - 38°C -
- -
-
-

- - Canberra - -

-
-
- Mostly sunny -
- 20°C - 38°C - Fine, mostly sunny. -
-
-
- Mostly sunny -
- Tomorrow - 20°C - 30°C -
- -
-
-

- - Coolangatta - -

-
-
- Mostly sunny -
- 21°C - 30°C - Fine. -
-
-
- Late thunder -
- Tomorrow - 25°C - 32°C -
- -
-
-

- - Darwin - -

-
-
- Thunderstorms -
- 25°C - 31°C - Showers or storms. -
-
-
- Mostly sunny -
- Tomorrow - 14°C - 36°C -
- -
-
-

- - Hobart - -

-
-
- Rain clearing -
- 20°C - 28°C - A little rain, clearing later. -
-
-
- Mostly sunny -
- Tomorrow - 21°C - 43°C -
- -
-
-

- - Melbourne - -

-
-
- Showers -
- 27°C - 33°C - Cool change. Few showers. -
-
-
- Increasing sunshine -
- Tomorrow - 21°C - 28°C -
- -
-
-

- - Newcastle - -

-
-
- Mostly sunny -
- 21°C - 34°C - Fine. -
-
-
- Mostly sunny -
- Tomorrow - 13°C - 24°C -
- -
-
-

- - Perth - -

-
-
- Sunny -
- 12°C - 30°C - Sunny. -
-
-
- Increasing sunshine -
- Tomorrow - 21°C - 27°C -
- -
-
-

- - Sydney - -

-
-
- Cloud increasing -
- 22°C - 33°C - Fine. Cloud increasing. -
-
-
- Mostly cloudy -
- Tomorrow - 24°C - 32°C -
- -
-
-

- - Adelaide - -

-
-
- Windy -
- 29°C - 42°C - Dry and windy. -
-
-
- Mostly cloudy -
- Tomorrow - 24°C - 32°C -
- -
-
-
- - -
- -
- -
-
-
-
-
- - - - - -
- - -
-
-
-

- - Giant hummus in name of world peas - -

- hummus world record -

- - ISRAELI Arab and Jewish chefs have put aside their differences to serve up a world record dish of hummus. -

- -
-
-
-
-

- - Robber hides in see-through plastic bag - -

- plastic bag -

- - A ROBBER wearing a transparent plastic bag over his head has held up a service station. -

- -
-
-
-
-

- - Speeding millionaire cops $315,000 fine - -

- news image ferrari 20100108 -

- - A MULTI-millionaire was fined a staggering $315,000 for trying to evade a hefty speeding fine. -

- -
-
-
-
-

- - Man's Happy Birthday wish - in manure - -

- Manure -

- - ASK one wife if she got the perfect birthday present and she'll tell you her hubby "dung good". -

- -
-
-
-
-

- - Machine is a real turn-off - literally - -

- Machine -

- - IT'S made of wood and has a switch on top. That's it really. So what is the appeal of this box? -

- -
-
-
-
-

- - Bungling bank robbers top Darwin Awards - -

- ATM -

- - TWO robbers who blew themselves up trying to make an ATM "withdrawal" win awards. -

- -
-
-
-
-

Prev

-

1 of 6

-

Next

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

Blogroll

-
-
-
- -
-
Ask Bossy, Kate de Brito
-
- -

I gave  my flatmate a shiner. Now I'm sad, porking up and everyone hates me.

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

- Why can't pollies just be good at politics? -

- putin -

-

-

PAUL Colgan's all for politicians having hobbies but they make the rest of us feel like we’re in for a lifetime of mediocrity.

-

 

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

Capricorn

-

Dec 22 - Jan 20 -

- -

-Good builders rarely clear up after themselves. It is, apparently, impossible to operate a vacuum cleaner if you know how to use a drill. But, then, they are not alone. Surgeo... Read more

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

National & Local

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

Select your state to view your local news here:

- - - nswact - qld - vic - sa - wa - nt - tas - -
-
- - -
-
-
- - -
-
-

- - Brace yourself for Metro meltdown - -

- Traffic jam -

- TENS of thousands of Sydney commuters face transport chaos that will last years while the CBD Metro is built, the State Government has admitted. -

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

- - QR security guard assaulted - -

- QR security guard assaulted -

- A SECURITY guard has been bitten and punched after disturbing a burglar at a Queensland Rail workshop at Redbank, west of Brisbane. -

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

Victoria

- -
- -
-
-

- - Naughty corners 'bad for kids' - -

- An expert has warned against naughty corners -

- A MELBOURNE expert says naughty corners in bedrooms are inappropriate because they shame and humiliate. -

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

- - Craypot crackpots in hoax emergency - -

- binoculars -

- PRANKSTERS have tied up already-stretched beach rescue resources with a fake emergency at Middleton. -

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

- - Perth bouncer glassed - -

- glassing in sydney -

- POLICE have charged a 26-year-old man after a Tiger Lil's Night Club bouncer was glassed in the head in the early hours of Sunday morning. -

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

- Northern Territory -

-

- RSS -

- -
-
-
-

- Fears for missing pair as floods rise -

-

GRAVE fears are held for two brothers who are still missing after flood waters washed through Central Australia.

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

- Tasmania -

-

- RSS -

- -
-
-
-

- Bypass deadline warning -

-

PREMIER David Bartlett has warned Aboriginal activists opposing the Brighton bypass they may have only two weeks to co-operate before the project proceeds.

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

World

-
-
-
-
-
-

World

-
- -
-
-

- - Dead Playboy model 'left club with man' - -

- Paula Sladewski -

- - POLICE are searching for a man who left a club with Paula Sladewski  before her body was found burned beyond recognition. -

-
- -
-
- - - - -
-
- -
-
Enceladus
-
- -

Saturn's moon Enceladus could potentially have the right conditions to support life

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

Rebels join race for Thurston

- Rebels join race for Thurston -

THE tug of war for Johnathan Thurston's signature has taken a twist, with the Melbourne Super Rugby franchise targeting the star.

-
-
- -
- -
-
- -
- - Play Video - FOXSPORTS Video Player - -

It's on all the time... Updates throughout the day

-
Available on FoxTel
-
- -
-
- -
-
-
- - -
-
-

Business

-
-
-
-
-
-

Business

- -
- -
-
-

- - Big jump in number of job ads - -

- jobs -

- - THE number of job ads in newspapers and online jumped 6 per cent, the strongest monthly growth in two-and-a-half years. -

-
- -
- -
- - -
-
-

ASX200 - Top Gainers & Losers - at 12:00PM -

-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CodeNamePricePercent
- NXS - - Nexus Energy - 0.3358.06%
- AGO - - Atlas Iron - 2.286.04%
- PLA - - Platinum Austra.. - 1.135.6%
- SDL - - Sundance Resour.. - 0.155-3.13%
- WOR - - WorleyParsons L.. - 29.61-2.8%
- PBG - - Pacific Brands - 1.165-2.52%
-
- -
- - -
-
-

Stock Quotes

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

Money

-
-
-
-
-
-

Money

- -
- -
-
-

- - Add some spice to your super nest egg - -

- retirees -

- - MANY people think super is boring, but there are ways to spice up your nest egg that are definitely not dull. -

-
- -
-
- - -
-
-
- -
-
interest rates dice
-
- -

Find out how interest rates affect you with the latest news, features and multimedia

-
-
- -
-
- -
-
Money compass
-
- -

Join everyday Australians and financial experts and chat about money issues that matter

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

Entertainment

-
-
-
- - - -
-
-

Entertainment Features

-
-
-
- -
-
Dennis Rodman
-
- -

Dennis Rodman reportedly thrown out of restaurant for being drunk and disorderly

-
-
- -
-
- -
-
Tila Tequila
-
- -

Tila Tequila argues with two celebs in catfight at her home
- Odd farewell to Casey

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

Travel

-
-
-
-
-
- -
- -
-
-

- - Is this the most desired airline seat? - -

- A380 -

- - DOM Perignon, a private mini-bar and a shower suit - Brian Crisp enters a world of unimaginable luxury on the Emirates A380. -

- -
- -
-
- - -
-
-

Travel Features

-
-
-
- -
-
Pink dress
-
- -

Airline under fire for its new uniforms which have been likened to drag queen's outfits

-
-
- -
-
- -
-
Bike
-
- -

Explore one of the world's most famous parks in style. But watch out for strollers

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

Technology

-
-
-
-
-
-
-

- - Pocket projector, web TV box win awards - -

- Consumer Electronics Show -

- - A TINY laser projector and a set-top box which delivers web content to your TV among the best products at gadget show CES. -

-

- 4 comments on this story -

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

- - Digital auction ramped up - -

- Stephen Conroy -

- A SOARING demand for limited bandwidth is putting the heat on key players ahead of the second leg of the government's digital spectrum auction. -

-
- -
- -
- - -
-
- -
-
news home intel buyers guide
-
-
-
- -
- -
-
- -
-
- - - - -
-
-

Network Sites

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

- Stay Up To Date -

- woman at computer -

Stay up to date with the latest career news and advice with the free Networker Career Newsletter

-
-
-
- - -
-
-

Cars

-
-
- -
-

- Buy a car -

- Buy A Car -

-Carsguide has a wide range of cars for sale.  Our reviews, road tests and tools will help you choose the car for you.

-
-
-
- - -
-
-

Win $5000

-
-
- -
-

- Free business listing - Truelocal.com.au -

- truelocal -

List for free to go in the draw to win. Upload content or purchase a paid listing and get more chances to win.

-
-
-
- - -
- -
- -
-

- NEW tools to help you get the best price -

- realestate -

Know your market with weekly Auction results and information on recent sales in your area. Find out more.

-
-
-
- -
-
-
- -
-
- -
- - - - - - - - - - - - - - - - - -
-
- - \ No newline at end of file diff --git a/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/nyt-article-1.html b/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/nyt-article-1.html deleted file mode 100644 index de10a9577b..0000000000 --- a/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/nyt-article-1.html +++ /dev/null @@ -1,948 +0,0 @@ - - - - - - - - - - -BP to Replace Hayward as Chief Executive - NYTimes.com - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - -
-
- -
- - -
- -
-
-
- - - - - -
-
-
-
- -
- -

- -Global Business - -

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

As BP Lays Out Future, It Will Not Include Hayward

- - - -
-
-
-
    -
  • comments
  • - -
  • -Print -
  • - - - - - - -
  • -
    - - - - - - - - -
    -Reprints -
  • - -
    -
-
- -
-
-
-
- - - - - - - - - - -

-Tony Hayward, the embattled chief executive of BP, has agreed to step down and be replaced by Robert Dudley, the company’s most senior American executive who is now in charge of BP’s operations in the Gulf of Mexico, according to a person close to the company’s board.

-
-
- - -
- -
Susan Walsh/Associated Press
-

CEO Tony Hayward, left, may be replaced by Bob Dudley, right, BP’s most senior American executive, according to a person close to the board.

-
- -
-

Related

- -
-
-

Add to Portfolio

- -

Go to your Portfolio »

-
- -
-
- -
-
Steven Senne/Associated Press
-

Robert Dudley.

-
- -
-
-
-

-The change in leadership will be discussed by the board of directors on Monday and may be announced Tuesday if the board ratifies the decision. Mr. Hayward would probably be replaced in the fall, the person said, but a decision has already been made by mutual agreement between Mr. Hayward and senior BP management.

-“It is in the best interest of the company to go forward with fresh leadership,” the person said.

-Mr. Hayward, who has been running BP since 2007, is the first senior executive at BP to pay the price for the largest oil spill in the United States, after the Deepwater Horizon blew up on April 20. His handling of the crisis has infuriated Gulf Coast residents and government officials alike, especially after a series of public gaffes forced him to retreat from the spotlight.

-A great deal is at stake for BP, which remains under considerable pressure even though the oil has stopped gushing from its well underneath the Gulf of Mexico. A tropical storm over the weekend briefly forced BP to suspend operations to permanently plug the doomed well. Some members of Congress want to ban BP from running new offshore ventures. The Senate, meanwhile, is expected to vote on legislation this week that would hold “BP accountable,” said Senator Harry Reid, the Democratic majority leader.

-And the company continues to lurch from one public relations embarrassment to another. Last week, BP admitted it posted doctored pictures of its spill operations on its corporate Web site.

-And on Saturday, Kenneth Feinberg, the administrator managing the $20 billion claims fund BP set up under pressure from the White House, accused the company of holding up compensation payments to spill victims.

-“I have a concern that BP is stalling claims,” Mr. Feinberg told reporters. “I doubt they are stalling for money. It’s not that. I just don’t think they know the answers to the questions” by the claimants.

-This uncertainty about BP’s future business, its ultimate liabilities and its public relations debacle continue to weigh on the company’s share price, which is down about 40 percent since the spill started.

-“The key issue now is whether investors and BP’s board think Tony Hayward is the right person to move the company forward,” said Matthew J. Slaughter, a professor at Dartmouth College’s Tuck School of Business. “Is this a BP problem or is this a Tony Hayward problem?”

-Regardless of who leads the company, BP’s top executives have a lot to tackle. They need to convince the company’s constituents — its shareholders, regulators and government officials in the United States and other countries where BP has operations — that BP can pay all costs related to the spill, clean up the Gulf Coast, and still manage to grow its business around the world, analysts said.

-In recent weeks, BP has taken steps to put the oil spill behind it. It has been busy negotiating the sale of some of its assets in Texas, Egypt and Canada to the Apache Corporation, raising $7 billion. Mr. Hayward personally sought to reassure key officials in Russia and Azerbaijan, where BP has large operations, that the company was still a reliable and safe partner.

-BP also recently announced that it had won new concessions to drill offshore Egypt; alongside Chevron, it reportedly bid for an offshore exploration block in the South China Sea; and this month, it spent nearly $100 million to buy a cellulosic biofuel business.

-In the gulf, there was positive news when BP finally managed to stem the flow of oil with a new cap. The company hopes to permanently shut the well within the next few weeks.

-Bruce Lanni, an energy portfolio strategist at Nollenberger Capital Partners, said the fact that no more oil was spilling the gulf was “an inflection point” for BP.

-“There are a lot of good things now going in BP’s favor,” Mr. Lanni said. “There has been an overreaction to the cost of the spill. BP has the opportunity to emerge as a stronger company. I think this is where investors are missing a window of opportunity.”

-Some investors, however, are still concerned about the ultimate price tag for the spill. Uncertainty over BP’s liabilities is keeping its shares under considerable pressure, although they rebounded somewhat in recent weeks. BP stock closed at $36.86 on Friday, valuing the company at $115 billion.

-“Right now the market is just guessing what the liability might be for BP,” Jay Singhania, a vice president at Westwood Management. “If BP could help outline exactly what the costs would be, then investors could gain more confidence.”

-The final bill will depend, in part, on whether the investigation determines that BP was negligent and responsible for the blowout at its Macondo oil well. The explosion on the Deepwater Horizon drilling rig on April 20 killed 11 workers.

-So far, BP said it has spent $3.95 billion on its containment and clean up efforts. The company warned in a statement, “It is too early to quantify other potential costs and liabilities associated with the incident.”

-Investors and analysts also insisted that BP must rapidly tackle its safety record head-on. “It is very clear BP will need to show that its management practices will improve and instill an greater safety discipline within the organization,” said Catharina Milostan, an energy analyst at Morningstar.

-Mr. Hayward, a geologist who began his career at BP and became chief executive in 2007, inherited a company with a poor safety record that resulted in a string of deadly accidents and spills in the United States. He sought to change the “top-down” style of management while trying to simplify its structure. Last year, he said it would take five years to change BP’s culture and adopt a single, companywide operating system.

-

Julia Werdigier contributed reporting.

-
-
-
-
- - -
- -
-
- -
-
-
-
-
-
-
    -
  • comments
  • - -
  • -Print -
  • - - - - -
  • -Reprints -
  • -
-
-
-
- -
-
- - - - - -
-
Related Searches
-
- -
-
-
-
-
-
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- - -
- -
- -
- -
- -
- -
- -
-
- - -

MOST POPULAR - BUSINESS

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

- Inside NYTimes.com

-
- - -
- - - - - - - - - - - - - - - - - -
-
-
- Television » -
-
- Friend or Faux: Not Quite Joey, but Not Himself -
-
Friend or Faux: Not Quite Joey, but Not Himself
-
-
-
-
- Opinion » -
-
- Op-Ed: Memories on the Half Shell -
-
Op-Ed: Memories on the Half Shell
-
-
-
-
- Fashion & Style » -
-
- Weddings and Celebrations -
-
Weddings and Celebrations
-
-
-
-
Opinion »
-

Eric Schlosser: Unsafe at Any Meal

-

Will the Senate act to protect Americans from food-borne illnesses?

-
-
-
-
- Week in Review » -
-
- The Vagabond Cat That Came to Stay -
-
The Vagabond Cat That Came to Stay
-
-
-
-
- Travel » -
-
- Hidden in Hungary, Treasures on the Vine -
-
Hidden in Hungary, Treasures on the Vine
-
-
-
- -
- -
- -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/smh-biz-article-1.html b/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/smh-biz-article-1.html deleted file mode 100644 index cb2cdf0173..0000000000 --- a/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/smh-biz-article-1.html +++ /dev/null @@ -1,1633 +0,0 @@ - - - - The board’s next fear: the female quota - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- - - - - - - - - - -
-
- - - -

Business

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

The board’s next fear: the female quota

- - -
- - - -
- January 6, 2010 - 1:12PM -
- - - - -
-

For all the protestations, there’s been an almost audible sigh of relief in the directors’ club about the watered-down and more workable recommendations from the Productivity Commission on remuneration report votes. Besides, the whole question of obscene executive pay was effectively ducked anyway.

-

But the way is now cleared for various boardrooms to move on to the next big fear: that the Federal Government might impose a quota for female directors. After all, the Labor Party has done something like that to itself with a quota of 40 per cent of candidates being women, resulting in a third of Labor MHRs being female.

-

(In case you’re wondering, women have 27 per cent of all House of Reps seats and make up 36 per cent of the Senate.)

-

In a recent social setting and therefore anonymously, a prominent member of the directors’ club and chairman of major company told me his fellows were appalled at the prospect.

-

The usual reservations were cited: a quota means the best person for the job may not be chosen; it demeans women who are chosen as the suspicion will be that they didn’t get the job on merit.

-

But much more important to this chairman was that there was not a sufficient pool of female talent at the top of the executive aquatic centre from which to fish an imposed quota of directors. And once a government started mandating quotas for one group, he feared it would be liable to repeat the exercise for another. A quota for indigenous Australians, perhaps.

-

My suspicion is that this chairman was representative of the thinking of his peers, if not what they’re prepared to say in public. In that case, there’s a lot more to be done in the evolution of women CEOs before the boardrooms can start to mirror Federal Parliament – and it shouldn’t need to be said that there is a vast difference between what’s required to be a “successful” MP and a successful director, as the miserable boardroom careers of many retired pollies indicates.

-

This week’s Economist magazine cover revives the World War II image of Rosie the Riveter with the headline: “We Did It! What happens when women are over half the workforce”. It celebrates the fact that in the next few months, women will cross the 50 per cent threshold and make up the majority of the American workforce.

-

“Women already make up the majority of university graduates in the OECD countries and the majority of professional workers in several rich countries, including the United States. Women run many of the world’s great companies, from PepsiCo in America to Areva in France,” notes the Economist’s leader – and it could have continued “and Westpac and Harvey Norman in Australia”.

-

“Women’s economic empowerment is arguably the biggest social change of our times. Just a generation ago, women were largely confined to repetitive, menial jobs. They were routinely subjected to casual sexism and were expected to abandon their careers when they married and had children. Today they are running some of the organisations that once treated them as second-class citizens. Millions of women have been given more control over their own lives. And millions of brains have been put to more productive use. Societies that try to resist this trend - most notably the Arab countries, but also Japan and some southern European countries - will pay a heavy price in the form of wasted talent and frustrated citizens.”

-

The leader goes on to face the two major remaining issues: that women are still under-represented at the top making up only 2 per cent of the bosses of major American companies and 5 per cent of British; and that women are paid significantly less than men on average.

-

In keeping with the Economist’s rational and liberal credo, it argues for, mostly, letting the market do the work in fixing those problems as it’s been doing a good job of it over the past decade. When the Scandinavian experience is cited as a way of speeding up the process, the magazine answers:

-

“If that means massive intervention, in the shape of affirmative-action programs and across-the-board benefits for parents of all sorts, the answer is no. To begin with, promoting people on the basis of their sex is illiberal and unfair, and stigmatises its beneficiaries. And there are practical problems. Lengthy periods of paid maternity leave can put firms off hiring women, which helps explain why most Swedish women work in the public sector and Sweden has a lower proportion of women in management than America does.”

-

The leader argues that there are plenty of cheaper and subtler ways in which governments can make life easier for women.

-

“Welfare states were designed when most women stayed at home. They need to change the way they operate. German schools, for instance, close at midday. American schools shut down for two months in the summer. These things can be changed without huge cost.”

-

Perhaps without huge cost, but it would be a very brave minister who would take on the Teachers’ Union for a start. It would be so much easier for a federal Labor politicians to simply mandate a female quota for the nation’s boardrooms, but as the saying goes: For every large and difficult problem, you can generally find an easy solution – and it will be wrong.

-

Michael Pascoe is a BusinessDay contributing editor.

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

Executive Style

- - - -
- - Tom Smitheringale. - -
-

Adventurer aims for the North Pole

-

The risk of a frozen death does not phase Tom Smitheringale. He will trek to the North Pole, alone.

-
-
- - - -
-

Physical activity: Impact of sleep loss on health

-

- - A gym. - - Over time, a lack of sleep could affect a person's weight and general health because of the impact is has on physical activity, study shows. -

-
- - - -
-

Arcade action: When pinball was king

-

- - One of Tony Mather's pinball  machines. - - It was outlawed in the '40s and killed off by Space Invaders in the '80s. But for a few glorious decades pinball ruled. -

-
- - - -
-

All Men are Liars: Pardon the self promotion

-

- - Sam De Brito, All Men are Liars blog. - - Nominate All Men Are Liars for the 2010 Weblog Awards. -

-
- - - -
-

Snow blind: World's top ski destinations

-

- - skiing - - For die hard powder-hounds and devoted apres-skiers alike, these resorts are the best in snow business. -

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

Today's bank ratesPowered by Mozo

- -
- - - -
- - - -
- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - -
- - -
- - -
- - - \ No newline at end of file diff --git a/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/thumb.jpg b/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/thumb.jpg deleted file mode 100644 index c3e3762c33..0000000000 Binary files a/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/thumb.jpg and /dev/null differ diff --git a/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/xml-test.xml b/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/xml-test.xml deleted file mode 100644 index 02100e463b..0000000000 --- a/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/xml-test.xml +++ /dev/null @@ -1 +0,0 @@ -OneTwoThree diff --git a/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/yahoo-article-1.html b/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/yahoo-article-1.html deleted file mode 100644 index dfbf55fe63..0000000000 --- a/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/yahoo-article-1.html +++ /dev/null @@ -1,2043 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - GM expects competitive Chevy Volt pricing in China - Yahoo! News - - - - - - - - -
- - Skip to navigation » - Skip to content » - -
- - - - - - - - - - - - - - - -
- -
- -
- -
- - - - -
- -
- - - -

GM expects competitive Chevy Volt pricing in China

- - - - -
- - - - -
    -
  • - - -
    - - - - - - - - - - - - - -
    - -
  • -
  • -
    -
  • -
- - - - - - - -
- -
- -
- -
- -
-
- - Dan Akerson poses for a portrait at General Motors headquarters in Detroit - - - - - Reuters – Dan Akerson poses for a portrait at General Motors headquarters in Detroit, Michigan, August 31, 2010. … -
- - -
- - -
- - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Related Quotes
SymbolPriceChange
- - ^DJI - - 10,014.72+4.99
- - ^GSPC - - 1,049.33+0.41
- - ^IXIC - - 2,114.03-5.94
- - - -
- -
- -
- - -
- - - - - - - - - -
-

SHANGHAI (Reuters) – General Motors expects competitive pricing for its electric Chevrolet Volt in China as it hopes to gain a foothold in China's fledgling environmentally friendly car industry with the highly anticipated car.

-

-Kevin Wale, president and managing director of GM China, said the launch of Chevrolet Volt, expected in the second half of 2011, is key to the Detroit-based carmaker's broader strategy to grow its electric car business in China after Beijing unveiled subsidy measures for the sector.

-

-Wale said the selling price of Chevrolet Volt in China will only be unveiled when it is officially launched.

-

-"I believe the pricing will be competitive," he told a news conference in Shanghai on Tuesday.

-

-In July, GM said its electric Chevrolet Volt will be sold in the United States at $41,000 -- $8,000 more than its nearest competitor, the Nissan Leaf.

-

-The U.S. automaker expects to produce 10,000 Volts for the 2011 model year and about 30,000 for 2012.

-

-China will spend more than 100 billion yuan ($14.70 billion) to subsidize the electric car industry over the next 10 years, local media reported.

-

-"China is the country that needs to move to electrification more than any other country and we know the government wants to move to electrification so we want to participate in that movement," Wale said.

-

-However, the Chevrolet Volt will likely face fierce competition in the domestic market where smaller rivals are making and selling similar products at a much lower price.

-

-Chinese carmaker BYD, backed by U.S. billionaire Warren Buffett, said it plans to export large quantities of its E6 electric car in the United States where it will be competing head on with the likes of Nissan's Leaf and GM's Volt.

-

-Despite rising competition, Wale said GM China has not sacrificed its profitability for sales growth.

-

-"It's our responsibility to be successful in China, successful means to grow volume in China, and successful means to generate profitability for our shareholders and to generate enough cash to be reinvested in our business," he said.

-

-"We are doing all of those and we are going to continue to run a strong, balanced business in China and we will continue to grow," he said.

-

-($1=6.802 Yuan)

-

-(Reporting by Soo Ai Peng; Editing by Jacqueline Wong)

-

-
-
Follow Yahoo! News on , become a fan on
- -
- -
- - - -
- - -
    -
  • - - -
    - - - - - - - - - - - - - -
    - -
  • -
  • -
    -
  • -
- - - - -
- - - -
- -
- -
- - - - -
- - - -
- - - - -
-
-

20 Comments

-
-
-
- - - - - -
-
-
-
-
-  Post a Comment -
-
-
-

Post a Comment

- Sign in to post a comment, or Sign up for a free account. -
- - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- - - -
- -
- - - -
-
Yahoo! News Network
- - -
- -
- - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/yahoo-jp.html b/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/yahoo-jp.html deleted file mode 100644 index 6aeb207b2d..0000000000 --- a/jun_java_plugins/jun_jsoup/src/test/resources/htmltests/yahoo-jp.html +++ /dev/null @@ -1,602 +0,0 @@ - - - - - - - -Yahoo! JAPAN - - - - - - - - - - - -
- -
-
- - - - -
-
- -
- - - - -
-
-
-

あこがれの街に暮らす自分
さあ、想像してみてください

-

たった一度の人生だから、せっかく住むなら住みたい街に。大好きな街で暮らせば、仕事も遊びももっと楽しい。

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

最新の記事を表示

-
過去の記事
1
2
3
4
5
- -
-
- - -
-
-

みんなのアンテナ

-

『オフィス百景』-第55回-

- -
-
-

英語とオシゴト

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

表示する地域を指定

- -
-
-
-
- -地域選択 -
-
郵便番号または市区町村名を入力してください。
-指定した地域周辺の情報が表示されます。
-
例:「1060032」「港区」「六本木駅」など
-
-
-
-
-
- -
-
- - - -
-
- -
-
- -
- - - - - - - - - - - - diff --git a/jun_java_plugins/jun_memcached/pom.xml b/jun_java_plugins/jun_memcached/pom.xml deleted file mode 100644 index 1a90347745..0000000000 --- a/jun_java_plugins/jun_memcached/pom.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_memcached - 1.0 - war - - - UTF-8 - - - - - junit - junit - 3.8.1 - test - - - - - mysql - mysql-connector-java - 5.1.40 - - - - jun_memcached - - diff --git a/jun_java_plugins/jun_minio/pom.xml b/jun_java_plugins/jun_minio/pom.xml deleted file mode 100644 index f2d075c61e..0000000000 --- a/jun_java_plugins/jun_minio/pom.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - jun_test - io.github.wujun728 - 1.0 - 4.0.0 - - - - 17 - 17 - UTF-8 - - - - - - io.minio - minio - 8.5.8 - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_minio/src/test/java/MinioTest.java b/jun_java_plugins/jun_minio/src/test/java/MinioTest.java deleted file mode 100644 index 95fe657669..0000000000 --- a/jun_java_plugins/jun_minio/src/test/java/MinioTest.java +++ /dev/null @@ -1,44 +0,0 @@ -import io.minio.MinioClient; -import io.minio.PutObjectArgs; - -import java.io.FileInputStream; - -/** - * @project heima-leadnews - * @description - * @author capture or new - * @date 2023/7/14 13:42:53 - * @version 1.0 - */ - -public class MinioTest { - public static void main(String[] args) { - FileInputStream fileInputStream = null; - try { - - // 本地文件地址 - fileInputStream = new FileInputStream("D:\\Documents\\Desktop\\list.html"); - - //1.创建minio链接客户端 - MinioClient minioClient = MinioClient.builder().credentials("root", "minioadmin") - .endpoint("http://10.100.254.13:30346") - .build(); - //2.上传 - PutObjectArgs putObjectArgs = PutObjectArgs.builder() - .object("list.html")//文件名 - .contentType("text/html")//文件类型 - .bucket("byk2kubevirt")//桶名词 与minio创建的名词一致 - // fileInputStream.available() 表示一直有内容就会上传 -1 表示将所有的相关文件的内容都上传 - .stream(fileInputStream, fileInputStream.available(), -1) //文件流 - .build(); - minioClient.putObject(putObjectArgs); - // 输出访问地址 - //System.out.println("http://10.13.167.16:30346/byk2kubevirt/list.html"); - - } catch (Exception ex) { - ex.printStackTrace(); - } - } -} - - diff --git a/jun_java_plugins/jun_mongodb/pom.xml b/jun_java_plugins/jun_mongodb/pom.xml deleted file mode 100644 index 2c5ac593de..0000000000 --- a/jun_java_plugins/jun_mongodb/pom.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_mongodb - 1.0 - war - - - UTF-8 - - - - - - org.mongodb - mongodb-driver - 3.12.13 - - - - - junit - junit - 4.13.2 - test - - - - - - mysql - mysql-connector-java - 5.1.40 - - - - jun_mongodb - - diff --git a/jun_java_plugins/jun_mongodb/src/test/java/MongoDBCRUDTest.java b/jun_java_plugins/jun_mongodb/src/test/java/MongoDBCRUDTest.java deleted file mode 100644 index c150c5f15c..0000000000 --- a/jun_java_plugins/jun_mongodb/src/test/java/MongoDBCRUDTest.java +++ /dev/null @@ -1,206 +0,0 @@ - -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.List; - -import org.bson.types.ObjectId; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.mongodb.BasicDBObject; -import com.mongodb.Bytes; -import com.mongodb.DB; -import com.mongodb.DBCollection; -import com.mongodb.DBCursor; -import com.mongodb.DBObject; -import com.mongodb.Mongo; -import com.mongodb.MongoException; -import com.mongodb.QueryOperators; -import com.mongodb.util.JSON; - -/** - * @author Wujun - * 创建时间 : 2014年11月4日 下午3:15:17 - * - * MongoDB的简单CRUD操作 - * MongoDB环境的安装:http://www.cnblogs.com/mecity/archive/2011/06/11/2078527.html - * - * mongoDB对Java支持的驱动包下载地址:https://github.com/mongodb/mongo-java-driver/downloads - * mongoDB对Java的相关支持、技术:http://www.mongodb.org/display/DOCS/Java+Language+Center - * 在线查看源码:https://github.com/mongodb/mongo-java-driver - */ -public class MongoDBCRUDTest { - private Mongo mg = null; - private DB db;//数据库 - private DBCollection users;//表 - - @Before - public void init() { - try { - mg = new Mongo(); - //mg = new Mongo("localhost", 27017);//默认是本地,端口为27017. - } catch (MongoException e) { - e.printStackTrace(); - } - // 获取temp DB;如果没有创建,mongodb会自动创建.temp就是平常所说的Database - db = mg.getDB("temp"); - // 获取users DBCollection;如果没有创建,mongodb会自动创建,users就是平常所说的table - users = db.getCollection("users"); - } - - @After - public void destory() { - if (mg != null) - mg.close(); - mg = null; - db = null; - users = null; - System.gc(); - } - - private void print(Object o) { - System.out.println(o); - } - - /** - * 查询所有数据 - * - * @author Wujun - * 创建时间 : 2014年11月4日 下午3:17:14 - */ - @Test - public void queryAll() { - print("查询users的所有数据:"); - //db游标 - DBCursor cur = users.find(); - while (cur.hasNext()) { - print(cur.next()); - } - } - - /** - * 添加数据 - * - * @author Wujun - * 创建时间 : 2014年11月4日 下午3:38:44 - */ - @Test - public void add() { - //先查询所有数据 - queryAll(); - DBObject user = new BasicDBObject(); - user.put("name", "小周"); - user.put("age", 121); - //users.save(user)保存,getN()获取影响行数 - //print(users.save(user).getN()); - - //扩展字段,随意添加字段,不影响现有数据 - user.put("sex", "男"); - - //添加多条数据,传递Array对象 - users.insert(user, new BasicDBObject("name3", "tom3"),new BasicDBObject("name4", "lucy4")); - - //添加List集合 - List list = new ArrayList(); - list.add(user); - - //查询下数据,看看是否添加成功 - print("总数: " + users.count()); - queryAll(); - } - - - /** - * 删除数据 - * - * @author Wujun - * 创建时间 : 2014年11月4日 下午3:38:57 - */ - @Test - public void remove() { - queryAll(); - print("删除id = 545882728cd3ffeb216e171b:" + users.remove(new BasicDBObject("_id", new ObjectId("545882728cd3ffeb216e171b"))).getN()); - print("remove age >= 24: " + users.remove(new BasicDBObject("age", new BasicDBObject("$gte", 24))).getN()); - } - - /** - * 修改数据 - * - * @author Wujun - * 创建时间 : 2014年11月4日 下午3:41:31 - */ - @Test - public void modify() { - print("修改:" + users.update(new BasicDBObject("_id", - new ObjectId("545883808cd31df938313342")), - new BasicDBObject("age", 99)).getN()); - print("修改:" + users.update( - new BasicDBObject("_id", - new ObjectId("545883808cd31df938313340")), - new BasicDBObject("age", 121), true,// 如果数据库不存在,是否添加 - false// 多条修改 - ).getN()); - } - - - @SuppressWarnings("deprecation") - @Test - public void query() { - //查询所有 - //queryAll(); - //查询id = 4de73f7acd812d61b4626a77 - print("find id = 4de73f7acd812d61b4626a77: " + users.find(new BasicDBObject("_id", new ObjectId("545883808cd31df938313342"))).toArray()); - //查询age = 121 - print("find age = 121: " + users.find(new BasicDBObject("age", 121)).toArray()); - //查询age >= 99 - print("find age >= 99: " + users.find(new BasicDBObject("age", new BasicDBObject("$gte", 99))).toArray()); - print("find age <= 121: " + users.find(new BasicDBObject("age", new BasicDBObject("$lte", 121))).toArray()); - print("查询age!=99:" + users.find(new BasicDBObject("age", new BasicDBObject("$ne", 99))).toArray()); - print("查询age in 99/121:" + users.find(new BasicDBObject("age", new BasicDBObject(QueryOperators.IN, new int[] { 99, 121}))).toArray()); - print("查询age not in 121:" + users.find(new BasicDBObject("age", new BasicDBObject(QueryOperators.NIN, new int[] {121}))).toArray()); - print("查询age exists 排序:" + users.find(new BasicDBObject("age", new BasicDBObject(QueryOperators.EXISTS, true))).toArray()); - print("只查询age属性:" + users.find(null, new BasicDBObject("age", true)).toArray()); - print("只查属性:" + users.find(null, new BasicDBObject("age", true), 0, 2).toArray()); - print("只查属性:" + users.find(null, new BasicDBObject("age", true), 0, 2, Bytes.QUERYOPTION_NOTIMEOUT).toArray()); - //只查询一条数据,多条去第一条 - print("findOne: " + users.findOne()); - print("findOne: " + users.findOne(new BasicDBObject("age", 99))); - print("findOne: " + users.findOne(new BasicDBObject("age", 121), new BasicDBObject("name", true))); - //查询修改、删除 - print("findAndRemove 查询age=99的数据,并且删除: " + users.findAndRemove(new BasicDBObject("name", "小周Abc"))); - queryAll(); - } - - - /** - * 其他操作 - * - * @author Wujun - * 创建时间 : 2014年11月4日 下午4:06:33 - */ - @Test - public void testOthers() { - DBObject user = new BasicDBObject(); - user.put("name", "hoojo"); - user.put("age", 24); - //JSON 对象转换 - print("serialize: " + JSON.serialize(user)); - //反序列化 - print("parse: " + JSON.parse("{ \"name\" : \"hoojo\" , \"age\" : 24}")); - print("判断temp Collection是否存在: " + db.collectionExists("temp")); - //如果不存在就创建 - if (!db.collectionExists("temp")) { - DBObject options = new BasicDBObject(); - options.put("size", 20); - options.put("capped", 20); - options.put("max", 20); - print(db.createCollection("account5",null).save(options)); - } - //设置db为只读 - //db.setReadOnly(true); - - //尝试向只读的数据库写入数据。运行时候出现异常,说明不能向只读数据库写入数据. - db.getCollection("test").save(user); - } -} diff --git a/jun_java_plugins/jun_mongodb/src/test/java/MongoDBConnTest.java b/jun_java_plugins/jun_mongodb/src/test/java/MongoDBConnTest.java deleted file mode 100644 index 80ad72b0d9..0000000000 --- a/jun_java_plugins/jun_mongodb/src/test/java/MongoDBConnTest.java +++ /dev/null @@ -1,46 +0,0 @@ - -import java.net.UnknownHostException; - -import com.mongodb.DB; -import com.mongodb.DBCollection; -import com.mongodb.DBCursor; -import com.mongodb.Mongo; -import com.mongodb.util.JSON; - -/** - * @author Wujun - * 创建时间 : 2014年11月4日 下午3:01:27 - * - * MongoDB的简单CRUD操作 - * MongoDB环境的安装:http://www.cnblogs.com/mecity/archive/2011/06/11/2078527.html - */ -public class MongoDBConnTest { - public static void main(String[] args) throws UnknownHostException { - //创建了一个MongoDB的数据库连接对象,它默认连接到当前机器的localhost地址,端口是27017 - Mongo mongo = new Mongo(); - - //查询所有的Database - for (String name : mongo.getDatabaseNames()) { - System.out.println("dbName: " + name); - } - - //获得了一个test的数据库,如果mongoDB中没有创建这个数据库也是可以正常运行的。 - //mongoDB可以在没有创建这个数据库的情况下,完成数据的添加操作。当添加的时候,没有这个库,mongoDB会自动创建当前数据库。 - DB db = mongo.getDB("test"); - //查询所有的聚集集合,也就是test数据库下面的表 - for (String name : db.getCollectionNames()) { - System.out.println("collectionName: " + name); - } - - //获取一个“聚集集合DBCollection”,获取foo表 - DBCollection users = db.getCollection("foo"); - - DBCursor cur = users.find(); - while (cur.hasNext()) { - System.out.println(cur.next()); - } - System.out.println(cur.count()); - System.out.println(cur.getCursorId()); - System.out.println(JSON.serialize(cur)); - } -} diff --git a/jun_java_plugins/jun_multicluster/pom.xml b/jun_java_plugins/jun_multicluster/pom.xml deleted file mode 100644 index 9c10d9f251..0000000000 --- a/jun_java_plugins/jun_multicluster/pom.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_multicluster - 1.0 - war - - - UTF-8 - - - - - junit - junit - 3.8.1 - test - - - - - mysql - mysql-connector-java - 5.1.40 - - - - jun_multicluster - - diff --git a/jun_java_plugins/jun_mybatis/all.log b/jun_java_plugins/jun_mybatis/all.log deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/jun_java_plugins/jun_mybatis/mybatis.sql b/jun_java_plugins/jun_mybatis/mybatis.sql deleted file mode 100644 index e2c1e4fb1a..0000000000 --- a/jun_java_plugins/jun_mybatis/mybatis.sql +++ /dev/null @@ -1,129 +0,0 @@ -SET NAMES utf8mb4; -SET FOREIGN_KEY_CHECKS = 0; - -CREATE TABLE `user` ( - `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '自增主键', - `user_name` varchar(50) NOT NULL COMMENT '用户名', - `age` int(3) DEFAULT NULL COMMENT '年龄', - `create_time` datetime DEFAULT NULL COMMENT '创建时间', - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户表'; - --- ---------------------------- --- Table structure for blog --- ---------------------------- -DROP TABLE IF EXISTS `blog`; -CREATE TABLE `blog` ( - `sex` int(0) NULL DEFAULT NULL, - `id` varchar(70) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '博客id', - `title` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '博客标题', - `author` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '博客作者', - `create_time` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, - `views` int(0) NULL DEFAULT NULL COMMENT '浏览量' -) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; - --- ---------------------------- --- Records of blog --- ---------------------------- -INSERT INTO `blog` VALUES (0, '1', '好困好累', '李斌', '2020-12-13 10:08:29', 5555); -INSERT INTO `blog` VALUES (1, '2', '好想睡觉', '李斌2', '2020-12-13 10:08:29', 15555); -INSERT INTO `blog` VALUES (0, '3', '咩咩咩咩', '李斌3', '2020-12-13 10:08:29', 3255); -INSERT INTO `blog` VALUES (1, '99', '测试', 'yznl2', '2020-12-22 15.52.22', 1); -INSERT INTO `blog` VALUES (1, '199', '1测试', 'yznl', '2020-12-22 15.52.22', 1); -INSERT INTO `blog` VALUES (0, '10', '测试转换器', '转换器', '2020-12-22 15.52.22', 8); -INSERT INTO `blog` VALUES (1, '999', '测试', 'sex测试', '2020-12-22 15.52.22', 1); -INSERT INTO `blog` VALUES (1, '999', '测试', 'sex测试', '2020-12-22 15.52.22', 1); -INSERT INTO `blog` VALUES (NULL, '222', '1测试', 'yznl', '2020-12-22 15.52.22', 1); - --- ---------------------------- --- Table structure for books --- ---------------------------- -DROP TABLE IF EXISTS `books`; -CREATE TABLE `books` ( - `bookID` int(0) NOT NULL AUTO_INCREMENT, - `bookName` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '书名', - `bookCounts` int(0) NOT NULL COMMENT '数量', - `detail` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '描述', - INDEX `bookID`(`bookID`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; - --- ---------------------------- --- Records of books --- ---------------------------- -INSERT INTO `books` VALUES (1, 'Java', 1, '从入门到放弃'); -INSERT INTO `books` VALUES (2, 'Mysql', 100, '从删库到跑路'); -INSERT INTO `books` VALUES (3, 'Linux', 5, '从进门到进牢'); - --- ---------------------------- --- Table structure for student --- ---------------------------- -DROP TABLE IF EXISTS `student`; -CREATE TABLE `student` ( - `id` int(0) NOT NULL, - `name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, - `sex` int(0) NULL DEFAULT NULL, - `class_id` int(0) NULL DEFAULT NULL, - PRIMARY KEY (`id`) USING BTREE, - INDEX `fktid`(`sex`) USING BTREE -) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; - --- ---------------------------- --- Records of student --- ---------------------------- -INSERT INTO `student` VALUES (1, '张三', 0, 2); -INSERT INTO `student` VALUES (2, '李四', 1, 1); -INSERT INTO `student` VALUES (3, '王刚', 1, 1); -INSERT INTO `student` VALUES (4, '广顺', 0, 1); - --- ---------------------------- --- Table structure for studentclass --- ---------------------------- -DROP TABLE IF EXISTS `studentclass`; -CREATE TABLE `studentclass` ( - `class_id` int(0) NOT NULL COMMENT '班级Id', - `class_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '班级名称', - PRIMARY KEY (`class_id`) USING BTREE -) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; - --- ---------------------------- --- Records of studentclass --- ---------------------------- -INSERT INTO `studentclass` VALUES (1, '高三四班'); - --- ---------------------------- --- Table structure for teacher --- ---------------------------- -DROP TABLE IF EXISTS `teacher`; -CREATE TABLE `teacher` ( - `id` int(0) NOT NULL, - `name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, - PRIMARY KEY (`id`) USING BTREE -) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; - --- ---------------------------- --- Records of teacher --- ---------------------------- -INSERT INTO `teacher` VALUES (113, '李老师'); - --- ---------------------------- --- Table structure for user --- ---------------------------- -DROP TABLE IF EXISTS `user`; -CREATE TABLE `user` ( - `id` int(0) NOT NULL, - `name` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, - `pwd` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, - PRIMARY KEY (`id`) USING BTREE -) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; - --- ---------------------------- --- Records of user --- ---------------------------- -INSERT INTO `user` VALUES (1, '李斌', '123456'); -INSERT INTO `user` VALUES (2, '李斌2', '123456'); -INSERT INTO `user` VALUES (3, '李斌3', '123456'); -INSERT INTO `user` VALUES (13, 'l13', '123456'); -INSERT INTO `user` VALUES (824, 'lb', '123'); -INSERT INTO `user` VALUES (825, 'lb', '123'); - -SET FOREIGN_KEY_CHECKS = 1; diff --git a/jun_java_plugins/jun_mybatis/pom.xml b/jun_java_plugins/jun_mybatis/pom.xml deleted file mode 100644 index c4e07e3ac0..0000000000 --- a/jun_java_plugins/jun_mybatis/pom.xml +++ /dev/null @@ -1,68 +0,0 @@ - - - 4.0.0 - - io.github.wujun728 - jun_mybatis - 1.0 - jar - - - - mysql - mysql-connector-java - 8.0.17 - - - log4j - log4j - 1.2.17 - - - org.mybatis - mybatis - 3.4.6 - - - junit - junit - 4.12 - - - org.projectlombok - lombok - 1.18.0 - - - com.alibaba - druid - 1.2.24 - - - - - - - src/main/java - - **/*.xml - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.1 - - 8 - 8 - UTF-8 - - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/Blog.java b/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/Blog.java deleted file mode 100644 index 94baa91a90..0000000000 --- a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/Blog.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.jun.plugin.mybatis; - -import java.util.Date; - -/** - * 辅助实体类:博客(用于测试类型转换器、复杂foreach等) - */ -public class Blog { - private Integer id; - private String blogTitle; // 对应数据库列:blog_title - private String content; - private Date publishTime; // 对应数据库列:publish_time(测试日期类型转换) - private Integer authorId; - - // 无参构造器 - public Blog() {} - - // 有参构造器 - public Blog(String blogTitle, String content, Date publishTime, Integer authorId) { - this.blogTitle = blogTitle; - this.content = content; - this.publishTime = publishTime; - this.authorId = authorId; - } - - // getter/setter 方法 - public Integer getId() { return id; } - public void setId(Integer id) { this.id = id; } - public String getBlogTitle() { return blogTitle; } - public void setBlogTitle(String blogTitle) { this.blogTitle = blogTitle; } - public String getContent() { return content; } - public void setContent(String content) { this.content = content; } - public Date getPublishTime() { return publishTime; } - public void setPublishTime(Date publishTime) { this.publishTime = publishTime; } - public Integer getAuthorId() { return authorId; } - public void setAuthorId(Integer authorId) { this.authorId = authorId; } - - // toString() 方法 - @Override - public String toString() { - return "Blog{" + - "id=" + id + - ", blogTitle='" + blogTitle + '\'' + - ", content='" + content + '\'' + - ", publishTime=" + publishTime + - ", authorId=" + authorId + - '}'; - } -} diff --git a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/BlogMapper.java b/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/BlogMapper.java deleted file mode 100644 index e399e830d3..0000000000 --- a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/BlogMapper.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.jun.plugin.mybatis; - -import org.apache.ibatis.annotations.*; - -import java.util.Date; -import java.util.List; -import java.util.Map; - -/** - * Blog Mapper接口(测试类型转换器、对象foreach等) - */ -public interface BlogMapper { - // ==== 基础CRUD ==== - @Insert("INSERT INTO blog (blog_title, content, publish_time, author_id) VALUES (#{blogTitle}, #{content}, #{publishTime}, #{authorId})") - int insertBlog(Blog blog); - - @Select("SELECT id, blog_title, content, publish_time, author_id FROM blog WHERE id = #{id}") - Blog findBlogById(Integer id); - - @Update("UPDATE blog SET blog_title = #{blogTitle}, content = #{content} WHERE id = #{id}") - int updateBlog(Blog blog); - - @Delete("DELETE FROM blog WHERE id = #{id}") - int deleteBlogById(Integer id); - - // ==== 类型转换器 ==== - // 自定义日期转换器(查询,将字符串日期转为Date) - @Select("SELECT id, blog_title, content, publish_time, author_id FROM blog WHERE publish_time = #{publishTime}") - Blog findBlogByPublishTime(@Param("publishTime") Date publishTime); - - // 新增带日期转换器 - @Insert("INSERT INTO blog (blog_title, content, publish_time, author_id) VALUES (#{blogTitle}, #{content}, #{publishTime}, #{authorId})") - int insertBlogWithConverter(Blog blog); - - // ==== Map与foreach ==== - // 输入参数为Map,返回Blog列表 - @Select("") - List findBlogByMap(@Param("paramMap") Map paramMap); - - // 迭代对象数组(批量查询博客) - @Select("") - List findBlogByObjectArray(@Param("blogArray") Blog[] blogArray); - - // 迭代对象集合(批量新增博客) - @Insert("") - int batchInsertBlog(@Param("blogList") List blogList); -} diff --git a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/DateTypeHandler.java b/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/DateTypeHandler.java deleted file mode 100644 index f61eb73841..0000000000 --- a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/DateTypeHandler.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.jun.plugin.mybatis; - -import org.apache.ibatis.type.BaseTypeHandler; -import org.apache.ibatis.type.JdbcType; -import org.apache.ibatis.type.MappedJdbcTypes; -import org.apache.ibatis.type.MappedTypes; - -import java.sql.*; -import java.text.SimpleDateFormat; -import java.util.Date; - -/** - * 自定义日期类型转换器:处理Date与VARCHAR/ TIMESTAMP之间的转换 - * MappedTypes:指定Java类型 - * MappedJdbcTypes:指定JDBC类型 - */ -@MappedTypes({Date.class}) -@MappedJdbcTypes({JdbcType.VARCHAR, JdbcType.TIMESTAMP}) -public class DateTypeHandler extends BaseTypeHandler { - // 日期格式化器 - private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - - // ==== 将Java类型转换为JDBC类型(写入数据库) ==== - @Override - public void setNonNullParameter(PreparedStatement ps, int i, Date parameter, JdbcType jdbcType) throws SQLException { - ps.setString(i, sdf.format(parameter)); - } - - // ==== 将JDBC类型转换为Java类型(从数据库读取) ==== - @Override - public Date getNullableResult(ResultSet rs, String columnName) throws SQLException { - String dateStr = rs.getString(columnName); - return convertStrToDate(dateStr); - } - - @Override - public Date getNullableResult(ResultSet rs, int columnIndex) throws SQLException { - String dateStr = rs.getString(columnIndex); - return convertStrToDate(dateStr); - } - - @Override - public Date getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { - String dateStr = cs.getString(columnIndex); - return convertStrToDate(dateStr); - } - - // 辅助方法:字符串转Date - private Date convertStrToDate(String dateStr) { - if (dateStr == null || dateStr.trim().isEmpty()) { - return null; - } - try { - return sdf.parse(dateStr); - } catch (Exception e) { - throw new RuntimeException("日期转换失败", e); - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/MyBatisDruidMainTest.java b/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/MyBatisDruidMainTest.java deleted file mode 100644 index 1616f884ff..0000000000 --- a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/MyBatisDruidMainTest.java +++ /dev/null @@ -1,307 +0,0 @@ -package com.jun.plugin.mybatis; - -import com.alibaba.druid.pool.DruidDataSource; -import org.apache.ibatis.mapping.Environment; -import org.apache.ibatis.session.Configuration; -import org.apache.ibatis.session.SqlSession; -import org.apache.ibatis.session.SqlSessionFactory; -import org.apache.ibatis.session.SqlSessionFactoryBuilder; -import org.apache.ibatis.transaction.TransactionFactory; -import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory; - -import java.text.SimpleDateFormat; -import java.util.*; - -/** - * 无任何配置文件 + 手动new Druid数据源 + 全量MyBatis操作示例 - */ -public class MyBatisDruidMainTest { - // 全局SqlSessionFactory(单例) - private static SqlSessionFactory sqlSessionFactory; - - // 静态代码块:初始化MyBatis环境(Druid数据源 + 配置) - static { - // 步骤1:手动构建Druid数据源 - DruidDataSource druidDataSource = new DruidDataSource(); - druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - druidDataSource.setUrl("jdbc:mysql://localhost:3307/db_test?useSSL=false&serverTimezone=UTC&characterEncoding=utf8"); - druidDataSource.setUsername("root"); - druidDataSource.setPassword("mysqladmin"); - // Druid连接池优化配置 - druidDataSource.setInitialSize(5); - druidDataSource.setMaxActive(20); - druidDataSource.setMinIdle(3); - - // 步骤2:构建MyBatis Environment - TransactionFactory transactionFactory = new JdbcTransactionFactory(); - Environment environment = new Environment("development", transactionFactory, druidDataSource); - - // 步骤3:构建MyBatis Configuration(注册Mapper + 配置全局属性 + 注册类型转换器) - Configuration configuration = new Configuration(environment); - configuration.setMapUnderscoreToCamelCase(true); // 下划线转驼峰 - configuration.addMapper(UserMapper.class); // 注册UserMapper - configuration.addMapper(BlogMapper.class); // 注册BlogMapper - configuration.getTypeHandlerRegistry().register(DateTypeHandler.class); // 注册自定义类型转换器 - - // 步骤4:构建SqlSessionFactory - sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration); - } - - // ==================== 核心测试方法:main(调用所有示例) ==================== - public static void main(String[] args) { - // 查询单个 - queryOne(); - - // 查询多个 - queryAll(); - - // 增加 - add(); - - // 删除 - delete(); - - // 修改 - update(); - - // 带转换器查询 - selectBlogByIdWithConverter(); - - // 带转换器新增 - addBlogWithConverter(); - - // 使用map作为输入参数 - selectBlogWithHashMap(); - - // 返回值是HashMap - resultByMap(); - - // 使用foreach 迭代List - listForeach(); - - // 使用foreach 迭代数组 - array(); - - // 使用foreach 迭代对象数组 - objectForeach(); - - // 使用foreach 迭代对象集合 - batchInsertBlogList(); - } - - // ==================== 测试方法实现 ==================== - /** - * 1. 查询单个(根据ID查询User) - */ - private static void queryOne() { - try (SqlSession sqlSession = sqlSessionFactory.openSession(true)) { - UserMapper userMapper = sqlSession.getMapper(UserMapper.class); - User user = userMapper.findUserById(1); - System.out.println("===== 查询单个用户 ====="); - System.out.println(user == null ? "用户不存在" : user); - } catch (Exception e) { - e.printStackTrace(); - System.out.println("单个查询失败"); - } - } - - /** - * 2. 查询多个(查询所有User) - */ - private static void queryAll() { - try (SqlSession sqlSession = sqlSessionFactory.openSession(true)) { - UserMapper userMapper = sqlSession.getMapper(UserMapper.class); - List userList = userMapper.findAllUser(); - System.out.println("\n===== 查询所有用户 ====="); - userList.forEach(System.out::println); - } catch (Exception e) { - e.printStackTrace(); - System.out.println("批量查询失败"); - } - } - - /** - * 3. 增加(新增单个User) - */ - private static void add() { - try (SqlSession sqlSession = sqlSessionFactory.openSession(true)) { - UserMapper userMapper = sqlSession.getMapper(UserMapper.class); - User newUser = new User("MyBatis Add Test", 25, new Date()); - int affectedRows = userMapper.insertUser(newUser); - System.out.println("\n===== 新增用户 ====="); - System.out.println("新增受影响行数:" + affectedRows); - } catch (Exception e) { - e.printStackTrace(); - System.out.println("新增失败"); - } - } - - /** - * 4. 删除(根据ID删除User) - */ - private static void delete() { - try (SqlSession sqlSession = sqlSessionFactory.openSession(true)) { - UserMapper userMapper = sqlSession.getMapper(UserMapper.class); - int affectedRows = userMapper.deleteUserById(2); // 假设删除ID=2的用户 - System.out.println("\n===== 删除用户 ====="); - System.out.println("删除受影响行数:" + affectedRows); - } catch (Exception e) { - e.printStackTrace(); - System.out.println("删除失败"); - } - } - - /** - * 5. 修改(更新User信息) - */ - private static void update() { - try (SqlSession sqlSession = sqlSessionFactory.openSession(true)) { - UserMapper userMapper = sqlSession.getMapper(UserMapper.class); - User updateUser = new User(); - updateUser.setId(1); - updateUser.setUserName("MyBatis Update Test"); - updateUser.setAge(29); - int affectedRows = userMapper.updateUser(updateUser); - System.out.println("\n===== 修改用户 ====="); - System.out.println("修改受影响行数:" + affectedRows); - } catch (Exception e) { - e.printStackTrace(); - System.out.println("修改失败"); - } - } - - /** - * 6. 带转换器查询(根据发布时间查询Blog) - */ - private static void selectBlogByIdWithConverter() { - try (SqlSession sqlSession = sqlSessionFactory.openSession(true)) { - BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class); - Date publishTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2026-01-19 10:00:00"); - Blog blog = blogMapper.findBlogByPublishTime(publishTime); - System.out.println("\n===== 带转换器查询博客 ====="); - System.out.println(blog == null ? "博客不存在" : blog); - } catch (Exception e) { - e.printStackTrace(); - System.out.println("带转换器查询失败"); - } - } - - /** - * 7. 带转换器新增(新增Blog并使用自定义日期转换器) - */ - private static void addBlogWithConverter() { - try (SqlSession sqlSession = sqlSessionFactory.openSession(true)) { - BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class); - Blog newBlog = new Blog("转换器测试博客", "这是一篇带日期转换器的博客", new Date(), 1); - int affectedRows = blogMapper.insertBlogWithConverter(newBlog); - System.out.println("\n===== 带转换器新增博客 ====="); - System.out.println("新增受影响行数:" + affectedRows); - } catch (Exception e) { - e.printStackTrace(); - System.out.println("带转换器新增失败"); - } - } - - /** - * 8. 使用Map作为输入参数(查询Blog) - */ - private static void selectBlogWithHashMap() { - try (SqlSession sqlSession = sqlSessionFactory.openSession(true)) { - BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class); - Map paramMap = new HashMap<>(); - List authorIds = Arrays.asList(1, 2, 3); - paramMap.put("authorIds", authorIds); - List blogList = blogMapper.findBlogByMap(paramMap); - System.out.println("\n===== Map参数查询博客 ====="); - blogList.forEach(System.out::println); - } catch (Exception e) { - e.printStackTrace(); - System.out.println("Map参数查询失败"); - } - } - - /** - * 9. 返回值是HashMap(查询User并返回Map) - */ - private static void resultByMap() { - try (SqlSession sqlSession = sqlSessionFactory.openSession(true)) { - UserMapper userMapper = sqlSession.getMapper(UserMapper.class); - Map userMap = userMapper.findUserMapById(1); - System.out.println("\n===== 返回值为HashMap ====="); - userMap.forEach((key, value) -> System.out.println(key + ":" + value)); - } catch (Exception e) { - e.printStackTrace(); - System.out.println("HashMap返回失败"); - } - } - - /** - * 10. 使用foreach 迭代List(批量查询User) - */ - private static void listForeach() { - try (SqlSession sqlSession = sqlSessionFactory.openSession(true)) { - UserMapper userMapper = sqlSession.getMapper(UserMapper.class); - List idList = Arrays.asList(1, 3, 5); - List userList = userMapper.findUserListByIds(idList); - System.out.println("\n===== foreach迭代List ====="); - userList.forEach(System.out::println); - } catch (Exception e) { - e.printStackTrace(); - System.out.println("List foreach迭代失败"); - } - } - - /** - * 11. 使用foreach 迭代数组(批量删除User) - */ - private static void array() { - try (SqlSession sqlSession = sqlSessionFactory.openSession(true)) { - UserMapper userMapper = sqlSession.getMapper(UserMapper.class); - Integer[] idArray = new Integer[]{3, 4, 5}; - int affectedRows = userMapper.deleteUserByArray(idArray); - System.out.println("\n===== foreach迭代数组 ====="); - System.out.println("批量删除受影响行数:" + affectedRows); - } catch (Exception e) { - e.printStackTrace(); - System.out.println("数组 foreach迭代失败"); - } - } - - /** - * 12. 使用foreach 迭代对象数组(批量查询Blog) - */ - private static void objectForeach() { - try (SqlSession sqlSession = sqlSessionFactory.openSession(true)) { - BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class); - Blog[] blogArray = new Blog[2]; - blogArray[0] = new Blog(); - blogArray[0].setId(1); - blogArray[1] = new Blog(); - blogArray[1].setId(2); - List blogList = blogMapper.findBlogByObjectArray(blogArray); - System.out.println("\n===== foreach迭代对象数组 ====="); - blogList.forEach(System.out::println); - } catch (Exception e) { - e.printStackTrace(); - System.out.println("对象数组 foreach迭代失败"); - } - } - - /** - * 13. 使用foreach 迭代对象集合(批量新增Blog) - */ - private static void batchInsertBlogList() { - try (SqlSession sqlSession = sqlSessionFactory.openSession(true)) { - BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class); - List blogList = new ArrayList<>(); - blogList.add(new Blog("批量新增博客1", "批量插入内容1", new Date(), 1)); - blogList.add(new Blog("批量新增博客2", "批量插入内容2", new Date(), 1)); - int affectedRows = blogMapper.batchInsertBlog(blogList); - System.out.println("\n===== foreach迭代对象集合 ====="); - System.out.println("批量新增博客受影响行数:" + affectedRows); - } catch (Exception e) { - e.printStackTrace(); - System.out.println("对象集合 foreach迭代失败"); - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/User.java b/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/User.java deleted file mode 100644 index 884381f181..0000000000 --- a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/User.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.jun.plugin.mybatis; - -import java.util.Date; - -/** - * MyBatis 实体类:对应数据库user表 - * 字段映射: - * id → id(自增主键) - * userName → user_name(数据库列) - * age → age - * createTime → create_time(数据库列) - */ -public class User { - // 对应数据库表字段 - private Integer id; - private String userName; // 驼峰命名,适配MyBatis下划线转驼峰配置 - private Integer age; - private Date createTime; // 对应数据库列create_time,存储创建时间 - - // 无参构造器(MyBatis反射实例化必需,不可缺少) - public User() {} - - // 有参构造器(方便测试,快速创建用户对象,不含id(自增)) - public User(String userName, Integer age, Date createTime) { - this.userName = userName; - this.age = age; - this.createTime = createTime; - } - - // 全量getter/setter方法(MyBatis结果映射、属性赋值必需,不可缺少) - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - - public Integer getAge() { - return age; - } - - public void setAge(Integer age) { - this.age = age; - } - - public Date getCreateTime() { - return createTime; - } - - public void setCreateTime(Date createTime) { - this.createTime = createTime; - } - - // toString()方法(方便控制台打印对象信息,查看操作结果) - @Override - public String toString() { - return "User{" + - "id=" + id + - ", userName='" + userName + '\'' + - ", age=" + age + - ", createTime=" + createTime + - '}'; - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/UserMapper.java b/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/UserMapper.java deleted file mode 100644 index ed2c0d48f8..0000000000 --- a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/UserMapper.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.jun.plugin.mybatis; - -import org.apache.ibatis.annotations.*; - -import java.util.List; -import java.util.Map; - -/** - * User Mapper接口(包含基础CRUD、Map参数/返回值、foreach等) - */ -public interface UserMapper { - // ==== 基础CRUD ==== - // 新增 - @Insert("INSERT INTO user (user_name, age, create_time) VALUES (#{userName}, #{age}, #{createTime})") - int insertUser(User user); - - // 单个查询(根据ID) - @Select("SELECT id, user_name, age, create_time FROM user WHERE id = #{id}") - User findUserById(Integer id); - - // 批量查询(所有用户) - @Select("SELECT id, user_name, age, create_time FROM user ORDER BY id DESC") - List findAllUser(); - - // 修改(根据ID更新用户名和年龄) - @Update("UPDATE user SET user_name = #{userName}, age = #{age} WHERE id = #{id}") - int updateUser(User user); - - // 删除(根据ID) - @Delete("DELETE FROM user WHERE id = #{id}") - int deleteUserById(Integer id); - - // ==== Map相关 ==== - // 输入参数为Map(查询用户) - @Select("SELECT id, user_name, age, create_time FROM user WHERE user_name = #{userName} AND age = #{age}") - User findUserByMap(Map paramMap); - - // 返回值为HashMap(根据ID查询,键为数据库列名) - @Select("SELECT id, user_name, age, create_time FROM user WHERE id = #{id}") - Map findUserMapById(Integer id); - - // ==== foreach迭代 ==== - // foreach 迭代List(批量查询用户) - @Select("") - List findUserListByIds(@Param("idList") List idList); - - // foreach 迭代数组(批量删除用户) - @Delete("") - int deleteUserByArray(@Param("idArray") Integer[] idArray); - - // foreach 迭代对象数组(批量新增用户) - @Insert("") - int batchInsertUser(@Param("userArray") User[] userArray); - - // foreach 迭代对象集合(批量查询博客关联用户,复用User示例) - @Select("") - List findUserByBlogList(@Param("blogList") List blogList); -} \ No newline at end of file diff --git a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/Grade.java b/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/Grade.java deleted file mode 100644 index 616d6e999d..0000000000 --- a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/Grade.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.jun.plugin.mybatis.pojo; - -import lombok.Data; - -import java.util.List; - -/** - * @author LB - * @version 1.0 - * @date 2020/12/23 18:04 - */ -@Data -public class Grade { - //id - private List ids; -} diff --git a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/IBlogMapper.java b/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/IBlogMapper.java deleted file mode 100644 index d59d585b72..0000000000 --- a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/IBlogMapper.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.jun.plugin.mybatis.pojo; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * @author LB - * @version 1.0 - * @date 2020/12/22 16:18 - */ -public interface IBlogMapper { - /* 约定 - 省略statement 根据约定直接定位出sql语句 - 方法名和映射文件中的id值一样 - 方法的输入参数和映射文件中parameterType保持一致 - 方法的返回值和mapper.xml文件中的resultType类型一致 - - 调用到该方法就会自动映射到该标签 - namespace的值保证了 接口---xxxMapper之间的对应 - 保证了 我们在操作接口中的某一个方法的时候可以匹配到某一个mapper中的sql语句 - mapper接口不需要实现类 因为只需要找到对应的sql就ok - */ - List queryAll(); - - int addBlog(blog blog); - - int addBlogWithConverter(blog blog); - - int deleteBlogById(int id); - - int updateBlog(blog blog); - - blog selectBlogById(int id); - - blog selectBlogByIdWithConverter(int id); - - List selectBlogWithHashMap(HashMap map); - - List> ResultByMap(); - - List foreach(Grade grade); - - List arrayForeach(int[] ids2); - - List listForeach(List ids); - - List objectForeach(blog[] blogs); -} diff --git a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/blog.java b/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/blog.java deleted file mode 100644 index fe0c65fee3..0000000000 --- a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/blog.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.jun.plugin.mybatis.pojo; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.util.Date; - -/** - * @author LB - * @version 1.0 - * @date 2020/12/22 14:20 - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -public class blog { - private String id; - private String title; - private String authOr; - private String create_time; - private Integer views; - private Boolean sex; -} diff --git a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/blogMapper.xml b/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/blogMapper.xml deleted file mode 100644 index 69b11777de..0000000000 --- a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/blogMapper.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - - - - - - - - - insert into blog(id,title,author,create_time,views) values(#{id},#{title},#{authOr},#{create_time},#{views}) - - - - - delete from blog where id =#{id} - - - - update blog set title=#{title},authoR=#{authOr},create_time=#{create_time},views=#{views} where id =#{id} - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/blogMapperInterface.xml b/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/blogMapperInterface.xml deleted file mode 100644 index 9bb11799ca..0000000000 --- a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/blogMapperInterface.xml +++ /dev/null @@ -1,106 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - insert into blog(id,title,author,create_time,views) values(#{id},#{title},#{authOr},#{create_time},#{views}) - - - - insert into blog(id,title,author,create_time,views,sex) values(#{id},#{title},#{authOr},#{create_time},#{views},#{sex, javaType=boolean,jdbcType=INTEGER}) - - - - delete from blog where id =#{id} - - - - update blog set title=#{title},authoR=#{authOr},create_time=#{create_time},views=#{views} where id =#{id} - - - - - - - - - - - - - diff --git a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/student.java b/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/student.java deleted file mode 100644 index 74c9469ef3..0000000000 --- a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/student.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.jun.plugin.mybatis.pojo; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * @author LB - * @version 1.0 - * @date 2020/12/22 17:11 - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -public class student { - private Integer id; - private String name; - private Boolean sex; //true男 false女 - private String classId; -} diff --git a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/studentClass.java b/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/studentClass.java deleted file mode 100644 index 4b98bc1b7a..0000000000 --- a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/studentClass.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.jun.plugin.mybatis.pojo; - -import lombok.Data; - -import java.util.List; - -/** - * @author LB - * @version 1.0 - * @date 2020/12/23 21:08 - */ -@Data -public class studentClass { - private Integer classId; - private String className; - //通过该字段将student和studentClass之间建立起来联系 - private List students; -} diff --git a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/studentClassMapper.java b/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/studentClassMapper.java deleted file mode 100644 index d285488abf..0000000000 --- a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/studentClassMapper.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.jun.plugin.mybatis.pojo; - -/** - * @author LB - * @version 1.0 - * @date 2020/12/23 21:11 - */ -public interface studentClassMapper { - studentClass querystudentAndClassLazy(int classId); -} diff --git a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/studentClassMapper.xml b/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/studentClassMapper.xml deleted file mode 100644 index 984bbb50b0..0000000000 --- a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/studentClassMapper.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/studentMapper.java b/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/studentMapper.java deleted file mode 100644 index f054c80d0e..0000000000 --- a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/studentMapper.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.jun.plugin.mybatis.pojo; - -/** - * @author LB - * @version 1.0 - * @date 2020/12/23 21:11 - */ -public interface studentMapper { - studentClass querystudentAndClass(int id); - student testTf(int id); -} diff --git a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/studentMapper.xml b/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/studentMapper.xml deleted file mode 100644 index 72ae087d16..0000000000 --- a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/pojo/studentMapper.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/test/DemoTest1.java b/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/test/DemoTest1.java deleted file mode 100644 index ec0b466bb1..0000000000 --- a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/test/DemoTest1.java +++ /dev/null @@ -1,140 +0,0 @@ -package com.jun.plugin.mybatis.test; - -import org.apache.ibatis.io.Resources; -import org.apache.ibatis.session.SqlSession; -import org.apache.ibatis.session.SqlSessionFactory; -import org.apache.ibatis.session.SqlSessionFactoryBuilder; - -import com.jun.plugin.mybatis.pojo.blog; - -import java.io.IOException; -import java.io.InputStream; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.List; - -/** - * @author LB - * @version 1.0 - * @date 2020/12/22 14:25 - */ -public class DemoTest1 { - public static void main(String[] args) { - //查询单个blog - // queryOne(); - - //查询多个 - // queryAll(); - //增加 - add(); - //删除 - //delete(); - //修改 - update(); - - } - - private static void update() { - String resource = "mybatis-config.xml"; - InputStream inputStream = null; - SqlSession sqlSession =null; - try { - inputStream = Resources.getResourceAsStream(resource); - SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); - sqlSession = sqlSessionFactory.openSession(); - String statement = "com.jun.plugin.mybatis.pojo.blogMapper.updateBlog"; - blog blog =new blog("99","测试","yznl2","2020-12-22 15.52.22",1,true); - int count = sqlSession.delete(statement,blog); - //JDBC 方式 需要手动commit - sqlSession.commit(); - System.out.println("修改"+count+"个"); - } catch (IOException e) { - e.printStackTrace(); - }finally{ - sqlSession.close(); - } - } - - private static void delete() { - String resource = "mybatis-config.xml"; - InputStream inputStream = null; - SqlSession sqlSession =null; - try { - inputStream = Resources.getResourceAsStream(resource); - SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); - sqlSession = sqlSessionFactory.openSession(); - String statement = "com.jun.plugin.mybatis.pojo.blogMapper.deleteBlogById"; - int id = 99; - int count = sqlSession.delete(statement,id); - //JDBC 方式 需要手动commit - sqlSession.commit(); - System.out.println("删除"+count+"个"); - } catch (IOException e) { - e.printStackTrace(); - }finally{ - sqlSession.close(); - } - } - - private static void add() { - String resource = "mybatis-config.xml"; - InputStream inputStream = null; - SqlSession sqlSession =null; - try { - inputStream = Resources.getResourceAsStream(resource); - SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); - sqlSession = sqlSessionFactory.openSession(); - String statement = "com.jun.plugin.mybatis.pojo.blogMapper.addBlog"; - blog blog =new blog("99","测试","yznl","2020-12-22 15.52.22",1,true); - int count = sqlSession.insert(statement,blog); - //JDBC 方式 需要手动commit - sqlSession.commit(); - System.out.println("增加了"+count+"个"); - } catch (IOException e) { - e.printStackTrace(); - }finally{ - sqlSession.close(); - } - } - - private static void queryAll() { - String resource = "mybatis-config.xml"; - InputStream inputStream = null; - SqlSession sqlSession =null; - try { - inputStream = Resources.getResourceAsStream(resource); - SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); - sqlSession = sqlSessionFactory.openSession(); - String statement = "com.jun.plugin.mybatis.pojo.blogMapper.queryAll"; - //动态代理 动态的将Object转换为blog - List blogs = sqlSession.selectList(statement); - System.out.println(blogs.size()); - } catch (IOException e) { - e.printStackTrace(); - }finally{ - sqlSession.close(); - } - } - - public static void queryOne(){ - String resource = "mybatis-config.xml"; - InputStream inputStream = null; - SqlSession sqlSession =null; - try { - inputStream = Resources.getResourceAsStream(resource); - SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); - sqlSession = sqlSessionFactory.openSession(); - String statement = "com.jun.plugin.mybatis.pojo.blogMapper.selectBlogById"; - String statement2 = "com.jun.plugin.mybatis.pojo.blogMapper.time"; - //动态代理 动态的将Object转换为blog - blog blog = sqlSession.selectOne(statement,1); - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - //String times = sqlSession.selectOne(statement2,2); - System.out.println(blog); - } catch (IOException e) { - e.printStackTrace(); - }finally{ - sqlSession.close(); - } - } -} diff --git a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/test/DemoTest2.java b/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/test/DemoTest2.java deleted file mode 100644 index a17551729b..0000000000 --- a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/test/DemoTest2.java +++ /dev/null @@ -1,358 +0,0 @@ -package com.jun.plugin.mybatis.test; - -import org.apache.ibatis.io.Resources; -import org.apache.ibatis.session.SqlSession; -import org.apache.ibatis.session.SqlSessionFactory; -import org.apache.ibatis.session.SqlSessionFactoryBuilder; - -import com.jun.plugin.mybatis.pojo.Grade; -import com.jun.plugin.mybatis.pojo.IBlogMapper; -import com.jun.plugin.mybatis.pojo.blog; - -import java.io.IOException; -import java.io.InputStream; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -/** - * @author LB - * @version 1.0 - * @date 2020/12/22 14:25 - */ -public class DemoTest2 { - - public static void main(String[] args) { - //查询单个 - //queryOne(); - - //查询多个 - //queryAll(); - - //增加 - //add(); - - //删除 - //delete(); - - //修改 - //update(); - - //带转换器 - //selectBlogByIdWithConverter(); - - //添加 转换器 - //addBlogWithConverter(); - - //使用map作为输入参数 - //SelectBlogWithHashMap(); - - //返回值是HashMap - //ResultByMap(); - - //使用foreach 迭代对象数组 - //foreach(); - - //使用foreach 迭代对象数组 - //array(); - - //使用foreach 迭代集合 - //listForeach(); - - //使用foreach 迭代对象数组 - objectForeach(); - } - - private static void objectForeach() { - String resource="mybatis-config.xml"; - InputStream inputStream = null; - SqlSession sqlSession =null; - try { - inputStream = Resources.getResourceAsStream(resource); - SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); - sqlSession = sqlSessionFactory.openSession(); - IBlogMapper blogMapper = sqlSession.getMapper(IBlogMapper.class); - blog blog1 = new blog(); blog1.setTitle("1"); - blog blog2 = new blog(); blog2.setTitle("2"); - blog blog3 = new blog(); blog3.setTitle("2"); - blog[] blogs ={blog1,blog2,blog3}; - List blogArray = blogMapper.objectForeach(blogs); - for (blog blog : blogArray) { - System.out.println("这个blog是"+blog); - } - //JDBC 方式 需要手动commit - sqlSession.commit(); - } catch (IOException e) { - e.printStackTrace(); - }finally{ - //sqlSession.close(); - } - } - - private static void listForeach() { - String resource="mybatis-config.xml"; - InputStream inputStream = null; - SqlSession sqlSession =null; - try { - inputStream = Resources.getResourceAsStream(resource); - SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); - sqlSession = sqlSessionFactory.openSession(); - IBlogMapper blogMapper = sqlSession.getMapper(IBlogMapper.class); - ArrayList ids = new ArrayList(); - ids.add(1); ids.add(2); - List blogs = blogMapper.listForeach(ids); - for (blog blog : blogs) { - System.out.println("这个blog是"+blog); - } - //JDBC 方式 需要手动commit - sqlSession.commit(); - } catch (IOException e) { - e.printStackTrace(); - }finally{ - //sqlSession.close(); - } - } - - //foreach 迭代集合 - private static void foreach() { - String resource="mybatis-config.xml"; - InputStream inputStream = null; - SqlSession sqlSession =null; - try { - inputStream = Resources.getResourceAsStream(resource); - SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); - sqlSession = sqlSessionFactory.openSession(); - IBlogMapper blogMapper = sqlSession.getMapper(IBlogMapper.class); - Grade grade = new Grade(); - ArrayList ids = new ArrayList(); - ids.add(1); ids.add(2); - grade.setIds(ids); - List blogs = blogMapper.foreach(grade); - for (blog blog : blogs) { - System.out.println("这个blog是"+blog); - } - //JDBC 方式 需要手动commit - sqlSession.commit(); - } catch (IOException e) { - e.printStackTrace(); - }finally{ - //sqlSession.close(); - } - } - - private static void array() { - String resource="mybatis-config.xml"; - InputStream inputStream = null; - SqlSession sqlSession =null; - try { - inputStream = Resources.getResourceAsStream(resource); - SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); - sqlSession = sqlSessionFactory.openSession(); - IBlogMapper blogMapper = sqlSession.getMapper(IBlogMapper.class); - Grade grade = new Grade(); - int[] ids2 = new int[10]; - ids2[0] = 1; ids2[1] = 2; - List blogs = blogMapper.arrayForeach(ids2); - for (blog blog : blogs) { - System.out.println("这个blog是"+blog); - } - //JDBC 方式 需要手动commit - sqlSession.commit(); - } catch (IOException e) { - e.printStackTrace(); - }finally{ - //sqlSession.close(); - } - } - - //查询Blog结果为Map类型 - private static void ResultByMap() { - String resource="mybatis-config.xml"; - InputStream inputStream = null; - SqlSession sqlSession =null; - try { - inputStream = Resources.getResourceAsStream(resource); - SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); - sqlSession = sqlSessionFactory.openSession(); - IBlogMapper blogMapper = sqlSession.getMapper(IBlogMapper.class); - List> hashMaps = blogMapper.ResultByMap(); - for (HashMap hashMap : hashMaps) { - System.out.println(hashMap); - } - - //JDBC 方式 需要手动commit - sqlSession.commit(); - } catch (IOException e) { - e.printStackTrace(); - }finally{ - //sqlSession.close(); - } - } - - private static void SelectBlogWithHashMap() { - String resource="mybatis-config.xml"; - InputStream inputStream = null; - SqlSession sqlSession =null; - try { - inputStream = Resources.getResourceAsStream(resource); - SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); - sqlSession = sqlSessionFactory.openSession(); - IBlogMapper blogMapper = sqlSession.getMapper(IBlogMapper.class); - HashMap map = new HashMap(); - map.put("id",999); - List list = blogMapper.selectBlogWithHashMap(map); - System.out.println("一共拥有"+list.size()+"个"); - //JDBC 方式 需要手动commit - sqlSession.commit(); - } catch (IOException e) { - e.printStackTrace(); - }finally{ - sqlSession.close(); - } - } - - private static void addBlogWithConverter() { - String resource = "mybatis-config.xml"; - InputStream inputStream = null; - SqlSession sqlSession =null; - try { - inputStream = Resources.getResourceAsStream(resource); - SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); - sqlSession = sqlSessionFactory.openSession(); - IBlogMapper blogMapper = sqlSession.getMapper(IBlogMapper.class); - blog blog =new blog("999","测试","sex测试","2020-12-22 15.52.22",1,true); - int addCount = blogMapper.addBlogWithConverter(blog); - System.out.println("添加了"+addCount+"个"); - //JDBC 方式 需要手动commit - sqlSession.commit(); - System.out.println(blog); - } catch (IOException e) { - e.printStackTrace(); - }finally{ - sqlSession.close(); - } - } - - private static void selectBlogByIdWithConverter() { - String resource = "mybatis-config.xml"; - InputStream inputStream = null; - SqlSession sqlSession =null; - try { - inputStream = Resources.getResourceAsStream(resource); - SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); - sqlSession = sqlSessionFactory.openSession(); - IBlogMapper blogMapper = sqlSession.getMapper(IBlogMapper.class); - blog blog = blogMapper.selectBlogByIdWithConverter(1); - //JDBC 方式 需要手动commit - sqlSession.commit(); - System.out.println(blog); - } catch (IOException e) { - e.printStackTrace(); - }finally{ - sqlSession.close(); - } - } - - private static void update() { - String resource = "mybatis-config.xml"; - InputStream inputStream = null; - SqlSession sqlSession =null; - try { - inputStream = Resources.getResourceAsStream(resource); - SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); - sqlSession = sqlSessionFactory.openSession(); - IBlogMapper blogMapper = sqlSession.getMapper(IBlogMapper.class); - blog blog =new blog("999","测试","yznl2","2020-12-22 15.52.22",1,true); - int count = blogMapper.updateBlog(blog); - //JDBC 方式 需要手动commit - sqlSession.commit(); - System.out.println("修改"+count+"个"); - } catch (IOException e) { - e.printStackTrace(); - }finally{ - sqlSession.close(); - } - } - - private static void delete() { - String resource = "mybatis-config.xml"; - InputStream inputStream = null; - SqlSession sqlSession =null; - try { - inputStream = Resources.getResourceAsStream(resource); - SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); - sqlSession = sqlSessionFactory.openSession(); - IBlogMapper blogMapper = sqlSession.getMapper(IBlogMapper.class); - int id = 99; - int count = blogMapper.deleteBlogById(id); - //JDBC 方式 需要手动commit - sqlSession.commit(); - System.out.println("删除"+count+"个"); - } catch (IOException e) { - e.printStackTrace(); - }finally{ - sqlSession.close(); - } - } - - private static void add() { - String resource = "mybatis-config.xml"; - InputStream inputStream = null; - SqlSession sqlSession =null; - try { - inputStream = Resources.getResourceAsStream(resource); - SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); - sqlSession = sqlSessionFactory.openSession(); - IBlogMapper blogMapper = sqlSession.getMapper(IBlogMapper.class); - blog blog =new blog("222","1测试","yznl","2020-12-22 15.52.22",1,false); - int count = blogMapper.addBlog(blog); - //JDBC 方式 需要手动commit - sqlSession.commit(); - System.out.println("增加了"+count+"个"); - } catch (IOException e) { - e.printStackTrace(); - }finally{ - sqlSession.close(); - sqlSession.close(); - } - } - - private static void queryAll() { - String resource = "mybatis-config.xml"; - InputStream inputStream = null; - SqlSession sqlSession =null; - try { - inputStream = Resources.getResourceAsStream(resource); - SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); - sqlSession = sqlSessionFactory.openSession(); - IBlogMapper blogMapper = sqlSession.getMapper(IBlogMapper.class); - //动态代理 动态的将Object转换为blog - List blogs = blogMapper.queryAll(); - System.out.println(blogs.size()); - } catch (IOException e) { - e.printStackTrace(); - }finally{ - sqlSession.close(); - } - } - - public static void queryOne(){ - String resource = "mybatis-config.xml"; - InputStream inputStream = null; - SqlSession sqlSession =null; - try { - inputStream = Resources.getResourceAsStream(resource); - SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); - sqlSession = sqlSessionFactory.openSession(); - //动态代理 动态的将Object转换为blog - IBlogMapper blogMapper = sqlSession.getMapper(IBlogMapper.class); - blog blog = blogMapper.selectBlogById(1); - System.out.println(blog); - } catch (IOException e) { - e.printStackTrace(); - }finally{ - sqlSession.close(); - } - } -} diff --git a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/test/DemoTest3.java b/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/test/DemoTest3.java deleted file mode 100644 index 37e3c014e5..0000000000 --- a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/test/DemoTest3.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.jun.plugin.mybatis.test; - -import org.apache.ibatis.io.Resources; -import org.apache.ibatis.session.SqlSession; -import org.apache.ibatis.session.SqlSessionFactory; -import org.apache.ibatis.session.SqlSessionFactoryBuilder; - -import com.jun.plugin.mybatis.pojo.*; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -/** - * @author LB - * @version 1.0 - * @date 2020/12/22 14:25 - */ -public class DemoTest3 { - - public static void main(String[] args) { - //一对多查询 - querystudentAndClass(); - //测试驼峰转换 - //testTf(); - //一对多查询 延迟加载 - querystudentAndClassLazy(); - } - - private static void querystudentAndClassLazy() { - String resource="mybatis-config.xml"; - InputStream inputStream = null; - SqlSession sqlSession =null; - try { - inputStream = Resources.getResourceAsStream(resource); - SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); - sqlSession = sqlSessionFactory.openSession(); - studentClassMapper studentMapper = sqlSession.getMapper(studentClassMapper.class); - studentClass studentClass = studentMapper.querystudentAndClassLazy(1); - System.out.println(studentClass.getClassId()+"==="+studentClass.getClassName()); - //JDBC 方式 需要手动commit - sqlSession.commit(); - } catch (IOException e) { - e.printStackTrace(); - }finally{ - sqlSession.close(); - } - } - - private static void testTf() { - String resource="mybatis-config.xml"; - InputStream inputStream = null; - SqlSession sqlSession =null; - try { - inputStream = Resources.getResourceAsStream(resource); - SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); - sqlSession = sqlSessionFactory.openSession(); - studentMapper studentMapper = sqlSession.getMapper(studentMapper.class); - student student = studentMapper.testTf(2); - System.out.println(student); - //JDBC 方式 需要手动commit - sqlSession.commit(); - } catch (IOException e) { - e.printStackTrace(); - }finally{ - //sqlSession.close(); - } - } - - private static void querystudentAndClass() { - String resource="mybatis-config.xml"; - InputStream inputStream = null; - SqlSession sqlSession =null; - try { - inputStream = Resources.getResourceAsStream(resource); - SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); - sqlSession = sqlSessionFactory.openSession(); - studentMapper studentMapper = sqlSession.getMapper(studentMapper.class); - studentClass studentClass = studentMapper.querystudentAndClass(1); - System.out.println(studentClass); - //JDBC 方式 需要手动commit - sqlSession.commit(); - } catch (IOException e) { - e.printStackTrace(); - }finally{ - //sqlSession.close(); - } - } - - - -} diff --git "a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/test/\345\205\263\350\201\224\346\237\245\350\257\242.txt" "b/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/test/\345\205\263\350\201\224\346\237\245\350\257\242.txt" deleted file mode 100644 index 4ecec87b71..0000000000 --- "a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/test/\345\205\263\350\201\224\346\237\245\350\257\242.txt" +++ /dev/null @@ -1,34 +0,0 @@ -关联查询 -一对一: 业务扩展类 - -一对一: resultMap 将其中的一个类作为属性作为其中的一个类的成员 - - - - - - - - - - - - - - 一对多 collection 关联: - 通过该字段将student和studentClass之间建立起来联系 - private List students; - - diff --git "a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/test/\345\212\250\346\200\201sql" "b/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/test/\345\212\250\346\200\201sql" deleted file mode 100644 index 5873ecbf26..0000000000 --- "a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/test/\345\212\250\346\200\201sql" +++ /dev/null @@ -1,67 +0,0 @@ - 语句会自动处理第一个 标签中的 and 但不会处理之后的 - - 查询id为 1,2,3的信息 -迭代的类型: 数组 对象数组 集合 属性类(Grade类: List ids) -ids={1,2,53} -select stuno,stuname,stuAge from student where stuno in(ids) - - -其中的参数 先拼接open 然后就是item的东西 之后就是close中的东西 - - - - - - - - - - - - - - \ No newline at end of file diff --git "a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/test/\345\217\202\346\225\260\344\270\215\344\270\200\350\207\264.txt" "b/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/test/\345\217\202\346\225\260\344\270\215\344\270\200\350\207\264.txt" deleted file mode 100644 index e56b5b1bf6..0000000000 --- "a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/test/\345\217\202\346\225\260\344\270\215\344\270\200\350\207\264.txt" +++ /dev/null @@ -1,5 +0,0 @@ -当属性名字和字段名不一致的时候,除了使用resultMap以外,还可以使用resultType + HashMap - - \ No newline at end of file diff --git "a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/test/\345\273\266\350\277\237\345\212\240\350\275\275.txt" "b/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/test/\345\273\266\350\277\237\345\212\240\350\275\275.txt" deleted file mode 100644 index 4cb43ac357..0000000000 --- "a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/test/\345\273\266\350\277\237\345\212\240\350\275\275.txt" +++ /dev/null @@ -1,23 +0,0 @@ -需要再写一个mapper文件 和 sql语句 -建立 studentClassMapper.xml - -一对多延迟加载 - -mybatis中的延迟加载 需要配置 - - - - - - - - - - - - - - \ No newline at end of file diff --git "a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/test/\346\227\245\345\277\227Log4uj.txt" "b/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/test/\346\227\245\345\277\227Log4uj.txt" deleted file mode 100644 index 86b94b1a8e..0000000000 --- "a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/test/\346\227\245\345\277\227Log4uj.txt" +++ /dev/null @@ -1,16 +0,0 @@ -log4j的jar - - log4j - log4j - 1.2.17 - - -开启日志 - - - - -编写配置日志输出文件 log4j.propertis - -日志级别: 从高到低 ERROR、WARN、INFO、DEBUG -如果设置为INFO 则只会先是info及以上级别的信息 \ No newline at end of file diff --git "a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/test/\350\276\223\345\205\245\345\217\202\346\225\260\350\257\264\346\230\216.txt" "b/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/test/\350\276\223\345\205\245\345\217\202\346\225\260\350\257\264\346\230\216.txt" deleted file mode 100644 index 00d6389eea..0000000000 --- "a/jun_java_plugins/jun_mybatis/src/main/java/com/jun/plugin/mybatis/test/\350\276\223\345\205\245\345\217\202\346\225\260\350\257\264\346\230\216.txt" +++ /dev/null @@ -1,19 +0,0 @@ -输入参数是: parameterType -1:类型是简单类型(8个基本类型+String) -#{}和${} -#{任意值} -${value} -#{}自动给String类型加上‘’ (自动类型转换) -${} 原样输出 但是适合于 动态排序 (动态转换) - -select stuno,stuname,stuage from student where stuname =#{value} -select stuno,stuname,stuage from student where stuname ='${value}' - -动态排序 重点是 不加'' -select * from student order by ${value} asc - -#{} 可以放置sql注入 不适合like 在传入值得时候就应该加上 %% -${} 这个不可以 适合like eg: '%${stuNo}%' - -级联属性 -select * from studentwhere homeaddress = #{address.homeAddress} or schooladdress = '${address.schoolAddress}' \ No newline at end of file diff --git a/jun_java_plugins/jun_mybatis/src/main/resources/db.properties b/jun_java_plugins/jun_mybatis/src/main/resources/db.properties deleted file mode 100644 index 4d57bd8998..0000000000 --- a/jun_java_plugins/jun_mybatis/src/main/resources/db.properties +++ /dev/null @@ -1,4 +0,0 @@ -driver=com.mysql.cj.jdbc.Driver -url=jdbc:mysql://localhost:3307/mybatis?serverTimezone=UTC&characterEncoding=utf-8 -username=root -password=123456 \ No newline at end of file diff --git a/jun_java_plugins/jun_mybatis/src/main/resources/log4j.properties b/jun_java_plugins/jun_mybatis/src/main/resources/log4j.properties deleted file mode 100644 index b659fa860e..0000000000 --- a/jun_java_plugins/jun_mybatis/src/main/resources/log4j.properties +++ /dev/null @@ -1,9 +0,0 @@ -# 控制台输出配置 -log4j.appender.Console=org.apache.log4j.ConsoleAppender -log4j.appender.Console.layout=org.apache.log4j.PatternLayout -log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n -log4j.appender.Console.encoding=UTF-8 - - -#指定日志的输出级别与输出端 -log4j.rootLogger=DEBUG,Console \ No newline at end of file diff --git a/jun_java_plugins/jun_mybatis/src/main/resources/mybatis-config.xml b/jun_java_plugins/jun_mybatis/src/main/resources/mybatis-config.xml deleted file mode 100644 index ee9f787bb3..0000000000 --- a/jun_java_plugins/jun_mybatis/src/main/resources/mybatis-config.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_mybatisplus/pom.xml b/jun_java_plugins/jun_mybatisplus/pom.xml deleted file mode 100644 index fb5b635509..0000000000 --- a/jun_java_plugins/jun_mybatisplus/pom.xml +++ /dev/null @@ -1,162 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_mybatisplus - jar - 1.0 - - - 1.8 - 1.8 - - 5.1.9.RELEASE - - - - - - com.baomidou - mybatis-plus - 3.0.3 - - - - junit - junit - 4.9 - - - - log4j - log4j - 1.2.17 - - - - com.mchange - c3p0 - 0.9.5.4 - - - - mysql - mysql-connector-java - 8.0.11 - - - - org.springframework - spring-orm - 4.3.10.RELEASE - - - - org.projectlombok - lombok - 1.18.2 - provided - - - - - - org.springframework - spring-core - ${spring.version} - - - - - org.springframework - spring-beans - ${spring.version} - - - - org.springframework - spring-context - ${spring.version} - - - - org.springframework - spring-jdbc - ${spring.version} - - - org.springframework - spring-tx - ${spring.version} - - - org.springframework - spring-web - ${spring.version} - - - org.springframework - spring-webmvc - ${spring.version} - - - org.springframework - spring-test - ${spring.version} - test - - - - - javax.servlet - javax.servlet-api - 3.1.0 - - - - com.fasterxml.jackson.core - jackson-databind - 2.9.10.1 - - - - org.slf4j - slf4j-api - 1.7.25 - - - org.slf4j - slf4j-log4j12 - 1.7.25 - - - - org.apache.velocity - velocity-engine-core - 2.0 - - - org.freemarker - freemarker - 2.3.9 - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.1 - - 8 - 8 - UTF-8 - - - - - diff --git a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/CodeGenerator.java b/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/CodeGenerator.java deleted file mode 100644 index ef5903902e..0000000000 --- a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/CodeGenerator.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.jun.plugin.mybatisplus; - -import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException; -import com.baomidou.mybatisplus.core.toolkit.StringPool; -import com.baomidou.mybatisplus.core.toolkit.StringUtils; -import com.baomidou.mybatisplus.generator.AutoGenerator; -import com.baomidou.mybatisplus.generator.InjectionConfig; -import com.baomidou.mybatisplus.generator.config.*; -import com.baomidou.mybatisplus.generator.config.po.TableInfo; -import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; -import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; - -import java.util.ArrayList; -import java.util.List; -import java.util.Scanner; - -public class CodeGenerator { - - /** - *

- * 读取控制台内容 - *

- */ - public static String scanner(String tip) { - Scanner scanner = new Scanner(System.in); - StringBuilder help = new StringBuilder(); - help.append("请输入" + tip + ":"); - System.out.println(help.toString()); - if (scanner.hasNext()) { - String ipt = scanner.next(); - if (StringUtils.isNotEmpty(ipt)) { - return ipt; - } - } - throw new MybatisPlusException("请输入正确的" + tip + "!"); - } - - public static void main(String[] args) { - // 代码生成器 - AutoGenerator mpg = new AutoGenerator(); - - // 全局配置 - GlobalConfig gc = new GlobalConfig(); - final String projectPath = System.getProperty("user.dir"); - gc.setOutputDir(projectPath + "/MyBatisGenerator/src/main/java"); - gc.setAuthor("bzcoder"); - gc.setEnableCache(true); - gc.setOpen(false); - gc.setBaseResultMap(true); - gc.setBaseColumnList(true); - mpg.setGlobalConfig(gc); - - // 数据源配置 - DataSourceConfig dsc = new DataSourceConfig(); - - dsc.setUrl("jdbc:mysql://192.168.15.128:3306/myBatisPlus?useUnicode=true&useSSL=false&characterEncoding=utf8"); - // dsc.setSchemaName("public"); - dsc.setDriverName("com.mysql.cj.jdbc.Driver"); - dsc.setUsername("root"); - dsc.setPassword("123456"); - mpg.setDataSource(dsc); - - // 包配置 - final PackageConfig pc = new PackageConfig(); - pc.setModuleName(scanner("")); - pc.setParent("com.bzcoder"); - mpg.setPackageInfo(pc); - - // 自定义配置 - InjectionConfig cfg = new InjectionConfig() { - @Override - public void initMap() { - // to do nothing - } - }; - List focList = new ArrayList<>(); - focList.add(new FileOutConfig("/templates/mapper.xml.ftl") { - @Override - public String outputFile(TableInfo tableInfo) { - // 自定义输入文件名称 - return projectPath + "/MyBatisGenerator/src/main/resources/mapper/" + pc.getModuleName() - + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; - } - }); - cfg.setFileOutConfigList(focList); - - mpg.setCfg(cfg); - mpg.setTemplate(new TemplateConfig().setXml(null)); - - // 策略配置 - StrategyConfig strategy = new StrategyConfig(); - strategy.setNaming(NamingStrategy.underline_to_camel); - strategy.setColumnNaming(NamingStrategy.underline_to_camel); - strategy.setSuperEntityClass("com.baomidou.ant.common.BaseEntity"); - strategy.setEntityLombokModel(true); - strategy.setRestControllerStyle(true); - strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController"); - strategy.setInclude("tbl_employee","tbl_company"); - strategy.setSuperEntityColumns("id"); - strategy.setControllerMappingHyphenStyle(true); - strategy.setTablePrefix(pc.getModuleName() + "_"); - mpg.setStrategy(strategy); - mpg.setTemplateEngine(new FreemarkerTemplateEngine()); - mpg.execute(); - } - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/entity/Company.java b/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/entity/Company.java deleted file mode 100644 index 2ec53281c7..0000000000 --- a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/entity/Company.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.jun.plugin.mybatisplus.biz.entity; - -import com.baomidou.mybatisplus.annotation.IdType; -import com.baomidou.mybatisplus.annotation.TableId; -import com.baomidou.mybatisplus.extension.activerecord.Model; -import lombok.Data; - -import java.io.Serializable; - -/** - * 活动模式 - * @author BaoZhou - * @date 2018/10/1 - */ -@Data -public class Company extends Model { - @TableId(value = "id",type = IdType.AUTO) - private Integer id; - private String name; - private String owner; - private String location; - private Integer status; - /** - * @return 返回当前表的主键 - */ - @Override - protected Serializable pkVal() { - return id; - } -} - - diff --git a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/entity/Employee.java b/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/entity/Employee.java deleted file mode 100644 index 51259d6f8f..0000000000 --- a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/entity/Employee.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jun.plugin.mybatisplus.biz.entity; - -import com.baomidou.mybatisplus.annotation.IdType; -import com.baomidou.mybatisplus.annotation.TableId; -import lombok.Data; - -/** - * @author BaoZhou - * @date 2018/10/1 - */ -@Data -public class Employee { - @TableId(value = "id",type = IdType.AUTO) - private Integer id; - private String lastName; - private String email; - private Integer gender; - private Integer age; -} - - diff --git a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/mapper/CompanyMapper.java b/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/mapper/CompanyMapper.java deleted file mode 100644 index 2ce5bdc291..0000000000 --- a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/mapper/CompanyMapper.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.jun.plugin.mybatisplus.biz.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.jun.plugin.mybatisplus.biz.entity.Company; - -/** - * @author BaoZhou - * @date 2018/10/2 - */ -public interface CompanyMapper extends BaseMapper { -} diff --git a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/mapper/EmployeeMapper.java b/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/mapper/EmployeeMapper.java deleted file mode 100644 index f1d1c2fc0d..0000000000 --- a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/mapper/EmployeeMapper.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.jun.plugin.mybatisplus.biz.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.jun.plugin.mybatisplus.biz.entity.Employee; - -/** - * Mapper接口 - * - * @author BaoZhou - * @date 2018/10/1 - */ -public interface EmployeeMapper extends BaseMapper { -} diff --git a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/MyMetaObjectHandler.java b/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/MyMetaObjectHandler.java deleted file mode 100644 index 18fd09d4ed..0000000000 --- a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/MyMetaObjectHandler.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.jun.plugin.mybatisplus.biz.test; - -import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; -import org.apache.ibatis.reflection.MetaObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - -/** - * 自定义公共字段处理器 - * @author: BaoZhou - * @date : 2018/10/8 22:41 - */ -public class MyMetaObjectHandler implements MetaObjectHandler { - - private static final Logger LOGGER = LoggerFactory.getLogger(MyMetaObjectHandler.class); - - /** - * 插入操作自动填充 - */ - @Override - public void insertFill(MetaObject metaObject) { - LOGGER.info("start insert fill ...."); - this.setFieldValByName("age", 99, metaObject); - } - - /** - * 更新操作自动填充 - */ - @Override - public void updateFill(MetaObject metaObject) { - LOGGER.info("start update fill ...."); - this.setFieldValByName("age", 98, metaObject); - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/controller/CompanyController.java b/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/controller/CompanyController.java deleted file mode 100644 index 96eb4b0695..0000000000 --- a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/controller/CompanyController.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jun.plugin.mybatisplus.biz.test.controller; - - -import org.springframework.web.bind.annotation.RequestMapping; - -import org.springframework.stereotype.Controller; - -/** - *

- * 前端控制器 - *

- * - * @author BaoZhou - * @since 2018-10-03 - */ -@Controller -@RequestMapping("/test/company") -public class CompanyController { - -} - diff --git a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/controller/EmployeeController.java b/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/controller/EmployeeController.java deleted file mode 100644 index 214bebbf42..0000000000 --- a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/controller/EmployeeController.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jun.plugin.mybatisplus.biz.test.controller; - - -import org.springframework.web.bind.annotation.RequestMapping; - -import org.springframework.stereotype.Controller; - -/** - *

- * 前端控制器 - *

- * - * @author BaoZhou - * @since 2018-10-03 - */ -@Controller -@RequestMapping("/test/employee") -public class EmployeeController { - -} - diff --git a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/entity/Company.java b/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/entity/Company.java deleted file mode 100644 index 965db1747a..0000000000 --- a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/entity/Company.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.jun.plugin.mybatisplus.biz.test.entity; - -import com.baomidou.mybatisplus.annotation.*; -import com.baomidou.mybatisplus.extension.activerecord.Model; - -import java.io.Serializable; - -/** - *

- * - *

- * - * @author BaoZhou - * @since 2018-10-03 - */ -@TableName("tbl_company") -public class Company extends Model { - - private static final long serialVersionUID = 1L; - - @TableId(value = "id", type = IdType.AUTO) - private Integer id; - - private String name; - - private String owner; - - private String location; - - @TableField(fill = FieldFill.INSERT_UPDATE) - private Integer status; - - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getOwner() { - return owner; - } - - public void setOwner(String owner) { - this.owner = owner; - } - - public String getLocation() { - return location; - } - - public void setLocation(String location) { - this.location = location; - } - - public Integer getStatus() { - return status; - } - - public void setStatus(Integer status) { - this.status = status; - } - - @Override - protected Serializable pkVal() { - return this.id; - } - - @Override - public String toString() { - return "Company{" + - "id=" + id + - ", name=" + name + - ", owner=" + owner + - ", location=" + location + - ", status=" + status + - "}"; - } -} diff --git a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/entity/Employee.java b/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/entity/Employee.java deleted file mode 100644 index 1717fd4c51..0000000000 --- a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/entity/Employee.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.jun.plugin.mybatisplus.biz.test.entity; - -import com.baomidou.mybatisplus.annotation.*; -import com.baomidou.mybatisplus.extension.activerecord.Model; - -import java.io.Serializable; - -/** - *

- * - *

- * - * @author BaoZhou - * @since 2018-10-03 - */ -@TableName("tbl_employee") -public class Employee extends Model { - - private static final long serialVersionUID = 1L; - - @TableId(value = "id", type = IdType.AUTO) - private Integer id; - - private String lastName; - - private String email; - - private String gender; - - private Integer age; - - @Version - private Integer version; - - @TableLogic - private Integer deleted; - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - public String getGender() { - return gender; - } - - public void setGender(String gender) { - this.gender = gender; - } - - public Integer getAge() { - return age; - } - - public void setAge(Integer age) { - this.age = age; - } - - public Integer getVersion() { - return version; - } - - public void setVersion(Integer version) { - this.version = version; - } - public Integer getDeleted() { - return deleted; - } - - public void setDeleted(Integer deleted) { - this.deleted = deleted; - } - - @Override - protected Serializable pkVal() { - return this.id; - } - - @Override - public String toString() { - return "Employee{" + - "id=" + id + - ", lastName=" + lastName + - ", email=" + email + - ", gender=" + gender + - ", age=" + age + - "}"; - } -} diff --git a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/mapper/CompanyMapper.java b/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/mapper/CompanyMapper.java deleted file mode 100644 index 71baaa3644..0000000000 --- a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/mapper/CompanyMapper.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.jun.plugin.mybatisplus.biz.test.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.jun.plugin.mybatisplus.biz.test.entity.Company; - -/** - *

- * Mapper 接口 - *

- * - * @author BaoZhou - * @since 2018-10-03 - */ -public interface CompanyMapper extends BaseMapper { - -} diff --git a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/mapper/EmployeeMapper.java b/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/mapper/EmployeeMapper.java deleted file mode 100644 index b2f40f5d5b..0000000000 --- a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/mapper/EmployeeMapper.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.jun.plugin.mybatisplus.biz.test.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.jun.plugin.mybatisplus.biz.test.entity.Employee; - -/** - *

- * Mapper 接口 - *

- * - * @author BaoZhou - * @since 2018-10-03 - */ -public interface EmployeeMapper extends BaseMapper { - -} diff --git a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/service/ICompanyService.java b/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/service/ICompanyService.java deleted file mode 100644 index 62006c3241..0000000000 --- a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/service/ICompanyService.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.jun.plugin.mybatisplus.biz.test.service; - -import com.baomidou.mybatisplus.extension.service.IService; -import com.jun.plugin.mybatisplus.biz.test.entity.Company; - -/** - *

- * 服务类 - *

- * - * @author BaoZhou - * @since 2018-10-03 - */ -public interface ICompanyService extends IService { - -} diff --git a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/service/IEmployeeService.java b/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/service/IEmployeeService.java deleted file mode 100644 index ec45d7697d..0000000000 --- a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/service/IEmployeeService.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.jun.plugin.mybatisplus.biz.test.service; - -import com.baomidou.mybatisplus.extension.service.IService; -import com.jun.plugin.mybatisplus.biz.test.entity.Employee; - -/** - *

- * 服务类 - *

- * - * @author BaoZhou - * @since 2018-10-03 - */ -public interface IEmployeeService extends IService { - -} diff --git a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/service/impl/CompanyServiceImpl.java b/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/service/impl/CompanyServiceImpl.java deleted file mode 100644 index cfe72d1cb4..0000000000 --- a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/service/impl/CompanyServiceImpl.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jun.plugin.mybatisplus.biz.test.service.impl; - -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.jun.plugin.mybatisplus.biz.test.entity.Company; -import com.jun.plugin.mybatisplus.biz.test.mapper.CompanyMapper; -import com.jun.plugin.mybatisplus.biz.test.service.ICompanyService; - -import org.springframework.stereotype.Service; - -/** - *

- * 服务实现类 - *

- * - * @author BaoZhou - * @since 2018-10-03 - */ -@Service -public class CompanyServiceImpl extends ServiceImpl implements ICompanyService { - -} diff --git a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/service/impl/EmployeeServiceImpl.java b/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/service/impl/EmployeeServiceImpl.java deleted file mode 100644 index 4fad4119db..0000000000 --- a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/biz/test/service/impl/EmployeeServiceImpl.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jun.plugin.mybatisplus.biz.test.service.impl; - -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.jun.plugin.mybatisplus.biz.test.entity.Employee; -import com.jun.plugin.mybatisplus.biz.test.mapper.EmployeeMapper; -import com.jun.plugin.mybatisplus.biz.test.service.IEmployeeService; - -import org.springframework.stereotype.Service; - -/** - *

- * 服务实现类 - *

- * - * @author BaoZhou - * @since 2018-10-03 - */ -@Service -public class EmployeeServiceImpl extends ServiceImpl implements IEmployeeService { - -} diff --git a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/generator/GeneratorTest.java b/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/generator/GeneratorTest.java deleted file mode 100644 index 35b257a0c6..0000000000 --- a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/generator/GeneratorTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.jun.plugin.mybatisplus.generator; - -import java.util.Scanner; - - -/** - *

- * Generator test - *

- * - * @author hubin - * @since 2018-01-11 - */ -public class GeneratorTest { - - /** - *

- * 读取控制台内容 - *

- */ - public static int scanner() { - Scanner scanner = new Scanner(System.in); - StringBuilder help = new StringBuilder(); - help.append(" !!代码生成, 输入 0 表示使用 Velocity 引擎 !!"); - help.append("\n对照表:"); - help.append("\n0 = Velocity 引擎"); - help.append("\n1 = Freemarker 引擎"); - help.append("\n请输入:"); - System.out.println(help.toString()); - int slt = 0; - // 现在有输入数据 - if (scanner.hasNext()) { - String ipt = scanner.next(); - if ("1".equals(ipt)) { - slt = 1; - } - } - return slt; - } -} diff --git a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/generator/MysqlGenerator.java b/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/generator/MysqlGenerator.java deleted file mode 100644 index 75f197b2d5..0000000000 --- a/jun_java_plugins/jun_mybatisplus/src/main/java/com/jun/plugin/mybatisplus/generator/MysqlGenerator.java +++ /dev/null @@ -1,170 +0,0 @@ -/** - * Copyright (c) 2011-2016, hubin (jobob@qq.com). - *

- * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - *

- * http://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package com.jun.plugin.mybatisplus.generator; - -import com.baomidou.mybatisplus.annotation.DbType; -import com.baomidou.mybatisplus.annotation.FieldFill; -import com.baomidou.mybatisplus.generator.AutoGenerator; -import com.baomidou.mybatisplus.generator.InjectionConfig; -import com.baomidou.mybatisplus.generator.config.*; -import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert; -import com.baomidou.mybatisplus.generator.config.po.TableFill; -import com.baomidou.mybatisplus.generator.config.po.TableInfo; -import com.baomidou.mybatisplus.generator.config.rules.DbColumnType; -import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; -import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; - -import java.util.*; - -/** - *

- * 代码生成器演示 - *

- * - * @author hubin - * @since 2016-12-01 - */ -public class MysqlGenerator extends GeneratorTest { - - /** - *

- * MySQL 生成演示 - *

- */ - public static void main(String[] args) { - int result = scanner(); - // 自定义需要填充的字段 - List tableFillList = new ArrayList<>(); - tableFillList.add(new TableFill("ASDD_SS", FieldFill.INSERT_UPDATE)); - - // 代码生成器 - AutoGenerator mpg = new AutoGenerator().setGlobalConfig( - // 全局配置 - new GlobalConfig() - .setOutputDir("D:\\SpringBootStudy\\MyBatisPlus\\MyBatisGenerator\\src\\main\\java")//输出目录 - .setFileOverride(true)// 是否覆盖文件 - .setActiveRecord(true)// 开启 activeRecord 模式 - .setEnableCache(false)// XML 二级缓存 - .setBaseResultMap(true)// XML ResultMap - .setBaseColumnList(true)// XML columList - //.setKotlin(true) 是否生成 kotlin 代码 - .setAuthor("BaoZhou") - // 自定义文件命名,注意 %s 会自动填充表实体属性! - // .setEntityName("%sEntity"); - // .setMapperName("%sDao") - // .setXmlName("%sDao") - // .setServiceName("MP%sService") - // .setServiceImplName("%sServiceDiy") - // .setControllerName("%sAction") - ).setDataSource( - // 数据源配置 - new DataSourceConfig() - .setDbType(DbType.MYSQL)// 数据库类型 - //.setTypeConvert(new MySqlTypeConvert() { - // // 自定义数据库表字段类型转换【可选】 - // @Override - // public DbColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) { - // System.out.println("转换类型:" + fieldType); - // // if ( fieldType.toLowerCase().contains( "tinyint" ) ) { - // // return DbColumnType.BOOLEAN; - // // } - // return super.processTypeConvert(globalConfig, fieldType); - // } - //}) - .setDriverName("com.mysql.cj.jdbc.Driver") - .setUsername("root") - .setPassword("123456") - .setUrl("jdbc:mysql://192.168.15.128:3306/myBatisPlus?characterEncoding=utf8") - ).setStrategy( - // 策略配置 - new StrategyConfig() - // .setCapitalMode(true)// 全局大写命名 - // .setDbColumnUnderline(true)//全局下划线命名 - .setTablePrefix(new String[]{"tbl_", "mp_"})// 此处可以修改为您的表前缀 - .setNaming(NamingStrategy.underline_to_camel)// 表名生成策略 - // .setInclude(new String[] { "user" }) // 需要生成的表 - // .setExclude(new String[]{"test"}) // 排除生成的表 - // 自定义实体父类 - // .setSuperEntityClass("com.baomidou.demo.TestEntity") - // 自定义实体,公共字段 - .setSuperEntityColumns(new String[]{"test_id"}) - .setTableFillList(tableFillList) - // 自定义 mapper 父类 - // .setSuperMapperClass("com.baomidou.demo.TestMapper") - // 自定义 service 父类 - // .setSuperServiceClass("com.baomidou.demo.TestService") - // 自定义 service 实现类父类 - // .setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl") - // 自定义 controller 父类 - // .setSuperControllerClass("com.baomidou.demo.TestController") - // 【实体】是否生成字段常量(默认 false) - // public static final String ID = "test_id"; - // .setEntityColumnConstant(true) - // 【实体】是否为构建者模型(默认 false) - // public User setName(String name) {this.name = name; return this;} - // .setEntityBuilderModel(true) - // 【实体】是否为lombok模型(默认 false)document - // .setEntityLombokModel(true) - // Boolean类型字段是否移除is前缀处理 - // .setEntityBooleanColumnRemoveIsPrefix(true) - // .setRestControllerStyle(true) - // .setControllerMappingHyphenStyle(true) - ).setPackageInfo( - // 包配置 - new PackageConfig() - .setModuleName("test") - .setParent("com.bzcoder")// 自定义包路径 - .setController("controller")// 这里是控制器包名,默认 web - ).setCfg( - // 注入自定义配置,可以在 VM 中使用 cfg.abc 设置的值 - new InjectionConfig() { - @Override - public void initMap() { - Map map = new HashMap<>(); - map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp"); - this.setMap(map); - } - }.setFileOutConfigList(Collections.singletonList(new FileOutConfig( - "/templates/mapper.xml" + ((1 == result) ? ".ftl" : ".vm")) { - // 自定义输出文件目录 - @Override - public String outputFile(TableInfo tableInfo) { - return "D:/develop/code/xml/" + tableInfo.getEntityName() + ".xml"; - } - })) - ).setTemplate( - // 关闭默认 xml 生成,调整生成 至 根目录 - new TemplateConfig().setXml(null) - // 自定义模板配置,模板可以参考源码 /mybatis-plus/src/main/resources/template 使用 copy - // 至您项目 src/main/resources/template 目录下,模板名称也可自定义如下配置: - // .setController("..."); - // .setEntity("..."); - // .setMapper("..."); - // .setXml("..."); - // .setService("..."); - // .setServiceImpl("..."); - ); - // 执行生成 - if (1 == result) { - mpg.setTemplateEngine(new FreemarkerTemplateEngine()); - } - mpg.execute(); - - // 打印注入设置,这里演示模板里面怎么获取注入内容【可无】 - System.err.println(mpg.getCfg().getMap().get("abc")); - } - -} diff --git a/jun_java_plugins/jun_mybatisplus/src/main/resources/applicationContext.xml b/jun_java_plugins/jun_mybatisplus/src/main/resources/applicationContext.xml deleted file mode 100644 index 36c6499909..0000000000 --- a/jun_java_plugins/jun_mybatisplus/src/main/resources/applicationContext.xml +++ /dev/null @@ -1,106 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/jun_java_plugins/jun_mybatisplus/src/main/resources/db.properties b/jun_java_plugins/jun_mybatisplus/src/main/resources/db.properties deleted file mode 100644 index dccdd78617..0000000000 --- a/jun_java_plugins/jun_mybatisplus/src/main/resources/db.properties +++ /dev/null @@ -1,4 +0,0 @@ -jdbc.driver=com.mysql.cj.jdbc.Driver -jdbc.url=jdbc:mysql://192.168.15.128:3306/myBatisPlus -jdbc.username=root -jdbc.password=123456 diff --git a/jun_java_plugins/jun_mybatisplus/src/main/resources/log4j.xml b/jun_java_plugins/jun_mybatisplus/src/main/resources/log4j.xml deleted file mode 100644 index 22ceb34bee..0000000000 --- a/jun_java_plugins/jun_mybatisplus/src/main/resources/log4j.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/jun_java_plugins/jun_mybatisplus/src/main/resources/mapper/Company.xml b/jun_java_plugins/jun_mybatisplus/src/main/resources/mapper/Company.xml deleted file mode 100644 index 618b0a49f0..0000000000 --- a/jun_java_plugins/jun_mybatisplus/src/main/resources/mapper/Company.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - id, name, owner, location, status - - - diff --git a/jun_java_plugins/jun_mybatisplus/src/main/resources/mapper/Employee.xml b/jun_java_plugins/jun_mybatisplus/src/main/resources/mapper/Employee.xml deleted file mode 100644 index 1d42a1ef1c..0000000000 --- a/jun_java_plugins/jun_mybatisplus/src/main/resources/mapper/Employee.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - id, last_name, email, gender, age - - - diff --git a/jun_java_plugins/jun_mybatisplus/src/main/resources/mybatis-config.xml b/jun_java_plugins/jun_mybatisplus/src/main/resources/mybatis-config.xml deleted file mode 100644 index 1ad521f490..0000000000 --- a/jun_java_plugins/jun_mybatisplus/src/main/resources/mybatis-config.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - diff --git a/jun_java_plugins/jun_mybatisplus/src/test/java/TestARMP.java b/jun_java_plugins/jun_mybatisplus/src/test/java/TestARMP.java deleted file mode 100644 index 888fef702a..0000000000 --- a/jun_java_plugins/jun_mybatisplus/src/test/java/TestARMP.java +++ /dev/null @@ -1,49 +0,0 @@ -import org.junit.Test; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -import com.jun.plugin.mybatisplus.biz.entity.Company; - -/** - * AR操作 - * @author BaoZhou - * @date 2018/10/2 - */ -public class TestARMP { - ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml"); - @Test - public void arInsert() - { - Company company = new Company(); - company.setOwner("bzz"); - company.setName("超级宇宙公司"); - company.setLocation("杭州"); - boolean insert = company.insert(); - System.out.println("==============================="); - System.out.println("添加状态" + insert); - System.out.println("==============================="); - } - - @Test - public void arSelect() - { - Company company = new Company(); - Company result = company.selectById(2); - System.out.println(result); - - System.out.println("==============================="); - - Company company1 = new Company(); - company1.setId(2); - Company result2 = company1.selectById(); - System.out.println(result2); - } - - @Test - public void arDelete() - { - Company company = new Company(); - boolean result = company.deleteById(5); - System.out.println(result); - } -} diff --git a/jun_java_plugins/jun_mybatisplus/src/test/java/TestMP.java b/jun_java_plugins/jun_mybatisplus/src/test/java/TestMP.java deleted file mode 100644 index 813f6f3212..0000000000 --- a/jun_java_plugins/jun_mybatisplus/src/test/java/TestMP.java +++ /dev/null @@ -1,71 +0,0 @@ -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.baomidou.mybatisplus.core.metadata.IPage; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.jun.plugin.mybatisplus.biz.test.entity.Employee; -import com.jun.plugin.mybatisplus.biz.test.mapper.EmployeeMapper; - -import org.junit.Test; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -/** - * @author BaoZhou - * @date 2018/10/8 - */ -public class TestMP { - ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml"); - EmployeeMapper employeeMapper = ioc.getBean("employeeMapper", EmployeeMapper.class); - - @Test - public void testPage() { - IPage employeeIPage = employeeMapper.selectPage(new Page<>(2, 2), null); - System.out.println(employeeIPage.getTotal()); - System.out.println(employeeIPage.getRecords()); - } - - @Test - public void testSQLExplain() { - employeeMapper.delete(null); - - } - - @Test - public void updateEmployee() { - int id = 12; - int version = 1; - - Employee u = new Employee(); - u.setId(id); - u.setVersion(version); - - if (employeeMapper.updateById(u) > 0) { - System.out.println("Update successfully"); - } else { - System.out.println("Update failed due to modified by others"); - } - } - - - @Test - public void insert() { - Employee employee = new Employee(); - employee.insert(); - } - @Test - public void update() { - Employee employee = new Employee(); - employee.setLastName("BZBZZ"); - employeeMapper.update(employee,new QueryWrapper() - .eq("id", 15)); - } - - @Test - public void deleteLogic() { - employeeMapper.deleteById(13); - } - - @Test - public void selectLogin() { - employeeMapper.selectList(null); - } -} diff --git a/jun_java_plugins/jun_mybatisplus/src/test/java/TestMbp.java b/jun_java_plugins/jun_mybatisplus/src/test/java/TestMbp.java deleted file mode 100644 index 8517e9628d..0000000000 --- a/jun_java_plugins/jun_mybatisplus/src/test/java/TestMbp.java +++ /dev/null @@ -1,118 +0,0 @@ - -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.baomidou.mybatisplus.core.metadata.IPage; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.jun.plugin.mybatisplus.biz.entity.Employee; -import com.jun.plugin.mybatisplus.biz.mapper.EmployeeMapper; - -import org.junit.Test; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * 普通模式 - * @author BaoZhou - * @date 2018/10/1 - */ -public class TestMbp { - ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml"); - EmployeeMapper employeeMapper = ioc.getBean("employeeMapper", EmployeeMapper.class); - - @Test - public void insert() { - Employee employee = new Employee(); - employee.setLastName("BZ"); - employee.setAge(27); - employee.setEmail("123@qq.com"); - employeeMapper.insert(employee); - System.out.println(employee.getId()); - } - - @Test - public void select() { - Map map = new HashMap<>(); - map.put("age", 27); - List employees = employeeMapper.selectByMap(map); - System.out.println(employees.toString()); - - //内存分页,不是从数据表的真实分页 - IPage employeeIPage = employeeMapper.selectPage(new Page(2, 2), null); - System.out.println(employeeIPage.getRecords().toString()); - - //升序排列 - List employees1 = employeeMapper - .selectList(new QueryWrapper() - .eq("gender", "1") - .orderByAsc("age")); - System.out.println("==============================="); - System.out.println(employees1); - System.out.println("==============================="); - - - } - - @Test - public void selectAsc() - { - //升序排列 - List employees2 = employeeMapper - .selectList(new QueryWrapper() - .eq("gender", "1") - .orderBy(true, true, "age")); - System.out.println("==============================="); - System.out.println(employees2); - System.out.println("==============================="); - } - /** - * 批量删除 - */ - @Test - public void delete() { - List list = Arrays.asList(1, 2, 3); - int i = employeeMapper.deleteBatchIds(list); - System.out.println(i); - } - - /** - * 根据ID删除 - */ - @Test - public void delete2() { - int i = employeeMapper.deleteById(6); - System.out.println(i); - } - - /** - * 使用条件构造器QueryWrapper - */ - @Test - public void testEntityWrapperSelect() { - IPage page = employeeMapper.selectPage(new Page(1, 2), new QueryWrapper() - .between("age", "27", "40") - .eq("gender", "1") - .eq("last_name", "BZ")); - System.out.println(page.getRecords().toString()); - } - - @Test - public void testConditionSelect() { - List employees = employeeMapper.selectList(new QueryWrapper() - .eq("gender", 0) - .like("last_name", "Z") - .or() - .like("email", "Z")); - System.out.println(employees.toString()); - - List employees2 = employeeMapper.selectList(new QueryWrapper() - .eq("gender", 0) - .like("last_name", "Z") - .or(i -> i.eq("last_name", "李白").ne("email", "活着"))); - - System.out.println(employees2.toString()); - } -} diff --git a/jun_java_plugins/jun_mycat/pom.xml b/jun_java_plugins/jun_mycat/pom.xml deleted file mode 100644 index 763eddfff0..0000000000 --- a/jun_java_plugins/jun_mycat/pom.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - 1.0 - jun_mycat - war - - - UTF-8 - - - - - junit - junit - 3.8.1 - test - - - - - mysql - mysql-connector-java - 5.1.40 - - - - jun_mycat - - diff --git a/jun_java_plugins/jun_mysql/db_book.sql b/jun_java_plugins/jun_mysql/db_book.sql deleted file mode 100644 index 313dfd4ff2..0000000000 --- a/jun_java_plugins/jun_mysql/db_book.sql +++ /dev/null @@ -1,53 +0,0 @@ -/* -SQLyog 企业版 - MySQL GUI v8.14 -MySQL - 5.1.49-community : Database - db_book -********************************************************************* -*/ - -/*!40101 SET NAMES utf8 */; - -/*!40101 SET SQL_MODE=''*/; - -/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; -/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; -/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; -/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -CREATE DATABASE /*!32312 IF NOT EXISTS*/`db_book` /*!40100 DEFAULT CHARACTER SET utf8 */; - -USE `db_book`; - -/*Table structure for table `t_book` */ - -DROP TABLE IF EXISTS `t_book`; - -CREATE TABLE `t_book` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `bookName` varchar(20) DEFAULT NULL, - `price` decimal(6,2) DEFAULT NULL, - `author` varchar(20) DEFAULT NULL, - `bookTypeId` int(11) DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; - -/*Data for the table `t_book` */ - -insert into `t_book`(`id`,`bookName`,`price`,`author`,`bookTypeId`) values (1,'Java编程思想','100.00','埃史尔',1),(2,'Java从入门到精通','80.00','李钟尉',1),(3,'三剑客','70.00','大仲马',2),(4,'生理学(第二版)','24.00','刘先国',4); - -/*Table structure for table `t_booktype` */ - -DROP TABLE IF EXISTS `t_booktype`; - -CREATE TABLE `t_booktype` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `bookTypeName` varchar(20) DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; - -/*Data for the table `t_booktype` */ - -insert into `t_booktype`(`id`,`bookTypeName`) values (1,'计算机类'),(2,'文学类'),(3,'教育类'); - -/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; -/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; -/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; -/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; diff --git a/jun_java_plugins/jun_mysql/mysql_backup.md b/jun_java_plugins/jun_mysql/mysql_backup.md deleted file mode 100644 index 3c829161d4..0000000000 --- a/jun_java_plugins/jun_mysql/mysql_backup.md +++ /dev/null @@ -1 +0,0 @@ -mysqldump -u root -p db_book > c:\db_book.sql \ No newline at end of file diff --git a/jun_java_plugins/jun_mysql/mysql_date.md b/jun_java_plugins/jun_mysql/mysql_date.md deleted file mode 100644 index d8a8354163..0000000000 --- a/jun_java_plugins/jun_mysql/mysql_date.md +++ /dev/null @@ -1,15 +0,0 @@ -SELECT CURDATE(),CURTIME(),MONTH(birthday) AS m FROM t_t; - -SELECT userName,CHAR_LENGTH(userName),UPPER(userName),LOWER(userName) FROM t_t; - -SELECT num,ABS(num) FROM t_t; - -SELECT SQRT(4),MOD(9,4) FROM t_t; - -INSERT INTO t_t VALUES(NULL,'2013-1-1','a',1,PASSWORD('123456')); - -INSERT INTO t_t VALUES(NULL,'2013-1-1','a',1,MD5('123456')); - -INSERT INTO t_t VALUES(NULL,'2013-1-1','a',1,MD5('123456'),ENCODE('abcd','aa')); - -SELECT DECODE(pp,'aa') FROM t_t WHERE id=5; diff --git a/jun_java_plugins/jun_mysql/mysql_index.md b/jun_java_plugins/jun_mysql/mysql_index.md deleted file mode 100644 index f05ed6f401..0000000000 --- a/jun_java_plugins/jun_mysql/mysql_index.md +++ /dev/null @@ -1,34 +0,0 @@ -CREATE TABLE t_user1(id INT , - userName VARCHAR(20), - PASSWORD VARCHAR(20), - INDEX (userName) - ); - -CREATE TABLE t_user2(id INT , - userName VARCHAR(20), - PASSWORD VARCHAR(20), - UNIQUE INDEX index_userName(userName) - ); - -CREATE TABLE t_user3(id INT , - userName VARCHAR(20), - PASSWORD VARCHAR(20), - INDEX index_userName_password(userName,PASSWORD) - ); - -CREATE INDEX index_userName ON t_user4(userName); - - -CREATE UNIQUE INDEX index_userName ON t_user4(userName); - -CREATE INDEX index_userName_password ON t_user4(userName,PASSWORD); - -ALTER TABLE t_user5 ADD INDEX index_userName(userName); - -ALTER TABLE t_user5 ADD UNIQUE INDEX index_userName(userName); - -ALTER TABLE t_user5 ADD INDEX index_userName_password(userName,PASSWORD); - -DROP INDEX index_userName ON t_user5; - -DROP INDEX index_userName_password ON t_user5; \ No newline at end of file diff --git a/jun_java_plugins/jun_mysql/mysql_procedure.md b/jun_java_plugins/jun_mysql/mysql_procedure.md deleted file mode 100644 index 65838b3274..0000000000 --- a/jun_java_plugins/jun_mysql/mysql_procedure.md +++ /dev/null @@ -1,22 +0,0 @@ -DELIMITER && -CREATE PROCEDURE pro_book ( IN bT INT,OUT count_num INT) - READS SQL DATA - BEGIN - SELECT COUNT(*) FROM t_book WHERE bookTypeId=bT; - END - && -DELIMITER ; - -CALL pro_book(1,@total); - - -DELIMITER && -CREATE FUNCTION func_book (bookId INT) - RETURNS VARCHAR(20) - BEGIN - RETURN ( SELECT bookName FROM t_book WHERE id=bookId ); - END - && -DELIMITER ; - -SELECT func_book(2); \ No newline at end of file diff --git a/jun_java_plugins/jun_mysql/mysql_procedure2.md b/jun_java_plugins/jun_mysql/mysql_procedure2.md deleted file mode 100644 index e617d3309b..0000000000 --- a/jun_java_plugins/jun_mysql/mysql_procedure2.md +++ /dev/null @@ -1,143 +0,0 @@ -DELIMITER && -CREATE PROCEDURE pro_user() - BEGIN - DECLARE a,b VARCHAR(20) ; - INSERT INTO t_user VALUES(NULL,a,b); - END -&& -DELIMITER ; - -DELIMITER && -CREATE PROCEDURE pro_user2() - BEGIN - DECLARE a,b VARCHAR(20) ; - SET a='java1234',b='123456'; - INSERT INTO t_user VALUES(NULL,a,b); - END -&& -DELIMITER ; - -DELIMITER && -CREATE PROCEDURE pro_user3() - BEGIN - DECLARE a,b VARCHAR(20) ; - SELECT userName2,password2 INTO a,b FROM t_user2 WHERE id2=1; - INSERT INTO t_user VALUES(NULL,a,b); - END -&& -DELIMITER ; - - -DELIMITER && -CREATE PROCEDURE pro_user4() - BEGIN - DECLARE a,b VARCHAR(20) ; - DECLARE cur_t_user2 CURSOR FOR SELECT userName2,password2 FROM t_user2; - OPEN cur_t_user2; - FETCH cur_t_user2 INTO a,b; - INSERT INTO t_user VALUES(NULL,a,b); - CLOSE cur_t_user2; - END -&& -DELIMITER ; - -DELIMITER && -CREATE PROCEDURE pro_user5(IN bookId INT) - BEGIN - SELECT COUNT(*) INTO @num FROM t_user WHERE id=bookId; - IF @num>0 THEN UPDATE t_user SET userName='java12345' WHERE id=bookId; - ELSE - INSERT INTO t_user VALUES(NULL,'2312312','2321312'); - END IF ; - END -&& -DELIMITER ; - -DELIMITER && -CREATE PROCEDURE pro_user6(IN bookId INT) - BEGIN - SELECT COUNT(*) INTO @num FROM t_user WHERE id=bookId; - CASE @num - WHEN 1 THEN UPDATE t_user SET userName='java12345' WHERE id=bookId; - WHEN 2 THEN INSERT INTO t_user VALUES(NULL,'2312312','2321312'); - ELSE INSERT INTO t_user VALUES(NULL,'231231221321312','2321312321312'); - END CASE ; - END -&& -DELIMITER ; - - -DELIMITER && -CREATE PROCEDURE pro_user7(IN totalNum INT) - BEGIN - aaa:LOOP - SET totalNum=totalNum-1; - IF totalNum=0 THEN LEAVE aaa ; - ELSE INSERT INTO t_user VALUES(totalNum,'2312312','2321312'); - END IF ; - END LOOP aaa ; - END -&& -DELIMITER ; - - - -DELIMITER && -CREATE PROCEDURE pro_user8(IN totalNum INT) - BEGIN - aaa:LOOP - SET totalNum=totalNum-1; - IF totalNum=0 THEN LEAVE aaa ; - ELSEIF totalNum=3 THEN ITERATE aaa ; - END IF ; - INSERT INTO t_user VALUES(totalNum,'2312312','2321312'); - END LOOP aaa ; - END -&& -DELIMITER ; - -DELIMITER && -CREATE PROCEDURE pro_user9(IN totalNum INT) - BEGIN - REPEAT - SET totalNum=totalNum-1; - INSERT INTO t_user VALUES(totalNum,'2312312','2321312'); - UNTIL totalNum=1 - END REPEAT; - END -&& -DELIMITER ; - -DELIMITER && -CREATE PROCEDURE pro_user10(IN totalNum INT) - BEGIN - WHILE totalNum>0 DO - INSERT INTO t_user VALUES(totalNum,'2312312','2321312'); - SET totalNum=totalNum-1; - END WHILE ; - END -&& -DELIMITER ; - -CALL pro_user(); - -CALL pro_user2(); - -CALL pro_user3(); - -CALL pro_user4(); - -CALL pro_user5(5); - -CALL pro_user6(6); - -CALL pro_user7(11); - -CALL pro_user8(11); - -CALL pro_user9(11); - -CALL pro_user10(10); - - -DELETE FROM t_user; \ No newline at end of file diff --git a/jun_java_plugins/jun_mysql/mysql_procedure3.md b/jun_java_plugins/jun_mysql/mysql_procedure3.md deleted file mode 100644 index ad1db52ebd..0000000000 --- a/jun_java_plugins/jun_mysql/mysql_procedure3.md +++ /dev/null @@ -1,7 +0,0 @@ -SHOW PROCEDURE STATUS LIKE 'pro_book'; - -SHOW CREATE PROCEDURE pro_book; - -ALTER PROCEDURE pro_book COMMENT '我来测试一个COMMENT'; - -DROP PROCEDURE pro_user3; \ No newline at end of file diff --git a/jun_java_plugins/jun_mysql/mysql_sqltext.md b/jun_java_plugins/jun_mysql/mysql_sqltext.md deleted file mode 100644 index 6d86ead491..0000000000 --- a/jun_java_plugins/jun_mysql/mysql_sqltext.md +++ /dev/null @@ -1,48 +0,0 @@ -SELECT id,stuName,age,sex,gradeName FROM t_student ; - -SELECT stuName,id,age,sex,gradeName FROM t_student ; - -SELECT * FROM t_student; - -SELECT stuName,gradeName FROM t_student; - -SELECT * FROM t_student WHERE id=1; - -SELECT * FROM t_student WHERE age>22; - -SELECT * FROM t_student WHERE age IN (21,23); -SELECT * FROM t_student WHERE age NOT IN (21,23); - -SELECT * FROM t_student WHERE age BETWEEN 21 AND 24; -SELECT * FROM t_student WHERE age NOT BETWEEN 21 AND 24; - -SELECT * FROM t_student WHERE stuName LIKE ''; -SELECT * FROM t_student WHERE stuName LIKE '%'; -SELECT * FROM t_student WHERE stuName LIKE '__'; -SELECT * FROM t_student WHERE stuName LIKE '%%'; - -SELECT * FROM t_student WHERE sex IS NULL; -SELECT * FROM t_student WHERE sex IS NOT NULL; - -SELECT * FROM t_student WHERE gradeName='һ꼶' AND age=23 -SELECT * FROM t_student WHERE gradeName='һ꼶' OR age=23 - -SELECT DISTINCT gradeName FROM t_student; - -SELECT * FROM t_student ORDER BY age ASC; -SELECT * FROM t_student ORDER BY age DESC; - -SELECT * FROM t_student GROUP BY gradeName; - -SELECT gradeName,GROUP_CONCAT(stuName) FROM t_student GROUP BY gradeName; - -SELECT gradeName,COUNT(stuName) FROM t_student GROUP BY gradeName; - -SELECT gradeName,COUNT(stuName) FROM t_student GROUP BY gradeName HAVING COUNT(stuName)>3; - -SELECT gradeName,COUNT(stuName) FROM t_student GROUP BY gradeName WITH ROLLUP; -SELECT gradeName,GROUP_CONCAT(stuName) FROM t_student GROUP BY gradeName WITH ROLLUP; - -SELECT * FROM t_student LIMIT 0,5; -SELECT * FROM t_student LIMIT 5,5; -SELECT * FROM t_student LIMIT 10,5; \ No newline at end of file diff --git a/jun_java_plugins/jun_mysql/mysql_sqltext2.md b/jun_java_plugins/jun_mysql/mysql_sqltext2.md deleted file mode 100644 index 4fe1a4dc0d..0000000000 --- a/jun_java_plugins/jun_mysql/mysql_sqltext2.md +++ /dev/null @@ -1,21 +0,0 @@ -SELECT COUNT(*) FROM t_grade; - -SELECT COUNT(*) AS total FROM t_grade; - -SELECT stuName,COUNT(*) FROM t_grade GROUP BY stuName; - -SELECT stuName,SUM(score) FROM t_grade WHERE stuName="张三"; - -SELECT stuName,SUM(score) FROM t_grade GROUP BY stuName; - -SELECT stuName,AVG(score) FROM t_grade WHERE stuName="张三"; - -SELECT stuName,AVG(score) FROM t_grade GROUP BY stuName; - -SELECT stuName,course,MAX(score) FROM t_grade WHERE stuName="张三"; - -SELECT stuName,MAX(score) FROM t_grade GROUP BY stuName; - -SELECT stuName,course,MIN(score) FROM t_grade WHERE stuName="张三"; - -SELECT stuName,MIN(score) FROM t_grade GROUP BY stuName; \ No newline at end of file diff --git a/jun_java_plugins/jun_mysql/mysql_sqltext3.md b/jun_java_plugins/jun_mysql/mysql_sqltext3.md deleted file mode 100644 index 6bebf51ba9..0000000000 --- a/jun_java_plugins/jun_mysql/mysql_sqltext3.md +++ /dev/null @@ -1,21 +0,0 @@ -SELECT * FROM t_book,t_bookType; - -SELECT * FROM t_book,t_bookType WHERE t_book.bookTypeId=t_bookType.id; - -SELECT bookName,author,bookTypeName FROM t_book,t_bookType WHERE t_book.bookTypeId=t_bookType.id; - -SELECT tb.bookName,tb.author,tby.bookTypeName FROM t_book tb,t_bookType tby WHERE tb.bookTypeId=tby.id; - -SELECT * FROM t_book LEFT JOIN t_bookType ON t_book.bookTypeId=t_bookType.id; - -SELECT tb.bookName,tb.author,tby.bookTypeName FROM t_book tb LEFT JOIN t_bookType tby ON tb.bookTypeId=tby.id; - - -SELECT * FROM t_book RIGHT JOIN t_bookType ON t_book.bookTypeId=t_bookType.id; - -SELECT tb.bookName,tb.author,tby.bookTypeName FROM t_book tb RIGHT JOIN t_bookType tby ON tb.bookTypeId=tby.id; - - - - -SELECT tb.bookName,tb.author,tby.bookTypeName FROM t_book tb,t_bookType tby WHERE tb.bookTypeId=tby.id AND tb.price>70; \ No newline at end of file diff --git a/jun_java_plugins/jun_mysql/mysql_sqltext4.md b/jun_java_plugins/jun_mysql/mysql_sqltext4.md deleted file mode 100644 index 395efd6dd5..0000000000 --- a/jun_java_plugins/jun_mysql/mysql_sqltext4.md +++ /dev/null @@ -1,16 +0,0 @@ -SELECT * FROM t_book WHERE booktypeId IN (SELECT id FROM t_booktype); - -SELECT * FROM t_book WHERE booktypeId NOT IN (SELECT id FROM t_booktype); - - - -SELECT * FROM t_book WHERE price>=(SELECT price FROM t_pricelevel WHERE priceLevel=1); - - -SELECT * FROM t_book WHERE EXISTS (SELECT * FROM t_booktype); - -SELECT * FROM t_book WHERE NOT EXISTS (SELECT * FROM t_booktype); - -SELECT * FROM t_book WHERE price>= ANY (SELECT price FROM t_pricelevel); - -SELECT * FROM t_book WHERE price>= ALL (SELECT price FROM t_pricelevel); \ No newline at end of file diff --git a/jun_java_plugins/jun_mysql/mysql_sqltext5.md b/jun_java_plugins/jun_mysql/mysql_sqltext5.md deleted file mode 100644 index b0b29bf753..0000000000 --- a/jun_java_plugins/jun_mysql/mysql_sqltext5.md +++ /dev/null @@ -1,7 +0,0 @@ -SELECT id FROM t_book; - -SELECT id FROM t_booktype; - -SELECT id FROM t_book UNION SELECT id FROM t_booktype; - -SELECT id FROM t_book UNION ALL SELECT id FROM t_booktype; \ No newline at end of file diff --git a/jun_java_plugins/jun_mysql/mysql_sqltext6.md b/jun_java_plugins/jun_mysql/mysql_sqltext6.md deleted file mode 100644 index b086fbe662..0000000000 --- a/jun_java_plugins/jun_mysql/mysql_sqltext6.md +++ /dev/null @@ -1,9 +0,0 @@ -SELECT * FROM t_book WHERE id=1; - -SELECT * FROM t_book t WHERE t.id=1; - -SELECT t.bookName FROM t_book t WHERE t.id=1; - -SELECT t.bookName bName FROM t_book t WHERE t.id=1; - -SELECT t.bookName AS bName FROM t_book t WHERE t.id=1; \ No newline at end of file diff --git a/jun_java_plugins/jun_mysql/mysql_table.md b/jun_java_plugins/jun_mysql/mysql_table.md deleted file mode 100644 index 0658cf726c..0000000000 --- a/jun_java_plugins/jun_mysql/mysql_table.md +++ /dev/null @@ -1,33 +0,0 @@ -CREATE TABLE t_bookType( - id int primary key auto_increment, - bookTypeName varchar(20), - bookTypeDesc varchar(200) -); - - -CREATE TABLE t_book( - id int primary key auto_increment, - bookName varchar(20), - author varchar(10), - price decimal(6,2), - bookTypeId int, - constraint `fk` foreign key (`bookTypeId`) references `t_bookType`(`id`) -); - - -desc t_bookType; - -show create table t_bookType; - -alter table t_book rename t_book2; - - -alter table t_book change bookName bookName2 varchar(20); - -alter table t_book add testField int first ; - -alter table t_book drop testField; - -drop table t_bookType; - -drop table t_book; \ No newline at end of file diff --git a/jun_java_plugins/jun_mysql/mysql_triger.md b/jun_java_plugins/jun_mysql/mysql_triger.md deleted file mode 100644 index 363beaae9e..0000000000 --- a/jun_java_plugins/jun_mysql/mysql_triger.md +++ /dev/null @@ -1,25 +0,0 @@ -CREATE TRIGGER trig_book AFTER INSERT - ON t_book FOR EACH ROW - UPDATE t_bookType SET bookNum=bookNum+1 WHERE new.bookTypeId=t_booktype.id; - - -INSERT INTO t_book VALUES(NULL,'java好',100,'ke',1); - - - -DELIMITER | -CREATE TRIGGER trig_book2 AFTER DELETE - ON t_book FOR EACH ROW - BEGIN - UPDATE t_bookType SET bookNum=bookNum-1 WHERE old.bookTypeId=t_booktype.id; - INSERT INTO t_log VALUES(NULL,NOW(),'在book表里删除了一条数据'); - DELETE FROM t_test WHERE old.bookTypeId=t_test.id; - END -| -DELIMITER ; - -DELETE FROM t_book WHERE id=5; - -SHOW TRIGGERS; - -DROP TRIGGER trig_book2 ; \ No newline at end of file diff --git a/jun_java_plugins/jun_mysql/mysql_view.md b/jun_java_plugins/jun_mysql/mysql_view.md deleted file mode 100644 index 9ef874255d..0000000000 --- a/jun_java_plugins/jun_mysql/mysql_view.md +++ /dev/null @@ -1,28 +0,0 @@ -CREATE VIEW v1 AS SELECT * FROM t_book; - -CREATE VIEW v2 AS SELECT bookName,price FROM t_book; - -CREATE VIEW v3(b,p) AS SELECT bookName,price FROM t_book; - - -SELECT * FROM v1; - -SELECT * FROM v2; - -SELECT * FROM v3; - -CREATE VIEW v4 AS SELECT bookName,bookTypeName FROM t_book,t_booktype WHERE t_book.bookTypeId=t_booktype.id; - -CREATE VIEW v5 AS SELECT tb.bookName,tby.bookTypeName FROM t_book tb,t_booktype tby WHERE tb.bookTypeId=tby.id; - -SELECT * FROM v4; - -SELECT * FROM v5; - -DESC v5; - -SHOW TABLE STATUS LIKE 'v5'; - -SHOW TABLE STATUS LIKE 't_book'; - -SHOW CREATE VIEW v5; \ No newline at end of file diff --git a/jun_java_plugins/jun_mysql/pom.xml b/jun_java_plugins/jun_mysql/pom.xml deleted file mode 100644 index b449e80602..0000000000 --- a/jun_java_plugins/jun_mysql/pom.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_mysql - 1.0 - jar - - - - - website - scp://webhost.company.com/www/website - - - - UTF-8 - - diff --git a/jun_java_plugins/jun_mysql/src/site/apt/index.apt b/jun_java_plugins/jun_mysql/src/site/apt/index.apt deleted file mode 100644 index 31b624611e..0000000000 --- a/jun_java_plugins/jun_mysql/src/site/apt/index.apt +++ /dev/null @@ -1,18 +0,0 @@ - ----- - Title Here - ----- - Author Here - ----- - Date Here - ----- - -Maven Site for your project - - Congratulations! If you are looking at this page then you have successfully generated a - template site employing the site archetype and you have run: - -+-----+ - -mvn site - -+-----+ diff --git a/jun_java_plugins/jun_mysql/src/site/site.xml b/jun_java_plugins/jun_mysql/src/site/site.xml deleted file mode 100644 index b8d2ed8558..0000000000 --- a/jun_java_plugins/jun_mysql/src/site/site.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - diff --git a/jun_java_plugins/jun_mysql/t_grade.sql b/jun_java_plugins/jun_mysql/t_grade.sql deleted file mode 100644 index b2b1f46094..0000000000 --- a/jun_java_plugins/jun_mysql/t_grade.sql +++ /dev/null @@ -1,22 +0,0 @@ -/* -SQLyog 企业版 - MySQL GUI v8.14 -MySQL - 5.1.49-community -********************************************************************* -*/ -/*!40101 SET NAMES utf8 */; - -create table `t_grade` ( - `id` int , - `stuName` varchar (60), - `course` varchar (60), - `score` int -); -insert into `t_grade` (`id`, `stuName`, `course`, `score`) values('1','张三','语文','91'); -insert into `t_grade` (`id`, `stuName`, `course`, `score`) values('2','张三','数学','90'); -insert into `t_grade` (`id`, `stuName`, `course`, `score`) values('3','张三','英语','87'); -insert into `t_grade` (`id`, `stuName`, `course`, `score`) values('4','李四','语文','79'); -insert into `t_grade` (`id`, `stuName`, `course`, `score`) values('5','李四','数学','95'); -insert into `t_grade` (`id`, `stuName`, `course`, `score`) values('6','李四','英语','80'); -insert into `t_grade` (`id`, `stuName`, `course`, `score`) values('7','王五','语文','77'); -insert into `t_grade` (`id`, `stuName`, `course`, `score`) values('8','王五','数学','81'); -insert into `t_grade` (`id`, `stuName`, `course`, `score`) values('9','王五','英语','89'); diff --git a/jun_java_plugins/jun_mysql/t_pricelevel.sql b/jun_java_plugins/jun_mysql/t_pricelevel.sql deleted file mode 100644 index 402b98d356..0000000000 --- a/jun_java_plugins/jun_mysql/t_pricelevel.sql +++ /dev/null @@ -1,16 +0,0 @@ -/* -SQLyog 企业版 - MySQL GUI v8.14 -MySQL - 5.1.49-community -********************************************************************* -*/ -/*!40101 SET NAMES utf8 */; - -create table `t_pricelevel` ( - `id` int , - `priceLevel` int , - `price` float , - `description` varchar (300) -); -insert into `t_pricelevel` (`id`, `priceLevel`, `price`, `description`) values('1','1','80.00','价格贵的书'); -insert into `t_pricelevel` (`id`, `priceLevel`, `price`, `description`) values('2','2','60.00','价格适中的书'); -insert into `t_pricelevel` (`id`, `priceLevel`, `price`, `description`) values('3','3','40.00','价格便宜的书'); diff --git a/jun_java_plugins/jun_mysql/t_student.sql b/jun_java_plugins/jun_mysql/t_student.sql deleted file mode 100644 index b4455d1abf..0000000000 --- a/jun_java_plugins/jun_mysql/t_student.sql +++ /dev/null @@ -1,27 +0,0 @@ -/* -SQLyog 企业版 - MySQL GUI v8.14 -MySQL - 5.1.49-community -********************************************************************* -*/ -/*!40101 SET NAMES utf8 */; - -create table `t_student` ( - `id` double , - `stuName` varchar (60), - `age` double , - `sex` varchar (30), - `gradeName` varchar (60) -); -insert into `t_student` (`id`, `stuName`, `age`, `sex`, `gradeName`) values('1','张三','23','男','一年级'); -insert into `t_student` (`id`, `stuName`, `age`, `sex`, `gradeName`) values('2','张三丰','25','男','二年级'); -insert into `t_student` (`id`, `stuName`, `age`, `sex`, `gradeName`) values('3','李四','23','男','一年级'); -insert into `t_student` (`id`, `stuName`, `age`, `sex`, `gradeName`) values('4','王五','22','男','三年级'); -insert into `t_student` (`id`, `stuName`, `age`, `sex`, `gradeName`) values('5','珍妮','21','女','一年级'); -insert into `t_student` (`id`, `stuName`, `age`, `sex`, `gradeName`) values('6','李娜','26','女','二年级'); -insert into `t_student` (`id`, `stuName`, `age`, `sex`, `gradeName`) values('7','王峰','20','男','三年级'); -insert into `t_student` (`id`, `stuName`, `age`, `sex`, `gradeName`) values('8','梦娜','21','女','二年级'); -insert into `t_student` (`id`, `stuName`, `age`, `sex`, `gradeName`) values('9','小黑','22','男','一年级'); -insert into `t_student` (`id`, `stuName`, `age`, `sex`, `gradeName`) values('10','追风','25','男','二年级'); -insert into `t_student` (`id`, `stuName`, `age`, `sex`, `gradeName`) values('11','小小张三','21',NULL,'二年级'); -insert into `t_student` (`id`, `stuName`, `age`, `sex`, `gradeName`) values('12','小张三','23','男','二年级'); -insert into `t_student` (`id`, `stuName`, `age`, `sex`, `gradeName`) values('13','张三锋小','24',NULL,'二年级'); diff --git a/jun_java_plugins/jun_okhttp/README.md b/jun_java_plugins/jun_okhttp/README.md deleted file mode 100644 index 2192cd80c7..0000000000 --- a/jun_java_plugins/jun_okhttp/README.md +++ /dev/null @@ -1,385 +0,0 @@ -# easy-okhttp -============== - -[![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.mzlion/easy-okhttp/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.mzlion/easy-okhttp/) -[![License](https://img.shields.io/badge/license-Apache%202-4EB1BA.svg)](https://www.apache.org/licenses/LICENSE-2.0.html) - -Java网络框架的另一种选择 - -============== -`easy-okhttp`是Java网络框架,简化网络操作,专注于业务处理 - -## 文档目录(点击快速导航) - -- [简介](#简介) -- [依赖说明](#依赖说明) -- [框架引入](#框架引入) -- [框架特性说明](#框架特性说明) -- [全局配置(可选)](#全局配置) -- [基本示例](#基本示例) - + [1.普通的GET请求无参数](#1.普通的GET请求无参数) - + [2.普通的GET请求带参数](#2.普通的GET请求带参数) - + [3.POST普通表单提交](#3.POST普通表单提交) -- [上传大文本数据、JSON类型的文本、大文件等](#上传大文本数据、JSON类型的文本、大文件等) - + [1.POST提交String](#1.POST提交String) - + [2.POST提交JSON格式的文本](#2.POST提交JSON格式的文本) - + [3.POST提交XML等其他格式的文本](#3.POST提交XML等其他格式的文本) - + [4.POST提交二进制文件](4.POST提交二进制文件) -- [表单提交、一参数多值](#表单提交、一参数多值) - + [1.POST表单提交含文件上传](#1.POST表单提交含文件上传) - + [2.POST提交支持一个参数设置多个值或替换](#2.POST提交支持一个参数设置多个值或替换) -- [HttpResponse对象介绍](#HttpResponse对象介绍) -- [数据处理器DataHandler](#数据处理器DataHandler) -- [高级配置](#高级配置) - + [异步请求](#异步请求) - + [Callback回调接口](#Callback回调接口) - + [为单个请求设置超时](#为单个请求设置超时) -+ [关于demo](#关于demo) - -** 在GITOSC下不生效 ** - -## 简介 - -`easy-okhttp`是对[OkHttp](https://github.com/square/okhttp)网络框架封装,提供文件上传和下载,表单(含文件)提交,链式调用,支持HTTPS和自定义签名证书等特性。 -`OkHttp`网络框架的流行始于`Android`,但是在`Java`后端仍然是`Apache HttpClient`网络框架,这个框架功能非常强大,但缺点在于设计非常的复杂且jar的比较大。 -所以才有`easy-okhttp`项目,主要目的希望弃用`Apache HttpClient`,其次也是为了帮助`OkHttp`的推广啦。 - -## 依赖说明 - -* `OkHttp`,本项目核心所在,底层依赖了`okio`框架,框架的大小在500Kb之内 -* `mzlion-core`,项目依赖的工具类,底层依赖了`slf4j-api`和`gson`两个框架,框架的大小在400Kb之内 - -也就是说`easy-okhttp`整个包的大小在1M左右,相对于`Apache HttpClient`体积非常的小,而且使用也更为方便。 - -## 联系方式 - -* 邮箱地址 - [mzllon@qq.com](mailto:mzllon@qq.com) -* QQ群 - QQ基本已废弃,可以考虑加入微信群 -* 微信群 - ![easy-okhttp交流群](https://images.gitee.com/uploads/images/2019/0304/164933_4f1db70d_8858.jpeg "easy-okhttp交流群") - -## 框架引入 - -`easy-okhttp`需要JDK7及其以上版本的支持,如果您还不是JDK7的话,新项目赶紧升级吧。 - -maven - -```xml - - com.mzlion - easy-okhttp - 1.1.0 - -``` - -Gradle - -``` -compile 'com.mzlion:easy-okhttp:1.1.0' -``` - -下载jar - - -## 框架特性说明 - -* 支持GET和POST请求 -* 基于POST的大文本数据、二进制文件上传,即通过Http Body提交 -* 普通的表单提交 -* 带有文件表单提交 -* 表单提交支持参数名重复,即在后台接收到的是数组或集合 -* 支持session保持 -* 支持链式调用 -* 支持可信任证书和自定义签名证书的https访问 -* Debug调试模式,开发环境推荐启用 -* 增加异步请求的支持 -* 提供数据处理器,轻松将数据转为自己想要的结果 -* 更多特性增加中 - -## 全局配置 - -框架会自动读取classpath下的`easy-okhttp.properties`配置文件,如果没有特别的要求话,一般不需要重载该配置文件。 - - * `easy-okhttp.properties`配置文件的配置信息 - + connectTimeout 连接超时时间,默认设置10秒 - + readTimeout 内容读取超时时间,默认是30秒 - + writeTimeout 内容写入超时时间,默认30秒 - * 如果需要更改这些默认配置,有两种方式 - + 覆盖框架提供的配置`easy-okhttp.properties`,框架优先加载项目中的配置文件,超时时间的单位都是秒 - + 通过代码设置全局配置 - * 通过代码也可以设置全局参数,该配置操作只需要操作一次,因而可以放在项目启动时配置。 - + 设置连接超时时间 `HttpClient.Instance.setConnectTimeout(int)` - + 设置读取超时时间 `HttpClient.Instance.setReadTimeout(int)` - + 设置写入超时时间 `HttpClient.Instance.writeTimeout(int)` - + 设置自定义签名证书 `HttpClient.Instance.customSSL(?)` - + 设置默认Header `HttpClient.Instance.setDefaultHeader(?)` -* SSL证书配置 - 2017年是SSL活跃率非常高的一年,所以增加了HTTPS单向认证和双向认证。HTTPS全局配置需要通过代码设置。 - + 网站启用了HTTPS,如果SSL证书由信任的Root CA发布的,那么框架自动信信任,不需要你做任何配置 - + 忽略HTTPS,即客户端不验证,非常不推荐这么使用,调用方式 `HttpClient.Instance.customSSL()` - + 假如使用的自签证书(经典的12306网站)或系统不能自动信任的SSL证书(如Let's Encrypt) `HttpClient.Instance.customSSL(HttpClient.class.getClassLoader().getResourceAsStream("mzlion_com.cer"))` - + 最严格就是双向认证 `HttpClient.Instance.customSSL(InputStream pfxStream, char[] pfxPwd, InputStream... certificates)` - -## 基本示例 - -**这几天我会提供测试接口,供大家调试使用,敬请期待,期待的来啦: [https://project.mzlion.com/easy-okhttp/api](https://project.mzlion.com/easy-okhttp/api)** - - -### 1.普通的GET请求无参数 - -```java - String responseData = HttpClient - // 请求方式和请求url - .get("http://localhost:8080/user-sys/user/list") - .asString(); -``` - -### 2.普通的GET请求带参数 - -```java - String responseData = HttpClient - // 请求方式和请求url - .get("http://localhost:8080/user-sys/user/list") - //设置请求参数 - .queryString("mobile","18018110018") - .asString(); -``` - -### 3.POST普通表单提交 - -```java - String responseData = HttpClient - // 请求方式和请求url - .post("http://localhost:8080/user-sys/user/add") - // 表单参数 - .param("name","张三") - .param("mobile", "13023614020") - .param("langs", "Java") - .param("langs", "Python") - //url参数 - //queryString("queryTime","20160530") - .asString(); -``` - -## 上传大文本数据、JSON类型的文本、大文件等 - -一般针对POST提交数据内容较为复杂、接口约定需要POST上传时调用本方法非常有效。这种提交方式也是POST,但是数据内容和格式直接写入请求流中。比如微信接口就是这种模式。 - -### 1.POST提交String - -```java - String responseData = HttpClient - // 请求方式和请求url - .textBody("http://localhost:8080/user-sys/user/body1") - .text("设施一串和服务端约定好的数据格式") - //设置编码 - //.charset("utf-8") - .asString(); -``` - -### 2.POST提交JSON格式的文本 - -```java - String responseData = HttpClient - // 请求方式和请求url - .textBody("http://localhost:8080/user-sys/user/import") - // post提交json - .json("[{\"name\": \"test-13\",\"mobile\": \"18321001200\",\"programLangs\": \"Java,Pyhton\",\"remark\": \"0\"}]") - //post提交xml - //.xml("") - //post提交html - //.html("function fun(){}") - //.charset("utf-8") - //设置编码 - .asString(); -``` - -### 3.POST提交XML等其他格式的文本 - -```java - String responseData = HttpClient - // 请求方式和请求url - .textBody("http://localhost:8080/user-sys/user/body2") - //post提交xml - .xml("") - //post提交html - //.html("function fun(){}") - //post提交一段javascript - //.javascript("function fn(){}") - //设置编码 - //.charset("utf-8") - .asString(); -``` - -### 4.POST提交二进制文件 - -```java - String responseData = HttpClient - // 请求方式和请求url - .binaryBody("http://localhost:8080/user-sys/user/body3") - // post提交流 - .stream(this.getClass().getClassLoader().getResourceAsStream("avatar.png")) - //设置请求内容类型 - .contentType(ContentType.IMAGE_JPG) - //post提交文件 - //.file(new File("d:/avatar.png")) - .asString(); -//ContentType内置常见的MIME类型,基本上不用自己创建 -``` - -## 表单提交、一参数多值 - -### 1.POST表单提交含文件上传 - -```java - String responseData = HttpClient - // 请求方式和请求url - .post("http://localhost:8080/user-sys/user/add") - .param("name", "李四") - .param("mobile", "13023614021") - .param("avatarFile", this.getClassLoader().getResourceAsStream("avatar.png"), "avatar.png") - //.param("avatarFile", new File("D:/avatar.png") - .asString(); -``` - -### 2.POST提交支持一个参数设置多个值或替换 - -```java - String responseData = HttpClient - // 请求方式和请求url - .post("http://localhost:8080/user-sys/user/add") - // 表单参数 - .param("name","张三") - .param("mobile", "13023614020") - .param("langs", "Java") - .param("langs", "Python")//会多种语言 - .asString(); -``` - - -## HttpResponse对象介绍 - -以上展示的代码都是基于同步请求的,并且你会发现示例代码中总是出现`asString()`方法,这个方法来自`HttpResponse`类, -目前`as***`方法已经提升和`execute`方法级别一样,用法和`HttpResponse`提供的方法一样。 - -1. `HttpResponse.isSuccess()`表示请求是否成功,只有请求成功才会有后面的功能。 -2. `HttpResponse.getErrorMessage` 请求失败时错误消息。 - -**下面就是非常非常非常好用的方法** - -1. `public String asString()` 将响应结果直接转为字符串 -2. `public E asBean(Class targetClass)` 将响应结果转为JavaBean -3. `public E asBean(TypeRef typeRef)` 也是将响应结果转为JavaBean,和上面的区别在于该方法能够提取到泛型信息 -4. `public byte[] asByteData()` 将响应结果转为二进制内容,这是数据在网络请求的原始数据 -5. `public void asFile(File saveFile)` 将响应结果转为文件存储,当远程是文件时该方法非常有用 -6. `public void asStream(OutputStream out)` 直接将响应结果输出到另外一个流中 -7. `public T custom(DataHandler dataHandler)` 当以上这些方法都满足不了你的话,这个方法可以自己DIY,随你怎么蹂躏 - -下面给出一些简单的代码,这些方法已经非常简单了。 - -```java - //将响应结果转为字符串输出 - String responseData = httpResponse.asString(); - - //将响应结果转为文件保存 - File frc = new File("d:\\web\\save.txt"); - httpResponse.asFile(frc); - - //json转换器 - List personList = httpResponse.asBean(new TypeToken>(){}); - //重载方法 - //Person person = httpResponse.asBean(Person.class); - - //将响应结果转为输出流中 - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - httpResponse.asStream(baos); -``` - -## HTTPS - -前面已经提到HTTPS的配置,下面给出一些简单的示例更直观了解用法。 - -```java - //由信任CA机构发布的,比如GitHub的https,框架不需要你做什么事情,正常使用即可 - String githubContent = HttpClient - .get("https://www.mzlion.com") - .asString(); - - //不管三七二十几,直接忽略HTTPS - String mzlionIndexContent = HttpClient - .get("https://kyfw.12306.cn/otn/") - .customSSL() - .asString(); - - //自签SSL或程序不认可实际安全的,可以指定客户端证书 - String mzlionIndexContent = HttpClient - .get("https://kyfw.12306.cn/otn/") - .customSSL(this.getClass().getClassLoader().getResourceAsStream("SRCA.cer")) - .asString(); - -``` - -## 数据处理器DataHandler - -这是新版本的新增的一个功能,数据处理器定义接口返回数据处理能力,该接口就只有一个函数 -```java - T handle(final okhttp3.Response response) throws IOException; -``` -该函数提供了将原始数据格式转为业务所需数据格式,框架提供了常用接口处理器实现,若以下的处理器无法满足需求可以自己实现一个处理器。 - -* `StringDataHandler` 字符串处理器,该处理器比较常用,可以直接调用`StringDataHandler.create()`得到处理器的实例 -* `JsonDataHandler` JSON处理器,该处理器也比较常用,即将JSON字符串转为Javabean -* `FileDataHandler` 文件处理器,将结果存储到文件中,该处理器有两个构造参数,其中`dirPath`保存目录必填,`filename`保存的文件名可选,如果为空时框架自动从header、url中获取,如果获取不到则随机生成一个文件名。 - -## 高级配置 - -### 异步请求 - -异步请求不会阻塞当前线程(特别是网络慢的时候),适用于对返回结果不关心或不需要立即知晓的情况下,比如推送、通知等。 -异步请求只有在执行网络请求的时候有一点区别,其他地方和同步请求配置和操作都是一样的。 - -```java - String githubContent = HttpClient - .get("https://www.github.com") - .execute(new CallbackAdaptor(){ - - @Override - public DataHandler getDataHandler() { - return StringDataHandler.create(); - } - - @Override - public void onSuccess(String data) { - //data就是经过处理后的数据,直接在这里写自己的业务逻辑 - } - }); -``` - -### Callback回调接口 - -`Callback`是回调定义接口,里面总共定义了6个函数,每个函数被调用的顺序不一样。 - -* `onBefore()` 第一被调用,主要在请求网络之前,这个函数有返回值,如果返回`false`则阻止此次请求了; -* `postProgress()` 第二被调用,上传进度回调函数 -* `onError()` 第三被调用,当只有请求失败时才会触发; -* `onComplete()` 第四被调用,当请求接口完成后触发该函数; -* `onSuccess()` 第五被调用,当请求接口成功(HTTP状态码为200)则会触发该函数, -该函数会依赖另外一个函数`getDataHandler()`,返回一个指定的数据处理器,处理原始数据。对于数据处理器前面已经了解过了。 - -异步回调接口`Callback`总共定义了6个函数,但是一般不会关心所有函数处理情况,所以提供了`CallbackAdaptor`空实现类,想要关注哪个函数的执行结果,重载那个函数即可。 - -### 为单个请求设置超时 - -当我们需要对单个请求设置连接超时时间、读取超时时间等属性时,可以在执行`execute`方法之前调用。主要有如下几个方法可以进行调用。 - -+ `connectTimeout(int)` 连接超时时间 -+ `readTimeout(int)` 读取超时时间 -+ `writeTimeout(int)` 写入超时时间 -+ `customSSL()` 设置https证书 - -## 关单单例说明 - -一般一个项目只请求一个远程服务,所以这些配置可以在全局配置,共享一个`OkHttpClient`对象(相当于共享一个浏览器), -以上这些方法的调用会使得框架创建一个新的`OkHttpClient`对象(相当于又打开了一个浏览器)。下面给出一个snippet加以说明。 diff --git a/jun_java_plugins/jun_okhttp/pom.xml b/jun_java_plugins/jun_okhttp/pom.xml deleted file mode 100644 index 6596d0e677..0000000000 --- a/jun_java_plugins/jun_okhttp/pom.xml +++ /dev/null @@ -1,139 +0,0 @@ - - - 4.0.0 - - io.github.wujun728 - jun_okhttp - 1.0 - jar - - - easy-okhttp是对okhttp3上层封装的网络框架,支持文件上传和下载表单提交(文件和一个参数对应多值), - 链式调用,并且默认整合Gson,对返回结果多种转换,同时还支持HTTPS单向认证和双向认证等特性。 - - - - - mzlion - mzlion - mzllon@qq.com - https://www.mzlion.com - +8 - - Project leader - - - - - - - 1.1.2 - 3.10.0 - true - - - - - junit - junit - 4.13.2 - - - - - com.squareup.okhttp3 - okhttp - ${okhttp3.version} - - - - - com.mzlion - mzlion-core - ${mzlion-core.version} - - - - - - nexus - aliyun nexus - http://maven.aliyun.com/nexus/content/groups/public/ - - true - - - true - - - - - - nexus-plugins - aliyun nexus - http://maven.aliyun.com/nexus/content/groups/public/ - - true - - - false - - - - - - bintray-repo-maven - https://api.bintray.com/maven/mzllon/maven/easy-okhttp/;publish=1 - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - - org.apache.maven.plugins - maven-javadoc-plugin - - - - org.apache.maven.plugins - maven-source-plugin - - - - org.apache.maven.plugins - maven-dependency-plugin - - ${basedir}/target/lib - compile - - - - copy - package - - copy-dependencies - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.1 - - 8 - 8 - UTF-8 - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/HttpClient.java b/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/HttpClient.java deleted file mode 100644 index 0e8a148346..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/HttpClient.java +++ /dev/null @@ -1,492 +0,0 @@ -/* - * Copyright (C) 2016-2017 mzlion(mzllon@qq.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mzlion.easyokhttp; - -import com.mzlion.core.lang.Assert; -import com.mzlion.core.lang.CollectionUtils; -import com.mzlion.core.utils.PlaceholderPropertyResolver; -import com.mzlion.core.utils.PropertyResolver; -import com.mzlion.easyokhttp.cookie.CookieStore; -import com.mzlion.easyokhttp.cookie.DefaultCookieJar; -import com.mzlion.easyokhttp.cookie.MemoryCookieStore; -import com.mzlion.easyokhttp.http.DebugLoggingInterceptor; -import com.mzlion.easyokhttp.request.BinaryBodyPostRequest; -import com.mzlion.easyokhttp.request.GetRequest; -import com.mzlion.easyokhttp.request.PostRequest; -import com.mzlion.easyokhttp.request.TextBodyRequest; -import com.mzlion.easyokhttp.utils.SSLContexts; -import okhttp3.HttpUrl; -import okhttp3.Interceptor; -import okhttp3.OkHttpClient; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLSession; -import javax.net.ssl.X509TrustManager; -import java.io.InputStream; -import java.util.Collections; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.TimeUnit; - -/** - *

- * {@linkplain HttpClient}是对{@code OkHttpClient}封装,提供更便捷的网络操作。 - *

- * 修订历史: - *
    - *
  • 2016-05-12 项目创建
  • - *
  • 2016-12-28 项目改版及其优化
  • - *
- * - * @author mzlion(https://git.oschina.net/mzllon/easy-okhttp) - * @version 1.0 - */ -public enum HttpClient { - Instance; - - public static final int DEFAULT_TIMEOUT = 10;//10seconds - //logger - private static final Logger LOGGER = LoggerFactory.getLogger(HttpClient.class); - - /* OkHttp */ - private OkHttpClient.Builder builder; - private CookieStore cookieStore; - private OkHttpClient okHttpClient; - - /* 默认的Header存储 */ - private Map> defaultHeaders; -// private Map defaultParameters; - - /* default constructor */ - HttpClient() { - //default init - this.cookieStore = new MemoryCookieStore(); - this.builder = new OkHttpClient.Builder() - //设置cookie自动管理 - .cookieJar(new DefaultCookieJar(this.cookieStore)) - //设置默认主机验证规则 - .hostnameVerifier(new HostnameVerifier() { - @Override - public boolean verify(String hostname, SSLSession session) { - return true; - } - }); - - //读取默认配置文件 - PropertyResolver propertyResolver = new PlaceholderPropertyResolver.Builder() - .path("classpath:easy-okhttp.properties").build(); - - //连接超时时间 - int timeout = propertyResolver.getProperty("connectTimeout", int.class); - if (timeout <= 0) { - timeout = DEFAULT_TIMEOUT; - } - this.builder.connectTimeout(timeout, TimeUnit.SECONDS); - - //读取超时时间 - timeout = propertyResolver.getProperty("readTimeout", int.class); - if (timeout <= 0) { - timeout = DEFAULT_TIMEOUT; - } - this.builder.readTimeout(timeout, TimeUnit.SECONDS); - - //写入超时时间 - timeout = propertyResolver.getProperty("writeTimeout", int.class); - if (timeout <= 0) { - timeout = DEFAULT_TIMEOUT; - } - this.builder.writeTimeout(timeout, TimeUnit.SECONDS); - - this.defaultHeaders = new ConcurrentHashMap<>(10); -// this.defaultParameters = new ConcurrentHashMap<>(); - -// String key, value; -// String[] valueArray; -// for (Map.Entry entry : propertyResolver.getAllProperties().entrySet()) { -// key = entry.getKey(); -// value = entry.getValue(); -// if (value == null) continue; -// if (StringUtils.startsWithIgnoreCase(key, "header")) { -// valueArray = StringUtils.splitAtFirst(key, "."); -// this.defaultHeaders.put(valueArray[1], value); -// } -// else if (StringUtils.startsWithIgnoreCase(key, "param")) { -// valueArray = StringUtils.splitAtFirst(key, "."); -// this.defaultParameters.put(valueArray[1], value); -// } -// } - } - - - //region================超时时间设置方法================ - - /** - * 设置连接超时时间 - * - * @param connectTimeout 超时时间 - * @param timeUnit 超时时间单位 - * @return {@linkplain HttpClient} - */ - public HttpClient connectTimeout(int connectTimeout, TimeUnit timeUnit) { - if (connectTimeout <= 0) { - LOGGER.error(" ===> Connect timeout must not be less than 0."); - return this; - } - Assert.notNull(timeUnit, "TimeUnit may not be null."); - this.builder.connectTimeout(connectTimeout, timeUnit); - return this; - } - - /** - * 设置连接超时时间 - * - * @param connectTimeout 超时时间,单位秒 - * @return {@linkplain HttpClient} - * @see #connectTimeout(int, TimeUnit) - */ - public HttpClient connectTimeout(int connectTimeout) { - return connectTimeout(connectTimeout, TimeUnit.SECONDS); - } - - /** - * 设置流读取超时时间 - * - * @param readTimeout 读取超时时间,单位毫秒 - * @param timeUnit 超时时间单位 - * @return {@linkplain HttpClient} - */ - public HttpClient readTimeout(int readTimeout, TimeUnit timeUnit) { - if (readTimeout <= 0) { - LOGGER.error(" ===> Read timeout must not be less than 0."); - return this; - } - Assert.notNull(timeUnit, "TimeUnit may not be null."); - this.builder.readTimeout(readTimeout, timeUnit); - return this; - } - - /** - * 设置流读取超时时间 - * - * @param readTimeout 读取超时时间,单位秒 - * @return {@linkplain HttpClient} - * @see #readTimeout(int, TimeUnit) - */ - public HttpClient readTimeout(int readTimeout) { - return readTimeout(readTimeout, TimeUnit.SECONDS); - } - - /** - * 设置流的写入超时时间 - * - * @param writeTimeout 写入超时时间,单位是毫秒 - * @param timeUnit 超时时间单位 - * @return {@linkplain HttpClient} - */ - public HttpClient writeTimeout(int writeTimeout, TimeUnit timeUnit) { - if (writeTimeout <= 0) { - LOGGER.error(" ===> Write timeout must not be less than 0."); - return this; - } - Assert.notNull(timeUnit, "TimeUnit may not be null."); - this.builder.writeTimeout(writeTimeout, timeUnit); - return this; - } - - /** - * 设置流的写入超时时间 - * - * @param writeTimeout 写入超时时间,单位是秒 - * @return {@linkplain HttpClient} - * @see #writeTimeout(int, TimeUnit) - */ - public HttpClient writeTimeout(int writeTimeout) { - return writeTimeout(writeTimeout, TimeUnit.SECONDS); - } - //endregion - - - //region================SSL证书设置方法================ - - /** - * https单向认证 - * - * @param certificates 含有服务端公钥的证书 - * @return {@link HttpClient} - */ - public HttpClient customSSL(InputStream... certificates) { - return customSSL(null, null, certificates); - } - - /** - * https单向认证,直接配置证书管理 - * - * @param trustManager 证书管理器 - * @return {@link HttpClient} - */ - public HttpClient customSSL(X509TrustManager trustManager) { - return customSSL(null, null, trustManager); - } - - /** - * https双向认证 - * - * @param pfxStream 客户端证书,支持P12的证书 - * @param pfxPwd 客户端证书密码 - * @param certificates 含有服务端公钥的证书 - * @return {@link HttpClient} - */ - public HttpClient customSSL(InputStream pfxStream, char[] pfxPwd, InputStream... certificates) { - SSLContexts.SSLConfig sslConfig = SSLContexts.tryParse(certificates, null, pfxStream, pfxPwd); - this.builder.sslSocketFactory(sslConfig.getSslSocketFactory(), sslConfig.getX509TrustManager()); - return this; - } - - /** - * https双向认证 - * - * @param pfxStream 客户端证书,支持P12的证书 - * @param pfxPwd 客户端证书密码 - * @param trustManager 证书管理器 - * @return {@link HttpClient} - */ - public HttpClient customSSL(InputStream pfxStream, char[] pfxPwd, X509TrustManager trustManager) { - SSLContexts.SSLConfig sslConfig = SSLContexts.tryParse(null, trustManager, pfxStream, pfxPwd); - this.builder.sslSocketFactory(sslConfig.getSslSocketFactory(), sslConfig.getX509TrustManager()); - return this; - } - //endregion - - - //region================设置默认请求================ - - /** - * 设置默认的Http Header - * - * @param host 主机名 - * @param name Header名称 - * @param value Header值 - * @return {@linkplain HttpClient} - */ - public HttpClient setDefaultHeader(String host, String name, String value) { - Assert.hasLength(host, "Host may not be null or empty."); - Assert.hasLength(name, "Name may not be null or empty."); - Assert.notNull(value, "Value may not be null."); - HttpUrl httpUrl = HttpUrl.parse(host); - if (httpUrl == null) { - throw new IllegalArgumentException("Host [" + host + "] is invalid."); - } - Map headers = defaultHeaders.get(httpUrl.host()); - if (CollectionUtils.isEmpty(headers)) { - headers = new ConcurrentHashMap<>(); - defaultHeaders.put(httpUrl.host(), headers); - } - headers.put(name, value); - return this; - } - - /** - * 获取默认的Http Header列表 - * - * @param host 主机名 - * @return Header键值对列表 - */ - public Map getDefaultHeaders(String host) { - Assert.hasLength(host, "Host may not be null or empty."); - HttpUrl httpUrl = HttpUrl.parse(host); - return getDefaultHeaders(httpUrl); - } - - /** - * 获取默认的Http Header列表 - * - * @param httpUrl 地址信息 - * @return Header键值对列表 - */ - public Map getDefaultHeaders(HttpUrl httpUrl) { - Assert.notNull(httpUrl, "HttpUrl is null or invalid."); - Map headers = defaultHeaders.get(httpUrl.host()); - return headers == null ? Collections.emptyMap() : Collections.unmodifiableMap(headers); - } - - /** - * 清除默认参数 - * - * @param host 主机名 - * @return {@linkplain HttpClient} - */ - public HttpClient clearDefaultHeaders(String host) { - Assert.hasLength(host, "Host may not be null or empty."); - HttpUrl httpUrl = HttpUrl.parse(host); - return clearDefaultHeaders(httpUrl); - } - - /** - * 清除默认参数 - * - * @param httpUrl 地址信息 - * @return {@linkplain HttpClient} - */ - private HttpClient clearDefaultHeaders(HttpUrl httpUrl) { - Assert.notNull(httpUrl, "HttpUrl is null or invalid."); - defaultHeaders.remove(httpUrl.host()); - return this; - } - //endregion - -// /** -// * 获取默认的请求参数列表 -// * -// * @return 请求参数键值对列表 -// */ -// public Map getDefaultParams() { -// return new ConcurrentHashMap<>(this.defaultParameters); -// } - - //region================Cookie和拦截器================ - - /** - * 提供自己管理Cookie的能力 - * - * @param cookieStore 操作Cookie的接口 - * @return {@linkplain HttpClient} - */ - public HttpClient setCookieStore(CookieStore cookieStore) { - Assert.notNull(cookieStore, "CookieStore may not be null."); - this.cookieStore = cookieStore; - this.builder.cookieJar(new DefaultCookieJar(cookieStore)); - return this; - } - - /** - * 返回{@linkplain CookieStore}实现类 - * - * @return {@link CookieStore} - */ - public CookieStore getCookieStore() { - return this.cookieStore; - } - - /** - * 添加全局拦截器 - * - * @param customInterceptor 拦截器接口 - * @return {@linkplain HttpClient} - */ - public HttpClient addInterceptor(Interceptor customInterceptor) { - this.builder.addInterceptor(customInterceptor); - return this; - } - //endregion - - //region================Debug调试================ - - /** - * 调试模式,默认打印请求参数和响应结果 - * - * @return {@linkplain HttpClient} - */ - public HttpClient debugLog() { - return debugLog(DebugLoggingInterceptor.Level.BASIC); - } - - /** - * 调试模式,自定义设置日志级别 - * - * @param loggingLevel 日志级别 - * @return {@linkplain HttpClient} - * @see DebugLoggingInterceptor.Level - */ - public HttpClient debugLog(DebugLoggingInterceptor.Level loggingLevel) { - DebugLoggingInterceptor instance = DebugLoggingInterceptor.INSTANCE; - instance.setLoggingLevel(loggingLevel); - this.builder.addInterceptor(instance); - return this; - } - //endregion - - - //region============构建OkHttpClient=================== - - /** - * 返回{@linkplain OkHttpClient}对象 - * - * @return {@link OkHttpClient} - */ - public OkHttpClient getOkHttpClient() { - if (this.okHttpClient == null) { - synchronized (Instance) { - if (this.okHttpClient == null) { - this.okHttpClient = builder.build(); - } - } - } - return this.okHttpClient; - } - - public OkHttpClient.Builder getOkHttpClientBuilder() { - this.getOkHttpClient();//为了创建默认的OkHttpClient - return this.builder; - } - //endregion - - - //region=====================request====================== - - /** - * Get请求 - * - * @param url 请求地址 - * @return {@link GetRequest} - */ - public static GetRequest get(String url) { - return new GetRequest(url); - } - - /** - * FORM/POST表单提交 - * - * @param url 提交地址 - * @return {@link PostRequest} - */ - public static PostRequest post(String url) { - return new PostRequest(url); - } - - /** - * 向请求体中传入二进制流 - * - * @param url 请求地址 - * @return {@linkplain BinaryBodyPostRequest} - */ - public static BinaryBodyPostRequest binaryBody(String url) { - return new BinaryBodyPostRequest(url); - } - - /** - * 文本POST请求体 - * - * @param url 请求地址 - * @return {@link TextBodyRequest} - */ - public static TextBodyRequest textBody(String url) { - return new TextBodyRequest(url); - } - //endregion - -} diff --git a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/cookie/CookieStore.java b/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/cookie/CookieStore.java deleted file mode 100644 index fe96ce9f86..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/cookie/CookieStore.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (C) 2016-2017 mzlion(mzllon@qq.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mzlion.easyokhttp.cookie; - -import okhttp3.Cookie; -import okhttp3.HttpUrl; - -import java.util.List; - -/** - * 定义Cookie存储机制 - * - * @author mzlion on 2016/4/17. - */ -public interface CookieStore { - - /** - * 为请求地址{@code url}增加Cookie - * - * @param uri 请求地址 - * @param cookies Cookie列表 - * @see Cookie - */ - void add(HttpUrl uri, List cookies); - - /** - * 获取某个请求地址的Cookie列表 - * - * @param uri 请求地址 - * @return Cookie列表 - * @see Cookie - */ - List get(HttpUrl uri); - - /** - * 获取所有Cookie列表 - * - * @return {@link Cookie} - */ - List getCookies(); - - /** - * 删除请求的某个Cookie - * - * @param uri 请求地址 - * @param cookie Cookie对象 - * @return 删除成功则返回{@code true},否则返回{@code false} - */ - boolean remove(HttpUrl uri, Cookie cookie); - - /** - * 清空所有Cookie列表 - * - * @return 清空成功则返回{@code true},否则返回{@code false} - */ - boolean removeAll(); - -} diff --git a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/cookie/DefaultCookieJar.java b/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/cookie/DefaultCookieJar.java deleted file mode 100644 index 9bb8a6711e..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/cookie/DefaultCookieJar.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2016-2017 mzlion(mzllon@qq.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mzlion.easyokhttp.cookie; - -import okhttp3.Cookie; -import okhttp3.CookieJar; -import okhttp3.HttpUrl; - -import java.util.List; - -/** - * 默认的Cookie处理,自动管理用户的Cookie. - * - * @author mzlion on 2016/4/17. - */ -public class DefaultCookieJar implements CookieJar { - - private CookieStore cookieStore; - - public DefaultCookieJar(CookieStore cookieStore) { - if (cookieStore == null) { - throw new NullPointerException("CookieStore may not be null."); - } - this.cookieStore = cookieStore; - } - - @Override - public void saveFromResponse(HttpUrl url, List cookies) { - cookieStore.add(url, cookies); - } - - @Override - public List loadForRequest(HttpUrl url) { - return cookieStore.get(url); - } -} diff --git a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/cookie/MemoryCookieStore.java b/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/cookie/MemoryCookieStore.java deleted file mode 100644 index bb93caa978..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/cookie/MemoryCookieStore.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2016-2017 mzlion(mzllon@qq.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mzlion.easyokhttp.cookie; - -import com.mzlion.core.lang.CollectionUtils; -import okhttp3.Cookie; -import okhttp3.HttpUrl; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * 内存缓存Cookie - * - * @author mzlionon 2016/4/17. - */ -public class MemoryCookieStore implements CookieStore { - private final Map> allCookies = new ConcurrentHashMap<>(); - - @Override - public void add(HttpUrl uri, List cookies) { - if (uri == null) { - throw new NullPointerException("Uri must not be null."); - } - if (CollectionUtils.isEmpty(cookies)) { - throw new NullPointerException("Cookies must not be null."); - } - List oldCookies = allCookies.get(uri.host()); - List deleteCookies = new ArrayList<>(oldCookies.size()); - for (Cookie cookie : cookies) { - for (Cookie oldCookie : oldCookies) { - if (oldCookie.name().equals(cookie.name())) { - deleteCookies.add(oldCookie); - } - } - } - oldCookies.removeAll(deleteCookies); - oldCookies.addAll(cookies); - } - - @Override - public List get(HttpUrl uri) { - if (uri == null) { - throw new NullPointerException("Uri must not be null."); - } - List cookies = allCookies.get(uri.host()); - if (cookies == null) { - cookies = new ArrayList<>(); - allCookies.put(uri.host(), cookies); - } - return cookies; - } - - @Override - public List getCookies() { - List cookies = new ArrayList<>(20); - for (String host : allCookies.keySet()) { - cookies.addAll(allCookies.get(host)); - } - return cookies; - } - - @Override - public boolean remove(HttpUrl uri, Cookie cookie) { - if (uri == null) { - throw new NullPointerException("Uri must not be null."); - } - if (cookie == null) { - throw new NullPointerException("Cookie must not be null."); - } - return allCookies.remove(uri.host()) != null; - } - - @Override - public boolean removeAll() { - allCookies.clear(); - return true; - } -} diff --git a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/exception/HttpClientConfigException.java b/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/exception/HttpClientConfigException.java deleted file mode 100644 index 433c44adeb..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/exception/HttpClientConfigException.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2016-2017 mzlion(mzllon@qq.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mzlion.easyokhttp.exception; - -/** - * 配置HttpClient异常 - * - * @author mzlion on 2016/5/24. - */ -public class HttpClientConfigException extends RuntimeException { - - private static final long serialVersionUID = 1788789757077983056L; - - public HttpClientConfigException(Throwable cause) { - super(cause); - } - - public HttpClientConfigException(String message) { - super(message); - } -} diff --git a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/exception/HttpClientException.java b/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/exception/HttpClientException.java deleted file mode 100644 index 4bf87da893..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/exception/HttpClientException.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2016-2017 mzlion(mzllon@qq.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mzlion.easyokhttp.exception; - -/** - * HttpClient执行过程的异常 - * - * @author mzlion on 2016/7/12. - */ -public class HttpClientException extends RuntimeException { - - private static final long serialVersionUID = 8168339677503663451L; - - /** - * Constructs a new runtime exception with {@code null} as its - * detail message. The cause is not initialized, and may subsequently be - * initialized by a call to {@link #initCause}. - */ - public HttpClientException() { - super(); - } - - /** - * Constructs a new runtime exception with the specified detail message. - * The cause is not initialized, and may subsequently be initialized by a - * call to {@link #initCause}. - * - * @param message the detail message. The detail message is saved for - * later retrieval by the {@link #getMessage()} method. - */ - public HttpClientException(String message) { - super(message); - } - - /** - * Constructs a new runtime exception with the specified cause and a - * detail message of (cause==null ? null : cause.toString()) - * (which typically contains the class and detail message of - * cause). This constructor is useful for runtime exceptions - * that are little more than wrappers for other throwables. - * - * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is - * permitted, and indicates that the cause is nonexistent or - * unknown.) - * @since 1.4 - */ - public HttpClientException(Throwable cause) { - super(cause); - } -} diff --git a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/exception/HttpStatusCodeException.java b/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/exception/HttpStatusCodeException.java deleted file mode 100644 index 06c172ab47..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/exception/HttpStatusCodeException.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2016-2017 mzlion(mzllon@qq.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mzlion.easyokhttp.exception; - -/** - * Http Status Code exception,当code不是200时则会跑出本异常信息 - * - * @author mzlion on 2016/12/15. - */ -public class HttpStatusCodeException extends HttpClientException { - - private static final long serialVersionUID = -1584716934177136972L; - private final String url; - private final int statusCode; - private final String statusMessage; - - public HttpStatusCodeException(String url, int statusCode, String statusMessage) { - super("Request url[=" + url + "] failed, status code is " + statusCode + ",status message is " + statusMessage); - this.url = url; - this.statusCode = statusCode; - this.statusMessage = statusMessage; - } - - /** - * 请求失败时的HTTP Status Code - * - * @return Http错误码 - */ - public int getStatusCode() { - return statusCode; - } - - /** - * 请求失败时错误消息 - * - * @return 失败消息 - */ - public String getStatusMessage() { - return statusMessage; - } - - /** - * 返回请求地址 - * - * @return 请求地址 - */ - public String getUrl() { - return url; - } -} diff --git a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/http/BasicHeader.java b/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/http/BasicHeader.java deleted file mode 100644 index 6c543addf4..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/http/BasicHeader.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Copyright (C) 2016-2017 mzlion(mzllon@qq.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mzlion.easyokhttp.http; - -import com.mzlion.core.lang.Assert; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; - -/** - * 消息头 - * - * @author mzlion on 2016/12/8. - */ -public class BasicHeader implements Header, Serializable, Cloneable { - - private static final long serialVersionUID = -6025489654253774764L; - private final String name; - private final String value; - - public BasicHeader(String name, String value) { - Assert.hasLength(name, "name may not be null."); - Assert.notNull(value, "Value may not be null."); - this.name = name; - this.value = value; - } - - /** - * Get the name of the Header. - * - * @return the name of the Header, never {@code null} - */ - @Override - - public String getName() { - return name; - } - - /** - * Get the value of the Header. - * - * @return the value of the Header, may be {@code null} - */ - @Override - public String getValue() { - return value; - } - - /** - * Clone it. - * - * @see Cloneable - */ - @Override - public Object clone() throws CloneNotSupportedException { - return super.clone(); - } - - /** - * Represent standard headeroutput - * - * @return a string representation - */ - @Override - public String toString() { - int length = this.name.length() + 2; - if (this.value != null) length += this.value.length(); - StringBuilder result = new StringBuilder(length); - result.append(this.name).append(" :"); - if (this.value != null) result.append(this.value); - return result.toString(); - } - - public static StandardBuilder standard() { - return StandardBuilder.create(); - } - - /** - * 标准的消息头Builder - * - * @author mzlion - */ - public static class StandardBuilder { - - private final List headerFields; - private final List headerValues; - - StandardBuilder() { - this.headerFields = new ArrayList<>(); - this.headerValues = new ArrayList<>(); - } - - public static StandardBuilder create() { - return new StandardBuilder(); - } - - public StandardBuilder accept(String value) { - this.tryDo(Header.ACCEPT, value); - return this; - } - - public StandardBuilder acceptCharset(String value) { - this.tryDo(Header.ACCEPT_CHARSET, value); - return this; - } - - public StandardBuilder acceptEncoding(String value) { - this.tryDo(Header.ACCEPT_ENCODING, value); - return this; - } - - public StandardBuilder acceptLanguage(String value) { - this.tryDo(Header.ACCEPT_LANGUAGE, value); - return this; - } - - public StandardBuilder acceptRanges(String value) { - this.tryDo(Header.ACCEPT_RANGES, value); - return this; - } - - public StandardBuilder age(String value) { - this.tryDo(Header.AGE, value); - return this; - } - - public StandardBuilder allow(String value) { - this.tryDo(Header.ALLOW, value); - return this; - } - - public StandardBuilder cacheControl(String value) { - this.tryDo(Header.CACHE_CONTROL, value); - return this; - } - - public StandardBuilder connection(String value) { - this.tryDo(Header.CONNECTION, value); - return this; - } - - public StandardBuilder contentEncoding(String value) { - this.tryDo(Header.CONTENT_ENCODING, value); - return this; - } - - public StandardBuilder contentLanguage(String value) { - this.tryDo(Header.CONTENT_LANGUAGE, value); - return this; - } - - public StandardBuilder contentLength(String value) { - this.tryDo(Header.CONTENT_LENGTH, value); - return this; - } - - public StandardBuilder contentLocation(String value) { - this.tryDo(Header.CONTENT_LOCATION, value); - return this; - } - - public StandardBuilder contentMD5(String value) { - this.tryDo(Header.CONTENT_MD5, value); - return this; - } - - public StandardBuilder contentRange(String value) { - this.tryDo(Header.CONTENT_RANGE, value); - return this; - } - - public StandardBuilder contentType(String value) { - this.tryDo(Header.CONTENT_TYPE, value); - return this; - } - - public StandardBuilder contentDisposition(String value) { - this.tryDo(Header.CONTENT_DISPOSITION, value); - return this; - } - - public StandardBuilder userAgent(String value) { - this.tryDo(Header.USER_AGENT, value); - return this; - } - - public List
build() { - List
headerList = new LinkedList<>(); - Header header; - for (int i = 0, size = this.headerFields.size(); i < size; i++) { - header = new BasicHeader(this.headerFields.get(i), this.headerValues.get(i)); - headerList.add(header); - } - return headerList; - } - - private void tryDo(String name, String value) { - int index = this.headerFields.indexOf(name); - if (index == -1) { - this.headerFields.add(name); - this.headerValues.set(this.headerFields.size() - 1, value); - } else { - this.headerValues.set(index, value); - } - } - - } -} diff --git a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/http/DebugLoggingInterceptor.java b/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/http/DebugLoggingInterceptor.java deleted file mode 100644 index 2ff0182ff3..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/http/DebugLoggingInterceptor.java +++ /dev/null @@ -1,199 +0,0 @@ -/* - * Copyright (C) 2016-2017 mzlion(mzllon@qq.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mzlion.easyokhttp.http; - -import okhttp3.*; -import okhttp3.internal.Util; -import okhttp3.internal.http.HttpHeaders; -import okio.Buffer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.concurrent.TimeUnit; - -/** - * 日志打印 - * - * @author mzlion on 2017/1/24. - */ -public enum DebugLoggingInterceptor implements Interceptor { - INSTANCE; - - private final Logger logger = LoggerFactory.getLogger(DebugLoggingInterceptor.class); - - /** - * 日志级别 - */ - private Level loggingLevel; - - DebugLoggingInterceptor() { - loggingLevel = Level.NONE; - } - - public void setLoggingLevel(Level loggingLevel) { - this.loggingLevel = loggingLevel == null ? Level.NONE : loggingLevel; - } - - @Override - public Response intercept(Chain chain) throws IOException { - //这个chain里面包含了request和response,所以你要什么都可以从这里拿 - Request request = chain.request(); - loggingRequest(request); - - long startTime = System.nanoTime(); - Response response = chain.proceed(request); - long usedTimes = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime); - loggingResponse(response, usedTimes); - - return response; - } - - private void loggingResponse(Response response, long usedTimes) throws IOException { - if (loggingLevel == Level.NONE || loggingLevel == Level.REQUEST) { - return; - } - boolean bodyPrint = loggingLevel == Level.RESPONSE || loggingLevel == Level.BASIC || loggingLevel == Level.ALL, - headerPrint = loggingLevel == Level.RESPONSE || loggingLevel == Level.HEADER || loggingLevel == Level.ALL; - HttpUrl httpUrl = response.request().url(); - ResponseBody responseBody = response.peekBody(1024 << 1); - - if (loggingLevel == Level.RESPONSE) { - logger.info(" |=== Start to print the connection[{}] data ===|", httpUrl.toString()); - } - logger.info(" |=== The request executes over,http statusCode is {},http message is {},taking {} ms", - response.code(), response.message(), usedTimes); - if (headerPrint) { - logger.info(" |=== Start to print response headers === |"); - Headers headers = response.headers(); - for (String name : headers.names()) { - logger.info(" |=== {} : {} ===|", name, headers.get(name)); - } - logger.info(" |=== Finish to print response headers === |"); - } - if (bodyPrint && HttpHeaders.hasBody(response)) { - if (isPlainText(responseBody.contentType())) { - logger.info(" |=== Start to print response body === |"); - logger.info(" |=== The body data is \n{}", responseBody.string()); - logger.info(" |=== Finish to print response body === |"); - } else { - logger.warn(" |=== The response body may contains 'file' part, ignore to print! ===|"); - } - } - logger.info(" |=== Finish to print the connection[{}] data ===|\n", httpUrl.toString()); - } - - private void loggingRequest(Request request) throws IOException { - if (loggingLevel == Level.NONE || loggingLevel == Level.RESPONSE) { - return; - } - boolean bodyPrint = loggingLevel == Level.REQUEST || loggingLevel == Level.BASIC || loggingLevel == Level.ALL, - headerPrint = loggingLevel == Level.REQUEST || loggingLevel == Level.HEADER || loggingLevel == Level.ALL; - HttpUrl httpUrl = request.url(); - logger.info(" |=== Start to print the connection[{}] data ===|", httpUrl.toString()); - if (headerPrint) { - logger.info(" |=== Start to print request headers === |"); - Headers headers = request.headers(); - for (String name : headers.names()) { - logger.info(" |=== {} : {} ===|", name, headers.get(name)); - } - logger.info(" |=== Finish to print request headers === |"); - } - if (bodyPrint) { - RequestBody requestBody = request.body(); - if (requestBody != null) { - if (isPlainText(requestBody.contentType())) { - logger.info(" |=== Start to print request body === |"); - Request copy = request.newBuilder().build(); - requestBody = copy.body(); - Buffer buffer = new Buffer(); - requestBody.writeTo(buffer); - MediaType mediaType = requestBody.contentType(); - logger.info(" |=== The body data is {} ===|", buffer.readString(mediaType.charset(Util.UTF_8))); - logger.info(" |=== Finish to print request body === |"); - } else { - logger.warn(" |=== The request body may contains 'file' part, ignore to print! ===|"); - } - } - } - if (loggingLevel == Level.REQUEST) { - logger.info(" |=== Finish to print the connection[{}] data ===|\n", httpUrl.toString()); - } - } - - /** - * Returns true if the body in question probably contains human readable text. Uses a small sample - * of code points to detect unicode control characters commonly used in binary file signatures. - * - * @param mediaType The content type - */ - private boolean isPlainText(MediaType mediaType) { - if (mediaType == null) { - return false; - } - if (mediaType.type() != null && mediaType.type().equals("text")) { - return true; - } - String subtype = mediaType.subtype(); - if (subtype != null) { - if (subtype.contains("x-www-form-urlencoded") || subtype.contains("json") || - subtype.contains("xml") || subtype.contains("html")) { - return true; - } - } - return false; - } - - /** - * 定义日志打印级别 - * - * @author mzlion on 2017/1/24. - */ - public enum Level { - - /** - * 不打印日志 - */ - NONE, - - /** - * 打印请求参数和响应结果 - */ - BASIC, - - /** - * 打印请求Header和响应Header - */ - HEADER, - - /** - * 打印请求参数和header - */ - REQUEST, - - /** - * 打印响应结果和header - */ - RESPONSE, - - /** - * 打印所有信息 - */ - ALL, - } - - -} diff --git a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/http/FileRequestBody.java b/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/http/FileRequestBody.java deleted file mode 100644 index b23f0ea2ba..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/http/FileRequestBody.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) 2016-2017 mzlion(mzllon@qq.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mzlion.easyokhttp.http; - -import okhttp3.MediaType; -import okhttp3.RequestBody; -import okhttp3.internal.Util; -import okio.BufferedSink; -import okio.Okio; -import okio.Source; - -import java.io.File; -import java.io.IOException; - -/** - * 文件请求对象 - * - * @author mzlion on 2016/12/9. - */ -public class FileRequestBody extends RequestBody { - - private final File file; - private final MediaType mediaType; - - public FileRequestBody(File file, MediaType mediaType) { - this.file = file; - this.mediaType = mediaType; - } - - /** - * Returns the number of bytes that will be written to {@code out} in a call to {@link #writeTo}, - * or -1 if that count is unknown. - */ - @Override - public long contentLength() throws IOException { - return file.length(); - } - - /** - * Returns the Content-Type header for this body. - */ - @Override - public MediaType contentType() { - return this.mediaType; - } - - /** - * Writes the content of this request to {@code out}. - */ - @Override - public void writeTo(BufferedSink sink) throws IOException { - Source source = null; - try { - source = Okio.source(file); - sink.writeAll(source); - } finally { - Util.closeQuietly(source); - } - } -} diff --git a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/http/FileWrapper.java b/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/http/FileWrapper.java deleted file mode 100644 index 2373bfa8e8..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/http/FileWrapper.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (C) 2016-2017 mzlion(mzllon@qq.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mzlion.easyokhttp.http; - -import com.mzlion.core.lang.Assert; -import com.mzlion.easyokhttp.exception.HttpClientException; -import com.mzlion.easyokhttp.utils.Utils; -import okhttp3.MediaType; -import okhttp3.RequestBody; - -import java.io.File; -import java.io.InputStream; - -/** - * 文件包装类 - * - * @author mzlion on 2016/12/9. - */ -public class FileWrapper { - - private InputStream content; - private File file; - private String filename; - - private MediaType mediaType; - - FileWrapper(Builder builder) { - this.mediaType = builder.mediaType; - this.file = builder.file; - this.filename = builder.filename; - this.content = builder.content; - } - - public String getFilename() { - return filename; - } - - public static Builder create() { - return new Builder(); - } - - public RequestBody requestBody() { - if (this.file != null) { - return new FileRequestBody(this.file, this.mediaType); - } - return new InputStreamRequestBody(this.content, this.mediaType); - } - - public static class Builder { - - private InputStream content; - - private File file; - private String filename; - - private MediaType mediaType; - - - public Builder file(File file) { - Assert.notNull(file, "File may not be null."); - if (!file.exists()) { - throw new HttpClientException("File does not exist."); - } - this.file = file; - return this; - } - - public Builder filename(String filename) { - Assert.hasLength(filename, "Filename may not be null."); - this.filename = filename; - return this; - } - - public Builder stream(InputStream stream) { - Assert.notNull(stream, "Stream may not be null."); - this.content = stream; - return this; - } - - public Builder contentType(String contentType) { - Assert.hasLength(contentType, "ContentType may not be null."); - this.mediaType = MediaType.parse(contentType); - return this; - } - - public Builder mediaType(MediaType mediaType) { - Assert.notNull(mediaType, "Media may not be null."); - this.mediaType = mediaType; - return this; - } - - public FileWrapper build() { - if (this.file != null) { - if (this.filename == null) { - this.filename = file.getName(); - } - } else if (this.content != null) { - if (this.filename == null) { - throw new HttpClientException("Filename may not be null"); - } - } else { - throw new HttpClientException("The content is null."); - } - if (this.mediaType == null) { - this.mediaType = Utils.guessMediaType(this.filename); - } - return new FileWrapper(this); - } - - } -} diff --git a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/http/Header.java b/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/http/Header.java deleted file mode 100644 index df3aa79542..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/http/Header.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (C) 2016-2017 mzlion(mzllon@qq.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mzlion.easyokhttp.http; - -/** - * HTTP header对象 - * - * @author mzlion on 2016/12/8. - */ -public interface Header { - - /** - * Get the name of the Header. - * - * @return the name of the Header, never {@code null} - */ - String getName(); - - /** - * Get the value of the Header. - * - * @return the value of the Header, may be {@code null} - */ - String getValue(); - - //region==============定义常用的标准header name============== - /** - * The header Accept - */ - String ACCEPT = "Accept"; - /** - * The header Accept-Charset - */ - String ACCEPT_CHARSET = "Accept-Charset"; - /** - * The header Accept-Encoding - */ - String ACCEPT_ENCODING = "Accept-Encoding"; - /** - * The header Accept-Language - */ - String ACCEPT_LANGUAGE = "Accept-Language"; - /** - * The header Accept-Ranges - */ - String ACCEPT_RANGES = "Accept-Ranges"; - /** - * The header Age - */ - String AGE = "Age"; - /** - * The header Allow - */ - String ALLOW = "Allow"; - /** - * The header Cache-Control - */ - String CACHE_CONTROL = "Cache-Control"; - /** - * The header Connection - */ - String CONNECTION = "Connection"; - /** - * The header Content-Encoding - */ - String CONTENT_ENCODING = "Content-Encoding"; - /** - * The header Content-Language - */ - String CONTENT_LANGUAGE = "Content-Language"; - /** - * The header Content-Length - */ - String CONTENT_LENGTH = "Content-Length"; - /** - * The header Content-Location - */ - String CONTENT_LOCATION = "Content-Location"; - /** - * The header Content-MD5 - */ - String CONTENT_MD5 = "Content-MD5"; - /** - * The header Content-Range - */ - String CONTENT_RANGE = "Content-Range"; - /** - * The header Content-Type - */ - String CONTENT_TYPE = "Content-Type"; - /** - * The header Content-Disposition - */ - String CONTENT_DISPOSITION = "Content-Disposition"; - /** - * The header User-Agent - */ - String USER_AGENT = "User-Agent"; - /** - * The header Transfer-Encoding - */ - String TRANSFER_ENCODING = "Transfer-Encoding"; - //endregion==============定义常用的标准header name============== -} diff --git a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/http/InputStreamRequestBody.java b/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/http/InputStreamRequestBody.java deleted file mode 100644 index 88a201c035..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/http/InputStreamRequestBody.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2016-2017 mzlion(mzllon@qq.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mzlion.easyokhttp.http; - -import com.mzlion.core.io.IOUtils; -import okhttp3.MediaType; -import okhttp3.RequestBody; -import okio.BufferedSink; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; - -/** - * Request body封装 - * - * @author tony on 2016-12-09 - */ -public class InputStreamRequestBody extends RequestBody { - - private final byte[] content; - private final int byteCount; - private final MediaType mediaType; - - public InputStreamRequestBody(InputStream content, MediaType mediaType) { - this.mediaType = mediaType; - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try { - IOUtils.copy(content, baos); - this.content = baos.toByteArray(); - this.byteCount = this.content.length; - } finally { - IOUtils.closeQuietly(content); - } - } - - /** - * Returns the number of bytes that will be written to {@code out} in a call to {@link #writeTo}, - * or -1 if that count is unknown. - */ - @Override - public long contentLength() throws IOException { - return this.byteCount; - } - - /** - * Returns the Content-Type header for this body. - */ - @Override - public MediaType contentType() { - return this.mediaType; - } - - /** - * Writes the content of this request to {@code out}. - */ - @Override - public void writeTo(BufferedSink sink) throws IOException { - sink.write(this.content, 0, this.byteCount); - } -} diff --git a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/http/ProcessRequestBody.java b/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/http/ProcessRequestBody.java deleted file mode 100644 index 056de5ddd0..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/http/ProcessRequestBody.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (C) 2016-2017 mzlion(mzllon@qq.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mzlion.easyokhttp.http; - -import okhttp3.MediaType; -import okhttp3.RequestBody; -import okio.*; - -import java.io.IOException; - -/** - * 处理提交进度,一般对有进度展示需求的有用 - * - * @author mzlion on 2016-12-14 - */ -public class ProcessRequestBody extends RequestBody { - - private RequestBody delegate; - private Listener listener; - - public ProcessRequestBody(RequestBody delegate, Listener listener) { - this.delegate = delegate; - this.listener = listener; - } - - /** - * Returns the Content-Type header for this body. - */ - @Override - public MediaType contentType() { - return this.delegate.contentType(); - } - - /** - * Returns the number of bytes that will be written to {@code out} in a call to {@link #writeTo}, - * or -1 if that count is unknown. - */ - @Override - public long contentLength() throws IOException { - return this.delegate.contentLength(); - } - - /** - * Writes the content of this request to {@code out}. - * - * @param sink {@link BufferedSink} - */ - @Override - public void writeTo(BufferedSink sink) throws IOException { - ProgressSink progressSink = new ProgressSink(sink); - BufferedSink bufferedSink = Okio.buffer(progressSink); - this.delegate.writeTo(bufferedSink); - bufferedSink.flush();//必须调用flush保证都写入完成 - } - - /** - * 计算字节处理进度 - */ - private final class ProgressSink extends ForwardingSink { - - private long bytesWritten;//当前写入字节数 - - ProgressSink(Sink delegate) { - super(delegate); - } - - @Override - public void write(Buffer source, long byteCount) throws IOException { - super.write(source, byteCount); - this.bytesWritten += byteCount; - listener.onRequestProgress(this.bytesWritten, contentLength()); - } - } - - - /** - * 回调接口 - */ - public interface Listener { - void onRequestProgress(final long bytesWritten, final long contentLength); - } -} diff --git a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/request/AbsHttpRequest.java b/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/request/AbsHttpRequest.java deleted file mode 100644 index 4597c23415..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/request/AbsHttpRequest.java +++ /dev/null @@ -1,637 +0,0 @@ -/* - * Copyright (C) 2016-2017 mzlion(mzllon@qq.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mzlion.easyokhttp.request; - -import com.mzlion.core.io.IOUtils; -import com.mzlion.core.json.TypeRef; -import com.mzlion.core.lang.Assert; -import com.mzlion.core.lang.CollectionUtils; -import com.mzlion.core.lang.StringUtils; -import com.mzlion.easyokhttp.HttpClient; -import com.mzlion.easyokhttp.exception.HttpClientConfigException; -import com.mzlion.easyokhttp.exception.HttpClientException; -import com.mzlion.easyokhttp.exception.HttpStatusCodeException; -import com.mzlion.easyokhttp.http.Header; -import com.mzlion.easyokhttp.http.ProcessRequestBody; -import com.mzlion.easyokhttp.response.HttpResponse; -import com.mzlion.easyokhttp.response.callback.Callback; -import com.mzlion.easyokhttp.utils.SSLContexts; -import com.mzlion.easyokhttp.utils.Utils; -import okhttp3.*; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.net.ssl.X509TrustManager; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -/** - *

- * 2016-04-16 {@linkplain HttpRequest}的抽象实现,实现了大部分方法. - *

- * - * @author mzlion on 2016-04-16 - */ -@SuppressWarnings("unchecked") -public abstract class AbsHttpRequest> implements HttpRequest { - protected Logger logger = LoggerFactory.getLogger(AbsHttpRequest.class); - protected String url; - - /** - * 连接超时时间 - */ - private TimeoutHolder connectTimeout; - /** - * 流读取超时时间 - */ - private TimeoutHolder readTimeout; - /** - * 流写入超时时间 - */ - private TimeoutHolder writeTimeout; - - /** - * SSL证书文件列表 - */ - private CertificateHolder certificateHolder = null; - - /** - * 存储请求头信息 - */ - private Map headers; - - private Map> queryParams; - - /** - * default constructor - * - * @param url 请求地址 - */ - AbsHttpRequest(String url) { - this.url = url; - this.headers = new LinkedHashMap<>(); - this.queryParams = new LinkedHashMap<>(); - - //设置默认的User-Agent和Accept-Language - this.header(Header.ACCEPT_LANGUAGE, Utils.getAcceptLanguage()); - this.header(Header.USER_AGENT, Utils.getUserAgent()); - } - - /** - * 设置请求地址 - * - * @param url 请求地址 - * @return 返回当前类{@linkplain Req}的对象自己 - */ - @Override - public Req url(String url) { - this.url = url; - return (Req) this; - } - - - //region===============为URL后面追加参数=============== - - /** - * 为url地址设置请求参数,即url?username=admin pwd=123 - * - * @param name 参数名 - * @param value 参数值 - * @return 返回当前类{@linkplain Req}的对象自己 - */ - @Override - public Req queryString(String name, Number value) { - return this.queryString(name, value == null ? null : value.toString()); - } - - /** - * 为url地址设置请求参数,即url?username=admin pwd=123 - * - * @param name 参数名 - * @param value 参数值 - * @return 返回当前类{@linkplain Req}的对象自己 - */ - @Override - public Req queryString(String name, String value) { - return this.queryString(name, value, false); - } - - /** - * 为url地址设置请求参数,即url?username=admin pwd=123 - * - * @param name 参数名 - * @param value 参数值 - * @param replace 值为[@code true}则替换 - * @return 返回当前类{@linkplain Req}的对象自己 - */ - @Override - public Req queryString(String name, String value, boolean replace) { - //Assert.hasLength(name, "Name must not be null."); - if (StringUtils.isEmpty(name)) { - return (Req) this; - } - if (!replace && value == null) { - logger.warn(" ===> The value is null,ignore:name={},value=null", name); - return (Req) this; - } - List valueList = this.queryParams.get(name); - if (valueList == null) { - valueList = new LinkedList<>(); - this.queryParams.put(name, valueList); - } - if (replace) { - valueList.clear(); - } - valueList.add(value); - return (Req) this; - } - - /** - * 为url地址设置请求参数,即url?username=admin pwd=123 - * - * @param parameters 参数对 - * @return 返回当前类{@linkplain Req}的对象自己 - */ - @Override - public Req queryString(Map parameters) { - //Assert.notEmpty(parameters, "Parameters may not be null or empty."); - if (CollectionUtils.isEmpty(parameters)) { - return (Req) this; - } - for (Map.Entry entry : parameters.entrySet()) { - this.queryString(entry.getKey(), entry.getValue()); - } - return (Req) this; - } - //endregion===============为URL后面追加参数=============== - - - //region===============设置HTTP Header=============== - - /** - * 添加请求头信息 - * - * @param name 请求头键名 - * @param value 请求头值 - * @return 返回当前类{@linkplain Req}的对象自己 - */ - @Override - public Req header(String name, String value) { - //Assert.hasLength(name, "Name may not be null or empty."); - //Assert.notNull(value, "Value may not be null."); - if (StringUtils.hasLength(name) && null != value) { - this.headers.put(name, value); - } - return (Req) this; - } - - /** - * 从请求头中移除键值 - * - * @param name 请求头键名 - * @return 返回当前类{@linkplain Req}的对象自己 - */ - @Override - public Req removeHeader(String name) { - //Assert.hasLength(name, "Name may noy be null or empty."); - if (StringUtils.hasLength(name)) { - this.headers.remove(name); - } - return (Req) this; - } - //endregion===============设置HTTP Header=============== - - - //region===============覆盖配置HttpClient=============== - - /** - * 为构建本次{@linkplain HttpRequest}设置单独连接超时时间。调用此方法会重新创建{@linkplain OkHttpClient}。 - * - * @param connectTimeout 连接超时时间 - * @param timeUnit 超时时间单位 - * @return 返回当前类{@linkplain Req}的对象自己 - */ - @Override - public Req connectTimeout(int connectTimeout, TimeUnit timeUnit) { - if (connectTimeout < 0) { - throw new HttpClientConfigException("Connect Timeout may be than 0."); - } - if (timeUnit == null) { - throw new HttpClientConfigException("TimeUnit may not be null."); - } - this.connectTimeout = new TimeoutHolder(connectTimeout, timeUnit); - return (Req) this; - } - - /** - * 为构建本次{@linkplain HttpRequest}设置单独连接超时时间。调用此方法会重新创建{@linkplain OkHttpClient}。 - * - * @param connectTimeout 连接超时时间 - * @return 返回当前类{@linkplain Req}的对象自己 - */ - @Override - public Req connectTimeout(int connectTimeout) { - return connectTimeout(connectTimeout, TimeUnit.SECONDS); - } - - /** - * 为构建本次{@linkplain HttpRequest}设置单独读取流超时。 - * - * @param readTimeout 流读取超时时间 - * @param timeUnit 超时时间单位 - * @return 返回当前类{@linkplain Req}的对象自己 - */ - @Override - public Req readTimeout(int readTimeout, TimeUnit timeUnit) { - if (readTimeout < 0) { - throw new HttpClientConfigException("Read Timeout may be than 0."); - } - if (timeUnit == null) { - throw new HttpClientConfigException("TimeUnit may not be null."); - } - this.readTimeout = new TimeoutHolder(readTimeout, timeUnit); - return (Req) this; - } - - /** - * 为构建本次{@linkplain HttpRequest}设置单独读取流超时。 - * - * @param readTimeout 流读取超时时间 - * @return 返回当前类{@linkplain Req}的对象自己 - */ - @Override - public Req readTimeout(int readTimeout) { - return readTimeout(readTimeout, TimeUnit.SECONDS); - } - - /** - * 为构建本次{@linkplain HttpRequest}设置单独写入流超时。 - * - * @param writeTimeout 流写入超时时间 - * @param timeUnit 超时时间单位 - * @return 返回当前类{@linkplain Req}的对象自己 - */ - @Override - public Req writeTimeout(int writeTimeout, TimeUnit timeUnit) { - if (writeTimeout < 0) { - throw new HttpClientConfigException("Write Timeout may be than 0."); - } - if (timeUnit == null) { - throw new HttpClientConfigException("TimeUnit may not be null."); - } - this.writeTimeout = new TimeoutHolder(writeTimeout, timeUnit); - return (Req) this; - } - - /** - * 为构建本次{@linkplain HttpRequest}设置单独写入流超时。 - * - * @param writeTimeout 流写入超时时间 - * @return 返回当前类{@linkplain Req}的对象自己 - */ - @Override - public Req writeTimeout(int writeTimeout) { - return writeTimeout(writeTimeout, TimeUnit.SECONDS); - } - - /** - * 为构建本次{@linkplain HttpRequest}设置单独SSL证书 - * - * @param certificates SSL证书文件 - * @return 返回当前类{@link Req}的对象自己 - */ - @Override - public Req customSSL(InputStream... certificates) { - return customSSL(null, null, certificates); - } - - /** - * 为构建本次{@linkplain HttpRequest}设置SSL单向认证 - * - * @param trustManager 证书管理器 - * @return 返回当前类{@linkplain Req}的对象自己 - */ - @Override - public Req customSSL(X509TrustManager trustManager) { - return customSSL(null, null, trustManager); - } - - /** - * SSL双向认证 - * - * @param pfxStream 客户端证书,支持P12的证书 - * @param pfxPwd 客户端证书密码 - * @param certificates 含有服务端公钥的证书 - * @return {@link Req} - */ - @Override - public Req customSSL(InputStream pfxStream, char[] pfxPwd, InputStream... certificates) { - this.certificateHolder = new CertificateHolder(certificates, null, pfxStream, pfxPwd); - return (Req) this; - } - - /** - * SSL双向认证 - * - * @param pfxStream 客户端证书,支持P12的证书 - * @param pfxPwd 客户端证书密码 - * @param trustManager 证书管理器 - * @return {@link Req} - */ - @Override - public Req customSSL(InputStream pfxStream, char[] pfxPwd, X509TrustManager trustManager) { - this.certificateHolder = new CertificateHolder(null, trustManager, pfxStream, pfxPwd); - return (Req) this; - } - //endregion===============覆盖配置HttpClient=============== - - - //region===============增加了便捷转换方法=============== - - /** - * 将响应结果转为字符串 - * - * @return 响应结果字符串 - * @throws HttpClientException 如果服务器返回非200则抛出此异常 - */ - public String asString() { - return execute().asString(); - } - - /** - * 将响应结果转为JavaBean对象 - * - * @param targetClass 目标类型 - * @param 泛型类型 - * @return JavaBean对象 - * @throws HttpClientException 如果服务器返回非200则抛出此异常 - */ - public E asBean(Class targetClass) { - return this.execute().asBean(targetClass); - } - - /** - * 将响应结果转为JavaBean对象 - *

- * 用法如下:Map<String,String> data = httpResponse.asBean(new TypeRef<Map<String,String>>); - *

- * - * @param typeRef 带有泛型类的封装类 - * @param 泛型类型 - * @return JavaBean对象 - * @throws HttpClientException 如果服务器返回非200则抛出此异常 - */ - public E asBean(TypeRef typeRef) { - return this.execute().asBean(typeRef); - } - - /** - * 将响应结果转为字节数组 - * - * @return 字节数组 - * @throws HttpClientException 如果服务器返回非200则抛出此异常 - */ - public byte[] asByteData() { - return this.execute().asByteData(); - } - - /** - * 将响应结果输出到文件中 - * - * @param saveFile 目标保存文件,非空 - */ - public void asFile(File saveFile) { - this.execute().asFile(saveFile); - } - - /** - * 将响应结果输出到输出流,并不会主动关闭输出流{@code out} - * - * @param out 输出流,非空 - */ - public void asStream(OutputStream out) { - this.execute().asStream(out); - } - //endregion - - /** - * 执行HTTP请求,获取响应结果 - * - * @return 将响应结果转为具体的JavaBean - */ - @Override - public HttpResponse execute() { - RequestBody requestBody = this.generateRequestBody(); - Request request = this.generateRequest(requestBody); - Call call = this.generateCall(request); - Response response = null; - try { - response = call.execute(); - ResponseBody responseBody = response.body(); - byte[] byteData = responseBody.bytes(); - - Response newResponse = response.newBuilder() - .body(ResponseBody.create(responseBody.contentType(), byteData)) - .build(); - - HttpResponse httpResponse = new HttpResponse(newResponse); - httpResponse.setErrorMessage(response.message()); - httpResponse.setHttpCode(response.code()); - if (response.code() < 200 || response.code() >= 300) { - if (!call.isCanceled()) { - call.cancel(); - } - httpResponse.setSuccess(false); - return httpResponse; - } else { - httpResponse.setSuccess(true); - } - return httpResponse; - } catch (IOException e) { - throw new HttpClientException(e); - } finally { - IOUtils.closeQuietly(response); - } - } - - /** - * 异步执行请求 - * - * @param callback 回调接口 - * @param 数据类型 - */ - @Override - public void execute(Callback callback) { - Callback _cb = callback; - if (_cb == null) { - _cb = Callback.EMPTY_CALLBACK; - } - if (!callback.onBefore(this)) { - return; - } - final Callback finalCb = _cb; - - ProcessRequestBody processRequestBody = new ProcessRequestBody(this.generateRequestBody(), new ProcessRequestBody.Listener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength) { - finalCb.postProgress(bytesWritten, contentLength, 1.0f * bytesWritten / contentLength); - } - }); - Call call = this.generateCall(this.generateRequest(processRequestBody)); - call.enqueue(new okhttp3.Callback() { - @Override - public void onFailure(Call call, IOException e) { - if (!call.isCanceled()) { - call.cancel(); - } - finalCb.onError(call, e); - } - - @Override - public void onResponse(Call call, Response response) throws IOException { - finalCb.onComplete(response); - if (response.code() >= 200 && response.code() < 300) { - try { - finalCb.onSuccess(finalCb.getDataHandler() == null ? null : finalCb.getDataHandler().handle(response)); - } finally { - response.close(); - } - } else { - if (!call.isCanceled()) { - call.cancel(); - } - finalCb.onError(call, new HttpStatusCodeException(url, response.code(), response.message())); - } - } - }); - } - - /** - * 获取{@linkplain RequestBody}对象 - * - * @return {@linkplain RequestBody} - */ - protected abstract RequestBody generateRequestBody(); - - /** - * 根据不同的请求方式,将RequestBody转换成Request对象 - * - * @param requestBody 请求体 - * @return {@link Request} - * @see RequestBody - */ - protected abstract Request generateRequest(RequestBody requestBody); - - /** - * 执行请求调用 - * - * @param request Request对象 - * @return {@linkplain Call} - */ - private Call generateCall(Request request) { - if (readTimeout == null && connectTimeout == null && - writeTimeout == null && certificateHolder == null) { - return HttpClient.Instance.getOkHttpClient().newCall(request); - } - OkHttpClient.Builder builder = HttpClient.Instance.getOkHttpClientBuilder(); - if (connectTimeout != null) { - builder.connectTimeout(connectTimeout.timeout, connectTimeout.timeUnit); - } - if (readTimeout != null) { - builder.readTimeout(readTimeout.timeout, readTimeout.timeUnit); - } - if (writeTimeout != null) { - builder.writeTimeout(writeTimeout.timeout, writeTimeout.timeUnit); - } - if (certificateHolder != null) { - SSLContexts.SSLConfig sslConfig = SSLContexts.tryParse(certificateHolder.certificates, - certificateHolder.trustManager, certificateHolder.pfxStream, certificateHolder.pfxPwd); - builder.sslSocketFactory(sslConfig.getSslSocketFactory(), sslConfig.getX509TrustManager()); - } - return builder.build().newCall(request); - } - - void collectHeader(Request.Builder builder, HttpUrl httpUrl) { - //加载默认Header - Map defaultHeaders = HttpClient.Instance.getDefaultHeaders(httpUrl); - if (CollectionUtils.isNotEmpty(defaultHeaders)) { - for (Map.Entry entry : defaultHeaders.entrySet()) { - builder.header(entry.getKey(), entry.getValue()); - } - } - if (CollectionUtils.isNotEmpty(headers)) { - for (Map.Entry entry : headers.entrySet()) { - builder.header(entry.getKey(), entry.getValue()); - } - } - } - - /** - * 构建URL地址 - */ - String buildUrl() { - Assert.hasLength(url, "Url must not be null."); - StringBuilder sb = new StringBuilder(url); - if (url.contains("?")) { - sb.append("&"); - } else { - sb.append("?"); - } - if (CollectionUtils.isNotEmpty(queryParams)) { - for (Map.Entry> entry : queryParams.entrySet()) { - for (String value : entry.getValue()) { - sb.append(entry.getKey()).append("=") - .append(Utils.urlEncode(value)).append("&"); - } - } - } - sb.deleteCharAt(sb.length() - 1); - return sb.toString(); - } - - final class CertificateHolder { - - InputStream[] certificates; - X509TrustManager trustManager; - InputStream pfxStream; - char[] pfxPwd; - - CertificateHolder(InputStream[] certificates, X509TrustManager trustManager, - InputStream pfxStream, char[] pfxPwd) { - this.certificates = certificates; - this.trustManager = trustManager; - this.pfxStream = pfxStream; - this.pfxPwd = pfxPwd; - } - } - - final class TimeoutHolder { - int timeout; - TimeUnit timeUnit; - - TimeoutHolder(int timeout, TimeUnit timeUnit) { - this.timeout = timeout; - this.timeUnit = timeUnit; - } - } -} diff --git a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/request/BaseBodyHttpRequest.java b/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/request/BaseBodyHttpRequest.java deleted file mode 100644 index bdfbbcad41..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/request/BaseBodyHttpRequest.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2016-2017 mzlion(mzllon@qq.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mzlion.easyokhttp.request; - -import okhttp3.HttpUrl; -import okhttp3.Request; -import okhttp3.RequestBody; - -/** - * POST请求基类 - * - * @author mzlion on 2016/12/9. - */ -abstract class BaseBodyHttpRequest> extends AbsHttpRequest { - - BaseBodyHttpRequest(String url) { - super(url); - } - - /** - * 根据不同的请求方式,将RequestBody转换成Request对象 - * - * @param requestBody 请求体 - * @return {@link Request} - * @see RequestBody - */ - @Override - protected Request generateRequest(RequestBody requestBody) { - Request.Builder builder = new Request.Builder(); - HttpUrl httpUrl = HttpUrl.parse(this.buildUrl()); - builder.url(httpUrl); - this.collectHeader(builder, httpUrl); - builder.post(requestBody); - return builder.build(); - } -} diff --git a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/request/BinaryBodyPostRequest.java b/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/request/BinaryBodyPostRequest.java deleted file mode 100644 index a870f902f9..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/request/BinaryBodyPostRequest.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (C) 2016-2017 mzlion(mzllon@qq.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mzlion.easyokhttp.request; - -import com.mzlion.core.http.ContentType; -import com.mzlion.core.io.IOUtils; -import com.mzlion.core.lang.Assert; -import com.mzlion.easyokhttp.utils.Utils; -import okhttp3.MediaType; -import okhttp3.RequestBody; - -import java.io.*; - -/** - *

- * 2016-05-15 22:33 POST提交二进制流,服务端应该从Request请求体获取二进制流。 - *

- * - * @author mzlion - */ -public class BinaryBodyPostRequest extends BaseBodyHttpRequest { - - /** - * 二进制流内容 - */ - private byte[] content; - private MediaType mediaType; - - /** - * 默认构造器 - * - * @param url 请求地址 - */ - public BinaryBodyPostRequest(String url) { - super(url); - } - - - /** - * 设置二进制流 - * - * @param inputStream 二进制流 - * @return {@link BinaryBodyPostRequest} - * @see MediaType - */ - public BinaryBodyPostRequest stream(InputStream inputStream) { - Assert.notNull(inputStream, "In must not be null."); - Assert.notNull(mediaType, "MediaType must not be null."); - try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { - if (IOUtils.copy(inputStream, outputStream) == -1) { - throw new IOException("Copy failed"); - } - this.content = outputStream.toByteArray(); - } catch (IOException e) { - throw new RuntimeException("Reading stream failed->", e); - } finally { - IOUtils.closeQuietly(inputStream); - } - return this; - } - - /** - * 设置文件,转为文件流 - * - * @param file 文件对象 - * @return {@link BinaryBodyPostRequest} - */ - public BinaryBodyPostRequest file(File file) { - Assert.notNull(file, "File must not be null."); - String filename = file.getName(); - MediaType mediaType = Utils.guessMediaType(filename); - try { - this.stream(new FileInputStream(file)); - this.mediaType = mediaType; - return this; - } catch (FileNotFoundException e) { - throw new RuntimeException(e); - } - } - - /** - * 设置请求内容类型 - * - * @param contentType 请求内容类型 - * @return {@link BinaryBodyPostRequest} - */ - public BinaryBodyPostRequest contentType(String contentType) { - Assert.hasLength(contentType, "ContentType must not be null."); - this.mediaType = MediaType.parse(contentType); - return this; - } - - /** - * 设置请求内容类型 - * - * @param contentType 请求内容类型 - * @return {@link BinaryBodyPostRequest} - */ - public BinaryBodyPostRequest contentType(ContentType contentType) { - Assert.notNull(contentType, "ContentType must not be null."); - this.mediaType = MediaType.parse(contentType.toString()); - return this; - } - - /** - * 获取{@linkplain RequestBody}对象 - */ - @Override - protected RequestBody generateRequestBody() { - return RequestBody.create(this.mediaType, this.content); - } - -} diff --git a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/request/GetRequest.java b/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/request/GetRequest.java deleted file mode 100644 index f1094ce201..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/request/GetRequest.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2016-2017 mzlion(mzllon@qq.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mzlion.easyokhttp.request; - -import okhttp3.HttpUrl; -import okhttp3.Request; -import okhttp3.RequestBody; - -/** - *

- * 2016-04-16 HTTP的GET请求对象 - *

- * - * @author mzlion - */ -public class GetRequest extends AbsHttpRequest { - - /** - * 构造GET请求对象 - * - * @param url 请求的URL地址 - */ - public GetRequest(String url) { - super(url); - } - - /** - * 获取{@linkplain RequestBody}对象 - */ - @Override - protected RequestBody generateRequestBody() { - return null; - } - - /** - * 根据不同的请求方式,将RequestBody转换成Request对象 - * - * @param requestBody 请求体 - * @return {@link Request} - * @see RequestBody - */ - @Override - protected Request generateRequest(RequestBody requestBody) { - Request.Builder builder = new Request.Builder(); - HttpUrl httpUrl = HttpUrl.parse(this.buildUrl()); - builder.url(httpUrl); - this.collectHeader(builder, httpUrl); - return builder.build(); - } - -} diff --git a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/request/HttpRequest.java b/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/request/HttpRequest.java deleted file mode 100644 index 1dc725b869..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/request/HttpRequest.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Copyright (C) 2016-2017 mzlion(mzllon@qq.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mzlion.easyokhttp.request; - -import com.mzlion.easyokhttp.response.HttpResponse; -import com.mzlion.easyokhttp.response.callback.Callback; - -import javax.net.ssl.X509TrustManager; -import java.io.InputStream; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -/** - *

- * 2016-04-16 构建HTTP的请求对象,接口中的大部分方法均返回接口本身便于链式写法. - *

- * - * @author mzlion - */ -public interface HttpRequest> { - - /** - * 设置请求地址 - * - * @param url 请求地址 - * @return 返回当前类{@linkplain Req}的对象自己 - */ - Req url(String url); - - /** - * 为url地址设置请求参数,即url?username=admin pwd=123 - * - * @param name 参数名 - * @param value 参数值 - * @return 返回当前类{@linkplain Req}的对象自己 - */ - Req queryString(String name, Number value); - - /** - * 为url地址设置请求参数,即url?username=admin pwd=123 - * - * @param name 参数名 - * @param value 参数值 - * @return 返回当前类{@linkplain Req}的对象自己 - */ - Req queryString(String name, String value); - - /** - * 为url地址设置请求参数,即url?username=admin pwd=123 - * - * @param name 参数名 - * @param value 参数值 - * @param replace 值为[@code true}则替换 - * @return 返回当前类{@linkplain Req}的对象自己 - */ - Req queryString(String name, String value, boolean replace); - - /** - * 为url地址设置请求参数,即url?username=admin pwd=123 - * - * @param parameters 参数对 - * @return 返回当前类{@linkplain Req}的对象自己 - */ - Req queryString(Map parameters); - - /** - * 添加请求头信息 - * - * @param key 请求头键名 - * @param value 请求头值 - * @return 返回当前类{@linkplain Req}的对象自己 - */ - Req header(String key, String value); - - /** - * 从请求头中移除键值 - * - * @param key 请求头键名 - * @return 返回当前类{@linkplain Req}的对象自己 - */ - Req removeHeader(String key); - - /** - * 为构建本次{@linkplain HttpRequest}设置单独连接超时时间。调用此方法会重新创建{@linkplain okhttp3.OkHttpClient}。 - * - * @param connectTimeout 连接超时时间 - * @param timeUnit 超时时间单位 - * @return 返回当前类{@linkplain Req}的对象自己 - */ - Req connectTimeout(int connectTimeout, TimeUnit timeUnit); - - /** - * 为构建本次{@linkplain HttpRequest}设置单独连接超时时间。调用此方法会重新创建{@linkplain okhttp3.OkHttpClient}。 - * - * @param connectTimeout 连接超时时间,单位秒 - * @return 返回当前类{@linkplain Req}的对象自己 - */ - Req connectTimeout(int connectTimeout); - - /** - * 为构建本次{@linkplain HttpRequest}设置单独读取流超时。 - * - * @param readTimeout 流读取超时时间 - * @param timeUnit 超时时间单位 - * @return 返回当前类{@linkplain Req}的对象自己 - */ - Req readTimeout(int readTimeout, TimeUnit timeUnit); - - /** - * 为构建本次{@linkplain HttpRequest}设置单独读取流超时。 - * - * @param readTimeout 流读取超时时间,单位秒 - * @return 返回当前类{@linkplain Req}的对象自己 - */ - Req readTimeout(int readTimeout); - - /** - * 为构建本次{@linkplain HttpRequest}设置单独写入流超时。 - * - * @param writeTimeout 流写入超时时间 - * @param timeUnit 超时时间单位 - * @return 返回当前类{@linkplain Req}的对象自己 - */ - Req writeTimeout(int writeTimeout, TimeUnit timeUnit); - - /** - * 为构建本次{@linkplain HttpRequest}设置单独写入流超时。 - * - * @param writeTimeout 流写入超时时间,单位秒 - * @return 返回当前类{@linkplain Req}的对象自己 - */ - Req writeTimeout(int writeTimeout); - - /** - * 为构建本次{@linkplain HttpRequest}设置SSL单向认证 - * - * @param certificates SSL证书文件 - * @return 返回当前类{@linkplain Req}的对象自己 - */ - Req customSSL(InputStream... certificates); - - /** - * 为构建本次{@linkplain HttpRequest}设置SSL单向认证 - * - * @param trustManager 证书管理器 - * @return 返回当前类{@linkplain Req}的对象自己 - */ - Req customSSL(X509TrustManager trustManager); - - /** - * SSL双向认证 - * - * @param pfxStream 客户端证书,支持P12的证书 - * @param pfxPwd 客户端证书密码 - * @param certificates 含有服务端公钥的证书 - * @return {@link Req} - */ - Req customSSL(InputStream pfxStream, char[] pfxPwd, InputStream... certificates); - - /** - * SSL双向认证 - * - * @param pfxStream 客户端证书,支持P12的证书 - * @param pfxPwd 客户端证书密码 - * @param trustManager 证书管理器 - * @return {@link Req} - */ - Req customSSL(InputStream pfxStream, char[] pfxPwd, X509TrustManager trustManager); - - /** - * 执行HTTP请求,获取响应结果 - * - * @return 将响应结果转为具体的JavaBean - */ - HttpResponse execute(); - - /** - * 异步执行HTTP请求, - * - * @param callback 回调接口 - * @param 数据类型 - */ - void execute(Callback callback); - -} diff --git a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/request/PostRequest.java b/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/request/PostRequest.java deleted file mode 100644 index 156d8757d3..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/request/PostRequest.java +++ /dev/null @@ -1,240 +0,0 @@ -/* - * Copyright (C) 2016-2017 mzlion(mzllon@qq.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mzlion.easyokhttp.request; - -import com.mzlion.core.lang.CollectionUtils; -import com.mzlion.core.lang.StringUtils; -import com.mzlion.easyokhttp.http.FileWrapper; -import okhttp3.FormBody; -import okhttp3.MultipartBody; -import okhttp3.RequestBody; - -import java.io.File; -import java.io.InputStream; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -/** - * 实现表单提交 - * - * @author mzlion on 2016/12/8. - */ -public class PostRequest extends BaseBodyHttpRequest { - - private boolean isMultipart; - - private Map> formParams; - private Map> fileParams; - - public PostRequest(String url) { - super(url); - this.formParams = new LinkedHashMap<>(); - this.fileParams = new LinkedHashMap<>(); - } - - /** - * 获取{@linkplain RequestBody}对象 - * - * @return {@linkplain RequestBody} - */ - @Override - protected RequestBody generateRequestBody() { - if (CollectionUtils.isEmpty(this.fileParams) && !this.isMultipart) { - FormBody.Builder builder = new FormBody.Builder(); - if (CollectionUtils.isNotEmpty(this.formParams)) { - for (Map.Entry> entry : this.formParams.entrySet()) { -// if (CollectionUtils.isEmpty()) - for (String value : entry.getValue()) { - builder.add(entry.getKey(), value); - } - } - } - return builder.build(); - } - - MultipartBody.Builder builder = new MultipartBody.Builder(); - builder.setType(MultipartBody.FORM); - if (CollectionUtils.isNotEmpty(this.formParams)) { - for (Map.Entry> entry : this.formParams.entrySet()) { - for (String value : entry.getValue()) { - builder.addFormDataPart(entry.getKey(), value); - } - } - } - if (CollectionUtils.isNotEmpty(this.fileParams)) { - for (Map.Entry> entry : this.fileParams.entrySet()) { - for (FileWrapper fileWrapper : entry.getValue()) { - builder.addFormDataPart(entry.getKey(), fileWrapper.getFilename(), fileWrapper.requestBody()); - } - } - } - return builder.build(); - } - - /** - * 是否强制开启文件上传(multipart/form-data),如果框架检测到有文件上传则该方法设置无效 - * - * @param isMultipart 如果值为{@code true}则开启,否则关闭 - * @return {@link RequestBody} - */ - public PostRequest isMultipart(boolean isMultipart) { - this.isMultipart = isMultipart; - return this; - } - - - /** - * 设置提交的请求参数及其值 - * - * @param name 参数名 - * @param value 参数值 - * @return {@linkplain PostRequest} - */ - public PostRequest param(String name, String value) { - return this.param(name, value, false); - } - - /** - * 设置提交的请求参数及其值 - * - * @param name 参数名 - * @param value 参数值 - * @param replace 值为[@code true}则替换处理 - * @return {@linkplain PostRequest} - */ - public PostRequest param(String name, String value, boolean replace) { - //Assert.hasLength(name, "Name may not be null or empty."); - if (StringUtils.isEmpty(name)) { - logger.debug(" ===> The parameter[name] is null or empty."); - return this; - } - if (!replace && value == null) { - logger.warn(" ===> The value is null,ignore:name={},value=null", name); - return this; - } - List valueList = this.formParams.get(name); - if (valueList == null) { - valueList = new LinkedList<>(); - this.formParams.put(name, valueList); - } - if (replace) { - valueList.clear(); - } - - valueList.add(value); - return this; - } - - /** - * 设置提交的请求参数及其值 - * - * @param parameters 键值对列表 - * @return {@linkplain PostRequest} - */ - public PostRequest param(Map parameters) { - //Assert.notEmpty(parameters, "Parameters may not be null."); - if (CollectionUtils.isEmpty(parameters)) { - logger.debug(" ===> The parameter[parameters] is null or empty."); - return this; - } - for (Map.Entry entry : parameters.entrySet()) { - this.param(entry.getKey(), entry.getValue(), false); - } - return this; - } - - /** - * 设置提交的文件 - * - * @param name 参数名 - * @param uploadFile 上传的文件 - * @return {@linkplain PostRequest} - */ - public PostRequest param(String name, File uploadFile) { - return this.param(name, uploadFile, uploadFile.getName()); - } - - /** - * 设置提交的文件 - * - * @param name 参数名 - * @param uploadFile 上传的文件 - * @param filename 文件名 - * @return {@linkplain PostRequest} - */ - public PostRequest param(String name, File uploadFile, String filename) { - //Assert.hasLength(name, "Name may not be null."); - //Assert.notNull(uploadFile, "UploadFile may not be null."); - //Assert.hasLength(filename, "Filename may not be null or empty."); - - if (StringUtils.isEmpty(name)) { - logger.debug(" ===> The parameter[name] is null or empty."); - return this; - } - if (uploadFile == null) { - logger.warn(" ===> The parameter[uploadFile] is null,ignore:name={}.", name); - return this; - } - if (StringUtils.isEmpty(filename)) { - logger.warn(" ===> The parameter[filename] is null,ignore:name={},uploadFile={}.", name, uploadFile); - return this; - } - List fileWrapperList = this.fileParams.get(name); - if (fileWrapperList == null) { - fileWrapperList = new LinkedList<>(); - this.fileParams.put(name, fileWrapperList); - } - fileWrapperList.add(FileWrapper.create().file(uploadFile).filename(filename).build()); - return this; - } - - /** - * 设置提交的文件 - * - * @param name 参数名 - * @param inputStream 上传数据流 - * @param streamName 数据流的标识 - * @return {@linkplain PostRequest} - */ - public PostRequest param(String name, InputStream inputStream, String streamName) { - //Assert.hasLength(name, "Name may not be null."); - //Assert.notNull(inputStream, "InputStream may not be null."); - //Assert.hasLength(streamName, "StreamName may not be null."); - if (StringUtils.isEmpty(name)) { - logger.debug(" ===> The parameter[name] is null or empty."); - return this; - } - if (inputStream == null) { - logger.warn(" ===> The parameter[inputStream] is null,ignore:name={}.", name); - return this; - } - if (StringUtils.isEmpty(streamName)) { - logger.warn(" ===> The parameter[streamName] is null,ignore:name={},inputStream={}.", name, inputStream); - return this; - } - - List fileWrapperList = this.fileParams.get(name); - if (fileWrapperList == null) { - fileWrapperList = new LinkedList<>(); - this.fileParams.put(name, fileWrapperList); - } - fileWrapperList.add(FileWrapper.create().stream(inputStream).filename(streamName).build()); - return this; - } - -} diff --git a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/request/TextBodyRequest.java b/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/request/TextBodyRequest.java deleted file mode 100644 index 2d1628453c..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/request/TextBodyRequest.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright (C) 2016-2017 mzlion(mzllon@qq.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mzlion.easyokhttp.request; - -import com.mzlion.core.json.gson.JsonUtil; -import com.mzlion.core.lang.Assert; -import okhttp3.MediaType; -import okhttp3.RequestBody; - -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; - -/** - *

- * 提交文本字符串,服务端应该从Request请求体获取文本字符串。 - *

- * - * @author mzlion - */ -public class TextBodyRequest extends BaseBodyHttpRequest { - - private String content; - private String _type; - private Charset charset; - - /** - * 默认构造器 - * - * @param url 请求地址 - */ - public TextBodyRequest(String url) { - super(url); - this.charset = StandardCharsets.UTF_8; - } - - /** - * POST提交一段j文本内容 - * - * @param text 文本字符串 - * @return {@link TextBodyRequest} - */ - public TextBodyRequest text(String text) { - this.content = text == null ? "" : text; - this._type = "text/plain"; - return this; - } - - /** - * POST提交一段json字符串 - * - * @param json json字符串 - * @return {@link TextBodyRequest} - */ - public TextBodyRequest json(String json) { - Assert.hasLength(json, "Json may not be null."); - this.content = json; - this._type = "application/json"; - return this; - } - - /** - * POST提交一段json字符串 - * - * @param value Java对象 - * @return {@link TextBodyRequest} - */ - public TextBodyRequest json(Object value) { - Assert.notNull(value, "Value may not be null."); - this.content = JsonUtil.toJson(value); - this._type = "application/json"; - return this; - } - - /** - * POST提交一段xml代码 - * - * @param xml xml字符串 - * @return {@link TextBodyRequest} - */ - public TextBodyRequest xml(String xml) { - Assert.hasLength(xml, "Xml may not be null."); - this.content = xml; - this._type = "application/xml"; - return this; - } - - /** - * POST提交一段html代码 - * - * @param html html字符串 - * @return {@link TextBodyRequest} - */ - public TextBodyRequest html(String html) { - Assert.hasLength(html, "Html may not be null."); - this.content = html; - this._type = "application/html"; - return this; - } - - /** - * POST提交一段javascript代码 - * - * @param javascript 字符串 - * @return {@link TextBodyRequest} - */ - public TextBodyRequest javascript(String javascript) { - Assert.hasLength(javascript, "Javascript may not be null."); - this.content = javascript; - this._type = "application/javascript"; - return this; - } - - /** - * 设置字符集 - * - * @param charset 字符编码 - * @return {@link TextBodyRequest} - */ - public TextBodyRequest charset(String charset) { - Assert.hasLength(charset, "Charset may not be null."); - this.charset = Charset.forName(charset); - return this; - } - - /** - * 获取{@linkplain RequestBody}对象 - */ - @Override - protected RequestBody generateRequestBody() { - MediaType contentType = MediaType.parse(String.format("%s; charset=%s", this._type, this.charset)); - return RequestBody.create(contentType, this.content); - } - -} diff --git a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/response/HttpResponse.java b/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/response/HttpResponse.java deleted file mode 100644 index 403e8fb720..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/response/HttpResponse.java +++ /dev/null @@ -1,236 +0,0 @@ -/* - * Copyright (C) 2016-2017 mzlion(mzllon@qq.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mzlion.easyokhttp.response; - -import com.mzlion.core.io.IOUtils; -import com.mzlion.core.json.TypeRef; -import com.mzlion.core.lang.Assert; -import com.mzlion.easyokhttp.exception.HttpClientException; -import com.mzlion.easyokhttp.exception.HttpStatusCodeException; -import com.mzlion.easyokhttp.response.handle.DataHandler; -import com.mzlion.easyokhttp.response.handle.FileDataHandler; -import com.mzlion.easyokhttp.response.handle.JsonDataHandler; -import com.mzlion.easyokhttp.response.handle.StringDataHandler; -import okhttp3.Response; -import okhttp3.ResponseBody; - -import java.io.File; -import java.io.IOException; -import java.io.OutputStream; -import java.io.Serializable; - -/** - *

- * Http响应结果处理类,通过{@linkplain #isSuccess()}可以得知服务器是否是200返回。 - * 并且该类提供了将结果转为其它对象的便捷方法,该类不再支持重复调用,重复会跑出异常。 - *

- * 当响应结果状态码不是200时,而强制调用某个数据转换方法则会跑出异常{@linkplain HttpStatusCodeException}, - * 如果项目需要判断Http Status Code来做一些特殊处理,可以捕获这个异常实现自己的逻辑。 - * - * @author mzlion on 2016/4/17 - * @see DataHandler - * @see HttpStatusCodeException - */ -public class HttpResponse implements Serializable { - - private transient final Response rawResponse; - - /** - * 请求是否成功 - */ - private boolean isSuccess; - - /** - * 请求失败时错误消息 - */ - private String errorMessage; - - /** - * HTTP Status Code - */ - private int httpCode; - - private byte[] byteData;//cache data - - public HttpResponse(Response rawResponse) { - this.rawResponse = rawResponse; - try { - this.byteData = this.rawResponse.body().bytes(); - } catch (IOException e) { - throw new HttpClientException(e); - } finally { - IOUtils.closeQuietly(this.rawResponse); - } - } - - /** - * 判断请求是否成功 - * - * @return 成功则[@code true}否则为{@code false} - */ - public boolean isSuccess() { - return isSuccess; - } - - public void setSuccess(boolean success) { - isSuccess = success; - } - - /** - * 请求失败时错误消息 - * - * @return 失败消息 - */ - public String getErrorMessage() { - return errorMessage; - } - - public void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } - - /** - * 请求失败时的HTTP Status Code - * - * @return Http错误码 - */ - public int getHttpCode() { - return httpCode; - } - - public void setHttpCode(int httpCode) { - this.httpCode = httpCode; - } - - public Response getRawResponse() { - if (rawResponse == null) { - return rawResponse; - } - return rawResponse.newBuilder().body(ResponseBody.create(rawResponse.body().contentType(), byteData)).build(); - } - - /** - * 将响应结果转为字符串 - * - * @return 响应结果字符串 - * @throws HttpClientException 如果服务器返回非200则抛出此异常 - */ - public String asString() { - return this.custom(StringDataHandler.create()); - } - - /** - * 将响应结果转为JavaBean对象 - * - * @param targetClass 目标类型 - * @param 泛型类型 - * @return JavaBean对象 - * @throws HttpClientException 如果服务器返回非200则抛出此异常 - */ - public E asBean(Class targetClass) { - return this.custom(new JsonDataHandler<>(targetClass)); - } - - /** - * 将响应结果转为JavaBean对象 - *

- * 用法如下:Map<String,String> data = httpResponse.asBean(new TypeRef<Map<String,String>>); - *

- * - * @param typeRef 带有泛型类的封装类 - * @param 泛型类型 - * @return JavaBean对象 - * @throws HttpClientException 如果服务器返回非200则抛出此异常 - */ - public E asBean(TypeRef typeRef) { - return this.custom(new JsonDataHandler<>(typeRef)); - } - - /** - * 将响应结果转为字节数组 - * - * @return 字节数组 - * @throws HttpClientException 如果服务器返回非200则抛出此异常 - */ - public byte[] asByteData() { - this.assertSuccess(); - return byteData; - } - - /** - * 将响应结果输出到文件中 - * - * @param saveFile 目标保存文件,非空 - */ - public void asFile(File saveFile) { - Assert.notNull(saveFile, "SaveFile may noy be null."); - this.custom(new FileDataHandler(saveFile.getParent(), saveFile.getName())); - } - - /** - * 将响应结果输出到输出流,并不会主动关闭输出流{@code out} - * - * @param out 输出流,非空 - */ - public void asStream(OutputStream out) { - Assert.notNull(out, "OutputStream is null."); - this.assertSuccess(); - try { - IOUtils.copy(this.rawResponse.body().byteStream(), out); - } finally { - IOUtils.closeQuietly(this.rawResponse); - } - } - - /** - * 响应结果转换 - * - * @param dataHandler 数据转换接口 - * @param 期望转换的类型 - * @return 抓好结果 - */ - public T custom(DataHandler dataHandler) { - return custom(dataHandler, true); - } - - /** - * 响应结果转换 - * - * @param dataHandler 数据转换接口 - * @param 期望转换的类型 - * @param checkHttpCode 是否检查状态码 - * @return 抓好结果 - */ - public T custom(DataHandler dataHandler, boolean checkHttpCode) { - if (checkHttpCode) { - this.assertSuccess(); - } - try { - return dataHandler.handle(getRawResponse()); - } catch (IOException e) { - throw new HttpClientException(e); - } finally { - IOUtils.closeQuietly(this.rawResponse); - } - } - - private void assertSuccess() { - if (!this.isSuccess) { - throw new HttpStatusCodeException(this.rawResponse.request().url().toString(), - this.httpCode, this.errorMessage); - } - } -} diff --git a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/response/callback/Callback.java b/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/response/callback/Callback.java deleted file mode 100644 index 9030d62b14..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/response/callback/Callback.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2016-2017 mzlion(mzllon@qq.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mzlion.easyokhttp.response.callback; - -import com.mzlion.easyokhttp.request.AbsHttpRequest; -import com.mzlion.easyokhttp.response.handle.DataHandler; -import okhttp3.Call; -import okhttp3.Response; - -/** - * 异步请求的回调接口 - * - * @author mzlion on 2016/4/17. - */ -public interface Callback { - - /** - * 在请求前调用,在这里可以设置一些参数 - * - * @param httpRequest 请求对象 - * @return 返回{@code false}则取消此次请求 - */ - boolean onBefore(AbsHttpRequest httpRequest); - - /** - * 上传请求调用 - * - * @param currentSize 当前上传的大小 - * @param totalSize 总的大小 - * @param progress 完成进度 - */ - void postProgress(final long currentSize, final long totalSize, final float progress); - - /** - * 请求失败调用 - * - * @param call The real call - * @param exception Exception - */ - void onError(Call call, Exception exception); - - /** - * 请求完成调用 - * - * @param response 原始的Response,方便调用者自行处理 - */ - void onComplete(Response response); - - /** - * 获取数据处理器,用于解析转换响应结果 - * - * @return {@linkplain DataHandler} - */ - DataHandler getDataHandler(); - - /** - * 根据数据处理器得到处理结果,调用者直接使用处理后的数据 - * 如果{@linkplain #getDataHandler()}返回{@code null}则{@code data}也为{@code null} - * - * @param data 响应经过处理的数据 - * @see #getDataHandler() - */ - void onSuccess(T data); - - /** - * 空实现 - */ - Callback EMPTY_CALLBACK = new CallbackAdaptor<>(); - -} diff --git a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/response/callback/CallbackAdaptor.java b/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/response/callback/CallbackAdaptor.java deleted file mode 100644 index 9d6816082b..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/response/callback/CallbackAdaptor.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (C) 2016-2017 mzlion(mzllon@qq.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mzlion.easyokhttp.response.callback; - -import com.mzlion.easyokhttp.request.AbsHttpRequest; -import com.mzlion.easyokhttp.response.handle.DataHandler; -import okhttp3.Call; -import okhttp3.Response; - -/** - * {@linkplain Callback}的默认实现 - * - * @author mzlion on 2016/12/14. - */ -public class CallbackAdaptor implements Callback { - - /** - * 在请求前调用,在这里可以设置一些参数 - * - * @param httpRequest 请求对象 - * @return 返回{@code false}则取消此次请求 - */ - @Override - public boolean onBefore(AbsHttpRequest httpRequest) { - return true; - } - - /** - * 上传请求调用 - * - * @param currentSize 当前上传的大小 - * @param totalSize 总的大小 - * @param progress 完成进度 - */ - @Override - public void postProgress(final long currentSize, final long totalSize, final float progress) { - - } - - /** - * 请求失败调用 - * - * @param call The real call - * @param exception Exception - */ - @Override - public void onError(Call call, Exception exception) { - - } - - /** - * 请求完成调用 - * - * @param response 原始的Response,方便调用者自行处理 - */ - @Override - public void onComplete(Response response) { - - } - - /** - * 获取数据处理器,用于解析转换响应结果 - * - * @return {@linkplain DataHandler} - */ - @Override - public DataHandler getDataHandler() { - return null; - } - - /** - * 根据数据处理器得到处理结果,调用者直接使用处理后的数据 - * 如果{@linkplain #getDataHandler()}返回{@code null}则{@code data}也为{@code null} - * - * @param data 响应经过处理的数据 - * @see #getDataHandler() - */ - @Override - public void onSuccess(T data) { - - } -} diff --git a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/response/handle/DataHandler.java b/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/response/handle/DataHandler.java deleted file mode 100644 index 74c9f0d7bd..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/response/handle/DataHandler.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2016-2017 mzlion(mzllon@qq.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mzlion.easyokhttp.response.handle; - -import java.io.IOException; - -/** - * 数据处理定义接口,将得到的响应结果转为所需的数据 - * - * @author mzlion on 2016/12/14. - * @see JsonDataHandler - * @see StringDataHandler - */ -public interface DataHandler { - - /** - * 得到相应结果后,将相应数据转为需要的数据格式 - * - * @param response 需要转换的对象 - * @return 转换结果 - * @throws IOException 出现异常 - */ - T handle(final okhttp3.Response response) throws IOException; - -} diff --git a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/response/handle/FileDataHandler.java b/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/response/handle/FileDataHandler.java deleted file mode 100644 index 6e2e72967d..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/response/handle/FileDataHandler.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (C) 2016-2017 mzlion(mzllon@qq.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mzlion.easyokhttp.response.handle; - -import com.mzlion.core.io.FileUtils; -import com.mzlion.core.lang.Assert; -import com.mzlion.core.lang.StringUtils; -import com.mzlion.easyokhttp.utils.Utils; -import okhttp3.Response; - -import java.io.File; -import java.io.IOException; - -/** - * 文件处理器,一般用于从远程下载资源(如图片、报表等) - * 支持自动获取文件名,也支持自定义文件名 - * - * @author mzlion on 2016/12/14. - */ -public class FileDataHandler implements DataHandler { - - /** - * 保存的文件目录 - */ - private final String dirPath; - - /** - * 保存的文件名 - */ - private String filename; - - public FileDataHandler(String dirPath) { - Assert.notNull(dirPath, "DirPath may not be null."); - this.dirPath = dirPath; - } - - public FileDataHandler(String dirPath, String filename) { - this(dirPath); - this.filename = filename; - } - - /** - * 返回保存的文件目录 - * - * @return 保存的文件目录 - */ - public String getDirPath() { - return dirPath; - } - - /** - * 返回保存的文件名 - * - * @return 保存的文件名 - */ - public String getFilename() { - return filename; - } - - /** - * 设置保存的文件名 - * - * @param filename 保存的文件名 - */ - public void setFilename(String filename) { - this.filename = filename; - } - - /** - * 得到相应结果后,将相应数据转为需要的数据格式 - * - * @param response 需要转换的对象 - * @return 存储的文件信息 - * @throws IOException 出现异常 - */ - @Override - public File handle(final Response response) throws IOException { - String name = this.filename; - if (StringUtils.isEmpty(name)) name = Utils.getFilename(response); - File saveFile = new File(this.dirPath, name); - FileUtils.copyStream(response.body().byteStream(), saveFile); - return saveFile; - } -} diff --git a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/response/handle/JsonDataHandler.java b/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/response/handle/JsonDataHandler.java deleted file mode 100644 index 9dfb70ed33..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/response/handle/JsonDataHandler.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (C) 2016-2017 mzlion(mzllon@qq.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mzlion.easyokhttp.response.handle; - -import com.mzlion.core.json.TypeRef; -import com.mzlion.core.json.gson.JsonUtil; -import com.mzlion.core.lang.StringUtils; -import okhttp3.Response; - -import java.io.IOException; - -/** - * JSON处理器,将得到的JSON字符串转为JavaBean.主要必须指定{@code delegateClass}和{@code typeRef}其中一个值,否则返回结果为{@code null} - * - * @param 泛型类型 - * @author mzlion on 2016/12/14. - */ -public class JsonDataHandler implements DataHandler { - - /** - * 指定类型 - */ - private Class delegateClass; - - /** - * 携带泛型信息的类型 - */ - private TypeRef typeRef; - - public JsonDataHandler() { - } - - public JsonDataHandler(Class delegateClass) { - this.delegateClass = delegateClass; - } - - public JsonDataHandler(TypeRef typeRef) { - this.typeRef = typeRef; - } - - public JsonDataHandler(Class delegateClass, TypeRef typeRef) { - this.delegateClass = delegateClass; - this.typeRef = typeRef; - } - - public Class getDelegateClass() { - return delegateClass; - } - - public void setDelegateClass(Class delegateClass) { - this.delegateClass = delegateClass; - } - - public TypeRef getTypeRef() { - return typeRef; - } - - public void setTypeRef(TypeRef typeRef) { - this.typeRef = typeRef; - } - - /** - * 得到相应结果后,将相应数据转为需要的数据格式 - * - * @param response 需要转换的对象 - * @return 转换结果 - * @throws IOException 出现异常 - */ - @Override - public T handle(final Response response) throws IOException { - StringDataHandler stringDataHandler = StringDataHandler.create(); - String valueContent = stringDataHandler.handle(response); - if (StringUtils.hasLength(valueContent)) { - if (null != this.delegateClass) { - return JsonUtil.fromJson(valueContent, delegateClass); - } else if (null != this.typeRef) { - return JsonUtil.fromJson(valueContent, this.typeRef); - } else { - return null; - } - } - return null; - } -} diff --git a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/response/handle/StringDataHandler.java b/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/response/handle/StringDataHandler.java deleted file mode 100644 index 5f2e792275..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/response/handle/StringDataHandler.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (C) 2016-2017 mzlion(mzllon@qq.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mzlion.easyokhttp.response.handle; - -import okhttp3.Response; - -import java.io.IOException; -import java.nio.charset.Charset; - -/** - * 字符串数据处理器 - * - * @author mzlion on 2016/12/14. - */ -public class StringDataHandler implements DataHandler { - - /** - * 返回字符串数据处理器 - * - * @return 字符串数据处理器 - */ - public static StringDataHandler create() { - return Holder.handler; - } - - /** - * 单例Holder - * - * @author mzlion - */ - private static class Holder { - /** - * 因为{@linkplain StringDataHandler}使用频率非常高,所以这里直接缓存 - */ - private static StringDataHandler handler = new StringDataHandler(); - } - - /** - * 字符编码 - */ - private Charset charset; - - /** - * 获取字符编码 - * - * @return 字符编码 - */ - public Charset getCharset() { - return charset; - } - - /** - * 设置字符编码 - * - * @param charset 字符编码 - */ - public void setCharset(Charset charset) { - this.charset = charset; - } - - /** - * 得到相应结果后,将相应数据转为需要的数据格式 - * - * @param response 需要转换的对象 - * @return 转换结果 - */ - @Override - public String handle(Response response) throws IOException { - if (this.charset != null) { - return new String(response.body().bytes()); - } - return response.body().string(); - } -} diff --git a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/utils/SSLContexts.java b/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/utils/SSLContexts.java deleted file mode 100644 index 5bf351760a..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/utils/SSLContexts.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (C) 2016-2017 mzlion(mzllon@qq.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mzlion.easyokhttp.utils; - -import com.mzlion.core.io.IOUtils; -import com.mzlion.core.lang.ArrayUtils; - -import javax.net.ssl.*; -import java.io.InputStream; -import java.security.KeyStore; -import java.security.SecureRandom; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; - -/** - * SSL证书 - * - * @author mzlion on 2016/12/7. - */ -public class SSLContexts { - - /** - * 尝试解析SSL证书 - * - * @param certificates 远程服务端的证书 - * @param x509TrustManager 自定义证书管理器 - * @param pfxCertificate 客户端证书 - * @param pfxPassword 客户端证书密码 - * @return {@link SSLConfig} - */ - public static SSLConfig tryParse(InputStream[] certificates, X509TrustManager x509TrustManager, - InputStream pfxCertificate, char[] pfxPassword) { - try { - SSLConfig sslConfig = new SSLConfig(); - - KeyManager[] keyManagers = prepareKeyManagers(pfxCertificate, pfxPassword); - X509TrustManager trustManager; - if (x509TrustManager != null) { - //优先使用用户自定义的TrustManager - trustManager = x509TrustManager; - } else { - //然后使用默认的TrustManager - trustManager = prepareX509TrustManager(certificates); - if (trustManager == null) { - trustManager = unSafeTrustManager; - } - } - - //创建TLS类型的SSLContext对象. - SSLContext sslContext = SSLContext.getInstance("TLS"); - // 用上面得到的trustManagers初始化SSLContext,这样sslContext就会信任keyStore中的证书 - sslContext.init(keyManagers, new TrustManager[]{trustManager}, new SecureRandom()); - - sslConfig.setSslSocketFactory(sslContext.getSocketFactory()); - sslConfig.setX509TrustManager(trustManager); - return sslConfig; - } catch (Exception e) { - throw new AssertionError(e); - } - } - - /** - * 不对证书进行验证 - */ - private static X509TrustManager unSafeTrustManager = new X509TrustManager() { - @Override - public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { - - } - - @Override - public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { - - } - - @Override - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[0]; - } - }; - - /** - * 根据证书文件生成{@linkplain X509TrustManager} - * - * @param certificates 证书文件 - * @return {@link X509TrustManager} - */ - private static X509TrustManager prepareX509TrustManager(InputStream... certificates) throws Exception { - if (ArrayUtils.isEmpty(certificates)) { - return null; - } - - //创建证书工厂 - CertificateFactory factory = CertificateFactory.getInstance("X.509"); - //创建一个默认类型的KeyStore,存储我们信任的证书 - KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(null); - - //开始处理证书 - for (int i = 0, length = certificates.length; i < length; i++) { - //将证书对象作为可信证书放入到keyStore中 - keyStore.setCertificateEntry(String.valueOf(i + 1), factory.generateCertificate(certificates[i])); - IOUtils.closeQuietly(certificates[i]); - } - - // Use it to build an X509 trust manager. - TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - //用我们之前的keyStore实例初始化TrustManagerFactory,这样tmf就会信任keyStore中的证书 - trustManagerFactory.init(keyStore); - TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); - if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) { - throw new IllegalStateException("Unexpected default trust managers:" + ArrayUtils.toString(trustManagers)); - } - return (X509TrustManager) trustManagers[0]; - } - - private static KeyManager[] prepareKeyManagers(InputStream pfxCertificate, char[] pfxPassword) throws Exception { - if (pfxCertificate == null || ArrayUtils.isEmpty(pfxPassword)) { - return null; - } - KeyStore clientKS = KeyStore.getInstance("PKCS12"); - clientKS.load(pfxCertificate, pfxPassword); - KeyManagerFactory factory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); - factory.init(clientKS, pfxPassword); - return factory.getKeyManagers(); - } - - public static final class SSLConfig { - - private SSLSocketFactory sslSocketFactory; - private X509TrustManager x509TrustManager; - - public SSLSocketFactory getSslSocketFactory() { - return sslSocketFactory; - } - - void setSslSocketFactory(SSLSocketFactory sslSocketFactory) { - this.sslSocketFactory = sslSocketFactory; - } - - public X509TrustManager getX509TrustManager() { - return x509TrustManager; - } - - void setX509TrustManager(X509TrustManager x509TrustManager) { - this.x509TrustManager = x509TrustManager; - } - } -} diff --git a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/utils/Utils.java b/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/utils/Utils.java deleted file mode 100644 index 71ee5bcf6d..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/java/com/mzlion/easyokhttp/utils/Utils.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (C) 2016-2017 mzlion(mzllon@qq.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mzlion.easyokhttp.utils; - -import com.mzlion.core.digest.MD5; -import com.mzlion.core.lang.StringUtils; -import com.mzlion.easyokhttp.http.Header; -import okhttp3.MediaType; -import okhttp3.Response; - -import java.io.UnsupportedEncodingException; -import java.net.FileNameMap; -import java.net.URLConnection; -import java.net.URLEncoder; -import java.util.Locale; - -/** - * 项目的工具类 - * - * @author mzlion on 2016/12/9. - */ -public class Utils { - - private static String acceptLanguage; - private static String userAgent; - - /** - * 自定义客户端语言 - * - * @param acceptLanguage 客户端语言 - */ - public static void setAcceptLanguage(String acceptLanguage) { - Utils.acceptLanguage = acceptLanguage; - } - - /** - * 客户端语言 - * - * @return 客户端语言 - */ - public static String getAcceptLanguage() { - if (StringUtils.isEmpty(acceptLanguage)) { - Locale locale = Locale.getDefault(); - String language = locale.getLanguage(); - String country = locale.getCountry(); - StringBuffer sb = new StringBuffer(language); - if (StringUtils.hasLength(country)) { - sb.append('-').append(country).append(',').append(language).append(";q=0.8"); - } - acceptLanguage = sb.toString(); - } - return acceptLanguage; - } - - /** - * 获取UA - * - * @return UA - */ - public static String getUserAgent() { - if (StringUtils.isEmpty(userAgent)) { - userAgent = "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36"; - } - return userAgent; - } - - /** - * 对URL中的请求参数UTF-8编码 - * - * @param value 参数值 - * @return 编码的值 - */ - public static String urlEncode(String value) { - try { - return URLEncoder.encode(value, "UTF-8"); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - return value; - } - } - - /** - * 猜测文件的MIME类型 - * - * @param filename 文件名 - * @return {@link MediaType} - */ - public static MediaType guessMediaType(String filename) { - if (filename == null) { - return MediaType.parse("application/octet-stream"); - } - FileNameMap fileNameMap = URLConnection.getFileNameMap(); - String pathname = filename.replace("#", ""); - String contentType = fileNameMap.getContentTypeFor(pathname); - if (contentType == null) { - contentType = "application/octet-stream"; - } - return MediaType.parse(contentType); - } - - /** - * 根据响应头或url获取文件名,当都无法获取时则根据url生成MD5值 - * - * @param response HTTP响应对象 - * @return 文件名 - */ - public static String getFilename(Response response) { - //首先从请求头里获取 - String headerValue = response.header(Header.CONTENT_DISPOSITION); - if (headerValue != null) { - String split = "filename="; - int index = headerValue.indexOf(split); - if (index != -1) { - String pathname = headerValue.substring(index + split.length()); - index = pathname.lastIndexOf("/"); - if (index != -1) { - return pathname.substring(index + 1); - } - return pathname; - } - } - - //然后从url里获取 - String url = response.request().url().toString(); - int index = url.indexOf("?"); - if (index > 0) { - String urlSnippet = url.substring(0, index); - String filename = urlSnippet.substring(url.lastIndexOf("/") + 1); - if (filename.contains(".")) { - return filename; - } - } - - //通过URL生成一个随机文件名 - return MD5.digestHex(url); - } -} diff --git a/jun_java_plugins/jun_okhttp/src/main/resources/easy-okhttp.properties b/jun_java_plugins/jun_okhttp/src/main/resources/easy-okhttp.properties deleted file mode 100644 index 82211689ef..0000000000 --- a/jun_java_plugins/jun_okhttp/src/main/resources/easy-okhttp.properties +++ /dev/null @@ -1,29 +0,0 @@ -#/* -#* Copyright (C) 2016-2017 mzlion(mzllon@qq.com). -#* -#* Licensed under the Apache License, Version 2.0 (the "License"); -#* you may not use this file except in compliance with the License. -#* You may obtain a copy of the License at -#* -#* http://www.apache.org/licenses/LICENSE-2.0 -#* -#* Unless required by applicable law or agreed to in writing, software -#* distributed under the License is distributed on an "AS IS" BASIS, -#* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -#* See the License for the specific language governing permissions and -#* limitations under the License. -#*/ -#==========================\u652F\u6301\u516C\u5171Header\u548CParam\u7684\u8BBE\u7F6E==========================# -#\u89C4\u5219\u8BF4\u660E\u5982\u4E0B -#\u4EE5header\u5F00\u5934\u7684\u8868\u793A\u8BBE\u7F6E\u516C\u5171\u8BF7\u6C42\u5934,header.\u4E4B\u540E\u5C31\u662F\u952E\u540D,\u7B49\u53F7\u4E4B\u540E\u7684\u952E\u5BF9\u5E94\u7684\u503C -#header.partner = MZ2017 -#header.rememberMe = 1 -#==========================\u652F\u6301\u516C\u5171Header\u548CParam\u7684\u8BBE\u7F6E==========================# -#==========================\u5BF9OKHTTP\u5168\u5C40\u914D\u7F6E==========================# -#\u8FDE\u63A5\u8D85\u65F6\u65F6\u95F4,\u5355\u4F4D\u79D2 -connectTimeout=5 -#\u8BFB\u53D6\u8D85\u65F6\u65F6\u95F4,\u5355\u4F4D\u79D2 -readTimeout=5 -#\u5199\u5165\u8D85\u65F6\u65F6\u95F4,\u5355\u4F4D\u79D2 -writeTimeout=5 -#==========================\u5BF9OKHTTP\u5168\u5C40\u914D\u7F6E==========================# \ No newline at end of file diff --git a/jun_java_plugins/jun_okhttp/src/test/java/com/mzlion/easyokhttp/HttpClientTest.java b/jun_java_plugins/jun_okhttp/src/test/java/com/mzlion/easyokhttp/HttpClientTest.java deleted file mode 100644 index c14953487e..0000000000 --- a/jun_java_plugins/jun_okhttp/src/test/java/com/mzlion/easyokhttp/HttpClientTest.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.mzlion.easyokhttp; - -import com.mzlion.easyokhttp.response.HttpResponse; -import com.mzlion.easyokhttp.response.handle.StringDataHandler; -import org.junit.Test; - -/** - * @author kudo on 2017-10-31 13:52:57 - */ -public class HttpClientTest { - - @Test - public void post() throws Exception { -// HttpResponse httpResponse = HttpClient -// .post("https://project.mzlion.com/easy-okhttp/api/post/simple") -// .param("blog", "https://www.mzlion.com") -// .param("author", "mzlion") -// .param("location", "上海") -// .param("projectName", "easy-okhttp") -// .param("projectUrl", "https://git.oschina.net/mzllon/easy-okhttp") -// .header("customHeader1", "customValue1")//自定义header -// .execute(); - HttpResponse httpResponse = HttpClient.post("http://localhost:8060/c1-svc-server/lan/svc/yjlmk/hb_activity/test2") - .param("flag", "flag") - .execute(); - System.out.println("http code = " + httpResponse.getHttpCode()); - System.out.println("http message = " + httpResponse.getErrorMessage()); - - String asString = httpResponse.custom(StringDataHandler.create(), false); - System.out.println("asString = " + asString); - } - - @Test - public void post2() throws Exception { - HttpResponse httpResponse = HttpClient.post("http://localhost:8060/c1-svc-server/lan/svc/yjlmk/hb_activity/stop") - .param("flag", "flag") - .execute(); - System.out.println("http code = " + httpResponse.getHttpCode()); - System.out.println("http message = " + httpResponse.getErrorMessage()); - - String asString = httpResponse.custom(StringDataHandler.create(), false); - System.out.println("asString = " + asString); - - - } - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_online_java_complier/.gitignore b/jun_java_plugins/jun_online_java_complier/.gitignore deleted file mode 100644 index 2af7cefb0a..0000000000 --- a/jun_java_plugins/jun_online_java_complier/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -target/ -!.mvn/wrapper/maven-wrapper.jar - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -nbproject/private/ -build/ -nbbuild/ -dist/ -nbdist/ -.nb-gradle/ \ No newline at end of file diff --git a/jun_java_plugins/jun_online_java_complier/LICENSE b/jun_java_plugins/jun_online_java_complier/LICENSE deleted file mode 100644 index c6efeed960..0000000000 --- a/jun_java_plugins/jun_online_java_complier/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2017 ping - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/jun_java_plugins/jun_online_java_complier/README.en.md b/jun_java_plugins/jun_online_java_complier/README.en.md deleted file mode 100644 index fd316d99e8..0000000000 --- a/jun_java_plugins/jun_online_java_complier/README.en.md +++ /dev/null @@ -1,36 +0,0 @@ -# OnlineJavaComile - -#### Description -java 在线编译 - -#### Software Architecture -Software architecture description - -#### Installation - -1. xxxx -2. xxxx -3. xxxx - -#### Instructions - -1. xxxx -2. xxxx -3. xxxx - -#### Contribution - -1. Fork the repository -2. Create Feat_xxx branch -3. Commit your code -4. Create Pull Request - - -#### Gitee Feature - -1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md -2. Gitee blog [blog.gitee.com](https://blog.gitee.com) -3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore) -4. The most valuable open source project [GVP](https://gitee.com/gvp) -5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help) -6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) \ No newline at end of file diff --git a/jun_java_plugins/jun_online_java_complier/README.md b/jun_java_plugins/jun_online_java_complier/README.md deleted file mode 100644 index 41787d56f2..0000000000 --- a/jun_java_plugins/jun_online_java_complier/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# onlineJavaCompile - -此项目为对应 vue-cnlinecode的后端 - -vue-onlinecode码云地址:https://gitee.com/china-bin/vue-onlinecode.git - -所用技术: -* 基于springBoot框架开发 -* MAVEN管理项目 -* JAVA class动态编译 -* 自定义classloader -* 标准输入输出重定向 -* FutureTask多线程应用 -* JAVA SecurityManager安全管理 -* 集成swaggr:http://localhost:8080/swagger-ui.html -* 使用logback打印日志 - -# 注意 -* path.properites 记得配置你要把 .class 存储的路径 - -# 功能 -* 可以对传入的java代码 行编译 -* 在subject自定义题目, 自定义测试用例,对测试用例进行判断 - - -# 未来 -* 现在的试题是在java代码中写死的, 未来考虑放到数据库中 -* .............. - diff --git a/jun_java_plugins/jun_online_java_complier/images/OnlieIDE_preview.png b/jun_java_plugins/jun_online_java_complier/images/OnlieIDE_preview.png deleted file mode 100644 index c9a30db9a1..0000000000 Binary files a/jun_java_plugins/jun_online_java_complier/images/OnlieIDE_preview.png and /dev/null differ diff --git a/jun_java_plugins/jun_online_java_complier/mvnw b/jun_java_plugins/jun_online_java_complier/mvnw deleted file mode 100644 index 5bf251c077..0000000000 --- a/jun_java_plugins/jun_online_java_complier/mvnw +++ /dev/null @@ -1,225 +0,0 @@ -#!/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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven2 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 Migwn, 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)`" - # TODO classpath? -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 - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} -echo $MAVEN_PROJECTBASEDIR -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 - -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/jun_java_plugins/jun_online_java_complier/mvnw.cmd b/jun_java_plugins/jun_online_java_complier/mvnw.cmd deleted file mode 100644 index 019bd74d76..0000000000 --- a/jun_java_plugins/jun_online_java_complier/mvnw.cmd +++ /dev/null @@ -1,143 +0,0 @@ -@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 http://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 Maven2 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 key stroke 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 enable echoing my 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 - -%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/jun_java_plugins/jun_online_java_complier/pom.xml b/jun_java_plugins/jun_online_java_complier/pom.xml deleted file mode 100644 index 89ddc116d6..0000000000 --- a/jun_java_plugins/jun_online_java_complier/pom.xml +++ /dev/null @@ -1,120 +0,0 @@ - - - 4.0.0 - - io.github.wujun728 - jun_online_java_complier - 1.0 - jar - - Online JavaComplier.Use SpringBoot. - - - org.springframework.boot - spring-boot-starter-parent - 1.5.7.RELEASE - - - - - UTF-8 - UTF-8 - 1.8 - - - - - commons-io - commons-io - 2.4 - - - - io.springfox - springfox-swagger-ui - 2.9.2 - - - io.springfox - springfox-swagger2 - 2.9.2 - - - com.alibaba - fastjson - 1.2.47 - - - commons-lang - commons-lang - 2.6 - - - org.springframework.boot - spring-boot-devtools - true - - - org.springframework.boot - spring-boot-starter-freemarker - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.security - spring-security-test - test - - - - - org.webjars - jquery - 1.11.3 - - - org.webjars - bootstrap - 3.3.7 - - - org.webjars.bower - github-com-sentsin-layer - 3.0.3 - - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - org.springframework.boot - spring-boot-maven-plugin - - true - - - - - - - - diff --git a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/ComplierApplication.java b/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/ComplierApplication.java deleted file mode 100644 index df0ef26495..0000000000 --- a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/ComplierApplication.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.lzb.onlinejava.complier; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.web.servlet.ServletComponentScan; - -import java.security.Permission; - -/** - * author: haiyangp - * date: 2017/9/26 - * desc: APP入口 - */ -@SpringBootApplication -@ServletComponentScan(basePackages = "com.lzb.onlinejava.complier.filter") -public class ComplierApplication { - - public static void main(String[] args) { - SpringApplication.run(ComplierApplication.class, args); - initPermission(); - } - - /** - * 配置权限,禁止执行CMD 命令 - */ - private static void initPermission() { - SecurityManager originalSecurityManager = System.getSecurityManager(); - if (originalSecurityManager == null) { - // 创建自己的SecurityManager - SecurityManager sm = new SecurityManager() { - private void check(Permission perm) { -// // 禁止exec -// if (perm instanceof java.io.FilePermission) { -// String actions = perm.getActions(); -// if (actions != null && actions.contains("execute")) { -// throw new SecurityException("execute denied!"); -// } -// } -// -// // 禁止设置新的SecurityManager,保护自己 -// if (perm instanceof java.lang.RuntimePermission) { -// String name = perm.getName(); -// if (name != null && name.contains("setSecurityManager")) { -// throw new SecurityException("System.setSecurityManager denied!"); -// } -// } - - - } - - @Override - public void checkPermission(Permission perm) { - check(perm); - } - - @Override - public void checkPermission(Permission perm, Object context) { - check(perm); - } - }; - - System.setSecurityManager(sm); - } - } -} diff --git a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/config/Constans.java b/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/config/Constans.java deleted file mode 100644 index 329c2edff5..0000000000 --- a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/config/Constans.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.lzb.onlinejava.complier.config; - -import com.lzb.onlinejava.complier.util.ResourcesUtil; -import org.springframework.util.ResourceUtils; - -/** - * author: haiyangp - * date: 2017/9/23 - * desc: 配置常量 - */ -public class Constans { - -// public static final String classPath = "C:\\Users\\bin\\Desktop\\java\\"; - - public static String classPath = "C:\\Users\\ucmed\\Desktop\\java\\"; - public static final String excuteMainMethodName = "main"; - - static { - Constans.classPath = ResourcesUtil.getValue("path", "file"); - } -} diff --git a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/config/SwaggerConfig.java b/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/config/SwaggerConfig.java deleted file mode 100644 index cc5d59d87e..0000000000 --- a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/config/SwaggerConfig.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.lzb.onlinejava.complier.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import springfox.documentation.builders.PathSelectors; -import springfox.documentation.builders.RequestHandlerSelectors; -import springfox.documentation.service.ApiInfo; -import springfox.documentation.service.Contact; -import springfox.documentation.spi.DocumentationType; -import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger2.annotations.EnableSwagger2; - -import java.util.Collections; - -@Configuration -@EnableSwagger2 -public class SwaggerConfig { - @Bean - public Docket api() { - return new Docket(DocumentationType.SWAGGER_2) - .select() - .apis(RequestHandlerSelectors.any()) - .paths(PathSelectors.any()) - .build() - .apiInfo(apiInfo()); - } - private ApiInfo apiInfo() { - return new ApiInfo( - "在线编译Swagger 实例文档", - "", - "API V1.0", - "Terms of service", - new Contact("柳宗斌", "", "958615915@qq.com"), - "", "", Collections.emptyList()); - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/config/WebMvcConfig.java b/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/config/WebMvcConfig.java deleted file mode 100644 index 01ca6a96a7..0000000000 --- a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/config/WebMvcConfig.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.lzb.onlinejava.complier.config; - -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.CorsRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; - -/** - * cors 跨域配置 - */ -@Configuration -public class WebMvcConfig extends WebMvcConfigurerAdapter { - - @Override - public void addCorsMappings(CorsRegistry registry) { - registry.addMapping("/**") - .allowedOrigins("*") - .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE") - .maxAge(3600) - .allowCredentials(true); - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/config/WebSecurityConfig.java b/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/config/WebSecurityConfig.java deleted file mode 100644 index 7e9e565139..0000000000 --- a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/config/WebSecurityConfig.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.lzb.onlinejava.complier.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; - -@Configuration -@EnableGlobalMethodSecurity(prePostEnabled = true)//开启security注解 -public class WebSecurityConfig extends WebSecurityConfigurerAdapter { - - @Bean - @Override - protected AuthenticationManager authenticationManager() throws Exception { - return super.authenticationManager(); - } - - - @Override - protected void configure(HttpSecurity http) throws Exception { - http.csrf().disable(); - //允许所有用户访问"/"和"/home" - http.authorizeRequests() - .antMatchers("/", "/home").permitAll(); - //其他地址的访问均需验证权限 -// .anyRequest().authenticated() -// .and() -// .formLogin() -// //指定登录页是"/login" -// .loginPage("/login") -// .defaultSuccessUrl("/hello")//登录成功后默认跳转到"/hello" -// .permitAll() -// .and() -// .logout() -// .logoutSuccessUrl("/home")//退出登录后的默认url是"/home" -// .permitAll(); - - } - - -} diff --git a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/controller/JavaCompileController.java b/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/controller/JavaCompileController.java deleted file mode 100644 index 6401e82adf..0000000000 --- a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/controller/JavaCompileController.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.lzb.onlinejava.complier.controller; - -import com.lzb.onlinejava.complier.enums.ResultTypeEnum; -import com.lzb.onlinejava.complier.service.JavaComileService; -import com.lzb.onlinejava.complier.vo.ResultResponse; -import org.springframework.stereotype.Controller; -import org.springframework.util.StringUtils; -import org.springframework.web.bind.annotation.*; - -import javax.annotation.Resource; - -/** - * author: haiyangp - * date: 2017/9/22 - * desc: JAVA编译器controller - */ -@CrossOrigin -@Controller - -public class JavaCompileController { - - - @Resource - private JavaComileService javaComplieService; - - - /** - * 执行编译 - * - * @param javaSource JAVA代码 - * @return 编译结果 - */ - @ResponseBody - @RequestMapping(value = "/compile") - public ResultResponse complie(String javaSource, - @RequestParam(value = "excuteTimeLimit", required = false) Long excuteTimeLimit, - @RequestParam(value = "excuteArgs", required = false) String excuteArgs) { - - System.out.println("javaSource: " + javaSource); - try { - if (StringUtils.isEmpty(javaSource)) { - return ResultResponse.Build(ResultTypeEnum.error, "代码不能为空!"); - } - Class clazz = javaComplieService.complie(javaSource, "Main"); - String[] args = getInputArgs(excuteArgs); - if (null == excuteTimeLimit && null == args) { - //无参数 无时限 - return javaComplieService.excuteMainMethod(clazz); - } else if (null == excuteTimeLimit) { - //有参数 无时限 - return javaComplieService.excuteMainMethod(clazz, args); - } else if (null == args) { - //无参数 有时限 - if (excuteTimeLimit <= 0) { - return ResultResponse.Build(ResultTypeEnum.error, "限制时间不能小于1毫秒!"); - } - return javaComplieService.excuteMainMethod(clazz, excuteTimeLimit); - } else { - //有参数 有时限 - if (excuteTimeLimit <= 0) { - return ResultResponse.Build(ResultTypeEnum.error, "限制时间不能小于1毫秒!"); - } - return javaComplieService.excuteMainMethod(clazz, excuteTimeLimit, args); - } - } catch (Exception e) { - e.printStackTrace(); - return ResultResponse.Build(ResultTypeEnum.error, "编译出错了! 错误信息:" + e.getMessage()); - } - } - - /** - * 获取运行时程序需要的参数 - * - * @param excuteArgsStr 参数字符串 - */ - private String[] getInputArgs(String excuteArgsStr) { - if (StringUtils.isEmpty(excuteArgsStr)) { - return null; - } else { - return excuteArgsStr.split(" "); - } - } - - @GetMapping(value = {"", "index"}) - public String index() { - - return "index"; - } - - -} diff --git a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/controller/SubjectComileController.java b/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/controller/SubjectComileController.java deleted file mode 100644 index 1daeda761f..0000000000 --- a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/controller/SubjectComileController.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.lzb.onlinejava.complier.controller; - -import com.lzb.onlinejava.complier.dto.SubjectDetail; -import com.lzb.onlinejava.complier.dto.SubjectResult; -import com.lzb.onlinejava.complier.subject.Subject; -import com.lzb.onlinejava.complier.subject.SubjectFactory; -import io.swagger.annotations.ApiOperation; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class SubjectComileController { - - private Logger log = LoggerFactory.getLogger(SubjectComileController.class); - - /** - * 对应界面 执行代码 - * @param javaSource - * @param subjectId - * @return - */ - @ApiOperation("compiles") - @PostMapping("/executeMethod") - public SubjectResult executeMethod(String javaSource, - @RequestParam(value = "subjectId", required = true) int subjectId) { - javaSource = javaSource.replace("\"", ""); - javaSource = javaSource.replace("\\n", ""); - javaSource = javaSource.replace("+", ""); - log.info("javaSource:" + javaSource); - log.info("subjectId:" + subjectId); - Subject subject = SubjectFactory.getBySubjectId(subjectId); - - SubjectResult subjectResult = subject.execueMethod(javaSource); - - return subjectResult; - - } - - @PostMapping("/submit") - public SubjectResult submit(String javaSource, - @RequestParam(value = "subjectId", required = true) int subjectId) { - - javaSource = javaSource.replace("\"", ""); - javaSource = javaSource.replace("\\n", ""); - javaSource = javaSource.replace("+", ""); - log.info("javaSource:" + javaSource); - Subject subject = SubjectFactory.getBySubjectId(subjectId); - - SubjectResult subjectResult = subject.submit(javaSource); - - return subjectResult; - } - - - - @PostMapping("/getSubject") - public SubjectDetail getSujbect(@RequestParam(value = "subjectId", required = false, defaultValue = "1") int subjectId) { - Subject subject = SubjectFactory.getBySubjectId(subjectId); - - SubjectDetail subjectDetail = new SubjectDetail(); - subjectDetail.setTitle(subject.getTitle()); - subjectDetail.setDescribe(subject.getDescribe()); - subjectDetail.setExample(subject.getExample()); - subjectDetail.setInitcode(subject.getIntitCode()); - return subjectDetail; - } - - -} diff --git a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/dto/JavaComileResult.java b/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/dto/JavaComileResult.java deleted file mode 100644 index 7d0ac59a13..0000000000 --- a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/dto/JavaComileResult.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.lzb.onlinejava.complier.dto; - -public class JavaComileResult { - - private Boolean state; // 整体状态码 - - private ResultItem[] resultItems; - - public Boolean getState() { - return state; - } - - public void setState(Boolean state) { - this.state = state; - } - - public ResultItem[] getResultItems() { - return resultItems; - } - - public void setResultItems(ResultItem[] resultItems) { - this.resultItems = resultItems; - } - - public static class ResultItem { - String testData; // 测试数据 - private Boolean state; //测试是否通过 - - public String getTestData() { - return testData; - } - - public void setTestData(String testData) { - this.testData = testData; - } - - public Boolean getState() { - return state; - } - - public void setState(Boolean state) { - this.state = state; - } - } - -} diff --git a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/dto/SubjectDetail.java b/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/dto/SubjectDetail.java deleted file mode 100644 index 6f03ede02a..0000000000 --- a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/dto/SubjectDetail.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.lzb.onlinejava.complier.dto; - -public class SubjectDetail { - private String title; - private String initcode; - private String describe; - private String example; - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public String getInitcode() { - return initcode; - } - - public void setInitcode(String initcode) { - this.initcode = initcode; - } - - public String getDescribe() { - return describe; - } - - public void setDescribe(String describe) { - this.describe = describe; - } - - public String getExample() { - return example; - } - - public void setExample(String example) { - this.example = example; - } -} diff --git a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/dto/SubjectResult.java b/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/dto/SubjectResult.java deleted file mode 100644 index 68a13e6052..0000000000 --- a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/dto/SubjectResult.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.lzb.onlinejava.complier.dto; - -public class SubjectResult { - private int status; - private String info; - private String input; - private String output; - private String expect; - - - public SubjectResult() { - } - - public SubjectResult(int status, String info) { - this.status = status; - this.info = info; - } - - - public int getStatus() { - return status; - } - - public void setStatus(int status) { - this.status = status; - } - - public String getInfo() { - return info; - } - - public void setInfo(String info) { - this.info = info; - } - - public String getInput() { - return input; - } - - public void setInput(String input) { - this.input = input; - } - - public String getOutput() { - return output; - } - - public void setOutput(String output) { - this.output = output; - } - - public String getExpect() { - return expect; - } - - public void setExpect(String expect) { - this.expect = expect; - } -} diff --git a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/enums/InvokeTypeEnum.java b/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/enums/InvokeTypeEnum.java deleted file mode 100644 index 69cbcc540e..0000000000 --- a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/enums/InvokeTypeEnum.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.lzb.onlinejava.complier.enums; - -public enum InvokeTypeEnum { - intType(1, int.class), - stringType(2, String.class), - intArrayType(3, int[].class), - stringArrayType(4, String[].class); - - - private int code; - private Class cls; - - InvokeTypeEnum(int code, Class cls) { - this.code = code; - this.cls = cls; - } - - public Class getCls() { - return this.cls; - } - - public int getCode() { - return this.code; - } - -} diff --git a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/enums/ResultTypeEnum.java b/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/enums/ResultTypeEnum.java deleted file mode 100644 index 772534d3db..0000000000 --- a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/enums/ResultTypeEnum.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.lzb.onlinejava.complier.enums; - - -/** - * author: haiyangp - * date: 2017/9/26 - * desc: 请求结果ENUM - */ -public enum ResultTypeEnum { - ok(200), fail(400), error(500); - private Integer typeCode; - - ResultTypeEnum(Integer code) { - this.typeCode = code; - } - - public Integer getTypeCode() { - return typeCode; - } -} diff --git a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/exception/ComplieException.java b/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/exception/ComplieException.java deleted file mode 100644 index 3652f785e8..0000000000 --- a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/exception/ComplieException.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.lzb.onlinejava.complier.exception; - -/** - * author: haiyangp - * date: 2017/9/22 - * desc: 编译异常 - */ -public class ComplieException extends RuntimeException { - public ComplieException(String message) { - super(message); - } - - -} diff --git a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/service/JavaComileService.java b/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/service/JavaComileService.java deleted file mode 100644 index e6217e94c6..0000000000 --- a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/service/JavaComileService.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.lzb.onlinejava.complier.service; - -import com.lzb.onlinejava.complier.vo.ResultResponse; - -/** - * author: haiyangp - * date: 2017/9/22 - * desc: JAVA编译器service接口 - */ -public interface JavaComileService { - - /** - * 编译,并获取编译后的class类 - * - * @param javaSource JAVA代码 - * @return 编译后的CLASS - */ - Class complie(String javaSource, String className) throws Exception; - - /** - * 执行MAIN方法 - * - * @param clazz 编译后的CLASS - * @return 执行结果 - */ - ResultResponse excuteMainMethod(Class clazz) throws Exception; - - /** - * 执行MAIN方法 - * - * @param clazz 编译后的CLASS - * @param args 运行参数数组 - * @return 执行结果 - */ - ResultResponse excuteMainMethod(Class clazz, String[] args) throws Exception; - - /** - * 执行MAIN方法 - * - * @param timeLimit 时间限制 - */ - ResultResponse excuteMainMethod(Class clazz, Long timeLimit) throws Exception; - - /** - * 执行MAIN方法 - * - * @param timeLimit 时间限制 - * @param args 运行参数数组 - */ - ResultResponse excuteMainMethod(Class clazz, Long timeLimit,String[] args) throws Exception; -} diff --git a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/service/impl/JavaComplieServiceImpl.java b/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/service/impl/JavaComplieServiceImpl.java deleted file mode 100644 index 4ecce6d027..0000000000 --- a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/service/impl/JavaComplieServiceImpl.java +++ /dev/null @@ -1,194 +0,0 @@ -package com.lzb.onlinejava.complier.service.impl; - -import com.lzb.onlinejava.complier.config.Constans; -import com.lzb.onlinejava.complier.enums.ResultTypeEnum; -import com.lzb.onlinejava.complier.exception.ComplieException; -import com.lzb.onlinejava.complier.service.JavaComileService; -import com.lzb.onlinejava.complier.util.ClassClassLoader; -import com.lzb.onlinejava.complier.util.DeleteFileUtil; -import com.lzb.onlinejava.complier.vo.ResultResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; - -import javax.tools.*; -import java.io.*; -import java.lang.reflect.Method; -import java.net.URI; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.*; - -@Service -public class JavaComplieServiceImpl implements JavaComileService { - private Logger logger = LoggerFactory.getLogger(this.getClass()); - - @Override - public Class complie(String javaSource, String className) throws Exception { - - JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler(); - StandardJavaFileManager standardFileManager = javaCompiler.getStandardFileManager(null, null, null); - long currentTime = System.currentTimeMillis(); - StringObject so = new StringObject(className, javaSource); - JavaFileObject file = so; - Iterable options = Arrays.asList("-d", Constans.classPath); - Iterable files = Arrays.asList(file); - - JavaCompiler.CompilationTask task = javaCompiler.getTask(null, standardFileManager, null, options, null, files); - -// // 先删除之前的class -// DeleteFileUtil.deleteFile(className); - - // 在这就会在目录下产生 class文件 - Boolean result = task.call(); - if (result) { - logger.info("complie java source success!"); - } else { - logger.info("complie java scoure fail!"); - throw new ComplieException("complie java scoure fail exception"); - } - return loadClass(className); - } - - - - /** - * 加载CLASS - * - * @param clasName 类名 - * @return class文件 - */ - public Class loadClass(String clasName) throws Exception { -// Class clazz = Class.forName("Main"); - //用自定义classLoader加载这个class - ClassClassLoader classClassLoader = new ClassClassLoader(getClass().getClassLoader()); - Class clazz = classClassLoader.loadClass(clasName); - return clazz; - } - - - @Override - public ResultResponse excuteMainMethod(Class clazz) throws Exception { - return excuteMainMethodWithClass(clazz, new String[]{}); - } - - @Override - public ResultResponse excuteMainMethod(Class clazz, String[] args) throws Exception { - return excuteMainMethodWithClass(clazz, args); - } - - @Override - public ResultResponse excuteMainMethod(Class clazz, Long timeLimit) throws Exception { - return excuteMainMethod(clazz, timeLimit, new String[]{}); - } - - @Override - public ResultResponse excuteMainMethod(Class clazz, Long timeLimit, String[] args) throws Exception { - final ExecutorService executorService = Executors.newFixedThreadPool(10); - List> futureTaskList = new ArrayList<>(); - Callable mainMethodExcuteCallable = new Callable() { - @Override - public ResultResponse call() throws Exception { - return excuteMainMethodWithClass(clazz, args); - } - }; - FutureTask futureTask = new FutureTask(mainMethodExcuteCallable); - futureTaskList.add(futureTask); - executorService.submit(futureTask);//提交到线程池中去执行 - //只里仅仅为了测试,这样写,把多线程当没有线程来用,意思一下 - ResultResponse resultResponse = null; - FutureTask taskItem = futureTaskList.get(0); -// for (FutureTask taskItem : futureTaskList) { - try { - resultResponse = taskItem.get(timeLimit, TimeUnit.MILLISECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (ExecutionException e) { - e.printStackTrace(); - } catch (TimeoutException e) { - taskItem.cancel(true);//超时,就取消 - e.printStackTrace(); - throw new RuntimeException("运行超时了!限定时间为:" + timeLimit + "毫秒"); - } -// } - return resultResponse; - } - - private ResultResponse excuteMainMethodWithClass(Class clazz, String[] args) throws Exception { - setInputArgs(args); - ByteArrayOutputStream baoStream = new ByteArrayOutputStream(1024); - PrintStream cacheStream = new PrintStream(baoStream); - PrintStream oldStream = System.out; - System.setOut(cacheStream);//将输出结果保持到baoStream中,以便后面用 - //执行Main方法 - Method method = clazz.getMethod(Constans.excuteMainMethodName, String[].class); - - Long startTime = System.currentTimeMillis();//开始时间 - - method.invoke(null, (Object) new String[]{}); - - Long endTime = System.currentTimeMillis();//结束时间 - - System.setOut(oldStream);//将输出打印到控制台 - String reusltInfo = baoStream.toString(); - ResultResponse resultResponse = new ResultResponse(); - resultResponse.setExcuteResult(reusltInfo); - resultResponse.setExcuteDurationTime(endTime - startTime); - resultResponse.setResultTypeEnum(ResultTypeEnum.ok); - resultResponse.setMessage("ok"); - return resultResponse; - } - - /** - * 将args参数设为程序运行时的参数 - * - * @param args 参数数组 - */ - private void setInputArgs(String[] args) { - StringBuffer argSb = new StringBuffer(); - for (String argItem : args) { - argSb.append(argItem); - argSb.append(" "); - } - BufferedInputStream argInputStrem = new BufferedInputStream(new ByteArrayInputStream(argSb.toString().getBytes())); - System.setIn(argInputStrem); - } - - - private class StringObject extends SimpleJavaFileObject { - private String contents = null; - - public StringObject(String clasName, String contents) throws Exception { - super(URI.create("String:///" + clasName + Kind.SOURCE.extension), Kind.SOURCE); - this.contents = contents; - } - - @Override - public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { - return contents; - } - } - - - public static void main(String[] args) { - String code = "public class Main {\n" + - "\tpublic static void main(String[] args){\n" + - "\t\tSystem.out.println(\"hello\t\t\t\t\tworld\");\n" + - "\t}\n" + - "}"; - System.out.println(code); - JavaComplieServiceImpl javaComplieService = new JavaComplieServiceImpl(); - try { - Class clazz = javaComplieService.complie(code, "Main"); - Method method = clazz.getMethod("main", String[].class); - Object obj = method.invoke(clazz.newInstance(), (Object) new String[]{"fuck", "you"}); -// System.out.println("返回值:" + obj.toString()); -// ResultResponse resultResponse = javaComplieService.excuteMainMethod(clazz); -// System.out.println("--------->" + resultResponse.getExcuteResult()); - } catch (Exception e) { - e.printStackTrace(); - } - - } -} diff --git a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/subject/Subject.java b/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/subject/Subject.java deleted file mode 100644 index 63e3a400c2..0000000000 --- a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/subject/Subject.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.lzb.onlinejava.complier.subject; - -import com.lzb.onlinejava.complier.dto.SubjectResult; - -public interface Subject { -// public String title = "title"; -// public String initcode = "initcode"; -// public String describe = "describe"; -// public String example = "example"; - - public String getTitle(); - public String getIntitCode(); - public String getDescribe(); - public String getExample(); - - - /** - * 对应界面 执行代码 - * @param javaCode - * @return - */ - public SubjectResult execueMethod(String javaCode); - - /** - * 对应界面 提交 - * @param javaCode - * @return - */ - public SubjectResult submit(String javaCode); -} diff --git a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/subject/Subject1Impl.java b/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/subject/Subject1Impl.java deleted file mode 100644 index d0d39a9b55..0000000000 --- a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/subject/Subject1Impl.java +++ /dev/null @@ -1,197 +0,0 @@ -package com.lzb.onlinejava.complier.subject; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONArray; -import com.lzb.onlinejava.complier.dto.SubjectResult; -import com.lzb.onlinejava.complier.service.JavaComileService; -import com.lzb.onlinejava.complier.service.impl.JavaComplieServiceImpl; -import com.lzb.onlinejava.complier.util.EqualUtil; -import com.lzb.onlinejava.complier.util.ToStringUtil; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.List; - -public class Subject1Impl implements Subject { - - public String title = "两数之和"; - - public String initcode = "public class Solution {\n" + - " public int[] twoSum(int[] nums, int target) {\n" + - " int[] a = new int[2];\n" + - " a[0] = 0;\n" + - " a[1] = 1;\n" + - " return a;\n" + - " \n" + - " }\n" + - "}\n"; - - public String describe = "

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

\n" + - "

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

"; - - - public String example = "给定 nums = [2, 7, 11, 15], target = 9
" + - "因为 nums[0] + nums[1] = 2 + 7 = 9
" + - "所以返回 [0, 1]"; - - - private String arg1 = "[[2,7,11,15], [1,4,6,2]]"; - private String arg2 = "[9,8]"; - private String result = "[[0,1], [2,3]]"; - - public String methodName = "twoSum"; - - @Override - public String getTitle() { - return this.title; - } - - @Override - public String getIntitCode() { - return this.initcode; - } - - @Override - public String getDescribe() { - return this.describe; - } - - @Override - public String getExample() { - return this.example; - } - - /** - * 执行代码 - * @param javaCode - * @return - */ - @Override - public SubjectResult execueMethod(String javaCode) { - JSONArray array1 = JSON.parseArray(arg1); - JSONArray array2 = JSON.parseArray(arg2); - JSONArray resultArray = JSON.parseArray(result); - JavaComileService javaComileService = new JavaComplieServiceImpl(); - Class runClass = null; - try { - runClass = javaComileService.complie(javaCode, "Solution"); - } catch (Exception e) { - e.printStackTrace(); - return new SubjectResult(0, "编译错误"); - } - - Method method = null; - try { - method = runClass.getMethod(methodName, int[].class, int.class); - } catch (NoSuchMethodException e) { - e.printStackTrace(); - } - - - JSONArray intJSONArray = array1.getJSONArray(0); - - int[] arg1 = JSONArrayToIntArray(intJSONArray); - System.out.println(arg1.length); - int arg2 = array2.getInteger(0); - int[] result = JSONArrayToIntArray(resultArray.getJSONArray(0)); - try { - int[] resultIntArray = (int[]) method.invoke(runClass.newInstance(), arg1, arg2); - if (!EqualUtil.intArray(resultIntArray, result)) { - SubjectResult subjectResult = new SubjectResult(); - subjectResult.setStatus(0); - subjectResult.setInfo("第:" + 0 + "个测试用例没通过"); - subjectResult.setInput("arg1:" + ToStringUtil.IntArrayToString(arg1) + "arg2:" + arg2); - subjectResult.setOutput(ToStringUtil.IntArrayToString(resultIntArray)); - subjectResult.setExpect(ToStringUtil.IntArrayToString(result)); - return subjectResult; - - } - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } catch (InstantiationException e) { - e.printStackTrace(); - } - return new SubjectResult(1, "测试完成"); - } - - - /** - * 提交代码 - * @param javaCode - * @return - */ - @Override - public SubjectResult submit(String javaCode) { - JSONArray array1 = JSON.parseArray(arg1); - JSONArray array2 = JSON.parseArray(arg2); - JSONArray resultArray = JSON.parseArray(result); - JavaComileService javaComileService = new JavaComplieServiceImpl(); - Class runClass = null; - try { - runClass = javaComileService.complie(javaCode, "Solution"); - } catch (Exception e) { - e.printStackTrace(); - return new SubjectResult(0, "编译错误"); - } - - Method method = null; - try { - method = runClass.getMethod(methodName, int[].class, int.class); - } catch (NoSuchMethodException e) { - e.printStackTrace(); - return new SubjectResult(0, "运行错误"); - } - - for (int i = 0; i < array1.size(); i++) { - JSONArray intJSONArray = array1.getJSONArray(i); - - int[] arg1 = JSONArrayToIntArray(intJSONArray); - System.out.println(arg1.length); - int arg2 = array2.getInteger(i); - int[] result = JSONArrayToIntArray(resultArray.getJSONArray(i)); - try { - int[] resultIntArray = (int[]) method.invoke(runClass.newInstance(), arg1, arg2); - if (!EqualUtil.intArray(resultIntArray, result)) { - SubjectResult subjectResult = new SubjectResult(); - subjectResult.setStatus(0); - subjectResult.setInfo("第:" + i + "个测试用例没通过"); - subjectResult.setInput("arg1:" + ToStringUtil.IntArrayToString(arg1) + "arg2:" + arg2); - subjectResult.setOutput(ToStringUtil.IntArrayToString(resultIntArray)); - subjectResult.setExpect(ToStringUtil.IntArrayToString(result)); - return subjectResult; - - } - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } catch (InstantiationException e) { - e.printStackTrace(); - } - - } - return new SubjectResult(1, "测试通过"); - - } - - - private int[] JSONArrayToIntArray(JSONArray intJSONArray) { - List intList = intJSONArray.toJavaList(Integer.class); - int[] intArray = new int[intList.size()]; - for (int i = 0; i < intList.size(); i++) { - intArray[i] = intList.get(i); - } - return intArray; - - } - - public static void main(String[] args) { - new Subject1Impl().execueMethod("f"); - } - - - - -} diff --git a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/subject/SubjectFactory.java b/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/subject/SubjectFactory.java deleted file mode 100644 index 6c35d39ad7..0000000000 --- a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/subject/SubjectFactory.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.lzb.onlinejava.complier.subject; - -/** - * 根据 subjectid 创建 subject 的工厂类 - */ -public class SubjectFactory { - - public static Subject getBySubjectId(int subjectId) { - switch (subjectId) { - case 1: - return new Subject1Impl(); - } - - - return null; - - } - -} diff --git a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/testJava/Solution.java b/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/testJava/Solution.java deleted file mode 100644 index fdf2aa68fd..0000000000 --- a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/testJava/Solution.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.lzb.onlinejava.complier.testJava; - -/** - * @author: bin - * @email: 958615915@qq.com - * @create: 2019-08-03 - */ -public class Solution { - public String sayHello() { - return "hello word"; - } - - public String sayHello(String[] strs) { - String s = ""; - for (int i = 0; i < strs.length; i++) { - s = s + strs[i]; - } - return s; - } - - public String sayHello(int i, int j) { - return "i + j =" + (i + j); - } - - public Boolean isTrue() { - return true; - } - - public int[] sayIntArray() { - return new int[]{1, 3, 43}; - } - -} diff --git a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/util/ClassClassLoader.java b/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/util/ClassClassLoader.java deleted file mode 100644 index 1555333c1e..0000000000 --- a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/util/ClassClassLoader.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.lzb.onlinejava.complier.util; - - -import com.lzb.onlinejava.complier.config.Constans; - -import java.io.ByteArrayOutputStream; -import java.io.FileInputStream; -import java.nio.ByteBuffer; -import java.nio.channels.Channels; -import java.nio.channels.FileChannel; -import java.nio.channels.WritableByteChannel; - -/** - * author: haiyangp - * date: 2017/9/23 - * desc: 自定义classLoader,用来加载动态编译好的CLASS文件 - */ -public class ClassClassLoader extends ClassLoader { - private String path = Constans.classPath; - - public ClassClassLoader(ClassLoader parent) { - super(parent); - } - -// @Override -// public Class loadClass(String name) throws ClassNotFoundException { -// Class clazz = findLoadedClass(name); -// if (null == clazz) { -// ClassLoader parentParent = getParent().getParent(); -// try { -// clazz = parentParent.loadClass(name); -// } catch (ClassNotFoundException e) { -// -// } -// if (null == clazz) { -// clazz = findClass(name); -// } -// } -// return clazz; -// } - - - @Override - protected Class findClass(String name) throws ClassNotFoundException { - //这个classLoader的主要方法 - String classPath = name.replace(".", "\\") + ".class";//将包转为目录 - String classFile = path + classPath;//拼接完整的目录 - Class clazz = null; - try { - byte[] data = getClassFileBytes(classFile); - clazz = defineClass(name, data, 0, data.length); - if (null == clazz) {//如果在这个类加载器中都不能找到这个类的话,就真的找不到了 - - - } - - } catch (Exception e) { - e.printStackTrace(); - } - return clazz; - - } - - private byte[] getClassFileBytes(String classFile) throws Exception { - //采用NIO读取 - FileInputStream fis = new FileInputStream(classFile); - FileChannel fileC = fis.getChannel(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - WritableByteChannel outC = Channels.newChannel(baos); - ByteBuffer buffer = ByteBuffer.allocateDirect(1024); - while (true) { - int i = fileC.read(buffer); - if (i == 0 || i == -1) { - break; - } - buffer.flip(); - outC.write(buffer); - buffer.clear(); - } - fis.close(); - return baos.toByteArray(); - } -} diff --git a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/util/DeleteFileUtil.java b/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/util/DeleteFileUtil.java deleted file mode 100644 index 671cfbf6d5..0000000000 --- a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/util/DeleteFileUtil.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.lzb.onlinejava.complier.util; - -import java.io.File; -import java.io.IOException; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.FilenameUtils; -import org.springframework.util.ResourceUtils; - -/** - * 根据文件的名字到对应的文件夹下面删除对应的文件 - * - * @author QiaoLiQiang - * @time 2018年2月6日下午2:22:40 - */ -public class DeleteFileUtil { - /** - * 删除文件(因为一个文件可能存在pdf,doc,docx三种格式,因此需要删除) - * - * @param fileName - * @return - */ - public static boolean deleteFile(String fileName) { - if (fileName == null) { - return false; - } - String dir = ResourcesUtil.getValue("path", "file");// 获取文件的基本目录 - String baseName = FilenameUtils.getBaseName(fileName);// 获取文件的基本名字 - System.out.println("baseName:" + baseName); - try { - FileUtils.forceDeleteOnExit(new File(dir + baseName + ".class")); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return true; - } - - /** - * 到存放图片的文件夹下面删除图片 - * - * @param fileName - * @return - */ - public static boolean deletePicture(String fileName) { - if (fileName == null) { - return false; - } - String dir = ResourcesUtil.getValue("path", "picture");// 获取文件图片的基本目录 - try { - FileUtils.forceDeleteOnExit(new File(dir + fileName)); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return true; - } - - public static void main(String[] args) { - String file = ResourcesUtil.getValue("path", "file"); - System.out.println(file); - DeleteFileUtil.deleteFile("Solution.class"); -// DeleteFileUtil.deleteFile("ef0c4d250561413e9777fb439e8fbc27.doc"); -// System.out.println("sss"); - } - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/util/EqualUtil.java b/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/util/EqualUtil.java deleted file mode 100644 index 8b66756c2f..0000000000 --- a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/util/EqualUtil.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.lzb.onlinejava.complier.util; - -public class EqualUtil { - - public static Boolean intArray(int[] a, int[] b) { - int i = 0, j = 0; - for (; i < a.length && j < b.length; i++, j++) { - if (a[i] != b[j]) { - return false; - } - } - return true; - } -} diff --git a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/util/JavaCodeCompileHelper.java b/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/util/JavaCodeCompileHelper.java deleted file mode 100644 index 0718876d78..0000000000 --- a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/util/JavaCodeCompileHelper.java +++ /dev/null @@ -1,135 +0,0 @@ -package com.lzb.onlinejava.complier.util; - -import com.lzb.onlinejava.complier.config.Constans; - -import javax.tools.*; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URI; -import java.util.Arrays; - -/** - * @author: bin - * @email: 958615915@qq.com - * @create: 2019-08-03 - */ -public class JavaCodeCompileHelper { - // path 是你想把.class 放在哪里的路径, - // private String path = "C:\\Users\\bin\\Desktop\\java\\"; -// private String path = "C:\\Users\\ucmed\\Desktop\\java\\"; - private String path = Constans.classPath; - - /** - * 将java代码在内存中编译,并获得这个class - * @param javaCode - * @param className - * @return - * @throws Exception - */ - public Class compileAndGetClass(String javaCode, String className) throws Exception { - JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler(); - - // StandardJavaFileManager 对象主要负责 - // 编译文件对象的创建,编译的参数等等,我们只对它做些基本设置比如编译 CLASSPATH 等。 - StandardJavaFileManager standardJavaFileManager = javaCompiler.getStandardFileManager(null, null, null); - - // JavaFileObject 为类文件上进行操作的工具的文件抽象 - JavaFileObject javaFileObject = new myJavaFileObject(className, javaCode); - - // Array Map Set 等都属于Itreable类型 - Iterable options = Arrays.asList("-d", path); - - Iterable files = Arrays.asList(javaFileObject); - - // 通过一些选项,javafileObject, classPath 来获取JvaComiler.ComilationTask - JavaCompiler.CompilationTask task = javaCompiler.getTask(null, - standardJavaFileManager, null, options, null, files); - - // 将Class 在内存中编译 - Boolean result = task.call(); - - // 通过类名 加载class - ClassLoader classLoader = new ClassClassLoader(getClass().getClassLoader()); - return classLoader.loadClass(className); - } - - - /** - * 传入类, 方法名, 参数, 获得返回值 - * @param cls - * @param methodName - * @param args - * @return - * @throws NoSuchMethodException - * @throws InvocationTargetException - * @throws IllegalAccessException - * @throws InstantiationException - */ - public Object executeMethod(Class cls, String methodName, Object... args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { - Class[] clsArray; - - // 无参方法 - if (args == null) { - Method method = cls.getMethod(methodName, null); - method.setAccessible(true); - Object obj = method.invoke(cls.newInstance(), null); - - return obj; - } - - - // 一个String[] 传参 - if (args instanceof String[]) { - - Method method = cls.getMethod(methodName, String[].class); - method.setAccessible(true); - // java 的 bug, 为String[] 时要 用 Object 强转 - Object obj = method.invoke(cls.newInstance(), (Object) args); - - return obj; - - - // 多个传参 - } else if (args instanceof Object[]) { - - clsArray = new Class[args.length]; - - for (int i = 0; i < args.length; i++) { - clsArray[i] = args[i].getClass(); - } - Method method = cls.getMethod(methodName, clsArray); - method.setAccessible(true); - Object obj = method.invoke(cls.newInstance(), args); - - return obj; - - - } else { - - } - - return null; - - } - - public static void main(String[] args) { - } - - - private class myJavaFileObject extends SimpleJavaFileObject { - private String contents = null; - - public myJavaFileObject(String clasName, String contents) throws Exception { - super(URI.create("String:///" + clasName + Kind.SOURCE.extension), Kind.SOURCE); - this.contents = contents; - } - - @Override - public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { - return contents; - } - } - - -} diff --git a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/util/ResourcesUtil.java b/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/util/ResourcesUtil.java deleted file mode 100644 index fb3c0c7af1..0000000000 --- a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/util/ResourcesUtil.java +++ /dev/null @@ -1,139 +0,0 @@ -package com.lzb.onlinejava.complier.util; - - - -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.ResourceBundle; -import java.util.Set; - -/** - * 读取properties文件的工具类 - * @author QiaoLiQiang - * @time 2018年2月5日下午4:28:18 - */ -public class ResourcesUtil implements Serializable { - - private static final long serialVersionUID = -7657898714983901418L; - - /** - * 系统语言环境,默认为中文zh - */ - public static final String LANGUAGE = "zh"; - - /** - * 系统国家环境,默认为中国CN - */ - public static final String COUNTRY = "CN"; - private static Locale getLocale() { - Locale locale = new Locale(LANGUAGE, COUNTRY); - return locale; - } - - /** - * 根据语言、国家、资源文件名和key名字获取资源文件值 - * - * @param language - * 语言 - * - * @param country - * 国家 - * - * @param baseName - * 资源文件名 - * - * @param section - * key名字 - * - * @return 值 - */ - private static String getProperties(String baseName, String section) { - String retValue = ""; - try { - Locale locale = getLocale(); - ResourceBundle rb = ResourceBundle.getBundle(baseName, locale); - retValue = (String) rb.getObject(section); - } catch (Exception e) { - e.printStackTrace(); - // TODO 添加处理 - } - return retValue; - } - - /** - * 通过key从资源文件读取内容 - * - * @param fileName - * 资源文件名 - * - * @param key - * 索引 - * - * @return 索引对应的内容 - */ - public static String getValue(String fileName, String key) { - String value = getProperties(fileName,key); - return value; - } - - public static List gekeyList(String baseName) { - Locale locale = getLocale(); - ResourceBundle rb = ResourceBundle.getBundle(baseName, locale); - - List reslist = new ArrayList(); - - Set keyset = rb.keySet(); - for (Iterator it = keyset.iterator(); it.hasNext();) { - String lkey = (String)it.next(); - reslist.add(lkey); - } - - return reslist; - - } - - /** - * 通过key从资源文件读取内容,并格式化 - * - * @param fileName - * 资源文件名 - * - * @param key - * 索引 - * - * @param objs - * 格式化参数 - * - * @return 格式化后的内容 - */ - public static String getValue(String fileName, String key, Object[] objs) { - String pattern = getValue(fileName, key); - String value = MessageFormat.format(pattern, objs); - return value; - } - - public static void main(String[] args) { - System.out.println(getValue("resources.messages", "101",new Object[]{100,200})); - - - //根据操作系统环境获取语言环境 - /*Locale locale = Locale.getDefault(); - System.out.println(locale.getCountry());//输出国家代码 - System.out.println(locale.getLanguage());//输出语言代码s - - //加载国际化资源(classpath下resources目录下的messages.properties,如果是中文环境会优先找messages_zh_CN.properties) - ResourceBundle rb = ResourceBundle.getBundle("resources.messages", locale); - String retValue = rb.getString("101");//101是messages.properties文件中的key - System.out.println(retValue); - - //信息格式化,如果资源中有{}的参数则需要使用MessageFormat格式化,Object[]为传递的参数,数量根据资源文件中的{}个数决定 - String value = MessageFormat.format(retValue, new Object[]{100,200}); - System.out.println(value); -*/ - - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/util/ToStringUtil.java b/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/util/ToStringUtil.java deleted file mode 100644 index e32883446b..0000000000 --- a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/util/ToStringUtil.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.lzb.onlinejava.complier.util; - -public class ToStringUtil { - - public static String IntArrayToString(int [] array) { - String str = "["; - - for (int i = 0; i < array.length; i++) { - str = str + array[i] + ","; - } - str = str.substring(0, str.length() - 1); - str = str + "]"; - return str; - } - - public static void main(String[] args) { - System.out.println(ToStringUtil.IntArrayToString(new int[]{1, 3, 4})); - } -} diff --git a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/vo/ResultResponse.java b/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/vo/ResultResponse.java deleted file mode 100644 index 785d573bb6..0000000000 --- a/jun_java_plugins/jun_online_java_complier/src/main/java/com/lzb/onlinejava/complier/vo/ResultResponse.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.lzb.onlinejava.complier.vo; - -import com.lzb.onlinejava.complier.enums.ResultTypeEnum; - -import java.io.Serializable; - -/** - * author: haiyangp - * date: 2017/9/26 - * desc: 响应结果 - */ -public class ResultResponse implements Serializable { - //执行结果 - private String excuteResult; - //状态类型 - private ResultTypeEnum resultTypeEnum; - //执行时间 - private Long excuteDurationTime=-1l; - - private String message; - - public String getExcuteResult() { - return excuteResult; - } - - - public static ResultResponse Build(ResultTypeEnum resultTypeEnum) { - ResultResponse resultResponse = new ResultResponse(); - resultResponse.setResultTypeEnum(resultTypeEnum); - return resultResponse; - } - - public static ResultResponse Build(ResultTypeEnum resultTypeEnum, String message) { - ResultResponse resultResponse = Build(resultTypeEnum); - resultResponse.setMessage(message); - return resultResponse; - } - - - public void setExcuteResult(String excuteResult) { - this.excuteResult = excuteResult; - } - - public Integer getResultTypeEnum() { - return resultTypeEnum.getTypeCode(); - } - - public void setResultTypeEnum(ResultTypeEnum resultTypeEnum) { - this.resultTypeEnum = resultTypeEnum; - } - - public Long getExcuteDurationTime() { - return excuteDurationTime; - } - - public void setExcuteDurationTime(Long excuteDurationTime) { - this.excuteDurationTime = excuteDurationTime; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } -} diff --git a/jun_java_plugins/jun_online_java_complier/src/main/resources/application.properties b/jun_java_plugins/jun_online_java_complier/src/main/resources/application.properties deleted file mode 100644 index 2b6923b351..0000000000 --- a/jun_java_plugins/jun_online_java_complier/src/main/resources/application.properties +++ /dev/null @@ -1,4 +0,0 @@ -server.port=8080 - -spring.devtools.restart.enabled=true -spring.freemarker.cache=false \ No newline at end of file diff --git a/jun_java_plugins/jun_online_java_complier/src/main/resources/logback-spring.xml b/jun_java_plugins/jun_online_java_complier/src/main/resources/logback-spring.xml deleted file mode 100644 index 27553c9438..0000000000 --- a/jun_java_plugins/jun_online_java_complier/src/main/resources/logback-spring.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - - - - [%d{yyyy-MM-dd HH:mm:ss.SSS}] [%thread] %-5level %logger{80} Line:%line ----> %msg%n - UTF-8 - - - - - - - - - INFO - - ${user.home}/logs/yyzxyy-yqw/defult.log - - - - - ${user.home}/logs/defult.%d{yyyy-MM-dd}.log - - 90 - - - %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} Line:%line ----> %msg%n - - UTF-8 - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_online_java_complier/src/main/resources/path.properties b/jun_java_plugins/jun_online_java_complier/src/main/resources/path.properties deleted file mode 100644 index e626945d69..0000000000 --- a/jun_java_plugins/jun_online_java_complier/src/main/resources/path.properties +++ /dev/null @@ -1 +0,0 @@ -file=C:\\Users\\ucmed\\Desktop\\java\\ \ No newline at end of file diff --git a/jun_java_plugins/jun_online_java_complier/src/main/resources/templates/index.ftl b/jun_java_plugins/jun_online_java_complier/src/main/resources/templates/index.ftl deleted file mode 100644 index d744901202..0000000000 --- a/jun_java_plugins/jun_online_java_complier/src/main/resources/templates/index.ftl +++ /dev/null @@ -1,115 +0,0 @@ - - - - - OnLine JAVA IDE - - - - - - - -
-
- - -
-
- -
-
- -
- - -


- -
-
-
-

运行信息

-
-
-
-
-
- -
-
-
-

运行结果

-
-
- -
-
-
-
- - - \ No newline at end of file diff --git a/jun_java_plugins/jun_oracle/oracle to_date.md b/jun_java_plugins/jun_oracle/oracle to_date.md deleted file mode 100644 index 76425fb7f0..0000000000 --- a/jun_java_plugins/jun_oracle/oracle to_date.md +++ /dev/null @@ -1,264 +0,0 @@ -OracleTO_DATEʽ2009-04-14 10:53TO_DATEʽ(ʱ:2007-11-02 13:45:25Ϊ) - - Year: - yy two digits λ ʾֵ:07 - yyy three digits λ ʾֵ:007 - yyyy four digits λ ʾֵ:2007 - - Month: - mm number λ ʾֵ:11 - mon abbreviated ַʾ ʾֵ:11,Ӣİ,ʾnov - month spelled out ַʾ ʾֵ:11,Ӣİ,ʾnovember - - Day: - dd number µڼ ʾֵ:02 - ddd number ڼ ʾֵ:02 - dy abbreviated ܵڼд ʾֵ:,Ӣİ,ʾfri - day spelled out ܵڼȫд ʾֵ:,Ӣİ,ʾfriday - ddspth spelled out, ordinal twelfth - - Hour: - hh two digits 12Сʱ ʾֵ:01 - hh24 two digits 24Сʱ ʾֵ:13 - - Minute: - mi two digits 60 ʾֵ:45 - - Second: - ss two digits 60 ʾֵ:25 - - - Q digit ʾֵ:4 - WW digit ڼ ʾֵ:44 - W digit µڼ ʾֵ:1 - - 24Сʱʽʱ䷶ΧΪ 0:00:00 - 23:59:59.... - 12Сʱʽʱ䷶ΧΪ 1:00:00 - 12:59:59 .... - -1. ںַת÷to_date,to_char - -select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') as nowTime from dual; //תΪַ -select to_char(sysdate,'yyyy') as nowYear from dual; //ȡʱ -select to_char(sysdate,'mm') as nowMonth from dual; //ȡʱ -select to_char(sysdate,'dd') as nowDay from dual; //ȡʱ -select to_char(sysdate,'hh24') as nowHour from dual; //ȡʱʱ -select to_char(sysdate,'mi') as nowMinute from dual; //ȡʱķ -select to_char(sysdate,'ss') as nowSecond from dual; //ȡʱ - -select to_date('2004-05-07 13:23:44','yyyy-mm-dd hh24:mi:ss') from dual// -2. - select to_char( to_date(222,'J'),'Jsp') from dual - - ʾTwo Hundred Twenty-Two -3.ijڼ - select to_char(to_date('2002-08-26','yyyy-mm-dd'),'day') from dual; - һ - select to_char(to_date('2002-08-26','yyyy-mm-dd'),'day','NLS_DATE_LANGUAGE = American') from dual; - monday - - ALTER SESSION SET NLS_DATE_LANGUAGE='AMERICAN'; - Ҳ - TO_DATE ('2002-08-26', 'YYYY-mm-dd', 'NLS_DATE_LANGUAGE = American') -4. ڼ - select floor(sysdate - to_date('20020405','yyyymmdd')) from dual; -5. ʱΪnull÷ - select id, active_date from table1 - UNION - select 1, TO_DATE(null) from dual; - - עҪTO_DATE(null) -6.·ݲ - a_date between to_date('20011201','yyyymmdd') and to_date('20011231','yyyymmdd') - ô123112֮121ŵ12֮ǰDzΧ֮ڵġ - ԣʱҪȷʱ򣬾to_charDZҪ - -7. ڸʽͻ - ĸʽҪ㰲װORACLEַ, : US7ASCII, dateʽ;: '01-Jan-01' - alter system set NLS_DATE_LANGUAGE = American - alter session set NLS_DATE_LANGUAGE = American - to_dateд - select to_char(to_date('2002-08-26','yyyy-mm-dd'),'day','NLS_DATE_LANGUAGE = American') from dual; - עֻǾNLS_DATE_LANGUAGEȻкܶ࣬ - ɲ鿴 - select * from nls_session_parameters - select * from V$NLS_PARAMETERS -8. - select count(*) - from ( select rownum-1 rnum - from all_objects - where rownum <= to_date('2002-02-28','yyyy-mm-dd') - to_date('2002- - 02-01','yyyy-mm-dd')+1 - ) - where to_char( to_date('2002-02-01','yyyy-mm-dd')+rnum-1, 'D' ) - not in ( '1', '7' ) - - 2002-02-282002-02-01һߵ - ǰֱDBMS_UTILITY.GET_TIME, ú󽫽(õ1/100, Ǻ). -9. · - select months_between(to_date('01-31-1999','MM-DD-YYYY'),to_date('12-31-1998','MM-DD-YYYY')) "MONTHS" FROM DUAL; - 1 - select months_between(to_date('02-01-1999','MM-DD-YYYY'),to_date('12-31-1998','MM-DD-YYYY')) "MONTHS" FROM DUAL; - 1.03225806451613 - -10. Next_day÷ - Next_day(date, day) - - Monday-Sunday, for format code DAY - Mon-Sun, for format code DY - 1-7, for format code D -11 - select to_char(sysdate,'hh:mi:ss') TIME from all_objects - ע⣺һ¼TIME һһ - Խһ - create or replace function sys_date return date is - begin - return sysdate; - end; - - select to_char(sys_date,'hh:mi:ss') from all_objects; - -12.Сʱ - extract()ҳڻֵֵֶ - SELECT EXTRACT(HOUR FROM TIMESTAMP '2001-02-16 2:38:40') from offer - SQL> select sysdate ,to_char(sysdate,'hh') from dual; - - SYSDATE TO_CHAR(SYSDATE,'HH') - -------------------- --------------------- - 2003-10-13 19:35:21 07 - - SQL> select sysdate ,to_char(sysdate,'hh24') from dual; - - SYSDATE TO_CHAR(SYSDATE,'HH24') - -------------------- ----------------------- - 2003-10-13 19:35:21 19 - -13.յĴ - select older_date, - newer_date, - years, - months, - abs( - trunc( - newer_date- - add_months( older_date,years*12+months ) - ) - ) days - - from ( select - trunc(months_between( newer_date, older_date )/12) YEARS, - mod(trunc(months_between( newer_date, older_date )),12 ) MONTHS, - newer_date, - older_date - from ( - select hiredate older_date, add_months(hiredate,rownum)+rownum newer_date - from emp - ) - ) -14.·İ취 - select to_char(add_months(last_day(sysdate) +1, -2), 'yyyymmdd'),last_day(sysdate) from dual -16.ҳ - select add_months(trunc(sysdate,'year'), 12) - trunc(sysdate,'year') from dual - Ĵ - to_char( last_day( to_date('02' | | :year,'mmyyyy') ), 'dd' ) - 28Ͳ -17.yyyyrrrr - 'YYYY99 TO_C - ------- ---- - yyyy 99 0099 - rrrr 99 1999 - yyyy 01 0001 - rrrr 01 2001 -18.ͬʱĴ - select to_char( NEW_TIME( sysdate, 'GMT','EST'), 'dd/mm/yyyy hh:mi:ss') ,sysdate - from dual; -19.5һ - Select TO_DATE(FLOOR(TO_CHAR(sysdate,'SSSSS')/300) * 300,'SSSSS') ,TO_CHAR(sysdate,'SSSSS') - from dual - 2002-11-1 9:55:00 35786 - SSSSSʾ5λ -20.һĵڼ - select TO_CHAR(SYSDATE,'DDD'),sysdate from dual - - 310 2002-11-6 10:03:51 -21.Сʱ,,, - select - Days, - A, - TRUNC(A*24) Hours, - TRUNC(A*24*60 - 60*TRUNC(A*24)) Minutes, - TRUNC(A*24*60*60 - 60*TRUNC(A*24*60)) Seconds, - TRUNC(A*24*60*60*100 - 100*TRUNC(A*24*60*60)) mSeconds - from - ( - select - trunc(sysdate) Days, - sysdate - trunc(sysdate) A - from dual - ) - - select * from tabname - order by decode(mode,'FIFO',1,-1)*to_char(rq,'yyyymmddhh24miss'); - - // - floor((date2-date1) /365) Ϊ - floor((date2-date1, 365) /30) Ϊ - d(mod(date2-date1, 365), 30)Ϊ. -23.next_day ¸ڵ,dayΪ1-7-,1ʾ - next_day(sysdate,6)Ǵӵǰʼһ塣Ǵտʼ - 1 2 3 4 5 6 7 - һ - - --------------------------------------------------------------- - - select (sysdate-to_date('2003-12-03 12:55:45','yyyy-mm-dd hh24:mi:ss'))*24*60*60 from ddual - ص Ȼ תΪss - -24,round[뵽ӽ](day:뵽ӽ) - select sysdate S1, - round(sysdate) S2 , - round(sysdate,'year') YEAR, - round(sysdate,'month') MONTH , - round(sysdate,'day') DAY from dual -25,trunc[ضϵӽ,λΪ] ,ص - select sysdate S1, - trunc(sysdate) S2, //صǰ,ʱ - trunc(sysdate,'year') YEAR, //صǰ11,ʱ - trunc(sysdate,'month') MONTH , //صǰµ1,ʱ - trunc(sysdate,'day') DAY //صǰڵ,ʱ - from dual -26,б - select greatest('01-1-04','04-1-04','10-2-04') from dual -27.ʱ - ע:oracleʱΪλ,Ի, - - select floor(to_number(sysdate-to_date('2007-11-02 15:55:03','yyyy-mm-dd hh24:mi:ss'))/365) as spanYears from dual -//ʱ- - select ceil(moths_between(sysdate-to_date('2007-11-02 15:55:03','yyyy-mm-dd hh24:mi:ss'))) as spanMonths from dual -//ʱ- - select floor(to_number(sysdate-to_date('2007-11-02 15:55:03','yyyy-mm-dd hh24:mi:ss'))) as spanDays from dual -//ʱ- - select floor(to_number(sysdate-to_date('2007-11-02 15:55:03','yyyy-mm-dd hh24:mi:ss'))*24) as spanHours from dual -//ʱ-ʱ - select floor(to_number(sysdate-to_date('2007-11-02 15:55:03','yyyy-mm-dd hh24:mi:ss'))*24*60) as spanMinutes from dual -//ʱ- - select floor(to_number(sysdate-to_date('2007-11-02 15:55:03','yyyy-mm-dd hh24:mi:ss'))*24*60*60) as spanSeconds from dual -//ʱ- -28.ʱ - ע:oracleʱӼΪλ,ıΪn,Ի, - select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss'),to_char(sysdate+n*365,'yyyy-mm-dd hh24:mi:ss') as newTime from dual -//ıʱ- - select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss'),add_months(sysdate,n) as newTime from dual //ıʱ- - select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss'),to_char(sysdate+n,'yyyy-mm-dd hh24:mi:ss') as newTime from dual -//ıʱ- - select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss'),to_char(sysdate+n/24,'yyyy-mm-dd hh24:mi:ss') as newTime from dual -//ıʱ-ʱ - select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss'),to_char(sysdate+n/24/60,'yyyy-mm-dd hh24:mi:ss') as newTime from dual -//ıʱ- - select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss'),to_char(sysdate+n/24/60/60,'yyyy-mm-dd hh24:mi:ss') as newTime from dual -//ıʱ- -29.µĵһ,һ - SELECT Trunc(Trunc(SYSDATE, 'MONTH') - 1, 'MONTH') First_Day_Last_Month, - Trunc(SYSDATE, 'MONTH') - 1 / 86400 Last_Day_Last_Month, - Trunc(SYSDATE, 'MONTH') First_Day_Cur_Month, - LAST_DAY(Trunc(SYSDATE, 'MONTH')) + 1 - 1 / 86400 Last_Day_Cur_Month - FROM dual; \ No newline at end of file diff --git a/jun_java_plugins/jun_oracle/oracle_book.sql b/jun_java_plugins/jun_oracle/oracle_book.sql deleted file mode 100644 index e4f0e9eec9..0000000000 --- a/jun_java_plugins/jun_oracle/oracle_book.sql +++ /dev/null @@ -1,153 +0,0 @@ -prompt PL/SQL Developer import file -prompt Created on 20151022 by Administrator -set feedback off -set define off -prompt Creating T_BOOKTYPE... -create table T_BOOKTYPE -( - id NUMBER not null, - typename VARCHAR2(20), - num NUMBER -) -tablespace USERS - pctfree 10 - initrans 1 - maxtrans 255 - storage - ( - initial 64K - next 1M - minextents 1 - maxextents unlimited - ); -alter table T_BOOKTYPE - add constraint IDP primary key (ID) - using index - tablespace USERS - pctfree 10 - initrans 2 - maxtrans 255 - storage - ( - initial 64K - next 1M - minextents 1 - maxextents unlimited - ); - -prompt Creating T_BOOK... -create table T_BOOK -( - id NUMBER not null, - bookname VARCHAR2(20), - typeid NUMBER -) -tablespace USERS - pctfree 10 - initrans 1 - maxtrans 255 - storage - ( - initial 64K - next 1M - minextents 1 - maxextents unlimited - ); -alter table T_BOOK - add constraint IDPP primary key (ID) - using index - tablespace USERS - pctfree 10 - initrans 2 - maxtrans 255 - storage - ( - initial 64K - next 1M - minextents 1 - maxextents unlimited - ); -alter table T_BOOK - add constraint TYPEIDF foreign key (TYPEID) - references T_BOOKTYPE (ID); - -prompt Creating T_BOOK_LOG... -create table T_BOOK_LOG -( - actionuser VARCHAR2(20), - actionname VARCHAR2(20), - actiontime DATE -) -tablespace USERS - pctfree 10 - initrans 1 - maxtrans 255 - storage - ( - initial 64K - next 1M - minextents 1 - maxextents unlimited - ); - -prompt Disabling triggers for T_BOOKTYPE... -alter table T_BOOKTYPE disable all triggers; -prompt Disabling triggers for T_BOOK... -alter table T_BOOK disable all triggers; -prompt Disabling triggers for T_BOOK_LOG... -alter table T_BOOK_LOG disable all triggers; -prompt Disabling foreign key constraints for T_BOOK... -alter table T_BOOK disable constraint TYPEIDF; -prompt Deleting T_BOOK_LOG... -delete from T_BOOK_LOG; -commit; -prompt Deleting T_BOOK... -delete from T_BOOK; -commit; -prompt Deleting T_BOOKTYPE... -delete from T_BOOKTYPE; -commit; -prompt Loading T_BOOKTYPE... -insert into T_BOOKTYPE (id, typename, num) -values (1, '', 3); -insert into T_BOOKTYPE (id, typename, num) -values (2, '', 1); -commit; -prompt 2 records loaded -prompt Loading T_BOOK... -insert into T_BOOK (id, bookname, typeid) -values (1, 'java˼', 1); -insert into T_BOOK (id, bookname, typeid) -values (2, 'һͷJava', 1); -insert into T_BOOK (id, bookname, typeid) -values (3, 'Դ', 2); -insert into T_BOOK (id, bookname, typeid) -values (4, 'xx3', 1); -commit; -prompt 4 records loaded -prompt Loading T_BOOK_LOG... -insert into T_BOOK_LOG (actionuser, actionname, actiontime) -values ('SCOTT', 'insert', to_date('22-10-2015 08:11:13', 'dd-mm-yyyy hh24:mi:ss')); -insert into T_BOOK_LOG (actionuser, actionname, actiontime) -values ('SCOTT', 'update', to_date('22-10-2015 08:12:19', 'dd-mm-yyyy hh24:mi:ss')); -insert into T_BOOK_LOG (actionuser, actionname, actiontime) -values ('SCOTT', 'delete', to_date('22-10-2015 08:12:37', 'dd-mm-yyyy hh24:mi:ss')); -insert into T_BOOK_LOG (actionuser, actionname, actiontime) -values ('SCOTT', 'insert', to_date('22-10-2015 08:17:09', 'dd-mm-yyyy hh24:mi:ss')); -insert into T_BOOK_LOG (actionuser, actionname, actiontime) -values ('SCOTT', 'delete', to_date('22-10-2015 08:18:50', 'dd-mm-yyyy hh24:mi:ss')); -insert into T_BOOK_LOG (actionuser, actionname, actiontime) -values ('SCOTT', 'update', to_date('22-10-2015 08:21:02', 'dd-mm-yyyy hh24:mi:ss')); -commit; -prompt 6 records loaded -prompt Enabling foreign key constraints for T_BOOK... -alter table T_BOOK enable constraint TYPEIDF; -prompt Enabling triggers for T_BOOKTYPE... -alter table T_BOOKTYPE enable all triggers; -prompt Enabling triggers for T_BOOK... -alter table T_BOOK enable all triggers; -prompt Enabling triggers for T_BOOK_LOG... -alter table T_BOOK_LOG enable all triggers; -set feedback on -set define on -prompt Done. diff --git a/jun_java_plugins/jun_oracle/oracle_cursor.md b/jun_java_plugins/jun_oracle/oracle_cursor.md deleted file mode 100644 index 9656aebdce..0000000000 --- a/jun_java_plugins/jun_oracle/oracle_cursor.md +++ /dev/null @@ -1,142 +0,0 @@ -set serverout on; -declare cursor cu_emp is select empno,ename,sal from emp; -e_no number; -e_name varchar2(10); -e_sal number; -begin - open cu_emp; - fetch cu_emp into e_no,e_name,e_sal; - while cu_emp%found loop - dbms_output.put_line('ţ'||e_no||''||e_name||'нʣ'||e_sal); - fetch cu_emp into e_no,e_name,e_sal; - end loop; - close cu_emp; -end; - - -set serverout on; -declare cursor cu_emp is select empno,ename,sal from emp; -e_no emp.empno%type; -e_name emp.ename%type; -e_sal emp.sal%type; -begin - open cu_emp; - fetch cu_emp into e_no,e_name,e_sal; - while cu_emp%found loop - dbms_output.put_line('ţ'||e_no||''||e_name||'нʣ'||e_sal); - fetch cu_emp into e_no,e_name,e_sal; - end loop; - close cu_emp; -end; - -set serverout on; -declare cursor cu_emp is select * from emp; -e emp%rowtype; -begin - open cu_emp; - fetch cu_emp into e; - while cu_emp%found loop - dbms_output.put_line('ţ'||e.empno||''||e.ename||'нʣ'||e.sal); - fetch cu_emp into e; - end loop; - close cu_emp; -end; - - -set serverout on; -declare cursor cu_emp is select * from emp where sal>2000 and sal<3000; -e emp%rowtype; -begin - open cu_emp; - fetch cu_emp into e; - while cu_emp%found loop - dbms_output.put_line('ţ'||e.empno||''||e.ename||'нʣ'||e.sal); - fetch cu_emp into e; - end loop; - close cu_emp; -end; - -begin - if sql%isopen then - dbms_output.put_line('sqlαѴ'); - else - dbms_output.put_line('sqlαδ'); - end if; -end; - -declare e_count number; -begin - select count(*) into e_count from emp; - dbms_output.put_line('α겶ļ¼'||sql%rowcount); -end; - -declare e_count number; -begin - select count(*) into e_count from emp; - dbms_output.put_line('α겶ļ¼'||sql%rowcount); -end; - - -begin - update emp set ename='sb3' where empno=111; - if sql%rowcount=1 then - dbms_output.put_line('Ѹ'); - else - dbms_output.put_line('δ'); - end if; -end; - -begin - update emp set ename='sb3' where empno=111; - if sql%found then - dbms_output.put_line('Ѹ'); - else - dbms_output.put_line('δ'); - end if; -end; - -declare type emptype is ref cursor return emp%rowtype; -cu_emp emptype; -e_count number; -e emp%rowtype; -begin - select count(*) into e_count from emp where job='PRESIDENT1'; - if e_count=0 then - open cu_emp for select * from emp; - else - open cu_emp for select * from emp where job='PRESIDENT'; - end if; - fetch cu_emp into e; - while cu_emp%found loop - dbms_output.put_line('ţ'||e.empno||''||e.ename||'нʣ'||e.sal); - fetch cu_emp into e; - end loop; - close cu_emp; -end; - - -declare type customType is ref cursor; -e_count number; -e emp%rowtype; -s salgrade%rowType; -cType customType; -begin - select count(*) into e_count from emp where job='PRESIDENT1'; - if e_count=0 then - open cType for select * from salgrade; - fetch cType into s; - while cType%found loop - dbms_output.put_line('ȼ'||s.grade||'нʣ'||s.losal||'нʣ'||s.hisal); - fetch cType into s; - end loop; - close cType; - else - open cType for select * from emp where job='PRESIDENT'; - fetch cType into e; - while cType%found loop - dbms_output.put_line('ţ'||e.empno||''||e.ename||'нʣ'||e.sal); - fetch cType into e; - end loop; - close cType; - end if; -end; \ No newline at end of file diff --git a/jun_java_plugins/jun_oracle/oracle_impexp.md b/jun_java_plugins/jun_oracle/oracle_impexp.md deleted file mode 100644 index 72bbf31551..0000000000 --- a/jun_java_plugins/jun_oracle/oracle_impexp.md +++ /dev/null @@ -1,33 +0,0 @@ - -Oracle 版本 11.2.0.1.0 -schema:zhuser -使用expdp导出,用impdp导入 -表空间: -TS_BUSIIDX_PTX -TS_BUSI_PTX -TS_DATA_LOB -TS_DATA_PTX -TS_IDX_PTX - - -create tablespace TS_BUSIIDX_PTX logging datafile 'D:\Oracle\TS_BUSIIDX_PTX.dbf' size 50m autoextend on next 50m ; -create tablespace TS_BUSI_PTX logging datafile 'D:\Oracle\TS_BUSI_PTX.dbf' size 50m autoextend on next 50m ; -create tablespace TS_DATA_LOB logging datafile 'D:\Oracle\TS_DATA_LOB.dbf' size 50m autoextend on next 50m ; -create tablespace TS_DATA_PTX logging datafile 'D:\Oracle\TS_DATA_PTX.dbf' size 50m autoextend on next 50m ; -create tablespace TS_IDX_PTX logging datafile 'D:\Oracle\TS_IDX_PTX.dbf' size 50m autoextend on next 50m ; - - -create user zhuser identified by zhuser default tablespace TS_DATA_PTX temporary tablespace temp; - -grant connect, resource to zhuser; -grant create session to zhuser; -grant create table,create session,create view to zhuser ; - - -grant read,write on directory DATA_FILE_DIR to zhuser; - -create directory dpdata1 as 'd:\Oracle'; -impdp scott/tiger DIRECTORY=dpdata1 DUMPFILE=‪expdp_140507_1450.dmp SCHEMAS=zhuser; - - -impdp system/passsystem directory=dmp_dir dumpfile=user1.dmp REMAP_SCHEMA=user1:user2 \ No newline at end of file diff --git a/jun_java_plugins/jun_oracle/oracle_number.md b/jun_java_plugins/jun_oracle/oracle_number.md deleted file mode 100644 index 0d593e4e72..0000000000 --- a/jun_java_plugins/jun_oracle/oracle_number.md +++ /dev/null @@ -1,33 +0,0 @@ -insert into t_number values(6,23.4564,123556); - -select abs(n1) from t_number; - -select round(n1,2) from t_number; - -select ceil(-12.3) from dual; - -select floor(-12.3) from dual; - -select mod(5,3) from dual; - -select sign(-100) from dual; - -select sqrt(9) from dual; - -select power(2,3) from dual; - -select trunc(123.456,2) from dual; - -123.45 - -select to_char(123.45,'9999.999') from dual; - -select to_char(123123,'99,999,999.99') from dual; - -select to_char(123123.3,'FM99,999,999.99') from dual; - -select to_char(123123.3,'FM$99,999,999.99') from dual; - -select to_char(123123.3,'L99,999,999.99') from dual; - -select to_char(123123.3,'FM99,999,999.99C') from dual; \ No newline at end of file diff --git a/jun_java_plugins/jun_oracle/oracle_package.md b/jun_java_plugins/jun_oracle/oracle_package.md deleted file mode 100644 index a81c30a75f..0000000000 --- a/jun_java_plugins/jun_oracle/oracle_package.md +++ /dev/null @@ -1,64 +0,0 @@ -create package pkg_book as - function getbookcount return number; - function getTableCount(table_name varchar2) return number; - procedure addBook(bookName in varchar2,typeId in number); -end pkg_book; - - -create package body pkg_book as - - function getBookCount return number as - begin - declare book_count number; - begin - select count(*) into book_count from t_book; - return book_count; - end; - end getBookCount; - - - function getTableCount(table_name varchar2) return number as - begin - declare recore_count number; - query_sql varchar2(300); - begin - query_sql:='select count(*) from ' || table_name; - execute immediate query_sql into recore_count; - return recore_count; - end; - end getTableCount; - - - procedure addBook(bookName in varchar2,typeId in number) as - begin - declare maxId number; - begin - select max(id) into maxId from t_book; - insert into t_book values(maxId+1,bookName,typeId); - commit; - end; - end addBook; - - -end pkg_book; - - - -set serveroutput on; -begin - dbms_output.put_line('t_book'|| pkg_book.getBookCount() ||''); -end; - - - -create user TEST identified by 123456 default tablespace users; - -grant create session to TEST; - -alter user TEST account lock; - -alter user TEST account unlock; - -alter user TEST identified by 123; - -drop user TEST cascade; \ No newline at end of file diff --git a/jun_java_plugins/jun_oracle/oracle_plsql.md b/jun_java_plugins/jun_oracle/oracle_plsql.md deleted file mode 100644 index 1c71f7dac4..0000000000 --- a/jun_java_plugins/jun_oracle/oracle_plsql.md +++ /dev/null @@ -1,91 +0,0 @@ -set serverout on; -declare n number:=1; - v varchar2(20):='world'; -begin - dbms_output.put_line('hello'||n||v); -end; - - -set serverout on; -declare emp_count number; -begin - select count(*) into emp_count from emp where sal>=3000; - if emp_count>0 then - dbms_output.put_line(''||emp_count||'ԱĻнʴڵ3000'); - else - dbms_output.put_line('ûԱĻнʴڵ3000'); - end if; -end; - - -set serverout on; -declare emp_count number; -begin - select count(*) into emp_count from emp where sal>=3000; - if emp_count=1 then - dbms_output.put_line('1ԱĻнʴڵ3000'); - else if emp_count>1 then - dbms_output.put_line('г1ԱĻнʴڵ3000'); - else - dbms_output.put_line('ûԱĻнʴڵ3000'); - end if; - end if; -end; - -set serverout on; -declare emp_count number; -begin - select count(*) into emp_count from emp where sal>=3000; - case emp_count - when 0 then dbms_output.put_line('ûԱĻнʴڵ3000'); - when 1 then dbms_output.put_line('1ԱĻнʴڵ3000'); - when 2 then dbms_output.put_line('2ԱĻнʴڵ3000'); - when 3 then dbms_output.put_line('3ԱĻнʴڵ3000'); - else dbms_output.put_line('3ԱĻнʴڵ3000'); - end case; -end; - -set serverout on; -declare g_id number:=2; - g_losal number; - g_hisal number; -begin - loop - if(g_id>4) then - exit; - end if; - - select losal,hisal into g_losal,g_hisal from salgrade where grade=g_id; - dbms_output.put_line(g_id || 'ȼн'|| g_losal || 'нʣ' || g_hisal); - - g_id:=g_id+1; - - end loop; -end; - - -set serverout on; -declare g_id number:=2; - g_losal number; - g_hisal number; -begin - - while g_id<5 loop - - select losal,hisal into g_losal,g_hisal from salgrade where grade=g_id; - dbms_output.put_line(g_id || 'ȼн'|| g_losal || 'нʣ' || g_hisal); - g_id:=g_id+1; - end loop; - -end; - - -set serverout on; -declare g_losal number; - g_hisal number; -begin - for g_id in 2..4 loop - select losal,hisal into g_losal,g_hisal from salgrade where grade=g_id; - dbms_output.put_line(g_id || 'ȼн'|| g_losal || 'нʣ' || g_hisal); - end loop; -end; \ No newline at end of file diff --git a/jun_java_plugins/jun_oracle/oracle_procedure.md b/jun_java_plugins/jun_oracle/oracle_procedure.md deleted file mode 100644 index e156a99938..0000000000 --- a/jun_java_plugins/jun_oracle/oracle_procedure.md +++ /dev/null @@ -1,88 +0,0 @@ -create function getBookCount return number as -begin - declare book_count number; - begin - select count(*) into book_count from t_book; - return book_count; - end; -end getBookCount; - - -set serveroutput on; -begin - dbms_output.put_line('t_book'|| getBookCount() ||''); -end; - - -create function getTableCount(table_name varchar2) return number as -begin - declare recore_count number; - query_sql varchar2(300); - begin - query_sql:='select count(*) from ' || table_name; - execute immediate query_sql into recore_count; - return recore_count; - end; -end getTableCount; - - -begin - dbms_output.put_line(''|| getTableCount('t_bookType') ||''); -end; - - -create procedure addBook(bookName in varchar2,typeId in number) as -begin - declare maxId number; - begin - select max(id) into maxId from t_book; - insert into t_book values(maxId+1,bookName,typeId); - commit; - end; -end addBook; - -execute addBook('javaö',1); - - -create procedure addBook2(bN in varchar2,typeId in number) as -begin - declare maxId number; - n number; - begin - select count(*) into n from t_book where bookName=bN; - if(n>0) then - return; - end if; - select max(id) into maxId from t_book; - insert into t_book values(maxId+1,bN,typeId); - commit; - end; -end addBook2; - -execute addBook2('javaö33',1); - - -create procedure addBook3(bN in varchar2,typeId in number,n1 out number,n2 out number) as -begin - declare maxId number; - n number; - begin - select count(*) into n1 from t_book; - select count(*) into n from t_book where bookName=bN; - if(n>0) then - return; - end if; - select max(id) into maxId from t_book; - insert into t_book values(maxId+1,bN,typeId); - select count(*) into n2 from t_book; - commit; - end; -end addBook3; - -declare n1 number; - n2 number; -begin - addBook3('Ⱥ33223',2,n1,n2); - dbms_output.put_line('n1='||n1); - dbms_output.put_line('n2='||n2); -end; \ No newline at end of file diff --git a/jun_java_plugins/jun_oracle/oracle_role.md b/jun_java_plugins/jun_oracle/oracle_role.md deleted file mode 100644 index 9d1b122002..0000000000 --- a/jun_java_plugins/jun_oracle/oracle_role.md +++ /dev/null @@ -1,68 +0,0 @@ -create user TEST identified by 123456 default tablespace users; - - - - -create user TEST identified by 123456 default tablespace users; - -grant create session to TEST; - -grant create table to TEST; - -select * from dba_sys_privs; - -create user TEST2 identified by 123456 default tablespace users; - -grant create session,create table to TEST with admin option; - -revoke create session,create table from TEST; - -create user TEST2 identified by 123456 default tablespace users; - -grant create session to TEST2; - -grant create table to TEST2; - - - -grant create session to TEST; - -grant create table to TEST; - - -select * from sys.aa ; - -Ȩ - -grant select on AA to TEST; - -update sys.AA set name='Ⱥ'; - -delete from sys.AA ; - -grant all on AA to TEST; - - - -grant select on sys.AA to TEST2; - - -grant select on AA to TEST with grant option; - -select * from dba_tab_privs where grantee='TEST' - - -revoke update on AA from TEST; - - -ɫ -select * from dba_roles; - - -grant select, update,insert ,delete on AA to role_AA; - - -revoke all on AA from TEST,TEST2; - -grant role_AA to TEST; - diff --git a/jun_java_plugins/jun_oracle/oracle_sqltxt.md b/jun_java_plugins/jun_oracle/oracle_sqltxt.md deleted file mode 100644 index f206c72ad3..0000000000 --- a/jun_java_plugins/jun_oracle/oracle_sqltxt.md +++ /dev/null @@ -1,60 +0,0 @@ -select t.*, t.rowid from T_BOOK t - -insert into t_book values(6,'xx7',2); - -delete from t_book where id=6; - -update t_book set bookname='xx4' where id=4; - - - -create trigger tr_book -before insert -on t_book -begin - if user!='cc' then - raise_application_error(-20001,'Ȩ޲'); - end if; -end; - - -create trigger tr_book2 -before update or delete -on t_book -begin - if user!='CC' then - raise_application_error(-20001,'Ȩ޲'); - end if; -end; - -create trigger tr_book_log -after insert or update or delete -on t_book -begin - if updating then - insert into t_book_log values(user,'update',sysdate); - else if inserting then - insert into t_book_log values(user,'insert',sysdate); - else if deleting then - insert into t_book_log values(user,'delete',sysdate); - end if; - end if; - end if; -end; - -create trigger tr_book_add -after insert -on t_book -for each row -begin - update t_booktype set num=num+1 where id=:new.typeId; -end; - -create trigger tr_book_delete -after delete -on t_book -for each row -begin - update t_booktype set num=num-1 where id=:old.typeId; -end; - diff --git a/jun_java_plugins/jun_oracle/oracle_sum.md b/jun_java_plugins/jun_oracle/oracle_sum.md deleted file mode 100644 index 08371c09f7..0000000000 --- a/jun_java_plugins/jun_oracle/oracle_sum.md +++ /dev/null @@ -1,28 +0,0 @@ -select max(sal) from emp ; -select min(sal) from emp ; -select avg(sal) from emp ; -select sum(sal) from emp ; -select count(ename) from emp ; - -select ename,nvl(sal,0) from emp; - -select e.*,rownum from emp e; - - select * from (select a.*,rownum rn from (select * from emp) a where rownum<=10) where rn>5; - - select 2+1 from dual; -select 2-1 from dual; -select 2*1 from dual; -select 2/1 from dual; - -select * from emp where sal between 900 and 1500; - -select * from emp where sal>=900 and sal<=1500; - -select distinct ename from bonus - -select ename,hiredate from emp where ename in (select distinct ename from bonus) - -select * from emp where ename like '%M%' -select * from emp where ename like 'M%' -select * from emp where ename like '_M%' \ No newline at end of file diff --git a/jun_java_plugins/jun_oracle/oracle_to_data2.md b/jun_java_plugins/jun_oracle/oracle_to_data2.md deleted file mode 100644 index 5c8b249ae7..0000000000 --- a/jun_java_plugins/jun_oracle/oracle_to_data2.md +++ /dev/null @@ -1,30 +0,0 @@ -select * from T_DATE t - -select add_months(d1,2) from t_date where id=1; - -select last_day(d1) from t_date where id=1; - -update t_date set d3=to_date('2016-12-20','YYYY-MM-DD') where id=1; - -update t_date set d3=to_date('2016-12-20 18:31:34','YYYY-MM-DD HH24:MI:SS') where id=1; - -select months_between(d1,d3) from t_date where id=1; - -select next_day(d1,2) from t_date where id=1; - -select trunc(d1,'YYYY') from t_date where id=1; -select trunc(d1,'MM') from t_date where id=1; -select trunc(d1,'DD') from t_date where id=1; -select trunc(d1,'HH') from t_date where id=1; -select trunc(d1,'MI') from t_date where id=1; - - -select extract(year from sysdate) from dual; -select extract(month from sysdate) from dual; -select extract(day from sysdate) from dual; -select extract(Hour from systimestamp) from dual; -select extract(minute from systimestamp) from dual; -select extract(second from systimestamp) from dual; - -select to_char(d1,'YYYY-MM-DD') from t_date where id=1; -select to_char(d1,'YYYY-MM-DD HH24:MI:SS') from t_date where id=1; \ No newline at end of file diff --git a/jun_java_plugins/jun_oracle/pom.xml b/jun_java_plugins/jun_oracle/pom.xml deleted file mode 100644 index 2feb0a921d..0000000000 --- a/jun_java_plugins/jun_oracle/pom.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_oracle - 1.0 - jar - - - - - website - scp://webhost.company.com/www/website - - - - UTF-8 - - diff --git a/jun_java_plugins/jun_oracle/src/site/apt/index.apt b/jun_java_plugins/jun_oracle/src/site/apt/index.apt deleted file mode 100644 index 31b624611e..0000000000 --- a/jun_java_plugins/jun_oracle/src/site/apt/index.apt +++ /dev/null @@ -1,18 +0,0 @@ - ----- - Title Here - ----- - Author Here - ----- - Date Here - ----- - -Maven Site for your project - - Congratulations! If you are looking at this page then you have successfully generated a - template site employing the site archetype and you have run: - -+-----+ - -mvn site - -+-----+ diff --git a/jun_java_plugins/jun_oracle/src/site/site.xml b/jun_java_plugins/jun_oracle/src/site/site.xml deleted file mode 100644 index b8d2ed8558..0000000000 --- a/jun_java_plugins/jun_oracle/src/site/site.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - diff --git a/jun_java_plugins/jun_pay/jun_pay_weixin/readme.md b/jun_java_plugins/jun_pay/jun_pay_weixin/readme.md deleted file mode 100644 index 56a6051ca2..0000000000 --- a/jun_java_plugins/jun_pay/jun_pay_weixin/readme.md +++ /dev/null @@ -1 +0,0 @@ -1 \ No newline at end of file diff --git a/jun_java_plugins/jun_pay/jun_pay_zhifubao/readme.md b/jun_java_plugins/jun_pay/jun_pay_zhifubao/readme.md deleted file mode 100644 index 56a6051ca2..0000000000 --- a/jun_java_plugins/jun_pay/jun_pay_zhifubao/readme.md +++ /dev/null @@ -1 +0,0 @@ -1 \ No newline at end of file diff --git a/jun_java_plugins/jun_pay/pom.xml b/jun_java_plugins/jun_pay/pom.xml deleted file mode 100644 index 2d0fd26675..0000000000 --- a/jun_java_plugins/jun_pay/pom.xml +++ /dev/null @@ -1,72 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_pay - 1.0 - jar - - - UTF-8 - 1.8 - 1.8 - - - - - - - - - - junit - junit - 3.8.1 - test - - - javax.servlet - javax.servlet-api - 3.1.0 - provided - - - mysql - mysql-connector-java - 5.1.40 - - - - - - - jdk-1.8 - - true - 1.8 - - - 1.8 - 1.8 - 1.8 - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.0 - - 1.8 - 1.8 - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_pdf/pom.xml b/jun_java_plugins/jun_pdf/pom.xml deleted file mode 100644 index faec1251b7..0000000000 --- a/jun_java_plugins/jun_pdf/pom.xml +++ /dev/null @@ -1,40 +0,0 @@ - - 4.0.0 - io.github.wujun728 - jun_pdf - 1.0 - - - - - com.lowagie - itext - 2.1.7 - - - - com.lowagie - itext-rtf - 2.1.7 - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.1 - - 8 - 8 - UTF-8 - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_pdf/src/main/java/com/jun/plugin/pdf/itext/ReadWord.java b/jun_java_plugins/jun_pdf/src/main/java/com/jun/plugin/pdf/itext/ReadWord.java deleted file mode 100644 index bfa9d0e8f2..0000000000 --- a/jun_java_plugins/jun_pdf/src/main/java/com/jun/plugin/pdf/itext/ReadWord.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.jun.plugin.pdf.itext; - -/** - * @author Wujun - * @since 2013年11月4日 上午10:30:01 - */ -public class ReadWord { - - /** - * @param args - */ - public static void main(String[] args) { - // TODO Auto-generated method stub - - } - -} diff --git a/jun_java_plugins/jun_poi/README.md b/jun_java_plugins/jun_poi/README.md deleted file mode 100644 index 6525575ecc..0000000000 --- a/jun_java_plugins/jun_poi/README.md +++ /dev/null @@ -1,44 +0,0 @@ -# poi-el -excel导出与导入神器,poi-el。 -* poi-el支持强大的excel模板导出功能 -* poi-el支持方便的excel导入API - -## excel模板导出 -使用poi + spEl,支持各种普通模板和复杂模板的导出功能 -### Quick Start: -参考: -com.jun.plugin.poitest.export_test.ForeachTest.java -com.jun.plugin.poitest.export_test.MixTemplateTest.java -com.jun.plugin.poitest.export_test.MultiPoiForeachTest.java - -**API:** -> - PoiExporter.export2Destination(InputStream templateInputStream, Map rootObjectMap, OutputStream des) -**模板示例** - -## 普通模板: -![foreach](img/foreach.png) - -## 复杂模板——多个foreach模板: -![多个foreach](img/多个foreach.jpg) - -## 复杂模板——混合模板: -![混合模板](img/混合模板.jpg) - -## excel模板导入 -支持简洁易用的excel导入API -### Quick Start: -参考: -com.jun.plugin.poitest.import_test.ImportRawTest.java -com.jun.plugin.poitest.import_test.ImportGenericTest.java - -**API** -> - PoiSheetVo sheetVo = PoiImporter.importFirstSheetFrom(is); - -> - PoiGenericSheetVo genericSheetVo = PoiImporter.importFirstSheetFrom(is, OrderImportVo.class); - -# 计划 -1. 后续可以考虑使用MyBatis解析动态SQL的思想,来扩展属性占位符(${}、#{}等)和数据来源(rootObjectMap,可以有多来源),将属性占位符和数据来源解耦 - diff --git a/jun_java_plugins/jun_poi/doc/foreach.png b/jun_java_plugins/jun_poi/doc/foreach.png deleted file mode 100644 index 0008811e12..0000000000 Binary files a/jun_java_plugins/jun_poi/doc/foreach.png and /dev/null differ diff --git a/jun_java_plugins/jun_poi/pom.xml b/jun_java_plugins/jun_poi/pom.xml deleted file mode 100644 index 18d891e936..0000000000 --- a/jun_java_plugins/jun_poi/pom.xml +++ /dev/null @@ -1,207 +0,0 @@ - - 4.0.0 - io.github.wujun728 - jun_poi - 1.0 - war - - - - 3.14 - 4.1.6.RELEASE - 1.7.12 - 1.1.2 - 0.9.9-RC1 - - 1.1.35 - 3.3.2 - 3.2.2 - 15.0 - 2.9.7 - - - - - - - junit - junit - 4.13 - test - - - io.github.wujun728 - jun_datasource - 1.0 - - - org.apache.poi - poi-ooxml - ${poi.version} - - - - - com.alibaba - easyexcel - 1.1.2-beta4 - - - - org.apache.poi - poi - - - org.apache.poi - poi-ooxml - - - org.apache.poi - poi-ooxml-schemas - - - - - - org.springframework - spring-expression - ${spel.version} - provided - - - - org.reflections - reflections - ${reflections.version} - - - - - - org.slf4j - slf4j-api - ${slf4j.version} - - - org.slf4j - jcl-over-slf4j - ${slf4j.version} - - - org.slf4j - log4j-over-slf4j - ${slf4j.version} - - - ch.qos.logback - logback-core - ${logback.version} - test - - - ch.qos.logback - logback-classic - ${logback.version} - test - - - - - - com.alibaba - fastjson - ${fastjson.version} - - - org.apache.commons - commons-lang3 - ${commons.lang3.version} - - - commons-collections - commons-collections - ${commons.collections.version} - - - com.google.guava - guava - ${guava.version} - - - joda-time - joda-time - ${joda.version} - - - - - - com.google.guava - guava - 29.0-jre - - - - org.apache.poi - poi - ${poi.version} - - - org.apache.poi - poi-scratchpad - ${poi.version} - - - - org.apache.commons - commons-lang3 - 3.1 - - - commons-io - commons-io - 2.4 - - - - - javax.servlet - servlet-api - 3.0-alpha-1 - provided - - - - javax.servlet - jstl - 1.2 - - - - - net.sf.json-lib - json-lib - 2.4 - jdk15 - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.1 - - 8 - 8 - UTF-8 - - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poiExp/action/UserAction.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poiExp/action/UserAction.java deleted file mode 100644 index f478c971cd..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poiExp/action/UserAction.java +++ /dev/null @@ -1,131 +0,0 @@ -package com.jun.plugin.poiExp.action; -/* - * package com.java1234.action; - * - * import java.io.File; import java.io.FileInputStream; import - * java.sql.Connection; import java.sql.ResultSet; - * - * import net.sf.json.JSONArray; import net.sf.json.JSONObject; - * - * import org.apache.poi.hssf.usermodel.HSSFRow; import - * org.apache.poi.hssf.usermodel.HSSFSheet; import - * org.apache.poi.hssf.usermodel.HSSFWorkbook; import - * org.apache.poi.poifs.filesystem.POIFSFileSystem; import - * org.apache.poi.ss.usermodel.Workbook; import - * org.apache.struts2.ServletActionContext; - * - * import com.java1234.dao.UserDao; import com.java1234.model.PageBean; import - * com.java1234.model.User; import com.java1234.util.DbUtil; import - * com.java1234.util.ExcelUtil; import com.java1234.util.JsonUtil; import - * com.java1234.util.ResponseUtil; import com.java1234.util.StringUtil; import - * com.opensymphony.xwork2.ActionSupport; - * - * public class UserAction extends ActionSupport { - * - *//** - * - *//* - * private static final long serialVersionUID = 1L; - * - * private String page; private String rows; private String id; private User - * user; private String delId; - * - * private File userUploadFile; - * - * public String getPage() { return page; } public void setPage(String page) { - * this.page = page; } public String getRows() { return rows; } public void - * setRows(String rows) { this.rows = rows; } - * - * public String getDelId() { return delId; } public void setDelId(String delId) - * { this.delId = delId; } public User getUser() { return user; } public void - * setUser(User user) { this.user = user; } - * - * - * public String getId() { return id; } public void setId(String id) { this.id = - * id; } - * - * - * - * - * public File getUserUploadFile() { return userUploadFile; } public void - * setUserUploadFile(File userUploadFile) { this.userUploadFile = - * userUploadFile; } - * - * - * - * - * DbUtil dbUtil=new DbUtil(); UserDao userDao=new UserDao(); - * - * public String list()throws Exception{ Connection con=null; PageBean - * pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(rows)); try{ - * con=dbUtil.getCon(); JSONObject result=new JSONObject(); JSONArray - * jsonArray=JsonUtil.formatRsToJsonArray(userDao.userList(con, pageBean)); int - * total=userDao.userCount(con); result.put("rows", jsonArray); - * result.put("total", total); - * ResponseUtil.write(ServletActionContext.getResponse(),result); - * }catch(Exception e){ e.printStackTrace(); }finally{ try { - * dbUtil.closeCon(con); } catch (Exception e) { // TODO Auto-generated catch - * block e.printStackTrace(); } } return null; } - * - * public String save()throws Exception{ if(StringUtil.isNotEmpty(id)){ - * user.setId(Integer.parseInt(id)); } Connection con=null; try{ - * con=dbUtil.getCon(); int saveNums=0; JSONObject result=new JSONObject(); - * if(StringUtil.isNotEmpty(id)){ saveNums=userDao.userModify(con, user); }else{ - * saveNums=userDao.userAdd(con, user); } if(saveNums>0){ result.put("success", - * "true"); }else{ result.put("success", "true"); result.put("errorMsg", - * "����ʧ��"); } ResponseUtil.write(ServletActionContext.getResponse(), result); - * }catch(Exception e){ e.printStackTrace(); }finally{ try { - * dbUtil.closeCon(con); } catch (Exception e) { // TODO Auto-generated catch - * block e.printStackTrace(); } } return null; } - * - * public String delete()throws Exception{ Connection con=null; try { - * con=dbUtil.getCon(); JSONObject result=new JSONObject(); int - * delNums=userDao.userDelete(con, delId); if(delNums==1){ result.put("success", - * "true"); }else{ result.put("errorMsg", "ɾ��ʧ��"); } - * ResponseUtil.write(ServletActionContext.getResponse(), result); } catch - * (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); - * }finally{ try { dbUtil.closeCon(con); } catch (Exception e) { // TODO - * Auto-generated catch block e.printStackTrace(); } } return null; } - * - * - * public String export()throws Exception{ Connection con=null; try { - * con=dbUtil.getCon(); Workbook wb=new HSSFWorkbook(); String - * headers[]={"���","����","�绰","Email","QQ"}; ResultSet - * rs=userDao.userList(con, null); ExcelUtil.fillExcelData(rs, wb, headers); - * ResponseUtil.export(ServletActionContext.getResponse(), wb, "����excel.xls"); - * } catch (Exception e) { // TODO Auto-generated catch block - * e.printStackTrace(); }finally{ try { dbUtil.closeCon(con); } catch (Exception - * e) { // TODO Auto-generated catch block e.printStackTrace(); } } return null; - * } - * - * public String export2()throws Exception{ Connection con=null; try { - * con=dbUtil.getCon(); ResultSet rs=userDao.userList(con, null); Workbook - * wb=ExcelUtil.fillExcelDataWithTemplate(userDao.userList(con, null), - * "userExporTemplate.xls"); - * ResponseUtil.export(ServletActionContext.getResponse(), wb, - * "����ģ�浼��excel.xls"); } catch (Exception e) { // TODO Auto-generated catch - * block e.printStackTrace(); }finally{ try { dbUtil.closeCon(con); } catch - * (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } - * return null; } - * - * - * public String upload()throws Exception{ POIFSFileSystem fs=new - * POIFSFileSystem(new FileInputStream(userUploadFile)); HSSFWorkbook wb=new - * HSSFWorkbook(fs); HSSFSheet hssfSheet=wb.getSheetAt(0); // ��ȡ��һ��Sheetҳ - * if(hssfSheet!=null){ for(int - * rowNum=1;rowNum<=hssfSheet.getLastRowNum();rowNum++){ HSSFRow - * hssfRow=hssfSheet.getRow(rowNum); if(hssfRow==null){ continue; } User - * user=new User(); user.setName(ExcelUtil.formatCell(hssfRow.getCell(0))); - * user.setPhone(ExcelUtil.formatCell(hssfRow.getCell(1))); - * user.setEmail(ExcelUtil.formatCell(hssfRow.getCell(2))); - * user.setQq(ExcelUtil.formatCell(hssfRow.getCell(3))); Connection con=null; - * try{ con=dbUtil.getCon(); userDao.userAdd(con, user); }catch(Exception e){ - * e.printStackTrace(); }finally{ dbUtil.closeCon(con); } } } JSONObject - * result=new JSONObject(); result.put("success", "true"); - * ResponseUtil.write(ServletActionContext.getResponse(), result); return null; - * } - * - * - * - * } - */ \ No newline at end of file diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poiExp/dao/UserDao.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poiExp/dao/UserDao.java deleted file mode 100644 index ebc5fe6512..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poiExp/dao/UserDao.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.jun.plugin.poiExp.dao; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; - -import com.jun.plugin.poiExp.model.PageBean; -import com.jun.plugin.poiExp.model.User; - -public class UserDao { - - public ResultSet userList(Connection con,PageBean pageBean)throws Exception{ - StringBuffer sb=new StringBuffer("select * from t_user"); - if(pageBean!=null){ - sb.append(" limit ?,?"); - } - PreparedStatement pstmt=con.prepareStatement(sb.toString()); - if(pageBean!=null){ - pstmt.setInt(1, pageBean.getStart()); - pstmt.setInt(2, pageBean.getRows()); - } - return pstmt.executeQuery(); - } - - public int userCount(Connection con)throws Exception{ - String sql="select count(*) as total from t_user"; - PreparedStatement pstmt=con.prepareStatement(sql); - ResultSet rs=pstmt.executeQuery(); - if(rs.next()){ - return rs.getInt("total"); - }else{ - return 0; - } - } - - public int userDelete(Connection con,String delId)throws Exception{ - String sql="delete from t_user where id=?"; - PreparedStatement pstmt=con.prepareStatement(sql); - pstmt.setString(1, delId); - return pstmt.executeUpdate(); - } - - public int userAdd(Connection con,User user)throws Exception{ - String sql="insert into t_user values(null,?,?,?,?)"; - PreparedStatement pstmt=con.prepareStatement(sql); - pstmt.setString(1, user.getName()); - pstmt.setString(2, user.getPhone()); - pstmt.setString(3, user.getEmail()); - pstmt.setString(4, user.getQq()); - return pstmt.executeUpdate(); - } - - public int userModify(Connection con,User user)throws Exception{ - String sql="update t_user set name=?,phone=?,email=?,qq=? where id=?"; - PreparedStatement pstmt=con.prepareStatement(sql); - pstmt.setString(1, user.getName()); - pstmt.setString(2, user.getPhone()); - pstmt.setString(3, user.getEmail()); - pstmt.setString(4, user.getQq()); - pstmt.setInt(5,user.getId()); - return pstmt.executeUpdate(); - } -} diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poiExp/model/PageBean.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poiExp/model/PageBean.java deleted file mode 100644 index bbfcc98b2b..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poiExp/model/PageBean.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.jun.plugin.poiExp.model; - -public class PageBean { - - private int page; // �ڼ�ҳ - private int rows; // ÿҳ�ļ�¼�� - private int start; // ��ʼҳ - - public PageBean(int page, int rows) { - super(); - this.page = page; - this.rows = rows; - } - public int getPage() { - return page; - } - public void setPage(int page) { - this.page = page; - } - public int getRows() { - return rows; - } - public void setRows(int rows) { - this.rows = rows; - } - - public int getStart() { - return (page-1)*rows; - } - - - -} diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poiExp/model/User.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poiExp/model/User.java deleted file mode 100644 index 1b0f16afe9..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poiExp/model/User.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.jun.plugin.poiExp.model; - -public class User { - - private int id; - private String name; - private String phone; - private String email; - private String qq; - - public User() { - } - - public User(String name, String phone, String email, String qq) { - this.name = name; - this.phone = phone; - this.email = email; - this.qq = qq; - } - - public int getId() { - return id; - } - public void setId(int id) { - this.id = id; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public String getEmail() { - return email; - } - public void setEmail(String email) { - this.email = email; - } - public String getQq() { - return qq; - } - public void setQq(String qq) { - this.qq = qq; - } - public String getPhone() { - return phone; - } - public void setPhone(String phone) { - this.phone = phone; - } - - -} diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poiExp/template/userExporTemplate.xls b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poiExp/template/userExporTemplate.xls deleted file mode 100644 index ed357eb2c8..0000000000 Binary files a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poiExp/template/userExporTemplate.xls and /dev/null differ diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poiExp/util/DbUtil.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poiExp/util/DbUtil.java deleted file mode 100644 index 398fea9db8..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poiExp/util/DbUtil.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.jun.plugin.poiExp.util; - -import java.sql.Connection; -import java.sql.DriverManager; - -public class DbUtil { - - private String dbUrl="jdbc:mysql://localhost:3306/db_test?useUnicode=true&characterEncoding=utf-8"; - private String dbUserName="root"; - private String dbPassword=""; - private String jdbcName="com.mysql.jdbc.Driver"; - - public Connection getCon()throws Exception{ - Class.forName(jdbcName); - Connection con=DriverManager.getConnection(dbUrl,dbUserName,dbPassword); - return con; - } - - public void closeCon(Connection con)throws Exception{ - if(con!=null){ - con.close(); - } - } -} diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poiExp/util/ExcelUtil.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poiExp/util/ExcelUtil.java deleted file mode 100644 index bde71dca5b..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poiExp/util/ExcelUtil.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.jun.plugin.poiExp.util; - -import java.io.InputStream; -import java.sql.ResultSet; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; - -public class ExcelUtil { - - public static void fillExcelData(ResultSet rs,Workbook wb,String[] headers)throws Exception{ - int rowIndex=0; - Sheet sheet=wb.createSheet(); - Row row=sheet.createRow(rowIndex++); - for(int i=0;i"; - public static final String POI_FOREACH_END_REGEXP = ""; - - public static final String POI_PROPERTY_START_REGEXP = ""; - public static final String POI_PROPERTY_END_REGEXP = ""; - - // 处理类似${key}的串 - public static final String POI_KEY_REGEXP = "\\$\\{(\\w+)\\}"; - // 处理类似${vo.key}的串 - public static final String POI_VO_DOT_KEY_REGEXP = "\\$(\\{)(\\w+\\.)(.+?\\})"; -} diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/common/PoiUtils.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/common/PoiUtils.java deleted file mode 100644 index 91ac4cc7cb..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/common/PoiUtils.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.jun.plugin.poitest.common; - -import java.math.BigDecimal; -import java.sql.Date; - -import org.joda.time.DateTime; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; - -/** -* @author wzy -* @date 2017年7月12日 下午12:53:34 -*/ -public class PoiUtils { - - @SuppressWarnings("unchecked") - public static T parse2Type(Object value, Class type){ - if(String.class.isAssignableFrom(type)){ - return (T) value.toString(); - } - - if(isPrimitiveOrWrapClass(type)){ - String className = type.getName(); - switch (className) { - case "java.lang.Boolean": - case "boolean": - return (T) Boolean.valueOf(value.toString()); - case "java.lang.Character": - case "char": - return (T) Character.valueOf(value.toString().charAt(0)); - case "java.lang.Byte": - case "byte": - return (T) Byte.valueOf(value.toString()); - case "java.lang.Short": - case "short": - return (T) Short.valueOf(value.toString()); - case "java.lang.Integer": - case "int": - return (T) Integer.valueOf(value.toString()); - case "java.lang.Long": - case "long": - return (T) Long.valueOf(value.toString()); - case "java.lang.Float": - case "float": - return (T) Float.valueOf(value.toString()); - case "java.lang.Double": - case "double": - return (T) Double.valueOf(value.toString()); - default: - throw new RuntimeException(className + "不支持,bug"); - } - } - - if(Date.class.isAssignableFrom(type)){ - // TODO - DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); - return (T) DateTime.parse(value.toString(), formatter); - } - - if(BigDecimal.class.isAssignableFrom(type)){ - return (T) new BigDecimal(value.toString()); - } - - throw new RuntimeException("不支持的类型:" + type.getName()); - } - - - /** - * 决断clz是否是基本类型 或者 基本类型的包装类型 - * @param clz - * @return - */ - public static boolean isPrimitiveOrWrapClass(Class clz){ - if(clz.isPrimitive()){ - return true; - } - - return isWrapClass(clz); - } - - public static boolean isWrapClass(Class clz) { - try { - return ((Class) clz.getField("TYPE").get(null)).isPrimitive(); - } catch (Exception e) { - return false; - } - } - -} diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/common/ReflectionUtil.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/common/ReflectionUtil.java deleted file mode 100644 index 5b9f71043b..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/common/ReflectionUtil.java +++ /dev/null @@ -1,296 +0,0 @@ -package com.jun.plugin.poitest.common; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; - -/** - *

Utility class that uses {@code java.lang.reflect} standard library. - * It provides easy access to the standard reflect methods that are - * needed usually when dealing with generic object types.

- * - *
- * ReflectionUtil中包含以下几种功能:
-	通过Type获取对象class;
-	通过Type创建对象;
-	获取泛型对象的泛型化参数;
-	检查对象是否存在默认构造函数;
-	获取指定类型中的特定field类型;
-	获取指定类型中的特定method返回类型;
-	根据字符串标示获取枚举常量;
- * 
- * - * @author Qussay Najjar - * - * @version 1.0 - * @since 2013-09-27 - * - * @version 1.1 - * @since 2014-04-13 - * - * @link http://qussay.com/2013/09/28/handling-java-generic-types-with-reflection - * @link http://www.cnblogs.com/whitewolf/p/4355541.html - */ -public class ReflectionUtil { - - /** - * When {@code Type} initialized with a value of an object, its fully qualified class name - * will be prefixed with this. - * - * @see {@link ReflectionUtil#getClassName(Type)} - */ - private static final String TYPE_CLASS_NAME_PREFIX = "class "; - private static final String TYPE_INTERFACE_NAME_PREFIX = "interface "; - - /* - * Utility class with static access methods, no need for constructor. - */ - private ReflectionUtil() {} - - /** - * {@link Type#toString()} value is the fully qualified class name prefixed - * with {@link ReflectionUtil#TYPE_NAME_PREFIX}. This method will substring it, for it to be eligible - * for {@link Class#forName(String)}. - * - * @param type the {@code Type} value whose class name is needed. - * @return {@code String} class name of the invoked {@code type}. - * - * @see {@link ReflectionUtil#getClass()} - */ - public static String getClassName(Type type) { - if (type==null) { - return ""; - } - String className = type.toString(); - if (className.startsWith(TYPE_CLASS_NAME_PREFIX)) { - className = className.substring(TYPE_CLASS_NAME_PREFIX.length()); - } else if (className.startsWith(TYPE_INTERFACE_NAME_PREFIX)) { - className = className.substring(TYPE_INTERFACE_NAME_PREFIX.length()); - } - return className; - } - - /** - * Returns the {@code Class} object associated with the given {@link Type} - * depending on its fully qualified name. - * - * @param type the {@code Type} whose {@code Class} is needed. - * @return the {@code Class} object for the class with the specified name. - * - * @throws ClassNotFoundException if the class cannot be located. - * - * @see {@link ReflectionUtil#getClassName(Type)} - */ - public static Class getClass(Type type) - throws ClassNotFoundException { - String className = getClassName(type); - if (className==null || className.isEmpty()) { - return null; - } - return Class.forName(className); - } - - /** - * Creates a new instance of the class represented by this {@code Type} object. - * - * @param type the {@code Type} object whose its representing {@code Class} object - * will be instantiated. - * @return a newly allocated instance of the class represented by - * the invoked {@code Type} object. - * - * @throws ClassNotFoundException if the class represented by this {@code Type} object - * cannot be located. - * @throws InstantiationException if this {@code Type} represents an abstract class, - * an interface, an array class, a primitive type, or void; - * or if the class has no nullary constructor; - * or if the instantiation fails for some other reason. - * @throws IllegalAccessException if the class or its nullary constructor is not accessible. - * - * @see {@link Class#newInstance()} - */ - public static Object newInstance(Type type) - throws ClassNotFoundException, InstantiationException, IllegalAccessException { - Class clazz = getClass(type); - if (clazz==null) { - return null; - } - return clazz.newInstance(); - } - - /** - * Returns an array of {@code Type} objects representing the actual type - * arguments to this object. - * If the returned value is null, then this object represents a non-parameterized - * object. - * - * @param object the {@code object} whose type arguments are needed. - * @return an array of {@code Type} objects representing the actual type - * arguments to this object. - * - * @see {@link Class#getGenericSuperclass()} - * @see {@link ParameterizedType#getActualTypeArguments()} - */ - public static Type[] getParameterizedTypes(Object object) { - Type superclassType = object.getClass().getGenericSuperclass(); - if (!ParameterizedType.class.isAssignableFrom(superclassType.getClass())) { - return null; - } - - return ((ParameterizedType)superclassType).getActualTypeArguments(); - } - - public static Type[] getParameterizedTypes(Class clazz) { - Type superclassType = clazz.getGenericSuperclass(); - if (!ParameterizedType.class.isAssignableFrom(superclassType.getClass())) { - return null; - } - - return ((ParameterizedType)superclassType).getActualTypeArguments(); - } - - /** - * Checks whether a {@code Constructor} object with no parameter types is specified - * by the invoked {@code Class} object or not. - * - * @param clazz the {@code Class} object whose constructors are checked. - * @return {@code true} if a {@code Constructor} object with no parameter types is specified. - * @throws SecurityException If a security manager, s is present and any of the - * following conditions is met: - *
    - *
  • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.PUBLIC)} denies - * access to the constructor - * - *
  • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class - *
- * - * @see {@link Class#getConstructor(Class...)} - */ - public static boolean hasDefaultConstructor(Class clazz) throws SecurityException { - Class[] empty = {}; - try { - clazz.getConstructor(empty); - } catch (NoSuchMethodException e) { - return false; - } - return true; - } - - /** - * Returns a {@code Class} object that identifies the - * declared class for the field represented by the given {@code String name} parameter inside - * the invoked {@code Class clazz} parameter. - * - * @param clazz the {@code Class} object whose declared fields to be - * checked for a certain field. - * @param name the field name as {@code String} to be - * compared with {@link Field#getName()} - * @return the {@code Class} object representing the type of given field name. - * - * @see {@link Class#getDeclaredFields()} - * @see {@link Field#getType()} - */ - public static Class getFieldClass(Class clazz, String name) { - if (clazz==null || name==null || name.isEmpty()) { - return null; - } - - Class propertyClass = null; - - for (Field field : clazz.getDeclaredFields()) { - field.setAccessible(true); - if (field.getName().equalsIgnoreCase(name)) { - propertyClass = field.getType(); - break; - } - } - - return propertyClass; - } - - /** - * Returns a {@code Class} object that identifies the - * declared class as a return type for the method represented by the given - * {@code String name} parameter inside the invoked {@code Class clazz} parameter. - * - * @param clazz the {@code Class} object whose declared methods to be - * checked for the wanted method name. - * @param name the method name as {@code String} to be - * compared with {@link Method#getName()} - * @return the {@code Class} object representing the return type of the given method name. - * - * @see {@link Class#getDeclaredMethods()} - * @see {@link Method#getReturnType()} - */ - public static Class getMethodReturnType(Class clazz, String name) { - if (clazz==null || name==null || name.isEmpty()) { - return null; - } - - name = name.toLowerCase(); - Class returnType = null; - - for (Method method : clazz.getDeclaredMethods()) { - if (method.getName().equals(name)) { - returnType = method.getReturnType(); - break; - } - } - - return returnType; - } - - /** - * Extracts the enum constant of the specified enum class with the - * specified name. The name must match exactly an identifier used - * to declare an enum constant in the given class. - * - * @param clazz the {@code Class} object of the enum type from which - * to return a constant. - * @param name the name of the constant to return. - * @return the enum constant of the specified enum type with the - * specified name. - * - * @throws IllegalArgumentException if the specified enum type has - * no constant with the specified name, or the specified - * class object does not represent an enum type. - * - * @see {@link Enum#valueOf(Class, String)} - */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - public static Object getEnumConstant(Class clazz, String name) { - if (clazz==null || name==null || name.isEmpty()) { - return null; - } - return Enum.valueOf((Class)clazz, name); - } - - /** - * 决断clz是否是基本类型 或者 基本类型的包装类型 - * @param clz - * @return - */ - public static boolean isPrimitiveOrWrapClass(Class clz){ - if(clz.isPrimitive()){ - return true; - } - - return isWrapClass(clz); - } - - public static boolean isWrapClass(Class clz) { - try { - return ((Class) clz.getField("TYPE").get(null)).isPrimitive(); - } catch (Exception e) { -// e.printStackTrace(); - return false; - } - } - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exception/IErrors.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exception/IErrors.java deleted file mode 100644 index c310ae31f1..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exception/IErrors.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.jun.plugin.poitest.exception; - -/** - * 错误枚举的接口类 - * - */ -public interface IErrors { - - /** - * 采用枚举中定义的message作为异常的信息 - * - * @return - */ - public PoiElException exp(); - - /** - * 采用枚举中定义的message作为异常信息,并传递一些参数 - * - * @param args - * 参数列表 - * @return - */ - public PoiElException exp(Object... args); - - /** - * 采用枚举中定义的message作为异常信息,并传递一些参数,支持传入底层的异常 - * - * @param cause - * 原始异常 - * @param args - * 参数列表 - * @return - */ - public PoiElException exp(Throwable cause, Object... args); - - /** - * 采用枚举中定义的code,使用自定义的message作为异常信息,并可能会带上一些参数 - * - * @param message - * 错误信息 - * @param args - * 具体参数列表 - * @return - */ - public PoiElException expMsg(String message, Object... args); - - /** - * 采用枚举中定义的code,使用自定义的message作为异常信息,并可能会带上一些参数,并自持传入底层的异常 - * - * @param message - * 错误信息 - * @param cause - * 原始异常 - * @param args - * 具体参数列表 - * @return - */ - public PoiElException expMsg(String message, Throwable cause, Object... args); -} diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exception/PoiElErrorCode.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exception/PoiElErrorCode.java deleted file mode 100644 index c1df76c8fb..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exception/PoiElErrorCode.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.jun.plugin.poitest.exception; - -import java.text.MessageFormat; - -/** - * 异常码区段:[1001-1999] -* @author wzy -* @date 2017年6月20日 上午11:59:32 -*/ -public enum PoiElErrorCode implements IErrors { - TAG_NOT_FOUND(1001, "[{0}]中找不到tag:[{1}]"), - TEMPLATE_FILE_NOT_FOUND(1002, "找不到模板[{0}]"), - EXCEL_FILE_NOT_FOUND(1003, "找不到被导入的excel[{0}]"), - /**-----------------COMMON ERROR--------------------*/ - SYSTEM_ERROR(1998, "系统错误"), - ILLEGAL_PARAM(1999, "参数异常:{0}"); - - - private int code; - private String msg; - - private PoiElErrorCode(int code, String msg) { - this.code = code; - this.msg = msg; - } - - public int getCode() { - return code; - } - - public void setCode(int code) { - this.code = code; - } - - public String getMsg() { - return msg; - } - - public void setMsg(String msg) { - this.msg = msg; - } - - - @Override - public PoiElException exp() { - return new PoiElException(code, msg); - } - - @Override - public PoiElException exp(Object... args) { - return new PoiElException(code, MessageFormat.format(msg, args)); - } - - @Override - public PoiElException exp(Throwable cause, Object... args) { - return new PoiElException(code, MessageFormat.format(msg, args), cause); - } - - @Override - public PoiElException expMsg(String message, Object... args) { - return new PoiElException(code, MessageFormat.format(message, args)); - } - - @Override - public PoiElException expMsg(String message, Throwable cause, Object... args) { - return new PoiElException(code, MessageFormat.format(message, args), cause); - } - -} diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exception/PoiElException.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exception/PoiElException.java deleted file mode 100644 index 31b8c024da..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exception/PoiElException.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.jun.plugin.poitest.exception; -/** -* @author wzy -* @date 2017年6月20日 上午11:53:59 -*/ -public class PoiElException extends RuntimeException { - private static final long serialVersionUID = 1L; - - /** - * 异常错误码 - */ - protected int code; - - public PoiElException(int code, String message) { - super(message); - this.code = code; - } - - public PoiElException(int code, String message, Throwable cause) { - super(message, cause); - this.code = code; - } -} diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exp/PoiExporter.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exp/PoiExporter.java deleted file mode 100644 index 23a0785f61..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exp/PoiExporter.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.jun.plugin.poitest.exp; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Map; - -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.expression.spel.standard.SpelExpressionParser; - -import com.jun.plugin.poitest.exception.PoiElErrorCode; -import com.jun.plugin.poitest.exp.context.PoiExporterContext; -import com.jun.plugin.poitest.exp.function.FunctionRegister; -import com.jun.plugin.poitest.exp.processor.RowProcessorStrategy; -import com.jun.plugin.poitest.log.Log; - -/** - * excel导出类 - * @author wzy - * @date 2017年7月5日 上午9:41:52 - */ -public class PoiExporter { - private static final Logger logger = LoggerFactory.getLogger(PoiExporter.class); - - /** - * 向StandardEvaluationContext中注册内部函数 - */ - static { - FunctionRegister.registerInternalFunction(); - } - - public static void export(XSSFWorkbook wb, Map rootObjectMap) { - Long start = System.currentTimeMillis(); - - PoiExporterContext peContext = new PoiExporterContext(new SpelExpressionParser(), rootObjectMap); - - // 分sheet进行处理 - for (int i = 0; i < wb.getNumberOfSheets(); i++) { - XSSFSheet sheet = wb.getSheetAt(i); - // 开始行结束行 - int j = sheet.getFirstRowNum(); - // 每行 - while (j <= sheet.getLastRowNum()) { - XSSFRow row = sheet.getRow(j); - if (row == null) { - continue; - } - int dealRows = RowProcessorStrategy.getRowProcessor(row).dealRow(row, peContext); - j = j + dealRows; - } - } - - long end = System.currentTimeMillis(); - - logger.info(Log.op("PoiEl#parse").msg("PoiEl解析模板耗时[{0}]ms", (end - start)).toString()); - } - - /** - * 导出到指定地方 des - * @param templateFile - * @param rootObjectMap - * @param des - * @return - */ - public static XSSFWorkbook export2Destination(File templateFile, Map rootObjectMap, OutputStream des){ - InputStream in = null; - try { - in = new FileInputStream(templateFile); - } catch (FileNotFoundException e) { - throw PoiElErrorCode.TEMPLATE_FILE_NOT_FOUND.exp(e, templateFile.getName()); - } - return export2Destination(in, rootObjectMap, des); - } - - /** - * 导出到指定地方 des - * @param templateInputStream 模板 - * @param rootObjectMap 数据 - * @param des 导出的位置 - * @return - */ - public static XSSFWorkbook export2Destination(InputStream templateInputStream, Map rootObjectMap, OutputStream des){ - XSSFWorkbook wb = null; - try { - wb = new XSSFWorkbook(templateInputStream); - } catch (IOException e) { - throw PoiElErrorCode.SYSTEM_ERROR.exp(e); - } - PoiExporter.export(wb, rootObjectMap); - - // 关闭资源 - try { - wb.write(des); - des.flush(); - des.close(); - } catch (IOException e) { - throw PoiElErrorCode.SYSTEM_ERROR.exp(e); - } - - return wb; - } -} diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exp/context/PoiExporterContext.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exp/context/PoiExporterContext.java deleted file mode 100644 index 9839e6f763..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exp/context/PoiExporterContext.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.jun.plugin.poitest.exp.context; - -import java.util.Map; - -import org.springframework.expression.spel.standard.SpelExpressionParser; -import org.springframework.expression.spel.support.StandardEvaluationContext; - -/** - * 上下文 - * - * @author wzy - * @date 2017年7月11日 下午7:54:10 - */ -public class PoiExporterContext { - private SpelExpressionParser spelExpParser; - public static final StandardEvaluationContext EVAL_CONTEXT = new StandardEvaluationContext(); - private Map rootObjectMap; - - public PoiExporterContext() { - super(); - } - - public PoiExporterContext(SpelExpressionParser spelExpressionParser, Map rootObjectMap) { - this.spelExpParser = spelExpressionParser; - this.rootObjectMap = rootObjectMap; - } - - public SpelExpressionParser getSpelExpParser() { - return spelExpParser; - } - - public Map getRootObjectMap() { - return rootObjectMap; - } - -} diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exp/domain/MutiRowModel.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exp/domain/MutiRowModel.java deleted file mode 100644 index cccf0c7fb3..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exp/domain/MutiRowModel.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.jun.plugin.poitest.exp.domain; - -import java.util.Map; - -public class MutiRowModel { - private Integer begin; // 开始行(相对于模板) - private Integer end; // 结束行(相对于模板) - private String listKey; // 循环标签取数据的key -// 第一个Integer:行号 第二个Integer:单元列号 Object:单元格里面的值 - private Map> cellMap; // 存放需要循环的行里面的模板值 - - public Integer getBegin() { - return begin; - } - public void setBegin(Integer begin) { - this.begin = begin; - } - public Integer getEnd() { - return end; - } - public void setEnd(Integer end) { - this.end = end; - } - public String getListKey() { - return listKey; - } - public void setListKey(String listKey) { - this.listKey = listKey; - } - public Map> getCellMap() { - return cellMap; - } - public void setCellMap(Map> cellMap) { - this.cellMap = cellMap; - } - -} diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exp/function/FunctionRegister.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exp/function/FunctionRegister.java deleted file mode 100644 index 46f2dfa225..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exp/function/FunctionRegister.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.jun.plugin.poitest.exp.function; - -import java.lang.reflect.Method; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.jun.plugin.poitest.exp.context.PoiExporterContext; - -/** - * 函数注册器 - * @author wzy - * @date 2017年7月11日 下午7:57:23 - */ -public class FunctionRegister { - private static final Logger logger = LoggerFactory.getLogger(FunctionRegister.class); - - public static void registerInternalFunction(){ - Method[] methods = InternalUtils.class.getDeclaredMethods(); - logger.info("|----------PoiEl注册的内部函数------------|"); - for(Method m : methods){ - String funName = m.getName(); - logger.info("|-----------" + funName + "------------------|"); - PoiExporterContext.EVAL_CONTEXT.registerFunction(funName, m); - } - logger.info("|------------------------------------|"); - } -} diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exp/function/InternalUtils.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exp/function/InternalUtils.java deleted file mode 100644 index deca4db122..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exp/function/InternalUtils.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.jun.plugin.poitest.exp.function; - -import java.util.Date; - -import org.joda.time.DateTime; - -/** - *
- * 内部函数库,使用EL表达式在excel模板中调用。
- * 示例:
- *  #{ T(com.kvn.poi.function.InternalUtils).fmtDate(beginTime,'yyyy-MM-dd') }
- * 
- * - * @author wzy - * @date 2017年7月6日 下午5:47:03 - */ -public class InternalUtils { - - /** - * 日期格式化 - * - * @param date - * @param pattern - * @return - */ - public static String fmtDate(Date date, String pattern) { - DateTime dt = new DateTime(date.getTime()); - return dt.toString(pattern); - } - -} diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exp/processor/DefaultRowProcessor.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exp/processor/DefaultRowProcessor.java deleted file mode 100644 index 4db691e830..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exp/processor/DefaultRowProcessor.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.jun.plugin.poitest.exp.processor; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.expression.EvaluationException; -import org.springframework.expression.ParseException; -import org.springframework.expression.common.TemplateParserContext; - -import com.jun.plugin.poitest.common.Constants; -import com.jun.plugin.poitest.exp.context.PoiExporterContext; -import com.jun.plugin.poitest.log.Log; - -/** - * 默认的行处理器。单元格内容中含有${key}的进行替换,否则不处理 - * - * @author wzy - */ -public class DefaultRowProcessor implements RowProcessor { - private static final Logger logger = LoggerFactory.getLogger(DefaultRowProcessor.class); - - public static class SINGLE { - public static DefaultRowProcessor INSTANCE = new DefaultRowProcessor(); - } - - @Override - public int support(XSSFRow row) { - return 0; - } - - @Override - public int dealRow(XSSFRow currentRow, PoiExporterContext peContext) { - for (int i = 0; i < currentRow.getLastCellNum(); i++) { - XSSFCell cell = currentRow.getCell(i); - if (null != cell && cell.getCellType() == XSSFCell.CELL_TYPE_STRING) { - String cellContent = cell.getStringCellValue(); - String resolvedContent = resolve(cellContent, peContext); - cell.setCellValue(resolvedContent); - } - - } - return 1; - } - - /** - * 将带有${key}和${vo.key}的内容进行替换 - * - * @param cellContent - * @param rootObjectMap - * @param parser - * @return - */ - public static String resolve(String cellContent, PoiExporterContext peContext) { - String resolvedContent = cellContent; - Pattern pattern = Pattern.compile(Constants.POI_KEY_REGEXP); - // 处理${key} - for (Matcher matcher = pattern.matcher(resolvedContent); matcher.find(); matcher = pattern.matcher(resolvedContent)) { - String key = matcher.group(1); - String value = (String) peContext.getRootObjectMap().get(key); - resolvedContent = matcher.replaceFirst(value); - } - - // 处理${vo.key} - pattern = Pattern.compile(Constants.POI_VO_DOT_KEY_REGEXP); - try { - for (Matcher matcher = pattern.matcher(resolvedContent); matcher.find(); matcher = pattern.matcher(resolvedContent)) { - String vo = matcher.group(2); - vo = vo.substring(0, vo.length()-1); - Object rootObjectItem = peContext.getRootObjectMap().get(vo); - String expression = matcher.replaceFirst("#$1$3"); // 转换成EL - String resolvedKey = peContext.getSpelExpParser().parseExpression(expression, new TemplateParserContext()).getValue(peContext.EVAL_CONTEXT, rootObjectItem, String.class); - resolvedContent = resolvedKey; // 替换内容 - } - } catch (EvaluationException | ParseException e) { - logger.error(Log.op("DefaultRowProcessor#resolve").msg("EL解析出错").toString(), e); - } - return resolvedContent; - } - -} diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exp/processor/ForeachRowProcessor.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exp/processor/ForeachRowProcessor.java deleted file mode 100644 index b63613aa04..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exp/processor/ForeachRowProcessor.java +++ /dev/null @@ -1,218 +0,0 @@ -package com.jun.plugin.poitest.exp.processor; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.expression.EvaluationException; -import org.springframework.expression.Expression; -import org.springframework.expression.common.TemplateParserContext; - -import com.jun.plugin.poitest.common.Constants; -import com.jun.plugin.poitest.exception.PoiElErrorCode; -import com.jun.plugin.poitest.exp.context.PoiExporterContext; -import com.jun.plugin.poitest.exp.domain.MutiRowModel; -import com.jun.plugin.poitest.log.Log; - -/** - * 的处理器 - * @author wzy - * - */ -public class ForeachRowProcessor implements RowProcessor { - private static final Logger logger = LoggerFactory.getLogger(ForeachRowProcessor.class); - - @Override - public int dealRow(XSSFRow currentRow, PoiExporterContext peContext) { - XSSFCell beginCell = currentRow.getCell(support(currentRow)); - - // 从beginCell中找出list key - String beginCellContent = beginCell.getStringCellValue(); - Matcher ma = Pattern.compile(Constants.POI_FOREACH_START_REGEXP).matcher(beginCellContent); - String key = null; - if (ma.find()) { - key = ma.group(1).trim(); - } else { - throw PoiElErrorCode.TAG_NOT_FOUND.exp(beginCellContent, Constants.POI_FOREACH_START_REGEXP); - } - - MutiRowModel tpRow = new MutiRowModel(); - tpRow.setListKey(key); - tpRow.setBegin(beginCell.getRowIndex()); - Map> cellMap = new TreeMap<>(); - int beginRowNum = beginCell.getRow().getRowNum(); - Pattern prePattern = Pattern.compile(Constants.POI_FOREACH_START_REGEXP); - Pattern postPattern = Pattern.compile(Constants.POI_FOREACH_END_REGEXP); - while (beginRowNum <= beginCell.getSheet().getLastRowNum() && null == tpRow.getEnd()) { - XSSFRow row = beginCell.getSheet().getRow(beginRowNum); - if (row == null) { - // throw new Exception(); - } - Map map = new HashMap<>(); - short end = row.getLastCellNum(); - for (int k = 0; k <= end; k++) { - XSSFCell cell = row.getCell(k); - if (null == cell) { - continue; - } - String cellValue = cell.getRichStringCellValue().getString().trim(); - if (cellValue.equals("")) { - continue; - } - String value = cellValue; - Matcher preMatcher = prePattern.matcher(cellValue); - if (preMatcher.find()) { - value = preMatcher.replaceAll(""); - } - Matcher postMatcher = postPattern.matcher(cellValue); - if (postMatcher.find()) { - value = postMatcher.replaceAll(""); - tpRow.setEnd(beginRowNum); - } - // 存放<单元格列号, 单元格内容>。单元格内容是除去tag之外的 - map.put(k, value); - } - cellMap.put(beginRowNum, map); - beginRowNum++; - } - tpRow.setCellMap(cellMap); - - Object rootObject = peContext.getRootObjectMap().get(key); - if(!(rootObject instanceof List)){ - throw PoiElErrorCode.ILLEGAL_PARAM.exp("中list:" + key + "对应的值应该为List"); - } - - List ls = (List) rootObject; - - // transfer - setMutiData(beginCell, ls, tpRow, peContext); - - return ls.size() * (tpRow.getEnd() - tpRow.getBegin() + 1); - } - - /** - * 进行拷贝和赋值 - * @param cell - * @param ls - * @param tpRow - * @param parser - */ - private static void setMutiData(XSSFCell cell, List ls, MutiRowModel tpRow, PoiExporterContext peContext) { - XSSFSheet sheet = cell.getSheet(); - int mutiRow = tpRow.getEnd() - tpRow.getBegin() + 1; // 循环的行数 - // 行往下移 - sheet.shiftRows(tpRow.getEnd() + 1, sheet.getLastRowNum() + 3, (ls.size() - 1) * mutiRow, true, false); - - Map> cellMap = tpRow.getCellMap(); - - for (int i = 0; i < ls.size(); i++) { - Object rootObjectItem = ls.get(i); - for (Integer key1 : cellMap.keySet()) { // key1为row行号 - XSSFRow curRow = null; - if (i == 0) { - curRow = sheet.getRow(key1); - } else { - curRow = sheet.createRow(i * mutiRow + key1); - // 拷贝样式 - copyCellStyle(sheet.getRow(key1), curRow); - // 合并 - copyMergeRegion(sheet, key1, i * mutiRow + key1); - } - - // 处理当前行里面的每个单元格:替换内容 - Map map = cellMap.get(key1); - for (Integer key : map.keySet()) { - String cellContent = map.get(key) == null ? "" : (String) map.get(key); - XSSFCell c = curRow.getCell(key); - c.setCellValue(parseValue(cellContent, rootObjectItem, peContext)); - } - } - } - - } - - private static String parseValue(String cellContent, Object rootObjectItem, PoiExporterContext peContext) { - // 处理EL表达式 - Expression expression = peContext.getSpelExpParser().parseExpression(cellContent, new TemplateParserContext()); - String parsedContent = null; - try { - parsedContent = expression.getValue(PoiExporterContext.EVAL_CONTEXT, rootObjectItem, String.class); - } catch (EvaluationException e) { - logger.error(Log.op("ForeachRowProcessor#parseValue").msg("EL解析出错啦").toString(), e); - return cellContent; // 异常后,原样返回,不再处理 - } - // 处理${key} - return DefaultRowProcessor.resolve(parsedContent, peContext); - } - - /** - * 拷贝样式 - * - * @param src - * @param des - */ - private static void copyCellStyle(XSSFRow src, XSSFRow des) { - for (int i = src.getFirstCellNum(); i < src.getLastCellNum(); i++) { - des.createCell(i).setCellStyle(src.getCell(i).getCellStyle()); - } - } - - /** - * 拷贝合并单元格 - * - * @param sheet - * @param srcRow - * @param desRow - */ - private static void copyMergeRegion(XSSFSheet sheet, int srcRow, int desRow) { - for (int j = 0; j < sheet.getNumMergedRegions(); j++) { - CellRangeAddress oldRegion = sheet.getMergedRegion(j); - if ((oldRegion.getFirstRow() == srcRow) && (oldRegion.getLastRow() == srcRow)) { - int oldFirstCol = oldRegion.getFirstColumn(); - int oldLastCol = oldRegion.getLastColumn(); - CellRangeAddress newRegion = new CellRangeAddress(desRow, desRow, oldFirstCol, oldLastCol); - // System.out.println(desRow+","+desRow+","+oldFirstCol+","+oldLastCol); - sheet.addMergedRegion(newRegion); - } - } - } - - @Override - public int support(XSSFRow row) { - for (int k = 0; k <= row.getLastCellNum(); k++) { - XSSFCell cell = row.getCell(k); - if (null != cell && cell.getCellType() == XSSFCell.CELL_TYPE_STRING) { - String content = cell.getStringCellValue().trim(); - Pattern prePattern = Pattern.compile(Constants.POI_FOREACH_START_REGEXP); - Matcher matcher = prePattern.matcher(content); - if (matcher.find()) { - return k; - } - } - } - return -1; - } - - public static void main(String[] args) { - String content = " #{index}"; -// String content = ""; - boolean flag = content.matches(""); - System.out.println(flag); - - Pattern prePattern = Pattern.compile(Constants.POI_FOREACH_START_REGEXP); - Matcher matcher = prePattern.matcher(content); - boolean f = matcher.find(); - System.out.println(f); - System.out.println(matcher.replaceAll("")); - } - -} diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exp/processor/RowProcessor.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exp/processor/RowProcessor.java deleted file mode 100644 index 375c209342..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exp/processor/RowProcessor.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.jun.plugin.poitest.exp.processor; - -import org.apache.poi.xssf.usermodel.XSSFRow; - -import com.jun.plugin.poitest.exp.context.PoiExporterContext; - -public interface RowProcessor { - int dealRow(XSSFRow currentRow, PoiExporterContext peContext); - int support(XSSFRow row); -} diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exp/processor/RowProcessorStrategy.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exp/processor/RowProcessorStrategy.java deleted file mode 100644 index a94c1c71fb..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/exp/processor/RowProcessorStrategy.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.jun.plugin.poitest.exp.processor; - -import java.util.List; - -import org.apache.poi.xssf.usermodel.XSSFRow; - -import com.google.common.collect.Lists; - -public class RowProcessorStrategy { - - public static final List processors = Lists.newArrayList(); - static{ - processors.add(new ForeachRowProcessor()); - } - - public static RowProcessor getRowProcessor(XSSFRow row){ - for(RowProcessor processor : processors){ - int flag = processor.support(row); - if(flag >= 0){ - return processor; - } - } - - return DefaultRowProcessor.SINGLE.INSTANCE; - } - -} diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/PoiImporter.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/PoiImporter.java deleted file mode 100644 index 4781c28d5f..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/PoiImporter.java +++ /dev/null @@ -1,225 +0,0 @@ -package com.jun.plugin.poitest.imp; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.text.DecimalFormat; -import java.util.List; - -import org.apache.poi.hssf.usermodel.HSSFDateUtil; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.collect.Lists; -import com.jun.plugin.poitest.exception.PoiElErrorCode; -import com.jun.plugin.poitest.imp.vo.PoiGenericSheetVo; -import com.jun.plugin.poitest.imp.vo.PoiSheetVo; -import com.jun.plugin.poitest.log.Log; - -/** - * excel 导入类 - * - * @author wzy - * @date 2017年7月12日 上午9:43:53 - */ -public class PoiImporter { - private static final Logger logger = LoggerFactory.getLogger(PoiImporter.class); - - public static PoiSheetVo importFirstSheetFrom(InputStream is){ - XSSFWorkbook wb = null; - try { - wb = new XSSFWorkbook(is); - } catch (IOException e) { - try { - is.close(); - } catch (IOException e1) { - logger.error(Log.op("PoiImporter#importFirstSheetFrom").msg("关闭资源失败").toString(), e); - } - throw PoiElErrorCode.SYSTEM_ERROR.exp(e); - } - - long start = System.currentTimeMillis(); - PoiSheetVo sheetVo = processSheet(wb.getSheetAt(0)); - long end = System.currentTimeMillis(); - - logger.info(Log.op("PoiImporter#importFirstSheetFrom").msg("处理导入共耗时[{0}ms]", (end - start)).toString()); - - // 关闭资源 - try { - is.close(); - } catch (IOException e) { - logger.error(Log.op("PoiImporter#importFirstSheetFrom").msg("关闭资源失败").toString(), e); - } - - return sheetVo; - } - - - public static PoiSheetVo importFirstSheetFrom(File excelFile) { - FileInputStream is = null; - - try { - is = new FileInputStream(excelFile); - } catch (FileNotFoundException e) { - throw PoiElErrorCode.TEMPLATE_FILE_NOT_FOUND.exp(e, excelFile.getName()); - } - - return importFirstSheetFrom(is); - } - - /** - * 导入所有的sheet - * @param excelFile - * @return - */ - public static List importAllSheetFrom(File excelFile){ - FileInputStream is = null; - - try { - is = new FileInputStream(excelFile); - } catch (FileNotFoundException e) { - throw PoiElErrorCode.TEMPLATE_FILE_NOT_FOUND.exp(e, excelFile.getName()); - } - - XSSFWorkbook wb = null; - try { - wb = new XSSFWorkbook(is); - } catch (IOException e) { - try { - is.close(); - } catch (IOException e1) { - logger.error(Log.op("PoiImporter#importAllSheetFrom").msg("关闭资源失败").toString(), e); - } - throw PoiElErrorCode.SYSTEM_ERROR.exp(e); - } - - long start = System.currentTimeMillis(); - List sheetVoLs = Lists.newArrayList(); - for(int i=0; i oneRow = Lists.newArrayList(); // 行内容 - // 单元格起始位置可能不是第0个 - for (int j = row.getFirstCellNum();j >= 0 && j <= row.getLastCellNum(); j++) { -// System.out.println("列:" + j); - XSSFCell cell = row.getCell(j); - Object value; // 单元格内容 - if (cell == null) { - value = null; - } else if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC && HSSFDateUtil.isCellDateFormatted(cell)) { - value = cell.getDateCellValue(); - } else { - value = getCellValueText(cell, row, sheet, sheet.getWorkbook()); - } - oneRow.add(value); - } - - sheetVo.getContent().add(oneRow); - } - - return sheetVo; - } - - /** - * 取cell值,统一转为String - * - * @param cell - * @return - */ - private static String getCellValueText(XSSFCell cell, XSSFRow row, XSSFSheet sheet, XSSFWorkbook wb) { - String cv = ""; - switch (cell.getCellType()) { - case XSSFCell.CELL_TYPE_NUMERIC: - DecimalFormat df = new DecimalFormat(); - df.setParseIntegerOnly(true); - double value = cell.getNumericCellValue(); - if (value % 1 == 0) { - cv = df.format(value); - cv = cv.replaceAll(",", ""); - } else { - if ((value + "").length() >= 7) { - // 四舍五入小数点后四位 - value = Math.round(value * 10000); - value = value / 10000; - df = new DecimalFormat("0.0000"); - cv = df.format(value); - } else { - cv = value + ""; - } - } - break; - case XSSFCell.CELL_TYPE_STRING: - cv = cell.getRichStringCellValue().getString().trim(); - break; - case XSSFCell.CELL_TYPE_BLANK: -// logger.info("case CELL_TYPE_BLANK"); - break; - case XSSFCell.CELL_TYPE_FORMULA: - try { - XSSFFormulaEvaluator evaluator = new XSSFFormulaEvaluator(wb); - cv = evaluator.evaluate(cell).getStringValue(); - - } catch (Exception e) { - logger.error(Log.op("PoiImporter#getCellValueText").msg("解析出错!").toString(), e); - } - break; - default: - logger.warn(Log.op("PoiImporter#getCellValueText").msg("未知的单元格类型[{0}]", cell.getCellType()).toString()); - break; - } - return cv; - } - - - public static PoiGenericSheetVo importFirstSheetFrom(File excelFile, Class clazz) { - // 导入原生的内容 - PoiSheetVo rawSheetVo = importFirstSheetFrom(excelFile); - return PoiGenericSheetVo.resolve2Generic(rawSheetVo, clazz); - } - - public static PoiGenericSheetVo importFirstSheetFrom(InputStream is, Class clazz) { - // 导入原生的内容 - PoiSheetVo rawSheetVo = importFirstSheetFrom(is); - return PoiGenericSheetVo.resolve2Generic(rawSheetVo, clazz); - } - -} diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/anno/ExcelColum.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/anno/ExcelColum.java deleted file mode 100644 index faf8423a2d..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/anno/ExcelColum.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.jun.plugin.poitest.imp.anno; - -import static java.lang.annotation.ElementType.FIELD; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -/** -* @author wzy -* @date 2017年7月12日 上午11:15:57 -*/ -@Target({ FIELD }) -@Retention(RUNTIME) -public @interface ExcelColum { - String value(); // 导入excel的列名 -} diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/anno/ExcelDateColum.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/anno/ExcelDateColum.java deleted file mode 100644 index b668b28359..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/anno/ExcelDateColum.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.jun.plugin.poitest.imp.anno; - -import static java.lang.annotation.ElementType.FIELD; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -/** -* @author wzy -* @date 2017年7月12日 上午11:15:57 -*/ -@Target({ FIELD }) -@Retention(RUNTIME) -public @interface ExcelDateColum { - String value(); // 导入excel的列名 - String pattern() default "yyyy-MM-dd"; -} diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/processor/AbstractResolver.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/processor/AbstractResolver.java deleted file mode 100644 index 04f39e2ae9..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/processor/AbstractResolver.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.jun.plugin.poitest.imp.processor; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Field; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.List; - -import com.jun.plugin.poitest.common.ReflectionUtil; - -/** -* @author wzy -* @date 2017年7月12日 下午4:03:50 -*/ -public abstract class AbstractResolver implements Resolver { - protected Field field; - /** - * 行内容 - */ - protected List row; - /** - * 头信息 - */ - protected List head; - - public Resolver build(List input, List head) { - this.row = input; - this.head = head; - return this; - } - - @Deprecated - public boolean support(Field field) { - ParameterizedType parameterizedType = (ParameterizedType) this.getClass().getGenericSuperclass(); - Type pa = parameterizedType.getActualTypeArguments()[0]; - Class anno = null; - try { - anno = (Class) ReflectionUtil.getClass(pa); - } catch (ClassNotFoundException e) { - throw new RuntimeException(e); - } - - return field.getAnnotation(anno) != null; - } - -} diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/processor/DateFieldResolver.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/processor/DateFieldResolver.java deleted file mode 100644 index e39e413d33..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/processor/DateFieldResolver.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.jun.plugin.poitest.imp.processor; - -import java.lang.reflect.Field; - -import org.joda.time.DateTime; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; - -import com.jun.plugin.poitest.imp.anno.ExcelDateColum; - -/** -* @author wzy -* @date 2017年7月12日 下午2:40:20 -*/ -public class DateFieldResolver extends AbstractResolver { - private ExcelDateColum excelDateColum; - - public DateFieldResolver(Field field, ExcelDateColum edc) { - super(); - this.field = field; - this.excelDateColum = edc; - } - - @Override - public Object process() { - String columnName = excelDateColum.value(); - int indexOfColumn = head.indexOf(columnName); - Object columnRawValue = row.get(indexOfColumn); - DateTimeFormatter format = DateTimeFormat.forPattern(excelDateColum.pattern()); -// // 时间解析 - return DateTime.parse(columnRawValue.toString(), format).toDate(); - } - - -} diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/processor/DefaultFieldResolver.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/processor/DefaultFieldResolver.java deleted file mode 100644 index 7dc74aba8e..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/processor/DefaultFieldResolver.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.jun.plugin.poitest.imp.processor; - -import java.lang.reflect.Field; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; - -import com.jun.plugin.poitest.common.PoiUtils; -import com.jun.plugin.poitest.imp.anno.ExcelColum; - -/** -* @author wzy -* @date 2017年7月12日 下午2:40:20 -*/ -public class DefaultFieldResolver extends AbstractResolver { - private ExcelColum excelColum; - - public DefaultFieldResolver(Field field, ExcelColum excelColum) { - super(); - this.field = field; - this.excelColum = excelColum; - } - - public Object process() { - String columnName = excelColum.value(); - int indexOfColumn = head.indexOf(columnName); - Object columnRawValue = row.get(indexOfColumn); - return PoiUtils.parse2Type(columnRawValue, field.getType()); - } - - public static void main(String[] args) { - DefaultFieldResolver resovler = new DefaultFieldResolver(null, null); - ParameterizedType parameterizedType = (ParameterizedType) resovler.getClass().getGenericSuperclass(); - Type pa = parameterizedType.getActualTypeArguments()[0]; - } - -} diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/processor/EmptyResolver.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/processor/EmptyResolver.java deleted file mode 100644 index 39d1063b5b..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/processor/EmptyResolver.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.jun.plugin.poitest.imp.processor; - -import java.lang.reflect.Field; - -/** -* @author wzy -* @date 2017年7月12日 下午2:40:20 -*/ -@SuppressWarnings("rawtypes") -public class EmptyResolver extends AbstractResolver { - - private EmptyResolver() { - super(); - } - - public static class SINGLE { - public static final EmptyResolver INSTANCE = new EmptyResolver(); - } - - /** - * 永远为true - */ - @Override - public boolean support(Field field) { - return true; - } - - @Override - public Object process() { - return null; - } - -} diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/processor/Resolver.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/processor/Resolver.java deleted file mode 100644 index 565d6452d6..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/processor/Resolver.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jun.plugin.poitest.imp.processor; - -/** -* @author wzy -* @date 2017年7月12日 下午3:31:16 -*/ -public interface Resolver { - Object process(); -} diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/processor/ResolverAdaptor.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/processor/ResolverAdaptor.java deleted file mode 100644 index a4e3aefce2..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/processor/ResolverAdaptor.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.jun.plugin.poitest.imp.processor; - -import java.lang.reflect.Field; - -import com.jun.plugin.poitest.imp.anno.ExcelColum; -import com.jun.plugin.poitest.imp.anno.ExcelDateColum; - -/** - * 解析器适配器 - * @author wzy - * @date 2017年7月12日 下午3:30:52 - */ -public class ResolverAdaptor { - - public static AbstractResolver adapt(Field field) { - ExcelColum ec = field.getAnnotation(ExcelColum.class); - if (ec != null) { - return new DefaultFieldResolver(field, ec); - } - - ExcelDateColum edc = field.getAnnotation(ExcelDateColum.class); - if (edc != null) { - return new DateFieldResolver(field, edc); - } - - return EmptyResolver.SINGLE.INSTANCE; - } - -} diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/vo/PoiGenericSheetVo.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/vo/PoiGenericSheetVo.java deleted file mode 100644 index 67f9cd8676..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/vo/PoiGenericSheetVo.java +++ /dev/null @@ -1,105 +0,0 @@ -package com.jun.plugin.poitest.imp.vo; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.Date; -import java.util.List; - -import org.apache.commons.collections.CollectionUtils; -import org.joda.time.DateTime; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; -import org.springframework.util.StringUtils; - -import com.google.common.base.Function; -import com.google.common.collect.Lists; -import com.jun.plugin.poitest.common.PoiUtils; -import com.jun.plugin.poitest.exception.PoiElErrorCode; -import com.jun.plugin.poitest.imp.anno.ExcelColum; -import com.jun.plugin.poitest.imp.anno.ExcelDateColum; -import com.jun.plugin.poitest.imp.processor.DefaultFieldResolver; -import com.jun.plugin.poitest.imp.processor.ResolverAdaptor; - -/** - * 作为excel解析结果的载体(单sheet)。
- * 分为两部分,head头信息 和 body内容 - * - * @author wzy - * @date 2017年7月12日 上午9:54:22 - */ -public class PoiGenericSheetVo { - /** - * 头信息(第一行) - */ - private List head; - - /** - * 内容 - */ - private List body; - - public List getHead() { - return head; - } - - public void setHead(List head) { - this.head = head; - } - - public List getBody() { - return body; - } - - public void setBody(List body) { - this.body = body; - } - - public static PoiGenericSheetVo resolve2Generic(PoiSheetVo rawSheetVo, final Class clazz) { - final PoiGenericSheetVo genericSheetVo = new PoiGenericSheetVo(); - - genericSheetVo.setHead(rawSheetVo.getHead()); - - // 解析body - List> rawBody = rawSheetVo.getRawBody(); - - List body = Lists.transform(rawBody, new Function, T>() { - @Override - public T apply(List input) { - return transfer2Generic(input, clazz); - } - - private T transfer2Generic(List input, Class clazz) { - if (CollectionUtils.isEmpty(input)) { - return null; - } - - try { - T vo = clazz.newInstance(); - Field[] fields = clazz.getDeclaredFields(); - for (Field f : fields) { - Object columnGenericValue = ResolverAdaptor.adapt(f).build(input, genericSheetVo.getHead()).process(); - Method setter = findSetter(clazz, f); - setter.invoke(vo, columnGenericValue); - } - return vo; - } catch (Exception e) { - throw PoiElErrorCode.SYSTEM_ERROR.exp(e); - } - - } - - private Method findSetter(Class clazz, Field f) { - String setterName = "set" + StringUtils.capitalize(f.getName()); - try { - return clazz.getMethod(setterName, f.getType()); - } catch (NoSuchMethodException | SecurityException e) { - throw PoiElErrorCode.SYSTEM_ERROR.exp(e); - } - } - }); - - genericSheetVo.setBody(body); - return genericSheetVo; - } - -} diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/vo/PoiSheetVo.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/vo/PoiSheetVo.java deleted file mode 100644 index 72a2119a7d..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/imp/vo/PoiSheetVo.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.jun.plugin.poitest.imp.vo; - -import java.util.List; - -import org.apache.commons.collections.CollectionUtils; - -import com.google.common.collect.Lists; - -/** - * 作为excel解析结果的载体(单sheet)。
- * 分为两部分,head头信息 和 body内容 - * @author wzy - * @date 2017年7月12日 上午9:54:22 - */ -public class PoiSheetVo { - /** - * 整个sheet的内容 - */ - private List> content = Lists.newArrayList(); - - public List getHead() { - if(CollectionUtils.isEmpty(content)){ - return null; - } - - return content.get(0); // 首行 - } - - - public List> getRawBody(){ - if(CollectionUtils.isEmpty(content) || content.size() <= 1){ - return null; - } - // 除第一行以外的内容 - List> rawBody = content.subList(1, content.size() - 1); - return rawBody; - } - - public List> getContent() { - return content; - } - -} diff --git a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/log/Log.java b/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/log/Log.java deleted file mode 100644 index d7dc5ed750..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/com/jun/plugin/poitest/log/Log.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.jun.plugin.poitest.log; - -import java.text.MessageFormat; -import java.util.HashMap; -import java.util.Map; - -/** - * 日志规范的工具封装 - * - */ -public class Log { - /** - * 操作类型 - */ - private String operation; - - /** - * 日志信息 - */ - private String message = EMPTY_STR; - - /** - * 额外的参数 - */ - private Map params = new HashMap(); - - /** - * 日志格式 [operation][message],{key1=value1,key2=value2,key3=value3} - */ - private static final String LOG_FORMAT = "%d|%s|%s|%s"; - - /** - * 空字符串 - */ - private static final String EMPTY_STR = ""; - - /** - * - * @param operation 操作 - */ - public Log(String operation) { - this.operation = operation; - } - - /** - * 创建Log对象 - * @param op 操作 - * @return - */ - public static Log op(String op) { - return new Log(op); - } - - /** - * - * @param message 信息 - * @return - */ - public Log msg(String message) { - this.message = message; - return this; - } - - /** - * - * @param message 信息 - * @return - */ - public Log msg(String message, Object... args) { - this.message = MessageFormat.format(message, args); - return this; - } - - /** - * 键值对 - * @param key key - * @param value 值 - * @return - */ - public Log kv(String key, Object value) { - params.put(key, value); - return this; - } - - - - /** - * - * @param maps - * @return - */ - public Log kvs(Map maps) { - params.putAll(maps); - return this; - } - - @Override - public String toString() { - return String.format(LOG_FORMAT, System.currentTimeMillis(), operation, params.toString(), message); - } -} diff --git a/jun_java_plugins/jun_poi/src/main/java/struts.xml b/jun_java_plugins/jun_poi/src/main/java/struts.xml deleted file mode 100644 index 809569d233..0000000000 --- a/jun_java_plugins/jun_poi/src/main/java/struts.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo1.java b/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo1.java deleted file mode 100644 index b39e7f0d23..0000000000 --- a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo1.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.jun.plugin.poi.demo; - -import java.io.FileOutputStream; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Workbook; - -public class Demo1 { - - public static void main(String[] args) throws Exception { - Workbook wb=new HSSFWorkbook(); // ����һ���µĹ����� - FileOutputStream fileOut=new FileOutputStream("D:\\��Poi������Ĺ�����.xls"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo10.java b/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo10.java deleted file mode 100644 index 6f94273ea7..0000000000 --- a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo10.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.jun.plugin.poi.demo; - -import java.io.FileOutputStream; -import java.util.Calendar; -import java.util.Date; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; - -public class Demo10 { - - public static void main(String[] args) throws Exception{ - Workbook wb=new HSSFWorkbook(); // ����һ���µĹ����� - Sheet sheet=wb.createSheet("��һ��Sheetҳ"); // ������һ��Sheetҳ - Row row=sheet.createRow(1); // ����һ���� - - Cell cell=row.createCell(1); - cell.setCellValue("XX"); - CellStyle cellStyle=wb.createCellStyle(); - cellStyle.setFillBackgroundColor(IndexedColors.AQUA.getIndex()); // ����ɫ - cellStyle.setFillPattern(CellStyle.BIG_SPOTS); - cell.setCellStyle(cellStyle); - - - Cell cell2=row.createCell(2); - cell2.setCellValue("YYY"); - CellStyle cellStyle2=wb.createCellStyle(); - cellStyle2.setFillForegroundColor(IndexedColors.RED.getIndex()); // ǰ��ɫ - cellStyle2.setFillPattern(CellStyle.SOLID_FOREGROUND); - cell2.setCellStyle(cellStyle2); - - FileOutputStream fileOut=new FileOutputStream("c:\\������.xls"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo11.java b/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo11.java deleted file mode 100644 index 79eae64fd8..0000000000 --- a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo11.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.jun.plugin.poi.demo; - -import java.io.FileOutputStream; -import java.util.Calendar; -import java.util.Date; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddress; - -public class Demo11 { - - public static void main(String[] args) throws Exception{ - Workbook wb=new HSSFWorkbook(); // ����һ���µĹ����� - Sheet sheet=wb.createSheet("��һ��Sheetҳ"); // ������һ��Sheetҳ - Row row=sheet.createRow(1); // ����һ���� - - Cell cell=row.createCell(1); - cell.setCellValue("��Ԫ��ϲ�����"); - - sheet.addMergedRegion(new CellRangeAddress( - 1, // ��ʼ�� - 2, // ������ - 1, // ��ʵ�� - 2 // ������ - )); - - - FileOutputStream fileOut=new FileOutputStream("c:\\������.xls"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo12.java b/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo12.java deleted file mode 100644 index fb28f340e7..0000000000 --- a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo12.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.jun.plugin.poi.demo; - -import java.io.FileOutputStream; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; - -public class Demo12 { - - public static void main(String[] args) throws Exception{ - Workbook wb=new HSSFWorkbook(); // ����һ���µĹ����� - Sheet sheet=wb.createSheet("��һ��Sheetҳ"); // ������һ��Sheetҳ - Row row=sheet.createRow(1); // ����һ���� - - // ����һ�����崦���� - Font font=wb.createFont(); - font.setFontHeightInPoints((short)24); - font.setFontName("Courier New"); - font.setItalic(true); - font.setStrikeout(true); - - CellStyle style=wb.createCellStyle(); - style.setFont(font); - - Cell cell=row.createCell((short)1); - cell.setCellValue("This is test of fonts"); - cell.setCellStyle(style); - - FileOutputStream fileOut=new FileOutputStream("c:\\������.xls"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo13.java b/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo13.java deleted file mode 100644 index 97f7d17bb0..0000000000 --- a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo13.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.jun.plugin.poi.demo; - -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.InputStream; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; - -public class Demo13 { - - public static void main(String[] args) throws Exception{ - InputStream inp=new FileInputStream("c:\\������.xls"); - POIFSFileSystem fs=new POIFSFileSystem(inp); - Workbook wb=new HSSFWorkbook(fs); - Sheet sheet=wb.getSheetAt(0); // ��ȡ��һ��Sheetҳ - Row row=sheet.getRow(0); // ��ȡ��һ�� - Cell cell=row.getCell(0); // ��ȡ��Ԫ�� - if(cell==null){ - cell=row.createCell(3); - } - cell.setCellType(Cell.CELL_TYPE_STRING); - cell.setCellValue("���Ե�Ԫ��"); - - FileOutputStream fileOut=new FileOutputStream("c:\\������.xls"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo14.java b/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo14.java deleted file mode 100644 index 239caa13f8..0000000000 --- a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo14.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.jun.plugin.poi.demo; - -import java.io.FileOutputStream; -import java.util.Calendar; -import java.util.Date; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddress; - -public class Demo14 { - - public static void main(String[] args) throws Exception{ - Workbook wb=new HSSFWorkbook(); // ����һ���µĹ����� - Sheet sheet=wb.createSheet("��һ��Sheetҳ"); // ������һ��Sheetҳ - Row row=sheet.createRow(2); // ����һ���� - Cell cell=row.createCell(2); - cell.setCellValue("��Ҫ���� \n �ɹ�����"); - - CellStyle cs=wb.createCellStyle(); - // ���ÿ��Ի��� - cs.setWrapText(true); - cell.setCellStyle(cs); - - // �������еĸ߶� - row.setHeightInPoints(2*sheet.getDefaultRowHeightInPoints()); - // ������Ԫ���� - sheet.autoSizeColumn(2); - - FileOutputStream fileOut=new FileOutputStream("c:\\������.xls"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo15.java b/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo15.java deleted file mode 100644 index 339866157f..0000000000 --- a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo15.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.jun.plugin.poi.demo; - -import java.io.FileOutputStream; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.DataFormat; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; - -public class Demo15 { - - public static void main(String[] args) throws Exception{ - Workbook wb=new HSSFWorkbook(); // ����һ���µĹ����� - Sheet sheet=wb.createSheet("��һ��Sheetҳ"); // ������һ��Sheetҳ - CellStyle style; - DataFormat format=wb.createDataFormat(); - Row row; - Cell cell; - short rowNum=0; - short colNum=0; - - row=sheet.createRow(rowNum++); - cell=row.createCell(colNum); - cell.setCellValue(111111.25); - - style=wb.createCellStyle(); - style.setDataFormat(format.getFormat("0.0")); // �������ݸ�ʽ - cell.setCellStyle(style); - - row=sheet.createRow(rowNum++); - cell=row.createCell(colNum); - cell.setCellValue(1111111.25); - style=wb.createCellStyle(); - style.setDataFormat(format.getFormat("#,##0.000")); - cell.setCellStyle(style); - - FileOutputStream fileOut=new FileOutputStream("c:\\������.xls"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo2.java b/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo2.java deleted file mode 100644 index b19cd6fec8..0000000000 --- a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo2.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.jun.plugin.poi.demo; - -import java.io.FileOutputStream; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Workbook; - -public class Demo2 { - - public static void main(String[] args) throws Exception { - - Workbook wb=new HSSFWorkbook(); // ����һ���µĹ����� - wb.createSheet("��һ��Sheetҳ"); // ������һ��Sheetҳ - wb.createSheet("�ڶ���Sheetҳ"); // �����ڶ���Sheetҳ - FileOutputStream fileOut=new FileOutputStream("c:\\��Poi�������Sheetҳ.xls"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo3.java b/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo3.java deleted file mode 100644 index 378b5459d5..0000000000 --- a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo3.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.jun.plugin.poi.demo; - -import java.io.FileOutputStream; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; - -public class Demo3 { - - public static void main(String[] args) throws Exception{ - Workbook wb=new HSSFWorkbook(); // ����һ���µĹ����� - Sheet sheet=wb.createSheet("��һ��Sheetҳ"); // ������һ��Sheetҳ - Row row=sheet.createRow(0); // ����һ���� - Cell cell=row.createCell(0); // ����һ����Ԫ�� ��1�� - cell.setCellValue(1); // ����Ԫ������ֵ - - row.createCell(1).setCellValue(1.2); // ����һ����Ԫ�� ��2�� ֵ��1.2 - - row.createCell(2).setCellValue("����һ���ַ�������"); // ����һ����Ԫ�� ��3�� ֵΪһ���ַ��� - - row.createCell(3).setCellValue(false); // ����һ����Ԫ�� ��4�� ֵΪ�������� - - FileOutputStream fileOut=new FileOutputStream("c:\\��Poi�������Cell.xls"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo4.java b/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo4.java deleted file mode 100644 index 4287a24843..0000000000 --- a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo4.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.jun.plugin.poi.demo; - -import java.io.FileOutputStream; -import java.util.Calendar; -import java.util.Date; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; - -public class Demo4 { - - public static void main(String[] args) throws Exception{ - Workbook wb=new HSSFWorkbook(); // ����һ���µĹ����� - Sheet sheet=wb.createSheet("��һ��Sheetҳ"); // ������һ��Sheetҳ - Row row=sheet.createRow(0); // ����һ���� - Cell cell=row.createCell(0); // ����һ����Ԫ�� ��1�� - cell.setCellValue(new Date()); // ����Ԫ������ֵ - - CreationHelper createHelper=wb.getCreationHelper(); - CellStyle cellStyle=wb.createCellStyle(); //��Ԫ����ʽ�� - cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyy-mm-dd hh:mm:ss")); - cell=row.createCell(1); // �ڶ��� - cell.setCellValue(new Date()); - cell.setCellStyle(cellStyle); - - cell=row.createCell(2); // ������ - cell.setCellValue(Calendar.getInstance()); - cell.setCellStyle(cellStyle); - - FileOutputStream fileOut=new FileOutputStream("c:\\������.xls"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo5.java b/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo5.java deleted file mode 100644 index fc31a1a031..0000000000 --- a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo5.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.jun.plugin.poi.demo; - -import java.io.FileOutputStream; -import java.util.Calendar; -import java.util.Date; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; - -public class Demo5 { - - public static void main(String[] args) throws Exception{ - Workbook wb=new HSSFWorkbook(); // ����һ���µĹ����� - Sheet sheet=wb.createSheet("��һ��Sheetҳ"); // ������һ��Sheetҳ - Row row=sheet.createRow(0); // ����һ���� - Cell cell=row.createCell(0); // ����һ����Ԫ�� ��1�� - cell.setCellValue(new Date()); // ����Ԫ������ֵ - - row.createCell(1).setCellValue(1); - row.createCell(2).setCellValue("һ���ַ���"); - row.createCell(3).setCellValue(true); - row.createCell(4).setCellValue(HSSFCell.CELL_TYPE_NUMERIC); - row.createCell(5).setCellValue(false); - - FileOutputStream fileOut=new FileOutputStream("c:\\������.xls"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo6.java b/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo6.java deleted file mode 100644 index c325458824..0000000000 --- a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo6.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.jun.plugin.poi.demo; - -import java.io.FileInputStream; -import java.io.InputStream; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; - -public class Demo6 { - - public static void main(String[] args) throws Exception{ - InputStream is=new FileInputStream("c:\\��������.xls"); - POIFSFileSystem fs=new POIFSFileSystem(is); - HSSFWorkbook wb=new HSSFWorkbook(fs); - HSSFSheet hssfSheet=wb.getSheetAt(0); // ��ȡ��һ��Sheetҳ - if(hssfSheet==null){ - return; - } - // ������Row - for(int rowNum=0;rowNum<=hssfSheet.getLastRowNum();rowNum++){ - HSSFRow hssfRow=hssfSheet.getRow(rowNum); - if(hssfRow==null){ - continue; - } - // ������Cell - for(int cellNum=0;cellNum<=hssfRow.getLastCellNum();cellNum++){ - HSSFCell hssfCell=hssfRow.getCell(cellNum); - if(hssfCell==null){ - continue; - } - System.out.print(" "+getValue(hssfCell)); - } - System.out.println(); - } - } - - private static String getValue(HSSFCell hssfCell){ - if(hssfCell.getCellType()==HSSFCell.CELL_TYPE_BOOLEAN){ - return String.valueOf(hssfCell.getBooleanCellValue()); - }else if(hssfCell.getCellType()==HSSFCell.CELL_TYPE_NUMERIC){ - return String.valueOf(hssfCell.getNumericCellValue()); - }else{ - return String.valueOf(hssfCell.getStringCellValue()); - } - } -} diff --git a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo7.java b/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo7.java deleted file mode 100644 index 654e9d0f6a..0000000000 --- a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo7.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.jun.plugin.poi.demo; - -import java.io.FileInputStream; -import java.io.InputStream; - -import org.apache.poi.hssf.extractor.ExcelExtractor; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; - -public class Demo7 { - - public static void main(String[] args) throws Exception{ - InputStream is=new FileInputStream("c:\\��������.xls"); - POIFSFileSystem fs=new POIFSFileSystem(is); - HSSFWorkbook wb=new HSSFWorkbook(fs); - - ExcelExtractor excelExtractor=new ExcelExtractor(wb); - excelExtractor.setIncludeSheetNames(false);// ���Dz���ҪSheetҳ������ - System.out.println(excelExtractor.getText()); - } - - -} diff --git a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo8.java b/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo8.java deleted file mode 100644 index 72bdcfae42..0000000000 --- a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo8.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.jun.plugin.poi.demo; - -import java.io.FileOutputStream; -import java.util.Date; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFCellStyle; -import org.apache.poi.hssf.usermodel.HSSFRichTextString; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; - -public class Demo8 { - - public static void main(String[] args) throws Exception{ - Workbook wb=new HSSFWorkbook(); // ����һ���µĹ����� - Sheet sheet=wb.createSheet("��һ��Sheetҳ"); // ������һ��Sheetҳ - Row row=sheet.createRow(2); // ����һ���� - row.setHeightInPoints(30); - - createCell(wb, row, (short)0, HSSFCellStyle.ALIGN_CENTER, HSSFCellStyle.VERTICAL_BOTTOM); - createCell(wb, row, (short)1, HSSFCellStyle.ALIGN_FILL, HSSFCellStyle.VERTICAL_CENTER); - createCell(wb, row, (short)2, HSSFCellStyle.ALIGN_LEFT, HSSFCellStyle.VERTICAL_TOP); - createCell(wb, row, (short)3, HSSFCellStyle.ALIGN_RIGHT, HSSFCellStyle.VERTICAL_TOP); - - FileOutputStream fileOut=new FileOutputStream("c:\\������.xls"); - wb.write(fileOut); - fileOut.close(); - } - - /** - * ����һ����Ԫ��Ϊ���趨ָ���Ķ��䷽ʽ - * @param wb ������ - * @param row �� - * @param column �� - * @param halign ˮƽ������䷽ʽ - * @param valign ��ֱ������䷽ʽ - */ - private static void createCell(Workbook wb,Row row,short column,short halign,short valign){ - Cell cell=row.createCell(column); // ������Ԫ�� - cell.setCellValue(new HSSFRichTextString("Align It")); // ����ֵ - CellStyle cellStyle=wb.createCellStyle(); // ������Ԫ����ʽ - cellStyle.setAlignment(halign); // ���õ�Ԫ��ˮƽ������䷽ʽ - cellStyle.setVerticalAlignment(valign); // ���õ�Ԫ��ֱ������䷽ʽ - cell.setCellStyle(cellStyle); // ���õ�Ԫ����ʽ - } - - -} diff --git a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo9.java b/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo9.java deleted file mode 100644 index 7e26dd2551..0000000000 --- a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/demo/Demo9.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.jun.plugin.poi.demo; - -import java.io.FileOutputStream; -import java.util.Calendar; -import java.util.Date; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; - -public class Demo9 { - - public static void main(String[] args) throws Exception{ - Workbook wb=new HSSFWorkbook(); // ����һ���µĹ����� - Sheet sheet=wb.createSheet("��һ��Sheetҳ"); // ������һ��Sheetҳ - Row row=sheet.createRow(1); // ����һ���� - - Cell cell=row.createCell(1); // ����һ����Ԫ�� - cell.setCellValue(4); - - CellStyle cellStyle=wb.createCellStyle(); - cellStyle.setBorderBottom(CellStyle.BORDER_THIN); // �ײ��߿� - cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex()); // �ײ��߿���ɫ - - cellStyle.setBorderLeft(CellStyle.BORDER_THIN); // ��߱߿� - cellStyle.setLeftBorderColor(IndexedColors.GREEN.getIndex()); // ��߱߿���ɫ - - cellStyle.setBorderRight(CellStyle.BORDER_THIN); // �ұ߱߿� - cellStyle.setRightBorderColor(IndexedColors.BLUE.getIndex()); // �ұ߱߿���ɫ - - cellStyle.setBorderTop(CellStyle.BORDER_MEDIUM_DASHED); // �ϱ߱߿� - cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex()); // �ϱ߱߿���ɫ - - cell.setCellStyle(cellStyle); - FileOutputStream fileOut=new FileOutputStream("c:\\������.xls"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/replace/ExcelUtil.java b/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/replace/ExcelUtil.java deleted file mode 100644 index fbc4bdec48..0000000000 --- a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/replace/ExcelUtil.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.jun.plugin.poi.replace; - -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.util.List; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; - -public class ExcelUtil { - /** - * 替换Excel模板文件内容 - * - * @param datas - * 文档数据 - * @param sourceFilePath - * Excel模板文件路径 - * @param targetFilePath - * Excel生成文件路径 - */ - public static boolean replaceModel(List datas, - String sourceFilePath, String targetFilePath) { - boolean bool = true; - try { - POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream( - sourceFilePath)); - HSSFWorkbook wb = new HSSFWorkbook(fs); - HSSFSheet sheet = wb.getSheetAt(0); - for (ExcelReplaceDataVO data : datas) { - // 获取单元格内容 - HSSFRow row = sheet.getRow(data.getRow()); - HSSFCell cell = row.getCell((short) data.getColumn()); - String str = cell.getStringCellValue(); - // 替换单元格内容 - str = str.replace(data.getKey(), data.getValue()); - // 写入单元格内容 - cell.setCellType(HSSFCell.CELL_TYPE_STRING); - // cell.setEncoding(HSSFCell.ENCODING_UTF_16); - cell.setCellValue(str); - } - // 输出文件 - FileOutputStream fileOut = new FileOutputStream(targetFilePath); - wb.write(fileOut); - fileOut.close(); - } catch (Exception e) { - bool = false; - e.printStackTrace(); - } - return bool; - } -} diff --git a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/test/common/Builder.java b/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/test/common/Builder.java deleted file mode 100644 index 709ef93d7f..0000000000 --- a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/test/common/Builder.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.jun.plugin.poi.test.common; - -import com.jun.plugin.poi.test.excel.converter.FieldValueConverter; -import com.jun.plugin.poi.test.excel.core.BingExcel; - -/** - * @author Wujun - * - * @date 2015-12-17 - * Description: - */ -public interface Builder { - - T builder(); - - Builder registerFieldConverter(Class clazz, - FieldValueConverter converter); -} diff --git a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/test/excel/converter/collections/ArrayConverter.java b/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/test/excel/converter/collections/ArrayConverter.java deleted file mode 100644 index ba7ecf95bc..0000000000 --- a/jun_java_plugins/jun_poi/src/test/java/com/jun/plugin/poi/test/excel/converter/collections/ArrayConverter.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.jun.plugin.poi.test.excel.converter.collections; - -import java.lang.reflect.Array; -import java.lang.reflect.Type; - -import com.google.common.base.Strings; -import com.jun.plugin.poi.test.excel.converter.AbstractFieldConvertor; -import com.jun.plugin.poi.test.excel.converter.FieldValueConverter; -import com.jun.plugin.poi.test.excel.core.handler.ConverterHandler; -import com.jun.plugin.poi.test.excel.exception.ConversionException; -import com.jun.plugin.poi.test.excel.exception.IllegalEntityException; -import com.jun.plugin.poi.test.excel.vo.OutValue; - -/** - * @author Wujun - * - * @date 2016-3-24 - * Description: - */ -public class ArrayConverter extends AbstractFieldConvertor { - - - - private final String splitCharacter; - public final static String SPACE_SPLIT=" "; - public final static String SPACE_COMMA=","; - public final static String SPACE_SEMICOLON=";"; - - public ArrayConverter() { - splitCharacter=SPACE_COMMA; - } - - public ArrayConverter(String splitCharacter) { - this.splitCharacter=splitCharacter; - } - - @Override - public boolean canConvert(Class clz) { - - return clz.isArray(); - - } - - - @Override - public OutValue toObject(Object source,ConverterHandler converterHandler) { - if(source==null){ - return null; - } - Class type = source.getClass().getComponentType(); - FieldValueConverter converter = converterHandler.getLocalConverter(type); - if(converter==null){ - throw new ConversionException("can find the converter for type [" - + type + "]"); - } - int length = Array.getLength(source); - StringBuilder bd=new StringBuilder(); - for(int i=0;i - - - - - - - - ${logPattern} - - - - - - ${log.base}/${log.proj}-error.log - - ERROR - ACCEPT - DENY - - - ${log.base}/${log.proj}-error_%d{yyyy-MM-dd}-%i.log - 30 - - 200MB - - - - ${logPattern} - - - - - 0 - 1024 - - - - - - ${log.base}/${log.proj}.log - - ${log.base}/${log.proj}_%d{yyyy-MM-dd}-%i.log - 30 - - 200MB - - - - ${logPattern} - - - - - 0 - 1024 - - - - - - ${log.base}/trace.log - - ${log.base}/trace_%d{yyyy-MM-dd}-%i.log - 10 - - 200MB - - - - %m%n - - - - - 0 - 1024 - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_poi/src/test/resources/template/01_Template_foreach.xlsx b/jun_java_plugins/jun_poi/src/test/resources/template/01_Template_foreach.xlsx deleted file mode 100644 index 78592d59af..0000000000 Binary files a/jun_java_plugins/jun_poi/src/test/resources/template/01_Template_foreach.xlsx and /dev/null differ diff --git "a/jun_java_plugins/jun_poi/src/test/resources/template/02_Template_\345\244\232\344\270\252foreach.xlsx" "b/jun_java_plugins/jun_poi/src/test/resources/template/02_Template_\345\244\232\344\270\252foreach.xlsx" deleted file mode 100644 index 4b7802f06d..0000000000 Binary files "a/jun_java_plugins/jun_poi/src/test/resources/template/02_Template_\345\244\232\344\270\252foreach.xlsx" and /dev/null differ diff --git a/jun_java_plugins/jun_poi/t_user.sql b/jun_java_plugins/jun_poi/t_user.sql deleted file mode 100644 index 120374aa4b..0000000000 --- a/jun_java_plugins/jun_poi/t_user.sql +++ /dev/null @@ -1,39 +0,0 @@ -/* -SQLyog 企业版 - MySQL GUI v8.14 -MySQL - 5.1.49-community : Database - db_easyui -********************************************************************* -*/ - -/*!40101 SET NAMES utf8 */; - -/*!40101 SET SQL_MODE=''*/; - -/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; -/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; -/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; -/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -CREATE DATABASE /*!32312 IF NOT EXISTS*/`db_easyui` /*!40100 DEFAULT CHARACTER SET utf8 */; - -USE `db_easyui`; - -/*Table structure for table `t_user` */ - -DROP TABLE IF EXISTS `t_user`; - -CREATE TABLE `t_user` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `name` varchar(20) DEFAULT NULL, - `phone` varchar(20) DEFAULT NULL, - `email` varchar(20) DEFAULT NULL, - `qq` varchar(20) DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=55 DEFAULT CHARSET=utf8; - -/*Data for the table `t_user` */ - -insert into `t_user`(`id`,`name`,`phone`,`email`,`qq`) values (1,'张三12233','12345672233','1234567@qq2233.com','12345672233'),(7,'张三7','1234567','1234567@qq.com','1234567'),(9,'张三9','1234567','1234567@qq.com','1234567'),(12,'张三12','1234567','1234567@qq.com','1234567'),(13,'张三13','1234567','1234567@qq.com','1234567'),(14,'张三14','1234567','1234567@qq.com','1234567'),(15,'张三15','1234567','1234567@qq.com','1234567'),(16,'d2233','212133','111321@121331.com','212133'),(19,'是3444','2344','21@q33.com','23123333'),(20,'二哥22','12312','231@qq2.com','3213122222'),(21,'1','1','12345672233@qq.com','1'),(23,'211','2121','321@11.com','21'),(26,'是','是','是','是'),(27,'是','是','是','是'),(28,'1.0','2.0','2.0','2.0'),(29,'我们谁','312.0','321@qq.com','321321.0'),(30,'321.0','321.0','321@qq.com','321.0'),(31,'我们谁','312.0','321@qq.com','321321.0'),(32,'321.0','321.0','321@qq.com','321.0'),(33,'我们谁','312.0','321@qq.com','321321.0'),(34,'321.0','321.0','321@qq.com','321.0'),(35,'我们谁','312.0','321@qq.com','321321.0'),(36,'321.0','321.0','321@qq.com','321.0'),(37,'21.0','21.0','21.0','111.0'),(38,'12.0','我','32.0','321.0'),(39,'12.0','我','32.0','321'),(40,'12.0','我','32.0','321'),(41,'111','21','1221@qq.com','12'),(42,'21','21','1221@qq.com','211111'),(43,'2100','2100','122100@qq.com','211111000'),(44,'21001','21001','1221010@qq.com','2111110001'),(45,'210012','210012','1221010@qq.com','2111110001'),(46,'210012我1','21001221','1221010@qq.com','211111000121'),(48,'21','21','1221@qq.com','21'),(53,'王八1','123.0','123@123.com','123.0'),(54,'王八2','124.0','123@124.com','124.0'); - -/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; -/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; -/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; -/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; diff --git a/jun_java_plugins/jun_poi_tl_word_export/READE.md b/jun_java_plugins/jun_poi_tl_word_export/READE.md deleted file mode 100644 index 746137219c..0000000000 --- a/jun_java_plugins/jun_poi_tl_word_export/READE.md +++ /dev/null @@ -1 +0,0 @@ -http://deepoove.com/poi-tl/ \ No newline at end of file diff --git a/jun_java_plugins/jun_poi_tl_word_export/pom.xml b/jun_java_plugins/jun_poi_tl_word_export/pom.xml deleted file mode 100644 index 6338dd7b59..0000000000 --- a/jun_java_plugins/jun_poi_tl_word_export/pom.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 2.5.5 - - - com.dcits.tool - jun_poi_tl_word_export - 1.0 - - - 1.8 - 1.8 - 1.8 - - - - org.springframework.boot - spring-boot-starter - 2.5.5 - - - - com.deepoove - poi-tl - 1.9.1 - - - com.alibaba - fastjson - 1.2.76 - - - org.projectlombok - lombok - - - - - - - src/main/java - - - - - org.springframework.boot - spring-boot-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - 3.0.2 - - - - true - com.dcits.tool.resume.ExcelImportMain - - - - - - - - diff --git a/jun_java_plugins/jun_poi_tl_word_export/src/main/java/META-INF/MANIFEST.MF b/jun_java_plugins/jun_poi_tl_word_export/src/main/java/META-INF/MANIFEST.MF deleted file mode 100644 index 0b27f4a39c..0000000000 --- a/jun_java_plugins/jun_poi_tl_word_export/src/main/java/META-INF/MANIFEST.MF +++ /dev/null @@ -1,3 +0,0 @@ -Manifest-Version: 1.0 -Main-Class: com.dcits.tool.resume.ExcelImportMain - diff --git a/jun_java_plugins/jun_poi_tl_word_export/src/main/java/com/jun/plugin/poi/resume/BreakPagePolicy.java b/jun_java_plugins/jun_poi_tl_word_export/src/main/java/com/jun/plugin/poi/resume/BreakPagePolicy.java deleted file mode 100644 index ad5168a6aa..0000000000 --- a/jun_java_plugins/jun_poi_tl_word_export/src/main/java/com/jun/plugin/poi/resume/BreakPagePolicy.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.jun.plugin.poi.resume; - -import com.deepoove.poi.XWPFTemplate; -import com.deepoove.poi.policy.RenderPolicy; -import com.deepoove.poi.template.ElementTemplate; -import com.deepoove.poi.template.run.RunTemplate; -import org.apache.poi.xwpf.usermodel.BreakClear; -import org.apache.poi.xwpf.usermodel.BreakType; -import org.apache.poi.xwpf.usermodel.XWPFRun; - -public class BreakPagePolicy implements RenderPolicy { - @Override - public void render(ElementTemplate elementTemplate, Object breakPage, XWPFTemplate xwpfTemplate) { - //当前位置 - XWPFRun run = ((RunTemplate) elementTemplate).getRun(); - run.setText(null,0); - if((boolean)breakPage){ - run.addBreak(BreakType.PAGE); - } - - } -} diff --git a/jun_java_plugins/jun_poi_tl_word_export/src/main/java/com/jun/plugin/poi/resume/ExcelImportMain.java b/jun_java_plugins/jun_poi_tl_word_export/src/main/java/com/jun/plugin/poi/resume/ExcelImportMain.java deleted file mode 100644 index 96177f092f..0000000000 --- a/jun_java_plugins/jun_poi_tl_word_export/src/main/java/com/jun/plugin/poi/resume/ExcelImportMain.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.jun.plugin.poi.resume; - -import com.deepoove.poi.XWPFTemplate; -import com.deepoove.poi.config.Configure; -import com.jun.plugin.poi.resume.tool.ExcelUtil; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class ExcelImportMain { - static File mappingFile=new File(".","映射关系.xlsx"); - static File dataFile=new File(".","人员清单.xlsx"); - static File templateFile=new File(".","简历模板.docx"); - static File exportFile=new File(".","简历.docx"); - - public static void main(String[] args) { - String mappingPath="C:\\Users\\yanwlb\\Desktop\\task\\mapping.xlsx"; - mappingFile=new File(mappingPath); - List> mapping= ExcelUtil.readExcelMapping(mappingFile.getAbsolutePath(),0); - System.out.println("解析映射表完成......"); - Map mappingHead=mapping.get(0); - String path="C:\\Users\\yanwlb\\Desktop\\task\\人员清单样例.xlsx"; - dataFile=new File(path); - final List> data= ExcelUtil.readExcel(dataFile.getAbsolutePath(),0,mappingHead); - if(data==null || data.size()==0){ - System.out.println("没有数据可生成,请检查人员清单数据......"); - return; - - } - System.out.println("检测发现"+data.size()+"条职员信息"); - for(int i=1;i<=data.size();i++){ - int index=i-1; - Map item=data.get(index); - String desc= (String) item.get("desc"); - item.put("experience",desc); - item.put("breakPage",i() {{ - put("resume",data); - - }} - ); - System.out.println("解析导出简历模板样式完成........."); - try { - //生成简历 - String exportPath="C:\\Users\\yanwlb\\Desktop\\task\\简历template.docx"; - exportFile=new File(exportPath); - FileOutputStream out = new FileOutputStream(exportFile.getAbsolutePath());//要导出的文件名 - template.writeAndClose(out); - } catch (IOException e) { - e.printStackTrace(); - } - System.out.println("导出简历模板完成"); - } - - -} diff --git a/jun_java_plugins/jun_poi_tl_word_export/src/main/java/com/jun/plugin/poi/resume/ExcelVo.java b/jun_java_plugins/jun_poi_tl_word_export/src/main/java/com/jun/plugin/poi/resume/ExcelVo.java deleted file mode 100644 index 8c9b0af8c6..0000000000 --- a/jun_java_plugins/jun_poi_tl_word_export/src/main/java/com/jun/plugin/poi/resume/ExcelVo.java +++ /dev/null @@ -1,219 +0,0 @@ -package com.jun.plugin.poi.resume; - -import com.jun.plugin.poi.resume.annotation.ExcelField; - - - -/** - * 表 b_staff_baseinfo - * - * @author yanwlb - * @date 2021-09-30 - */ - -public class ExcelVo -{ - @ExcelField(name = "姓名") - private String name; - - @ExcelField(name = "性别") - private String gender; - - @ExcelField(name = "出生日期") - private String birthday; - - @ExcelField(name = "学历") - private String studyLevel; - - @ExcelField(name = "毕业学校") - private String school; - - @ExcelField(name = "技术职称") - private String technicalTitle; - - @ExcelField(name = "任职公司") - private String company; - - @ExcelField(name = "公司职务") - private String post; - - @ExcelField(name = "任职时间") - private String officeTime; - - @ExcelField(name = "本项目任职") - private String workName; - - @ExcelField(name = "人员档次") - private String level; - - @ExcelField(name = "工作简历及主要业绩") - private String desc; - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name to set - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the gender - */ - public String getGender() { - return gender; - } - - /** - * @param gender to set - */ - public void setGender(String gender) { - this.gender = gender; - } - - /** - * @return the birthday - */ - public String getBirthday() { - return birthday; - } - - /** - * @param birthday to set - */ - public void setBirthday(String birthday) { - this.birthday = birthday; - } - - /** - * @return the studyLevel - */ - public String getStudyLevel() { - return studyLevel; - } - - /** - * @param studyLevel to set - */ - public void setStudyLevel(String studyLevel) { - this.studyLevel = studyLevel; - } - - /** - * @return the school - */ - public String getSchool() { - return school; - } - - /** - * @param school to set - */ - public void setSchool(String school) { - this.school = school; - } - - /** - * @return the technicalTitle - */ - public String getTechnicalTitle() { - return technicalTitle; - } - - /** - * @param technicalTitle to set - */ - public void setTechnicalTitle(String technicalTitle) { - this.technicalTitle = technicalTitle; - } - - /** - * @return the company - */ - public String getCompany() { - return company; - } - - /** - * @param company to set - */ - public void setCompany(String company) { - this.company = company; - } - - /** - * @return the post - */ - public String getPost() { - return post; - } - - /** - * @param post to set - */ - public void setPost(String post) { - this.post = post; - } - - /** - * @return the officeTime - */ - public String getOfficeTime() { - return officeTime; - } - - /** - * @param officeTime to set - */ - public void setOfficeTime(String officeTime) { - this.officeTime = officeTime; - } - - /** - * @return the workName - */ - public String getWorkName() { - return workName; - } - - /** - * @param workName to set - */ - public void setWorkName(String workName) { - this.workName = workName; - } - - /** - * @return the level - */ - public String getLevel() { - return level; - } - - /** - * @param level to set - */ - public void setLevel(String level) { - this.level = level; - } - - /** - * @return the desc - */ - public String getDesc() { - return desc; - } - - /** - * @param desc to set - */ - public void setDesc(String desc) { - this.desc = desc; - } -} diff --git a/jun_java_plugins/jun_poi_tl_word_export/src/main/java/com/jun/plugin/poi/resume/ExperiencePolicy.java b/jun_java_plugins/jun_poi_tl_word_export/src/main/java/com/jun/plugin/poi/resume/ExperiencePolicy.java deleted file mode 100644 index 8400e84687..0000000000 --- a/jun_java_plugins/jun_poi_tl_word_export/src/main/java/com/jun/plugin/poi/resume/ExperiencePolicy.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.jun.plugin.poi.resume; - -import com.deepoove.poi.XWPFTemplate; -import com.deepoove.poi.policy.RenderPolicy; -import com.deepoove.poi.template.ElementTemplate; -import com.deepoove.poi.template.run.RunTemplate; -import org.apache.poi.xwpf.usermodel.XWPFRun; - -public class ExperiencePolicy implements RenderPolicy { - @Override - public void render(ElementTemplate elementTemplate, Object data, XWPFTemplate xwpfTemplate) { - //当前位置 - XWPFRun run = ((RunTemplate) elementTemplate).getRun(); - String[] array=((String) data).split("#"); - for(int i=0;i resume = new HashMap<>(); - Map data = new HashMap<>(); - -// ListRenderPolicy policy = new ListRenderPolicy(); -// Configure config = Configure.newBuilder() -// .bind("pictures", policy).build(); -// List detailList = new ArrayList<>(); -// WordVO two = new WordVO(); -// two.setProblem("问题测试2"); -// two.setReason("原因测试2"); -// List pList2 = new ArrayList<>(); -// pList2.add(new PictureRenderData(100, 120, "D:\\Documents\\Desktop\\dynamic-resume\\start\\img\\3.png")); -// two.setPicture(pList2); -// detailList.add(two); -// List list = new ArrayList<>(); -// detailList.forEach(wordVO -> { -// list.add(new TextRenderData(wordVO.getProblem())); -// list.add(new TextRenderData(wordVO.getReason())); -// if (CollectionUtils.isNotEmpty(wordVO.getPicture())) { -// list.addAll(wordVO.getPicture()); -// } -// }); - data.put("pictures", new PictureRenderData(100, 120, "D:\\Documents\\Desktop\\dynamic-resume\\start\\img\\3.png")); - - data.put("name", "Sayi"); - data.put("itcode","lxra"); - data.put("staffName","李小冉"); - data.put("age",23); - data.put("gender","女"); - data.put("workplace","北京"); - data.put("highestEducation","本科"); - data.put("beginWordTime","20211009"); - data.put("enterCompanyTime","20211009"); - data.put("judicialEntity","北京神州信息"); - data.put("flPlace","北京"); - data.put("department","政府SBU"); - data.put("majorName","计算机科学与应用"); - data.put("photo","xxx.png"); - - data.put("post","工程师"); - data.put("experience","1111111111111111"); - List> list11=new ArrayList<>(); - list11.add(data); - resume.put("resume",list11); - XWPFTemplate template = XWPFTemplate.compile(basePath+"简历模板2.docx").render( - resume); - template.writeAndClose(new FileOutputStream(basePath+"简历模板output41611.docx")); - } - - - private static void test() throws IOException { - Map data = new HashMap<>(); - data.put("name", "Sayi"); - data.put("itcode","lxra"); - data.put("staffName","李小冉"); - data.put("age",23); - data.put("gender","女"); - data.put("workplace","北京"); - data.put("highestEducation","本科"); - data.put("beginWordTime","20211009"); - data.put("enterCompanyTime","20211009"); - data.put("judicialEntity","北京神州信息"); - data.put("flPlace","北京"); - data.put("department","政府SBU"); - data.put("majorName","计算机科学与应用"); - data.put("photo","xxx.png"); - List> announce=new ArrayList<>(); - Map map1=new HashMap<>(); - map1.put("name","张三"); - map1.put("age",23); - Map map2=new HashMap<>(); - map2.put("name","李四"); - map2.put("age",13); - announce.add(map1); - announce.add(map2); - List list=new ArrayList<>(); - list.add("hhh"); - list.add("bbb"); - data.put("announce", list); - - JSONObject json=new JSONObject(); - json.put("announce",new String[]{"zhagnsan","list"}); - System.out.println(json.toJSONString()); - XWPFTemplate template = XWPFTemplate.compile(basePath+"简历模板.docx").render( - data); - template.writeAndClose(new FileOutputStream(basePath+"output1111-12.docx")); - } -} diff --git a/jun_java_plugins/jun_poi_tl_word_export/src/main/java/com/jun/plugin/poi/resume/Test.java b/jun_java_plugins/jun_poi_tl_word_export/src/main/java/com/jun/plugin/poi/resume/Test.java deleted file mode 100644 index 92462591d0..0000000000 --- a/jun_java_plugins/jun_poi_tl_word_export/src/main/java/com/jun/plugin/poi/resume/Test.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.jun.plugin.poi.resume; - -import com.deepoove.poi.XWPFTemplate; -import com.deepoove.poi.config.Configure; -import com.deepoove.poi.data.PictureRenderData; -import com.deepoove.poi.data.TextRenderData; -import com.deepoove.poi.policy.ListRenderPolicy; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.poi.ss.usermodel.CellStyle; - -import java.io.IOException; -import java.io.InputStream; -import java.math.BigDecimal; -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class Test { - public static void main(String[] args) throws IOException { - Map map = new HashMap(); -// InputStream inputStream = Thread.currentThread().getContextClassLoader() -// .getResourceAsStream("template/test.docx"); - ListRenderPolicy policy = new ListRenderPolicy(); - Configure config = Configure.newBuilder() - .bind("pictures", policy).build(); - List detailList = new ArrayList<>(); - WordVO one = new WordVO(); - WordVO two = new WordVO(); - one.setProblem("问题测试1"); - two.setProblem("问题测试2"); - one.setReason("原因测试1"); - two.setReason("原因测试2"); - List pList1 = new ArrayList<>(); - List pList2 = new ArrayList<>(); - pList1.add(new PictureRenderData(100, 120, "D:\\Documents\\Desktop\\dynamic-resume\\start\\img\\1.png")); - pList1.add(new PictureRenderData(100, 120, "D:\\Documents\\Desktop\\dynamic-resume\\start\\img\\2.png")); - pList2.add(new PictureRenderData(100, 120, "D:\\Documents\\Desktop\\dynamic-resume\\start\\img\\3.png")); - //one.setPicture(pList1); - two.setPicture(pList2); - //detailList.add(one); - detailList.add(two); - List list = new ArrayList<>(); - detailList.forEach(wordVO -> { - list.add(new TextRenderData(wordVO.getProblem())); - list.add(new TextRenderData(wordVO.getReason())); - if (CollectionUtils.isNotEmpty(wordVO.getPicture())) { - list.addAll(wordVO.getPicture()); - } - }); - map.put("pictures", list); - - -// XWPFTemplate template = XWPFTemplate.compile(inputStream, config).render(map); - XWPFTemplate template = XWPFTemplate.compile("D:\\Documents\\Desktop\\dynamic-resume\\start\\test-template.docx", config).render(map); - template.writeToFile("D:\\Documents\\Desktop\\dynamic-resume\\start\\测试416-222222.docx"); - } - - -} diff --git a/jun_java_plugins/jun_poi_tl_word_export/src/main/java/com/jun/plugin/poi/resume/WordVO.java b/jun_java_plugins/jun_poi_tl_word_export/src/main/java/com/jun/plugin/poi/resume/WordVO.java deleted file mode 100644 index 1288a02e31..0000000000 --- a/jun_java_plugins/jun_poi_tl_word_export/src/main/java/com/jun/plugin/poi/resume/WordVO.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.jun.plugin.poi.resume; - -import com.deepoove.poi.data.PictureRenderData; -import lombok.Data; - -import java.util.List; - -@Data -public class WordVO { - private List picture; - - private String problem; - - private String reason; -} diff --git a/jun_java_plugins/jun_poi_tl_word_export/src/main/java/com/jun/plugin/poi/resume/annotation/ExcelField.java b/jun_java_plugins/jun_poi_tl_word_export/src/main/java/com/jun/plugin/poi/resume/annotation/ExcelField.java deleted file mode 100644 index dbd1b51061..0000000000 --- a/jun_java_plugins/jun_poi_tl_word_export/src/main/java/com/jun/plugin/poi/resume/annotation/ExcelField.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.jun.plugin.poi.resume.annotation; - - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * NOTE: This @ExcelField annotation is duplicated in jun_poi module - * (com.jun.plugin.poi.impexp.excel.annotation.ExcelField). - * Consider consolidating to avoid maintaining two copies. - * - * @Author: yanwlb - * @Date: 2021/10/15 14:21 - * @Description: //自定义注解,标志导入导出的excel字段名称 - */ -@Target(ElementType.FIELD) -@Retention(RetentionPolicy.RUNTIME) -public @interface ExcelField { - - String name(); -} diff --git a/jun_java_plugins/jun_poi_tl_word_export/src/main/java/com/jun/plugin/poi/resume/tool/ExcelUtil.java b/jun_java_plugins/jun_poi_tl_word_export/src/main/java/com/jun/plugin/poi/resume/tool/ExcelUtil.java deleted file mode 100644 index 9aa08f7cce..0000000000 --- a/jun_java_plugins/jun_poi_tl_word_export/src/main/java/com/jun/plugin/poi/resume/tool/ExcelUtil.java +++ /dev/null @@ -1,257 +0,0 @@ -package com.jun.plugin.poi.resume.tool; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -import com.jun.plugin.poi.resume.annotation.ExcelField; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Field; -import java.text.DateFormat; -import java.text.DecimalFormat; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -public class ExcelUtil { - - public static List> readExcel(String filePath, Integer sheetIndex,Map mapping) { - Workbook wb = ExcelUtil.createWorkBook(filePath); - return getWorkbook(wb,sheetIndex,mapping); - } - - - public static List> readExcel(String filePath, Integer sheetIndex,Class mappingType) { - Workbook wb = ExcelUtil.createWorkBook(filePath); - return getWorkbook(wb,sheetIndex,mappingType); - } - - public static List> readExcelMapping(String filePath, Integer sheetIndex) { - Workbook wb = ExcelUtil.createWorkBook(filePath); - return getWorkbook(wb,sheetIndex); - } - - private static List> getWorkbook(Workbook workbook,Integer sheetIndex){ - List> dataList = new ArrayList<>(); - if (workbook != null) { - Sheet sheet = workbook.getSheetAt(sheetIndex); - int maxRownum = sheet.getPhysicalNumberOfRows(); - Row firstRow = sheet.getRow(0); - int maxColnum = firstRow.getPhysicalNumberOfCells(); - String columns[] = new String[maxColnum]; - for (int i = 0; i < maxRownum; i++) { - Map map = null; - if (i > 0) { - map = new LinkedHashMap<>(); - firstRow = sheet.getRow(i); - } - if (firstRow != null) { - String cellData = null; - for (int j = 0; j < maxColnum; j++) { - cellData = (String) ExcelUtil.getCellFormatValue(firstRow.getCell(j)); - if (i == 0) { - columns[j] = cellData; - } else { - map.put(columns[j], cellData); - } - } - } else { - break; - } - if (i > 0) { - dataList.add(map); - } - } - } - return dataList; - } - - private static Workbook createWorkBook(String filePath) { - Workbook wb = null; - if (filePath == null) { - return null; - } - String extString = filePath.substring(filePath.lastIndexOf(".")); - InputStream is = null; - try { - is = new FileInputStream(filePath); - if (".xls".equals(extString)) { - return wb = new HSSFWorkbook(is); - } else if (".xlsx".equals(extString)) { - return wb = new XSSFWorkbook(is); - } else { - return wb; - } - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - return wb; - } - - private static List> getWorkbook(Workbook workbook,Integer sheetIndex,Class mappingType){ - List> dataList = new ArrayList<>(); - if (workbook != null) { - Sheet sheet = workbook.getSheetAt(sheetIndex); - int maxRownum = sheet.getPhysicalNumberOfRows(); - Row firstRow = sheet.getRow(0); - int maxColnum = firstRow.getPhysicalNumberOfCells(); - String columns[] = new String[maxColnum]; - for (int i = 0; i < maxRownum; i++) { - Map map = null; - if (i > 0) { - map = new LinkedHashMap<>(); - firstRow = sheet.getRow(i); - } - if (firstRow != null) { - String cellData = null; - for (int j = 0; j < maxColnum; j++) { - cellData = (String) ExcelUtil.getCellFormatValue(firstRow.getCell(j)); - if (i == 0) { - columns[j] = cellData; - } else { - String key=getColumnName(columns[j],mappingType); - map.put(key, cellData); - } - } - } else { - break; - } - if (i > 0) { - dataList.add(map); - } - } - } - return dataList; - } - - private static List> getWorkbook(Workbook workbook,Integer sheetIndex,Map mapping){ - List> dataList = new ArrayList<>(); - if (workbook != null) { - Sheet sheet = workbook.getSheetAt(sheetIndex); - int maxRownum = sheet.getPhysicalNumberOfRows(); - Row firstRow = sheet.getRow(0); - int maxColnum = firstRow.getPhysicalNumberOfCells(); - String columns[] = new String[maxColnum]; - for (int i = 0; i < maxRownum; i++) { - Map map = null; - if (i > 0) { - map = new LinkedHashMap<>(); - firstRow = sheet.getRow(i); - } - if (firstRow != null) { - String cellData = null; - for (int j = 0; j < maxColnum; j++) { - cellData = (String) ExcelUtil.getCellFormatValue(firstRow.getCell(j)); - if (i == 0) { - columns[j] = cellData; - } else { - String key=getColumnName(columns[j],mapping); - map.put(key, cellData); - } - } - } else { - break; - } - if (i > 0) { - dataList.add(map); - } - } - } - return dataList; - } - - /** - * 将字段转为相应的格式 - * @param cell - * @return - */ - private static Object getCellFormatValue(Cell cell) { - Object cellValue = null; - if (cell != null) { - //判断cell类型 - switch (cell.getCellType()) { - case NUMERIC: { - if(DateUtil.isCellDateFormatted(cell)){ - cellValue = cell.getDateCellValue(); - SimpleDateFormat format=new SimpleDateFormat("yyyy/MM/dd"); - cellValue=format.format(cellValue); - break; - } - DecimalFormat bigDecimal=new DecimalFormat("########"); - cellValue = String.valueOf(bigDecimal.format(cell.getNumericCellValue())); - break; - } - case FORMULA: { - if (DateUtil.isCellDateFormatted(cell)) { - cellValue = cell.getDateCellValue();//转换为日期格式YYYY-mm-dd - } else { - cellValue = String.valueOf(cell.getNumericCellValue()); //数字 - } - break; - } - case STRING: { - cellValue = cell.getRichStringCellValue().getString(); - break; - } - default: - cellValue = ""; - } - } else { - cellValue = ""; - } - return cellValue; - } - - /** - * 根据中文列明获得对应的实体类属性名 - * @param fieldName - * @param clazz - * @return - */ - public static String getColumnName(String fieldName,Class clazz){ - Field[] fields=clazz.getDeclaredFields(); - for (Field field : fields) { - if(field.getAnnotation(ExcelField.class)==null) - continue; - - ExcelField annotation=field.getAnnotation(ExcelField.class); - String name=annotation.name(); - if(name.equals(fieldName)){ - return field.getName(); - } - } - System.out.println("未匹配到字段名:"+fieldName); - return null; - - } - - public static String getColumnName(String fieldName,Map mapping){ - return mapping.get(fieldName); - } - - - - - - - - - - - - - - -} diff --git a/jun_java_plugins/jun_poi_tl_word_export/start/README.md b/jun_java_plugins/jun_poi_tl_word_export/start/README.md deleted file mode 100644 index a11bdfec3e..0000000000 --- a/jun_java_plugins/jun_poi_tl_word_export/start/README.md +++ /dev/null @@ -1,2 +0,0 @@ -在该文件夹下放入jre文件夹, -点击启动.bat即可生成简历 \ No newline at end of file diff --git a/jun_java_plugins/jun_poi_tl_word_export/start/output1111-1.docx b/jun_java_plugins/jun_poi_tl_word_export/start/output1111-1.docx deleted file mode 100644 index 4d397f7ce7..0000000000 Binary files a/jun_java_plugins/jun_poi_tl_word_export/start/output1111-1.docx and /dev/null differ diff --git a/jun_java_plugins/jun_poi_tl_word_export/start/output1111-12.docx b/jun_java_plugins/jun_poi_tl_word_export/start/output1111-12.docx deleted file mode 100644 index 246e58c6b2..0000000000 Binary files a/jun_java_plugins/jun_poi_tl_word_export/start/output1111-12.docx and /dev/null differ diff --git a/jun_java_plugins/jun_poi_tl_word_export/start/test-template.docx b/jun_java_plugins/jun_poi_tl_word_export/start/test-template.docx deleted file mode 100644 index d72b9b4e5c..0000000000 Binary files a/jun_java_plugins/jun_poi_tl_word_export/start/test-template.docx and /dev/null differ diff --git a/jun_java_plugins/jun_poi_tl_word_export/start/test-template2.docx b/jun_java_plugins/jun_poi_tl_word_export/start/test-template2.docx deleted file mode 100644 index d72b9b4e5c..0000000000 Binary files a/jun_java_plugins/jun_poi_tl_word_export/start/test-template2.docx and /dev/null differ diff --git "a/jun_java_plugins/jun_poi_tl_word_export/start/\344\272\272\345\221\230\346\270\205\345\215\225.xlsx" "b/jun_java_plugins/jun_poi_tl_word_export/start/\344\272\272\345\221\230\346\270\205\345\215\225.xlsx" deleted file mode 100644 index 0746733be9..0000000000 Binary files "a/jun_java_plugins/jun_poi_tl_word_export/start/\344\272\272\345\221\230\346\270\205\345\215\225.xlsx" and /dev/null differ diff --git "a/jun_java_plugins/jun_poi_tl_word_export/start/\345\220\257\345\212\250.bat" "b/jun_java_plugins/jun_poi_tl_word_export/start/\345\220\257\345\212\250.bat" deleted file mode 100644 index 1608130cb7..0000000000 --- "a/jun_java_plugins/jun_poi_tl_word_export/start/\345\220\257\345\212\250.bat" +++ /dev/null @@ -1,3 +0,0 @@ -@echo -jre\bin\java -jar dcits-resume-0.0.1-SNAPSHOT.jar -pause \ No newline at end of file diff --git "a/jun_java_plugins/jun_poi_tl_word_export/start/\346\230\240\345\260\204\345\205\263\347\263\273.xlsx" "b/jun_java_plugins/jun_poi_tl_word_export/start/\346\230\240\345\260\204\345\205\263\347\263\273.xlsx" deleted file mode 100644 index 35587d430f..0000000000 Binary files "a/jun_java_plugins/jun_poi_tl_word_export/start/\346\230\240\345\260\204\345\205\263\347\263\273.xlsx" and /dev/null differ diff --git "a/jun_java_plugins/jun_poi_tl_word_export/start/\346\265\213\350\257\225416-2.docx" "b/jun_java_plugins/jun_poi_tl_word_export/start/\346\265\213\350\257\225416-2.docx" deleted file mode 100644 index 328546377d..0000000000 Binary files "a/jun_java_plugins/jun_poi_tl_word_export/start/\346\265\213\350\257\225416-2.docx" and /dev/null differ diff --git "a/jun_java_plugins/jun_poi_tl_word_export/start/\347\256\200\345\216\206.docx" "b/jun_java_plugins/jun_poi_tl_word_export/start/\347\256\200\345\216\206.docx" deleted file mode 100644 index 01fb99dffa..0000000000 Binary files "a/jun_java_plugins/jun_poi_tl_word_export/start/\347\256\200\345\216\206.docx" and /dev/null differ diff --git "a/jun_java_plugins/jun_poi_tl_word_export/start/\347\256\200\345\216\206\346\250\241\346\235\277.docx" "b/jun_java_plugins/jun_poi_tl_word_export/start/\347\256\200\345\216\206\346\250\241\346\235\277.docx" deleted file mode 100644 index acb773e943..0000000000 Binary files "a/jun_java_plugins/jun_poi_tl_word_export/start/\347\256\200\345\216\206\346\250\241\346\235\277.docx" and /dev/null differ diff --git "a/jun_java_plugins/jun_poi_tl_word_export/start/\347\256\200\345\216\206\346\250\241\346\235\2772.docx" "b/jun_java_plugins/jun_poi_tl_word_export/start/\347\256\200\345\216\206\346\250\241\346\235\2772.docx" deleted file mode 100644 index 87808d9b12..0000000000 Binary files "a/jun_java_plugins/jun_poi_tl_word_export/start/\347\256\200\345\216\206\346\250\241\346\235\2772.docx" and /dev/null differ diff --git "a/jun_java_plugins/jun_poi_tl_word_export/start/\347\256\200\345\216\206\346\250\241\346\235\277output416.docx" "b/jun_java_plugins/jun_poi_tl_word_export/start/\347\256\200\345\216\206\346\250\241\346\235\277output416.docx" deleted file mode 100644 index b6eac9ab11..0000000000 Binary files "a/jun_java_plugins/jun_poi_tl_word_export/start/\347\256\200\345\216\206\346\250\241\346\235\277output416.docx" and /dev/null differ diff --git a/jun_java_plugins/jun_qrcode/pom.xml b/jun_java_plugins/jun_qrcode/pom.xml deleted file mode 100644 index c1b18828db..0000000000 --- a/jun_java_plugins/jun_qrcode/pom.xml +++ /dev/null @@ -1,79 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_qrcode - 1.0 - war - - - UTF-8 - - - - - junit - junit - 4.13 - - - com.google.zxing - core - 3.4.0 - - - - com.google.zxing - javase - 2.2 - - - - com.google.guava - guava - 29.0-jre - - - org.slf4j - slf4j-api - 1.7.22 - - - org.slf4j - slf4j-log4j12 - 1.7.22 - test - - - commons-io - commons-io - 2.7 - - - org.testng - testng - 6.9.10 - test - - - - - - - - - - - - mysql - mysql-connector-java - 5.1.40 - - - - jun_qrcode - - diff --git a/jun_java_plugins/jun_qrcode/src/main/java/com/jun/plugin/zxing/support/BufferedImageLuminanceSource.java b/jun_java_plugins/jun_qrcode/src/main/java/com/jun/plugin/zxing/support/BufferedImageLuminanceSource.java deleted file mode 100644 index b3d01ab01a..0000000000 --- a/jun_java_plugins/jun_qrcode/src/main/java/com/jun/plugin/zxing/support/BufferedImageLuminanceSource.java +++ /dev/null @@ -1,107 +0,0 @@ -/** - * Copyright 2013 ABSir's Studio - * - * All right reserved - * - * Create on 2013-8-13 上午10:44:44 - */ -package com.jun.plugin.zxing.support; - -import java.awt.Graphics2D; -import java.awt.geom.AffineTransform; -import java.awt.image.BufferedImage; - -import com.google.zxing.LuminanceSource; - -/** - * @author absir - * - */ -public class BufferedImageLuminanceSource extends LuminanceSource { - - private final BufferedImage image; - private final int left; - private final int top; - - public BufferedImageLuminanceSource(BufferedImage image) { - this(image, 0, 0, image.getWidth(), image.getHeight()); - } - - public BufferedImageLuminanceSource(BufferedImage image, int left, int top, int width, int height) { - super(width, height); - - int sourceWidth = image.getWidth(); - int sourceHeight = image.getHeight(); - if (left + width > sourceWidth || top + height > sourceHeight) { - throw new IllegalArgumentException("Crop rectangle does not fit within image data."); - } - - for (int y = top; y < top + height; y++) { - for (int x = left; x < left + width; x++) { - if ((image.getRGB(x, y) & 0xFF000000) == 0) { - image.setRGB(x, y, 0xFFFFFFFF); // = white - } - } - } - - this.image = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY); - this.image.getGraphics().drawImage(image, 0, 0, null); - this.left = left; - this.top = top; - } - - @Override - public byte[] getRow(int y, byte[] row) { - if (y < 0 || y >= getHeight()) { - throw new IllegalArgumentException("Requested row is outside the image: " + y); - } - int width = getWidth(); - if (row == null || row.length < width) { - row = new byte[width]; - } - image.getRaster().getDataElements(left, top + y, width, 1, row); - return row; - } - - @Override - public byte[] getMatrix() { - int width = getWidth(); - int height = getHeight(); - int area = width * height; - byte[] matrix = new byte[area]; - image.getRaster().getDataElements(left, top, width, height, matrix); - return matrix; - } - - @Override - public boolean isCropSupported() { - return true; - } - - @Override - public LuminanceSource crop(int left, int top, int width, int height) { - return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height); - } - - @Override - public boolean isRotateSupported() { - return true; - } - - @Override - public LuminanceSource rotateCounterClockwise() { - int sourceWidth = image.getWidth(); - int sourceHeight = image.getHeight(); - - AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth); - - BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY); - - Graphics2D g = rotatedImage.createGraphics(); - g.drawImage(image, transform, null); - g.dispose(); - - int width = getWidth(); - return new BufferedImageLuminanceSource(rotatedImage, top, sourceWidth - (left + width), getHeight(), width); - } -} diff --git a/jun_java_plugins/jun_qrcode/src/main/java/com/jun/plugin/zxing/support/BufferedImageSource.java b/jun_java_plugins/jun_qrcode/src/main/java/com/jun/plugin/zxing/support/BufferedImageSource.java deleted file mode 100644 index 8c3293ffc3..0000000000 --- a/jun_java_plugins/jun_qrcode/src/main/java/com/jun/plugin/zxing/support/BufferedImageSource.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright 2013 ABSir's Studio - * - * All right reserved - * - * Create on 2013-8-13 上午10:56:54 - */ -package com.jun.plugin.zxing.support; - -import java.awt.image.BufferedImage; - -/** - * @author absir - * - */ -public class BufferedImageSource { - - /** width */ - private int width; - - /** height */ - private int height; - - /** rgbas */ - private byte[] rgbas; - - /** - * @param image - */ - public BufferedImageSource(BufferedImage bufferedImage) { - width = bufferedImage.getWidth(); - height = bufferedImage.getHeight(); - rgbas = new byte[width * height * 4]; - int k = 0; - for (int i = 0; i < width; i++) { - for (int j = 0; j < height; j++) { - int pixel = bufferedImage.getRGB(i, j); - rgbas[k++] = (byte) ((pixel) & 0xff); - rgbas[k++] = (byte) ((pixel >> 8) & 0xff); - rgbas[k++] = (byte) ((pixel >> 16) & 0xff); - rgbas[k++] = (byte) ((pixel >> 24) & 0xff); - } - } - } -} diff --git a/jun_java_plugins/jun_qrcode/src/main/java/com/jun/plugin/zxing/support/BufferedImageUtils.java b/jun_java_plugins/jun_qrcode/src/main/java/com/jun/plugin/zxing/support/BufferedImageUtils.java deleted file mode 100644 index 5d712ecf9c..0000000000 --- a/jun_java_plugins/jun_qrcode/src/main/java/com/jun/plugin/zxing/support/BufferedImageUtils.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Copyright 2013 ABSir's Studio - * - * All right reserved - * - * Create on 2013-8-13 上午11:40:24 - */ -package com.jun.plugin.zxing.support; - -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.image.BufferedImage; -import java.awt.image.ImageObserver; - -/** - * @author absir - * - */ -public class BufferedImageUtils { - - /** - * @param image - * @return - */ - public static BufferedImage getBufferedImage(Image image) { - return getBufferedImage(image, image.getWidth(null), image.getHeight(null)); - } - - /** - * @param image - * @param width - * @param height - * @return - */ - public static BufferedImage getBufferedImage(Image image, int width, int height) { - return getBufferedImage(image, width, height, BufferedImage.TYPE_INT_ARGB); - } - - /** - * @param image - * @param width - * @param height - * @param imageType - * @return - */ - public static BufferedImage getBufferedImage(Image image, int width, int height, int imageType) { - BufferedImage bufferedImage = new BufferedImage(width, height, imageType); - Graphics2D g = bufferedImage.createGraphics(); - g.drawImage(image, 0, 0, width, height, 0, 0, image.getWidth(null), image.getHeight(null), null); - waitForImage(bufferedImage); - return bufferedImage; - } - - /** - * @param bufferedImage - */ - private static void waitForImage(BufferedImage bufferedImage) { - bufferedImage.getHeight(new ImageObserver() { - public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) { - if (infoflags == ALLBITS) { - return true; - } - - return false; - } - }); - } - -} diff --git a/jun_java_plugins/jun_qrcode/src/main/webapp/WEB-INF/web (2).xml b/jun_java_plugins/jun_qrcode/src/main/webapp/WEB-INF/web (2).xml deleted file mode 100644 index 9f88c1f963..0000000000 --- a/jun_java_plugins/jun_qrcode/src/main/webapp/WEB-INF/web (2).xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - Archetype Created Web Application - diff --git a/jun_java_plugins/jun_qrcode/src/main/webapp/WEB-INF/web.xml b/jun_java_plugins/jun_qrcode/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 100489b942..0000000000 --- a/jun_java_plugins/jun_qrcode/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - jun_test - - index.html - index.htm - index.jsp - default.html - default.htm - default.jsp - - \ No newline at end of file diff --git a/jun_java_plugins/jun_qrcode/src/test/java/ReadLogoTest.java b/jun_java_plugins/jun_qrcode/src/test/java/ReadLogoTest.java deleted file mode 100644 index 6fed9a746a..0000000000 --- a/jun_java_plugins/jun_qrcode/src/test/java/ReadLogoTest.java +++ /dev/null @@ -1,21 +0,0 @@ -import org.junit.Test; - -import com.google.zxing.BinaryBitmap; -import com.google.zxing.ChecksumException; -import com.google.zxing.FormatException; -import com.google.zxing.LuminanceSource; -import com.google.zxing.NotFoundException; -import com.google.zxing.common.HybridBinarizer; -import com.google.zxing.qrcode.QRCodeReader; -import com.jun.plugin.zxing.support.BufferedImageLuminanceSource; - - -public class ReadLogoTest { - - @Test - public void test() throws NotFoundException, ChecksumException, FormatException { - LuminanceSource luminanceSource = new BufferedImageLuminanceSource(null); - QRCodeReader qrCodeReader = new QRCodeReader(); - qrCodeReader.decode(new BinaryBitmap(new HybridBinarizer(luminanceSource))); - } -} diff --git a/jun_java_plugins/jun_quartz/doc/quartz/test.jsp b/jun_java_plugins/jun_quartz/doc/quartz/test.jsp deleted file mode 100644 index e558025e0a..0000000000 --- a/jun_java_plugins/jun_quartz/doc/quartz/test.jsp +++ /dev/null @@ -1,51 +0,0 @@ -<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> -<%@page import="org.quartz.*"%> -<%@page import="org.quartz.impl.*"%> -<%@page import="org.springframework.scheduling.quartz.*"%> -<%@page import="com.jun.plugin.teamplate.common.*"%> -<%@page import="java.text.*"%> -<%@page import="java.util.*"%> - -<% - String cronExpression = request.getParameter("cronExpression"); - - CronTriggerBean dataSyncTrigger=(CronTriggerBean)ServiceLocator.getService("dataSyncTrigger"); - try { - dataSyncTrigger.setCronExpression(cronExpression); - } catch (ParseException e) { - e.printStackTrace(); - } - - StdScheduler scheduler = (StdScheduler)ServiceLocator.getService("schedulerFactoryBean"); - try { - scheduler.rescheduleJob(dataSyncTrigger.getName(), scheduler.DEFAULT_GROUP, dataSyncTrigger); - } catch (SchedulerException e) { - e.printStackTrace(); - } -%> - - - - - - - - - - - - - - -
- <%=dataSyncTrigger.getCronExpression()%>   - -
- - - - - - diff --git a/jun_java_plugins/jun_quartz/pom.xml b/jun_java_plugins/jun_quartz/pom.xml deleted file mode 100644 index cddc862544..0000000000 --- a/jun_java_plugins/jun_quartz/pom.xml +++ /dev/null @@ -1,199 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_quartz - 1.0 - war - - - UTF-8 - 5.0.8.RELEASE - 1.9.13 - 2.5.1 - 1.0.18 - - 4.12 - 1.8 - UTF-8 - 1.7.25 - 2.8.2 - 2.2.3 - 1.1.9 - 1.2.17 - - - - - - org.slf4j - slf4j-api - 1.6.1 - - - - org.springframework - spring-core - ${spring.version} - - - org.springframework - spring-expression - ${spring.version} - - - org.springframework - spring-beans - ${spring.version} - - - org.springframework - spring-aop - ${spring.version} - - - org.springframework - spring-orm - ${spring.version} - - - org.springframework - spring-web - ${spring.version} - - - org.springframework - spring-webmvc - ${spring.version} - - - org.springframework - spring-oxm - ${spring.version} - - - - mysql - mysql-connector-java - 5.1.39 - - - - junit - junit - ${junit-version} - test - - - - org.apache.commons - commons-lang3 - 3.4 - - - - commons-collections - commons-collections - 3.2.2 - - - - com.alibaba - druid - ${druid-version} - - - - org.quartz-scheduler - quartz - ${quartz-version} - - - org.quartz-scheduler - quartz-jobs - ${quartz-version} - - - - - org.apache.logging.log4j - log4j-core - ${log4j-version} - - - - org.apache.logging.log4j - log4j-slf4j-impl - ${log4j-version} - - - - org.apache.logging.log4j - log4j-jcl - ${log4j-version} - - - - com.alibaba - fastjson - ${fastjson-version} - - - - - - - javax.servlet - javax.servlet-api - 3.1.0 - provided - - - - com.oracle - ojdbc6 - 11.2.0.3 - - - - org.springframework - spring-context - ${spring.version} - - - - org.springframework - spring-context-support - ${spring.version} - - - - org.springframework - spring-jdbc - ${spring.version} - - - - org.springframework - spring-tx - ${spring.version} - - - - - org.springframework - spring-test - ${spring.version} - test - - - - - - - jun_quartz - - diff --git a/jun_java_plugins/jun_quartz/src/main/java/com/jun/plugin/quartz/job/PrintWordsJob.java b/jun_java_plugins/jun_quartz/src/main/java/com/jun/plugin/quartz/job/PrintWordsJob.java deleted file mode 100644 index 5d38adbebb..0000000000 --- a/jun_java_plugins/jun_quartz/src/main/java/com/jun/plugin/quartz/job/PrintWordsJob.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.jun.plugin.quartz.job; - -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Random; - -import org.quartz.Job; -import org.quartz.JobExecutionContext; -import org.quartz.JobExecutionException; - -/** - * Description: 打印任意内容 - */ -public class PrintWordsJob implements Job{ - - @Override - public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { - String printTime = new SimpleDateFormat("yy-MM-dd HH-mm-ss").format(new Date()); - System.out.println("PrintWordsJob start at:" + printTime + ", prints: Hello Job-" + new Random().nextInt(100)); - - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_quartz/src/main/java/com/jun/plugin/quartz/schedule/MyScheduler.java b/jun_java_plugins/jun_quartz/src/main/java/com/jun/plugin/quartz/schedule/MyScheduler.java deleted file mode 100644 index 163bf9d6d2..0000000000 --- a/jun_java_plugins/jun_quartz/src/main/java/com/jun/plugin/quartz/schedule/MyScheduler.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.jun.plugin.quartz.schedule; - -import java.util.concurrent.TimeUnit; - -import org.quartz.JobBuilder; -import org.quartz.JobDetail; -import org.quartz.Scheduler; -import org.quartz.SchedulerException; -import org.quartz.SchedulerFactory; -import org.quartz.SimpleScheduleBuilder; -import org.quartz.Trigger; -import org.quartz.TriggerBuilder; -import org.quartz.impl.StdSchedulerFactory; - -import com.jun.plugin.quartz.job.PrintWordsJob; - -public class MyScheduler { - - public static void main(String[] args) throws SchedulerException, InterruptedException { - // 1、创建调度器Scheduler - SchedulerFactory schedulerFactory = new StdSchedulerFactory(); - Scheduler scheduler = schedulerFactory.getScheduler(); - // 2、创建JobDetail实例,并与PrintWordsJob类绑定(Job执行内容) - JobDetail jobDetail = JobBuilder.newJob(PrintWordsJob.class) - .withIdentity("job1", "group1").build(); - // 3、构建Trigger实例,每隔1s执行一次 - Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "triggerGroup1") - .startNow()//立即生效 - .withSchedule(SimpleScheduleBuilder.simpleSchedule() - .withIntervalInSeconds(1)//每隔1s执行一次 - .repeatForever()).build();//一直执行 - - //4、执行 - scheduler.scheduleJob(jobDetail, trigger); - System.out.println("--------scheduler start ! ------------"); - scheduler.start(); - - //睡眠 - TimeUnit.MINUTES.sleep(1); - scheduler.shutdown(); - System.out.println("--------scheduler shutdown ! ------------"); - - - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_quartz/src/main/java/com/jun/plugin/quartz/schedule/MyScheduler2.java b/jun_java_plugins/jun_quartz/src/main/java/com/jun/plugin/quartz/schedule/MyScheduler2.java deleted file mode 100644 index 15f181d790..0000000000 --- a/jun_java_plugins/jun_quartz/src/main/java/com/jun/plugin/quartz/schedule/MyScheduler2.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.jun.plugin.quartz.schedule; - -import java.util.Date; - -import org.quartz.CronScheduleBuilder; -import org.quartz.CronTrigger; -import org.quartz.JobBuilder; -import org.quartz.JobDetail; -import org.quartz.Scheduler; -import org.quartz.SchedulerException; -import org.quartz.SchedulerFactory; -import org.quartz.TriggerBuilder; -import org.quartz.impl.StdSchedulerFactory; - -import com.jun.plugin.quartz.job.PrintWordsJob; - -public class MyScheduler2 { - public static void main(String[] args) throws SchedulerException, InterruptedException { - // 1、创建调度器Scheduler - SchedulerFactory schedulerFactory = new StdSchedulerFactory(); - Scheduler scheduler = schedulerFactory.getScheduler(); - // 2、创建JobDetail实例,并与PrintWordsJob类绑定(Job执行内容) - JobDetail jobDetail = JobBuilder.newJob(PrintWordsJob.class) - .usingJobData("jobDetail1", "这个Job用来测试的") - .withIdentity("job1", "group1").build(); - // 3、构建Trigger实例,每隔1s执行一次 - Date startDate = new Date(); - startDate.setTime(startDate.getTime() + 5000); - - Date endDate = new Date(); - endDate.setTime(startDate.getTime() + 5000); - - CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "triggerGroup1") - .usingJobData("trigger1", "这是jobDetail1的trigger") - .startNow()//立即生效 - .startAt(startDate) - .endAt(endDate) - .withSchedule(CronScheduleBuilder.cronSchedule("* 30 10 ? * 1/5 2018")) - .build(); - - //4、执行 - scheduler.scheduleJob(jobDetail, cronTrigger); - System.out.println("--------scheduler start ! ------------"); - scheduler.start(); - System.out.println("--------scheduler shutdown ! ------------"); - - } -} -//原文链接:https://blog.csdn.net/noaman_wgs/article/details/80984873 \ No newline at end of file diff --git a/jun_java_plugins/jun_quartz/src/main/webapp/WEB-INF/web.xml b/jun_java_plugins/jun_quartz/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 100489b942..0000000000 --- a/jun_java_plugins/jun_quartz/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - jun_test - - index.html - index.htm - index.jsp - default.html - default.htm - default.jsp - - \ No newline at end of file diff --git a/jun_java_plugins/jun_quartz/src/main/webapp/index (2).jsp b/jun_java_plugins/jun_quartz/src/main/webapp/index (2).jsp deleted file mode 100644 index c38169bb95..0000000000 --- a/jun_java_plugins/jun_quartz/src/main/webapp/index (2).jsp +++ /dev/null @@ -1,5 +0,0 @@ - - -

Hello World!

- - diff --git a/jun_java_plugins/jun_redis/pom.xml b/jun_java_plugins/jun_redis/pom.xml deleted file mode 100644 index bcb6211ce9..0000000000 --- a/jun_java_plugins/jun_redis/pom.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_redis - 1.0 - - - 1.7 - 2.16 - 1.7.2 - 2.3.0 - 1.0.9 - UTF-8 - - - - - - org.springframework.data - spring-data-redis - 2.0.1.RELEASE - - - redis.clients - jedis - 2.9.0 - - - org.springframework - spring-test - 5.0.1.RELEASE - - - - com.fasterxml.jackson.core - jackson-core - ${jackson.version} - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - com.fasterxml.jackson.core - jackson-annotations - ${jackson.version} - - - - com.google.guava - guava - 18.0 - - - - - org.slf4j - slf4j-api - ${slf4j.version} - - - ch.qos.logback - logback-classic - 1.0.9 - test - - - ch.qos.logback - logback-core - 1.0.9 - test - - - - junit - junit - 4.11 - test - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_redis/shiro-redis/README.md b/jun_java_plugins/jun_redis/shiro-redis/README.md deleted file mode 100644 index 0ff29fc4f0..0000000000 --- a/jun_java_plugins/jun_redis/shiro-redis/README.md +++ /dev/null @@ -1,24 +0,0 @@ -**shiro-redis** - -shiro集成redis的适配器,为解决shrio-ehcache不利于集群而打造的缓存集群方案。 - -**Maven坐标** -``` - - org.iherus.shiro - shiro-redis - 1.0.0 - -``` - - -更多正在补充中。。。。。 :smile: - - -**Features** - -欢迎提出更好的意见,帮助完善 shiro-redis - -**Copyright** - -Apache License, Version 2.0 \ No newline at end of file diff --git a/jun_java_plugins/jun_redis/shiro-redis/pom.xml b/jun_java_plugins/jun_redis/shiro-redis/pom.xml deleted file mode 100644 index eedc6a6438..0000000000 --- a/jun_java_plugins/jun_redis/shiro-redis/pom.xml +++ /dev/null @@ -1,166 +0,0 @@ - - 4.0.0 - - org.iherus.shiro - shiro-redis - 1.0.0 - jar - - shiro-redis - Shiro cache Integration Adapter. - http://maven.apache.org - - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - - - - - - Bosco.Liao - bosco_liao@126.com - - - - - scm:git:git@git.oschina.net:iherus/shiro-redis.git - scm:git:git@git.oschina.net:iherus/shiro-redis.git - git@git.oschina.net:iherus/shiro-redis.git - v1.0.0 - - - - UTF-8 - 1.2.4 - 2.8.1 - 1.7.21 - 1.7.21 - 1.2 - 4.12 - - - - - org.apache.shiro - shiro-core - ${shiro.version} - compile - - - - redis.clients - jedis - ${jedis.version} - compile - - - - org.slf4j - slf4j-api - ${slf4j.api.version} - compile - - - - org.slf4j - slf4j-log4j12 - ${slf4j.log4j12.version} - compile - - - - commons-logging - commons-logging - ${commons.logging.version} - - - - junit - junit - ${junit.version} - test - - - - - - release - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.5.1 - - 1.7 - 1.7 - - - - org.apache.maven.plugins - maven-source-plugin - 3.0.0 - - true - - - - attach-sources - package - - jar-no-fork - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.10.3 - - true - UTF-8 - - - - attach-javadocs - package - - jar - - - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.6 - - - sign-artifacts - verify - - sign - - - - - - - - - oss - https://oss.sonatype.org/content/repositories/snapshots - - - oss - https://oss.sonatype.org/service/local/staging/deploy/maven2 - - - - - - diff --git a/jun_java_plugins/jun_redis/shiro-redis/src/main/java/org/iherus/shiro/cache/redis/RedisCache.java b/jun_java_plugins/jun_redis/shiro-redis/src/main/java/org/iherus/shiro/cache/redis/RedisCache.java deleted file mode 100644 index c4285ad5fa..0000000000 --- a/jun_java_plugins/jun_redis/shiro-redis/src/main/java/org/iherus/shiro/cache/redis/RedisCache.java +++ /dev/null @@ -1,325 +0,0 @@ -/** - * Copyright (c) 2016-~, Bosco.Liao (bosco_liao@126.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package org.iherus.shiro.cache.redis; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; - -import org.apache.shiro.cache.Cache; -import org.apache.shiro.cache.CacheException; -import org.apache.shiro.util.CollectionUtils; -import org.iherus.shiro.util.ArrayUtils; -import org.iherus.shiro.util.SerializeUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import redis.clients.jedis.Jedis; -import redis.clients.util.SafeEncoder; - -/** - *

缓存接口实现类

- *

Description:实现Shiro缓存接口,提供远程获取缓存对象、远程保存缓存对象和远程清空缓存库等功能

- * @author Wujun - * @version 1.0.0 - * @date 2016年4月11日-下午4:06:06 - */ -public class RedisCache implements Cache, Serializable { - - /** - * Required for serialization support. - * - * @see java.io.Serializable - */ - private static final long serialVersionUID = 4521785299624111291L; - - /** - * Private internal log instance. - */ - private static final Logger logger = LoggerFactory.getLogger(RedisCache.class); - - /** - * Default Shiro cache name. - */ - private static final String DEFAULT_CACHE_NAME = "shiro_redis_cache"; - - /** - * Shiro cache name. - */ - private String name = DEFAULT_CACHE_NAME; - - /** - * Shiro cache key prefix. - */ - private String shiroCacheKeyPrefix; - - /** - * The wrapped RedisCachePool instance. - */ - protected RedisCachePool cachePool; - - /** - * Constructs a new RedisCache instance with the given CachePool. - */ - public RedisCache(RedisCachePool cachePool) { - this.cachePool = cachePool; - } - - /** - * Constructs a new RedisCache instance with the given CachePool and name. - */ - public RedisCache(RedisCachePool cachePool, final String name) { - if (cachePool == null) { - throw new IllegalArgumentException("CachePool argument cannot be null."); - } - this.cachePool = cachePool; - this.name = name; - } - - /** - * Gets bytes key with key prefix. - */ - private final byte[] getKeyToBytes(K key) { - if (key instanceof byte[]) { - return (byte[]) key; - } - final byte[] preBytes = getPrefixToBytes(); - byte[] keyBytes = SerializeUtils.serialize(key); - return ArrayUtils.mergeAll(preBytes, keyBytes); - } - - /** - * Gets key prefix to byte[]. - */ - private final byte[] getPrefixToBytes() { - return SafeEncoder.encode(getShiroCacheKeyPrefix()); - } - - /** - * Gets pattern to byte[] base on prefix. - */ - private final byte[] getKeyPattern() { - return SafeEncoder.encode(getShiroCacheKeyPrefix() + "*"); - } - - @Override - @SuppressWarnings("unchecked") - public V get(K key) throws CacheException { - if (logger.isDebugEnabled()) { - logger.debug("Getting object from cache [" + getName() + "] for key [" + key + "]"); - } - Jedis jedis = initJedis(cachePool); - try { - if (key == null) { - return null; - } else { - byte[] value = jedis.get(getKeyToBytes(key)); - if (value == null) { - if (logger.isDebugEnabled()) { - logger.debug("Cache for [" + key + "] is null."); - } - return null; - } else { - if (logger.isDebugEnabled()) { - logger.debug("Cache for [" + key + "] is exist, ready to use it."); - } - return (V) SerializeUtils.deserialize(value); - } - } - } catch (Throwable t) { - throw new CacheException(t); - } finally { - close(jedis); - } - } - - @Override - public V put(K key, V value) throws CacheException { - if (logger.isDebugEnabled()) { - logger.debug("Putting object in cache [" + getName() + "] for key [" + key + "]"); - } - Jedis jedis = initJedis(cachePool); - try { - V previous = get(key); - byte[] nval = SerializeUtils.serialize(value); - jedis.set(getKeyToBytes(key), nval); - return previous; - } catch (Throwable t) { - throw new CacheException(t); - } finally { - close(jedis); - } - } - - @Override - public V remove(K key) throws CacheException { - if (logger.isDebugEnabled()) { - logger.debug("Removing object from cache [" + getName() + "] for key [" + key + "]"); - } - Jedis jedis = initJedis(cachePool); - try { - V previous = get(key); - long statusCode = jedis.del(getKeyToBytes(key)); - if (statusCode > 0) { - if (logger.isInfoEnabled()) { - logger.info("Remove key [{}] successfully.", key); - } - } - return previous; - } catch (Throwable t) { - throw new CacheException(t); - } finally { - close(jedis); - } - } - - @Override - public void clear() throws CacheException { - if (logger.isDebugEnabled()) { - logger.debug("Clearing all objects from cache [" + getName() + "]"); - } - Jedis jedis = initJedis(cachePool); - try { - String statusCode = jedis.flushDB(); - /** - * Temporarily clear the current DB. If the intensity is too large, - * then could remove value base on the keys. - */ - //jedis.del(keys); - if ("OK".equalsIgnoreCase(statusCode)) { - if (logger.isInfoEnabled()) { - logger.info("Flush DB_{} successfully.", jedis.getDB()); - } - } - } catch (Throwable t) { - throw new CacheException(t); - } finally { - close(jedis); - } - } - - @Override - public int size() { - Jedis jedis = initJedis(cachePool); - try { - long size = jedis.dbSize(); - return Long.valueOf(size).intValue(); - } catch (Throwable t) { - throw new CacheException(t); - } finally { - close(jedis); - } - } - - @Override - @SuppressWarnings("unchecked") - public Set keys() { - Jedis jedis = initJedis(cachePool); - try { - Set keySet = jedis.keys(getKeyPattern()); - if (!CollectionUtils.isEmpty(keySet)) { - Set keys = new LinkedHashSet(); - for (byte[] key : keySet) { - keys.add((K) key); - } - return keys; - } else { - return Collections.emptySet(); - } - } catch (Throwable t) { - throw new CacheException(t); - } finally { - close(jedis); - } - } - - @Override - public Collection values() { - try { - Set keys = keys(); - if (!CollectionUtils.isEmpty(keys)) { - List values = new ArrayList(keys.size()); - for (K key : keys) { - V value = get(key); - if (value != null) { - values.add(value); - } - } - return Collections.unmodifiableList(values); - } else { - return Collections.emptyList(); - } - } catch (Throwable t) { - throw new CacheException(t); - } - } - - /** - * Constructs a Jedis instance. - */ - public static Jedis initJedis(final RedisCachePool cachePool) { - if (cachePool == null) { - throw new IllegalArgumentException("CachePool argument cannot be null."); - } - Jedis jedis = null; - try { - jedis = cachePool.getResource(); - jedis.select(cachePool.getDatabaseIndex()); - if (logger.isDebugEnabled()) { - logger.debug("The current application database is located in DB_{}.", jedis.getDB()); - } - return jedis; - } catch (Exception e) { - close(jedis); //If throw exception, and Jedis is not null, then close Jedis instance. - throw new CacheException(e); - } - } - - /** - * Close Jedis instance. - */ - public static void close(final Jedis jedis) { - if (jedis != null) { - jedis.close(); - } - } - - @Override - public String toString() { - return "RedisCache [" + getName() + "]"; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getShiroCacheKeyPrefix() { - return shiroCacheKeyPrefix; - } - - public void setShiroCacheKeyPrefix(String shiroCacheKeyPrefix) { - this.shiroCacheKeyPrefix = shiroCacheKeyPrefix; - } - -} diff --git a/jun_java_plugins/jun_redis/shiro-redis/src/main/java/org/iherus/shiro/cache/redis/RedisCacheConfigFactory.java b/jun_java_plugins/jun_redis/shiro-redis/src/main/java/org/iherus/shiro/cache/redis/RedisCacheConfigFactory.java deleted file mode 100644 index 0481951a5c..0000000000 --- a/jun_java_plugins/jun_redis/shiro-redis/src/main/java/org/iherus/shiro/cache/redis/RedisCacheConfigFactory.java +++ /dev/null @@ -1,147 +0,0 @@ -/** - * Copyright (c) 2016-~, Bosco.Liao (bosco_liao@126.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package org.iherus.shiro.cache.redis; - -import java.io.Serializable; - -import redis.clients.jedis.JedisPoolConfig; -import redis.clients.jedis.Protocol; - -/** - *

客户端配置工厂

- *

Description:缓存池主要依赖本工厂实现实例化

- * @author Wujun - * @version 1.0.0 - * @date 2016年4月11日-下午4:05:08 - */ -public class RedisCacheConfigFactory implements Serializable { - - /** - * Required for serialization support. - * - * @see java.io.Serializable - */ - private static final long serialVersionUID = 6348565977009073672L; - - private static final String DEFAULT_HOST = "127.0.0.1"; - - private static final String DEFAULT_CLIENT_NAME = "shiro-cache"; - - private static final int DEFAULT_DATABASE = 2; - - protected String host = DEFAULT_HOST; - - protected int port = Protocol.DEFAULT_PORT; - - protected int timeout = Protocol.DEFAULT_TIMEOUT; - - protected int database = DEFAULT_DATABASE; - - protected String password = null; - - protected String clientName = DEFAULT_CLIENT_NAME; - - /** - * JedisPoolConfig - */ - protected JedisPoolConfig poolConfig = null; - - /** - * Default constructor - */ - public RedisCacheConfigFactory() { - if (poolConfig == null) { - this.poolConfig = new JedisPoolConfig(); - } - } - - public String getHost() { - return host; - } - - public void setHost(String host) { - this.host = host; - } - - public int getPort() { - return port; - } - - public void setPort(int port) { - this.port = port; - } - - public int getTimeout() { - return timeout; - } - - public void setTimeout(int timeout) { - this.timeout = timeout; - } - - public int getDatabase() { - return database; - } - - public void setDatabase(int database) { - this.database = database; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getClientName() { - return clientName; - } - - public void setClientName(String clientName) { - this.clientName = clientName; - } - - public JedisPoolConfig getPoolConfig() { - return poolConfig; - } - - public void setPoolConfig(JedisPoolConfig poolConfig) { - this.poolConfig = poolConfig; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((clientName == null) ? 0 : clientName.hashCode()); - result = prime * result + database; - result = prime * result + ((host == null) ? 0 : host.hashCode()); - result = prime * result + ((password == null) ? 0 : password.hashCode()); - result = prime * result + ((poolConfig == null) ? 0 : poolConfig.hashCode()); - result = prime * result + port; - result = prime * result + timeout; - return result; - } - - @Override - public String toString() { - return "RedisConfig [host=" + host + ", port=" + port + ", timeout=" + timeout + ", database=" + database - + ", password=" + password + ", clientName=" + clientName + ", poolConfig=" + poolConfig + "]"; - } - -} diff --git a/jun_java_plugins/jun_redis/shiro-redis/src/main/java/org/iherus/shiro/cache/redis/RedisCacheManager.java b/jun_java_plugins/jun_redis/shiro-redis/src/main/java/org/iherus/shiro/cache/redis/RedisCacheManager.java deleted file mode 100644 index 777be3f085..0000000000 --- a/jun_java_plugins/jun_redis/shiro-redis/src/main/java/org/iherus/shiro/cache/redis/RedisCacheManager.java +++ /dev/null @@ -1,148 +0,0 @@ -/** - * Copyright (c) 2016-~, Bosco.Liao (bosco_liao@126.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package org.iherus.shiro.cache.redis; - -import org.apache.shiro.ShiroException; -import org.apache.shiro.cache.Cache; -import org.apache.shiro.cache.CacheException; -import org.apache.shiro.cache.CacheManager; -import org.apache.shiro.util.Destroyable; -import org.apache.shiro.util.Initializable; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - *

缓存管理器

- *

Description:管理缓存池的初始化、获取当前缓存对象和销毁缓存池

- * @author Wujun - * @version 1.0.0 - * @date 2016年4月11日-下午4:03:01 - */ -public class RedisCacheManager implements CacheManager, Initializable, Destroyable { - - /** - * Private internal log instance. - */ - private static final Logger logger = LoggerFactory.getLogger(RedisCacheManager.class); - - private static final String DEFAULT_CACHE_KEY_PREFIX = "shiro_cache_"; - - /** - * The cache pool used by this implementation to create caches. - */ - protected RedisCachePool cachePool; - - /** - * Set a Default key prefix for all caches. - */ - private String shiroCacheKeyPrefix = DEFAULT_CACHE_KEY_PREFIX; - - /** - * The cache pool base on this factory - */ - private RedisCacheConfigFactory configFactory; - - /** - * Indicates if the CachePool instance was implicitly/automatically created - * by this instance, indicating that it should be automatically destroy. - */ - private boolean cachePoolImplicitlyCreated = false; - - /** - * Default constructor - */ - public RedisCacheManager() { - - } - - public RedisCachePool getCachePool() { - return cachePool; - } - - public String getShiroCacheKeyPrefix() { - return shiroCacheKeyPrefix; - } - - public void setShiroCacheKeyPrefix(String shiroCacheKeyPrefix) { - this.shiroCacheKeyPrefix = shiroCacheKeyPrefix; - } - - public RedisCacheConfigFactory getConfigFactory() { - return configFactory; - } - - public void setConfigFactory(RedisCacheConfigFactory configFactory) { - this.configFactory = configFactory; - } - - @Override - public final void init() throws ShiroException { - ensureCacheManager(); - } - - /** - * Initialize the cache pool. If current cache pool is null, - * then create CachePool instance, else use the exist. - */ - private RedisCachePool ensureCacheManager() { - try { - if (null == this.cachePool) { - if (logger.isDebugEnabled()) { - logger.debug("cachePoolManager property not set. Constructing cachePoolManager instance... "); - } - this.cachePool = new RedisCachePool(this.configFactory); - if (logger.isTraceEnabled()) { - logger.trace("instantiated Redis cachePool instance."); - } - this.cachePoolImplicitlyCreated = true; - if (logger.isDebugEnabled()) { - logger.debug("implicit cachePool created successfully."); - } - } - return this.cachePool; - } catch (Exception e) { - throw new CacheException(e); - } - } - - @Override - @SuppressWarnings({ "unchecked", "rawtypes" }) - public Cache getCache(String name) throws CacheException { - if (logger.isDebugEnabled()) { - logger.debug("Acquiring Cache instance named [" + name + "]"); - } - RedisCache redisCache = ensureCacheManager().getCache(name); - redisCache.setShiroCacheKeyPrefix(getShiroCacheKeyPrefix()); - return redisCache; - } - - @Override - public void destroy() throws Exception { - if (this.cachePoolImplicitlyCreated) { - try { - RedisCachePool cachePool = getCachePool(); - cachePool.destroy(); - } catch (Exception e) { - if (logger.isWarnEnabled()) { - logger.warn("Unable to cleanly shutdown implicitly created CachePool instance. " + - "Ignoring (shutting down)..."); - } - } - this.cachePoolImplicitlyCreated = false; - } - } - -} diff --git a/jun_java_plugins/jun_redis/shiro-redis/src/main/java/org/iherus/shiro/cache/redis/RedisCachePool.java b/jun_java_plugins/jun_redis/shiro-redis/src/main/java/org/iherus/shiro/cache/redis/RedisCachePool.java deleted file mode 100644 index 5238f80333..0000000000 --- a/jun_java_plugins/jun_redis/shiro-redis/src/main/java/org/iherus/shiro/cache/redis/RedisCachePool.java +++ /dev/null @@ -1,116 +0,0 @@ -/** - * Copyright (c) 2016-~, Bosco.Liao (bosco_liao@126.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package org.iherus.shiro.cache.redis; - -import java.io.Serializable; - -import org.apache.shiro.cache.CacheException; -import org.iherus.shiro.util.SerializeUtils; -import org.iherus.shiro.util.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisPool; - -/** - *

缓存池

- *

Description:主要作用于JedisPool的实例化和提供获取当前池内缓存对象功能

- * @author Wujun - * @version 1.0.0 - * @date 2016年4月11日-下午3:59:53 - */ -public class RedisCachePool extends JedisPool implements Serializable { - - /** - * Required for serialization support. - * - * @see java.io.Serializable - */ - private static final long serialVersionUID = -4990239742530217458L; - - /** - * Private internal log instance. - */ - private static final Logger logger = LoggerFactory.getLogger(RedisCachePool.class); - - /** - * The current application database. - */ - private int databaseIndex; - - /** - * Constructs a new RedisCache instance with the given factory. - */ - public RedisCachePool(RedisCacheConfigFactory factory) { - super(factory.getPoolConfig(), factory.host, factory.getPort(), factory.getTimeout(), factory.getPassword(), - factory.getDatabase(), factory.clientName); - - this.databaseIndex = factory.getDatabase(); - } - - /** - * Gets cache object from cache database. - */ - @SuppressWarnings("rawtypes") - public RedisCache getCache(final String name) { - - RedisCache cache = null; - - byte[] serializedValue = null; - - if (StringUtils.isNotEmpty(name)) { - Jedis jedis = null; - try { - jedis = this.getResource(); - byte[] key = name.getBytes(); - serializedValue = jedis.get(key); - if (serializedValue == null) { - if (logger.isInfoEnabled()) { - logger.info("Cache with name '{}' does not yet exist. Creating now.", name); - } - cache = new RedisCache(this, name); - serializedValue = SerializeUtils.serialize(cache); // serialized - jedis.set(key, serializedValue); - if (logger.isInfoEnabled()) { - logger.info("Added Cache named [" + name + "]"); - } - } else { - cache = (RedisCache) SerializeUtils.deserialize(serializedValue); - if (logger.isInfoEnabled()) { - logger.info("Using existing Cache named [" + cache.getName() + "]"); - } - } - return cache; - } catch (Exception e) { - throw new CacheException(e); - } finally { - jedis.close(); - } - } else { - return null; - } - } - - public int getDatabaseIndex() { - return databaseIndex; - } - - public void setDatabaseIndex(int databaseIndex) { - this.databaseIndex = databaseIndex; - } - -} diff --git a/jun_java_plugins/jun_redis/shiro-redis/src/main/java/org/iherus/shiro/exception/SerializationException.java b/jun_java_plugins/jun_redis/shiro-redis/src/main/java/org/iherus/shiro/exception/SerializationException.java deleted file mode 100644 index d253b07b11..0000000000 --- a/jun_java_plugins/jun_redis/shiro-redis/src/main/java/org/iherus/shiro/exception/SerializationException.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright (c) 2016-~, Bosco.Liao (bosco_liao@126.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package org.iherus.shiro.exception; - -/** - *

序列化异常类

- *

Description:供序列化工具使用.

- * @author Wujun - * @version 1.0.0 - * @date 2016年4月10日-下午10:49:36 - */ -public class SerializationException extends RuntimeException { - - /** - * - */ - private static final long serialVersionUID = -4301915165433653517L; - - - public SerializationException() { - super(); - } - - public SerializationException(final String message) { - super(message); - } - - - public SerializationException(final Throwable cause) { - super(cause); - } - - public SerializationException(final String message, final Throwable cause) { - super(message, cause); - } - -} diff --git a/jun_java_plugins/jun_redis/shiro-redis/src/main/java/org/iherus/shiro/util/ArrayUtils.java b/jun_java_plugins/jun_redis/shiro-redis/src/main/java/org/iherus/shiro/util/ArrayUtils.java deleted file mode 100644 index ce1b124289..0000000000 --- a/jun_java_plugins/jun_redis/shiro-redis/src/main/java/org/iherus/shiro/util/ArrayUtils.java +++ /dev/null @@ -1,264 +0,0 @@ -/** - * Copyright (c) 2016-~, Bosco.Liao (bosco_liao@126.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package org.iherus.shiro.util; - -import java.lang.reflect.Array; - -/** - *

数组工具类

- *

Description:提供常用的数组克隆、数组合并和截取子数组等功能

- * @author Wujun - * @version 1.0.0 - * @date 2016年4月12日-下午8:30:59 - */ -public final class ArrayUtils { - - public static final int[] EMPTY_INT_ARRAY = new int[0]; - - public static final char[] EMPTY_CHAR_ARRAY = new char[0]; - - public static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; - - private ArrayUtils() { - - } - - /** - *

- * Clones an array returning a typecast result and handling {@code null}. - *

- */ - public static int[] clone(final int[] array) { - if (array == null) { - return null; - } - return array.clone(); - } - - /** - *

- * Clones an array returning a typecast result and handling {@code null}. - *

- */ - public static char[] clone(final char[] array) { - if (array == null) { - return null; - } - return array.clone(); - } - - /** - *

- * Clones an array returning a typecast result and handling {@code null}. - *

- */ - public static byte[] clone(final byte[] array) { - if (array == null) { - return null; - } - return array.clone(); - } - - /** - *

- * Merges all the elements of the given arrays into a new array. - *

- */ - public static char[] mergeAll(final char[] array1, final char... array2) { - if (array1 == null) { - return clone(array2); - } else if (array2 == null) { - return clone(array1); - } - final char[] joinedArray = new char[array1.length + array2.length]; - System.arraycopy(array1, 0, joinedArray, 0, array1.length); - System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); - return joinedArray; - } - - /** - *

- * Merges all the elements of the given arrays into a new array. - *

- */ - public static byte[] mergeAll(final byte[] array1, final byte... array2) { - if (array1 == null) { - return clone(array2); - } else if (array2 == null) { - return clone(array1); - } - final byte[] joinedArray = new byte[array1.length + array2.length]; - System.arraycopy(array1, 0, joinedArray, 0, array1.length); - System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); - return joinedArray; - } - - /** - *

- * Merges all the elements of the given arrays into a new array. - *

- */ - public static int[] mergeAll(final int[] array1, final int... array2) { - if (array1 == null) { - return clone(array2); - } else if (array2 == null) { - return clone(array1); - } - final int[] joinedArray = new int[array1.length + array2.length]; - System.arraycopy(array1, 0, joinedArray, 0, array1.length); - System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); - return joinedArray; - } - - /** - *

- * Copies the given array and merges the given element at the end of the new - * array. - *

- */ - @SuppressWarnings("unchecked") - public static T[] merge(final T[] array, final T element) { - Class type; - if (array != null) { - type = array.getClass().getComponentType(); - } else if (element != null) { - type = element.getClass(); - } else { - throw new IllegalArgumentException("Arguments cannot both be null"); - } - final T[] newArray = (T[]) expandCopy(array, type); - newArray[newArray.length - 1] = element; - return newArray; - } - - /** - *

- * Produces a new {@code int} array containing the elements between the - * start and end indices. - *

- */ - public static int[] subarray(final int[] array, int startIndexInclusive, int endIndexExclusive) { - if (array == null) { - return null; - } - if (startIndexInclusive < 0) { - startIndexInclusive = 0; - } - if (endIndexExclusive > array.length) { - endIndexExclusive = array.length; - } - final int newSize = endIndexExclusive - startIndexInclusive; - if (newSize <= 0) { - return EMPTY_INT_ARRAY; - } - final int[] subarray = new int[newSize]; - System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); - return subarray; - } - - /** - *

- * Produces a new {@code char} array containing the elements between the - * start and end indices. - *

- */ - public static char[] subarray(final char[] array, int startIndexInclusive, int endIndexExclusive) { - if (array == null) { - return null; - } - if (startIndexInclusive < 0) { - startIndexInclusive = 0; - } - if (endIndexExclusive > array.length) { - endIndexExclusive = array.length; - } - final int newSize = endIndexExclusive - startIndexInclusive; - if (newSize <= 0) { - return EMPTY_CHAR_ARRAY; - } - final char[] subarray = new char[newSize]; - System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); - return subarray; - } - - /** - *

- * Produces a new {@code byte} array containing the elements between the - * start and end indices. - *

- */ - public static byte[] subarray(final byte[] array, int startIndexInclusive, int endIndexExclusive) { - if (array == null) { - return null; - } - if (startIndexInclusive < 0) { - startIndexInclusive = 0; - } - if (endIndexExclusive > array.length) { - endIndexExclusive = array.length; - } - final int newSize = endIndexExclusive - startIndexInclusive; - if (newSize <= 0) { - return EMPTY_BYTE_ARRAY; - } - final byte[] subarray = new byte[newSize]; - System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); - return subarray; - } - - /** - *

- * Produces a new array containing the elements between the start and end - * indices. - *

- */ - @SuppressWarnings("unchecked") - public static T[] subarray(final T[] array, int startIndexInclusive, int endIndexExclusive) { - if (array == null) { - return null; - } - if (startIndexInclusive < 0) { - startIndexInclusive = 0; - } - if (endIndexExclusive > array.length) { - endIndexExclusive = array.length; - } - final int newSize = endIndexExclusive - startIndexInclusive; - final Class type = array.getClass().getComponentType(); - if (newSize <= 0) { - final T[] emptyArray = (T[]) Array.newInstance(type, 0); - return emptyArray; - } - final T[] subarray = (T[]) Array.newInstance(type, newSize); - System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); - return subarray; - } - - /** - * Returns a copy of the given array of size 1 greater than the argument. - * The last value of the array is left to the default value. - */ - private static Object expandCopy(final Object array, final Class newArrayComponentType) { - if (array != null) { - final int arrayLength = Array.getLength(array); - final Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1); - System.arraycopy(array, 0, newArray, 0, arrayLength); - return newArray; - } - return Array.newInstance(newArrayComponentType, 1); - } - -} diff --git a/jun_java_plugins/jun_redis/shiro-redis/src/main/java/org/iherus/shiro/util/SerializeUtils.java b/jun_java_plugins/jun_redis/shiro-redis/src/main/java/org/iherus/shiro/util/SerializeUtils.java deleted file mode 100644 index 701d86b8b5..0000000000 --- a/jun_java_plugins/jun_redis/shiro-redis/src/main/java/org/iherus/shiro/util/SerializeUtils.java +++ /dev/null @@ -1,125 +0,0 @@ -/** - * Copyright (c) 2016-~, Bosco.Liao (bosco_liao@126.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package org.iherus.shiro.util; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.NotSerializableException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; - -import org.iherus.shiro.exception.SerializationException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - *

序列化工具类

- *

Description:基于JDK原生实现,支持序列化和反序列化.

- * @author Wujun - * @version 1.0.0 - * @date 2016年4月10日-下午8:25:27 - */ -public final class SerializeUtils { - - private static final Logger logger = LoggerFactory.getLogger(SerializeUtils.class); - - private static final int DEFAULT_BUFFER_SIZE = 1024; // default buffer size - - private SerializeUtils() { - - } - - /** - *

Serialize the given object to a byte array.

- * @param object the object to serialize - * @return an array of bytes representing the object in a portable fashion - */ - public static byte[] serialize(final Object object) { - if (object == null) { - return new byte[0]; - } - byte[] serializedValue = null; - ByteArrayOutputStream byteOutStream = null; - ObjectOutputStream objectOutStream = null; - try { - byteOutStream = new ByteArrayOutputStream(DEFAULT_BUFFER_SIZE); - objectOutStream = new ObjectOutputStream(byteOutStream); - try { - objectOutStream.writeObject(object); - } catch (NotSerializableException ex) { - throw new SerializationException(object.getClass().getName() - + " does not implement Serializable or externalizable.", ex); - } - objectOutStream.flush(); - serializedValue = byteOutStream.toByteArray(); - if (logger.isDebugEnabled()) { - logger.debug("Object serialzed successfully."); - } - } catch (Throwable e) { - logger.error("Failed to serialize object of type: " + object.getClass().getName() + ".", e); - } finally { - if (objectOutStream != null) { - try { - objectOutStream.close(); - byteOutStream.close(); - } catch (IOException e) { - // ignore - } - } - } - return serializedValue; - } - - /** - *

Deserialize the byte array into an object.

- * @param serializedBytes a serialized object - * @return the result of deserializing the bytes - */ - public static Object deserialize(final byte[] serializedBytes) { - if (null == serializedBytes || serializedBytes.length == 0) { - return null; - } - Object source = null; - ByteArrayInputStream byteInStream = null; - ObjectInputStream objectInStream = null; - try { - byteInStream = new ByteArrayInputStream(serializedBytes); - objectInStream = new ObjectInputStream(byteInStream); - try { - source = objectInStream.readObject(); - } catch (ClassNotFoundException ex) { - throw new SerializationException("Failed to deserialize object type.", ex); - } - if (logger.isDebugEnabled()) { - logger.debug("SerializedBytes deserialzed successfully."); - } - } catch (Throwable e) { - logger.error("Failed to deserialize.", e); - } finally { - if (objectInStream != null) { - try { - objectInStream.close(); - byteInStream.close(); - } catch (IOException e) { - // ignore - } - } - } - return source; - } - -} diff --git a/jun_java_plugins/jun_redis/shiro-redis/src/main/java/org/iherus/shiro/util/StringUtils.java b/jun_java_plugins/jun_redis/shiro-redis/src/main/java/org/iherus/shiro/util/StringUtils.java deleted file mode 100644 index a0a6a314f1..0000000000 --- a/jun_java_plugins/jun_redis/shiro-redis/src/main/java/org/iherus/shiro/util/StringUtils.java +++ /dev/null @@ -1,166 +0,0 @@ -/** - * Copyright (c) 2016-~, Bosco.Liao (bosco_liao@126.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package org.iherus.shiro.util; - -/** - *

字符串工具类

- *

Description:提供空值判断、字符串截取和获取字符串长度等功能.

- * @author Wujun - * @version 1.0.0 - * @date 2016年4月10日-下午11:20:04 - */ -public final class StringUtils { - - private static final String EMPTY = ""; - - private StringUtils() { - - } - - /** - *

- * Checks if a CharSequence is empty ("") or null. - *

- */ - public static boolean isEmpty(final CharSequence cs) { - return cs == null || cs.length() == 0; - } - - /** - *

- * Checks if a CharSequence is not empty ("") and not null. - *

- */ - public static boolean isNotEmpty(final CharSequence cs) { - return !isEmpty(cs); - } - - /** - *

- * Checks if a CharSequence is whitespace, empty ("") or null. - *

- */ - public static boolean isBlank(final CharSequence cs) { - int strLen; - if (cs == null || (strLen = cs.length()) == 0) { - return true; - } - for (int i = 0; i < strLen; i++) { - if (Character.isWhitespace(cs.charAt(i)) == false) { - return false; - } - } - return true; - } - - /** - *

- * Checks if a CharSequence is not empty (""), not null and not whitespace - * only. - *

- */ - public static boolean isNotBlank(final CharSequence cs) { - return !isBlank(cs); - } - - /** - *

- * Remove the Spaces before and after. - *

- */ - public static String trim(final String str) { - return str == null ? null : str.trim(); - } - - /** - *

- * Remove the Spaces before and after,if empty, return null. - *

- */ - public static String trimToNull(final String str) { - final String ts = trim(str); - return isEmpty(ts) ? null : ts; - } - - /** - *

- * Remove the Spaces before and after,if null,return empty. - *

- */ - public static String trimToEmpty(final String str) { - return str == null ? EMPTY : str.trim(); - } - - /** - *

- * Intercept a CharSequence base on String. - *

- */ - public static String substring(final String str, int start) { - if (str == null) { - return null; - } - if (start < 0) { - start = str.length() + start; - } - if (start < 0) { - start = 0; - } - if (start > str.length()) { - return EMPTY; - } - return str.substring(start); - } - - /** - *

- * Intercept a CharSequence base on String. - *

- */ - public static String substring(final String str, int start, int end) { - if (str == null) { - return null; - } - if (end < 0) { - end = str.length() + end; - } - if (start < 0) { - start = str.length() + start; - } - if (end > str.length()) { - end = str.length(); - } - if (start > end) { - return EMPTY; - } - if (start < 0) { - start = 0; - } - if (end < 0) { - end = 0; - } - return str.substring(start, end); - } - - /** - * Gets a CharSequence length or {@code 0} if the CharSequence is - * {@code null}. - */ - public static int length(final CharSequence cs) { - return cs == null ? 0 : cs.length(); - } - -} diff --git a/jun_java_plugins/jun_redis/shiro-redis/src/test/java/org/iherus/shiro/tester/CustomRealm.java b/jun_java_plugins/jun_redis/shiro-redis/src/test/java/org/iherus/shiro/tester/CustomRealm.java deleted file mode 100644 index cfff934db8..0000000000 --- a/jun_java_plugins/jun_redis/shiro-redis/src/test/java/org/iherus/shiro/tester/CustomRealm.java +++ /dev/null @@ -1,97 +0,0 @@ -/** - * Copyright (c) 2016-~, Bosco.Liao (bosco_liao@126.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package org.iherus.shiro.tester; - -import java.util.HashSet; -import java.util.Set; - -import org.apache.shiro.SecurityUtils; -import org.apache.shiro.authc.AuthenticationException; -import org.apache.shiro.authc.AuthenticationInfo; -import org.apache.shiro.authc.AuthenticationToken; -import org.apache.shiro.authc.SimpleAuthenticationInfo; -import org.apache.shiro.authz.AuthorizationInfo; -import org.apache.shiro.authz.SimpleAuthorizationInfo; -import org.apache.shiro.realm.AuthorizingRealm; -import org.apache.shiro.subject.PrincipalCollection; -import org.apache.shiro.util.ByteSource; - -/** - *

CustomRealm

- *

Description:

- * @author Wujun - * @version 1.0.0 - * @date 2016年4月12日-下午9:24:44 - */ -public class CustomRealm extends AuthorizingRealm { - - @Override - protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { - - String caccount = (String) token.getPrincipal(); - - if ("".equals(caccount) || null == caccount) { - return null; - } - - // Connects DB, get user data.(production environment) - - // Constructing virtual data.(testing environment) - - final String password = "3d82edb0f2cf95c1fbe636cf124c3618"; //correct password (123456) - //final String password = "4d82edb0f2cf95c1fbe636cf124c3620"; //incorrect password - final String salt = "tester"; - final String saccount = salt; - final String realname = saccount; - - User user = new User(1, saccount, realname, password, salt, 25, null); - - // permissions - Set permissions = new HashSet(); - permissions.add("user:query"); - permissions.add("user:create"); - permissions.add("user:update"); - permissions.add("user:delete"); - - user.setPermissions(permissions); - - SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), - ByteSource.Util.bytes(user.getSalt()), user.getRealname()); - - return info; - } - - @Override - protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { - - User user = (User) principals.getPrimaryPrincipal(); - - SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); - - info.addStringPermissions(user.getPermissions()); - - return info; - } - - /** - * Clear Shiro Cache. - */ - public void clearCache() { - PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals(); - super.clearCache(principals); - } - -} diff --git a/jun_java_plugins/jun_redis/shiro-redis/src/test/java/org/iherus/shiro/tester/MD5Generator.java b/jun_java_plugins/jun_redis/shiro-redis/src/test/java/org/iherus/shiro/tester/MD5Generator.java deleted file mode 100644 index 4ecec4daeb..0000000000 --- a/jun_java_plugins/jun_redis/shiro-redis/src/test/java/org/iherus/shiro/tester/MD5Generator.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright (c) 2016-~, Bosco.Liao (bosco_liao@126.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package org.iherus.shiro.tester; - -import org.apache.shiro.crypto.hash.Md5Hash; -import org.junit.Test; - -public class MD5Generator { - - @Test - public void generatorMD5() { - - final String source = "123456"; // 明文密码 - - final String salt = "tester"; // 盐值 - - final int hashIterations = 2; // 散列次数,例如:2 等于 MD5(md5()) - - Md5Hash md5Hash = new Md5Hash(source, salt, hashIterations); - - // 上述的底层实现如下: - // SimpleHash sh = new SimpleHash("MD5", source, salt, hashIterations); - - System.out.println(md5Hash.toString()); - - } - -} diff --git a/jun_java_plugins/jun_redis/shiro-redis/src/test/java/org/iherus/shiro/tester/SimpleCacheTest.java b/jun_java_plugins/jun_redis/shiro-redis/src/test/java/org/iherus/shiro/tester/SimpleCacheTest.java deleted file mode 100644 index 79c09c0e62..0000000000 --- a/jun_java_plugins/jun_redis/shiro-redis/src/test/java/org/iherus/shiro/tester/SimpleCacheTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Copyright (c) 2016-~, Bosco.Liao (bosco_liao@126.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package org.iherus.shiro.tester; - -import org.apache.shiro.SecurityUtils; -import org.apache.shiro.authc.AuthenticationException; -import org.apache.shiro.authc.UsernamePasswordToken; -import org.apache.shiro.authz.AuthorizationException; -import org.apache.shiro.config.IniSecurityManagerFactory; -import org.apache.shiro.mgt.SecurityManager; -import org.apache.shiro.subject.Subject; -import org.apache.shiro.util.Factory; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SimpleCacheTest { - - private static final Logger logger = LoggerFactory.getLogger(SimpleCacheTest.class); - - private Subject subject = null; - - @Before - public void init() { - Factory factory = new IniSecurityManagerFactory("classpath:shiro-realm-test.ini"); - SecurityManager securityManager = factory.getInstance(); - SecurityUtils.setSecurityManager(securityManager); - subject = SecurityUtils.getSubject(); - } - - @Test - public void authorization() { - - UsernamePasswordToken token = new UsernamePasswordToken("tester", "123456"); - - try { - //Authentication - this.subject.login(token); - if (logger.isDebugEnabled()) { - logger.debug("Authentication result is {}.", this.subject.isAuthenticated()); - } - final String[] permissions = {"user:create", "user:update"}; - //authorization - this.subject.checkPermissions(permissions); - - } catch (AuthenticationException e1) { - e1.printStackTrace(); //身份认证异常 - } catch (AuthorizationException e2) { - e2.printStackTrace(); - } - } - - @After - public void destory() { - //Logout will clear the cache, Please be careful. - this.subject.logout(); - } - -} diff --git a/jun_java_plugins/jun_redis/shiro-redis/src/test/java/org/iherus/shiro/tester/User.java b/jun_java_plugins/jun_redis/shiro-redis/src/test/java/org/iherus/shiro/tester/User.java deleted file mode 100644 index 6ff720feaf..0000000000 --- a/jun_java_plugins/jun_redis/shiro-redis/src/test/java/org/iherus/shiro/tester/User.java +++ /dev/null @@ -1,144 +0,0 @@ -/** - * Copyright (c) 2016-~, Bosco.Liao (bosco_liao@126.com). - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package org.iherus.shiro.tester; - -import java.io.Serializable; -import java.util.Date; -import java.util.HashSet; -import java.util.Set; - -public class User implements Serializable { - - /** - * - */ - private static final long serialVersionUID = -2378517398066137981L; - - private Integer id; - - private String account; - - private String realname; - - private String password; - - private String salt; - - private Integer age; - - private String email; - - private Date createTime; - - private Set permissions = new HashSet(); - - public User() { - super(); - } - - public User(Integer id, String account, String realname, String password, - String salt, Integer age, String email) { - super(); - this.id = id; - this.account = account; - this.realname = realname; - this.password = password; - this.salt = salt; - this.age = age; - this.email = email; - this.createTime = new Date(); - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getAccount() { - return account; - } - - public void setAccount(String account) { - this.account = account; - } - - public String getRealname() { - return realname; - } - - public void setRealname(String realname) { - this.realname = realname; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getSalt() { - return salt; - } - - public void setSalt(String salt) { - this.salt = salt; - } - - public Integer getAge() { - return age; - } - - public void setAge(Integer age) { - this.age = age; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - public Date getCreateTime() { - return createTime; - } - - public void setCreateTime(Date createTime) { - this.createTime = createTime; - } - - public Set getPermissions() { - return permissions; - } - - public void setPermissions(Set permissions) { - this.permissions = permissions; - } - - @Override - public String toString() { - return "User [id=" + id + ", account=" + account + ", realname=" + realname + ", password=" + password - + ", salt=" + salt + ", age=" + age + ", email=" + email + ", createTime=" + createTime - + ", permissions=" + permissions + "]"; - } - -} diff --git a/jun_java_plugins/jun_redis/shiro-redis/src/test/resources/log4j.properties b/jun_java_plugins/jun_redis/shiro-redis/src/test/resources/log4j.properties deleted file mode 100644 index 649b8b209f..0000000000 --- a/jun_java_plugins/jun_redis/shiro-redis/src/test/resources/log4j.properties +++ /dev/null @@ -1,4 +0,0 @@ -log4j.rootLogger=debug,stdout -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n diff --git a/jun_java_plugins/jun_redis/shiro-redis/src/test/resources/shiro-realm-test.ini b/jun_java_plugins/jun_redis/shiro-redis/src/test/resources/shiro-realm-test.ini deleted file mode 100644 index 9f398d888e..0000000000 --- a/jun_java_plugins/jun_redis/shiro-redis/src/test/resources/shiro-realm-test.ini +++ /dev/null @@ -1,26 +0,0 @@ -[main] -#\u5b9a\u4e49\u51ed\u8bc1\u5339\u914d\u5668 -credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher -#\u6563\u5217\u7b97\u6cd5 -credentialsMatcher.hashAlgorithmName=MD5 -#\u6563\u5217\u6b21\u6570 -credentialsMatcher.hashIterations=2 - -#\u5b9a\u4e49\u7f13\u5b58\u6c60\u914d\u7f6e -poolConfig=redis.clients.jedis.JedisPoolConfig -poolConfig.minIdle=3 -poolConfig.maxIdle=20 -poolConfig.maxWaitMillis=1000 -poolConfig.maxTotal=300 -#\u5b9a\u4e49\u7f13\u5b58\u914d\u7f6e\u5de5\u5382 -configFactory=org.iherus.shiro.cache.redis.RedisCacheConfigFactory -configFactory.poolConfig=$poolConfig -#\u5b9a\u4e49\u7f13\u5b58\u7ba1\u7406\u5668 -cacheManager=org.iherus.shiro.cache.redis.RedisCacheManager -cacheManager.configFactory=$configFactory - -#\u5c06\u51ed\u8bc1\u5339\u914d\u5668\u8bbe\u7f6e\u5230realm -customRealm=org.iherus.shiro.tester.CustomRealm -customRealm.credentialsMatcher=$credentialsMatcher -securityManager.realms=$customRealm -securityManager.cacheManager=$cacheManager \ No newline at end of file diff --git a/jun_java_plugins/jun_redis/src/main/java/RedisJava.java b/jun_java_plugins/jun_redis/src/main/java/RedisJava.java deleted file mode 100644 index b8074aaeba..0000000000 --- a/jun_java_plugins/jun_redis/src/main/java/RedisJava.java +++ /dev/null @@ -1,57 +0,0 @@ -import redis.clients.jedis.Jedis; - -import java.util.List; -import java.util.Set; - -/** - * Created by Administrator on 2017/11/7. - */ -public class RedisJava { - public static void main(String[] args) throws InterruptedException { - // 连接Redis数据库 - Jedis jedis = new Jedis("127.0.0.1", 6379, 60000); - System.out.println("连接成功"); - System.out.println("服务正在运行: " + jedis.ping()); - jedis.set("string_key", "你好!"); - System.out.println("string……"); - System.out.println(jedis.get("string_key")); - if (jedis.exists("list_key")) { - jedis.del("list_key"); - } - jedis.lpush("list_key", "list1", "list2", "list3"); - List list = jedis.lrange("list_key", 0, 20); - System.out.println("list……"); - for (String s : list) { - System.out.println(s); - } - jedis.sadd("set_key", "set1", "set2", "set3"); - Set set = jedis.smembers("set_key"); - System.out.println("set……"); - for (String s : set) { - System.out.println(s); - } - jedis.zadd("zset_key", 1, "zset1"); - jedis.zadd("zset_key", 2, "zset2"); - jedis.zadd("zset_key", 0, "zset3"); - Set zset = jedis.zrange("zset_key", 0, 10); - System.out.println("zset……"); - for (String s : zset) { - System.out.println(s); - } - jedis.hset("hash_key", "field1", "value1"); - jedis.hset("hash_key", "field2", "value2"); - System.out.println(jedis.hget("hash_key", "field2")); - System.out.println("hash……"); - List hashValues = jedis.hmget("hash_key", "field1", "field2"); - for (String s : hashValues) { - System.out.println(s); - } - - jedis.set("key1", "value1"); - jedis.expire("key1", 5); - Thread.sleep(6 * 1000); - if (!jedis.exists("key1")) { - System.out.println("已失效"); - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_redis/src/main/java/SerializeUtil.java b/jun_java_plugins/jun_redis/src/main/java/SerializeUtil.java deleted file mode 100644 index bbbbf7b414..0000000000 --- a/jun_java_plugins/jun_redis/src/main/java/SerializeUtil.java +++ /dev/null @@ -1,67 +0,0 @@ -//import java.io.ByteArrayInputStream; -//import java.io.ByteArrayOutputStream; -//import java.io.IOException; -//import java.io.ObjectInputStream; -//import java.io.ObjectOutputStream; -// -//import redis.clients.jedis.Jedis; -// -//public class SerializeUtil { -// public static void main(String [] args){ -// Jedis jedis = new Jedis("172.16.135.2"); -// String keys = "name"; -// //删数据 -// //jedis.del(keys); -// //存数据 -// jedis.set(keys, "zy"); -// //取数据 -// String value = jedis.get(keys); -//System.out.println(value); -// -// //存对象 -// Person p=new Person(); //peson类记得实现序列化接口Serializable -// p.setAge(20); -// p.setName("姚波"); -// p.setId(1); -// jedis.set("person".getBytes(), serialize(p)); -// byte[] byt=jedis.get("person".getBytes()); -// Object obj=unserizlize(byt); -// if(obj instanceof Person){ -//System.out.println(obj); -// } -// } -// -// //序列化 -// public static byte [] serialize(Object obj){ -// ObjectOutputStream obi=null; -// ByteArrayOutputStream bai=null; -// try { -// bai=new ByteArrayOutputStream(); -// obi=new ObjectOutputStream(bai); -// obi.writeObject(obj); -// byte[] byt=bai.toByteArray(); -// return byt; -// } catch (IOException e) { -// e.printStackTrace(); -// } -// return null; -// } -// -// //反序列化 -// public static Object unserizlize(byte[] byt){ -// ObjectInputStream oii=null; -// ByteArrayInputStream bis=null; -// bis=new ByteArrayInputStream(byt); -// try { -// oii=new ObjectInputStream(bis); -// Object obj=oii.readObject(); -// return obj; -// } catch (Exception e) { -// -// e.printStackTrace(); -// } -// -// -// return null; -// } -//} diff --git a/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/redis/bean/User.java b/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/redis/bean/User.java deleted file mode 100644 index c43b6800db..0000000000 --- a/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/redis/bean/User.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jun.plugin.redis.bean; - -import java.io.Serializable; - -/** - * Created by Administrator on 2017/11/7. - */ -public class User implements Serializable { -} diff --git a/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/redis/service/RedisService.java b/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/redis/service/RedisService.java deleted file mode 100644 index df5e728079..0000000000 --- a/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/redis/service/RedisService.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.jun.plugin.redis.service; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.redis.core.ListOperations; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.core.ValueOperations; -import org.springframework.stereotype.Service; - -import com.jun.plugin.redis.bean.User; - -import java.util.ArrayList; -import java.util.List; - -/** - * Created by Administrator on 2017/11/7. - */ -@Service -public class RedisService { - - @Autowired - private RedisTemplate redisTemplate; - - public String getById(int id) { - // 查找用户 - ValueOperations valueOperations = redisTemplate.opsForValue(); - String value = valueOperations.get(id + ""); - if (value != null) { - System.out.println("从缓存中拿数据"); - return value; - } else { - // 去数据库里拿 - String a = "test"; - valueOperations.set(id + "", a); - return a; - } - } - - public List listAll() { - ListOperations listOperations = redisTemplate.opsForList(); - List userList = listOperations.range("list_user", 0, 20); - if (userList != null && userList.size() > 0) { - System.out.println("从缓存中拿数据"); - return userList; - } else { - // 模拟从数据库拿数据 - List userList1 = new ArrayList(); - userList1.add(new User()); - listOperations.leftPushAll("list_user", userList1); - return userList1; - } - } - -} diff --git a/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/rediscache/builder/AbstractCacheBuilder.java b/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/rediscache/builder/AbstractCacheBuilder.java deleted file mode 100644 index 17c1e39590..0000000000 --- a/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/rediscache/builder/AbstractCacheBuilder.java +++ /dev/null @@ -1,148 +0,0 @@ -package com.jun.plugin.rediscache.builder; - -import java.util.Map; -import java.util.concurrent.Callable; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.locks.ReentrantLock; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public abstract class AbstractCacheBuilder implements CacheBuilder { - - protected static final Logger CACHE_BUILDER_LOG = LoggerFactory.getLogger(AbstractCacheBuilder.class); - protected static final ExecutorService asyncService = Executors.newCachedThreadPool(); - - protected int expireSeconds = 30; - protected boolean autoRefresh = false; - protected String keyPrefix = ""; - protected volatile boolean loadingMutex = false; - - protected ReentrantLock loadingLock = new ReentrantLock(); - protected Map> keyLoadingTask = new ConcurrentHashMap<>(); - - public class AsyncBuilder implements Callable { - - private String key; - - public AsyncBuilder(String key) { - this.key = key; - } - - @Override - public T call() throws Exception { - T obj = null; - try { - obj = build(key); - } finally { - loadingLock.lock(); - try { - keyLoadingTask.remove(key); - } finally { - loadingLock.unlock(); - } - } - return obj; - } - - } - - @Override - public T asyncBuild(String key) throws Exception { - if (this.loadingMutex) { - boolean asyncSuccess = false; - Future future = keyLoadingTask.get(key); - if (null == future) { - loadingLock.lock(); - try { - future = keyLoadingTask.get(key); - if (null == future) { - try { - future = asyncService.submit(new AsyncBuilder(key)); - asyncSuccess = true; - } catch (Exception e) { - future = null; - } - if (asyncSuccess && null != future) { - keyLoadingTask.put(key, future); - } - } - } finally { - loadingLock.unlock(); - } - } else { - return future.get(); - } - // 异步线程提交线程池处理失败,直接返回结果 - if (!asyncSuccess && null == future) { - return build(key); - } - return future.get(); - } else { - return build(key); - } - } - - @Override - public T build(String key) throws Exception { - if (CACHE_BUILDER_LOG.isDebugEnabled()) { - CACHE_BUILDER_LOG.debug("load data for key:" + key); - } - T ret = buildIntern(key); - return ret; - } - - public abstract T buildIntern(String key) throws Exception; - - @Override - public CacheBuilder setLoadingMutex(boolean loadingMutex) { - this.loadingMutex = loadingMutex; - return this; - } - - @Override - public CacheBuilder setExpireSeconds(int expireSeconds) { - this.expireSeconds = expireSeconds; - return this; - } - - @Override - public CacheBuilder setAutoRefresh(boolean autoRefresh) { - this.autoRefresh = autoRefresh; - return this; - } - - @Override - public CacheBuilder setKeyPrefix(String keyPrefix) { - if (null == keyPrefix) { - keyPrefix = ""; - } else { - this.keyPrefix = keyPrefix; - } - return this; - } - - @Override - public boolean getLoadingMutex() { - return this.loadingMutex; - } - - @Override - public int getExpireSeconds() { - return this.expireSeconds; - } - - @Override - public boolean getAutoRefresh() { - return this.autoRefresh; - } - - @Override - public String getKeyPrefix() { - return this.keyPrefix; - } - -} diff --git a/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/rediscache/builder/CacheBuilder.java b/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/rediscache/builder/CacheBuilder.java deleted file mode 100644 index 09f8e581c0..0000000000 --- a/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/rediscache/builder/CacheBuilder.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.jun.plugin.rediscache.builder; - - -public interface CacheBuilder { - T build(String key) throws Exception; - - T asyncBuild(String key) throws Exception; - - CacheBuilder setExpireSeconds(int expireSeconds); - - CacheBuilder setAutoRefresh(boolean autoRefresh); - - CacheBuilder setKeyPrefix(String keyPrefix); - - CacheBuilder setLoadingMutex(boolean loadingMutex); - - int getExpireSeconds(); - - boolean getAutoRefresh(); - - String getKeyPrefix(); - - boolean getLoadingMutex(); -} diff --git a/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/rediscache/builder/CacheBuilderFactory.java b/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/rediscache/builder/CacheBuilderFactory.java deleted file mode 100644 index fe8f517863..0000000000 --- a/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/rediscache/builder/CacheBuilderFactory.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.jun.plugin.rediscache.builder; - -public class CacheBuilderFactory { - - private boolean autoRefresh; - private String keyPrefix; - private int expireSeconds; - private boolean loadingMutex; - - private CacheBuilderFactory() { - autoRefresh = false; - keyPrefix = "Cache_" + System.currentTimeMillis() + "_"; - expireSeconds = 30; - loadingMutex = false; - } - - public static CacheBuilderFactory newBuilder() { - return new CacheBuilderFactory(); - } - - public CacheBuilderFactory keyPrefix(String keyPrefix) { - this.keyPrefix = keyPrefix; - return this; - } - - public CacheBuilderFactory expireSeconds(int expireSeconds) { - this.expireSeconds = expireSeconds; - return this; - } - - public CacheBuilderFactory autoRefresh(boolean autoRefresh) { - this.autoRefresh = autoRefresh; - return this; - } - - public CacheBuilderFactory loadingMutex(boolean loadingMutex) { - this.loadingMutex = loadingMutex; - return this; - } - - public CacheBuilder build(CacheBuilder cacheBuilder) { - cacheBuilder.setAutoRefresh(this.autoRefresh).setExpireSeconds(this.expireSeconds).setKeyPrefix(this.keyPrefix) - .setLoadingMutex(loadingMutex); - return cacheBuilder; - } - -} diff --git a/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/rediscache/loader/AbstractCacheLoader.java b/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/rediscache/loader/AbstractCacheLoader.java deleted file mode 100644 index 8516305786..0000000000 --- a/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/rediscache/loader/AbstractCacheLoader.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.jun.plugin.rediscache.loader; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.SynchronousQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.eventbus.AsyncEventBus; -import com.google.common.eventbus.Subscribe; -import com.jun.plugin.rediscache.builder.CacheBuilder; -import com.jun.plugin.rediscache.serialize.Serializer; - -public abstract class AbstractCacheLoader implements CacheLoader { - protected static final Logger log = LoggerFactory.getLogger(AbstractCacheLoader.class); - protected Serializer serializer; - - protected ExecutorService loadThreads = new ThreadPoolExecutor(0, 200, 1L, TimeUnit.SECONDS, - new SynchronousQueue()); - - protected AsyncEventBus asyncEventBus; - - public AbstractCacheLoader() { - asyncEventBus = new AsyncEventBus(loadThreads); - asyncEventBus.register(this); - } - - protected T loadData(String key, String cacheKey, CacheBuilder builder) throws Exception { - try { - T ret = builder.asyncBuild(key); - saveData(cacheKey, builder, ret); - return ret; - } catch (Exception e) { - log.error("get content for key:" + key + ", error:", e); - throw e; - } - } - - public abstract void saveData(String cacheKey, CacheBuilder builder, T result) throws Exception; - - public abstract boolean needRefresh(String key, int expire, boolean autoRefresh); - - @Subscribe - public void listenRefreshMessage(RefreshEventMessage message) { - try { - refresh(message.getKey(), message.getCacheBuilder()); - } catch (Exception e) { - log.error("auto refresh error :", e); - } - } - - public static class RefreshEventMessage { - private String key; - private CacheBuilder cacheBuilder; - - public RefreshEventMessage(String key, CacheBuilder cacheBuilder) { - super(); - this.key = key; - this.cacheBuilder = cacheBuilder; - } - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - public CacheBuilder getCacheBuilder() { - return cacheBuilder; - } - - public void setCacheBuilder(CacheBuilder cacheBuilder) { - this.cacheBuilder = cacheBuilder; - } - - } - - public Serializer getSerializer() { - return serializer; - } - - public void setSerializer(Serializer serializer) { - this.serializer = serializer; - } - -} diff --git a/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/rediscache/loader/CacheLoader.java b/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/rediscache/loader/CacheLoader.java deleted file mode 100644 index b829e1eeee..0000000000 --- a/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/rediscache/loader/CacheLoader.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.jun.plugin.rediscache.loader; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.jun.plugin.rediscache.builder.CacheBuilder; - -public interface CacheLoader { - T get(String key, Class clz, CacheBuilder builder) throws Exception; - - List getList(String key, Class clz, CacheBuilder> builder) throws Exception; - - Set getSet(String key, Class clz, CacheBuilder> builder) throws Exception; - - Map getMap(String key, Class keyClz, Class valueClz, CacheBuilder> builder) - throws Exception; - - void refresh(final String key, final CacheBuilder builder) throws Exception; - - void delete(String key, CacheBuilder builder) throws Exception; -} diff --git a/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/rediscache/loader/RedisCacheLoader.java b/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/rediscache/loader/RedisCacheLoader.java deleted file mode 100644 index 47363d7ac3..0000000000 --- a/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/rediscache/loader/RedisCacheLoader.java +++ /dev/null @@ -1,186 +0,0 @@ -package com.jun.plugin.rediscache.loader; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.jun.plugin.rediscache.builder.CacheBuilder; -import com.jun.plugin.rediscache.serialize.Serializer; -import com.jun.plugin.rediscache.util.RedisUtil; - -public class RedisCacheLoader extends AbstractCacheLoader { - - private static final String REFRESH_SUBFIX = ".refresh_subfix"; - private static final String EXPIRE_SUBFIX = ".expireAt"; - - private RedisUtil redisClient; - - private int dbIndex = 0; - - private String getCacheKey(String key, CacheBuilder builder) { - return builder.getKeyPrefix() + key; - } - - private byte[] getFromRedis(String key, String cacheKey, CacheBuilder builder) { - byte[] ckBytes = cacheKey.getBytes(); - try { - byte[] t = redisClient.getAndReturn(dbIndex, ckBytes); - return t; - } catch (Exception e) { - log.error("getByteFromRedis cacheKey=" + cacheKey + ",error:", e); - } - return null; - } - - @Override - public void saveData(String cacheKey, CacheBuilder builder, T result) throws Exception { - if (null != result) { - byte[] t = serializer.serialize(result); - redisClient.setAndReturn(dbIndex, cacheKey.getBytes(), t, builder.getExpireSeconds()); - } - } - - @Override - public T get(String key, Class clz, CacheBuilder builder) throws Exception { - String cacheKey = getCacheKey(key, builder); - T result = null; - byte[] t = getFromRedis(key, cacheKey, builder); - if (null == t) { - result = loadData(key, cacheKey, builder); - } else { - this.asyncEventBus.post(new RefreshEventMessage(key, builder)); - try { - result = serializer.deserialize(t, clz); - } catch (Exception e) { - log.error("deserialize for key:" + key + ", error:", e); - } - } - return result; - } - - @Override - public List getList(String key, Class clz, CacheBuilder> builder) throws Exception { - String cacheKey = getCacheKey(key, builder); - List result = null; - byte[] t = getFromRedis(key, cacheKey, builder); - if (null == t) { - result = loadData(key, cacheKey, builder); - } else { - this.asyncEventBus.post(new RefreshEventMessage(key, builder)); - try { - result = serializer.deserializeList(t, clz); - } catch (Exception e) { - log.error("deserialize for key:" + key + ", error:", e); - } - } - return result; - } - - @Override - public Set getSet(String key, Class clz, CacheBuilder> builder) throws Exception { - String cacheKey = getCacheKey(key, builder); - Set result = null; - byte[] t = getFromRedis(key, cacheKey, builder); - if (null == t) { - result = loadData(key, cacheKey, builder); - } else { - refresh(key, builder); - try { - result = serializer.deserializeSet(t, clz); - } catch (Exception e) { - log.error("deserializeSet for key:" + key + ", error:", e); - } - } - return result; - } - - @Override - public Map getMap(String key, Class keyClz, Class valueClz, CacheBuilder> builder) - throws Exception { - String cacheKey = getCacheKey(key, builder); - Map result = null; - byte[] t = getFromRedis(key, cacheKey, builder); - if (null == t) { - result = loadData(key, cacheKey, builder); - } else { - this.asyncEventBus.post(new RefreshEventMessage(key, builder)); - try { - result = serializer.deserializeMap(t, keyClz, valueClz); - } catch (Exception e) { - log.error("deserializeSet for key:" + key + ", error:", e); - } - } - return result; - } - - @Override - public boolean needRefresh(String cacheKey, int expire, boolean autoRefresh) { - if (!autoRefresh) { - return false; - } - if (0 >= expire) { - return false; - } - long time = -1; - Long t = redisClient.ttl(dbIndex, cacheKey); - if (-1 == t) { - // 不会超时 - return false; - } - if (-2 == t || -3 == t) { - // key不存在 - return false; - } - if (null != t) { - time = t; - } - if (time > 0 && time <= 5) { - if (null != t && 1 == t) { - if (expire > 10) { - t = redisClient.setnx(dbIndex, cacheKey + REFRESH_SUBFIX, - String.valueOf(System.currentTimeMillis()), expire - 10); - } else { - t = redisClient.setnx(dbIndex, cacheKey + REFRESH_SUBFIX, - String.valueOf(System.currentTimeMillis()), expire - 2); - } - return t == 1; - } - } - return false; - } - - @Override - public void refresh(final String key, final CacheBuilder builder) throws Exception { - String cacheKey = getCacheKey(key, builder); - if (!needRefresh(cacheKey, builder.getExpireSeconds(), builder.getAutoRefresh())) { - return; - } - if (log.isDebugEnabled()) { - log.debug("refresh of key:" + cacheKey); - } - loadData(key, cacheKey, builder); - } - - @Override - public void delete(String key, CacheBuilder builder) throws Exception { - String cacheKey = getCacheKey(key, builder); - redisClient.delete(dbIndex, cacheKey); - } - - public RedisUtil getRedisClient() { - return redisClient; - } - - public void setRedisClient(RedisUtil redisClient) { - this.redisClient = redisClient; - } - - public int getDbIndex() { - return dbIndex; - } - - public void setDbIndex(int dbIndex) { - this.dbIndex = dbIndex; - } - -} diff --git a/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/rediscache/serialize/JsonSerializer.java b/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/rediscache/serialize/JsonSerializer.java deleted file mode 100644 index 4abd36472f..0000000000 --- a/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/rediscache/serialize/JsonSerializer.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.jun.plugin.rediscache.serialize; - -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JavaType; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class JsonSerializer implements Serializer { - - private String CHARSET = "UTF-8"; - private static final ObjectMapper mapper = new ObjectMapper(); - static { - mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // 忽略不存在的属性 - mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT); - mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS")); - } - - public static String ObjToStr(Object obj) { - if (obj == null) { - throw new RuntimeException("Failed to map object, which is null"); - } - try { - return mapper.writeValueAsString(obj); - } catch (Exception e) { - String msg = String.format("Failed to map object {}", obj); - throw new RuntimeException(msg, e); - } - } - - public static T strToObj(String jsonStr, Class type) { - try { - return mapper.readValue(jsonStr, type); - } catch (Exception e) { - String msg = String.format("Failed to parse json %s", jsonStr); - throw new RuntimeException(msg, e); - } - } - - public String getCHARSET() { - return CHARSET; - } - - public void setCHARSET(String cHARSET) { - CHARSET = cHARSET; - } - - @Override - public byte[] serialize(Object o) throws Exception { - return ObjToStr(o).getBytes(CHARSET); - } - - @Override - public String serializeToString(Object o) throws Exception { - return ObjToStr(o); - } - - private String getString(byte[] buf) throws Exception { - return new String(buf, CHARSET); - } - - @Override - public T deserialize(byte[] buf, Class clz) throws Exception { - return strToObj(getString(buf), clz); - } - - @Override - public List deserializeList(byte[] buf, Class clz) throws Exception { - return deserializeList(getString(buf), clz); - } - - @Override - public Set deserializeSet(byte[] buf, Class clz) throws Exception { - return deserializeSet(getString(buf), clz); - } - - @Override - public Map deserializeMap(byte[] buf, Class keyClz, Class valueClz) throws Exception { - return deserializeMap(getString(buf), keyClz, valueClz); - } - - @Override - public T deserialize(String content, Class clz) throws Exception { - return strToObj(content, clz); - } - - @Override - public List deserializeList(String content, Class clz) throws Exception { - JavaType type = mapper.getTypeFactory().constructCollectionType(ArrayList.class, clz); - return mapper.readValue(content, type); - } - - @Override - public Set deserializeSet(String content, Class clz) throws Exception { - JavaType type = mapper.getTypeFactory().constructCollectionLikeType(ArrayList.class, clz); - return mapper.readValue(content, type); - } - - @Override - public Map deserializeMap(String content, Class keyClz, Class valueClz) throws Exception { - JavaType type = mapper.getTypeFactory().constructMapType(HashMap.class, keyClz, valueClz); - return mapper.readValue(content, type); - } - -} diff --git a/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/rediscache/serialize/Serializer.java b/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/rediscache/serialize/Serializer.java deleted file mode 100644 index dc7a091fa2..0000000000 --- a/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/rediscache/serialize/Serializer.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.jun.plugin.rediscache.serialize; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -public interface Serializer { - byte[] serialize(Object o) throws Exception; - - String serializeToString(Object o) throws Exception; - - T deserialize(byte[] buf, Class clz) throws Exception; - - List deserializeList(byte[] buf, Class clz) throws Exception; - - Set deserializeSet(byte[] buf, Class clz) throws Exception; - - Map deserializeMap(byte[] buf, Class keyClz, Class valueClz) throws Exception; - - T deserialize(String content, Class clz) throws Exception; - - List deserializeList(String content, Class clz) throws Exception; - - Set deserializeSet(String content, Class clz) throws Exception; - - Map deserializeMap(String content, Class keyClz, Class valueClz) throws Exception; - -} diff --git a/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/rediscache/util/RedisUtil.java b/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/rediscache/util/RedisUtil.java deleted file mode 100644 index 3cb35abb3a..0000000000 --- a/jun_java_plugins/jun_redis/src/main/java/com/jun/plugin/rediscache/util/RedisUtil.java +++ /dev/null @@ -1,141 +0,0 @@ -package com.jun.plugin.rediscache.util; - -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisPool; - -public class RedisUtil { - - private JedisPool masterPool; - private JedisPool slavePool; - - public JedisPool getMasterPool() { - return masterPool; - } - - public JedisPool getSlavePool() { - return slavePool; - } - - public void setMasterPool(JedisPool masterPool) { - this.masterPool = masterPool; - } - - public void setSlavePool(JedisPool slavePool) { - this.slavePool = slavePool; - } - - public byte[] getAndReturn(int dbIndex, final byte[] key) { - Jedis jedis = null; - JedisPool jedisPool = null == slavePool ? masterPool : slavePool; - try { - jedis = jedisPool.getResource(); - if (dbIndex != 0) { - jedis.select(dbIndex); - } - return jedis.get(key); - } catch (Exception e) { - jedisPool.returnBrokenResource(jedis); - jedis = null; - throw e; - } finally { - if (jedis != null) { - jedisPool.returnResource(jedis); - } - } - } - - public String setAndReturn(int dbIndex, final byte[] key, byte[] value, int seconds) { - Jedis jedis = null; - JedisPool jedisPool = null; - try { - jedisPool = masterPool; - jedis = jedisPool.getResource(); - - if (dbIndex != 0) { - jedis.select(dbIndex); - } - return jedis.setex(key, seconds, value); - } catch (Exception e) { - jedisPool.returnBrokenResource(jedis); - jedis = null; - throw e; - } finally { - if (jedis != null) { - jedisPool.returnResource(jedis); - } - } - } - - /** - * - * @param dbIndex - * @param key - * @return -2 key not exists ; -1 not timeout - */ - public Long ttl(int dbIndex, String key) { - long time = -3; - JedisPool pool = masterPool; - Jedis jedis = null; - try { - jedis = pool.getResource(); - jedis.select(dbIndex); - time = jedis.ttl(key); - } catch (Exception e) { - if (null != jedis) { - pool.returnBrokenResource(jedis); - jedis = null; - } - throw e; - } finally { - if (null != jedis) { - pool.returnResource(jedis); - } - } - return time; - } - - public long setnx(int dbIndex, String key, String value,int expire) { - long result = 0; - JedisPool pool = masterPool; - Jedis jedis = null; - try { - jedis = pool.getResource(); - jedis.select(dbIndex); - result = jedis.setnx(key, value); - if(1 == result){ - jedis.expire(key, expire); - } - } catch (Exception e) { - if (null != jedis) { - pool.returnBrokenResource(jedis); - jedis = null; - } - throw e; - } finally { - if (null != jedis) { - pool.returnResource(jedis); - } - } - return result; - } - - public void delete(int dbIndex, String key) { - Jedis jedis = null; - try { - jedis = masterPool.getResource(); - jedis.select(dbIndex); - jedis.del(key); - } catch (Exception e) { - if (null != jedis) { - masterPool.returnBrokenResource(jedis); - jedis = null; - } - throw e; - } finally { - if (null != jedis) { - masterPool.returnResource(jedis); - } - } - } - -} diff --git a/jun_java_plugins/jun_redis/src/main/resources/config/redis.properties b/jun_java_plugins/jun_redis/src/main/resources/config/redis.properties deleted file mode 100644 index 116a754747..0000000000 --- a/jun_java_plugins/jun_redis/src/main/resources/config/redis.properties +++ /dev/null @@ -1,15 +0,0 @@ -redis.host=127.0.0.1 -redis.port=6379 -redis.timeout=15000 -redis.usePool=true - -redis.maxTotal=10 -redis.maxIdle=6 -redis.minIdle=2 -redis.maxWaitMillis=15000 -redis.minEvictableIdleTimeMillis=300000 -redis.numTestsPerEvictionRun=3 -redis.timeBetweenEvictionRunsMillis=60000 -redis.testOnBorrow=true -redis.testOnReturn=true -redis.testWhileIdle=true \ No newline at end of file diff --git a/jun_java_plugins/jun_redis/src/main/resources/config/spring-context.xml b/jun_java_plugins/jun_redis/src/main/resources/config/spring-context.xml deleted file mode 100644 index 39b58283f0..0000000000 --- a/jun_java_plugins/jun_redis/src/main/resources/config/spring-context.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_redis/src/main/resources/config/spring-redis-single.xml b/jun_java_plugins/jun_redis/src/main/resources/config/spring-redis-single.xml deleted file mode 100644 index 40797cbe2a..0000000000 --- a/jun_java_plugins/jun_redis/src/main/resources/config/spring-redis-single.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_redis/src/main/resources/logback.xml b/jun_java_plugins/jun_redis/src/main/resources/logback.xml deleted file mode 100644 index 65b2200522..0000000000 --- a/jun_java_plugins/jun_redis/src/main/resources/logback.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - UTF-8 - %date [%thread] [%level %logger{0}:%line] - %msg%n - - - - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_redis/src/main/webapp/WEB-INF/web.xml b/jun_java_plugins/jun_redis/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index a0b58fd42a..0000000000 --- a/jun_java_plugins/jun_redis/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_redis/src/main/webapp/index.jsp b/jun_java_plugins/jun_redis/src/main/webapp/index.jsp deleted file mode 100644 index f2e7856bd7..0000000000 --- a/jun_java_plugins/jun_redis/src/main/webapp/index.jsp +++ /dev/null @@ -1,16 +0,0 @@ -<%-- - Created by IntelliJ IDEA. - User: Administrator - Date: 2017/11/7 - Time: 10:13 - To change this template use File | Settings | File Templates. ---%> -<%@ page contentType="text/html;charset=UTF-8" language="java" %> - - - $Title$ - - - $END$ - - diff --git a/jun_java_plugins/jun_redis/src/test/java/RedisServiceTest.java b/jun_java_plugins/jun_redis/src/test/java/RedisServiceTest.java deleted file mode 100644 index b205165aeb..0000000000 --- a/jun_java_plugins/jun_redis/src/test/java/RedisServiceTest.java +++ /dev/null @@ -1,29 +0,0 @@ -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.jun.plugin.redis.service.RedisService; - -/** - * Created by Administrator on 2017/11/7. - */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration({"classpath:/config/spring-context.xml", - "classpath:/config/spring-redis-single.xml"}) -public class RedisServiceTest { - - @Autowired - private RedisService redisService; - - @Test - public void testRedis() { - redisService.getById(1); - } - - @Test - public void testRedisList() { - redisService.listAll(); - } -} diff --git a/jun_java_plugins/jun_redis/src/test/java/com/jun/plugin/rediscache/test/TestCache.java b/jun_java_plugins/jun_redis/src/test/java/com/jun/plugin/rediscache/test/TestCache.java deleted file mode 100644 index 4d0d960e2c..0000000000 --- a/jun_java_plugins/jun_redis/src/test/java/com/jun/plugin/rediscache/test/TestCache.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.jun.plugin.rediscache.test; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; - -import com.jun.plugin.rediscache.builder.AbstractCacheBuilder; -import com.jun.plugin.rediscache.builder.CacheBuilder; -import com.jun.plugin.rediscache.builder.CacheBuilderFactory; -import com.jun.plugin.rediscache.loader.RedisCacheLoader; -import com.jun.plugin.rediscache.serialize.JsonSerializer; -import com.jun.plugin.rediscache.util.RedisUtil; - -import redis.clients.jedis.JedisPool; - -public class TestCache { - - private RedisUtil redisUtil; - private RedisCacheLoader cacheLoader; - - private CacheBuilder cacheBuilder = CacheBuilderFactory.newBuilder().autoRefresh(true).expireSeconds(30) - .keyPrefix("Test").loadingMutex(true).build(new AbstractCacheBuilder() { - - @Override - public Long buildIntern(String key) throws Exception { - Long tmp = Long.valueOf(key); - return tmp + (long) (Math.random() * 100000); - } - - }); - - public TestCache() { - redisUtil = new RedisUtil(); - JedisPool master = new JedisPool("127.0.0.1", 6379); - JedisPool slave = new JedisPool("127.0.0.1", 6380); - redisUtil.setMasterPool(master); - redisUtil.setSlavePool(slave); - cacheLoader = new RedisCacheLoader(); - cacheLoader.setRedisClient(redisUtil); - cacheLoader.setSerializer(new JsonSerializer()); - } - - public Long test(String key) throws Exception { - return cacheLoader.get(key, Long.class, cacheBuilder); - } - - public static void main(String[] args) throws Exception { - final TestCache testCache = new TestCache(); - final CountDownLatch start = new CountDownLatch(1); - ExecutorService threadPool = Executors.newFixedThreadPool(3); - List> resultFuture = new ArrayList<>(); - - for (int i = 0; i < 3; i++) { - resultFuture.add(threadPool.submit(new Callable() { - - @Override - public Long call() throws Exception { - start.await(); - long start = System.nanoTime(); - for (int i = 0; i < 1000000; i++) { - if(testCache.test(String.valueOf(i % 3))==null){ - return -1L; - } - } - return System.nanoTime() - start; - - } - - })); - start.countDown(); - } - for (Future f : resultFuture) { - System.out.println(f.get() / 1000000.0); - } - } -} diff --git a/jun_java_plugins/jun_serialization/README.md b/jun_java_plugins/jun_serialization/README.md deleted file mode 100644 index 5a68c3f847..0000000000 --- a/jun_java_plugins/jun_serialization/README.md +++ /dev/null @@ -1,84 +0,0 @@ -# 序列化和反序列化实现 - -* [JDK方式](https://github.com/lgjlife/serialization/blob/master/src%2Fmain%2Fjava%2Fcom%2Futils%2Fserialization%2FJdkSerializeUtil.java) -* [Fastjson方式](https://github.com/lgjlife/serialization/blob/master/src%2Fmain%2Fjava%2Fcom%2Futils%2Fserialization%2FFastjsonSerializeUtil.java) -```XML - - - com.alibaba - fastjson - 1.2.56 - -``` -* [Protostuff方式](https://github.com/lgjlife/serialization/blob/master/src%2Fmain%2Fjava%2Fcom%2Futils%2Fserialization%2FProtostuffSerializeUtil.java) -```XML - - - io.protostuff - protostuff-core - 1.6.0 - test - - - - - - - io.protostuff - protostuff-runtime - 1.6.0 - -``` -* [Hessian方式](https://github.com/lgjlife/serialization/blob/master/src%2Fmain%2Fjava%2Fcom%2Futils%2Fserialization%2HessianSerializeUtil.java) -```XML - - - com.caucho - hessian - 4.0.60 - -``` -# 使用事例 - -* 定义pojo -如果使用JDK方式,还需要实现Serializable接口 -```java - -@Data -@Builder -public class model.User implements Serializable { - - private String name; - private int age; -} - -``` - -```java -model.User user = model.User.builder().name("用户"+i).age(i).build(); -private AbstractSerialize serialize = new ProtostuffSerializeUtil(); -byte[] body = serialize.serialize(msg); -model.User user1 = serialize.deserialize(body,model.User.class); - - - -``` -## 测试 -[测试类](https://github.com/lgjlife/serialization/blob/master/src%2Fmain%2Fjava%2Fcom%2Futils%2Ftest%2FSerializeTest.java) - -综合来看,hessian 的效率是比较高的。fastjson效率相对偏低。 -```java -序列化对象类:java.util.ArrayList 序列化类:com.utils.serialization.JdkSerializeUtil 序列化花费时间:369 字节长度 = 788948 -序列化对象类:java.util.ArrayList 序列化类:com.utils.serialization.FastjsonSerializeUtil 序列化花费时间:417 字节长度 = 788891 -序列化对象类:java.util.ArrayList 序列化类:com.utils.serialization.HessianSerializeUtil 序列化花费时间:242 字节长度 = 788897 - -序列化对象类:java.util.HashMap 序列化类:com.utils.serialization.JdkSerializeUtil 序列化花费时间:284 字节长度 = 1577862 -序列化对象类:java.util.HashMap 序列化类:com.utils.serialization.FastjsonSerializeUtil 序列化花费时间:393 字节长度 = 1577781 -序列化对象类:java.util.HashMap 序列化类:com.utils.serialization.HessianSerializeUtil 序列化花费时间:184 字节长度 = 1577785 - -序列化对象类:com.utils.pojo.TestPojo 序列化类:com.utils.serialization.JdkSerializeUtil 序列化花费时间:21 字节长度 = 977 -序列化对象类:com.utils.pojo.TestPojo 序列化类:com.utils.serialization.FastjsonSerializeUtil 序列化花费时间:58 字节长度 = 1192 -序列化对象类:com.utils.pojo.TestPojo 序列化类:com.utils.serialization.HessianSerializeUtil 序列化花费时间:4 字节长度 = 1319 -序列化对象类:com.utils.pojo.TestPojo 序列化类:com.utils.serialization.ProtostuffSerializeUtil 序列化花费时间:67 字节长度 = 825 - -``` \ No newline at end of file diff --git a/jun_java_plugins/jun_serialization/guava.md b/jun_java_plugins/jun_serialization/guava.md deleted file mode 100644 index 7325a5d0a6..0000000000 --- a/jun_java_plugins/jun_serialization/guava.md +++ /dev/null @@ -1,29 +0,0 @@ - -        ImmutableList list = ImmutableList.of("1", "2"); -        List lists = Lists.newArrayList("abc","abcd","123"); -        System.err.println(Joiner.on(",").join(lists)); -        Map map = Maps.newHashMap(); -        Set set = Sets.newHashSet("1", "2"); -        ImmutableMap map2 = ImmutableMap.of("key1", "value1", "key2", "value2"); -        System.err.println(Joiner.on(",").withKeyValueSeparator("=").join(map2)); -//        System.err.println(map2.get("key2")); -//        map.forEach((key,value)->{System.out.println(key+""+value);}); -        -        Multimap m = ArrayListMultimap.create(); -        m.put("a", "1"); -        m.put("a", "2"); -        m.forEach((key,value)->{System.out.println(key+"-"+value);}); -//        System.err.println(m.get("a")); -        -        Stopwatch sw = Stopwatch.createStarted(); -        String str = "1-2-3-4-5-6"; -        System.err.println(Splitter.on("-").splitToList(str)); -        String str2 = "xiaoming=11,xiaohong=23"; -        System.err.println(Splitter.on(",").withKeyValueSeparator("=").split(str2)); -        Strings.isNullOrEmpty(""); -//        List list = Splitter.on("-").splitToList(str); -        long time = sw.elapsed(TimeUnit.MILLISECONDS); -        System.err.println(time); -        Thread.currentThread().sleep(500); -        time = sw.elapsed(TimeUnit.MILLISECONDS); -        System.err.println(time); \ No newline at end of file diff --git a/jun_java_plugins/jun_serialization/pom.xml b/jun_java_plugins/jun_serialization/pom.xml deleted file mode 100644 index 3517d9aa7b..0000000000 --- a/jun_java_plugins/jun_serialization/pom.xml +++ /dev/null @@ -1,80 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_serialization - 1.0 - - - - org.springframework.boot - spring-boot-starter - 2.1.0.RELEASE - - - - - io.protostuff - protostuff-core - 1.6.0 - - - - - io.protostuff - protostuff-runtime - 1.6.0 - - - - - org.projectlombok - lombok - 1.18.6 - provided - - - - - - - com.caucho - hessian - 4.0.60 - - - - - - com.alibaba - fastjson - 1.2.56 - - - com.fasterxml.jackson.core - jackson-databind - 2.9.9.3 - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.1 - - 8 - 8 - UTF-8 - - - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/pojo/Location.java b/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/pojo/Location.java deleted file mode 100644 index 0c73551280..0000000000 --- a/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/pojo/Location.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.jun.plugin.utils.pojo; - - -import java.io.Serializable; - -public class Location implements Serializable { - - - private String city; - - public Location() { - - } - - public Location(String city) { - this.city = city; - } - - @Override - public String toString() { - return "Location{" + - "city='" + city + '\'' + - '}'; - } -} diff --git a/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/pojo/TestPojo.java b/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/pojo/TestPojo.java deleted file mode 100644 index a5150e4790..0000000000 --- a/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/pojo/TestPojo.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.jun.plugin.utils.pojo; - - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.io.Serializable; - -@Data -@NoArgsConstructor -@AllArgsConstructor -public class TestPojo implements Serializable { - - private String name1 = "aaaaaaaaaaaaaaaaaa"; - private String name2 = "aaaaaaaaaaaaaaaaaa"; - private String name3 = "aaaaaaaaaaaaaaaaaa"; - private String name4 = "aaaaaaaaaaaaaaaaaa"; - private String name5 = "aaaaaaaaaaaaaaaaaa"; - private String name6 = "aaaaaaaaaaaaaaaaaa"; - private String name7 = "aaaaaaaaaaaaaaaaaa"; - private String name8 = "aaaaaaaaaaaaaaaaaa"; - private String name9 = "aaaaaaaaaaaaaaaaaa"; - private String name10 = "aaaaaaaaaaaaaaaaaa"; - - private String name11 = "aaaaaaaaaaaaaaaaaa"; - private String name12 = "aaaaaaaaaaaaaaaaaa"; - private String name13 = "aaaaaaaaaaaaaaaaaa"; - private String name14 = "aaaaaaaaaaaaaaaaaa"; - private String name15 = "aaaaaaaaaaaaaaaaaa"; - private String name16 = "aaaaaaaaaaaaaaaaaa"; - private String name17 = "aaaaaaaaaaaaaaaaaa"; - private String name18 = "aaaaaaaaaaaaaaaaaa"; - private String name19 = "aaaaaaaaaaaaaaaaaa"; - private String name20 = "aaaaaaaaaaaaaaaaaa"; - - private String name21 = "aaaaaaaaaaaaaaaaaa"; - private String name22 = "aaaaaaaaaaaaaaaaaa"; - private String name23 = "aaaaaaaaaaaaaaaaaa"; - private String name24 = "aaaaaaaaaaaaaaaaaa"; - private String name25 = "aaaaaaaaaaaaaaaaaa"; - private String name26 = "aaaaaaaaaaaaaaaaaa"; - private String name27 = "aaaaaaaaaaaaaaaaaa"; - private String name28 = "aaaaaaaaaaaaaaaaaa"; - private String name29 = "aaaaaaaaaaaaaaaaaa"; - private String name30 = "aaaaaaaaaaaaaaaaaa"; - - private String name31 = "aaaaaaaaaaaaaaaaaa"; - private String name32 = "aaaaaaaaaaaaaaaaaa"; - private String name33 = "aaaaaaaaaaaaaaaaaa"; - private String name34 = "aaaaaaaaaaaaaaaaaa"; - private String name35 = "aaaaaaaaaaaaaaaaaa"; - private String name36 = "aaaaaaaaaaaaaaaaaa"; - private String name37 = "aaaaaaaaaaaaaaaaaa"; - private String name38 = "aaaaaaaaaaaaaaaaaa"; - private String name39 = "aaaaaaaaaaaaaaaaaa"; - private String name40 = "aaaaaaaaaaaaaaaaaa"; - - private String name41; - private String name42; - private String name43; - private String name44; - private String name45; - private String name46; - private String name47; - private String name48; - private String name49; - private String name50; - - - - -} diff --git a/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/pojo/User.java b/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/pojo/User.java deleted file mode 100644 index f8795e6d6c..0000000000 --- a/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/pojo/User.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.jun.plugin.utils.pojo; - - -import lombok.Builder; -import lombok.Data; - -import java.io.Serializable; -import java.util.List; -import java.util.Map; - -@Data -@Builder -public class User implements Serializable { - - private String id; - - private String name; - - private Integer age; - - private String desc; - - - private Object obj; - - private List list; - private Map map; - - public User(){ - - } - - public User(String id, String name, Integer age, String desc, Object obj) { - this.id = id; - this.name = name; - this.age = age; - this.desc = desc; - this.obj = obj; - } - - - public User(String id, String name, Integer age, String desc, Object obj, List list, Map map) { - this.id = id; - this.name = name; - this.age = age; - this.desc = desc; - this.obj = obj; - this.list = list; - this.map = map; - } -} diff --git a/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/serialization/AbstractSerialize.java b/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/serialization/AbstractSerialize.java deleted file mode 100644 index 208a598342..0000000000 --- a/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/serialization/AbstractSerialize.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.jun.plugin.utils.serialization; - -public abstract class AbstractSerialize { - - public abstract byte[] serialize(T obj); - public abstract T deserialize(byte[] data, Class clazz); - - - -} diff --git a/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/serialization/FastjsonSerializeUtil.java b/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/serialization/FastjsonSerializeUtil.java deleted file mode 100644 index c3086462ff..0000000000 --- a/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/serialization/FastjsonSerializeUtil.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.jun.plugin.utils.serialization; - -import com.alibaba.fastjson.JSON; - -/** - *功能描述 - * @author lgj - * @Description fastjson ,对象属性需要实现get/set - * @date 3/24/19 -*/ -public class FastjsonSerializeUtil extends AbstractSerialize { - - private static FastjsonSerializeUtil serializeUtil = new FastjsonSerializeUtil(); - - public static FastjsonSerializeUtil getSingleton(){ - return serializeUtil; - } - - - public byte[] serialize(T obj) { - if (obj == null){ - throw new NullPointerException(); - } - - String json = JSON.toJSONString(obj); - byte[] data = json.getBytes(); - return data; - } - - public T deserialize(byte[] data, Class clazz) { - - T obj = JSON.parseObject(new String(data),clazz); - return obj; - } -} diff --git a/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/serialization/HessianSerializeUtil.java b/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/serialization/HessianSerializeUtil.java deleted file mode 100644 index 86b041b217..0000000000 --- a/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/serialization/HessianSerializeUtil.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.jun.plugin.utils.serialization; - -import com.caucho.hessian.io.HessianInput; -import com.caucho.hessian.io.HessianOutput; -import com.jun.plugin.utils.pojo.Location; -import com.jun.plugin.utils.pojo.User; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; - -public class HessianSerializeUtil extends AbstractSerialize { - - public static HessianSerializeUtil serializeUtil = new HessianSerializeUtil(); - public static HessianSerializeUtil getSingleton(){ - return serializeUtil; - } - - public static void main(String args[]){ - Location location = new Location("深圳"); - User user = User.builder().age(15).desc("libai").name("zhangfei").obj(location).build(); - - byte[] serData = HessianSerializeUtil.serializeUtil.serialize(user); - User user1 = HessianSerializeUtil.serializeUtil.deserialize(serData,null); - - System.out.println(user1); - } - public byte[] serialize(T obj) { - - if (obj == null){ - throw new NullPointerException(); - } - try{ - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - HessianOutput ho = new HessianOutput(bos); - ho.writeObject(obj); - - return bos.toByteArray(); - } - catch(Exception ex){ - throw new RuntimeException(); - } - - } - - public T deserialize(byte[] data, Class clazz) { - - if (data == null){ - throw new NullPointerException(); - } - try{ - ByteArrayInputStream bis = new ByteArrayInputStream(data); - HessianInput hi = new HessianInput(bis); - return (T)hi.readObject(); - - } - catch(Exception ex){ - throw new RuntimeException(); - } - - } -} diff --git a/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/serialization/JacksonSerialize.java b/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/serialization/JacksonSerialize.java deleted file mode 100644 index ceacd1d9bf..0000000000 --- a/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/serialization/JacksonSerialize.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.jun.plugin.utils.serialization; - -import java.io.IOException; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class JacksonSerialize { - - - public static void main(String[] args) throws ParseException, IOException { - User user = new User(); - user.setName("小民"); - user.setEmail("xiaomin@sina.com"); - user.setAge(20); - - SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd"); - user.setBirthday(dateformat.parse("1996-10-01")); - - /** - * ObjectMapper是JSON操作的核心,Jackson的所有JSON操作都是在ObjectMapper中实现。 - * ObjectMapper有多个JSON序列化的方法,可以把JSON字符串保存File、OutputStream等不同的介质中。 - * writeValue(File arg0, Object arg1)把arg1转成json序列,并保存到arg0文件中。 - * writeValue(OutputStream arg0, Object arg1)把arg1转成json序列,并保存到arg0输出流中。 - * writeValueAsBytes(Object arg0)把arg0转成json序列,并把结果输出成字节数组。 - * writeValueAsString(Object arg0)把arg0转成json序列,并把结果输出成字符串。 - */ - ObjectMapper mapper = new ObjectMapper(); - - //User类转JSON - //输出结果:{"name":"小民","age":20,"birthday":844099200000,"email":"xiaomin@sina.com"} - String json = mapper.writeValueAsString(user); - System.out.println(json); - - //Java集合转JSON - //输出结果:[{"name":"小民","age":20,"birthday":844099200000,"email":"xiaomin@sina.com"}] - List users = new ArrayList(); - users.add(user); - String jsonlist = mapper.writeValueAsString(users); - System.out.println(jsonlist); - } - public static void main2(String[] args) throws ParseException, IOException { - String json = "{\"name\":\"小民\",\"age\":20,\"birthday\":844099200000,\"email\":\"xiaomin@sina.com\"}"; - - /** - * ObjectMapper支持从byte[]、File、InputStream、字符串等数据的JSON反序列化。 - */ - ObjectMapper mapper = new ObjectMapper(); - User user = mapper.readValue(json, User.class); - System.out.println(user); - } - - public static void main3(String[] args) throws ParseException, IOException { - User user = new User(); - user.setName("小民"); - user.setEmail("xiaomin@sina.com"); - user.setAge(20); - - SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd"); - user.setBirthday(dateformat.parse("1996-10-01")); - - ObjectMapper mapper = new ObjectMapper(); - String json = mapper.writeValueAsString(user); - System.out.println(json); - //输出结果:{"name":"小民","birthday":"1996年09月30日","mail":"xiaomin@sina.com"} - } - - - - - - - static class User { - private String name; - - //不JSON序列化年龄属性 - @JsonIgnore - private Integer age; - - //格式化日期属性 - @JsonFormat(pattern = "yyyy年MM月dd日") - private Date birthday; - - //序列化email属性为mail - @JsonProperty("mail") - private String email; - - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - - public Integer getAge() { - return age; - } - public void setAge(Integer age) { - this.age = age; - } - - public Date getBirthday() { - return birthday; - } - public void setBirthday(Date birthday) { - this.birthday = birthday; - } - - public String getEmail() { - return email; - } - public void setEmail(String email) { - this.email = email; - } - } -} diff --git a/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/serialization/JdkSerializeUtil.java b/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/serialization/JdkSerializeUtil.java deleted file mode 100644 index ca73731e2d..0000000000 --- a/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/serialization/JdkSerializeUtil.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.jun.plugin.utils.serialization; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; - -import com.jun.plugin.utils.pojo.Location; -import com.jun.plugin.utils.pojo.User; - -public class JdkSerializeUtil extends AbstractSerialize { - - private static JdkSerializeUtil serializeUtil = new JdkSerializeUtil(); - - public static JdkSerializeUtil getSingleton(){ - return serializeUtil; - } - - public static void main(String args[]){ - Location location = new Location("深圳"); - User user = User.builder().age(15).desc("libai").name("zhangfei").obj(location).build(); - - byte[] serData = JdkSerializeUtil.serializeUtil.serialize(user); - User user1 = JdkSerializeUtil.serializeUtil.deserialize(serData,null); - - System.out.println(user1); - } - public byte[] serialize(T obj) { - - if (obj == null){ - throw new NullPointerException(); - } - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - ObjectOutputStream oos = new ObjectOutputStream(bos); - - oos.writeObject(obj); - return bos.toByteArray(); - } catch (Exception ex) { - ex.printStackTrace(); - } - return new byte[0]; - } - - public T deserialize(byte[] data, Class clazz) { - ByteArrayInputStream bis = new ByteArrayInputStream(data); - - try { - ObjectInputStream ois = new ObjectInputStream(bis); - T obj = (T)ois.readObject(); - return obj; - } catch (Exception ex) { - ex.printStackTrace(); - } - - return null; - } -} diff --git a/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/serialization/ProtostuffSerializeUtil.java b/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/serialization/ProtostuffSerializeUtil.java deleted file mode 100644 index 3583df96ed..0000000000 --- a/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/serialization/ProtostuffSerializeUtil.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.jun.plugin.utils.serialization; - -import io.protostuff.LinkedBuffer; -import io.protostuff.ProtostuffIOUtil; -import io.protostuff.Schema; -import io.protostuff.runtime.RuntimeSchema; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import com.jun.plugin.utils.pojo.Location; -import com.jun.plugin.utils.pojo.User; - - - -public class ProtostuffSerializeUtil extends AbstractSerialize{ - - private static ProtostuffSerializeUtil serializeUtil = new ProtostuffSerializeUtil(); - - public static ProtostuffSerializeUtil getSingleton(){ - return serializeUtil; - } - - - /** - * 避免每次序列化都重新申请Buffer空间 - */ - private static LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE); - /** - * 缓存Schema - */ - private static Map, Schema> schemaCache = new ConcurrentHashMap, Schema>(); - - - - public static void main(String args[]){ - - Location location = new Location("深圳"); - User user = User.builder().age(15).desc("libai").name("zhangfei").obj(location).build(); - - byte[] serData = ProtostuffSerializeUtil.serializeUtil.serialize(user); - User user1 = ProtostuffSerializeUtil.serializeUtil.deserialize(serData,User.class); - - System.out.println(user1); - - } - - public byte[] serialize(T obj) { - - if (obj == null){ - throw new NullPointerException(); - } - Class clazz = (Class) obj.getClass(); - Schema schema = getSchema(clazz); - byte[] data; - try { - data = ProtostuffIOUtil.toByteArray(obj, schema, buffer); - } finally { - buffer.clear(); - } - - return data; - } - - public T deserialize(byte[] data, Class clazz) { - Schema schema = getSchema(clazz); - T obj = schema.newMessage(); - ProtostuffIOUtil.mergeFrom(data, obj, schema); - return obj; - } - - - private static Schema getSchema(Class clazz) { - Schema schema = (Schema) schemaCache.get(clazz); - if (schema == null) { - //这个schema通过RuntimeSchema进行懒创建并缓存 - //所以可以一直调用RuntimeSchema.getSchema(),这个方法是线程安全的 - schema = RuntimeSchema.getSchema(clazz); - if (schema != null) { - schemaCache.put(clazz, schema); - } - } - - return schema; - } - - -} diff --git a/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/serialization/SerializeTest.java b/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/serialization/SerializeTest.java deleted file mode 100644 index 4dbd19701e..0000000000 --- a/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/serialization/SerializeTest.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.jun.plugin.utils.serialization; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.jun.plugin.utils.pojo.Location; -import com.jun.plugin.utils.pojo.User; - -public class SerializeTest { - - public static void main(String args[]){ - - long start = 0; - long end = 0; - - Location location = new Location("深圳"); - - List list = new ArrayList(); - list.add(1); - list.add(2); - - Map map = new HashMap(); - map.put("a","a1"); - map.put("b","b1"); - User user = User.builder().age(15).desc("libai").name("zhangfei").obj(location).list(list).map(map).build(); - System.out.println(user); - - - System.out.println("JDK序列化......"); - start = System.currentTimeMillis(); - byte[] serData = JdkSerializeUtil.getSingleton().serialize(user); - System.out.println("JDK序列化占用字节数:" + serData.length); - User user1 = JdkSerializeUtil.getSingleton().deserialize(serData,null); - end = System.currentTimeMillis(); - System.out.println("JDK序列化花费时间:" + (end - start)); - System.out.println(user1); - - System.out.println(); - - System.out.println("Protostuff序列化......"); - start = System.currentTimeMillis(); - serData = ProtostuffSerializeUtil.getSingleton().serialize(user); - System.out.println("Protostuff序列化占用字节数:" + serData.length); - user1 = ProtostuffSerializeUtil.getSingleton().deserialize(serData,User.class); - end = System.currentTimeMillis(); - System.out.println("Protostuff序列化花费时间:" + (end - start)); - System.out.println(user1); - - - System.out.println(); - - - System.out.println("fastjson序列化......"); - start = System.currentTimeMillis(); - serData = FastjsonSerializeUtil.getSingleton().serialize(user); - System.out.println("fastjson序列化占用字节数:" + serData.length); - user1 = FastjsonSerializeUtil.getSingleton().deserialize(serData,User.class); - end = System.currentTimeMillis(); - System.out.println("fastjson序列化花费时间:" + (end - start)); - System.out.println(user1); - - - - - } -} diff --git a/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/test/SerializeTest.java b/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/test/SerializeTest.java deleted file mode 100644 index a29fe7defb..0000000000 --- a/jun_java_plugins/jun_serialization/src/main/java/com/jun/plugin/utils/test/SerializeTest.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.jun.plugin.utils.test; - -import org.springframework.util.StopWatch; - -import com.jun.plugin.utils.pojo.TestPojo; -import com.jun.plugin.utils.serialization.*; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - *功能描述 - * @author lgj 序列化性能测试 - * @Description - * @date 3/26/19 - -序列化对象类:java.util.ArrayList 序列化类:com.utils.serialization.JdkSerializeUtil 序列化花费时间:369 字节长度 = 788948 -序列化对象类:java.util.ArrayList 序列化类:com.utils.serialization.FastjsonSerializeUtil 序列化花费时间:417 字节长度 = 788891 -序列化对象类:java.util.ArrayList 序列化类:com.utils.serialization.HessianSerializeUtil 序列化花费时间:242 字节长度 = 788897 - -序列化对象类:java.util.HashMap 序列化类:com.utils.serialization.JdkSerializeUtil 序列化花费时间:284 字节长度 = 1577862 -序列化对象类:java.util.HashMap 序列化类:com.utils.serialization.FastjsonSerializeUtil 序列化花费时间:393 字节长度 = 1577781 -序列化对象类:java.util.HashMap 序列化类:com.utils.serialization.HessianSerializeUtil 序列化花费时间:184 字节长度 = 1577785 - -序列化对象类:com.utils.pojo.TestPojo 序列化类:com.utils.serialization.JdkSerializeUtil 序列化花费时间:21 字节长度 = 977 -序列化对象类:com.utils.pojo.TestPojo 序列化类:com.utils.serialization.FastjsonSerializeUtil 序列化花费时间:58 字节长度 = 1192 -序列化对象类:com.utils.pojo.TestPojo 序列化类:com.utils.serialization.HessianSerializeUtil 序列化花费时间:4 字节长度 = 1319 -序列化对象类:com.utils.pojo.TestPojo 序列化类:com.utils.serialization.ProtostuffSerializeUtil 序列化花费时间:67 字节长度 = 825 - - 综合来看,hessian 的效率是比较高的。fastjson效率相对偏低。 - */ - -public class SerializeTest { - - public static void main(String args[]){ - - JdkSerializeUtil jdkSerializeUtil = JdkSerializeUtil.getSingleton(); - FastjsonSerializeUtil fastjsonSerializeUtil = FastjsonSerializeUtil.getSingleton(); - HessianSerializeUtil hessianSerializeUtil = HessianSerializeUtil.getSingleton(); - ProtostuffSerializeUtil protostuffSerializeUtil = ProtostuffSerializeUtil.getSingleton(); - - // for list test - List list = new ArrayList(); - - for(int i = 0;i < 100000; i++){ - list.add(String.valueOf(i)); - } - int testCount = 1; - - performanceTest(jdkSerializeUtil,list,testCount,ArrayList.class); - performanceTest(fastjsonSerializeUtil,list,testCount,ArrayList.class); - performanceTest(hessianSerializeUtil,list,testCount,ArrayList.class); - System.out.println(); - - - //for map test - Map map = new HashMap(); - - for(int i = 0;i < 100000; i++){ - map.put(String.valueOf(i),String.valueOf(i)); - } - - performanceTest(jdkSerializeUtil,map,testCount,HashMap.class); - performanceTest(fastjsonSerializeUtil,map,testCount,HashMap.class); - performanceTest(hessianSerializeUtil,map,testCount,HashMap.class); - System.out.println(); - - //for other object test - TestPojo testPojo = new TestPojo(); - performanceTest(jdkSerializeUtil,testPojo,testCount,TestPojo.class); - performanceTest(fastjsonSerializeUtil,testPojo,testCount,TestPojo.class); - performanceTest(hessianSerializeUtil,testPojo,testCount,TestPojo.class); - performanceTest(protostuffSerializeUtil,testPojo,testCount,TestPojo.class); - - System.out.println(); - } - /** - *功能描述 - * @author lgj - * @Description - * @date 3/26/19 - * @param: - * @return: - * - */ - public static void performanceTest(AbstractSerialize serialize , Object object , int tesCount, Class clazz){ - - long start = 0; - long end = 0; - long totalTime = 0; - byte[] serData = null; - - for(int i = 0; i< tesCount ; i++){ - StopWatch stopWatch = new StopWatch("my-watch"); - stopWatch.start(); - serData = serialize.serialize(object); - T obj = serialize.deserialize(serData,clazz); - stopWatch.stop(); - totalTime += stopWatch.getTotalTimeMillis(); - // System.out.println(obj); - } - - System.out.println("序列化对象类:" + clazz.getName() - + " 序列化类:" + serialize.getClass().getName() - + " 序列化花费时间:" + (totalTime/tesCount) - + " 字节长度 = " + serData.length); - - } - - - - -} diff --git "a/jun_java_plugins/jun_serialization/\345\272\217\345\210\227\345\214\226.md" "b/jun_java_plugins/jun_serialization/\345\272\217\345\210\227\345\214\226.md" deleted file mode 100644 index c13c869be3..0000000000 --- "a/jun_java_plugins/jun_serialization/\345\272\217\345\210\227\345\214\226.md" +++ /dev/null @@ -1,417 +0,0 @@ -## 序列化 - -将对象转换为字节数组,方便在网络中进行对象的传输。在网络通信中,不同的计算机进行相互通信主要的方式就是将数据流从一台机器传输给另外一台计算机,常见的传输协议包括了TCP,UDP,HTTP等,网络io的方式主要包括有了aio,bio,nio三种方式。 - -当客户端将需要请求的数据封装好了之后就需要进行转换为**二进制格式**再转换为流进行传输,当服务端接收到流之后再将数据解析为**二进制格式**的内容,再按照约定好的协议进行处理解析。最常见的场景就是rpc远程调用的时候,对发送数据和接收数据时候的处理。 - -下边我们来一一介绍一下现在比较常见的几款序列化技术框架。 - -## **jdk序列化** - -jdk自身便带有序列化的功能,Java序列化API允许我们将一个对象转换为流,并通过网络发送,或将其存入文件或数据库以便未来使用,反序列化则是将对象流转换为实际程序中使用的Java对象的过程。 - -**先来看看实际的代码案例** - -首先我们创建一个基础的测试Person类 - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -``` -package com.sise.test; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.io.Serializable; - -/** - * @author linhao - * @date 2019/8/15 - * @Version V1.0 - */ -@AllArgsConstructor -@NoArgsConstructor -@Data -public class Person implements Serializable { - private static final long serialVersionUID = 3829252771168681281L; - - private Integer id; - - private String username; - - private String tel; -} -``` - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - - - -**如果某些特殊字段不希望被序列化该如何处理?** - -这里面如果有相应的属性不希望被序列化操作的话,可以使用transient关键字进行修饰,例如希望tel属性不希望被序列化,可以改成这样: - -``` - private transient String tel; -``` - - - -*这样的话,该对象在反序列化出来结果之后,相应的属性就会为null值。* - -**为什么要定义serialVersionUID?** - -序列化操作时,系统会把当前类声明的serialVersionUID写入到序列化文件中,用于反序列化时系统会去检测文件中的serialVersionUID,判断它是否与当前类的serialVersionUID一致,如果一致就说明序列化类的版本与当前类版本是一样的,可以反序列化成功,否则失败。 - -**如果没有定义serialVersionUID时** - -当实现当前类没有显式地定义一个serialVersionUID变量时候,Java序列化机制会根据编译的Class自动生成一个serialVersionUID作序列化版本比较用,这种情况下,如果类信息进行修改,会导致反序列化时serialVersionUID与原先值无法match,反序列化失败。 - -通过jdk提升的序列化对其进行相应的序列化和反序列化的代码案例 - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -``` -package com.sise.test.jdk; - - -import com.sise.test.Person; - -import java.io.IOException; - -/** - * @author idea - * @date 2019/8/15 - * @Version V1.0 - */ -public class SerializationTest { - - /** - * - * @param args - * @throws IOException - */ - public static void main(String[] args) throws IOException, ClassNotFoundException { - - long begin = System.currentTimeMillis(); - for (int i = 0; i < 2000; i++) { - String fileName = "test-person.txt"; - Person person = new Person(); - person.setId(1); - person.setTel("99562352"); - person.setUsername("idea"); - SerializationUtil.serialize(person, fileName); - Person newPerson = (Person) SerializationUtil.deserialize(fileName); - } - long end = System.currentTimeMillis(); - System.out.println("耗时:" + (end - begin)); - } -} -``` - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - - - -**jdk序列化的缺点** - -**1、无法跨语言** - -这一缺点几乎是致命伤害,对于跨进程的服务调用,通常都需要考虑到不同语言的相互调用时候的兼容性,而这一点对于jdk序列化操作来说却无法做到。这是因为jdk序列化操作时是使用了java语言内部的私有协议,在对其他语言进行反序列化的时候会有严重的阻碍。 - -**2、序列化之后的码流过大** - -jdk进行序列化编码之后产生的字节数组过大,占用的存储内存空间也较高,这就导致了相应的流在网络传输的时候带宽占用较高,性能相比较为低下的情况。 - -## Hessian序列化框架 - -Hessian是一款支持多种语言进行序列化操作的框架技术,同时在进行序列化之后产生的码流也较小,处理数据的性能方面远超于java内置的jdk序列化方式。 - -相关的代码案例: - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -``` -package com.sise.test.hessian; - -import com.caucho.hessian.io.HessianInput; -import com.caucho.hessian.io.HessianOutput; -import com.sise.test.Person; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -/** - * @author idea - * @date 2019/8/15 - * @Version V1.0 - */ -public class HessianTest { - - /** - * - * @param args - * @throws IOException - */ - public static void main(String[] args) throws IOException { - long begin = System.currentTimeMillis(); - for (int i = 0; i < 2000; i++) { - Person person = new Person(); - person.setId(1); - person.setUsername("idea"); - person.setTel("99562352"); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - HessianOutput ho = new HessianOutput(os); - ho.writeObject(person); - byte[] userByte = os.toByteArray(); - ByteArrayInputStream is = new ByteArrayInputStream(userByte); - //Hessian的反序列化读取对象 - HessianInput hi = new HessianInput(is); - Person newPerson = (Person) hi.readObject(); - } - long end = System.currentTimeMillis(); - System.out.println("耗时:" + (end - begin)); - } -} -``` - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - - - -Hessian的源码里面,核心主要还是com.caucho.hessian.io里面的代码,AbstractSerializer是Hessian里面的核心序列化类,当我们仔细查看源码的时候就会发现hessian提供了许多种序列化和反序列化的类进行不同类型数据的处理。(我使用的是hessian4.0,因此相应的类会多很多) - -![序列化框架的选型和比对](https://www.javazhiyin.com/wp-content/uploads/2019/08/java3-1566180549.jpg) - - -在SerializerFactory里面有getSerializer和getDefaultSerializer的函数,专门用于提取这些序列化和反序列化的工具类,这样可以避免在使用该工具类的时候又要重新实例化,这些工具类都会被存储到不同的ConcurrentHashMap里面去。 - - - -![序列化框架的选型和比对](https://www.javazhiyin.com/wp-content/uploads/2019/08/java1-1566180549.png) - - -*ps:对于hessian3.0时候的Serializer/Derializer实现功能没有考虑到对于异常信息进行序列化处理,因此如果遇到相应问题的朋友可以考虑将hessian的版本提升到3.1.5以上。* - -## Kryo序列化技术 - -Kryo是一种非常成熟的序列化实现,已经在Twitter、Groupon、 Yahoo以及多个著名开源项目(如Hive、Storm)中广泛的使用,它的性能在各个方面都比hessian2要优秀些,因此dubbo后期也开始渐渐引入了使用Kryo进行序列化的方式。 - -对于kryo的使用,我们来看看相应代码: - -首先我们引入相应的依赖: - -``` - - com.esotericsoftware - kryo-shaded - 3.0.3 - -``` - - - -然后就是基础的序列化和反序列化代码操作了 - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -``` -package com.sise.test.kryo; - -import com.esotericsoftware.kryo.Kryo; -import com.esotericsoftware.kryo.io.Input; -import com.esotericsoftware.kryo.io.Output; -import com.sise.test.Person; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; - -/** - * @author idea - * @date 2019/8/15 - * @Version V1.0 - */ -public class KryoTest { - - public static void main(String[] args) throws FileNotFoundException { - Kryo kryo=new Kryo(); - Output output = new Output(new FileOutputStream("person.txt")); - Person person=new Person(); - person.setId(1); - person.setUsername("idea"); - kryo.writeObject(output, person); - output.close(); - Input input = new Input(new FileInputStream("person.txt")); - Person person1 = kryo.readObject(input, Person.class); - input.close(); - System.out.println(person1.toString()); - assert "idea".equals(person1.getUsername()); - } -} -``` - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - - - -ps:*这里我们需要注意,Kryo不支持没有无参构造函数的对象进行反序列化,因此如果某个对象希望使用Kryo来进行序列化操作的话,需要有相应的无参构造函数才可以。* - -由于Kryo不是线程安全,因此当我们希望使用Kryo构建的工具类时候,需要在实例化的时候注意线程安全的问题。代码案例: - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -``` -package com.sise.test.kryo; - -import com.esotericsoftware.kryo.Kryo; -import com.esotericsoftware.kryo.io.Input; -import com.esotericsoftware.kryo.io.Output; -import com.sise.test.Person; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; - -/** - * @author idea - * @data 2019/8/17 - */ -public class KryoUtils { - - - public byte[] serialize(Object obj){ - Kryo kryo = kryos.get(); - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - Output output = new Output(byteArrayOutputStream); - kryo.writeClassAndObject(output, obj); - output.close(); - return byteArrayOutputStream.toByteArray(); - } - - public T deserialize(byte[] bytes) { - Kryo kryo = kryos.get(); - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); - Input input = new Input(byteArrayInputStream); - input.close(); - return (T) kryo.readClassAndObject(input); - } - - - private static final ThreadLocal kryos=new ThreadLocal(){ - @Override - protected Kryo initialValue(){ - Kryo kryo=new Kryo(); - return kryo; - } - - }; - - - public static void main(String[] args) { - KryoUtils kryoUtils=new KryoUtils(); - for(int i=0;i<1000;i++){ - Person person=new Person(1,"idea"); - byte[] bytes=kryoUtils.serialize(person); - Person newPerson=kryoUtils.deserialize(bytes); - System.out.println(newPerson.toString()); - } - } -} -``` - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - - - -## XStream实现对象的序列化 - -在使用XStream进行序列化技术的实现过程中,类中的字符串组成了 XML 中的元素内容,而且该对象还不需要实现 Serializable 接口。XStream不关心被序列化/反序列化的类字段的可见性,该对象也不需要有getter/setter方法和默认的构造函数。 - -引入的依赖: - -``` - - com.thoughtworks.xstream - xstream - 1.4.9 - -``` - - - -通过使用XStream来对对象进行序列化和反序列化操作: - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - -``` -package com.sise.test.xstream; - - -import com.sise.test.Person; -import com.thoughtworks.xstream.XStream; -import com.thoughtworks.xstream.io.xml.DomDriver; - -/** - * @author idea - * @date 2019/8/15 - * @Version V1.0 - */ -public class XStreamTest { - - - private static XStream xStream; - - static { - xStream = new XStream(new DomDriver()); - /* - * 使用xStream.alias(String name, Class Type)为任何一个自定义类创建到类到元素的别名 - * 如果不使用别名,则生成的标签名为类全名 - */ - xStream.alias("person", Person.class); - } - - //xml转java对象 - public static Object xmlToBean(String xml) { - return xStream.fromXML(xml); - } - - //java对象转xml - public static String beanToXml(Object obj) { - return "n" + xStream.toXML(obj); - } - - /** - * - * @param args - */ - public static void main(String[] args) { - long begin = System.currentTimeMillis(); - for (int i = 0; i < 2000; i++) { - Person person = new Person(); - person.setId(1); - person.setUsername("idea"); - String xml = XStreamTest.beanToXml(person); - Person newPerson = (Person) XStreamTest.xmlToBean(xml); - } - long end = System.currentTimeMillis(); - System.out.println("耗时:" + (end - begin)); - } -} -``` - -[![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0);) - - - -## google的Protobuf - -google protobuf是一个灵活的、高效的用于序列化数据的协议。相比较XML和JSON格式,protobuf更小、更快、更便捷。google protobuf是跨语言的,并且自带了一个编译器(protoc),只需要用它进行编译,可以编译成Java、python、C++、C#、Go等代码,然后就可以直接使用,不需要再写其他代码,自带有解析的代码。 -protobuf相对于kryo来说具有更加高效的性能和灵活性,能够在实际使用中,当对象序列化之后新增了字段,在反序列化出来的时候依旧可以正常使用。(这一点kryo无法支持) - -## 不同序列化框架的总结 - -![序列化框架的选型和比对](https://www.javazhiyin.com/wp-content/uploads/2019/08/java7-1566180549.png) - -目前已有的序列化框架还有很多在文中没有提到,日后假若在开发中遇到的时候可以适当的进行归纳总结,比对各种不同的序列化框架之间的特点。 \ No newline at end of file diff --git a/jun_java_plugins/jun_shiro/pom.xml b/jun_java_plugins/jun_shiro/pom.xml deleted file mode 100644 index 045a6b356e..0000000000 --- a/jun_java_plugins/jun_shiro/pom.xml +++ /dev/null @@ -1,6 +0,0 @@ - - 4.0.0 - io.github.wujun728 - jun_shiro - 1.0 - \ No newline at end of file diff --git a/jun_java_plugins/jun_solr/.gitignore b/jun_java_plugins/jun_solr/.gitignore deleted file mode 100644 index 3d753b6792..0000000000 --- a/jun_java_plugins/jun_solr/.gitignore +++ /dev/null @@ -1,40 +0,0 @@ -*.class - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ - -# Package Files # -*.jar -*.war -*.ear - -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* - -# Ignore all logfiles and tempfiles. -.project -/*/.project - -.classpath -/*/.classpath - -.settings -/*/.settings -/*/.settings/* - -target -/*/target -/*/target/* - -.DS_Store - -.svn -.svn/* - -.idea -.idea/* - -Thumbs.db - -*.log -*.out diff --git a/jun_java_plugins/jun_solr/.keep b/jun_java_plugins/jun_solr/.keep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/jun_java_plugins/jun_solr/README.md b/jun_java_plugins/jun_solr/README.md deleted file mode 100644 index 28062a2f25..0000000000 --- a/jun_java_plugins/jun_solr/README.md +++ /dev/null @@ -1,39 +0,0 @@ -jun_solr -================== - -基于Solr的搜索系统 - - -一、前置项目依赖 - -https://github.com/pumadong/cl-commodity - -Solr官网:http://lucene.apache.org/solr/ - -二、项目说明 - -简单演示对商品信息的全量索引建立、主从配置以及搜索的Dubbo接口提供。 - -对Solr做了入门型的说明,基本满足基于Solr的搜索的日常应用,对于更多Solr的参数设置,深入研究需要在实践中不断总结进步。 - -Solr版本4.9.0,关于Solr4.9.0的入门级使用,基本配置、中文分词、主从配置,可以参阅这篇文章: - -http://blog.csdn.net/puma_dong/article/details/38880699 - -关于索引,基本内容大致包含如下:商品(编码,款号、名称、价格、尺码编号、尺码名称、颜色、价格、折扣、图片链接、销量)、分类(名称、别名、编码、拼音名称)、品牌(编码、中英文名称、别名、拼音名称、首字母拼音名称)、商品的属性项目(属性值),以及一些用来排序的信息:销量、价格、折扣等。对于品牌分类等,需要同时记录英文名称。 - -索引还需要一些管理控制功能,比如脏词屏蔽、扩展词库等;为了提高建立索引的效率,可能还需要对一些中间结果进行计算,比如:商品的2周销售数量。 - -注:关于分类的别名、品牌的别名之类,不建议在搜索系统中单独为,建议提需求给商品管理系统。 - -本项目仅仅是演示的雏形,流程是可用的,单没有完整的信息完整的索引创建、索引接口、及管理控制功能,这个留待以后是否有足够的业余时间。 - -索引建立的运行方式如下: - -crontab: */10 * * * * /usr/local/cl/create_index.sh & - -三、技术框架 - -在索引建立项目中,没有使用任何框架,使用最基础的JDK编码,定时任务方式采用crontab,任务流程控制采用linux shell命令。 - -索引查询接口项目中,依旧是采用dubbo提供接口。 \ No newline at end of file diff --git a/jun_java_plugins/jun_solr/create_index.sh b/jun_java_plugins/jun_solr/create_index.sh deleted file mode 100644 index 1167acff54..0000000000 --- a/jun_java_plugins/jun_solr/create_index.sh +++ /dev/null @@ -1,39 +0,0 @@ -path=/usr/local/cl/search -tempfile=/usr/local/cl/search/tmp.txt -log=/usr/local/cl/search/createIndex.log - -export JAVA_HOME=/usr/local/java/jdk1.7.0_45 -export CLASSPATH=.:$JAVA_HOME/jre/lib/rt.jar:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar -export PATH=$PATH:$JAVA_HOME/bin - -export LC_ALL=zh_CN.UTF-8 - -date >> "$log" - -if [ -f "$tempfile" ]; then - echo '索引正在生成,尚未完成' >> "$log" - echo '' >> "$log" -else - echo '索引准备生成 ' >> "$log" - echo '' >> "$log" - touch "$tempfile" - cd "$path" - - CLASSPATH=. - - for f in ./*.jar; do - CLASSPATH=${CLASSPATH}:$f; - done - - for f in lib/*.jar; do - CLASSPATH=${CLASSPATH}:$f; - done - - echo '索引开始生成......' >> "$log" - echo '' >> "$log" - java -Xms1024m -Xmx4096m -classpath $CLASSPATH com.cl.search.CreateIndex >> "$log" - sleep 10 - rm "$tempfile" - echo '索引生成完毕' >> "$log" - echo '' >> "$log" -fi \ No newline at end of file diff --git a/jun_java_plugins/jun_solr/jun_solr_api/pom.xml b/jun_java_plugins/jun_solr/jun_solr_api/pom.xml deleted file mode 100644 index 06a4c90057..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_api/pom.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_solr_api - 1.0 - jar - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.1 - - 8 - 8 - UTF-8 - - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_solr/jun_solr_api/src/main/java/com/jun/plugin/solr/api/ISearchBaseApiService.java b/jun_java_plugins/jun_solr/jun_solr_api/src/main/java/com/jun/plugin/solr/api/ISearchBaseApiService.java deleted file mode 100644 index d512a9822c..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_api/src/main/java/com/jun/plugin/solr/api/ISearchBaseApiService.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jun.plugin.solr.api; - -import com.jun.plugin.solr.model.SearchModel; -import com.jun.plugin.solr.model.SearchResult; - -public interface ISearchBaseApiService { - - SearchResult getWebSearchResult(SearchModel searchModel); -} diff --git a/jun_java_plugins/jun_solr/jun_solr_api/src/main/java/com/jun/plugin/solr/model/Commodity.java b/jun_java_plugins/jun_solr/jun_solr_api/src/main/java/com/jun/plugin/solr/model/Commodity.java deleted file mode 100644 index daa132b2f8..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_api/src/main/java/com/jun/plugin/solr/model/Commodity.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.jun.plugin.solr.model; - -import java.io.Serializable; - -public class Commodity implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - - private String no; - private Integer brandId; - private String name; - private String styleNo; - private Integer salePrice; - - public String getNo() { - return no; - } - public void setNo(String no) { - this.no = no; - } - public Integer getBrandId() { - return brandId; - } - public void setBrandId(Integer brandId) { - this.brandId = brandId; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public String getStyleNo() { - return styleNo; - } - public void setStyleNo(String styleNo) { - this.styleNo = styleNo; - } - public Integer getSalePrice() { - return salePrice; - } - public void setSalePrice(Integer salePrice) { - this.salePrice = salePrice; - } - -} diff --git a/jun_java_plugins/jun_solr/jun_solr_api/src/main/java/com/jun/plugin/solr/model/FacetItem.java b/jun_java_plugins/jun_solr/jun_solr_api/src/main/java/com/jun/plugin/solr/model/FacetItem.java deleted file mode 100644 index f621617fa4..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_api/src/main/java/com/jun/plugin/solr/model/FacetItem.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.jun.plugin.solr.model; - -import java.io.Serializable; -import java.util.List; - -public class FacetItem implements Serializable { - - private static final long serialVersionUID = 1L; - - private String id; - private String name; - private Integer valueCount; - private List valueList; - - public String getId() { - return id; - } - public void setId(String id) { - this.id = id; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public Integer getValueCount() { - return valueCount; - } - public void setValueCount(Integer valueCount) { - this.valueCount = valueCount; - } - public List getValueList() { - return valueList; - } - public void setValueList(List valueList) { - this.valueList = valueList; - } - - -} diff --git a/jun_java_plugins/jun_solr/jun_solr_api/src/main/java/com/jun/plugin/solr/model/FacetValue.java b/jun_java_plugins/jun_solr/jun_solr_api/src/main/java/com/jun/plugin/solr/model/FacetValue.java deleted file mode 100644 index 456b2324f7..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_api/src/main/java/com/jun/plugin/solr/model/FacetValue.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.jun.plugin.solr.model; - -import java.io.Serializable; - -public class FacetValue implements Serializable { - - private static final long serialVersionUID = 1L; - - private String id; - private String name; - private Integer count; - - public String getId() { - return id; - } - public void setId(String id) { - this.id = id; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public Integer getCount() { - return count; - } - public void setCount(Integer count) { - this.count = count; - } - -} diff --git a/jun_java_plugins/jun_solr/jun_solr_api/src/main/java/com/jun/plugin/solr/model/ResultType.java b/jun_java_plugins/jun_solr/jun_solr_api/src/main/java/com/jun/plugin/solr/model/ResultType.java deleted file mode 100644 index 16b43c594a..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_api/src/main/java/com/jun/plugin/solr/model/ResultType.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.jun.plugin.solr.model; - -public enum ResultType { - - EMPYTY(0), //无结果 - NORMAL(1), //正常 - PINYIN(2), //关键字拼音查询 - ANALYZER(3); //关键字中文分词查询 - - private int type; - - private ResultType(int type){ - this.type = type; - } - - public int getResultType(){ - return type; - } -} diff --git a/jun_java_plugins/jun_solr/jun_solr_api/src/main/java/com/jun/plugin/solr/model/SearchModel.java b/jun_java_plugins/jun_solr/jun_solr_api/src/main/java/com/jun/plugin/solr/model/SearchModel.java deleted file mode 100644 index 84c1c3d53c..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_api/src/main/java/com/jun/plugin/solr/model/SearchModel.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.jun.plugin.solr.model; - -import java.io.Serializable; - -public class SearchModel implements Serializable { - - private static final long serialVersionUID = 1L; - - private Integer pageNo; - private String keyword; - private Integer brandId; - - public Integer getPageNo() { - return pageNo; - } - - public void setPageNo(Integer pageNo) { - this.pageNo = pageNo; - } - - public String getKeyword() { - return keyword; - } - - public void setKeyword(String keyword) { - this.keyword = keyword; - } - - public Integer getBrandId() { - return brandId; - } - - public void setBrandId(Integer brandId) { - this.brandId = brandId; - } - -} diff --git a/jun_java_plugins/jun_solr/jun_solr_api/src/main/java/com/jun/plugin/solr/model/SearchResult.java b/jun_java_plugins/jun_solr/jun_solr_api/src/main/java/com/jun/plugin/solr/model/SearchResult.java deleted file mode 100644 index 1d6641ab98..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_api/src/main/java/com/jun/plugin/solr/model/SearchResult.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.jun.plugin.solr.model; - -import java.io.Serializable; -import java.util.List; -import java.util.Map; - -public class SearchResult implements Serializable { - - private static final long serialVersionUID = 1L; - - private ResultType resultType; - private List commodityList; //正常查询时的结果 - private Map> commodityMap; //分词查询时的结果 - private List facetItemList; //对于有多条件过滤的搜索页面需要的Facet内容 - - public ResultType getResultType() { - return resultType; - } - public void setResultType(ResultType resultType) { - this.resultType = resultType; - } - public List getCommodityList() { - return commodityList; - } - public void setCommodityList(List commodityList) { - this.commodityList = commodityList; - } - public Map> getCommodityMap() { - return commodityMap; - } - public void setCommodityMap(Map> commodityMap) { - this.commodityMap = commodityMap; - } - public List getFacetItemList() { - return facetItemList; - } - public void setFacetItemList(List facetItemList) { - this.facetItemList = facetItemList; - } -} diff --git a/jun_java_plugins/jun_solr/jun_solr_api_server/pom.xml b/jun_java_plugins/jun_solr/jun_solr_api_server/pom.xml deleted file mode 100644 index 990c8f81bb..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_api_server/pom.xml +++ /dev/null @@ -1,161 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_solr_api_server - 1.0 - war - - - UTF-8 - 4.0.6.RELEASE - - - - - io.github.wujun728 - jun_solr_api - 1.0 - - - - org.jasig.cas.client - cas-client-core - 3.2.2 - - - org.apache.solr - solr-core - 4.3.1 - - - commons-io - commons-io - - - - - - - log4j - log4j - 1.2.16 - - - org.slf4j - slf4j-api - 1.6.1 - - - org.slf4j - slf4j-log4j12 - 1.6.1 - - - - org.springframework - spring-core - ${spring.version} - - - org.springframework - spring-beans - ${spring.version} - - - org.springframework - spring-context - ${spring.version} - - - org.springframework - spring-context-support - ${spring.version} - - - org.springframework - spring-web - ${spring.version} - - - org.springframework - spring-webmvc - ${spring.version} - - - org.springframework - spring-aspects - ${spring.version} - - - org.springframework - spring-jdbc - ${spring.version} - - - org.springframework.data - spring-data-redis - 1.3.1.RELEASE - - - - com.alibaba - dubbo - 2.5.3 - - - org.springframework - spring - - - netty - org.jboss.netty - - - - - com.github.sgroschupf - zkclient - 0.1 - - - - com.caucho - hessian - 4.0.7 - - - - mysql - mysql-connector-java - test - 5.1.14 - - - - org.mybatis - mybatis - 3.2.3 - - - org.mybatis - mybatis-spring - 1.2.0 - - - com.belerweb - pinyin4j - 2.5.1 - - - com.twelvemonkeys.common - common-io - 3.4.1 - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/java/com/jun/plugin/solr/api/impl/SearchBaseApiServiceImpl.java b/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/java/com/jun/plugin/solr/api/impl/SearchBaseApiServiceImpl.java deleted file mode 100644 index e6bced4bbc..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/java/com/jun/plugin/solr/api/impl/SearchBaseApiServiceImpl.java +++ /dev/null @@ -1,175 +0,0 @@ -package com.jun.plugin.solr.api.impl; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.lang.StringUtils; -import org.apache.solr.client.solrj.SolrQuery; -import org.apache.solr.client.solrj.SolrServerException; -import org.apache.solr.client.solrj.impl.HttpSolrServer; -import org.apache.solr.client.solrj.response.FacetField; -import org.apache.solr.client.solrj.response.FacetField.Count; -import org.apache.solr.client.solrj.response.QueryResponse; -import org.apache.solr.common.SolrDocument; -import org.apache.solr.common.SolrDocumentList; -import org.apache.solr.common.params.FacetParams; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import com.jun.plugin.solr.api.ISearchBaseApiService; -import com.jun.plugin.solr.model.Commodity; -import com.jun.plugin.solr.model.FacetItem; -import com.jun.plugin.solr.model.FacetValue; -import com.jun.plugin.solr.model.ResultType; -import com.jun.plugin.solr.model.SearchModel; -import com.jun.plugin.solr.model.SearchResult; -import com.jun.plugin.solr.utils.ConstantUtil; -import com.jun.plugin.solr.utils.PinyinUtil; -import com.jun.plugin.solr.utils.SolrUtil; - -@Service -public class SearchBaseApiServiceImpl implements ISearchBaseApiService { - - @Autowired - private SolrUtil solrUtil; - - @Override - public SearchResult getWebSearchResult(SearchModel searchModel) { - - initSearchModel(searchModel); - - SearchResult sr = null; - - SolrQuery solrQuery = new SolrQuery(); - setF1(solrQuery); //设置返回列 - setPage(solrQuery,searchModel); //设置分页 - setFacet(solrQuery); //设置Facet,如果页面不需要Facet,则不查询,这个查询会更耗时 - setOrderBy(solrQuery); //设置结果排序 - - solrQuery.setQuery(searchModel.getKeyword()); - setFilter(solrQuery,searchModel); - - sr = search(solrQuery,ResultType.NORMAL); - if(sr!=null) return sr; - - //如果没有结果,按照拼音查询一次 - solrQuery.setQuery(PinyinUtil.getPingYin(searchModel.getKeyword())); - sr = search(solrQuery,ResultType.PINYIN); - if(sr!=null) return sr; - - //如果还没有结果,按照分词后的查询一次 - - //如果还没有结果,返回null - return null; - } - - private void initSearchModel(SearchModel searchModel) - { - if(StringUtils.isEmpty(searchModel.getKeyword())) searchModel.setKeyword("*"); - if(searchModel.getPageNo()==null) searchModel.setPageNo(1); - } - private void setF1(SolrQuery solrQuery) - { - solrQuery.setParam("fl", "no,name,style_no,sale_price,brand_id"); - } - private void setPage(SolrQuery solrQuery,SearchModel searchModel) - { - solrQuery.setStart((searchModel.getPageNo()-1)*ConstantUtil.PageSize); - solrQuery.setRows(ConstantUtil.PageSize); - } - private void setFacet(SolrQuery solrQuery) - { - String[] ff = new String[2]; - ff[0] = "style_no"; - ff[1] = "brand_id"; - - solrQuery.setFacet(true); - solrQuery.addFacetField(ff); - solrQuery.setFacetLimit(-1); - solrQuery.setFacetSort(FacetParams.FACET_SORT_COUNT ); - solrQuery.setFacetMinCount(1); - } - private void setFilter(SolrQuery solrQuery,SearchModel searchModel) - { - solrQuery.addFilterQuery("brand_id:" + "(1)"); - } - private void setOrderBy(SolrQuery solrQuery) - { - solrQuery.setParam("sort", "no desc"); - } - private List getCommodityList(SolrDocumentList sdList) - { - List commodityList = new ArrayList(); - for(SolrDocument sd : sdList) - { - Commodity c = new Commodity(); - c.setName(sd.get("name").toString()); - c.setNo(sd.get("no").toString()); - c.setSalePrice(Integer.parseInt(sd.get("sale_price").toString())); - c.setStyleNo(sd.get("style_no").toString()); - c.setSalePrice(Integer.parseInt(sd.get("brand_id").toString())); - commodityList.add(c); - } - return commodityList; - } - private List getFacetList(List ffList) - { - List facetItemList = new ArrayList(); - for(FacetField f: ffList) - { - FacetItem fi = new FacetItem(); - fi.setId(f.getName()); - fi.setName("null"); //关于Filter显示的选项名称,需要计算 - fi.setValueCount(f.getValueCount()); - - List fvList = new ArrayList(); - - for(Count c:f.getValues()) - { - FacetValue fv = new FacetValue(); - fv.setId(c.getName()); - fv.setName("null"); //关于Filter显示的选项名称,需要计算 - fv.setCount((int) c.getCount()); - fvList.add(fv); - } - - fi.setValueList(fvList); - - facetItemList.add(fi); - } - return facetItemList; - } - private SearchResult search(SolrQuery solrQuery,ResultType resultType) - { - HttpSolrServer hss = solrUtil.getSolrHttpConnect(); - - SearchResult sr = null; - SolrDocumentList sdList = null; - QueryResponse qr = null; - - try { - qr = hss.query(solrQuery); - sdList = qr.getResults(); - } catch (SolrServerException e) { - e.printStackTrace(); //吃掉,下一个 - return null; - } - - if(sdList.getNumFound() > 0){ - sr = new SearchResult(); - sr.setResultType(resultType); - List commodityList = getCommodityList(sdList); - sr.setCommodityList(commodityList); - - List ffList = qr.getFacetFields(); - if(ffList.size() > 0) - { - List facetItemList = getFacetList(ffList); - sr.setFacetItemList(facetItemList); - } - return sr; - } - - return null; - } -} diff --git a/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/java/com/jun/plugin/solr/utils/ConfigUtil.java b/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/java/com/jun/plugin/solr/utils/ConfigUtil.java deleted file mode 100644 index b49af9eff9..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/java/com/jun/plugin/solr/utils/ConfigUtil.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.jun.plugin.solr.utils; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -@Component -public class ConfigUtil { - - private @Value("${solrUrl}")String solrUrl; - - public String getCasServerUrl() { - return solrUrl; - } - -} diff --git a/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/java/com/jun/plugin/solr/utils/ConstantUtil.java b/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/java/com/jun/plugin/solr/utils/ConstantUtil.java deleted file mode 100644 index c088bb1b04..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/java/com/jun/plugin/solr/utils/ConstantUtil.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.jun.plugin.solr.utils; - -public class ConstantUtil { - - public static final String Fail = "fail"; - - public static final String Success = "success"; - - public static final String Exists = "exists"; - - public static final String EmptyJsonObject = "{}"; - - public static final String DefaultMd5Password = "63a9f0ea7bb98050796b649e85481845"; //root - - /** - * 分页,每页记录数 - */ - public static final Integer PageSize = 20; -} diff --git a/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/java/com/jun/plugin/solr/utils/PinyinUtil.java b/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/java/com/jun/plugin/solr/utils/PinyinUtil.java deleted file mode 100644 index af1075b5b5..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/java/com/jun/plugin/solr/utils/PinyinUtil.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.jun.plugin.solr.utils; - -import net.sourceforge.pinyin4j.PinyinHelper; -import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType; -import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat; -import net.sourceforge.pinyin4j.format.HanyuPinyinToneType; -import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType; -import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination; - -public class PinyinUtil { - - private static HanyuPinyinOutputFormat hypof; - - static { - hypof = new HanyuPinyinOutputFormat(); - hypof.setCaseType(HanyuPinyinCaseType.LOWERCASE); - hypof.setToneType(HanyuPinyinToneType.WITHOUT_TONE); - hypof.setVCharType(HanyuPinyinVCharType.WITH_V); - } - - public static String getPingYin(String src) { - char[] t1 = src.toCharArray(); - String[] t2 = new String[t1.length]; - String t4 = ""; - int t0 = t1.length; - try { - for (int i = 0; i < t0; i++) { - // 判断是否为汉字字符 - if (Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")) { - t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], - hypof); - if(t2!=null){ - t4 += t2[0]; - } - } else - t4 += Character.toString(t1[i]); - } - t1 = null; - t2 = null; - } catch (BadHanyuPinyinOutputFormatCombination e1) { - e1.printStackTrace(); - } - return t4; - } - - public static String getPinYinHeadChar(String str) { - String convert = ""; - char word; - String[] pinyinArray = null; - for (int j = 0; j < str.length(); j++) { - word = str.charAt(j); - pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word); - if (pinyinArray != null) { - convert += pinyinArray[0].charAt(0); - } else { - convert += word; - } - } - return convert; - } -} diff --git a/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/java/com/jun/plugin/solr/utils/SolrUtil.java b/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/java/com/jun/plugin/solr/utils/SolrUtil.java deleted file mode 100644 index c335018dda..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/java/com/jun/plugin/solr/utils/SolrUtil.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.jun.plugin.solr.utils; - -import org.apache.solr.client.solrj.impl.BinaryRequestWriter; -import org.apache.solr.client.solrj.impl.HttpSolrServer; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - - -@Service -public class SolrUtil { - - @Autowired - private ConfigUtil configUtil; - - public HttpSolrServer getSolrHttpConnect() { - - HttpSolrServer ss = new HttpSolrServer(configUtil.getCasServerUrl()); - ss.setSoTimeout(500000); - ss.setConnectionTimeout(500000); - ss.setDefaultMaxConnectionsPerHost(1000); - ss.setMaxTotalConnections(1000); - ss.setFollowRedirects(false); - ss.setAllowCompression(true); - ss.setRequestWriter(new BinaryRequestWriter()); - ss.setMaxRetries(5); - return ss; - } - -} diff --git a/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/java/com/jun/plugin/solr/utils/SpringContextHolder.java b/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/java/com/jun/plugin/solr/utils/SpringContextHolder.java deleted file mode 100644 index b27de04d2c..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/java/com/jun/plugin/solr/utils/SpringContextHolder.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.jun.plugin.solr.utils; - - -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; - -public class SpringContextHolder implements ApplicationContextAware { - - private static ApplicationContext applicationContext; - - public void setApplicationContext(ApplicationContext ac) - { - applicationContext = ac; - } - - public static ApplicationContext getApplicationContext() - { - checkApplicationContext(); - return applicationContext; - } - - @SuppressWarnings("unchecked") - public static T getBean(String name) - { - checkApplicationContext(); - return (T) applicationContext.getBean(name); - } - - public static T getBean(Class requiredType) - { - checkApplicationContext(); - return applicationContext.getBean(requiredType); - } - - public static void cleanApplicationContext() - { - applicationContext = null; - } - - private static void checkApplicationContext() { - if (applicationContext == null) - throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder"); - } - -} diff --git a/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/java/com/jun/plugin/solr/utils/StringUtil.java b/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/java/com/jun/plugin/solr/utils/StringUtil.java deleted file mode 100644 index 6ba4c55e76..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/java/com/jun/plugin/solr/utils/StringUtil.java +++ /dev/null @@ -1,1220 +0,0 @@ -package com.jun.plugin.solr.utils; - -import java.io.UnsupportedEncodingException; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.security.MessageDigest; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class StringUtil -{ - /** - * 按照数字的方式比较两个字符串 - * @param str1 - * @param str2 - * @return - */ - public static int compareTo(String str1,String str2) - { - int dis = Math.abs(str1.length()-str2.length()); - if(dis!=0) - { - String temp = ""; - for(int i=0;istr2.length()) - { - str2 = temp + str2; - } else { - str1 = temp + str1; - } - } - - return str1.compareTo(str2); - } - - public static String getValue(String str) - { - if (str == null) return ""; - if (str.trim().length() <= 0) return ""; - str = "H" + str; - str = str.trim(); - str = str.substring(1); - return str; - } - - public static boolean isStrEmpty(String str) - { - return ((str == null) || (str.equals(""))); - } - - public static boolean isStrTrimEmpty(String str) - { - return ((str == null) || (str.trim().equals(""))); - } - - public static boolean chkTextLen(String text, int len) - { - return ((text != null) && (text.length() <= len)); - } - - public static boolean chkTextTrimLen(String text, int len) - { - return ((text != null) && (text.trim().length() <= len)); - } - - public static boolean isStrEn(String text) - { - for (int i = 0; i < text.length(); ++i) { - if (text.charAt(i) > '') { - return false; - } - } - return true; - } - - public static boolean isCharNum(char ch) - { - return ((ch > '/') && (ch < ':')); - } - - public static boolean isStrNum(String str) - { - if (isStrEmpty(str)) { - return true; - } - boolean notNum = false; - for (int i = 0; i < str.length(); ++i) { - if (!(isCharNum(str.charAt(i)))) { - notNum = true; - } - } - return (!(notNum)); - } - - public static boolean isNum(String strSrc) - throws Exception - { - for (int i = 0; i < strSrc.length(); ++i) { - if (!(isCharNum(strSrc.charAt(i)))) - return false; - } - return true; - } - - public static boolean isCharLetter(char ch) - { - return (((ch >= 'A') && (ch <= 'Z')) || ((ch >= 'a') && (ch <= 'z'))); - } - - public static boolean isStrLetter(String str) - { - if (isStrEmpty(str)) - return true; - boolean notLetter = false; - for (int i = 0; i < str.length(); ++i) { - if (!(isCharLetter(str.charAt(i)))) { - notLetter = true; - } - } - return (!(notLetter)); - } - - public String nullToSpace(String Content) - { - if (Content == null) { - Content = ""; - } - return Content; - } - - public static char StrToChar(String src) - { - src = src.trim(); - char result = src.charAt(0); - return result; - } - - public static String encodeSQL(String sql) - { - StringBuffer tempBuff = new StringBuffer(); - for (int i = 0; i < sql.length(); ++i) { - tempBuff.append(Integer.toHexString(sql.charAt(i))); - } - return tempBuff.toString(); - } - - public static String decodeSQL(String encoded) - { - StringBuffer tempBuff = new StringBuffer(); - for (int i = 0; i < encoded.length(); i += 2) { - tempBuff.append((char)Integer.parseInt(encoded.substring(i, i + 2), 16)); - } - - return tempBuff.toString(); - } - - public static String getAbsolutePath(String path1, String context1) - { - int i1 = path1.indexOf(context1); - if (i1 < 0) return path1; - - return path1.substring(path1.indexOf(context1) + context1.length()); - } - - public static String getSubString(String str1, int sindex, int eindex) - { - if (str1 == null) return ""; - if (str1.trim().length() <= 0) return ""; - if (str1.length() > sindex) - { - if (eindex >= 0) - return str1.substring(sindex, eindex); - if (eindex < 0) - return str1.substring(sindex); - } - return ""; - } - - public static String[] getValues(String[] strs, int size1) - { - String[] strs1 = new String[size1]; - for (int i = 0; i < size1; ++i) - { - strs1[i] = ""; - } - if (strs == null) return strs1; - - if (strs.length < size1) - { - for (int i = 0; i < strs.length; ++i) - { - strs1[i] = strs[i]; - } - return strs1; - } - - return strs; - } - - public static String replaceStrAll(String strSource, String strFrom, String strTo) - { - String strDest = ""; - int intFromLen = strFrom.length(); - - int intPos; - while ((intPos = strSource.indexOf(strFrom)) != -1) - { - strDest = strDest + strSource.substring(0, intPos); - strDest = strDest + strTo; - strSource = strSource.substring(intPos + intFromLen); - } - strDest = strDest + strSource; - return strDest; - } - - public static String replaceStr(String strTarget, String strNew) - { - int iIndex = -1; - while (true) - { - iIndex = strTarget.indexOf(10); - - if (iIndex < 0) { - break; - } - - String strTemp = null; - strTemp = strTarget.substring(0, iIndex); - - strTarget = strTemp + strNew + strTarget.substring(iIndex + 1); - } - - return strTarget; - } - - public static boolean includestr(String str1, String[] strarray) - { - if ((strarray == null) || (strarray.length <= 0)) return false; - for (int i = 0; i < strarray.length; ++i) - { - if (strarray[i] == null) - { - if (str1 == null) return true; - - } - else if (strarray[i].trim().equals(str1)) - { - return true; - } - } - return false; - } - - public static String[] getAreaValues(String fvalue) - { - String tmpstr = fvalue; - int i = 0; - if (tmpstr == null) return null; - if (tmpstr.trim().equals("")) return null; - while (tmpstr.indexOf("\n") >= 0) { - ++i; - tmpstr = tmpstr.substring(tmpstr.indexOf("\n") + 1); - } - if (tmpstr.trim().equals("")) --i; - String[] fvalues = new String[i + 1]; - tmpstr = fvalue; - i = 0; - while (tmpstr.indexOf("\n") >= 0) - { - fvalues[i] = tmpstr.substring(0, tmpstr.indexOf("\n")); - if (fvalues[i].indexOf("\r") >= 0) fvalues[i] = fvalues[i].substring(0, fvalues[i].indexOf("\r")); - ++i; - tmpstr = tmpstr.substring(tmpstr.indexOf("\n") + 1); - } - if (!(tmpstr.trim().equals(""))) - fvalues[i] = tmpstr; - return fvalues; - } - - public static String getrealAreaValues(String fvalue) - { - String tmpstr = fvalue; - String returnstr = ""; - if (tmpstr == null) return null; - if (tmpstr.trim().equals("")) return ""; - while (tmpstr.indexOf("|") > 0) - { - returnstr = returnstr + tmpstr.substring(0, tmpstr.indexOf("|")) + "\n"; - tmpstr = tmpstr.substring(tmpstr.indexOf("|") + 1); - } - return returnstr; - } - - public static int CountChar(String strInput, char chr) - { - int iCount = 0; - char chrTmp = ' '; - - if (strInput.trim().length() == 0) { - return 0; - } - for (int i = 0; i < strInput.length(); ++i) { - chrTmp = strInput.charAt(i); - if (chrTmp == chr) { - ++iCount; - } - } - return iCount; - } - - public static String StrArrayToStr(String[] strs) - { - StringBuffer returnstr = new StringBuffer(""); - if (strs == null) return ""; - for (int i = 0; i < strs.length; ++i) { - returnstr.append(strs[i]); - } - return returnstr.toString(); - } - - public static void printStrs(String[] strs) - { - for (int i = 0; i < strs.length; ++i) - System.out.println(strs[i]); - } - - public static void printDualStr(String[][] dualStr) - { - for (int i = 0; i < dualStr.length; ++i) { - for (int j = 0; j < dualStr[i].length; ++j) { - System.out.print(dualStr[i][j] + " "); - } - System.out.println(); - } - } - - public static String[][] rowToColumn(String[][] dualStr) - { - String[][] returnDualStr = (String[][])null; - if (dualStr != null) { - returnDualStr = new String[dualStr[0].length][dualStr.length]; - for (int i = 0; i < dualStr.length; ++i) - for (int j = 0; j < dualStr[0].length; ++j) - returnDualStr[j][i] = dualStr[i][j]; - } - return returnDualStr; - } - - public static String latinString(String inStr) - { - String res = inStr; - if (null == res) return null; - res = replaceStrAll(res, "\"", "\\\""); - res = replaceStrAll(res, "'", "\\'"); - return res; - } - - /** - * 替换空格 - * @param strTarget - * @param strNew - * @return - */ - public static String replaceWhiteSpace(String strTarget, String strNew) - { - if(strTarget==null) - { - return ""; - } - int iIndex = -1; - while (true) { - char cRep = ' '; - iIndex = strTarget.indexOf(cRep); - if (iIndex < 0) { - break; - } - String strTemp = null; - strTemp = strTarget.substring(0, iIndex); - - strTarget = strTemp + strNew + strTarget.substring(iIndex + 1); - } - return strTarget; - } - - public static String double2str(double amount, int length) - { - String strAmt = Double.toString(amount); - - int pos = strAmt.indexOf(46); - - if ((pos != -1) && (strAmt.length() > length + pos + 1)) { - strAmt = strAmt.substring(0, pos + length + 1); - } - return strAmt; - } - - public static String[] doSplit(String str, char chr) - { - int iCount = 0; - char chrTmp = ' '; - - for (int i = 0; i < str.length(); ++i) { - chrTmp = str.charAt(i); - if (chrTmp == chr) { - ++iCount; - } - } - String[] strArray = new String[iCount]; - for (int i = 0; i < iCount; ++i) { - int iPos = str.indexOf(chr); - if (iPos == 0) { - strArray[i] = ""; - } - else { - strArray[i] = str.substring(0, iPos); - } - str = str.substring(iPos + 1); - } - return strArray; - } - - public static String strIntercept(String src, int len) - { - if (src == null) { - return ""; - } - if (src.length() > len) { - src = String.valueOf(String.valueOf(src.substring(0, len))).concat("..."); - } - - return src; - } - - public static String strtochn(String str_in) - { - try - { - String temp_p = str_in; - if (temp_p == null) { - temp_p = ""; - } - String temp = ""; - if (!(temp_p.equals(""))) { - byte[] byte1 = temp_p.getBytes("ISO8859_1"); - temp = new String(byte1); - } - return temp; - } - catch (Exception e) { - } - return "null"; - } - - public static String ISO2GBK(String strvalue) - { - try - { - if (strvalue == null) { - return null; - } - strvalue = new String(strvalue.getBytes("ISO8859_1"), "GBK"); - return strvalue; - } - catch (Exception e) { - } - return null; - } - - public String GBK2ISO(String strvalue) - throws Exception - { - try - { - if (strvalue == null) { - return null; - } - strvalue = new String(strvalue.getBytes("GBK"), "ISO8859_1"); - return strvalue; - } - catch (Exception e) { - } - return null; - } - - public static String cnCodeTrans(String str) - { - String s = ""; - try { - s = new String(str.getBytes("GB2312"), "8859_1"); - } - catch (UnsupportedEncodingException a) { - System.out.print("chinese thansform exception"); - } - return s; - } - - public static String chiEnUTF8(String str) - { - String s = ""; - try { - s = new String(URLEncoder.encode(str, "UTF-8")); - } - catch (UnsupportedEncodingException a) { - System.out.print("chinese thansform exception"); - } - return s; - } - - public static String chiDeUTF8(String str) - { - String s = ""; - try { - s = new String(URLDecoder.decode(str, "UTF-8")); - - byte[] bytes = s.getBytes("ISO-8859-1"); - s = new String(bytes, "UTF-8"); - } - catch (UnsupportedEncodingException a) { - System.out.print("chinese thansform exception"); - } - return s; - } - - public static boolean judgeMatch(String strSource, String strRule) - { - int i = 0; - - if ((null == strSource) || (strSource.length() == 0)) { - return false; - } - if ((null == strRule) || (strRule.length() == 0)) { - return false; - } - if (strSource.length() > strRule.length()) { - return false; - } - for (i = 0; i < strRule.length(); ++i) - { - if (strSource.length() < i + 1) { - break; - } - if ((strRule.charAt(i) != '*') && (strSource.charAt(i) != strRule.charAt(i))) - { - return false; - } - } - - for (; i < strRule.length(); ++i) { - if (strRule.charAt(i) != '*') - return false; - } - return true; - } - - public static String getFullChnStr(String strSource) - { - if ((null == strSource) || (strSource.length() == 0)) { - return ""; - } - if (strSource.length() == 1) - { - if (strSource.charAt(0) > '') - { - return ""; - } - return strSource; - } - if ((strSource.charAt(strSource.length() - 2) <= '') && (strSource.charAt(strSource.length() - 1) > '')) { - return strSource.substring(0, strSource.length() - 1); - } - - boolean prechn = false; - String returnstr = ""; - for (int i = 0; i < strSource.length(); ++i) - { - if (strSource.charAt(i) <= '') - { - if (prechn) - { - returnstr = returnstr.substring(0, returnstr.length() - 1); - } - - returnstr = returnstr + strSource.charAt(i); - prechn = false; - } - else { - returnstr = returnstr + strSource.charAt(i); - if (prechn) - { - prechn = false; - } - else prechn = true; - } - } - - if (prechn) - { - returnstr = returnstr.substring(0, returnstr.length() - 1); - } - return returnstr; - } - - public static String filerQuery(String qryStr) - { - int comma = 0; - int len = 0; - String Str = ""; - - comma = qryStr.indexOf("'"); - len = qryStr.length(); - - if (qryStr == "") { - Str = ""; - } - else if (comma > 0) - Str = qryStr.substring(0, comma) + "''" + qryStr.substring(comma + 1, len); - else if (comma == 0) - Str = "''"; - else if (comma < 0) { - Str = qryStr; - } - - return Str; - } - - public static String appendStr(String str) - { - int strlength = 0; - int adddot = 0; - int tmpstrlength = 0; - int callength = 0; - int plusdot = 0; - String firststr = ""; - String endstr = ""; - String returnStr = ""; - String tmpfirststr = ""; - String tmpendstr = ""; - boolean isNegative = false; - - if (str.startsWith("-")) { - isNegative = true; - } - tmpstrlength = str.indexOf("."); - if (isNegative) - firststr = str.substring(1, tmpstrlength); - else { - firststr = str.substring(0, tmpstrlength); - } - - endstr = str.substring(tmpstrlength); - strlength = firststr.length(); - adddot = strlength / 3; - plusdot = strlength % 3; - if (plusdot == 0) - { - adddot -= 1; - } - for (int i = 0; i < adddot; ++i) - { - callength = firststr.length(); - tmpfirststr = firststr.substring(0, callength - (4 * i + 3)); - tmpendstr = firststr.substring(callength - (4 * i + 3)); - firststr = tmpfirststr + "," + tmpendstr; - } - - if (isNegative) - returnStr = "-" + firststr + endstr; - else { - returnStr = firststr + endstr; - } - return returnStr; - } - - public static boolean CompareString(String str1, String str2) - { - if (str1.equals(str2)) - { - return true; - } - if ((str1.endsWith("\r\n")) && (str1.length() > 2)) - { - str1 = str1.substring(0, str1.length() - 2); - } - if ((str2.endsWith("\r\n")) && (str2.length() > 2)) - { - str2 = str2.substring(0, str2.length() - 2); - } - - return (str1.equals(str2)); - } - - public static String SepFormatStr(String SourceStr, int maxlength, String separator) - { - if (SourceStr == null) return null; - SourceStr = SourceStr.replaceAll("\r", ""); - SourceStr = SourceStr.replaceAll("\n", ""); - SourceStr = SourceStr.replaceAll(separator, ""); - - boolean cnflag = false; - - boolean end = false; - - StringBuffer resultsb = new StringBuffer(); - - StringBuffer tempsb = new StringBuffer(); - - String tempstr = ""; - for (int i = 0; i < SourceStr.length(); ++i) - { - char Cindex = SourceStr.charAt(i); - - if (Cindex > '') - { - if (cnflag) - { - if (tempsb.length() >= maxlength - 1) - { - if (resultsb.length() > 0) - { - resultsb.append(separator); - } - resultsb.append(tempsb); - tempsb.delete(0, tempsb.length()); - } - - tempstr = SourceStr.substring(i - 1, i + 1); - - tempsb.append(tempstr); - cnflag = false; - } else { - cnflag = true; - } - } - else { - if (cnflag) - { - cnflag = false; - } - - tempsb.append(Cindex); - } - - if (i == SourceStr.length() - 1) end = true; - - if ((tempsb.length() <= 0) || ((tempsb.length() < maxlength) && (!(end)))) { - continue; - } - if (resultsb.length() > 0) - { - resultsb.append(separator); - } - resultsb.append(tempsb); - tempsb.delete(0, tempsb.length()); - end = false; - } - - return resultsb.toString(); - } - - public static String exchangeName(String strTmp) - { - String ori = strTmp.trim(); - if (ori != null) - { - if ((ori.length() == 4) || (ori.length() == 6)) - { - if (ori.length() == 4) - { - ori = ori.substring(2, 4) + ori.substring(0, 2); - } - else - { - ori = ori.substring(2, 6) + ori.substring(0, 2); - } - - } - else - { - return ori; - } - } - return ori; - } - - public static String isExistAcc(String strIn) - { - strIn = strIn.replaceAll("\r\n", "\n"); - strIn = strIn.replaceAll("\n", ""); - - String strAccRet = ""; - int iCount = 0; - if ((strIn != null) && (strIn.length() > 0)) - { - StringBuffer buff = new StringBuffer(strIn); - int len = buff.length(); - for (int i = 0; i < len; ++i) - { - char ch = buff.charAt(i); - if ((ch >= '0') && (ch <= '9')) - { - ++iCount; - strAccRet = strAccRet + String.valueOf(ch); - } - else - { - if (iCount > 15) - break; - iCount = 0; - strAccRet = ""; - } - } - } - - if (iCount > 15) { - return strAccRet; - } - return ""; - } - - public static boolean judgeAllNumberic(String strIn) - { - strIn = strIn.replaceAll("\r\n", "\n"); - strIn = strIn.replaceAll("\n", ""); - strIn = strIn.replaceAll(" ", ""); - - if ((strIn != null) && (strIn.length() > 0)) - { - StringBuffer buff = new StringBuffer(strIn); - int len = buff.length(); - for (int i = 0; i < len; ++i) - { - char ch = buff.charAt(i); - if ((ch < '0') || (ch > '9')) - { - return false; - } - } - } - else { - return false; } - return true; - } - - public static boolean judgeAllChn(String strIn) - { - strIn = strIn.replaceAll("\r\n", "\n"); - strIn = strIn.replaceAll("\n", ""); - strIn = strIn.replaceAll(" ", ""); - - if ((strIn != null) && (strIn.length() > 0)) - { - StringBuffer buff = new StringBuffer(strIn); - int len = buff.length(); - for (int i = 0; i < len; ++i) - { - char ch = buff.charAt(i); - if (ch <= 0) continue; if (ch < '~') - { - return false; } - } - return true; - } - - return false; - } - - public static boolean judgeChnCode(String strIn) - { - strIn = strIn.replaceAll("\r\n", "\n"); - strIn = strIn.replaceAll("\n", ""); - strIn = strIn.replaceAll(" ", ""); - - if ((strIn != null) && (strIn.length() > 0)) - { - StringBuffer buff = new StringBuffer(strIn); - int len = buff.length(); - for (int i = 0; i < len; ++i) - { - char ch = buff.charAt(i); - if (((ch >= '0') && (ch <= '9')) || (ch <= 0)) continue; if (ch < '~') - { - return false; - } - } - } - else { - return false; } - return true; - } - - public static boolean judgeExistChn(String strIn) - { - if (judgeChnCode(strIn)) - { - return true; - } - - strIn = strIn.replaceAll("\r\n", "\n"); - strIn = strIn.replaceAll("\n", ""); - strIn = strIn.replaceAll(" ", ""); - - if ((strIn != null) && (strIn.length() > 0)) - { - StringBuffer buff = new StringBuffer(strIn); - int len = buff.length(); - for (int i = 0; i < len; ++i) - { - char ch = buff.charAt(i); - if ((ch <= 0) || (ch >= '~')) - { - return true; - } - - } - - return false; - } - - return false; - } - - public static boolean judgeExistNumber(String strIn) - { - if (judgeChnCode(strIn)) - { - return true; - } - - strIn = strIn.replaceAll("\r\n", "\n"); - strIn = strIn.replaceAll("\n", ""); - strIn = strIn.replaceAll(" ", ""); - - if ((strIn != null) && (strIn.length() > 0)) - { - StringBuffer buff = new StringBuffer(strIn); - int len = buff.length(); - for (int i = 0; i < len; ++i) - { - char ch = buff.charAt(i); - if ((ch >= '0') && (ch <= '9')) - { - return true; - } - - } - - return false; - } - - return false; - } - - public static boolean chkString(String existStr, String value) - { - Pattern pattern = Pattern.compile(existStr); - Matcher matcher = pattern.matcher(value); - boolean didMatch = matcher.matches(); - return didMatch; - } - - public static boolean isExist_Str(String regexp, String mathStr) - { - boolean result = false; - Pattern pattern = Pattern.compile(regexp); - Matcher matcher = pattern.matcher(mathStr); - result = matcher.find(); - return result; - } - - public static String getSeqNumber(String numStr) - { - numStr = numStr.replaceAll("\r\n", "\n"); - numStr = numStr.replaceAll("\n", ""); - - String seqNumRet = ""; - int iCount = 0; - if ((numStr != null) && (numStr.length() > 0)) - { - StringBuffer buff = new StringBuffer(numStr); - int len = buff.length(); - for (int i = 0; i < len; ++i) - { - char ch = buff.charAt(i); - if ((ch >= '0') && (ch <= '9')) - { - ++iCount; - seqNumRet = seqNumRet + String.valueOf(ch); - } - else - { - if (iCount > 10) { if (ch < '0') break; if (ch > '9') break; - } - iCount = 0; - seqNumRet = ""; - } - } - - } - - return seqNumRet; - } - - public static double round(double v, int scale) - { - if (scale < 0) { - throw new IllegalArgumentException("参数scale必须是大于0的整数"); - } - - BigDecimal b = new BigDecimal(Double.toString(v)); - BigDecimal one = new BigDecimal("1"); - return b.divide(one, scale, 4).doubleValue(); - } - - public static String rfillCharater(String str, char ch, int len) - { - StringBuffer fillStr = new StringBuffer(str); - int fillLen = len - fillStr.length(); - - for (int i = 0; i < fillLen; ++i) { - fillStr.append(ch); - } - - return fillStr.toString(); - } - - public static String lfillCharater(String str, char ch, int len) - { - StringBuffer fillStr = new StringBuffer(); - int fillLen = len - str.length(); - - for (int i = 0; i < fillLen; ++i) { - fillStr.append(ch); - } - fillStr.append(str); - - return fillStr.toString(); - } - - public static boolean propRule(String regexPattern, String value) - { - Pattern pattern = Pattern.compile(regexPattern); - Matcher matcher = pattern.matcher(value); - boolean didMatch = matcher.matches(); - return didMatch; - } - - public static boolean isExistStr(String str, String[] strarray) - { - if ((strarray == null) || (strarray.length <= 0)) return false; - for (int i = 0; i < strarray.length; ++i) - { - if (strarray[i] == null) - { - if (str == null) return true; - - } - else if (str.indexOf(strarray[i].trim()) != -1) - { - return true; - } - } - return false; - } - - public static String codeToLines(String str) - { - String strTemp = ""; - if (str == null) { - return strTemp; - } - while (str.length() > 19) { - strTemp = strTemp + "\n" + str.substring(0, 19); - if (' ' == str.charAt(19)) { - str = str.substring(20); - } - str = str.substring(19); - } - - strTemp = strTemp + "\n" + str; - strTemp = strTemp.substring(1); - return strTemp; - } - - public static String nameToLines(String str) - { - String strTemp = ""; - if (str == null) { - return strTemp; - } - while (str.length() > 8) { - strTemp = strTemp + "
" + str.substring(0, 8); - str = str.substring(8); - } - strTemp = strTemp + "
" + str; - strTemp = strTemp.substring(4); - return strTemp; - } - - public static String lowerToUppser(String str) { - str = str.trim(); - String strTemp = ""; - - if ((str == null) || (str.trim().length() == 0)) { - return strTemp; - } - for (int i = 0; i < str.length(); ++i) { - char a = str.charAt(i); - if ((a >= 'a') && (a <= 'z')) { - a = (char)(a - ' '); - } - strTemp = strTemp + a; - } - return strTemp; - } - - public static String getDomain(String str) - { - String strTemp = ""; - if (str == null) { - return strTemp; - } - int i = str.indexOf("http://"); - if (i >= 0) - { - strTemp = str.substring(i + 7); - } - i = str.indexOf("www."); - if (i >= 0) - { - strTemp = strTemp.substring(i + 4); - } - i = str.indexOf(47); - if (i >= 0) - { - strTemp = strTemp.substring(0, i); - } - return strTemp; - } - - public static boolean isExist(String str) - { - return ((str != null) && (str.length() > 0)); - } - - public static boolean isNumber(String str) - { - return str.matches("^\\d+(\\,\\d+)*$"); - } - - public static boolean isValidDate(String dateStr) - { - boolean isValid = false; - if ((dateStr == null) || (dateStr.length() <= 0)) { - return false; - } - String pattern = "yyyy-MM-dd"; - try { - SimpleDateFormat sdf = new SimpleDateFormat(pattern); - String date = sdf.format(sdf.parse(dateStr)); - if (date.equalsIgnoreCase(dateStr)) - isValid = true; - } - catch (Exception e) { - isValid = false; - } - return isValid; } - - public static String joinStr(String[] array, String joinChar) { - if (array == null) - return ""; - if (joinChar == null) joinChar = ","; - String str = ""; - for (int i = 0; i < array.length; ++i) { - str = str + array[i]; - if (i >= array.length - 1) continue; str = str + joinChar; - } - return str; - } - - /** - * 对日期进行格式化 - * @param d - * @param f - * @return - */ - public static String formatDate(Date d,String f) - { - SimpleDateFormat sdf = new SimpleDateFormat(f); - return sdf.format(d); - } - - /** - * md5加密 - * @param password - * @return - */ - public static String makeMD5(String password) { - MessageDigest md; - try { - // 生成一个MD5加密计算摘要 - md = MessageDigest.getInstance("MD5"); - // 计算md5函数 - md.update(password.getBytes()); - // digest()最后确定返回md5 hash值,返回值为8为字符串。因为md5 hash值是16位的hex值,实际上就是8位的字符 - // BigInteger函数则将8位的字符串转换成16位hex值,用字符串来表示;得到字符串形式的hash值 - String pwd = new BigInteger(1, md.digest()).toString(16); - return pwd; - } catch (Exception e) { - e.printStackTrace(); - } - return password; - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/resources/applicationContext-dubbo.xml b/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/resources/applicationContext-dubbo.xml deleted file mode 100644 index a02ed2cb90..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/resources/applicationContext-dubbo.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - Dubbo provider配置 - - - - - - - - - - - - - - - - - - diff --git a/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/resources/applicationContext.xml b/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/resources/applicationContext.xml deleted file mode 100644 index 0a38ff4ebd..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/resources/applicationContext.xml +++ /dev/null @@ -1,82 +0,0 @@ - - - - Spring公共配置 - - - - - - - - - - - - - - - - - - - - - - - - - classpath*:/config.properties - - file:/d:/conf/cl/search-api-server/*.properties - - file:/etc/conf/cl/search-api-server/*.properties - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/resources/config.properties b/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/resources/config.properties deleted file mode 100644 index e773313ef2..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/resources/config.properties +++ /dev/null @@ -1,6 +0,0 @@ -#ZooKeeper -dubbo.registry.address=127.0.0.1:2181 -dubbo.registry.address.client=127.0.0.1:2181 - -#Solr -solrUrl = http://127.0.0.1:8080/solr/c \ No newline at end of file diff --git a/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/resources/log4j.dtd b/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/resources/log4j.dtd deleted file mode 100644 index f8e433a50e..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/resources/log4j.dtd +++ /dev/null @@ -1,237 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/resources/log4j.xml b/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/resources/log4j.xml deleted file mode 100644 index 5033ff2159..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_api_server/src/main/resources/log4j.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/jun_java_plugins/jun_solr/jun_solr_api_server/src/test/java/com/jun/plugin/solr/api/impl/test/SearchBaseApiServiceImplTest.java b/jun_java_plugins/jun_solr/jun_solr_api_server/src/test/java/com/jun/plugin/solr/api/impl/test/SearchBaseApiServiceImplTest.java deleted file mode 100644 index 8f0a79bf5a..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_api_server/src/test/java/com/jun/plugin/solr/api/impl/test/SearchBaseApiServiceImplTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.jun.plugin.solr.api.impl.test; - -import java.util.List; - -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -import com.jun.plugin.solr.api.impl.SearchBaseApiServiceImpl; -import com.jun.plugin.solr.model.Commodity; -import com.jun.plugin.solr.model.FacetItem; -import com.jun.plugin.solr.model.SearchModel; -import com.jun.plugin.solr.model.SearchResult; - -public class SearchBaseApiServiceImplTest { - - private static SearchBaseApiServiceImpl service; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-test.xml"); - service = (SearchBaseApiServiceImpl)ctx.getBean("searchBaseApiServiceImpl"); - ctx.close(); - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void getWebSearchResult() { - SearchModel searchModel = new SearchModel(); - //searchModel.setKeyword("*"); - //searchModel.setPageNo(1); - SearchResult sr = service.getWebSearchResult(searchModel); - if(sr !=null) - { - List commodityList = sr.getCommodityList(); - for(Commodity c : commodityList) - { - System.out.println(c.getNo() + "\t" + c.getName()); - } - List facetItemList = sr.getFacetItemList(); - for(FacetItem fi : facetItemList) - { - System.out.println(fi.getId() + "\t" + fi.getValueCount()); - } - } else { - System.out.println("null"); - } - } - -} diff --git a/jun_java_plugins/jun_solr/jun_solr_api_server/src/test/resources/applicationContext-test.xml b/jun_java_plugins/jun_solr/jun_solr_api_server/src/test/resources/applicationContext-test.xml deleted file mode 100644 index b4b49638ae..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_api_server/src/test/resources/applicationContext-test.xml +++ /dev/null @@ -1,75 +0,0 @@ - - - - Spring公共配置 - - - - - - - - - - - - - - - - - - - - - - - - - classpath*:/config.properties - - file:/d:/conf/cl/search-api-server/*.properties - - file:/etc/conf/cl/search-api-server/*.properties - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/jun_java_plugins/jun_solr/jun_solr_api_server/src/test/resources/config.properties b/jun_java_plugins/jun_solr/jun_solr_api_server/src/test/resources/config.properties deleted file mode 100644 index e773313ef2..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_api_server/src/test/resources/config.properties +++ /dev/null @@ -1,6 +0,0 @@ -#ZooKeeper -dubbo.registry.address=127.0.0.1:2181 -dubbo.registry.address.client=127.0.0.1:2181 - -#Solr -solrUrl = http://127.0.0.1:8080/solr/c \ No newline at end of file diff --git a/jun_java_plugins/jun_solr/jun_solr_index/pom.xml b/jun_java_plugins/jun_solr/jun_solr_index/pom.xml deleted file mode 100644 index 35f65632d5..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_index/pom.xml +++ /dev/null @@ -1,63 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_solr_index - 1.0 - jar - - - UTF-8 - - - - - org.apache.solr - solr-core - 4.3.1 - - - commons-io - commons-io - - - - - com.belerweb - pinyin4j - 2.5.1 - - - mysql - mysql-connector-java - 5.1.24 - - - - commons-logging - commons-logging - 1.2 - - - log4j - log4j - 1.2.16 - - - org.slf4j - slf4j-api - 1.6.1 - - - org.slf4j - slf4j-log4j12 - 1.6.1 - - - com.twelvemonkeys.common - common-io - 3.4.1 - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_solr/jun_solr_index/src/main/java/com/jun/plugin/solr/CreateIndex.java b/jun_java_plugins/jun_solr/jun_solr_index/src/main/java/com/jun/plugin/solr/CreateIndex.java deleted file mode 100644 index 65f2773270..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_index/src/main/java/com/jun/plugin/solr/CreateIndex.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.jun.plugin.solr; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map.Entry; - -import org.apache.solr.client.solrj.SolrServerException; -import org.apache.solr.client.solrj.impl.HttpSolrServer; -import org.apache.solr.common.SolrInputDocument; - -import com.jun.plugin.solr.db.CommodityDao; -import com.jun.plugin.solr.util.CommonUtil; -import com.jun.plugin.solr.util.SolrUtil; - -public class CreateIndex { - - private CommodityDao commodityDao = new CommodityDao(); - - private void run() - { - long begin = System.currentTimeMillis(); - - HttpSolrServer solrConn = SolrUtil.getSolrHttpConnect(); - - HashMap> commodityMap = commodityDao.getCommodityList(); - - List docList = new ArrayList(); - SolrInputDocument doc = null; - int docNum = 0, commitNum=0; - - for(Entry> commodityEntry : commodityMap.entrySet()) { - docNum++; - doc = new SolrInputDocument(); - HashMap commodity = commodityEntry.getValue(); - - doc.addField("no", commodity.get("no")); - doc.addField("brand_id", commodity.get("brand_id")); - doc.addField("name", commodity.get("name")); - doc.addField("style_no", commodity.get("style_no")); - doc.addField("sale_price", commodity.get("sale_price")); - - docList.add(doc); - - //10000个提交一次 - if(docNum%10000==0){ - commitNum++; - if(commitNum==1){ - try { - solrConn.deleteByQuery("*:*"); - } catch (Exception e) { - e.printStackTrace(); - } - } - try { - solrConn.add(docList); - solrConn.commit(); - } catch (Exception e) { - e.printStackTrace(); - } - docList.clear(); - System.out.println(CommonUtil.getCurrentDatetime() + ",Commit :\t"+commitNum); - } - } - - if(docList.size()>0){ - commitNum++; - if(commitNum==1){ - try { - solrConn.deleteByQuery("*:*"); - } catch (Exception e) { - e.printStackTrace(); - } - } - try { - solrConn.add(docList); - solrConn.commit(); - solrConn.optimize(); - } catch (Exception e) { - e.printStackTrace(); - } - System.out.println(CommonUtil.getCurrentDatetime() + ",last commit :\t"+commitNum); - }else{ - try { - solrConn.optimize(); - } catch (SolrServerException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - long end = System.currentTimeMillis(); - System.out.println("索引完毕,共耗时: "+((double)(end-begin)/(1000))+"秒。"); - } - - - public static void main(String[] args) - { - CreateIndex ci = new CreateIndex(); - ci.run(); - } -} diff --git a/jun_java_plugins/jun_solr/jun_solr_index/src/main/java/com/jun/plugin/solr/db/CommodityDao.java b/jun_java_plugins/jun_solr/jun_solr_index/src/main/java/com/jun/plugin/solr/db/CommodityDao.java deleted file mode 100644 index 78ca072ef4..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_index/src/main/java/com/jun/plugin/solr/db/CommodityDao.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.jun.plugin.solr.db; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.HashMap; - -import com.jun.plugin.solr.util.DbUtil; - - - -public class CommodityDao { - - private DbUtil dbUtil = DbUtil.getInstance(); - private String commodityPoolName = "commodity"; - protected Connection conn; - - public HashMap> getCommodityList() - { - HashMap> commodityMap = new HashMap>(); - String strSql = "select * from c_commodity"; - String no = null; - PreparedStatement ps = null; - ResultSet rs = null; - HashMap commodity = null; - try{ - conn = dbUtil.getConnection(commodityPoolName); - ps = conn.prepareStatement(strSql); - rs = ps.executeQuery(); - - while(rs.next()){ - no = rs.getString("no"); - commodity = new HashMap(); - commodity.put("no", rs.getString("no")); - commodity.put("brand_id", Integer.toString(rs.getInt("brand_id"))); - commodity.put("name", rs.getString("name")); - commodity.put("style_no", rs.getString("style_no")); - commodity.put("sale_price", Integer.toString(rs.getInt("sale_price"))); - commodityMap.put(no, commodity); - } - } catch (SQLException e) { - e.printStackTrace(); - } - this.closeConnection(rs, ps, conn); - - return commodityMap; - } - - private void closeConnection(ResultSet rs,PreparedStatement ps,Connection conn) - { - try { - if (rs != null) { - rs.close(); - rs = null; - } - if (ps != null) { - ps.close(); - ps = null; - } - dbUtil.freeConnection(commodityPoolName, conn); - } catch (SQLException e) { - e.printStackTrace(); - } - } -} diff --git a/jun_java_plugins/jun_solr/jun_solr_index/src/main/java/com/jun/plugin/solr/util/CommonUtil.java b/jun_java_plugins/jun_solr/jun_solr_index/src/main/java/com/jun/plugin/solr/util/CommonUtil.java deleted file mode 100644 index fa0ea62942..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_index/src/main/java/com/jun/plugin/solr/util/CommonUtil.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.jun.plugin.solr.util; - -import java.text.SimpleDateFormat; -import java.util.Date; - -public class CommonUtil { - - public static String getCurrentDatetime() - { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - return sdf.format(new Date()); - } -} diff --git a/jun_java_plugins/jun_solr/jun_solr_index/src/main/java/com/jun/plugin/solr/util/DbUtil.java b/jun_java_plugins/jun_solr/jun_solr_index/src/main/java/com/jun/plugin/solr/util/DbUtil.java deleted file mode 100644 index 04a504de05..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_index/src/main/java/com/jun/plugin/solr/util/DbUtil.java +++ /dev/null @@ -1,329 +0,0 @@ -package com.jun.plugin.solr.util; - -import java.sql.Connection; -import java.sql.Driver; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Properties; -import java.util.StringTokenizer; -import java.util.Vector; - - -/** - * 数据库连接池 - * 这个类实现的是对多个数据源的连接池,用Vector存储 - * 在Spring引入之前,这是最常用的数据库连接池实现办法 - */ -public class DbUtil { - - private static DbUtil instance; // 唯一实例 - private static int clients; // 连接的客户端 - private Vector drivers = new Vector();// 驱动集合 - private Hashtable pools = new Hashtable();// 数据库连接池 - private Properties dbProps; - - /** - * 单例模式 - */ - private DbUtil() { - this.init(); - } - - /** - * 采用单例模式,返回唯一实例,第一次调用时创建 - * - * @return DBConnectionManager 唯一实例 - */ - public static synchronized DbUtil getInstance() { - if (instance == null) { - instance = new DbUtil(); - } - clients++; - return instance; - } - - public int getClientNum(){ - return clients; - } - - /** - * 获得可用的空闲连接.如果没有可用连接,且已有连接数小于最大连接数限制,则创建并返回新连接 - * - * @param name: 在属性文件中定义的连接池名字 - * @return Connection 可用连接或null - */ - public Connection getConnection(String name) { - DBPool dbPool = pools.get(name); - if (dbPool != null) { - return dbPool.getConnection(); - } - return null; - } - - /** - * 获得可用连接.若没有可用连接,且已有连接数小于最大连接数限制, 则创建并返回新连接. 否则,在指定的时间内等待其它线程释放连接. - * - * @param name: 连接池名? - * @param time: 以毫秒计的等待时间 - * @return Connection 可用连接或null - */ - public Connection getConnection(String name, long time) { - DBPool dbPool = pools.get(name); - if (dbPool != null) { - return dbPool.getConnection(time); - } - return null; - } - - /** - * 将连接对象返回给由名字指定的连接池 - * - * @param name: 在属性文件中定义的连接池名字 - * @param con: 连接对象 - */ - public void freeConnection(String name, Connection con) { - DBPool dbPool = pools.get(name); - if (dbPool != null) { - dbPool.freeConnection(con); - } - } - - /** - * 关闭所有连接,撤销驱动程序的注册 - */ - public synchronized void release() { - // 等待直到最后一个客户程序调用结束 - if (--clients != 0) { - return; - } - Enumeration allPools = pools.elements(); - DBPool pool = null; - while (allPools.hasMoreElements()) { - pool = allPools.nextElement(); - pool.release(); - } - Enumeration allDrivers = drivers.elements(); - while (allDrivers.hasMoreElements()) { - Driver driver = allDrivers.nextElement(); - try { - DriverManager.deregisterDriver(driver); - System.out.println("撤销JDBC驱动程序 " + driver.getClass().getName() + "的注册"); - } catch (SQLException e) { - System.out.println("无法撤销下列JDBC驱动程序的注册: " + driver.getClass().getName()); - } - } - } - - /** - * 读取属性完成初始化 - */ - private void init() { - dbProps = PropertyFile.getProps(); - // 加载驱动 - loadDrivers(dbProps); - // 创建数据连接池 - createPools(dbProps); - } - - /** - * 装载和注册所有JDBC驱动程序 - * - * @param props 属性 - */ - private void loadDrivers(Properties props) { - String driverClasses = props.getProperty("drivers"); - StringTokenizer st = new StringTokenizer(driverClasses); - while (st.hasMoreElements()) { - String driverClassName = st.nextToken().trim(); - try { - Driver driver = (Driver)Class.forName(driverClassName).newInstance(); - DriverManager.registerDriver(driver); - drivers.addElement(driver); - System.out.println("成功注册JDBC驱动程序: " + driverClassName); - } catch (Exception e) { - System.out.println("无法注册JDBC驱动程序: " + driverClassName + ", 错误: " + e); - } - } - } - - /** - * 根据指定属性创建连接池实例 - * - * @param props: 连接池属性 - */ - private void createPools(Properties props) { - Enumeration propNames = props.propertyNames(); - String name = null, url=null,user=null,password=null, maxconn=null; - String poolName = null; - while (propNames.hasMoreElements()) { - name = (String) propNames.nextElement(); - if (name.endsWith(".url")) { - poolName = name.substring(0, name.lastIndexOf(".")); - System.out.println("数据库连接池: " + poolName + " 启动"); - url = props.getProperty(poolName + ".url"); - if (url == null) { - System.out.println("没有为连接池" + poolName + "指定数据库访问地址"); - continue; - } - user = props.getProperty(poolName + ".user"); - password = props.getProperty(poolName + ".password"); - maxconn = props.getProperty(poolName + ".maxconn", "100"); - int max=0; - try { - max = Integer.valueOf(maxconn).intValue(); - } catch (NumberFormatException e) { - System.err.println(e.getMessage()); - System.out.println("错误的最大连接数限制: " + maxconn + " .连接池名: " + poolName); - max = 0; - } - DBPool pool = new DBPool(poolName, url, user, password, max); - pools.put(poolName, pool); - System.out.println("数据库连接池: " + poolName + " 创建完毕!"); - } - } - } - - - /** - * - * 数据库连接池内部类, 此内部类定义了一个连接池.它能够根据要求创建新连接,直到预定的最大连接数为止. - * 在返回连接给客户程序之前,它能够验证连接的有效性 - * - */ - class DBPool { - - private String poolName; // 连接池名称 - private String dbConnUrl; // 数据库的JDBC URL - private String dbUserName; // 数据库账号或null - private String dbPassWord; // 数据库账号密码或null - private int maxConn; // 此连接池允许建立的最大连接数 - private int checkedOut; // 当前连接数 - private Vector freeConnections; // 保存的可用链接 - - public DBPool(){} - /** - * 创建新的连接池构造函数 - * - * @param poolName: 连接池名称 - * @param dbConnUrl: 数据库的JDBC URL - * @param dbUserName: 数据库用户名 - * @param dbPassWord: 数据库密码 - * @param maxConn: 此连接池允许建立的最大连接数 - */ - public DBPool(String poolName, String dbConnUrl, String dbUserName, String dbPassWord, int maxConn) { - this.poolName = poolName; - this.dbConnUrl = dbConnUrl; - this.dbUserName = dbUserName; - this.dbPassWord = dbPassWord; - this.maxConn = maxConn; - this.freeConnections = new Vector(); - } - - /** - * 从连接池获得可用连接,如果没有空闲的连接且当前连接数小于最大连接数限制,则创建新连接. - * 如原来登记为可用的连接不再有用,则从向量删除,然后递归调用自己以尝试新的可用连接. - */ - @SuppressWarnings("resource") - public synchronized Connection getConnection() { - Connection conn = null;// 定义连接标量 - - if (freeConnections.size()>0) { - // 获取向量中第个可用连接 - conn = freeConnections.firstElement(); - freeConnections.removeElementAt(0); - try { - if (conn.isClosed()) { - // 递归调用自己,尝试再次获取可用连接 - conn = getConnection(); - } - } catch (SQLException e) { - // 递归调用自己,尝试再次获取可用连接 - conn = getConnection(); - } - } - else if (maxConn == 0 || checkedOut < maxConn) { - conn = newConnection(); - } - if (conn != null) { - checkedOut++; - } - return conn; - } - - /** - * 从连接池获取可用连接.可以指定客户程序能够等待的最长时间 - * - * @param timeout: 以毫秒计的等待时间限制 - */ - public synchronized Connection getConnection(long timeout) { - long startTime = System.currentTimeMillis(); - Connection conn = null;// 定义连接标量 - while ((conn = getConnection()) == null) { - try { - wait(timeout); - } catch (InterruptedException e) { - e.printStackTrace(); - } - if ((System.currentTimeMillis() - startTime) >= timeout) { - // wait()返回的原因是超时 - return null; - } - } - return conn; - } - - /** - * 创建新的连接 - * - * @return 返回数据库链接 - */ - private Connection newConnection() { - Connection conn = null;// 定义连接标量 - try { - if (dbUserName == null) { - conn = DriverManager.getConnection(dbConnUrl); - } else { - conn = DriverManager.getConnection(dbConnUrl, dbUserName, - dbPassWord); - } - System.out.println("数据库连接池: " + poolName + " 创建新的连接"); - } catch (SQLException e) { - System.out.println("无法创建下列URL的连接: " + dbConnUrl); - return null; - } - return conn; - } - - /** - * 将不再使用的连接返回给连接池 - * - * @param con: 客户程序释放的连接 - */ - public synchronized void freeConnection(Connection conn) { - // 将指定连接加入到向量末尾 - freeConnections.addElement(conn); - checkedOut--; - notifyAll(); // 删除等待队列中的连接 数据库连接请求 - } - - /** - * 关闭连接 - */ - public synchronized void release() { - Enumeration allConnections = freeConnections.elements(); - while (allConnections.hasMoreElements()) { - Connection con = allConnections.nextElement(); - try { - con.close(); - System.out.println("关闭连接池" + poolName + "中的个连接"); - } catch (SQLException e) { - System.out.println("无法关闭连接池" + poolName + "中的连接"); - } - } - freeConnections.removeAllElements(); - } - - } -} diff --git a/jun_java_plugins/jun_solr/jun_solr_index/src/main/java/com/jun/plugin/solr/util/PinyinUtil.java b/jun_java_plugins/jun_solr/jun_solr_index/src/main/java/com/jun/plugin/solr/util/PinyinUtil.java deleted file mode 100644 index f994189c51..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_index/src/main/java/com/jun/plugin/solr/util/PinyinUtil.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.jun.plugin.solr.util; - -import net.sourceforge.pinyin4j.PinyinHelper; -import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType; -import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat; -import net.sourceforge.pinyin4j.format.HanyuPinyinToneType; -import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType; -import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination; - -public class PinyinUtil { - - private static HanyuPinyinOutputFormat hypof; - - static { - hypof = new HanyuPinyinOutputFormat(); - hypof.setCaseType(HanyuPinyinCaseType.LOWERCASE); - hypof.setToneType(HanyuPinyinToneType.WITHOUT_TONE); - hypof.setVCharType(HanyuPinyinVCharType.WITH_V); - } - - public static String getPingYin(String src) { - char[] t1 = src.toCharArray(); - String[] t2 = new String[t1.length]; - String t4 = ""; - int t0 = t1.length; - try { - for (int i = 0; i < t0; i++) { - // 判断是否为汉字字符 - if (Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")) { - t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], - hypof); - if(t2!=null){ - t4 += t2[0]; - } - } else - t4 += Character.toString(t1[i]); - } - t1 = null; - t2 = null; - } catch (BadHanyuPinyinOutputFormatCombination e1) { - e1.printStackTrace(); - } - return t4; - } - - public static String getPinYinHeadChar(String str) { - String convert = ""; - char word; - String[] pinyinArray = null; - for (int j = 0; j < str.length(); j++) { - word = str.charAt(j); - pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word); - if (pinyinArray != null) { - convert += pinyinArray[0].charAt(0); - } else { - convert += word; - } - } - return convert; - } -} diff --git a/jun_java_plugins/jun_solr/jun_solr_index/src/main/java/com/jun/plugin/solr/util/PropertyFile.java b/jun_java_plugins/jun_solr/jun_solr_index/src/main/java/com/jun/plugin/solr/util/PropertyFile.java deleted file mode 100644 index af3667695e..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_index/src/main/java/com/jun/plugin/solr/util/PropertyFile.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.jun.plugin.solr.util; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -public class PropertyFile { - private static Properties configProp; - - private static synchronized void init_prop(){ - configProp = new Properties(); - String path = PropertyFile.class.getClassLoader().getResource("").getPath(); - path = path.replaceAll("%20", " "); - InputStream fileinputstream = null; - try { - fileinputstream = new FileInputStream(path+"config.properties"); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - try { - configProp.load(fileinputstream); - } catch (IOException e) { - e.printStackTrace(); - System.err.println("不能读取配置文件, 请确保config.properties在CLASSPATH指定的路径中!"); - } - } - - public static Properties getProps(){ - if(configProp==null) - init_prop(); - return configProp; - } - - public static void main(String[] args) { - System.out.println(PropertyFile.getProps().getProperty("solr_url")); - - } -} diff --git a/jun_java_plugins/jun_solr/jun_solr_index/src/main/java/com/jun/plugin/solr/util/SolrUtil.java b/jun_java_plugins/jun_solr/jun_solr_index/src/main/java/com/jun/plugin/solr/util/SolrUtil.java deleted file mode 100644 index 97756dba59..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_index/src/main/java/com/jun/plugin/solr/util/SolrUtil.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.jun.plugin.solr.util; - -import org.apache.solr.client.solrj.impl.BinaryRequestWriter; -import org.apache.solr.client.solrj.impl.HttpSolrServer; - - -public class SolrUtil { - - private static String solrUrl = PropertyFile.getProps().getProperty("solrUrl"); - - public static HttpSolrServer getSolrHttpConnect() { - - HttpSolrServer ss = new HttpSolrServer(solrUrl); - ss.setSoTimeout(500000); - ss.setConnectionTimeout(500000); - ss.setDefaultMaxConnectionsPerHost(1000); - ss.setMaxTotalConnections(1000); - ss.setFollowRedirects(false); - ss.setAllowCompression(true); - ss.setRequestWriter(new BinaryRequestWriter()); - ss.setMaxRetries(5); - return ss; - } - -} diff --git a/jun_java_plugins/jun_solr/jun_solr_index/src/main/resources/config.properties b/jun_java_plugins/jun_solr/jun_solr_index/src/main/resources/config.properties deleted file mode 100644 index 63e080ec42..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_index/src/main/resources/config.properties +++ /dev/null @@ -1,8 +0,0 @@ -drivers = org.gjt.mm.mysql.Driver - -commodity.url = jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8 -commodity.user = root -commodity.password = -goods.maxconn = 300 - -solrUrl = http://127.0.0.1:8080/solr/c \ No newline at end of file diff --git a/jun_java_plugins/jun_solr/jun_solr_index/src/main/resources/log4j.dtd b/jun_java_plugins/jun_solr/jun_solr_index/src/main/resources/log4j.dtd deleted file mode 100644 index f8e433a50e..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_index/src/main/resources/log4j.dtd +++ /dev/null @@ -1,237 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/jun_java_plugins/jun_solr/jun_solr_index/src/main/resources/log4j.xml b/jun_java_plugins/jun_solr/jun_solr_index/src/main/resources/log4j.xml deleted file mode 100644 index 6ec81da5f1..0000000000 --- a/jun_java_plugins/jun_solr/jun_solr_index/src/main/resources/log4j.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/jun_java_plugins/jun_solr/pom.xml b/jun_java_plugins/jun_solr/pom.xml deleted file mode 100644 index f10bf0ed4b..0000000000 --- a/jun_java_plugins/jun_solr/pom.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_solr - 1.0 - - pom - jun_solr - http://maven.apache.org - - - - junit - junit - 4.11 - test - - - - - - releases - Cl Releases - http://192.168.1.11:8081/nexus/content/repositories/releases - - - snapshots - Cl Snapshots - http://192.168.1.11:8081/nexus/content/repositories/snapshots - - - - - jun_solr_api - jun_solr_api_server - jun_solr_index - - \ No newline at end of file diff --git a/jun_java_plugins/jun_solr/schema.xml b/jun_java_plugins/jun_solr/schema.xml deleted file mode 100644 index 5ccb88069e..0000000000 --- a/jun_java_plugins/jun_solr/schema.xml +++ /dev/null @@ -1,1066 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - no - - - text - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/jun_java_plugins/jun_threadpool/pom.xml b/jun_java_plugins/jun_threadpool/pom.xml deleted file mode 100644 index d70b694aff..0000000000 --- a/jun_java_plugins/jun_threadpool/pom.xml +++ /dev/null @@ -1,119 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_threadpool - 1.0 - war - Thread pool examples, Netty networking, Socket/NIO/AIO/BIO demos, and RPC framework samples - - - - UTF-8 - 1.8 - UTF-8 - UTF-8 - UTF-8 - 1.8 - 1.8 - 1.8 - 1.8 - - - - - - io.netty - netty-all - 4.1.26.Final - - - - - com.alibaba - fastjson - 1.2.47 - - - - - org.junit.jupiter - junit-jupiter - 5.5.2 - test - - - - - org.apache.logging.log4j - log4j-core - 2.9.1 - - - - - - - - - org.apache.commons - commons-email - 1.5 - - - com.sun.mail - javax.mail - 1.6.2 - - - - - mysql - mysql-connector-java - 5.1.40 - - - - - - jun_executor - - - - org.apache.maven.plugins - maven-compiler-plugin - - - ${java.version} - ${java.version} - ${java.encoding} - - - - - org.apache.maven.plugins - maven-shade-plugin - 3.2.1 - - - package - - shade - - - - - threadpool.io.github.wujun728.ThreadPoolDemoTest - - - - - - - - - diff --git a/jun_java_plugins/jun_threadpool/src/main/java/com/jun/base/io/aio/Test.java b/jun_java_plugins/jun_threadpool/src/main/java/com/jun/base/io/aio/Test.java deleted file mode 100644 index 75678b904e..0000000000 --- a/jun_java_plugins/jun_threadpool/src/main/java/com/jun/base/io/aio/Test.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.jun.base.io.aio; - - -import java.util.Scanner; - -import com.jun.base.io.aio.client.Client; - -/** - * 测试方法 - * @author Wujun - * @version 1.0 - */ -public class Test { - //测试主方法 - @SuppressWarnings("resource") - public static void main(String[] args) throws Exception{ - //运行服务器 - Server.start(); - //避免客户端先于服务器启动前执行代码 - Thread.sleep(100); - //运行客户端 - Client.start(); - System.out.println("请输入请求消息:"); - Scanner scanner = new Scanner(System.in); - while(Client.sendMsg(scanner.nextLine())); - } -} - diff --git a/jun_java_plugins/jun_threadpool/src/main/java/com/jun/base/io/bio/ServerHandler.java b/jun_java_plugins/jun_threadpool/src/main/java/com/jun/base/io/bio/ServerHandler.java deleted file mode 100644 index aeaf985004..0000000000 --- a/jun_java_plugins/jun_threadpool/src/main/java/com/jun/base/io/bio/ServerHandler.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.jun.base.io.bio; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.net.Socket; - -/** - * 客户端线程 - * @author Wujun - * 用于处理一个客户端的Socket链路 - */ -public class ServerHandler implements Runnable{ - private Socket socket; - public ServerHandler(Socket socket) { - this.socket = socket; - } - @Override - public void run() { - BufferedReader in = null; - PrintWriter out = null; - try{ - in = new BufferedReader(new InputStreamReader(socket.getInputStream())); - out = new PrintWriter(socket.getOutputStream(),true); - String expression; - String result; - while(true){ - //通过BufferedReader读取一行 - //如果已经读到输入流尾部,返回null,退出循环 - //如果得到非空值,就尝试计算结果并返回 - if((expression = in.readLine())==null) break; - System.out.println("服务器收到消息:" + expression); - try{ - result = Calculator.cal(expression).toString(); - - }catch(Exception e){ - result = "计算错误:" + e.getMessage(); - } - out.println(result); - } - }catch(Exception e){ - e.printStackTrace(); - }finally{ - //一些必要的清理工作 - if(in != null){ - try { - in.close(); - } catch (IOException e) { - e.printStackTrace(); - } - in = null; - } - if(out != null){ - out.close(); - out = null; - } - if(socket != null){ - try { - socket.close(); - } catch (IOException e) { - e.printStackTrace(); - } - socket = null; - } - } - } -} diff --git a/jun_java_plugins/jun_threadpool/src/main/java/com/jun/base/io/bio/Test.java b/jun_java_plugins/jun_threadpool/src/main/java/com/jun/base/io/bio/Test.java deleted file mode 100644 index 03c2e20fdf..0000000000 --- a/jun_java_plugins/jun_threadpool/src/main/java/com/jun/base/io/bio/Test.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.jun.base.io.bio; - - -import java.io.IOException; -import java.util.Random; -/** - * 测试方法 - * @author Wujun - * @version 1.0 - */ -public class Test { - //测试主方法 - public static void main(String[] args) throws InterruptedException { - //运行服务器 - new Thread(new Runnable() { - @Override - public void run() { - try { - ServerBetter.start(); - } catch (IOException e) { - e.printStackTrace(); - } - } - }).start(); - //避免客户端先于服务器启动前执行代码 - Thread.sleep(100); - //运行客户端 - char operators[] = {'+','-','*','/'}; - Random random = new Random(System.currentTimeMillis()); - new Thread(new Runnable() { - @SuppressWarnings("static-access") - @Override - public void run() { - while(true){ - //随机产生算术表达式 - String expression = random.nextInt(10)+""+operators[random.nextInt(4)]+(random.nextInt(10)+1); - Client.send(expression); - try { - Thread.currentThread().sleep(random.nextInt(1000)); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - }).start(); - } -} diff --git a/jun_java_plugins/jun_threadpool/src/main/java/com/jun/base/io/nio/Test.java b/jun_java_plugins/jun_threadpool/src/main/java/com/jun/base/io/nio/Test.java deleted file mode 100644 index d2c2673d22..0000000000 --- a/jun_java_plugins/jun_threadpool/src/main/java/com/jun/base/io/nio/Test.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.jun.base.io.nio; - - -import java.util.Scanner; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * 测试方法 - * @author Wujun - * @version 1.0 - */ -public class Test { - //测试主方法 - @SuppressWarnings("resource") - public static void main(String[] args) throws Exception{ - //运行服务器 - Server.start(); - //避免客户端先于服务器启动前执行代码 - //Thread.sleep(3000); - //System.out.println("运行客户端"); - //运行客户端 - //Client.start(); - - // while(Client.sendMsg(new Scanner(System.in).nextLine())); -// Thread.sleep(3000); -// System.out.println("向服务器发送:"); - //cliens(); - //Client.sendMsg("1+1"); - /*for(int i = 0; i <100; i++){ - - Client.sendMsg("0001+"+i); - }*/ - - - } - - public static void cliens() { - ExecutorService fixedThreadPool = Executors.newFixedThreadPool(1); - - - for(int i = 0; i <=2; i++){ - - final int j = i; - fixedThreadPool.execute(new Runnable() { - - @Override - public void run() { - try { - - Client.sendMsg("1+"+j); - Thread.sleep(1); - - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - }); - } - } -} diff --git a/jun_java_plugins/jun_uid/.gitignore b/jun_java_plugins/jun_uid/.gitignore deleted file mode 100644 index a1c2a238a9..0000000000 --- a/jun_java_plugins/jun_uid/.gitignore +++ /dev/null @@ -1,23 +0,0 @@ -# Compiled class file -*.class - -# Log file -*.log - -# BlueJ files -*.ctxt - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ - -# Package Files # -*.jar -*.war -*.nar -*.ear -*.zip -*.tar.gz -*.rar - -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* diff --git a/jun_java_plugins/jun_uid/README.md b/jun_java_plugins/jun_uid/README.md deleted file mode 100644 index c7c2346d4c..0000000000 --- a/jun_java_plugins/jun_uid/README.md +++ /dev/null @@ -1,146 +0,0 @@ -# ecp-uid -居于美团leaf、百度UidGenerator、原生snowflake 进行整合的 唯一ID生成器 - -一、介绍 -------------------- - 1、本项目为uid生成器,支持segment、snowflake、UidGenerator、spring四种策略生成id - - 2、本项目可生成混淆id,目前混淆策略为:gene(基因法) - - 3、项目地址: - github : https://github.com/linhuaichuan/ecp-uid - 码云: https://gitee.com/zmds/ecp-uid - -二、策略说明 -------------------- - 1、snowflake - snowflake 是基于Twitter [snowflake](https://github.com/twitter/snowflake) 算法的优化策略 - 本策略优化了闰秒回拨处理、新增默认workId 与 datacenterId 的提供方法。 - - - 2、baidu - 是 基于[百度UidGenerator](https://github.com/baidu/uid-generator)上的的优化策略。 - - - (1)、workerId提供策略 - * DisposableWorkerIdAssigner,利用数据库来管理生成workId,依赖数据库和spring-jdbc框架(需有jdbcTemplate的bean)。mysql表示例: - DROP TABLE IF EXISTS WORKER_NODE; - CREATE TABLE WORKER_NODE ( - ID BIGINT NOT NULL AUTO_INCREMENT COMMENT '自增 id', - HOST_NAME VARCHAR(64) NOT NULL COMMENT '主机名', - PORT VARCHAR(64) NOT NULL COMMENT '端口', - TYPE INT NOT NULL COMMENT '节点类型: ACTUAL or CONTAINER', - LAUNCH_DATE DATE NOT NULL COMMENT '启动时间', - MODIFIED TIMESTAMP NOT NULL COMMENT '修改时间', - CREATED TIMESTAMP NOT NULL COMMENT '创建时间', - PRIMARY KEY(ID) - ) COMMENT='DB WorkerID Assigner for UID Generator',ENGINE = INNODB; - - 示例: - - ... - - * SimpleWorkerIdAssigner ,固定了workId的提供。值为0.示例: - - - * ZkWorkerIdAssigner ,利用zookeeper来实现wordId的提供管理,依赖原生Zookeeper驱动.示例: - - 可设置interval-心跳间隔、pidHome-workerId文件存储目录、zkAddress-zk地址、pidPort-心跳端口 - - * RedisWorkIdAssigner ,利用redis来实现wordId的提供管理,依赖了spring-data-redis框架的RedisTemplate.示例: - - 可设置interval-心跳间隔、pidHome-workerId文件存储目录、pidPort-心跳端口 - - (2)、uid生成策略 - * DefaultUidGenerator 是Snowflake算法的变种,取消datacenterId, 并扩展了支持自定义workerId位数和初始化策略。 - a、可配置 delta seconds (28 bits) - 当前时间,相对于时间基点"2016-05-20"的增量值,单位:秒,最多可支持约8.7年 - - b、worker id (22 bits) - 机器id,最多可支持约420w次机器启动。内置实现为在启动时由数据库分配,默认分配策略为用后即弃,后续可提供复用策略。 - - c、sequence (13 bits) - 每秒下的并发序列,13 bits可支持每秒8192个并发。 - - 注: 三者之和为63 - - 示例: - - - - - - - - - * CachedUidGenerator借用未来时间来解决sequence天然存在的并发限制; 采用RingBuffer来缓存已生成的UID, 并行化UID的生产和消费, - 同时对CacheLine补齐,避免了由RingBuffer带来的硬件级「伪共享」问题. 最终单机QPS可达600万 - - 示例: - - - - - - - - - - - - - - - - - - - - - - - - - - - (3)、比特分配的建议 - *对于并发数要求不高、期望长期使用的应用, 可增加```timeBits```位数, 减少```seqBits```位数. - 例如节点采取用完即弃的WorkerIdAssigner策略, 重启频率为12次/天, - 那么配置成```{"workerBits":23,"timeBits":31,"seqBits":9}```时, 可支持28个节点以整体并发量14400 UID/s的速度持续运行68年. - - *对于节点重启频率频繁、期望长期使用的应用, 可增加```workerBits```和```timeBits```位数, 减少```seqBits```位数. - 例如节点采取用完即弃的WorkerIdAssigner策略, 重启频率为24*12次/天, - 那么配置成```{"workerBits":27,"timeBits":30,"seqBits":6}```时, 可支持37个节点以整体并发量2400 UID/s的速度持续运行34年. - - 3、segment - 是 基于美团[leaf-segment](https://tech.meituan.com/MT_Leaf.html) 的优化策略, 使用双Buffer实现。依赖数据库与spring-jdbc框架 - - - (1)、SegmentServiceImpl 是具体实现类,数据库表结构为(mysql示例): - DROP TABLE IF EXISTS id_segment; - CREATE TABLE id_segment ( - BIZ_TAG VARCHAR(64) NOT NULL COMMENT '业务标识', - STEP int NOT NULL COMMENT '步长', - MAX_ID BIGINT NOT NULL COMMENT '最大值', - LAST_UPDATE_TIME TIMESTAMP NOT NULL COMMENT '上次修改时间', - CURRENT_UPDATE_TIME TIMESTAMP NOT NULL COMMENT '当前修改时间', - PRIMARY KEY(BIZ_TAG) - ) COMMENT='号段存储表',ENGINE = INNODB; - - (2)、支持 同步/异步两种更新数据库方式。可选配置asynLoadingSegment(true-异步,false-同步),默认使用异步。 - 示例: - ... - - 4、spring 增量ID - 是 基于 segment策略提供给spring 增量实现。非直接使用的策略 - - 5、混淆算法 - 是 基于 基因分库法这个理论扩展出来的混淆算法 - -三 、使用 -------------------- - - - - - diff --git a/jun_java_plugins/jun_uid/pom.xml b/jun_java_plugins/jun_uid/pom.xml deleted file mode 100644 index 28191d02f8..0000000000 --- a/jun_java_plugins/jun_uid/pom.xml +++ /dev/null @@ -1,246 +0,0 @@ - - - 4.0.0 - jun_uid - io.github.wujun728 - jun_uid - 1.0 - jar - - - - UTF-8 - UTF-8 - 1.8 - 1.8 - - 1.8 - - 3.5 - 4.3.19.RELEASE - 1.8.15.RELEASE - - 5.1.47 - 1.7.25 - 3.4.14 - - 1.18.4 - 4.12 - - - - src/main/java - - - - src/main/resources - true - - ** - - - - src/test/java - - - src/test/resources - - ** - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.0 - - ${java.version} - ${java.version} - UTF-8 - - - - - org.apache.maven.plugins - maven-resources-plugin - 3.1.0 - - UTF-8 - - - pem - jks - pfx - - - - - - org.apache.maven.plugins - maven-jar-plugin - 3.1.0 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - org.apache.maven.plugins - maven-resources-plugin - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.1 - - 8 - 8 - UTF-8 - - - - - - - - central - http://repo1.maven.org/maven2 - - - true - - - - osgeo - Open Source Geospatial Foundation Repository - http://download.osgeo.org/webdav/geotools/ - - - - - - - org.springframework - spring-core - ${org.springframework.version} - - - commons-logging - commons-logging - - - - - org.springframework - spring-beans - ${org.springframework.version} - - - org.springframework - spring-context - ${org.springframework.version} - - - - - org.slf4j - slf4j-api - ${slf4j.version} - - - - org.slf4j - jcl-over-slf4j - ${slf4j.version} - - - - org.projectlombok - lombok - ${lombok.version} - provided - - - - org.springframework - spring-jdbc - ${org.springframework.version} - true - - - mysql - mysql-connector-java - ${mysql.version} - true - - - - - org.apache.zookeeper - zookeeper - ${zookeeper.version} - true - - - log4j - log4j - - - slf4j-log4j12 - org.slf4j - - - io.netty - netty - - - - - - - org.springframework.data - spring-data-redis - ${org.springframework.data.version} - true - - - - - junit - junit - ${junit.version} - test - - - com.alibaba - fastjson - true - 1.2.58 - test - - - - - org.springframework - spring-test - ${org.springframework.version} - test - - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/UidContext.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/UidContext.java deleted file mode 100644 index 11ecfb3fe2..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/UidContext.java +++ /dev/null @@ -1,164 +0,0 @@ -package com.myzmds.ecp.core.uid; - -import com.myzmds.ecp.core.uid.extend.strategy.IUidStrategy; - -/** - * @类名称 UidContext.java - * @类描述
Uid策略上下文
- * @作者 庄梦蝶殇 linhuaichuan1989@126.com - * @创建时间 2018年9月7日 上午9:51:21 - * @版本 1.00 - * - * @修改记录 - *
- *     版本                       修改人 		修改日期 		 修改内容描述
- *     ----------------------------------------------
- *     1.00 	庄梦蝶殇 	2018年9月7日             
- *     ----------------------------------------------
- * 
- */ -public class UidContext { - /** - * 空组 - */ - private static final String EMPTY_STR = ""; - - private IUidStrategy uidStrategy; - - /** - * 除余基数(建议使用固定值)--控制位移 - */ - private Integer fixed = 25; - - /** - * 基因因子 - */ - public Long factor; - - public UidContext(IUidStrategy uidStrategy) { - this.uidStrategy = uidStrategy; - } - - /** - * @方法名称 getUidStr - * @功能描述
获取ID
- */ - public String getUidStr() { - return getUidStr(EMPTY_STR); - } - - /** - * @方法名称 getUidStr - * @功能描述
获取ID
- * @param prefix 前缀(有group作用) - */ - public String getUidStr(String prefix) { - return prefix + getUID(prefix); - } - - /** - * @方法名称 getUID - * @功能描述
获取ID
- */ - public long getUID() { - return getUID(EMPTY_STR); - } - - /** - * @方法名称 getUID - * @功能描述
获取ID
- * @param group 分组 - */ - public long getUID(String group) { - return geneId(uidStrategy.getUID(group)); - } - - /** - * @方法名称 parseUID - * @功能描述
解析ID
- * @param uid - * @param group 分组 - * @return 输出json字符串:{\"UID\":\"\",\"timestamp\":\"\",\"workerId\":\"\",\"dataCenterId\":\"\",\"sequence\":\"\"} - */ - public String parseUID(long uid, String group) { - return uidStrategy.parseUID(restoreId(uid), group); - } - - /** - * @方法名称 parseUID - * @功能描述
解析ID
- * @param uid - * @return 输出json字符串:{\"UID\":\"\",\"timestamp\":\"\",\"workerId\":\"\",\"dataCenterId\":\"\",\"sequence\":\"\"} - */ - public String parseUID(long uid) { - return parseUID(uid, EMPTY_STR); - } - - /** - * @方法名称 parseUID - * @功能描述
解析ID
- * @param uid - * @return 输出json字符串:{\"UID\":\"\",\"timestamp\":\"\",\"workerId\":\"\",\"dataCenterId\":\"\",\"sequence\":\"\"} - */ - public String parseUID(String uid) { - return parseUID(uid, EMPTY_STR); - } - - /** - * @方法名称 parseUID - * @功能描述
解析ID
- * @param uid - * @param group 分组 - * @return 输出json字符串:{\"UID\":\"\",\"timestamp\":\"\",\"workerId\":\"\",\"dataCenterId\":\"\",\"sequence\":\"\"} - */ - public String parseUID(String uid, String group) { - return parseUID(Long.valueOf(uid.replaceFirst("[^(0-9)]*", "")), group); - } - - /** - * 根据基因因子生成基因id - */ - public Long geneId(Long primitiveId) { - if (null == factor) { - return primitiveId; - } - int moveBit = Integer.toBinaryString(fixed).length() - 1; - // 加入factor基因 - return (primitiveId << moveBit) | (factor % fixed); - } - - /** - * 还原id - */ - public long restoreId(long uid) { - if (null == factor) { - return uid; - } - int leftMoveBit = Integer.toBinaryString(fixed).length() - 1; - return uid >>> leftMoveBit; - } - - public IUidStrategy getUidStrategy() { - return uidStrategy; - } - - public void setUidStrategy(IUidStrategy uidStrategy) { - this.uidStrategy = uidStrategy; - } - - public Integer getFixed() { - return fixed; - } - - public void setFixed(Integer fixed) { - this.fixed = fixed; - } - - public Long getFactor() { - return factor; - } - - public void setFactor(Long factor) { - this.factor = factor; - } -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/BitsAllocator.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/BitsAllocator.java deleted file mode 100644 index 10d93ab688..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/BitsAllocator.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.myzmds.ecp.core.uid.baidu; - -import org.springframework.util.Assert; - -import lombok.ToString; - -/** - * Allocate 64 bits for the UID(long)
- * sign (fixed 1bit) -> deltaSecond -> workerId -> sequence(within the same second) - * - * @author yutianbao - */ -@ToString -public class BitsAllocator { - /** - * Total 64 bits - */ - public static final int TOTAL_BITS = 1 << 6; - - /** - * Bits for [sign-> second-> workId-> sequence] - */ - private int signBits = 1; - private final int timestampBits; - private final int workerIdBits; - private final int sequenceBits; - - /** - * Max value for workId & sequence - */ - private final long maxDeltaSeconds; - private final long maxWorkerId; - private final long maxSequence; - - /** - * Shift for timestamp & workerId - */ - private final int timestampShift; - private final int workerIdShift; - - /** - * Constructor with timestampBits, workerIdBits, sequenceBits
- * The highest bit used for sign, so 63 bits for timestampBits, workerIdBits, sequenceBits - */ - public BitsAllocator(int timestampBits, int workerIdBits, int sequenceBits) { - // make sure allocated 64 bits - int allocateTotalBits = signBits + timestampBits + workerIdBits + sequenceBits; - Assert.isTrue(allocateTotalBits == TOTAL_BITS, "allocate not enough 64 bits"); - - // initialize bits - this.timestampBits = timestampBits; - this.workerIdBits = workerIdBits; - this.sequenceBits = sequenceBits; - - // initialize max value - this.maxDeltaSeconds = ~(-1L << timestampBits); - this.maxWorkerId = ~(-1L << workerIdBits); - this.maxSequence = ~(-1L << sequenceBits); - - // initialize shift - this.timestampShift = workerIdBits + sequenceBits; - this.workerIdShift = sequenceBits; - } - - /** - * Allocate bits for UID according to delta seconds & workerId & sequence
- * Note that: The highest bit will always be 0 for sign - * - * @param deltaSeconds - * @param workerId - * @param sequence - * @return - */ - public long allocate(long deltaSeconds, long workerId, long sequence) { - return (deltaSeconds << timestampShift) | (workerId << workerIdShift) | sequence; - } - - /** - * Getters - */ - public int getSignBits() { - return signBits; - } - - public int getTimestampBits() { - return timestampBits; - } - - public int getWorkerIdBits() { - return workerIdBits; - } - - public int getSequenceBits() { - return sequenceBits; - } - - public long getMaxDeltaSeconds() { - return maxDeltaSeconds; - } - - public long getMaxWorkerId() { - return maxWorkerId; - } - - public long getMaxSequence() { - return maxSequence; - } - - public int getTimestampShift() { - return timestampShift; - } - - public int getWorkerIdShift() { - return workerIdShift; - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/UidGenerator.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/UidGenerator.java deleted file mode 100644 index bcd61d64c1..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/UidGenerator.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.myzmds.ecp.core.uid.baidu; - -import com.myzmds.ecp.core.uid.baidu.exception.UidGenerateException; - -/** - * Represents a unique id generator. - * - * @author yutianbao - */ -public interface UidGenerator { - - /** - * Get a unique ID - * - * @return UID - * @throws UidGenerateException - */ - long getUID() throws UidGenerateException; - - /** - * Parse the UID into elements which are used to generate the UID.
- * Such as timestamp & workerId & sequence... - * - * @param uid - * @return Parsed info - */ - String parseUID(long uid); - -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/buffer/BufferPaddingExecutor.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/buffer/BufferPaddingExecutor.java deleted file mode 100644 index 453c37296c..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/buffer/BufferPaddingExecutor.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.myzmds.ecp.core.uid.baidu.buffer; - -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.util.Assert; - -import com.myzmds.ecp.core.uid.baidu.utils.NamingThreadFactory; -import com.myzmds.ecp.core.uid.baidu.utils.PaddedAtomicLong; - -/** - * Represents an executor for padding {@link RingBuffer}
- * There are two kinds of executors: one for scheduled padding, the other for padding immediately. - * - * @author yutianbao - */ -public class BufferPaddingExecutor { - private static final Logger LOGGER = LoggerFactory.getLogger(RingBuffer.class); - - /** Constants */ - private static final String WORKER_NAME = "RingBuffer-Padding-Worker"; - private static final String SCHEDULE_NAME = "RingBuffer-Padding-Schedule"; - /** 5 minutes(分钟)**/ - private static final long DEFAULT_SCHEDULE_INTERVAL = 5 * 60L; - - /** Whether buffer padding is running */ - private final AtomicBoolean running; - - /** We can borrow UIDs from the future, here store the last second we have consumed */ - private final PaddedAtomicLong lastSecond; - - /** RingBuffer & BufferUidProvider */ - private final RingBuffer ringBuffer; - private final BufferedUidProvider uidProvider; - - /** Padding immediately by the thread pool */ - private final ExecutorService bufferPadExecutors; - /** Padding schedule thread */ - private final ScheduledExecutorService bufferPadSchedule; - - /** Schedule interval Unit as seconds */ - private long scheduleInterval = DEFAULT_SCHEDULE_INTERVAL; - - /** - * Constructor with {@link RingBuffer} and {@link BufferedUidProvider}, default use schedule - * - * @param ringBuffer {@link RingBuffer} - * @param uidProvider {@link BufferedUidProvider} - */ - public BufferPaddingExecutor(RingBuffer ringBuffer, BufferedUidProvider uidProvider) { - this(ringBuffer, uidProvider, true); - } - - /** - * Constructor with {@link RingBuffer}, {@link BufferedUidProvider}, and whether use schedule padding - * - * @param ringBuffer {@link RingBuffer} - * @param uidProvider {@link BufferedUidProvider} - * @param usingSchedule - */ - public BufferPaddingExecutor(RingBuffer ringBuffer, BufferedUidProvider uidProvider, boolean usingSchedule) { - this.running = new AtomicBoolean(false); - this.lastSecond = new PaddedAtomicLong(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis())); - this.ringBuffer = ringBuffer; - this.uidProvider = uidProvider; - - // initialize thread pool - int cores = Runtime.getRuntime().availableProcessors(); - bufferPadExecutors = new ThreadPoolExecutor(cores * 2, cores * 2, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(), new NamingThreadFactory(WORKER_NAME)); - - // initialize schedule thread - if (usingSchedule) { - bufferPadSchedule = new ScheduledThreadPoolExecutor(1, new NamingThreadFactory(SCHEDULE_NAME, true)); - } else { - bufferPadSchedule = null; - } - } - - /** - * Start executors such as schedule - */ - public void start() { - if (bufferPadSchedule != null) { - bufferPadSchedule.scheduleWithFixedDelay(new Runnable() { - @Override - public void run() { - paddingBuffer(); - } - }, scheduleInterval, scheduleInterval, TimeUnit.SECONDS); - } - } - - /** - * Shutdown executors - */ - public void shutdown() { - if (!bufferPadExecutors.isShutdown()) { - bufferPadExecutors.shutdownNow(); - } - - if (bufferPadSchedule != null && !bufferPadSchedule.isShutdown()) { - bufferPadSchedule.shutdownNow(); - } - } - - /** - * Whether is padding - * - * @return - */ - public boolean isRunning() { - return running.get(); - } - - /** - * Padding buffer in the thread pool - */ - public void asyncPadding() { - bufferPadExecutors.submit(new Runnable() { - @Override - public void run() { - paddingBuffer(); - } - }); - } - - /** - * Padding buffer fill the slots until to catch the cursor - */ - public void paddingBuffer() { - LOGGER.info("Ready to padding buffer lastSecond:{}. {}", lastSecond.get(), ringBuffer); - - // is still running - if (!running.compareAndSet(false, true)) { - LOGGER.info("Padding buffer is still running. {}", ringBuffer); - return; - } - - // fill the rest slots until to catch the cursor - boolean isFullRingBuffer = false; - while (!isFullRingBuffer) { - List uidList = uidProvider.provide(lastSecond.incrementAndGet()); - for (Long uid : uidList) { - isFullRingBuffer = !ringBuffer.put(uid); - if (isFullRingBuffer) { - break; - } - } - } - - // not running now - running.compareAndSet(true, false); - LOGGER.info("End to padding buffer lastSecond:{}. {}", lastSecond.get(), ringBuffer); - } - - /** - * Setters - */ - public void setScheduleInterval(long scheduleInterval) { - Assert.isTrue(scheduleInterval > 0, "Schedule interval must positive!"); - this.scheduleInterval = scheduleInterval; - } - -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/buffer/BufferedUidProvider.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/buffer/BufferedUidProvider.java deleted file mode 100644 index 1e85254e84..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/buffer/BufferedUidProvider.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.myzmds.ecp.core.uid.baidu.buffer; - -import java.util.List; - -/** - * Buffered UID provider(Lambda supported), which provides UID in the same one second - * - * @author yutianbao - */ -public interface BufferedUidProvider { - - /** - * Provides UID in one second - * - * @param momentInSecond - * @return - */ - List provide(long momentInSecond); -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/buffer/RejectedPutBufferHandler.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/buffer/RejectedPutBufferHandler.java deleted file mode 100644 index 32d050a0cb..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/buffer/RejectedPutBufferHandler.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.myzmds.ecp.core.uid.baidu.buffer; - -/** - * If tail catches the cursor it means that the ring buffer is full, any more buffer put request will be rejected. - * Specify the policy to handle the reject. This is a Lambda supported interface - * - * @author yutianbao - */ -public interface RejectedPutBufferHandler { - - /** - * Reject put buffer request - * - * @param ringBuffer - * @param uid - */ - void rejectPutBuffer(RingBuffer ringBuffer, long uid); -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/buffer/RejectedTakeBufferHandler.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/buffer/RejectedTakeBufferHandler.java deleted file mode 100644 index 966e1dee9a..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/buffer/RejectedTakeBufferHandler.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.myzmds.ecp.core.uid.baidu.buffer; - -/** - * If cursor catches the tail it means that the ring buffer is empty, any more buffer take request will be rejected. - * Specify the policy to handle the reject. This is a Lambda supported interface - * - * @author yutianbao - */ -public interface RejectedTakeBufferHandler { - - /** - * Reject take buffer request - * - * @param ringBuffer - */ - void rejectTakeBuffer(RingBuffer ringBuffer); -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/buffer/RingBuffer.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/buffer/RingBuffer.java deleted file mode 100644 index 91bfe1b782..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/buffer/RingBuffer.java +++ /dev/null @@ -1,284 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.myzmds.ecp.core.uid.baidu.buffer; - -import java.util.concurrent.atomic.AtomicLong; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.util.Assert; - -import com.myzmds.ecp.core.uid.baidu.utils.PaddedAtomicLong; - -/** - * Represents a ring buffer based on array.
- * Using array could improve read element performance due to the CUP cache line. To prevent - * the side effect of False Sharing, {@link PaddedAtomicLong} is using on 'tail' and 'cursor'

- * - * A ring buffer is consisted of: - *

  • slots: each element of the array is a slot, which is be set with a UID - *
  • flags: flag array corresponding the same index with the slots, indicates whether can take or put slot - *
  • tail: a sequence of the max slot position to produce - *
  • cursor: a sequence of the min slot position to consume - * - * @author yutianbao - */ -public class RingBuffer { - private static final Logger LOGGER = LoggerFactory.getLogger(RingBuffer.class); - - /** Constants */ - private static final int START_POINT = -1; - private static final long CAN_PUT_FLAG = 0L; - private static final long CAN_TAKE_FLAG = 1L; - public static final int DEFAULT_PADDING_PERCENT = 50; - - /** The size of RingBuffer's slots, each slot hold a UID */ - private final int bufferSize; - private final long indexMask; - private final long[] slots; - private final PaddedAtomicLong[] flags; - - /** Tail: last position sequence to produce */ - private final AtomicLong tail = new PaddedAtomicLong(START_POINT); - - /** Cursor: current position sequence to consume */ - private final AtomicLong cursor = new PaddedAtomicLong(START_POINT); - - /** Threshold for trigger padding buffer*/ - private final int paddingThreshold; - - /** Reject put/take buffer handle policy */ - private RejectedPutBufferHandler rejectedPutHandler = new RejectedPutBufferHandler() { - @Override - public void rejectPutBuffer(RingBuffer ringBuffer, long uid) { - discardPutBuffer(ringBuffer, uid); - } - }; - - private RejectedTakeBufferHandler rejectedTakeHandler = new RejectedTakeBufferHandler() { - @Override - public void rejectTakeBuffer(RingBuffer ringBuffer) { - exceptionRejectedTakeBuffer(ringBuffer); - } - }; - - /** Executor of padding buffer */ - private BufferPaddingExecutor bufferPaddingExecutor; - - /** - * Constructor with buffer size, paddingFactor default as {@value #DEFAULT_PADDING_PERCENT} - * - * @param bufferSize must be positive & a power of 2 - */ - public RingBuffer(int bufferSize) { - this(bufferSize, DEFAULT_PADDING_PERCENT); - } - - /** - * Constructor with buffer size & padding factor - * - * @param bufferSize must be positive & a power of 2 - * @param paddingFactor percent in (0 - 100). When the count of rest available UIDs reach the threshold, it will trigger padding buffer
    - * Sample: paddingFactor=20, bufferSize=1000 -> threshold=1000 * 20 /100, - * padding buffer will be triggered when tail-cursor 0L, "RingBuffer size must be positive"); - Assert.isTrue(Integer.bitCount(bufferSize) == 1, "RingBuffer size must be a power of 2"); - Assert.isTrue(paddingFactor > 0 && paddingFactor < 100, "RingBuffer size must be positive"); - - this.bufferSize = bufferSize; - this.indexMask = bufferSize - 1; - this.slots = new long[bufferSize]; - this.flags = initFlags(bufferSize); - - this.paddingThreshold = bufferSize * paddingFactor / 100; - } - - /** - * Put an UID in the ring & tail moved
    - * We use 'synchronized' to guarantee the UID fill in slot & publish new tail sequence as atomic operations
    - * - * Note that: It is recommended to put UID in a serialize way, cause we once batch generate a series UIDs and put - * the one by one into the buffer, so it is unnecessary put in multi-threads - * - * @param uid - * @return false means that the buffer is full, apply {@link RejectedPutBufferHandler} - */ - public synchronized boolean put(long uid) { - long currentTail = tail.get(); - long currentCursor = cursor.get(); - - // tail catches the cursor, means that you can't put any cause of RingBuffer is full - long distance = currentTail - (currentCursor == START_POINT ? 0 : currentCursor); - if (distance == bufferSize - 1) { - rejectedPutHandler.rejectPutBuffer(this, uid); - return false; - } - - // 1. pre-check whether the flag is CAN_PUT_FLAG - int nextTailIndex = calSlotIndex(currentTail + 1); - if (flags[nextTailIndex].get() != CAN_PUT_FLAG) { - rejectedPutHandler.rejectPutBuffer(this, uid); - return false; - } - - // 2. put UID in the next slot - // 3. update next slot' flag to CAN_TAKE_FLAG - // 4. publish tail with sequence increase by one - slots[nextTailIndex] = uid; - flags[nextTailIndex].set(CAN_TAKE_FLAG); - tail.incrementAndGet(); - - // The atomicity of operations above, guarantees by 'synchronized'. In another word, - // the take operation can't consume the UID we just put, until the tail is published(tail.incrementAndGet()) - return true; - } - - /** - * cursor.updateAndGet(old -> old == tail.get() ? old : old + 1) - */ - public final long updateAndGet() { - long prev, next; - do { - prev = cursor.get(); - next = prev == tail.get() ? prev : prev + 1; - } while (!cursor.compareAndSet(prev, next)); - return next; - } - - /** - * Take an UID of the ring at the next cursor, this is a lock free operation by using atomic cursor

    - * - * Before getting the UID, we also check whether reach the padding threshold, - * the padding buffer operation will be triggered in another thread
    - * If there is no more available UID to be taken, the specified {@link RejectedTakeBufferHandler} will be applied
    - * - * @return UID - * @throws IllegalStateException if the cursor moved back - */ - public long take() { - // spin get next available cursor - long currentCursor = cursor.get(); - long nextCursor = updateAndGet(); - - // check for safety consideration, it never occurs - Assert.isTrue(nextCursor >= currentCursor, "Curosr can't move back"); - - // trigger padding in an async-mode if reach the threshold - long currentTail = tail.get(); - if (currentTail - nextCursor < paddingThreshold) { - LOGGER.info("Reach the padding threshold:{}. tail:{}, cursor:{}, rest:{}", paddingThreshold, currentTail, - nextCursor, currentTail - nextCursor); - bufferPaddingExecutor.asyncPadding(); - } - - // cursor catch the tail, means that there is no more available UID to take - if (nextCursor == currentCursor) { - rejectedTakeHandler.rejectTakeBuffer(this); - } - - // 1. check next slot flag is CAN_TAKE_FLAG - int nextCursorIndex = calSlotIndex(nextCursor); - Assert.isTrue(flags[nextCursorIndex].get() == CAN_TAKE_FLAG, "Curosr not in can take status"); - - // 2. get UID from next slot - // 3. set next slot flag as CAN_PUT_FLAG. - long uid = slots[nextCursorIndex]; - flags[nextCursorIndex].set(CAN_PUT_FLAG); - - // Note that: Step 2,3 can not swap. If we set flag before get value of slot, the producer may overwrite the - // slot with a new UID, and this may cause the consumer take the UID twice after walk a round the ring - return uid; - } - - /** - * Calculate slot index with the slot sequence (sequence % bufferSize) - */ - protected int calSlotIndex(long sequence) { - return (int) (sequence & indexMask); - } - - /** - * Discard policy for {@link RejectedPutBufferHandler}, we just do logging - */ - protected void discardPutBuffer(RingBuffer ringBuffer, long uid) { - LOGGER.warn("Rejected putting buffer for uid:{}. {}", uid, ringBuffer); - } - - /** - * Policy for {@link RejectedTakeBufferHandler}, throws {@link RuntimeException} after logging - */ - protected void exceptionRejectedTakeBuffer(RingBuffer ringBuffer) { - LOGGER.warn("Rejected take buffer. {}", ringBuffer); - throw new RuntimeException("Rejected take buffer. " + ringBuffer); - } - - /** - * Initialize flags as CAN_PUT_FLAG - */ - private PaddedAtomicLong[] initFlags(int bufferSize) { - PaddedAtomicLong[] flags = new PaddedAtomicLong[bufferSize]; - for (int i = 0; i < bufferSize; i++) { - flags[i] = new PaddedAtomicLong(CAN_PUT_FLAG); - } - - return flags; - } - - /** - * Getters - */ - public long getTail() { - return tail.get(); - } - - public long getCursor() { - return cursor.get(); - } - - public int getBufferSize() { - return bufferSize; - } - - /** - * Setters - */ - public void setBufferPaddingExecutor(BufferPaddingExecutor bufferPaddingExecutor) { - this.bufferPaddingExecutor = bufferPaddingExecutor; - } - - public void setRejectedPutHandler(RejectedPutBufferHandler rejectedPutHandler) { - this.rejectedPutHandler = rejectedPutHandler; - } - - public void setRejectedTakeHandler(RejectedTakeBufferHandler rejectedTakeHandler) { - this.rejectedTakeHandler = rejectedTakeHandler; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("RingBuffer [bufferSize=").append(bufferSize) - .append(", tail=").append(tail) - .append(", cursor=").append(cursor) - .append(", paddingThreshold=").append(paddingThreshold).append("]"); - - return builder.toString(); - } - -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/exception/UidGenerateException.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/exception/UidGenerateException.java deleted file mode 100644 index bc36ce90c1..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/exception/UidGenerateException.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.myzmds.ecp.core.uid.baidu.exception; - -/** - * UidGenerateException - * - * @author yutianbao - */ -public class UidGenerateException extends RuntimeException { - - /** - * Serial Version UID - */ - private static final long serialVersionUID = -27048199131316992L; - - /** - * Default constructor - */ - public UidGenerateException() { - super(); - } - - /** - * Constructor with message & cause - * - * @param message - * @param cause - */ - public UidGenerateException(String message, Throwable cause) { - super(message, cause); - } - - /** - * Constructor with message - * - * @param message - */ - public UidGenerateException(String message) { - super(message); - } - - /** - * Constructor with message format - * - * @param msgFormat - * @param args - */ - public UidGenerateException(String msgFormat, Object... args) { - super(String.format(msgFormat, args)); - } - - /** - * Constructor with cause - * - * @param cause - */ - public UidGenerateException(Throwable cause) { - super(cause); - } - -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/impl/CachedUidGenerator.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/impl/CachedUidGenerator.java deleted file mode 100644 index 673d18f258..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/impl/CachedUidGenerator.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.myzmds.ecp.core.uid.baidu.impl; - -import java.util.ArrayList; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.DisposableBean; -import org.springframework.util.Assert; - -import com.myzmds.ecp.core.uid.baidu.BitsAllocator; -import com.myzmds.ecp.core.uid.baidu.UidGenerator; -import com.myzmds.ecp.core.uid.baidu.buffer.BufferPaddingExecutor; -import com.myzmds.ecp.core.uid.baidu.buffer.BufferedUidProvider; -import com.myzmds.ecp.core.uid.baidu.buffer.RejectedPutBufferHandler; -import com.myzmds.ecp.core.uid.baidu.buffer.RejectedTakeBufferHandler; -import com.myzmds.ecp.core.uid.baidu.buffer.RingBuffer; -import com.myzmds.ecp.core.uid.baidu.exception.UidGenerateException; - -/** - * Represents a cached implementation of {@link UidGenerator} extends - * from {@link DefaultUidGenerator}, based on a lock free {@link RingBuffer}

    - * - * The spring properties you can specified as below:
    - *

  • boostPower: RingBuffer size boost for a power of 2, Sample: boostPower is 3, it means the buffer size - * will be ({@link BitsAllocator#getMaxSequence()} + 1) << - * {@link #boostPower}, Default as {@value #DEFAULT_BOOST_POWER} - *
  • paddingFactor: Represents a percent value of (0 - 100). When the count of rest available UIDs reach the - * threshold, it will trigger padding buffer. Default as{@link RingBuffer#DEFAULT_PADDING_PERCENT} - * Sample: paddingFactor=20, bufferSize=1000 -> threshold=1000 * 20 /100, padding buffer will be triggered when tail-cursorscheduleInterval: Padding buffer in a schedule, specify padding buffer interval, Unit as second - *
  • rejectedPutBufferHandler: Policy for rejected put buffer. Default as discard put request, just do logging - *
  • rejectedTakeBufferHandler: Policy for rejected take buffer. Default as throwing up an exception - * - * @author yutianbao - */ -public class CachedUidGenerator extends DefaultUidGenerator implements DisposableBean { - private static final Logger LOGGER = LoggerFactory.getLogger(CachedUidGenerator.class); - private static final int DEFAULT_BOOST_POWER = 3; - - /** Spring properties */ - private int boostPower = DEFAULT_BOOST_POWER; - private int paddingFactor = RingBuffer.DEFAULT_PADDING_PERCENT; - private Long scheduleInterval; - - private RejectedPutBufferHandler rejectedPutBufferHandler; - private RejectedTakeBufferHandler rejectedTakeBufferHandler; - - /** RingBuffer */ - private RingBuffer ringBuffer; - private BufferPaddingExecutor bufferPaddingExecutor; - - @Override - public void afterPropertiesSet() throws Exception { - // initialize workerId & bitsAllocator - super.afterPropertiesSet(); - - // initialize RingBuffer & RingBufferPaddingExecutor - this.initRingBuffer(); - LOGGER.info("Initialized RingBuffer successfully."); - } - - @Override - public long getUID() { - try { - return ringBuffer.take(); - } catch (Exception e) { - LOGGER.error("Generate unique id exception. ", e); - throw new UidGenerateException(e); - } - } - - @Override - public String parseUID(long uid) { - return super.parseUID(uid); - } - - @Override - public void destroy() throws Exception { - bufferPaddingExecutor.shutdown(); - } - - /** - * Get the UIDs in the same specified second under the max sequence - * - * @param currentSecond - * @return UID list, size of {@link BitsAllocator#getMaxSequence()} + 1 - */ - protected List nextIdsForOneSecond(long currentSecond) { - // Initialize result list size of (max sequence + 1) - int listSize = (int) bitsAllocator.getMaxSequence() + 1; - List uidList = new ArrayList<>(listSize); - - // Allocate the first sequence of the second, the others can be calculated with the offset - long firstSeqUid = bitsAllocator.allocate(currentSecond - epochSeconds, workerId, 0L); - for (int offset = 0; offset < listSize; offset++) { - uidList.add(firstSeqUid + offset); - } - - return uidList; - } - - /** - * Initialize RingBuffer & RingBufferPaddingExecutor - */ - private void initRingBuffer() { - // initialize RingBuffer - int bufferSize = ((int) bitsAllocator.getMaxSequence() + 1) << boostPower; - this.ringBuffer = new RingBuffer(bufferSize, paddingFactor); - LOGGER.info("Initialized ring buffer size:{}, paddingFactor:{}", bufferSize, paddingFactor); - - // initialize RingBufferPaddingExecutor - boolean usingSchedule = (scheduleInterval != null); - this.bufferPaddingExecutor = new BufferPaddingExecutor(ringBuffer, new BufferedUidProvider() { - @Override - public List provide(long momentInSecond) { - return nextIdsForOneSecond(momentInSecond); - } - }, usingSchedule); - if (usingSchedule) { - bufferPaddingExecutor.setScheduleInterval(scheduleInterval); - } - - LOGGER.info("Initialized BufferPaddingExecutor. Using schdule:{}, interval:{}", usingSchedule, scheduleInterval); - - // set rejected put/take handle policy - this.ringBuffer.setBufferPaddingExecutor(bufferPaddingExecutor); - if (rejectedPutBufferHandler != null) { - this.ringBuffer.setRejectedPutHandler(rejectedPutBufferHandler); - } - if (rejectedTakeBufferHandler != null) { - this.ringBuffer.setRejectedTakeHandler(rejectedTakeBufferHandler); - } - - // fill in all slots of the RingBuffer - bufferPaddingExecutor.paddingBuffer(); - - // start buffer padding threads - bufferPaddingExecutor.start(); - } - - /** - * Setters for spring property - */ - public void setBoostPower(int boostPower) { - Assert.isTrue(boostPower > 0, "Boost power must be positive!"); - this.boostPower = boostPower; - } - - public void setRejectedPutBufferHandler(RejectedPutBufferHandler rejectedPutBufferHandler) { - Assert.notNull(rejectedPutBufferHandler, "RejectedPutBufferHandler can't be null!"); - this.rejectedPutBufferHandler = rejectedPutBufferHandler; - } - - public void setRejectedTakeBufferHandler(RejectedTakeBufferHandler rejectedTakeBufferHandler) { - Assert.notNull(rejectedTakeBufferHandler, "RejectedTakeBufferHandler can't be null!"); - this.rejectedTakeBufferHandler = rejectedTakeBufferHandler; - } - - public void setScheduleInterval(long scheduleInterval) { - Assert.isTrue(scheduleInterval > 0, "Schedule interval must positive!"); - this.scheduleInterval = scheduleInterval; - } - -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/impl/DefaultUidGenerator.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/impl/DefaultUidGenerator.java deleted file mode 100644 index 949e943e6b..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/impl/DefaultUidGenerator.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.myzmds.ecp.core.uid.baidu.impl; - -import java.util.Date; -import java.util.concurrent.TimeUnit; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.InitializingBean; -import org.springframework.util.StringUtils; - -import com.myzmds.ecp.core.uid.baidu.BitsAllocator; -import com.myzmds.ecp.core.uid.baidu.UidGenerator; -import com.myzmds.ecp.core.uid.baidu.exception.UidGenerateException; -import com.myzmds.ecp.core.uid.baidu.utils.DateUtils; -import com.myzmds.ecp.core.uid.worker.WorkerIdAssigner; - -/** - * Represents an implementation of {@link UidGenerator} - * - * The unique id has 64bits (long), default allocated as blow:
    - *
  • sign: The highest bit is 0 - *
  • delta seconds: The next 28 bits, represents delta seconds since a customer epoch(2016-05-20 00:00:00.000). - * Supports about 8.7 years until to 2024-11-20 21:24:16 - *
  • worker id: The next 22 bits, represents the worker's id which assigns based on database, max id is about 420W - *
  • sequence: The next 13 bits, represents a sequence within the same second, max for 8192/s

    - * - * The {@link DefaultUidGenerator#parseUID(long)} is a tool method to parse the bits - * - *
    {@code
    - * +------+----------------------+----------------+-----------+
    - * | sign |     delta seconds    | worker node id | sequence  |
    - * +------+----------------------+----------------+-----------+
    - *   1bit          28bits              22bits         13bits
    - * }
    - * - * You can also specified the bits by Spring property setting. - *
  • timeBits: default as 28 - *
  • workerBits: default as 22 - *
  • seqBits: default as 13 - *
  • epochStr: Epoch date string format 'yyyy-MM-dd'. Default as '2016-05-20'

    - * - * Note that: The total bits must be 64 -1 - * - * @author yutianbao - */ -public class DefaultUidGenerator implements UidGenerator, InitializingBean { - private static final Logger LOGGER = LoggerFactory.getLogger(DefaultUidGenerator.class); - - /** Bits allocate */ - protected int timeBits = 28; - protected int workerBits = 22; - protected int seqBits = 13; - - /** Customer epoch, unit as second. For example 2016-05-20 (ms: 1463673600000)*/ - protected String epochStr = "2016-05-20"; - protected long epochSeconds = TimeUnit.MILLISECONDS.toSeconds(1463673600000L); - - /** Stable fields after spring bean initializing */ - protected BitsAllocator bitsAllocator; - protected long workerId; - - /** Volatile fields caused by nextId() */ - protected long sequence = 0L; - protected long lastSecond = -1L; - - /** Spring property */ - protected WorkerIdAssigner workerIdAssigner; - - @Override - public void afterPropertiesSet() throws Exception { - // initialize bits allocator - bitsAllocator = new BitsAllocator(timeBits, workerBits, seqBits); - - // initialize worker id - workerId = workerIdAssigner.assignWorkerId(); - if (workerId > bitsAllocator.getMaxWorkerId()) { - throw new RuntimeException("Worker id " + workerId + " exceeds the max " + bitsAllocator.getMaxWorkerId()); - } - - LOGGER.info("Initialized bits(1, {}, {}, {}) for workerID:{}", timeBits, workerBits, seqBits, workerId); - } - - @Override - public long getUID() throws UidGenerateException { - try { - return nextId(); - } catch (Exception e) { - LOGGER.error("Generate unique id exception. ", e); - throw new UidGenerateException(e); - } - } - - @Override - public String parseUID(long uid) { - long totalBits = BitsAllocator.TOTAL_BITS; - long signBits = bitsAllocator.getSignBits(); - long timestampBits = bitsAllocator.getTimestampBits(); - long workerIdBits = bitsAllocator.getWorkerIdBits(); - long sequenceBits = bitsAllocator.getSequenceBits(); - - // parse UID - long sequence = (uid << (totalBits - sequenceBits)) >>> (totalBits - sequenceBits); - long workerId = (uid << (timestampBits + signBits)) >>> (totalBits - workerIdBits); - long deltaSeconds = uid >>> (workerIdBits + sequenceBits); - - Date thatTime = new Date(TimeUnit.SECONDS.toMillis(epochSeconds + deltaSeconds)); - String thatTimeStr = DateUtils.formatByDateTimePattern(thatTime); - - // format as string - return String.format("{\"UID\":\"%d\",\"timestamp\":\"%s\",\"workerId\":\"%d\",\"sequence\":\"%d\"}", - uid, thatTimeStr, workerId, sequence); - } - - /** - * Get UID - * - * @return UID - * @throws UidGenerateException in the case: Clock moved backwards; Exceeds the max timestamp - */ - protected synchronized long nextId() { - long currentSecond = getCurrentSecond(); - - // Clock moved backwards, refuse to generate uid - if (currentSecond < lastSecond) { - long refusedSeconds = lastSecond - currentSecond; - throw new UidGenerateException("Clock moved backwards. Refusing for %d seconds", refusedSeconds); - } - - // At the same second, increase sequence - if (currentSecond == lastSecond) { - sequence = (sequence + 1) & bitsAllocator.getMaxSequence(); - // Exceed the max sequence, we wait the next second to generate uid - if (sequence == 0) { - currentSecond = getNextSecond(lastSecond); - } - - // At the different second, sequence restart from zero - } else { - sequence = 0L; - } - - lastSecond = currentSecond; - - // Allocate bits for UID - return bitsAllocator.allocate(currentSecond - epochSeconds, workerId, sequence); - } - - /** - * Get next millisecond - */ - private long getNextSecond(long lastTimestamp) { - long timestamp = getCurrentSecond(); - while (timestamp <= lastTimestamp) { - timestamp = getCurrentSecond(); - } - - return timestamp; - } - - /** - * Get current second - */ - private long getCurrentSecond() { - long currentSecond = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()); - if (currentSecond - epochSeconds > bitsAllocator.getMaxDeltaSeconds()) { - throw new UidGenerateException("Timestamp bits is exhausted. Refusing UID generate. Now: " + currentSecond); - } - - return currentSecond; - } - - /** - * Setters for spring property - */ - public void setWorkerIdAssigner(WorkerIdAssigner workerIdAssigner) { - this.workerIdAssigner = workerIdAssigner; - } - - public void setTimeBits(int timeBits) { - if (timeBits > 0) { - this.timeBits = timeBits; - } - } - - public void setWorkerBits(int workerBits) { - if (workerBits > 0) { - this.workerBits = workerBits; - } - } - - public void setSeqBits(int seqBits) { - if (seqBits > 0) { - this.seqBits = seqBits; - } - } - - public void setEpochStr(String epochStr) { - if (!StringUtils.isEmpty(epochStr)) { - this.epochStr = epochStr; - this.epochSeconds = TimeUnit.MILLISECONDS.toSeconds(DateUtils.parseByDayPattern(epochStr).getTime()); - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/package-info.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/package-info.java deleted file mode 100644 index db887094b0..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ - -/** - * github地址为https://github.com/baidu/uid-generator - * - */ -package com.myzmds.ecp.core.uid.baidu; \ No newline at end of file diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/utils/DateUtils.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/utils/DateUtils.java deleted file mode 100644 index 5fc3a1f24a..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/utils/DateUtils.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.myzmds.ecp.core.uid.baidu.utils; - -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -/** - * @ DateUtils.java - * @

    ʱ丨(SimpleDateFormat̲߳ȫģ˾̬)
    - * linhuaichuan1989@126.com - * @ʱ 201978 11:15:29 - * @汾 1.0.0 - * - * @޸ļ¼ - *
    - *     汾                       ޸ 		޸ 		 ޸
    - *     ----------------------------------------------
    - *     1.0.0 	 	201978             
    - *     ----------------------------------------------
    - * 
    - */ -public class DateUtils { - /** - * -ʽ - */ - public static final String DAY_PATTERN = "yyyy-MM-dd"; - - /** - * ʱ-ʽ - */ - public static final String DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss"; - - /** - * ʱ()-ʽ - */ - public static final String DATETIME_MS_PATTERN = "yyyy-MM-dd HH:mm:ss.SSS"; - - /** - * df - */ - private static ThreadLocal> dfMap = new ThreadLocal>() { - @Override - protected Map initialValue() { - return new HashMap(10); - } - }; - - /** - * @ getDateFormat - * @
    һDateFormat,ÿֻ߳newһpatternӦsdf
    - * @param pattern ʽ ʽ - * @return DateFormat - */ - private static DateFormat getDateFormat(final String pattern) { - Map tl = dfMap.get(); - DateFormat df = tl.get(pattern); - if (df == null) { - df = new SimpleDateFormat(pattern); - tl.put(pattern, df); - } - return df; - } - - /** - * @ formatByDateTimePattern - * @
    ȡ'yyyy-MM-dd HH:mm:ss'ʽʱַ
    - * @param date ʱ - * @return ʱַ - */ - public static String formatByDateTimePattern(Date date) { - return getDateFormat(DATETIME_PATTERN).format(date); - } - - /** - * @ parseByDayPattern - * @
    'yyyy-MM-dd'ʽʱ
    - * @param str ʱַ - * @return ʱ - */ - public static Date parseByDayPattern(String str) { - return parseDate(str, DAY_PATTERN); - } - - /** - * @ parseDate - * @
    ָʽʱ
    - * @param str ʱַ - * @param pattern ʽʽ - * @return ʱ - */ - public static Date parseDate(String str, String pattern) { - try { - return getDateFormat(pattern).parse(str); - } catch (ParseException e) { - throw new RuntimeException(e); - } - } -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/utils/DockerUtils.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/utils/DockerUtils.java deleted file mode 100644 index 09d2d169b0..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/utils/DockerUtils.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.myzmds.ecp.core.uid.baidu.utils; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.util.StringUtils; - -/** - * DockerUtils - * - * @author yutianbao - */ -public class DockerUtils { - private static final Logger LOGGER = LoggerFactory.getLogger(DockerUtils.class); - - /** Environment param keys */ - private static final String ENV_KEY_HOST = "JPAAS_HOST"; - private static final String ENV_KEY_PORT = "JPAAS_HTTP_PORT"; - private static final String ENV_KEY_PORT_ORIGINAL = "JPAAS_HOST_PORT_8080"; - - /** Docker host & port */ - private static String DOCKER_HOST = ""; - private static String DOCKER_PORT = ""; - - /** Whether is docker */ - private static boolean IS_DOCKER; - - static { - retrieveFromEnv(); - } - - /** - * Retrieve docker host - * - * @return empty string if not a docker - */ - public static String getDockerHost() { - return DOCKER_HOST; - } - - /** - * Retrieve docker port - * - * @return empty string if not a docker - */ - public static String getDockerPort() { - return DOCKER_PORT; - } - - /** - * Whether a docker - * - * @return - */ - public static boolean isDocker() { - return IS_DOCKER; - } - - /** - * Retrieve host & port from environment - */ - private static void retrieveFromEnv() { - // retrieve host & port from environment - DOCKER_HOST = System.getenv(ENV_KEY_HOST); - DOCKER_PORT = System.getenv(ENV_KEY_PORT); - - // not found from 'JPAAS_HTTP_PORT', then try to find from 'JPAAS_HOST_PORT_8080' - if (StringUtils.isEmpty(DOCKER_PORT)) { - DOCKER_PORT = System.getenv(ENV_KEY_PORT_ORIGINAL); - } - - boolean hasEnvHost = !StringUtils.isEmpty(DOCKER_HOST); - boolean hasEnvPort = !StringUtils.isEmpty(DOCKER_PORT); - - // docker can find both host & port from environment - if (hasEnvHost && hasEnvPort) { - IS_DOCKER = true; - - // found nothing means not a docker, maybe an actual machine - } else if (!hasEnvHost && !hasEnvPort) { - IS_DOCKER = false; - - } else { - LOGGER.error("Missing host or port from env for Docker. host:{}, port:{}", DOCKER_HOST, DOCKER_PORT); - throw new RuntimeException( - "Missing host or port from env for Docker. host:" + DOCKER_HOST + ", port:" + DOCKER_PORT); - } - } - -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/utils/EnumUtils.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/utils/EnumUtils.java deleted file mode 100644 index c2945b0cbe..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/utils/EnumUtils.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.myzmds.ecp.core.uid.baidu.utils; - -import org.springframework.util.Assert; - -/** - * EnumUtils provides the operations for {@link ValuedEnum} such as Parse, value of... - * - * @author yutianbao - */ -public class EnumUtils { - - /** - * Parse the bounded value into ValuedEnum - * - * @param clz - * @param value - * @return - */ - public static , V> T parse(Class clz, V value) { - Assert.notNull(clz, "clz can not be null"); - if (value == null) { - return null; - } - - for (T t : clz.getEnumConstants()) { - if (value.equals(t.value())) { - return t; - } - } - return null; - } - - /** - * Null-safe valueOf function - * - * @param - * @param enumType - * @param name - * @return - */ - public static > T valueOf(Class enumType, String name) { - if (name == null) { - return null; - } - - return Enum.valueOf(enumType, name); - } - -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/utils/NamingThreadFactory.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/utils/NamingThreadFactory.java deleted file mode 100644 index 381fddf060..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/utils/NamingThreadFactory.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.myzmds.ecp.core.uid.baidu.utils; - -import java.lang.Thread.UncaughtExceptionHandler; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.atomic.AtomicLong; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.util.ClassUtils; -import org.springframework.util.StringUtils; - -/** - * Named thread in ThreadFactory. If there is no specified name for thread, it - * will auto detect using the invoker classname instead. - * - * @author yutianbao - */ -public class NamingThreadFactory implements ThreadFactory { - private static final Logger LOGGER = LoggerFactory.getLogger(NamingThreadFactory.class); - - /** - * Thread name pre - */ - private String name; - /** - * Is daemon thread - */ - private boolean daemon; - /** - * UncaughtExceptionHandler - */ - private UncaughtExceptionHandler uncaughtExceptionHandler; - /** - * Sequences for multi thread name prefix - */ - private final ConcurrentHashMap sequences; - - /** - * Constructors - */ - public NamingThreadFactory() { - this(null, false, null); - } - - public NamingThreadFactory(String name) { - this(name, false, null); - } - - public NamingThreadFactory(String name, boolean daemon) { - this(name, daemon, null); - } - - public NamingThreadFactory(String name, boolean daemon, UncaughtExceptionHandler handler) { - this.name = name; - this.daemon = daemon; - this.uncaughtExceptionHandler = handler; - this.sequences = new ConcurrentHashMap(); - } - - @Override - public Thread newThread(Runnable r) { - Thread thread = new Thread(r); - thread.setDaemon(this.daemon); - - // If there is no specified name for thread, it will auto detect using the invoker classname instead. - // Notice that auto detect may cause some performance overhead - String prefix = this.name; - if (StringUtils.isEmpty(prefix)) { - prefix = getInvoker(2); - } - thread.setName(prefix + "-" + getSequence(prefix)); - - // no specified uncaughtExceptionHandler, just do logging. - if (this.uncaughtExceptionHandler != null) { - thread.setUncaughtExceptionHandler(this.uncaughtExceptionHandler); - } else { - thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { - @Override - public void uncaughtException(Thread t, Throwable e) { - LOGGER.error("unhandled exception in thread: " + t.getId() + ":" + t.getName(), e); - } - }); - } - - return thread; - } - - /** - * Get the method invoker's class name - * - * @param depth - * @return - */ - private String getInvoker(int depth) { - Exception e = new Exception(); - StackTraceElement[] stes = e.getStackTrace(); - if (stes.length > depth) { - return ClassUtils.getShortName(stes[depth].getClassName()); - } - return getClass().getSimpleName(); - } - - /** - * Get sequence for different naming prefix - * - * @param invoker - * @return - */ - private long getSequence(String invoker) { - AtomicLong r = this.sequences.get(invoker); - if (r == null) { - r = new AtomicLong(0); - AtomicLong previous = this.sequences.putIfAbsent(invoker, r); - if (previous != null) { - r = previous; - } - } - - return r.incrementAndGet(); - } - - /** - * Getters & Setters - */ - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public boolean isDaemon() { - return daemon; - } - - public void setDaemon(boolean daemon) { - this.daemon = daemon; - } - - public UncaughtExceptionHandler getUncaughtExceptionHandler() { - return uncaughtExceptionHandler; - } - - public void setUncaughtExceptionHandler(UncaughtExceptionHandler handler) { - this.uncaughtExceptionHandler = handler; - } -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/utils/PaddedAtomicLong.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/utils/PaddedAtomicLong.java deleted file mode 100644 index a448600479..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/utils/PaddedAtomicLong.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.myzmds.ecp.core.uid.baidu.utils; - -import java.util.concurrent.atomic.AtomicLong; - -/** - * Represents a padded {@link AtomicLong} to prevent the FalseSharing problem

    - * - * The CPU cache line commonly be 64 bytes, here is a sample of cache line after padding:
    - * 64 bytes = 8 bytes (object reference) + 6 * 8 bytes (padded long) + 8 bytes (a long value) - * - * @author yutianbao - */ -public class PaddedAtomicLong extends AtomicLong { - private static final long serialVersionUID = -3415778863941386253L; - - /** Padded 6 long (48 bytes) */ - public volatile long p1, p2, p3, p4, p5, p6 = 7L; - - /** - * Constructors from {@link AtomicLong} - */ - public PaddedAtomicLong() { - super(); - } - - public PaddedAtomicLong(long initialValue) { - super(initialValue); - } - - /** - * To prevent GC optimizations for cleaning unused padded references - */ - public long sumPaddingToPreventOptimization() { - return p1 + p2 + p3 + p4 + p5 + p6; - } - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/utils/ValuedEnum.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/utils/ValuedEnum.java deleted file mode 100644 index f038f84812..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/baidu/utils/ValuedEnum.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.myzmds.ecp.core.uid.baidu.utils; - -/** - * {@code ValuedEnum} defines an enumeration which is bounded to a value, you - * may implements this interface when you defines such kind of enumeration, that - * you can use {@link EnumUtils} to simplify parse and valueOf operation. - * - * @author yutianbao - */ -public interface ValuedEnum { - /** - * 获取值 - * @return 枚举映射的值 - */ - T value(); -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/extend/annotation/Uid.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/extend/annotation/Uid.java deleted file mode 100644 index fcf91b0a75..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/extend/annotation/Uid.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.myzmds.ecp.core.uid.extend.annotation; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * - * @类名称 Uid.java - * @类描述

    uid生成注解
    - * @作者 庄梦蝶殇 linhuaichuan1989@126.com - * @创建时间 2018年8月31日 下午4:18:51 - * @版本 1.00 - * - * @修改记录 - *
    - *     版本                       修改人 		修改日期 		 修改内容描述
    - *     ----------------------------------------------
    - *     1.00 	庄梦蝶殇 	2018年8月31日             
    - *     ----------------------------------------------
    - * 
    - */ -@Target({ElementType.FIELD}) -@Retention(RetentionPolicy.RUNTIME) -@Documented -public @interface Uid { - /** - * uid 生成模式 - * @方法名称 model - * @功能描述
    uid 生成模式
    - */ - UidModel model() default UidModel.step; - - /** - * 前缀 - * @方法名称 prefix - * @功能描述
    前缀
    - */ - String prefix() default ""; - - /** - * 是否数字类型 - * @方法名称 isNum - * @功能描述
    是否数字类型
    - */ - boolean isNum() default true; -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/extend/annotation/UidModel.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/extend/annotation/UidModel.java deleted file mode 100644 index 28225a797c..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/extend/annotation/UidModel.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.myzmds.ecp.core.uid.extend.annotation; - -/** - * @类名称 UidModel.java - * @类描述
    id生产模式
    - * @作者 庄梦蝶殇 linhuaichuan1989@126.com - * @创建时间 2018年9月3日 上午9:54:09 - * @版本 1.00 - * - * @修改记录 - *
    - *     版本                       修改人 		修改日期 		 修改内容描述
    - *     ----------------------------------------------
    - *     1.00 	庄梦蝶殇 	2018年9月3日             
    - *     ----------------------------------------------
    - * 
    - */ -public enum UidModel { - /** - * 步长自增(空实现,依赖数据库步长设置) - */ - step("step"), - /** - * 分段批量(基于leaf) - */ - segment("segment"), - /** - * Snowflake算法(源自twitter) - */ - snowflake("snowflake"), - /** - * 百度UidGenerator - */ - baidu("baidu"); - - private UidModel(String name) { - this.name = name; - } - - private String name; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/extend/strategy/BaiduUidStrategy.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/extend/strategy/BaiduUidStrategy.java deleted file mode 100644 index 4fcb13ca1b..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/extend/strategy/BaiduUidStrategy.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.myzmds.ecp.core.uid.extend.strategy; - -import java.util.HashMap; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Lookup; -import org.springframework.util.StringUtils; - -import com.myzmds.ecp.core.uid.baidu.UidGenerator; -import com.myzmds.ecp.core.uid.extend.annotation.UidModel; - -/** - * baidu uid生成策略 - * @类名称 BaiduUidStrategy.java - * @类描述
    baidu uid生成策略
    - * @作者 庄梦蝶殇 linhuaichuan1989@126.com - * @创建时间 2018年4月27日 下午8:47:27 - * @版本 1.00 - * - * @修改记录 - *
    - *     版本                       修改人 		修改日期 		 修改内容描述
    - *     ----------------------------------------------
    - *     1.00 	庄梦蝶殇 	2018年4月27日             
    - *     ----------------------------------------------
    - * 
    - */ -public class BaiduUidStrategy implements IUidStrategy { - - private static Map generatorMap = new HashMap<>(); - - @Autowired - private UidGenerator uidGenerator; - - @Override - public UidModel getName() { - return UidModel.baidu; - } - - /** - * 获取uid生成器 - * @方法名称 getUidGenerator - * @功能描述
    获取uid生成器
    - * @param prefix 前缀 - * @return uid生成器 - */ - public UidGenerator getUidGenerator(String prefix) { - if (StringUtils.isEmpty(prefix)) { - return uidGenerator; - } - UidGenerator generator = generatorMap.get(prefix); - if (null == generator) { - synchronized (generatorMap) { - if (null == generator) { - generator = getGenerator(); - } - generatorMap.put(prefix, generator); - } - } - return generator; - } - - @Override - public long getUID(String group) { - return getUidGenerator(group).getUID(); - } - - @Override - public String parseUID(long uid, String group) { - return getUidGenerator(group).parseUID(uid); - } - - /** - * @方法名称 getGenerator - * @功能描述
    多实例返回uidGenerator(返回值不重要,动态注入)
    - * @return - */ - @Lookup - public UidGenerator getGenerator() { - return null; - } - - public UidGenerator getUidGenerator() { - return uidGenerator; - } - - public void setUidGenerator(UidGenerator uidGenerator) { - this.uidGenerator = uidGenerator; - } -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/extend/strategy/IUidStrategy.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/extend/strategy/IUidStrategy.java deleted file mode 100644 index 24dbe19607..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/extend/strategy/IUidStrategy.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.myzmds.ecp.core.uid.extend.strategy; - -import com.myzmds.ecp.core.uid.extend.annotation.UidModel; - -/** - * @类名称 IUidStrategy.java - * @类描述
    uid策略接口
    - * @作者 庄梦蝶殇 linhuaichuan1989@126.com - * @创建时间 2018年8月31日 下午5:27:38 - * @版本 1.00 - * - * @修改记录 - *
    - *     版本                       修改人 		修改日期 		 修改内容描述
    - *     ----------------------------------------------
    - *     1.00 	庄梦蝶殇 	2018年8月31日             
    - *     ----------------------------------------------
    - * 
    - */ -public interface IUidStrategy { - /** - * 策略名 - * @方法名称 getName - * @功能描述
    策略名
    - * @return - */ - public UidModel getName(); - - /** - * @方法名称 getUID - * @功能描述
    获取ID
    - * @param group 分组 - * @return id - */ - public long getUID(String group); - - /** - * @方法名称 parseUID - * @功能描述
    解析ID
    - * @param uid - * @param group 分组 - * @return 输出json字符串:{\"UID\":\"\",\"timestamp\":\"\",\"workerId\":\"\",\"dataCenterId\":\"\",\"sequence\":\"\"} - */ - String parseUID(long uid, String group); -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/extend/strategy/LeafSegmentStrategy.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/extend/strategy/LeafSegmentStrategy.java deleted file mode 100644 index 8b4e94f489..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/extend/strategy/LeafSegmentStrategy.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.myzmds.ecp.core.uid.extend.strategy; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.jdbc.core.JdbcTemplate; - -import com.myzmds.ecp.core.uid.extend.annotation.UidModel; -import com.myzmds.ecp.core.uid.leaf.ISegmentService; -import com.myzmds.ecp.core.uid.leaf.SegmentServiceImpl; - -/** - * @类名称 LeafSegmentStrategy.java - * @类描述
    Leaf分段批量Id策略(可配置asynLoadingSegment-异步标识)
    - * @作者 庄梦蝶殇 linhuaichuan1989@126.com - * @创建时间 2018年9月5日 上午11:35:53 - * @版本 1.00 - * - * @修改记录 - *
    - *     版本                       修改人 		修改日期 		 修改内容描述
    - *     ----------------------------------------------
    - *     1.00 	庄梦蝶殇 	2018年9月5日             
    - *     ----------------------------------------------
    - * 
    - */ -public class LeafSegmentStrategy implements IUidStrategy { - private final static String MSG_UID_PARSE = "{\"UID\":\"%s\"}"; - - /** - * 生成器集合 - */ - protected static Map generatorMap = new ConcurrentHashMap<>(); - - @Autowired - protected JdbcTemplate jdbcTemplate; - - private boolean asynLoadingSegment = true; - - /** - * 获取uid生成器 - * @方法名称 getUidGenerator - * @功能描述
    获取uid生成器
    - * @param prefix 前缀 - * @return uid生成器 - */ - public ISegmentService getSegmentService(String prefix) { - ISegmentService segmentService = generatorMap.get(prefix); - if (null == segmentService) { - synchronized (generatorMap) { - if (null == segmentService) { - segmentService = new SegmentServiceImpl(jdbcTemplate, prefix); - } - generatorMap.put(prefix, segmentService); - } - } - return segmentService; - } - - @Override - public UidModel getName() { - return UidModel.segment; - } - - @Override - public long getUID(String group) { - return getSegmentService(group).getId(); - } - - @Override - public String parseUID(long uid, String group) { - return String.format(MSG_UID_PARSE, uid); - } - - public boolean isAsynLoadingSegment() { - return asynLoadingSegment; - } - - public void setAsynLoadingSegment(boolean asynLoadingSegment) { - this.asynLoadingSegment = asynLoadingSegment; - } - - public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { - this.jdbcTemplate = jdbcTemplate; - } -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/extend/strategy/SpringStrategy.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/extend/strategy/SpringStrategy.java deleted file mode 100644 index 4f3e5c2a57..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/extend/strategy/SpringStrategy.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.myzmds.ecp.core.uid.extend.strategy; - -import com.myzmds.ecp.core.uid.extend.annotation.UidModel; -import com.myzmds.ecp.core.uid.leaf.ISegmentService; -import com.myzmds.ecp.core.uid.spring.ColumnMaxValueIncrementer; - -/** - * @类名称 SpringStrategy.java - * @类描述
    spring 分段批量Id策略(可配置asynLoadingSegment-异步标识)
    - * @作者 庄梦蝶殇 linhuaichuan1989@126.com - * @创建时间 2019年3月15日 下午7:48:58 - * @版本 1.0.0 - * - * @修改记录 - *
    - *     版本                       修改人 		修改日期 		 修改内容描述
    - *     ----------------------------------------------
    - *     1.0.0 	       庄梦蝶殇 	2019年3月15日             
    - *     ----------------------------------------------
    - * 
    - */ -public class SpringStrategy extends LeafSegmentStrategy { - @Override - public UidModel getName() { - return UidModel.step; - } - - @Override - public ISegmentService getSegmentService(String prefix) { - ISegmentService segmentService = generatorMap.get(prefix); - if (null == segmentService) { - synchronized (generatorMap) { - if (null == segmentService) { - segmentService = new ColumnMaxValueIncrementer(jdbcTemplate, prefix); - } - generatorMap.put(prefix, segmentService); - } - } - return segmentService; - } - -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/extend/strategy/TwitterSnowflakeStrategy.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/extend/strategy/TwitterSnowflakeStrategy.java deleted file mode 100644 index 25143c3c0a..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/extend/strategy/TwitterSnowflakeStrategy.java +++ /dev/null @@ -1,146 +0,0 @@ -package com.myzmds.ecp.core.uid.extend.strategy; - -import java.lang.management.ManagementFactory; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import com.myzmds.ecp.core.uid.extend.annotation.UidModel; -import com.myzmds.ecp.core.uid.twitter.SnowflakeIdWorker; -import com.myzmds.ecp.core.uid.util.NetUtils; -import com.myzmds.ecp.core.uid.worker.WorkerIdAssigner; - -/** - * @类名称 TwitterSnowflakeStrategy.java - * @类描述
    Twitter策略(workerId的获取可使用WorkerIdAssigner的各种实例)
    - * @作者 庄梦蝶殇 linhuaichuan1989@126.com - * @创建时间 2018年8月31日 下午5:05:15 - * @版本 1.00 - * - * @修改记录 - *
    - *     版本                       修改人 		修改日期 		 修改内容描述
    - *     ----------------------------------------------
    - *     1.00 	庄梦蝶殇 	2018年8月31日             
    - *     ----------------------------------------------
    - * 
    - */ -public class TwitterSnowflakeStrategy implements IUidStrategy { - /** - * 生成器集合 - */ - private static Map generatorMap = new ConcurrentHashMap<>(); - - /** - * 机器ID - */ - private Long workerId; - - /** - * 数据中心id - */ - private Long datacenterId; - - protected WorkerIdAssigner assigner; - - @Override - public UidModel getName() { - return UidModel.snowflake; - } - - @Override - public long getUID(String group) { - return getSnowflakeId(group).nextId(); - } - - @Override - public String parseUID(long uid, String group) { - return getSnowflakeId(group).parseUID(uid); - } - - /** - * 获取uid生成器 - * @方法名称 getSnowflakeId - * @功能描述
    获取uid生成器
    - * @param prefix 前缀 - * @return uid生成器 - */ - public SnowflakeIdWorker getSnowflakeId(String prefix) { - SnowflakeIdWorker snowflakeIdWorker = generatorMap.get(prefix); - if (null == snowflakeIdWorker) { - synchronized (generatorMap) { - if (null == snowflakeIdWorker) { - // 数据中心id--默认取机器码 - Long realDid = null == datacenterId ? getMachineNum(31) : datacenterId; - // 机器id--默认取进程id - long realWid; - if (null != assigner) { - realWid = assigner.assignWorkerId(); - } else if (null != workerId) { - realWid = workerId; - } else { - realWid = getProcessNum(realDid, 31); - } - snowflakeIdWorker = new SnowflakeIdWorker(realWid, realDid); - snowflakeIdWorker.setClock(true); - } - generatorMap.put(prefix, snowflakeIdWorker); - } - } - return snowflakeIdWorker; - } - - /** - * 获取机器码 - * - * @param maxId 最大值 - */ - public static long getMachineNum(long maxId) { - byte[] mac = NetUtils.getMachineNum(); - long id = 0L; - if (mac == null) { - id = 1L; - } else { - id = ((0x000000FF & (long)mac[mac.length - 1]) | (0x0000FF00 & (((long)mac[mac.length - 2]) << 8))) >> 6; - id = id % (maxId + 1); - } - return id; - } - - /** - * 获取 进程id - * - * @param dataCenterId 数据中心id - * @param maxWorkerId 最大机器id - */ - public static long getProcessNum(long dataCenterId, long maxWorkerId) { - StringBuilder mpid = new StringBuilder(); - mpid.append(dataCenterId); - String name = ManagementFactory.getRuntimeMXBean().getName(); - if (null != name && !"".equals(name)) { - // 获取 jvm Pid - mpid.append(name.split("@")[0]); - } - // dataCenterId + PID 的 hashcode 获取16个低位 - return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1); - } - - public Long getWorkerId() { - return workerId; - } - - public void setWorkerId(Long workerId) { - this.workerId = workerId; - } - - public Long getDatacenterId() { - return datacenterId; - } - - public void setDatacenterId(Long datacenterId) { - this.datacenterId = datacenterId; - } - - public void setAssigner(WorkerIdAssigner assigner) { - this.assigner = assigner; - } -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/leaf/ISegmentService.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/leaf/ISegmentService.java deleted file mode 100644 index 5da648f751..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/leaf/ISegmentService.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.myzmds.ecp.core.uid.leaf; - -/** - * @类名称 IdLeafService.java - * @类描述
    Leaf理论的分段批量id生成服务
    - * @作者 庄梦蝶殇 linhuaichuan1989@126.com - * @创建时间 2018年9月5日 上午11:46:37 - * @版本 1.00 - * - * @修改记录 - *
    - *     版本                       修改人 		修改日期 		 修改内容描述
    - *     ----------------------------------------------
    - *     1.00 	庄梦蝶殇 	2018年9月5日             
    - *     ----------------------------------------------
    - * 
    - */ -public interface ISegmentService { - /** - * 获取id - * @return id - */ - public Long getId(); - - /** - * 设置业务标识 - * @param bizTag 业务标识 - */ - public void setBizTag(String bizTag); -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/leaf/IdSegment.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/leaf/IdSegment.java deleted file mode 100644 index 7667ed34c0..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/leaf/IdSegment.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.myzmds.ecp.core.uid.leaf; - -import java.util.Date; - -/** - * @类名称 IdSegment.java - * @类描述
    分段ID实体
    - * @作者 庄梦蝶殇 linhuaichuan1989@126.com - * @创建时间 2018年9月6日 下午3:58:29 - * @版本 1.00 - * - * @修改记录 - *
    - *     版本                       修改人 		修改日期 		 修改内容描述
    - *     ----------------------------------------------
    - *     1.00 	庄梦蝶殇 	2018年9月6日             
    - *     ----------------------------------------------
    - * 
    - */ -public class IdSegment { - /** - * 最小id - */ - private Long minId; - - /** - * 最大id - */ - private Long maxId; - - /** - * 步长 - */ - private Long step; - - /** - * 中间值(缓存阈值-用于更新双buffer的阈值。目前阈值比是50%) - */ - private Long middleId; - - /** - * 上次更新时间 - */ - private Date lastUpdateTime; - - /** - * 本次更新时间 - */ - private Date currentUpdateTime; - - public IdSegment() { - - } - - public Date getLastUpdateTime() { - return lastUpdateTime; - } - - public void setLastUpdateTime(Date lastUpdateTime) { - this.lastUpdateTime = lastUpdateTime; - } - - public Date getCurrentUpdateTime() { - return currentUpdateTime; - } - - public void setCurrentUpdateTime(Date currentUpdateTime) { - this.currentUpdateTime = currentUpdateTime; - } - - public Long getMiddleId() { - if (this.middleId == null) { - this.middleId = this.maxId - (step / 2); - } - return middleId; - } - - public Long getMinId() { - if (this.minId == null) { - if (this.maxId != null && this.step != null) { - this.minId = this.maxId - this.step; - } else { - throw new RuntimeException("maxid or step is null"); - } - } - return minId; - } - - public Long getMaxId() { - return maxId; - } - - public void setMaxId(Long maxId) { - this.maxId = maxId; - } - - public Long getStep() { - return step; - } - - public void setStep(Long step) { - this.step = step; - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/leaf/SegmentServiceImpl.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/leaf/SegmentServiceImpl.java deleted file mode 100644 index 81792e848d..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/leaf/SegmentServiceImpl.java +++ /dev/null @@ -1,258 +0,0 @@ -package com.myzmds.ecp.core.uid.leaf; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Date; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.FutureTask; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.locks.ReentrantLock; - -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowCallbackHandler; - -import com.myzmds.ecp.core.uid.baidu.utils.NamingThreadFactory; - -/** - * @类名称 SegmentServiceImpl.java - * @类描述
    Segment 策略id生成实现类
    - * @作者 庄梦蝶殇 linhuaichuan1989@126.com - * @创建时间 2018年9月6日 下午4:28:36 - * @版本 1.0.2 - * - * @修改记录 - *
    - *     版本                       修改人 		修改日期 		 修改内容描述
    - *     ----------------------------------------------
    - *     1.0.0    庄梦蝶殇    2018年09月06日             
    - *     1.0.1    庄梦蝶殇    2019年02月28日             更改阈值碰撞时重复执行问题
    - *     1.0.2    庄梦蝶殇    2019年03月06日             突破并发数被step限制的bug
    - *     ----------------------------------------------
    - * 
    - */ -public class SegmentServiceImpl implements ISegmentService { - - /** - * 线程名-心跳 - */ - public static final String THREAD_BUFFER_NAME = "leaf_buffer_sw"; - - private static ReentrantLock lock = new ReentrantLock(); - - /** - * 创建线程池 - */ - private ExecutorService taskExecutor; - - /** - * 两段buffer - */ - private volatile IdSegment[] segment = new IdSegment[2]; - - /** - * 缓冲切换标识(true-切换,false-不切换) - */ - private volatile boolean sw; - - /** - * 当前id - */ - private AtomicLong currentId; - - private JdbcTemplate jdbcTemplate; - - /** - * 业务标识 - */ - private String bizTag; - - /** - * 异步标识(true-异步,false-同步) - */ - private boolean asynLoadingSegment = true; - - /** - * 异步线程任务 - */ - FutureTask asynLoadSegmentTask = null; - - public SegmentServiceImpl(JdbcTemplate jdbcTemplate, String bizTag) { - this.jdbcTemplate = jdbcTemplate; - if (taskExecutor == null) { - taskExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(), new NamingThreadFactory(THREAD_BUFFER_NAME)); - } - this.bizTag = bizTag; - // 获取第一段buffer缓冲 - segment[0] = doUpdateNextSegment(bizTag); - setSw(false); - // 初始id - currentId = new AtomicLong(segment[index()].getMinId()); - } - - @Override - public Long getId() { - // 1.0.1 fix:uid:ecp-190227001 #1(github)更改阈值(middle与max)lock在高速碰撞时的可能多次执行 - // 下一个id - Long nextId = null; - if (segment[index()].getMiddleId().equals(currentId.longValue()) || segment[index()].getMaxId().equals(currentId.longValue())) { - try { - lock.lock(); - // 阈值50%时,加载下一个buffer - if (segment[index()].getMiddleId().equals(currentId.longValue())) { - thresholdHandler(); - nextId = currentId.incrementAndGet(); - } - if (segment[index()].getMaxId().equals(currentId.longValue())) { - fullHandler(); - nextId = currentId.incrementAndGet(); - } - } finally { - lock.unlock(); - } - } - nextId = null == nextId ? currentId.incrementAndGet() : nextId; - // 1.0.2 fix:uid:ecp-190306001 突破并发数被step限制的bug - return nextId <= segment[index()].getMaxId() ? nextId : getId(); - } - - /** - * 阈值处理,是否同/异步加载下一个buffer的值(即更新DB) - */ - private void thresholdHandler() { - if (asynLoadingSegment) { - // 异步处理-启动线程更新DB,由线程池执行 - asynLoadSegmentTask = new FutureTask<>(new Callable() { - @Override - public Boolean call() - throws Exception { - final int currentIndex = reIndex(); - segment[currentIndex] = doUpdateNextSegment(bizTag); - return true; - } - }); - taskExecutor.submit(asynLoadSegmentTask); - } else { - // 同步处理,直接更新DB - final int currentIndex = reIndex(); - segment[currentIndex] = doUpdateNextSegment(bizTag); - } - } - - /** - * buffer使用完时切换buffer。 - */ - public void fullHandler() { - if (asynLoadingSegment) { - // 异步时,需判断 异步线程的状态(是否已经执行) - try { - asynLoadSegmentTask.get(); - } catch (Exception e) { - e.printStackTrace(); - // 未执行,强制同步切换 - segment[reIndex()] = doUpdateNextSegment(bizTag); - } - } - // 设置切换标识 - setSw(!isSw()); - // 进行切换 - currentId = new AtomicLong(segment[index()].getMinId()); - } - - /** - * 获取下一个buffer的索引 - */ - private int reIndex() { - return isSw() ? 0 : 1; - } - - /** - * 获取当前buffer的索引 - */ - private int index() { - return isSw() ? 1 : 0; - } - - /** - * @方法名称 doUpdateNextSegment - * @功能描述
    更新下一个buffer
    - * @param bizTag 业务标识 - * @return 下一个buffer的分段id实体 - */ - private IdSegment doUpdateNextSegment(String bizTag) { - try { - return updateId(bizTag); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - private IdSegment updateId(String bizTag) - throws Exception { - String querySql = "select step, max_id, last_update_time, current_update_time from id_segment where biz_tag=?"; - String updateSql = "update id_segment set max_id=?, last_update_time=?, current_update_time=now() where biz_tag=? and max_id=?"; - final IdSegment currentSegment = new IdSegment(); - this.jdbcTemplate.query(querySql, new String[] {bizTag}, new RowCallbackHandler() { - @Override - public void processRow(ResultSet rs) - throws SQLException { - Long step = null; - Long currentMaxId = null; - step = rs.getLong("step"); - currentMaxId = rs.getLong("max_id"); - Date lastUpdateTime = new Date(); - if (rs.getTimestamp("last_update_time") != null) { - lastUpdateTime = (java.util.Date)rs.getTimestamp("last_update_time"); - } - Date currentUpdateTime = new Date(); - if (rs.getTimestamp("current_update_time") != null) { - currentUpdateTime = (java.util.Date)rs.getTimestamp("current_update_time"); - } - currentSegment.setStep(step); - currentSegment.setMaxId(currentMaxId); - currentSegment.setLastUpdateTime(lastUpdateTime); - currentSegment.setCurrentUpdateTime(currentUpdateTime); - } - }); - Long newMaxId = currentSegment.getMaxId() + currentSegment.getStep(); - int row = this.jdbcTemplate.update(updateSql, new Object[] {newMaxId, currentSegment.getCurrentUpdateTime(), bizTag, currentSegment.getMaxId()}); - if (row == 1) { - IdSegment newSegment = new IdSegment(); - newSegment.setStep(currentSegment.getStep()); - newSegment.setMaxId(newMaxId); - return newSegment; - } else { - // 递归,直至更新成功 - return updateId(bizTag); - } - } - - public void setTaskExecutor(ExecutorService taskExecutor) { - this.taskExecutor = taskExecutor; - } - - private boolean isSw() { - return sw; - } - - private void setSw(boolean sw) { - this.sw = sw; - } - - public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { - this.jdbcTemplate = jdbcTemplate; - } - - @Override - public void setBizTag(String bizTag) { - this.bizTag = bizTag; - } - - public void setAsynLoadingSegment(boolean asynLoadingSegment) { - this.asynLoadingSegment = asynLoadingSegment; - } -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/spring/ColumnMaxValueIncrementer.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/spring/ColumnMaxValueIncrementer.java deleted file mode 100644 index 74de2c1369..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/spring/ColumnMaxValueIncrementer.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.myzmds.ecp.core.uid.spring; - -import org.springframework.dao.DataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.support.incrementer.DataFieldMaxValueIncrementer; - -import com.myzmds.ecp.core.uid.leaf.SegmentServiceImpl; - -/** - * @类名称 ColumnMaxValueIncrementer.java - * @类描述
    Spring 增量id实现(基于Segment策略)
    - * @作者 庄梦蝶殇 linhuaichuan1989@126.com - * @创建时间 2018年9月12日 下午3:55:17 - * @版本 1.0.0 - * - * @修改记录 - *
    - *     版本                       修改人 		修改日期 		 修改内容描述
    - *     ----------------------------------------------
    - *     1.0.0 		庄梦蝶殇 	2018年9月12日             
    - *     ----------------------------------------------
    - * 
    - */ -public class ColumnMaxValueIncrementer extends SegmentServiceImpl implements DataFieldMaxValueIncrementer { - - /** - * 填充长度 - */ - protected int paddingLength = 8; - - public ColumnMaxValueIncrementer(JdbcTemplate jdbcTemplate, String bizTag) { - super(jdbcTemplate, bizTag); - } - - @Override - public int nextIntValue() - throws DataAccessException { - return getId().intValue(); - } - - @Override - public long nextLongValue() - throws DataAccessException { - return getId(); - } - - @Override - public String nextStringValue() - throws DataAccessException { - String s = Long.toString(getId()); - int len = s.length(); - if (len < this.paddingLength) { - StringBuilder sb = new StringBuilder(this.paddingLength); - for (int i = 0; i < this.paddingLength - len; i++) { - sb.append('0'); - } - sb.append(s); - s = sb.toString(); - } - return s; - } - - public void setPaddingLength(int paddingLength) { - this.paddingLength = paddingLength; - } - - public int getPaddingLength() { - return this.paddingLength; - } -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/twitter/SnowflakeIdWorker.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/twitter/SnowflakeIdWorker.java deleted file mode 100644 index 5093f3746b..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/twitter/SnowflakeIdWorker.java +++ /dev/null @@ -1,251 +0,0 @@ -package com.myzmds.ecp.core.uid.twitter; - -import java.text.SimpleDateFormat; -import java.util.Date; - -/** - * twitter Snowflake 算法,提供uid生成器 - * @类名称 SnowflakeIdWorker.java - * @类描述
    twitter Snowflake 算法,提供uid生成器:
    - * 
    - * SnowFlake的结构如下(每部分用-分开): - *
    - * 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 - *
    - * 1位标识,由于long基本类型在Java中是带符号的,最高位是符号位,正数是0,负数是1,所以id一般是正数,最高位是0 - *
    - * 41位时间截(毫秒级),注意,41位时间截不是存储当前时间的时间截,而是存储时间截的差值(当前时间截 - 开始时间截) - *
    - * 这里的的开始时间截,一般是我们的id生成器开始使用的时间,由我们程序来指定的(如下下面程序IdWorker类的startTime属性)。 - * 41位的时间截,可以使用69年,年T = (1L << 41) / (1000L * 60 * 60 * 24 * 365) = 69 - *
    - * 10位的数据机器位,可以部署在1024个节点,包括5位datacenterId和5位workerId
    - *
    - * 12位序列,毫秒内的计数,12位的计数顺序号支持每个节点每毫秒(同一机器,同一时间截)产生4096个ID序号
    - *
    - *
    - * 加起来刚好64位,为一个Long型。
    - *
    - * @作者 庄梦蝶殇 linhuaichuan1989@126.com - * @创建时间 2018年3月23日 下午6:31:48 - * @版本 1.0.2 - * - * @修改记录 - *
    - *     版本                       修改人 		修改日期 		 修改内容描述
    - *     ----------------------------------------------
    - *     1.0.0 	庄梦蝶殇 	2018年3月23日         参考多版本Snowflake算法进行合并
    - *     1.0.1    庄梦蝶殇     2018年8月31日         引进闰秒回拨处理机制     
    - *     1.0.2    庄梦蝶殇     2018年9月3日           新增parseId(反解析方法)        
    - *     ----------------------------------------------
    - * 
    - */ -public class SnowflakeIdWorker { - // ============================== Constants=========================================== - /** - * 回拨超时错误 - */ - private final static String ERROR_CLOCK_BACK = "时间回拨,拒绝为超出%d毫秒生成ID"; - - private final static String ERROR_ATTR_LIMIT = "%s属性的范围为0-%d"; - - private final static String MSG_UID_PARSE = "{\"UID\":\"%s\",\"timestamp\":\"%s\",\"workerId\":\"%d\",\"dataCenterId\":\"%d\",\"sequence\":\"%d\"}"; - - private final static String DATE_PATTERN_DEFAULT = "yyyy-MM-dd HH:mm:ss"; - - // ==============================Fields=========================================== - /** 开始时间截 (2017-12-25),用于用当前时间戳减去这个时间戳,算出偏移量 */ - private final long twepoch = 1514131200000L; - - /** 机器id所占的位数(表示只允许workId的范围为:0-1023) */ - private final long workerIdBits = 5L; - - /** 数据标识id所占的位数 */ - private final long datacenterIdBits = 5L; - - /** 支持的最大机器id,结果是31 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数) */ - public final long maxWorkerId = -1L ^ (-1L << workerIdBits); - - /** 支持的最大数据标识id,结果是31 */ - private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); - - /** 序列在id中占的位数 (表示只允许sequenceId的范围为:0-4095)*/ - private final long sequenceBits = 12L; - - /** 机器ID向左移12位 */ - private final long workerIdShift = sequenceBits; - - /** 数据标识id向左移17位(12+5) */ - private final long datacenterIdShift = sequenceBits + workerIdBits; - - /** 时间截向左移22位(5+5+12) */ - private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; - - /** 生成序列的掩码,(防止溢出:位与运算保证计算的结果范围始终是 0-4095,0b111111111111=0xfff=4095) */ - private final long sequenceMask = -1L ^ (-1L << sequenceBits); - - /** 工作机器ID(0~31) */ - private long workerId; - - /** 数据中心ID(0~31) */ - private long datacenterId; - - /** 毫秒内序列(0~4095) */ - private long sequence = 0L; - - /** 上次生成ID的时间截 */ - private long lastTimestamp = -1L; - - private boolean isClock = false; - - public void setClock(boolean clock) { - isClock = clock; - } - - // ==============================Constructors===================================== - /** - * 构造函数 - * - * @param workerId 工作ID (0~31) - * @param datacenterId 数据中心ID (0~31) - */ - public SnowflakeIdWorker(long workerId, long datacenterId) { - if (workerId > maxWorkerId || workerId < 0) { - throw new IllegalArgumentException(String.format(ERROR_ATTR_LIMIT, "workerId", maxWorkerId)); - } - if (datacenterId > maxDatacenterId || datacenterId < 0) { - throw new IllegalArgumentException(String.format(ERROR_ATTR_LIMIT, "datacenterId", maxDatacenterId)); - } - this.workerId = workerId; - this.datacenterId = datacenterId; - } - - // ==============================Methods========================================== - /** - * 获得下一个ID (该方法是线程安全的) - * - * @return SnowflakeId - */ - public synchronized long nextId() { - long timestamp = timeGen(); - // 闰秒:如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常 - if (timestamp < lastTimestamp) { - long offset = lastTimestamp - timestamp; - if (offset <= 5) { - try { - // 时间偏差大小小于5ms,则等待两倍时间 - wait(offset << 1); - timestamp = timeGen(); - if (timestamp < lastTimestamp) { - // 还是小于,抛异常并上报 - throw new RuntimeException(String.format(ERROR_CLOCK_BACK, lastTimestamp - timestamp)); - } - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - } else { - throw new RuntimeException(String.format(ERROR_CLOCK_BACK, lastTimestamp - timestamp)); - } - } - - // 解决跨毫秒生成ID序列号始终为偶数的缺陷:如果是同一时间生成的,则进行毫秒内序列 - if (lastTimestamp == timestamp) { - // 通过位与运算保证计算的结果范围始终是 0-4095 - sequence = (sequence + 1) & sequenceMask; - // 毫秒内序列溢出 - if (sequence == 0) { - // 阻塞到下一个毫秒,获得新的时间戳 - timestamp = tilNextMillis(lastTimestamp); - } - } else { - // 时间戳改变,毫秒内序列重置 - sequence = 0L; - } - - // 上次生成ID的时间截 - lastTimestamp = timestamp; - - /* - * 1.左移运算是为了将数值移动到对应的段(41、5、5,12那段因为本来就在最右,因此不用左移) - * 2.然后对每个左移后的值(la、lb、lc、sequence)做位或运算,是为了把各个短的数据合并起来,合并成一个二进制数 - * 3.最后转换成10进制,就是最终生成的id(64位的ID) - */ - return ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence; - } - - /** - * @方法名称 parseUID - * @功能描述
    反解析UID
    - */ - public String parseUID(Long uid) { - // 总位数 - long totalBits = 64L; - // 标识 - long signBits = 1L; - // 时间戳 - long timestampBits = 41L; - // 解析Uid:标识 -- 时间戳 -- 数据中心 -- 机器码 --序列 - long sequence = (uid << (totalBits - sequenceBits)) >>> (totalBits - sequenceBits); - long dataCenterId = (uid << (timestampBits + signBits)) >>> (totalBits - datacenterIdBits); - long workerId = (uid << (timestampBits + signBits + datacenterIdBits)) >>> (totalBits - workerIdBits); - long deltaSeconds = uid >>> (datacenterIdBits + workerIdBits + sequenceBits); - // 时间处理(补上开始时间戳) - Date thatTime = new Date(twepoch + deltaSeconds); - String date = new SimpleDateFormat(DATE_PATTERN_DEFAULT).format(thatTime); - // 格式化输出 - return String.format(MSG_UID_PARSE, uid, date, workerId, dataCenterId, sequence); - } - - /** - * @方法名称 parseUID - * @功能描述
    反解析UID(字符串截取,性能相对差;不推荐使用)
    - */ - public String parseUID(String uid) { - uid = Long.toBinaryString(Long.parseLong(uid)); - int len = uid.length(); - /* 解析Uid:标识 -- 时间戳 -- 数据中心 -- 机器码 --序列 */ - // sequence起始数 - int sequenceStart = len < workerIdShift ? 0 : (int)(len - workerIdShift); - // worker起始数 - int workerStart = len < datacenterIdShift ? 0 : (int)(len - datacenterIdShift); - // 时间起始数 - int timeStart = len < timestampLeftShift ? 0 : (int)(len - timestampLeftShift); - String sequence = uid.substring(sequenceStart, len); - String workerId = sequenceStart == 0 ? "0" : uid.substring(workerStart, sequenceStart); - String dataCenterId = workerStart == 0 ? "0" : uid.substring(timeStart, workerStart); - // 时间处理(补上开始时间戳) - String time = timeStart == 0 ? "0" : uid.substring(0, timeStart); - Date timeDate = new Date(Long.parseLong(time, 2) + twepoch); - String date = new SimpleDateFormat(DATE_PATTERN_DEFAULT).format(timeDate); - // 格式化输出 - return String.format(MSG_UID_PARSE, uid, date, Integer.valueOf(workerId, 2), Integer.valueOf(dataCenterId, 2), Integer.valueOf(sequence, 2)); - } - - /** - * 保证返回的毫秒数在参数之后(阻塞到下一个毫秒,直到获得新的时间戳) - * - * @param lastTimestamp 上次生成ID的时间截 - * @return 当前时间戳 - */ - protected long tilNextMillis(long lastTimestamp) { - long timestamp = timeGen(); - while (timestamp <= lastTimestamp) { - timestamp = timeGen(); - } - return timestamp; - } - - /** - * 获得系统当前毫秒数 - * - * @return 当前时间(毫秒) - */ - protected long timeGen() { - if (isClock) { - // 解决高并发下获取时间戳的性能问题 - return SystemClock.now(); - } else { - return System.currentTimeMillis(); - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/twitter/SystemClock.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/twitter/SystemClock.java deleted file mode 100644 index 0cb1fe9ee2..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/twitter/SystemClock.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.myzmds.ecp.core.uid.twitter; - -import java.sql.Timestamp; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; - -import com.myzmds.ecp.core.uid.baidu.utils.NamingThreadFactory; - -/** - * 高并发场景下System.currentTimeMillis()的性能问题的优化 - *

    - *

    - * System.currentTimeMillis()的调用比new一个普通对象要耗时的多(参加https://www.jianshu.com/p/3fbe607600a5) - *

    - * System.currentTimeMillis()之所以慢是因为去跟系统打了一次交道 - *

    - * 后台定时更新时钟,JVM退出时,线程自动回收 - *

    - * 10亿:43410,206,210.72815533980582% - *

    - * 1亿:4699,29,162.0344827586207% - *

    - * 1000万:480,12,40.0% - *

    - * 100万:50,10,5.0% - *

    - * - * @author lry - */ -public class SystemClock { - - /** - * 线程名--系统时钟 - */ - public static final String THREAD_CLOCK_NAME="System Clock"; - - private final long period; - - private final AtomicLong now; - - private SystemClock(long period) { - this.period = period; - this.now = new AtomicLong(System.currentTimeMillis()); - scheduleClockUpdating(); - } - - private static class InstanceHolder { - public static final SystemClock INSTANCE = new SystemClock(1); - } - - private static SystemClock instance() { - return InstanceHolder.INSTANCE; - } - - private void scheduleClockUpdating() { - ScheduledExecutorService scheduledpool = new ScheduledThreadPoolExecutor(1, new NamingThreadFactory(THREAD_CLOCK_NAME, true)); - scheduledpool.scheduleAtFixedRate(() -> { - now.set(System.currentTimeMillis()); - }, period, period, TimeUnit.MILLISECONDS); - } - - private long currentTimeMillis() { - return now.get(); - } - - public static long now() { - return instance().currentTimeMillis(); - } - - public static String nowDate() { - return new Timestamp(instance().currentTimeMillis()).toString(); - } -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/util/NetUtils.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/util/NetUtils.java deleted file mode 100644 index aec3ca9da9..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/util/NetUtils.java +++ /dev/null @@ -1,170 +0,0 @@ -package com.myzmds.ecp.core.uid.util; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.ServerSocket; -import java.net.UnknownHostException; -import java.util.Enumeration; -import java.util.Random; -import java.util.regex.Pattern; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @类名称 NetUtils.java - * @类描述

    网络ip辅助类(本机)
    - * @作者 庄梦蝶殇 linhuaichuan1989@126.com - * @创建时间 2018年9月3日 下午5:04:05 - * @版本 1.00 - * - * @修改记录 - *
    - *     版本                       修改人 		修改日期 		 修改内容描述
    - *     ----------------------------------------------
    - *     1.00 	庄梦蝶殇 	2018年9月3日             
    - *     ----------------------------------------------
    - * 
    - */ -public class NetUtils { - public static Logger logger = LoggerFactory.getLogger(NetUtils.class); - - public static final String ANYHOST = "0.0.0.0"; - - public static final String LOCALHOST = "127.0.0.1"; - - private static final int RND_PORT_START = 30000; - - private static final int RND_PORT_RANGE = 10000; - - private static final Random RANDOM = new Random(System.currentTimeMillis()); - - private static final int MAX_PORT = 65535; - - private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$"); - - /** - * 获取本地地址 - */ - public static InetAddress getLocalInetAddress() { - InetAddress localAddress; - try { - localAddress = InetAddress.getLocalHost(); - if (isValidAddress(localAddress)) { - return localAddress; - } - } catch (UnknownHostException e) { - logger.error("本地地址获取失败: " + e.getMessage()); - } - return getLocalLanAddress(); - } - - /** - * 获取Lan地址 - */ - public static InetAddress getLocalLanAddress() { - try { - // 1、遍历所有的网络接口 - Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); - if (interfaces != null) { - while (interfaces.hasMoreElements()) { - NetworkInterface network = interfaces.nextElement(); - if (network.isLoopback()) { - // 排除loopback类型地址 - continue; - } - Enumeration addresses = network.getInetAddresses(); - if (addresses == null) { - continue; - } - // 2、在所有的接口下再遍历IP - while (addresses.hasMoreElements()) { - InetAddress address = addresses.nextElement(); - if (isValidAddress(address)) { - return address; - } - } - } - } - } catch (Exception e) { - logger.error("无法确定Lan地址: " + e.getMessage()); - } - return null; - } - - /** - * 获取机器码 - */ - public static byte[] getMachineNum() { - try { - InetAddress ip = NetUtils.getLocalInetAddress(); - NetworkInterface network = NetworkInterface.getByInetAddress(ip); - if (network != null) { - byte[] mac = network.getHardwareAddress(); - if (null != mac) { - return mac; - } - } - } catch (Exception e) { - logger.error("机器码获取失败:" + e.getMessage()); - } - return null; - } - - /** - * 是否有效地址 - */ - private static boolean isValidAddress(InetAddress address) { - if (address == null || address.isLoopbackAddress()) { - return false; - } - String name = address.getHostAddress(); - return (name != null && !ANYHOST.equals(name) && !LOCALHOST.equals(name) && IP_PATTERN.matcher(name).matches()); - } - - public static int getRandomPort() { - return RND_PORT_START + RANDOM.nextInt(RND_PORT_RANGE); - } - - public static int getAvailablePort() { - ServerSocket ss = null; - try { - ss = new ServerSocket(); - ss.bind(null); - return ss.getLocalPort(); - } catch (IOException e) { - return getRandomPort(); - } finally { - if (ss != null) { - try { - ss.close(); - } catch (IOException e) { - } - } - } - } - - public static int getAvailablePort(int port) { - if (port <= 0) { - return getAvailablePort(); - } - for (int i = port; i < MAX_PORT; i++) { - ServerSocket ss = null; - try { - ss = new ServerSocket(i); - return i; - } catch (IOException e) { - // continue - } finally { - if (ss != null) { - try { - ss.close(); - } catch (IOException e) { - } - } - } - } - return port; - } -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/util/WorkerIdUtils.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/util/WorkerIdUtils.java deleted file mode 100644 index 746b4eb0eb..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/util/WorkerIdUtils.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.myzmds.ecp.core.uid.util; - -import java.io.File; -import java.io.IOException; -import java.net.ServerSocket; - -/** - * @类名称 WorkerIdUtils.java - * @类描述
    workid 文件操作类
    - * @作者 庄梦蝶殇 linhuaichuan1989@126.com - * @创建时间 2019年1月16日 下午2:31:31 - * @版本 1.0.0 - * - * @修改记录 - *
    - *     版本                       修改人 		修改日期 		 修改内容描述
    - *     ----------------------------------------------
    - *     1.0.0 		庄梦蝶殇 	2019年1月16日             
    - *     ----------------------------------------------
    - * 
    - */ -public class WorkerIdUtils { - /** - * workerID文件 分隔符 - */ - public static final String WORKER_SPLIT = "_"; - - /** - * @方法名称 getPidName - * @功能描述
    获取workId文件名
    - * @param pidPort 使用端口(同机多uid应用时区分端口) - * @param socket - * @return - */ - public static String getPidName(Integer pidPort, ServerSocket socket) { - String pidName = NetUtils.getLocalInetAddress().getHostAddress(); - if (-1 != pidPort) { - // 占用端口 - pidPort = null != pidPort && pidPort > 0 ? pidPort : NetUtils.getAvailablePort(); - try { - socket = new ServerSocket(pidPort); - } catch (IOException e) { - throw new RuntimeException("接口占用失败!"); - } - } - return pidName + WorkerIdUtils.WORKER_SPLIT + pidPort; - } - - /** - * @方法名称 getPid - * @功能描述
    查找pid文件,根据前缀获取workid
    - * @param pidHome workerID文件存储路径 - * @param prefix workerID文件前缀 - * @return workerID值 - */ - public static Long getPid(String pidHome, String prefix) { - String pid = null; - File home = new File(pidHome); - if (home.exists() && home.isDirectory()) { - File[] files = home.listFiles(); - for (File file : files) { - if (file.getName().startsWith(prefix)) { - pid = file.getName(); - break; - } - } - if (null != pid) { - return Long.valueOf(pid.substring(pid.lastIndexOf(WORKER_SPLIT) + 1)); - } - } else { - home.mkdirs(); - } - return null; - } - - /** - * @方法名称 sleepMs - * @功能描述
    回拨时间睡眠等待
    - * @param ms 平均心跳时间 - * @param diff 回拨差时间 - */ - public static void sleepMs(long ms, long diff) { - try { - Thread.sleep(ms); - } catch (InterruptedException e) { - - } - diff += ms; - if (diff < 0) { - sleepMs(ms, diff); - } - } - - /** - * @方法名称 writePidFile - * @功能描述
    创建workerID文件(workerID文件已经存在,则不创建,返回一个false;如果没有,则返回true)
    - * @param name - */ - public static void writePidFile(String name) { - File pidFile = new File(name); - try { - pidFile.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); - } - } -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/worker/AbstractIntervalWorkId.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/worker/AbstractIntervalWorkId.java deleted file mode 100644 index 881533fc03..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/worker/AbstractIntervalWorkId.java +++ /dev/null @@ -1,164 +0,0 @@ -package com.myzmds.ecp.core.uid.worker; - -import java.io.File; -import java.net.ServerSocket; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.springframework.beans.factory.InitializingBean; - -import com.myzmds.ecp.core.uid.baidu.utils.NamingThreadFactory; -import com.myzmds.ecp.core.uid.util.WorkerIdUtils; - -/** - * @类名称 AbstractIntervalWorkId.java - * @类描述
    WorkId生成基类
    - * @作者 庄梦蝶殇 linhuaichuan1989@126.com - * @创建时间 2019年1月17日 下午4:21:17 - * @版本 1.0.0 - * - * @修改记录 - *
    - *     版本                       修改人 		修改日期 		 修改内容描述
    - *     ----------------------------------------------
    - *     1.0.0 		庄梦蝶殇 	2019年1月17日             
    - *     ----------------------------------------------
    - * 
    - */ -public abstract class AbstractIntervalWorkId implements WorkerIdAssigner, InitializingBean { - /** - * 本地workid文件跟目录 - */ - public static final String PID_ROOT = "/data/pids/"; - - /** - * 线程名-心跳 - */ - public static final String THREAD_HEARTBEAT_NAME = "zk_heartbeat"; - - /** - * 心跳原子标识 - */ - protected AtomicBoolean active = new AtomicBoolean(false); - - /** - * 心跳间隔 - */ - protected Long interval = 3000L; - - /** - * workerID 文件存储路径 - */ - protected String pidHome = PID_ROOT; - - /** - * 因子ID - */ - protected Long workerId; - - /** - * 使用端口(同机多uid应用时区分端口) - */ - private Integer pidPort = -1; - - protected String pidName; - - protected ServerSocket socket; - - @Override - public void afterPropertiesSet() - throws Exception { - try { - /** - * 1、检查workId文件是否存在。文件名为ip:port-redis顺序编号 - */ - pidName = WorkerIdUtils.getPidName(pidPort, socket); - workerId = WorkerIdUtils.getPid(pidHome, pidName); - /** - * 3、获取本地时间,跟uid 机器节点心跳列表的时间平均值做比较(uid 机器节点心跳列表 用于存储活跃节点的上报时间,每隔一段时间上报一次临时节点时间) - */ - long diff = System.currentTimeMillis() - action(); - if (diff < 0) { - // 当前时间小于活跃节点的平均心跳时间,证明出现时间回拨,进入等待。 - WorkerIdUtils.sleepMs(interval * 2, diff); - } - if (null != workerId) { - startHeartBeatThread(); - // 赋值workerId - WorkerIdUtils.writePidFile(pidHome + File.separatorChar + pidName + WorkerIdUtils.WORKER_SPLIT + workerId); - } - } catch (Exception e) { - active.set(false); - if (null != socket) { - socket.close(); - } - throw e; - } - } - - /** - * @方法名称 action - * @功能描述
    workId文件不存在时的操作
    - * @return 机器节点列表的 活跃时间平均值 - */ - public abstract long action(); - - /** - * @方法名称 startHeartBeatThread - * @功能描述
    心跳线程,用于每隔一段时间上报一次临时节点时间
    - */ - protected void startHeartBeatThread() { - ScheduledExecutorService scheduledpool = new ScheduledThreadPoolExecutor(1, new NamingThreadFactory(THREAD_HEARTBEAT_NAME, true)); - scheduledpool.scheduleAtFixedRate(() -> { - if (active.get() == false) { - scheduledpool.shutdownNow(); - } else if (where()) { - report(); - } - }, 0L, interval, TimeUnit.MILLISECONDS); - } - - /** - * @方法名称 where - * @功能描述
    心跳条件
    - * @return true:执行心跳上报,false:空动作 - */ - public abstract boolean where(); - - /** - * @方法名称 report - * @功能描述
    心跳上报
    - */ - public abstract void report(); - - @Override - public long assignWorkerId() { - return workerId; - } - - public Long getInterval() { - return interval; - } - - public void setInterval(Long interval) { - this.interval = interval; - } - - public String getPidHome() { - return pidHome; - } - - public void setPidHome(String pidHome) { - this.pidHome = pidHome; - } - - public Integer getPidPort() { - return pidPort; - } - - public void setPidPort(Integer pidPort) { - this.pidPort = pidPort; - } -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/worker/DisposableWorkerIdAssigner.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/worker/DisposableWorkerIdAssigner.java deleted file mode 100644 index e8f3bfb3c4..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/worker/DisposableWorkerIdAssigner.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.myzmds.ecp.core.uid.worker; - -import java.util.Random; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.transaction.annotation.Transactional; - -import com.myzmds.ecp.core.uid.baidu.utils.DockerUtils; -import com.myzmds.ecp.core.uid.util.NetUtils; -import com.myzmds.ecp.core.uid.worker.dao.WorkerNodeDAO; -import com.myzmds.ecp.core.uid.worker.entity.WorkerNode; - -/** - * DB编号分配器(利用数据库来管理) - * @author yutianbao - */ -public class DisposableWorkerIdAssigner implements WorkerIdAssigner { - private static final Logger LOGGER = LoggerFactory.getLogger(DisposableWorkerIdAssigner.class); - - private WorkerNodeDAO workerNodeDAO; - - /** - * Assign worker id base on database.

    - * If there is host name & port in the environment, we considered that the node runs in Docker container
    - * Otherwise, the node runs on an actual machine. - * - * @return assigned worker id - */ - @Transactional(rollbackFor = Exception.class) - @Override - public long assignWorkerId() { - // build worker node entity - WorkerNode workerNodeEntity = buildWorkerNode(); - - // add worker node for new (ignore the same IP + PORT) - workerNodeDAO.addWorkerNode(workerNodeEntity); - LOGGER.info("Add worker node:" + workerNodeEntity); - - return workerNodeEntity.getId(); - } - - /** - * Build worker node entity by IP and PORT - */ - private WorkerNode buildWorkerNode() { - WorkerNode workerNodeEntity = new WorkerNode(); - if (DockerUtils.isDocker()) { - workerNodeEntity.setType(WorkerNodeType.CONTAINER.value()); - workerNodeEntity.setHostName(DockerUtils.getDockerHost()); - workerNodeEntity.setPort(DockerUtils.getDockerPort()); - - } else { - workerNodeEntity.setType(WorkerNodeType.ACTUAL.value()); - workerNodeEntity.setHostName(NetUtils.getLocalInetAddress().getHostAddress()); - workerNodeEntity.setPort(System.currentTimeMillis() + "-" + RANDOM.nextInt(100000)); - } - - return workerNodeEntity; - } - - private static final Random RANDOM = new Random(); -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/worker/RedisWorkIdAssigner.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/worker/RedisWorkIdAssigner.java deleted file mode 100644 index 9f85483c9a..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/worker/RedisWorkIdAssigner.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.myzmds.ecp.core.uid.worker; - -import java.util.Set; -import java.util.concurrent.TimeUnit; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.redis.core.RedisTemplate; - -/** - * @类名称 RedisWorkIdAssigner.java - * @类描述

    Redis编号分配器
    - * @作者 庄梦蝶殇 linhuaichuan1989@126.com - * @创建时间 2019年1月16日 下午3:32:07 - * @版本 1.0.1 - * - * @修改记录 - *
    - *     版本                       修改人 		修改日期 		 修改内容描述
    - *     ----------------------------------------------
    - *     1.0.0 		庄梦蝶殇 	2019年1月16日             
    - *     1.0.1        庄梦蝶殇    2019年1月18日      完善代码
    - *     ----------------------------------------------
    - * 
    - */ -public class RedisWorkIdAssigner extends AbstractIntervalWorkId { - /** - * redis上uid 机器节点的key前缀 - */ - public static final String UID_ROOT = "ecp:uid:"; - - /** - * uid 机器节点列表 - */ - public static final String UID_FOREVER = UID_ROOT.concat("forever"); - - /** - * uid 活跃节点心跳列表(用于保存活跃节点及活跃心跳) - */ - public static final String UID_TEMPORARY = UID_ROOT.concat("temporary:"); - - @Autowired - private RedisTemplate redisTemplate; - - @Override - public long action() { - /** - * 1、文件不存在,检查redis上是否存在ip:port的机器节点 - */ - Set uidWork = redisTemplate.opsForZSet().range(UID_FOREVER, 0, -1); - if (null == workerId) { - // a、 检查redis上是否存在ip:port的节点,存在,获取节点的顺序编号 - Long i = 0L; - for (Object item : uidWork) { - i++; - if (item.toString().equals(pidName)) { - workerId = i; - break; - } - } - // b、 不存在,创建ip:port节点 - if (null == workerId) { - workerId = (long)uidWork.size(); - // 使用zset 时间排序,保证有序性 - redisTemplate.opsForZSet().add(UID_FOREVER, pidName, System.currentTimeMillis()); - uidWork.add(pidName); - } - } - /** - * 2、创建临时机器节点的时间 - */ - redisTemplate.opsForValue().set(UID_TEMPORARY + pidName, System.currentTimeMillis(), interval * 3, TimeUnit.MILLISECONDS); - active.set(true); - - /** - * 3、获取本地时间,跟uid 活跃节点心跳列表的时间平均值做比较(uid 活跃节点心跳列表 用于存储活跃节点的上报时间,每隔一段时间上报一次临时节点时间) - */ - Long sumTime = 0L; - if (null != uidWork && uidWork.size() > 0) { - for (Object itemName : uidWork) { - Object itemTime = redisTemplate.opsForValue().get(UID_TEMPORARY + itemName); - sumTime += null == itemTime ? 0 : Long.valueOf(itemTime.toString()); - } - return sumTime / uidWork.size(); - } - return 0; - } - - @Override - public boolean where() { - return null != workerId; - } - - @Override - public void report() { - redisTemplate.opsForValue().set(UID_TEMPORARY + pidName, System.currentTimeMillis(), interval * 3, TimeUnit.MILLISECONDS); - } -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/worker/SimpleWorkerIdAssigner.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/worker/SimpleWorkerIdAssigner.java deleted file mode 100644 index 6ba8f9dd47..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/worker/SimpleWorkerIdAssigner.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.myzmds.ecp.core.uid.worker; - -/** - * @类名称 SimpleWorkerIdAssigner.java - * @类描述
    简单编号分配器(即不用workerId)
    - * @作者 庄梦蝶殇 linhuaichuan1989@126.com - * @创建时间 2018年9月5日 上午11:43:45 - * @版本 1.00 - * - * @修改记录 - *
    - *     版本                       修改人 		修改日期 		 修改内容描述
    - *     ----------------------------------------------
    - *     1.00 	庄梦蝶殇 	2018年9月5日             
    - *     ----------------------------------------------
    - * 
    - */ -public class SimpleWorkerIdAssigner implements WorkerIdAssigner { - - @Override - public long assignWorkerId() { - return 0; - } -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/worker/WorkerIdAssigner.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/worker/WorkerIdAssigner.java deleted file mode 100644 index 67cd00c2db..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/worker/WorkerIdAssigner.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.myzmds.ecp.core.uid.worker; - -/** - * Represents a worker id assigner for {@link com.myzmds.ecp.core.uid.baidu.impl.DefaultUidGenerator} - * - * @author yutianbao - */ -public interface WorkerIdAssigner { - - /** - * Assign worker id for {@link com.myzmds.ecp.core.uid.baidu.impl.DefaultUidGenerator} - * - * @return assigned worker id - */ - long assignWorkerId(); - -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/worker/WorkerNodeType.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/worker/WorkerNodeType.java deleted file mode 100644 index 763780483d..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/worker/WorkerNodeType.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.myzmds.ecp.core.uid.worker; - -import com.myzmds.ecp.core.uid.baidu.utils.ValuedEnum; - -/** - * WorkerNodeType - *
  • CONTAINER: Such as Docker - *
  • ACTUAL: Actual machine - * - * @author yutianbao - */ -public enum WorkerNodeType implements ValuedEnum { - /** - * docker容器节点 - */ - CONTAINER(1), - /** - * 普通节点 - */ - ACTUAL(2); - - /** - * Lock type - */ - private final Integer type; - - /** - * Constructor with field of type - */ - private WorkerNodeType(Integer type) { - this.type = type; - } - - @Override - public Integer value() { - return type; - } - -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/worker/ZkWorkerIdAssigner.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/worker/ZkWorkerIdAssigner.java deleted file mode 100644 index 3032b40ce3..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/worker/ZkWorkerIdAssigner.java +++ /dev/null @@ -1,176 +0,0 @@ -package com.myzmds.ecp.core.uid.worker; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.util.List; - -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.KeeperException; -import org.apache.zookeeper.WatchedEvent; -import org.apache.zookeeper.Watcher; -import org.apache.zookeeper.ZooDefs.Ids; -import org.apache.zookeeper.ZooKeeper; -import org.apache.zookeeper.data.Stat; - -/** - * @类名称 ZkWorkerIdAssigner.java - * @类描述
    zk编号分配器{可设置interval-心跳间隔、pidHome-workerId文件存储目录、zkAddress-zk地址、pidPort-使用端口(默认不开,同机多uid应用时区分端口)}
    - * @作者 庄梦蝶殇 linhuaichuan1989@126.com - * @创建时间 2018年4月27日 下午8:14:21 - * @版本 2.1.0 - * - * @修改记录 - *
    - *     版本                       修改人 		修改日期 		 修改内容描述
    - *     ----------------------------------------------
    - *     1.0.0 	庄梦蝶殇 	2018年04月27日             利用zk的版本实现workid
    - *     2.0.0    庄梦蝶殇      2018年09月04日             引入leaf的理念基于zkclient进行开发
    - *     2.1.0    庄梦蝶殇      2019年03月27日             使用原生Zookeeper。去除zkclient依赖
    - *     ----------------------------------------------
    - * 
    - */ -public class ZkWorkerIdAssigner extends AbstractIntervalWorkId { - public static final String ZK_SPLIT = "/"; - - /** - * ZK上uid根目录 - */ - public static final String UID_ROOT = "/ecp-uid"; - - /** - * 持久顺序节点根目录(用于保存节点的顺序编号) - */ - public static final String UID_FOREVER = UID_ROOT.concat("/forever"); - - /** - * 临时节点根目录(用于保存活跃节点及活跃心跳) - */ - public static final String UID_TEMPORARY = UID_ROOT.concat("/temporary"); - - /** - * 本地workid文件跟目录 - */ - public static final String PID_ROOT = "/data/pids/"; - - /** - * session失效时间 - */ - public static final int SESSION_TIMEOUT = 3000; - - /** - * connection连接时间 - */ - public static final int CONNECTION_TIMEOUT = 30000; - - /** - * zk客户端 - */ - private ZooKeeper zkClient; - - /** - * zk注册地址 - */ - private String zkAddress = "127.0.0.1:2181"; - - /** - * 临时节点名,用于上报时间使用 - */ - private String temporaryNode; - - @Override - public long action() { - try { - zkClient = new ZooKeeper(zkAddress, SESSION_TIMEOUT, new Watcher() { - @Override - public void process(WatchedEvent event) { - - } - }); - if (null == zkClient.exists(UID_ROOT, false)) { - zkClient.create(UID_ROOT, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); - } - String workNode = UID_FOREVER + ZK_SPLIT + pidName; - - /** - * 2、文件不存在,检查zk上是否存在ip:port的节点 - */ - if (null == zkClient.exists(UID_FOREVER, false)) { - zkClient.create(UID_FOREVER, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); - } - if (null == workerId || null != zkClient.exists(workNode, false)) { - // a、 检查zk上是否存在ip:port的节点,存在,获取节点的顺序编号 - List uidWork = zkClient.getChildren(UID_FOREVER, false); - for (String nodePath : uidWork) { - if (nodePath.startsWith(pidName)) { - workerId = Long.valueOf(nodePath.substring(nodePath.length() - 10)); - break; - } - } - // b、 不存在,创建ip:port节点 - if (null == workerId) { - String nodePath = zkClient.create(workNode, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL); - workerId = Long.valueOf(nodePath.substring(nodePath.length() - 10)); - } - } - - /** - * 3、创建临时节点 - */ - if (null == zkClient.exists(UID_TEMPORARY, false)) { - zkClient.create(UID_TEMPORARY, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); - } - - temporaryNode = zkClient.create(UID_TEMPORARY + ZK_SPLIT + workerId, longToBytes(System.currentTimeMillis()), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); - active.set(true); - - /** - * 4、获取本地时间,跟zk临时节点列表的时间平均值做比较(zk临时节点用于存储活跃节点的上报时间,每隔一段时间上报一次临时节点时间) - */ - List activeNodes = zkClient.getChildren(UID_TEMPORARY, false); - Long sumTime = 0L; - for (String itemNode : activeNodes) { - Long nodeTime = bytesToLong(zkClient.getData(UID_TEMPORARY + ZK_SPLIT + itemNode, false, new Stat())); - sumTime += nodeTime; - } - return sumTime / activeNodes.size(); - } catch (KeeperException | InterruptedException | IOException e) { - e.printStackTrace(); - } - return System.currentTimeMillis(); - } - - @Override - public boolean where() { - return null != workerId && null != zkClient; - } - - @Override - public void report() { - try { - zkClient.setData(temporaryNode, longToBytes(System.currentTimeMillis()), -1); - } catch (KeeperException | InterruptedException e) { - e.printStackTrace(); - } - } - - public String getZkAddress() { - return zkAddress; - } - - public void setZkAddress(String zkAddress) { - this.zkAddress = zkAddress; - } - - private static ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES); - - public static byte[] longToBytes(long x) { - buffer.putLong(0, x); - return buffer.array(); - } - - public static long bytesToLong(byte[] bytes) { - buffer.put(bytes, 0, bytes.length); - buffer.flip();// need flip - return buffer.getLong(); - } -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/worker/dao/WorkerNodeDAO.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/worker/dao/WorkerNodeDAO.java deleted file mode 100644 index 352f008e32..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/worker/dao/WorkerNodeDAO.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.myzmds.ecp.core.uid.worker.dao; - -import java.sql.ResultSet; -import java.sql.SQLException; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowCallbackHandler; - -import com.myzmds.ecp.core.uid.worker.entity.WorkerNode; - -/** - * DAO for M_WORKER_NODE - * - * @author yutianbao - */ -public class WorkerNodeDAO { - - @Autowired - private JdbcTemplate jdbcTemplate; - - /** - * Get {@link WorkerNode} by node host - * - * @param host - * @param port - * @return - */ - public WorkerNode getWorkerNodeByHostPort(String host, String port) { - final WorkerNode workerNode = new WorkerNode(); - String querySql = "select * from WORKER_NODE where HOST_NAME = ? AND PORT = ? "; - this.jdbcTemplate.query(querySql, new String[] {host, port}, new RowCallbackHandler() { - @Override - public void processRow(ResultSet rs) - throws SQLException { - workerNode.setId(rs.getLong("ID")); - workerNode.setHostName(rs.getString("HOST_NAME")); - workerNode.setPort(rs.getString("PORT")); - workerNode.setType(rs.getInt("TYPE")); - workerNode.setLaunchDateDate(rs.getDate("LAUNCH_DATE")); - workerNode.setModified(rs.getDate("MODIFIED")); - workerNode.setCreated(rs.getDate("CREATED")); - } - }); - return workerNode; - } - - /** - * Add {@link WorkerNode} - * - * @param workerNode - */ - public void addWorkerNode(WorkerNode workerNode) { - String sql = "INSERT INTO WORKER_NODE(HOST_NAME, PORT, TYPE, LAUNCH_DATE, MODIFIED, CREATED) " + " VALUES (?, ?, ?, ?, NOW(), NOW())"; - this.jdbcTemplate.update(sql, new Object[] {workerNode.getHostName(), workerNode.getPort(), workerNode.getType(), workerNode.getLaunchDate()}); - } - -} diff --git a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/worker/entity/WorkerNode.java b/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/worker/entity/WorkerNode.java deleted file mode 100644 index c8a58af850..0000000000 --- a/jun_java_plugins/jun_uid/src/main/java/com/myzmds/ecp/core/uid/worker/entity/WorkerNode.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.myzmds.ecp.core.uid.worker.entity; - -import java.util.Date; - -import com.myzmds.ecp.core.uid.worker.WorkerNodeType; - -import lombok.ToString; - -/** - * Entity for M_WORKER_NODE - * - * @author yutianbao - */ -@ToString -public class WorkerNode { - - /** - * Entity unique id (table unique) - */ - private long id; - - /** - * Type of CONTAINER: HostName, ACTUAL : IP. - */ - private String hostName; - - /** - * Type of CONTAINER: Port, ACTUAL : Timestamp + Random(0-10000) - */ - private String port; - - /** - * type of {@link WorkerNodeType} - */ - private int type; - - /** - * Worker launch date, default now - */ - private Date launchDate = new Date(); - - /** - * Created time - */ - private Date created; - - /** - * Last modified - */ - private Date modified; - - /** - * Getters & Setters - */ - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getHostName() { - return hostName; - } - - public void setHostName(String hostName) { - this.hostName = hostName; - } - - public String getPort() { - return port; - } - - public void setPort(String port) { - this.port = port; - } - - public int getType() { - return type; - } - - public void setType(int type) { - this.type = type; - } - - public Date getLaunchDate() { - return launchDate; - } - - public void setLaunchDateDate(Date launchDate) { - this.launchDate = launchDate; - } - - public Date getCreated() { - return created; - } - - public void setCreated(Date created) { - this.created = created; - } - - public Date getModified() { - return modified; - } - - public void setModified(Date modified) { - this.modified = modified; - } -} diff --git a/jun_java_plugins/jun_uid/src/main/resources/README.txt b/jun_java_plugins/jun_uid/src/main/resources/README.txt deleted file mode 100644 index 3174f28350..0000000000 --- a/jun_java_plugins/jun_uid/src/main/resources/README.txt +++ /dev/null @@ -1,141 +0,0 @@ -一、介绍 -========================== - 1、本项目为uid生成器,支持segment、snowflake、UidGenerator、spring四种策略生成id - - 2、本项目可生成混淆id,目前混淆策略为:gene(基因法) - -二、策略说明 -========================== - 1、snowflake - snowflake 是基于Twitter[snowflake](https://github.com/twitter/snowflake) 算法的优化策略 - 本策略优化了闰秒回拨处理、新增默认workId(可复用baidu-workerId策略) 与 datacenterId 的提供方法。 - - - - - 2、baidu - 是 基于[百度UidGenerator](https://github.com/baidu/uid-generator)上的的优化策略。 - - - (1)、workerId提供策略 - * DisposableWorkerIdAssigner,利用数据库来管理生成workId,依赖数据库和spring-jdbc框架(需有jdbcTemplate的bean)。mysql表示例: - DROP TABLE IF EXISTS WORKER_NODE; - CREATE TABLE WORKER_NODE ( - ID BIGINT NOT NULL AUTO_INCREMENT COMMENT '自增 id', - HOST_NAME VARCHAR(64) NOT NULL COMMENT '主机名', - PORT VARCHAR(64) NOT NULL COMMENT '端口', - TYPE INT NOT NULL COMMENT '节点类型: ACTUAL or CONTAINER', - LAUNCH_DATE DATE NOT NULL COMMENT '启动时间', - MODIFIED TIMESTAMP NOT NULL COMMENT '修改时间', - CREATED TIMESTAMP NOT NULL COMMENT '创建时间', - PRIMARY KEY(ID) - ) COMMENT='Uid WorkerId 存储表',ENGINE = INNODB; - - 示例: - - ... - - * SimpleWorkerIdAssigner ,固定了workId的提供。值为0.示例: - - - * ZkWorkerIdAssigner ,利用zookeeper来实现wordId的提供管理,依赖原生Zookeeper驱动包.示例: - - 可设置interval-心跳间隔、pidHome-workerId文件存储目录、zkAddress-zk地址、pidPort-心跳端口 - - * RedisWorkIdAssigner ,利用redis来实现wordId的提供管理,依赖了spring-data-redis框架(依赖注入RedisTemplate).示例: - - 可设置interval-心跳间隔、pidHome-workerId文件存储目录、pidPort-心跳端口 - - (2)、uid生成策略 - * DefaultUidGenerator 是Snowflake算法的变种,取消datacenterId, 并扩展了支持自定义workerId位数和初始化策略。 - a、可配置 delta seconds (28 bits) - 当前时间,相对于时间基点"2016-05-20"的增量值,单位:秒,最多可支持约8.7年 - - b、worker id (22 bits) - 机器id,最多可支持约420w次机器启动。内置实现为在启动时由数据库分配,默认分配策略为用后即弃,后续可提供复用策略。 - - c、sequence (13 bits) - 每秒下的并发序列,13 bits可支持每秒8192个并发。 - - 注: 三者之和为63 - - 示例: - - - - - - - - - * CachedUidGenerator借用未来时间来解决sequence天然存在的并发限制; 采用RingBuffer来缓存已生成的UID, 并行化UID的生产和消费, - 同时对CacheLine补齐,避免了由RingBuffer带来的硬件级「伪共享」问题. 最终单机QPS可达600万 - - 示例: - - - - - - - - - - - - - - - - - - - - - - - - - - - (3)、比特分配的建议 - *对于并发数要求不高、期望长期使用的应用, 可增加```timeBits```位数, 减少```seqBits```位数. - 例如节点采取用完即弃的WorkerIdAssigner策略, 重启频率为12次/天, - 那么配置成```{"workerBits":23,"timeBits":31,"seqBits":9}```时, 可支持28个节点以整体并发量14400 UID/s的速度持续运行68年. - - *对于节点重启频率频繁、期望长期使用的应用, 可增加```workerBits```和```timeBits```位数, 减少```seqBits```位数. - 例如节点采取用完即弃的WorkerIdAssigner策略, 重启频率为24*12次/天, - 那么配置成```{"workerBits":27,"timeBits":30,"seqBits":6}```时, 可支持37个节点以整体并发量2400 UID/s的速度持续运行34年. - - 3、segment - segment 是基于美团[leaf-segment](https://tech.meituan.com/MT_Leaf.html) 的优化策略, 使用双Buffer实现。依赖数据库与spring-jdbc框架 - - - (1)、SegmentServiceImpl 是具体实现类,数据库表结构为(mysql示例): - DROP TABLE IF EXISTS id_segment; - CREATE TABLE id_segment ( - BIZ_TAG VARCHAR(64) NOT NULL COMMENT '业务标识', - STEP int NOT NULL COMMENT '步长', - MAX_ID BIGINT NOT NULL COMMENT '最大值', - LAST_UPDATE_TIME TIMESTAMP NOT NULL COMMENT '上次修改时间', - CURRENT_UPDATE_TIME TIMESTAMP NOT NULL COMMENT '当前修改时间', - PRIMARY KEY(BIZ_TAG) - ) COMMENT='号段存储表',ENGINE = INNODB; - - (2)、支持 同步/异步两种更新数据库方式。可选配置asynLoadingSegment(true-异步,false-同步),默认使用异步。 - 示例: - ... - - 4、spring 增量ID - 是 基于 segment策略提供给spring 增量实现。非直接使用的策略 - - 5、混淆算法 - 是 基于 基因分库法这个理论扩展出来的混淆算法 - -三 、使用 -------------------- - - - - - diff --git a/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/standard/distributed/lock/CurlUtil.java b/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/standard/distributed/lock/CurlUtil.java deleted file mode 100644 index b4ee55333d..0000000000 --- a/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/standard/distributed/lock/CurlUtil.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.myzmds.ecp.core.standard.distributed.lock; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @类名称 CurlUtil.java - * @类描述
    CURL命令辅助类
    - * @作者 庄梦蝶殇 linhuaichuan1989@126.com - * @创建时间 2019年12月16日 上午11:16:16 - * @版本 1.0.0 - * - * @修改记录 - *
    - *     版本                       修改人 		修改日期 		 修改内容描述
    - *     ----------------------------------------------
    - *     1.0.0 	       庄梦蝶殇 	2019年12月16日             
    - *     ----------------------------------------------
    - * 
    - */ -public class CurlUtil { - public static Logger logger = LoggerFactory.getLogger(CurlUtil.class); - - /** - * 默认命令头 - */ - private static final String CURL = "curl"; - - /** - * @方法名称 execCurl - * @功能描述
    执行命令
    - * @param cmds java curl不支持空格,所有用空格分割命令 - * @return 执行结果:null-错误/检查操作,""-无返回值 - */ - public static String execCurl(List cmds) { - if (null == cmds || cmds.size() == 0) { - return null; - } - if (!cmds.get(0).equals(CURL)) { - cmds.add(0, CURL); - } - ProcessBuilder process = new ProcessBuilder(cmds); - try { - Process p = process.start(); - StringBuilder builder = new StringBuilder(); - try (BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()))) { - String line = null; - while ((line = reader.readLine()) != null) { - builder.append(line).append(System.getProperty("line.separator")); - } - logger.debug(Thread.currentThread().getName().concat(":").concat(builder.toString().trim())); - } - return builder.toString().trim(); - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } -} diff --git a/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/standard/distributed/lock/EtcdSharedLock.java b/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/standard/distributed/lock/EtcdSharedLock.java deleted file mode 100644 index 488c66077a..0000000000 --- a/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/standard/distributed/lock/EtcdSharedLock.java +++ /dev/null @@ -1,158 +0,0 @@ -package com.myzmds.ecp.core.standard.distributed.lock; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import com.alibaba.fastjson.JSONObject; -import com.myzmds.ecp.core.uid.baidu.utils.NamingThreadFactory; - -/** - * @类名称 EtcdSharedLock.java - * @类描述
    etcd分布式锁:支持等待锁,竞争锁;可自动续租/释放资源;CP模式,强一致性
    - * @作者 庄梦蝶殇 linhuaichuan1989@126.com - * @创建时间 2019年12月16日 上午11:02:17 - * @版本 1.0.0 - * - * @修改记录 - *
    - *     版本                       修改人 		修改日期 		 修改内容描述
    - *     ----------------------------------------------
    - *     1.0.0 	       庄梦蝶殇 	2019年12月16日             
    - *     ----------------------------------------------
    - * 
    - */ -public class EtcdSharedLock implements ISharedLock { - - /** - * 过期时间命令 - */ - private static String PREFIX_TTL = "ttl="; - - /** - * 锁值命令 - */ - private static String PREFIX_VAL = "?prevValue="; - - /** - * 默认锁值 - */ - private static final String DEFAULT_VALUE = "1"; - - /** - * 默认etcd服务地址 - */ - private static String DEFAULT_URL = "http://172.16.104.105:2379/v2/keys/"; - - /** - * 整锁命令 - */ - private static final List LOCK_APPLY = Arrays.asList(new String[] {"-XPUT", "-d", "value=1", "-d", "prevExist=false", "-d"}); - - /** - * 续租命令 - */ - private static final List LOCK_RELET = Arrays.asList(new String[] {"-XPUT", "-d", "refresh=true", "-d", "prevExist=true", "-d"}); - - /** - * 解锁命令 - */ - private static final List LOCK_DELETE = Arrays.asList(new String[] {"-XDELETE"}); - - /** - * 配置地址 - */ - public String url; - - /** - * 锁名 - */ - public String name; - - /** - * 锁值 - */ - public String value; - - /** - * 锁过期时间,毫秒 - */ - public int ttl; - - /** - * 心跳线程池 - */ - private ScheduledExecutorService scheduledpool; - - public EtcdSharedLock(String name) { - this(name, DEFAULT_VALUE); - } - - public EtcdSharedLock(String name, String value) { - this(DEFAULT_URL, name, value); - } - - public EtcdSharedLock(String url, String name, String value) { - this.url = url; - this.name = name; - this.value = value; - } - - @Override - public boolean lock(int ttl) - throws RuntimeException { - this.ttl = ttl; - List commonds = new ArrayList(); - commonds.add(url.concat(name)); - commonds.addAll(LOCK_APPLY); - commonds.add(PREFIX_TTL + ttl); - String result = CurlUtil.execCurl(commonds); - if (null == result || "".equals(result)) { - return false; - } - JSONObject jsonObject = JSONObject.parseObject(result); - if (jsonObject.containsKey("errorCode")) { - if ("105".equals(jsonObject.getString("errorCode"))) { - return false; - } else { - logger.warn(MSG_LOCK_ERROR, name, result); - throw new RuntimeException(result); - } - } - return true; - } - - @Override - public void startHeartBeatThread() { - scheduledpool = new ScheduledThreadPoolExecutor(1, new NamingThreadFactory(Thread.currentThread().getName().concat(LOCK_HEART_BEAT), true)); - scheduledpool.scheduleAtFixedRate(() -> { - List commonds = new ArrayList(); - commonds.add(url.concat(name).concat(PREFIX_VAL).concat(value)); - commonds.addAll(LOCK_RELET); - commonds.add(PREFIX_TTL + ttl); - CurlUtil.execCurl(commonds); - logger.debug(MSG_RELET, Thread.currentThread().getName(), name); - }, 0L, ttl / 3, TimeUnit.MILLISECONDS); - } - - @Override - public void close() { - // 有锁才释放 - if (null != scheduledpool) { - scheduledpool.shutdown(); - List commonds = new ArrayList(); - commonds.add(url.concat(name).concat(PREFIX_VAL).concat(value)); - commonds.addAll(LOCK_DELETE); - String result = CurlUtil.execCurl(commonds); - logger.debug(result); - } - } - - @Override - public String getName() { - return name; - } -} diff --git a/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/standard/distributed/lock/ISharedLock.java b/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/standard/distributed/lock/ISharedLock.java deleted file mode 100644 index 3308eeed4d..0000000000 --- a/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/standard/distributed/lock/ISharedLock.java +++ /dev/null @@ -1,130 +0,0 @@ -package com.myzmds.ecp.core.standard.distributed.lock; - -import java.io.Closeable; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @类名称 ISharedLock.java - * @类描述
    分布式锁:支持等待锁,竞争锁;可自动续租/释放资源;
    - * @作者 庄梦蝶殇 linhuaichuan1989@126.com - * @版本 1.0.0 - * - * @修改记录 - *
    - *     版本                       修改人 		修改日期 		 修改内容描述
    - *     ----------------------------------------------
    - *     1.0.0 	       庄梦蝶殇 	2019年12月13日             
    - *     ----------------------------------------------
    - * 
    - */ -public interface ISharedLock extends Closeable { - public static Logger logger = LoggerFactory.getLogger(ISharedLock.class); - - /** - * 线程名-心跳 - */ - public static final String LOCK_HEART_BEAT = ":heart_beat"; - - /** - * 取锁日志 - */ - public final static String MSG_LOCK = "{}获得锁"; - - /** - * 取锁错误日志 - */ - public final static String MSG_LOCK_ERROR = "{}取锁失败,错误为{}"; - - /** - * 续租日志 - */ - public final static String MSG_RELET = "{}续租锁"; - - /** - * 解锁日志 - */ - public final static String MSG_UNLOCK = "{}释放锁"; - - /** - * 取锁超时日志 - */ - public final static String MSG_LOCK_TIMEOUT = "{}取锁超时"; - - /** - * @方法名称 acquire - * @功能描述
    竞争锁,并自动续租
    - * @param ttl 锁过期时间,单位毫秒 - * @return true-获取锁,false-为获得锁 - * @throws RuntimeException 操作锁失败,需要业务判断是否重试 - */ - default boolean acquire(int ttl) - throws RuntimeException { - if (lock(ttl)) { - logger.debug(MSG_LOCK, getName()); - startHeartBeatThread(); - return true; - } - return false; - } - - /** - * @方法名称 lock - * @功能描述
    获取锁
    - * @param ttl 锁过期时间,单位毫秒 - * @return true-获取锁,false-为获得锁 - * @throws RuntimeException 操作锁失败,需要业务判断是否重试 - */ - boolean lock(int ttl) - throws RuntimeException; - - /** - * @方法名称 acquireOrWait - * @功能描述
    竞争锁或等待锁
    - * @param ttl 锁过期时间,单位毫秒 - * @param waitTime 等待时间,单位毫秒 - * @return true-获取锁,false-为获得锁 - * @throws InterruptedException - * @throws RuntimeException 操作锁失败,需要业务判断是否重试 - */ - default boolean acquireOrWait(int ttl, int waitTime) - throws InterruptedException, RuntimeException { - while (!lock(ttl)) { - waitTime = waitTime - ttl / 2; - Thread.sleep(ttl / 2); - if (waitTime <= 0) { - logger.debug(MSG_LOCK_TIMEOUT, getName()); - return false; - } - } - startHeartBeatThread(); - return true; - } - - /** - * @方法名称 startHeartBeatThread - * @功能描述
    续租心跳
    - */ - void startHeartBeatThread(); - - /** - * @方法名称 close - * @功能描述
    释放锁
    - */ - @Override - void close(); - - /** - * @方法名称 release - * @功能描述
    释放锁
    - */ - default void release() { - close(); - } - - /** - * 获取锁名 - */ - public String getName(); -} diff --git a/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/standard/distributed/lock/RedisSharedLock.java b/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/standard/distributed/lock/RedisSharedLock.java deleted file mode 100644 index daefa2fdc9..0000000000 --- a/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/standard/distributed/lock/RedisSharedLock.java +++ /dev/null @@ -1,174 +0,0 @@ -package com.myzmds.ecp.core.standard.distributed.lock; - -import java.util.Collections; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.core.script.RedisScript; - -import com.myzmds.ecp.core.uid.baidu.utils.NamingThreadFactory; - -/** - * @类名称 RedisSharedLock.java - * @类描述
    redis 分布式锁(redis是ap模式,无法保证强一致性: 集群可能造成多重获锁,Redissond红锁 RedissonRedLock一样存在极端情况重复取锁问题)
    - * @作者 庄梦蝶殇 linhuaichuan1989@126.com - * @创建时间 2018年5月8日 下午8:09:15 - * @版本 1.3.0 - * - * @修改记录 - *
    - *     版本                       修改人 		修改日期 		 修改内容描述
    - *     ----------------------------------------------
    - *     1.0.0 	庄梦蝶殇    2018年05月08日             
    - *     1.1.0    庄梦蝶殇    2018年11月21日             Redis pipeline操作,一致性增强,精简代码 (pipeline不保证原子性)
    - *     1.2.0    庄梦蝶殇    2019年01月16日             改用Lua脚本,保证原子性
    - *     1.3.0    庄梦蝶殇    2019年12月13日             统一锁接口
    - *     ----------------------------------------------
    - * 
    - */ -public class RedisSharedLock implements ISharedLock { - /** - * 加锁脚本 - */ - private static final String SCRIPT_LOCK = "if redis.call('setnx', KEYS[1], ARGV[1]) == 1 then redis.call('pexpire', KEYS[1], ARGV[2]) return 1 else return 0 end"; - - /** - * 解锁脚本 - */ - private static final String SCRIPT_UNLOCK = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; - - /** - * 加锁脚本sha1值 - */ - private static final String SCRIPT_LOCK_SHA1 = "8525317db2b346fffb9050797aee5fa8b8231872"; - - /** - * 解锁脚本sha1值 - */ - private static final String SCRIPT_UNLOCK_SHA1 = "e9f69f2beb755be68b5e456ee2ce9aadfbc4ebf4"; - - /** - * 成功标识 - */ - private static final Long SUCCESS = 1L; - - /** - * 警告消息:降级删锁 - */ - private static final String WARN_MSG_EVAL = "Redis不支持EVAL命令,使用降级方式解锁:{}"; - - /** - * redis lock 前缀,方便redis key管理 - */ - private static final String LOCK_PREFIX = "lock:"; - - @Autowired - private RedisTemplate redisTemplate; - - /** - * 心跳线程池 - */ - private ScheduledExecutorService scheduledpool; - - /** - * 锁名,即key值 - */ - public String lockKey; - - /** - * 锁过期时间,毫秒 - */ - public int ttl; - - public RedisSharedLock(String name) { - lockKey = getLockKey(name); - } - - public RedisSharedLock(RedisTemplate redisTemplate, String name) { - this(name); - this.redisTemplate = redisTemplate; - } - - @Override - public boolean lock(int ttl) - throws RuntimeException { - this.ttl = ttl; - // 锁不存在时:上锁并过期时间,最后跳出。 - Long result = redisTemplate.execute(new RedisScript() { - @Override - public String getSha1() { - return SCRIPT_LOCK_SHA1; - } - - @Override - public Class getResultType() { - return Long.class; - } - - @Override - public String getScriptAsString() { - return SCRIPT_LOCK; - } - - }, Collections.singletonList(lockKey), "1", String.valueOf(ttl)); - if (SUCCESS.equals(result)) { - return true; - } - return false; - } - - @Override - public void startHeartBeatThread() { - scheduledpool = new ScheduledThreadPoolExecutor(1, new NamingThreadFactory(Thread.currentThread().getName().concat(LOCK_HEART_BEAT), true)); - scheduledpool.scheduleAtFixedRate(() -> { - redisTemplate.expire(lockKey, ttl, TimeUnit.MILLISECONDS); - logger.debug(MSG_RELET, Thread.currentThread().getName(), lockKey); - }, 0L, ttl / 3, TimeUnit.MILLISECONDS); - - } - - @Override - public void close() { - if (null != scheduledpool && redisTemplate.hasKey(lockKey)) { - try { - redisTemplate.execute(new RedisScript() { - @Override - public Class getResultType() { - return Long.class; - } - - @Override - public String getScriptAsString() { - return SCRIPT_UNLOCK; - } - - @Override - public String getSha1() { - return SCRIPT_UNLOCK_SHA1; - } - }, Collections.singletonList(lockKey), "1"); - } catch (Exception e) { - logger.warn(WARN_MSG_EVAL, e.getMessage()); - redisTemplate.delete(lockKey); - } - } - } - - /** - * @方法名称 getLockKey - * @功能描述
    获取锁key
    - * @param name 锁名 - * @return 锁key - */ - public static String getLockKey(String name) { - return LOCK_PREFIX.concat(name); - } - - @Override - public String getName() { - return lockKey; - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/standard/distributed/lock/ZkSharedLock.java b/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/standard/distributed/lock/ZkSharedLock.java deleted file mode 100644 index 623d9af8ee..0000000000 --- a/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/standard/distributed/lock/ZkSharedLock.java +++ /dev/null @@ -1,274 +0,0 @@ -package com.myzmds.ecp.core.standard.distributed.lock; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.KeeperException; -import org.apache.zookeeper.WatchedEvent; -import org.apache.zookeeper.Watcher; -import org.apache.zookeeper.Watcher.Event.EventType; -import org.apache.zookeeper.ZooDefs.Ids; -import org.apache.zookeeper.ZooKeeper; -import org.apache.zookeeper.data.Stat; -import org.springframework.util.Assert; - -/** - * @类名称 ZkSharedLock.java - * @类描述
    zk分布式锁(有缺陷,原生zkclient监听处理不完善):支持等待锁,竞争锁;天然自动续租/释放资源,轮训检测;CP模式,强一致性
    - * @作者 庄梦蝶殇 linhuaichuan1989@126.com - * @创建时间 2019年12月16日 下午4:38:11 - * @版本 1.0.0 - * - * @修改记录 - *
    - *     版本                       修改人 		修改日期 		 修改内容描述
    - *     ----------------------------------------------
    - *     1.0.0 	       庄梦蝶殇 	2019年12月16日             
    - *     ----------------------------------------------
    - * 
    - */ -public class ZkSharedLock implements ISharedLock { - /** - * 锁在zk上的根路径/根节点 - */ - private final static String ROOT_PATH = "/locks"; - - /** - * 最大重试次数 - */ - private static final Integer MAX_RETRY_COUNT = 10; - - /** - * zk客户端 - */ - private ZooKeeper client; - - /** - * zk地址 - */ - private String connectIp; - - /** - * 计数器 - */ - private CountDownLatch latch; - - /** - * 锁名 - */ - public String name; - - /** - * 锁在zk上的完整路径 - */ - public String ourPath; - - /** - * 锁根路径 - */ - public String basePath; - - public ZkSharedLock(String connectIp, String name) { - Assert.notNull(connectIp, "zk地址不能为空!"); - this.name = name; - this.connectIp = connectIp; - init(); - } - - /** - * @方法名称 init - * @功能描述
    初始化
    - */ - public void init() { - initClient(); - this.basePath = ROOT_PATH.concat(ZkUtil.PATH_SPILT).concat(name); - try { - if (null == client.exists(ROOT_PATH, false)) { - client.create(ROOT_PATH, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); - } - client.close(); - } catch (Exception e) { - // 忽略 初始化根路径错误 - } - } - - @Override - public boolean lock(int ttl) { - initClient(); - List children = getSortLockNode(); - if (null == children) { - return false; - } - // 当前有序节点名(锁名) - String sequenceNodeName = ourPath.substring(basePath.length() + 1); - // 计算刚才客户端创建的顺序节点在locker的所有子节点中排序位置,如果是排序为0,则表示获取到了锁 - int ourIndex = children.indexOf(sequenceNodeName); - // 没有找到之前创建的[临时]顺序节点,这表示可能由于网络闪断而导致 Zookeeper认为连接断开而删除了我们创建的节点,证明获取锁失败 - if (ourIndex < 0) { - return false; - } - // 检验是否未最小节点,是则获取锁 - if (ourIndex == 0) { - // 获取锁成功 - logger.debug(MSG_LOCK, sequenceNodeName); - return true; - } - return false; - } - - @Override - public boolean acquireOrWait(int ttl, int waitTime) - throws InterruptedException { - initClient(); - /** - * 1、获取锁的所有竞争者列表 - */ - List children = getSortLockNode(); - if (null == children) { - return false; - } - boolean haveTheLock = false; - // 重置计数器 - latch = new CountDownLatch(1); - // 当前有序节点名(锁名) - String sequenceNodeName = ourPath.substring(basePath.length() + 1); - // 起始时间 - long startMillis = System.currentTimeMillis(); - // 等待时间 - while (!haveTheLock) { - // 重新获取列表 - children = getSortLockNode(); - /** - * 2、检验是否未最小节点,是则获取锁 - */ - // 计算刚才客户端创建的顺序节点在locker的所有子节点中排序位置,如果是排序为0,则表示获取到了锁 - int ourIndex = children.indexOf(sequenceNodeName); - // 没有找到之前创建的[临时]顺序节点,这表示可能由于网络闪断而导致 Zookeeper认为连接断开而删除了我们创建的节点,证明获取锁失败 - if (ourIndex < 0) { - return false; - } - // 检验是否未最小节点,是则获取锁 - if (ourIndex == 0) { - // 获取锁成功 - logger.debug(MSG_LOCK, sequenceNodeName); - return true; - } - - /** - * 3、订阅次小节点的监听,进行等待 - */ - // 获取次小节点名 - String pathToWatch = children.get(ourIndex - 1); - // 如果次小的节点被删除了,则表示当前客户端的节点应该是最小的了,所以使用CountDownLatch来实现等待 - // 上一有序节点名(上个锁名) - String prevNodePath = basePath.concat(ZkUtil.PATH_SPILT).concat(pathToWatch); - - // 查询前一个目录是否存在,并且注册目录事件监听器,监听一次事件后即删除 - try { - Stat state = client.exists(prevNodePath, true); - if (null == state) { - continue; - } - // 发生超时需要删除节点,防止无限等待造成线程垃圾。 - waitTime -= (System.currentTimeMillis() - startMillis); - startMillis = System.currentTimeMillis(); - if (waitTime <= 0) { - logger.debug(MSG_LOCK_TIMEOUT, sequenceNodeName); - // 等待超时,删除我们的节点 - client.close(); - return false; - } - // 等待 - latch.await(waitTime, TimeUnit.MICROSECONDS); - } catch (KeeperException | InterruptedException e) { - // ignore - } - } - return haveTheLock; - } - - @Override - public void startHeartBeatThread() { - - } - - @Override - public void close() { - if (null == ourPath) { - // 空锁时,直接返回 - return; - } - try { - client.delete(ourPath, -1); - client.close(); - } catch (Exception e) { - } - } - - /** - * @方法名称 getSortLockNode - * @功能描述
    获取本锁路径下的所有子节点,并按小->大排序
    - * @return 当前锁的所有竞争者列表 - */ - private List getSortLockNode() { - /** - * 1、zk跟路径检测 - */ - // 锁路径 - String path = basePath.concat(ZkUtil.PATH_SPILT).concat(name); - try { - if (null == client.exists(basePath, false)) { - client.create(basePath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); - } - } catch (Exception e) { - // 锁根路径 - } - - /** - * 2、创建 当前锁名 的临时节点(在[basePath持久节点]下创建客户端要获取锁的[临时]顺序节点) - */ - // 是否需要重试 - boolean isDone = false; - // 重试次数 - int retryCount = 0; - // 网络闪断需要重试一试 - while (!isDone) { - isDone = true; - try { - ourPath = client.create(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); - /** - * 3、获取本锁路径下的所有子节点,并按小->大排序 - */ - return ZkUtil.getSortedChildren(client, basePath, name); - } catch (Exception e) { - if (retryCount++ < MAX_RETRY_COUNT) { - isDone = false; - } - } - } - return null == ourPath ? null : new ArrayList(); - } - - private void initClient() { - try { - client = new ZooKeeper(connectIp, 300000, new Watcher() { - @Override - public void process(WatchedEvent event) { - if (event.getType().equals(EventType.NodeDeleted) && null != latch) { - latch.countDown(); - } - } - }); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Override - public String getName() { - return ourPath; - } -} diff --git a/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/standard/distributed/lock/ZkUtil.java b/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/standard/distributed/lock/ZkUtil.java deleted file mode 100644 index a22b4bb405..0000000000 --- a/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/standard/distributed/lock/ZkUtil.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.myzmds.ecp.core.standard.distributed.lock; - -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -import org.apache.zookeeper.KeeperException; -import org.apache.zookeeper.ZooKeeper; - -/** - * @类名称 ZkUtils.java - * @类描述
    zk辅助类
    - * @作者 庄梦蝶殇 linhuaichuan1989@126.com - * @创建时间 2019年3月27日 下午2:54:29 - * @版本 1.0.0 - * - * @修改记录 - *
    - *     版本                       修改人 		修改日期 		 修改内容描述
    - *     ----------------------------------------------
    - *     1.0.0 	       庄梦蝶殇 	2019年3月27日             
    - *     ----------------------------------------------
    - * 
    - */ -public class ZkUtil { - /** - * zk节点分隔符 - */ - public final static String PATH_SPILT = "/"; - - /** - * 计数器根目录 - */ - public static final String COUNT_PATH = "/count"; - - /** - * @方法名称 getSortedChildren - * @功能描述
    获取子节点列表,并由小到大排序
    - * @param client zk客户端对象 - * @param basePath 顺序节点根目录 - * @param lockName 锁名 - * @return 子节点列表 - */ - public static List getSortedChildren(ZooKeeper client, String basePath, final String lockName) { - try { - if (null == client.exists(basePath, false)) { - return null; - } - List children = client.getChildren(basePath, false); - Collections.sort(children, new Comparator() { - @Override - public int compare(String lhs, String rhs) { - return getLockNodeNumber(lhs, lockName).compareTo(getLockNodeNumber(rhs, lockName)); - } - }); - return children; - } catch (InterruptedException | KeeperException e) { - throw new RuntimeException(e); - } - } - - /** - * @方法名称 getLockNodeNumber - * @功能描述
    获取节点版本标识
    - * @param str 节点完整名(含版本标识) - * @param lockName 节点名 - * @return 节点版本标识 - */ - public static String getLockNodeNumber(String str, String lockName) { - int index = str.lastIndexOf(lockName); - if (index >= 0) { - index += lockName.length(); - return index <= str.length() ? str.substring(index) : ""; - } - return str; - } -} diff --git a/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/uid/ParseUidTest.java b/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/uid/ParseUidTest.java deleted file mode 100644 index a0a7c8c14d..0000000000 --- a/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/uid/ParseUidTest.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.myzmds.ecp.core.uid; - -import java.net.NetworkInterface; -import java.net.SocketException; -import java.util.Enumeration; - -import com.myzmds.ecp.core.uid.baidu.impl.DefaultUidGenerator; -import com.myzmds.ecp.core.uid.extend.strategy.TwitterSnowflakeStrategy; -import com.myzmds.ecp.core.uid.twitter.SnowflakeIdWorker; -import com.myzmds.ecp.core.uid.worker.SimpleWorkerIdAssigner; - -public class ParseUidTest { - public static void testParseUid() { - System.out.println(new SnowflakeIdWorker(10, 12).nextId()); - System.out.println(new SnowflakeIdWorker(10, 12).parseUID("91543914239533056")); - System.out.println(new SnowflakeIdWorker(10, 12).parseUID(91543914239533056L)); - - // 百度 - DefaultUidGenerator uidGenerator = new DefaultUidGenerator(); - uidGenerator.setWorkerIdAssigner(new SimpleWorkerIdAssigner()); - uidGenerator.setSeqBits(13); - uidGenerator.setTimeBits(29); - uidGenerator.setWorkerBits(21); - uidGenerator.setEpochStr("2017-12-25"); - try { - uidGenerator.afterPropertiesSet(); - } catch (Exception e) { - e.printStackTrace(); - } - System.out.println(uidGenerator.getUID()); - System.out.println(uidGenerator.parseUID(374964732433530880L)); - } - - public static void testBuildRule() { - Long did = TwitterSnowflakeStrategy.getMachineNum(31L); - System.out.println(did); - System.out.println(TwitterSnowflakeStrategy.getProcessNum(did, 31L)); - System.out.println(getMachineNum(31L)); - } - - public static void main(String[] args) { - testBuildRule(); - try { -// testZkNode(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - private static long getMachineNum(long maxWorkerId) { - StringBuilder sb = new StringBuilder(); - Enumeration e = null; - try { - e = NetworkInterface.getNetworkInterfaces(); - } catch (SocketException e1) { - e1.printStackTrace(); - } - while (e.hasMoreElements()) { - NetworkInterface ni = e.nextElement(); - sb.append(ni.toString()); - } - return (sb.toString().hashCode() & 0xffff) % (maxWorkerId + 1); - } - -} diff --git a/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/uid/baidu/CachedUidGeneratorTest.java b/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/uid/baidu/CachedUidGeneratorTest.java deleted file mode 100644 index 7162a12f84..0000000000 --- a/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/uid/baidu/CachedUidGeneratorTest.java +++ /dev/null @@ -1,142 +0,0 @@ -package com.myzmds.ecp.core.uid.baidu; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.util.StringUtils; - -import com.myzmds.ecp.core.uid.baidu.UidGenerator; -import com.myzmds.ecp.core.uid.baidu.impl.CachedUidGenerator; - -import javax.annotation.Resource; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.ConcurrentSkipListSet; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * Test for {@link CachedUidGenerator} - * - * @author yutianbao - */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = {"file:src/test/resources/uid/cached-uid-baidu.xml" }) -public class CachedUidGeneratorTest { - private static final int SIZE = 7000000; // 700w - private static final boolean VERBOSE = false; - private static final int THREADS = Runtime.getRuntime().availableProcessors() << 1; - - @Resource - private UidGenerator uidGenerator; - - /** - * Test for serially generate - * - * @throws IOException - */ - @Test - public void testSerialGenerate() throws IOException { - // Generate UID serially - Set uidSet = new HashSet<>(SIZE); - for (int i = 0; i < SIZE; i++) { - doGenerate(uidSet, i); - } - - // Check UIDs are all unique - checkUniqueID(uidSet); - } - - /** - * Test for parallel generate - * - * @throws InterruptedException - * @throws IOException - */ - @Test - public void testParallelGenerate() throws InterruptedException, IOException { - final AtomicInteger control = new AtomicInteger(-1); - final Set uidSet = new ConcurrentSkipListSet<>(); - - // Initialize threads - List threadList = new ArrayList<>(THREADS); - for (int i = 0; i < THREADS; i++) { - Thread thread = new Thread() { - @Override - public void run() { - workerRun(uidSet, control); - } - }; - thread.setName("UID-generator-" + i); - - threadList.add(thread); - thread.start(); - } - - // Wait for worker done - for (Thread thread : threadList) { - thread.join(); - } - - // Check generate 700w times - Assert.assertEquals(SIZE, control.get()); - - // Check UIDs are all unique - checkUniqueID(uidSet); - } - public int updateAndGet(AtomicInteger control) { - int prev, next; - do { - prev = control.get(); - next = prev == SIZE ? SIZE : prev + 1; - } while (!control.compareAndSet(prev, next)); - return next; - } - - /** - * Woker run - */ - private void workerRun(Set uidSet, AtomicInteger control) { - for (;;) { - int myPosition = updateAndGet(control); - if (myPosition == SIZE) { - return; - } - - doGenerate(uidSet, myPosition); - } - } - - /** - * Do generating - */ - private void doGenerate(Set uidSet, int index) { - long uid = uidGenerator.getUID(); - String parsedInfo = uidGenerator.parseUID(uid); - boolean existed = !uidSet.add(uid); - if (existed) { - System.out.println("Found duplicate UID " + uid); - } - - // Check UID is positive, and can be parsed - Assert.assertTrue(uid > 0L); - Assert.assertTrue(!StringUtils.isEmpty(parsedInfo)); - - if (VERBOSE) { - System.out.println(Thread.currentThread().getName() + " No." + index + " >>> " + parsedInfo); - } - } - - /** - * Check UIDs are all unique - */ - private void checkUniqueID(Set uidSet) throws IOException { - System.out.println(uidSet.size()); - Assert.assertEquals(SIZE, uidSet.size()); - } - -} diff --git a/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/uid/baidu/DefaultUidGeneratorTest.java b/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/uid/baidu/DefaultUidGeneratorTest.java deleted file mode 100644 index aebf271bbc..0000000000 --- a/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/uid/baidu/DefaultUidGeneratorTest.java +++ /dev/null @@ -1,136 +0,0 @@ -package com.myzmds.ecp.core.uid.baidu; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.ConcurrentSkipListSet; -import java.util.concurrent.atomic.AtomicInteger; - -import javax.annotation.Resource; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.util.StringUtils; - -import com.myzmds.ecp.core.uid.baidu.impl.DefaultUidGenerator; - -/** - * Test for {@link DefaultUidGenerator} - * - * @author yutianbao - */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = {"file:src/test/resources/uid/default-uid-baidu.xml" }) -public class DefaultUidGeneratorTest { - private static final int SIZE = 100000; // 10w - private static final boolean VERBOSE = true; - private static final int THREADS = Runtime.getRuntime().availableProcessors() << 1; - - @Resource - private UidGenerator uidGenerator; - - /** - * Test for serially generate - */ - @Test - public void testSerialGenerate() { - // Generate UID serially - Set uidSet = new HashSet<>(SIZE); - for (int i = 0; i < SIZE; i++) { - doGenerate(uidSet, i); - } - - // Check UIDs are all unique - checkUniqueID(uidSet); - } - - /** - * Test for parallel generate - * - * @throws InterruptedException - */ - @Test - public void testParallelGenerate() throws InterruptedException { - final AtomicInteger control = new AtomicInteger(-1); - final Set uidSet = new ConcurrentSkipListSet<>(); - - // Initialize threads - List threadList = new ArrayList<>(THREADS); - for (int i = 0; i < THREADS; i++) { - Thread thread = new Thread(new Runnable() { - @Override - public void run() { - workerRun(uidSet, control); - } - }); - thread.setName("UID-generator-" + i); - - threadList.add(thread); - thread.start(); - } - - // Wait for worker done - for (Thread thread : threadList) { - thread.join(); - } - - // Check generate 10w times - Assert.assertEquals(SIZE, control.get()); - - // Check UIDs are all unique - checkUniqueID(uidSet); - } - - public int updateAndGet(AtomicInteger control) { - int prev, next; - do { - prev = control.get(); - next = prev == SIZE ? SIZE : prev + 1; - } while (!control.compareAndSet(prev, next)); - return next; - } - - /** - * Worker run - */ - private void workerRun(Set uidSet, AtomicInteger control) { - for (;;) { - int myPosition = updateAndGet(control); - if (myPosition == SIZE) { - return; - } - - doGenerate(uidSet, myPosition); - } - } - - /** - * Do generating - */ - private void doGenerate(Set uidSet, int index) { - long uid = uidGenerator.getUID(); - String parsedInfo = uidGenerator.parseUID(uid); - uidSet.add(uid); - - // Check UID is positive, and can be parsed - Assert.assertTrue(uid > 0L); - Assert.assertTrue(!StringUtils.isEmpty(parsedInfo)); - - if (VERBOSE) { - System.out.println(Thread.currentThread().getName() + " No." + index + " >>> " + parsedInfo); - } - } - - /** - * Check UIDs are all unique - */ - private void checkUniqueID(Set uidSet) { - System.out.println(uidSet.size()); - Assert.assertEquals(SIZE, uidSet.size()); - } - -} diff --git a/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/uid/baidu/SimpleUidTest.java b/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/uid/baidu/SimpleUidTest.java deleted file mode 100644 index 480c7f8166..0000000000 --- a/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/uid/baidu/SimpleUidTest.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.myzmds.ecp.core.uid.baidu; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.myzmds.ecp.core.uid.UidContext; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = {"classpath:uid/simple-uid-baidu.xml"}) -public class SimpleUidTest { - @Autowired - private UidContext context; - - @Test - public void test() { - System.out.println(context.getUID()); - System.out.println("test:" +context.getUID("test")); - System.out.println(context.getUID("qwer")); - System.out.println("test:" +context.getUID("test")); - } -} diff --git a/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/uid/baidu/UidTest.java b/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/uid/baidu/UidTest.java deleted file mode 100644 index 33ba8f5e38..0000000000 --- a/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/uid/baidu/UidTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.myzmds.ecp.core.uid.baidu; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = {"classpath:uid/zk-uid-baidu.xml"}) -public class UidTest { - @Autowired - private UidGenerator uidOne; - - @Autowired - private UidGenerator uidTwo; - - @Test - public void test() { - // Generate UID - long uid = uidOne.getUID(); - System.out.println("one:" + uid); - System.out.println("one:" + uidOne.getUID()); - // Parse UID into [Timestamp, WorkerId, Sequence] - // {"UID":"180363646902239241","parsed":{ "timestamp":"2017-01-19 12:15:46", "workerId":"4", "sequence":"9" }} - System.out.println("one:" + uidOne.parseUID(uid)); - - Runnable threadOne= new Runnable() { - @Override - public void run() { - for (int i = 0; i < 10; i++) { - System.out.println("one:" + uidOne.getUID()); - } - } - }; - - Runnable threadTwo= new Runnable() { - @Override - public void run() { - for (int i = 0; i < 10; i++) { - System.out.println("two:" + uidTwo.getUID()); - } - } - }; - threadOne.run(); - threadTwo.run(); - - uid = uidTwo.getUID(); - System.out.println("two:" + uid); - System.out.println("two:" + uidTwo.getUID()); - // Parse UID into [Timestamp, WorkerId, Sequence] - // {"UID":"180363646902239241","parsed":{ "timestamp":"2017-01-19 12:15:46", "workerId":"4", "sequence":"9" }} - System.out.println("two:" + uidTwo.parseUID(uid)); - } -} diff --git a/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/uid/idleaf/ColumnMaxValueIncrementerTest.java b/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/uid/idleaf/ColumnMaxValueIncrementerTest.java deleted file mode 100644 index 7e8364301f..0000000000 --- a/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/uid/idleaf/ColumnMaxValueIncrementerTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.myzmds.ecp.core.uid.idleaf; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.support.incrementer.DataFieldMaxValueIncrementer; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -/** - * @author sunff - * - */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = {"file:src/test/resources/idleaf/app-springId.xml" }) -public class ColumnMaxValueIncrementerTest { - - @Autowired - @Qualifier("productNoIncrementer") - private DataFieldMaxValueIncrementer incrementer; - - @Test - public void test() { - int i = 0; - while (i < 10) { - System.out.println("long id=" + incrementer.nextLongValue()); - System.out.println("int id=" + incrementer.nextIntValue()); - System.out.println("string id=" + incrementer.nextStringValue()); - i++; - } - } -} diff --git a/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/uid/idleaf/LeafSegmentServiceTest.java b/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/uid/idleaf/LeafSegmentServiceTest.java deleted file mode 100644 index 1269f274e2..0000000000 --- a/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/uid/idleaf/LeafSegmentServiceTest.java +++ /dev/null @@ -1,163 +0,0 @@ -/** - * - */ -package com.myzmds.ecp.core.uid.idleaf; - -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.BatchPreparedStatementSetter; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.transaction.TransactionStatus; -import org.springframework.transaction.support.TransactionCallback; -import org.springframework.transaction.support.TransactionTemplate; - -import com.myzmds.ecp.core.uid.leaf.SegmentServiceImpl; - -/** - * @author sunff - * - */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = {"file:src/test/resources/idleaf/app-leaf.xml"}) -public class LeafSegmentServiceTest { - - @Autowired - @Qualifier("segmentService") - private SegmentServiceImpl segmentServiceImpl; - - @Autowired - private JdbcTemplate jdbcTemplate; - - private BlockingQueue queue = new LinkedBlockingQueue(1000); - - @Test - public void synGetId() { - int i =0; - while (true) { - System.out.println(++i +" :" + segmentServiceImpl.getId()); - } - } - - @Autowired - private TransactionTemplate transactionTemplate; - - public void batchInsert() { - - List list = new ArrayList(1000); - for (Long i = 0L; i < 1000L; i++) { - list.add(i); - } - try { - TimeUnit.SECONDS.sleep(3); - } catch (InterruptedException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - try { - - final List insertedList = list; - - transactionTemplate.execute(new TransactionCallback() { - - @Override - public Integer doInTransaction(TransactionStatus status) { - jdbcTemplate.batchUpdate("insert into id_test(p_id) values(?)", new BatchPreparedStatementSetter() { - @Override - public void setValues(PreparedStatement ps, int i) - throws SQLException { - Long insertedId = insertedList.get(i); - ps.setLong(1, insertedId); - } - @Override - public int getBatchSize() { - return insertedList.size(); - } - }); - return insertedList.size(); - } - }); - - System.out.println("oooolk"); - - } catch (Exception e) { - - } - } - - public void getId() { - new Thread() { - @Override - public void run() { - List list = new ArrayList(10000); - while (true) { - try { - Long id = queue.take(); - // jdbcTemplate.update("insert into id_test(p_id) values(?)", - // l); - // System.out.println("id=" + id); - - if (list.size() == 10000) { - - final List insertedList = list; - - transactionTemplate.execute(new TransactionCallback() { - - @Override - public Integer doInTransaction(TransactionStatus status) { - jdbcTemplate.batchUpdate("insert into id_test(p_id) values(?)", new BatchPreparedStatementSetter() { - @Override - public void setValues(PreparedStatement ps, int i) - throws SQLException { - Long insertedId = insertedList.get(i); - ps.setLong(1, insertedId); - } - @Override - public int getBatchSize() { - return insertedList.size(); - } - }); - return insertedList.size(); - } - }); - list.clear(); - - } else { - list.add(id); - } - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - } - }.start(); - - int count = 0; - while (true) { - // System.out.println(idLeafService.getId()); - try { - queue.put(segmentServiceImpl.getId()); - count++; - if (count % 1000 == 0) { - System.out.println("current count no is " + count); - } - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } -} diff --git a/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/uid/idleaf/SegmentServiceImplTest.java b/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/uid/idleaf/SegmentServiceImplTest.java deleted file mode 100644 index 20ac5adff5..0000000000 --- a/jun_java_plugins/jun_uid/src/test/java/com/myzmds/ecp/core/uid/idleaf/SegmentServiceImplTest.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.myzmds.ecp.core.uid.idleaf; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.myzmds.ecp.core.uid.leaf.SegmentServiceImpl; - -import net.sourceforge.groboutils.junit.v1.MultiThreadedTestRunner; -import net.sourceforge.groboutils.junit.v1.TestRunnable; - -/** - * @类名称 SegmentServiceImplTest.java - * @类描述
    Segment多线程并发测试
    - * @作者 庄梦蝶殇 linhuaichuan1989@126.com - * @创建时间 2019年3月6日 下午4:42:59 - * @版本 1.0.0 - * - * @修改记录 - *
    - *     版本                       修改人 		修改日期 		 修改内容描述
    - *     ----------------------------------------------
    - *     1.0.0 	       庄梦蝶殇 	2019年3月6日             
    - *     ----------------------------------------------
    - * 
    - */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = {"file:src/test/resources/idleaf/app-leaf.xml"}) -public class SegmentServiceImplTest extends Thread { - - @Autowired - SegmentServiceImpl segmentServiceImpl; - - @Test - public void testSych() { - TestRunnable runner = new TestRunnable() { - @Override - public void runTest() - throws Throwable { - System.out.println(Thread.currentThread().getName() + ":" + segmentServiceImpl.getId()); - } - }; - // 开13,23,43个线程进行测试,step设置为10 - int runnerCount = 43; - TestRunnable[] trs = new TestRunnable[runnerCount]; - for (int i = 0; i < runnerCount; i++) { - trs[i] = runner; - } - - MultiThreadedTestRunner mttr = new MultiThreadedTestRunner(trs); - try { - mttr.runTestRunnables(); - } catch (Throwable e) { - e.printStackTrace(); - } - - } - - class LeafThread extends Thread { - @Override - public void run() { - System.out.println(this.getName() + "的id:" + segmentServiceImpl.getId()); - } - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_uid/src/test/resources/app-zk.xml b/jun_java_plugins/jun_uid/src/test/resources/app-zk.xml deleted file mode 100644 index 5455e18484..0000000000 --- a/jun_java_plugins/jun_uid/src/test/resources/app-zk.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_uid/src/test/resources/idleaf/app-leaf.xml b/jun_java_plugins/jun_uid/src/test/resources/idleaf/app-leaf.xml deleted file mode 100644 index 990d483df4..0000000000 --- a/jun_java_plugins/jun_uid/src/test/resources/idleaf/app-leaf.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_uid/src/test/resources/idleaf/app-springId.xml b/jun_java_plugins/jun_uid/src/test/resources/idleaf/app-springId.xml deleted file mode 100644 index c3d58b2331..0000000000 --- a/jun_java_plugins/jun_uid/src/test/resources/idleaf/app-springId.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_uid/src/test/resources/redis.properties b/jun_java_plugins/jun_uid/src/test/resources/redis.properties deleted file mode 100644 index 74ee161839..0000000000 --- a/jun_java_plugins/jun_uid/src/test/resources/redis.properties +++ /dev/null @@ -1,22 +0,0 @@ -redis.hostName=172.16.51.123 -redis.port=6379 -redis.password=ecp -# \u8fde\u63a5\u8d85\u65f6\u65f6\u95f4 -redis.timeout=10000 - -#\u6700\u5927\u7a7a\u95f2\u6570 -redis.maxIdle=300 -#\u63a7\u5236\u4e00\u4e2apool\u53ef\u5206\u914d\u591a\u5c11\u4e2ajedis\u5b9e\u4f8b,\u7528\u6765\u66ff\u6362\u4e0a\u9762\u7684redis.maxActive,\u5982\u679c\u662fjedis 2.4\u4ee5\u540e\u7528\u8be5\u5c5e\u6027 -redis.maxTotal=1000 -#\u6700\u5927\u5efa\u7acb\u8fde\u63a5\u7b49\u5f85\u65f6\u95f4\u3002\u5982\u679c\u8d85\u8fc7\u6b64\u65f6\u95f4\u5c06\u63a5\u5230\u5f02\u5e38\u3002\u8bbe\u4e3a-1\u8868\u793a\u65e0\u9650\u5236\u3002 -redis.maxWaitMillis=1000 -#\u8fde\u63a5\u7684\u6700\u5c0f\u7a7a\u95f2\u65f6\u95f4 \u9ed8\u8ba41800000\u6beb\u79d2(30\u5206\u949f) -redis.minEvictableIdleTimeMillis=300000 -#\u6bcf\u6b21\u91ca\u653e\u8fde\u63a5\u7684\u6700\u5927\u6570\u76ee,\u9ed8\u8ba43 -redis.numTestsPerEvictionRun=1024 -#\u9010\u51fa\u626b\u63cf\u7684\u65f6\u95f4\u95f4\u9694(\u6beb\u79d2) \u5982\u679c\u4e3a\u8d1f\u6570,\u5219\u4e0d\u8fd0\u884c\u9010\u51fa\u7ebf\u7a0b, \u9ed8\u8ba4-1 -redis.timeBetweenEvictionRunsMillis=30000 -#\u662f\u5426\u5728\u4ece\u6c60\u4e2d\u53d6\u51fa\u8fde\u63a5\u524d\u8fdb\u884c\u68c0\u9a8c,\u5982\u679c\u68c0\u9a8c\u5931\u8d25,\u5219\u4ece\u6c60\u4e2d\u53bb\u9664\u8fde\u63a5\u5e76\u5c1d\u8bd5\u53d6\u51fa\u53e6\u4e00\u4e2a -redis.testOnBorrow=true -#\u5728\u7a7a\u95f2\u65f6\u68c0\u67e5\u6709\u6548\u6027, \u9ed8\u8ba4false -redis.testWhileIdle=true \ No newline at end of file diff --git a/jun_java_plugins/jun_uid/src/test/resources/uid/cached-uid-baidu.xml b/jun_java_plugins/jun_uid/src/test/resources/uid/cached-uid-baidu.xml deleted file mode 100644 index 6e5b82a68b..0000000000 --- a/jun_java_plugins/jun_uid/src/test/resources/uid/cached-uid-baidu.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/jun_java_plugins/jun_uid/src/test/resources/uid/default-uid-baidu.xml b/jun_java_plugins/jun_uid/src/test/resources/uid/default-uid-baidu.xml deleted file mode 100644 index 8dfe126c74..0000000000 --- a/jun_java_plugins/jun_uid/src/test/resources/uid/default-uid-baidu.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/jun_java_plugins/jun_uid/src/test/resources/uid/mybatis-uid.xml b/jun_java_plugins/jun_uid/src/test/resources/uid/mybatis-uid.xml deleted file mode 100644 index 4b1815bc39..0000000000 --- a/jun_java_plugins/jun_uid/src/test/resources/uid/mybatis-uid.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/jun_java_plugins/jun_uid/src/test/resources/uid/simple-uid-baidu.xml b/jun_java_plugins/jun_uid/src/test/resources/uid/simple-uid-baidu.xml deleted file mode 100644 index df60c705cc..0000000000 --- a/jun_java_plugins/jun_uid/src/test/resources/uid/simple-uid-baidu.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/jun_java_plugins/jun_uid/src/test/resources/uid/uid-default.properties b/jun_java_plugins/jun_uid/src/test/resources/uid/uid-default.properties deleted file mode 100644 index 95e2c28a3c..0000000000 --- a/jun_java_plugins/jun_uid/src/test/resources/uid/uid-default.properties +++ /dev/null @@ -1,23 +0,0 @@ -#datasource db info -jdbc.driver=com.mysql.jdbc.Driver -jdbc.url=jdbc:mysql://172.16.51.52:3306/test?characterEncoding=UTF-8&useSSL=false -jdbc.username=root -jdbc.password=5hMEUO9LQFOtSU3 -jdbc.maxActive=2 - -#datasource base -datasource.defaultAutoCommit=true -datasource.initialSize=2 -datasource.minIdle=0 -datasource.maxWait=5000 -datasource.testWhileIdle=true -datasource.testOnBorrow=true -datasource.testOnReturn=false -datasource.validationQuery=SELECT 1 FROM DUAL -datasource.timeBetweenEvictionRunsMillis=30000 -datasource.minEvictableIdleTimeMillis=60000 -datasource.logAbandoned=true -datasource.removeAbandoned=true -datasource.removeAbandonedTimeout=120 -datasource.filters=stat - diff --git a/jun_java_plugins/jun_uid/src/test/resources/uid/zk-uid-baidu.xml b/jun_java_plugins/jun_uid/src/test/resources/uid/zk-uid-baidu.xml deleted file mode 100644 index 5f3351ebf1..0000000000 --- a/jun_java_plugins/jun_uid/src/test/resources/uid/zk-uid-baidu.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/jun_java_plugins/jun_upload_jsp_servlet/.gitignore b/jun_java_plugins/jun_upload_jsp_servlet/.gitignore deleted file mode 100644 index 96374c4e7f..0000000000 --- a/jun_java_plugins/jun_upload_jsp_servlet/.gitignore +++ /dev/null @@ -1,43 +0,0 @@ -# Windows image file caches -Thumbs.db -ehthumbs.db - -# Folder config file -Desktop.ini - -# Recycle Bin used on file shares -$RECYCLE.BIN/ - -# Windows Installer files -*.cab -*.msi -*.msm -*.msp - -# Windows shortcuts -*.lnk - -# ========================= -# Operating System Files -# ========================= - -# OSX -# ========================= - -.DS_Store -.AppleDouble -.LSOverride - -# Thumbnails -._* - -# Files that might appear on external disk -.Spotlight-V100 -.Trashes - -# Directories potentially created on remote AFP share -.AppleDB -.AppleDesktop -Network Trash Folder -Temporary Items -.apdisk diff --git a/jun_java_plugins/jun_upload_jsp_servlet/pom.xml b/jun_java_plugins/jun_upload_jsp_servlet/pom.xml deleted file mode 100644 index 49dfc51081..0000000000 --- a/jun_java_plugins/jun_upload_jsp_servlet/pom.xml +++ /dev/null @@ -1,53 +0,0 @@ - - 4.0.0 - - io.github.wujun728 - jun_upload_jsp_servlet - 1.0 - - - - junit - junit - 3.8.1 - test - - - log4j - log4j - 1.2.17 - - - javax.servlet - javax.servlet-api - 3.1.0 - - - - commons-httpclient - commons-httpclient - 3.1 - - - - - jsp_upload - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.1 - - 8 - 8 - UTF-8 - - - - - diff --git a/jun_java_plugins/jun_upload_jsp_servlet/src/main/java/com/google/servlet/FileLoadServlet.java b/jun_java_plugins/jun_upload_jsp_servlet/src/main/java/com/google/servlet/FileLoadServlet.java deleted file mode 100644 index 734a494421..0000000000 --- a/jun_java_plugins/jun_upload_jsp_servlet/src/main/java/com/google/servlet/FileLoadServlet.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.google.servlet; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.log4j.Logger; - -// @WebServlet(name = "FileLoadServlet", urlPatterns = {"/fileload"}) -public class FileLoadServlet extends HttpServlet { - - private static Logger logger = Logger.getLogger(FileLoadServlet.class); - - /** - * - */ - private static final long serialVersionUID = 1302377908285976972L; - - @Override - protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - logger.info("------------ FileLoadServlet ------------"); - - if (request.getContentLength() > 0) { - - InputStream inputStream = null; - FileOutputStream outputStream = null; - - try { - - inputStream = request.getInputStream(); - // 给新文件拼上时间毫秒,防止重名 - long now = System.currentTimeMillis(); - File file = new File("c:/", "file-" + now + ".txt"); - file.createNewFile(); - - outputStream = new FileOutputStream(file); - - byte temp[] = new byte[1024]; - int size = -1; - while ((size = inputStream.read(temp)) != -1) { // 每次读取1KB,直至读完 - outputStream.write(temp, 0, size); - } - - logger.info("File load success."); - } catch (IOException e) { - logger.warn("File load fail.", e); - request.getRequestDispatcher("/fail.jsp").forward(request, response); - } finally { - outputStream.close(); - inputStream.close(); - } - } - - request.getRequestDispatcher("/succ.jsp").forward(request, response); - } - -} diff --git a/jun_java_plugins/jun_upload_jsp_servlet/src/main/java/com/google/tool/FileLoadClient.java b/jun_java_plugins/jun_upload_jsp_servlet/src/main/java/com/google/tool/FileLoadClient.java deleted file mode 100644 index 0041465494..0000000000 --- a/jun_java_plugins/jun_upload_jsp_servlet/src/main/java/com/google/tool/FileLoadClient.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.google.tool; - -import java.io.BufferedReader; -import java.io.File; -import java.io.InputStream; -import java.io.InputStreamReader; - -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpStatus; -import org.apache.commons.httpclient.methods.PostMethod; -import org.apache.commons.httpclient.methods.multipart.FilePart; -import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; -import org.apache.commons.httpclient.methods.multipart.Part; -import org.apache.log4j.Logger; - -public class FileLoadClient { - - private static Logger logger = Logger.getLogger(FileLoadClient.class); - - public static String fileload(String url, File file) { - String body = "{}"; - - if (url == null || url.equals("")) { - return "参数不合法"; - } - if (!file.exists()) { - return "要上传的文件名不存在"; - } - - PostMethod postMethod = new PostMethod(url); - - try { - - // FilePart:用来上传文件的类,file即要上传的文件 - FilePart fp = new FilePart("file", file); - Part[] parts = { fp }; - - // 对于MIME类型的请求,httpclient建议全用MulitPartRequestEntity进行包装 - MultipartRequestEntity mre = new MultipartRequestEntity(parts, postMethod.getParams()); - postMethod.setRequestEntity(mre); - - HttpClient client = new HttpClient(); - // 由于要上传的文件可能比较大 , 因此在此设置最大的连接超时时间 - client.getHttpConnectionManager().getParams() .setConnectionTimeout(50000); - - int status = client.executeMethod(postMethod); - if (status == HttpStatus.SC_OK) { - InputStream inputStream = postMethod.getResponseBodyAsStream(); - BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); - - StringBuffer stringBuffer = new StringBuffer(); - String str = ""; - while ((str = br.readLine()) != null) { - stringBuffer.append(str); - } - - body = stringBuffer.toString(); - - } else { - body = "fail"; - } - } catch (Exception e) { - logger.warn("上传文件异常", e); - } finally { - // 释放连接 - postMethod.releaseConnection(); - } - - return body; - } - - - public static void main(String[] args) throws Exception { - String body = fileload("http://localhost:8080/jsp_upload-servlet/fileload", new File("C:/1111.txt")); - System.out.println(body); - } - -} diff --git a/jun_java_plugins/jun_upload_jsp_servlet/src/main/resources/log4j.properties b/jun_java_plugins/jun_upload_jsp_servlet/src/main/resources/log4j.properties deleted file mode 100644 index 1c9db917f1..0000000000 --- a/jun_java_plugins/jun_upload_jsp_servlet/src/main/resources/log4j.properties +++ /dev/null @@ -1,32 +0,0 @@ -# -# Copyright (c) 2012. Hortonworks, Inc. All rights reserved -# - -log4j.rootCategory=INFO,STDOUT,ROLLING_FILE -log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender -log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout -log4j.appender.STDOUT.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%t] %p %c{2} %x: %m%n -######################## -# Rolling File -######################## -log4j.appender.ROLLING_FILE=org.apache.log4j.RollingFileAppender -log4j.appender.ROLLING_FILE.Threshold=INFO -log4j.appender.ROLLING_FILE.File=jsp_upload-servlet.log -log4j.appender.ROLLING_FILE.Append=true -log4j.appender.ROLLING_FILE.MaxFileSize=1024KB -log4j.appender.ROLLING_FILE.MaxBackupIndex=1 -log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout -log4j.appender.ROLLING_FILE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n - -# All hibernate log output of "info" level or higher goes to stdout. -# For more verbose logging, change the "info" to "debug" on the last line. -log4j.logger.org.hibernate.ps.PreparedStatementCache=WARN -log4j.logger.org.hibernate=WARN - -# Changing the log level to DEBUG will result in Hibernate generated -# SQL to be logged. -log4j.logger.org.hibernate.SQL=ERROR - -# Changing the log level to DEBUG will result in the PreparedStatement -# bound variable values to be logged. -log4j.logger.org.hibernate.type=ERROR \ No newline at end of file diff --git a/jun_java_plugins/jun_upload_jsp_servlet/src/main/webapp/WEB-INF/web.xml b/jun_java_plugins/jun_upload_jsp_servlet/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 1c1c388a3f..0000000000 --- a/jun_java_plugins/jun_upload_jsp_servlet/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - Archetype Created Web Application - - - - FileLoadServlet - com.google.servlet.FileLoadServlet - - - FileLoadServlet - /fileload - - - diff --git a/jun_java_plugins/jun_upload_jsp_servlet/src/main/webapp/fail.jsp b/jun_java_plugins/jun_upload_jsp_servlet/src/main/webapp/fail.jsp deleted file mode 100644 index e8d64a1c91..0000000000 --- a/jun_java_plugins/jun_upload_jsp_servlet/src/main/webapp/fail.jsp +++ /dev/null @@ -1,9 +0,0 @@ - - - - - -

    File upload fail

    -return - - diff --git a/jun_java_plugins/jun_upload_jsp_servlet/src/main/webapp/index.jsp b/jun_java_plugins/jun_upload_jsp_servlet/src/main/webapp/index.jsp deleted file mode 100644 index 52f675f2e4..0000000000 --- a/jun_java_plugins/jun_upload_jsp_servlet/src/main/webapp/index.jsp +++ /dev/null @@ -1,12 +0,0 @@ - - - - - -

    File upload demo

    -
    -
    - -
    - - diff --git a/jun_java_plugins/jun_upload_jsp_servlet/src/main/webapp/index_multi.jsp b/jun_java_plugins/jun_upload_jsp_servlet/src/main/webapp/index_multi.jsp deleted file mode 100644 index ea2d90bdac..0000000000 --- a/jun_java_plugins/jun_upload_jsp_servlet/src/main/webapp/index_multi.jsp +++ /dev/null @@ -1,14 +0,0 @@ - - - - - -

    File upload demo

    -
    -
    -
    -
    - -
    - - diff --git a/jun_java_plugins/jun_upload_jsp_servlet/src/main/webapp/succ.jsp b/jun_java_plugins/jun_upload_jsp_servlet/src/main/webapp/succ.jsp deleted file mode 100644 index c5526e7210..0000000000 --- a/jun_java_plugins/jun_upload_jsp_servlet/src/main/webapp/succ.jsp +++ /dev/null @@ -1,9 +0,0 @@ - - - - - -

    File upload success

    -return - - diff --git "a/jun_java_plugins/jun_upload_jsp_servlet/\345\217\202\350\200\203.txt" "b/jun_java_plugins/jun_upload_jsp_servlet/\345\217\202\350\200\203.txt" deleted file mode 100644 index e622a93b6e..0000000000 --- "a/jun_java_plugins/jun_upload_jsp_servlet/\345\217\202\350\200\203.txt" +++ /dev/null @@ -1,3 +0,0 @@ -http://zhangjunhd.blog.51cto.com/113473/19631/ -http://kb.cnblogs.com/page/130970/ -http://www.cnblogs.com/ITtangtang/p/3968093.html \ No newline at end of file diff --git a/jun_java_plugins/jun_webmagic/pom.xml b/jun_java_plugins/jun_webmagic/pom.xml deleted file mode 100644 index 48786ef28b..0000000000 --- a/jun_java_plugins/jun_webmagic/pom.xml +++ /dev/null @@ -1,113 +0,0 @@ - - 4.0.0 - io.github.wujun728 - jun_webmagic - 1.0 - - - - jar - - - UTF-8 - - - - - us.codecraft - webmagic-core - 1.0.0 - - - us.codecraft - webmagic-extension - 1.0.0 - - - us.codecraft - webmagic-extension - 1.0.0 - - - org.slf4j - slf4j-log4j12 - - - - - - junit - junit - 4.12 - - - - - org.jsoup - jsoup - 1.10.3 - - - - commons-dbutils - commons-dbutils - 1.7 - - - - - - com.alibaba - druid - 1.0.29 - - - - mysql - mysql-connector-java - 5.1.41 - - - - - javax.servlet - javax.servlet-api - 4.0.1 - - - - - - - org.slf4j - slf4j-api - 1.8.0-beta4 - - - org.slf4j - slf4j-log4j12 - 1.8.0-beta4 - - - log4j - log4j - 1.2.17 - - - - \ No newline at end of file diff --git a/jun_java_plugins/jun_webmagic/src/main/java/jun_webmagic/AniMusicProcessor2.java b/jun_java_plugins/jun_webmagic/src/main/java/jun_webmagic/AniMusicProcessor2.java deleted file mode 100644 index 1c1775ecbc..0000000000 --- a/jun_java_plugins/jun_webmagic/src/main/java/jun_webmagic/AniMusicProcessor2.java +++ /dev/null @@ -1,70 +0,0 @@ -package jun_webmagic; - - -import us.codecraft.webmagic.Page; -import us.codecraft.webmagic.Site; -import us.codecraft.webmagic.Spider; -import us.codecraft.webmagic.pipeline.ConsolePipeline; -import us.codecraft.webmagic.processor.PageProcessor; -import us.codecraft.webmagic.selector.Selectable; - -import java.util.List; - -/** - * - * @author ReverieNight@Foxmail.com - * - */ -public class AniMusicProcessor2 implements PageProcessor{ - - private Site site = Site.me().setSleepTime(1000).setRetryTimes(3); - - //列表页的正则表达式 - public static final String URL_LIST = "http://xh2\\.1024xp2\\.com/pw/thread\\.php?fid=14"; - public static final String URL_POST = "http://xh2\\.1024xp2\\.com/pw/html_data/14/1907/[0-9]{7}\\.html"; - - @Override - public Site getSite() { - return site; - } - - @Override - public void process(Page page) { - //列表页 - System.err.println(page.getUrl()); - Selectable se = page.getUrl(); - se.toString(); - System.err.println(se.toString()); - List requests = page.getHtml().links().regex(URL_LIST).all(); - - System.err.println(page.getHtml().links().toString()); - page.addTargetRequests(requests); - if (page.getUrl().toString().startsWith("http://xh2.1024xp2.com/pw/thread.php?fid=14") ) { -// if (page.getUrl().regex(URL_LIST).match()) { -// System.err.println(page.getHtml()); - List l_post = page.getHtml().xpath("//*[@id=\"ajaxtable\"]/tbody[2]").links().regex(URL_POST).all(); //目标详情 - List l_url = page.getHtml().links().regex(URL_LIST).all(); //所有的列表 - page.addTargetRequests(l_post); - page.addTargetRequests(l_url); - //详情页 - } else { -// String title = page.getHtml().xpath("//div[@class='location']").regex("\\[[\\S|\\s]+\\<").toString(); //匹配标题 -// page.putField("title", title.substring(0, title.length() - 1).trim()); -// page.putField("torrent", page.getHtml().xpath("//p[@class='original download']").links().toString().trim()); //匹配种子 - String title = page.getHtml().xpath("//*[@id=\"breadCrumb\"]/font/a[4]/text()").get(); - String content = page.getHtml().xpath("//*[@id=\"read_tpc\"]/img[1]/").get(); - System.err.println("title="+title+",content="+content); - System.err.println(); - } - } - - public static void main(String[] args) { - Spider.create(new AniMusicProcessor2()) - .addUrl("http://xh2.1024xp2.com/pw/thread.php?fid=14") //开始地址 - .addPipeline(new ConsolePipeline()) //打印到控制台 -// .addPipeline(new FilePipeline("D:\\webmagic\\AniMusic")) //保存到文件夹 - .thread(5) //开启5线程 - .run(); - } - -} diff --git a/jun_java_plugins/jun_webmagic/src/main/java/jun_webmagic/GithubRepoPageProcessor2.java b/jun_java_plugins/jun_webmagic/src/main/java/jun_webmagic/GithubRepoPageProcessor2.java deleted file mode 100644 index 81349d5e9c..0000000000 --- a/jun_java_plugins/jun_webmagic/src/main/java/jun_webmagic/GithubRepoPageProcessor2.java +++ /dev/null @@ -1,46 +0,0 @@ -package jun_webmagic; - -import us.codecraft.webmagic.Page; -import us.codecraft.webmagic.Site; -import us.codecraft.webmagic.Spider; -import us.codecraft.webmagic.processor.PageProcessor; - -public class GithubRepoPageProcessor2 implements PageProcessor { - - // 部分一:抓取网站的相关配置,包括编码、抓取间隔、重试次数等 - private Site site = Site.me().setRetryTimes(3).setSleepTime(1000); - - @Override - // process是定制爬虫逻辑的核心接口,在这里编写抽取逻辑 - public void process(Page page) { - System.out.println(page.getUrl().get()); - - // 部分二:定义如何抽取页面信息,并保存下来 - page.putField("author", page.getUrl().regex("https://github\\.com/(\\w+)/.*").toString()); - page.putField("name", page.getHtml().xpath("//h1[@class='entry-title public']/strong/a/text()").toString()); - if (page.getResultItems().get("name") == null) { - // 不符合规则的,跳过该页面 - page.setSkip(true); - } - page.putField("readme", page.getHtml().xpath("//div[@id='readme']/tidyText()")); - - // 部分三:从页面发现后续的url地址来抓取 - page.addTargetRequests(page.getHtml().links().regex("(https://github\\.com/[\\w\\-]+/[\\w\\-]+)").all()); - } - - @Override - public Site getSite() { - return site; - } - - public static void main(String[] args) { - - Spider.create(new GithubRepoPageProcessor()) - //从该页面开始抓 - .addUrl("https://github.com/code4craft") - //开启5个线程抓取 - .thread(5) - //启动爬虫 - .run(); - } -} diff --git a/jun_java_plugins/jun_webmagic/src/main/java/jun_webmagic/OschinaBlog.java b/jun_java_plugins/jun_webmagic/src/main/java/jun_webmagic/OschinaBlog.java deleted file mode 100644 index 90de6cb9b5..0000000000 --- a/jun_java_plugins/jun_webmagic/src/main/java/jun_webmagic/OschinaBlog.java +++ /dev/null @@ -1,28 +0,0 @@ -package jun_webmagic; - -import us.codecraft.webmagic.Site; -import us.codecraft.webmagic.model.ConsolePageModelPipeline; -import us.codecraft.webmagic.model.OOSpider; -import us.codecraft.webmagic.model.annotation.ExtractBy; -import us.codecraft.webmagic.model.annotation.TargetUrl; - -import java.util.List; - -@TargetUrl("http://my.oschina.net/flashsword/blog/\\d+") -public class OschinaBlog { - - @ExtractBy("//title") - private String title; - - @ExtractBy(value = "div.BlogContent",type = ExtractBy.Type.Css) - private String content; - - @ExtractBy(value = "//div[@class='BlogTags']/a/text()", multi = true) - private List tags; - - public static void main(String[] args) { - OOSpider.create( - Site.me(), - new ConsolePageModelPipeline(), OschinaBlog.class).addUrl("http://my.oschina.net/flashsword/blog").run(); - } -} diff --git a/jun_java_plugins/jun_webmagic/src/main/java/jun_webmagic/OschinaBlogPageProcessor.java b/jun_java_plugins/jun_webmagic/src/main/java/jun_webmagic/OschinaBlogPageProcessor.java deleted file mode 100644 index 848e05e6ef..0000000000 --- a/jun_java_plugins/jun_webmagic/src/main/java/jun_webmagic/OschinaBlogPageProcessor.java +++ /dev/null @@ -1,36 +0,0 @@ -package jun_webmagic; - -import com.alibaba.druid.support.json.JSONUtils; -import us.codecraft.webmagic.Page; -import us.codecraft.webmagic.Site; -import us.codecraft.webmagic.Spider; -import us.codecraft.webmagic.pipeline.ConsolePipeline; -import us.codecraft.webmagic.processor.PageProcessor; - -import java.util.List; - -public class OschinaBlogPageProcessor implements PageProcessor { - - private Site site = Site.me().setDomain("my.oschina.net"); - - @Override - public void process(Page page) { - List links = page.getHtml().links().regex("https://my\\.oschina\\.net/flashsword/blog/\\d+").all(); - page.addTargetRequests(links); - page.putField("title", page.getHtml().xpath("//div[@class='BlogEntity']/div[@class='BlogTitle']/h1").toString()); - page.putField("content", page.getHtml().$("div.content").toString()); - page.putField("tags",page.getHtml().xpath("//div[@class='BlogTags']/a/text()").all()); - System.out.println(JSONUtils.toJSONString(page)); - } - - @Override - public Site getSite() { - return site; - - } - - public static void main(String[] args) { - Spider.create(new OschinaBlogPageProcessor()).addUrl("https://my.oschina.net/flashsword/blog") - .addPipeline(new ConsolePipeline()).run(); - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_webmagic/src/test/java/dbutils/QueryRunnerCRUDTest.java b/jun_java_plugins/jun_webmagic/src/test/java/dbutils/QueryRunnerCRUDTest.java deleted file mode 100644 index 2bb7ca1603..0000000000 --- a/jun_java_plugins/jun_webmagic/src/test/java/dbutils/QueryRunnerCRUDTest.java +++ /dev/null @@ -1,130 +0,0 @@ -package dbutils; - - -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.sql.SQLException; -import java.util.Date; -import java.util.List; - -import javax.sql.rowset.serial.SerialClob; - -import org.apache.commons.dbutils.QueryRunner; -import org.apache.commons.dbutils.handlers.BeanHandler; -import org.apache.commons.dbutils.handlers.BeanListHandler; -import org.junit.Test; - - -/** -*ResultSetHandler鎺ュ彛鐨勫疄鐜扮被 -ArrayHandler锛氭妸缁撴灉闆嗕腑鐨勭涓�琛屾暟鎹浆鎴愬璞℃暟缁勩�� -ArrayListHandler锛氭妸缁撴灉闆嗕腑鐨勬瘡涓�琛屾暟鎹兘杞垚涓�涓暟缁勶紝鍐嶅瓨鏀惧埌List涓�� -BeanHandler锛氬皢缁撴灉闆嗕腑鐨勭涓�琛屾暟鎹皝瑁呭埌涓�涓搴旂殑JavaBean瀹炰緥涓�� -BeanListHandler锛氬皢缁撴灉闆嗕腑鐨勬瘡涓�琛屾暟鎹兘灏佽鍒颁竴涓搴旂殑JavaBean瀹炰緥涓紝瀛樻斁鍒癓ist閲屻�� -ColumnListHandler锛氬皢缁撴灉闆嗕腑鏌愪竴鍒楃殑鏁版嵁瀛樻斁鍒癓ist涓�� -KeyedHandler(name)锛氬皢缁撴灉闆嗕腑鐨勬瘡涓�琛屾暟鎹兘灏佽鍒颁竴涓狹ap閲岋紝鍐嶆妸杩欎簺map鍐嶅瓨鍒颁竴涓猰ap閲岋紝鍏秌ey涓烘寚瀹氱殑key銆� -MapHandler锛氬皢缁撴灉闆嗕腑鐨勭涓�琛屾暟鎹皝瑁呭埌涓�涓狹ap閲岋紝key鏄垪鍚嶏紝value灏辨槸瀵瑰簲鐨勫�笺�� -MapListHandler锛氬皢缁撴灉闆嗕腑鐨勬瘡涓�琛屾暟鎹兘灏佽鍒颁竴涓狹ap閲岋紝鐒跺悗鍐嶅瓨鏀惧埌List -*/ - -public class QueryRunnerCRUDTest { - - /* - *娴嬭瘯琛� - create table users( - id int primary key auto_increment, - name varchar(40), - password varchar(40), - email varchar(60), - birthday date - ); - */ - - @Test - public void add() throws SQLException { - //灏嗘暟鎹簮浼犻�掔粰QueryRunner锛孮ueryRunner鍐呴儴閫氳繃鏁版嵁婧愯幏鍙栨暟鎹簱杩炴帴 - QueryRunner qr = new QueryRunner(DBUtils.getDataSource()); - String sql = "insert into users(name,password,email,birthday) values(?,?,?,?)"; - Object params[] = {"1111","11122", "gacl@sina.com", new Date()}; - //Object params[] = {"鐧借檸绁炵殗","123", "gacl@sina.com", "1988-05-07"}; - qr.update(sql, params); - } - - @Test - public void delete() throws SQLException { - - QueryRunner qr = new QueryRunner(DBUtils.getDataSource()); - String sql = "delete from users where id=?"; - qr.update(sql, 1); - - } - - @Test - public void update() throws SQLException { - QueryRunner qr = new QueryRunner(DBUtils.getDataSource()); - String sql = "update users set name=? where id=?"; - Object params[] = { "ddd", 5}; - qr.update(sql, params); - } - - @Test - public void find() throws SQLException { - QueryRunner qr = new QueryRunner(DBUtils.getDataSource()); - String sql = "select * from users where id=?"; - Object params[] = {2}; -// User user = (User) qr.query(sql, params, new BeanHandler(User.class)); -// System.out.println(user.getBirthday()); - } - - @Test - public void getAll() throws SQLException { - QueryRunner qr = new QueryRunner(DBUtils.getDataSource()); - String sql = "select * from users"; -// List list = (List) qr.query(sql, new BeanListHandler(User.class)); -// System.out.println(list.size()); - } - - /** - * @Method: testBatch - * @Description:鎵瑰鐞� - * @Anthor:瀛ゅ偛鑻嶇嫾 - * - * @throws SQLException - */ - @Test - public void testBatch() throws SQLException { - QueryRunner qr = new QueryRunner(DBUtils.getDataSource()); - String sql = "insert into users(name,password,email,birthday) values(?,?,?,?)"; - Object params[][] = new Object[10][]; - for (int i = 0; i < 10; i++) { - params[i] = new Object[] { "aa" + i, "123", "aa@sina.com", - new Date() }; - } - qr.batch(sql, params); - } - - //鐢╠butils瀹屾垚澶ф暟鎹紙涓嶅缓璁敤锛� - /*************************************************************************** - create table testclob - ( - id int primary key auto_increment, - resume text - ); - **************************************************************************/ - @Test - public void testclob() throws SQLException, IOException{ - QueryRunner runner = new QueryRunner(DBUtils.getDataSource()); - String sql = "insert into testclob(resume) values(?)"; //clob - //杩欑鏂瑰紡鑾峰彇鐨勮矾寰勶紝鍏朵腑鐨勭┖鏍间細琚娇鐢ㄢ��%20鈥濅唬鏇� - String path = QueryRunnerCRUDTest.class.getClassLoader().getResource("data.xml").getPath(); - //灏嗏��%20鈥濇浛鎹㈠洖绌烘牸 - path = path.replaceAll("%20", " "); - FileReader in = new FileReader(path); - char[] buffer = new char[(int) new File(path).length()]; - in.read(buffer); - SerialClob clob = new SerialClob(buffer); - Object params[] = {clob}; - runner.update(sql, params); - } -} \ No newline at end of file diff --git a/jun_java_plugins/jun_webservice/pom.xml b/jun_java_plugins/jun_webservice/pom.xml deleted file mode 100644 index a8e0e27fc7..0000000000 --- a/jun_java_plugins/jun_webservice/pom.xml +++ /dev/null @@ -1,237 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_webservice - 1.0 - war - - - UTF-8 - 1.8 - 1.8 - 5.0.2.RELEASE - 1.6.6 - 1.2.12 - 11.2.0.1.0 - 3.4.5 - 5.0.1.RELEASE - 2.9.1 - - - - - - org.slf4j - slf4j-api - 1.7.25 - - - - - org.apache.logging.log4j - log4j-slf4j-impl - ${log4j2.version} - - runtime - - true - - - - - org.apache.logging.log4j - log4j-core - ${log4j2.version} - runtime - true - - - org.apache.logging.log4j - log4j-api - ${log4j2.version} - runtime - true - - - - junit - junit - 3.8.1 - test - - - - - mysql - mysql-connector-java - 5.1.40 - - - - - - - - - - - - org.aspectj - aspectjweaver - 1.6.8 - - - org.springframework - spring-aop - ${spring.version} - - - org.springframework - spring-context - ${spring.version} - - - org.springframework - spring-context-support - ${spring.version} - - - org.springframework - spring-web - ${spring.version} - - - org.springframework - spring-orm - ${spring.version} - - - org.springframework - spring-beans - ${spring.version} - - - org.springframework - spring-core - ${spring.version} - - - org.springframework - spring-test - ${spring.version} - - - org.springframework - spring-webmvc - ${spring.version} - - - - org.springframework - spring-tx - ${spring.version} - - - junit - junit - 4.12 - test - - - - javax.servlet - javax.servlet-api - 3.1.0 - provided - - - javax.servlet.jsp - jsp-api - 2.0 - provided - - - jstl - jstl - 1.2 - - - - - - - - - - - - - - - - - - - - org.mybatis - mybatis - ${mybatis.version} - - - org.mybatis - mybatis-spring - 1.3.0 - - - com.github.pagehelper - pagehelper - 5.1.2 - - - org.springframework.security - spring-security-web - ${spring.security.version} - - - org.springframework.security - spring-security-config - ${spring.security.version} - - - org.springframework.security - spring-security-core - ${spring.security.version} - - - org.springframework.security - spring-security-taglibs - ${spring.security.version} - - - - mysql - mysql-connector-java - 5.1.46 - - - com.alibaba - druid - 1.1.19 - - - - javax.annotation - jsr250-api - 1.0 - - - - - - jun_log - - diff --git "a/jun_java_plugins/jun_webservice/webservice/WebService\344\271\213CXF\343\200\213\347\254\254\344\272\214\350\256\262 \346\272\220\347\240\201.zip" "b/jun_java_plugins/jun_webservice/webservice/WebService\344\271\213CXF\343\200\213\347\254\254\344\272\214\350\256\262 \346\272\220\347\240\201.zip" deleted file mode 100644 index c27336c7a0..0000000000 Binary files "a/jun_java_plugins/jun_webservice/webservice/WebService\344\271\213CXF\343\200\213\347\254\254\344\272\214\350\256\262 \346\272\220\347\240\201.zip" and /dev/null differ diff --git a/jun_java_plugins/jun_webservice/webservice/src/com/zhu/webservice/bean/UserBean.java b/jun_java_plugins/jun_webservice/webservice/src/com/zhu/webservice/bean/UserBean.java deleted file mode 100644 index a9f0843633..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/src/com/zhu/webservice/bean/UserBean.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.zhu.webservice.bean; - -public class UserBean { - int uid; - String username; - String password; - - public int getUid() { - return uid; - } - - public void setUid(int uid) { - this.uid = uid; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - -} diff --git a/jun_java_plugins/jun_webservice/webservice/src/com/zhu/webservice/controller/LoginController.java b/jun_java_plugins/jun_webservice/webservice/src/com/zhu/webservice/controller/LoginController.java deleted file mode 100644 index 458709365a..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/src/com/zhu/webservice/controller/LoginController.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.zhu.webservice.controller; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; - -import com.zhu.webservice.service.ILoginService; - -@Controller -@RequestMapping("/login") -public class LoginController { - - @Autowired - ILoginService loginService; - - @RequestMapping("/login") - public String showView() { - System.out.print("45"); - return "helloWorld"; - } - -} diff --git a/jun_java_plugins/jun_webservice/webservice/src/com/zhu/webservice/dao/IUserOperate.java b/jun_java_plugins/jun_webservice/webservice/src/com/zhu/webservice/dao/IUserOperate.java deleted file mode 100644 index 75d0315e6c..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/src/com/zhu/webservice/dao/IUserOperate.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.zhu.webservice.dao; - -import org.apache.ibatis.annotations.Select; -import org.springframework.stereotype.Repository; - -import com.zhu.webservice.bean.UserBean; - -@Repository -public interface IUserOperate { - @Select("select * from t_user where uid=#{id}") - public UserBean selectUserByID(int id); -} diff --git a/jun_java_plugins/jun_webservice/webservice/src/com/zhu/webservice/service/ILoginService.java b/jun_java_plugins/jun_webservice/webservice/src/com/zhu/webservice/service/ILoginService.java deleted file mode 100644 index 2f1f34edf1..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/src/com/zhu/webservice/service/ILoginService.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.zhu.webservice.service; - -import org.springframework.stereotype.Service; - -import com.zhu.webservice.bean.UserBean; - -@Service -public interface ILoginService { - - public abstract UserBean searchUser(UserBean user); - -} \ No newline at end of file diff --git a/jun_java_plugins/jun_webservice/webservice/src/com/zhu/webservice/service/impl/LoginServiceImpl.java b/jun_java_plugins/jun_webservice/webservice/src/com/zhu/webservice/service/impl/LoginServiceImpl.java deleted file mode 100644 index 4b070861a4..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/src/com/zhu/webservice/service/impl/LoginServiceImpl.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.zhu.webservice.service.impl; - -import com.zhu.webservice.bean.UserBean; -import com.zhu.webservice.dao.IUserOperate; -import com.zhu.webservice.service.ILoginService; - -public class LoginServiceImpl implements ILoginService { - IUserOperate userOperate; - - @Override - public UserBean searchUser(UserBean user) { - return userOperate.selectUserByID(user.getUid()); - } - - - -} diff --git a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/ServletModule.java b/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/ServletModule.java deleted file mode 100644 index 95680f520a..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/ServletModule.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.techsoft; - -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; -import java.util.Map; - -import org.apache.commons.fileupload.FileItem; - -public interface ServletModule { - - public static String JSONP = "callback"; - - public String getName(); - - public void process(Map in, boolean isMultiPart, - InputStream inputs, OutputStream outs, List list, - Map result, DataConverter dataConverter) - throws TechException; -} diff --git a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/TechException.java b/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/TechException.java deleted file mode 100644 index e09a4ea10b..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/TechException.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.techsoft; - -public class TechException extends Exception { - private static final long serialVersionUID = -1456070014374034056L; - - public TechException() { - super(); - } - - public TechException(String message) { - super(message); - } - - public TechException(String message, Throwable cause) { - super(message, cause); - } - - public TechException(Throwable cause) { - super(cause); - } - -} diff --git a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/container/DataServer.java b/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/container/DataServer.java deleted file mode 100644 index 174172e9c3..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/container/DataServer.java +++ /dev/null @@ -1,300 +0,0 @@ -package com.techsoft.container; - -import java.io.File; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.techsoft.servlet.ConfigProperties; -import com.techsoft.ConnectionPool; -import com.techsoft.ConnectionPoolException; -import com.techsoft.ServletModule; -import com.techsoft.TechException; -import com.techsoft.modules.LoginModule; -import com.techsoft.modules.LogoutModule; -import com.techsoft.modules.QueryMetaModule; -import com.techsoft.modules.QueryModule; -import com.techsoft.modules.QueryParamModule; -import com.techsoft.modules.SaveModule; -import com.techsoft.plugins.PluginManager; -import com.techsoft.pool.ConnectionPoolFactory; - -public class DataServer { - private static final Logger Log = LoggerFactory.getLogger(DataServer.class); - private static DataServer instance; - - private PluginManager pluginsManager; - private File webHome; - private Map coreHandlers; - private Map> pluginHandlers; - private Map> newpluginHandlers; - private ConfigProperties properties; - private ConnectionPool pool; - private boolean debug = false; - private boolean started = false; - - public boolean isStarted() { - return started; - } - - public void setDebug(boolean debug) { - this.debug = debug; - } - - public boolean isDebug() { - return debug; - } - - public ConnectionPool getPool() { - return pool; - } - - public ConfigProperties getProperties() { - return properties; - } - - public PluginManager getPluginsManager() { - return pluginsManager; - } - - public Map getCoreHandlers() { - return coreHandlers; - } - - public void addModule(ServletModule module) { - coreHandlers.put(module.getName().toLowerCase(), module); - } - - private boolean isExistpluginHandlers(ServletModule module) { - boolean result = false; - Map modules = null; - ServletModule iterModule = null; - Iterator> itermodules = pluginHandlers.values() - .iterator(); - while (itermodules.hasNext()) { - modules = itermodules.next(); - Iterator iter = modules.values().iterator(); - while (iter.hasNext()) { - iterModule = iter.next(); - if (iterModule.getName().equalsIgnoreCase(module.getName())) { - result = true; - break; - } - } - } - - return result; - } - - private boolean isExistnewPluginHandlers(ServletModule module) { - boolean result = false; - Map modules = null; - ServletModule iterModule = null; - Iterator> itermodules = newpluginHandlers.values() - .iterator(); - while (itermodules.hasNext()) { - modules = itermodules.next(); - Iterator iter = modules.values().iterator(); - while (iter.hasNext()) { - iterModule = iter.next(); - if (iterModule.getName().equalsIgnoreCase(module.getName())) { - result = true; - break; - } - } - } - - return result; - } - - public void addPluginModule(String pluginName, ServletModule module) - throws TechException { - if (isExistpluginHandlers(module)) { - if (!isExistnewPluginHandlers(module)) { - Map modules = null; - if (newpluginHandlers.get(pluginName) == null) { - modules = new HashMap(); - } else { - modules = newpluginHandlers.get(pluginName); - } - modules.put(module.getName(), module); - newpluginHandlers.put(pluginName, modules); - } else { - Log.error(module.getName() + " 此模块的的方法名称已经存在, 请修改模块名称!"); - throw new TechException(module.getName() - + " 此模块的的方法名称已经存在, 请修改模块名称!"); - } - } else { - Map modules = null; - if (pluginHandlers.get(pluginName) == null) { - modules = new HashMap(); - } else { - modules = pluginHandlers.get(pluginName); - } - modules.put(module.getName(), module); - pluginHandlers.put(pluginName, modules); - } - } - - public ServletModule getPluginModuleByMethod(String methodName) { - ServletModule result = null; - ServletModule module = null; - Iterator> itermap = newpluginHandlers.values() - .iterator(); - Map map = null; - Iterator iter = null; - while (itermap.hasNext()) { - map = itermap.next(); - iter = map.values().iterator(); - while (iter.hasNext()) { - module = iter.next(); - if (module.getName().equalsIgnoreCase(methodName)) { - result = module; - break; - } - } - } - - if (result == null) { - itermap = pluginHandlers.values().iterator(); - while (itermap.hasNext()) { - map = itermap.next(); - iter = map.values().iterator(); - while (iter.hasNext()) { - module = iter.next(); - if (module.getName().equalsIgnoreCase(methodName)) { - result = module; - break; - } - } - } - } - - return result; - } - - public void removePluginModule(String pluginName) { - if (pluginHandlers.get(pluginName) != null) { - pluginHandlers.remove(pluginName); - } else { - newpluginHandlers.remove(pluginName); - } - } - - public DataServer(File webHome) { - if (instance != null) { - Log.error("A server is already running"); - throw new IllegalStateException("A server is already running"); - } - this.webHome = webHome; - coreHandlers = new ConcurrentHashMap(); - pluginHandlers = new ConcurrentHashMap>(); - newpluginHandlers = new ConcurrentHashMap>(); - properties = new ConfigProperties(webHome); - - instance = this; - } - - public static DataServer getInstance() { - return instance; - } - - public void start() { - File pluginDir = null; - File logdir = null; - debug = Boolean.parseBoolean(properties.getisDebug()); - Integer maxpool = 5; - Integer minpool = 1; - Integer initpool = 1; - try { - maxpool = Integer.valueOf(properties.getMaxPool()); - } catch (Exception e) { - maxpool = 5; - } - try { - minpool = Integer.valueOf(properties.getMinPool()); - } catch (Exception e) { - minpool = 1; - } - try { - initpool = Integer.valueOf(properties.getDefaultPool()); - } catch (Exception e) { - initpool = 1; - } - - try { - pool = ConnectionPoolFactory.getInstance().getConnectionPool(); - - pool.setDriverName(properties.getDriver()); - pool.setJdbcURL(properties.getURL()); - pool.setUserName(properties.getUser()); - pool.setPassword(properties.getPassword()); - pool.setMaxPool(maxpool); - pool.setMinPool(minpool); - pool.setInitPool(initpool); - pool.setDatabaseType(properties.getDbtype()); - try { - pool.start(); - - this.addModule(QueryModule.getInstance()); - this.addModule(SaveModule.getInstance()); - this.addModule(LoginModule.getInstance()); - this.addModule(LogoutModule.getInstance()); - this.addModule(QueryParamModule.getInstance()); - this.addModule(QueryMetaModule.getInstance()); - pluginDir = new File(webHome, "plugins"); - if (!pluginDir.exists()) { - pluginDir.mkdirs(); - } - - logdir = new File(webHome, "logs"); - if (!logdir.exists()) { - logdir.mkdirs(); - } - // 必须等连接池启动完后才启动插件,因为插件有可能使用连接池 - pluginsManager = new PluginManager(pluginDir); - pluginsManager.setIsDebug(debug); - Log.info("pluginsManager debug is " - + pluginsManager.getIsDebug()); - pluginsManager.start(); - - started = true; - } catch (ConnectionPoolException e) { - this.shutdown(); - Log.error(e.getMessage(), e); - } - } catch (ConnectionPoolException e) { - this.shutdown(); - Log.error(e.getMessage(), e); - } - } - - public void shutdown() { - started = false; - if (pluginsManager != null) { - pluginsManager.shutdown(); - pluginsManager = null; - } - - if (pool != null) { - try { - pool.shutdown(); - } catch (Exception e) { - // 这里可能会有内存问题 - try { - pool.shutdown(); - } catch (Exception e1) { - // - } - } - pool = null; - } - coreHandlers.clear(); - pluginHandlers.clear(); - newpluginHandlers.clear(); - } -} diff --git a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/modules/LoginModule.java b/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/modules/LoginModule.java deleted file mode 100644 index e9b330a343..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/modules/LoginModule.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.techsoft.modules; - -import java.io.InputStream; -import java.io.OutputStream; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.fileupload.FileItem; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.alibaba.fastjson.JSONObject; -import com.techsoft.DataConverter; -import com.techsoft.ServletModule; -import com.techsoft.Session; -import com.techsoft.TechException; -import com.techsoft.session.SessionManager; -import com.techsoft.utils.DataSet; - -public class LoginModule implements ServletModule { - private static final Logger Log = LoggerFactory - .getLogger(LoginModule.class); - private static final String name = "login"; - private static LoginModule instance = null; - - private LoginModule() { - } - - public static LoginModule getInstance() { - if (instance == null) { - instance = new LoginModule(); - } - - return instance; - } - - @Override - public String getName() { - return name; - } - - public Map readUserInfo(String username, String password) - throws TechException { - Map result = null; - DataSet dataset = new DataSet(); - dataset.setSqlid(Session.loginsqlid); - dataset.getParams().put("psusercode", username); - dataset.getParams().put("pspassword", password); - try { - dataset.open(); - if (dataset.getRecordCount() > 0) { - result = new HashMap(dataset.getDatas().get(0)); - } else { - throw new TechException(String.valueOf(dataset - .getResultParams().get("pserrinfo"))); - } - } catch (Exception e) { - throw new TechException(e.getMessage()); - } finally { - dataset.close(); - } - - return result; - } - - public void createSession(Map in, InputStream input, - OutputStream output, DataConverter dataConverter, - Map result) throws TechException { - Map sessionobj = new HashMap(); - try { - Session session = null; - JSONObject inputjson = (JSONObject) dataConverter - .readFromInputStream(input); - String sessionid = inputjson.getString(Session.sessionid); - if ((sessionid != null) && (!sessionid.equals(""))) { - session = SessionManager.getInstance().getSession(sessionid); - if (session != null) { - // JSONObject userjson = (JSONObject) JSON.parse(session - // .getUserInfo()); - // sessionobj.put(StringConsts.username, - // userjson.getString(StringConsts.userNameField)); - // sessionobj.put(StringConsts.username, - // userjson.getString(StringConsts.passwordField)); - // sessionobj.put(StringConsts.sessionid, sessionid); - } else { - Map userinfo = this.readUserInfo( - inputjson.getString(Session.userNameField), - inputjson.getString(Session.userPasswordField)); - session = SessionManager.getInstance().CreateLocalSession(); - session.setLastAccessTime(System.currentTimeMillis()); - String passwordEntry = String.valueOf(userinfo - .get(Session.userPasswordField)); - userinfo.put(Session.userPasswordField, passwordEntry); - // session.setUserInfo(JSON.toJSONString(userinfo)); - SessionManager.getInstance().setSession(sessionid, session); - } - } else { - Map userinfo = this.readUserInfo( - inputjson.getString(Session.userNameField), - inputjson.getString(Session.userPasswordField)); - session = SessionManager.getInstance().CreateLocalSession(); - session.setLastAccessTime(System.currentTimeMillis()); - SessionManager.getInstance().setSession( - String.valueOf(in.get(Session.sessionid)), session); - } - } catch (Exception e) { - Log.error(e.getClass().getName() + " \n" + e.getMessage()); - throw new TechException(e.getClass().getName() + " \n" - + e.getMessage()); - } - } - - @Override - public void process(Map in, boolean isMultiPart, - InputStream inputs, OutputStream outs, List list, - Map results, DataConverter dataConverter) - throws TechException { - // createSession(in, input, output, serialization, results); - } -} diff --git a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/modules/LogoutModule.java b/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/modules/LogoutModule.java deleted file mode 100644 index eff282bd86..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/modules/LogoutModule.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.techsoft.modules; - -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; -import java.util.Map; - -import org.apache.commons.fileupload.FileItem; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.techsoft.DataConverter; -import com.techsoft.ServletModule; -import com.techsoft.TechException; - -public class LogoutModule implements ServletModule { - private static final Logger Log = LoggerFactory.getLogger(LogoutModule.class); - private static final String name = "logout"; - private static LogoutModule instance = null; - - private LogoutModule() { - Log.info("Log out..."); - } - - public static LogoutModule getInstance() { - if (instance == null) { - instance = new LogoutModule(); - } - - return instance; - } - - @Override - public String getName() { - return LogoutModule.name; - } - - public void removeSession(Map in, InputStream input, Map result) { - - } - - @Override - public void process(Map in, boolean isMultiPart, InputStream inputs, OutputStream outs, - List list, Map results, DataConverter dataConverter) throws TechException { - removeSession(in, inputs, results); - } - -} diff --git a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/modules/QueryMetaModule.java b/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/modules/QueryMetaModule.java deleted file mode 100644 index a1ee933122..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/modules/QueryMetaModule.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.techsoft.modules; - -import java.io.InputStream; -import java.io.OutputStream; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.apache.commons.fileupload.FileItem; - -import com.techsoft.DataConverter; -import com.techsoft.MetaData; -import com.techsoft.ServletModule; -import com.techsoft.TechException; -import com.techsoft.sql.SQLObjectManager; - -public class QueryMetaModule implements ServletModule { - - private static final String moduleName = "querymeta"; - private static final String metasqldefine = "metasqldefine"; - private static final String sql_options = "sql_options"; - private static QueryMetaModule instance = null; - - @Override - public String getName() { - return QueryMetaModule.moduleName; - } - - public static QueryMetaModule getInstance() { - if (instance == null) { - instance = new QueryMetaModule(); - } - - return instance; - } - - @SuppressWarnings("unchecked") - public Map readParamfromInputStream(Map in, - InputStream input, DataConverter dataConverter) { - Map result = null; - if (input != null) { - try { - Object obj = dataConverter.readFromInputStream(input); - if (obj != null) { - result = (Map) dataConverter - .deserializeObject(obj); - } else { - result = new HashMap(); - } - } catch (Exception e) { - // 输入流中可能不存在内容,在Ajax调用时 - result = new HashMap(); - } - - } else { - result = new HashMap(); - } - String key = null; - Object value = null; - Iterator iter = in.keySet().iterator(); - while (iter.hasNext()) { - key = iter.next(); - value = in.get(key); - value = dataConverter.deserializeObject(value); - result.put(key, value); - } - return result; - } - - @Override - public void process(Map in, boolean isMultiPart, - InputStream inputs, OutputStream outs, List list, - Map results, DataConverter dataConverter) - throws TechException { - try { - Map input = this.readParamfromInputStream(in, - inputs, dataConverter); - - String metaquerysql = (String) input - .get(QueryMetaModule.metasqldefine); - String sql_options = (String) input - .get(QueryMetaModule.sql_options); - Boolean checked = Integer.valueOf(sql_options) / Math.pow(2, 0) % 2 >= 1; - if (metaquerysql != null) { - metaquerysql = metaquerysql.toLowerCase().trim(); - } - List metaDatas = SQLObjectManager.getInstance() - .queryMetaData(metaquerysql, checked); - results.put("datas", metaDatas); - } catch (Exception e) { - throw new TechException(e.getClass().getName() + " \n" - + e.getMessage()); - } - } - -} diff --git a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/modules/QueryModule.java b/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/modules/QueryModule.java deleted file mode 100644 index 286f9513f2..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/modules/QueryModule.java +++ /dev/null @@ -1,305 +0,0 @@ -package com.techsoft.modules; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.sql.Connection; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.apache.commons.fileupload.FileItem; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.techsoft.Cache; -import com.techsoft.DBException; -import com.techsoft.DataConverter; -import com.techsoft.DataExecutor; -import com.techsoft.SQLObject; -import com.techsoft.SQLParam; -import com.techsoft.ServletModule; -import com.techsoft.StringConsts; -import com.techsoft.TechException; -import com.techsoft.cache.CacheFactory; -import com.techsoft.container.DataServer; -import com.techsoft.executor.DataExecutorFactory; -import com.techsoft.sql.SQLObjectManager; - -public class QueryModule implements ServletModule { - private static final Logger Log = LoggerFactory - .getLogger(QueryModule.class); - private static QueryModule instance = null; - - private QueryModule() { - } - - public static QueryModule getInstance() { - if (instance == null) { - instance = new QueryModule(); - } - - return instance; - } - - @Override - public String getName() { - return StringConsts.querymodule; - } - - private List> queryData(SQLObject sqlobj, - Map paramobj, Map globalParams, - Integer pageNo, Integer pageSize, DataExecutor executor, - Connection nativeconn, Map results) - throws SQLException, IOException, DBException { - /* - * Log.info("sqlid=" + sqlobj.getSqlId() + " params is " + - * paramobj.toString()); - */ - List> result = null; - Map ignoreCaseParams = new HashMap(); - Map ignoreCaseGlobalParams = new HashMap(); - Integer startnum = 0; - Integer endnum = 0; - if ((pageNo != null) && (pageNo > 0)) { - startnum = (pageNo - 1) * pageSize + 1; - endnum = pageNo * pageSize; - - paramobj.put("piStartNo", startnum); - paramobj.put("piEndNo", endnum); - } - - // 处理参数名称的大小写 - if (paramobj != null) { - String key = null; - Iterator strIter = paramobj.keySet().iterator(); - while (strIter.hasNext()) { - key = strIter.next(); - ignoreCaseParams.put(key.toLowerCase(), paramobj.get(key)); - } - } - - if (globalParams != null) { - String key = null; - Iterator strIter = globalParams.keySet().iterator(); - while (strIter.hasNext()) { - key = strIter.next(); - ignoreCaseGlobalParams.put(key.toLowerCase(), - globalParams.get(key)); - } - } - - SQLParam sqlparam = null; - SQLParam itersparam = null; - List params = new ArrayList(); - Iterator sqliters = sqlobj.getSelectParams().iterator(); - while (sqliters.hasNext()) { - sqlparam = new SQLParam(); - itersparam = sqliters.next(); - sqlparam.setDtype(itersparam.getDtype()); - sqlparam.setDtypename(itersparam.getDtypename()); - sqlparam.setIndex(itersparam.getIndex()); - sqlparam.setIotype(itersparam.getIotype()); - sqlparam.setName(itersparam.getName().toLowerCase()); - // sqlparam.buildPositions(); - params.add(sqlparam); - } - - Iterator iter = params.iterator(); - SQLParam param = null; - while (iter.hasNext()) { - param = iter.next(); - if (param.getName().equalsIgnoreCase(StringConsts.pageNo)) { - param.setValue(pageNo); - } else if (param.getName().equalsIgnoreCase(StringConsts.pageSize)) { - param.setValue(pageSize); - } else if (ignoreCaseParams.get(param.getName()) != null) { - param.setValue(ignoreCaseParams.get(param.getName())); - } else if (ignoreCaseGlobalParams.get(param.getName()) != null) { - param.setValue(ignoreCaseGlobalParams.get(param.getName())); - } - } - - if (!sqlobj.getIsCursor()) { - if (pageNo > 0) { - results.put(StringConsts.recordcount, executor - .queryRecordCount(sqlobj.getSelectSql(), params, - nativeconn)); - result = executor.queryDataByPage(sqlobj.getSelectSql(), false, - pageNo, pageSize, params, nativeconn); - } else { - result = executor.queryData(sqlobj.getSelectSql(), false, - params, nativeconn); - results.put(StringConsts.recordcount, result.size()); - } - } else { - result = executor.queryData(sqlobj.getSelectSql(), - sqlobj.getIsCursor(), params, nativeconn); - - if ((pageNo != null) && (pageNo > 0)) { - Iterator iterparam = params.iterator(); - while (iterparam.hasNext()) { - param = iterparam.next(); - if (param.getIotype().equalsIgnoreCase( - SQLParam.ParamType.out.name())) { - results.put(param.getName().toLowerCase(), - param.getValue()); - } - } - - if (results.get("piTotalRecord".toLowerCase()) != null) { - results.put(StringConsts.recordcount, - results.get("piTotalRecord".toLowerCase())); - } - } - } - - return result; - } - - @SuppressWarnings("unchecked") - public Map readParamfromInputStream(Map in, - InputStream input, DataConverter dataConverter) { - Map result = null; - if (input != null) { - try { - Object obj = dataConverter.readFromInputStream(input); - if (obj != null) { - result = (Map) dataConverter - .deserializeObject(obj); - } else { - result = new HashMap(); - } - } catch (Exception e) { - // 输入流中可能不存在内容,在Ajax调用时 - result = new HashMap(); - } - - } else { - result = new HashMap(); - } - String key = null; - Object value = null; - Iterator iter = in.keySet().iterator(); - while (iter.hasNext()) { - key = iter.next(); - value = in.get(key); - value = dataConverter.deserializeObject(value); - result.put(key, value); - } - return result; - } - - @SuppressWarnings("unchecked") - public Map queryService(Map inputs, - Map results) throws TechException { - String sqlid = null; - Integer pageno = 0; - Integer pagesize = 0; - Map paramobj = null; - try { - sqlid = (String) inputs.get(StringConsts.sqlid); - if ((sqlid == null) || (sqlid.equals(""))) { - throw new Exception("sqlid不能为空!"); - } - if ((inputs.get(StringConsts.pageNo) != null) - && (!inputs.get(StringConsts.pageNo).equals(""))) { - pageno = (Integer) inputs.get(StringConsts.pageNo); - } - if ((inputs.get(StringConsts.pageSize) != null) - && (!inputs.get(StringConsts.pageSize).equals(""))) { - pagesize = (Integer) inputs.get(StringConsts.pageSize); - } - if ((inputs.get(StringConsts.params) != null) - && (!inputs.get(StringConsts.params).equals(""))) { - paramobj = (Map) inputs - .get(StringConsts.params); - } - SQLObject sqlobj = SQLObjectManager.getInstance().getSQLObjectById( - sqlid); - if (sqlobj == null) { - throw new TechException("id值为 [" + sqlid - + "]的SQLObject并不存在, 请检查!"); - } - - Connection conn = DataServer.getInstance().getPool() - .getConnection(); - try { - Connection nativeconn = DataServer.getInstance().getPool() - .getNativeConnection(conn); - try { - DataExecutor executor = DataExecutorFactory - .getExecutor(DataServer.getInstance() - .getProperties().getDbtype()); - - List> datas = this.queryData(sqlobj, - paramobj, inputs, pageno, pagesize, executor, - nativeconn, results); - - results.put(StringConsts.outdata, datas); - results.put(StringConsts.outmetadata, sqlobj.getMetaDatas()); - nativeconn.commit(); - - // 同步缓存数据 - if (sqlobj.getIsSQLIDCache() || sqlobj.getIsKeyCache()) { - Cache sqlcache = CacheFactory - .getCache(sqlobj.getSqlId()); - String keyfield = sqlobj.getKeyField(); - if ((keyfield != null) && (!keyfield.equals(""))) { - - Iterator> iter = datas - .iterator(); - Map data = null; - String keyValue = null; - while (iter.hasNext()) { - data = iter.next(); - if (data.get(keyfield) != null) { - keyValue = String.valueOf(data - .get(keyfield)); - } - if ((keyValue != null) - && (!keyValue.equals(""))) { - sqlcache.put(keyValue, - new HashMap(data)); - } else { - Log.error("SQLID值为: [" + sqlobj.getSqlId() - + "] 设置的主键字段不正确, 不能进行缓存, 请检查!"); - } - } - } else { - Log.error("SQLID值为: [" + sqlobj.getSqlId() - + "] 设置的主键字段不存在, 不能进行缓存, 请检查!"); - } - } - } catch (Exception e) { - nativeconn.rollback(); - throw e; - } - } finally { - conn.close(); - conn = null; - } - } catch (Exception e) { - Log.error(e.getClass().getName() + " \n" + e.getMessage()); - throw new TechException(e.getClass().getName() + " \n" - + e.getMessage()); - } - - return results; - } - - @Override - public void process(Map in, boolean isMultiPart, - InputStream inputs, OutputStream outs, List list, - Map result, DataConverter dataConverter) - throws TechException { - Map input = this.readParamfromInputStream(in, inputs, - dataConverter); - this.queryService(input, result); - - } - -} diff --git a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/modules/QueryParamModule.java b/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/modules/QueryParamModule.java deleted file mode 100644 index baa5feb334..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/modules/QueryParamModule.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.techsoft.modules; - -import java.io.InputStream; -import java.io.OutputStream; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.apache.commons.fileupload.FileItem; - -import com.techsoft.DataConverter; -import com.techsoft.ServletModule; -import com.techsoft.TechException; -import com.techsoft.sql.SQLObjectManager; - -public class QueryParamModule implements ServletModule { - private static final String moduleName = "queryparams"; - private static final String sqldefine = "sqldefine"; - private static QueryParamModule instance = null; - - private QueryParamModule() { - } - - public static QueryParamModule getInstance() { - if (instance == null) { - instance = new QueryParamModule(); - } - - return instance; - } - - @Override - public String getName() { - return QueryParamModule.moduleName; - } - - @SuppressWarnings("unchecked") - public Map readParamfromInputStream(Map in, - InputStream input, DataConverter dataConverter) { - Map result = null; - if (input != null) { - try { - Object obj = dataConverter.readFromInputStream(input); - if (obj != null) { - result = (Map) dataConverter - .deserializeObject(obj); - } else { - result = new HashMap(); - } - } catch (Exception e) { - // 输入流中可能不存在内容,在Ajax调用时 - result = new HashMap(); - } - - } else { - result = new HashMap(); - } - String key = null; - Object value = null; - Iterator iter = in.keySet().iterator(); - while (iter.hasNext()) { - key = iter.next(); - value = in.get(key); - value = dataConverter.deserializeObject(value); - result.put(key, value); - } - return result; - } - - @Override - public void process(Map in, boolean isMultiPart, - InputStream inputs, OutputStream outs, List list, - Map result, DataConverter dataConverter) - throws TechException { - Map input = this.readParamfromInputStream(in, inputs, - dataConverter); - - SQLObjectManager.getInstance().queryParams( - (String) input.get(QueryParamModule.sqldefine), result); - - } - -} diff --git a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/modules/SaveModule.java b/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/modules/SaveModule.java deleted file mode 100644 index 818bdb13e8..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/modules/SaveModule.java +++ /dev/null @@ -1,517 +0,0 @@ -package com.techsoft.modules; - -import java.io.InputStream; -import java.io.OutputStream; -import java.sql.Connection; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.apache.commons.fileupload.FileItem; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.alibaba.fastjson.JSONObject; -import com.techsoft.Cache; -import com.techsoft.DataConverter; -import com.techsoft.DataExecutor; -import com.techsoft.SQLObject; -import com.techsoft.SQLParam; -import com.techsoft.ServletModule; -import com.techsoft.StringConsts; -import com.techsoft.TechException; -import com.techsoft.cache.CacheFactory; -import com.techsoft.container.DataServer; -import com.techsoft.executor.DataExecutorFactory; -import com.techsoft.sql.SQLObjectManager; - -public class SaveModule implements ServletModule { - private static final Logger Log = LoggerFactory.getLogger(SaveModule.class); - private static SaveModule instance = null; - - private SaveModule() { - } - - public static SaveModule getInstance() { - if (instance == null) { - instance = new SaveModule(); - } - - return instance; - } - - @Override - public String getName() { - return StringConsts.savemodule; - } - - @SuppressWarnings("unchecked") - public Map readParamfromInputStream(Map in, - InputStream input, DataConverter dataConverter) { - Map result = null; - if (input != null) { - try { - Object obj = dataConverter.readFromInputStream(input); - if (obj != null) { - result = (Map) dataConverter - .deserializeObject(obj); - } else { - result = new HashMap(); - } - } catch (Exception e) { - result = new HashMap(); - } - - } else { - result = new HashMap(); - } - String key = null; - Object value = null; - Iterator iter = in.keySet().iterator(); - while (iter.hasNext()) { - key = iter.next(); - value = in.get(key); - value = dataConverter.deserializeObject(value); - result.put(key, value); - } - return result; - } - - @SuppressWarnings("unchecked") - public void saveDeleted(List list, Map result, - DataExecutor executor, SQLObject sqlobj, - Map globalParams, Connection conn) - throws TechException { - Map map = null; - Map ignoremap = new HashMap(); - Map ignoreCaseGlobalParams = new HashMap(); - List params = null; - Iterator iter = list.iterator(); - Iterator iterparam = null; - Iterator keyiter = null; - String key = null; - SQLParam param = null; - String paramName = null; - Object paramValue = null; - if (globalParams != null) { - Iterator strIter = globalParams.keySet().iterator(); - while (strIter.hasNext()) { - key = strIter.next(); - ignoreCaseGlobalParams.put(key.toLowerCase(), - globalParams.get(key)); - } - } - List> deleted = new ArrayList>(); - while (iter.hasNext()) { - ignoremap.clear(); - map = (Map) iter.next(); - keyiter = map.keySet().iterator(); - while (keyiter.hasNext()) { - key = keyiter.next(); - ignoremap.put(key.toLowerCase(), map.get(key)); - } - params = new ArrayList(sqlobj.getDeleteParams()); - - iterparam = params.iterator(); - while (iterparam.hasNext()) { - param = iterparam.next(); - paramName = param.getName().toLowerCase(); - if (ignoremap.get(paramName) != null) { - paramValue = ignoremap.get(paramName); - param.setValue(paramValue); - } else if (ignoreCaseGlobalParams.get(paramName) != null) { - paramValue = ignoreCaseGlobalParams.get(paramName); - param.setValue(paramValue); - } - } - - Map returnparam = new HashMap(map); - try { - Map eResult = executor.saveData( - sqlobj.getDeleteSql(), params, conn); - iterparam = params.iterator(); - while (iterparam.hasNext()) { - param = iterparam.next(); - if (param.getIotype().equalsIgnoreCase( - SQLParam.ParamType.out.name()) - || param.getIotype().equalsIgnoreCase( - SQLParam.ParamType.inout.name())) { - returnparam.put(param.getName(), param.getValue()); - } - } - if (eResult.size() > 0) { - returnparam.put(StringConsts.rowresult, - eResult.get(StringConsts.rowresult)); - returnparam.put(StringConsts.rowdesc, - eResult.get(StringConsts.rowdesc)); - } else { - returnparam.put(StringConsts.rowresult, "1"); - returnparam.put(StringConsts.rowdesc, ""); - } - } catch (Exception e) { - throw new TechException(sqlobj.getSqlId() - + " delete Exception: " + e.getMessage()); - } finally { - if (returnparam != null) { - deleted.add(returnparam); - } - } - } - - result.put(StringConsts.deletes, deleted); - - } - - @SuppressWarnings("unchecked") - public void saveUpdated(List list, Map result, - DataExecutor executor, SQLObject sqlobj, - Map globalParams, Connection conn) - throws TechException { - Map map = null; - Map ignoremap = new HashMap(); - Map ignoreCaseGlobalParams = new HashMap(); - List params = null; - Iterator iter = list.iterator(); - Iterator iterparam = null; - Iterator keyiter = null; - String key = null; - SQLParam param = null; - String paramName = null; - Object paramValue = null; - if (globalParams != null) { - Iterator strIter = globalParams.keySet().iterator(); - while (strIter.hasNext()) { - key = strIter.next(); - ignoreCaseGlobalParams.put(key.toLowerCase(), - globalParams.get(key)); - } - } - List> updated = new ArrayList>(); - while (iter.hasNext()) { - ignoremap.clear(); - map = (Map) iter.next(); - keyiter = map.keySet().iterator(); - while (keyiter.hasNext()) { - key = keyiter.next(); - ignoremap.put(key.toLowerCase(), map.get(key)); - } - params = new ArrayList(sqlobj.getUpdateParams()); - - iterparam = params.iterator(); - while (iterparam.hasNext()) { - param = iterparam.next(); - paramName = param.getName().toLowerCase(); - if (ignoremap.get(paramName) != null) { - paramValue = ignoremap.get(paramName); - param.setValue(paramValue); - } else if (ignoreCaseGlobalParams.get(paramName) != null) { - paramValue = ignoreCaseGlobalParams.get(paramName); - param.setValue(paramValue); - } - } - - Map returnparam = new HashMap(map); - try { - Map eResult = executor.saveData( - sqlobj.getUpdateSql(), params, conn); - iterparam = params.iterator(); - while (iterparam.hasNext()) { - param = iterparam.next(); - if (param.getIotype().equalsIgnoreCase( - SQLParam.ParamType.out.name()) - || param.getIotype().equalsIgnoreCase( - SQLParam.ParamType.out.name())) { - - returnparam.put(param.getName(), param.getValue()); - } - } - if (eResult.size() > 0) { - returnparam.put(StringConsts.rowresult, - eResult.get(StringConsts.rowresult)); - returnparam.put(StringConsts.rowdesc, - eResult.get(StringConsts.rowdesc)); - } else { - returnparam.put(StringConsts.rowresult, "1"); - returnparam.put(StringConsts.rowdesc, ""); - } - } catch (Exception e) { - returnparam.put(StringConsts.rowresult, "0"); - returnparam.put(StringConsts.rowdesc, e.getMessage()); - throw new TechException(sqlobj.getSqlId() - + " update Exception: " + e.getMessage()); - } finally { - if (returnparam != null) { - updated.add(returnparam); - } - } - } - SQLObjectManager.getInstance().loadSqlCache(sqlobj.getSqlId(), - ignoremap); - result.put(StringConsts.updates, updated); - } - - @SuppressWarnings("unchecked") - public void saveInserted(List list, Map result, - DataExecutor executor, SQLObject sqlobj, - Map globalParams, Connection conn) - throws TechException { - Map map = null; - Map ignoremap = new HashMap(); - Map ignoreCaseGlobalParams = new HashMap(); - List params = null; - Iterator iter = list.iterator(); - Iterator iterparam = null; - Iterator keyiter = null; - String key = null; - SQLParam param = null; - String paramName = null; - Object paramValue = null; - - if (globalParams != null) { - Iterator strIter = globalParams.keySet().iterator(); - while (strIter.hasNext()) { - key = strIter.next(); - ignoreCaseGlobalParams.put(key.toLowerCase(), - globalParams.get(key)); - } - } - List> inserted = new ArrayList>(); - while (iter.hasNext()) { - ignoremap.clear(); - map = (Map) iter.next(); - keyiter = map.keySet().iterator(); - while (keyiter.hasNext()) { - key = keyiter.next(); - ignoremap.put(key.toLowerCase(), map.get(key)); - } - params = new ArrayList(sqlobj.getInsertParams()); - - iterparam = params.iterator(); - while (iterparam.hasNext()) { - param = iterparam.next(); - paramName = param.getName().toLowerCase(); - if (ignoremap.get(paramName) != null) { - paramValue = ignoremap.get(paramName); - param.setValue(paramValue); - } else if (ignoreCaseGlobalParams.get(paramName) != null) { - paramValue = ignoreCaseGlobalParams.get(paramName); - param.setValue(paramValue); - } - } - - Map returnparam = new HashMap(map); - try { - Map eResult = executor.saveData( - sqlobj.getInsertSql(), params, conn); - iterparam = params.iterator(); - while (iterparam.hasNext()) { - param = iterparam.next(); - if (param.getIotype().equalsIgnoreCase( - SQLParam.ParamType.out.name()) - || param.getIotype().equalsIgnoreCase( - SQLParam.ParamType.out.name())) { - returnparam.put(param.getName(), param.getValue()); - } - } - if (eResult.size() > 0) { - returnparam.put(StringConsts.rowresult, - eResult.get(StringConsts.rowresult)); - returnparam.put(StringConsts.rowdesc, - eResult.get(StringConsts.rowdesc)); - } else { - returnparam.put(StringConsts.rowresult, "1"); - returnparam.put(StringConsts.rowdesc, ""); - } - } catch (Exception e) { - returnparam.put(StringConsts.rowresult, "0"); - returnparam.put(StringConsts.rowdesc, e.getMessage()); - throw new TechException(sqlobj.getSqlId() - + " Insert Exception: " + e.getMessage()); - } finally { - if (returnparam != null) { - inserted.add(returnparam); - } - } - } - SQLObjectManager.getInstance().loadSqlCache(sqlobj.getSqlId(), - ignoremap); - result.put(StringConsts.inserts, inserted); - } - - @SuppressWarnings("unchecked") - public void saveData(Map inputs, Map results) - throws TechException { - Map paramobj = null; - String sqlid = null; - Map outdata = new HashMap(); - try { - sqlid = (String) inputs.get(StringConsts.sqlid); - if ((sqlid == null) || (sqlid.equals(""))) { - throw new TechException("sqlid 不能为空!"); - } - if ((inputs.get(StringConsts.params) != null) - && (!inputs.get(StringConsts.params).equals(""))) { - paramobj = (Map) inputs - .get(StringConsts.params); - } - SQLObject sqlobj = SQLObjectManager.getInstance().getSQLObjectById( - sqlid); - if (sqlobj == null) { - throw new TechException("id值为 [" + sqlid - + "]的SQLObject并不存在, 请检查!"); - } - if (paramobj == null) { - throw new TechException("id值为 [" + sqlid + "]的保存参数并不存在, 请检查!"); - } - - List inserted = null; - List updated = null; - List deleted = null; - - Object jn = paramobj.get(StringConsts.inserts); - if (jn instanceof Map) { - inserted = new ArrayList(); - inserted.add(jn); - } else if (jn instanceof List) { - inserted = (List) paramobj.get(StringConsts.inserts); - } - - jn = paramobj.get(StringConsts.updates); - if (jn instanceof Map) { - updated = new ArrayList(); - updated.add(jn); - } else if (jn instanceof List) { - updated = (List) paramobj.get(StringConsts.updates); - } - - jn = paramobj.get(StringConsts.deletes); - if (jn instanceof JSONObject) { - deleted = new ArrayList(); - deleted.add(jn); - } else if (jn instanceof List) { - deleted = (List) paramobj.get(StringConsts.deletes); - } - - Connection conn = DataServer.getInstance().getPool() - .getConnection(); - try { - Connection nativeconn = DataServer.getInstance().getPool() - .getNativeConnection(conn); - try { - - DataExecutor executor = DataExecutorFactory - .getExecutor(DataServer.getInstance() - .getProperties().getDbtype()); - - if ((inserted != null) && (inserted.size() > 0)) { - this.saveInserted(inserted, outdata, executor, sqlobj, - inputs, nativeconn); - } - - if ((updated != null) && (updated.size() > 0)) { - this.saveUpdated(updated, outdata, executor, sqlobj, - inputs, nativeconn); - } - - if ((deleted != null) && (deleted.size() > 0)) { - this.saveDeleted(deleted, outdata, executor, sqlobj, - inputs, nativeconn); - } - - results.put(StringConsts.outdata, outdata); - nativeconn.commit(); - } catch (Exception e) { - nativeconn.rollback(); - throw e; - } - } finally { - conn.close(); - conn = null; - } - - // 同步缓存数据 - if (sqlobj.getIsSQLIDCache() || sqlobj.getIsKeyCache()) { - Cache sqlcache = CacheFactory.getCache(sqlobj - .getSqlId()); - String keyfield = sqlobj.getKeyField(); - Map data = null; - String keyValue = null; - if ((keyfield != null) && (!keyfield.equals(""))) { - - if ((inserted != null) && (inserted.size() > 0)) { - Iterator iter = inserted.iterator(); - while (iter.hasNext()) { - data = (Map) iter.next(); - if (data.get(keyfield) != null) { - keyValue = String.valueOf(data.get(keyfield)); - } - if ((keyValue != null) && (!keyValue.equals(""))) { - sqlcache.put(keyValue, - new HashMap(data)); - } else { - Log.error("SQLID值为: [" + sqlobj.getSqlId() - + "] 设置的主键字段不正确, 不能进行缓存, 请检查!"); - } - } - } - - if ((updated != null) && (updated.size() > 0)) { - Iterator iter = updated.iterator(); - while (iter.hasNext()) { - data = (Map) iter.next(); - if (data.get(keyfield) != null) { - keyValue = String.valueOf(data.get(keyfield)); - } - if ((keyValue != null) && (!keyValue.equals(""))) { - sqlcache.put(keyValue, - new HashMap(data)); - } else { - Log.error("SQLID值为: [" + sqlobj.getSqlId() - + "] 设置的主键字段不正确, 不能进行缓存, 请检查!"); - } - } - } - - if ((deleted != null) && (deleted.size() > 0)) { - Iterator iter = deleted.iterator(); - while (iter.hasNext()) { - data = (Map) iter.next(); - if (data.get(keyfield) != null) { - keyValue = String.valueOf(data.get(keyfield)); - } - if ((keyValue != null) && (!keyValue.equals(""))) { - sqlcache.remove(keyValue); - } else { - Log.error("SQLID值为: [" + sqlobj.getSqlId() - + "] 设置的主键字段不正确, 不能进行缓存, 请检查!"); - } - } - } - - } else { - Log.error("SQLID值为: [" + sqlobj.getSqlId() - + "] 设置的主键字段不存在, 不能进行缓存, 请检查!"); - } - } - } catch (Exception e) { - Log.error(e.getClass().getName() + " \n" + e.getMessage()); - throw new TechException(e.getClass().getName() + " \n" - + e.getMessage()); - } - - } - - @Override - public void process(Map in, boolean isMultiPart, - InputStream inputs, OutputStream outs, List list, - Map result, DataConverter dataConverter) - throws TechException { - Map input = this.readParamfromInputStream(in, inputs, - dataConverter); - saveData(input, result); - - } - -} diff --git a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/servlet/ConfigProperties.java b/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/servlet/ConfigProperties.java deleted file mode 100644 index b4c7405378..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/servlet/ConfigProperties.java +++ /dev/null @@ -1,172 +0,0 @@ -package com.techsoft.servlet; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.UnsupportedEncodingException; - -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.Element; -import org.dom4j.io.SAXReader; -import org.dom4j.io.XMLWriter; - -import com.techsoft.ConnectionPool.DatabaseType; -import com.techsoft.container.DataServer; - -public class ConfigProperties { - private static String configfile = "conf/config.xml"; - private File home; - private Document doc = null; - private Element root = null; - - public ConfigProperties(File webHome) { - home = webHome; - File file = new File(home, configfile); - SAXReader reader = new SAXReader(); - try { - doc = reader.read(file); - root = doc.getRootElement(); - } catch (DocumentException e) { - e.printStackTrace(); - } - } - - public void writeDocument() { - try { - XMLWriter writer = new XMLWriter(new FileOutputStream(home - + configfile)); - writer.write(doc); - writer.close(); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public String getDriver() { - return root.elementText("driver"); - } - - public void setDriver(String driver) { - root.element("driver").setText(driver); - this.writeDocument(); - } - - public String getURL() { - return root.elementText("URL"); - } - - public void setURL(String URL) { - root.element("URL").setText(URL); - this.writeDocument(); - } - - public String getUser() { - return root.elementText("User"); - } - - public void setUser(String User) { - root.element("User").setText(User); - this.writeDocument(); - } - - public String getPassword() { - return root.elementText("Password"); - } - - public void setPassword(String Password) { - root.element("Password").setText(Password); - this.writeDocument(); - } - - public String getMaxPool() { - return root.elementText("MaxPool"); - } - - public void setMaxPool(String MaxPool) throws Exception { - Integer maxpool = -1; - try { - maxpool = Integer.valueOf(MaxPool); - } catch (Exception e) { - throw new Exception("设置的最大连接池参数不是一个有效的整数, 请检查!"); - } - root.element("MaxPool").setText(MaxPool); - this.writeDocument(); - - DataServer.getInstance().getPool().setMaxPool(maxpool); - } - - public String getMinPool() { - return root.elementText("MinPool"); - } - - public void setMinPool(String MinPool) throws Exception { - Integer minpool = -1; - try { - minpool = Integer.valueOf(MinPool); - } catch (Exception e) { - throw new Exception("设置的最小连接池参数不是一个有效的整数, 请检查!"); - } - root.element("MinPool").setText(MinPool); - this.writeDocument(); - - DataServer.getInstance().getPool().setMinPool(minpool); - } - - public String getDefaultPool() { - return root.elementText("DefaultPool"); - } - - public void setDefaultPool(String DefaultPool) throws Exception { - Integer defaultpool = -1; - try { - defaultpool = Integer.valueOf(DefaultPool); - } catch (Exception e) { - throw new Exception("设置的初始连接池参数不是一个有效的整数, 请检查!"); - } - root.element("DefaultPool").setText(DefaultPool); - this.writeDocument(); - DataServer.getInstance().getPool().setInitPool(defaultpool); - } - - public String getisDebug() { - return root.elementText("isDebug"); - } - - public void setisDebug(String isDebug) { - Boolean bool = Boolean.valueOf(isDebug); - root.element("isDebug").setText(bool.toString()); - this.writeDocument(); - - DataServer.getInstance().setDebug(bool); - DataServer.getInstance().getPluginsManager().setIsDebug(bool); - } - - public DatabaseType getDbtype() { - return DatabaseType.valueOf(root.elementText("Dbtype").toUpperCase()); - } - - public void setDBType(DatabaseType type) { - root.element("Dbtype").setText(type.name()); - this.writeDocument(); - } - - public String getSessionURL() { - return root.elementText("sessionurl"); - } - - public String getGOperUserId(){ - return root.elementText("GUserId"); - } - - public void setGOperUserId(String gUserId){ - root.element("GUserId").setText(gUserId); - this.writeDocument(); - } - -} diff --git a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/servlet/DataService.java b/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/servlet/DataService.java deleted file mode 100644 index 2dc81a9d40..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/servlet/DataService.java +++ /dev/null @@ -1,253 +0,0 @@ -package com.techsoft.servlet; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.net.URLDecoder; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.fileupload.FileItem; -import org.apache.commons.fileupload.FileUploadException; -import org.apache.commons.fileupload.disk.DiskFileItemFactory; -import org.apache.commons.fileupload.servlet.ServletFileUpload; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.alibaba.fastjson.JSONObject; -import com.techsoft.DataConverter; -import com.techsoft.ServletModule; -import com.techsoft.Session; -import com.techsoft.StringConsts; -import com.techsoft.container.DataServer; -import com.techsoft.dataconverter.DataConverterFactory; - -public class DataService extends HttpServlet { - private static final Logger Log = LoggerFactory - .getLogger(DataService.class); - private static final long serialVersionUID = 6929000280719060477L; - - private void readParamsFromParameter(HttpServletRequest request, - Map map) { - // url后的参数 - String paramName = null; - String[] paramValues = null; - Object paramValue = null; - JSONObject obj = null; - Iterator iter = null; - String key = null; - Enumeration paramNames = request.getParameterNames(); - while (paramNames.hasMoreElements()) { - paramName = paramNames.nextElement(); - paramValues = request.getParameterValues(paramName); - if (paramValues.length >= 1) { - paramValue = paramValues[0]; - } - - if (paramName.equalsIgnoreCase(StringConsts.allparams)) { - obj = JSONObject.parseObject((String) paramValue); - iter = obj.keySet().iterator(); - while (iter.hasNext()) { - key = iter.next(); - map.put(key.toLowerCase(), obj.get(key)); - } - } else { - map.put(paramName.toLowerCase(), paramValue); - } - } - } - - private void readParamsFromAttribute(HttpServletRequest request, - Map map) { - // Sesionn上下文参数 - Enumeration names = request.getAttributeNames(); - String name = null; - while (names.hasMoreElements()) { - name = names.nextElement(); - if (name.equals("g_s")) { - // 表示数据格式的全局参数 - map.put("s", request.getAttribute(name)); - } else if (name.startsWith("g_")) { - map.put(name, request.getAttribute(name)); - request.removeAttribute(name); - } - - } - } - - @SuppressWarnings("unchecked") - private List readParamsFromInputStream( - HttpServletRequest request, Map map) - throws IOException { - List result = null; - JSONObject obj = null; - String key = null; - Iterator iter = null; - if (map.get("m") == null) { - DiskFileItemFactory factory = new DiskFileItemFactory(); - ServletFileUpload upload = new ServletFileUpload(factory); - // 使用开源库读取POST分段参数 - if (ServletFileUpload.isMultipartContent(request)) { - upload.setHeaderEncoding(System - .getProperty(StringConsts.jvmcharset)); - try { - List list = upload.parseRequest(request); - for (FileItem item : list) { - - String fieldName = item.getFieldName(); - if (StringConsts.allparams.equalsIgnoreCase(fieldName)) { - obj = JSONObject.parseObject(item.getString()); - iter = obj.keySet().iterator(); - while (iter.hasNext()) { - key = iter.next(); - map.put(key, obj.get(key)); - } - } - } - result = list; - } catch (FileUploadException e) { - throw new IOException(e.getMessage()); - } - } - - } - - if (map.get("m") == null) { - InputStream input = request.getInputStream(); - try { - BufferedReader tBufferedReader = new BufferedReader( - new InputStreamReader(input)); - StringBuffer tStringBuffer = new StringBuffer(); - String sTempOneLine = ""; - try { - while ((sTempOneLine = tBufferedReader.readLine()) != null) { - tStringBuffer.append(sTempOneLine); - } - - String s = URLDecoder.decode(tStringBuffer.toString(), - System.getProperty(StringConsts.jvmcharset)); - if (s.length() > 10) { - s = s.substring(10); - obj = JSONObject.parseObject(s); - iter = obj.keySet().iterator(); - while (iter.hasNext()) { - key = iter.next(); - map.put(key, obj.get(key)); - } - } - } finally { - tBufferedReader.close(); - } - } finally { - input.close(); - } - } - - return result; - } - - protected void doGet(HttpServletRequest request, - HttpServletResponse response) throws ServletException, IOException { - doPost(request, response); - } - - protected void doPost(HttpServletRequest request, - HttpServletResponse response) throws ServletException, IOException { - Map map = new HashMap(); - Map results = new HashMap(); - DataConverter dataConverter = null; - OutputStream out = response.getOutputStream(); - InputStream input = request.getInputStream(); - try { - try { - readParamsFromAttribute(request, map); - readParamsFromParameter(request, map); - List list = readParamsFromInputStream(request, map); - - String m = String.valueOf(map.get(StringConsts.MethodName)); - String s = String.valueOf(map.get(StringConsts.Serization)); - if ((m == null) || (m.equalsIgnoreCase(""))) { - throw new Exception("请求的方法名称为空,请客户端检查协议!"); - } - if ((s == null) || (s.equalsIgnoreCase(""))) { - throw new Exception("请求的数据格式为空, 请客户端指定数据格式!"); - } else { - if (!DataConverterFactory.containDataFormat(s)) { - throw new Exception("客户端传入的数据格式 [" + s + "],服务器还不支持!"); - } - } - - // 得到输出格式对象 - if (map.get(ServletModule.JSONP) != null) { - dataConverter = DataConverterFactory - .getSerialization(StringConsts.jsonp); - dataConverter.setPrefix(String.valueOf(map - .get(ServletModule.JSONP))); - } else { - dataConverter = DataConverterFactory - .getSerialization((String) map - .get(StringConsts.Serization)); - } - Log.info("Servlet IP: " + map.get("ip")); - map.put(Session.sessionid, request.getSession().getId()); - - m = String.valueOf(map.get(StringConsts.MethodName)) - .toLowerCase(); - - Object obj = DataServer.getInstance().getCoreHandlers().get(m); - if (obj != null) { - ServletModule handler = (ServletModule) obj; - if (list != null) { - handler.process(map, true, null, out, list, results, - dataConverter); - } else { - handler.process(map, false, input, out, null, results, - dataConverter); - } - } else { - obj = DataServer.getInstance().getPluginModuleByMethod(m); - if (obj != null) { - ServletModule handler = (ServletModule) obj; - if (list != null) { - handler.process(map, true, null, out, list, - results, dataConverter); - } else { - handler.process(map, false, input, out, null, - results, dataConverter); - } - } else { - throw new Exception("服务器还不支持此方法,请联系开发人员或等待插件完全安装!"); - } - } - results.put(StringConsts.ResultType, StringConsts.Success); - results.put(StringConsts.ResultDesc, ""); - } catch (Exception e) { - results.put(StringConsts.ResultType, StringConsts.Error); - results.put(StringConsts.ResultDesc, e.getClass().getName() - + " \n" + e.getMessage()); - } - - // 输出结果 - if (dataConverter != null) { - if (results.get("result") == null) { - // 如果不为空, 表示内部已处理了输出流 - Object resultobj = dataConverter.serializeObject(results); - dataConverter.writeToOutputStream(resultobj, out); - } - } - } finally { - out.close(); - input.close(); - } - } -} diff --git a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/servlet/EncodingFilter.java b/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/servlet/EncodingFilter.java deleted file mode 100644 index ac16db05ff..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/servlet/EncodingFilter.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.techsoft.servlet; - -import java.io.IOException; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; - -public class EncodingFilter implements Filter { - protected String encoding; - protected FilterConfig config; - - public FilterConfig getConfig() { - return config; - } - - public void setConfig(FilterConfig config) { - this.config = config; - } - - @Override - public void destroy() { - config = null; - } - - @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { - if (encoding != null) { - request.setCharacterEncoding(encoding); - } - - if (encoding != null) { - response.setCharacterEncoding(encoding); - response.setContentType("text/html;charset=" + encoding); - } - - chain.doFilter(request, response); - } - - @Override - public void init(FilterConfig filterConfig) throws ServletException { - this.encoding = filterConfig.getInitParameter("encoding"); - } - -} diff --git a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/servlet/InitWebServlet.java b/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/servlet/InitWebServlet.java deleted file mode 100644 index 72e3cc7eed..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/servlet/InitWebServlet.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.techsoft.servlet; - -import java.io.File; - -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; - -import org.apache.log4j.xml.DOMConfigurator; - -import com.techsoft.container.DataServer; - -public class InitWebServlet extends HttpServlet { - private static final long serialVersionUID = -2244907179466739916L; - - public InitWebServlet() { - super(); - } - - public void init(ServletConfig config) throws ServletException { - super.init(config); - String webpath = config.getServletContext().getRealPath("/"); - // 设定日志路径 - String Logpath = webpath + "logs"; - System.setProperty("logsdir", Logpath); - DOMConfigurator.configure(webpath + "WEB-INF" + File.separator + "lib" - + File.separator + "log4j.xml"); - try { - new DataServer(new File(webpath)).start(); - } catch (Exception e) { - // 服务器在启动时出错要手动停止服务器, 配置正常后再启动 - } - } -} diff --git a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/servlet/SessionFilter.java b/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/servlet/SessionFilter.java deleted file mode 100644 index 63670dc0f1..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/servlet/SessionFilter.java +++ /dev/null @@ -1,122 +0,0 @@ -package com.techsoft.servlet; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.URLDecoder; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; - -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.HttpMethod; -import org.apache.commons.httpclient.methods.PostMethod; - -import com.alibaba.fastjson.JSONObject; -import com.techsoft.StringConsts; -import com.techsoft.container.DataServer; - -public class SessionFilter implements Filter { - @Override - public void destroy() { - - } - - @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { - HttpServletRequest req = (HttpServletRequest) request; - - ConfigProperties configProp = DataServer.getInstance().getProperties(); - - String gOperUserId=configProp.getGOperUserId(); - - if(gOperUserId!=null && !"".equals(gOperUserId)){ - request.setAttribute("g_user_id", new Long(gOperUserId)); - }else{ - Cookie[] cookies = req.getCookies(); - String url = null; - if (cookies != null) { - for (final Cookie oItem : cookies) { - final String sName = oItem.getName(); - if (sName.equalsIgnoreCase("authToken")) { - url = DataServer.getInstance().getProperties() - .getSessionURL(); - if ((url != null) && (!url.equalsIgnoreCase(""))) { - url = url + "?authToken=" + oItem.getValue(); - HttpClient client = new HttpClient(); - JSONObject result = null; - HttpMethod httpGet = new PostMethod(url); - try { - client.executeMethod(httpGet); - if ((httpGet.getStatusLine() != null) - && (httpGet.getStatusLine().getStatusCode() == 200)) { - BufferedReader tBufferedReader = new BufferedReader( - new InputStreamReader(httpGet - .getResponseBodyAsStream())); - StringBuffer tStringBuffer = new StringBuffer(); - String sTempOneLine = ""; - try { - while ((sTempOneLine = tBufferedReader - .readLine()) != null) { - tStringBuffer.append(sTempOneLine); - } - - String s = URLDecoder - .decode(tStringBuffer.toString(), - System.getProperty(StringConsts.jvmcharset)); - result = JSONObject.parseObject(s); - - JSONObject json = result - .getJSONObject("valueObject"); - if (json != null) { - String temp = json - .getString("userInfo"); - temp = temp.replace("\\\"", "\""); - json = (JSONObject) JSONObject - .parse(temp); - // json = - // json.getJSONObject("userInfo"); - if (json != null) { - json = json.getJSONObject("user"); - if (json != null) { - Long user_id = Long - .valueOf(json - .getString("fOperUserId")); - request.setAttribute( - "g_user_id", user_id); - } - } - } - - } catch (IOException e) { - e.printStackTrace(); - } - } - } catch (HttpException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - } - } - } - - chain.doFilter(request, response); - } - - @Override - public void init(FilterConfig arg0) throws ServletException { - - } - -} diff --git a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/sql/OracleSql.java b/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/sql/OracleSql.java deleted file mode 100644 index 7cfda06d27..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/sql/OracleSql.java +++ /dev/null @@ -1,129 +0,0 @@ -package com.techsoft.sql; - -public class OracleSql { - - public static final String SELECT_ALL_SQL = "SELECT SQLID, \n" - + "OID, \n" - + "PID, \n" - + "MID, \n" - + "OBJ_VERSION, \n" - + "SQLNAME, \n" - + "SQLDESC, \n" - + "DEF_SELECT_SQL, \n" - + "DEF_SELECT_PARAMS, \n" - + "DEF_SELECT_METADATA, \n" - + "DEF_INSERT_SQL, \n" - + "DEF_INSERT_PARAMS, \n" - + "DEF_UPDATE_SQL, \n" - + "DEF_UPDATE_PARAMS, \n" - + "DEF_DELETE_SQL, \n" - + "DEF_DELETE_PARAMS, \n" - + "SELECT_SQL, \n" - + "INSERT_SQL, \n" - + "UPDATE_SQL, \n" - + "DELETE_SQL, \n" - + "SQL_OPTIONS, \n" - + "TABLENAME, \n" - + "KEYFIELD \n" - + "FROM TB_SM_SQLDEFINE "; - - public static final String SELECT_SQL = "SELECT SQLID, \n" - + "OID, \n" - + "PID, \n" - + "MID, \n" - + "OBJ_VERSION, \n" - + "SQLNAME, \n" - + "SQLDESC, \n" - + "DEF_SELECT_SQL, \n" - + "DEF_SELECT_PARAMS, \n" - + "DEF_SELECT_METADATA, \n" - + "DEF_INSERT_SQL, \n" - + "DEF_INSERT_PARAMS, \n" - + "DEF_UPDATE_SQL, \n" - + "DEF_UPDATE_PARAMS, \n" - + "DEF_DELETE_SQL, \n" - + "DEF_DELETE_PARAMS, \n" - + "SELECT_SQL, \n" - + "INSERT_SQL, \n" - + "UPDATE_SQL, \n" - + "DELETE_SQL, \n" - + "SQL_OPTIONS, \n" - + "TABLENAME, \n" - + "KEYFIELD \n" - + "FROM TB_SM_SQLDEFINE " - + "WHERE SQLID = ?"; - - public static final String INSERT_SQL = "declare \n" - + " rec number; \n" - + "begin \n" - + " select count(*) into rec from tb_sm_sqldefine t where t.sqlid = ?; \n" - + " if (rec <= 0) then \n" - + " insert into tb_sm_sqldefine t \n" - + " (t.oid, \n" - + " T.SQLID, \n" - + " T.OBJ_VERSION, \n" - + " T.SQLNAME, \n" - + " T.DEF_SELECT_SQL, \n" - + " T.DEF_SELECT_PARAMS, \n" - + " T.DEF_SELECT_METADATA, \n" - + " T.DEF_INSERT_SQL, \n" - + " T.DEF_INSERT_PARAMS, \n" - + " T.DEF_UPDATE_SQL, \n" - + " T.DEF_UPDATE_PARAMS, \n" - + " T.DEF_DELETE_SQL, \n" - + " T.DEF_DELETE_PARAMS, \n" - + " T.SELECT_SQL, \n" - + " T.INSERT_SQL, \n" - + " T.UPDATE_SQL, \n" - + " T.DELETE_SQL, \n" - + " T.SQL_OPTIONS, \n" - + " T.TABLENAME, \n" - + " T.KEYFIELD)" - + " values \n" - + " (to_char(sysdate, 'yyyy-MM-dd-hh24-mi-ss-ssssssssss'), \n" - + " ?, \n" - + " 1, \n" - + " ?, \n" - + " ?, \n" - + " ?, \n" - + " ?, \n" - + " ?, \n" - + " ?, \n" - + " ?, \n" - + " ?, \n" - + " ?, \n" - + " ?, \n" - + " ?, \n" - + " ?, \n" - + " ?, \n" - + " ?, \n" - + " ?, \n" - + " ?, \n" - + " ?); \n" - + " else \n" - + " update tb_sm_sqldefine t \n" - + " set T.OBJ_VERSION = T.OBJ_VERSION + 1, \n" - + " T.SQLNAME = ?, \n" - + " T.DEF_SELECT_SQL = ?, \n" - + " T.DEF_SELECT_PARAMS = ?, \n" - + " T.DEF_SELECT_METADATA = ?, \n" - + " T.DEF_INSERT_SQL = ?, \n" - + " T.DEF_INSERT_PARAMS = ?, \n" - + " T.DEF_UPDATE_SQL = ?, \n" - + " T.DEF_UPDATE_PARAMS = ?, \n" - + " T.DEF_DELETE_SQL = ?, \n" - + " T.DEF_DELETE_PARAMS = ?, \n" - + " T.SELECT_SQL = ?, \n" - + " T.INSERT_SQL = ?, \n" - + " T.UPDATE_SQL = ?, \n" - + " T.DELETE_SQL = ?, \n" - + " T.SQL_OPTIONS = ?, \n" - + " T.TABLENAME = ?, \n" - + " T.KEYFIELD = ? \n" - + " where t.sqlid = ?; \n" - + " end if; \n" - + "end; \n"; - - public static final String DELETE_SQL = ""; - -} diff --git a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/sql/SQLObjectManager.java b/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/sql/SQLObjectManager.java deleted file mode 100644 index fb985446c4..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/sql/SQLObjectManager.java +++ /dev/null @@ -1,605 +0,0 @@ -package com.techsoft.sql; - -import java.io.File; -import java.sql.Connection; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -import oracle.jdbc.OracleTypes; - -import com.techsoft.Cache; -import com.techsoft.ConnectionPool; -import com.techsoft.DataExecutor; -import com.techsoft.MetaData; -import com.techsoft.SQLObject; -import com.techsoft.SQLParam; -import com.techsoft.TechException; -import com.techsoft.cache.CacheFactory; -import com.techsoft.container.DataServer; -import com.techsoft.executor.DataExecutorFactory; - -public class SQLObjectManager { - private static SQLObjectManager instance; - private static String sqlCacheName = "1000"; - private Cache orasqlcache; - private ReadWriteLock lock = null; - private Lock readLock = null; - private Lock writeLock = null; - private SQLObject oraclesql = null; - - private void buildOracleSQLObject() { - oraclesql.setSelectSql(OracleSql.SELECT_ALL_SQL); - oraclesql.setInsertSql(OracleSql.INSERT_SQL); - oraclesql.setDeleteSql(OracleSql.DELETE_SQL); - - SQLParam SQLID = new SQLParam(); - SQLID.setDtype("12"); - SQLID.setDtypename("VARCHAR"); - SQLID.setIndex("1,2,37"); - SQLID.setIotype(SQLParam.ParamType.in.name()); - SQLID.setName("SQLID"); - // SQLID.buildPositions(); - oraclesql.getInsertParams().add(SQLID); - - SQLParam SQLNAME = new SQLParam(); - SQLNAME.setDtype("12"); - SQLNAME.setDtypename("VARCHAR"); - SQLNAME.setIndex("3,20"); - SQLNAME.setIotype(SQLParam.ParamType.in.name()); - SQLNAME.setName("SQLNAME"); - // SQLNAME.buildPositions(); - oraclesql.getInsertParams().add(SQLNAME); - - SQLParam DEF_SELECT_SQL = new SQLParam(); - DEF_SELECT_SQL.setDtype("2005"); - DEF_SELECT_SQL.setDtypename("CLOB"); - DEF_SELECT_SQL.setIndex("4,21"); - DEF_SELECT_SQL.setIotype(SQLParam.ParamType.in.name()); - DEF_SELECT_SQL.setName("DEF_SELECT_SQL"); - // DEF_SELECT_SQL.buildPositions(); - oraclesql.getInsertParams().add(DEF_SELECT_SQL); - - SQLParam DEF_SELECT_PARAMS = new SQLParam(); - DEF_SELECT_PARAMS.setDtype("2005"); - DEF_SELECT_PARAMS.setDtypename("CLOB"); - DEF_SELECT_PARAMS.setIndex("5,22"); - DEF_SELECT_PARAMS.setIotype(SQLParam.ParamType.in.name()); - DEF_SELECT_PARAMS.setName("DEF_SELECT_PARAMS"); - // DEF_SELECT_PARAMS.buildPositions(); - oraclesql.getInsertParams().add(DEF_SELECT_PARAMS); - - SQLParam DEF_SELECT_METADATA = new SQLParam(); - DEF_SELECT_METADATA.setDtype("2005"); - DEF_SELECT_METADATA.setDtypename("CLOB"); - DEF_SELECT_METADATA.setIndex("6,23"); - DEF_SELECT_METADATA.setIotype(SQLParam.ParamType.in.name()); - DEF_SELECT_METADATA.setName("DEF_SELECT_METADATA"); - // DEF_SELECT_METADATA.buildPositions(); - oraclesql.getInsertParams().add(DEF_SELECT_METADATA); - - SQLParam DEF_INSERT_SQL = new SQLParam(); - DEF_INSERT_SQL.setDtype("2005"); - DEF_INSERT_SQL.setDtypename("CLOB"); - DEF_INSERT_SQL.setIndex("7,24"); - DEF_INSERT_SQL.setIotype(SQLParam.ParamType.in.name()); - DEF_INSERT_SQL.setName("DEF_INSERT_SQL"); - // DEF_INSERT_SQL.buildPositions(); - oraclesql.getInsertParams().add(DEF_INSERT_SQL); - - SQLParam DEF_INSERT_PARAMS = new SQLParam(); - DEF_INSERT_PARAMS.setDtype("2005"); - DEF_INSERT_PARAMS.setDtypename("CLOB"); - DEF_INSERT_PARAMS.setIndex("8,25"); - DEF_INSERT_PARAMS.setIotype(SQLParam.ParamType.in.name()); - DEF_INSERT_PARAMS.setName("DEF_INSERT_PARAMS"); - // DEF_INSERT_PARAMS.buildPositions(); - oraclesql.getInsertParams().add(DEF_INSERT_PARAMS); - - SQLParam DEF_UPDATE_SQL = new SQLParam(); - DEF_UPDATE_SQL.setDtype("2005"); - DEF_UPDATE_SQL.setDtypename("CLOB"); - DEF_UPDATE_SQL.setIndex("9,26"); - DEF_UPDATE_SQL.setIotype(SQLParam.ParamType.in.name()); - DEF_UPDATE_SQL.setName("DEF_UPDATE_SQL"); - // DEF_UPDATE_SQL.buildPositions(); - oraclesql.getInsertParams().add(DEF_UPDATE_SQL); - - SQLParam DEF_UPDATE_PARAMS = new SQLParam(); - DEF_UPDATE_PARAMS.setDtype("2005"); - DEF_UPDATE_PARAMS.setDtypename("CLOB"); - DEF_UPDATE_PARAMS.setIndex("10,27"); - DEF_UPDATE_PARAMS.setIotype(SQLParam.ParamType.in.name()); - DEF_UPDATE_PARAMS.setName("DEF_UPDATE_PARAMS"); - // DEF_UPDATE_PARAMS.buildPositions(); - oraclesql.getInsertParams().add(DEF_UPDATE_PARAMS); - - SQLParam DEF_DELETE_SQL = new SQLParam(); - DEF_DELETE_SQL.setDtype("2005"); - DEF_DELETE_SQL.setDtypename("CLOB"); - DEF_DELETE_SQL.setIndex("11,28"); - DEF_DELETE_SQL.setIotype(SQLParam.ParamType.in.name()); - DEF_DELETE_SQL.setName("DEF_DELETE_SQL"); - // DEF_DELETE_SQL.buildPositions(); - oraclesql.getInsertParams().add(DEF_DELETE_SQL); - - SQLParam DEF_DELETE_PARAMS = new SQLParam(); - DEF_DELETE_PARAMS.setDtype("2005"); - DEF_DELETE_PARAMS.setDtypename("CLOB"); - DEF_DELETE_PARAMS.setIndex("12,29"); - DEF_DELETE_PARAMS.setIotype(SQLParam.ParamType.in.name()); - DEF_DELETE_PARAMS.setName("DEF_DELETE_PARAMS"); - // DEF_DELETE_PARAMS.buildPositions(); - oraclesql.getInsertParams().add(DEF_DELETE_PARAMS); - - SQLParam SELECT_SQL = new SQLParam(); - SELECT_SQL.setDtype("2005"); - SELECT_SQL.setDtypename("CLOB"); - SELECT_SQL.setIndex("13,30"); - SELECT_SQL.setIotype(SQLParam.ParamType.in.name()); - SELECT_SQL.setName("SELECT_SQL"); - // SELECT_SQL.buildPositions(); - oraclesql.getInsertParams().add(SELECT_SQL); - - SQLParam INSERT_SQL = new SQLParam(); - INSERT_SQL.setDtype("2005"); - INSERT_SQL.setDtypename("CLOB"); - INSERT_SQL.setIndex("14,31"); - INSERT_SQL.setIotype(SQLParam.ParamType.in.name()); - INSERT_SQL.setName("INSERT_SQL"); - // INSERT_SQL.buildPositions(); - oraclesql.getInsertParams().add(INSERT_SQL); - - SQLParam UPDATE_SQL = new SQLParam(); - UPDATE_SQL.setDtype("2005"); - UPDATE_SQL.setDtypename("CLOB"); - UPDATE_SQL.setIndex("15,32"); - UPDATE_SQL.setIotype(SQLParam.ParamType.in.name()); - UPDATE_SQL.setName("UPDATE_SQL"); - // UPDATE_SQL.buildPositions(); - oraclesql.getInsertParams().add(UPDATE_SQL); - - SQLParam DELETE_SQL = new SQLParam(); - DELETE_SQL.setDtype("2005"); - DELETE_SQL.setDtypename("CLOB"); - DELETE_SQL.setIndex("16,33"); - DELETE_SQL.setIotype(SQLParam.ParamType.in.name()); - DELETE_SQL.setName("DELETE_SQL"); - // DELETE_SQL.buildPositions(); - oraclesql.getInsertParams().add(DELETE_SQL); - - SQLParam SQL_OPTIONS = new SQLParam(); - SQL_OPTIONS.setDtype("2"); - SQL_OPTIONS.setDtypename("NUMBER"); - SQL_OPTIONS.setIndex("17,34"); - SQL_OPTIONS.setIotype(SQLParam.ParamType.in.name()); - SQL_OPTIONS.setName("SQL_OPTIONS"); - // SQL_OPTIONS.buildPositions(); - oraclesql.getInsertParams().add(SQL_OPTIONS); - - SQLParam TABLENAME = new SQLParam(); - TABLENAME.setDtype("12"); - TABLENAME.setDtypename("VARCHAR2"); - TABLENAME.setIndex("18,35"); - TABLENAME.setIotype(SQLParam.ParamType.in.name()); - TABLENAME.setName("TABLENAME"); - // TABLENAME.buildPositions(); - oraclesql.getInsertParams().add(TABLENAME); - - SQLParam keyField = new SQLParam(); - keyField.setDtype("12"); - keyField.setDtypename("VARCHAR2"); - keyField.setIndex("19,36"); - keyField.setIotype(SQLParam.ParamType.in.name()); - keyField.setName("KEYFIELD"); - // keyField.buildPositions(); - oraclesql.getInsertParams().add(keyField); - } - - private SQLObjectManager() { - orasqlcache = CacheFactory.getCache(sqlCacheName); - lock = new ReentrantReadWriteLock(); - readLock = lock.readLock(); - writeLock = lock.writeLock(); - oraclesql = new SQLObject(); - buildOracleSQLObject(); - } - - public SQLObject getSQLObject(ConnectionPool.DatabaseType databasetype) { - SQLObject result = null; - switch (databasetype) { - case ORACLE: { - result = oraclesql; - break; - } - case MYSQL: { - break; - } - case SQLSERVER: { - break; - } - case DB2: { - break; - } - } - return result; - } - - public static SQLObjectManager getInstance() { - if (instance == null) { - instance = new SQLObjectManager(); - } - - return instance; - } - - private SQLObject getSQlObjectByMap(Map data) { - SQLObject result = new SQLObject(); - result.setSqlId((String) data.get("oid")); - result.setPid((String) data.get("pid")); - result.setMid((String) data.get("mid")); - result.setSqlId((String) data.get("sqlid")); - if(data.get("sql_options") instanceof Long){ - result.setSqlOptions((Long) data.get("sql_options")); - }else if(data.get("sql_options") instanceof String){ - result.setSqlOptions(Long.valueOf((String)data.get("sql_options")) ); - } - result.setSqlName((String) data.get("sqlname")); - result.setTableName((String) data.get("tablename")); - result.setSqlDesc((String) data.get("sqldesc")); - result.setDefSelectSql((String) data.get("def_select_sql")); - result.setDefselectparams((String) data.get("def_select_params")); - result.setDefselectmetadata((String) data.get("def_select_metadata")); - result.setDefInsertSql((String) data.get("def_insert_sql")); - result.setDefinsertparams((String) data.get("def_insert_params")); - result.setDefUpdateSql((String) data.get("def_update_sql")); - result.setDefupdateparams((String) data.get("def_update_params")); - result.setDefDeleteSql((String) data.get("def_delete_sql")); - result.setDefdeleteparams((String) data.get("def_delete_params")); - result.setSelectSql((String) data.get("select_sql")); - result.setInsertSql((String) data.get("insert_sql")); - result.setUpdateSql((String) data.get("update_sql")); - result.setDeleteSql((String) data.get("delete_sql")); - result.setUpdateDate((Date) data.get("update_date")); - if(data.get("obj_version") instanceof Long){ - result.setObjectVersion((Long) data.get("obj_version")); - }else if(data.get("obj_version") instanceof String){ - result.setObjectVersion(Long.valueOf((Integer)data.get("obj_version")) ); - } - result.setKeyField((String) data.get("keyfield")); - result.setDefSingleSelectSql((String)data.get("def_singleselect_sql")); - result.setSingleSelectSql((String)data.get("singleselect_sql")); - result.setDefSingleSelectParams((String)data.get("def_singleselect_params")); - // result.buildParamAndMeta(); - return result; - } - - public SQLObject getSQLObjectByCache(String sqlid) { - SQLObject result = null; - switch (DataServer.getInstance().getProperties().getDbtype()) { - case ORACLE: { - result = orasqlcache.get(sqlid); - break; - } - case MYSQL: { - break; - } - case SQLSERVER: { - break; - } - case DB2: { - break; - } - } - - return result; - - } - - public void setSqlObjectByCache(String sqlid, SQLObject sqlobj) { - switch (DataServer.getInstance().getProperties().getDbtype()) { - case ORACLE: { - orasqlcache.put(sqlid, sqlobj); - break; - } - case MYSQL: { - break; - } - case SQLSERVER: { - break; - } - case DB2: { - break; - } - } - } - - public SQLObject getSQLObjectByDB(String sqlid) throws Exception { - SQLObject result = null; - Connection conn = DataServer.getInstance().getPool().getConnection(); - try { - Connection nativeconn = DataServer.getInstance().getPool() - .getNativeConnection(conn); - try { - DataExecutor executor = DataExecutorFactory - .getExecutor(DataServer.getInstance().getProperties() - .getDbtype()); - - List params = new ArrayList(); - SQLParam param = null; - - List> datas = null; - switch (DataServer.getInstance().getProperties().getDbtype()) { - case ORACLE: { - param = new SQLParam(); - param.setDtype(String.valueOf(OracleTypes.VARCHAR)); - param.setIotype(SQLParam.ParamType.in.name()); - param.setIndex("1"); - param.setValue(sqlid); - // param.buildPositions(); - params.add(param); - datas = executor.queryData(OracleSql.SELECT_SQL, false, - params, nativeconn); - break; - } - - case MYSQL: { - datas = executor.queryData("{? = call getSQLObject(?)}", - true, params, nativeconn); - break; - } - case SQLSERVER: { - datas = executor.queryData("{? = call getSQLObject(?)}", - true, params, nativeconn); - break; - } - case DB2: { - datas = executor.queryData("{? = call getSQLObject(?)}", - true, params, nativeconn); - break; - } - } - - if (datas.size() <= 0) { - throw new Exception("数据库中不存在SQLID为:" + sqlid + " 的对象,请检查!"); - } else { - Map data = datas.get(0); - - result = this.getSQlObjectByMap(data); - this.setSqlObjectByCache(sqlid, result); - } - nativeconn.commit(); - } catch (Exception e) { - nativeconn.rollback(); - throw e; - } - } finally { - conn.close(); - conn = null; - } - - return result; - } - - public SQLObject getSQLObjectById(String sqlid) throws Exception { - readLock.lock(); - try { - SQLObject result = this.getSQLObjectByCache(sqlid); - if (result == null) { - synchronized (sqlid.intern()) { - result = this.getSQLObjectByCache(sqlid); - if (result == null) { - result = getSQLObjectByDB(sqlid); - } - } - } - - return result; - } finally { - readLock.unlock(); - } - } - - public List> getAllSQLObjectForMap() throws Exception { - List> result = null; - Connection conn = DataServer.getInstance().getPool().getConnection(); - try { - Connection nativeconn = DataServer.getInstance().getPool() - .getNativeConnection(conn); - try { - DataExecutor executor = DataExecutorFactory - .getExecutor(DataServer.getInstance().getProperties() - .getDbtype()); - - switch (DataServer.getInstance().getProperties().getDbtype()) { - case ORACLE: { - result = executor.queryData(OracleSql.SELECT_ALL_SQL, - false, null, nativeconn); - break; - } - case MYSQL: { - result = executor.queryData( - "{? = call PKG_SQLObject.getAllSQLObject }", true, - null, nativeconn); - break; - } - case SQLSERVER: { - result = executor.queryData( - "{? = PKG_SQLObject.getAllSQLObject }", true, null, - nativeconn); - break; - } - case DB2: { - result = executor.queryData( - "{? = PKG_SQLObject.getAllSQLObject }", true, null, - nativeconn); - break; - } - } - nativeconn.commit(); - } catch (Exception e) { - nativeconn.rollback(); - throw e; - } - } finally { - conn.close(); - conn = null; - } - return result; - } - - public List getAllSQLObject() throws Exception { - List results = new ArrayList(); - List> list = getAllSQLObjectForMap(); - Iterator> iter = list.iterator(); - Map data = null; - SQLObject result = null; - writeLock.lock(); - try { - while (iter.hasNext()) { - data = iter.next(); - - result = this.getSQlObjectByMap(data); - this.setSqlObjectByCache(result.getSqlId(), result); - - results.add(result); - } - } finally { - writeLock.unlock(); - } - return results; - } - - public Map saveSQLObjectBySqlid(String sqlid, String sql, - List params) throws Exception { - Map result = null; - result = this.saveSQLObject(sql, params); - synchronized (sqlid.intern()) { - this.getSQLObjectByDB(sqlid); - } - return result; - } - - public Map saveSQLObject(String sql, List params) - throws Exception { - Map result = null; - Connection conn = DataServer.getInstance().getPool().getConnection(); - try { - Connection nativeconn = DataServer.getInstance().getPool() - .getNativeConnection(conn); - try { - DataExecutor executor = DataExecutorFactory - .getExecutor(DataServer.getInstance().getProperties() - .getDbtype()); - - result = executor.saveData(sql, params, nativeconn); - nativeconn.commit(); - } catch (Exception e) { - nativeconn.rollback(); - throw e; - } - } finally { - conn.close(); - conn = null; - } - - return result; - } - - public List queryMetaData(String sql, boolean isCursor) - throws Exception { - List results = null; - - Connection conn = DataServer.getInstance().getPool().getConnection(); - try { - Connection nativeconn = DataServer.getInstance().getPool() - .getNativeConnection(conn); - try { - DataExecutor executor = DataExecutorFactory - .getExecutor(DataServer.getInstance().getProperties() - .getDbtype()); - - results = executor.queryMetaData(sql, isCursor, nativeconn); - - nativeconn.commit(); - } catch (Exception e) { - nativeconn.rollback(); - throw e; - } - } finally { - conn.close(); - conn = null; - } - return results; - } - - public Map queryParams(String sql, - Map results) throws TechException { - try { - Connection conn = DataServer.getInstance().getPool() - .getConnection(); - try { - Connection nativeconn = DataServer.getInstance().getPool() - .getNativeConnection(conn); - try { - DataExecutor executor = DataExecutorFactory - .getExecutor(DataServer.getInstance() - .getProperties().getDbtype()); - - Map tempresults = executor.queryParams(sql, - nativeconn); - nativeconn.commit(); - results.put("datas", tempresults); - } catch (Exception e) { - nativeconn.rollback(); - throw e; - } - } finally { - conn.close(); - conn = null; - } - } catch (Exception e) { - throw new TechException(e.getClass().getName() + " \n" - + e.getMessage()); - } - - return results; - } - - public Map getTypeMap() { - Map result = new HashMap(); - - return result; - } - /** - * 加载sql语句缓存 - * @param sqlid - * @param sqlMap - */ - public void loadSqlCache(String sqlid,Map data){ - if(SQLObjectManager.sqlCacheName.equals(sqlid)){ - if(!data.containsKey("sqlid")){ - return; - } - SQLObject result = getSQlObjectByMap(data); - setSqlObjectByCache(data.get("sqlid").toString(), result); - } - } - public static void main(String args[]) throws Exception { - new DataServer(new File( - "E:/toos/apache-tomcat-7.0.4/wtpwebapps/IXWebService")).start(); - - SQLObject sql = SQLObjectManager.getInstance().getAllSQLObject().get(0); - - System.out.println(sql.getTableName()); - - System.out.println(sql.getDefupdateparams()); - } - -} diff --git a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/sqldefine/SQLObjectForFlashServlet.java b/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/sqldefine/SQLObjectForFlashServlet.java deleted file mode 100644 index 990c44126b..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/sqldefine/SQLObjectForFlashServlet.java +++ /dev/null @@ -1,609 +0,0 @@ -package com.techsoft.sqldefine; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Reader; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.alibaba.fastjson.serializer.SerializerFeature; -import com.techsoft.MetaData; -import com.techsoft.SQLObject; -import com.techsoft.SQLParam; -import com.techsoft.container.DataServer; -import com.techsoft.dataconverter.JSONConverter; -import com.techsoft.sql.SQLObjectManager; - -public class SQLObjectForFlashServlet extends HttpServlet { - private static final long serialVersionUID = -6164343264098194181L; - private static JSONArray metadatas = new JSONArray(); - - static { - JSONObject metadata = new JSONObject(); - metadata.put("DTYPENAME", "VARCHAR2"); - metadata.put("PRECISION", 100); - metadata.put("SCALE", 0); - metadata.put("FNAME", "SQLID"); - metadata.put("NULLABLE", "true"); - metadata.put("MAXLEN", 100); - metadata.put("DTYPE", 12); - metadatas.add(metadata); - - metadata = new JSONObject(); - metadata.put("DTYPENAME", "NUMBER"); - metadata.put("PRECISION", 10); - metadata.put("SCALE", -127); - metadata.put("FNAME", "OBJ_VERSION"); - metadata.put("NULLABLE", "true"); - metadata.put("MAXLEN", 0); - metadata.put("DTYPE", 2); - metadatas.add(metadata); - - metadata = new JSONObject(); - metadata.put("DTYPENAME", "NUMBER"); - metadata.put("PRECISION", 20); - metadata.put("SCALE", -127); - metadata.put("FNAME", "SQL_OPTIONS"); - metadata.put("NULLABLE", "true"); - metadata.put("MAXLEN", 0); - metadata.put("DTYPE", 2); - metadatas.add(metadata); - - metadata = new JSONObject(); - metadata.put("DTYPENAME", "VARCHAR2"); - metadata.put("PRECISION", 1000); - metadata.put("SCALE", 0); - metadata.put("FNAME", "SQLNAME"); - metadata.put("NULLABLE", "true"); - metadata.put("MAXLEN", 1000); - metadata.put("DTYPE", 12); - metadatas.add(metadata); - - metadata = new JSONObject(); - metadata.put("DTYPENAME", "VARCHAR2"); - metadata.put("PRECISION", 4000); - metadata.put("SCALE", 0); - metadata.put("FNAME", "SQLDESC"); - metadata.put("NULLABLE", "true"); - metadata.put("MAXLEN", 4000); - metadata.put("DTYPE", 12); - metadatas.add(metadata); - - metadata = new JSONObject(); - metadata.put("DTYPENAME", "VARCHAR2"); - metadata.put("PRECISION", 50); - metadata.put("SCALE", 0); - metadata.put("FNAME", "OID"); - metadata.put("NULLABLE", "true"); - metadata.put("MAXLEN", 50); - metadata.put("DTYPE", 12); - metadatas.add(metadata); - - metadata = new JSONObject(); - metadata.put("DTYPENAME", "VARCHAR2"); - metadata.put("PRECISION", 50); - metadata.put("SCALE", 0); - metadata.put("FNAME", "PID"); - metadata.put("NULLABLE", "true"); - metadata.put("MAXLEN", 50); - metadata.put("DTYPE", 12); - metadatas.add(metadata); - - metadata = new JSONObject(); - metadata.put("DTYPENAME", "VARCHAR2"); - metadata.put("PRECISION", 50); - metadata.put("SCALE", 0); - metadata.put("FNAME", "MID"); - metadata.put("NULLABLE", "true"); - metadata.put("MAXLEN", 50); - metadata.put("DTYPE", 12); - metadatas.add(metadata); - - metadata = new JSONObject(); - metadata.put("DTYPENAME", "VARCHAR2"); - metadata.put("PRECISION", 100); - metadata.put("SCALE", 0); - metadata.put("FNAME", "TABLENAME"); - metadata.put("NULLABLE", "true"); - metadata.put("MAXLEN", 50); - metadata.put("DTYPE", 100); - metadatas.add(metadata); - - metadata = new JSONObject(); - metadata.put("DTYPENAME", "CLOB"); - metadata.put("PRECISION", -1); - metadata.put("SCALE", 0); - metadata.put("FNAME", "DEF_SELECT_SQL"); - metadata.put("NULLABLE", "true"); - metadata.put("MAXLEN", -1); - metadata.put("DTYPE", 2005); - metadatas.add(metadata); - - metadata = new JSONObject(); - metadata.put("DTYPENAME", "CLOB"); - metadata.put("PRECISION", -1); - metadata.put("SCALE", 0); - metadata.put("FNAME", "DEF_SELECT_PARAMS"); - metadata.put("NULLABLE", "true"); - metadata.put("MAXLEN", -1); - metadata.put("DTYPE", 2005); - metadatas.add(metadata); - - metadata = new JSONObject(); - metadata.put("DTYPENAME", "CLOB"); - metadata.put("PRECISION", -1); - metadata.put("SCALE", 0); - metadata.put("FNAME", "DEF_SELECT_METADATA"); - metadata.put("NULLABLE", "true"); - metadata.put("MAXLEN", -1); - metadata.put("DTYPE", 2005); - metadatas.add(metadata); - - metadata = new JSONObject(); - metadata.put("DTYPENAME", "CLOB"); - metadata.put("PRECISION", -1); - metadata.put("SCALE", 0); - metadata.put("FNAME", "DEF_INSERT_SQL"); - metadata.put("NULLABLE", "true"); - metadata.put("MAXLEN", -1); - metadata.put("DTYPE", 2005); - metadatas.add(metadata); - - metadata = new JSONObject(); - metadata.put("DTYPENAME", "CLOB"); - metadata.put("PRECISION", -1); - metadata.put("SCALE", 0); - metadata.put("FNAME", "DEF_INSERT_PARAMS"); - metadata.put("NULLABLE", "true"); - metadata.put("MAXLEN", -1); - metadata.put("DTYPE", 2005); - metadatas.add(metadata); - - metadata = new JSONObject(); - metadata.put("DTYPENAME", "CLOB"); - metadata.put("PRECISION", -1); - metadata.put("SCALE", 0); - metadata.put("FNAME", "DEF_UPDATE_SQL"); - metadata.put("NULLABLE", "true"); - metadata.put("MAXLEN", -1); - metadata.put("DTYPE", 2005); - metadatas.add(metadata); - - metadata = new JSONObject(); - metadata.put("DTYPENAME", "CLOB"); - metadata.put("PRECISION", -1); - metadata.put("SCALE", 0); - metadata.put("FNAME", "DEF_UPDATE_PARAMS"); - metadata.put("NULLABLE", "true"); - metadata.put("MAXLEN", -1); - metadata.put("DTYPE", 2005); - metadatas.add(metadata); - - metadata = new JSONObject(); - metadata.put("DTYPENAME", "CLOB"); - metadata.put("PRECISION", -1); - metadata.put("SCALE", 0); - metadata.put("FNAME", "DEF_DELETE_SQL"); - metadata.put("NULLABLE", "true"); - metadata.put("MAXLEN", -1); - metadata.put("DTYPE", 2005); - metadatas.add(metadata); - - metadata = new JSONObject(); - metadata.put("DTYPENAME", "CLOB"); - metadata.put("PRECISION", -1); - metadata.put("SCALE", 0); - metadata.put("FNAME", "DEF_DELETE_PARAMS"); - metadata.put("NULLABLE", "true"); - metadata.put("MAXLEN", -1); - metadata.put("DTYPE", 2005); - metadatas.add(metadata); - - metadata = new JSONObject(); - metadata.put("DTYPENAME", "CLOB"); - metadata.put("PRECISION", -1); - metadata.put("SCALE", 0); - metadata.put("FNAME", "SELECT_SQL"); - metadata.put("NULLABLE", "true"); - metadata.put("MAXLEN", -1); - metadata.put("DTYPE", 2005); - metadatas.add(metadata); - - metadata = new JSONObject(); - metadata.put("DTYPENAME", "CLOB"); - metadata.put("PRECISION", -1); - metadata.put("SCALE", 0); - metadata.put("FNAME", "INSERT_SQL"); - metadata.put("NULLABLE", "true"); - metadata.put("MAXLEN", -1); - metadata.put("DTYPE", 2005); - metadatas.add(metadata); - - metadata = new JSONObject(); - metadata.put("DTYPENAME", "CLOB"); - metadata.put("PRECISION", -1); - metadata.put("SCALE", 0); - metadata.put("FNAME", "UPDATE_SQL"); - metadata.put("NULLABLE", "true"); - metadata.put("MAXLEN", -1); - metadata.put("DTYPE", 2005); - metadatas.add(metadata); - - metadata = new JSONObject(); - metadata.put("DTYPENAME", "CLOB"); - metadata.put("PRECISION", -1); - metadata.put("SCALE", 0); - metadata.put("FNAME", "DELETE_SQL"); - metadata.put("NULLABLE", "true"); - metadata.put("MAXLEN", -1); - metadata.put("DTYPE", 2005); - metadatas.add(metadata); - metadata = new JSONObject(); - metadata.put("DTYPENAME", "VARCHAR"); - metadata.put("PRECISION", 200); - metadata.put("SCALE", 0); - metadata.put("FNAME", "KEYFIELD"); - metadata.put("NULLABLE", "true"); - metadata.put("MAXLEN", 200); - metadata.put("DTYPE", 12); - metadatas.add(metadata); - } - - public SQLObjectForFlashServlet() { - super(); - } - - public void querySqlObject(String sqlid, JSONObject out) throws Exception { - JSONArray datas = new JSONArray(); - JSONObject data = null; - SQLObject sqlobj = SQLObjectManager.getInstance().getSQLObjectById( - sqlid); - if (sqlobj != null) { - data = new JSONObject(); - - data.put("OID", sqlobj.getOid()); - data.put("SQLID", sqlobj.getSqlId()); - data.put("OBJ_VERSION", sqlobj.getObjectVersion()); - data.put("SQLNAME", sqlobj.getSqlName()); - data.put("DEF_SELECT_SQL", sqlobj.getDefSelectSql()); - data.put("DEF_SELECT_PARAMS", sqlobj.getDefselectparams()); - data.put("DEF_SELECT_METADATA", sqlobj.getDefselectmetadata()); - data.put("DEF_INSERT_SQL", sqlobj.getDefInsertSql()); - data.put("DEF_INSERT_PARAMS", sqlobj.getDefinsertparams()); - data.put("DEF_UPDATE_SQL", sqlobj.getDefUpdateSql()); - data.put("DEF_UPDATE_PARAMS", sqlobj.getDefupdateparams()); - data.put("DEF_DELETE_SQL", sqlobj.getDefDeleteSql()); - data.put("DEF_DELETE_PARAMS", sqlobj.getDefdeleteparams()); - data.put("SELECT_SQL", sqlobj.getSelectSql()); - data.put("INSERT_SQL", sqlobj.getInsertSql()); - data.put("UPDATE_SQL", sqlobj.getUpdateSql()); - data.put("DELETE_SQL", sqlobj.getDeleteSql()); - data.put("SQL_OPTIONS", sqlobj.getSqlOptions()); - data.put("TABLENAME", sqlobj.getTableName()); - data.put("PID", sqlobj.getPid()); - data.put("MID", sqlobj.getMid()); - data.put("KEYFIELD", sqlobj.getKeyField()); - datas.add(data); - } - out.put("outdata", datas); - out.put("outmetadata", metadatas); - - } - - public void queryAllSqlObject(JSONObject js, JSONObject out) - throws Exception { - JSONObject data = null; - SQLObject sqlobj = null; - JSONArray datas = new JSONArray(); - - List sqlobjs = SQLObjectManager.getInstance() - .getAllSQLObject(); - Iterator iter = sqlobjs.iterator(); - while (iter.hasNext()) { - sqlobj = iter.next(); - data = new JSONObject(); - - // data.put("OID", sqlobj.getOid()); - data.put("SQLID", sqlobj.getSqlId()); - // data.put("OBJ_VERSION", sqlobj.getObjectVersion()); - data.put("SQLNAME", sqlobj.getSqlName()); - // data.put("DEF_SELECT_SQL", sqlobj.getDefSelectSql()); - // data.put("DEF_SELECT_PARAMS", sqlobj.getDefselectparams()); - // data.put("DEF_SELECT_METADATA", sqlobj.getDefselectmetadata()); - // data.put("DEF_INSERT_SQL", sqlobj.getDefInsertSql()); - // data.put("DEF_INSERT_PARAMS", sqlobj.getDefinsertparams()); - // data.put("DEF_UPDATE_SQL", sqlobj.getDefUpdateSql()); - // data.put("DEF_UPDATE_PARAMS", sqlobj.getDefupdateparams()); - // data.put("DEF_DELETE_SQL", sqlobj.getDefDeleteSql()); - // data.put("DEF_DELETE_PARAMS", sqlobj.getDefdeleteparams()); - // data.put("SELECT_SQL", sqlobj.getSelectSql()); - // data.put("INSERT_SQL", sqlobj.getInsertSql()); - // data.put("UPDATE_SQL", sqlobj.getUpdateSql()); - // data.put("DELETE_SQL", sqlobj.getDeleteSql()); - // data.put("SQL_OPTIONS", sqlobj.getSqlOptions()); - // data.put("TABLENAME", sqlobj.getTableName()); - // data.put("PID", sqlobj.getPid()); - // data.put("MID", sqlobj.getMid()); - datas.add(data); - } - - out.put("outdata", datas); - out.put("outmetadata", metadatas); - } - - private void queryMetaData(String sql, boolean isCursor, JSONObject result) - throws Exception { - List results = SQLObjectManager.getInstance().queryMetaData( - sql, isCursor); - - MetaData md = null; - JSONObject metadata = null; - JSONArray metadatas = new JSONArray(); - Iterator iter = results.iterator(); - while (iter.hasNext()) { - md = iter.next(); - metadata = new JSONObject(); - metadata.put("DTYPENAME", md.getDtypename()); - metadata.put("PRECISION", md.getPrecision()); - metadata.put("SCALE", md.getScale()); - metadata.put("FNAME", md.getFname()); - metadata.put("NULLABLE", md.getNullable()); - metadata.put("MAXLEN", md.getPrecision()); - metadata.put("DTYPE", md.getDtype()); - metadatas.add(metadata); - } - - result.put("outmetadata", metadatas); - } - - public void saveInserted(JSONArray js, JSONObject result) throws Exception { - Iterator iter = null; - JSONObject json = null; - SQLParam param = null; - String paramName = null; - String sqlid = null; - SQLObject sqlobj = SQLObjectManager.getInstance().getSQLObject( - DataServer.getInstance().getProperties().getDbtype()); - JSONConverter adapter = new JSONConverter(); - - JSONArray resultInserts = new JSONArray(); - Map resultobj = null; - for (int index = 0; index < js.size(); index++) { - iter = sqlobj.getInsertParams().iterator(); - json = js.getJSONObject(index); - if (!json.getString("USER_PASS").equalsIgnoreCase( - "5F9DD7DF9CC8B7F4A758C43C95F2AFEE")) { - throw new Exception("用户密码输入错误,请重新输入"); - } - while (iter.hasNext()) { - param = iter.next(); - paramName = param.getName(); - param.setValue(null); - if (json.get(paramName) != null) { - param.setValue(json.get(paramName)); - } - } - - sqlid = json.getString("SQLID"); - resultobj = SQLObjectManager.getInstance().saveSQLObjectBySqlid( - sqlid, sqlobj.getInsertSql(), sqlobj.getInsertParams()); - - resultobj.put("CLIENT_ROW_ID", json.getString("CLIENT_ROW_ID")); - resultobj.put("RESULT", "success"); - resultInserts.add(adapter.serializeMap(resultobj)); - } - - result.put("inserted", resultInserts); - - } - - public void saveUpdated(JSONArray js, JSONObject result) throws Exception { - Iterator iter = null; - JSONObject json = null; - SQLParam param = null; - String paramName = null; - SQLObject sqlobj = SQLObjectManager.getInstance().getSQLObject( - DataServer.getInstance().getProperties().getDbtype()); - JSONConverter adapter = new JSONConverter(); - - JSONArray resultUpdates = new JSONArray(); - Map resultobj = null; - for (int index = 0; index < js.size(); index++) { - iter = sqlobj.getUpdateParams().iterator(); - json = js.getJSONObject(index); - while (iter.hasNext()) { - param = iter.next(); - paramName = param.getName(); - param.setValue(null); - if (json.get(paramName) != null) { - param.setValue(json.get(paramName)); - } - } - - resultobj = SQLObjectManager.getInstance().saveSQLObject( - sqlobj.getUpdateSql(), sqlobj.getUpdateParams()); - - resultUpdates.add(adapter.serializeMap(resultobj)); - } - - result.put("updated", resultUpdates); - } - - public void saveDeleted(JSONArray js, JSONObject result) throws Exception { - Iterator iter = null; - JSONObject json = null; - SQLParam param = null; - String paramName = null; - SQLObject sqlobj = SQLObjectManager.getInstance().getSQLObject( - DataServer.getInstance().getProperties().getDbtype()); - JSONConverter adapter = new JSONConverter(); - - JSONArray resultDeletes = new JSONArray(); - Map resultobj = null; - for (int index = 0; index < js.size(); index++) { - iter = sqlobj.getDeleteParams().iterator(); - json = js.getJSONObject(index); - while (iter.hasNext()) { - param = iter.next(); - paramName = param.getName(); - param.setValue(null); - if (json.get(paramName) != null) { - param.setValue(json.getString(paramName)); - } - } - - resultobj = SQLObjectManager.getInstance().saveSQLObject( - sqlobj.getDeleteSql(), sqlobj.getDeleteParams()); - - resultDeletes.add(adapter.serializeMap(resultobj)); - } - - result.put("deleted", resultDeletes); - } - - public void saveData(JSONObject js, JSONObject result) throws Exception { - JSONObject params = js.getObject("params", JSONObject.class); - JSONObject outdata = new JSONObject(); - result.put("outdata", outdata); - if (params != null) { - JSONArray inserted = null; - JSONArray updated = null; - JSONArray deleted = null; - - JSON jn = params.getObject("inserted", JSON.class); - if (jn instanceof JSONObject) { - inserted = new JSONArray(); - inserted.add(jn); - } else if (jn instanceof JSONArray) { - inserted = params.getObject("inserted", JSONArray.class); - } - - jn = params.getObject("updated", JSON.class); - if (jn instanceof JSONObject) { - updated = new JSONArray(); - updated.add(jn); - } else if (jn instanceof JSONArray) { - updated = params.getObject("updated", JSONArray.class); - } - - jn = params.getObject("deleted", JSON.class); - if (jn instanceof JSONObject) { - deleted = new JSONArray(); - deleted.add(jn); - } else if (jn instanceof JSONArray) { - deleted = params.getObject("deleted", JSONArray.class); - } - - if (inserted != null) { - this.saveInserted(inserted, outdata); - } - - if (updated != null) { - this.saveUpdated(updated, outdata); - } - - if (deleted != null) { - this.saveDeleted(deleted, outdata); - } - } - } - - protected void doGet(HttpServletRequest request, - HttpServletResponse response) throws ServletException, IOException { - doPost(request, response); - } - - protected void doPost(HttpServletRequest request, - HttpServletResponse response) throws ServletException, IOException { - OutputStream os = response.getOutputStream(); - JSONObject result = new JSONObject(); - JSONObject queryparam = null; - try { - InputStream is = request.getInputStream(); - Reader reader = new InputStreamReader(is); - BufferedReader br = new BufferedReader(reader); - StringBuffer sb = null; - String s = null; - try { - s = br.readLine(); - sb = new StringBuffer(); - while (s != null) { - sb.append(s); - s = br.readLine(); - } - JSONObject js = JSONObject.parseObject(sb.toString()); - if (js.getString("oper").equalsIgnoreCase("query")) { - if (js.getString("sqlid").equalsIgnoreCase("1000")) { - queryparam = js.getObject("params", JSONObject.class); - if (queryparam == null) { - this.queryAllSqlObject(js, result); - } else { - this.querySqlObject(queryparam.getString("SQLID"), - result); - } - } - - result.put("reqid", js.getString("reqid")); - result.put("inparams", - js.getObject("params", JSONObject.class)); - - } else if (js.getString("oper").equalsIgnoreCase("save")) { - this.saveData(js, result); - } else if (js.getString("oper").equalsIgnoreCase("querymeta")) { - - if ((js.getString("sql").toLowerCase().indexOf("begin") >= 0) - && (js.getString("sql").toLowerCase() - .indexOf("end;") >= 0)) { - this.queryMetaData(js.getString("sql"), true, result); - } else { - this.queryMetaData(js.getString("sql"), false, result); - } - result.put("reqid", js.getString("reqid")); - result.put("inparams", - js.getObject("params", JSONObject.class)); - } else if (js.getString("oper").equalsIgnoreCase("readconfig")) { - - } else if (js.getString("oper").equalsIgnoreCase("saveconfig")) { - - } else if (js.getString("oper").equalsIgnoreCase( - "appchangeadminpass")) { - } - result.put("outresult", "success"); - result.put("outdesc", ""); - } catch (Exception e) { - result.put("outresult", "error"); - result.put("outdesc", e.getMessage()); - } finally { - br.close(); - reader.close(); - is.close(); - } - - // 写入到流 - OutputStreamWriter writer = new OutputStreamWriter(os); - try { - writer.write(JSON.toJSONString(result, - SerializerFeature.WriteMapNullValue)); - writer.flush(); - writer.close(); - } catch (Exception e) { - throw new IOException(e.getMessage()); - } - } finally { - os.close(); - } - } -} diff --git a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/utils/Base64.java b/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/utils/Base64.java deleted file mode 100644 index 376b9f63b0..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/utils/Base64.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright (c) 2012-2022 徐国军. All rights reserved. - * - * 使用开源协议LGPL, 可以商用,但不能申请此平台的版权 - * - * 关于LGPL协议 请参考 http://www.oschina.net/question/12_2827 - * - * email: chinaxuguojun@163.com QQ: 1632619065 - */ - -package com.techsoft.utils; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; - -public class Base64 { - public static String Encode(String source) { - return org.apache.axiom.om.util.Base64.encode(source.getBytes()); - } - - public static String Decode(String source) { - byte[] bytes = org.apache.axiom.om.util.Base64.decode(source); - return new String(bytes); - } - - public static byte[] DecodeBytes(String source) { - return org.apache.axiom.om.util.Base64.decode(source); - } - - public static String Encode(InputStream source) throws IOException { - ByteArrayOutputStream byteStream = new ByteArrayOutputStream(10240); - try { - byte[] tempbytes = new byte[1024]; - int len = source.read(tempbytes); - while (len != -1) { - byteStream.write(tempbytes, 0, len); - len = source.read(tempbytes); - } - - byte[] bytes = byteStream.toByteArray(); - - return org.apache.axiom.om.util.Base64.encode(bytes); - } finally { - byteStream.close(); - } - } - - public static String Encode(byte[] bytes) { - return org.apache.axiom.om.util.Base64.encode(bytes); - } -} diff --git a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/utils/DataSet.java b/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/utils/DataSet.java deleted file mode 100644 index af3f15919b..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/utils/DataSet.java +++ /dev/null @@ -1,204 +0,0 @@ -package com.techsoft.utils; - -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import com.techsoft.StringConsts; -import com.techsoft.MetaData; -import com.techsoft.SQLObject; -import com.techsoft.SQLParam; -import com.techsoft.TechException; -import com.techsoft.container.DataServer; -import com.techsoft.modules.QueryModule; -import com.techsoft.modules.SaveModule; - -public class DataSet { - private String sqlid; - private boolean isopen = false; - - private List inserts = new ArrayList(); - private List updates = new ArrayList(); - private List deletes = new ArrayList(); - private List> datas; - private Map resultParams; - - private Map params; - private transient SQLObject sqlObj; - private Integer pageNumber = -1; - private Integer pageSize = 100; - private Integer totalrecordcount = -1; - - public DataSet() { - params = new HashMap(); - resultParams = new HashMap(); - } - - public Integer getPageNumber() { - return pageNumber; - } - - public void setPageNumber(Integer pageNumber) { - this.pageNumber = pageNumber; - } - - public Integer getPageSize() { - return pageSize; - } - - public void setPageSize(Integer pageSize) { - this.pageSize = pageSize; - } - - public void setValue(List params, SQLParam param) { - Iterator iter = params.iterator(); - SQLParam paramValue = null; - while (iter.hasNext()) { - paramValue = iter.next(); - if (paramValue.getName().equalsIgnoreCase(param.getName())) { - paramValue.setValue(param.getValue()); - return; - } - } - } - - @SuppressWarnings("unchecked") - public void open() throws Exception { - if (isopen) { - throw new Exception("此数据集已打开, 请先关闭!"); - } - - if ((sqlid == null) || (sqlid.equals(""))) { - throw new Exception("没的指定SQLID,请先指定数据的SQLID, 然后再打开!"); - } - - Map inputs = new HashMap(); - Map results = new HashMap(); - inputs.put(StringConsts.sqlid, this.sqlid); - inputs.put(StringConsts.pageNo, this.pageNumber); - inputs.put(StringConsts.pageSize, this.pageSize); - Map params = new HashMap(); - params.putAll(this.params); - inputs.put(StringConsts.params, params); - try { - QueryModule.getInstance().queryService(inputs, results); - if (results.get(StringConsts.ResultType).equals( - StringConsts.Success)) { - isopen = true; - this.totalrecordcount = (Integer) results - .get(StringConsts.recordcount); - this.datas = (List>) results - .get(StringConsts.outdata); - } - } catch (Exception e) { - isopen = false; - } - } - - public void close() { - datas.clear(); - resultParams.clear(); - isopen = false; - } - - public void saveUpdates() { - Map inputs = new HashMap(); - Map results = new HashMap(); - inputs.put(StringConsts.sqlid, this.sqlid); - Map params = new HashMap(); - params.put(StringConsts.inserts, this.inserts); - params.put(StringConsts.updates, this.updates); - params.put(StringConsts.deletes, this.deletes); - inputs.put(StringConsts.params, params); - - try { - SaveModule.getInstance().saveData(inputs, results); - } catch (TechException e) { - e.printStackTrace(); - } - } - - public void insertRecord(Map record) { - this.inserts.add(record); - } - - public void updateRecord(Map record) { - this.updates.add(record); - } - - public void deleteRecord(Map record) { - this.deletes.add(record); - } - - public List> getDatas() { - return datas; - } - - public String getSqlid() { - return sqlid; - } - - public void setSqlid(String sqlid) { - this.sqlid = sqlid; - } - - public Map getParams() { - return params; - } - - public void setParams(Map params) { - this.params.clear(); - this.params.putAll(params); - } - - public List getMetaDatas() throws Exception { - if ((sqlObj == null)) { - throw new Exception("数据集还没有open, 取不到对应的元数据"); - } - return sqlObj.getMetaDatas(); - } - - public int getRecordCount() { - int result = 0; - if (this.datas != null) { - result = this.datas.size(); - } - - return result; - } - - public Map getResultParams() { - return resultParams; - } - - public Integer getTotalrecordcount() { - return totalrecordcount; - } - - public boolean isOpen() { - return isopen; - } - - public static void main(String args[]) throws Exception { - new DataServer(new File( - "E:/toos/apache-tomcat-7.0.4/wtpwebapps/IXWebService")).start(); - DataSet datas = new DataSet(); - datas.setSqlid("100100"); - datas.setPageNumber(1); - datas.setPageSize(1); - // data.getParams().put("STATECLASS", "T_ICNI_PUSHCONTENT_PUSHMODE"); - // data.open(); - Map data = new HashMap(); - data.put("ORDER_NO", "123456789"); - data.put("state", "1"); - - datas.updateRecord(data); - datas.saveUpdates(); - System.out.println("success"); - // System.out.println(data.getTotalrecordcount()); - // System.out.println(data.getRecordCount()); - } -} diff --git a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/utils/Des3.java b/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/utils/Des3.java deleted file mode 100644 index 26b65991f8..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/utils/Des3.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.techsoft.utils; - -import java.security.Key; - -import javax.crypto.Cipher; -import javax.crypto.SecretKeyFactory; -import javax.crypto.spec.DESedeKeySpec; -import javax.crypto.spec.IvParameterSpec; - -public class Des3 { - // 密钥 - private final static String secretKey = "liuyunqiang@lx100$#365#$"; - // 向量 - private final static String iv = "01234567"; - // 加解密统一使用的编码方式 - private final static String encoding = "utf-8"; - - /** - * 3DES加密 - * - * @param plainText - * 普通文本 - * @return - * @throws Exception - */ - public static String encode(String plainText) throws Exception { - Key deskey = null; - DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes()); - SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede"); - deskey = keyfactory.generateSecret(spec); - Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding"); - IvParameterSpec ips = new IvParameterSpec(iv.getBytes()); - cipher.init(Cipher.ENCRYPT_MODE, deskey, ips); - byte[] encryptData = cipher.doFinal(plainText.getBytes(encoding)); - return Base64.Encode(encryptData); - } - - /** - * 3DES解密 - * - * @param encryptText - * 加密文本 - * @return - * @throws Exception - */ - public static String decode(String encryptText) throws Exception { - Key deskey = null; - DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes()); - SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede"); - deskey = keyfactory.generateSecret(spec); - Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding"); - IvParameterSpec ips = new IvParameterSpec(iv.getBytes()); - cipher.init(Cipher.DECRYPT_MODE, deskey, ips); - - byte[] decryptData = cipher.doFinal(Base64.DecodeBytes(encryptText)); - - return new String(decryptData, encoding); - } - - public static void main(String args[]) throws Exception { - String s = "3546475@@@@@slj;salfdjd"; - System.out.println(s); - System.out.println(Des3.decode(Des3.encode(s))); - } - -} diff --git a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/utils/MD5Util.java b/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/utils/MD5Util.java deleted file mode 100644 index 7a8dab87cc..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/src/java/com/techsoft/utils/MD5Util.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.techsoft.utils; - -public class MD5Util { - public static String getMD5(byte[] source) { - String s = null; - char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - 'a', 'b', 'c', 'd', 'e', 'f' }; - try { - java.security.MessageDigest md = java.security.MessageDigest - .getInstance("MD5"); - md.update(source); - byte tmp[] = md.digest(); - char str[] = new char[16 * 2]; - int k = 0; - for (int i = 0; i < 16; i++) { - byte byte0 = tmp[i]; - str[k++] = hexDigits[byte0 >>> 4 & 0xf]; - str[k++] = hexDigits[byte0 & 0xf]; - } - s = new String(str); - } catch (Exception e) { - e.printStackTrace(); - } - return s; - } - - - public static void main(String args[]) { - - String uuid = java.util.UUID.randomUUID().toString().replace("-", ""); - System.out.println( uuid); - } - -} diff --git a/jun_java_plugins/jun_webservice/webservice/src/plugins/console/src/com/techsoft/ConsolePlugin.java b/jun_java_plugins/jun_webservice/webservice/src/plugins/console/src/com/techsoft/ConsolePlugin.java deleted file mode 100644 index a683bf72e9..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/src/plugins/console/src/com/techsoft/ConsolePlugin.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.techsoft; - -import java.io.File; - -import com.techsoft.Interceptor.InterceptorManager; -import com.techsoft.container.DataServer; -import com.techsoft.plugins.PluginManager; - -public class ConsolePlugin implements Plugin { - private File pluginDirectory; - @Override - public void initializePlugin(PluginManager manager, File pluginDirectory) { - InterceptorManager.getInstance().addInterceptor(new SqlIdProcessImpl()); - } - @Override - public void destroyPlugin() { - DataServer.getInstance().removePluginModule(pluginDirectory.getName()); - } - -} diff --git a/jun_java_plugins/jun_webservice/webservice/src/plugins/console/src/com/techsoft/SqlIdProcessImpl.java b/jun_java_plugins/jun_webservice/webservice/src/plugins/console/src/com/techsoft/SqlIdProcessImpl.java deleted file mode 100644 index 97cdec42db..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/src/plugins/console/src/com/techsoft/SqlIdProcessImpl.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.techsoft; - -import java.util.Map; - -import com.techsoft.Interceptor.SQLIDInterceptor; - -public class SqlIdProcessImpl implements SQLIDInterceptor { - - @Override - public void interceptSQLID(SQLObject arg0, Session arg1, DMLType arg2, - boolean arg3, Map arg4) - throws SQLIDRejectedException { - - } - -} diff --git a/jun_java_plugins/jun_webservice/webservice/src/plugins/console/src/plugin.xml b/jun_java_plugins/jun_webservice/webservice/src/plugins/console/src/plugin.xml deleted file mode 100644 index 878aa754a6..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/src/plugins/console/src/plugin.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - com.techsoft.ConsolePlugin - \ No newline at end of file diff --git a/jun_java_plugins/jun_webservice/webservice/test/com/techsoft/AllTests.java b/jun_java_plugins/jun_webservice/webservice/test/com/techsoft/AllTests.java deleted file mode 100644 index 75eadeb51b..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/test/com/techsoft/AllTests.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.techsoft; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -import com.techsoft.executor.TestOracleExecutor; -import com.techsoft.pool.TestConnectionPool; - -@RunWith(Suite.class) -@SuiteClasses({ TestConnectionPool.class, TestOracleExecutor.class }) -public class AllTests { - -} diff --git a/jun_java_plugins/jun_webservice/webservice/test/com/techsoft/TestConsts.java b/jun_java_plugins/jun_webservice/webservice/test/com/techsoft/TestConsts.java deleted file mode 100644 index bd87a1cca5..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/test/com/techsoft/TestConsts.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.techsoft; - -import com.techsoft.pool.PoolFactory; - -public class TestConsts { - private static ConnectionPool pool = null; - public static ConnectionPool.DatabaseType databaseType = ConnectionPool.DatabaseType.ORACLE; - - public static String driverName = "oracle.jdbc.driver.OracleDriver"; - - public static int minPool = 1; - - public static int MaxPool = 2; - - public static int initPool = 1; - - public static String URL = "jdbc:oracle:thin:@192.168.0.48:1521/ORA10G.localdomain"; - - public static String userName = "samp"; - - public static String password = "lxkj"; - - public static ConnectionPool getPool() { - if (pool == null) { - try { - pool = PoolFactory.getInstance().getConnectionPool(); - pool.setDatabaseType(TestConsts.databaseType); - pool.setDriverName(TestConsts.driverName); - pool.setInitPool(TestConsts.initPool); - pool.setIsDebug(true); - pool.setJdbcURL(TestConsts.URL); - pool.setMaxPool(TestConsts.MaxPool); - pool.setMinPool(TestConsts.minPool); - pool.setUserName(TestConsts.userName); - pool.setPassword(TestConsts.password); - pool.start(); - } catch (PoolException e) { - e.printStackTrace(); - } - } - - return pool; - - } - -} diff --git a/jun_java_plugins/jun_webservice/webservice/test/com/techsoft/executor/TestOracleExecutor.java b/jun_java_plugins/jun_webservice/webservice/test/com/techsoft/executor/TestOracleExecutor.java deleted file mode 100644 index 443926071b..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/test/com/techsoft/executor/TestOracleExecutor.java +++ /dev/null @@ -1,307 +0,0 @@ -package com.techsoft.executor; - -import java.io.IOException; -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; - -import junit.framework.Assert; -import junit.framework.TestCase; -import oracle.jdbc.OracleConnection; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.techsoft.DBException; -import com.techsoft.DataExecutor; -import com.techsoft.SQLParam; -import com.techsoft.TestConsts; - -public class TestOracleExecutor extends TestCase { - private Connection conn = null; - private OracleConnection oraconn = null; - private static DataExecutor executor = OracleExecutor.getInstance(); - private static String dropTable = "drop table TESTORACLEEXECUTOR"; - private static String createTable = "create table TESTORACLEEXECUTOR \n" - + "( \n" + " id NUMBER(7) not null,\n" - + " strfield VARCHAR2(200),\n" + " clobfield CLOB,\n" - + " blobfield BLOB,\n" + " datefield DATE,\n" - + " timestampfield TIMESTAMP(6),\n" + " longfield LONG,\n" - + " numfields NUMBER(20),\n" - + " floatfields NUMBER(30,6),\n" + " primary key (id)\n" + ")"; - - private static String insertSql = "insert into TESTORACLEEXECUTOR t \n" - + " (t.id, \n" + " t.strfield, \n" + " t.clobfield, \n" - + " t.blobfield, \n" + " t.datefield, \n" - + " t.timestampfield, \n" + " t.longfield, \n" - + " t.numfields, \n" + " t.floatfields) \n" + "values (\n" - + " ?,\n" + " ?,\n" + " ?,\n" + " ?,\n" + " ?,\n" + " ?,\n" - + " ?,\n" + " ?,\n" + " ?\n" + ")"; - - private static String paramSql = "begin \n" + " select t.id, \n" - + " t.strfield, \n" + " t.clobfield, \n" - + " t.blobfield, \n" + " t.datefield, \n" - + " t.timestampfield, \n" + " t.longfield, \n" - + " t.numfields, \n" + " t.floatfields \n" - + " into :id, \n" + " :strfield, \n" - + " :clobfield, \n" + " :blobfield, \n" - + " :datefield, \n" + " :timestampfield, \n" - + " :longfield, \n" + " :numfields, \n" - + " :floatfields \n" + " from TESTORACLEEXECUTOR t; \n" - + "end; \n"; - - @Before - protected void setUp() throws Exception { - super.setUp(); - conn = TestConsts.getPool().getConnection(); - oraconn = (OracleConnection) TestConsts.getPool().getNativeConnection( - conn); - try { - PreparedStatement statement = oraconn.prepareCall(createTable); - statement.execute(); - oraconn.commit(); - } catch (Exception e) { - oraconn.rollback(); - } - } - - @After - protected void tearDown() throws Exception { - try { - PreparedStatement statement = oraconn.prepareCall(dropTable); - statement.execute(); - oraconn.commit(); - } catch (Exception e) { - oraconn.rollback(); - } - conn.close(); - conn = null; - super.tearDown(); - } - - @Test - public void testsetParam() throws SQLException, IOException, DBException { - CallableStatement statement = oraconn.prepareCall(insertSql); - SQLParam param1 = new SQLParam(); - param1.setDtype("2"); - param1.setDtypename("NUMBER"); - param1.setIndex("1"); - param1.setIotype("in"); - param1.setName("id"); - param1.setValue(12); - param1.buildPositions(); - executor.setParam(param1, statement, oraconn); - - SQLParam param2 = new SQLParam(); - param2.setDtype("12"); - param2.setDtypename("VARCHAR"); - param2.setIndex("2"); - param2.setIotype("in"); - param2.setName("strfield"); - param2.setValue("sdfasdfasdf"); - param2.buildPositions(); - executor.setParam(param2, statement, oraconn); - - SQLParam param3 = new SQLParam(); - param3.setDtype("2005"); - param3.setDtypename("CLOB"); - param3.setIndex("3"); - param3.setIotype("in"); - param3.setName("clobfield"); - param3.setValue("bbbbbbbbbb"); - param3.buildPositions(); - executor.setParam(param3, statement, oraconn); - - SQLParam param4 = new SQLParam(); - param4.setDtype("2004"); - param4.setDtypename("BLOB"); - param4.setIndex("4"); - param4.setIotype("in"); - param4.setName("blobfield"); - param4.setValue("222222222222"); - param4.buildPositions(); - executor.setParam(param4, statement, oraconn); - - SQLParam param5 = new SQLParam(); - param5.setDtype("91"); - param5.setDtypename("DATE"); - param5.setIndex("5"); - param5.setIotype("in"); - param5.setName("datefield"); - param5.setValue("2005-01-04 12:12:12"); - param5.buildPositions(); - executor.setParam(param5, statement, oraconn); - - SQLParam param6 = new SQLParam(); - param6.setDtype("93"); - param6.setDtypename("TIMESTAMP"); - param6.setIndex("6"); - param6.setIotype("in"); - param6.setName("timestampfield"); - param6.setValue("2005-01-04 12:12:12:111"); - param6.buildPositions(); - executor.setParam(param6, statement, oraconn); - - SQLParam param7 = new SQLParam(); - param7.setDtype("-1"); - param7.setDtypename("LONGVARCHAR"); - param7.setIndex("7"); - param7.setIotype("in"); - param7.setName("longfield"); - param7.setValue("asdfsadfasdfsa"); - param7.buildPositions(); - executor.setParam(param7, statement, oraconn); - - SQLParam param8 = new SQLParam(); - param8.setDtype("2"); - param8.setDtypename("NUMBER"); - param8.setIndex("8"); - param8.setIotype("in"); - param8.setName("numfields"); - param8.setValue("58677"); - param8.buildPositions(); - executor.setParam(param8, statement, oraconn); - - SQLParam param9 = new SQLParam(); - param9.setDtype("2"); - param9.setDtypename("NUMBER"); - param9.setIndex("9"); - param9.setIotype("in"); - param9.setName("floatfields"); - param9.setValue(333333333333333333333344.333377); - param9.buildPositions(); - executor.setParam(param9, statement, oraconn); - - statement.execute(); - oraconn.commit(); - } - - @Test - public void testgetParam() throws SQLException, IOException, DBException { - this.testsetParam(); - CallableStatement statement = oraconn.prepareCall(paramSql); - statement.registerOutParameter(1, 2); - statement.registerOutParameter(2, 12); - statement.registerOutParameter(3, 2005); - statement.registerOutParameter(4, 2004); - statement.registerOutParameter(5, 91); - statement.registerOutParameter(6, 93); - statement.registerOutParameter(7, -1); - statement.registerOutParameter(8, 2); - statement.registerOutParameter(9, 2); - statement.execute(); - - SQLParam param1 = new SQLParam(); - param1.setDtype("2"); - param1.setDtypename("NUMBER"); - param1.setIndex("1"); - param1.setIotype("out"); - param1.setName("id"); - param1.buildPositions(); - executor.getParam(param1, statement, oraconn); - - SQLParam param2 = new SQLParam(); - param2.setDtype("12"); - param2.setDtypename("VARCHAR"); - param2.setIndex("2"); - param2.setIotype("out"); - param2.setName("strfield"); - param2.buildPositions(); - executor.getParam(param2, statement, oraconn); - - SQLParam param3 = new SQLParam(); - param3.setDtype("2005"); - param3.setDtypename("CLOB"); - param3.setIndex("3"); - param3.setIotype("out"); - param3.setName("clobfield"); - param3.buildPositions(); - executor.getParam(param3, statement, oraconn); - - SQLParam param4 = new SQLParam(); - param4.setDtype("2004"); - param4.setDtypename("BLOB"); - param4.setIndex("4"); - param4.setIotype("out"); - param4.setName("blobfield"); - param4.buildPositions(); - executor.getParam(param4, statement, oraconn); - - SQLParam param5 = new SQLParam(); - param5.setDtype("91"); - param5.setDtypename("DATE"); - param5.setIndex("5"); - param5.setIotype("out"); - param5.setName("datefield"); - param5.buildPositions(); - executor.getParam(param5, statement, oraconn); - - SQLParam param6 = new SQLParam(); - param6.setDtype("93"); - param6.setDtypename("TIMESTAMP"); - param6.setIndex("6"); - param6.setIotype("out"); - param6.setName("timestampfield"); - param6.buildPositions(); - executor.getParam(param6, statement, oraconn); - - SQLParam param7 = new SQLParam(); - param7.setDtype("-1"); - param7.setDtypename("LONGVARCHAR"); - param7.setIndex("7"); - param7.setIotype("out"); - param7.setName("longfield"); - param7.buildPositions(); - executor.getParam(param7, statement, oraconn); - - SQLParam param8 = new SQLParam(); - param8.setDtype("2"); - param8.setDtypename("NUMBER"); - param8.setIndex("8"); - param8.setIotype("out"); - param8.setName("numfields"); - param8.buildPositions(); - executor.getParam(param8, statement, oraconn); - - SQLParam param9 = new SQLParam(); - param9.setDtype("2"); - param9.setDtypename("NUMBER"); - param9.setIndex("9"); - param9.setIotype("out"); - param9.setName("floatfields"); - param9.buildPositions(); - executor.getParam(param9, statement, oraconn); - - System.out.println(param1.getValue()); - System.out.println(param2.getValue()); - System.out.println(param3.getValue()); - System.out.println(param4.getValue()); - System.out.println(param5.getValue()); - System.out.println(param6.getValue()); - System.out.println(param7.getValue()); - System.out.println(param8.getValue()); - System.out.println(param9.getValue()); - } - - @Test - public void testqueryMetaData() { - Assert.assertEquals(true, true); - } - - @Test - public void testqueryData() { - Assert.assertEquals(true, true); - } - - @Test - public void testsaveData() { - Assert.assertEquals(true, true); - } - - @Test - public void testserializeResultSet() { - Assert.assertEquals(true, true); - } -} diff --git a/jun_java_plugins/jun_webservice/webservice/test/com/techsoft/pool/TestConnectionPool.java b/jun_java_plugins/jun_webservice/webservice/test/com/techsoft/pool/TestConnectionPool.java deleted file mode 100644 index df96eb4013..0000000000 --- a/jun_java_plugins/jun_webservice/webservice/test/com/techsoft/pool/TestConnectionPool.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.techsoft.pool; - -import java.sql.Connection; - -import junit.framework.Assert; -import junit.framework.TestCase; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.techsoft.ConnectionPool; -import com.techsoft.TestConsts; - -public class TestConnectionPool extends TestCase { - private Connection connone = null; - private Connection conntwo = null; - - @Before - protected void setUp() throws Exception { - super.setUp(); - } - - @After - protected void tearDown() throws Exception { - if (connone != null) { - connone.close(); - connone = null; - } - if (conntwo != null) { - conntwo.close(); - conntwo = null; - } - super.tearDown(); - } - - @Test - public void testGetConnection() { - try { - connone = TestConsts.getPool().getConnection(); - assertEquals(2, TestConsts.getPool().getMaxPool()); - assertEquals(1, TestConsts.getPool().getBusyPool()); - - conntwo = TestConsts.getPool().getConnection(); - assertEquals(2, TestConsts.getPool().getMaxPool()); - assertEquals(2, TestConsts.getPool().getBusyPool()); - - TestConsts.getPool().getConnection(); - fail("最大池已满时,还能取得连接, 出错!"); - - } catch (Exception e) { - Assert.assertTrue(e.getMessage().equalsIgnoreCase( - ConnectionPool.MAXPOOLLIMIT)); - } - } - -} diff --git a/jun_java_plugins/jun_webservlet/README.md b/jun_java_plugins/jun_webservlet/README.md deleted file mode 100644 index 02ea091820..0000000000 --- a/jun_java_plugins/jun_webservlet/README.md +++ /dev/null @@ -1,457 +0,0 @@ -# jun_webservlet - -> 此 demo 主要演示了 Servlet 3.0 注解使用,异步回调、GET及POST请求返回、文件上传等。 - -#Servlet3.0 记得servlet3的特性有以下几点: - -1、异步处理支持:有了该特性,Servlet 线程不再需要一直阻塞,直到业务处理完毕才能再输出响应,最后才结束该 Servlet 线程。在接收到请求之后,Servlet 线程可以将耗时的操作委派给另一个线程来完成,自己在不生成响应的情况下返回至容器。针对业务处理较耗时的情况,这将大大减少服务器资源的占用,并且提高并发处理速度。 -2、新增的注解支持:该版本新增了若干注解,用于简化 Servlet、过滤器(Filter)和监听器(Listener)的声明,这使得 web.xml 部署描述文件从该版本开始不再是必选的了。 -3、可插性支持:熟悉 Struts2 的开发者一定会对其通过插件的方式与包括 Spring 在内的各种常用框架的整合特性记忆犹新。将相应的插件封装成 JAR 包并放在类路径下,Struts2 运行时便能自动加载这些插件。现在 Servlet 3.0 提供了类似的特性,开发者可以通过插件的方式很方便的扩充已有 Web 应用的功能,而不需要修改原有的应用。 - -以前的servlet的流程: - -首先,Servlet接收到请求之后,可能需要对请求携带的数据进行一些处理;接着,调用业务接口的某些方法,已完成业务处理;最后根据处理的结果提交响应,Servlet线程结束。其中第二步的业务处理通常是最耗时的,这主要体现数据库操作,以及其它的跨网络调用等、在此过程中、Servlet线程一直处于阻塞状态,直到业务方法执行完毕。在处理业务过程中、Servlet资源一直被占用而得不到释放,对于并发较大的应用,这有可能造成性能瓶颈,对此,在以前通常采用私有解决方案,来提前结束Servlet线程,并及时释放资源。 - -Servlet3.0流程: -首先,Servlet接收到请求之后,可能首先需要对请求携带的数据进行一些预处理;接着,Servlet线程将请求转交给一个异步线程来执行业务处理,线程本身返回至容器、此时Servlet还没有生成响应数据,异步线程处理完业务以后,可以直接生成响应数据(异步线程拥有ServletRequest和ServletResponse对象的引用),或者将请求继续转发给其它的Servlet,如此一来,Servlet线程不再是一直处于阻塞状态以等待业务逻辑的处理,而是启动异步线程之后可以立即返回。 - -注意: - -Servlet 3.0 还为异步处理提供了一个监听器,使用 AsyncListener 接口表示。它可以监控如下四种事件: - -异步线程开始时,调用 AsyncListener 的 onStartAsync(AsyncEvent event) 方法; -异步线程出错时,调用 AsyncListener 的 onError(AsyncEvent event) 方法; -异步线程执行超时,则调用 AsyncListener 的 onTimeout(AsyncEvent event) 方法; -异步执行完毕时,调用 AsyncListener 的 onComplete(AsyncEvent event) 方法; - -要注册一个 AsyncListener,只需将准备好的 AsyncListener 对象传递给 AsyncContext 对象的 addListener() 方法即可。 - -在这里插入图片描述 -代码实现: -##Http2Servlet3.java -```java -import javax.servlet.annotation.WebServlet; -import java.io.IOException; -import java.io.PrintWriter; -import java.text.DateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.List; -import java.util.Queue; -import java.util.Random; -import java.util.UUID; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.Executor; -import java.util.concurrent.Executors; -import javax.servlet.AsyncContext; -import javax.servlet.AsyncEvent; -import javax.servlet.AsyncListener; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -@WebServlet(value = {"/http23"}, asyncSupported = true) -public class Http2Servlet3 extends HttpServlet { - - private Queue messages = new ConcurrentLinkedQueue(); - private final Executor executor = Executors.newFixedThreadPool( 10 ); - private List ctxs = new ArrayList(); - - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { - res.setContentType( "text/plain" ); - res.setCharacterEncoding( "utf-8" ); - res.setHeader( "Access-Control-Allow-Origin", "*" ); - PrintWriter writer = res.getWriter(); - writer.print( "2;Hi;" ); - writer.flush(); - - final AsyncContext ctx = req.startAsync(); - ctx.addListener( new AsyncListener() { - @Override - public void onStartAsync(AsyncEvent event) throws IOException { - } - @Override - public void onTimeout(AsyncEvent event) throws IOException { - ctxs.remove( ctx ); - } - @Override - public void onError(AsyncEvent event) throws IOException { - ctxs.remove( ctx ); - } - @Override - public void onComplete(AsyncEvent event) throws IOException { - ctxs.remove( ctx ); - } - } ); - ctxs.add( ctx ); - } - - @Override - protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { - res.setContentType( "text/plain" ); - res.setCharacterEncoding( "utf-8" ); - messages.add( createRandomMessage() ); - } - - @Override - public void init() throws ServletException { - super.init(); - // produce random messages - //生成随机消息 - new Thread( new Runnable() { - @Override - public void run() { - while (true) { - messages.add( createRandomMessage() ); - try { - Thread.sleep( new Random().nextInt( 5 ) * 1000 ); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - } ).start(); - - // print messages to all users - //向所有用户打印message - - new Thread( new Runnable() { - @Override - public void run() { - while (true) { - if (!messages.isEmpty()) { - final String message = messages.poll(); - executor.execute( new Runnable() { - @Override - public void run() { - for (AsyncContext ctx : ctxs) { - try { - PrintWriter writer = ctx.getResponse().getWriter(); - writer.print( message.length() ); - writer.print( ';' ); - writer.print( message ); - writer.print( ';' ); - writer.flush(); - } catch (IOException e) { - e.printStackTrace(); - } - } - }; - } ); - } - } - } - } ).start(); - } - - protected String createRandomMessage() { - return DateFormat.getTimeInstance().format( Calendar.getInstance().getTime() ) + ' ' + UUID.randomUUID().toString(); - } -} -``` - -##AsyncDemoServlet.java -```java -import javax.servlet.AsyncContext; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.Date; - -@WebServlet(urlPatterns = "/servlet3", asyncSupported = true) -public class AsyncDemoServlet extends HttpServlet { - - @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { - resp.setContentType( "text/html;charset=UTF-8" ); - PrintWriter out = resp.getWriter(); - out.println( "进入Servlet的时间:" + new Date() + "." ); - out.flush(); - //在子线程中执行业务调用,并由其负责输出响应,主线程退出 - AsyncContext ctx = req.startAsync(); - new Thread( new Executor( ctx ) ).start(); - out.println( "结束Servlet的时间:" + new Date() + "." ); - out.flush(); - } -} - -/*public class Executor implements Runnable { - private AsyncContext ctx = null; - public Executor(AsyncContext ctx) { - this.ctx = ctx; - }*/ -class Executor implements Runnable { - private AsyncContext ctx = null; - public Executor(AsyncContext ctx) { - this.ctx = ctx; - } - - @Override - public void run() { - try { - //等待十秒钟,以模拟业务方法的执行 - Thread.sleep( 10000 ); - PrintWriter out = ctx.getResponse().getWriter(); - out.println( "业务处理完毕的时间:" + new Date() + "." ); - out.flush(); - ctx.complete(); - } catch (Exception e) { - e.printStackTrace(); - } - } -} -``` -##pom.xml -```xml - - - 4.0.0 - - Servlet4Push - Servlet4Push - 1.0-SNAPSHOT - - war - - - ${project.build.directory}/endorsed - UTF-8 - - - - - - - javax.servlet - javax.servlet-api - 4.0.1 - provided - - - - - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.1 - - 1.8 - 1.8 - - ${endorsed.dir} - - - - - org.apache.maven.plugins - maven-war-plugin - 2.6 - - Servlet4Push - false - - - - - - -``` -记得servlet4新功能: - -**1、服务器推送:**是最直观的 HTTP/2 强化功能,通过 PushBuilder 接口在 servlet 中公开。服务器推送功能还在 JavaServer Faces API 中实现,并在 RenderResponsePhase 生命周期内调用,以便 JSF 页面可以利用其增强性能。 -2、全新 servlet 映射发现接口: HttpServletMapping 使框架能够获取有关激活给定 servlet 请求的 URL 信息。这可能对框架尤为有用,这些框架需要这一信息来运行内部工作。 - -Servlet4.0优点: - -服务器推送使服务器能预测客户端请求的资源需求。然后,在完成请求处理之前,它可以将这些资源发送到客户端。 - -要了解服务器推送的好处,可以考虑一个包含图像和其他依赖项(比如 CSS 和 JavaScript 文件)的网页。客户端发出一个针对该网页的请求。服务器然后分析所请求的页面,确定呈现它所需的资源,并主动将这些资源发送到客户端的缓存。 - -在执行所有这些操作的同时,服务器仍在处理原始网页请求。客户端收到响应时,它需要的资源已经位于缓存中。Servlet 4.0 通过 PushBuilder 接口公开服务器推送、也可以推送静态资源等。 - -代码实现: - -##Http2Servlet4.java -```java -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.*; -import java.io.IOException; -import java.io.PrintWriter; - -//@WebServlet({"/path/*", "*.ext"}) -@WebServlet(value = {"/http24"}) -public class Http2Servlet4 extends HttpServlet { - - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - - PushBuilder pushBuilder = req.newPushBuilder(); - if (pushBuilder != null) { - pushBuilder - .path("images/kodedu-logo.png") - .addHeader("content-type", "image/png") - .push(); - } - - /*PushBuilder pushBuilder = request.newPushBuilder(); - - if (pushBuilder != null) { - pushBuilder.path("images/hero-banner.jpg").push(); - pushBuilder.path("css/menu.css").push(); - pushBuilder.path("js/marquee.js").push(); - }*/ - - - HttpServletMapping mappings = req.getHttpServletMapping(); - String mapping = mappings.getMappingMatch().name(); - String value = mappings.getMatchValue(); - String pattern = mappings.getPattern(); - String servletName = mappings.getServletName(); - - - try (PrintWriter respWriter = resp.getWriter();) { - respWriter.write("" + - "" + - ""); - } - - } -} -``` - -## pom.xml - -```xml - - - org.apache.tomcat.maven - tomcat7-maven-plugin - 2.1 - - 8080 - /jun_webservlet - UTF-8 - jun_webservlet - tomcat7 - - -``` - -## Servlet3Demo.java - -```java -/** - * 注解WebServlet用来描述一个Servlet - * 属性name描述Servlet的名字,可选 - * 属性urlPatterns定义访问的URL,或者使用属性value定义访问的URL.(定义访问的URL是必选属性) - */ - @WebServlet(name="Servlet3Demo",urlPatterns="/Servlet3Demo") - @WebInitParam(name="a", value="valuea") - public class Servlet3Demo extends HttpServlet { - /* - * 完成了一个使用注解描述的Servlet程序开发。 -   使用@WebServlet将一个继承于javax.servlet.http.HttpServlet的类定义为Servlet组件。 -   @WebServlet有很多的属性: -   1、asyncSupported: 声明Servlet是否支持异步操作模式。 -   2、description:   Servlet的描述。 -   3、displayName: Servlet的显示名称。 -   4、initParams: Servlet的init参数。 -   5、name:     Servlet的名称。 -   6、urlPatterns:   Servlet的访问URL。 -   7、value:    Servlet的访问URL。 -   Servlet的访问URL是Servlet的必选属性,可以选择使用urlPatterns或者value定义。 -   像上面的Servlet3Demo可以描述成@WebServlet(name="Servlet3Demo",value="/Servlet3Demo")。 -   也定义多个URL访问: -   如@WebServlet(name="Servlet3Demo",urlPatterns={"/Servlet3Demo","/Servlet3Demo2"}) -   或者@WebServlet(name="AnnotationServlet",value={"/Servlet3Demo","/Servlet3Demo2"}) - * - */ - public void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - response.getWriter().write("Hello Servlet3.0"); - } - - public void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - this.doGet(request, response); - } - } -``` - -## UploadServlet.java - -```java - //使用@WebServlet配置UploadServlet的访问路径 -//使用注解@MultipartConfig将一个Servlet标识为支持文件上传 -//标识Servlet支持文件上传 -@WebServlet(name="UploadServlet",urlPatterns="/UploadServlet") -@MultipartConfig -public class UploadServlet extends HttpServlet { - - public void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - request.setCharacterEncoding("utf-8"); - response.setCharacterEncoding("utf-8"); - response.setContentType("text/html;charset=utf-8"); - //存储路径 - String savePath = request.getServletContext().getRealPath("/WEB-INF/uploadFile"); - //获取上传的文件集合 - Collection parts = request.getParts(); - //上传单个文件 - if (parts.size()==1) { - //Servlet3.0将multipart/form-data的POST请求封装成Part,通过Part对上传的文件进行操作。 - //Part part = parts[0];//从上传的文件集合中获取Part对象 - Part part = request.getPart("file");//通过表单file控件()的名字直接获取Part对象 - //Servlet3没有提供直接获取文件名的方法,需要从请求头中解析出来 - //获取请求头,请求头的格式:form-data; name="file"; filename="snmp4j--api.zip" - String header = part.getHeader("content-disposition"); - //获取文件名 - String fileName = getFileName(header); - //把文件写到指定路径 - part.write(savePath+File.separator+fileName); - }else { - //一次性上传多个文件 - for (Part part : parts) {//循环处理上传的文件 - //获取请求头,请求头的格式:form-data; name="file"; filename="snmp4j--api.zip" - String header = part.getHeader("content-disposition"); - //获取文件名 - String fileName = getFileName(header); - //把文件写到指定路径 - part.write(savePath+File.separator+fileName); - } - } - PrintWriter out = response.getWriter(); - out.println("上传成功"); - out.flush(); - out.close(); - } -``` - -参考:https://www.ibm.com/developerworks/cn/java/j-lo-servlet30/index.html -参考:https://www.ibm.com/developerworks/cn/java/j-javaee8-servlet4/index.html \ No newline at end of file diff --git "a/jun_java_plugins/jun_webservlet/doc/jun_ajax/Ajax\350\257\246\350\247\243\345\217\202\350\200\203\346\226\207\346\241\243.md" "b/jun_java_plugins/jun_webservlet/doc/jun_ajax/Ajax\350\257\246\350\247\243\345\217\202\350\200\203\346\226\207\346\241\243.md" deleted file mode 100644 index ca621fd1c2..0000000000 --- "a/jun_java_plugins/jun_webservlet/doc/jun_ajax/Ajax\350\257\246\350\247\243\345\217\202\350\200\203\346\226\207\346\241\243.md" +++ /dev/null @@ -1,178 +0,0 @@ -# Ajax详解参考文档 - -Asynchronous Javascript And XML(可扩展标记语言),AJAX 不是一门的新的语言,而是对现有持术的综合利用。客户端渲染; - -本质:是在HTTP协议的基础上以异步的方式通过XMLHttpRequest对象与服务器进行通信。 - -作用:可以在页面不刷新(局部刷新)的情况下,请求服务器,局部更新页面的数据; - -异步(Asynchronous):指某段程序执行时不会阻塞其它程序执行,其表现形式为程序的执行顺序不依赖程序本身的书写顺序,相反则为同步。 - -同步:同一时刻只能做一件事,上一步完成才能开始下一步 -异步:同时做多件事,效率更高。 - -发送: -XMLHttpRequest可以以异步方式的处理程序。 - -1,获取用户数据; - -2,让异步对象发送请求; -2.1 创建异步对象;var xhr = new XMLHttpRequest(); - -``` -2.2 设置 请求行 open(请求方式,请求url): - get请求如果有参数就需要在url后面拼接参数; - post不用写参数,就在请求体中传递; - -2.3 设置 请求头 setRequestHeader('key':'value'): - get方式不需要设置请求头; - post需要设置 ("Content-Type","application/x-www-form-urlencoded"); - 如果没有设置,参数无法正确的传递到服务器(本质上说,如果没有参数,也不一定需要设置,不会影响请求的发送); - - 2.4 设置 请求体:发送请求 send(参数:key=value&key=value): - 如果有参数,post应该在这个位置来传递参数; - xhr.send("username="+name); - 对于 get请求不需要在这个位置来传递参数; - xhr.send(null); -1234567891011121314 -``` - -接收: -响应报文: -报文行:响应状态码 响应状态信息 200 ok; -报文头:服务器返回给客户端的一些额外信息 ; -报文体:服务器返回给客户端的数据; responseText:普通字符串 responseXML:符合xml格式的字符串; - -``` -一个真正成功的响应应该两个方面:1.服务器成功响应 2.数据已经回到客户端并且可以使用了; - 监听异步对象的响应状态::xhr.onreadystatechange = function(){} - xhr.status:可以获取当前服务器的响应状态 xhr.status== 200(成功); - 解析完毕(判断异步对象的响应状态):xhr.readystate == 4; - -(解析步骤: - 0:创建了异步对象,但是还没有真正的去发送请求 - 1.调用了send方法,正在发送请求 - 2.send方法执行完毕了,已经收到服务器的响应内容--原始内容,还不可以使用 - 3.正在解析数据 - 4.响应内容解析完毕,可以使用了;readystate == 4;) -1234567891011 -``` - -GET和POST请求方式的差异(面试题) - -1、GET没有请求主体,使用xhr.send(null); -2、GET可以通过在请求URL上添加请求参数; -3、POST可以通过xhr.send(‘name=itcast&age=10’); -4、POST需要设置: -Content-type:application/x-www-form-urlencoded -5、GET大小限制约4K,POST则没有限制; - -json(对象): -语法规则 -1、数据在名称/值对中 -2、数据由逗号分隔(最后一个健/值对不能带逗号) -3、花括号保存对象方括号保存数组 -4、使用双引号 - -``` -[]:数组;{}:对象; - -在js中通过JSON.pars()方法将json格式的字符串转换为js数组或者对象( 如果文件以[]来描述数据,那么就转换为数组,如果文件以{}来描述数据,那么就转换为对象) - JSON.stringify():把对象转为字符串; -1234 -``` - -XML:是一种标记语言,很类似HTML,其宗旨是用来传输数据,具有自我描述性(固定的格式的数据)。 -语法规则: -1、必须有一个根元素 ; -2、标签名称不可有空格、不可以数字或.开头、大小写敏感; -3、不可交叉嵌套; -4、属性双引号(浏览器自动修正成双引号了); -5、特殊符号要使用实体; -6、注释和HTML一样; - -sleep(4):线程暂停; - -jQUery中的Ajax: -$.ajax({}) 可配置方式发起Ajax请求; - -``` -$.get() 以GET方式发起Ajax请求: - $.get(url,data,success,datatype):本质上只能发送get请求; - -$.post() 以POST方式发起Ajax请求: - $.post(url,data,success,datatype):本质上只能发送post请求; - -$('form').serialize()序列化表单(即格式化key=val&key=val) - -url 接口地址 - -type 请求方式 - -timeout 请求超时;单位为毫秒,如果服务器的响应时间超过指定时间,那么请求失败; - -dataType 服务器返回格式 xml,josn,text,html,script,jsonp; - -data 发送请求数据 - -beforeSend:function () {} :请求发起前调用,如验证;在这个回调函数中,如果return false,那么本次请求会中止; - -success(): 成功响应后调用的函数; - -error ():错误响应时调用的函数; - - !! async: false, 重设为同步执行代码! - -complete 响应完成时调用(无论成功和失败都会执行的回调): -123456789101112131415161718192021222324252627 -``` - -.serialize():可以通过将表单序列化的方式来收集用户数据: -1.这个方法是jq的方式,所以需要使用jq对象来调用; -2.这个方法可以将表单中所有name属性的表单元素的值收集,生成 key=value&key=value…这种格式; -3.在ajax中,支持两种格式的参数(1.对象 2.参数格式字符串); - -模板引擎:http://aui.github.io/art-template/zh-cn/ -// 调用模板引擎动态生成页面结构 -// 如果参数是对象是直接传入对象 -// 如果参数是数组,就包装为对象 -var html = template(“musicTemp”,{“items”:result}); - -同源策略是浏览器的一种安全策略,所谓同源是指,域名,协议,端口完全相同。 - -跨域:不同源;ajax默认不支持跨域; - -JSONP: -dataType:‘jsonp’ 设置dataType值为jsonp即开启跨域访问; -开启jsonp会自动生成callback函数; -jsonpCallback 可以指定相应的回调函数,默认自动生成; - -``` -原理: - 1. 主要是利用了script标签的天然的跨域特性来发送请求; - 2. 它的实现方式:在发送请求的时候传递一个函数名称给后台,后台返回数据的时候会返回这个函数的调用形式,并且在()中拼接参数; - 3. ajax和jsonp的本质不一样。ajax的核心是通过XMLHttpRequest来发送请求,而jsonp是通过script标签来实现请求的发送; -1234 -``` - -FormData: - -``` - // 1.获取表单 - var myform = document.querySelector("#form1"); - // 2.将表单做为参数传递,在创建formData对象的时候 - var formdata = new FormData(myform); - // 特点之一:可以自由的追加参数 - formdata.append("address","传智播客"); - // 3.生成的formData对象就可以直接做为异步对象的参数传递 - xhr.send(formdata); -12345678 -``` - -$(’#test’)[0].reset(); 表单重置; - -动态添加的点击按钮,注册点击事件时,需要使用事件委托; - -mysqli_insert_id; - -解决获取地址栏汉字乱码:decodeURI(); \ No newline at end of file diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/README.md b/jun_java_plugins/jun_webservlet/doc/jun_ajax/README.md deleted file mode 100644 index 2f3cd603f6..0000000000 --- a/jun_java_plugins/jun_webservlet/doc/jun_ajax/README.md +++ /dev/null @@ -1,187 +0,0 @@ - -# jun_ajax,基于XMLHttpRequest+Servlet的Ajax实现 - -> 本 demo 主要是说明原生Ajax的实现,即基于XMLHttpRequest+Servlet的Ajax实现 - -## pom.xml -> 无特殊依赖 -```xml - - 4.0.0 - - io.github.wujun728 - jun_plugin - 1.0 - - jun_ajax - - - UTF-8 - - - - - - mysql - mysql-connector-java - 5.1.38 - - - - junit - junit - 4.11 - test - - - - -``` - -## web.xml -> 无特殊依赖 -```xml - - - - - This is the description of my J2EE component - This is the display name of my J2EE component - TestServlet - com.jun.plugin.ajax.servlet.TestServlet - - - This is the description of my J2EE component - This is the display name of my J2EE component - LoadServlet - com.jun.plugin.ajax.servlet.LoadServlet - - - This is the description of my J2EE component - This is the display name of my J2EE component - RegisterServlet - com.jun.plugin.ajax.servlet.RegisterServlet - - - This is the description of my J2EE component - This is the display name of my J2EE component - XmlFileServlet - com.jun.plugin.ajax.servlet.XmlFileServlet - - - TestServlet - /testServlet - - - LoadServlet - /loadServlet - - - RegisterServlet - /registerServlet - - - XmlFileServlet - /xmlFileServlet - - - index.jsp - - -``` - -## javascript.js -> 注册Dom树事件,创建XMLHttpRequest对象,建立服务器链接,请求发送数据,接受服务器数据 -```javascript -//当页面加载完毕之后,执行以下代码 -window.onload = function(){ - document.getElementById("ok").onclick = function(){ - /* - * 1 创建XMLHttpRequest对象 - */ - var xhr = ajaxFunction(); - - /* - * 2 服务器向浏览器响应请求 - * - * readyState 属性表示Ajax请求的当前状态。它的值用数字代表。 - 0 代表未初始化。 还没有调用 open 方法 - 1 代表正在加载。 open 方法已被调用,但 send 方法还没有被调用 - 2 代表已加载完毕。send 已被调用。请求已经开始 - 3 代表交互中。服务器正在发送响应 - 4 代表完成。响应发送完毕 - - 常用状态码及其含义: - 404 没找到页面(not found) - 403 禁止访问(forbidden) - 500 内部服务器出错(internal service error) - 200 一切正常(ok) - 304 没有被修改(not modified)(服务器返回304状态,表示源文件没有被修改 ) - */ - xhr.onreadystatechange = function(){ - alert(xhr.readyState); - //alert(xhr.status); - if(xhr.readyState==4){ - if(xhr.status==200||xhr.status==304){ - var data = xhr.responseText; - alert(data); - } - } - } - - /* - * 3 浏览器与服务器建立连接 - * - * xhr.open(method, url, asynch); - * * 与服务器建立连接使用 - * * method:请求类型,类似 “GET”或”POST”的字符串。 - * * url:路径字符串,指向你所请求的服务器上的那个文件。请求路径 - * * asynch:表示请求是否要异步传输,默认值为true(异步)。 - */ - xhr.open("GET","../testServlet?timeStamp="+new Date().getTime()+"&c=18",true); - - /* - * 4 浏览器向服务器发送请求 - * - * send()方法: - * * 如果浏览器请求的类型为GET类型时,通过send()方法发送请求数据,服务器接收不到 - */ - xhr.send("a=6&b=9"); //xhr.send(null); - } -} - -function ajaxFunction(){ - var xmlHttp; - try{ // Firefox, Opera 8.0+, Safari - xmlHttp=new XMLHttpRequest(); - } - catch (e){ - try{// Internet Explorer - xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); - } - catch (e){ - try{ - xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); - } - catch (e){} - } - } - - return xmlHttp; - } -``` - -## 运行&地址 - -将项目运行起来之后,会在**控制台**里查看所有可以访问的端口信息 -1. 打开浏览器,访问:http://localhost:8090/jun_ajax ,输入用户名(admin)密码(123456)即可看到所有的信息 -2. 打开webapp目录下面的文件,根据文件请求的路径访问 -3. 其余可访问的路径,参见文档 - -## 参考 -- Ajax文档:https://www.w3school.com.cn/jquery/ajax_ajax.asp diff --git a/jun_java_plugins/jun_webservlet/doc/jun_ajax/pom.xml b/jun_java_plugins/jun_webservlet/doc/jun_ajax/pom.xml deleted file mode 100644 index 24376d6564..0000000000 --- a/jun_java_plugins/jun_webservlet/doc/jun_ajax/pom.xml +++ /dev/null @@ -1,28 +0,0 @@ - - 4.0.0 - io.github.wujun728 - jun_ajax - 1.0 - - - UTF-8 - - - - - - mysql - mysql-connector-java - 5.1.38 - - - - junit - junit - 4.11 - test - - - - diff --git a/jun_java_plugins/jun_webservlet/doc/webservlet01/pom.xml b/jun_java_plugins/jun_webservlet/doc/webservlet01/pom.xml deleted file mode 100644 index 6c95db0f1f..0000000000 --- a/jun_java_plugins/jun_webservlet/doc/webservlet01/pom.xml +++ /dev/null @@ -1,86 +0,0 @@ - - - - 4.0.0 - - com.lf.web - web-servlet01 - 1.0 - war - - web-servlet01 Maven Webapp - - http://www.example.com - - - UTF-8 - 1.8 - 1.8 - - - - - junit - junit - 4.12 - test - - - - javax.servlet - javax.servlet-api - 3.1.0 - provided - - - mysql - mysql-connector-java - 5.1.48 - - - - commons-dbutils - commons-dbutils - 1.7 - - - - - - web-servlet01 - - - - maven-clean-plugin - 3.1.0 - - - - maven-resources-plugin - 3.0.2 - - - maven-compiler-plugin - 3.8.0 - - - maven-surefire-plugin - 2.22.1 - - - maven-war-plugin - 3.2.2 - - - maven-install-plugin - 2.5.2 - - - maven-deploy-plugin - 2.8.2 - - - - - diff --git a/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/java/com/lf/Dao/Dao.java b/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/java/com/lf/Dao/Dao.java deleted file mode 100644 index 00440e171c..0000000000 --- a/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/java/com/lf/Dao/Dao.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.lf.Dao; - -import com.lf.bean.userBean; - -import java.util.List; - -public interface Dao { - //注册.从前端传过来的数据,要写入到数据库中去 - int addMember(userBean userBean) throws Exception; - List selectAllDao() throws Exception; - -} diff --git a/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/java/com/lf/Dao/Impl/DaoImpl.java b/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/java/com/lf/Dao/Impl/DaoImpl.java deleted file mode 100644 index 52a53baa6d..0000000000 --- a/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/java/com/lf/Dao/Impl/DaoImpl.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.lf.Dao.Impl; -import com.lf.Dao.Dao; -import com.lf.bean.userBean; -import com.lf.util.dbConnector; -import org.apache.commons.dbutils.QueryRunner; -import org.apache.commons.dbutils.handlers.BeanListHandler; - -import java.util.List; - -/** - * @ClassName: DaoImpl - * @Description: - * @Author: 李峰 - * @Date: 2021 年 01月 18 18:10 - * @Version 1.0 - */ -public class DaoImpl implements Dao { - - QueryRunner queryRunner = dbConnector.getInstance(); - - @Override - public int addMember(userBean userBean) throws Exception { - int result=0; - queryRunner.update("insert into user values(null,?,?,?,?)", - userBean.getNaem(),userBean.getSex(),userBean.getAddress(),userBean.getDate()); - return result; - } - - @Override - public List selectAllDao() throws Exception { - List list=null; - queryRunner.query("select * from user",new BeanListHandler<>(userBean.class)); - return list; - - } -} diff --git a/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/java/com/lf/bean/userBean.java b/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/java/com/lf/bean/userBean.java deleted file mode 100644 index 129ff4cf98..0000000000 --- a/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/java/com/lf/bean/userBean.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.lf.bean; - -import java.util.Date; - -/** - * @ClassName: userBean - * @Description: - * @Author: 李峰 - * @Date: 2021 年 01月 20 12:58 - * @Version 1.0 - */ -public class userBean { - private int id; - private String naem; - private String sex; - private String address; - private Date date; - - public userBean() { - } - - public userBean(String naem, String sex, String address, Date date) { - this.naem = naem; - this.sex = sex; - this.address = address; - this.date = date; - } - - public userBean(int id, String naem, String sex, String address, Date date) { - this.id = id; - this.naem = naem; - this.sex = sex; - this.address = address; - this.date = date; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getNaem() { - return naem; - } - - public void setNaem(String naem) { - this.naem = naem; - } - - public String getSex() { - return sex; - } - - public void setSex(String sex) { - this.sex = sex; - } - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; - } - - public Date getDate() { - return date; - } - - public void setDate(Date date) { - this.date = date; - } - -} diff --git a/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/java/com/lf/service/serviceImpl/userServiceImpl.java b/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/java/com/lf/service/serviceImpl/userServiceImpl.java deleted file mode 100644 index 0162bc219d..0000000000 --- a/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/java/com/lf/service/serviceImpl/userServiceImpl.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.lf.service.serviceImpl; - -import com.lf.Dao.Dao; -import com.lf.Dao.Impl.DaoImpl; -import com.lf.bean.userBean; -import com.lf.service.userService1; - -import java.util.ArrayList; -import java.util.List; - -/** - * @ClassName: userServiceImpl - * @Description: - * @Author: 李峰 - * @Date: 2021 年 01月 18 18:12 - * @Version 1.0 - */ -public class userServiceImpl implements userService1 { - - Dao dao=new DaoImpl(); - @Override - - public int addUserService(userBean user) throws Exception { - return dao.addMember(user); - } - @Override - public List selectAll() throws Exception { - return dao.selectAllDao(); - } -} diff --git a/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/java/com/lf/service/userService1.java b/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/java/com/lf/service/userService1.java deleted file mode 100644 index df8a835edb..0000000000 --- a/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/java/com/lf/service/userService1.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.lf.service; - -import com.lf.bean.userBean; - -import java.util.List; - -public interface userService1 { - int addUserService(userBean user) throws Exception; - List selectAll() throws Exception; -} diff --git a/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/java/com/lf/servlet/selectServlet.java b/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/java/com/lf/servlet/selectServlet.java deleted file mode 100644 index 84e786404c..0000000000 --- a/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/java/com/lf/servlet/selectServlet.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.lf.servlet; - -import com.lf.bean.userBean; -import com.lf.service.serviceImpl.userServiceImpl; -import com.lf.service.userService1; - -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -@WebServlet(name = "selectServlet") -public class selectServlet extends HttpServlet { - - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - doGet(request,response); - - } - - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - //查询数据库的数据,在页面进行显示 - userService1 userService1= new userServiceImpl(); - List list= new ArrayList(); - try { - list=userService1.selectAll(); - } catch (Exception e) { - e.printStackTrace(); - } - //响应数据的时候乱码 - response.setCharacterEncoding("utf-8"); - response.setContentType("text/html;charset=utf-8"); - //在页面制表 - response.getWriter().print("
    "); - response.getWriter().print(""); - response.getWriter().print(""); - response.getWriter().print(""); - response.getWriter().print(""); - response.getWriter().print(""); - response.getWriter().print(""); - for (userBean userBean : list) { - response.getWriter().print(""); - //获取数据 - response.getWriter().print(userBean.getId()); - response.getWriter().print(userBean.getNaem()); - response.getWriter().print(userBean.getAddress()); - response.getWriter().print(userBean.getSex()); - response.getWriter().print(userBean.getDate()); - //定义操作 - response.getWriter().print(""); - response.getWriter().print(""); - } - - } -} diff --git a/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/java/com/lf/servlet/zhuceServlet.java b/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/java/com/lf/servlet/zhuceServlet.java deleted file mode 100644 index a311fe5c9f..0000000000 --- a/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/java/com/lf/servlet/zhuceServlet.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.lf.servlet; -import com.lf.bean.userBean; -import com.lf.service.serviceImpl.userServiceImpl; -import com.lf.service.userService1; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; - -//@WebServlet(name = "zhuceServlet") -public class zhuceServlet extends HttpServlet { - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - doGet(request,response); - - } - - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - //使用request获取前端页面的数据 - String UserName = request.getParameter("name"); - String UserSex = request.getParameter("sex"); - String UserAddress = request.getParameter("address"); - String date = request.getParameter("date"); - //然后把String类型的时间转换为Date类型 - SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); - Date date2=null; - try { - date2 = simpleDateFormat.parse(date); - System.out.print(date2); - } catch (ParseException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - //把数据封装在对象里面 - userBean user= new userBean(UserName,UserSex,UserAddress,date2); - //调用service把数据写入到数据库中 - int a=0; - userService1 userService=new userServiceImpl(); - try { - a=userService.addUserService(user); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } -// 响应数据的时候乱码 - response.setCharacterEncoding("utf-8"); - response.setContentType("text/html;charset=utf-8"); - if (a!=0) { - response.getWriter().print(""); - } - - } - -} diff --git a/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/java/com/lf/util/dbConnector.java b/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/java/com/lf/util/dbConnector.java deleted file mode 100644 index 39c0de2b98..0000000000 --- a/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/java/com/lf/util/dbConnector.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.lf.util; - -import com.mysql.jdbc.jdbc2.optional.MysqlDataSource; -import org.apache.commons.dbutils.QueryRunner; -import javax.sql.DataSource; -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; -/** - * @ClassName: dbConnector - * @Description:数据库连接 - * @Author: 李峰 - * @Date: 2021 年 01月 18 18:14 - * @Version 1.0 - */ -public class dbConnector { - private static QueryRunner queryRunner=new QueryRunner(getDateSource()); - public static DataSource getDateSource() { - MysqlDataSource dataSource = new MysqlDataSource(); - InputStream resourceAsStream = dbConnector.class.getClassLoader().getResourceAsStream("db.properties"); - Properties properties = new Properties(); - try { - properties.load(resourceAsStream); - dataSource.setURL(properties.getProperty("jdbc.Url")); - dataSource.setPassword(properties.getProperty("jdbc.Password")); - dataSource.setUser(properties.getProperty("jdbc.UserName")); - } catch (IOException e) { - e.printStackTrace(); - } - return dataSource; - } - public static QueryRunner getInstance(){ - return queryRunner; - } -} diff --git a/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/webapp/WEB-INF/web.xml b/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 893bb9fe9f..0000000000 --- a/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - zhuceServlet - com.lf.servlet.zhuceServlet - - - zhuceServlet - /zhuceServlet - - - selectServlet - com.lf.servlet.selectServlet - - - selectServlet - /selectServlet - - diff --git a/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/webapp/css/login.css b/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/webapp/css/login.css deleted file mode 100644 index 0b2410e4ed..0000000000 --- a/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/webapp/css/login.css +++ /dev/null @@ -1,65 +0,0 @@ -body{ - background: #ddd -} -.loginwarrp{ - margin: 250px auto; - width: 400px; - padding: 30px 50px; - background: #FFFFFF; - overflow: hidden; - font-size: 14px; - font-family: '΢ź','Ȫ',''; -} -.loginwarrp .logo{ - width:100%; - height:44px; - line-height: 44px; - font-size: 20px; - text-align: center; - border-bottom:1px solid #ddd; -} -.loginwarrp .login_form{ - margin-top: 15px; -} -.loginwarrp .login_form .login-item{ - padding: 2px 8px; - border:1px solid #dedede; - border-radius: 8px; - margin-top: 10px; -} -.loginwarrp .login_form .login_input{ - height: 35px; - border: none; - line-height: 35px; - width: 200px; - font-size: 14px; - outline: none; -} -.loginwarrp .login_form .verify{ - float: left; -} -.loginwarrp .verify .verify_input{ - width: 160px; -} -.loginwarrp .verifyimg{ - height: 30px; - margin: 20px 0 0 20px; -} -.loginwarrp .login-sub{ - text-align: center; -} -.loginwarrp .login-sub input{ - margin-top:15px; - background: #45B549; - line-height: 35px; - width: 150px; - color: #FFFFFF; - font-size: 16px; - font-family: '΢ź','Ȫ',''; - border: none; - border-radius: 5px; -} -.loginwarrp .login_form .login-item .error{ - color: #F00; - font-family: '΢ź','Ȫ',''; -} \ No newline at end of file diff --git a/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/webapp/css/reset.css b/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/webapp/css/reset.css deleted file mode 100644 index 5c0344e23a..0000000000 --- a/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/webapp/css/reset.css +++ /dev/null @@ -1,87 +0,0 @@ - -html, body, div, span, applet, object, iframe, -h1, h2, h3, h4, h5, h6, p, blockquote, pre, -a, abbr, acronym, address, big, cite, code, -del, dfn, em, img, ins, kbd, q, s, samp, -small, strike, strong, sub, sup, tt, var, -b, u, i, center, -dl, dt, dd, ol, ul, li, -fieldset, form, label, legend, -table, caption, tbody, tfoot, thead, tr, th, td, -article, aside, canvas, details, embed, -figure, figcaption, footer, header, hgroup, -menu, nav, output, ruby, section, summary, -time, mark, audio, video { - margin: 0; - padding: 0; - border: 0; - font-size: 100%; - font: inherit; -} -/* HTML5 display-role reset for older browsers */ -article, aside, details, figcaption, figure, -footer, header, hgroup, menu, nav, section { - display: block; -} -body { - line-height: 1; -} -ol, ul,li { - list-style: none; -} -blockquote, q { - quotes: none; -} -blockquote:before, blockquote:after, -q:before, q:after { - content: ''; - content: none; -} -table { - border-collapse: collapse; - border-spacing: 0; -} -a{ - text-decoration: none; - color: #333; - display: block; -} -body{ - font-size: 14px; -} -.clearfix{ - zoom:1; -} -.clearfix:after{ - content:"."; - display:block; - visibility:hidden; - height:0; - clear:both; -} -.fl,.l{ - float: left; -} -.fr,.r{ - float: right; -} -/*margin-top*/ -.mt10{ - margin-top: 10px; -} -.mt15{ - margin-top: 15px; -} -.mt20{ - margin-top: 20px; -} -.mt5{ - margin-top: 5px; -} -.mt0{ - margin-top: 0px; -} -/*padding-left*/ -.pl15{ - padding-left: 15px; -} \ No newline at end of file diff --git a/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/webapp/js/canvas-particle.js b/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/webapp/js/canvas-particle.js deleted file mode 100644 index 702b2a8d91..0000000000 --- a/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/webapp/js/canvas-particle.js +++ /dev/null @@ -1,168 +0,0 @@ -var CanvasParticle = (function(){ - function getElementByTag(name){ - return document.getElementsByTagName(name); - } - function getELementById(id){ - return document.getElementById(id); - } - // 根据传入的config初始化画布 - function canvasInit(canvasConfig){ - canvasConfig = canvasConfig || {}; - var html = getElementByTag("html")[0]; - var body = getElementByTag("body")[0]; - var canvasDiv = getELementById("canvas-particle"); - var canvasObj = document.createElement("canvas"); - - var canvas = { - element: canvasObj, - points : [], - // 默认配置 - config: { - vx: canvasConfig.vx || 4, - vy: canvasConfig.vy || 4, - height: canvasConfig.height || 2, - width: canvasConfig.width || 2, - count: canvasConfig.count || 100, - color: canvasConfig.color || "0, 0, 255", - stroke: canvasConfig.stroke || "130,255,255", - dist: canvasConfig.dist || 6000, - e_dist: canvasConfig.e_dist || 20000, - max_conn: 10 - } - }; - - // 获取context - if(canvas.element.getContext("2d")){ - canvas.context = canvas.element.getContext("2d"); - }else{ - return null; - } - - body.style.padding = "0"; - body.style.margin = "0"; - // body.replaceChild(canvas.element, canvasDiv); - body.appendChild(canvas.element); - - canvas.element.style = "position: absolute; top: 0; left: 0; z-index: -1;"; - canvasSize(canvas.element); - window.onresize = function(){ - canvasSize(canvas.element); - } - body.onmousemove = function(e){ - var event = e || window.event; - canvas.mouse = { - x: event.clientX, - y: event.clientY - } - } - document.onmouseleave = function(){ - canvas.mouse = undefined; - } - setInterval(function(){ - drawPoint(canvas); - }, 40); - } - - // 设置canvas大小 - function canvasSize(canvas){ - canvas.width = window.innerWeight || document.documentElement.clientWidth || document.body.clientWidth; - canvas.height = window.innerWeight || document.documentElement.clientHeight || document.body.clientHeight; - } - - // 画点 - function drawPoint(canvas){ - var context = canvas.context, - point, - dist; - context.clearRect(0, 0, canvas.element.width, canvas.element.height); - context.beginPath(); - context.fillStyle = "rgb("+ canvas.config.color +")"; - for(var i = 0, len = canvas.config.count; i < len; i++){ - if(canvas.points.length != canvas.config.count){ - // 初始化所有点 - point = { - x: Math.floor(Math.random() * canvas.element.width), - y: Math.floor(Math.random() * canvas.element.height), - vx: canvas.config.vx / 2 - Math.random() * canvas.config.vx, - vy: canvas.config.vy / 2 - Math.random() * canvas.config.vy - } - }else{ - // 处理球的速度和位置,并且做边界处理 - point = borderPoint(canvas.points[i], canvas); - } - context.fillRect(point.x - canvas.config.width / 2, point.y - canvas.config.height / 2, canvas.config.width, canvas.config.height); - - canvas.points[i] = point; - } - drawLine(context, canvas, canvas.mouse); - context.closePath(); - } - - // 边界处理 - function borderPoint(point, canvas){ - var p = point; - if(point.x <= 0 || point.x >= canvas.element.width){ - p.vx = -p.vx; - p.x += p.vx; - }else if(point.y <= 0 || point.y >= canvas.element.height){ - p.vy = -p.vy; - p.y += p.vy; - }else{ - p = { - x: p.x + p.vx, - y: p.y + p.vy, - vx: p.vx, - vy: p.vy - } - } - return p; - } - - // 画线 - function drawLine(context, canvas, mouse){ - context = context || canvas.context; - for(var i = 0, len = canvas.config.count; i < len; i++){ - // 初始化最大连接数 - canvas.points[i].max_conn = 0; - // point to point - for(var j = 0; j < len; j++){ - if(i != j){ - dist = Math.round(canvas.points[i].x - canvas.points[j].x) * Math.round(canvas.points[i].x - canvas.points[j].x) + - Math.round(canvas.points[i].y - canvas.points[j].y) * Math.round(canvas.points[i].y - canvas.points[j].y); - // 两点距离小于吸附距离,而且小于最大连接数,则画线 - if(dist <= canvas.config.dist && canvas.points[i].max_conn canvas.config.dist && dist <= canvas.config.e_dist){ - canvas.points[i].x = canvas.points[i].x + (mouse.x - canvas.points[i].x) / 20; - canvas.points[i].y = canvas.points[i].y + (mouse.y - canvas.points[i].y) / 20; - } - if(dist <= canvas.config.e_dist){ - context.lineWidth = 1; - context.strokeStyle = "rgba("+ canvas.config.stroke + ","+ (1 - dist / canvas.config.e_dist) +")"; - context.beginPath(); - context.moveTo(canvas.points[i].x, canvas.points[i].y); - context.lineTo(mouse.x, mouse.y); - context.stroke(); - } - } - } - } - return canvasInit; -})(); \ No newline at end of file diff --git a/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/webapp/js/jquery.min.js b/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/webapp/js/jquery.min.js deleted file mode 100644 index b18e05a957..0000000000 --- a/jun_java_plugins/jun_webservlet/doc/webservlet01/src/main/webapp/js/jquery.min.js +++ /dev/null @@ -1,6 +0,0 @@ -/*! jQuery v2.0.0 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license -//@ sourceMappingURL=jquery.min.map -*/ -(function(e,undefined){var t,n,r=typeof undefined,i=e.location,o=e.document,s=o.documentElement,a=e.jQuery,u=e.$,l={},c=[],f="2.0.0",p=c.concat,h=c.push,d=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=f.trim,x=function(e,n){return new x.fn.init(e,n,t)},b=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^-ms-/,N=/-([\da-z])/gi,E=function(e,t){return t.toUpperCase()},S=function(){o.removeEventListener("DOMContentLoaded",S,!1),e.removeEventListener("load",S,!1),x.ready()};x.fn=x.prototype={jquery:f,constructor:x,init:function(e,t,n){var r,i;if(!e)return this;if("string"==typeof e){if(r="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:T.exec(e),!r||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof x?t[0]:t,x.merge(this,x.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:o,!0)),C.test(r[1])&&x.isPlainObject(t))for(r in t)x.isFunction(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return i=o.getElementById(r[2]),i&&i.parentNode&&(this.length=1,this[0]=i),this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):x.isFunction(e)?n.ready(e):(e.selector!==undefined&&(this.selector=e.selector,this.context=e.context),x.makeArray(e,this))},selector:"",length:0,toArray:function(){return d.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=x.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return x.each(this,e,t)},ready:function(e){return x.ready.promise().done(e),this},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(x.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:h,sort:[].sort,splice:[].splice},x.fn.init.prototype=x.fn,x.extend=x.fn.extend=function(){var e,t,n,r,i,o,s=arguments[0]||{},a=1,u=arguments.length,l=!1;for("boolean"==typeof s&&(l=s,s=arguments[1]||{},a=2),"object"==typeof s||x.isFunction(s)||(s={}),u===a&&(s=this,--a);u>a;a++)if(null!=(e=arguments[a]))for(t in e)n=s[t],r=e[t],s!==r&&(l&&r&&(x.isPlainObject(r)||(i=x.isArray(r)))?(i?(i=!1,o=n&&x.isArray(n)?n:[]):o=n&&x.isPlainObject(n)?n:{},s[t]=x.extend(l,o,r)):r!==undefined&&(s[t]=r));return s},x.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),noConflict:function(t){return e.$===x&&(e.$=u),t&&e.jQuery===x&&(e.jQuery=a),x},isReady:!1,readyWait:1,holdReady:function(e){e?x.readyWait++:x.ready(!0)},ready:function(e){(e===!0?--x.readyWait:x.isReady)||(x.isReady=!0,e!==!0&&--x.readyWait>0||(n.resolveWith(o,[x]),x.fn.trigger&&x(o).trigger("ready").off("ready")))},isFunction:function(e){return"function"===x.type(e)},isArray:Array.isArray,isWindow:function(e){return null!=e&&e===e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if("object"!==x.type(e)||e.nodeType||x.isWindow(e))return!1;try{if(e.constructor&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(t){return!1}return!0},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=C.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=x.buildFragment([e],t,i),i&&x(i).remove(),x.merge([],r.childNodes))},parseJSON:JSON.parse,parseXML:function(e){var t,n;if(!e||"string"!=typeof e)return null;try{n=new DOMParser,t=n.parseFromString(e,"text/xml")}catch(r){t=undefined}return(!t||t.getElementsByTagName("parsererror").length)&&x.error("Invalid XML: "+e),t},noop:function(){},globalEval:function(e){var t,n=eval;e=x.trim(e),e&&(1===e.indexOf("use strict")?(t=o.createElement("script"),t.text=e,o.head.appendChild(t).parentNode.removeChild(t)):n(e))},camelCase:function(e){return e.replace(k,"ms-").replace(N,E)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,s=j(e);if(n){if(s){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(s){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:function(e){return null==e?"":v.call(e)},makeArray:function(e,t){var n=t||[];return null!=e&&(j(Object(e))?x.merge(n,"string"==typeof e?[e]:e):h.call(n,e)),n},inArray:function(e,t,n){return null==t?-1:g.call(t,e,n)},merge:function(e,t){var n=t.length,r=e.length,i=0;if("number"==typeof n)for(;n>i;i++)e[r++]=t[i];else while(t[i]!==undefined)e[r++]=t[i++];return e.length=r,e},grep:function(e,t,n){var r,i=[],o=0,s=e.length;for(n=!!n;s>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,s=j(e),a=[];if(s)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(a[a.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(a[a.length]=r);return p.apply([],a)},guid:1,proxy:function(e,t){var n,r,i;return"string"==typeof t&&(n=e[t],t=e,e=n),x.isFunction(e)?(r=d.call(arguments,2),i=function(){return e.apply(t||this,r.concat(d.call(arguments)))},i.guid=e.guid=e.guid||x.guid++,i):undefined},access:function(e,t,n,r,i,o,s){var a=0,u=e.length,l=null==n;if("object"===x.type(n)){i=!0;for(a in n)x.access(e,t,a,n[a],!0,o,s)}else if(r!==undefined&&(i=!0,x.isFunction(r)||(s=!0),l&&(s?(t.call(e,r),t=null):(l=t,t=function(e,t,n){return l.call(x(e),n)})),t))for(;u>a;a++)t(e[a],n,s?r:r.call(e[a],a,t(e[a],n)));return i?e:l?t.call(e):u?t(e[0],n):o},now:Date.now,swap:function(e,t,n,r){var i,o,s={};for(o in t)s[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=s[o];return i}}),x.ready.promise=function(t){return n||(n=x.Deferred(),"complete"===o.readyState?setTimeout(x.ready):(o.addEventListener("DOMContentLoaded",S,!1),e.addEventListener("load",S,!1))),n.promise(t)},x.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function j(e){var t=e.length,n=x.type(e);return x.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}t=x(o),function(e,undefined){var t,n,r,i,o,s,a,u,l,c,f,p,h,d,g,m,y="sizzle"+-new Date,v=e.document,b={},w=0,T=0,C=ot(),k=ot(),N=ot(),E=!1,S=function(){return 0},j=typeof undefined,D=1<<31,A=[],L=A.pop,q=A.push,H=A.push,O=A.slice,F=A.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},P="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",R="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",W=M.replace("w","w#"),$="\\["+R+"*("+M+")"+R+"*(?:([*^$|!~]?=)"+R+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+W+")|)|)"+R+"*\\]",B=":("+M+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+$.replace(3,8)+")*)|.*)\\)|)",I=RegExp("^"+R+"+|((?:^|[^\\\\])(?:\\\\.)*)"+R+"+$","g"),z=RegExp("^"+R+"*,"+R+"*"),_=RegExp("^"+R+"*([>+~]|"+R+")"+R+"*"),X=RegExp(R+"*[+~]"),U=RegExp("="+R+"*([^\\]'\"]*)"+R+"*\\]","g"),Y=RegExp(B),V=RegExp("^"+W+"$"),G={ID:RegExp("^#("+M+")"),CLASS:RegExp("^\\.("+M+")"),TAG:RegExp("^("+M.replace("w","w*")+")"),ATTR:RegExp("^"+$),PSEUDO:RegExp("^"+B),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+R+"*(even|odd|(([+-]|)(\\d*)n|)"+R+"*(?:([+-]|)"+R+"*(\\d+)|))"+R+"*\\)|)","i"),"boolean":RegExp("^(?:"+P+")$","i"),needsContext:RegExp("^"+R+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+R+"*((?:-\\d)?\\d*)"+R+"*\\)|)(?=[^-]|$)","i")},J=/^[^{]+\{\s*\[native \w/,Q=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,K=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,et=/'|\\/g,tt=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,nt=function(e,t){var n="0x"+t-65536;return n!==n?t:0>n?String.fromCharCode(n+65536):String.fromCharCode(55296|n>>10,56320|1023&n)};try{H.apply(A=O.call(v.childNodes),v.childNodes),A[v.childNodes.length].nodeType}catch(rt){H={apply:A.length?function(e,t){q.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function it(e){return J.test(e+"")}function ot(){var e,t=[];return e=function(n,i){return t.push(n+=" ")>r.cacheLength&&delete e[t.shift()],e[n]=i}}function st(e){return e[y]=!0,e}function at(e){var t=c.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function ut(e,t,n,r){var i,o,s,a,u,f,d,g,x,w;if((t?t.ownerDocument||t:v)!==c&&l(t),t=t||c,n=n||[],!e||"string"!=typeof e)return n;if(1!==(a=t.nodeType)&&9!==a)return[];if(p&&!r){if(i=Q.exec(e))if(s=i[1]){if(9===a){if(o=t.getElementById(s),!o||!o.parentNode)return n;if(o.id===s)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(s))&&m(t,o)&&o.id===s)return n.push(o),n}else{if(i[2])return H.apply(n,t.getElementsByTagName(e)),n;if((s=i[3])&&b.getElementsByClassName&&t.getElementsByClassName)return H.apply(n,t.getElementsByClassName(s)),n}if(b.qsa&&(!h||!h.test(e))){if(g=d=y,x=t,w=9===a&&e,1===a&&"object"!==t.nodeName.toLowerCase()){f=gt(e),(d=t.getAttribute("id"))?g=d.replace(et,"\\$&"):t.setAttribute("id",g),g="[id='"+g+"'] ",u=f.length;while(u--)f[u]=g+mt(f[u]);x=X.test(e)&&t.parentNode||t,w=f.join(",")}if(w)try{return H.apply(n,x.querySelectorAll(w)),n}catch(T){}finally{d||t.removeAttribute("id")}}}return kt(e.replace(I,"$1"),t,n,r)}o=ut.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},l=ut.setDocument=function(e){var t=e?e.ownerDocument||e:v;return t!==c&&9===t.nodeType&&t.documentElement?(c=t,f=t.documentElement,p=!o(t),b.getElementsByTagName=at(function(e){return e.appendChild(t.createComment("")),!e.getElementsByTagName("*").length}),b.attributes=at(function(e){return e.className="i",!e.getAttribute("className")}),b.getElementsByClassName=at(function(e){return e.innerHTML="
    ",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),b.sortDetached=at(function(e){return 1&e.compareDocumentPosition(c.createElement("div"))}),b.getById=at(function(e){return f.appendChild(e).id=y,!t.getElementsByName||!t.getElementsByName(y).length}),b.getById?(r.find.ID=function(e,t){if(typeof t.getElementById!==j&&p){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},r.filter.ID=function(e){var t=e.replace(tt,nt);return function(e){return e.getAttribute("id")===t}}):(r.find.ID=function(e,t){if(typeof t.getElementById!==j&&p){var n=t.getElementById(e);return n?n.id===e||typeof n.getAttributeNode!==j&&n.getAttributeNode("id").value===e?[n]:undefined:[]}},r.filter.ID=function(e){var t=e.replace(tt,nt);return function(e){var n=typeof e.getAttributeNode!==j&&e.getAttributeNode("id");return n&&n.value===t}}),r.find.TAG=b.getElementsByTagName?function(e,t){return typeof t.getElementsByTagName!==j?t.getElementsByTagName(e):undefined}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},r.find.CLASS=b.getElementsByClassName&&function(e,t){return typeof t.getElementsByClassName!==j&&p?t.getElementsByClassName(e):undefined},d=[],h=[],(b.qsa=it(t.querySelectorAll))&&(at(function(e){e.innerHTML="",e.querySelectorAll("[selected]").length||h.push("\\["+R+"*(?:value|"+P+")"),e.querySelectorAll(":checked").length||h.push(":checked")}),at(function(e){var t=c.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("t",""),e.querySelectorAll("[t^='']").length&&h.push("[*^$]="+R+"*(?:''|\"\")"),e.querySelectorAll(":enabled").length||h.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),h.push(",.*:")})),(b.matchesSelector=it(g=f.webkitMatchesSelector||f.mozMatchesSelector||f.oMatchesSelector||f.msMatchesSelector))&&at(function(e){b.disconnectedMatch=g.call(e,"div"),g.call(e,"[s!='']:x"),d.push("!=",B)}),h=h.length&&RegExp(h.join("|")),d=d.length&&RegExp(d.join("|")),m=it(f.contains)||f.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},S=f.compareDocumentPosition?function(e,n){if(e===n)return E=!0,0;var r=n.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(n);return r?1&r||!b.sortDetached&&n.compareDocumentPosition(e)===r?e===t||m(v,e)?-1:n===t||m(v,n)?1:u?F.call(u,e)-F.call(u,n):0:4&r?-1:1:e.compareDocumentPosition?-1:1}:function(e,n){var r,i=0,o=e.parentNode,s=n.parentNode,a=[e],l=[n];if(e===n)return E=!0,0;if(!o||!s)return e===t?-1:n===t?1:o?-1:s?1:u?F.call(u,e)-F.call(u,n):0;if(o===s)return lt(e,n);r=e;while(r=r.parentNode)a.unshift(r);r=n;while(r=r.parentNode)l.unshift(r);while(a[i]===l[i])i++;return i?lt(a[i],l[i]):a[i]===v?-1:l[i]===v?1:0},c):c},ut.matches=function(e,t){return ut(e,null,null,t)},ut.matchesSelector=function(e,t){if((e.ownerDocument||e)!==c&&l(e),t=t.replace(U,"='$1']"),!(!b.matchesSelector||!p||d&&d.test(t)||h&&h.test(t)))try{var n=g.call(e,t);if(n||b.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(r){}return ut(t,c,null,[e]).length>0},ut.contains=function(e,t){return(e.ownerDocument||e)!==c&&l(e),m(e,t)},ut.attr=function(e,t){(e.ownerDocument||e)!==c&&l(e);var n=r.attrHandle[t.toLowerCase()],i=n&&n(e,t,!p);return i===undefined?b.attributes||!p?e.getAttribute(t):(i=e.getAttributeNode(t))&&i.specified?i.value:null:i},ut.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},ut.uniqueSort=function(e){var t,n=[],r=0,i=0;if(E=!b.detectDuplicates,u=!b.sortStable&&e.slice(0),e.sort(S),E){while(t=e[i++])t===e[i]&&(r=n.push(i));while(r--)e.splice(n[r],1)}return e};function lt(e,t){var n=t&&e,r=n&&(~t.sourceIndex||D)-(~e.sourceIndex||D);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function ct(e,t,n){var r;return n?undefined:(r=e.getAttributeNode(t))&&r.specified?r.value:e[t]===!0?t.toLowerCase():null}function ft(e,t,n){var r;return n?undefined:r=e.getAttribute(t,"type"===t.toLowerCase()?1:2)}function pt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function ht(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function dt(e){return st(function(t){return t=+t,st(function(n,r){var i,o=e([],n.length,t),s=o.length;while(s--)n[i=o[s]]&&(n[i]=!(r[i]=n[i]))})})}i=ut.getText=function(e){var t,n="",r=0,o=e.nodeType;if(o){if(1===o||9===o||11===o){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=i(e)}else if(3===o||4===o)return e.nodeValue}else for(;t=e[r];r++)n+=i(t);return n},r=ut.selectors={cacheLength:50,createPseudo:st,match:G,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(tt,nt),e[3]=(e[4]||e[5]||"").replace(tt,nt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||ut.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&ut.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return G.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&Y.test(n)&&(t=gt(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(tt,nt).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=C[e+" "];return t||(t=RegExp("(^|"+R+")"+e+"("+R+"|$)"))&&C(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==j&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=ut.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),s="last"!==e.slice(-4),a="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,f,p,h,d,g=o!==s?"nextSibling":"previousSibling",m=t.parentNode,v=a&&t.nodeName.toLowerCase(),x=!u&&!a;if(m){if(o){while(g){f=t;while(f=f[g])if(a?f.nodeName.toLowerCase()===v:1===f.nodeType)return!1;d=g="only"===e&&!d&&"nextSibling"}return!0}if(d=[s?m.firstChild:m.lastChild],s&&x){c=m[y]||(m[y]={}),l=c[e]||[],h=l[0]===w&&l[1],p=l[0]===w&&l[2],f=h&&m.childNodes[h];while(f=++h&&f&&f[g]||(p=h=0)||d.pop())if(1===f.nodeType&&++p&&f===t){c[e]=[w,h,p];break}}else if(x&&(l=(t[y]||(t[y]={}))[e])&&l[0]===w)p=l[1];else while(f=++h&&f&&f[g]||(p=h=0)||d.pop())if((a?f.nodeName.toLowerCase()===v:1===f.nodeType)&&++p&&(x&&((f[y]||(f[y]={}))[e]=[w,p]),f===t))break;return p-=i,p===r||0===p%r&&p/r>=0}}},PSEUDO:function(e,t){var n,i=r.pseudos[e]||r.setFilters[e.toLowerCase()]||ut.error("unsupported pseudo: "+e);return i[y]?i(t):i.length>1?(n=[e,e,"",t],r.setFilters.hasOwnProperty(e.toLowerCase())?st(function(e,n){var r,o=i(e,t),s=o.length;while(s--)r=F.call(e,o[s]),e[r]=!(n[r]=o[s])}):function(e){return i(e,0,n)}):i}},pseudos:{not:st(function(e){var t=[],n=[],r=s(e.replace(I,"$1"));return r[y]?st(function(e,t,n,i){var o,s=r(e,null,i,[]),a=e.length;while(a--)(o=s[a])&&(e[a]=!(t[a]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:st(function(e){return function(t){return ut(e,t).length>0}}),contains:st(function(e){return function(t){return(t.textContent||t.innerText||i(t)).indexOf(e)>-1}}),lang:st(function(e){return V.test(e||"")||ut.error("unsupported lang: "+e),e=e.replace(tt,nt).toLowerCase(),function(t){var n;do if(n=p?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===f},focus:function(e){return e===c.activeElement&&(!c.hasFocus||c.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!r.pseudos.empty(e)},header:function(e){return Z.test(e.nodeName)},input:function(e){return K.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:dt(function(){return[0]}),last:dt(function(e,t){return[t-1]}),eq:dt(function(e,t,n){return[0>n?n+t:n]}),even:dt(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:dt(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:dt(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:dt(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}};for(t in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})r.pseudos[t]=pt(t);for(t in{submit:!0,reset:!0})r.pseudos[t]=ht(t);function gt(e,t){var n,i,o,s,a,u,l,c=k[e+" "];if(c)return t?0:c.slice(0);a=e,u=[],l=r.preFilter;while(a){(!n||(i=z.exec(a)))&&(i&&(a=a.slice(i[0].length)||a),u.push(o=[])),n=!1,(i=_.exec(a))&&(n=i.shift(),o.push({value:n,type:i[0].replace(I," ")}),a=a.slice(n.length));for(s in r.filter)!(i=G[s].exec(a))||l[s]&&!(i=l[s](i))||(n=i.shift(),o.push({value:n,type:s,matches:i}),a=a.slice(n.length));if(!n)break}return t?a.length:a?ut.error(e):k(e,u).slice(0)}function mt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function yt(e,t,r){var i=t.dir,o=r&&"parentNode"===i,s=T++;return t.first?function(t,n,r){while(t=t[i])if(1===t.nodeType||o)return e(t,n,r)}:function(t,r,a){var u,l,c,f=w+" "+s;if(a){while(t=t[i])if((1===t.nodeType||o)&&e(t,r,a))return!0}else while(t=t[i])if(1===t.nodeType||o)if(c=t[y]||(t[y]={}),(l=c[i])&&l[0]===f){if((u=l[1])===!0||u===n)return u===!0}else if(l=c[i]=[f],l[1]=e(t,r,a)||n,l[1]===!0)return!0}}function vt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function xt(e,t,n,r,i){var o,s=[],a=0,u=e.length,l=null!=t;for(;u>a;a++)(o=e[a])&&(!n||n(o,r,i))&&(s.push(o),l&&t.push(a));return s}function bt(e,t,n,r,i,o){return r&&!r[y]&&(r=bt(r)),i&&!i[y]&&(i=bt(i,o)),st(function(o,s,a,u){var l,c,f,p=[],h=[],d=s.length,g=o||Ct(t||"*",a.nodeType?[a]:a,[]),m=!e||!o&&t?g:xt(g,p,e,a,u),y=n?i||(o?e:d||r)?[]:s:m;if(n&&n(m,y,a,u),r){l=xt(y,h),r(l,[],a,u),c=l.length;while(c--)(f=l[c])&&(y[h[c]]=!(m[h[c]]=f))}if(o){if(i||e){if(i){l=[],c=y.length;while(c--)(f=y[c])&&l.push(m[c]=f);i(null,y=[],l,u)}c=y.length;while(c--)(f=y[c])&&(l=i?F.call(o,f):p[c])>-1&&(o[l]=!(s[l]=f))}}else y=xt(y===s?y.splice(d,y.length):y),i?i(null,s,y,u):H.apply(s,y)})}function wt(e){var t,n,i,o=e.length,s=r.relative[e[0].type],u=s||r.relative[" "],l=s?1:0,c=yt(function(e){return e===t},u,!0),f=yt(function(e){return F.call(t,e)>-1},u,!0),p=[function(e,n,r){return!s&&(r||n!==a)||((t=n).nodeType?c(e,n,r):f(e,n,r))}];for(;o>l;l++)if(n=r.relative[e[l].type])p=[yt(vt(p),n)];else{if(n=r.filter[e[l].type].apply(null,e[l].matches),n[y]){for(i=++l;o>i;i++)if(r.relative[e[i].type])break;return bt(l>1&&vt(p),l>1&&mt(e.slice(0,l-1)).replace(I,"$1"),n,i>l&&wt(e.slice(l,i)),o>i&&wt(e=e.slice(i)),o>i&&mt(e))}p.push(n)}return vt(p)}function Tt(e,t){var i=0,o=t.length>0,s=e.length>0,u=function(u,l,f,p,h){var d,g,m,y=[],v=0,x="0",b=u&&[],T=null!=h,C=a,k=u||s&&r.find.TAG("*",h&&l.parentNode||l),N=w+=null==C?1:Math.random()||.1;for(T&&(a=l!==c&&l,n=i);null!=(d=k[x]);x++){if(s&&d){g=0;while(m=e[g++])if(m(d,l,f)){p.push(d);break}T&&(w=N,n=++i)}o&&((d=!m&&d)&&v--,u&&b.push(d))}if(v+=x,o&&x!==v){g=0;while(m=t[g++])m(b,y,l,f);if(u){if(v>0)while(x--)b[x]||y[x]||(y[x]=L.call(p));y=xt(y)}H.apply(p,y),T&&!u&&y.length>0&&v+t.length>1&&ut.uniqueSort(p)}return T&&(w=N,a=C),b};return o?st(u):u}s=ut.compile=function(e,t){var n,r=[],i=[],o=N[e+" "];if(!o){t||(t=gt(e)),n=t.length;while(n--)o=wt(t[n]),o[y]?r.push(o):i.push(o);o=N(e,Tt(i,r))}return o};function Ct(e,t,n){var r=0,i=t.length;for(;i>r;r++)ut(e,t[r],n);return n}function kt(e,t,n,i){var o,a,u,l,c,f=gt(e);if(!i&&1===f.length){if(a=f[0]=f[0].slice(0),a.length>2&&"ID"===(u=a[0]).type&&9===t.nodeType&&p&&r.relative[a[1].type]){if(t=(r.find.ID(u.matches[0].replace(tt,nt),t)||[])[0],!t)return n;e=e.slice(a.shift().value.length)}o=G.needsContext.test(e)?0:a.length;while(o--){if(u=a[o],r.relative[l=u.type])break;if((c=r.find[l])&&(i=c(u.matches[0].replace(tt,nt),X.test(a[0].type)&&t.parentNode||t))){if(a.splice(o,1),e=i.length&&mt(a),!e)return H.apply(n,i),n;break}}}return s(e,f)(i,t,!p,n,X.test(e)),n}r.pseudos.nth=r.pseudos.eq;function Nt(){}Nt.prototype=r.filters=r.pseudos,r.setFilters=new Nt,b.sortStable=y.split("").sort(S).join("")===y,l(),[0,0].sort(S),b.detectDuplicates=E,at(function(e){if(e.innerHTML="","#"!==e.firstChild.getAttribute("href")){var t="type|href|height|width".split("|"),n=t.length;while(n--)r.attrHandle[t[n]]=ft}}),at(function(e){if(null!=e.getAttribute("disabled")){var t=P.split("|"),n=t.length;while(n--)r.attrHandle[t[n]]=ct}}),x.find=ut,x.expr=ut.selectors,x.expr[":"]=x.expr.pseudos,x.unique=ut.uniqueSort,x.text=ut.getText,x.isXMLDoc=ut.isXML,x.contains=ut.contains}(e);var D={};function A(e){var t=D[e]={};return x.each(e.match(w)||[],function(e,n){t[n]=!0}),t}x.Callbacks=function(e){e="string"==typeof e?D[e]||A(e):x.extend({},e);var t,n,r,i,o,s,a=[],u=!e.once&&[],l=function(f){for(t=e.memory&&f,n=!0,s=i||0,i=0,o=a.length,r=!0;a&&o>s;s++)if(a[s].apply(f[0],f[1])===!1&&e.stopOnFalse){t=!1;break}r=!1,a&&(u?u.length&&l(u.shift()):t?a=[]:c.disable())},c={add:function(){if(a){var n=a.length;(function s(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&c.has(n)||a.push(n):n&&n.length&&"string"!==r&&s(n)})})(arguments),r?o=a.length:t&&(i=n,l(t))}return this},remove:function(){return a&&x.each(arguments,function(e,t){var n;while((n=x.inArray(t,a,n))>-1)a.splice(n,1),r&&(o>=n&&o--,s>=n&&s--)}),this},has:function(e){return e?x.inArray(e,a)>-1:!(!a||!a.length)},empty:function(){return a=[],o=0,this},disable:function(){return a=u=t=undefined,this},disabled:function(){return!a},lock:function(){return u=undefined,t||c.disable(),this},locked:function(){return!u},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!a||n&&!u||(r?u.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!n}};return c},x.extend({Deferred:function(e){var t=[["resolve","done",x.Callbacks("once memory"),"resolved"],["reject","fail",x.Callbacks("once memory"),"rejected"],["notify","progress",x.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return x.Deferred(function(n){x.each(t,function(t,o){var s=o[0],a=x.isFunction(e[t])&&e[t];i[o[1]](function(){var e=a&&a.apply(this,arguments);e&&x.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===r?n.promise():this,a?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?x.extend(e,r):r}},i={};return r.pipe=r.then,x.each(t,function(e,o){var s=o[2],a=o[3];r[o[1]]=s.add,a&&s.add(function(){n=a},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=s.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=d.call(arguments),r=n.length,i=1!==r||e&&x.isFunction(e.promise)?r:0,o=1===i?e:x.Deferred(),s=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?d.call(arguments):r,n===a?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},a,u,l;if(r>1)for(a=Array(r),u=Array(r),l=Array(r);r>t;t++)n[t]&&x.isFunction(n[t].promise)?n[t].promise().done(s(t,l,n)).fail(o.reject).progress(s(t,u,a)):--i;return i||o.resolveWith(l,n),o.promise()}}),x.support=function(t){var n=o.createElement("input"),r=o.createDocumentFragment(),i=o.createElement("div"),s=o.createElement("select"),a=s.appendChild(o.createElement("option"));return n.type?(n.type="checkbox",t.checkOn=""!==n.value,t.optSelected=a.selected,t.reliableMarginRight=!0,t.boxSizingReliable=!0,t.pixelPosition=!1,n.checked=!0,t.noCloneChecked=n.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!a.disabled,n=o.createElement("input"),n.value="t",n.type="radio",t.radioValue="t"===n.value,n.setAttribute("checked","t"),n.setAttribute("name","t"),r.appendChild(n),t.checkClone=r.cloneNode(!0).cloneNode(!0).lastChild.checked,t.focusinBubbles="onfocusin"in e,i.style.backgroundClip="content-box",i.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===i.style.backgroundClip,x(function(){var n,r,s="padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box",a=o.getElementsByTagName("body")[0];a&&(n=o.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",a.appendChild(n).appendChild(i),i.innerHTML="",i.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%",x.swap(a,null!=a.style.zoom?{zoom:1}:{},function(){t.boxSizing=4===i.offsetWidth}),e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(i,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(i,null)||{width:"4px"}).width,r=i.appendChild(o.createElement("div")),r.style.cssText=i.style.cssText=s,r.style.marginRight=r.style.width="0",i.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),a.removeChild(n))}),t):t}({});var L,q,H=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,O=/([A-Z])/g;function F(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=x.expando+Math.random()}F.uid=1,F.accepts=function(e){return e.nodeType?1===e.nodeType||9===e.nodeType:!0},F.prototype={key:function(e){if(!F.accepts(e))return 0;var t={},n=e[this.expando];if(!n){n=F.uid++;try{t[this.expando]={value:n},Object.defineProperties(e,t)}catch(r){t[this.expando]=n,x.extend(e,t)}}return this.cache[n]||(this.cache[n]={}),n},set:function(e,t,n){var r,i=this.key(e),o=this.cache[i];if("string"==typeof t)o[t]=n;else if(x.isEmptyObject(o))this.cache[i]=t;else for(r in t)o[r]=t[r]},get:function(e,t){var n=this.cache[this.key(e)];return t===undefined?n:n[t]},access:function(e,t,n){return t===undefined||t&&"string"==typeof t&&n===undefined?this.get(e,t):(this.set(e,t,n),n!==undefined?n:t)},remove:function(e,t){var n,r,i=this.key(e),o=this.cache[i];if(t===undefined)this.cache[i]={};else{x.isArray(t)?r=t.concat(t.map(x.camelCase)):t in o?r=[t]:(r=x.camelCase(t),r=r in o?[r]:r.match(w)||[]),n=r.length;while(n--)delete o[r[n]]}},hasData:function(e){return!x.isEmptyObject(this.cache[e[this.expando]]||{})},discard:function(e){delete this.cache[this.key(e)]}},L=new F,q=new F,x.extend({acceptData:F.accepts,hasData:function(e){return L.hasData(e)||q.hasData(e)},data:function(e,t,n){return L.access(e,t,n)},removeData:function(e,t){L.remove(e,t)},_data:function(e,t,n){return q.access(e,t,n)},_removeData:function(e,t){q.remove(e,t)}}),x.fn.extend({data:function(e,t){var n,r,i=this[0],o=0,s=null;if(e===undefined){if(this.length&&(s=L.get(i),1===i.nodeType&&!q.get(i,"hasDataAttrs"))){for(n=i.attributes;n.length>o;o++)r=n[o].name,0===r.indexOf("data-")&&(r=x.camelCase(r.substring(5)),P(i,r,s[r]));q.set(i,"hasDataAttrs",!0)}return s}return"object"==typeof e?this.each(function(){L.set(this,e)}):x.access(this,function(t){var n,r=x.camelCase(e);if(i&&t===undefined){if(n=L.get(i,e),n!==undefined)return n;if(n=L.get(i,r),n!==undefined)return n;if(n=P(i,r,undefined),n!==undefined)return n}else this.each(function(){var n=L.get(this,r);L.set(this,r,t),-1!==e.indexOf("-")&&n!==undefined&&L.set(this,e,t)})},null,t,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){L.remove(this,e)})}});function P(e,t,n){var r;if(n===undefined&&1===e.nodeType)if(r="data-"+t.replace(O,"-$1").toLowerCase(),n=e.getAttribute(r),"string"==typeof n){try{n="true"===n?!0:"false"===n?!1:"null"===n?null:+n+""===n?+n:H.test(n)?JSON.parse(n):n}catch(i){}L.set(e,t,n)}else n=undefined;return n}x.extend({queue:function(e,t,n){var r;return e?(t=(t||"fx")+"queue",r=q.get(e,t),n&&(!r||x.isArray(n)?r=q.access(e,t,x.makeArray(n)):r.push(n)),r||[]):undefined},dequeue:function(e,t){t=t||"fx";var n=x.queue(e,t),r=n.length,i=n.shift(),o=x._queueHooks(e,t),s=function(){x.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),o.cur=i,i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,s,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return q.get(e,n)||q.access(e,n,{empty:x.Callbacks("once memory").add(function(){q.remove(e,[t+"queue",n])})})}}),x.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),n>arguments.length?x.queue(this[0],e):t===undefined?this:this.each(function(){var n=x.queue(this,e,t); -x._queueHooks(this,e),"fx"===e&&"inprogress"!==n[0]&&x.dequeue(this,e)})},dequeue:function(e){return this.each(function(){x.dequeue(this,e)})},delay:function(e,t){return e=x.fx?x.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=x.Deferred(),o=this,s=this.length,a=function(){--r||i.resolveWith(o,[o])};"string"!=typeof e&&(t=e,e=undefined),e=e||"fx";while(s--)n=q.get(o[s],e+"queueHooks"),n&&n.empty&&(r++,n.empty.add(a));return a(),i.promise(t)}});var R,M,W=/[\t\r\n]/g,$=/\r/g,B=/^(?:input|select|textarea|button)$/i;x.fn.extend({attr:function(e,t){return x.access(this,x.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){x.removeAttr(this,e)})},prop:function(e,t){return x.access(this,x.prop,e,t,arguments.length>1)},removeProp:function(e){return this.each(function(){delete this[x.propFix[e]||e]})},addClass:function(e){var t,n,r,i,o,s=0,a=this.length,u="string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];a>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(W," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=x.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,s=0,a=this.length,u=0===arguments.length||"string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];a>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(W," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?x.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,i="boolean"==typeof t;return x.isFunction(e)?this.each(function(n){x(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,s=0,a=x(this),u=t,l=e.match(w)||[];while(o=l[s++])u=i?u:!a.hasClass(o),a[u?"addClass":"removeClass"](o)}else(n===r||"boolean"===n)&&(this.className&&q.set(this,"__className__",this.className),this.className=this.className||e===!1?"":q.get(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(W," ").indexOf(t)>=0)return!0;return!1},val:function(e){var t,n,r,i=this[0];{if(arguments.length)return r=x.isFunction(e),this.each(function(n){var i,o=x(this);1===this.nodeType&&(i=r?e.call(this,n,o.val()):e,null==i?i="":"number"==typeof i?i+="":x.isArray(i)&&(i=x.map(i,function(e){return null==e?"":e+""})),t=x.valHooks[this.type]||x.valHooks[this.nodeName.toLowerCase()],t&&"set"in t&&t.set(this,i,"value")!==undefined||(this.value=i))});if(i)return t=x.valHooks[i.type]||x.valHooks[i.nodeName.toLowerCase()],t&&"get"in t&&(n=t.get(i,"value"))!==undefined?n:(n=i.value,"string"==typeof n?n.replace($,""):null==n?"":n)}}}),x.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,s=o?null:[],a=o?i+1:r.length,u=0>i?a:o?i:0;for(;a>u;u++)if(n=r[u],!(!n.selected&&u!==i||(x.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&x.nodeName(n.parentNode,"optgroup"))){if(t=x(n).val(),o)return t;s.push(t)}return s},set:function(e,t){var n,r,i=e.options,o=x.makeArray(t),s=i.length;while(s--)r=i[s],(r.selected=x.inArray(x(r).val(),o)>=0)&&(n=!0);return n||(e.selectedIndex=-1),o}}},attr:function(e,t,n){var i,o,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return typeof e.getAttribute===r?x.prop(e,t,n):(1===s&&x.isXMLDoc(e)||(t=t.toLowerCase(),i=x.attrHooks[t]||(x.expr.match.boolean.test(t)?M:R)),n===undefined?i&&"get"in i&&null!==(o=i.get(e,t))?o:(o=x.find.attr(e,t),null==o?undefined:o):null!==n?i&&"set"in i&&(o=i.set(e,n,t))!==undefined?o:(e.setAttribute(t,n+""),n):(x.removeAttr(e,t),undefined))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(w);if(o&&1===e.nodeType)while(n=o[i++])r=x.propFix[n]||n,x.expr.match.boolean.test(n)&&(e[r]=!1),e.removeAttribute(n)},attrHooks:{type:{set:function(e,t){if(!x.support.radioValue&&"radio"===t&&x.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(e,t,n){var r,i,o,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return o=1!==s||!x.isXMLDoc(e),o&&(t=x.propFix[t]||t,i=x.propHooks[t]),n!==undefined?i&&"set"in i&&(r=i.set(e,n,t))!==undefined?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){return e.hasAttribute("tabindex")||B.test(e.nodeName)||e.href?e.tabIndex:-1}}}}),M={set:function(e,t,n){return t===!1?x.removeAttr(e,n):e.setAttribute(n,n),n}},x.each(x.expr.match.boolean.source.match(/\w+/g),function(e,t){var n=x.expr.attrHandle[t]||x.find.attr;x.expr.attrHandle[t]=function(e,t,r){var i=x.expr.attrHandle[t],o=r?undefined:(x.expr.attrHandle[t]=undefined)!=n(e,t,r)?t.toLowerCase():null;return x.expr.attrHandle[t]=i,o}}),x.support.optSelected||(x.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null}}),x.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){x.propFix[this.toLowerCase()]=this}),x.each(["radio","checkbox"],function(){x.valHooks[this]={set:function(e,t){return x.isArray(t)?e.checked=x.inArray(x(e).val(),t)>=0:undefined}},x.support.checkOn||(x.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var I=/^key/,z=/^(?:mouse|contextmenu)|click/,_=/^(?:focusinfocus|focusoutblur)$/,X=/^([^.]*)(?:\.(.+)|)$/;function U(){return!0}function Y(){return!1}function V(){try{return o.activeElement}catch(e){}}x.event={global:{},add:function(e,t,n,i,o){var s,a,u,l,c,f,p,h,d,g,m,y=q.get(e);if(y){n.handler&&(s=n,n=s.handler,o=s.selector),n.guid||(n.guid=x.guid++),(l=y.events)||(l=y.events={}),(a=y.handle)||(a=y.handle=function(e){return typeof x===r||e&&x.event.triggered===e.type?undefined:x.event.dispatch.apply(a.elem,arguments)},a.elem=e),t=(t||"").match(w)||[""],c=t.length;while(c--)u=X.exec(t[c])||[],d=m=u[1],g=(u[2]||"").split(".").sort(),d&&(p=x.event.special[d]||{},d=(o?p.delegateType:p.bindType)||d,p=x.event.special[d]||{},f=x.extend({type:d,origType:m,data:i,handler:n,guid:n.guid,selector:o,needsContext:o&&x.expr.match.needsContext.test(o),namespace:g.join(".")},s),(h=l[d])||(h=l[d]=[],h.delegateCount=0,p.setup&&p.setup.call(e,i,g,a)!==!1||e.addEventListener&&e.addEventListener(d,a,!1)),p.add&&(p.add.call(e,f),f.handler.guid||(f.handler.guid=n.guid)),o?h.splice(h.delegateCount++,0,f):h.push(f),x.event.global[d]=!0);e=null}},remove:function(e,t,n,r,i){var o,s,a,u,l,c,f,p,h,d,g,m=q.hasData(e)&&q.get(e);if(m&&(u=m.events)){t=(t||"").match(w)||[""],l=t.length;while(l--)if(a=X.exec(t[l])||[],h=g=a[1],d=(a[2]||"").split(".").sort(),h){f=x.event.special[h]||{},h=(r?f.delegateType:f.bindType)||h,p=u[h]||[],a=a[2]&&RegExp("(^|\\.)"+d.join("\\.(?:.*\\.|)")+"(\\.|$)"),s=o=p.length;while(o--)c=p[o],!i&&g!==c.origType||n&&n.guid!==c.guid||a&&!a.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(p.splice(o,1),c.selector&&p.delegateCount--,f.remove&&f.remove.call(e,c));s&&!p.length&&(f.teardown&&f.teardown.call(e,d,m.handle)!==!1||x.removeEvent(e,h,m.handle),delete u[h])}else for(h in u)x.event.remove(e,h+t[l],n,r,!0);x.isEmptyObject(u)&&(delete m.handle,q.remove(e,"events"))}},trigger:function(t,n,r,i){var s,a,u,l,c,f,p,h=[r||o],d=y.call(t,"type")?t.type:t,g=y.call(t,"namespace")?t.namespace.split("."):[];if(a=u=r=r||o,3!==r.nodeType&&8!==r.nodeType&&!_.test(d+x.event.triggered)&&(d.indexOf(".")>=0&&(g=d.split("."),d=g.shift(),g.sort()),c=0>d.indexOf(":")&&"on"+d,t=t[x.expando]?t:new x.Event(d,"object"==typeof t&&t),t.isTrigger=i?2:3,t.namespace=g.join("."),t.namespace_re=t.namespace?RegExp("(^|\\.)"+g.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,t.result=undefined,t.target||(t.target=r),n=null==n?[t]:x.makeArray(n,[t]),p=x.event.special[d]||{},i||!p.trigger||p.trigger.apply(r,n)!==!1)){if(!i&&!p.noBubble&&!x.isWindow(r)){for(l=p.delegateType||d,_.test(l+d)||(a=a.parentNode);a;a=a.parentNode)h.push(a),u=a;u===(r.ownerDocument||o)&&h.push(u.defaultView||u.parentWindow||e)}s=0;while((a=h[s++])&&!t.isPropagationStopped())t.type=s>1?l:p.bindType||d,f=(q.get(a,"events")||{})[t.type]&&q.get(a,"handle"),f&&f.apply(a,n),f=c&&a[c],f&&x.acceptData(a)&&f.apply&&f.apply(a,n)===!1&&t.preventDefault();return t.type=d,i||t.isDefaultPrevented()||p._default&&p._default.apply(h.pop(),n)!==!1||!x.acceptData(r)||c&&x.isFunction(r[d])&&!x.isWindow(r)&&(u=r[c],u&&(r[c]=null),x.event.triggered=d,r[d](),x.event.triggered=undefined,u&&(r[c]=u)),t.result}},dispatch:function(e){e=x.event.fix(e);var t,n,r,i,o,s=[],a=d.call(arguments),u=(q.get(this,"events")||{})[e.type]||[],l=x.event.special[e.type]||{};if(a[0]=e,e.delegateTarget=this,!l.preDispatch||l.preDispatch.call(this,e)!==!1){s=x.event.handlers.call(this,e,u),t=0;while((i=s[t++])&&!e.isPropagationStopped()){e.currentTarget=i.elem,n=0;while((o=i.handlers[n++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(o.namespace))&&(e.handleObj=o,e.data=o.data,r=((x.event.special[o.origType]||{}).handle||o.handler).apply(i.elem,a),r!==undefined&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return l.postDispatch&&l.postDispatch.call(this,e),e.result}},handlers:function(e,t){var n,r,i,o,s=[],a=t.delegateCount,u=e.target;if(a&&u.nodeType&&(!e.button||"click"!==e.type))for(;u!==this;u=u.parentNode||this)if(u.disabled!==!0||"click"!==e.type){for(r=[],n=0;a>n;n++)o=t[n],i=o.selector+" ",r[i]===undefined&&(r[i]=o.needsContext?x(i,this).index(u)>=0:x.find(i,this,null,[u]).length),r[i]&&r.push(o);r.length&&s.push({elem:u,handlers:r})}return t.length>a&&s.push({elem:this,handlers:t.slice(a)}),s},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,t){var n,r,i,s=t.button;return null==e.pageX&&null!=t.clientX&&(n=e.target.ownerDocument||o,r=n.documentElement,i=n.body,e.pageX=t.clientX+(r&&r.scrollLeft||i&&i.scrollLeft||0)-(r&&r.clientLeft||i&&i.clientLeft||0),e.pageY=t.clientY+(r&&r.scrollTop||i&&i.scrollTop||0)-(r&&r.clientTop||i&&i.clientTop||0)),e.which||s===undefined||(e.which=1&s?1:2&s?3:4&s?2:0),e}},fix:function(e){if(e[x.expando])return e;var t,n,r,i=e.type,o=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=z.test(i)?this.mouseHooks:I.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new x.Event(o),t=r.length;while(t--)n=r[t],e[n]=o[n];return 3===e.target.nodeType&&(e.target=e.target.parentNode),s.filter?s.filter(e,o):e},special:{load:{noBubble:!0},focus:{trigger:function(){return this!==V()&&this.focus?(this.focus(),!1):undefined},delegateType:"focusin"},blur:{trigger:function(){return this===V()&&this.blur?(this.blur(),!1):undefined},delegateType:"focusout"},click:{trigger:function(){return"checkbox"===this.type&&this.click&&x.nodeName(this,"input")?(this.click(),!1):undefined},_default:function(e){return x.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){e.result!==undefined&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=x.extend(new x.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?x.event.trigger(i,null,t):x.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},x.removeEvent=function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)},x.Event=function(e,t){return this instanceof x.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.getPreventDefault&&e.getPreventDefault()?U:Y):this.type=e,t&&x.extend(this,t),this.timeStamp=e&&e.timeStamp||x.now(),this[x.expando]=!0,undefined):new x.Event(e,t)},x.Event.prototype={isDefaultPrevented:Y,isPropagationStopped:Y,isImmediatePropagationStopped:Y,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=U,e&&e.preventDefault&&e.preventDefault()},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=U,e&&e.stopPropagation&&e.stopPropagation()},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=U,this.stopPropagation()}},x.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){x.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!x.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),x.support.focusinBubbles||x.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){x.event.simulate(t,e.target,x.event.fix(e),!0)};x.event.special[t]={setup:function(){0===n++&&o.addEventListener(e,r,!0)},teardown:function(){0===--n&&o.removeEventListener(e,r,!0)}}}),x.fn.extend({on:function(e,t,n,r,i){var o,s;if("object"==typeof e){"string"!=typeof t&&(n=n||t,t=undefined);for(s in e)this.on(s,t,n,e[s],i);return this}if(null==n&&null==r?(r=t,n=t=undefined):null==r&&("string"==typeof t?(r=n,n=undefined):(r=n,n=t,t=undefined)),r===!1)r=Y;else if(!r)return this;return 1===i&&(o=r,r=function(e){return x().off(e),o.apply(this,arguments)},r.guid=o.guid||(o.guid=x.guid++)),this.each(function(){x.event.add(this,e,r,n,t)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,x(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(i in e)this.off(i,t,e[i]);return this}return(t===!1||"function"==typeof t)&&(n=t,t=undefined),n===!1&&(n=Y),this.each(function(){x.event.remove(this,e,n,t)})},trigger:function(e,t){return this.each(function(){x.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];return n?x.event.trigger(e,t,n,!0):undefined}});var G=/^.[^:#\[\.,]*$/,J=x.expr.match.needsContext,Q={children:!0,contents:!0,next:!0,prev:!0};x.fn.extend({find:function(e){var t,n,r,i=this.length;if("string"!=typeof e)return t=this,this.pushStack(x(e).filter(function(){for(r=0;i>r;r++)if(x.contains(t[r],this))return!0}));for(n=[],r=0;i>r;r++)x.find(e,this[r],n);return n=this.pushStack(i>1?x.unique(n):n),n.selector=(this.selector?this.selector+" ":"")+e,n},has:function(e){var t=x(e,this),n=t.length;return this.filter(function(){var e=0;for(;n>e;e++)if(x.contains(this,t[e]))return!0})},not:function(e){return this.pushStack(Z(this,e||[],!0))},filter:function(e){return this.pushStack(Z(this,e||[],!1))},is:function(e){return!!e&&("string"==typeof e?J.test(e)?x(e,this.context).index(this[0])>=0:x.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,o=[],s=J.test(e)||"string"!=typeof e?x(e,t||this.context):0;for(;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(11>n.nodeType&&(s?s.index(n)>-1:1===n.nodeType&&x.find.matchesSelector(n,e))){n=o.push(n);break}return this.pushStack(o.length>1?x.unique(o):o)},index:function(e){return e?"string"==typeof e?g.call(x(e),this[0]):g.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?x(e,t):x.makeArray(e&&e.nodeType?[e]:e),r=x.merge(this.get(),n);return this.pushStack(x.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function K(e,t){while((e=e[t])&&1!==e.nodeType);return e}x.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return x.dir(e,"parentNode")},parentsUntil:function(e,t,n){return x.dir(e,"parentNode",n)},next:function(e){return K(e,"nextSibling")},prev:function(e){return K(e,"previousSibling")},nextAll:function(e){return x.dir(e,"nextSibling")},prevAll:function(e){return x.dir(e,"previousSibling")},nextUntil:function(e,t,n){return x.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return x.dir(e,"previousSibling",n)},siblings:function(e){return x.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return x.sibling(e.firstChild)},contents:function(e){return x.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:x.merge([],e.childNodes)}},function(e,t){x.fn[e]=function(n,r){var i=x.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=x.filter(r,i)),this.length>1&&(Q[e]||x.unique(i),"p"===e[0]&&i.reverse()),this.pushStack(i)}}),x.extend({filter:function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?x.find.matchesSelector(r,e)?[r]:[]:x.find.matches(e,x.grep(t,function(e){return 1===e.nodeType}))},dir:function(e,t,n){var r=[],i=n!==undefined;while((e=e[t])&&9!==e.nodeType)if(1===e.nodeType){if(i&&x(e).is(n))break;r.push(e)}return r},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function Z(e,t,n){if(x.isFunction(t))return x.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return x.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(G.test(t))return x.filter(t,e,n);t=x.filter(t,e)}return x.grep(e,function(e){return g.call(t,e)>=0!==n})}var et=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,tt=/<([\w:]+)/,nt=/<|&#?\w+;/,rt=/<(?:script|style|link)/i,it=/^(?:checkbox|radio)$/i,ot=/checked\s*(?:[^=]|=\s*.checked.)/i,st=/^$|\/(?:java|ecma)script/i,at=/^true\/(.*)/,ut=/^\s*\s*$/g,lt={option:[1,""],thead:[1,"
    用户用户名称用户性别用户地址操作
    " - + "删除/修改
    ","
    "],tr:[2,"","
    "],td:[3,"","
    "],_default:[0,"",""]};lt.optgroup=lt.option,lt.tbody=lt.tfoot=lt.colgroup=lt.caption=lt.col=lt.thead,lt.th=lt.td,x.fn.extend({text:function(e){return x.access(this,function(e){return e===undefined?x.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=ct(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=ct(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=e?x.filter(e,this):this,i=0;for(;null!=(n=r[i]);i++)t||1!==n.nodeType||x.cleanData(gt(n)),n.parentNode&&(t&&x.contains(n.ownerDocument,n)&&ht(gt(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++)1===e.nodeType&&(x.cleanData(gt(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return x.clone(this,e,t)})},html:function(e){return x.access(this,function(e){var t=this[0]||{},n=0,r=this.length;if(e===undefined&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!rt.test(e)&&!lt[(tt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(et,"<$1>");try{for(;r>n;n++)t=this[n]||{},1===t.nodeType&&(x.cleanData(gt(t,!1)),t.innerHTML=e);t=0}catch(i){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=x.map(this,function(e){return[e.nextSibling,e.parentNode]}),t=0;return this.domManip(arguments,function(n){var r=e[t++],i=e[t++];i&&(x(this).remove(),i.insertBefore(n,r))},!0),t?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t,n){e=p.apply([],e);var r,i,o,s,a,u,l=0,c=this.length,f=this,h=c-1,d=e[0],g=x.isFunction(d);if(g||!(1>=c||"string"!=typeof d||x.support.checkClone)&&ot.test(d))return this.each(function(r){var i=f.eq(r);g&&(e[0]=d.call(this,r,i.html())),i.domManip(e,t,n)});if(c&&(r=x.buildFragment(e,this[0].ownerDocument,!1,!n&&this),i=r.firstChild,1===r.childNodes.length&&(r=i),i)){for(o=x.map(gt(r,"script"),ft),s=o.length;c>l;l++)a=r,l!==h&&(a=x.clone(a,!0,!0),s&&x.merge(o,gt(a,"script"))),t.call(this[l],a,l);if(s)for(u=o[o.length-1].ownerDocument,x.map(o,pt),l=0;s>l;l++)a=o[l],st.test(a.type||"")&&!q.access(a,"globalEval")&&x.contains(u,a)&&(a.src?x._evalUrl(a.src):x.globalEval(a.textContent.replace(ut,"")))}return this}}),x.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){x.fn[e]=function(e){var n,r=[],i=x(e),o=i.length-1,s=0;for(;o>=s;s++)n=s===o?this:this.clone(!0),x(i[s])[t](n),h.apply(r,n.get());return this.pushStack(r)}}),x.extend({clone:function(e,t,n){var r,i,o,s,a=e.cloneNode(!0),u=x.contains(e.ownerDocument,e);if(!(x.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||x.isXMLDoc(e)))for(s=gt(a),o=gt(e),r=0,i=o.length;i>r;r++)mt(o[r],s[r]);if(t)if(n)for(o=o||gt(e),s=s||gt(a),r=0,i=o.length;i>r;r++)dt(o[r],s[r]);else dt(e,a);return s=gt(a,"script"),s.length>0&&ht(s,!u&>(e,"script")),a},buildFragment:function(e,t,n,r){var i,o,s,a,u,l,c=0,f=e.length,p=t.createDocumentFragment(),h=[];for(;f>c;c++)if(i=e[c],i||0===i)if("object"===x.type(i))x.merge(h,i.nodeType?[i]:i);else if(nt.test(i)){o=o||p.appendChild(t.createElement("div")),s=(tt.exec(i)||["",""])[1].toLowerCase(),a=lt[s]||lt._default,o.innerHTML=a[1]+i.replace(et,"<$1>")+a[2],l=a[0];while(l--)o=o.firstChild;x.merge(h,o.childNodes),o=p.firstChild,o.textContent=""}else h.push(t.createTextNode(i));p.textContent="",c=0;while(i=h[c++])if((!r||-1===x.inArray(i,r))&&(u=x.contains(i.ownerDocument,i),o=gt(p.appendChild(i),"script"),u&&ht(o),n)){l=0;while(i=o[l++])st.test(i.type||"")&&n.push(i)}return p},cleanData:function(e){var t,n,r,i=e.length,o=0,s=x.event.special;for(;i>o;o++){if(n=e[o],x.acceptData(n)&&(t=q.access(n)))for(r in t.events)s[r]?x.event.remove(n,r):x.removeEvent(n,r,t.handle);L.discard(n),q.discard(n)}},_evalUrl:function(e){return x.ajax({url:e,type:"GET",dataType:"text",async:!1,global:!1,success:x.globalEval})}});function ct(e,t){return x.nodeName(e,"table")&&x.nodeName(1===t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function ft(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function pt(e){var t=at.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function ht(e,t){var n=e.length,r=0;for(;n>r;r++)q.set(e[r],"globalEval",!t||q.get(t[r],"globalEval"))}function dt(e,t){var n,r,i,o,s,a,u,l;if(1===t.nodeType){if(q.hasData(e)&&(o=q.access(e),s=x.extend({},o),l=o.events,q.set(t,s),l)){delete s.handle,s.events={};for(i in l)for(n=0,r=l[i].length;r>n;n++)x.event.add(t,i,l[i][n])}L.hasData(e)&&(a=L.access(e),u=x.extend({},a),L.set(t,u))}}function gt(e,t){var n=e.getElementsByTagName?e.getElementsByTagName(t||"*"):e.querySelectorAll?e.querySelectorAll(t||"*"):[];return t===undefined||t&&x.nodeName(e,t)?x.merge([e],n):n}function mt(e,t){var n=t.nodeName.toLowerCase();"input"===n&&it.test(e.type)?t.checked=e.checked:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}x.fn.extend({wrapAll:function(e){var t;return x.isFunction(e)?this.each(function(t){x(this).wrapAll(e.call(this,t))}):(this[0]&&(t=x(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstElementChild)e=e.firstElementChild;return e}).append(this)),this)},wrapInner:function(e){return x.isFunction(e)?this.each(function(t){x(this).wrapInner(e.call(this,t))}):this.each(function(){var t=x(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=x.isFunction(e);return this.each(function(n){x(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){x.nodeName(this,"body")||x(this).replaceWith(this.childNodes)}).end()}});var yt,vt,xt=/^(none|table(?!-c[ea]).+)/,bt=/^margin/,wt=RegExp("^("+b+")(.*)$","i"),Tt=RegExp("^("+b+")(?!px)[a-z%]+$","i"),Ct=RegExp("^([+-])=("+b+")","i"),kt={BODY:"block"},Nt={position:"absolute",visibility:"hidden",display:"block"},Et={letterSpacing:0,fontWeight:400},St=["Top","Right","Bottom","Left"],jt=["Webkit","O","Moz","ms"];function Dt(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=jt.length;while(i--)if(t=jt[i]+n,t in e)return t;return r}function At(e,t){return e=t||e,"none"===x.css(e,"display")||!x.contains(e.ownerDocument,e)}function Lt(t){return e.getComputedStyle(t,null)}function qt(e,t){var n,r,i,o=[],s=0,a=e.length;for(;a>s;s++)r=e[s],r.style&&(o[s]=q.get(r,"olddisplay"),n=r.style.display,t?(o[s]||"none"!==n||(r.style.display=""),""===r.style.display&&At(r)&&(o[s]=q.access(r,"olddisplay",Pt(r.nodeName)))):o[s]||(i=At(r),(n&&"none"!==n||!i)&&q.set(r,"olddisplay",i?n:x.css(r,"display"))));for(s=0;a>s;s++)r=e[s],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[s]||"":"none"));return e}x.fn.extend({css:function(e,t){return x.access(this,function(e,t,n){var r,i,o={},s=0;if(x.isArray(t)){for(r=Lt(e),i=t.length;i>s;s++)o[t[s]]=x.css(e,t[s],!1,r);return o}return n!==undefined?x.style(e,t,n):x.css(e,t)},e,t,arguments.length>1)},show:function(){return qt(this,!0)},hide:function(){return qt(this)},toggle:function(e){var t="boolean"==typeof e;return this.each(function(){(t?e:At(this))?x(this).show():x(this).hide()})}}),x.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=yt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,s,a=x.camelCase(t),u=e.style;return t=x.cssProps[a]||(x.cssProps[a]=Dt(u,a)),s=x.cssHooks[t]||x.cssHooks[a],n===undefined?s&&"get"in s&&(i=s.get(e,!1,r))!==undefined?i:u[t]:(o=typeof n,"string"===o&&(i=Ct.exec(n))&&(n=(i[1]+1)*i[2]+parseFloat(x.css(e,t)),o="number"),null==n||"number"===o&&isNaN(n)||("number"!==o||x.cssNumber[a]||(n+="px"),x.support.clearCloneStyle||""!==n||0!==t.indexOf("background")||(u[t]="inherit"),s&&"set"in s&&(n=s.set(e,n,r))===undefined||(u[t]=n)),undefined)}},css:function(e,t,n,r){var i,o,s,a=x.camelCase(t);return t=x.cssProps[a]||(x.cssProps[a]=Dt(e.style,a)),s=x.cssHooks[t]||x.cssHooks[a],s&&"get"in s&&(i=s.get(e,!0,n)),i===undefined&&(i=yt(e,t,r)),"normal"===i&&t in Et&&(i=Et[t]),""===n||n?(o=parseFloat(i),n===!0||x.isNumeric(o)?o||0:i):i}}),yt=function(e,t,n){var r,i,o,s=n||Lt(e),a=s?s.getPropertyValue(t)||s[t]:undefined,u=e.style;return s&&(""!==a||x.contains(e.ownerDocument,e)||(a=x.style(e,t)),Tt.test(a)&&bt.test(t)&&(r=u.width,i=u.minWidth,o=u.maxWidth,u.minWidth=u.maxWidth=u.width=a,a=s.width,u.width=r,u.minWidth=i,u.maxWidth=o)),a};function Ht(e,t,n){var r=wt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function Ot(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,s=0;for(;4>o;o+=2)"margin"===n&&(s+=x.css(e,n+St[o],!0,i)),r?("content"===n&&(s-=x.css(e,"padding"+St[o],!0,i)),"margin"!==n&&(s-=x.css(e,"border"+St[o]+"Width",!0,i))):(s+=x.css(e,"padding"+St[o],!0,i),"padding"!==n&&(s+=x.css(e,"border"+St[o]+"Width",!0,i)));return s}function Ft(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Lt(e),s=x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=yt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Tt.test(i))return i;r=s&&(x.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+Ot(e,t,n||(s?"border":"content"),r,o)+"px"}function Pt(e){var t=o,n=kt[e];return n||(n=Rt(e,t),"none"!==n&&n||(vt=(vt||x(" - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_log4jmonitor/src/main/resources/static/resources/jquery/jquery-1.11.3.min.js b/jun_springboot_plugin/springboot_log4jmonitor/src/main/resources/static/resources/jquery/jquery-1.11.3.min.js deleted file mode 100644 index 60f1f60461..0000000000 --- a/jun_springboot_plugin/springboot_log4jmonitor/src/main/resources/static/resources/jquery/jquery-1.11.3.min.js +++ /dev/null @@ -1,26 +0,0 @@ -/*! - * jQuery JavaScript Library v1.11.3 - * http://jquery.com/ - * - * Includes Sizzle.js - * http://sizzlejs.com/ - * - * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors - * Released under the MIT license - * http://jquery.org/license - * - * Date: 2015-04-28T16:19Z - */ -!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){function c(a){var b="length"in a&&a.length,c=ea.type(a);return"function"===c||ea.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}function d(a,b,c){if(ea.isFunction(b))return ea.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return ea.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(ma.test(b))return ea.filter(b,a,c);b=ea.filter(b,a)}return ea.grep(a,function(a){return ea.inArray(a,b)>=0!==c})}function e(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}function f(a){var b=ua[a]={};return ea.each(a.match(ta)||[],function(a,c){b[c]=!0}),b}function g(){oa.addEventListener?(oa.removeEventListener("DOMContentLoaded",h,!1),a.removeEventListener("load",h,!1)):(oa.detachEvent("onreadystatechange",h),a.detachEvent("onload",h))}function h(){(oa.addEventListener||"load"===event.type||"complete"===oa.readyState)&&(g(),ea.ready())}function i(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(za,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:ya.test(c)?ea.parseJSON(c):c}catch(e){}ea.data(a,b,c)}else c=void 0}return c}function j(a){var b;for(b in a)if(("data"!==b||!ea.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function k(a,b,c,d){if(ea.acceptData(a)){var e,f,g=ea.expando,h=a.nodeType,i=h?ea.cache:a,j=h?a[g]:a[g]&&g;if(j&&i[j]&&(d||i[j].data)||void 0!==c||"string"!=typeof b)return j||(j=h?a[g]=W.pop()||ea.guid++:g),i[j]||(i[j]=h?{}:{toJSON:ea.noop}),("object"==typeof b||"function"==typeof b)&&(d?i[j]=ea.extend(i[j],b):i[j].data=ea.extend(i[j].data,b)),f=i[j],d||(f.data||(f.data={}),f=f.data),void 0!==c&&(f[ea.camelCase(b)]=c),"string"==typeof b?(e=f[b],null==e&&(e=f[ea.camelCase(b)])):e=f,e}}function l(a,b,c){if(ea.acceptData(a)){var d,e,f=a.nodeType,g=f?ea.cache:a,h=f?a[ea.expando]:ea.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){ea.isArray(b)?b=b.concat(ea.map(b,ea.camelCase)):b in d?b=[b]:(b=ea.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;for(;e--;)delete d[b[e]];if(c?!j(d):!ea.isEmptyObject(d))return}(c||(delete g[h].data,j(g[h])))&&(f?ea.cleanData([a],!0):ca.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}function m(){return!0}function n(){return!1}function o(){try{return oa.activeElement}catch(a){}}function p(a){var b=Ka.split("|"),c=a.createDocumentFragment();if(c.createElement)for(;b.length;)c.createElement(b.pop());return c}function q(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==xa?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==xa?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||ea.nodeName(d,b)?f.push(d):ea.merge(f,q(d,b));return void 0===b||b&&ea.nodeName(a,b)?ea.merge([a],f):f}function r(a){Ea.test(a.type)&&(a.defaultChecked=a.checked)}function s(a,b){return ea.nodeName(a,"table")&&ea.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function t(a){return a.type=(null!==ea.find.attr(a,"type"))+"/"+a.type,a}function u(a){var b=Va.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function v(a,b){for(var c,d=0;null!=(c=a[d]);d++)ea._data(c,"globalEval",!b||ea._data(b[d],"globalEval"))}function w(a,b){if(1===b.nodeType&&ea.hasData(a)){var c,d,e,f=ea._data(a),g=ea._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)ea.event.add(b,c,h[c][d])}g.data&&(g.data=ea.extend({},g.data))}}function x(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!ca.noCloneEvent&&b[ea.expando]){e=ea._data(b);for(d in e.events)ea.removeEvent(b,d,e.handle);b.removeAttribute(ea.expando)}"script"===c&&b.text!==a.text?(t(b).text=a.text,u(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),ca.html5Clone&&a.innerHTML&&!ea.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&Ea.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}function y(b,c){var d,e=ea(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:ea.css(e[0],"display");return e.detach(),f}function z(a){var b=oa,c=_a[a];return c||(c=y(a,b),"none"!==c&&c||($a=($a||ea(" - - - -
    - Copyright © 2014-2018 爪哇笔记. All rights - reserved. -
    - - -
    - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_quartz/src/main/resources/templates/task/add.html b/jun_springboot_plugin/springboot_quartz/src/main/resources/templates/task/add.html deleted file mode 100644 index 7bd6ca5626..0000000000 --- a/jun_springboot_plugin/springboot_quartz/src/main/resources/templates/task/add.html +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - - - 任务首页 - 科帮网 - - - - - - - - - - -
    - -
    - - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_quartz/src/main/resources/templates/task/cron.html b/jun_springboot_plugin/springboot_quartz/src/main/resources/templates/task/cron.html deleted file mode 100644 index 288a63e2f0..0000000000 --- a/jun_springboot_plugin/springboot_quartz/src/main/resources/templates/task/cron.html +++ /dev/null @@ -1,771 +0,0 @@ - - - - - Cron Generator - - - - - - - - - - - - -
    -
    -
    -
    -

    生成器

    -
    -
    - - -
    -
    - -

      -   每秒

    - - -
    -

    - -

    -
    -
    - -    周期  从 - - - 秒 -
    -
    -
    -
    - 到 - - - - - 秒 -
    -
    -
    -

    -
    - - -
    -

    - -

    -
    -
    - -    循环  从 - - - 秒 开始 -
    -
    - -
    -
    - 每 - - - - - 秒 执行一次 -
    -
    -
    -

    -
    - - -
    -

       自定义 - -

    -
    - -
    -
    -

    -
    -
    - - -
    -

      -   每分

    - - -
    -

    - -

    -
    -
    - -    周期  从 - - - 分 -
    -
    -
    -
    - 到 - - - - - 分 -
    -
    -
    -

    -
    - - -
    -

    - -

    -
    -
    - -    循环  从 - - - 分 开始 -
    -
    - -
    -
    - 每 - - - - - 分 执行一次 -
    -
    -
    -

    -
    - -
    -

       自定义 - -

    -
    - -
    -
    -

    -
    -
    - -
    - -

      -   每时

    - - -
    -

    - -

    -
    -
    - -    周期  从 - - - 时 -
    -
    -
    -
    - 到 - - - - - 时 -
    -
    -
    -

    -
    - - -
    -

    - -

    -
    -
    - -    循环  从 - - - 时 开始 -
    -
    - -
    -
    - 每 - - - - - 时 执行一次 -
    -
    -
    -

    -
    - -
    -

       自定义 - -

    -
    - -
    -
    -

    -
    - -
    - -
    -

      -   每日

    - -

      -   不指定(指定周时,日 需设置为不指定)

    - -

      -   月最后一日

    - - -
    -

    - -

    -
    -
    - -    周期  从 - - - 日 -
    -
    -
    -
    - 到 - - - - - 日 -
    -
    -
    -

    -
    - - -
    -

    - -

    -
    -
    - -    循环  从 - - - 日 开始 -
    -
    - -
    -
    - 每 - - - - - 日 执行一次 -
    -
    -
    -

    -
    - -
    -

    - -

    -
    -
    - -    每月  离 - - - 日 最近工作日 -
    -
    - -
    -

    -
    - -
    -

       自定义 - -

    -
    - -
    -
    -

    -
    - -
    - -
    - -

      -   每月

    - - -
    -

    - -

    -
    -
    - -    周期  从 - - - 月 -
    -
    -
    -
    - 到 - - - - - 月 -
    -
    -
    -

    -
    - - -
    -

    - -

    -
    -
    - -    循环  从 - - - 月 开始 -
    -
    - -
    -
    - 每 - - - - - 月 执行一次 -
    -
    -
    -

    -
    - -
    -

       自定义 - -

    -
    - -
    -
    -

    -
    - -
    - - -
    -

      -   不指定

    - - -
    -

       自定义 - -

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

    -
    -
    -
    -

      -   每周

    - -

      -   不指定(指定日时,周 需设置为不指定)

    - - -
    -

    - -

    -
    -
    - -    周期  从周 - - - -
    -
    -
    -
    - 到周 - - - - - -
    -
    -
    -

    -
    - - -
    -

    - -

    -
    -
    - -    循环  从周 - - - 开始 -
    -
    - -
    -
    - 每隔 - - - - - 天执行一次 - -
    -
    -
    -

    -
    - - -
    -

    - -

    -
    -
    - -    指定       第 - - - 周的 -
    -
    - -
    -
    -      周 - - - - - -
    -
    -
    -

    -
    - -
    -

    - -

    -
    -
    - -    本月最后一个周 - - - -
    -
    - -
    -

    -
    - -
    -

       自定义 - -

    -
    - -
    -
    -

    -
    -
    -
    -

      -   不指定

    -

      -   每年

    - - -
    -

    - -

    -
    -
    - -    周期  从 - - - -
    -
    -
    -
    - 到 - - - - - -
    -
    -
    -

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

    表达式结果

    -
    - -
    -
    - - - - - - - - - - - - - - - - - - - - - - - - - -
    *****?
    - -
    - -
    -
    -
    - Cron表达式: -
    -
    - - -
    - -
    -
    -
    -
    - -
    -
    -
    -
    - - diff --git a/jun_springboot_plugin/springboot_quartz/src/main/resources/templates/task/index.html b/jun_springboot_plugin/springboot_quartz/src/main/resources/templates/task/index.html deleted file mode 100644 index f607cb0575..0000000000 --- a/jun_springboot_plugin/springboot_quartz/src/main/resources/templates/task/index.html +++ /dev/null @@ -1,293 +0,0 @@ - - - - - - - 任务首页 - 科帮网 - - - - - - - - - - - -
    -
    - - 搜索 - 清空 - 新增 -
    -
    - -
    -
    - - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_quartz/src/main/webapp/WEB-INF/web.xml b/jun_springboot_plugin/springboot_quartz/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 9f88c1f963..0000000000 --- a/jun_springboot_plugin/springboot_quartz/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - Archetype Created Web Application - diff --git a/jun_springboot_plugin/springboot_quartz/src/main/webapp/index.jsp b/jun_springboot_plugin/springboot_quartz/src/main/webapp/index.jsp deleted file mode 100644 index c38169bb95..0000000000 --- a/jun_springboot_plugin/springboot_quartz/src/main/webapp/index.jsp +++ /dev/null @@ -1,5 +0,0 @@ - - -

    Hello World!

    - - diff --git a/jun_springboot_plugin/springboot_ratelimit_guava/README.md b/jun_springboot_plugin/springboot_ratelimit_guava/README.md deleted file mode 100644 index ba8dbcb520..0000000000 --- a/jun_springboot_plugin/springboot_ratelimit_guava/README.md +++ /dev/null @@ -1,218 +0,0 @@ -# spring-boot-demo-ratelimit-guava - -> 此 demo 主要演示了 Spring Boot 项目如何通过 AOP 结合 Guava 的 RateLimiter 实现限流,旨在保护 API 被恶意频繁访问的问题。 - -## 1. 主要代码 - -### 1.1. pom.xml - -```xml - - - 4.0.0 - - spring-boot-demo-ratelimit-guava - 1.0.0-SNAPSHOT - jar - - spring-boot-demo-ratelimit-guava - Demo project for Spring Boot - - - io.github.wujun728 - spring-boot-demo - 1.0.0-SNAPSHOT - - - - UTF-8 - UTF-8 - 1.8 - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-aop - - - - cn.hutool - hutool-all - - - - com.google.guava - guava - - - - org.springframework.boot - spring-boot-starter-test - test - - - - org.projectlombok - lombok - true - - - - - spring-boot-demo-ratelimit-guava - - - org.springframework.boot - spring-boot-maven-plugin - - - - - -``` - -### 1.2. 定义一个限流注解 `RateLimiter.java` - -> 注意代码里使用了 `AliasFor` 设置一组属性的别名,所以获取注解的时候,需要通过 `Spring` 提供的注解工具类 `AnnotationUtils` 获取,不可以通过 `AOP` 参数注入的方式获取,否则有些属性的值将会设置不进去。 - -```java -/** - *

    - * 限流注解,添加了 {@link AliasFor} 必须通过 {@link AnnotationUtils} 获取,才会生效 - * - * @author yangkai.shen - * @date Created in 2019/9/12 14:14 - * @see AnnotationUtils - *

    - */ -@Target(ElementType.METHOD) -@Retention(RetentionPolicy.RUNTIME) -@Documented -public @interface RateLimiter { - int NOT_LIMITED = 0; - - /** - * qps - */ - @AliasFor("qps") double value() default NOT_LIMITED; - - /** - * qps - */ - @AliasFor("value") double qps() default NOT_LIMITED; - - /** - * 超时时长 - */ - int timeout() default 0; - - /** - * 超时时间单位 - */ - TimeUnit timeUnit() default TimeUnit.MILLISECONDS; -} -``` - -### 1.3. 定义一个切面 `RateLimiterAspect.java` - -```java -/** - *

    - * 限流切面 - *

    - * - * @author yangkai.shen - * @date Created in 2019/9/12 14:27 - */ -@Slf4j -@Aspect -@Component -public class RateLimiterAspect { - private static final ConcurrentMap RATE_LIMITER_CACHE = new ConcurrentHashMap<>(); - - @Pointcut("@annotation(com.jun.plugin.ratelimit.guava.annotation.RateLimiter)") - public void rateLimit() { - - } - - @Around("rateLimit()") - public Object pointcut(ProceedingJoinPoint point) throws Throwable { - MethodSignature signature = (MethodSignature) point.getSignature(); - Method method = signature.getMethod(); - // 通过 AnnotationUtils.findAnnotation 获取 RateLimiter 注解 - RateLimiter rateLimiter = AnnotationUtils.findAnnotation(method, RateLimiter.class); - if (rateLimiter != null && rateLimiter.qps() > RateLimiter.NOT_LIMITED) { - double qps = rateLimiter.qps(); - if (RATE_LIMITER_CACHE.get(method.getName()) == null) { - // 初始化 QPS - RATE_LIMITER_CACHE.put(method.getName(), com.google.common.util.concurrent.RateLimiter.create(qps)); - } - - log.debug("【{}】的QPS设置为: {}", method.getName(), RATE_LIMITER_CACHE.get(method.getName()).getRate()); - // 尝试获取令牌 - if (RATE_LIMITER_CACHE.get(method.getName()) != null && !RATE_LIMITER_CACHE.get(method.getName()).tryAcquire(rateLimiter.timeout(), rateLimiter.timeUnit())) { - throw new RuntimeException("手速太快了,慢点儿吧~"); - } - } - return point.proceed(); - } -} -``` - -### 1.4. 定义两个API接口用于测试限流 - -```java -/** - *

    - * 测试 - *

    - * - * @author yangkai.shen - * @date Created in 2019/9/12 14:22 - */ -@Slf4j -@RestController -public class TestController { - - @RateLimiter(value = 1.0, timeout = 300) - @GetMapping("/test1") - public Dict test1() { - log.info("【test1】被执行了。。。。。"); - return Dict.create().set("msg", "hello,world!").set("description", "别想一直看到我,不信你快速刷新看看~"); - } - - @GetMapping("/test2") - public Dict test2() { - log.info("【test2】被执行了。。。。。"); - return Dict.create().set("msg", "hello,world!").set("description", "我一直都在,卟离卟弃"); - } -} -``` - -## 2. 测试 - -- test1 接口未被限流的时候 - -image-20190912155209716 - -- test1 接口频繁刷新,触发限流的时候 - -image-20190912155229745 - -- test2 接口不做限流,可以一直刷新 - -image-20190912155146012 - -## 3. 参考 - -- [限流原理解读之guava中的RateLimiter](https://juejin.im/post/5bb48d7b5188255c865e31bc) - -- [使用Guava的RateLimiter做限流](https://my.oschina.net/hanchao/blog/1833612) - diff --git a/jun_springboot_plugin/springboot_ratelimit_guava/assets/image-20190912155146012.png b/jun_springboot_plugin/springboot_ratelimit_guava/assets/image-20190912155146012.png deleted file mode 100644 index e7c4eb1ff4..0000000000 Binary files a/jun_springboot_plugin/springboot_ratelimit_guava/assets/image-20190912155146012.png and /dev/null differ diff --git a/jun_springboot_plugin/springboot_ratelimit_guava/assets/image-20190912155209716.png b/jun_springboot_plugin/springboot_ratelimit_guava/assets/image-20190912155209716.png deleted file mode 100644 index 6750365b46..0000000000 Binary files a/jun_springboot_plugin/springboot_ratelimit_guava/assets/image-20190912155209716.png and /dev/null differ diff --git a/jun_springboot_plugin/springboot_ratelimit_guava/assets/image-20190912155229745.png b/jun_springboot_plugin/springboot_ratelimit_guava/assets/image-20190912155229745.png deleted file mode 100644 index 9ddcc71c6d..0000000000 Binary files a/jun_springboot_plugin/springboot_ratelimit_guava/assets/image-20190912155229745.png and /dev/null differ diff --git a/jun_springboot_plugin/springboot_ratelimit_guava/pom.xml b/jun_springboot_plugin/springboot_ratelimit_guava/pom.xml deleted file mode 100644 index a8fd19b918..0000000000 --- a/jun_springboot_plugin/springboot_ratelimit_guava/pom.xml +++ /dev/null @@ -1,71 +0,0 @@ - - - 4.0.0 - - io.github.wujun728 - springboot_ratelimit_guava - 1.0 - jar - - - springboot_ratelimit_guava - Demo project for Spring Boot - - - io.github.wujun728 - jun_springboot_plugin - 1.0 - - - - UTF-8 - UTF-8 - 1.8 - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-aop - - - - cn.hutool - hutool-all - - - - com.google.guava - guava - - - - org.springframework.boot - spring-boot-starter-test - test - - - - org.projectlombok - lombok - true - - - - - springboot_ratelimit_guava - - - org.springframework.boot - spring-boot-maven-plugin - - - - - diff --git a/jun_springboot_plugin/springboot_ratelimit_guava/src/main/java/com/jun/plugin/ratelimit/guava/SpringBootDemoRatelimitGuavaApplication.java b/jun_springboot_plugin/springboot_ratelimit_guava/src/main/java/com/jun/plugin/ratelimit/guava/SpringBootDemoRatelimitGuavaApplication.java deleted file mode 100644 index afe21a2f05..0000000000 --- a/jun_springboot_plugin/springboot_ratelimit_guava/src/main/java/com/jun/plugin/ratelimit/guava/SpringBootDemoRatelimitGuavaApplication.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jun.plugin.ratelimit.guava; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -/** - *

    - * 启动器 - *

    - * - * @author Wujun - * @date Created in 2019/9/12 14:06 - */ -@SpringBootApplication -public class SpringBootDemoRatelimitGuavaApplication { - - public static void main(String[] args) { - SpringApplication.run(SpringBootDemoRatelimitGuavaApplication.class, args); - } - -} diff --git a/jun_springboot_plugin/springboot_ratelimit_guava/src/main/java/com/jun/plugin/ratelimit/guava/annotation/RateLimiter.java b/jun_springboot_plugin/springboot_ratelimit_guava/src/main/java/com/jun/plugin/ratelimit/guava/annotation/RateLimiter.java deleted file mode 100644 index a235fc54fc..0000000000 --- a/jun_springboot_plugin/springboot_ratelimit_guava/src/main/java/com/jun/plugin/ratelimit/guava/annotation/RateLimiter.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.jun.plugin.ratelimit.guava.annotation; - -import org.springframework.core.annotation.AliasFor; -import org.springframework.core.annotation.AnnotationUtils; - -import java.lang.annotation.*; -import java.util.concurrent.TimeUnit; - -/** - *

    - * 限流注解,添加了 {@link AliasFor} 必须通过 {@link AnnotationUtils} 获取,才会生效 - * - * @author Wujun - * @date Created in 2019/9/12 14:14 - * @see AnnotationUtils - *

    - */ -@Target(ElementType.METHOD) -@Retention(RetentionPolicy.RUNTIME) -@Documented -public @interface RateLimiter { - int NOT_LIMITED = 0; - - /** - * qps - */ - @AliasFor("qps") double value() default NOT_LIMITED; - - /** - * qps - */ - @AliasFor("value") double qps() default NOT_LIMITED; - - /** - * 超时时长 - */ - int timeout() default 0; - - /** - * 超时时间单位 - */ - TimeUnit timeUnit() default TimeUnit.MILLISECONDS; -} diff --git a/jun_springboot_plugin/springboot_ratelimit_guava/src/main/java/com/jun/plugin/ratelimit/guava/aspect/RateLimiterAspect.java b/jun_springboot_plugin/springboot_ratelimit_guava/src/main/java/com/jun/plugin/ratelimit/guava/aspect/RateLimiterAspect.java deleted file mode 100644 index 86aee54bff..0000000000 --- a/jun_springboot_plugin/springboot_ratelimit_guava/src/main/java/com/jun/plugin/ratelimit/guava/aspect/RateLimiterAspect.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.jun.plugin.ratelimit.guava.aspect; - -import lombok.extern.slf4j.Slf4j; -import org.aspectj.lang.ProceedingJoinPoint; -import org.aspectj.lang.annotation.Around; -import org.aspectj.lang.annotation.Aspect; -import org.aspectj.lang.annotation.Pointcut; -import org.aspectj.lang.reflect.MethodSignature; -import org.springframework.core.annotation.AnnotationUtils; -import org.springframework.stereotype.Component; - -import com.jun.plugin.ratelimit.guava.annotation.RateLimiter; - -import java.lang.reflect.Method; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - *

    - * 限流切面 - *

    - * - * @author Wujun - * @date Created in 2019/9/12 14:27 - */ -@Slf4j -@Aspect -@Component -public class RateLimiterAspect { - private static final ConcurrentMap RATE_LIMITER_CACHE = new ConcurrentHashMap<>(); - - @Pointcut("@annotation(com.jun.plugin.ratelimit.guava.annotation.RateLimiter)") - public void rateLimit() { - - } - - @Around("rateLimit()") - public Object pointcut(ProceedingJoinPoint point) throws Throwable { - MethodSignature signature = (MethodSignature) point.getSignature(); - Method method = signature.getMethod(); - // 通过 AnnotationUtils.findAnnotation 获取 RateLimiter 注解 - RateLimiter rateLimiter = AnnotationUtils.findAnnotation(method, RateLimiter.class); - if (rateLimiter != null && rateLimiter.qps() > RateLimiter.NOT_LIMITED) { - double qps = rateLimiter.qps(); - if (RATE_LIMITER_CACHE.get(method.getName()) == null) { - // 初始化 QPS - RATE_LIMITER_CACHE.put(method.getName(), com.google.common.util.concurrent.RateLimiter.create(qps)); - } - - log.debug("【{}】的QPS设置为: {}", method.getName(), RATE_LIMITER_CACHE.get(method.getName()).getRate()); - // 尝试获取令牌 - if (RATE_LIMITER_CACHE.get(method.getName()) != null && !RATE_LIMITER_CACHE.get(method.getName()).tryAcquire(rateLimiter.timeout(), rateLimiter.timeUnit())) { - throw new RuntimeException("手速太快了,慢点儿吧~"); - } - } - return point.proceed(); - } -} diff --git a/jun_springboot_plugin/springboot_ratelimit_guava/src/main/java/com/jun/plugin/ratelimit/guava/controller/TestController.java b/jun_springboot_plugin/springboot_ratelimit_guava/src/main/java/com/jun/plugin/ratelimit/guava/controller/TestController.java deleted file mode 100644 index 556e29d0dc..0000000000 --- a/jun_springboot_plugin/springboot_ratelimit_guava/src/main/java/com/jun/plugin/ratelimit/guava/controller/TestController.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.jun.plugin.ratelimit.guava.controller; - -import cn.hutool.core.lang.Dict; -import lombok.extern.slf4j.Slf4j; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; - -import com.jun.plugin.ratelimit.guava.annotation.RateLimiter; - -/** - *

    - * 测试 - *

    - * - * @author Wujun - * @date Created in 2019/9/12 14:22 - */ -@Slf4j -@RestController -public class TestController { - - @RateLimiter(value = 1.0, timeout = 300) - @GetMapping("/test1") - public Dict test1() { - log.info("【test1】被执行了。。。。。"); - return Dict.create().set("msg", "hello,world!").set("description", "别想一直看到我,不信你快速刷新看看~"); - } - - @GetMapping("/test2") - public Dict test2() { - log.info("【test2】被执行了。。。。。"); - return Dict.create().set("msg", "hello,world!").set("description", "我一直都在,卟离卟弃"); - } - - @RateLimiter(value = 2.0, timeout = 300) - @GetMapping("/test3") - public Dict test3() { - log.info("【test3】被执行了。。。。。"); - return Dict.create().set("msg", "hello,world!").set("description", "别想一直看到我,不信你快速刷新看看~"); - } -} diff --git a/jun_springboot_plugin/springboot_ratelimit_guava/src/main/java/com/jun/plugin/ratelimit/guava/handler/GlobalExceptionHandler.java b/jun_springboot_plugin/springboot_ratelimit_guava/src/main/java/com/jun/plugin/ratelimit/guava/handler/GlobalExceptionHandler.java deleted file mode 100644 index f3b8a0d69f..0000000000 --- a/jun_springboot_plugin/springboot_ratelimit_guava/src/main/java/com/jun/plugin/ratelimit/guava/handler/GlobalExceptionHandler.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.jun.plugin.ratelimit.guava.handler; - -import cn.hutool.core.lang.Dict; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.RestControllerAdvice; - -/** - *

    - * 全局异常拦截 - *

    - * - * @author Wujun - * @date Created in 2019/9/12 15:00 - */ -@RestControllerAdvice -public class GlobalExceptionHandler { - - @ExceptionHandler(RuntimeException.class) - public Dict handler(RuntimeException ex) { - return Dict.create().set("msg", ex.getMessage()); - } -} diff --git a/jun_springboot_plugin/springboot_ratelimit_guava/src/main/resources/application.yml b/jun_springboot_plugin/springboot_ratelimit_guava/src/main/resources/application.yml deleted file mode 100644 index 36fed1b10e..0000000000 --- a/jun_springboot_plugin/springboot_ratelimit_guava/src/main/resources/application.yml +++ /dev/null @@ -1,7 +0,0 @@ -server: - port: 8080 - servlet: - context-path: /demo -logging: - level: - com.xkcoding: debug diff --git a/jun_springboot_plugin/springboot_ratelimit_guava/src/test/java/com/jun/plugin/ratelimit/guava/SpringBootDemoRatelimitGuavaApplicationTests.java b/jun_springboot_plugin/springboot_ratelimit_guava/src/test/java/com/jun/plugin/ratelimit/guava/SpringBootDemoRatelimitGuavaApplicationTests.java deleted file mode 100644 index bdadbf2c70..0000000000 --- a/jun_springboot_plugin/springboot_ratelimit_guava/src/test/java/com/jun/plugin/ratelimit/guava/SpringBootDemoRatelimitGuavaApplicationTests.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.jun.plugin.ratelimit.guava; - -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 SpringBootDemoRatelimitGuavaApplicationTests { - - @Test - public void contextLoads() { - } - -} diff --git a/jun_springboot_plugin/springboot_ratelimit_redis/README.md b/jun_springboot_plugin/springboot_ratelimit_redis/README.md deleted file mode 100644 index 029b92713b..0000000000 --- a/jun_springboot_plugin/springboot_ratelimit_redis/README.md +++ /dev/null @@ -1,296 +0,0 @@ -# spring-boot-demo-ratelimit-redis - -> 此 demo 主要演示了 Spring Boot 项目如何通过 AOP 结合 Redis + Lua 脚本实现分布式限流,旨在保护 API 被恶意频繁访问的问题,是 `spring-boot-demo-ratelimit-guava` 的升级版。 - -## 1. 主要代码 - -### 1.1. pom.xml - -```xml - - - 4.0.0 - - spring-boot-demo-ratelimit-redis - 1.0.0-SNAPSHOT - jar - - spring-boot-demo-ratelimit-redis - Demo project for Spring Boot - - - io.github.wujun728 - spring-boot-demo - 1.0.0-SNAPSHOT - - - - UTF-8 - UTF-8 - 1.8 - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-aop - - - - org.springframework.boot - spring-boot-starter-data-redis - - - - - org.apache.commons - commons-pool2 - - - - cn.hutool - hutool-all - - - - org.springframework.boot - spring-boot-starter-test - test - - - - org.projectlombok - lombok - true - - - - - spring-boot-demo-ratelimit-redis - - - org.springframework.boot - spring-boot-maven-plugin - - - - - -``` - -### 1.2. 限流注解 - -```java -/** - *

    - * 限流注解,添加了 {@link AliasFor} 必须通过 {@link AnnotationUtils} 获取,才会生效 - *

    - * - * @author yangkai.shen - * @date Created in 2019/9/30 10:31 - * @see AnnotationUtils - */ -@Target(ElementType.METHOD) -@Retention(RetentionPolicy.RUNTIME) -@Documented -public @interface RateLimiter { - long DEFAULT_REQUEST = 10; - - /** - * max 最大请求数 - */ - @AliasFor("max") long value() default DEFAULT_REQUEST; - - /** - * max 最大请求数 - */ - @AliasFor("value") long max() default DEFAULT_REQUEST; - - /** - * 限流key - */ - String key() default ""; - - /** - * 超时时长,默认1分钟 - */ - long timeout() default 1; - - /** - * 超时时间单位,默认 分钟 - */ - TimeUnit timeUnit() default TimeUnit.MINUTES; -} -``` - -### 1.3. AOP处理限流 - -```java -/** - *

    - * 限流切面 - *

    - * - * @author yangkai.shen - * @date Created in 2019/9/30 10:30 - */ -@Slf4j -@Aspect -@Component -@RequiredArgsConstructor(onConstructor_ = @Autowired) -public class RateLimiterAspect { - private final static String SEPARATOR = ":"; - private final static String REDIS_LIMIT_KEY_PREFIX = "limit:"; - private final StringRedisTemplate stringRedisTemplate; - private final RedisScript limitRedisScript; - - @Pointcut("@annotation(com.jun.plugin.ratelimit.redis.annotation.RateLimiter)") - public void rateLimit() { - - } - - @Around("rateLimit()") - public Object pointcut(ProceedingJoinPoint point) throws Throwable { - MethodSignature signature = (MethodSignature) point.getSignature(); - Method method = signature.getMethod(); - // 通过 AnnotationUtils.findAnnotation 获取 RateLimiter 注解 - RateLimiter rateLimiter = AnnotationUtils.findAnnotation(method, RateLimiter.class); - if (rateLimiter != null) { - String key = rateLimiter.key(); - // 默认用类名+方法名做限流的 key 前缀 - if (StrUtil.isBlank(key)) { - key = method.getDeclaringClass().getName()+StrUtil.DOT+method.getName(); - } - // 最终限流的 key 为 前缀 + IP地址 - // TODO: 此时需要考虑局域网多用户访问的情况,因此 key 后续需要加上方法参数更加合理 - key = key + SEPARATOR + IpUtil.getIpAddr(); - - long max = rateLimiter.max(); - long timeout = rateLimiter.timeout(); - TimeUnit timeUnit = rateLimiter.timeUnit(); - boolean limited = shouldLimited(key, max, timeout, timeUnit); - if (limited) { - throw new RuntimeException("手速太快了,慢点儿吧~"); - } - } - - return point.proceed(); - } - - private boolean shouldLimited(String key, long max, long timeout, TimeUnit timeUnit) { - // 最终的 key 格式为: - // limit:自定义key:IP - // limit:类名.方法名:IP - key = REDIS_LIMIT_KEY_PREFIX + key; - // 统一使用单位毫秒 - long ttl = timeUnit.toMillis(timeout); - // 当前时间毫秒数 - long now = Instant.now().toEpochMilli(); - long expired = now - ttl; - // 注意这里必须转为 String,否则会报错 java.lang.Long cannot be cast to java.lang.String - Long executeTimes = stringRedisTemplate.execute(limitRedisScript, Collections.singletonList(key), now + "", ttl + "", expired + "", max + ""); - if (executeTimes != null) { - if (executeTimes == 0) { - log.error("【{}】在单位时间 {} 毫秒内已达到访问上限,当前接口上限 {}", key, ttl, max); - return true; - } else { - log.info("【{}】在单位时间 {} 毫秒内访问 {} 次", key, ttl, executeTimes); - return false; - } - } - return false; - } -} -``` - -### 1.4. lua 脚本 - -```lua --- 下标从 1 开始 -local key = KEYS[1] -local now = tonumber(ARGV[1]) -local ttl = tonumber(ARGV[2]) -local expired = tonumber(ARGV[3]) --- 最大访问量 -local max = tonumber(ARGV[4]) - --- 清除过期的数据 --- 移除指定分数区间内的所有元素,expired 即已经过期的 score --- 根据当前时间毫秒数 - 超时毫秒数,得到过期时间 expired -redis.call('zremrangebyscore', key, 0, expired) - --- 获取 zset 中的当前元素个数 -local current = tonumber(redis.call('zcard', key)) -local next = current + 1 - -if next > max then - -- 达到限流大小 返回 0 - return 0; -else - -- 往 zset 中添加一个值、得分均为当前时间戳的元素,[value,score] - redis.call("zadd", key, now, now) - -- 每次访问均重新设置 zset 的过期时间,单位毫秒 - redis.call("pexpire", key, ttl) - return next -end -``` - -### 1.5. 接口测试 - -```java -/** - *

    - * 测试 - *

    - * - * @author yangkai.shen - * @date Created in 2019/9/30 10:30 - */ -@Slf4j -@RestController -public class TestController { - - @RateLimiter(value = 5) - @GetMapping("/test1") - public Dict test1() { - log.info("【test1】被执行了。。。。。"); - return Dict.create().set("msg", "hello,world!").set("description", "别想一直看到我,不信你快速刷新看看~"); - } - - @GetMapping("/test2") - public Dict test2() { - log.info("【test2】被执行了。。。。。"); - return Dict.create().set("msg", "hello,world!").set("description", "我一直都在,卟离卟弃"); - } - - @RateLimiter(value = 2, key = "测试自定义key") - @GetMapping("/test3") - public Dict test3() { - log.info("【test3】被执行了。。。。。"); - return Dict.create().set("msg", "hello,world!").set("description", "别想一直看到我,不信你快速刷新看看~"); - } -} -``` - -### 1.6. 其余代码参见 demo - -## 2. 测试 - -- 触发限流时控制台打印 - -![image-20190930155856711](assets/image-20190930155856711.png) - -- 触发限流的时候 Redis 的数据 - -![image-20190930155735300](assets/image-20190930155735300.png) - -## 3. 参考 - -- [mica-plus-redis 的分布式限流实现](https://github.com/lets-mica/mica/tree/master/mica-plus-redis) -- [Java并发:分布式应用限流 Redis + Lua 实践](https://segmentfault.com/a/1190000016042927) diff --git a/jun_springboot_plugin/springboot_ratelimit_redis/assets/image-20190930155735300.png b/jun_springboot_plugin/springboot_ratelimit_redis/assets/image-20190930155735300.png deleted file mode 100644 index 2018be762e..0000000000 Binary files a/jun_springboot_plugin/springboot_ratelimit_redis/assets/image-20190930155735300.png and /dev/null differ diff --git a/jun_springboot_plugin/springboot_ratelimit_redis/assets/image-20190930155856711.png b/jun_springboot_plugin/springboot_ratelimit_redis/assets/image-20190930155856711.png deleted file mode 100644 index 31f2f6f5d0..0000000000 Binary files a/jun_springboot_plugin/springboot_ratelimit_redis/assets/image-20190930155856711.png and /dev/null differ diff --git a/jun_springboot_plugin/springboot_ratelimit_redis/pom.xml b/jun_springboot_plugin/springboot_ratelimit_redis/pom.xml deleted file mode 100644 index 4492e75117..0000000000 --- a/jun_springboot_plugin/springboot_ratelimit_redis/pom.xml +++ /dev/null @@ -1,76 +0,0 @@ - - - 4.0.0 - - io.github.wujun728 - springboot_ratelimit_redis - 1.0 - jar - - springboot_ratelimit_redis - Demo project for Spring Boot - - - io.github.wujun728 - jun_springboot_plugin - 1.0 - - - - UTF-8 - UTF-8 - 1.8 - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-aop - - - - org.springframework.boot - spring-boot-starter-data-redis - - - - - org.apache.commons - commons-pool2 - - - - cn.hutool - hutool-all - - - - org.springframework.boot - spring-boot-starter-test - test - - - - org.projectlombok - lombok - true - - - - - springboot_ratelimit_redis - - - org.springframework.boot - spring-boot-maven-plugin - - - - - diff --git a/jun_springboot_plugin/springboot_ratelimit_redis/src/main/java/com/jun/plugin/ratelimit/redis/SpringBootDemoRatelimitRedisApplication.java b/jun_springboot_plugin/springboot_ratelimit_redis/src/main/java/com/jun/plugin/ratelimit/redis/SpringBootDemoRatelimitRedisApplication.java deleted file mode 100644 index 6e35bd48f2..0000000000 --- a/jun_springboot_plugin/springboot_ratelimit_redis/src/main/java/com/jun/plugin/ratelimit/redis/SpringBootDemoRatelimitRedisApplication.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jun.plugin.ratelimit.redis; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -/** - *

    - * 启动器 - *

    - * - * @author Wujun - * @date Created in 2019/9/30 09:32 - */ -@SpringBootApplication -public class SpringBootDemoRatelimitRedisApplication { - - public static void main(String[] args) { - SpringApplication.run(SpringBootDemoRatelimitRedisApplication.class, args); - } - -} diff --git a/jun_springboot_plugin/springboot_ratelimit_redis/src/main/java/com/jun/plugin/ratelimit/redis/annotation/RateLimiter.java b/jun_springboot_plugin/springboot_ratelimit_redis/src/main/java/com/jun/plugin/ratelimit/redis/annotation/RateLimiter.java deleted file mode 100644 index 7ac0fa60be..0000000000 --- a/jun_springboot_plugin/springboot_ratelimit_redis/src/main/java/com/jun/plugin/ratelimit/redis/annotation/RateLimiter.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.jun.plugin.ratelimit.redis.annotation; - -import org.springframework.core.annotation.AliasFor; -import org.springframework.core.annotation.AnnotationUtils; - -import java.lang.annotation.*; -import java.util.concurrent.TimeUnit; - -/** - *

    - * 限流注解,添加了 {@link AliasFor} 必须通过 {@link AnnotationUtils} 获取,才会生效 - *

    - * - * @author Wujun - * @date Created in 2019/9/30 10:31 - * @see AnnotationUtils - */ -@Target(ElementType.METHOD) -@Retention(RetentionPolicy.RUNTIME) -@Documented -public @interface RateLimiter { - long DEFAULT_REQUEST = 10; - - /** - * max 最大请求数 - */ - @AliasFor("max") long value() default DEFAULT_REQUEST; - - /** - * max 最大请求数 - */ - @AliasFor("value") long max() default DEFAULT_REQUEST; - - /** - * 限流key - */ - String key() default ""; - - /** - * 超时时长,默认1分钟 - */ - long timeout() default 1; - - /** - * 超时时间单位,默认 分钟 - */ - TimeUnit timeUnit() default TimeUnit.MINUTES; -} diff --git a/jun_springboot_plugin/springboot_ratelimit_redis/src/main/java/com/jun/plugin/ratelimit/redis/aspect/RateLimiterAspect.java b/jun_springboot_plugin/springboot_ratelimit_redis/src/main/java/com/jun/plugin/ratelimit/redis/aspect/RateLimiterAspect.java deleted file mode 100644 index d31793c18c..0000000000 --- a/jun_springboot_plugin/springboot_ratelimit_redis/src/main/java/com/jun/plugin/ratelimit/redis/aspect/RateLimiterAspect.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.jun.plugin.ratelimit.redis.aspect; - -import cn.hutool.core.util.StrUtil; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.aspectj.lang.ProceedingJoinPoint; -import org.aspectj.lang.annotation.Around; -import org.aspectj.lang.annotation.Aspect; -import org.aspectj.lang.annotation.Pointcut; -import org.aspectj.lang.reflect.MethodSignature; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.annotation.AnnotationUtils; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.data.redis.core.script.RedisScript; -import org.springframework.stereotype.Component; - -import com.jun.plugin.ratelimit.redis.annotation.RateLimiter; -import com.jun.plugin.ratelimit.redis.util.IpUtil; - -import java.lang.reflect.Method; -import java.time.Instant; -import java.util.Collections; -import java.util.concurrent.TimeUnit; - -/** - *

    - * 限流切面 - *

    - * - * @author Wujun - * @date Created in 2019/9/30 10:30 - */ -@Slf4j -@Aspect -@Component -@RequiredArgsConstructor(onConstructor_ = @Autowired) -public class RateLimiterAspect { - private final static String SEPARATOR = ":"; - private final static String REDIS_LIMIT_KEY_PREFIX = "limit:"; - private final StringRedisTemplate stringRedisTemplate; - private final RedisScript limitRedisScript; - - @Pointcut("@annotation(com.jun.plugin.ratelimit.redis.annotation.RateLimiter)") - public void rateLimit() { - - } - - @Around("rateLimit()") - public Object pointcut(ProceedingJoinPoint point) throws Throwable { - MethodSignature signature = (MethodSignature) point.getSignature(); - Method method = signature.getMethod(); - // 通过 AnnotationUtils.findAnnotation 获取 RateLimiter 注解 - RateLimiter rateLimiter = AnnotationUtils.findAnnotation(method, RateLimiter.class); - if (rateLimiter != null) { - String key = rateLimiter.key(); - // 默认用类名+方法名做限流的 key 前缀 - if (StrUtil.isBlank(key)) { - key = method.getDeclaringClass().getName()+StrUtil.DOT+method.getName(); - } - // 最终限流的 key 为 前缀 + IP地址 - // TODO: 此时需要考虑局域网多用户访问的情况,因此 key 后续需要加上方法参数更加合理 - key = key + SEPARATOR + IpUtil.getIpAddr(); - - long max = rateLimiter.max(); - long timeout = rateLimiter.timeout(); - TimeUnit timeUnit = rateLimiter.timeUnit(); - boolean limited = shouldLimited(key, max, timeout, timeUnit); - if (limited) { - throw new RuntimeException("手速太快了,慢点儿吧~"); - } - } - - return point.proceed(); - } - - private boolean shouldLimited(String key, long max, long timeout, TimeUnit timeUnit) { - // 最终的 key 格式为: - // limit:自定义key:IP - // limit:类名.方法名:IP - key = REDIS_LIMIT_KEY_PREFIX + key; - // 统一使用单位毫秒 - long ttl = timeUnit.toMillis(timeout); - // 当前时间毫秒数 - long now = Instant.now().toEpochMilli(); - long expired = now - ttl; - // 注意这里必须转为 String,否则会报错 java.lang.Long cannot be cast to java.lang.String - Long executeTimes = stringRedisTemplate.execute(limitRedisScript, Collections.singletonList(key), now + "", ttl + "", expired + "", max + ""); - if (executeTimes != null) { - if (executeTimes == 0) { - log.error("【{}】在单位时间 {} 毫秒内已达到访问上限,当前接口上限 {}", key, ttl, max); - return true; - } else { - log.info("【{}】在单位时间 {} 毫秒内访问 {} 次", key, ttl, executeTimes); - return false; - } - } - return false; - } -} diff --git a/jun_springboot_plugin/springboot_ratelimit_redis/src/main/java/com/jun/plugin/ratelimit/redis/config/RedisConfig.java b/jun_springboot_plugin/springboot_ratelimit_redis/src/main/java/com/jun/plugin/ratelimit/redis/config/RedisConfig.java deleted file mode 100644 index e807f8f7cd..0000000000 --- a/jun_springboot_plugin/springboot_ratelimit_redis/src/main/java/com/jun/plugin/ratelimit/redis/config/RedisConfig.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.jun.plugin.ratelimit.redis.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.io.ClassPathResource; -import org.springframework.data.redis.core.script.DefaultRedisScript; -import org.springframework.data.redis.core.script.RedisScript; -import org.springframework.scripting.support.ResourceScriptSource; - -/** - *

    - * Redis 配置 - *

    - * - * @author Wujun - * @date Created in 2019/9/30 11:37 - */ -@Configuration -public class RedisConfig { - @Bean - @SuppressWarnings("unchecked") - public RedisScript limitRedisScript() { - DefaultRedisScript redisScript = new DefaultRedisScript<>(); - redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("scripts/redis/limit.lua"))); - redisScript.setResultType(Long.class); - return redisScript; - } -} diff --git a/jun_springboot_plugin/springboot_ratelimit_redis/src/main/java/com/jun/plugin/ratelimit/redis/controller/TestController.java b/jun_springboot_plugin/springboot_ratelimit_redis/src/main/java/com/jun/plugin/ratelimit/redis/controller/TestController.java deleted file mode 100644 index bcbde9fb8b..0000000000 --- a/jun_springboot_plugin/springboot_ratelimit_redis/src/main/java/com/jun/plugin/ratelimit/redis/controller/TestController.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.jun.plugin.ratelimit.redis.controller; - -import cn.hutool.core.lang.Dict; -import lombok.extern.slf4j.Slf4j; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; - -import com.jun.plugin.ratelimit.redis.annotation.RateLimiter; - -/** - *

    - * 测试 - *

    - * - * @author Wujun - * @date Created in 2019/9/30 10:30 - */ -@Slf4j -@RestController -public class TestController { - - @RateLimiter(value = 5) - @GetMapping("/test1") - public Dict test1() { - log.info("【test1】被执行了。。。。。"); - return Dict.create().set("msg", "hello,world!").set("description", "别想一直看到我,不信你快速刷新看看~"); - } - - @GetMapping("/test2") - public Dict test2() { - log.info("【test2】被执行了。。。。。"); - return Dict.create().set("msg", "hello,world!").set("description", "我一直都在,卟离卟弃"); - } - - @RateLimiter(value = 2, key = "测试自定义key") - @GetMapping("/test3") - public Dict test3() { - log.info("【test3】被执行了。。。。。"); - return Dict.create().set("msg", "hello,world!").set("description", "别想一直看到我,不信你快速刷新看看~"); - } -} diff --git a/jun_springboot_plugin/springboot_ratelimit_redis/src/main/java/com/jun/plugin/ratelimit/redis/handler/GlobalExceptionHandler.java b/jun_springboot_plugin/springboot_ratelimit_redis/src/main/java/com/jun/plugin/ratelimit/redis/handler/GlobalExceptionHandler.java deleted file mode 100644 index 671a6e84f1..0000000000 --- a/jun_springboot_plugin/springboot_ratelimit_redis/src/main/java/com/jun/plugin/ratelimit/redis/handler/GlobalExceptionHandler.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.jun.plugin.ratelimit.redis.handler; - -import cn.hutool.core.lang.Dict; -import lombok.extern.slf4j.Slf4j; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.RestControllerAdvice; - -/** - *

    - * 全局异常拦截 - *

    - * - * @author Wujun - * @date Created in 2019/9/30 10:30 - */ -@Slf4j -@RestControllerAdvice -public class GlobalExceptionHandler { - - @ExceptionHandler(RuntimeException.class) - public Dict handler(RuntimeException ex) { - return Dict.create().set("msg", ex.getMessage()); - } -} diff --git a/jun_springboot_plugin/springboot_ratelimit_redis/src/main/java/com/jun/plugin/ratelimit/redis/util/IpUtil.java b/jun_springboot_plugin/springboot_ratelimit_redis/src/main/java/com/jun/plugin/ratelimit/redis/util/IpUtil.java deleted file mode 100644 index 4f453ab5c7..0000000000 --- a/jun_springboot_plugin/springboot_ratelimit_redis/src/main/java/com/jun/plugin/ratelimit/redis/util/IpUtil.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.jun.plugin.ratelimit.redis.util; - -import cn.hutool.core.util.StrUtil; -import lombok.extern.slf4j.Slf4j; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; - -import javax.servlet.http.HttpServletRequest; - -/** - *

    - * IP 工具类 - *

    - * - * @author Wujun - * @date Created in 2019/9/30 10:38 - */ -@Slf4j -public class IpUtil { - private final static String UNKNOWN = "unknown"; - private final static int MAX_LENGTH = 15; - - /** - * 获取IP地址 - * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址 - * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址 - */ - public static String getIpAddr() { - HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); - String ip = null; - try { - ip = request.getHeader("x-forwarded-for"); - if (StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) { - ip = request.getHeader("Proxy-Client-IP"); - } - if (StrUtil.isEmpty(ip) || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { - ip = request.getHeader("WL-Proxy-Client-IP"); - } - if (StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) { - ip = request.getHeader("HTTP_CLIENT_IP"); - } - if (StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) { - ip = request.getHeader("HTTP_X_FORWARDED_FOR"); - } - if (StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) { - ip = request.getRemoteAddr(); - } - } catch (Exception e) { - log.error("IPUtils ERROR ", e); - } - // 使用代理,则获取第一个IP地址 - if (!StrUtil.isEmpty(ip) && ip.length() > MAX_LENGTH) { - if (ip.indexOf(StrUtil.COMMA) > 0) { - ip = ip.substring(0, ip.indexOf(StrUtil.COMMA)); - } - } - return ip; - } -} diff --git a/jun_springboot_plugin/springboot_ratelimit_redis/src/main/resources/application.yml b/jun_springboot_plugin/springboot_ratelimit_redis/src/main/resources/application.yml deleted file mode 100644 index 43382fcd2c..0000000000 --- a/jun_springboot_plugin/springboot_ratelimit_redis/src/main/resources/application.yml +++ /dev/null @@ -1,21 +0,0 @@ -server: - port: 8080 - servlet: - context-path: /demo -spring: - redis: - host: localhost - # 连接超时时间(记得添加单位,Duration) - timeout: 10000ms - # Redis默认情况下有16个分片,这里配置具体使用的分片 - # database: 0 - lettuce: - pool: - # 连接池最大连接数(使用负值表示没有限制) 默认 8 - max-active: 8 - # 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1 - max-wait: -1ms - # 连接池中的最大空闲连接 默认 8 - max-idle: 8 - # 连接池中的最小空闲连接 默认 0 - min-idle: 0 diff --git a/jun_springboot_plugin/springboot_ratelimit_redis/src/main/resources/scripts/redis/limit.lua b/jun_springboot_plugin/springboot_ratelimit_redis/src/main/resources/scripts/redis/limit.lua deleted file mode 100644 index b9a4a15cc2..0000000000 --- a/jun_springboot_plugin/springboot_ratelimit_redis/src/main/resources/scripts/redis/limit.lua +++ /dev/null @@ -1,27 +0,0 @@ --- 下标从 1 开始 -local key = KEYS[1] -local now = tonumber(ARGV[1]) -local ttl = tonumber(ARGV[2]) -local expired = tonumber(ARGV[3]) --- 最大访问量 -local max = tonumber(ARGV[4]) - --- 清除过期的数据 --- 移除指定分数区间内的所有元素,expired 即已经过期的 score --- 根据当前时间毫秒数 - 超时毫秒数,得到过期时间 expired -redis.call('zremrangebyscore', key, 0, expired) - --- 获取 zset 中的当前元素个数 -local current = tonumber(redis.call('zcard', key)) -local next = current + 1 - -if next > max then - -- 达到限流大小 返回 0 - return 0; -else - -- 往 zset 中添加一个值、得分均为当前时间戳的元素,[value,score] - redis.call("zadd", key, now, now) - -- 每次访问均重新设置 zset 的过期时间,单位毫秒 - redis.call("pexpire", key, ttl) - return next -end diff --git a/jun_springboot_plugin/springboot_ratelimit_redis/src/test/java/com/jun/plugin/ratelimit/redis/SpringBootDemoRatelimiterRedisApplicationTests.java b/jun_springboot_plugin/springboot_ratelimit_redis/src/test/java/com/jun/plugin/ratelimit/redis/SpringBootDemoRatelimiterRedisApplicationTests.java deleted file mode 100644 index 207ba5d698..0000000000 --- a/jun_springboot_plugin/springboot_ratelimit_redis/src/test/java/com/jun/plugin/ratelimit/redis/SpringBootDemoRatelimiterRedisApplicationTests.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.jun.plugin.ratelimit.redis; - -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 SpringBootDemoRatelimiterRedisApplicationTests { - - @Test - public void contextLoads() { - } - -} diff --git a/jun_springboot_plugin/springboot_rbac_security/README.md b/jun_springboot_plugin/springboot_rbac_security/README.md deleted file mode 100644 index 779e402592..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/README.md +++ /dev/null @@ -1,906 +0,0 @@ -# spring-boot-demo-rbac-security - -> 此 demo 主要演示了 Spring Boot 项目如何集成 Spring Security 完成权限拦截操作。本 demo 为基于**前后端分离**的后端权限管理部分,不同于其他博客里使用的模板技术,希望对大家有所帮助。 - -## 1. 主要功能 - -- [x] 基于 `RBAC` 权限模型设计,详情参考数据库表结构设计 [`security.sql`](./sql/security.sql) -- [x] 支持**动态权限管理**,详情参考 [`RbacAuthorityService.java`](./src/main/java/com/xkcoding/rbac/security/config/RbacAuthorityService.java) -- [x] **登录 / 登出**部分均使用自定义 Controller 实现,未使用 `Spring Security` 内部默认的实现,适用于前后端分离项目,详情参考 [`SecurityConfig.java`](./src/main/java/com/xkcoding/rbac/security/config/SecurityConfig.java) 和 [`AuthController.java`](./src/main/java/com/xkcoding/rbac/security/controller/AuthController.java) -- [x] 持久化技术使用 `spring-data-jpa` 完成 -- [x] 使用 `JWT` 实现安全验证,同时引入 `Redis` 解决 `JWT` 无法手动设置过期的弊端,并且保证同一用户在同一时间仅支持同一设备登录,不同设备登录会将,详情参考 [`JwtUtil.java`](./src/main/java/com/xkcoding/rbac/security/util/JwtUtil.java) -- [x] 在线人数统计,详情参考 [`MonitorService.java`](./src/main/java/com/xkcoding/rbac/security/service/MonitorService.java) 和 [`RedisUtil.java`](./src/main/java/com/xkcoding/rbac/security/util/RedisUtil.java) -- [x] 手动踢出用户,详情参考 [`MonitorService.java`](./src/main/java/com/xkcoding/rbac/security/service/MonitorService.java) -- [x] 自定义配置不需要进行拦截的请求,详情参考 [`CustomConfig.java`](./src/main/java/com/xkcoding/rbac/security/config/CustomConfig.java) 和 [`application.yml`](./src/main/resources/application.yml) - -## 2. 运行 - -### 2.1. 环境 - -1. JDK 1.8 以上 -2. Maven 3.5 以上 -3. Mysql 5.7 以上 -4. Redis - -### 2.2. 运行方式 - -1. 新建一个名为 `spring-boot-demo` 的数据库,字符集设置为 `utf-8`,如果数据库名不是 `spring-boot-demo` 需要在 `application.yml` 中修改 `spring.datasource.url` -2. 使用 [`security.sql`](./sql/security.sql) 这个 SQL 文件,创建数据库表和初始化RBAC数据 -3. 运行 `SpringBootDemoRbacSecurityApplication` -4. 管理员账号:admin/123456 普通用户:user/123456 -5. 使用 `POST` 请求访问 `/${contextPath}/api/auth/login` 端点,输入账号密码,登陆成功之后返回token,将获得的 token 放在具体请求的 Header 里,key 固定是 `Authorization` ,value 前缀为 `Bearer 后面加空格`再加token,并加上具体请求的参数,就可以了 -6. enjoy ~​ :kissing_smiling_eyes: - -## 3. 部分关键代码 - -### 3.1. pom.xml - -```xml - - - 4.0.0 - - spring-boot-demo-rbac-security - 1.0.0-SNAPSHOT - jar - - spring-boot-demo-rbac-security - Demo project for Spring Boot - - - io.github.wujun728 - spring-boot-demo - 1.0.0-SNAPSHOT - - - - UTF-8 - UTF-8 - 1.8 - 0.9.1 - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-security - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - - org.springframework.boot - spring-boot-starter-data-redis - - - - - org.apache.commons - commons-pool2 - - - - org.springframework.boot - spring-boot-configuration-processor - true - - - - io.jsonwebtoken - jjwt - ${jjwt.veersion} - - - - mysql - mysql-connector-java - - - - org.springframework.boot - spring-boot-starter-test - test - - - - cn.hutool - hutool-all - - - - org.projectlombok - lombok - true - - - - - spring-boot-demo-rbac-security - - - org.springframework.boot - spring-boot-maven-plugin - - - - - -``` - -### 3.2. JwtUtil.java - -> JWT 工具类,主要功能:生成JWT并存入Redis、解析JWT并校验其准确性、从Request的Header中获取JWT - -```java -/** - *

    - * JWT 工具类 - *

    - * - * @package: com.jun.plugin.rbac.security.util - * @description: JWT 工具类 - * @author: yangkai.shen - * @date: Created in 2018-12-07 13:42 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@EnableConfigurationProperties(JwtConfig.class) -@Configuration -@Slf4j -public class JwtUtil { - @Autowired - private JwtConfig jwtConfig; - - @Autowired - private StringRedisTemplate stringRedisTemplate; - - /** - * 创建JWT - * - * @param rememberMe 记住我 - * @param id 用户id - * @param subject 用户名 - * @param roles 用户角色 - * @param authorities 用户权限 - * @return JWT - */ - public String createJWT(Boolean rememberMe, Long id, String subject, List roles, Collection authorities) { - Date now = new Date(); - JwtBuilder builder = Jwts.builder() - .setId(id.toString()) - .setSubject(subject) - .setIssuedAt(now) - .signWith(SignatureAlgorithm.HS256, jwtConfig.getKey()) - .claim("roles", roles) - .claim("authorities", authorities); - - // 设置过期时间 - Long ttl = rememberMe ? jwtConfig.getRemember() : jwtConfig.getTtl(); - if (ttl > 0) { - builder.setExpiration(DateUtil.offsetMillisecond(now, ttl.intValue())); - } - - String jwt = builder.compact(); - // 将生成的JWT保存至Redis - stringRedisTemplate.opsForValue() - .set(Consts.REDIS_JWT_KEY_PREFIX + subject, jwt, ttl, TimeUnit.MILLISECONDS); - return jwt; - } - - /** - * 创建JWT - * - * @param authentication 用户认证信息 - * @param rememberMe 记住我 - * @return JWT - */ - public String createJWT(Authentication authentication, Boolean rememberMe) { - UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal(); - return createJWT(rememberMe, userPrincipal.getId(), userPrincipal.getUsername(), userPrincipal.getRoles(), userPrincipal.getAuthorities()); - } - - /** - * 解析JWT - * - * @param jwt JWT - * @return {@link Claims} - */ - public Claims parseJWT(String jwt) { - try { - Claims claims = Jwts.parser() - .setSigningKey(jwtConfig.getKey()) - .parseClaimsJws(jwt) - .getBody(); - - String username = claims.getSubject(); - String redisKey = Consts.REDIS_JWT_KEY_PREFIX + username; - - // 校验redis中的JWT是否存在 - Long expire = stringRedisTemplate.getExpire(redisKey, TimeUnit.MILLISECONDS); - if (Objects.isNull(expire) || expire <= 0) { - throw new SecurityException(Status.TOKEN_EXPIRED); - } - - // 校验redis中的JWT是否与当前的一致,不一致则代表用户已注销/用户在不同设备登录,均代表JWT已过期 - String redisToken = stringRedisTemplate.opsForValue() - .get(redisKey); - if (!StrUtil.equals(jwt, redisToken)) { - throw new SecurityException(Status.TOKEN_OUT_OF_CTRL); - } - return claims; - } catch (ExpiredJwtException e) { - log.error("Token 已过期"); - throw new SecurityException(Status.TOKEN_EXPIRED); - } catch (UnsupportedJwtException e) { - log.error("不支持的 Token"); - throw new SecurityException(Status.TOKEN_PARSE_ERROR); - } catch (MalformedJwtException e) { - log.error("Token 无效"); - throw new SecurityException(Status.TOKEN_PARSE_ERROR); - } catch (SignatureException e) { - log.error("无效的 Token 签名"); - throw new SecurityException(Status.TOKEN_PARSE_ERROR); - } catch (IllegalArgumentException e) { - log.error("Token 参数不存在"); - throw new SecurityException(Status.TOKEN_PARSE_ERROR); - } - } - - /** - * 设置JWT过期 - * - * @param request 请求 - */ - public void invalidateJWT(HttpServletRequest request) { - String jwt = getJwtFromRequest(request); - String username = getUsernameFromJWT(jwt); - // 从redis中清除JWT - stringRedisTemplate.delete(Consts.REDIS_JWT_KEY_PREFIX + username); - } - - /** - * 根据 jwt 获取用户名 - * - * @param jwt JWT - * @return 用户名 - */ - public String getUsernameFromJWT(String jwt) { - Claims claims = parseJWT(jwt); - return claims.getSubject(); - } - - /** - * 从 request 的 header 中获取 JWT - * - * @param request 请求 - * @return JWT - */ - public String getJwtFromRequest(HttpServletRequest request) { - String bearerToken = request.getHeader("Authorization"); - if (StrUtil.isNotBlank(bearerToken) && bearerToken.startsWith("Bearer ")) { - return bearerToken.substring(7); - } - return null; - } - -} -``` - -### 3.3. SecurityConfig.java - -> Spring Security 配置类,主要功能:配置哪些URL不需要认证,哪些需要认证 - -```java -/** - *

    - * Security 配置 - *

    - * - * @package: com.jun.plugin.rbac.security.config - * @description: Security 配置 - * @author: yangkai.shen - * @date: Created in 2018-12-07 16:46 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Configuration -@EnableWebSecurity -@EnableConfigurationProperties(CustomConfig.class) -public class SecurityConfig extends WebSecurityConfigurerAdapter { - @Autowired - private CustomConfig customConfig; - - @Autowired - private AccessDeniedHandler accessDeniedHandler; - - @Autowired - private CustomUserDetailsService customUserDetailsService; - - @Autowired - private JwtAuthenticationFilter jwtAuthenticationFilter; - - @Bean - public BCryptPasswordEncoder encoder() { - return new BCryptPasswordEncoder(); - } - - @Override - @Bean - public AuthenticationManager authenticationManagerBean() throws Exception { - return super.authenticationManagerBean(); - } - - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.userDetailsService(customUserDetailsService) - .passwordEncoder(encoder()); - } - - @Override - protected void configure(HttpSecurity http) throws Exception { - http.cors() - - // 关闭 CSRF - .and() - .csrf() - .disable() - - // 登录行为由自己实现,参考 AuthController#login - .formLogin() - .disable() - .httpBasic() - .disable() - - // 认证请求 - .authorizeRequests() - // 所有请求都需要登录访问 - .anyRequest() - .authenticated() - // RBAC 动态 url 认证 - .anyRequest() - .access("@rbacAuthorityService.hasPermission(request,authentication)") - - // 登出行为由自己实现,参考 AuthController#logout - .and() - .logout() - .disable() - - // Session 管理 - .sessionManagement() - // 因为使用了JWT,所以这里不管理Session - .sessionCreationPolicy(SessionCreationPolicy.STATELESS) - - // 异常处理 - .and() - .exceptionHandling() - .accessDeniedHandler(accessDeniedHandler); - - // 添加自定义 JWT 过滤器 - http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); - } - - /** - * 放行所有不需要登录就可以访问的请求,参见 AuthController - * 也可以在 {@link #configure(HttpSecurity)} 中配置 - * {@code http.authorizeRequests().antMatchers("/api/auth/**").permitAll()} - */ - @Override - public void configure(WebSecurity web) { - WebSecurity and = web.ignoring() - .and(); - - // 忽略 GET - customConfig.getIgnores() - .getGet() - .forEach(url -> and.ignoring() - .antMatchers(HttpMethod.GET, url)); - - // 忽略 POST - customConfig.getIgnores() - .getPost() - .forEach(url -> and.ignoring() - .antMatchers(HttpMethod.POST, url)); - - // 忽略 DELETE - customConfig.getIgnores() - .getDelete() - .forEach(url -> and.ignoring() - .antMatchers(HttpMethod.DELETE, url)); - - // 忽略 PUT - customConfig.getIgnores() - .getPut() - .forEach(url -> and.ignoring() - .antMatchers(HttpMethod.PUT, url)); - - // 忽略 HEAD - customConfig.getIgnores() - .getHead() - .forEach(url -> and.ignoring() - .antMatchers(HttpMethod.HEAD, url)); - - // 忽略 PATCH - customConfig.getIgnores() - .getPatch() - .forEach(url -> and.ignoring() - .antMatchers(HttpMethod.PATCH, url)); - - // 忽略 OPTIONS - customConfig.getIgnores() - .getOptions() - .forEach(url -> and.ignoring() - .antMatchers(HttpMethod.OPTIONS, url)); - - // 忽略 TRACE - customConfig.getIgnores() - .getTrace() - .forEach(url -> and.ignoring() - .antMatchers(HttpMethod.TRACE, url)); - - // 按照请求格式忽略 - customConfig.getIgnores() - .getPattern() - .forEach(url -> and.ignoring() - .antMatchers(url)); - - } -} -``` - -### 3.4. RbacAuthorityService.java - -> 路由动态鉴权类,主要功能: -> -> 1. 校验请求的合法性,排除404和405这两种异常请求 -> 2. 根据当前请求路径与该用户可访问的资源做匹配,通过则可以访问,否则,不允许访问 - -```java -/** - *

    - * 动态路由认证 - *

    - * - * @package: com.jun.plugin.rbac.security.config - * @description: 动态路由认证 - * @author: yangkai.shen - * @date: Created in 2018-12-10 17:17 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Component -public class RbacAuthorityService { - @Autowired - private RoleDao roleDao; - - @Autowired - private PermissionDao permissionDao; - - @Autowired - private RequestMappingHandlerMapping mapping; - - public boolean hasPermission(HttpServletRequest request, Authentication authentication) { - checkRequest(request); - - Object userInfo = authentication.getPrincipal(); - boolean hasPermission = false; - - if (userInfo instanceof UserDetails) { - UserPrincipal principal = (UserPrincipal) userInfo; - Long userId = principal.getId(); - - List roles = roleDao.selectByUserId(userId); - List roleIds = roles.stream() - .map(Role::getId) - .collect(Collectors.toList()); - List permissions = permissionDao.selectByRoleIdList(roleIds); - - //获取资源,前后端分离,所以过滤页面权限,只保留按钮权限 - List btnPerms = permissions.stream() - // 过滤页面权限 - .filter(permission -> Objects.equals(permission.getType(), Consts.BUTTON)) - // 过滤 URL 为空 - .filter(permission -> StrUtil.isNotBlank(permission.getUrl())) - // 过滤 METHOD 为空 - .filter(permission -> StrUtil.isNotBlank(permission.getMethod())) - .collect(Collectors.toList()); - - for (Permission btnPerm : btnPerms) { - AntPathRequestMatcher antPathMatcher = new AntPathRequestMatcher(btnPerm.getUrl(), btnPerm.getMethod()); - if (antPathMatcher.matches(request)) { - hasPermission = true; - break; - } - } - - return hasPermission; - } else { - return false; - } - } - - /** - * 校验请求是否存在 - * - * @param request 请求 - */ - private void checkRequest(HttpServletRequest request) { - // 获取当前 request 的方法 - String currentMethod = request.getMethod(); - Multimap urlMapping = allUrlMapping(); - - for (String uri : urlMapping.keySet()) { - // 通过 AntPathRequestMatcher 匹配 url - // 可以通过 2 种方式创建 AntPathRequestMatcher - // 1:new AntPathRequestMatcher(uri,method) 这种方式可以直接判断方法是否匹配,因为这里我们把 方法不匹配 自定义抛出,所以,我们使用第2种方式创建 - // 2:new AntPathRequestMatcher(uri) 这种方式不校验请求方法,只校验请求路径 - AntPathRequestMatcher antPathMatcher = new AntPathRequestMatcher(uri); - if (antPathMatcher.matches(request)) { - if (!urlMapping.get(uri) - .contains(currentMethod)) { - throw new SecurityException(Status.HTTP_BAD_METHOD); - } else { - return; - } - } - } - - throw new SecurityException(Status.REQUEST_NOT_FOUND); - } - - /** - * 获取 所有URL Mapping,返回格式为{"/test":["GET","POST"],"/sys":["GET","DELETE"]} - * - * @return {@link ArrayListMultimap} 格式的 URL Mapping - */ - private Multimap allUrlMapping() { - Multimap urlMapping = ArrayListMultimap.create(); - - // 获取url与类和方法的对应信息 - Map handlerMethods = mapping.getHandlerMethods(); - - handlerMethods.forEach((k, v) -> { - // 获取当前 key 下的获取所有URL - Set url = k.getPatternsCondition() - .getPatterns(); - RequestMethodsRequestCondition method = k.getMethodsCondition(); - - // 为每个URL添加所有的请求方法 - url.forEach(s -> urlMapping.putAll(s, method.getMethods() - .stream() - .map(Enum::toString) - .collect(Collectors.toList()))); - }); - - return urlMapping; - } -} -``` - -### 3.5. JwtAuthenticationFilter.java - -> JWT 认证过滤器,主要功能: -> -> 1. 过滤不需要拦截的请求 -> 2. 根据当前请求的JWT,认证用户身份信息 - -```java -/** - *

    - * Jwt 认证过滤器 - *

    - * - * @package: com.jun.plugin.rbac.security.config - * @description: Jwt 认证过滤器 - * @author: yangkai.shen - * @date: Created in 2018-12-10 15:15 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Component -@Slf4j -public class JwtAuthenticationFilter extends OncePerRequestFilter { - @Autowired - private CustomUserDetailsService customUserDetailsService; - - @Autowired - private JwtUtil jwtUtil; - - @Autowired - private CustomConfig customConfig; - - @Override - protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { - - if (checkIgnores(request)) { - filterChain.doFilter(request, response); - return; - } - - String jwt = jwtUtil.getJwtFromRequest(request); - - if (StrUtil.isNotBlank(jwt)) { - try { - String username = jwtUtil.getUsernameFromJWT(jwt); - - UserDetails userDetails = customUserDetailsService.loadUserByUsername(username); - UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); - authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); - - SecurityContextHolder.getContext() - .setAuthentication(authentication); - filterChain.doFilter(request, response); - } catch (SecurityException e) { - ResponseUtil.renderJson(response, e); - } - } else { - ResponseUtil.renderJson(response, Status.UNAUTHORIZED, null); - } - - } - - /** - * 请求是否不需要进行权限拦截 - * - * @param request 当前请求 - * @return true - 忽略,false - 不忽略 - */ - private boolean checkIgnores(HttpServletRequest request) { - String method = request.getMethod(); - - HttpMethod httpMethod = HttpMethod.resolve(method); - if (ObjectUtil.isNull(httpMethod)) { - httpMethod = HttpMethod.GET; - } - - Set ignores = Sets.newHashSet(); - - switch (httpMethod) { - case GET: - ignores.addAll(customConfig.getIgnores() - .getGet()); - break; - case PUT: - ignores.addAll(customConfig.getIgnores() - .getPut()); - break; - case HEAD: - ignores.addAll(customConfig.getIgnores() - .getHead()); - break; - case POST: - ignores.addAll(customConfig.getIgnores() - .getPost()); - break; - case PATCH: - ignores.addAll(customConfig.getIgnores() - .getPatch()); - break; - case TRACE: - ignores.addAll(customConfig.getIgnores() - .getTrace()); - break; - case DELETE: - ignores.addAll(customConfig.getIgnores() - .getDelete()); - break; - case OPTIONS: - ignores.addAll(customConfig.getIgnores() - .getOptions()); - break; - default: - break; - } - - ignores.addAll(customConfig.getIgnores() - .getPattern()); - - if (CollUtil.isNotEmpty(ignores)) { - for (String ignore : ignores) { - AntPathRequestMatcher matcher = new AntPathRequestMatcher(ignore, method); - if (matcher.matches(request)) { - return true; - } - } - } - - return false; - } - -} -``` - -### 3.6. CustomUserDetailsService.java - -> 实现 `UserDetailsService` 接口,主要功能:根据用户名查询用户信息 - -```java -/** - *

    - * 自定义UserDetails查询 - *

    - * - * @package: com.jun.plugin.rbac.security.service - * @description: 自定义UserDetails查询 - * @author: yangkai.shen - * @date: Created in 2018-12-10 10:29 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Service -public class CustomUserDetailsService implements UserDetailsService { - @Autowired - private UserDao userDao; - - @Autowired - private RoleDao roleDao; - - @Autowired - private PermissionDao permissionDao; - - @Override - public UserDetails loadUserByUsername(String usernameOrEmailOrPhone) throws UsernameNotFoundException { - model.User user = userDao.findByUsernameOrEmailOrPhone(usernameOrEmailOrPhone, usernameOrEmailOrPhone, usernameOrEmailOrPhone) - .orElseThrow(() -> new UsernameNotFoundException("未找到用户信息 : " + usernameOrEmailOrPhone)); - List roles = roleDao.selectByUserId(user.getId()); - List roleIds = roles.stream() - .map(Role::getId) - .collect(Collectors.toList()); - List permissions = permissionDao.selectByRoleIdList(roleIds); - return UserPrincipal.create(user, roles, permissions); - } -} -``` - -### 3.7. RedisUtil.java - -> 主要功能:根据key的格式分页获取Redis存在的key列表 - -```java -/** - *

    - * Redis工具类 - *

    - * - * @package: com.jun.plugin.rbac.security.util - * @description: Redis工具类 - * @author: yangkai.shen - * @date: Created in 2018-12-11 20:24 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Component -@Slf4j -public class RedisUtil { - @Autowired - private StringRedisTemplate stringRedisTemplate; - - /** - * 分页获取指定格式key,使用 scan 命令代替 keys 命令,在大数据量的情况下可以提高查询效率 - * - * @param patternKey key格式 - * @param currentPage 当前页码 - * @param pageSize 每页条数 - * @return 分页获取指定格式key - */ - public PageResult findKeysForPage(String patternKey, int currentPage, int pageSize) { - ScanOptions options = ScanOptions.scanOptions() - .match(patternKey) - .build(); - RedisConnectionFactory factory = stringRedisTemplate.getConnectionFactory(); - RedisConnection rc = factory.getConnection(); - Cursor cursor = rc.scan(options); - - List result = Lists.newArrayList(); - - long tmpIndex = 0; - int startIndex = (currentPage - 1) * pageSize; - int end = currentPage * pageSize; - while (cursor.hasNext()) { - String key = new String(cursor.next()); - if (tmpIndex >= startIndex && tmpIndex < end) { - result.add(key); - } - tmpIndex++; - } - - try { - cursor.close(); - RedisConnectionUtils.releaseConnection(rc, factory); - } catch (Exception e) { - log.warn("Redis连接关闭异常,", e); - } - - return new PageResult<>(result, tmpIndex); - } -} -``` - -### 3.8. MonitorService.java - -> 监控服务,主要功能:查询当前在线人数分页列表,手动踢出某个用户 - -```java -package com.jun.plugin.rbac.security.service; - -import cn.hutool.core.util.StrUtil; -import com.google.common.collect.Lists; -import com.jun.plugin.rbac.security.common.Consts; -import com.jun.plugin.rbac.security.common.PageResult; -import com.jun.plugin.rbac.security.model.model.User; -import com.jun.plugin.rbac.security.repository.UserDao; -import com.jun.plugin.rbac.security.util.RedisUtil; -import com.jun.plugin.rbac.security.vo.OnlineUser; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.stream.Collectors; - -/** - *

    - * 监控 Service - *

    - * - * @package: com.jun.plugin.rbac.security.service - * @description: 监控 Service - * @author: yangkai.shen - * @date: Created in 2018-12-12 00:55 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Service -public class MonitorService { - @Autowired - private RedisUtil redisUtil; - - @Autowired - private UserDao userDao; - - public PageResult onlineUser(Integer page, Integer size) { - PageResult keys = redisUtil.findKeysForPage(Consts.REDIS_JWT_KEY_PREFIX + Consts.SYMBOL_STAR, page, size); - List rows = keys.getRows(); - Long total = keys.getTotal(); - - // 根据 redis 中键获取用户名列表 - List usernameList = rows.stream() - .map(s -> StrUtil.subAfter(s, Consts.REDIS_JWT_KEY_PREFIX, true)) - .collect(Collectors.toList()); - // 根据用户名查询用户信息 - List userList = userDao.findByUsernameIn(usernameList); - - // 封装在线用户信息 - List onlineUserList = Lists.newArrayList(); - userList.forEach(user -> onlineUserList.add(OnlineUser.create(user))); - - return new PageResult<>(onlineUserList, total); - } -} -``` - -### 3.9. 其余代码参见本 demo - -## 4. 参考 - -1. Spring Security 官方文档:https://docs.spring.io/spring-security/site/docs/5.1.1.RELEASE/reference/htmlsingle/ -2. JWT 官网:https://jwt.io/ -3. JJWT开源工具参考:https://github.com/jwtk/jjwt#quickstart -4. 授权部分参考官方文档:https://docs.spring.io/spring-security/site/docs/5.1.1.RELEASE/reference/htmlsingle/#authorization - -4. 动态授权部分,参考博客:https://blog.csdn.net/larger5/article/details/81063438 - diff --git a/jun_springboot_plugin/springboot_rbac_security/pom.xml b/jun_springboot_plugin/springboot_rbac_security/pom.xml deleted file mode 100644 index a1ff744e2a..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/pom.xml +++ /dev/null @@ -1,113 +0,0 @@ - - - 4.0.0 - - io.github.wujun728 - springboot_rbac_security - 1.0 - jar - - - springboot_rbac_security - Demo project for Spring Boot - - - io.github.wujun728 - jun_springboot_plugin - 1.0 - - - - UTF-8 - UTF-8 - 1.8 - 0.9.1 - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-security - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - - org.springframework.boot - spring-boot-starter-data-redis - - - - - org.apache.commons - commons-pool2 - - - - org.springframework.boot - spring-boot-configuration-processor - true - - - - io.jsonwebtoken - jjwt - ${jjwt.veersion} - - - - mysql - mysql-connector-java - - - - org.springframework.boot - spring-boot-starter-test - test - - - - cn.hutool - hutool-all - - - - com.google.guava - guava - - - - org.projectlombok - lombok - true - - - - - org.hibernate - hibernate-validator - 6.2.0.Final - - - - - - springboot_rbac_security - - - org.springframework.boot - spring-boot-maven-plugin - - - - - diff --git a/jun_springboot_plugin/springboot_rbac_security/sql/security.sql b/jun_springboot_plugin/springboot_rbac_security/sql/security.sql deleted file mode 100644 index 1ed22407a6..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/sql/security.sql +++ /dev/null @@ -1,176 +0,0 @@ -/* - Navicat Premium Data Transfer - - Source Server : 本机 - Source Server Type : MySQL - Source Server Version : 50718 - Source Host : localhost:3306 - Source Schema : spring-boot-demo - - Target Server Type : MySQL - Target Server Version : 50718 - File Encoding : 65001 - - Date: 12/12/2018 18:52:51 -*/ - -SET NAMES utf8mb4; -SET FOREIGN_KEY_CHECKS = 0; - --- ---------------------------- --- Table structure for sec_permission --- ---------------------------- -DROP TABLE IF EXISTS `sec_permission`; -CREATE TABLE `sec_permission` -( - `id` bigint(64) NOT NULL COMMENT '主键', - `name` varchar(50) NOT NULL COMMENT '权限名', - `url` varchar(1000) DEFAULT NULL COMMENT '类型为页面时,代表前端路由地址,类型为按钮时,代表后端接口地址', - `type` int(2) NOT NULL COMMENT '权限类型,页面-1,按钮-2', - `permission` varchar(50) DEFAULT NULL COMMENT '权限表达式', - `method` varchar(50) DEFAULT NULL COMMENT '后端接口访问方式', - `sort` int(11) NOT NULL COMMENT '排序', - `parent_id` bigint(64) NOT NULL COMMENT '父级id', - PRIMARY KEY (`id`) -) ENGINE = InnoDB - DEFAULT CHARSET = utf8 COMMENT ='权限表'; - --- ---------------------------- --- Records of sec_permission --- ---------------------------- -BEGIN; -INSERT INTO `sec_permission` -VALUES (1072806379288399872, '测试页面', '/test', 1, 'page:test', NULL, 1, 0); -INSERT INTO `sec_permission` -VALUES (1072806379313565696, '测试页面-查询', '/**/test', 2, 'btn:test:query', 'GET', 1, 1072806379288399872); -INSERT INTO `sec_permission` -VALUES (1072806379330342912, '测试页面-添加', '/**/test', 2, 'btn:test:insert', 'POST', 2, 1072806379288399872); -INSERT INTO `sec_permission` -VALUES (1072806379342925824, '监控在线用户页面', '/monitor', 1, 'page:monitor:online', NULL, 2, 0); -INSERT INTO `sec_permission` -VALUES (1072806379363897344, '在线用户页面-查询', '/**/api/monitor/online/user', 2, 'btn:monitor:online:query', 'GET', 1, - 1072806379342925824); -INSERT INTO `sec_permission` -VALUES (1072806379384868864, '在线用户页面-踢出', '/**/api/monitor/online/user/kickout', 2, 'btn:monitor:online:kickout', - 'DELETE', 2, 1072806379342925824); -COMMIT; - --- ---------------------------- --- Table structure for sec_role --- ---------------------------- -DROP TABLE IF EXISTS `sec_role`; -CREATE TABLE `sec_role` -( - `id` bigint(64) NOT NULL COMMENT '主键', - `name` varchar(50) NOT NULL COMMENT '角色名', - `description` varchar(100) DEFAULT NULL COMMENT '描述', - `create_time` bigint(13) NOT NULL COMMENT '创建时间', - `update_time` bigint(13) NOT NULL COMMENT '更新时间', - PRIMARY KEY (`id`), - UNIQUE KEY `name` (`name`) -) ENGINE = InnoDB - DEFAULT CHARSET = utf8 COMMENT ='角色表'; - --- ---------------------------- --- Records of sec_role --- ---------------------------- -BEGIN; -INSERT INTO `sec_role` -VALUES (1072806379208708096, '管理员', '超级管理员', 1544611947239, 1544611947239); -INSERT INTO `sec_role` -VALUES (1072806379238068224, '普通用户', '普通用户', 1544611947246, 1544611947246); -COMMIT; - --- ---------------------------- --- Table structure for sec_role_permission --- ---------------------------- -DROP TABLE IF EXISTS `sec_role_permission`; -CREATE TABLE `sec_role_permission` -( - `role_id` bigint(64) NOT NULL COMMENT '角色主键', - `permission_id` bigint(64) NOT NULL COMMENT '权限主键', - PRIMARY KEY (`role_id`, `permission_id`) -) ENGINE = InnoDB - DEFAULT CHARSET = utf8 COMMENT ='角色权限关系表'; - --- ---------------------------- --- Records of sec_role_permission --- ---------------------------- -BEGIN; -INSERT INTO `sec_role_permission` -VALUES (1072806379208708096, 1072806379288399872); -INSERT INTO `sec_role_permission` -VALUES (1072806379208708096, 1072806379313565696); -INSERT INTO `sec_role_permission` -VALUES (1072806379208708096, 1072806379330342912); -INSERT INTO `sec_role_permission` -VALUES (1072806379208708096, 1072806379342925824); -INSERT INTO `sec_role_permission` -VALUES (1072806379208708096, 1072806379363897344); -INSERT INTO `sec_role_permission` -VALUES (1072806379208708096, 1072806379384868864); -INSERT INTO `sec_role_permission` -VALUES (1072806379238068224, 1072806379288399872); -INSERT INTO `sec_role_permission` -VALUES (1072806379238068224, 1072806379313565696); -COMMIT; - --- ---------------------------- --- Table structure for sec_user --- ---------------------------- -DROP TABLE IF EXISTS `sec_user`; -CREATE TABLE `sec_user` -( - `id` bigint(64) NOT NULL COMMENT '主键', - `username` varchar(50) NOT NULL COMMENT '用户名', - `password` varchar(60) NOT NULL COMMENT '密码', - `nickname` varchar(255) DEFAULT NULL COMMENT '昵称', - `phone` varchar(11) DEFAULT NULL COMMENT '手机', - `email` varchar(50) DEFAULT NULL COMMENT '邮箱', - `birthday` bigint(13) DEFAULT NULL COMMENT '生日', - `sex` int(2) DEFAULT NULL COMMENT '性别,男-1,女-2', - `status` int(2) NOT NULL DEFAULT '1' COMMENT '状态,启用-1,禁用-0', - `create_time` bigint(13) NOT NULL COMMENT '创建时间', - `update_time` bigint(13) NOT NULL COMMENT '更新时间', - PRIMARY KEY (`id`), - UNIQUE KEY `username` (`username`), - UNIQUE KEY `phone` (`phone`), - UNIQUE KEY `email` (`email`) -) ENGINE = InnoDB - DEFAULT CHARSET = utf8 COMMENT ='用户表'; - --- ---------------------------- --- Records of sec_user --- ---------------------------- -BEGIN; -INSERT INTO `sec_user` -VALUES (1072806377661009920, 'admin', '$2a$10$64iuSLkKNhpTN19jGHs7xePvFsub7ZCcCmBqEYw8fbACGTE3XetYq', '管理员', - '17300000000', 'admin@xkcoding.com', 785433600000, 1, 1, 1544611947032, 1544611947032); -INSERT INTO `sec_user` -VALUES (1072806378780889088, 'user', '$2a$10$OUDl4thpcHfs7WZ1kMUOb.ZO5eD4QANW5E.cexBLiKDIzDNt87QbO', '普通用户', - '17300001111', 'user@xkcoding.com', 785433600000, 1, 1, 1544611947234, 1544611947234); -COMMIT; - --- ---------------------------- --- Table structure for sec_user_role --- ---------------------------- -DROP TABLE IF EXISTS `sec_user_role`; -CREATE TABLE `sec_user_role` -( - `user_id` bigint(64) NOT NULL COMMENT '用户主键', - `role_id` bigint(64) NOT NULL COMMENT '角色主键', - PRIMARY KEY (`user_id`, `role_id`) -) ENGINE = InnoDB - DEFAULT CHARSET = utf8 COMMENT ='用户角色关系表'; - --- ---------------------------- --- Records of sec_user_role --- ---------------------------- -BEGIN; -INSERT INTO `sec_user_role` -VALUES (1072806377661009920, 1072806379208708096); -INSERT INTO `sec_user_role` -VALUES (1072806378780889088, 1072806379238068224); -COMMIT; - -SET FOREIGN_KEY_CHECKS = 1; diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/SpringBootDemoRbacSecurityApplication.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/SpringBootDemoRbacSecurityApplication.java deleted file mode 100644 index 5d38124202..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/SpringBootDemoRbacSecurityApplication.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.jun.plugin.rbac.security; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -/** - *

    - * 启动器 - *

    - * - * @package: com.xkcoding.rbac.security - * @description: 启动器 - * @author: yangkai.shen - * @date: Created in 2018-12-10 11:28 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@SpringBootApplication -public class SpringBootDemoRbacSecurityApplication { - - public static void main(String[] args) { - SpringApplication.run(SpringBootDemoRbacSecurityApplication.class, args); - } -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/common/ApiResponse.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/common/ApiResponse.java deleted file mode 100644 index 5298d2595d..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/common/ApiResponse.java +++ /dev/null @@ -1,131 +0,0 @@ -package com.jun.plugin.rbac.security.common; - -import lombok.Data; - -import java.io.Serializable; - -/** - *

    - * 通用的 API 接口封装 - *

    - * - * @package: com.xkcoding.rbac.security.common - * @description: 通用的 API 接口封装 - * @author: yangkai.shen - * @date: Created in 2018-12-07 14:55 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Data -public class ApiResponse implements Serializable { - private static final long serialVersionUID = 8993485788201922830L; - - /** - * 状态码 - */ - private Integer code; - - /** - * 返回内容 - */ - private String message; - - /** - * 返回数据 - */ - private Object data; - - /** - * 无参构造函数 - */ - private ApiResponse() { - - } - - /** - * 全参构造函数 - * - * @param code 状态码 - * @param message 返回内容 - * @param data 返回数据 - */ - private ApiResponse(Integer code, String message, Object data) { - this.code = code; - this.message = message; - this.data = data; - } - - /** - * 构造一个自定义的API返回 - * - * @param code 状态码 - * @param message 返回内容 - * @param data 返回数据 - * @return ApiResponse - */ - public static ApiResponse of(Integer code, String message, Object data) { - return new ApiResponse(code, message, data); - } - - /** - * 构造一个成功且不带数据的API返回 - * - * @return ApiResponse - */ - public static ApiResponse ofSuccess() { - return ofSuccess(null); - } - - /** - * 构造一个成功且带数据的API返回 - * - * @param data 返回数据 - * @return ApiResponse - */ - public static ApiResponse ofSuccess(Object data) { - return ofStatus(Status.SUCCESS, data); - } - - /** - * 构造一个成功且自定义消息的API返回 - * - * @param message 返回内容 - * @return ApiResponse - */ - public static ApiResponse ofMessage(String message) { - return of(Status.SUCCESS.getCode(), message, null); - } - - /** - * 构造一个有状态的API返回 - * - * @param status 状态 {@link Status} - * @return ApiResponse - */ - public static ApiResponse ofStatus(Status status) { - return ofStatus(status, null); - } - - /** - * 构造一个有状态且带数据的API返回 - * - * @param status 状态 {@link IStatus} - * @param data 返回数据 - * @return ApiResponse - */ - public static ApiResponse ofStatus(IStatus status, Object data) { - return of(status.getCode(), status.getMessage(), data); - } - - /** - * 构造一个异常的API返回 - * - * @param t 异常 - * @param {@link BaseException} 的子类 - * @return ApiResponse - */ - public static ApiResponse ofException(T t) { - return of(t.getCode(), t.getMessage(), t.getData()); - } -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/common/BaseException.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/common/BaseException.java deleted file mode 100644 index fff43fc2a6..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/common/BaseException.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.jun.plugin.rbac.security.common; - -import lombok.Data; -import lombok.EqualsAndHashCode; - -/** - *

    - * 异常基类 - *

    - * - * @package: com.xkcoding.rbac.security.common - * @description: 异常基类 - * @author: yangkai.shen - * @date: Created in 2018-12-07 14:57 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@EqualsAndHashCode(callSuper = true) -@Data -public class BaseException extends RuntimeException { - private Integer code; - private String message; - private Object data; - - public BaseException(Status status) { - super(status.getMessage()); - this.code = status.getCode(); - this.message = status.getMessage(); - } - - public BaseException(Status status, Object data) { - this(status); - this.data = data; - } - - public BaseException(Integer code, String message) { - super(message); - this.code = code; - this.message = message; - } - - public BaseException(Integer code, String message, Object data) { - this(code, message); - this.data = data; - } -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/common/Consts.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/common/Consts.java deleted file mode 100644 index c678ccb3df..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/common/Consts.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.jun.plugin.rbac.security.common; - -/** - *

    - * 常量池 - *

    - * - * @package: com.xkcoding.rbac.security.common - * @description: 常量池 - * @author: yangkai.shen - * @date: Created in 2018-12-10 15:03 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -public interface Consts { - /** - * 启用 - */ - Integer ENABLE = 1; - /** - * 禁用 - */ - Integer DISABLE = 0; - - /** - * 页面 - */ - Integer PAGE = 1; - - /** - * 按钮 - */ - Integer BUTTON = 2; - - /** - * JWT 在 Redis 中保存的key前缀 - */ - String REDIS_JWT_KEY_PREFIX = "security:jwt:"; - - /** - * 星号 - */ - String SYMBOL_STAR = "*"; - - /** - * 邮箱符号 - */ - String SYMBOL_EMAIL = "@"; - - /** - * 默认当前页码 - */ - Integer DEFAULT_CURRENT_PAGE = 1; - - /** - * 默认每页条数 - */ - Integer DEFAULT_PAGE_SIZE = 10; - - /** - * 匿名用户 用户名 - */ - String ANONYMOUS_NAME = "匿名用户"; -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/common/IStatus.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/common/IStatus.java deleted file mode 100644 index a1695d17b8..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/common/IStatus.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.jun.plugin.rbac.security.common; - -/** - *

    - * REST API 错误码接口 - *

    - * - * @package: com.xkcoding.rbac.security.common - * @description: REST API 错误码接口 - * @author: yangkai.shen - * @date: Created in 2018-12-07 14:35 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -public interface IStatus { - - /** - * 状态码 - * - * @return 状态码 - */ - Integer getCode(); - - /** - * 返回信息 - * - * @return 返回信息 - */ - String getMessage(); - -} \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/common/PageResult.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/common/PageResult.java deleted file mode 100644 index f32b5d179b..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/common/PageResult.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.jun.plugin.rbac.security.common; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.io.Serializable; -import java.util.List; - -/** - *

    - * 通用分页参数返回 - *

    - * - * @package: com.xkcoding.rbac.security.common - * @description: 通用分页参数返回 - * @author: yangkai.shen - * @date: Created in 2018-12-11 20:26 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Data -@NoArgsConstructor -@AllArgsConstructor -public class PageResult implements Serializable { - private static final long serialVersionUID = 3420391142991247367L; - - /** - * 当前页数据 - */ - private List rows; - - /** - * 总条数 - */ - private Long total; - - public static PageResult of(List rows, Long total) { - return new PageResult<>(rows, total); - } -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/common/Status.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/common/Status.java deleted file mode 100644 index 82ca9a4af3..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/common/Status.java +++ /dev/null @@ -1,131 +0,0 @@ -package com.jun.plugin.rbac.security.common; - -import lombok.Getter; - -/** - *

    - * 通用状态码 - *

    - * - * @package: com.xkcoding.rbac.security.common - * @description: 通用状态码 - * @author: yangkai.shen - * @date: Created in 2018-12-07 14:31 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Getter -public enum Status implements IStatus { - /** - * 操作成功! - */ - SUCCESS(200, "操作成功!"), - - /** - * 操作异常! - */ - ERROR(500, "操作异常!"), - - /** - * 退出成功! - */ - LOGOUT(200, "退出成功!"), - - /** - * 请先登录! - */ - UNAUTHORIZED(401, "请先登录!"), - - /** - * 暂无权限访问! - */ - ACCESS_DENIED(403, "权限不足!"), - - /** - * 请求不存在! - */ - REQUEST_NOT_FOUND(404, "请求不存在!"), - - /** - * 请求方式不支持! - */ - HTTP_BAD_METHOD(405, "请求方式不支持!"), - - /** - * 请求异常! - */ - BAD_REQUEST(400, "请求异常!"), - - /** - * 参数不匹配! - */ - PARAM_NOT_MATCH(400, "参数不匹配!"), - - /** - * 参数不能为空! - */ - PARAM_NOT_NULL(400, "参数不能为空!"), - - /** - * 当前用户已被锁定,请联系管理员解锁! - */ - USER_DISABLED(403, "当前用户已被锁定,请联系管理员解锁!"), - - /** - * 用户名或密码错误! - */ - USERNAME_PASSWORD_ERROR(5001, "用户名或密码错误!"), - - /** - * token 已过期,请重新登录! - */ - TOKEN_EXPIRED(5002, "token 已过期,请重新登录!"), - - /** - * token 解析失败,请尝试重新登录! - */ - TOKEN_PARSE_ERROR(5002, "token 解析失败,请尝试重新登录!"), - - /** - * 当前用户已在别处登录,请尝试更改密码或重新登录! - */ - TOKEN_OUT_OF_CTRL(5003, "当前用户已在别处登录,请尝试更改密码或重新登录!"), - - /** - * 无法手动踢出自己,请尝试退出登录操作! - */ - KICKOUT_SELF(5004, "无法手动踢出自己,请尝试退出登录操作!"); - - /** - * 状态码 - */ - private Integer code; - - /** - * 返回信息 - */ - private String message; - - Status(Integer code, String message) { - this.code = code; - this.message = message; - } - - public static Status fromCode(Integer code) { - Status[] statuses = Status.values(); - for (Status status : statuses) { - if (status.getCode() - .equals(code)) { - return status; - } - } - return SUCCESS; - } - - @Override - public String toString() { - return String.format(" Status:{code=%s, message=%s} ", getCode(), getMessage()); - } - -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/config/CustomConfig.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/config/CustomConfig.java deleted file mode 100644 index 625beb3b99..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/config/CustomConfig.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.jun.plugin.rbac.security.config; - -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; - -/** - *

    - * 自定义配置 - *

    - * - * @package: com.xkcoding.rbac.security.config - * @description: 自定义配置 - * @author: yangkai.shen - * @date: Created in 2018-12-13 10:56 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@ConfigurationProperties(prefix = "custom.config") -@Data -public class CustomConfig { - /** - * 不需要拦截的地址 - */ - private IgnoreConfig ignores; -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/config/IdConfig.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/config/IdConfig.java deleted file mode 100644 index e9dca96529..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/config/IdConfig.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.jun.plugin.rbac.security.config; - -import cn.hutool.core.lang.Snowflake; -import cn.hutool.core.util.IdUtil; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - *

    - * 雪花主键生成器 - *

    - * - * @package: com.xkcoding.rbac.security.config - * @description: 雪花主键生成器 - * @author: yangkai.shen - * @date: Created in 2018-12-10 11:28 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Configuration -public class IdConfig { - /** - * 雪花生成器 - */ - @Bean - public Snowflake snowflake() { - return IdUtil.createSnowflake(1, 1); - } -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/config/IgnoreConfig.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/config/IgnoreConfig.java deleted file mode 100644 index 2a21ed4b5c..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/config/IgnoreConfig.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.jun.plugin.rbac.security.config; - -import com.google.common.collect.Lists; -import lombok.Data; - -import java.util.List; - -/** - *

    - * 忽略配置 - *

    - * - * @package: com.xkcoding.rbac.security.config - * @description: 忽略配置 - * @author: yangkai.shen - * @date: Created in 2018-12-17 17:37 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Data -public class IgnoreConfig { - /** - * 需要忽略的 URL 格式,不考虑请求方法 - */ - private List pattern = Lists.newArrayList(); - - /** - * 需要忽略的 GET 请求 - */ - private List get = Lists.newArrayList(); - - /** - * 需要忽略的 POST 请求 - */ - private List post = Lists.newArrayList(); - - /** - * 需要忽略的 DELETE 请求 - */ - private List delete = Lists.newArrayList(); - - /** - * 需要忽略的 PUT 请求 - */ - private List put = Lists.newArrayList(); - - /** - * 需要忽略的 HEAD 请求 - */ - private List head = Lists.newArrayList(); - - /** - * 需要忽略的 PATCH 请求 - */ - private List patch = Lists.newArrayList(); - - /** - * 需要忽略的 OPTIONS 请求 - */ - private List options = Lists.newArrayList(); - - /** - * 需要忽略的 TRACE 请求 - */ - private List trace = Lists.newArrayList(); -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/config/JwtAuthenticationFilter.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/config/JwtAuthenticationFilter.java deleted file mode 100644 index b819bb9e37..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/config/JwtAuthenticationFilter.java +++ /dev/null @@ -1,154 +0,0 @@ -package com.jun.plugin.rbac.security.config; - -import cn.hutool.core.collection.CollUtil; -import cn.hutool.core.util.ObjectUtil; -import cn.hutool.core.util.StrUtil; -import com.google.common.collect.Sets; -import com.jun.plugin.rbac.security.common.Status; -import com.jun.plugin.rbac.security.exception.SecurityException; -import com.jun.plugin.rbac.security.service.CustomUserDetailsService; -import com.jun.plugin.rbac.security.util.JwtUtil; -import com.jun.plugin.rbac.security.util.ResponseUtil; - -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpMethod; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; -import org.springframework.security.web.util.matcher.AntPathRequestMatcher; -import org.springframework.stereotype.Component; -import org.springframework.web.filter.OncePerRequestFilter; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.util.Set; - -/** - *

    - * Jwt 认证过滤器 - *

    - * - * @package: com.xkcoding.rbac.security.config - * @description: Jwt 认证过滤器 - * @author: yangkai.shen - * @date: Created in 2018-12-10 15:15 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Component -@Slf4j -public class JwtAuthenticationFilter extends OncePerRequestFilter { - @Autowired - private CustomUserDetailsService customUserDetailsService; - - @Autowired - private JwtUtil jwtUtil; - - @Autowired - private CustomConfig customConfig; - - @Override - protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { - - if (checkIgnores(request)) { - filterChain.doFilter(request, response); - return; - } - - String jwt = jwtUtil.getJwtFromRequest(request); - - if (StrUtil.isNotBlank(jwt)) { - try { - String username = jwtUtil.getUsernameFromJWT(jwt); - - UserDetails userDetails = customUserDetailsService.loadUserByUsername(username); - UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); - authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); - - SecurityContextHolder.getContext() - .setAuthentication(authentication); - filterChain.doFilter(request, response); - } catch (SecurityException e) { - ResponseUtil.renderJson(response, e); - } - } else { - ResponseUtil.renderJson(response, Status.UNAUTHORIZED, null); - } - - } - - /** - * 请求是否不需要进行权限拦截 - * - * @param request 当前请求 - * @return true - 忽略,false - 不忽略 - */ - private boolean checkIgnores(HttpServletRequest request) { - String method = request.getMethod(); - - HttpMethod httpMethod = HttpMethod.resolve(method); - if (ObjectUtil.isNull(httpMethod)) { - httpMethod = HttpMethod.GET; - } - - Set ignores = Sets.newHashSet(); - - switch (httpMethod) { - case GET: - ignores.addAll(customConfig.getIgnores() - .getGet()); - break; - case PUT: - ignores.addAll(customConfig.getIgnores() - .getPut()); - break; - case HEAD: - ignores.addAll(customConfig.getIgnores() - .getHead()); - break; - case POST: - ignores.addAll(customConfig.getIgnores() - .getPost()); - break; - case PATCH: - ignores.addAll(customConfig.getIgnores() - .getPatch()); - break; - case TRACE: - ignores.addAll(customConfig.getIgnores() - .getTrace()); - break; - case DELETE: - ignores.addAll(customConfig.getIgnores() - .getDelete()); - break; - case OPTIONS: - ignores.addAll(customConfig.getIgnores() - .getOptions()); - break; - default: - break; - } - - ignores.addAll(customConfig.getIgnores() - .getPattern()); - - if (CollUtil.isNotEmpty(ignores)) { - for (String ignore : ignores) { - AntPathRequestMatcher matcher = new AntPathRequestMatcher(ignore, method); - if (matcher.matches(request)) { - return true; - } - } - } - - return false; - } - -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/config/JwtConfig.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/config/JwtConfig.java deleted file mode 100644 index 47571dcb52..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/config/JwtConfig.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.jun.plugin.rbac.security.config; - -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; - -/** - *

    - * JWT 配置 - *

    - * - * @package: com.xkcoding.rbac.security.config - * @description: JWT 配置 - * @author: yangkai.shen - * @date: Created in 2018-12-07 13:42 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@ConfigurationProperties(prefix = "jwt.config") -@Data -public class JwtConfig { - /** - * jwt 加密 key,默认值:xkcoding. - */ - private String key = "xkcoding"; - - /** - * jwt 过期时间,默认值:600000 {@code 10 分钟}. - */ - private Long ttl = 600000L; - - /** - * 开启 记住我 之后 jwt 过期时间,默认值 604800000 {@code 7 天} - */ - private Long remember = 604800000L; -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/config/RbacAuthorityService.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/config/RbacAuthorityService.java deleted file mode 100644 index 2d863a904b..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/config/RbacAuthorityService.java +++ /dev/null @@ -1,151 +0,0 @@ -package com.jun.plugin.rbac.security.config; - -import cn.hutool.core.util.StrUtil; -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.Multimap; -import com.jun.plugin.rbac.security.common.Consts; -import com.jun.plugin.rbac.security.common.Status; -import com.jun.plugin.rbac.security.exception.SecurityException; -import com.jun.plugin.rbac.security.model.Permission; -import com.jun.plugin.rbac.security.model.Role; -import com.jun.plugin.rbac.security.repository.PermissionDao; -import com.jun.plugin.rbac.security.repository.RoleDao; -import com.jun.plugin.rbac.security.vo.UserPrincipal; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.web.util.matcher.AntPathRequestMatcher; -import org.springframework.stereotype.Component; -import org.springframework.web.method.HandlerMethod; -import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition; -import org.springframework.web.servlet.mvc.method.RequestMappingInfo; -import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; - -import javax.servlet.http.HttpServletRequest; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.stream.Collectors; - -/** - *

    - * 动态路由认证 - *

    - * - * @package: com.xkcoding.rbac.security.config - * @description: 动态路由认证 - * @author: yangkai.shen - * @date: Created in 2018-12-10 17:17 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Component -public class RbacAuthorityService { - @Autowired - private RoleDao roleDao; - - @Autowired - private PermissionDao permissionDao; - - @Autowired - private RequestMappingHandlerMapping mapping; - - public boolean hasPermission(HttpServletRequest request, Authentication authentication) { - checkRequest(request); - - Object userInfo = authentication.getPrincipal(); - boolean hasPermission = false; - - if (userInfo instanceof UserDetails) { - UserPrincipal principal = (UserPrincipal) userInfo; - Long userId = principal.getId(); - - List roles = roleDao.selectByUserId(userId); - List roleIds = roles.stream() - .map(Role::getId) - .collect(Collectors.toList()); - List permissions = permissionDao.selectByRoleIdList(roleIds); - - //获取资源,前后端分离,所以过滤页面权限,只保留按钮权限 - List btnPerms = permissions.stream() - // 过滤页面权限 - .filter(permission -> Objects.equals(permission.getType(), Consts.BUTTON)) - // 过滤 URL 为空 - .filter(permission -> StrUtil.isNotBlank(permission.getUrl())) - // 过滤 METHOD 为空 - .filter(permission -> StrUtil.isNotBlank(permission.getMethod())) - .collect(Collectors.toList()); - - for (Permission btnPerm : btnPerms) { - AntPathRequestMatcher antPathMatcher = new AntPathRequestMatcher(btnPerm.getUrl(), btnPerm.getMethod()); - if (antPathMatcher.matches(request)) { - hasPermission = true; - break; - } - } - - return hasPermission; - } else { - return false; - } - } - - /** - * 校验请求是否存在 - * - * @param request 请求 - */ - private void checkRequest(HttpServletRequest request) { - // 获取当前 request 的方法 - String currentMethod = request.getMethod(); - Multimap urlMapping = allUrlMapping(); - - for (String uri : urlMapping.keySet()) { - // 通过 AntPathRequestMatcher 匹配 url - // 可以通过 2 种方式创建 AntPathRequestMatcher - // 1:new AntPathRequestMatcher(uri,method) 这种方式可以直接判断方法是否匹配,因为这里我们把 方法不匹配 自定义抛出,所以,我们使用第2种方式创建 - // 2:new AntPathRequestMatcher(uri) 这种方式不校验请求方法,只校验请求路径 - AntPathRequestMatcher antPathMatcher = new AntPathRequestMatcher(uri); - if (antPathMatcher.matches(request)) { - if (!urlMapping.get(uri) - .contains(currentMethod)) { - throw new SecurityException(Status.HTTP_BAD_METHOD); - } else { - return; - } - } - } - - throw new SecurityException(Status.REQUEST_NOT_FOUND); - } - - /** - * 获取 所有URL Mapping,返回格式为{"/test":["GET","POST"],"/sys":["GET","DELETE"]} - * - * @return {@link ArrayListMultimap} 格式的 URL Mapping - */ - private Multimap allUrlMapping() { - Multimap urlMapping = ArrayListMultimap.create(); - - // 获取url与类和方法的对应信息 - Map handlerMethods = mapping.getHandlerMethods(); - - handlerMethods.forEach((k, v) -> { - // 获取当前 key 下的获取所有URL - Set url = k.getPatternsCondition() - .getPatterns(); - RequestMethodsRequestCondition method = k.getMethodsCondition(); - - // 为每个URL添加所有的请求方法 - url.forEach(s -> urlMapping.putAll(s, method.getMethods() - .stream() - .map(Enum::toString) - .collect(Collectors.toList()))); - }); - - return urlMapping; - } -} \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/config/RedisConfig.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/config/RedisConfig.java deleted file mode 100644 index f90cf6cdad..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/config/RedisConfig.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.jun.plugin.rbac.security.config; - -import org.springframework.boot.autoconfigure.AutoConfigureAfter; -import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; -import org.springframework.cache.annotation.EnableCaching; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; -import org.springframework.data.redis.serializer.StringRedisSerializer; - -import java.io.Serializable; - -/** - *

    - * redis配置 - *

    - * - * @package: com.xkcoding.rbac.security.config - * @description: redis配置 - * @author: yangkai.shen - * @date: Created in 2018-12-11 15:16 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Configuration -@AutoConfigureAfter(RedisAutoConfiguration.class) -@EnableCaching -public class RedisConfig { - - /** - * 默认情况下的模板只能支持RedisTemplate,也就是只能存入字符串,因此支持序列化 - */ - @Bean - public RedisTemplate redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) { - RedisTemplate template = new RedisTemplate<>(); - template.setKeySerializer(new StringRedisSerializer()); - template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); - template.setConnectionFactory(redisConnectionFactory); - return template; - } -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/config/SecurityConfig.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/config/SecurityConfig.java deleted file mode 100644 index d71312e253..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/config/SecurityConfig.java +++ /dev/null @@ -1,138 +0,0 @@ -package com.jun.plugin.rbac.security.config; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpMethod; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.builders.WebSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.config.http.SessionCreationPolicy; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.web.access.AccessDeniedHandler; -import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; - -import com.jun.plugin.rbac.security.service.CustomUserDetailsService; - -/** - *

    - * Security 配置 - *

    - * - * @package: com.xkcoding.rbac.security.config - * @description: Security 配置 - * @author: yangkai.shen - * @date: Created in 2018-12-07 16:46 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Configuration -@EnableWebSecurity -@EnableConfigurationProperties(CustomConfig.class) -public class SecurityConfig extends WebSecurityConfigurerAdapter { - @Autowired - private CustomConfig customConfig; - - @Autowired - private AccessDeniedHandler accessDeniedHandler; - - @Autowired - private CustomUserDetailsService customUserDetailsService; - - @Autowired - private JwtAuthenticationFilter jwtAuthenticationFilter; - - @Bean - public BCryptPasswordEncoder encoder() { - return new BCryptPasswordEncoder(); - } - - @Override - @Bean - public AuthenticationManager authenticationManagerBean() throws Exception { - return super.authenticationManagerBean(); - } - - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.userDetailsService(customUserDetailsService).passwordEncoder(encoder()); - } - - @Override - protected void configure(HttpSecurity http) throws Exception { - - // @formatter:off - http.cors() - // 关闭 CSRF - .and().csrf().disable() - // 登录行为由自己实现,参考 AuthController#login - .formLogin().disable() - .httpBasic().disable() - - // 认证请求 - .authorizeRequests() - // 所有请求都需要登录访问 - .anyRequest() - .authenticated() - // RBAC 动态 url 认证 - .anyRequest() - .access("@rbacAuthorityService.hasPermission(request,authentication)") - - // 登出行为由自己实现,参考 AuthController#logout - .and().logout().disable() - // Session 管理 - .sessionManagement() - // 因为使用了JWT,所以这里不管理Session - .sessionCreationPolicy(SessionCreationPolicy.STATELESS) - - // 异常处理 - .and().exceptionHandling().accessDeniedHandler(accessDeniedHandler); - // @formatter:on - - // 添加自定义 JWT 过滤器 - http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); - } - - /** - * 放行所有不需要登录就可以访问的请求,参见 AuthController - * 也可以在 {@link #configure(HttpSecurity)} 中配置 - * {@code http.authorizeRequests().antMatchers("/api/auth/**").permitAll()} - */ - @Override - public void configure(WebSecurity web) { - WebSecurity and = web.ignoring().and(); - - // 忽略 GET - customConfig.getIgnores().getGet().forEach(url -> and.ignoring().antMatchers(HttpMethod.GET, url)); - - // 忽略 POST - customConfig.getIgnores().getPost().forEach(url -> and.ignoring().antMatchers(HttpMethod.POST, url)); - - // 忽略 DELETE - customConfig.getIgnores().getDelete().forEach(url -> and.ignoring().antMatchers(HttpMethod.DELETE, url)); - - // 忽略 PUT - customConfig.getIgnores().getPut().forEach(url -> and.ignoring().antMatchers(HttpMethod.PUT, url)); - - // 忽略 HEAD - customConfig.getIgnores().getHead().forEach(url -> and.ignoring().antMatchers(HttpMethod.HEAD, url)); - - // 忽略 PATCH - customConfig.getIgnores().getPatch().forEach(url -> and.ignoring().antMatchers(HttpMethod.PATCH, url)); - - // 忽略 OPTIONS - customConfig.getIgnores().getOptions().forEach(url -> and.ignoring().antMatchers(HttpMethod.OPTIONS, url)); - - // 忽略 TRACE - customConfig.getIgnores().getTrace().forEach(url -> and.ignoring().antMatchers(HttpMethod.TRACE, url)); - - // 按照请求格式忽略 - customConfig.getIgnores().getPattern().forEach(url -> and.ignoring().antMatchers(url)); - - } -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/config/SecurityHandlerConfig.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/config/SecurityHandlerConfig.java deleted file mode 100644 index 4f50363294..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/config/SecurityHandlerConfig.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.jun.plugin.rbac.security.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.web.access.AccessDeniedHandler; - -import com.jun.plugin.rbac.security.common.Status; -import com.jun.plugin.rbac.security.util.ResponseUtil; - -/** - *

    - * Security 结果处理配置 - *

    - * - * @package: com.xkcoding.rbac.security.config - * @description: Security 结果处理配置 - * @author: yangkai.shen - * @date: Created in 2018-12-07 17:31 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Configuration -public class SecurityHandlerConfig { - - @Bean - public AccessDeniedHandler accessDeniedHandler() { - return (request, response, accessDeniedException) -> ResponseUtil.renderJson(response, Status.ACCESS_DENIED, null); - } - -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/config/WebMvcConfig.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/config/WebMvcConfig.java deleted file mode 100644 index 25de647fdd..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/config/WebMvcConfig.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.jun.plugin.rbac.security.config; - -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.CorsRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -/** - *

    - * MVC配置 - *

    - * - * @package: com.xkcoding.rbac.security.config - * @description: MVC配置 - * @author: yangkai.shen - * @date: Created in 2018-12-10 16:09 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Configuration -public class WebMvcConfig implements WebMvcConfigurer { - - private static final long MAX_AGE_SECS = 3600; - - @Override - public void addCorsMappings(CorsRegistry registry) { - registry.addMapping("/**") - .allowedOrigins("*") - .allowedMethods("HEAD", "OPTIONS", "GET", "POST", "PUT", "PATCH", "DELETE") - .maxAge(MAX_AGE_SECS); - } -} \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/controller/AuthController.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/controller/AuthController.java deleted file mode 100644 index dbd688a948..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/controller/AuthController.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.jun.plugin.rbac.security.controller; - -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import com.jun.plugin.rbac.security.common.ApiResponse; -import com.jun.plugin.rbac.security.common.Status; -import com.jun.plugin.rbac.security.exception.SecurityException; -import com.jun.plugin.rbac.security.payload.LoginRequest; -import com.jun.plugin.rbac.security.util.JwtUtil; -import com.jun.plugin.rbac.security.vo.JwtResponse; - -import javax.servlet.http.HttpServletRequest; -import javax.validation.Valid; - -/** - *

    - * 认证 Controller,包括用户注册,用户登录请求 - *

    - * - * @package: com.xkcoding.rbac.security.controller - * @description: 认证 Controller,包括用户注册,用户登录请求 - * @author: yangkai.shen - * @date: Created in 2018-12-07 17:23 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Slf4j -@RestController -@RequestMapping("/api/auth") -public class AuthController { - - @Autowired - private AuthenticationManager authenticationManager; - - @Autowired - private JwtUtil jwtUtil; - - /** - * 登录 - */ - @PostMapping("/login") - public ApiResponse login(@Valid @RequestBody LoginRequest loginRequest) { - Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUsernameOrEmailOrPhone(), loginRequest.getPassword())); - - SecurityContextHolder.getContext() - .setAuthentication(authentication); - - String jwt = jwtUtil.createJWT(authentication,loginRequest.getRememberMe()); - return ApiResponse.ofSuccess(new JwtResponse(jwt)); - } - - @PostMapping("/logout") - public ApiResponse logout(HttpServletRequest request) { - try { - // 设置JWT过期 - jwtUtil.invalidateJWT(request); - } catch (SecurityException e) { - throw new SecurityException(Status.UNAUTHORIZED); - } - return ApiResponse.ofStatus(Status.LOGOUT); - } -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/controller/MonitorController.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/controller/MonitorController.java deleted file mode 100644 index 2759a2193d..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/controller/MonitorController.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.jun.plugin.rbac.security.controller; - -import cn.hutool.core.collection.CollUtil; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; - -import com.jun.plugin.rbac.security.common.ApiResponse; -import com.jun.plugin.rbac.security.common.PageResult; -import com.jun.plugin.rbac.security.common.Status; -import com.jun.plugin.rbac.security.exception.SecurityException; -import com.jun.plugin.rbac.security.payload.PageCondition; -import com.jun.plugin.rbac.security.service.MonitorService; -import com.jun.plugin.rbac.security.util.PageUtil; -import com.jun.plugin.rbac.security.util.SecurityUtil; -import com.jun.plugin.rbac.security.vo.OnlineUser; - -import java.util.List; - -/** - *

    - * 监控 Controller,在线用户,手动踢出用户等功能 - *

    - * - * @package: com.xkcoding.rbac.security.controller - * @description: 监控 Controller,在线用户,手动踢出用户等功能 - * @author: yangkai.shen - * @date: Created in 2018-12-11 20:55 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Slf4j -@RestController -@RequestMapping("/api/monitor") -public class MonitorController { - @Autowired - private MonitorService monitorService; - - /** - * 在线用户列表 - * - * @param pageCondition 分页参数 - */ - @GetMapping("/online/user") - public ApiResponse onlineUser(PageCondition pageCondition) { - PageUtil.checkPageCondition(pageCondition, PageCondition.class); - PageResult pageResult = monitorService.onlineUser(pageCondition); - return ApiResponse.ofSuccess(pageResult); - } - - /** - * 批量踢出在线用户 - * - * @param names 用户名列表 - */ - @DeleteMapping("/online/user/kickout") - public ApiResponse kickoutOnlineUser(@RequestBody List names) { - if (CollUtil.isEmpty(names)) { - throw new SecurityException(Status.PARAM_NOT_NULL); - } - if (names.contains(SecurityUtil.getCurrentUsername())){ - throw new SecurityException(Status.KICKOUT_SELF); - } - monitorService.kickout(names); - return ApiResponse.ofSuccess(); - } -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/controller/TestController.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/controller/TestController.java deleted file mode 100644 index 8089859297..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/controller/TestController.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.jun.plugin.rbac.security.controller; - -import lombok.extern.slf4j.Slf4j; -import org.springframework.web.bind.annotation.*; - -import com.jun.plugin.rbac.security.common.ApiResponse; - -/** - *

    - * 测试Controller - *

    - * - * @package: com.xkcoding.rbac.security.controller - * @description: 测试Controller - * @author: yangkai.shen - * @date: Created in 2018-12-10 15:44 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Slf4j -@RestController -@RequestMapping("/test") -public class TestController { - @GetMapping - public ApiResponse list() { - log.info("测试列表查询"); - return ApiResponse.ofMessage("测试列表查询"); - } - - @PostMapping - public ApiResponse add() { - log.info("测试列表添加"); - return ApiResponse.ofMessage("测试列表添加"); - } - - @PutMapping("/{id}") - public ApiResponse update(@PathVariable Long id) { - log.info("测试列表修改"); - return ApiResponse.ofSuccess("测试列表修改"); - } -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/exception/SecurityException.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/exception/SecurityException.java deleted file mode 100644 index 8f919c3147..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/exception/SecurityException.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.jun.plugin.rbac.security.exception; - -import com.jun.plugin.rbac.security.common.BaseException; -import com.jun.plugin.rbac.security.common.Status; - -import lombok.Data; -import lombok.EqualsAndHashCode; - -/** - *

    - * 全局异常 - *

    - * - * @package: com.xkcoding.rbac.security.exception - * @description: 全局异常 - * @author: yangkai.shen - * @date: Created in 2018-12-10 17:24 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@EqualsAndHashCode(callSuper = true) -@Data -public class SecurityException extends BaseException { - public SecurityException(Status status) { - super(status); - } - - public SecurityException(Status status, Object data) { - super(status, data); - } - - public SecurityException(Integer code, String message) { - super(code, message); - } - - public SecurityException(Integer code, String message, Object data) { - super(code, message, data); - } -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/exception/handler/GlobalExceptionHandler.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/exception/handler/GlobalExceptionHandler.java deleted file mode 100644 index 482c4c245e..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/exception/handler/GlobalExceptionHandler.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.jun.plugin.rbac.security.exception.handler; - -import cn.hutool.core.collection.CollUtil; -import cn.hutool.json.JSONUtil; -import lombok.extern.slf4j.Slf4j; -import org.springframework.http.converter.HttpMessageNotReadableException; -import org.springframework.security.authentication.BadCredentialsException; -import org.springframework.security.authentication.DisabledException; -import org.springframework.web.HttpRequestMethodNotSupportedException; -import org.springframework.web.bind.MethodArgumentNotValidException; -import org.springframework.web.bind.annotation.ControllerAdvice; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; -import org.springframework.web.servlet.NoHandlerFoundException; - -import com.jun.plugin.rbac.security.common.ApiResponse; -import com.jun.plugin.rbac.security.common.BaseException; -import com.jun.plugin.rbac.security.common.Status; - -import javax.validation.ConstraintViolationException; - -/** - *

    - * 全局统一异常处理 - *

    - * - * @package: com.xkcoding.rbac.security.exception.handler - * @description: 全局统一异常处理 - * @author: yangkai.shen - * @date: Created in 2018-12-10 17:00 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@ControllerAdvice -@Slf4j -public class GlobalExceptionHandler { - - @ExceptionHandler(value = Exception.class) - @ResponseBody - public ApiResponse handlerException(Exception e) { - if (e instanceof NoHandlerFoundException) { - log.error("【全局异常拦截】NoHandlerFoundException: 请求方法 {}, 请求路径 {}", ((NoHandlerFoundException) e).getRequestURL(), ((NoHandlerFoundException) e).getHttpMethod()); - return ApiResponse.ofStatus(Status.REQUEST_NOT_FOUND); - } else if (e instanceof HttpRequestMethodNotSupportedException) { - log.error("【全局异常拦截】HttpRequestMethodNotSupportedException: 当前请求方式 {}, 支持请求方式 {}", ((HttpRequestMethodNotSupportedException) e).getMethod(), JSONUtil.toJsonStr(((HttpRequestMethodNotSupportedException) e).getSupportedHttpMethods())); - return ApiResponse.ofStatus(Status.HTTP_BAD_METHOD); - } else if (e instanceof MethodArgumentNotValidException) { - log.error("【全局异常拦截】MethodArgumentNotValidException", e); - return ApiResponse.of(Status.BAD_REQUEST.getCode(), ((MethodArgumentNotValidException) e).getBindingResult() - .getAllErrors() - .get(0) - .getDefaultMessage(), null); - } else if (e instanceof ConstraintViolationException) { - log.error("【全局异常拦截】ConstraintViolationException", e); - return ApiResponse.of(Status.BAD_REQUEST.getCode(), CollUtil.getFirst(((ConstraintViolationException) e).getConstraintViolations()) - .getMessage(), null); - } else if (e instanceof MethodArgumentTypeMismatchException) { - log.error("【全局异常拦截】MethodArgumentTypeMismatchException: 参数名 {}, 异常信息 {}", ((MethodArgumentTypeMismatchException) e).getName(), ((MethodArgumentTypeMismatchException) e).getMessage()); - return ApiResponse.ofStatus(Status.PARAM_NOT_MATCH); - } else if (e instanceof HttpMessageNotReadableException) { - log.error("【全局异常拦截】HttpMessageNotReadableException: 错误信息 {}", ((HttpMessageNotReadableException) e).getMessage()); - return ApiResponse.ofStatus(Status.PARAM_NOT_NULL); - } else if (e instanceof BadCredentialsException) { - log.error("【全局异常拦截】BadCredentialsException: 错误信息 {}", e.getMessage()); - return ApiResponse.ofStatus(Status.USERNAME_PASSWORD_ERROR); - } else if (e instanceof DisabledException) { - log.error("【全局异常拦截】BadCredentialsException: 错误信息 {}", e.getMessage()); - return ApiResponse.ofStatus(Status.USER_DISABLED); - } else if (e instanceof BaseException) { - log.error("【全局异常拦截】DataManagerException: 状态码 {}, 异常信息 {}", ((BaseException) e).getCode(), e.getMessage()); - return ApiResponse.ofException((BaseException) e); - } - - log.error("【全局异常拦截】: 异常信息 {} ", e.getMessage()); - return ApiResponse.ofStatus(Status.ERROR); - } -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/model/Permission.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/model/Permission.java deleted file mode 100644 index 13333fbef3..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/model/Permission.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.jun.plugin.rbac.security.model; - -import lombok.Data; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -/** - *

    - * 权限 - *

    - * - * @package: com.xkcoding.rbac.security.model - * @description: 权限 - * @author: yangkai.shen - * @date: Created in 2018-12-07 16:04 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Data -@Entity -@Table(name = "sec_permission") -public class Permission { - /** - * 主键 - */ - @Id - private Long id; - - /** - * 权限名 - */ - private String name; - - /** - * 类型为页面时,代表前端路由地址,类型为按钮时,代表后端接口地址 - */ - private String url; - - /** - * 权限类型,页面-1,按钮-2 - */ - private Integer type; - - /** - * 权限表达式 - */ - private String permission; - - /** - * 后端接口访问方式 - */ - private String method; - - /** - * 排序 - */ - private Integer sort; - - /** - * 父级id - */ - @Column(name = "parent_id") - private Long parentId; -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/model/Role.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/model/Role.java deleted file mode 100644 index 6aac53d0f3..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/model/Role.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.jun.plugin.rbac.security.model; - -import lombok.Data; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -/** - *

    - * 角色 - *

    - * - * @package: com.xkcoding.rbac.security.model - * @description: 角色 - * @author: yangkai.shen - * @date: Created in 2018-12-07 15:45 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Data -@Entity -@Table(name = "sec_role") -public class Role { - /** - * 主键 - */ - @Id - private Long id; - - /** - * 角色名 - */ - private String name; - - /** - * 描述 - */ - private String description; - - /** - * 创建时间 - */ - @Column(name = "create_time") - private Long createTime; - - /** - * 更新时间 - */ - @Column(name = "update_time") - private Long updateTime; -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/model/RolePermission.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/model/RolePermission.java deleted file mode 100644 index 210f281eaa..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/model/RolePermission.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.jun.plugin.rbac.security.model; - -import lombok.Data; - -import javax.persistence.EmbeddedId; -import javax.persistence.Entity; -import javax.persistence.Table; - -import com.jun.plugin.rbac.security.model.unionkey.RolePermissionKey; - -/** - *

    - * 角色-权限 - *

    - * - * @package: com.xkcoding.rbac.security.model - * @description: 角色-权限 - * @author: yangkai.shen - * @date: Created in 2018-12-10 13:46 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Data -@Entity -@Table(name = "sec_role_permission") -public class RolePermission { - /** - * 主键 - */ - @EmbeddedId - private RolePermissionKey id; -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/model/User.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/model/User.java deleted file mode 100644 index 651449cbf1..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/model/User.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.jun.plugin.rbac.security.model; - -import lombok.Data; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -/** - *

    - * 用户 - *

    - * - * @package: com.xkcoding.rbac.security.model - * @description: 用户 - * @author: yangkai.shen - * @date: Created in 2018-12-07 16:00 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Data -@Entity -@Table(name = "sec_user") -public class User { - - /** - * 主键 - */ - @Id - private Long id; - - /** - * 用户名 - */ - private String username; - - /** - * 密码 - */ - private String password; - - /** - * 昵称 - */ - private String nickname; - - /** - * 手机 - */ - private String phone; - - /** - * 邮箱 - */ - private String email; - - /** - * 生日 - */ - private Long birthday; - - /** - * 性别,男-1,女-2 - */ - private Integer sex; - - /** - * 状态,启用-1,禁用-0 - */ - private Integer status; - - /** - * 创建时间 - */ - @Column(name = "create_time") - private Long createTime; - - /** - * 更新时间 - */ - @Column(name = "update_time") - private Long updateTime; -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/model/UserRole.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/model/UserRole.java deleted file mode 100644 index 259013df4f..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/model/UserRole.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.jun.plugin.rbac.security.model; - -import lombok.Data; - -import javax.persistence.EmbeddedId; -import javax.persistence.Entity; -import javax.persistence.Table; - -import com.jun.plugin.rbac.security.model.unionkey.UserRoleKey; - -/** - *

    - * 用户角色关联 - *

    - * - * @package: com.xkcoding.rbac.security.model - * @description: 用户角色关联 - * @author: yangkai.shen - * @date: Created in 2018-12-10 11:18 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Data -@Entity -@Table(name = "sec_user_role") -public class UserRole { - /** - * 主键 - */ - @EmbeddedId - private UserRoleKey id; -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/model/unionkey/RolePermissionKey.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/model/unionkey/RolePermissionKey.java deleted file mode 100644 index 6612694113..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/model/unionkey/RolePermissionKey.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.jun.plugin.rbac.security.model.unionkey; - -import lombok.Data; - -import javax.persistence.Column; -import javax.persistence.Embeddable; -import java.io.Serializable; - -/** - *

    - * 角色-权限联合主键 - *

    - * - * @package: com.xkcoding.rbac.security.model.unionkey - * @description: 角色-权限联合主键 - * @author: yangkai.shen - * @date: Created in 2018-12-10 13:47 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Data -@Embeddable -public class RolePermissionKey implements Serializable { - private static final long serialVersionUID = 6850974328279713855L; - - /** - * 角色id - */ - @Column(name = "role_id") - private Long roleId; - - /** - * 权限id - */ - @Column(name = "permission_id") - private Long permissionId; -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/model/unionkey/UserRoleKey.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/model/unionkey/UserRoleKey.java deleted file mode 100644 index 0fc28d187c..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/model/unionkey/UserRoleKey.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.jun.plugin.rbac.security.model.unionkey; - -import lombok.Data; - -import javax.persistence.Column; -import javax.persistence.Embeddable; -import java.io.Serializable; - -/** - *

    - * 用户-角色联合主键 - *

    - * - * @package: com.xkcoding.rbac.security.model.unionkey - * @description: 用户-角色联合主键 - * @author: yangkai.shen - * @date: Created in 2018-12-10 11:20 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Embeddable -@Data -public class UserRoleKey implements Serializable { - private static final long serialVersionUID = 5633412144183654743L; - - /** - * 用户id - */ - @Column(name = "user_id") - private Long userId; - - /** - * 角色id - */ - @Column(name = "role_id") - private Long roleId; -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/payload/LoginRequest.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/payload/LoginRequest.java deleted file mode 100644 index 9c502600df..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/payload/LoginRequest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.jun.plugin.rbac.security.payload; - -import lombok.Data; - -import javax.validation.constraints.NotBlank; - -/** - *

    - * 登录请求参数 - *

    - * - * @package: com.xkcoding.rbac.security.payload - * @description: 登录请求参数 - * @author: yangkai.shen - * @date: Created in 2018-12-10 15:52 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Data -public class LoginRequest { - - /** - * 用户名或邮箱或手机号 - */ - @NotBlank(message = "用户名不能为空") - private String usernameOrEmailOrPhone; - - /** - * 密码 - */ - @NotBlank(message = "密码不能为空") - private String password; - - /** - * 记住我 - */ - private Boolean rememberMe = false; - -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/payload/PageCondition.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/payload/PageCondition.java deleted file mode 100644 index 0a3e7bc9a5..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/payload/PageCondition.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.jun.plugin.rbac.security.payload; - -import lombok.Data; - -/** - *

    - * 分页请求参数 - *

    - * - * @package: com.xkcoding.rbac.security.payload - * @description: 分页请求参数 - * @author: yangkai.shen - * @date: Created in 2018-12-12 18:05 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Data -public class PageCondition { - /** - * 当前页码 - */ - private Integer currentPage; - - /** - * 每页条数 - */ - private Integer pageSize; - -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/repository/PermissionDao.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/repository/PermissionDao.java deleted file mode 100644 index 7e1c4c9e8d..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/repository/PermissionDao.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.jun.plugin.rbac.security.repository; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; - -import com.jun.plugin.rbac.security.model.Permission; - -import java.util.List; - -/** - *

    - * 权限 DAO - *

    - * - * @package: com.xkcoding.rbac.security.repository - * @description: 权限 DAO - * @author: yangkai.shen - * @date: Created in 2018-12-07 16:21 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -public interface PermissionDao extends JpaRepository, JpaSpecificationExecutor { - - /** - * 根据角色列表查询权限列表 - * - * @param ids 角色id列表 - * @return 权限列表 - */ - @Query(value = "SELECT DISTINCT sec_permission.* FROM sec_permission,sec_role,sec_role_permission WHERE sec_role.id = sec_role_permission.role_id AND sec_permission.id = sec_role_permission.permission_id AND sec_role.id IN (:ids)", nativeQuery = true) - List selectByRoleIdList(@Param("ids") List ids); -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/repository/RoleDao.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/repository/RoleDao.java deleted file mode 100644 index d9e0137c60..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/repository/RoleDao.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.jun.plugin.rbac.security.repository; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; - -import com.jun.plugin.rbac.security.model.Role; - -import java.util.List; - -/** - *

    - * 角色 DAO - *

    - * - * @package: com.xkcoding.rbac.security.repository - * @description: 角色 DAO - * @author: yangkai.shen - * @date: Created in 2018-12-07 16:20 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -public interface RoleDao extends JpaRepository, JpaSpecificationExecutor { - /** - * 根据用户id 查询角色列表 - * - * @param userId 用户id - * @return 角色列表 - */ - @Query(value = "SELECT sec_role.* FROM sec_role,sec_user,sec_user_role WHERE sec_user.id = sec_user_role.user_id AND sec_role.id = sec_user_role.role_id AND sec_user.id = :userId", nativeQuery = true) - List selectByUserId(@Param("userId") Long userId); -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/repository/RolePermissionDao.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/repository/RolePermissionDao.java deleted file mode 100644 index b122fd6b22..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/repository/RolePermissionDao.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.jun.plugin.rbac.security.repository; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.JpaSpecificationExecutor; - -import com.jun.plugin.rbac.security.model.RolePermission; -import com.jun.plugin.rbac.security.model.unionkey.RolePermissionKey; - -/** - *

    - * 角色-权限 DAO - *

    - * - * @package: com.xkcoding.rbac.security.repository - * @description: 角色-权限 DAO - * @author: yangkai.shen - * @date: Created in 2018-12-10 13:45 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -public interface RolePermissionDao extends JpaRepository, JpaSpecificationExecutor { -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/repository/UserDao.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/repository/UserDao.java deleted file mode 100644 index 3f7fa4ef74..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/repository/UserDao.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.jun.plugin.rbac.security.repository; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.JpaSpecificationExecutor; - -import com.jun.plugin.rbac.security.model.User; - -import java.util.List; -import java.util.Optional; - -/** - *

    - * 用户 DAO - *

    - * - * @package: com.xkcoding.rbac.security.repository - * @description: 用户 DAO - * @author: yangkai.shen - * @date: Created in 2018-12-07 16:18 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -public interface UserDao extends JpaRepository, JpaSpecificationExecutor { - /** - * 根据用户名、邮箱、手机号查询用户 - * - * @param username 用户名 - * @param email 邮箱 - * @param phone 手机号 - * @return 用户信息 - */ - Optional findByUsernameOrEmailOrPhone(String username, String email, String phone); - - /** - * 根据用户名列表查询用户列表 - * - * @param usernameList 用户名列表 - * @return 用户列表 - */ - List findByUsernameIn(List usernameList); -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/repository/UserRoleDao.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/repository/UserRoleDao.java deleted file mode 100644 index f169716259..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/repository/UserRoleDao.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.jun.plugin.rbac.security.repository; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.JpaSpecificationExecutor; - -import com.jun.plugin.rbac.security.model.UserRole; -import com.jun.plugin.rbac.security.model.unionkey.UserRoleKey; - -/** - *

    - * 用户角色 DAO - *

    - * - * @package: com.xkcoding.rbac.security.repository - * @description: 用户角色 DAO - * @author: yangkai.shen - * @date: Created in 2018-12-10 11:24 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -public interface UserRoleDao extends JpaRepository, JpaSpecificationExecutor { - -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/service/CustomUserDetailsService.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/service/CustomUserDetailsService.java deleted file mode 100644 index 5a9de2eb94..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/service/CustomUserDetailsService.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.jun.plugin.rbac.security.service; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.core.userdetails.UsernameNotFoundException; -import org.springframework.stereotype.Service; - -import com.jun.plugin.rbac.security.model.Permission; -import com.jun.plugin.rbac.security.model.Role; -import com.jun.plugin.rbac.security.model.User; -import com.jun.plugin.rbac.security.repository.PermissionDao; -import com.jun.plugin.rbac.security.repository.RoleDao; -import com.jun.plugin.rbac.security.repository.UserDao; -import com.jun.plugin.rbac.security.vo.UserPrincipal; - -import java.util.List; -import java.util.stream.Collectors; - -/** - *

    - * 自定义UserDetails查询 - *

    - * - * @package: com.xkcoding.rbac.security.service - * @description: 自定义UserDetails查询 - * @author: yangkai.shen - * @date: Created in 2018-12-10 10:29 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Service -public class CustomUserDetailsService implements UserDetailsService { - @Autowired - private UserDao userDao; - - @Autowired - private RoleDao roleDao; - - @Autowired - private PermissionDao permissionDao; - - @Override - public UserDetails loadUserByUsername(String usernameOrEmailOrPhone) throws UsernameNotFoundException { - User user = userDao.findByUsernameOrEmailOrPhone(usernameOrEmailOrPhone, usernameOrEmailOrPhone, usernameOrEmailOrPhone) - .orElseThrow(() -> new UsernameNotFoundException("未找到用户信息 : " + usernameOrEmailOrPhone)); - List roles = roleDao.selectByUserId(user.getId()); - List roleIds = roles.stream() - .map(Role::getId) - .collect(Collectors.toList()); - List permissions = permissionDao.selectByRoleIdList(roleIds); - return UserPrincipal.create(user, roles, permissions); - } -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/service/MonitorService.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/service/MonitorService.java deleted file mode 100644 index 2323bfc363..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/service/MonitorService.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.jun.plugin.rbac.security.service; - -import cn.hutool.core.util.StrUtil; -import com.google.common.collect.Lists; -import com.jun.plugin.rbac.security.common.Consts; -import com.jun.plugin.rbac.security.common.PageResult; -import com.jun.plugin.rbac.security.model.User; -import com.jun.plugin.rbac.security.payload.PageCondition; -import com.jun.plugin.rbac.security.repository.UserDao; -import com.jun.plugin.rbac.security.util.RedisUtil; -import com.jun.plugin.rbac.security.util.SecurityUtil; -import com.jun.plugin.rbac.security.vo.OnlineUser; - -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.stream.Collectors; - -/** - *

    - * 监控 Service - *

    - * - * @package: com.xkcoding.rbac.security.service - * @description: 监控 Service - * @author: yangkai.shen - * @date: Created in 2018-12-12 00:55 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Slf4j -@Service -public class MonitorService { - @Autowired - private RedisUtil redisUtil; - - @Autowired - private UserDao userDao; - - /** - * 在线用户分页列表 - * - * @param pageCondition 分页参数 - * @return 在线用户分页列表 - */ - public PageResult onlineUser(PageCondition pageCondition) { - PageResult keys = redisUtil.findKeysForPage(Consts.REDIS_JWT_KEY_PREFIX + Consts.SYMBOL_STAR, pageCondition.getCurrentPage(), pageCondition.getPageSize()); - List rows = keys.getRows(); - Long total = keys.getTotal(); - - // 根据 redis 中键获取用户名列表 - List usernameList = rows.stream() - .map(s -> StrUtil.subAfter(s, Consts.REDIS_JWT_KEY_PREFIX, true)) - .collect(Collectors.toList()); - // 根据用户名查询用户信息 - List userList = userDao.findByUsernameIn(usernameList); - - // 封装在线用户信息 - List onlineUserList = Lists.newArrayList(); - userList.forEach(user -> onlineUserList.add(OnlineUser.create(user))); - - return new PageResult<>(onlineUserList, total); - } - - /** - * 踢出在线用户 - * - * @param names 用户名列表 - */ - public void kickout(List names) { - // 清除 Redis 中的 JWT 信息 - List redisKeys = names.parallelStream() - .map(s -> Consts.REDIS_JWT_KEY_PREFIX + s) - .collect(Collectors.toList()); - redisUtil.delete(redisKeys); - - // 获取当前用户名 - String currentUsername = SecurityUtil.getCurrentUsername(); - names.parallelStream() - .forEach(name -> { - // TODO: 通知被踢出的用户已被当前登录用户踢出, - // 后期考虑使用 websocket 实现,具体伪代码实现如下。 - // String message = "您已被用户【" + currentUsername + "】手动下线!"; - log.debug("用户【{}】被用户【{}】手动下线!", name, currentUsername); - }); - } -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/util/JwtUtil.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/util/JwtUtil.java deleted file mode 100644 index 4e34546701..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/util/JwtUtil.java +++ /dev/null @@ -1,179 +0,0 @@ -package com.jun.plugin.rbac.security.util; - -import cn.hutool.core.date.DateUtil; -import cn.hutool.core.util.StrUtil; -import io.jsonwebtoken.*; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.GrantedAuthority; - -import com.jun.plugin.rbac.security.common.Consts; -import com.jun.plugin.rbac.security.common.Status; -import com.jun.plugin.rbac.security.config.JwtConfig; -import com.jun.plugin.rbac.security.exception.SecurityException; -import com.jun.plugin.rbac.security.vo.UserPrincipal; - -import javax.servlet.http.HttpServletRequest; -import java.util.Collection; -import java.util.Date; -import java.util.List; -import java.util.Objects; -import java.util.concurrent.TimeUnit; - -/** - *

    - * JWT 工具类 - *

    - * - * @package: com.xkcoding.rbac.security.util - * @description: JWT 工具类 - * @author: yangkai.shen - * @date: Created in 2018-12-07 13:42 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@EnableConfigurationProperties(JwtConfig.class) -@Configuration -@Slf4j -public class JwtUtil { - @Autowired - private JwtConfig jwtConfig; - - @Autowired - private StringRedisTemplate stringRedisTemplate; - - /** - * 创建JWT - * - * @param rememberMe 记住我 - * @param id 用户id - * @param subject 用户名 - * @param roles 用户角色 - * @param authorities 用户权限 - * @return JWT - */ - public String createJWT(Boolean rememberMe, Long id, String subject, List roles, Collection authorities) { - Date now = new Date(); - JwtBuilder builder = Jwts.builder() - .setId(id.toString()) - .setSubject(subject) - .setIssuedAt(now) - .signWith(SignatureAlgorithm.HS256, jwtConfig.getKey()) - .claim("roles", roles) - .claim("authorities", authorities); - - // 设置过期时间 - Long ttl = rememberMe ? jwtConfig.getRemember() : jwtConfig.getTtl(); - if (ttl > 0) { - builder.setExpiration(DateUtil.offsetMillisecond(now, ttl.intValue())); - } - - String jwt = builder.compact(); - // 将生成的JWT保存至Redis - stringRedisTemplate.opsForValue() - .set(Consts.REDIS_JWT_KEY_PREFIX + subject, jwt, ttl, TimeUnit.MILLISECONDS); - return jwt; - } - - /** - * 创建JWT - * - * @param authentication 用户认证信息 - * @param rememberMe 记住我 - * @return JWT - */ - public String createJWT(Authentication authentication, Boolean rememberMe) { - UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal(); - return createJWT(rememberMe, userPrincipal.getId(), userPrincipal.getUsername(), userPrincipal.getRoles(), userPrincipal.getAuthorities()); - } - - /** - * 解析JWT - * - * @param jwt JWT - * @return {@link Claims} - */ - public Claims parseJWT(String jwt) { - try { - Claims claims = Jwts.parser() - .setSigningKey(jwtConfig.getKey()) - .parseClaimsJws(jwt) - .getBody(); - - String username = claims.getSubject(); - String redisKey = Consts.REDIS_JWT_KEY_PREFIX + username; - - // 校验redis中的JWT是否存在 - Long expire = stringRedisTemplate.getExpire(redisKey, TimeUnit.MILLISECONDS); - if (Objects.isNull(expire) || expire <= 0) { - throw new SecurityException(Status.TOKEN_EXPIRED); - } - - // 校验redis中的JWT是否与当前的一致,不一致则代表用户已注销/用户在不同设备登录,均代表JWT已过期 - String redisToken = stringRedisTemplate.opsForValue() - .get(redisKey); - if (!StrUtil.equals(jwt, redisToken)) { - throw new SecurityException(Status.TOKEN_OUT_OF_CTRL); - } - return claims; - } catch (ExpiredJwtException e) { - log.error("Token 已过期"); - throw new SecurityException(Status.TOKEN_EXPIRED); - } catch (UnsupportedJwtException e) { - log.error("不支持的 Token"); - throw new SecurityException(Status.TOKEN_PARSE_ERROR); - } catch (MalformedJwtException e) { - log.error("Token 无效"); - throw new SecurityException(Status.TOKEN_PARSE_ERROR); - } catch (SignatureException e) { - log.error("无效的 Token 签名"); - throw new SecurityException(Status.TOKEN_PARSE_ERROR); - } catch (IllegalArgumentException e) { - log.error("Token 参数不存在"); - throw new SecurityException(Status.TOKEN_PARSE_ERROR); - } - } - - /** - * 设置JWT过期 - * - * @param request 请求 - */ - public void invalidateJWT(HttpServletRequest request) { - String jwt = getJwtFromRequest(request); - String username = getUsernameFromJWT(jwt); - // 从redis中清除JWT - stringRedisTemplate.delete(Consts.REDIS_JWT_KEY_PREFIX + username); - } - - /** - * 根据 jwt 获取用户名 - * - * @param jwt JWT - * @return 用户名 - */ - public String getUsernameFromJWT(String jwt) { - Claims claims = parseJWT(jwt); - return claims.getSubject(); - } - - /** - * 从 request 的 header 中获取 JWT - * - * @param request 请求 - * @return JWT - */ - public String getJwtFromRequest(HttpServletRequest request) { - String bearerToken = request.getHeader("Authorization"); - if (StrUtil.isNotBlank(bearerToken) && bearerToken.startsWith("Bearer ")) { - return bearerToken.substring(7); - } - return null; - } - -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/util/PageUtil.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/util/PageUtil.java deleted file mode 100644 index 90d7576306..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/util/PageUtil.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.jun.plugin.rbac.security.util; - -import cn.hutool.core.util.ObjectUtil; -import cn.hutool.core.util.ReflectUtil; - -import org.springframework.data.domain.PageRequest; - -import com.jun.plugin.rbac.security.common.Consts; -import com.jun.plugin.rbac.security.payload.PageCondition; - -/** - *

    - * 分页工具类 - *

    - * - * @package: com.xkcoding.rbac.security.util - * @description: 分页工具类 - * @author: yangkai.shen - * @date: Created in 2018-12-12 18:09 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -public class PageUtil { - /** - * 校验分页参数,为NULL,设置分页参数默认值 - * - * @param condition 查询参数 - * @param clazz 类 - * @param {@link PageCondition} - */ - public static void checkPageCondition(T condition, Class clazz) { - if (ObjectUtil.isNull(condition)) { - condition = ReflectUtil.newInstance(clazz); - } - // 校验分页参数 - if (ObjectUtil.isNull(condition.getCurrentPage())) { - condition.setCurrentPage(Consts.DEFAULT_CURRENT_PAGE); - } - if (ObjectUtil.isNull(condition.getPageSize())) { - condition.setPageSize(Consts.DEFAULT_PAGE_SIZE); - } - } - - /** - * 根据分页参数构建{@link PageRequest} - * - * @param condition 查询参数 - * @param {@link PageCondition} - * @return {@link PageRequest} - */ - public static PageRequest ofPageRequest(T condition) { - return PageRequest.of(condition.getCurrentPage(), condition.getPageSize()); - } -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/util/RedisUtil.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/util/RedisUtil.java deleted file mode 100644 index e4a7cd5286..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/util/RedisUtil.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.jun.plugin.rbac.security.util; - -import com.google.common.collect.Lists; -import com.jun.plugin.rbac.security.common.PageResult; - -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.redis.connection.RedisConnection; -import org.springframework.data.redis.connection.RedisConnectionFactory; -import org.springframework.data.redis.core.Cursor; -import org.springframework.data.redis.core.RedisConnectionUtils; -import org.springframework.data.redis.core.ScanOptions; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.stereotype.Component; - -import java.util.Collection; -import java.util.List; - -/** - *

    - * Redis工具类 - *

    - * - * @package: com.xkcoding.rbac.security.util - * @description: Redis工具类 - * @author: yangkai.shen - * @date: Created in 2018-12-11 20:24 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Component -@Slf4j -public class RedisUtil { - @Autowired - private StringRedisTemplate stringRedisTemplate; - - /** - * 分页获取指定格式key,使用 scan 命令代替 keys 命令,在大数据量的情况下可以提高查询效率 - * - * @param patternKey key格式 - * @param currentPage 当前页码 - * @param pageSize 每页条数 - * @return 分页获取指定格式key - */ - public PageResult findKeysForPage(String patternKey, int currentPage, int pageSize) { - ScanOptions options = ScanOptions.scanOptions() - .match(patternKey) - .build(); - RedisConnectionFactory factory = stringRedisTemplate.getConnectionFactory(); - RedisConnection rc = factory.getConnection(); - Cursor cursor = rc.scan(options); - - List result = Lists.newArrayList(); - - long tmpIndex = 0; - int startIndex = (currentPage - 1) * pageSize; - int end = currentPage * pageSize; - while (cursor.hasNext()) { - String key = new String(cursor.next()); - if (tmpIndex >= startIndex && tmpIndex < end) { - result.add(key); - } - tmpIndex++; - } - - try { - cursor.close(); - RedisConnectionUtils.releaseConnection(rc, factory); - } catch (Exception e) { - log.warn("Redis连接关闭异常,", e); - } - - return new PageResult<>(result, tmpIndex); - } - - /** - * 删除 Redis 中的某个key - * - * @param key 键 - */ - public void delete(String key) { - stringRedisTemplate.delete(key); - } - - /** - * 批量删除 Redis 中的某些key - * - * @param keys 键列表 - */ - public void delete(Collection keys) { - stringRedisTemplate.delete(keys); - } -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/util/ResponseUtil.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/util/ResponseUtil.java deleted file mode 100644 index 9dd861cd6c..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/util/ResponseUtil.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.jun.plugin.rbac.security.util; - -import cn.hutool.json.JSONObject; -import cn.hutool.json.JSONUtil; -import lombok.extern.slf4j.Slf4j; - -import javax.servlet.http.HttpServletResponse; - -import com.jun.plugin.rbac.security.common.ApiResponse; -import com.jun.plugin.rbac.security.common.BaseException; -import com.jun.plugin.rbac.security.common.IStatus; - -import java.io.IOException; - -/** - *

    - * Response 通用工具类 - *

    - * - * @package: com.xkcoding.rbac.security.util - * @description: Response 通用工具类 - * @author: yangkai.shen - * @date: Created in 2018-12-07 17:37 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Slf4j -public class ResponseUtil { - - /** - * 往 response 写出 json - * - * @param response 响应 - * @param status 状态 - * @param data 返回数据 - */ - public static void renderJson(HttpServletResponse response, IStatus status, Object data) { - try { - response.setHeader("Access-Control-Allow-Origin", "*"); - response.setHeader("Access-Control-Allow-Methods", "*"); - response.setContentType("application/json;charset=UTF-8"); - response.setStatus(200); - - // FIXME: hutool 的 BUG:JSONUtil.toJsonStr() - // 将JSON转为String的时候,忽略null值的时候转成的String存在错误 - response.getWriter() - .write(JSONUtil.toJsonStr(new JSONObject(ApiResponse.ofStatus(status, data), false))); - } catch (IOException e) { - log.error("Response写出JSON异常,", e); - } - } - - /** - * 往 response 写出 json - * - * @param response 响应 - * @param exception 异常 - */ - public static void renderJson(HttpServletResponse response, BaseException exception) { - try { - response.setHeader("Access-Control-Allow-Origin", "*"); - response.setHeader("Access-Control-Allow-Methods", "*"); - response.setContentType("application/json;charset=UTF-8"); - response.setStatus(200); - - // FIXME: hutool 的 BUG:JSONUtil.toJsonStr() - // 将JSON转为String的时候,忽略null值的时候转成的String存在错误 - response.getWriter() - .write(JSONUtil.toJsonStr(new JSONObject(ApiResponse.ofException(exception), false))); - } catch (IOException e) { - log.error("Response写出JSON异常,", e); - } - } -} \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/util/SecurityUtil.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/util/SecurityUtil.java deleted file mode 100644 index c3f4219096..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/util/SecurityUtil.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.jun.plugin.rbac.security.util; - -import cn.hutool.core.util.ObjectUtil; - -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UserDetails; - -import com.jun.plugin.rbac.security.common.Consts; -import com.jun.plugin.rbac.security.vo.UserPrincipal; - -/** - *

    - * Spring Security工具类 - *

    - * - * @package: com.xkcoding.rbac.security.util - * @description: Spring Security工具类 - * @author: yangkai.shen - * @date: Created in 2018-12-12 18:30 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -public class SecurityUtil { - /** - * 获取当前登录用户用户名 - * - * @return 当前登录用户用户名 - */ - public static String getCurrentUsername() { - UserPrincipal currentUser = getCurrentUser(); - return ObjectUtil.isNull(currentUser) ? Consts.ANONYMOUS_NAME : currentUser.getUsername(); - } - - /** - * 获取当前登录用户信息 - * - * @return 当前登录用户信息,匿名登录时,为null - */ - public static UserPrincipal getCurrentUser() { - Object userInfo = SecurityContextHolder.getContext() - .getAuthentication() - .getPrincipal(); - if (userInfo instanceof UserDetails) { - return (UserPrincipal) userInfo; - } - return null; - } -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/vo/JwtResponse.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/vo/JwtResponse.java deleted file mode 100644 index 778d88fe66..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/vo/JwtResponse.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.jun.plugin.rbac.security.vo; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - *

    - * JWT 响应返回 - *

    - * - * @package: com.xkcoding.rbac.security.vo - * @description: JWT 响应返回 - * @author: yangkai.shen - * @date: Created in 2018-12-10 16:01 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Data -@NoArgsConstructor -@AllArgsConstructor -public class JwtResponse { - /** - * token 字段 - */ - private String token; - /** - * token类型 - */ - private String tokenType = "Bearer"; - - public JwtResponse(String token) { - this.token = token; - } -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/vo/OnlineUser.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/vo/OnlineUser.java deleted file mode 100644 index ac0f1de25e..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/vo/OnlineUser.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.jun.plugin.rbac.security.vo; - -import com.jun.plugin.rbac.security.common.Consts; -import com.jun.plugin.rbac.security.model.User; - -import cn.hutool.core.bean.BeanUtil; -import cn.hutool.core.util.StrUtil; -import lombok.Data; - -/** - *

    - * 在线用户 VO - *

    - * - * @package: com.xkcoding.rbac.security.vo - * @description: 在线用户 VO - * @author: yangkai.shen - * @date: Created in 2018-12-12 00:58 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Data -public class OnlineUser { - - /** - * 主键 - */ - private Long id; - - /** - * 用户名 - */ - private String username; - - /** - * 昵称 - */ - private String nickname; - - /** - * 手机 - */ - private String phone; - - /** - * 邮箱 - */ - private String email; - - /** - * 生日 - */ - private Long birthday; - - /** - * 性别,男-1,女-2 - */ - private Integer sex; - - public static OnlineUser create(User user) { - OnlineUser onlineUser = new OnlineUser(); - BeanUtil.copyProperties(user, onlineUser); - // 脱敏 - onlineUser.setPhone(StrUtil.hide(user.getPhone(), 3, 7)); - onlineUser.setEmail(StrUtil.hide(user.getEmail(), 1, StrUtil.indexOfIgnoreCase(user.getEmail(), Consts.SYMBOL_EMAIL))); - return onlineUser; - } -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/vo/UserPrincipal.java b/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/vo/UserPrincipal.java deleted file mode 100644 index ec8bbe19d8..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/java/com/jun/plugin/rbac/security/vo/UserPrincipal.java +++ /dev/null @@ -1,152 +0,0 @@ -package com.jun.plugin.rbac.security.vo; - -import cn.hutool.core.util.StrUtil; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.jun.plugin.rbac.security.common.Consts; -import com.jun.plugin.rbac.security.model.Permission; -import com.jun.plugin.rbac.security.model.Role; -import com.jun.plugin.rbac.security.model.User; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.userdetails.UserDetails; - -import java.util.Collection; -import java.util.List; -import java.util.Objects; -import java.util.stream.Collectors; - -/** - *

    - * 自定义User - *

    - * - * @package: com.xkcoding.rbac.security.vo - * @description: 自定义User - * @author: yangkai.shen - * @date: Created in 2018-12-10 15:09 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Data -@NoArgsConstructor -@AllArgsConstructor -public class UserPrincipal implements UserDetails { - /** - * 主键 - */ - private Long id; - - /** - * 用户名 - */ - private String username; - - /** - * 密码 - */ - @JsonIgnore - private String password; - - /** - * 昵称 - */ - private String nickname; - - /** - * 手机 - */ - private String phone; - - /** - * 邮箱 - */ - private String email; - - /** - * 生日 - */ - private Long birthday; - - /** - * 性别,男-1,女-2 - */ - private Integer sex; - - /** - * 状态,启用-1,禁用-0 - */ - private Integer status; - - /** - * 创建时间 - */ - private Long createTime; - - /** - * 更新时间 - */ - private Long updateTime; - - /** - * 用户角色列表 - */ - private List roles; - - /** - * 用户权限列表 - */ - private Collection authorities; - - public static UserPrincipal create(User user, List roles, List permissions) { - List roleNames = roles.stream() - .map(Role::getName) - .collect(Collectors.toList()); - - List authorities = permissions.stream() - .filter(permission -> StrUtil.isNotBlank(permission.getPermission())) - .map(permission -> new SimpleGrantedAuthority(permission.getPermission())) - .collect(Collectors.toList()); - - return new UserPrincipal(user.getId(), user.getUsername(), user.getPassword(), user.getNickname(), user.getPhone(), user.getEmail(), user.getBirthday(), user.getSex(), user.getStatus(), user.getCreateTime(), user.getUpdateTime(), roleNames, authorities); - } - - @Override - public Collection getAuthorities() { - return authorities; - } - - @Override - public String getPassword() { - return password; - } - - @Override - public String getUsername() { - return username; - } - - @Override - public boolean isAccountNonExpired() { - return true; - } - - @Override - public boolean isAccountNonLocked() { - return true; - } - - @Override - public boolean isCredentialsNonExpired() { - return true; - } - - @Override - public boolean isEnabled() { - return Objects.equals(this.status, Consts.ENABLE); - } -} \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_rbac_security/src/main/resources/application.yml b/jun_springboot_plugin/springboot_rbac_security/src/main/resources/application.yml deleted file mode 100644 index 6740dc603a..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/main/resources/application.yml +++ /dev/null @@ -1,59 +0,0 @@ -server: - port: 8080 - servlet: - context-path: /demo -spring: - datasource: - hikari: - username: root - password: root - driver-class-name: com.mysql.cj.jdbc.Driver - url: jdbc:mysql://127.0.0.1:3306/spring-boot-demo?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8 - jpa: - show-sql: true - generate-ddl: false - hibernate: - ddl-auto: validate - open-in-view: true - properties: - hibernate: - dialect: org.hibernate.dialect.MySQL57InnoDBDialect - resources: - add-mappings: false - mvc: - throw-exception-if-no-handler-found: true - redis: - host: localhost - port: 6379 - # 连接超时时间(记得添加单位,Duration) - timeout: 10000ms - # Redis默认情况下有16个分片,这里配置具体使用的分片 - # database: 0 - lettuce: - pool: - # 连接池最大连接数(使用负值表示没有限制) 默认 8 - max-active: 8 - # 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1 - max-wait: -1ms - # 连接池中的最大空闲连接 默认 8 - max-idle: 8 - # 连接池中的最小空闲连接 默认 0 - min-idle: 0 -jwt: - config: - key: xkcoding - ttl: 600000 - remember: 604800000 -logging: - level: - com.jun.plugin.rbac.security: debug -custom: - config: - ignores: - # 需要过滤的 post 请求 - post: - - "/api/auth/login" - - "/api/auth/logout" - # 需要过滤的请求,不限方法 - pattern: - - "/test/*" \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_rbac_security/src/test/java/com/jun/plugin/rbac/security/SpringBootDemoRbacSecurityApplicationTests.java b/jun_springboot_plugin/springboot_rbac_security/src/test/java/com/jun/plugin/rbac/security/SpringBootDemoRbacSecurityApplicationTests.java deleted file mode 100644 index f48d2793d6..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/test/java/com/jun/plugin/rbac/security/SpringBootDemoRbacSecurityApplicationTests.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.jun.plugin.rbac.security; - -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 SpringBootDemoRbacSecurityApplicationTests { - - @Test - public void contextLoads() { - } - -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/test/java/com/jun/plugin/rbac/security/repository/DataInitTest.java b/jun_springboot_plugin/springboot_rbac_security/src/test/java/com/jun/plugin/rbac/security/repository/DataInitTest.java deleted file mode 100644 index c57d9eef88..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/test/java/com/jun/plugin/rbac/security/repository/DataInitTest.java +++ /dev/null @@ -1,152 +0,0 @@ -package com.jun.plugin.rbac.security.repository; - -import cn.hutool.core.date.DateTime; -import cn.hutool.core.date.DateUtil; -import cn.hutool.core.lang.Snowflake; - -import com.jun.plugin.rbac.security.SpringBootDemoRbacSecurityApplicationTests; -import com.jun.plugin.rbac.security.model.*; -import com.jun.plugin.rbac.security.model.unionkey.RolePermissionKey; -import com.jun.plugin.rbac.security.model.unionkey.UserRoleKey; -import com.jun.plugin.rbac.security.repository.PermissionDao; -import com.jun.plugin.rbac.security.repository.RoleDao; -import com.jun.plugin.rbac.security.repository.RolePermissionDao; -import com.jun.plugin.rbac.security.repository.UserDao; -import com.jun.plugin.rbac.security.repository.UserRoleDao; - -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; - -/** - *

    - * 数据初始化测试 - *

    - * - * @package: com.xkcoding.rbac.security.repository - * @description: 数据初始化测试 - * @author: yangkai.shen - * @date: Created in 2018-12-10 11:26 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -public class DataInitTest extends SpringBootDemoRbacSecurityApplicationTests { - @Autowired - private UserDao userDao; - - @Autowired - private RoleDao roleDao; - - @Autowired - private PermissionDao permissionDao; - - @Autowired - private UserRoleDao userRoleDao; - - @Autowired - private RolePermissionDao rolePermissionDao; - - @Autowired - private Snowflake snowflake; - - @Autowired - private BCryptPasswordEncoder encoder; - - @Test - public void initTest() { - init(); - } - - private void init() { - User admin = createUser(true); - User user = createUser(false); - - Role roleAdmin = createRole(true); - Role roleUser = createRole(false); - - createUserRoleRelation(admin.getId(), roleAdmin.getId()); - createUserRoleRelation(user.getId(), roleUser.getId()); - - // 页面权限 - Permission testPagePerm = createPermission("/test", "测试页面", 1, "page:test", null, 1, 0L); - // 按钮权限 - Permission testBtnQueryPerm = createPermission("/**/test", "测试页面-查询", 2, "btn:test:query", "GET", 1, testPagePerm.getId()); - Permission testBtnPermInsert = createPermission("/**/test", "测试页面-添加", 2, "btn:test:insert", "POST", 2, testPagePerm.getId()); - - Permission monitorOnlinePagePerm = createPermission("/monitor", "监控在线用户页面", 1, "page:monitor:online", null, 2, 0L); - Permission monitorOnlineBtnQueryPerm = createPermission("/**/api/monitor/online/user", "在线用户页面-查询", 2, "btn:monitor:online:query", "GET", 1, monitorOnlinePagePerm.getId()); - Permission monitorOnlineBtnKickoutPerm = createPermission("/**/api/monitor/online/user/kickout", "在线用户页面-踢出", 2, "btn:monitor:online:kickout", "DELETE", 2, monitorOnlinePagePerm.getId()); - - createRolePermissionRelation(roleAdmin.getId(), testPagePerm.getId()); - createRolePermissionRelation(roleUser.getId(), testPagePerm.getId()); - createRolePermissionRelation(roleAdmin.getId(), testBtnQueryPerm.getId()); - createRolePermissionRelation(roleUser.getId(), testBtnQueryPerm.getId()); - createRolePermissionRelation(roleAdmin.getId(), testBtnPermInsert.getId()); - createRolePermissionRelation(roleAdmin.getId(), monitorOnlinePagePerm.getId()); - createRolePermissionRelation(roleAdmin.getId(), monitorOnlineBtnQueryPerm.getId()); - createRolePermissionRelation(roleAdmin.getId(), monitorOnlineBtnKickoutPerm.getId()); - } - - private void createRolePermissionRelation(Long roleId, Long permissionId) { - RolePermission adminPage = new RolePermission(); - RolePermissionKey adminPageKey = new RolePermissionKey(); - adminPageKey.setRoleId(roleId); - adminPageKey.setPermissionId(permissionId); - adminPage.setId(adminPageKey); - rolePermissionDao.save(adminPage); - } - - private Permission createPermission(String url, String name, Integer type, String permission, String method, Integer sort, Long parentId) { - Permission perm = new Permission(); - perm.setId(snowflake.nextId()); - perm.setUrl(url); - perm.setName(name); - perm.setType(type); - perm.setPermission(permission); - perm.setMethod(method); - perm.setSort(sort); - perm.setParentId(parentId); - permissionDao.save(perm); - return perm; - } - - private void createUserRoleRelation(Long userId, Long roleId) { - UserRole userRole = new UserRole(); - UserRoleKey key = new UserRoleKey(); - key.setUserId(userId); - key.setRoleId(roleId); - userRole.setId(key); - userRoleDao.save(userRole); - } - - private Role createRole(boolean isAdmin) { - Role role = new Role(); - role.setId(snowflake.nextId()); - role.setName(isAdmin ? "管理员" : "普通用户"); - role.setDescription(isAdmin ? "超级管理员" : "普通用户"); - role.setCreateTime(DateUtil.current(false)); - role.setUpdateTime(DateUtil.current(false)); - roleDao.save(role); - return role; - } - - private User createUser(boolean isAdmin) { - User user = new User(); - user.setId(snowflake.nextId()); - user.setUsername(isAdmin ? "admin" : "user"); - user.setNickname(isAdmin ? "管理员" : "普通用户"); - user.setPassword(encoder.encode("123456")); - user.setBirthday(DateTime.of("1994-11-22", "yyyy-MM-dd") - .getTime()); - user.setEmail((isAdmin ? "admin" : "user") + "@xkcoding.com"); - user.setPhone(isAdmin ? "17300000000" : "17300001111"); - user.setSex(1); - user.setStatus(1); - user.setCreateTime(DateUtil.current(false)); - user.setUpdateTime(DateUtil.current(false)); - userDao.save(user); - return user; - } - -} diff --git a/jun_springboot_plugin/springboot_rbac_security/src/test/java/com/jun/plugin/rbac/security/repository/UserDaoTest.java b/jun_springboot_plugin/springboot_rbac_security/src/test/java/com/jun/plugin/rbac/security/repository/UserDaoTest.java deleted file mode 100644 index 67b590eddf..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/test/java/com/jun/plugin/rbac/security/repository/UserDaoTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.jun.plugin.rbac.security.repository; - -import com.jun.plugin.rbac.security.SpringBootDemoRbacSecurityApplicationTests; -import com.jun.plugin.rbac.security.model.User; -import com.jun.plugin.rbac.security.repository.UserDao; - -import lombok.extern.slf4j.Slf4j; -import org.assertj.core.util.Lists; -import org.junit.Assert; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; - -import java.util.List; -import java.util.Optional; - -/** - *

    - * UserDao 测试 - *

    - * - * @package: com.xkcoding.rbac.security.repository - * @description: UserDao 测试 - * @author: yangkai.shen - * @date: Created in 2018-12-12 01:10 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Slf4j -public class UserDaoTest extends SpringBootDemoRbacSecurityApplicationTests { - @Autowired - private UserDao userDao; - - @Test - public void findByUsernameIn() { - List usernameList = Lists.newArrayList("admin", "user"); - List userList = userDao.findByUsernameIn(usernameList); - Assert.assertEquals(2, userList.size()); - log.info("【userList】= {}", userList); - } -} \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_rbac_security/src/test/java/com/jun/plugin/rbac/security/util/RedisUtilTest.java b/jun_springboot_plugin/springboot_rbac_security/src/test/java/com/jun/plugin/rbac/security/util/RedisUtilTest.java deleted file mode 100644 index a402a43374..0000000000 --- a/jun_springboot_plugin/springboot_rbac_security/src/test/java/com/jun/plugin/rbac/security/util/RedisUtilTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.jun.plugin.rbac.security.util; - -import cn.hutool.json.JSONUtil; - -import com.jun.plugin.rbac.security.SpringBootDemoRbacSecurityApplicationTests; -import com.jun.plugin.rbac.security.common.Consts; -import com.jun.plugin.rbac.security.common.PageResult; -import com.jun.plugin.rbac.security.util.RedisUtil; - -import lombok.extern.slf4j.Slf4j; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; - -/** - *

    - * 测试RedisUtil - *

    - * - * @package: com.xkcoding.rbac.security.util - * @description: 测试RedisUtil - * @author: yangkai.shen - * @date: Created in 2018-12-11 20:44 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Slf4j -public class RedisUtilTest extends SpringBootDemoRbacSecurityApplicationTests { - @Autowired - private RedisUtil redisUtil; - - @Test - public void findKeysForPage() { - PageResult pageResult = redisUtil.findKeysForPage(Consts.REDIS_JWT_KEY_PREFIX + Consts.SYMBOL_STAR, 2, 1); - log.info("【pageResult】= {}", JSONUtil.toJsonStr(pageResult)); - } -} \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_rbac_shiro/pom.xml b/jun_springboot_plugin/springboot_rbac_shiro/pom.xml deleted file mode 100644 index 313902374b..0000000000 --- a/jun_springboot_plugin/springboot_rbac_shiro/pom.xml +++ /dev/null @@ -1,100 +0,0 @@ - - - 4.0.0 - - io.github.wujun728 - springboot_rbac_shiro - 1.0 - jar - - springboot_rbac_shiro - Demo project for Spring Boot - - - io.github.wujun728 - jun_springboot_plugin - 1.0 - - - - UTF-8 - UTF-8 - 1.8 - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - - org.springframework.boot - spring-boot-starter-undertow - - - - org.springframework.boot - spring-boot-starter-test - test - - - - com.baomidou - mybatis-plus-boot-starter - 3.1.0 - - - - p6spy - p6spy - 3.8.1 - - - - - org.apache.shiro - shiro-spring-boot-starter - 1.4.0 - - - - mysql - mysql-connector-java - - - - cn.hutool - hutool-all - - - - com.google.guava - guava - - - - org.projectlombok - lombok - true - - - - - springboot_rbac_shiro - - - org.springframework.boot - spring-boot-maven-plugin - - - - - diff --git a/jun_springboot_plugin/springboot_rbac_shiro/sql/shiro.sql b/jun_springboot_plugin/springboot_rbac_shiro/sql/shiro.sql deleted file mode 100644 index 01b9213019..0000000000 --- a/jun_springboot_plugin/springboot_rbac_shiro/sql/shiro.sql +++ /dev/null @@ -1,101 +0,0 @@ -/* - Navicat Premium Data Transfer - - Source Server : 本机 - Source Server Type : MySQL - Source Server Version : 50718 - Source Host : localhost:3306 - Source Schema : spring-boot-demo - - Target Server Type : MySQL - Target Server Version : 50718 - File Encoding : 65001 - - Date: 12/12/2018 18:52:51 -*/ - -SET NAMES utf8mb4; -SET FOREIGN_KEY_CHECKS = 0; - --- ---------------------------- --- Table structure for sec_user --- ---------------------------- -DROP TABLE IF EXISTS `shiro_user`; -CREATE TABLE `shiro_user` -( - `id` bigint(64) NOT NULL COMMENT '主键', - `username` varchar(50) NOT NULL COMMENT '用户名', - `password` varchar(60) NOT NULL COMMENT '密码', - `salt` varchar(60) NOT NULL COMMENT '盐值', - `nickname` varchar(255) DEFAULT NULL COMMENT '昵称', - `phone` varchar(11) DEFAULT NULL COMMENT '手机', - `email` varchar(50) DEFAULT NULL COMMENT '邮箱', - `birthday` bigint(13) DEFAULT NULL COMMENT '生日', - `sex` int(2) DEFAULT NULL COMMENT '性别,男-1,女-2', - `status` int(2) NOT NULL DEFAULT '1' COMMENT '状态,启用-1,禁用-0', - `create_time` bigint(13) NOT NULL COMMENT '创建时间', - `update_time` bigint(13) NOT NULL COMMENT '更新时间', - PRIMARY KEY (`id`), - UNIQUE KEY `username` (`username`), - UNIQUE KEY `phone` (`phone`), - UNIQUE KEY `email` (`email`) -) ENGINE = InnoDB - DEFAULT CHARSET = utf8 COMMENT ='用户表'; - --- ---------------------------- --- Table structure for sec_role --- ---------------------------- -DROP TABLE IF EXISTS `shiro_role`; -CREATE TABLE `shiro_role` -( - `id` bigint(64) NOT NULL COMMENT '主键', - `name` varchar(50) NOT NULL COMMENT '角色名', - `description` varchar(100) DEFAULT NULL COMMENT '描述', - `create_time` bigint(13) NOT NULL COMMENT '创建时间', - `update_time` bigint(13) NOT NULL COMMENT '更新时间', - PRIMARY KEY (`id`), - UNIQUE KEY `name` (`name`) -) ENGINE = InnoDB - DEFAULT CHARSET = utf8 COMMENT ='角色表'; - --- ---------------------------- --- Table structure for sec_user_role --- ---------------------------- -DROP TABLE IF EXISTS `shiro_user_role`; -CREATE TABLE `shiro_user_role` -( - `user_id` bigint(64) NOT NULL COMMENT '用户主键', - `role_id` bigint(64) NOT NULL COMMENT '角色主键', - PRIMARY KEY (`user_id`, `role_id`) -) ENGINE = InnoDB - DEFAULT CHARSET = utf8 COMMENT ='用户角色关系表'; - --- ---------------------------- --- Table structure for sec_permission --- ---------------------------- -DROP TABLE IF EXISTS `shiro_permission`; -CREATE TABLE `shiro_permission` -( - `id` bigint(64) NOT NULL COMMENT '主键', - `name` varchar(50) NOT NULL COMMENT '权限名', - `url` varchar(1000) DEFAULT NULL COMMENT '类型为页面时,代表前端路由地址,类型为按钮时,代表后端接口地址', - `type` int(2) NOT NULL COMMENT '权限类型,页面-1,按钮-2', - `permission` varchar(50) DEFAULT NULL COMMENT '权限表达式', - `method` varchar(50) DEFAULT NULL COMMENT '后端接口访问方式', - `sort` int(11) NOT NULL COMMENT '排序', - `parent_id` bigint(64) NOT NULL COMMENT '父级id', - PRIMARY KEY (`id`) -) ENGINE = InnoDB - DEFAULT CHARSET = utf8 COMMENT ='权限表'; - --- ---------------------------- --- Table structure for sec_role_permission --- ---------------------------- -DROP TABLE IF EXISTS `shiro_role_permission`; -CREATE TABLE `shiro_role_permission` -( - `role_id` bigint(64) NOT NULL COMMENT '角色主键', - `permission_id` bigint(64) NOT NULL COMMENT '权限主键', - PRIMARY KEY (`role_id`, `permission_id`) -) ENGINE = InnoDB - DEFAULT CHARSET = utf8 COMMENT ='角色权限关系表'; \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_rbac_shiro/src/main/java/com/jun/plugin/rbac/shiro/SpringBootDemoRbacShiroApplication.java b/jun_springboot_plugin/springboot_rbac_shiro/src/main/java/com/jun/plugin/rbac/shiro/SpringBootDemoRbacShiroApplication.java deleted file mode 100644 index 0a0e0d867b..0000000000 --- a/jun_springboot_plugin/springboot_rbac_shiro/src/main/java/com/jun/plugin/rbac/shiro/SpringBootDemoRbacShiroApplication.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.jun.plugin.rbac.shiro; - -import org.mybatis.spring.annotation.MapperScan; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -/** - *

    - * 启动器 - *

    - * - * @package: com.xkcoding.rbac.shiro - * @description: 启动器 - * @author: yangkai.shen - * @date: Created in 2019-03-21 16:11 - * @copyright: Copyright (c) 2019 - * @version: V1.0 - * @modified: yangkai.shen - */ -@SpringBootApplication -@MapperScan("com.xkcoding.rbac.shiro.mapper") -public class SpringBootDemoRbacShiroApplication { - - public static void main(String[] args) { - SpringApplication.run(SpringBootDemoRbacShiroApplication.class, args); - } -} diff --git a/jun_springboot_plugin/springboot_rbac_shiro/src/main/java/com/jun/plugin/rbac/shiro/common/IResultCode.java b/jun_springboot_plugin/springboot_rbac_shiro/src/main/java/com/jun/plugin/rbac/shiro/common/IResultCode.java deleted file mode 100644 index 3087deed60..0000000000 --- a/jun_springboot_plugin/springboot_rbac_shiro/src/main/java/com/jun/plugin/rbac/shiro/common/IResultCode.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.jun.plugin.rbac.shiro.common; - -/** - *

    - * 统一状态码接口 - *

    - * - * @package: com.xkcoding.rbac.shiro.common - * @description: 统一状态码接口 - * @author: yangkai.shen - * @date: Created in 2019-03-21 16:28 - * @copyright: Copyright (c) 2019 - * @version: V1.0 - * @modified: yangkai.shen - */ -public interface IResultCode { - /** - * 获取状态码 - * - * @return 状态码 - */ - Integer getCode(); - - /** - * 获取返回消息 - * - * @return 返回消息 - */ - String getMessage(); -} diff --git a/jun_springboot_plugin/springboot_rbac_shiro/src/main/java/com/jun/plugin/rbac/shiro/common/R.java b/jun_springboot_plugin/springboot_rbac_shiro/src/main/java/com/jun/plugin/rbac/shiro/common/R.java deleted file mode 100644 index 49f2016e36..0000000000 --- a/jun_springboot_plugin/springboot_rbac_shiro/src/main/java/com/jun/plugin/rbac/shiro/common/R.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.jun.plugin.rbac.shiro.common; - -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - *

    - * 统一API对象返回 - *

    - * - * @package: com.xkcoding.rbac.shiro.common - * @description: 统一API对象返回 - * @author: yangkai.shen - * @date: Created in 2019-03-21 16:24 - * @copyright: Copyright (c) 2019 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Data -@NoArgsConstructor -public class R { - /** - * 状态码 - */ - private Integer code; - - /** - * 返回消息 - */ - private String message; - - /** - * 状态 - */ - private boolean status; - - /** - * 返回数据 - */ - private T data; - - public R(Integer code, String message, boolean status, T data) { - this.code = code; - this.message = message; - this.status = status; - this.data = data; - } - - public R(IResultCode resultCode, boolean status, T data) { - this.code = resultCode.getCode(); - this.message = resultCode.getMessage(); - this.status = status; - this.data = data; - } - - public R(IResultCode resultCode, boolean status) { - this.code = resultCode.getCode(); - this.message = resultCode.getMessage(); - this.status = status; - this.data = null; - } - - public static R success() { - return new R<>(ResultCode.OK, true); - } - - public static R message(String message) { - return new R<>(ResultCode.OK.getCode(), message, true, null); - } - - public static R success(T data) { - return new R<>(ResultCode.OK, true, data); - } - - public static R fail() { - return new R<>(ResultCode.ERROR, false); - } - - public static R fail(IResultCode resultCode) { - return new R<>(resultCode, false); - } - - public static R fail(Integer code, String message) { - return new R<>(code, message, false, null); - } - - public static R fail(IResultCode resultCode, T data) { - return new R<>(resultCode, false, data); - } - - public static R fail(Integer code, String message, T data) { - return new R<>(code, message, false, data); - } - -} diff --git a/jun_springboot_plugin/springboot_rbac_shiro/src/main/java/com/jun/plugin/rbac/shiro/common/ResultCode.java b/jun_springboot_plugin/springboot_rbac_shiro/src/main/java/com/jun/plugin/rbac/shiro/common/ResultCode.java deleted file mode 100644 index 702154d476..0000000000 --- a/jun_springboot_plugin/springboot_rbac_shiro/src/main/java/com/jun/plugin/rbac/shiro/common/ResultCode.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.jun.plugin.rbac.shiro.common; - -import lombok.Getter; - -/** - *

    - * 通用状态枚举 - *

    - * - * @package: com.xkcoding.rbac.shiro.common - * @description: 通用状态枚举 - * @author: yangkai.shen - * @date: Created in 2019-03-21 16:31 - * @copyright: Copyright (c) 2019 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Getter -public enum ResultCode implements IResultCode { - /** - * 成功 - */ - OK(200, "成功"), - /** - * 失败 - */ - ERROR(500, "失败"); - - /** - * 返回码 - */ - private Integer code; - - /** - * 返回消息 - */ - private String message; - - ResultCode(Integer code, String message) { - this.code = code; - this.message = message; - } - -} diff --git a/jun_springboot_plugin/springboot_rbac_shiro/src/main/java/com/jun/plugin/rbac/shiro/config/MybatisPlusConfig.java b/jun_springboot_plugin/springboot_rbac_shiro/src/main/java/com/jun/plugin/rbac/shiro/config/MybatisPlusConfig.java deleted file mode 100644 index 43484211ab..0000000000 --- a/jun_springboot_plugin/springboot_rbac_shiro/src/main/java/com/jun/plugin/rbac/shiro/config/MybatisPlusConfig.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.jun.plugin.rbac.shiro.config; - -import com.baomidou.mybatisplus.core.parser.ISqlParser; -import com.baomidou.mybatisplus.extension.parsers.BlockAttackSqlParser; -import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; -import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import java.util.ArrayList; -import java.util.List; - -/** - *

    - * MP3 配置 - *

    - * - * @package: com.xkcoding.rbac.shiro.config - * @description: MP3 配置 - * @author: yangkai.shen - * @date: Created in 2019-03-21 17:06 - * @copyright: Copyright (c) 2019 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Configuration -public class MybatisPlusConfig { - - @Bean - public PaginationInterceptor paginationInterceptor() { - PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); - - List sqlParserList = new ArrayList<>(); - // 攻击 SQL 阻断解析器、加入解析链 - sqlParserList.add(new BlockAttackSqlParser()); - paginationInterceptor.setSqlParserList(sqlParserList); - - return paginationInterceptor; - } - - /** - * SQL执行效率插件 - */ - @Bean - public PerformanceInterceptor performanceInterceptor() { - return new PerformanceInterceptor(); - } -} diff --git a/jun_springboot_plugin/springboot_rbac_shiro/src/main/java/com/jun/plugin/rbac/shiro/controller/TestController.java b/jun_springboot_plugin/springboot_rbac_shiro/src/main/java/com/jun/plugin/rbac/shiro/controller/TestController.java deleted file mode 100644 index bffd5a9fa4..0000000000 --- a/jun_springboot_plugin/springboot_rbac_shiro/src/main/java/com/jun/plugin/rbac/shiro/controller/TestController.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.jun.plugin.rbac.shiro.controller; - -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import com.jun.plugin.rbac.shiro.common.R; - -/** - *

    - * 测试Controller - *

    - * - * @package: com.xkcoding.rbac.shiro.controller - * @description: 测试Controller - * @author: yangkai.shen - * @date: Created in 2019-03-21 16:13 - * @copyright: Copyright (c) 2019 - * @version: V1.0 - * @modified: yangkai.shen - */ -@RestController -@RequestMapping("/test") -public class TestController { - - @GetMapping("") - public R test() { - return R.success(); - } -} diff --git a/jun_springboot_plugin/springboot_rbac_shiro/src/main/resources/application.yml b/jun_springboot_plugin/springboot_rbac_shiro/src/main/resources/application.yml deleted file mode 100644 index 44b6c3a74e..0000000000 --- a/jun_springboot_plugin/springboot_rbac_shiro/src/main/resources/application.yml +++ /dev/null @@ -1,15 +0,0 @@ -server: - port: 8080 - servlet: - context-path: /demo -spring: - datasource: - hikari: - username: root - password: root - driver-class-name: com.p6spy.engine.spy.P6SpyDriver - url: jdbc:p6spy:mysql://127.0.0.1:3306/spring-boot-demo?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8 -mybatis-plus: - global-config: - # 关闭banner - banner: false \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_rbac_shiro/src/main/resources/spy.properties b/jun_springboot_plugin/springboot_rbac_shiro/src/main/resources/spy.properties deleted file mode 100644 index f611f24ef6..0000000000 --- a/jun_springboot_plugin/springboot_rbac_shiro/src/main/resources/spy.properties +++ /dev/null @@ -1,21 +0,0 @@ -module.log=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory -# 自定义日志打印 -logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger -#日志输出到控制台 -appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger -# 使用日志系统记录 sql -#appender=com.p6spy.engine.spy.appender.Slf4JLogger -# 设置 p6spy driver 代理 -deregisterdrivers=true -# 取消JDBC URL前缀 -useprefix=true -# 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset. -excludecategories=info,debug,result,batch,resultset -# 日期格式 -dateformat=yyyy-MM-dd HH:mm:ss -# 实际驱动可多个 -#driverlist=org.h2.Driver -# 是否开启慢SQL记录 -outagedetection=true -# 慢SQL记录标准 2 秒 -outagedetectioninterval=2 \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_rbac_shiro/src/test/java/com/jun/plugin/rbac/shiro/SpringBootDemoRbacShiroApplicationTests.java b/jun_springboot_plugin/springboot_rbac_shiro/src/test/java/com/jun/plugin/rbac/shiro/SpringBootDemoRbacShiroApplicationTests.java deleted file mode 100644 index 9f083744b1..0000000000 --- a/jun_springboot_plugin/springboot_rbac_shiro/src/test/java/com/jun/plugin/rbac/shiro/SpringBootDemoRbacShiroApplicationTests.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.jun.plugin.rbac.shiro; - -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 SpringBootDemoRbacShiroApplicationTests { - - @Test - public void contextLoads() { - } - -} diff --git a/jun_springboot_plugin/springboot_redis/.gitignore b/jun_springboot_plugin/springboot_redis/.gitignore deleted file mode 100644 index 1e3c5bbc80..0000000000 --- a/jun_springboot_plugin/springboot_redis/.gitignore +++ /dev/null @@ -1,14 +0,0 @@ -# 此为注释– 将被Git 忽略 -# /结尾表示是目录,忽略目录和目录下的所有件 -# /开头表示根目录,否则是.gitignore的相对目录 -# !开头表示反选 -.idea/ -target/ -*.iml -*.ipr -*.iws -*.log -.svn/ -.project -rebel.xml -.rebel-remote.xml.* diff --git a/jun_springboot_plugin/springboot_redis/README.md b/jun_springboot_plugin/springboot_redis/README.md deleted file mode 100644 index 07493b209b..0000000000 --- a/jun_springboot_plugin/springboot_redis/README.md +++ /dev/null @@ -1,17 +0,0 @@ -## SpringBoot Redis演示项目 - -SpringBoot中通过RedisTemplate来直接操作Redis缓存数据库 - -## 运行 - -初始化sql文件在`resources/sql/t_user.sql`中 - -另外还需要安装Redis,配置好`application.yml`文件中的redis地址 - -测试用例:`com.xncoding.service.UserServiceTest.java` - -## 许可证 - -Copyright (c) 2018 Xiong Neng - -基于 MIT 协议发布: diff --git a/jun_springboot_plugin/springboot_redis/pom.xml b/jun_springboot_plugin/springboot_redis/pom.xml deleted file mode 100644 index 8ddeaa2f1d..0000000000 --- a/jun_springboot_plugin/springboot_redis/pom.xml +++ /dev/null @@ -1,138 +0,0 @@ - - - 4.0.0 - - io.github.wujun728 - springboot_redis - 1.0 - jar - - SpringBoot Redis演示 - - - org.springframework.boot - spring-boot-starter-parent - 2.5.14 - - - - - UTF-8 - UTF-8 - 1.8 - 2.9.4 - 1.1.2 - 8.0.7-dmr - 2.1.8 - 1.0.5 - - - - - org.springframework.boot - spring-boot-starter-data-redis - - - org.apache.commons - commons-pool2 - - - - com.fasterxml.jackson.core - jackson-core - ${jackson-databind-version} - - - com.fasterxml.jackson.core - jackson-databind - ${jackson-databind-version} - - - com.fasterxml.jackson.core - jackson-annotations - ${jackson-databind-version} - - - - org.springframework.boot - spring-boot-starter-test - test - - - com.vaadin.external.google - android-json - - - - - org.springframework.boot - spring-boot-starter-jdbc - - - mysql - mysql-connector-java - ${mysql-connector.version} - runtime - - - com.alibaba - druid - ${druid.version} - - - - com.baomidou - mybatis-plus - ${mybatis-plus.version} - - - com.baomidou - mybatisplus-spring-boot-starter - ${mybatisplus-spring-boot-starter.version} - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.6.1 - - - 1.8 - 1.8 - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.20 - - true - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - - - src/main/resources - - - src/main/java - - **/*.xml - - - - - - diff --git a/jun_springboot_plugin/springboot_redis/run.sh b/jun_springboot_plugin/springboot_redis/run.sh deleted file mode 100644 index 955efb1f86..0000000000 --- a/jun_springboot_plugin/springboot_redis/run.sh +++ /dev/null @@ -1,72 +0,0 @@ -#!/bin/bash -# 项目自动更新脚本 -# 先clone相应的分支下来: -# git clone ssh://git@120.24.173.142:7999/xxx.git -# 远程调试启动: -# nohup java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005 -Xms512m -Xmx1024m -jar -Dspring.profiles.active=${profile} ${jarfile} >/dev/null 2>&1 & - -function start { - profile="$1" - echo "启动环境profile=${profile}" - jarfile=$(ls target/*.jar) - if [[ "$?" == "0" ]]; then - stop $profile $jarfile - fi - branch=$(git branch |awk '{print $2}') - git pull origin ${branch} - echo "更新完代码开始重新打包" - mvn clean && mvn clean && mvn package -DskipTests=true - if [[ "$?" != "0" ]]; then - echo "编译出错,退出!" - exit 1 - fi - echo "nohup java -Xms512m -Xmx1024m -jar -Dspring.profiles.active=${profile} ${jarfile} >/dev/null 2>&1 &" - nohup java -Xms512m -Xmx1024m -jar -Dspring.profiles.active=${profile} ${jarfile} >/dev/null 2>&1 & - echo "启动应用中,请查看日志文件..." -} - -function stop { - profile="$1" - jarfile="$2" - ps aux | grep "${jarfile}" | grep "spring.profiles.active=${profile}" | grep -v grep > /dev/null - if [[ "$?" == "0" ]]; then - echo "该应用还在跑,我先停了它" - pid=$(ps aux | grep "${jarfile}" | grep "spring.profiles.active=${profile}" | grep -v grep |awk '{print $2}') - if [[ "$pid" != "" ]]; then - kill -9 $pid - fi - echo "停止应用成功..." - fi -} - -if [[ "$1" == "start" ]]; then - if [[ "$#" < 2 ]]; then - echo "请输入正确参数:./epay.sh start {profile}" - exit 1 - fi - profile="$2" - if [[ "$profile" != "dev" && "$profile" != "test" && "$profile" != "show" && "$profile" != "production" ]]; then - echo "参数错误,请输入正确的profile参数,使用方法:" - echo "./epay.sh start {profile} ==> 启动应用,{profile}取值:dev|test|show|production" - exit 1 - fi - start "${profile}" -elif [[ "$1" == "stop" ]]; then - if [[ "$#" < 2 ]]; then - echo "请输入正确参数:./epay.sh stop {profile}" - exit 1 - fi - profile="$2" - if [[ "$profile" != "dev" && "$profile" != "test" && "$profile" != "show" && "$profile" != "production" ]]; then - echo "参数错误,请输入正确的profile参数,使用方法:" - echo "./epay.sh stop {profile} ==> 停止应用,{profile}取值:dev|test|show|production" - exit 1 - fi - jarfile=$(ls target/*.jar) - stop $profile $jarfile -else - echo "参数错误,使用方法:{}参数是必填的,[]参数可选" - echo "./epay.sh start {profile} ==> 启动应用,{profile}取值:dev|test|show|production" - echo "./epay.sh stop {profile} ==> 停止应用,{profile}取值:dev|test|show|production" - exit 1 -fi diff --git a/jun_springboot_plugin/springboot_redis/src/main/java/com/xncoding/pos/Application.java b/jun_springboot_plugin/springboot_redis/src/main/java/com/xncoding/pos/Application.java deleted file mode 100644 index adc4c48d75..0000000000 --- a/jun_springboot_plugin/springboot_redis/src/main/java/com/xncoding/pos/Application.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.xncoding.pos; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class Application { - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} diff --git a/jun_springboot_plugin/springboot_redis/src/main/java/com/xncoding/pos/config/DruidProperties.java b/jun_springboot_plugin/springboot_redis/src/main/java/com/xncoding/pos/config/DruidProperties.java deleted file mode 100644 index ea3dd726c8..0000000000 --- a/jun_springboot_plugin/springboot_redis/src/main/java/com/xncoding/pos/config/DruidProperties.java +++ /dev/null @@ -1,249 +0,0 @@ -package com.xncoding.pos.config; - -import com.alibaba.druid.pool.DruidDataSource; -import com.alibaba.druid.util.JdbcConstants; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; - -import java.sql.SQLException; - -/** - *

    数据库数据源配置

    - *

    说明:这个类中包含了许多默认配置,若这些配置符合您的情况,您可以不用管,若不符合,建议不要修改本类,建议直接在"application.yml"中配置即可

    - * - * @author xiongneng - * @since 2017-05-21 11:18 - */ -@Component -@ConfigurationProperties(prefix = "spring.datasource") -public class DruidProperties { - - private String url; - - private String username; - - private String password; - - private String driverClassName = "com.mysql.cj.jdbc.Driver"; - - private Integer initialSize = 10; - - private Integer minIdle = 3; - - private Integer maxActive = 60; - - private Integer maxWait = 60000; - - private Boolean removeAbandoned = true; - - private Integer removeAbandonedTimeout = 180; - - private Integer timeBetweenEvictionRunsMillis = 60000; - - private Integer minEvictableIdleTimeMillis = 300000; - - private String validationQuery = "SELECT 'x'"; - - private Boolean testWhileIdle = true; - - private Boolean testOnBorrow = false; - - private Boolean testOnReturn = false; - - private Boolean poolPreparedStatements = true; - - private Integer maxPoolPreparedStatementPerConnectionSize = 50; - - private String filters = "stat"; - - public void config(DruidDataSource dataSource) { - dataSource.setDbType(JdbcConstants.MYSQL); - dataSource.setUrl(url); - dataSource.setUsername(username); - dataSource.setPassword(password); - dataSource.setDriverClassName(driverClassName); - dataSource.setInitialSize(initialSize); // 定义初始连接数 - dataSource.setMinIdle(minIdle); // 最小空闲 - dataSource.setMaxActive(maxActive); // 定义最大连接数 - dataSource.setMaxWait(maxWait); // 获取连接等待超时的时间 - dataSource.setRemoveAbandoned(removeAbandoned); // 超过时间限制是否回收 - dataSource.setRemoveAbandonedTimeout(removeAbandonedTimeout); // 超过时间限制多长 - - // 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 - dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); - // 配置一个连接在池中最小生存的时间,单位是毫秒 - dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); - // 用来检测连接是否有效的sql,要求是一个查询语句 - dataSource.setValidationQuery(validationQuery); - // 申请连接的时候检测 - dataSource.setTestWhileIdle(testWhileIdle); - // 申请连接时执行validationQuery检测连接是否有效,配置为true会降低性能 - dataSource.setTestOnBorrow(testOnBorrow); - // 归还连接时执行validationQuery检测连接是否有效,配置为true会降低性能 - dataSource.setTestOnReturn(testOnReturn); - // 打开PSCache,并且指定每个连接上PSCache的大小 - dataSource.setPoolPreparedStatements(poolPreparedStatements); - dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize); - // 属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有: - // 监控统计用的filter:stat - // 日志用的filter:log4j - // 防御SQL注入的filter:wall - try { - dataSource.setFilters(filters); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getDriverClassName() { - return driverClassName; - } - - public void setDriverClassName(String driverClassName) { - this.driverClassName = driverClassName; - } - - public Integer getInitialSize() { - return initialSize; - } - - public void setInitialSize(Integer initialSize) { - this.initialSize = initialSize; - } - - public Integer getMinIdle() { - return minIdle; - } - - public void setMinIdle(Integer minIdle) { - this.minIdle = minIdle; - } - - public Integer getMaxActive() { - return maxActive; - } - - public void setMaxActive(Integer maxActive) { - this.maxActive = maxActive; - } - - public Integer getMaxWait() { - return maxWait; - } - - public void setMaxWait(Integer maxWait) { - this.maxWait = maxWait; - } - - public Integer getTimeBetweenEvictionRunsMillis() { - return timeBetweenEvictionRunsMillis; - } - - public void setTimeBetweenEvictionRunsMillis(Integer timeBetweenEvictionRunsMillis) { - this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; - } - - public Integer getMinEvictableIdleTimeMillis() { - return minEvictableIdleTimeMillis; - } - - public void setMinEvictableIdleTimeMillis(Integer minEvictableIdleTimeMillis) { - this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; - } - - public String getValidationQuery() { - return validationQuery; - } - - public void setValidationQuery(String validationQuery) { - this.validationQuery = validationQuery; - } - - public Boolean getTestWhileIdle() { - return testWhileIdle; - } - - public void setTestWhileIdle(Boolean testWhileIdle) { - this.testWhileIdle = testWhileIdle; - } - - public Boolean getTestOnBorrow() { - return testOnBorrow; - } - - public void setTestOnBorrow(Boolean testOnBorrow) { - this.testOnBorrow = testOnBorrow; - } - - public Boolean getTestOnReturn() { - return testOnReturn; - } - - public void setTestOnReturn(Boolean testOnReturn) { - this.testOnReturn = testOnReturn; - } - - public Boolean getPoolPreparedStatements() { - return poolPreparedStatements; - } - - public void setPoolPreparedStatements(Boolean poolPreparedStatements) { - this.poolPreparedStatements = poolPreparedStatements; - } - - public Integer getMaxPoolPreparedStatementPerConnectionSize() { - return maxPoolPreparedStatementPerConnectionSize; - } - - public void setMaxPoolPreparedStatementPerConnectionSize(Integer maxPoolPreparedStatementPerConnectionSize) { - this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize; - } - - public String getFilters() { - return filters; - } - - public void setFilters(String filters) { - this.filters = filters; - } - - public Boolean getRemoveAbandoned() { - return removeAbandoned; - } - - public void setRemoveAbandoned(Boolean removeAbandoned) { - this.removeAbandoned = removeAbandoned; - } - - public Integer getRemoveAbandonedTimeout() { - return removeAbandonedTimeout; - } - - public void setRemoveAbandonedTimeout(Integer removeAbandonedTimeout) { - this.removeAbandonedTimeout = removeAbandonedTimeout; - } -} \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_redis/src/main/java/com/xncoding/pos/config/MybatisPlusConfig.java b/jun_springboot_plugin/springboot_redis/src/main/java/com/xncoding/pos/config/MybatisPlusConfig.java deleted file mode 100644 index 35b3af4cd5..0000000000 --- a/jun_springboot_plugin/springboot_redis/src/main/java/com/xncoding/pos/config/MybatisPlusConfig.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.xncoding.pos.config; - -import com.alibaba.druid.pool.DruidDataSource; -import com.baomidou.mybatisplus.plugins.PaginationInterceptor; -import org.mybatis.spring.annotation.MapperScan; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -import javax.annotation.Resource; - -/** - * MybatisPlus配置 - * - * @author xiongneng - * @since 2017/5/20 21:58 - */ -@Configuration -@EnableTransactionManagement(order = 2) -@MapperScan(basePackages = {"com.xncoding.pos.dao.repository"}) -public class MybatisPlusConfig { - - @Resource - private DruidProperties druidProperties; - - /** - * 单数据源连接池配置 - */ - @Bean - public DruidDataSource singleDatasource() { - DruidDataSource dataSource = new DruidDataSource(); - druidProperties.config(dataSource); - return dataSource; - } - - /** - * mybatis-plus分页插件 - */ - @Bean - public PaginationInterceptor paginationInterceptor() { - return new PaginationInterceptor(); - } -} diff --git a/jun_springboot_plugin/springboot_redis/src/main/java/com/xncoding/pos/config/RedisConfig.java b/jun_springboot_plugin/springboot_redis/src/main/java/com/xncoding/pos/config/RedisConfig.java deleted file mode 100644 index 0ffa92e6be..0000000000 --- a/jun_springboot_plugin/springboot_redis/src/main/java/com/xncoding/pos/config/RedisConfig.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.xncoding.pos.config; - -import com.fasterxml.jackson.annotation.JsonAutoDetect; -import com.fasterxml.jackson.annotation.PropertyAccessor; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.redis.connection.RedisConnectionFactory; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; -import org.springframework.data.redis.serializer.StringRedisSerializer; - -/** - * RedisConfig - * - * @author XiongNeng - * @version 1.0 - * @since 2018/2/3 - */ -@Configuration -public class RedisConfig { - /** - * redisTemplate 序列化使用的jdkSerializeable, 存储二进制字节码, 所以自定义序列化类 - * @param redisConnectionFactory redis连接工厂类 - * @return RedisTemplate - */ - @Bean - public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) { - RedisTemplate redisTemplate = new RedisTemplate<>(); - redisTemplate.setConnectionFactory(redisConnectionFactory); - - // 使用Jackson2JsonRedisSerialize 替换默认序列化 - Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); - - ObjectMapper objectMapper = new ObjectMapper(); - objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); - objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); - - jackson2JsonRedisSerializer.setObjectMapper(objectMapper); - - // 设置value的序列化规则和 key的序列化规则 - redisTemplate.setKeySerializer(new StringRedisSerializer()); - redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); - redisTemplate.afterPropertiesSet(); - return redisTemplate; - } -} diff --git a/jun_springboot_plugin/springboot_redis/src/main/java/com/xncoding/pos/dao/entity/User.java b/jun_springboot_plugin/springboot_redis/src/main/java/com/xncoding/pos/dao/entity/User.java deleted file mode 100644 index 3337cd538d..0000000000 --- a/jun_springboot_plugin/springboot_redis/src/main/java/com/xncoding/pos/dao/entity/User.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.xncoding.pos.dao.entity; - -import com.baomidou.mybatisplus.activerecord.Model; -import com.baomidou.mybatisplus.annotations.TableId; -import com.baomidou.mybatisplus.annotations.TableName; -import com.baomidou.mybatisplus.enums.IdType; - -import java.io.Serializable; - -@TableName(value = "t_user") -public class User extends Model { - /** - * 主键ID - */ - @TableId(value="id", type= IdType.INPUT) - private Integer id; - - private String username; - - private String password; - - public User() { - } - - public User(Integer id, String username, String password) { - this.id = id; - this.username = username; - this.password = password; - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - @Override - protected Serializable pkVal() { - return this.id; - } -} diff --git a/jun_springboot_plugin/springboot_redis/src/main/java/com/xncoding/pos/dao/repository/UserMapper.java b/jun_springboot_plugin/springboot_redis/src/main/java/com/xncoding/pos/dao/repository/UserMapper.java deleted file mode 100644 index c3b5d14515..0000000000 --- a/jun_springboot_plugin/springboot_redis/src/main/java/com/xncoding/pos/dao/repository/UserMapper.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.xncoding.pos.dao.repository; - -import com.baomidou.mybatisplus.mapper.BaseMapper; -import com.xncoding.pos.dao.entity.User; - -public interface UserMapper extends BaseMapper { -} diff --git a/jun_springboot_plugin/springboot_redis/src/main/java/com/xncoding/pos/service/UserService.java b/jun_springboot_plugin/springboot_redis/src/main/java/com/xncoding/pos/service/UserService.java deleted file mode 100644 index 9fd3baf426..0000000000 --- a/jun_springboot_plugin/springboot_redis/src/main/java/com/xncoding/pos/service/UserService.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.xncoding.pos.service; - -import com.xncoding.pos.dao.entity.User; -import com.xncoding.pos.dao.repository.UserMapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.core.ValueOperations; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import javax.annotation.Resource; -import java.util.concurrent.TimeUnit; - -@Service -@Transactional -public class UserService { - private Logger logger = LoggerFactory.getLogger(this.getClass()); - @Resource - private UserMapper userMapper; - - @Resource - private RedisTemplate redisTemplate; - - - /** - * 创建用户 - * 不会对缓存做任何操作 - */ - public void createUser(User user) { - logger.info("创建用户start..."); - userMapper.insert(user); - } - - /** - * 获取用户信息 - * 如果缓存存在,从缓存中获取城市信息 - * 如果缓存不存在,从 DB 中获取城市信息,然后插入缓存 - * - * @param id 用户ID - * @return 用户 - */ - public User getById(int id) { - logger.info("获取用户start..."); - // 从缓存中获取用户信息 - String key = "user_" + id; - ValueOperations operations = redisTemplate.opsForValue(); - - // 缓存存在 - boolean hasKey = redisTemplate.hasKey(key); - if (hasKey) { - User user = operations.get(key); - logger.info("从缓存中获取了用户 id = " + id); - return user; - } - - // 缓存不存在,从 DB 中获取 - User user = userMapper.selectById(id); - // 插入缓存 - operations.set(key, user, 10, TimeUnit.SECONDS); - - return user; - } - - /** - * 更新用户 - * 如果缓存存在,删除 - * 如果缓存不存在,不操作 - * - * @param user 用户 - */ - public void updateUser(User user) { - logger.info("更新用户start..."); - userMapper.updateById(user); - int userId = user.getId(); - // 缓存存在,删除缓存 - String key = "user_" + userId; - boolean hasKey = redisTemplate.hasKey(key); - if (hasKey) { - redisTemplate.delete(key); - logger.info("更新用户时候,从缓存中删除用户 >> " + userId); - } - } - - /** - * 删除用户 - * 如果缓存中存在,删除 - */ - public void deleteById(int id) { - logger.info("删除用户start..."); - userMapper.deleteById(id); - - // 缓存存在,删除缓存 - String key = "user_" + id; - boolean hasKey = redisTemplate.hasKey(key); - if (hasKey) { - redisTemplate.delete(key); - logger.info("更新用户时候,从缓存中删除用户 >> " + id); - } - } - -} diff --git a/jun_springboot_plugin/springboot_redis/src/main/resources/application.properties b/jun_springboot_plugin/springboot_redis/src/main/resources/application.properties deleted file mode 100644 index 2d4d7e89b9..0000000000 --- a/jun_springboot_plugin/springboot_redis/src/main/resources/application.properties +++ /dev/null @@ -1,17 +0,0 @@ -# REDIS -# Redis\u6570\u636E\u5E93\u7D22\u5F15\uFF08\u9ED8\u8BA4\u4E3A0\uFF09 -spring.redis.database=0 -# Redis\u670D\u52A1\u5668\u5730\u5740 -spring.redis.host=localhost -# Redis\u670D\u52A1\u5668\u8FDE\u63A5\u7AEF\u53E3 -spring.redis.port=6379 -# Redis\u670D\u52A1\u5668\u8FDE\u63A5\u5BC6\u7801\uFF08\u9ED8\u8BA4\u4E3A\u7A7A\uFF09 -spring.redis.password= -# \u8FDE\u63A5\u6C60\u6700\u5927\u8FDE\u63A5\u6570\uFF08\u4F7F\u7528\u8D1F\u503C\u8868\u793A\u6CA1\u6709\u9650\u5236\uFF09 \u9ED8\u8BA4 8 -spring.redis.lettuce.pool.max-active=8 -# \u8FDE\u63A5\u6C60\u6700\u5927\u963B\u585E\u7B49\u5F85\u65F6\u95F4\uFF08\u4F7F\u7528\u8D1F\u503C\u8868\u793A\u6CA1\u6709\u9650\u5236\uFF09 \u9ED8\u8BA4 -1 -spring.redis.lettuce.pool.max-wait=-1 -# \u8FDE\u63A5\u6C60\u4E2D\u7684\u6700\u5927\u7A7A\u95F2\u8FDE\u63A5 \u9ED8\u8BA4 8 -spring.redis.lettuce.pool.max-idle=8 -# \u8FDE\u63A5\u6C60\u4E2D\u7684\u6700\u5C0F\u7A7A\u95F2\u8FDE\u63A5 \u9ED8\u8BA4 0 -spring.redis.lettuce.pool.min-idle=0 diff --git a/jun_springboot_plugin/springboot_redis/src/main/resources/application.yml b/jun_springboot_plugin/springboot_redis/src/main/resources/application.yml deleted file mode 100644 index 18f437dede..0000000000 --- a/jun_springboot_plugin/springboot_redis/src/main/resources/application.yml +++ /dev/null @@ -1,58 +0,0 @@ -########################################################## -################## 所有profile共有的配置 ################# -########################################################## - -################### spring配置 ################### -spring: - profiles: - active: dev - datasource: - url: jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC&useSSL=false&autoReconnect=true&tinyInt1isBit=false&useUnicode=true&characterEncoding=utf8 - username: root - password: 123456 - -################### mybatis-plus配置 ################### -mybatis-plus: - mapper-locations: classpath*:com/xncoding/pos/dao/repository/mapping/*.xml - typeAliasesPackage: > - com.xncoding.pos.dao.entity - global-config: - id-type: 0 # 0:数据库ID自增 1:用户输入id 2:全局唯一id(IdWorker) 3:全局唯一ID(uuid) - db-column-underline: false - refresh-mapper: true - configuration: - map-underscore-to-camel-case: true - cache-enabled: true #配置的缓存的全局开关 - lazyLoadingEnabled: true #延时加载的开关 - multipleResultSetsEnabled: true #开启的话,延时加载一个属性时会加载该对象全部属性,否则按需加载属性 - -logging: - level: - org.springframework.web.servlet: ERROR - ---- - -##################################################################### -######################## 开发环境profile ########################## -##################################################################### -spring: - profiles: dev - redis: - host: 127.0.0.1 - port: 6379 - database: 0 - lettuce: - shutdown-timeout: 200ms - pool: - max-active: 7 - max-idle: 7 - min-idle: 2 - max-wait: -1ms - -logging: - level: - ROOT: INFO - com: - xncoding: DEBUG - file: D:/logs/app.log - diff --git a/jun_springboot_plugin/springboot_redis/src/main/resources/banner.txt b/jun_springboot_plugin/springboot_redis/src/main/resources/banner.txt deleted file mode 100644 index 2e697237e8..0000000000 --- a/jun_springboot_plugin/springboot_redis/src/main/resources/banner.txt +++ /dev/null @@ -1,139 +0,0 @@ - :: :.:..... : ....: ..: ..: : : :..: ..:...:.... :..........:.... .:.: : :.::..:.:......:.:..: : :...:..:::..::.:::::::..::.:::::.::::::::::::::::::::::::::::::::::::::::::;:::::: -.::.:.:::...: ::.:.:.:.:::.::::.::.:.:.:::.:.:.::::.::::.:::.::.:.:.:::::::::::::::.::::::::::::::::::::.:::.:::::::::::::::::::::::;:;:;;;:;;:;:i::::;;,;,,;::;,i;:i;,;:;,;;,;;i:;: -::.::: :::::::::::::::::.:::::::::::::::.:::::::::::::.::::::::::::::::::::::::::::::::::::::::::::::::::::::::::;;:;;:::::;::::::ii,;,ii,,;,,:ii:ii,;::i:ii:i;,;;,i:,;,:i:::;,,;,,: -::::.::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::;:::;;:::::::::::::::::;::::::;::::::::;:::;::::::i:,;:::;,;:;i:;,,;i;i:i,;,;,:,;,::,;;,;,:,;:;,,;i:;,;::i:,;,,;:;, -:;;:;;:,i:,;:;::i:i:;:,;,,ii,,:;;,:i,;,,;,,i:,:::;:i::,;::,;,:,::i;,;::;:::::,:;:,::::,::i;:,::::::,:,:,,:ii:i::i:,;,;,:::;:;:;i:i;ii:i;,i;,;:::,:,::,::i:i:,::;,i,;ii;,,::;,:::i:i: -;ii:,:,;;,;,,:,:;,:,:,::ii;,;:i::;::,:::::::;::,;:,;,:i:,;:::;:i::::::::::::::;,;,;;:::;:::::,::;:::::;,:i::i:;,::::;::::::,::,:i:iiiiiiiiii::i:::;:;:::::::;::i:,;i,i:i:i:,;::::::: -,;;:;,;::;:::;:i::::::,;::i:i;::::,::;,::::,:::::;:i::;,:::;iifffjiii;i:::::i:,;;:,,:::,::::::::::::::::;,;;,;:;:,;,:;,::::;i:;;:iiiiii,i:,;::::;,:,:::;,;,:,:;,;;ii;,;i;::;::,:i::: -,i:i::::::::::::::::,::i:i;;ii::;::,::::::::,::::;:i:;,;ijffLffffGGGDDLGfii;;:,;:i::::::;::::::::::::;::;:i;,;:;::;::::::,;:i:;;i:i:iii,;ii:,;::::,:;::::,:;::;,;;,;ii:i;,:;:;:::::: -:ii:;;:,:;,:::::,;,:::::iiiii;,;,:;:i::::::::;::;;,;ii;ifGLGGLGDGGGDDEDGffijiiii;::;:::::::::::::::::,:;:,::::,:,:::,;:::::,::,i:i,ii;;i,;;,;:,::;::::::;:::,;:,;i:i:,;,,;:,:,:;:::: -i;;,:::::::::::::::::::i::i:ii:,::::::::::;:::,;:iii;ifLDGfDDDGDDEEEKEEDEGDDGLfi:,;::::::,::::::::::::::;:;:i:::;:;::::::::;i:;,;:i:ii,;i:::,,::::,;::::,::::::;,:i:i;,;:,::::::,::: -i:,;,,:::,:::::,::,::,:,;;,;i:i::;,:::::::,::,;,;i;ifLDGGDEKEDEEEKKDEDKEKEEDDDGfi;,::::::::::::::::::::::::::::::::::::::::::,:;:i;;i:;,;,,;::;:;:::::::::::;::,;i:;::;,,;:;;:i:;::: -i:,;::::::::::::;::::,:::;:i::;,,:,:::::::;:,;iiifGGGDGDEEDKEKEEWW#WKKEWKEW#KKEGj;i;,::::::::::::::::::::.::..::.::...: ::::::,;:;:,;i:i:;::;::;:;:::::::::::::,;;:;:::i,:;:,::::::: -:;;,::,:;:,::::::,::::,;,:::;,:;;:;:::::::::;,jjfGDGDGGGEDEEKKK#KWK#E#WWW#KWEWEDffii:;::::::.:::::::::::...;;:ijiii:::: :::::;:,:i,:;::;:::,:,::::::::::::,::::::::,::;::::::::::::: -,::;,::::::::::::::::::::::i:;:::,:,::::.:;,iifffffDGGfLDEKKWK#WKEEWWWEWKKWWWWKKDGGi;,::::::::::::::.:.:;:;;;jLfGGfji;:::::.:::;::;;,:::;,;::;::;:::::::::;::::;:;:;::::::;:::i::::: -::;::::::::::.:::::::::::::;:::::::,::::::i,ififLDGDDDDEKWEWWK##KWEWWWWKKKWKWWKWWKDGfi;::::::..:::::;,;ijLGjjjtjLGDDGDGGGi::::::::;:::::::::;::;,::::.:::::::::;::,:::;::::::::::::: -:;:::::::::::.:::::::::::;:::,:;::;::::.::ijtGDGDDDDDEEKWWWKWWWWE##KK##KKWKWK#KWK#EGfii:::: :::::::::iiifLGGGGjjtGGEDGEGDj;;:::;:::;::::;::::::,;:::::::::::::::::;::::::::;:,;::::: -:::;:::::::.::.:::::::::;:::::::::,::::::ifDGDKEKEDELDKKEKEK#WW#K#WWWWWEWWKK#KK#KKKGGi;::::::.:.::.:;ijfGGGEEDGGtjGGKDDEDG;;:.::::::::::::::::::::::::::::::::::::::;::::::::::::::: -:::::::::::::::::::::::::::::::::::::::;ifDEDDD#GDEDEWWKEW#W#E#WWWKKWKWWKK#EWK#KEKGjii;:::::::: ::iiLGDGKKKKKDKKEjjGEDKEEjjGfj;:::::::::;:;:::::::::.:::::::::::;:;:::.::::::::::::: -::::::::::::::::::::::::::;::::::::::::iiGKKDGEWEKEWWK#K#KWK#WW#KW#WK#WWKWKWK#KKKDj,;:::::... :::i;jGGDEEKDKKKKKKGjjGEKKDjGGGjf::::;::::::::::::::.::.::::::.::.:.::.::::::::::::::: -:::::::::.::: ::::::::::;,::;::::::::,;ifLEKEEDEK#KKKWE#WW##KWWK##KK#KWWKKKWEGKGGi:;::::.::.:::::ifGGGEKKKEKDKWKEGLjGD#EKGGGGGG;:.::::::::::::::::::::..:::::::::::::::::::::::::::: -:::.::: :::.:::::::::::,::::::::::::i;ifGDEKKEEKKK#KK#KWWWKWWW##EWW#E#WEWEWEEDGjLi::::::::.: .:;ijjLGEGDGGEKGEKK#KGGGKKWEDEKDGGi;::::::::::::::::.:..:..:..::.::.:.:::::::::::::.::. -:::::.::::.::::::.:::::::::::.:.::::iifGGDK#EWEKEWK#E#WKWWWKWKWWWKKKK#WEWDGGGLit;;:...:::. :.:;ijLjjjjLGGEEKDEEDGEKDGGEDKKKEEGGi;::: :...:: :::. : ::.::..:::..: .::.::..:::::..:.:. -::::::.::.::: :.::::::::::::..:.: ::iiGGDEEWKKKKEE#K#KWWWWW#K#EW#KWW#KWEKEGfLf;;;;;: ::: ::::ijLGjtjLLGGKEEEEEDKEDKDEGGGKKEKKDGj;;:;;::::..:....:.: ...:..:....:::...:..:.....::.::. -:::.:.:::.: ::.:::::.::.::..:: :::::iLGDGDKWKE#KK#WWEKWWWWWKWWWEWWWWKKKKKDDfjj;;,,..:...:.::;jGjjjjLGKEEGEKDDEGDDGGGGfLjGKKEEKGjj;;,;;: :.:.:::...:. :....::.. : ..:::::..:::: :::: -.:..:..:: : ..:::: :..:: :....: .::ijGDKDGEWEW#EW#EWKWWWWWWKWWWEWKK#KWKKEDGGi;;;,,::.:.: ::;i;t;LEGGDGEGKEGGGLjiji;j;;;;tjGGEKDGjt;.:.:: :: ::.:: : :.......:..:: :.:.:...:.:...::. -..: ::..: :..::...: :.: :: :::..:::ifLGEKEKEK##WWK##KKWWWKKKWWK#K#KKKWKWKEKGti;:.:.,.:. : ;ij;;jGGGLGEGGDEGLjj;t;;;;;;;;;;tjGEDGjt;:.. ;:..........::..:.......: :... :..: ... :... -..... : : :.. :.: .: .: :.. ::::;ifGEEKKE#KKWWWEWK#K#K#K##EWKEWKWWWW#EEEDGi;;;.:.:..:: :;ijitGGLLGEGEKGGGjj;;;;;;,;.;;:;;;LGKEGt;.: :. :..:: ::. :. :... .... :.....: : :::.....:: - :......:. ..: ...::..: ::.....:::;iDEEWEKKKKKKK#WK#KWKW#K##EWWWKW#EKEKWKKEDGj;;;.::.,: ;;ii;jjGGLGGDKGGjLjji;;;,::,:.;:,::,;tjGGLL;................:... : .:: ::....:..: :: :..... -. .::..: : . : :..: :..:: :..:.:::iGDKKKK#KK##E##WWWW#KWW#WK#EKWWKKKEEWEKGEGj;,.:...,..::;;jjLGLGLGEGLGLjjtjt;;;;;.;;.::,:.,;iGDGG;;.............. :..: ::.. :.. : : .: :. : :..: -.::..: :..:... ...:: :: :: : : ::,iGDEEKEK#EWKW#WW#KWK#KWWWWWKEWKKEWDDDKKKDGGi;.:.:,.;::;;itLGLfLGGGGGjjjt;i;;;.;,,::,:...::,;LGGGL;:: .. : ....... : : :....: :: .. :.....: :: :: - :..::.::.: . :: : :.....: :: :::ijDGDWEKWWK#KWWW#K#WW#WW#WWWKK#KWKEKKKDKEEGGj;.:...:.,:;;;jLjGLLGKELjLjjt;t;;;,,;:.:.:..:..:.iGGGLj:.:..... : : ::..... ... :.:......: : : : : -.. : :..: :. ::. :.......: :: :::;fGDDDEWKWW##WW#KWWWWWWWWWWE#KWKEWEKEKGDEDGGj;:.:..:.,;i;jjGGLLDKEGLjjjtjt;;;,,;,:..:.:.:.:.:;;LGt;j:.: .. :....:: :: : : . : . : :.: :.: :.: .: -. : .... .: : : :.....:......:::ijfDEEWKK#K##K#WW#KWWEWEWWWWWKWEWKEKGGDGEGGjj;.:..:.,;jEitiGGLjGKELjjtijii;;;,;..;:.:.::.:.:..;jGjtt.:: :....: : :.: :.: ::...... ::......:.:.:. -: : .........: : : : : :...::itGDDKEW#KWKW#KWWWEE##WWKWEWEK#KKEKKDGKGGGGf;,:..:..;jGK;jLGLGGEKEjLjtt;j;;;;,,,::::.;..:...::.jGLj;j ::: :: :: : : ......:: :: :.:....:.: :.:.:. -: ...................: :....:...:;fGDDKEKWEW##W##KWWWW#WW#K#KWK#KKKDKGfGGGGLj;::..:.;ijjjjGGGGDKKEGjLjjLjjji;;;;,;.::.:..:....:.;fGLijj.:: ::.::.... :: : : : :..:.. : ::..:..: - ....: :.............:: ...:..: :ijGDKEWWWWWEK#KK#WWWKWE#KKWWK#KWDEGGGGfjGji;...:..;;;;;iLjGLGKKKGLLjLLGGLLLj;;:;:.;:..::.::....:jDLijj.:............. :..: :: :: :.......:: :: ::. -: : ..: .. : : :: :: ::. :: :: ;fGDEDEWWWKWWWWWWW#WK##WKWWK#KKEDKEDGfGfjL;;.:.,:.:;...;GLLGDDKEGLGLGGLjfjfLj;;;;,..::.:.::.:...jKLt;j;.................. .. : .........: .....:: - :...: :: .. : : ....: .. ... :: ;fLGDDEKWWKKWWW#K#E#KKWKWKWK#EKEDEGDGGGjji..:.::;.:.:..;LGLGKKELLjjjttt;;;;;;;;;,;..:.:;;;i;::..;KGj;;j; : : .. :: .. : . .. . .. :: . .. ..: - .. . : .. :: : .. : ....: . :;ffDGEK#K#K#WW##WWWW#KWWWK#KWWEKGDDGfGfjj;.:...:..:..:;jGGGEWKGLfLjtjtttij;.;;;;;.:.::;;;iji;:..;KGf;;;; .. : ... .... .: . ..: : .. : :: :... : -. .. ... .... . . .... . :: :. :LGDDDEK#WE##WW#K#KK#EWWW#KKWKEKDDGDjGfij;.::...::..:;j;iLEDKKGjLjjjtjjLLGLj.;;;;;..:.,:;;;t;j::.EGj;;;;: .: .. . : .. .. : . :. ....... . - . . . .: ... . . :. . : .. . ..;jGDGDKKKKKWK#WKW#EK#WKK#KWWWKEDDGGGjGjjtj,:...:.;..:;;;;;GKKGLLtjjtjjGGEEKD;.,;;;.:.;;,;,:::;;.:DGL;;;;...... : .. : .: : : : ... : .. :..... - : . : . :.. : . ... : . .. ...iGDGDEKKWE##EWWK#K#KWWKKKWWWEDDDGGGjGfjji;::.:.....::,..:,DKLjtjttLLGELiiEGG;;i;;.:,;;;;jjj;: :.GGj;;;;... .. : .. : : .. .... : : : .. :....: -. : . .... :.. ... . . : . . ;GEGDDEE#KWW#KWKK#WE##K#K#KKDKGEGGGGjjjjj;:.,..:.:....;,:,;EGLjtjjjjLLLLjLGK;;;;,: ;;;jGDWKG;. .Gjt:,:;: .: ... : .. : : . .... :: ......... - . ... : . . : .. .. .. : . : :GGDEDEWKKWWWEWWKKWWEWWEWKKKDGGGGGjjGjjji;:;:::....::.,:.;;jGLtjttjtjtj;;;;j;;t;;..;;;jiifDW;:.:Ei; :.; : : .. .. :.........:... .. : :... : .: - .. ... . .. : : . .... . .: ..GDGEEKKK#KKKKWWWW#KWWWKEWKKGLL...;jjfjji;,;::.:.. ...:;:;;,;Gtjtj;j;;;;;;;;;jtt;:.:.;;itjjLL; .L::..;... : .. :: .. : : ..........: : : ....: -. . . ..: .... . ........ .... :....LKLKDKKKWWWWWEWWWK#W#WKKKEELL;:;..,;jjjt;;.;.:.:.:....:;;;;iLjtjiti;;;;,,.;;tji;;:.:;t;;;.;;;..j:. .:. : : ..... : .. ..... : .. : :: :...: - .. . ... .. : .. :. :: .... ...: :.iGGDEKKWEWWWKWWKWWK#EWKWEKGLt,tt...;;jjj;;:;;:... :. .;;,;;jGjttti;;,,,;.;;ijtt;...:;;;;;..:. .j: :; .... . ...: ...... : .. : :: :: .::..: :: - . : . . : .. :: ..: :: :: .. : ....;jGGDKDKKKWKKK#KWWWWK#KKGLLtt,tj,..:;;;;;;:,,:,:.. . ..;,;LKLttjt;t,.:,;:,;ttjt;:...:,.:.:.: . j: .:. : : .... : : :: .. ......: : :: :..:: -. . ....: : : . : :.. : ....: :: :.:;fGDKDEWWKWEEWK#KWWWWKEGGjf;,ti:,...;;;;;;;:,:..:..:..,;jKELjttt;;;;,,,.;;jtj;;::....:,,:...:.j:..:.. . .. : .. :: : ........: : ::....: : : - :....... :...: :.. :...... ....::iGEEEKEKKWKWKWWK#KEWWELjLj;,,,j;.:.,;;;:,::;:.:......;;KKGLtttt;,;,.;,;:;jjj;;.....:.::... . f;..: ::.........: :: .......: :.:.:: :.......:: -. .... .....: .. : : : : ..... : .::GGDKEDWWEWK#EWWWK#KWGLjjf;;.tLL. ..;;;;;:;:,:...:. .,jEWGLtttt;;;,;:..;tjLj;;:.:...,:.:..: .ii.:.......... : : : :: :: :::.::.::.....::.. : -....... : . ..... ..: ..:..... .: .:.iGGKKKKKKK#EW##K#WWKGLjtLt,.;ff; .:.;;;;;;:;;:..:.:.:,LEELtjti;;,,::.;ttjtj;,:...;,:::.: . .i;;:::.::.:...:....::: : :::..:.::::..: :..:: :.: -..: :: :: ... :... : :...:..:::..:...;DGEKKEWWWKWWWWWKKKKLjjLfj;.,;t;.:.;,,;,:;.,:,,...::,:jDELtttt;;;:,.;;Ljtjj;;..:.;;.... :.. ;;;::.:.....:..:.:.: :: : ::..::::::::.:.::.::... -.: :::...................:.:..: : :..:.:jGDEEWWKKK#K##W#WWKLjjjtjt....;..;.;;;;;;.,,..,.:...,;GELtjtt;,;,,:;;jjLLLj;,;..;,,:..: : :;:;:::::::.:.:..:.: :.::::..::.::.::.:.::.::::.:: -::::::.:.:.......:.: :.:.:::::::.:...:::.;GDDEKEWKWW#WW#KKKLLjtjtj;....:,,;;;;;;;.,,:.......;;LKLtjtt;;,,;;it;tiij;.:;: ,;;,..:.: .:.:;.::::...::.:....::.:.:::...: : :..: ::.::...: -::::::.:: :::: ...:.:.:.. :::.:..:.:.....:LGEDWWWWW#KWKWKEEjjtjjjLt;.. .;;;;;,:,::::..::..:.:jKELttt;;;;:;;ttt;t;;:,:...:;;;.:.. .:::..:: ::.::.:.:::...: .: :.:..:.:.::.:..:::.:.. -.::.:.: ::: : : :.:.:.:..::...::: :.:..:.:LGDDE#WWW##WWWKKGLjjtttjLt;:.:,;,;;;;,,;:::.:..:.:,LGEGjttt;;;;t;tj;ttt;;...:.:;;,:.... :...;..::: : :: : ...::.:: :....:....:.: :.: :... -....: : .: :.:...:..: : :::....:: ::..:: :jDWKWWWEWWWWKKDDGjtjttit;;;;;;tt;t;;;,;:,.:.. :..:,;LGLttjt;;,;tLLDDDGGDLff;..::;;:..:. ..: .: :..::: ... ..:: : ...: ::........ :: :.: .. -.....:.:: :.: :...:: ::.. : :..:: : ..::..fKWWKWWWKEKKKEDGGjji;;t;;;,;;;;ttt;;;;.;....:..:,,;tGLLtit;;;.;tGELLLGLfffLjt,.;;,..:. ::...;... : :: :. :.: ::: :............: : ..... - :: :....: :.: ..: :.....: :: ::.........iEWWWKWWKKKEKEGGGj;jt;i;,,:.;tijt;;;;;;.;.:..:...,:tGLjtti;;,;;;LGLjt;;;t;ffft;;,;:.... :: :: : ....: : .: .... : ............ :: :: :: -: : : :.........: ::...................;GKWEKEKEKEGGGGGjjti;;;;,,.;;;tttjt;;;,:...:...,:;;;LLtjttt;;.;;;DGL,;:...:tfLf;;:..: .. : :...............:: : : ...........: :: :: :: - :: ::.. :: : : :: :: :: : : : :: :...:iDKGGGGGGGLGjjjjti;i;,,;:;:,;jjttti;;,,,..:..,:,,;:.;jtttt;;,;;itLDGLfft,,,Lft;;,.... : :. : .. . : : :...: . .. : : :: :: : : : : -........: .....: : : : ...: :: : : : :LGGGGGGGLLjjjtj;jt;;,;,,.,;;tjtjt;;;;;:,::..::,:,:..;;;i;;;;;;ttjfGDLffjjjjt,;,;:.:.: .. : : .. :: :: .... : : : : :: .. : : .. :...: - :: :: ::.....: : :: :: :: : .......: :: :: ;i;ijjjjjjjj;jtt;i;;,,::,.;;;jjiit;;;,,:..,.,.:;,...:;tiit;;;;;itjfGGLffjti..;;..... .. :. ...: . : .. .. : .. .........: .. : ..... - :: :: :: : : : :...: ... :: :: : : : . ::.:,:i::::::;t;;;,,;;::,,:;itjitit;;;;,:,:,,:,; :..:,;ti;;t;;;;;,;;;,;....;.:..... :: : .. :: :: :.. :: ... : : .. :.. ..... .... -: .......... :: : : ..........: .. : .. :..::i;,:;::::.:;;;;,;:::..:.,;;ttt;;;;,;;;:,,,,,, : ...:;t;jiit;;;;;;;,;...:.:..: .: .. :.. ..: :........... . : .. ....... : :: :: :: - :: :.......... : :: :: :... .. : :: :: :itfGDGffjii;::.:. ::;;.;:,:.,::,;;tittt;;;;;;,,,:;.. : ...;;ti;t;;;,,:.::.:: .:.:.... ...: :: : ..: .. .... ..... :: :: :... : : : : - .: ...... :: :: ....... .. .. : :...:ifLDDDWDWWEWKWKWEDf;. : .;:::.,.,;,;;;;t;;;;;;;;;;. . : ..:.:.;;tit;;;:,:..... :.... : : :: : : . : : : :..... :.. : .. . : ...: :.. .. - :.. .. : :... ..... ....... .. .. .. ;tfGGDEEEKWK#W#KWWKKEGf:.. :,.:...:::;;;:.. ...: ...... .:. ..:;;itt;;:;.::.::. :...: . .. .. . ........ . :: ..: .. : : :: .. : .... :: - . : ..... .. ... . ..... : .. .. : : iffDDDDDWKKWWKEWWEW#KKKKi...:::,.::;,,:. .. ... .. ..: ...:.:::;;;;jit;;:;.: ...... ..: ..: ... :.. : : :: .... : : .. .....: : : : . . -..: . : . .........: :.. ..... :: ..: :jffLDEDEEKKKK##WWKKEEKKEDL: ..:,:::.::; :: :.. :.. ... . :.:.:,,;;;itj;;;.:.....:: .. :... ... .. : : : : . ..... : ....: : : :: .. .. - . .... ...: . : ... .... . . ....ijLfLGDDDDKKWWWWKWKKKWEKWEEEKD: ..,.:.::. :.. :.:.. .. : :.::.;.;;iititt;;;;:::... :......... : : ..... : : .. : .... :.. : .... : . - .. ... ... : .... : : .. .....: : itjfGDDDEEEKKKWEW#KWWKKWEWEEKDDGi :.::,: .. .... . . : : : .::.::;;tttjttiti;:;..... :.. . : . .. : : : ...... : : :: : :.... ...... -..: : .. : : . :: : . : : ..fLfDDDDEEDKDEEKKKWWWKWWWEWEEEEEEDj..::.;: :: . : . : .. :.:.:.;;;titjtit;;:;:...:.... :....: .... ...: : : . : ... : .. ... ... .... . - ....... . ....: :: . : : . : : tGfDDEWEWEWWW##WW###W###K#KKEEEEDEf:.,: : .. ... .. : ....:.,:,:;;tit;t;,,,.,...... .: .... . : . .: . . . . : ...: . : ... ... . . . - .. :: :: : . . : .... .........: :ifffDDEEWEK#KEW#WK#WWWW#W#WWEKEEEEKf.:. : . : : . .. .. . :,:;;;jttt;;;;,::....:. : : : .. : . ... ... . : ... .. . .. : .. . ..... .. . -........ : .. :. : . ....: ........:ffffGLDDDKKKWK#E##W##W#W####WKWDEEEEf ..: ... :.. .. : ... : ..::.;;;j;;i;;:;::.::.... . ........ : . ... ........ : .... . .. :... . . .. - .. :: : .... ... . .. : :: .:iiffffGDGDDEDKKKK#KK#WWK#KK#KKEW##WKDWDEi.... .... ... ..... : ...:,;;tti;i;;,;.:.,::.:,:. :. : .......: .. :... : ....: : : :: .. : : . -.... : ....: ... .: :.. : .::tifDGLfGDDDGDDWEWKWKWWWWWWK#WK#WEKK##KDEWEi : :.. .. :...: .: ...,;;;;iti;;;;,.;:..:.:::::.. : ::..: : : : ..... : : .........:. :...... ::..:. -..: :... ....... ........... iiiitfEDDDfGDGGDDEEWWWWWWKKWWWK#KKEWEEED#WEDDG: .... :: : ....... : . ,;;;;j;t;t;;,;..:::..:.;....: : ... : .. :: ....::..: : .....: : ....:. : . .. -... :: :: : ......:: :...: :ititifLDGDfLGDfGLDWEWWKKK#EWK#KKKK#KKKKEKDWKEDDf............. : : . :;;;;tt;tt;;;:,..;..::.;.;;.:: .:::..::. :..:.:.....:..:. :.....::..:::...::.:: .. - ::.:: ::... :. :....:...:tDLifjtfDEDGGDDffffDKWEEWEWWEWWEWWEKKWKKEWEKEDEEDG:.: .:::....:::.:.: . .;t;ttt;ttt;;:;..,.:.,.:;;;;;.:. ::..::.:.:::::.::::::::::..:::.::.::::::.:.::.::. -: .: : .:::.:.:: :: :: :iDDfifffGDEDLLDLLffLDKEKKEWEEWEKEKKKWKKWEKWEWWEKDDLL..:: :..::::.:: .: . ;t;itt;tt;t;;,;,,.,,,:,;,;,;;;:: ::::: ::..:::..:::.::.::.:.::::.:.:.:::::::::: -.: :::.::: .:.: ::..:.:;iGDLtfffLDGDfLGLGLffGDKEKEWEEEDEKKKKKKEEWWKK#KKKKEDDLfff;::.::.:.:.::: : .;;ti;ijit;;;,;:.,..,:;;;;;,;;:;::.. :.:::.::.::::::.:::::::::::.:.:::.::::.::.::: -.:.:..::::.::::::.:.::tfGGfftDffLDfDGfffLLfDKEEDEEDKEKKKKKKEWEKWKKEWEWWEWKEKDDLDi::::::.::::: . . .;;;;i;j;;t;;;;..:.::;;;;;;;i;;:.. :.. .:::::::;::::;;:::::;:;:;:::;:;::;;::;: -:.:::::.:.::::.:.:::iitDfGfGfLffGLDDfLGGffDEDKEDEEWKKWEWWEDWEKKKKKKKKKKKKWEEEDDLi::;::::::::. .....:;;t;;titit;,,,;.;,;,;;;;;t;;;::.:..::.::. ::;::;::;i;,:ii;i;i:i:::;;:::;:::;,,; -:::.:::::::.:::.:::iitfDfGDfDDfffDGDLDLLLGKDKEKEEKKKKKKKKKEEKKKK#KWKKEEKKEWEDEDLLi;:;:;:;::: . . .,;;;;j;tt;;;;;;:;::;;;;;;;;;.:;::.:::;;;:::..;,:ii,i,;iiii,iiiii:i:i::i:;i:ii;iii -;iii;;:;;:;::;:iiiijffKffGfLWGfLDGDLLDGDDEEEEDWEKKKKKKK#EKKKWE##WKKKKKKKEKDEDEWEEDDii;i:: : : .: :,;;;;j;t;;t;;:;;;;:;:;,;;;;;;;;:;,:;;;;::::.:.::ii:i,;,;;i:,i::i:i;,;:i:::;,,;ii, -,;,;,,ii;,;,,:iiittttGDtGDfD#LLGLDfDLDGDEEDEDWEWEKKKKKKEEKDKKKKEWW#KKWKEWDKKKWEWWEEEGt: :...:. ;;;;;;jtt;;;:;;;;,;;;;,;;;;;j;:,,:;,;;;;,::.:: :::;:;;;::,;;:i;,;:::,:::;::,:i::; -iiii;;;;:i,;;iG,itiffWLfDLDWEDfLGDDLDDDEKKEEEEEKKKKKKKKKEWEKKKKWKKKKKWWEEKKK#EWEEKDEEDG . ...:.:. :,;;;;t;;;;;,;;;;;;;;,;;;;itj;;;:;;;;;;;::....: ::,;::,;:;::;::::::;:::::;::::;i: -;,,;;,;ii:i:LEttijffDWffDDDWWDGLGDfDGDEEDEEEKEEWEKEWEKKKWEWWEWEE#WWEWEEWEKE#EWEKDEEDEDEi. ...::;:..;;;;t;;;;;;,;;;;;;;;;;;;;tij;;:;;,;i;;;;.:.:. .: ::::;:::::::::;::::::::::::;:::: -:::::::::::jGiittffDKWtLDEWKKDLDLLDLGDDEEDDKKEKEWWEWEKKKWEWWEWKWW#KWKKEKK#KKEWEWDEEDWDKEDj::..: : ;,;t;;;;;;;;;;;;;i;;;;;;;;;j;;,:;;;;;i;;,:..:.: : :::::::::::::::::::::::::::::::: -::::::::::tKjijtffjE#EffDKKKDDGfGLGLDDEKDEDEKKWEWEWEWWEKKKKW#E##KWEWKKEWWEWEKEEEKKEKDEDEED.:::.:.:;;;;:.;;t;;;;;;it;;;;;;i;it;;:;;,;;;;;,;:.:.. . . :::::::::::::::::::.:::::::::.:. -::::::::::D#iftffffWWDfGDKKKEDLDLLLLLDDDEEEWEKKEWWEWEKKKKKKKKW#WWKKKKKEWKEWEKKKKEEEKDEEDED::....:,;;;,:;;t;;t;;i;;;i;;;;;;;;j;;,;,;;;i;;;;;.::... : :::::::::::.:::.:.::::...::.:... -:::.:::::EKfffjfffGWWLjDDEWDEDGfLLGGGDDDEEKKEWWEWWEWEKKEEWEWW#KWWKKKWEWWKWEKKKEKEEDEDKEKDED;..;::.;,,;;;t;;;;;;;;;;;;;;;;;;;;;;;;:;;;i;;,;:.::.. . .:.::::::::::::::::.::.:..::::::. -..:.:.:.jWGfffffjfD#DDfDEKKEEDLDLLGLDDEDEKDEKKWKEEWEWWEWKKKKK#W#EWKWEWWK#WKKEKEEEEEEKDEDEDDt ::.;;,;:;;;;;;;;;;;;;;i;;;;;;;;,;,;:;;;i;;;;,.:.. :.:. :::.:::.:...:..:::.::.::::::..:. -:::.:::.DKfGfffffLEWDDfDEKKEEGfDLDLGDDEEKDKKDWWEWWWWKKWEE#W#WK#WWWWKK##EWWEKKKEKEEEDEKEKDEED:..;:;;,;;;;;;;;;;;;;;;;;;;;;;;,;;;;;;;;;;;;,;:.:.: ....:::: ::::::::::::::::::::::::.: -:::.::::WfDLLffDfGKEDDfDEEWEDGDDDGGLDEDEEKKKEKKEWWEWWEWEEW#E#WEWWWKWWWKKKEKKKEDKKEWDEKDDEEEDG,::,:;,;;;;;:;;,;;;;,;:;;;,;:;,;;;;;i;;;i;;;,:.::. .....::.:..::::.::::::::;::;:;:;:::: -: :::: iELDDfffGfDWDGEfDDEDKEDLDDfDDDEDKEDEDKKKKWE#KWWWW#KK#WE#WW#KK#E#EWWEWKKKKKDEEKDEEDKDED::;:i;;;;,;:;::;;;,;;,;;;:;;;;;;;;;;;;;i;;,:,.:...... .::.:::..:..:::::::;;:;,;i:i,;i;: -:::.:::fGDDDGffLjD#GDEfDDDKEDGDDLDGLEEEDKEDKKKKKKKKKKWEWWK#E#KK#WKW#KWKWEKKKKKKEKKKKEKDDEDDDD.:;GG;;:;;::;::;:;;:;;;;;;,;;;;;i;;i;;j;;;;;::.:: .. ..:.:.:.::::::.:::;;iiii;i;i;;i;i; -.:::...DGDEWLtGffD#LDDfGEEDEDLDDDfDDDEDKDEEKKEEWKKWE#WKKKWEWKK#K#W#K#W#K#WKKEWEWKEDDKDKEEDEDE::jWG;;;;:;,:;;,;;:;;:,;,;;;i;ii;;;;;i;i;;:.:... : : ...:..::..::::::;:iiiiiiiiiiiii;i -:.::..fWDKKKLfDtLKWLKDfDDDDDGLDDDGDDEWEDEKEWEKKKKE#EWWKWKWWKKKW#KEWK#KWW##KKKKKDKDEEEEEDEDDDD::;;it;;:;:;;::;;;;;:;,;;;;;;;;tji;;;iti;;:...: ...... ....: ::......::;;iiitijiiiii;i; -.:::.:GWEKKKDfDiDEWGKKfGDEDDEGDDDGDEKDEKKDKEEWWKKKKWEK#KWWKWWWWW#KWWWKWKKKKKEWEKKEWKKEKEKDDED;:::;;;;:;:::;;;,;:;;;;;;;;;i;;;jji;iti;;:;;::.:.. . ...:...: :.:.:::::iiiiiiii;iiii;i -:...:iKDEW#ELDDiDWEDEKfDDGDEEDDDDDDEEEKEDKKEWEWKWWKKW#EWWWKKWE##KWEWWWWW#WWKKKKKKEDEEDEKDEEDDi.:;;;;:;:;;:;;,;:;;;;;i;;;;;;;tLjj;;;t;;;::.. . : ...:: ::....: :.:.;:i;iiii;ii;;iii; -.....fWLW#WEDDDjDKDKKKfDEDEWDDDEEEKDEEKEDWKKK##EWWKKWW#WWKKKWW#WK#WKWW#KWWWWWEKKKKEKDEDKDEKDE;:;::;:::;:;:;;;:;;;;;;;;;;;,;;jLj;;i;i;;;,.:...: : :.::..: : ....:.::::;iiiii;i;ii;i,; -:..: GWLWWW#DDLfDDLKKKLGDEDEDEDDEDEKKDEWDEWEWKK#K#KWWWK#KKKKWWWEWWK#WKKK#KKEEKKKKDEEKDKEDEEDEi;:;;:;:;:;:;;;;;;;;i;i;;;;;;;;jGji;ti;;;,,:...:. .. .. : :.::......:::;iii;iii;i;i,i; - :..:DEDW#WELEffDDDWKKfDEEDKDGEDDWDKDKEEWEEWE#KKWWK#W#WWWEK#W#WK#KKK#KWEWWEWWKKKKKKEKEDEKDDDEj::;:;:;:;:;;;tLGGGLL;;;;;;:;,;LLLti;t;;;;:.:.. : :...::..: : t,....:::;:i;ii;i;,;i;i;, - :...EEK##WEDDfLDEEW#DfDEEKDGDDDDKDEDKEDKWWWWKKKKE#WEW#EEKEWWW#K#W#KKWKKKKWEWKKKKKEKEEEEEDDEDj;:;:::;,tLEEEEEEKEKEDj;;;:;;;;ELj;i;t;;,:.:... : . .:::....,D,: ...:::;ii,ii;,;,ii;i,: -: ..iWDE#K##EDffGDKKWELDDDEDDDEDKDEKKEEKKEEWWK#WW#KW#WW#WEKW#K#WWWWK#W#WEKKWKK#KKKEEEDEEEDEDEi:;::,;fGEEEEEEEEEEEEEDG;;;;;;;GGjtti;;;;;:.:: : : .... : .,jD..::...:::,;ii:iiii;:iii; - : iEDEWW#WEEDjfDEE#EDfDDEDGDDEDDKEDKEWWEWWEWKKEWK#WWW#WEKW#K#W#W##KK#EWWWWK#WEWWEKEDEDDEWEEGj;::;jLEEEEEEEEDDEEKWEEEf,;,;;;GLjt;;i;;,:.:. . . :.::..,iDL : : :::;ii;i;i:;,iii;;, -::iWWWEE#K#WDLfLEDKK#DGGDDGDEDEDKEEKKKKKWWKK#KWW##WWW#KWKK#W#W#W#KWW#EWKWWKWWE#KKEKDEEDEDEDEDi;,tLLDEEEEEEDEDEDEEKKEEDEf;;;iELjij;;,;;,:.::..: :: : . ;ijG, : :..:::i;,,;ii;i;,;ii; - :W#KWEEW##WKLfGDKKEWDLDDDDEDDEEKDKDKKKWKWKWWWE#KK#W#WWWWWWW#KWWWWWWWWE#WWWWK#K#KKEEDEKEEEKDEffLGEEEEEEEDEDDDDDDEEWKKEEDDf;fDjtiti;;:;.:...:. . ...:iijDi. : . ::::;ii;i;i;i;,i,;i: -:f##DWDWWWWKELfGDWWWEELDELDDEEWEDEKKWWWKWKKWKKWEWK#K##EKWW##K#EW#WEWWWWKK#KWKKWEKEKEEEEKEDEKDLDEEEEEEEKDDDDDDDDDDEEKEEEDDELLGLjt;;;:,::.:.. ..: ....,ijDf.... : :.::;iiiii,ii;;iii; -iEW#DWEEW##KDDfDEKKWKDLDDGDEDWEDKEWE#WKKWEKKKEWW#W#W##WKW#W#KWK#E##W#WW#WWWWWW#WKEDWDKEDWEEDEDDEDEEEDEDEEDDDDDDDDDEKKKKEDEEKLjj;i;;;;::.:..... : ::.jijDj.: :.: :::::i:ii:i;;iiiiii: -EWW#D#EEW#WWDDfDEKKWEDfDDDEDEWDEEKKKK#WKWKKKKKWWW#W#K#KWW#WWE#EWWW#E#W#WKWWWWKKKDEKEEKDDEEDWEDEEEEEEEDDEDDDDDDDDDDEEKKWKEDDWLjt;;;,;:,.:..... :.:.,tijLf. :.......::::;,:;,;,;;;,;;: -K###DWKK#W#EELfDK#KKKGGDEDDEWKKKKEW##WWWWWEKEW#K#WW#WKK##K#E#WKW#WWW#KW#KK#WKKKEKKDEDEEEWDKKDDEEEDEDDDDDDDDDGDDDDDDEEEKKEEDEGLt;;;;;.::... ... .,,iijjDi : ....::::::::i:::;::::;:: -EWW#D#WDWWW#DLLDKWEKKGGDDEDEKWEKKKWKWW#WWEEWEWWWWWWWWWE###WW#KKWWWW#E##K##WWWWEEDEEEDKDEEKKEEGEGEDDEDDDDDDDDDDGDGDDDEWKWKEEDLjt;;;;.,....::.....,t,ijfD,...: :.: .:.:::::::::::::::: -WEW#E#WEW#WWDGLDKKKWDLLDGDEDKWEKK#WW#W##WKEKEWW#KWWWKWWWW#W#WEW#W##K#WW#KW#WWEEEDEEDEEEKKKEEDKEDDDDDDDDDDGDGDDDGDGDDDEEKWWEELft;;,;;:...:....: .i,ijGDD.... .......: .:..:.:::.:.::: -E##WE#EWWWKWDDfD#W#WELDLGEEEKKKEK#W#WW#EWEWEWWWWW#WWKW#WW##WWWWWWWWWWWWW##KEEDKEKKKEEEEK#WWEEWWEDDDDDDGGGDGDDGDDGDDDDEKKEKEWDft;;,:.:.: .... . .i,jfDDf: ....::..: :.... ::...:::... -KE##W#WEW##WDGfDWWWKDLDfDEEEKKEKKWKW#W#WKWEWEWKK##EW#W#K##WW#EK#W##W#WWWWK#WEKEWEKEDEEKWWEEDK##WEDDDDGDDDGDGDDGDGDDDDEEEKWKEEEf;;;::.::.: ... ..iijLDDi: :..: : : ::.:: :.:. : :. -WE#KKWWD#KWEDGLEWWWEKfLDDDKKKKKK#W#WK#KWKKEWWKW#WK#WEW#WWW##WE##K###E##W#KKEEEEKWEWKEWKWWWEE###WKDGGGDGDGDGDDDDGGGDDDDEEKEKKEED;::;:.....:.. ..,iiLLDD;......::..:... ...: : ::: :: -#KK##WWEWWEWDDLEW#KEEfDDEKKKKWE##W#WK#KWKK#KW#WWWE#W##W#W#WW#EWWW##WWWW#KEKEEDEKKWEEWW#WEEDE####WEDGGGGDDGDGDGGDGGDDDDEEEKEWKEEf;::.:. .: . . .iijLDDi.: : ....:..: :: :..: ..:: ::. -###KW#WEW##WDDfKEW#WDLLDKKDKEWWKWW#K#W#K#KKWKKKWW#K#KK###W#W#K#W#KK#W##W#EKDKKEEKKKKK#KWWEDKWWW##WEDDGDGGDGDGGGDGDGDDDDEEKKKKKKD,.;:..: .......tjfGDD,....:: :.....: ....: :.: : .. -#WW#KWWDK#KWDDLD#W#EDfDDKWEWEKK#W#K##K#EWKWKK#KWWKW#KW#W#W###KKWWWW##W##WWEKDEEWKKKW#W#EKDEE###W#WKDGDGGGDGGDGGGDGDGDEEEEEKKEEKDf,,:.:.:. ... ,jjLDDf ::... :.:....:.:.:...:..::.... -#K####WD#E#EDDLEW#WEDfGEWEWEW#K##K#WW#EWKKWEWWWK##W#WW#W#WW#W#K#K###W#WKKEKDKEWK#W##W#WEDEKEW#WKWW#KDDGGDGGGGDDGGDDDDDEEKKEKEKEEEi;.:.:.. ....ijLLDD,.. :....::....:..:....:...: ::. -W#K#WW#EK#WEDDfK#E#WDfDDWWEKKW#KW#K#WW##KWWWKWE#KWWWKK##W##W#WW#W#WWW#KKWKEKKKKKWE##W#KEDEEEKW##WWW#DGDDGDGDGGGGDGGDDDEDKEKEWEEEDL,:.:. : . .,tjfDDD : : :: :: :: : : :....:: :. -######WE#WEKDELEWW#EDfLEWKKKWW#WWWW#W#KKKKE#WKWWKW#W###W#W##WWW#K####KWEKKKKKKW##W##KKKDEKKEKWWWW#WWEDDGGGGGGDGDGDGDDEEEEKEKKEKEEDt.:.:..... tjjfEDD : ... : :.............. ...: -#WWW#E#D#WEDEDLWWWWKDffKKWKK#W#WWWW##K##EWEW#K#K##W#W#W#W#WK#WEK##W#EKWEKWEW#K#WK#WKWKEEEDDEWWKWWWWWWKDDGGGGGDGDGDDDDEEEEEEEEEEEEDD :.:..:.: jjtDDDf. :.... : : :.... : ..... ....: -W###WW#EE#KEDDfEWWKKDfDDKKKWWK#WW#K##W#KKWWWWKKW#WWWKW#####W##W##W#KKKKKEEWWK#E##K##WWDDEDEDEWWEWWWWWKEDDGGGDGDGDGGDDEDEEKKKEEEEEED..:. . . .iijEDDj : .. ... . .. .: . .. . . -#WW###WKWWEDEDLKW#KEDfDEWKWK#W#KW#WWW#EWKKWWWWWKKK#W#W#W#K###W##W#KKKKKKKKWWWWW##W#KWEEEDEDEKKWKWWWWW#KDGDGGGGGGDGDDDDEEEEEEEEEEDEDi. :..::..jjjDDG,. . .. : .. : . :. ..: : : .. -W#K#W##EWWWEDDLKWKKEDfDEEEW#KWK#WW#WK#WKWEWWWWW#WK#WWW###W#K###W###EKKW#WWE#WWWWWWWWEWDDEDDEEWKKWK#KWWWEDGGGDGDGDGDDDEDKEKEEEEKEEDDf,:. . . .tijDDf.. .. .. .. : .. : . . . -#WWWW##EK#KEEDfKWKWEGfDEKKW#KKWW#K#KWWWWWEWW#E#K##K#KW###W#K#####KWEKKW#WWK##KKWKW#KKKDDDDDDDKWKKKKWW#WWDDGGDGDGGDDDDEDEEEKEEEDEDEDDL, .:...,jjGDDt : .: : ...... : ... : ....: .. -#W#W#W#WKKEDDDLKWW#EDfGKK#KW###WW#K#K#KKKWW#KWW#WW#K##K##K###W#W##EKKW#K#E#E#WWWWEKKWWEEDEEDEKKKKKWWKWWWEDDGGGGDDGDDDDEEEEEEKEEDEDDDDj.: ...tjDEDG,. .. . .: .: ....:.... : ... : .. -WWW#W###EWKEDDLKKWKDDfGKKKW#WK#KWWWW#W#KWWWWEWK#WKW#KW##W###W####WWEWWW#WWE#K#WK#KWKWWEDEDEDEWKWKKKKWWWWWEDGDGGGDGDDDEEDEEEEEEDDDDEDDD.... .tDEDDD, ... :......... : : .: :: ..... -WW###W##EWEEDDLKEWEKGfDEWW#W##WWW#KW#W#WE#WWWEW#WE#K###WK#WWK###WWEKWW#W#KWW#W#EEKKKW#WDDDDEDEKKKKKKKW#WWWWGGGGGDGDDDDEDEEEEEEDDDDDDDDj. ..;DEDDDL...:..:...:...::.........:..::..: -##W#KW##EKWDGDfKKKKEDfDKEWWWWW#WK#K#WWWKWKW#KKK#WW#W##W#######W##WW#K##K##KW#KW#WEK#KKEEDKEDEDEWKWKWWKWKW#WDDGGGDGDDDEEEEEEEEDDDDDDDDDL,.. tEEDDDf..: ::..:: ::.::.::::..:..:..:.::. -WWK#W###DEEEGDLEKKKKDfDEWK#K##W##W#EW#KWWW#KKW#W##WWWW##W#W#W##W#KEWKWW#KWK##W#KEEWW##KDEDDDEEDKWKWKWWWWWWWEDGDGGDDDDDEDEEEEDEDDDDDDDDGL .,tEDKDGf.:.:. :...:. : :..:.::..: :. :... -W#W#W###DEWEDGGEDKKEDLDKK#K#WW###W#WK#KWWW#EWW#W##W#K##WW#W#WW##WKKKKKWWWWWWK#KWKKK##KKEDEEDEEEDWKKKWKW#WWWWKDGGGDGDDDEDEEEEEDEDDDGDGDDDD.LDEEDDDj:..:::....::.:..: ::.:.... :...:.: -#KW#WW##EEKDGDfDEKWEDLEK#K#K##W##K#KWWWWW#K#KWK###WW#W##W####W#KWE#EW##WWWW##WKKKK#WWKKDEDKKEEDEKWWWWKWKWWW#KEGGGGGDDEDEEEDEDDDDDDDDDGGGDjGDEDDDGj.:: ::.::: ::..::...: :.:::.....: diff --git a/jun_springboot_plugin/springboot_redis/src/main/resources/sql/t_user.sql b/jun_springboot_plugin/springboot_redis/src/main/resources/sql/t_user.sql deleted file mode 100644 index 7f1e4b8032..0000000000 --- a/jun_springboot_plugin/springboot_redis/src/main/resources/sql/t_user.sql +++ /dev/null @@ -1,32 +0,0 @@ -/* -Navicat MySQL Data Transfer - -Source Server : 127.0.0.1-mysql -Source Server Version : 50718 -Source Host : 127.0.0.1:3306 -Source Database : test - -Target Server Type : MYSQL -Target Server Version : 50718 -File Encoding : 65001 - -Date: 2018-02-27 16:12:19 -*/ - -SET FOREIGN_KEY_CHECKS=0; - --- ---------------------------- --- Table structure for t_user --- ---------------------------- -DROP TABLE IF EXISTS `t_user`; -CREATE TABLE `t_user` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `username` varchar(255) DEFAULT NULL, - `password` varchar(255) DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=96 DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of t_user --- ---------------------------- -INSERT INTO `t_user` VALUES ('52', 'admin', 'admin'); diff --git a/jun_springboot_plugin/springboot_redis/src/test/java/com/xncoding/service/UserServiceTest.java b/jun_springboot_plugin/springboot_redis/src/test/java/com/xncoding/service/UserServiceTest.java deleted file mode 100644 index 1289fec1ba..0000000000 --- a/jun_springboot_plugin/springboot_redis/src/test/java/com/xncoding/service/UserServiceTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.xncoding.service; - -import com.xncoding.pos.Application; -import com.xncoding.pos.dao.entity.User; -import com.xncoding.pos.service.UserService; -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 org.springframework.transaction.annotation.Transactional; - -import java.util.Random; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - - -/** - * UserServiceTest - * - * @author XiongNeng - * @version 1.0 - * @since 2018/2/2 - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -@Transactional -public class UserServiceTest { - @Autowired - private UserService userService; - @Test - public void testCache() { - int id = new Random().nextInt(1000); - User user = new User(id, "admin", "admin"); - userService.createUser(user); - User user1 = userService.getById(id); // 第1次访问 - assertEquals(user1.getPassword(), "admin"); - User user2 = userService.getById(id); // 第2次访问 - assertEquals(user2.getPassword(), "admin"); - user.setPassword("123456"); - userService.updateUser(user); - User user3 = userService.getById(id); // 第3次访问 - assertEquals(user3.getPassword(), "123456"); - userService.deleteById(id); - assertNull(userService.getById(id)); - } -} diff --git a/jun_springboot_plugin/springboot_redis_cluster/README.md b/jun_springboot_plugin/springboot_redis_cluster/README.md deleted file mode 100644 index 63af66ca52..0000000000 --- a/jun_springboot_plugin/springboot_redis_cluster/README.md +++ /dev/null @@ -1,180 +0,0 @@ -#springboot-jedisCluster - -项目主框架采用springboot,介绍redis集群安装及redis3.0安装方式以及和jedisCluster结合使用的方法! - -##Redis 3.0 集群搭建 - -### 虚拟机安装 - -``` -开启两个虚拟机 ,分别在两个虚拟机上开启3个Redis实例, -3主3从两个虚拟机里的实例互为主备,虚拟机安装非本文范畴,可查阅相关资料。 - -下面分别在两个虚拟机上安装,在安装redis之前需要先将两台虚拟机防火墙关闭,并配置好网络, -两台机器IP分别设置为:10.16.70.133,10.16.70.134。此处可根据自己网络环境自行设置。 -需要保证两台虚拟机均可连接外网,以方便执行yum安装相关软件。 -``` - -### 安装ruby rubygems - -``` - yum install ruby rubygems -y -``` - -### 安装Redis3.0.2 - -``` -  wget http://download.redis.io/releases/redis-3.0.2.tar.gz -  tar xzf redis-3.0.2.tar.gz -  cd redis-3.0.2 -  make -``` -##### 在执行 wget 命令时如果碰到如下提示,需要先执行命令:yum -y install wget - -``` -[root@centos7 local]# wget http://download.redis.io/releases/redis-3.0.2.tar.gz --bash: wget: command not found -``` - -##### 在执行 make 命令时,如果碰到如下提示,需要先执行命令:yum install gcc - -``` -cd src && make all -………略……… -"/bin/sh: cc: command not found" -make[1]: *** [adlist.o] Error 127 -make[1]: Leaving directory `/usr/local/redis-3.0.2/src' -make: *** [all] Error 2 -``` - -##### 在执行 make 命令时,如果碰到如下提示,需要将 make 命令替换为: make MALLOC=libc - -``` -[root@centos7 redis-3.0.2]# make -cd src && make all -make[1]: Entering directory `/usr/local/redis-3.0.2/src' - CC adlist.o -In file included from adlist.c:34:0: -zmalloc.h:50:31: fatal error: jemalloc/jemalloc.h: No such file or directory - #include - ^ -compilation terminated. -make[1]: *** [adlist.o] Error 1 -make[1]: Leaving directory `/usr/local/redis-3.0.2/src' -make: *** [all] Error 2 -``` - -### 配置 - -* 在两个机器上分别建立 6379 6380 6381 文件夹 - -``` -  [root@centos7 redis-3.0.2]# mkdir 6379 6380 6381 -  [root@centos7 redis-3.0.2]# cp redis.conf 6379 -  [root@centos7 redis-3.0.2]# cp redis.conf 6380 -  [root@centos7 redis-3.0.2]# cp redis.conf 6381 -``` - -### 分别修改位于文件夹6379,6380,6381下的Redis配置文件 - -``` - port 6379 - pidfile redis-6379.pid - dbfilename dump-6379.rdb - appendfilename "appendonly-6379.aof" - cluster-config-file nodes-6379.conf - cluster-enabled yes - cluster-node-timeout 5000 - appendonly yes -``` - -### 分别启动两个机器的Redis实例,更换端口,命令共在两台机器上执行6次 - -``` -  [root@centos7 src]# ./redis-server ../6379/redis.conf -``` - -### 启动集群  - -``` -  [root@centos7 src]# ./redis-trib.rb create --replicas 1 10.16.70.133:6379 10.16.70.133:6380 10.16.70.133:6381 - 10.16.70.134:6379 10.16.70.134:6380 10.16.70.134:6381 -  >>> Creating cluster - Connecting to node 10.16.70.133:6379: OK - Connecting to node 10.16.70.133:6380: OK - Connecting to node 10.16.70.133:6381: OK - Connecting to node 10.16.70.134:6379: OK - Connecting to node 10.16.70.134:6380: OK - Connecting to node 10.16.70.134:6381: OK - >>> Performing hash slots allocation on 6 nodes... - Using 3 masters: - 10.16.70.133:6379 - 10.16.70.134:6379 - 10.16.70.133:6380 - Adding replica 10.16.70.134:6380 to 10.16.70.133:6379 - Adding replica 10.16.70.133:6381 to 10.16.70.134:6379 - Adding replica 10.16.70.134:6381 to 10.16.70.133:6380 - M: 11dcaf921094fe7d000e6b684072f50fe860ba62 10.16.70.133:6379 - slots:0-5460 (5461 slots) master - M: f8767f679c53a949cbc65a1657a41617e4079bde 10.16.70.133:6380 - slots:10923-16383 (5461 slots) master - S: 0b0c95e7c8f6e1f366a8cc265b2ca39a5b56f4fe 10.16.70.133:6381 - replicates 52cf14a1919a9bf280aee2d0bfacd7811778bac8 - M: 52cf14a1919a9bf280aee2d0bfacd7811778bac8 10.16.70.134:6379 - slots:5461-10922 (5462 slots) master - S: 91273dcb163ddf54e6e0a50beac84ee034a9d92d 10.16.70.134:6380 - replicates 11dcaf921094fe7d000e6b684072f50fe860ba62 - S: 708710dd3926a5f61b65de2797385c3ac06c716a 10.16.70.134:6381 - replicates f8767f679c53a949cbc65a1657a41617e4079bde - Can I set the above configuration? (type 'yes' to accept): yes - >>> Nodes configuration updated - >>> Assign a different config epoch to each node - >>> Sending CLUSTER MEET messages to join the cluster - Waiting for the cluster to join.. - >>> Performing Cluster Check (using node 10.16.70.133:6379) - M: 11dcaf921094fe7d000e6b684072f50fe860ba62 10.16.70.133:6379 - slots:0-5460 (5461 slots) master - M: f8767f679c53a949cbc65a1657a41617e4079bde 10.16.70.133:6380 - slots:10923-16383 (5461 slots) master - M: 0b0c95e7c8f6e1f366a8cc265b2ca39a5b56f4fe 10.16.70.133:6381 - slots: (0 slots) master - replicates 52cf14a1919a9bf280aee2d0bfacd7811778bac8 - M: 52cf14a1919a9bf280aee2d0bfacd7811778bac8 10.16.70.134:6379 - slots:5461-10922 (5462 slots) master - M: 91273dcb163ddf54e6e0a50beac84ee034a9d92d 10.16.70.134:6380 - slots: (0 slots) master - replicates 11dcaf921094fe7d000e6b684072f50fe860ba62 - M: 708710dd3926a5f61b65de2797385c3ac06c716a 10.16.70.134:6381 - slots: (0 slots) master - replicates f8767f679c53a949cbc65a1657a41617e4079bde - [OK] All nodes agree about slots configuration. - >>> Check for open slots... - >>> Check slots coverage... - [OK] All 16384 slots covered. -  [root@centos7 src]# -``` -##### 启动集群时,如果碰到如下提示,需要先执行命令 gem install redis --version 3.0.0 - -``` -[root@centos7 src]# ./redis-trib.rb create --replicas 1 10.16.70.133:6379 10.16.70.133:6380 10.16.70.133:6381 - 10.16.70.134:6379 10.16.70.134:6380 10.16.70.134:6381 - /usr/share/rubygems/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- redis (LoadError) - from /usr/share/rubygems/rubygems/core_ext/kernel_require.rb:55:in `require' - from ./redis-trib.rb:25:in `
    ' -``` - -###参考 - -http://redisdoc.com/index.html - -### 期望 - -欢迎提出更好的意见,帮助完善我们的项目,以督促我们前行! - -### 版权 - -[Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0) - -### 捐赠 - -![捐赠 springboot-jedisCluster](http://git.oschina.net/uploads/images/2016/1023/084255_833edeac_364262.png "支持一下springboot-jedisCluster") diff --git a/jun_springboot_plugin/springboot_redis_cluster/pom.xml b/jun_springboot_plugin/springboot_redis_cluster/pom.xml deleted file mode 100644 index 437c64df19..0000000000 --- a/jun_springboot_plugin/springboot_redis_cluster/pom.xml +++ /dev/null @@ -1,63 +0,0 @@ - - - 4.0.0 - - io.github.wujun728 - springboot_redis_cluster - 1.0 - jar - - - org.springframework.boot - spring-boot-starter-parent - 1.4.1.RELEASE - - - - - UTF-8 - org.tdcg.Application - 1.8 - - - - - org.springframework.boot - spring-boot-starter - - - - org.springframework.boot - spring-boot-starter-redis - - - - org.springframework.boot - spring-boot-starter-test - test - - - - com.google.guava - guava - 17.0 - - - - commons-lang - commons-lang - 2.6 - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_redis_cluster/src/main/java/com/jun/plugin/redis/Application.java b/jun_springboot_plugin/springboot_redis_cluster/src/main/java/com/jun/plugin/redis/Application.java deleted file mode 100644 index 5c8469c2ec..0000000000 --- a/jun_springboot_plugin/springboot_redis_cluster/src/main/java/com/jun/plugin/redis/Application.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.jun.plugin.redis; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -/** - * @Title: Application - * @Package: org.tdcg - * @Description: 启动类 - * @Author: 二东 - * @date: 2016/10/24 - * @Version: V1.0 - */ -@SpringBootApplication -public class Application { - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } -} diff --git a/jun_springboot_plugin/springboot_redis_cluster/src/main/java/com/jun/plugin/redis/entity/User.java b/jun_springboot_plugin/springboot_redis_cluster/src/main/java/com/jun/plugin/redis/entity/User.java deleted file mode 100644 index 92ffd9537f..0000000000 --- a/jun_springboot_plugin/springboot_redis_cluster/src/main/java/com/jun/plugin/redis/entity/User.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.jun.plugin.redis.entity; - -import java.io.Serializable; - -/** - * @Title: User - * @Package: org.tdcg.entity - * @Description: 测试类,用户实体 - * @Author: 二东 - * @date: 2016/10/24 - * @Version: V1.0 - */ -public class User implements Serializable { - private static final long serialVersionUID = 3802423545972880637L; - private String id; - private String name; - private int age; - private String email; - - public User() { - } - - public User(String id, String name, int age) { - this.id = id; - this.name = name; - this.age = age; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - @Override - public String toString() { - return "User{" + - "id='" + id + '\'' + - ", name='" + name + '\'' + - ", age=" + age + - ", email='" + email + '\'' + - '}'; - } -} diff --git a/jun_springboot_plugin/springboot_redis_cluster/src/main/java/com/jun/plugin/redis/redis/ICacheManager.java b/jun_springboot_plugin/springboot_redis_cluster/src/main/java/com/jun/plugin/redis/redis/ICacheManager.java deleted file mode 100644 index d17d8b1491..0000000000 --- a/jun_springboot_plugin/springboot_redis_cluster/src/main/java/com/jun/plugin/redis/redis/ICacheManager.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.jun.plugin.redis.redis; - -import java.io.Serializable; -import java.util.List; -import java.util.Map; - -/** - * @Title: ICacheManager - * @Package: org.tdcg.redis - * @Description: 缓存接口,定义方法 - * @Author: 二东 - * @date: 2016/10/24 - * @Version: V1.0 - */ -public interface ICacheManager { - - /** - * 根据缓存key获取值 - * - * @param cacheKey - * @return - */ - public Object getCache(Serializable cacheKey); - - /** - * 设置缓存数据的key-value,并设置失效时间,单位为秒 - * - * @param cacheKey - * @param objValue - * @param expiration - * @return - */ - public boolean putCache(Serializable cacheKey, Object objValue, int expiration); - - /** - * 清除缓存 - * - * @param cacheKey - */ - public Long removeCache(Serializable cacheKey); - - /** - * 向指定list集合中添加对象,在list尾部添加对象 - * - * @param cacheKey - * @param objValue - * @return - */ - public boolean putListCache(Serializable cacheKey, Object objValue); - - /** - * 向指定list集合中添加对象,并指定位置坐标 - * - * @param cacheKey - * @param objValue - * @param index - * @return - */ - public boolean putListCache(Serializable cacheKey, Object objValue, int index); - - /** - * 根据坐标,返回一段集合 - * - * @param cacheKey - * @param start 起始坐标 头部为0 - * @param end 结束坐标 尾部为-1 - * @return - */ - public List getListCache(Serializable cacheKey, int start, int end); - - /** - * 返回结合 - * - * @param cacheKey - * @return - */ - public List getListCache(Serializable cacheKey); - - /** - * 裁剪list集合 - * - * @param cacheKey - * @param start 起始坐标 - * @param end 结束坐标 - * @return - */ - public boolean trimListCache(Serializable cacheKey, int start, int end); - - /** - * 添加map集合 - * - * @param cacheKey - * @param map - * @return - */ - public boolean putMapCache(Serializable cacheKey, Map map); - - /** - * 删除map中的键值 - * - * @param cacheKey - * @param mapKey - * @return - */ - public boolean deleteMapCache(Serializable cacheKey, Serializable mapKey); - - - /** - * 获取map中的值 - * - * @param cacheKey - * @param mapKey - * @return - */ - public Object getMapValueCache(Serializable cacheKey, Serializable mapKey); -} diff --git a/jun_springboot_plugin/springboot_redis_cluster/src/main/java/com/jun/plugin/redis/redis/JedisClusterFactory.java b/jun_springboot_plugin/springboot_redis_cluster/src/main/java/com/jun/plugin/redis/redis/JedisClusterFactory.java deleted file mode 100644 index edf1db7ce0..0000000000 --- a/jun_springboot_plugin/springboot_redis_cluster/src/main/java/com/jun/plugin/redis/redis/JedisClusterFactory.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.jun.plugin.redis.redis; - -import org.apache.commons.pool2.impl.GenericObjectPoolConfig; -import org.springframework.beans.factory.FactoryBean; -import org.springframework.beans.factory.InitializingBean; -import redis.clients.jedis.HostAndPort; -import redis.clients.jedis.JedisCluster; - -import java.text.ParseException; -import java.util.HashSet; -import java.util.Set; - -/** - * @Title: JedisClusterFactory - * @Package: org.tdcg.redis - * @Description: 工场类 - * @Author: 二东 - * @date: 2016/10/24 - * @Version: V1.0 - */ -public class JedisClusterFactory implements FactoryBean, InitializingBean { - - private GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig(); - private JedisCluster jedisCluster; - private int connectionTimeout = 2000; - private int soTimeout = 3000; - private int maxRedirections = 5; - private Set jedisClusterNodes; - - @Override - public void afterPropertiesSet() throws Exception { - if (jedisClusterNodes == null || jedisClusterNodes.size() == 0) { - throw new NullPointerException("jedisClusterNodes is null."); - } - Set haps = new HashSet(); - for (String node : jedisClusterNodes) { - String[] arr = node.split(":"); - if (arr.length != 2) { - throw new ParseException("node address error !",node.length()-1); - } - haps.add(new HostAndPort(arr[0], Integer.valueOf(arr[1]))); - } - jedisCluster = new JedisCluster(haps, connectionTimeout, soTimeout, maxRedirections, genericObjectPoolConfig); - } - - @Override - public JedisCluster getObject() throws Exception { - return jedisCluster; - } - - @Override - public Class getObjectType() { - return (this.jedisCluster != null ? this.jedisCluster.getClass() : JedisCluster.class); - } - - @Override - public boolean isSingleton() { - return true; - } - - public GenericObjectPoolConfig getGenericObjectPoolConfig() { - return genericObjectPoolConfig; - } - - public void setGenericObjectPoolConfig(GenericObjectPoolConfig genericObjectPoolConfig) { - this.genericObjectPoolConfig = genericObjectPoolConfig; - } - - public JedisCluster getJedisCluster() { - return jedisCluster; - } - - public void setJedisCluster(JedisCluster jedisCluster) { - this.jedisCluster = jedisCluster; - } - - public int getConnectionTimeout() { - return connectionTimeout; - } - - public void setConnectionTimeout(int connectionTimeout) { - this.connectionTimeout = connectionTimeout; - } - - public int getSoTimeout() { - return soTimeout; - } - - public void setSoTimeout(int soTimeout) { - this.soTimeout = soTimeout; - } - - public int getMaxRedirections() { - return maxRedirections; - } - - public void setMaxRedirections(int maxRedirections) { - this.maxRedirections = maxRedirections; - } - - public Set getJedisClusterNodes() { - return jedisClusterNodes; - } - - public void setJedisClusterNodes(Set jedisClusterNodes) { - this.jedisClusterNodes = jedisClusterNodes; - } -} \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_redis_cluster/src/main/java/com/jun/plugin/redis/redis/RedisConfiguration.java b/jun_springboot_plugin/springboot_redis_cluster/src/main/java/com/jun/plugin/redis/redis/RedisConfiguration.java deleted file mode 100644 index a4b99d812f..0000000000 --- a/jun_springboot_plugin/springboot_redis_cluster/src/main/java/com/jun/plugin/redis/redis/RedisConfiguration.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.jun.plugin.redis.redis; - - -import com.google.common.collect.Sets; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.cache.annotation.CachingConfigurerSupport; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import java.util.Collections; -import java.util.Set; - -/** - * @Title: RedisConfiguration - * @Package: org.tdcg.redis - * @Description: redis初始化配置 - * @Author: 二东 - * @date: 2016/10/24 - * @Version: V1.0 - */ -@Configuration -public class RedisConfiguration extends CachingConfigurerSupport { - - @Bean(name = "jedisCluster") - @ConfigurationProperties(prefix = "myCluster.cluster") - public JedisClusterFactory jedisCluster( - @Value("${myCluster.cluster.host}") String host, - @Value("${myCluster.cluster.connectionTimeout}") int connectionTimeout, - @Value("${myCluster.cluster.soTimeout}") int soTimeout, - @Value("${myCluster.cluster.maxRedirections}") int maxRedirections) { - JedisClusterFactory jedisClusterFactory = new JedisClusterFactory(); - jedisClusterFactory.setConnectionTimeout(connectionTimeout); - jedisClusterFactory.setSoTimeout(soTimeout); - jedisClusterFactory.setMaxRedirections(maxRedirections); - String[] split = host.split(","); - Set hosts = Sets.newHashSet(); - Collections.addAll(hosts, split); - jedisClusterFactory.setJedisClusterNodes(hosts); - return jedisClusterFactory; - } -} - diff --git a/jun_springboot_plugin/springboot_redis_cluster/src/main/java/com/jun/plugin/redis/redis/impl/CacheManager.java b/jun_springboot_plugin/springboot_redis_cluster/src/main/java/com/jun/plugin/redis/redis/impl/CacheManager.java deleted file mode 100644 index 1469623311..0000000000 --- a/jun_springboot_plugin/springboot_redis_cluster/src/main/java/com/jun/plugin/redis/redis/impl/CacheManager.java +++ /dev/null @@ -1,186 +0,0 @@ -package com.jun.plugin.redis.redis.impl; - -import org.apache.log4j.Logger; -import org.springframework.stereotype.Service; - -import com.jun.plugin.redis.redis.ICacheManager; - -import java.util.List; -import java.util.Map; - -/** - * @Title: CacheManager - * @Package: org.tdcg.redis.impl - * @Description: - * @Author: 二东 - * @date: 2016/10/24 - * @Version: V1.0 - */ -@Service("cacheManager") -public final class CacheManager { - - private static final Logger logger = Logger.getLogger(CacheManager.class); - // 超时时间,单位为秒 - private final int expiration = 3600; - private ICacheManager iCacheManager; - - public Object getCache(String cacheKey) { - return iCacheManager.getCache(cacheKey); - } - - public boolean putCache(String cacheKey, Object objValue) { - return putCache(cacheKey, objValue, expiration); - } - - public boolean putCache(String cacheKey, Object objValue, int expiration) { - try { - if (expiration <= 0) { - expiration = this.expiration; - } - return iCacheManager.putCache(cacheKey.toString(), objValue, expiration); - } catch (Throwable ex) { - logger.error("Cannot set the cache with the cacheKey:" + cacheKey.toString(), ex); - } - return false; - } - - public boolean removeCache(String cacheKey) { - try { - iCacheManager.removeCache(cacheKey); - return true; - } catch (Throwable ex) { - logger.error("Cannot remove the cache with the cacheKey:" + cacheKey.toString(), ex); - return false; - } - } - - /** - * 将对象以list集合形式存放 - * - * @param cacheKey - * @param objValue - * @param objValue - * @return - */ - public boolean putListCache(String cacheKey, Object objValue) { - try { - return iCacheManager.putListCache(cacheKey, objValue); - } catch (Throwable ex) { - logger.error("Cannot put the list cache with the cacheKey:" + cacheKey.toString(), ex); - return false; - } - } - - /** - * 将对象存放在list集合指定index位置 - * - * @param cacheKey - * @param objValue - * @param index - * @return - */ - public boolean putListCache(String cacheKey, Object objValue, int index) { - try { - return iCacheManager.putListCache(cacheKey, objValue, index); - } catch (Throwable ex) { - logger.error("Cannot put the list cache in the index with the cacheKey:" + cacheKey.toString(), ex); - return false; - } - } - - /** - * 获取list集合全部结果集 - * - * @param cacheKey - * @return - */ - public List getListCache(String cacheKey) { - try { - return iCacheManager.getListCache(cacheKey); - } catch (Throwable ex) { - logger.error("Cannot get the list cache with the cacheKey:" + cacheKey.toString(), ex); - return null; - } - } - - /** - * 获取指定索引段内的集合 - * - * @param cacheKey - * @return - */ - public List getListCache(String cacheKey, int start, int end) { - try { - return iCacheManager.getListCache(cacheKey, start, end); - } catch (Throwable ex) { - logger.error("Cannot get the list cache between start and end with the cacheKey:" + cacheKey.toString(), ex); - return null; - } - } - - /** - * 删减list集合指定坐标范围内数据 - * - * @param cacheKey - * @param start 起始坐标 - * @param end 结束坐标 - * @return - */ - public boolean trimListCache(String cacheKey, int start, int end) { - try { - return iCacheManager.trimListCache(cacheKey, start, end); - } catch (Throwable ex) { - logger.error("Cannot get the list cache with the cacheKey:" + cacheKey.toString(), ex); - return false; - } - } - - /** - * 存放map集合缓存 - * - * @param cacheKey - * @param map - * @return - */ - public boolean putMapCache(String cacheKey, Map map) { - try { - return iCacheManager.putMapCache(cacheKey, map); - } catch (Throwable ex) { - logger.error("Cannot put the map cache with the cacheKey:" + cacheKey.toString(), ex); - return false; - } - } - - /** - * 删除Map集合中指定key-value - * - * @param cacheKey - * @param mapKey - * @return - */ - public boolean deleteMapCache(String cacheKey, String mapKey) { - try { - return iCacheManager.deleteMapCache(cacheKey, mapKey); - } catch (Throwable ex) { - logger.error("Cannot delete the map cache with the cacheKey:" + cacheKey.toString() + " and the mapKey:" + mapKey, ex); - return false; - } - } - - /** - * 根据key查询集合中的value值 - * - * @param cacheKey - * @param mapKey - * @return - */ - public Object getMapValueCache(String cacheKey, String mapKey) { - try { - return iCacheManager.deleteMapCache(cacheKey, mapKey); - } catch (Throwable ex) { - logger.error("Cannot get the map value cache with the cacheKey:" + cacheKey.toString() + " and the mapKey:" + mapKey, ex); - return false; - } - } -} - diff --git a/jun_springboot_plugin/springboot_redis_cluster/src/main/java/com/jun/plugin/redis/redis/impl/JedisCacheManager.java b/jun_springboot_plugin/springboot_redis_cluster/src/main/java/com/jun/plugin/redis/redis/impl/JedisCacheManager.java deleted file mode 100644 index ab5aa6a87c..0000000000 --- a/jun_springboot_plugin/springboot_redis_cluster/src/main/java/com/jun/plugin/redis/redis/impl/JedisCacheManager.java +++ /dev/null @@ -1,132 +0,0 @@ -package com.jun.plugin.redis.redis.impl; - -import org.apache.commons.lang.StringUtils; -import org.springframework.stereotype.Service; - -import com.jun.plugin.redis.redis.ICacheManager; -import com.jun.plugin.redis.util.SerializingUtil; - -import redis.clients.jedis.JedisCluster; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -/** - * @Title: JedisCacheManager - * @Package: org.tdcg.redis.impl - * @Description: 接口实现 - * @Author: 二东 - * @date: 2016/10/24 - * @Version: V1.0 - */ -@Service("iCacheManager") -public class JedisCacheManager implements ICacheManager { - - private static final String JEDIS_SET_RETURN_OK = "OK"; - - private JedisCluster jedisCluster; - - @Override - public Object getCache(Serializable cacheKey) { - return SerializingUtil.deserialize((byte[]) jedisCluster.get(SerializingUtil.serialize(cacheKey))); - } - - @Override - public boolean putCache(Serializable cacheKey, Object objValue, int expiration) { - String result = jedisCluster.setex(SerializingUtil.serialize(cacheKey), expiration, SerializingUtil.serialize(objValue)); - if (StringUtils.equals(JEDIS_SET_RETURN_OK, result)) { - return true; - } - return false; - } - - @Override - public Long removeCache(Serializable cacheKey) { - return jedisCluster.del(SerializingUtil.serialize(cacheKey)); - } - - @Override - public boolean putListCache(Serializable cacheKey, Object objValue) { - Long num = jedisCluster.rpush(SerializingUtil.serialize(cacheKey), SerializingUtil.serialize(objValue)); - if (num > 0) { - return true; - } - return false; - } - - @Override - public boolean putListCache(Serializable cacheKey, Object objValue, int index) { - String result = jedisCluster.lset(SerializingUtil.serialize(cacheKey), index, SerializingUtil.serialize(objValue)); - if (StringUtils.equals(JEDIS_SET_RETURN_OK, result)) { - return true; - } - return false; - } - - @Override - public List getListCache(Serializable cacheKey, int start, int end) { - List list = jedisCluster.lrange(SerializingUtil.serialize(cacheKey), start, end); - if (null != list && list.size() > 0) { - List objList = new ArrayList(); - for (byte[] b : list) { - objList.add(SerializingUtil.deserialize(b)); - } - return objList; - } - return null; - } - - @Override - public List getListCache(Serializable cacheKey) { - return getListCache(cacheKey, 0, -1); - } - - @Override - public boolean trimListCache(Serializable cacheKey, int start, int end) { - String result = jedisCluster.ltrim(SerializingUtil.serialize(cacheKey), start, end); - if (StringUtils.equals(JEDIS_SET_RETURN_OK, result)) { - return true; - } - return false; - } - - @Override - public boolean putMapCache(Serializable cacheKey, Map map) { - if (null != map && !map.isEmpty()) { - Map byteMap = new HashMap(); - for (Entry entry : map.entrySet()) { - byteMap.put(SerializingUtil.serialize(entry.getKey()), SerializingUtil.serialize(entry.getValue())); - } - String result = jedisCluster.hmset(SerializingUtil.serialize(cacheKey), byteMap); - if (StringUtils.equals(JEDIS_SET_RETURN_OK, result)) { - return true; - } - return true; - } - return false; - } - - @Override - public boolean deleteMapCache(Serializable cacheKey, Serializable mapKey) { - Long result = jedisCluster.hdel(SerializingUtil.serialize(cacheKey), SerializingUtil.serialize(mapKey)); - if (result > 0) { - return true; - } - return false; - } - - - @Override - public Object getMapValueCache(Serializable cacheKey, Serializable mapKey) { - List list = jedisCluster.hmget(SerializingUtil.serialize(cacheKey), SerializingUtil.serialize(mapKey)); - if (null != list && list.size() > 0) { - return SerializingUtil.deserialize(list.get(0)); - } - return null; - } - -} diff --git a/jun_springboot_plugin/springboot_redis_cluster/src/main/java/com/jun/plugin/redis/util/SerializingUtil.java b/jun_springboot_plugin/springboot_redis_cluster/src/main/java/com/jun/plugin/redis/util/SerializingUtil.java deleted file mode 100644 index 947d87e53d..0000000000 --- a/jun_springboot_plugin/springboot_redis_cluster/src/main/java/com/jun/plugin/redis/util/SerializingUtil.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.jun.plugin.redis.util; - -import org.apache.log4j.Logger; -import org.springframework.cache.CacheManager; - -import java.io.*; - -/** - * @Title: SerializingUtil - * @Package: org.tdcg.util - * @Description: 序列化工具类,负责byte[]和Object之间的相互转换. - * @Author: 二东 - * @date: 2016/10/24 - * @Version: V1.0 - */ -public class SerializingUtil { - - private static final Logger logger = Logger.getLogger(CacheManager.class); - - /** - * 功能简述: 对实体Bean进行序列化操作. - * - * @param source 待转换的实体 - * @return 转换之后的字节数组 - * @throws Exception - */ - public static byte[] serialize(Object source) { - ByteArrayOutputStream byteOut = null; - ObjectOutputStream ObjOut = null; - try { - byteOut = new ByteArrayOutputStream(); - ObjOut = new ObjectOutputStream(byteOut); - ObjOut.writeObject(source); - ObjOut.flush(); - } catch (IOException e) { - logger.error(source.getClass().getName() + " serialized error !", e); - } finally { - try { - if (null != ObjOut) { - ObjOut.close(); - } - } catch (IOException e) { - ObjOut = null; - } - } - return byteOut.toByteArray(); - } - - /** - * 功能简述: 将字节数组反序列化为实体Bean. - * - * @param source 需要进行反序列化的字节数组 - * @return 反序列化后的实体Bean - * @throws Exception - */ - public static Object deserialize(byte[] source) { - ObjectInputStream ObjIn = null; - Object retVal = null; - try { - ByteArrayInputStream byteIn = new ByteArrayInputStream(source); - ObjIn = new ObjectInputStream(byteIn); - retVal = ObjIn.readObject(); - } catch (Exception e) { - logger.error("deserialized error !", e); - } finally { - try { - if (null != ObjIn) { - ObjIn.close(); - } - } catch (IOException e) { - ObjIn = null; - } - } - return retVal; - } -} \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_redis_cluster/src/main/resources/application.yml b/jun_springboot_plugin/springboot_redis_cluster/src/main/resources/application.yml deleted file mode 100644 index 31d6f56fed..0000000000 --- a/jun_springboot_plugin/springboot_redis_cluster/src/main/resources/application.yml +++ /dev/null @@ -1,15 +0,0 @@ -# server -server: - port: 8081 - -# LOG -logging: - config: classpath:logback.xml - -# RedisCluster -myCluster: - cluster: - host: 10.16.70.133:6379,10.16.70.133:6380,10.16.70.133:6381,10.16.70.134:7379,10.16.70.134:7380,10.16.70.134:7381 - connectionTimeout: 3000 - soTimeout: 3000 - maxRedirections: 5 \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_redis_cluster/src/main/resources/logback.xml b/jun_springboot_plugin/springboot_redis_cluster/src/main/resources/logback.xml deleted file mode 100644 index 5cb3861ef9..0000000000 --- a/jun_springboot_plugin/springboot_redis_cluster/src/main/resources/logback.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - %d{yyyy-MM-dd HH:mm:ss} %level %c:%L - %msg%n - UTF-8 - - - - - /home/logs/springboot-jedisCluster.log - - - /home/logs/springboot-jedisCluster.%d{yyyy-MM-dd}.log - - - 10 - - - %d{yyyy-MM-dd HH:mm:ss} %level %c:%L - %msg%n - UTF-8 - - - - - - - - - - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_redis_cluster/src/test/java/com/jun/plugin/redis/impl/JedisCacheManagerTest.java b/jun_springboot_plugin/springboot_redis_cluster/src/test/java/com/jun/plugin/redis/impl/JedisCacheManagerTest.java deleted file mode 100644 index 1cb81ee652..0000000000 --- a/jun_springboot_plugin/springboot_redis_cluster/src/test/java/com/jun/plugin/redis/impl/JedisCacheManagerTest.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.jun.plugin.redis.impl; - -import com.google.common.collect.Maps; -import com.jun.plugin.redis.Application; -import com.jun.plugin.redis.entity.User; -import com.jun.plugin.redis.redis.impl.JedisCacheManager; - -import org.junit.After; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Suite; -import org.springframework.boot.test.SpringApplicationConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import javax.annotation.Resource; - -import java.util.List; -import java.util.Map; - - -/** - * @Title: JedisCacheManagerTest - * @Description: 测试类,测试方法有顺序要求 - * 添加@FixMethodOrder(MethodSorters.NAME_ASCENDING) 以使执行方法按名称顺序执行 - * @Version: V1.0 - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = Application.class) -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class JedisCacheManagerTest { - - private final int expiration = 3600; - - @Resource - private JedisCacheManager jedisCacheManager; - - @Test() - public void testAPutCache() throws Exception { - boolean test = jedisCacheManager.putCache("test", "welocme redis cluster! created by tdcg!", expiration); - assert(test); - } - - @Test - public void testBGetCache() throws Exception { - Object test = jedisCacheManager.getCache("test"); - System.out.println(test); - assert(test.equals("welocme redis cluster! created by tdcg!")); - } - - - @Test - public void testCRemoveCache() throws Exception { - Long test = jedisCacheManager.removeCache("test"); - assert(test == 1L); - } - - @Test - public void testDPutListCache() throws Exception { - User user = new User("1","zhangsan",15); - boolean userList = jedisCacheManager.putListCache("userList", user); - assert(userList); - } - - @Test - public void testEPutListCache1() throws Exception { - User user = new User("2","lisi",18); - boolean userList = jedisCacheManager.putListCache("userList", user, 0); - assert(userList); - } - - @Test - public void testFGetListCache() throws Exception { - List userList = jedisCacheManager.getListCache("userList"); - User u = (User)userList.get(0); - assert (u.getId().equals("2")); - } - - @Test - public void testGGetListCache1() throws Exception { - List userList = jedisCacheManager.getListCache("userList", 0, 2); - User u = (User)userList.get(0); - assert (u.getId().equals("2")); - } - - @Test - public void testHTrimListCache() throws Exception { - boolean userList = jedisCacheManager.trimListCache("userList", 0, 2); - assert(userList); - } - - @Test - public void testIPutMapCache() throws Exception { - Map map = Maps.newHashMap(); - map.put("1",new User("1","zhangsan",15)); - map.put("2",new User("2","lisi",20)); - boolean userMap = jedisCacheManager.putMapCache("userMap", map); - assert (userMap); - } - - @Test - public void testJGetMapValueCache() throws Exception { - User user = (User)jedisCacheManager.getMapValueCache("userMap", "2"); - String id = user.getId(); - assert (id.equals("2")); - } - - @Test - public void testKDeleteMapCache() throws Exception { - boolean userMap = jedisCacheManager.deleteMapCache("userMap", "1"); - assert (userMap); - } - - @Test - public void testL(){ - Long userMap = jedisCacheManager.removeCache("userMap"); - assert(userMap == 1L); - Long userList = jedisCacheManager.removeCache("userList"); - assert(userList == 1L); - } - -} \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_redis_sentinel/Dockerfile b/jun_springboot_plugin/springboot_redis_sentinel/Dockerfile deleted file mode 100644 index 65b1e6193a..0000000000 --- a/jun_springboot_plugin/springboot_redis_sentinel/Dockerfile +++ /dev/null @@ -1,7 +0,0 @@ -FROM openjdk:8-jre-alpine - -ARG JAR_FILE - -COPY target/${JAR_FILE} /app.jar - -ENTRYPOINT ["java", "-jar", "/app.jar"] diff --git a/jun_springboot_plugin/springboot_redis_sentinel/README.md b/jun_springboot_plugin/springboot_redis_sentinel/README.md deleted file mode 100644 index 8f636e884a..0000000000 --- a/jun_springboot_plugin/springboot_redis_sentinel/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# spring-boot-redis-sentinel-example - -对应文章:https://chanjarster.github.io/post/redis-sentinel-spring-boot-example/ \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_redis_sentinel/docker/docker-compose.yml b/jun_springboot_plugin/springboot_redis_sentinel/docker/docker-compose.yml deleted file mode 100644 index b8e2c0b33e..0000000000 --- a/jun_springboot_plugin/springboot_redis_sentinel/docker/docker-compose.yml +++ /dev/null @@ -1,46 +0,0 @@ -version: "3.7" - -services: - - redis-master: - image: bitnami/redis:4.0 - networks: - - my-net - environment: - REDIS_REPLICATION_MODE: master - REDIS_PASSWORD: abc - ports: - - "5000:6379" - - redis-slave: - image: bitnami/redis:4.0 - networks: - - my-net - environment: - REDIS_REPLICATION_MODE: slave - REDIS_MASTER_HOST: redis-master - REDIS_MASTER_PASSWORD: abc - REDIS_PASSWORD: abc - ports: - - "5001:6379" - - redis-sentinel: - image: bitnami/redis-sentinel:4.0 - networks: - - my-net - environment: - REDIS_MASTER_HOST: redis-master - REDIS_MASTER_PASSWORD: abc - REDIS_MASTER_SET: springboot - REDIS_SENTINEL_QUORUM: 1 - ports: - - "26379:26379" - - spring-boot: - image: chanjarster/spring-boot-redis-sentinel-example:0.1 - networks: - - my-net - -networks: - my-net: - driver: overlay diff --git a/jun_springboot_plugin/springboot_redis_sentinel/pom.xml b/jun_springboot_plugin/springboot_redis_sentinel/pom.xml deleted file mode 100644 index 6f7218d299..0000000000 --- a/jun_springboot_plugin/springboot_redis_sentinel/pom.xml +++ /dev/null @@ -1,59 +0,0 @@ - - - 4.0.0 - - - org.springframework.boot - spring-boot-starter-parent - 2.1.4.RELEASE - - - - io.github.wujun728 - springboot_redis_sentinel - 1.0 - jar - - - - - org.springframework.boot - spring-boot-starter-data-redis-reactive - - - - - 1.8 - 1.4.8 - ${java.version} - ${java.version} - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - - - diff --git a/jun_springboot_plugin/springboot_redis_sentinel/src/main/java/hello/Application.java b/jun_springboot_plugin/springboot_redis_sentinel/src/main/java/hello/Application.java deleted file mode 100644 index 7f99eebc95..0000000000 --- a/jun_springboot_plugin/springboot_redis_sentinel/src/main/java/hello/Application.java +++ /dev/null @@ -1,37 +0,0 @@ -package hello; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.data.redis.core.ReactiveRedisOperations; - -import java.util.concurrent.TimeUnit; - -@SpringBootApplication -public class Application { - - private static final Logger LOGGER = LoggerFactory.getLogger(Application.class); - - @Autowired - private ReactiveRedisOperations redisOperations; - - public static void main(String[] args) throws InterruptedException { - ConfigurableApplicationContext context = SpringApplication.run(Application.class, args); - Application bean = context.getBean(Application.class); - bean.run(); - - } - - private void run() throws InterruptedException { - while (true) { - TimeUnit.SECONDS.sleep(3); - redisOperations.opsForValue() - .increment("foo") - .subscribe(num -> LOGGER.info("INCR foo: " + num)); - } - } - -} diff --git a/jun_springboot_plugin/springboot_redis_sentinel/src/main/java/hello/RedisConfiguration.java b/jun_springboot_plugin/springboot_redis_sentinel/src/main/java/hello/RedisConfiguration.java deleted file mode 100644 index a41b8592d7..0000000000 --- a/jun_springboot_plugin/springboot_redis_sentinel/src/main/java/hello/RedisConfiguration.java +++ /dev/null @@ -1,24 +0,0 @@ -package hello; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory; -import org.springframework.data.redis.core.ReactiveRedisOperations; -import org.springframework.data.redis.core.ReactiveRedisTemplate; -import org.springframework.data.redis.serializer.RedisSerializationContext; -import org.springframework.data.redis.serializer.StringRedisSerializer; - -@Configuration -public class RedisConfiguration { - @Bean - ReactiveRedisOperations redisOperations(ReactiveRedisConnectionFactory factory) { - - RedisSerializationContext.RedisSerializationContextBuilder builder = - RedisSerializationContext.newSerializationContext(new StringRedisSerializer()); - - RedisSerializationContext context = builder.value(new StringRedisSerializer()).build(); - - return new ReactiveRedisTemplate<>(factory, context); - } - -} diff --git a/jun_springboot_plugin/springboot_redis_sentinel/src/main/resources/application.yaml b/jun_springboot_plugin/springboot_redis_sentinel/src/main/resources/application.yaml deleted file mode 100644 index cb0cc5efe5..0000000000 --- a/jun_springboot_plugin/springboot_redis_sentinel/src/main/resources/application.yaml +++ /dev/null @@ -1,10 +0,0 @@ -spring: - redis: -# host: redis-master -# port: 6379 - password: abc - sentinel: - master: springboot - nodes: - - redis-sentinel:26379 - diff --git a/jun_springboot_plugin/springboot_redislock/LICENSE b/jun_springboot_plugin/springboot_redislock/LICENSE deleted file mode 100644 index ef356ce291..0000000000 --- a/jun_springboot_plugin/springboot_redislock/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ -Apache License -Version 2.0, January 2004 -http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - -"License" shall mean the terms and conditions for use, reproduction, and -distribution as defined by Sections 1 through 9 of this document. - -"Licensor" shall mean the copyright owner or entity authorized by the copyright -owner that is granting the License. - -"Legal Entity" shall mean the union of the acting entity and all other entities -that control, are controlled by, or are under common control with that entity. -For the purposes of this definition, "control" means (i) the power, direct or -indirect, to cause the direction or management of such entity, whether by -contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the -outstanding shares, or (iii) beneficial ownership of such entity. - -"You" (or "Your") shall mean an individual or Legal Entity exercising -permissions granted by this License. - -"Source" form shall mean the preferred form for making modifications, including -but not limited to software source code, documentation source, and configuration -files. - -"Object" form shall mean any form resulting from mechanical transformation or -translation of a Source form, including but not limited to compiled object code, -generated documentation, and conversions to other media types. - -"Work" shall mean the work of authorship, whether in Source or Object form, made -available under the License, as indicated by a copyright notice that is included -in or attached to the work (an example is provided in the Appendix below). - -"Derivative Works" shall mean any work, whether in Source or Object form, that -is based on (or derived from) the Work and for which the editorial revisions, -annotations, elaborations, or other modifications represent, as a whole, an -original work of authorship. For the purposes of this License, Derivative Works -shall not include works that remain separable from, or merely link (or bind by -name) to the interfaces of, the Work and Derivative Works thereof. - -"Contribution" shall mean any work of authorship, including the original version -of the Work and any modifications or additions to that Work or Derivative Works -thereof, that is intentionally submitted to Licensor for inclusion in the Work -by the copyright owner or by an individual or Legal Entity authorized to submit -on behalf of the copyright owner. For the purposes of this definition, -"submitted" means any form of electronic, verbal, or written communication sent -to the Licensor or its representatives, including but not limited to -communication on electronic mailing lists, source code control systems, and -issue tracking systems that are managed by, or on behalf of, the Licensor for -the purpose of discussing and improving the Work, but excluding communication -that is conspicuously marked or otherwise designated in writing by the copyright -owner as "Not a Contribution." - -"Contributor" shall mean Licensor and any individual or Legal Entity on behalf -of whom a Contribution has been received by Licensor and subsequently -incorporated within the Work. - -2. Grant of Copyright License. - -Subject to the terms and conditions of this License, each Contributor hereby -grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, -irrevocable copyright license to reproduce, prepare Derivative Works of, -publicly display, publicly perform, sublicense, and distribute the Work and such -Derivative Works in Source or Object form. - -3. Grant of Patent License. - -Subject to the terms and conditions of this License, each Contributor hereby -grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, -irrevocable (except as stated in this section) patent license to make, have -made, use, offer to sell, sell, import, and otherwise transfer the Work, where -such license applies only to those patent claims licensable by such Contributor -that are necessarily infringed by their Contribution(s) alone or by combination -of their Contribution(s) with the Work to which such Contribution(s) was -submitted. If You institute patent litigation against any entity (including a -cross-claim or counterclaim in a lawsuit) alleging that the Work or a -Contribution incorporated within the Work constitutes direct or contributory -patent infringement, then any patent licenses granted to You under this License -for that Work shall terminate as of the date such litigation is filed. - -4. Redistribution. - -You may reproduce and distribute copies of the Work or Derivative Works thereof -in any medium, with or without modifications, and in Source or Object form, -provided that You meet the following conditions: - -You must give any other recipients of the Work or Derivative Works a copy of -this License; and -You must cause any modified files to carry prominent notices stating that You -changed the files; and -You must retain, in the Source form of any Derivative Works that You distribute, -all copyright, patent, trademark, and attribution notices from the Source form -of the Work, excluding those notices that do not pertain to any part of the -Derivative Works; and -If the Work includes a "NOTICE" text file as part of its distribution, then any -Derivative Works that You distribute must include a readable copy of the -attribution notices contained within such NOTICE file, excluding those notices -that do not pertain to any part of the Derivative Works, in at least one of the -following places: within a NOTICE text file distributed as part of the -Derivative Works; within the Source form or documentation, if provided along -with the Derivative Works; or, within a display generated by the Derivative -Works, if and wherever such third-party notices normally appear. The contents of -the NOTICE file are for informational purposes only and do not modify the -License. You may add Your own attribution notices within Derivative Works that -You distribute, alongside or as an addendum to the NOTICE text from the Work, -provided that such additional attribution notices cannot be construed as -modifying the License. -You may add Your own copyright statement to Your modifications and may provide -additional or different license terms and conditions for use, reproduction, or -distribution of Your modifications, or for any such Derivative Works as a whole, -provided Your use, reproduction, and distribution of the Work otherwise complies -with the conditions stated in this License. - -5. Submission of Contributions. - -Unless You explicitly state otherwise, any Contribution intentionally submitted -for inclusion in the Work by You to the Licensor shall be under the terms and -conditions of this License, without any additional terms or conditions. -Notwithstanding the above, nothing herein shall supersede or modify the terms of -any separate license agreement you may have executed with Licensor regarding -such Contributions. - -6. Trademarks. - -This License does not grant permission to use the trade names, trademarks, -service marks, or product names of the Licensor, except as required for -reasonable and customary use in describing the origin of the Work and -reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. - -Unless required by applicable law or agreed to in writing, Licensor provides the -Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, -including, without limitation, any warranties or conditions of TITLE, -NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are -solely responsible for determining the appropriateness of using or -redistributing the Work and assume any risks associated with Your exercise of -permissions under this License. - -8. Limitation of Liability. - -In no event and under no legal theory, whether in tort (including negligence), -contract, or otherwise, unless required by applicable law (such as deliberate -and grossly negligent acts) or agreed to in writing, shall any Contributor be -liable to You for damages, including any direct, indirect, special, incidental, -or consequential damages of any character arising as a result of this License or -out of the use or inability to use the Work (including but not limited to -damages for loss of goodwill, work stoppage, computer failure or malfunction, or -any and all other commercial damages or losses), even if such Contributor has -been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. - -While redistributing the Work or Derivative Works thereof, You may choose to -offer, and charge a fee for, acceptance of support, warranty, indemnity, or -other liability obligations and/or rights consistent with this License. However, -in accepting such obligations, You may act only on Your own behalf and on Your -sole responsibility, not on behalf of any other Contributor, and only if You -agree to indemnify, defend, and hold each Contributor harmless for any liability -incurred by, or claims asserted against, such Contributor by reason of your -accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work - -To apply the Apache License to your work, attach the following boilerplate -notice, with the fields enclosed by brackets "{}" replaced with your own -identifying information. (Don't include the brackets!) The text should be -enclosed in the appropriate comment syntax for the file format. We also -recommend that a file or class name and description of purpose be included on -the same "printed page" as the copyright notice for easier identification within -third-party archives. - - Copyright 2017 fightingman - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_redislock/README.md b/jun_springboot_plugin/springboot_redislock/README.md deleted file mode 100644 index dae7e3378d..0000000000 --- a/jun_springboot_plugin/springboot_redislock/README.md +++ /dev/null @@ -1,28 +0,0 @@ -# springboot-redislock - -最轻量级的redis分布式锁实现,实现只使用不到300行代码,只需依赖spring-data-redis,也可自行扩展Jedis。 -如需使用springboot 自动装配, 切换到1.x版本即可 - -## 快速上手 -实现锁的思想参考可重入锁,该分布式锁支持重入机制。 - -## 加锁模式 - -- **RedisLock.lock**:直到加锁成功。 -- **RedisLock.tryLock**:尝试加锁。 - -## 准备工作 - -- **引入spring-data-redis依赖**: 可以在pom中直接引入,这边不多做叙述。 - -## 使用优点 -加锁在一个原子操作中完成,具有redis锁失效,以及本地解锁。 -会有人有疑问这样和setNx 加上 失效时间有何区别(下面简称普通方式),下面进行对比。 - -1.redislock 支持锁重入,使用方式与ReentrantLock 类似。 -2.普通方式无法解决当前锁在分布式情况下被另外的客户端解锁的可能。 - - -## 存在缺点 -客户端1在Redis一个主节点获得了一个锁。主节点挂了,而主从节点的写同步还没完成(异步复制)。 -从节点被提升为主节点,客户端2就有可能获得和1相同的锁。 \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_redislock/pom.xml b/jun_springboot_plugin/springboot_redislock/pom.xml deleted file mode 100644 index 972aa991b7..0000000000 --- a/jun_springboot_plugin/springboot_redislock/pom.xml +++ /dev/null @@ -1,82 +0,0 @@ - - - 4.0.0 - - io.github.wujun728 - springboot_redislock - 1.0 - jar - - - UTF-8 - UTF-8 - 1.8 - 2.9.0 - 2.8.10 - 4.12 - - - - - org.springframework.data - spring-data-redis - 2.0.7.RELEASE - compile - - - redis.clients - jedis - ${jedis} - test - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - test - - - junit - junit - ${junit.version} - test - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.7.0 - - ${java.version} - ${java.version} - - - - org.apache.maven.plugins - maven-javadoc-plugin - - - org.apache.maven.plugins - maven-source-plugin - 2.4 - - true - - - - compile - - jar - - - - - - - - - diff --git a/jun_springboot_plugin/springboot_redislock/src/main/java/com/redis/exception/RedisLockException.java b/jun_springboot_plugin/springboot_redislock/src/main/java/com/redis/exception/RedisLockException.java deleted file mode 100644 index 04629d02e7..0000000000 --- a/jun_springboot_plugin/springboot_redislock/src/main/java/com/redis/exception/RedisLockException.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.redis.exception; - -/** - * @author - * @version V1.0 - * @Description - * @date 2018-01-29 16:24 - **/ -public class RedisLockException extends Exception{ - public RedisLockException(String message) { - super(message); - } - - public RedisLockException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/jun_springboot_plugin/springboot_redislock/src/main/java/com/redis/lock/RedisLock.java b/jun_springboot_plugin/springboot_redislock/src/main/java/com/redis/lock/RedisLock.java deleted file mode 100644 index 0c7b709e3a..0000000000 --- a/jun_springboot_plugin/springboot_redislock/src/main/java/com/redis/lock/RedisLock.java +++ /dev/null @@ -1,132 +0,0 @@ -package com.redis.lock; - -import com.redis.exception.RedisLockException; -import com.redis.lock.api.RLock; -import com.redis.lock.api.RedisCommand; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.data.redis.core.RedisTemplate; - -import java.util.Random; -import java.util.UUID; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.LockSupport; - -/** - * @author zzm - * @version V1.0 - * @date 2017-09-26 14:18 - **/ -public class RedisLock implements RLock { - private static final Logger logger = LoggerFactory.getLogger(RedisLock.class); - private Thread thread; - private String key; - private UUID id = UUID.randomUUID(); - private Random random = new Random(); - private int unlockRetry; - private RedisTemplate redisTemplate; - //static final long spinForTimeoutThreshold = 1000L; - - public static RedisLock create(String key, RedisTemplate redisTemplate) { - return create(key, redisTemplate, 1); - } - - /** - * @param key 当前服务的别名 - * @param unlockRetry 解锁重试次数 - * @return - */ - public static RedisLock create(String key, RedisTemplate redisTemplate, int unlockRetry) { - return new RedisLock(key, redisTemplate, unlockRetry); - } - - private RedisLock(String key, RedisTemplate redisTemplate, int unlockRetry) { - this.key = key; - this.redisTemplate = redisTemplate; - this.unlockRetry = unlockRetry; - } - - /** - * 加锁 - * - * @param expire redis key timeout - * @param timeUnit the time unit of the timeout argument - * @throws InterruptedException - */ - @Override - public void lock(long expire, TimeUnit timeUnit) throws InterruptedException { - if (expire <= 0L) throw new IllegalArgumentException("expire time least gt zero"); - String field = getLockName(Thread.currentThread().getId()); - boolean result; - for (; ; ) { - result = RedisCommand.lock(redisTemplate, key, field, timeUnit.toMillis(expire)); - if (result) { - thread = Thread.currentThread(); - return; - } else { - Thread.sleep(random.nextInt(10)); - } - } - } - - @Override - public boolean tryLock(long expire, TimeUnit timeUnit) { - String field = getLockName(Thread.currentThread().getId()); - boolean result = RedisCommand.lock(redisTemplate, key, field, timeUnit.toMillis(expire)); - if (result) { - thread = Thread.currentThread(); - return true; - } - return false; - } - - @Override - public boolean tryLock(long timeout, long expire, TimeUnit timeUnit) throws InterruptedException { - if (expire <= 0L) throw new IllegalArgumentException("expire time least gt zero"); - if (timeout <= 0L) throw new IllegalArgumentException("timeout time least gt zero"); - final long deadline = System.nanoTime() + timeUnit.toNanos(timeout); - String field = getLockName(Thread.currentThread().getId()); - boolean result; - for (; ; ) { - result = RedisCommand.lock(redisTemplate, key, field, timeUnit.toMillis(expire)); - if (result) { - thread = Thread.currentThread(); - return true; - } else { - long remaining = deadline - System.nanoTime(); - if (remaining <= 0L) - return false; - LockSupport.parkNanos(remaining); - } - } - } - - @Override - public boolean isHeldByCurrentThread() { - return thread == Thread.currentThread(); - } - - @Override - public boolean isLocked() { - return RedisCommand.isLocked(redisTemplate, key, getLockName(Thread.currentThread().getId())); - } - - @Override - public void unlock() { - if (thread != Thread.currentThread()) throw new IllegalMonitorStateException(); - String field = getLockName(Thread.currentThread().getId()); - for (int i = 0; i <= unlockRetry; i++) { - try { - RedisCommand.unlock(redisTemplate, key, field); - break; - } catch (Exception e) { - logger.error("当前线程解锁异常,线程ID:{},error:{}", Thread.currentThread().getId(), e.getMessage()); - } - if (unlockRetry == i) logger.warn("当前线程解锁异常,线程ID:{}", Thread.currentThread().getId()); - } - } - - String getLockName(long threadId) { - return this.id + ":" + threadId; - } -} diff --git a/jun_springboot_plugin/springboot_redislock/src/main/java/com/redis/lock/api/RLock.java b/jun_springboot_plugin/springboot_redislock/src/main/java/com/redis/lock/api/RLock.java deleted file mode 100644 index 90b51fd7c7..0000000000 --- a/jun_springboot_plugin/springboot_redislock/src/main/java/com/redis/lock/api/RLock.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.redis.lock.api; - -import com.redis.exception.RedisLockException; - -import java.util.concurrent.TimeUnit; - -/** - * @author zzm - * @version V1.0 - * @date 2017-09-26 10:45 - **/ -public interface RLock { - /** - * acquires the lock. - * - * @param expire redis key timeout - * @param timeUnit the time unit of the timeout argument - */ - void lock(long expire, TimeUnit timeUnit) throws InterruptedException, RedisLockException; - - /** - * acquires the lock if lock is free - * - * @param expire redis key timeout - * @param timeUnit the time unit of the timeout argument - * @return - */ - boolean tryLock(long expire, TimeUnit timeUnit) throws RedisLockException; - - /** - * try to Acquires the lock - * - * @param timeout the time to wait for the lock - * @param expire redis key timeout - * @param timeUnit the time unit of the timeout argument - * @return - */ - boolean tryLock(long timeout, long expire, TimeUnit timeUnit) throws InterruptedException, RedisLockException; - - /** - * check if current thread is owner - * - * @return - */ - boolean isHeldByCurrentThread(); - - /** - * if any thread holds this lock - * - * @return - */ - boolean isLocked() throws RedisLockException; - - void unlock() throws RedisLockException; -} diff --git a/jun_springboot_plugin/springboot_redislock/src/main/java/com/redis/lock/api/RedisCommand.java b/jun_springboot_plugin/springboot_redislock/src/main/java/com/redis/lock/api/RedisCommand.java deleted file mode 100644 index 55a00b57d2..0000000000 --- a/jun_springboot_plugin/springboot_redislock/src/main/java/com/redis/lock/api/RedisCommand.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.redis.lock.api; - -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.core.script.DefaultRedisScript; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author zzm - * @version V1.0 - * @date 2017-09-26 14:38 - **/ -public class RedisCommand { - - public static boolean lock(RedisTemplate redisTemplate, String key, String id, long expire) { - DefaultRedisScript script = new DefaultRedisScript<>(); - script.setScriptText("if (redis.call('exists', KEYS[1]) == 0) then redis.call('hset', KEYS[1],ARGV[1], 1); " + - "redis.call('pexpire', KEYS[1], ARGV[2]); return nil; end; " + - "if (redis.call('hexists', KEYS[1], ARGV[1]) == 1) then redis.call('hincrby', KEYS[1], ARGV[1], 1); " + - "redis.call('pexpire', KEYS[1], ARGV[2]); return nil; end; return redis.call('pttl', KEYS[1]);"); - script.setResultType(String.class); - List list = new ArrayList<>(); - list.add(key); - String result = redisTemplate.execute(script, list, id, expire); - //result 为null时,加锁成功 - return result == null; - } - - public static void unlock(RedisTemplate redisTemplate, String key, String id) { - DefaultRedisScript script = new DefaultRedisScript<>(); - script.setScriptText("if (redis.call('exists', KEYS[1]) == 0) then return 0; end; " + - "if (redis.call('hexists', KEYS[1], ARGV[1]) == 0) then return 0; end; " + - "local counter = redis.call('hincrby', KEYS[1], ARGV[1], -1); " + - "if (counter > 0) then return 1; " + - "else " + - "redis.call('del', KEYS[1]); return 1; end;"); - script.setResultType(Long.class); - List list = new ArrayList<>(); - list.add(key); - redisTemplate.execute(script, list, id); - } - - public static boolean isLocked(RedisTemplate redisTemplate, String key, String id) { - DefaultRedisScript script = new DefaultRedisScript<>(); - script.setScriptText("if (redis.call('hexists', KEYS[1], ARGV[1]) == 0) then return 0; end; " + - "return 1;"); - script.setResultType(Long.class); - List list = new ArrayList<>(); - list.add(key); - Long result = redisTemplate.execute(script, list, id); - return result == 1L; - } -} diff --git a/jun_springboot_plugin/springboot_redislock/src/test/java/com/redis/LockTest.java b/jun_springboot_plugin/springboot_redislock/src/test/java/com/redis/LockTest.java deleted file mode 100644 index 0a48aa1b98..0000000000 --- a/jun_springboot_plugin/springboot_redislock/src/test/java/com/redis/LockTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.redis; - -import com.fasterxml.jackson.annotation.JsonAutoDetect; -import com.fasterxml.jackson.annotation.PropertyAccessor; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.redis.lock.RedisLock; -import org.junit.Before; -import org.junit.Test; -import org.springframework.data.redis.connection.RedisConnectionFactory; -import org.springframework.data.redis.connection.RedisPassword; -import org.springframework.data.redis.connection.RedisStandaloneConfiguration; -import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; -import org.springframework.data.redis.serializer.StringRedisSerializer; - -import java.util.concurrent.TimeUnit; - -/** - * @ClassName LockTest - * @Description 测试类 - * @Author zzm - * @Date 2019/7/5 9:33 - * @Version 1.0 - */ -public class LockTest { - RedisTemplate template; - - @Before - public void redis() { - RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(); - redisStandaloneConfiguration.setHostName("120.27.213.73"); - redisStandaloneConfiguration.setPort(6379); - redisStandaloneConfiguration.setDatabase(15); - RedisPassword redisPassword = RedisPassword.of("frgrgrgskl34gkk"); - redisStandaloneConfiguration.setPassword(redisPassword); - RedisConnectionFactory factory = new JedisConnectionFactory(redisStandaloneConfiguration); - template = new RedisTemplate<>(); - template.setConnectionFactory(factory); - Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); - ObjectMapper om = new ObjectMapper(); - om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); - om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); - jackson2JsonRedisSerializer.setObjectMapper(om); - template.setKeySerializer(new StringRedisSerializer()); - template.setValueSerializer(jackson2JsonRedisSerializer); - template.setHashValueSerializer(jackson2JsonRedisSerializer); - template.afterPropertiesSet(); - } - - @Test - public void lock() { - RedisLock redisLock = RedisLock.create("test", template); - try { - boolean result = redisLock.tryLock(1000, TimeUnit.SECONDS); - redisLock.unlock(); - } catch (Exception e) { - e.printStackTrace(); - } - - } -} diff --git a/jun_springboot_plugin/springboot_resttemplate/.gitignore b/jun_springboot_plugin/springboot_resttemplate/.gitignore deleted file mode 100644 index 1e3c5bbc80..0000000000 --- a/jun_springboot_plugin/springboot_resttemplate/.gitignore +++ /dev/null @@ -1,14 +0,0 @@ -# 此为注释– 将被Git 忽略 -# /结尾表示是目录,忽略目录和目录下的所有件 -# /开头表示根目录,否则是.gitignore的相对目录 -# !开头表示反选 -.idea/ -target/ -*.iml -*.ipr -*.iws -*.log -.svn/ -.project -rebel.xml -.rebel-remote.xml.* diff --git a/jun_springboot_plugin/springboot_resttemplate/README.md b/jun_springboot_plugin/springboot_resttemplate/README.md deleted file mode 100644 index 80d3308484..0000000000 --- a/jun_springboot_plugin/springboot_resttemplate/README.md +++ /dev/null @@ -1,13 +0,0 @@ -## 使用RestTemplate - -使用RestTemplate访问RESTful API接口 - -## 测试用例 - -`com.xncoding.pos.ApplicationTests.java` - -## 许可证 - -Copyright (c) 2018 Xiong Neng - -基于 MIT 协议发布: diff --git a/jun_springboot_plugin/springboot_resttemplate/pom.xml b/jun_springboot_plugin/springboot_resttemplate/pom.xml deleted file mode 100644 index 21d2d5babd..0000000000 --- a/jun_springboot_plugin/springboot_resttemplate/pom.xml +++ /dev/null @@ -1,112 +0,0 @@ - - - 4.0.0 - - io.github.wujun728 - springboot_resttemplate - 1.0 - jar - - 使用RestTemplate访问RESTful API接口 - - - org.springframework.boot - spring-boot-starter-parent - 2.5.14 - - - - UTF-8 - UTF-8 - 1.8 - - - - - - org.springframework.boot - spring-boot-configuration-processor - true - - - org.springframework.boot - spring-boot-starter-aop - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - org.springframework.boot - spring-boot-starter-jetty - - - org.apache.httpcomponents - httpclient - 4.5.3 - - - org.springframework.boot - spring-boot-starter-test - test - - - org.hamcrest - hamcrest-core - 1.3 - test - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.6.1 - - - 1.8 - 1.8 - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.20 - - true - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - - - src/main/resources - - - src/main/java - - **/*.xml - - - - - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_resttemplate/run.sh b/jun_springboot_plugin/springboot_resttemplate/run.sh deleted file mode 100644 index 955efb1f86..0000000000 --- a/jun_springboot_plugin/springboot_resttemplate/run.sh +++ /dev/null @@ -1,72 +0,0 @@ -#!/bin/bash -# 项目自动更新脚本 -# 先clone相应的分支下来: -# git clone ssh://git@120.24.173.142:7999/xxx.git -# 远程调试启动: -# nohup java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005 -Xms512m -Xmx1024m -jar -Dspring.profiles.active=${profile} ${jarfile} >/dev/null 2>&1 & - -function start { - profile="$1" - echo "启动环境profile=${profile}" - jarfile=$(ls target/*.jar) - if [[ "$?" == "0" ]]; then - stop $profile $jarfile - fi - branch=$(git branch |awk '{print $2}') - git pull origin ${branch} - echo "更新完代码开始重新打包" - mvn clean && mvn clean && mvn package -DskipTests=true - if [[ "$?" != "0" ]]; then - echo "编译出错,退出!" - exit 1 - fi - echo "nohup java -Xms512m -Xmx1024m -jar -Dspring.profiles.active=${profile} ${jarfile} >/dev/null 2>&1 &" - nohup java -Xms512m -Xmx1024m -jar -Dspring.profiles.active=${profile} ${jarfile} >/dev/null 2>&1 & - echo "启动应用中,请查看日志文件..." -} - -function stop { - profile="$1" - jarfile="$2" - ps aux | grep "${jarfile}" | grep "spring.profiles.active=${profile}" | grep -v grep > /dev/null - if [[ "$?" == "0" ]]; then - echo "该应用还在跑,我先停了它" - pid=$(ps aux | grep "${jarfile}" | grep "spring.profiles.active=${profile}" | grep -v grep |awk '{print $2}') - if [[ "$pid" != "" ]]; then - kill -9 $pid - fi - echo "停止应用成功..." - fi -} - -if [[ "$1" == "start" ]]; then - if [[ "$#" < 2 ]]; then - echo "请输入正确参数:./epay.sh start {profile}" - exit 1 - fi - profile="$2" - if [[ "$profile" != "dev" && "$profile" != "test" && "$profile" != "show" && "$profile" != "production" ]]; then - echo "参数错误,请输入正确的profile参数,使用方法:" - echo "./epay.sh start {profile} ==> 启动应用,{profile}取值:dev|test|show|production" - exit 1 - fi - start "${profile}" -elif [[ "$1" == "stop" ]]; then - if [[ "$#" < 2 ]]; then - echo "请输入正确参数:./epay.sh stop {profile}" - exit 1 - fi - profile="$2" - if [[ "$profile" != "dev" && "$profile" != "test" && "$profile" != "show" && "$profile" != "production" ]]; then - echo "参数错误,请输入正确的profile参数,使用方法:" - echo "./epay.sh stop {profile} ==> 停止应用,{profile}取值:dev|test|show|production" - exit 1 - fi - jarfile=$(ls target/*.jar) - stop $profile $jarfile -else - echo "参数错误,使用方法:{}参数是必填的,[]参数可选" - echo "./epay.sh start {profile} ==> 启动应用,{profile}取值:dev|test|show|production" - echo "./epay.sh stop {profile} ==> 停止应用,{profile}取值:dev|test|show|production" - exit 1 -fi diff --git a/jun_springboot_plugin/springboot_resttemplate/src/main/java/com/xncoding/pos/Application.java b/jun_springboot_plugin/springboot_resttemplate/src/main/java/com/xncoding/pos/Application.java deleted file mode 100644 index adc4c48d75..0000000000 --- a/jun_springboot_plugin/springboot_resttemplate/src/main/java/com/xncoding/pos/Application.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.xncoding.pos; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class Application { - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} diff --git a/jun_springboot_plugin/springboot_resttemplate/src/main/java/com/xncoding/pos/config/HttpClientConfig.java b/jun_springboot_plugin/springboot_resttemplate/src/main/java/com/xncoding/pos/config/HttpClientConfig.java deleted file mode 100644 index e4a7320c5b..0000000000 --- a/jun_springboot_plugin/springboot_resttemplate/src/main/java/com/xncoding/pos/config/HttpClientConfig.java +++ /dev/null @@ -1,153 +0,0 @@ -package com.xncoding.pos.config; - -import com.xncoding.pos.config.properties.HttpClientProperties; -import org.apache.http.HeaderElement; -import org.apache.http.HeaderElementIterator; -import org.apache.http.HttpResponse; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.config.Registry; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.conn.ConnectionKeepAliveStrategy; -import org.apache.http.conn.socket.ConnectionSocketFactory; -import org.apache.http.conn.socket.PlainConnectionSocketFactory; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.conn.ssl.TrustStrategy; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.http.message.BasicHeaderElementIterator; -import org.apache.http.protocol.HTTP; -import org.apache.http.protocol.HttpContext; -import org.apache.http.ssl.SSLContextBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.scheduling.TaskScheduler; -import org.springframework.scheduling.annotation.EnableScheduling; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; - -import javax.annotation.Resource; -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.X509Certificate; -import java.util.concurrent.TimeUnit; - -/** - * - Supports both HTTP and HTTPS - * - Uses a connection pool to re-use connections and save overhead of creating connections. - * - Has a custom connection keep-alive strategy (to apply a default keep-alive if one isn't specified) - * - Starts an idle connection monitor to continuously clean up stale connections. - * - * @author XiongNeng - * @version 1.0 - * @since 2018/7/5 - */ -@Configuration -@EnableScheduling -public class HttpClientConfig { - - private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientConfig.class); - - @Resource - private HttpClientProperties p; - - @Bean - public PoolingHttpClientConnectionManager poolingConnectionManager() { - SSLContextBuilder builder = new SSLContextBuilder(); - try { - builder.loadTrustMaterial(null, new TrustStrategy() { - public boolean isTrusted(X509Certificate[] arg0, String arg1) { - return true; - } - }); - } catch (NoSuchAlgorithmException | KeyStoreException e) { - LOGGER.error("Pooling Connection Manager Initialisation failure because of " + e.getMessage(), e); - } - - SSLConnectionSocketFactory sslsf = null; - try { - sslsf = new SSLConnectionSocketFactory(builder.build()); - } catch (KeyManagementException | NoSuchAlgorithmException e) { - LOGGER.error("Pooling Connection Manager Initialisation failure because of " + e.getMessage(), e); - } - - Registry socketFactoryRegistry = RegistryBuilder - .create() - .register("https", sslsf) - .register("http", new PlainConnectionSocketFactory()) - .build(); - - PoolingHttpClientConnectionManager poolingConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); - poolingConnectionManager.setMaxTotal(p.getMaxTotalConnections()); //最大连接数 - poolingConnectionManager.setDefaultMaxPerRoute(p.getDefaultMaxPerRoute()); //同路由并发数 - return poolingConnectionManager; - } - - @Bean - public ConnectionKeepAliveStrategy connectionKeepAliveStrategy() { - return new ConnectionKeepAliveStrategy() { - @Override - public long getKeepAliveDuration(HttpResponse response, HttpContext httpContext) { - HeaderElementIterator it = new BasicHeaderElementIterator - (response.headerIterator(HTTP.CONN_KEEP_ALIVE)); - while (it.hasNext()) { - HeaderElement he = it.nextElement(); - String param = he.getName(); - String value = he.getValue(); - if (value != null && param.equalsIgnoreCase("timeout")) { - return Long.parseLong(value) * 1000; - } - } - return p.getDefaultKeepAliveTimeMillis(); - } - }; - } - - @Bean - public CloseableHttpClient httpClient() { - RequestConfig requestConfig = RequestConfig.custom() - .setConnectionRequestTimeout(p.getRequestTimeout()) - .setConnectTimeout(p.getConnectTimeout()) - .setSocketTimeout(p.getSocketTimeout()).build(); - - return HttpClients.custom() - .setDefaultRequestConfig(requestConfig) - .setConnectionManager(poolingConnectionManager()) - .setKeepAliveStrategy(connectionKeepAliveStrategy()) - .setRetryHandler(new DefaultHttpRequestRetryHandler(3, true)) // 重试次数 - .build(); - } - - @Bean - public Runnable idleConnectionMonitor(final PoolingHttpClientConnectionManager connectionManager) { - return new Runnable() { - @Override - @Scheduled(fixedDelay = 10000) - public void run() { - try { - if (connectionManager != null) { - LOGGER.trace("run IdleConnectionMonitor - Closing expired and idle connections..."); - connectionManager.closeExpiredConnections(); - connectionManager.closeIdleConnections(p.getCloseIdleConnectionWaitTimeSecs(), TimeUnit.SECONDS); - } else { - LOGGER.trace("run IdleConnectionMonitor - Http Client Connection manager is not initialised"); - } - } catch (Exception e) { - LOGGER.error("run IdleConnectionMonitor - Exception occurred. msg={}, e={}", e.getMessage(), e); - } - } - }; - } - - @Bean - public TaskScheduler taskScheduler() { - ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); - scheduler.setThreadNamePrefix("poolScheduler"); - scheduler.setPoolSize(50); - return scheduler; - } -} diff --git a/jun_springboot_plugin/springboot_resttemplate/src/main/java/com/xncoding/pos/config/RestTemplateConfig.java b/jun_springboot_plugin/springboot_resttemplate/src/main/java/com/xncoding/pos/config/RestTemplateConfig.java deleted file mode 100644 index e07b3d1617..0000000000 --- a/jun_springboot_plugin/springboot_resttemplate/src/main/java/com/xncoding/pos/config/RestTemplateConfig.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.xncoding.pos.config; - -import org.apache.http.impl.client.CloseableHttpClient; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.EnableAspectJAutoProxy; -import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.converter.StringHttpMessageConverter; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; -import org.springframework.web.client.RestTemplate; - -import javax.annotation.Resource; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.List; - -/** - * RestTemplate客户端连接池配置 - * - * @author XiongNeng - * @version 1.0 - * @since 2018/1/24 - */ -@Configuration -@EnableAspectJAutoProxy(proxyTargetClass = true) -public class RestTemplateConfig { - - @Resource - private CloseableHttpClient httpClient; - - @Bean - public RestTemplate restTemplate(MappingJackson2HttpMessageConverter jackson2HttpMessageConverter) { - RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory()); - - List> messageConverters = new ArrayList<>(); - StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("utf-8")); - messageConverters.add(stringHttpMessageConverter); - messageConverters.add(jackson2HttpMessageConverter); - restTemplate.setMessageConverters(messageConverters); - - return restTemplate; - } - - @Bean - public HttpComponentsClientHttpRequestFactory clientHttpRequestFactory() { - HttpComponentsClientHttpRequestFactory rf = new HttpComponentsClientHttpRequestFactory(); - rf.setHttpClient(httpClient); - return rf; - } - -} diff --git a/jun_springboot_plugin/springboot_resttemplate/src/main/java/com/xncoding/pos/config/properties/HttpClientProperties.java b/jun_springboot_plugin/springboot_resttemplate/src/main/java/com/xncoding/pos/config/properties/HttpClientProperties.java deleted file mode 100644 index bc99b99a38..0000000000 --- a/jun_springboot_plugin/springboot_resttemplate/src/main/java/com/xncoding/pos/config/properties/HttpClientProperties.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.xncoding.pos.config.properties; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; - -/** - * HttpClient连接池配置 - * - * @author xiongneng - * @since 2018/7/09 22:31 - */ -@Component -@ConfigurationProperties(prefix = "httpclient") -public class HttpClientProperties { - /** - * 建立连接的超时时间 - */ - private int connectTimeout = 20000; - /** - * 连接不够用的等待时间 - */ - private int requestTimeout = 20000; - /** - * 每次请求等待返回的超时时间 - */ - private int socketTimeout = 30000; - /** - * 每个主机最大连接数 - */ - private int defaultMaxPerRoute = 100; - /** - * 最大连接数 - */ - private int maxTotalConnections = 300; - /** - * 默认连接保持活跃的时间 - */ - private int defaultKeepAliveTimeMillis = 20000; - /** - * 空闲连接生的存时间 - */ - private int closeIdleConnectionWaitTimeSecs = 30; - - public int getConnectTimeout() { - return connectTimeout; - } - - public void setConnectTimeout(int connectTimeout) { - this.connectTimeout = connectTimeout; - } - - public int getRequestTimeout() { - return requestTimeout; - } - - public void setRequestTimeout(int requestTimeout) { - this.requestTimeout = requestTimeout; - } - - public int getSocketTimeout() { - return socketTimeout; - } - - public void setSocketTimeout(int socketTimeout) { - this.socketTimeout = socketTimeout; - } - - public int getDefaultMaxPerRoute() { - return defaultMaxPerRoute; - } - - public void setDefaultMaxPerRoute(int defaultMaxPerRoute) { - this.defaultMaxPerRoute = defaultMaxPerRoute; - } - - public int getMaxTotalConnections() { - return maxTotalConnections; - } - - public void setMaxTotalConnections(int maxTotalConnections) { - this.maxTotalConnections = maxTotalConnections; - } - - public int getDefaultKeepAliveTimeMillis() { - return defaultKeepAliveTimeMillis; - } - - public void setDefaultKeepAliveTimeMillis(int defaultKeepAliveTimeMillis) { - this.defaultKeepAliveTimeMillis = defaultKeepAliveTimeMillis; - } - - public int getCloseIdleConnectionWaitTimeSecs() { - return closeIdleConnectionWaitTimeSecs; - } - - public void setCloseIdleConnectionWaitTimeSecs(int closeIdleConnectionWaitTimeSecs) { - this.closeIdleConnectionWaitTimeSecs = closeIdleConnectionWaitTimeSecs; - } -} diff --git a/jun_springboot_plugin/springboot_resttemplate/src/main/java/com/xncoding/pos/controller/LoginController.java b/jun_springboot_plugin/springboot_resttemplate/src/main/java/com/xncoding/pos/controller/LoginController.java deleted file mode 100644 index 7ec4e60d7c..0000000000 --- a/jun_springboot_plugin/springboot_resttemplate/src/main/java/com/xncoding/pos/controller/LoginController.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.xncoding.pos.controller; - -import com.xncoding.pos.model.LoginParam; -import com.xncoding.pos.model.UnbindParam; -import com.xncoding.pos.model.BaseResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; -import org.springframework.web.bind.annotation.RestController; - -/** - * 登录接口类 - */ -@RestController -public class LoginController { - - private static final Logger _logger = LoggerFactory.getLogger(LoginController.class); - - @PostMapping("/login") - public BaseResponse login(@RequestHeader(name = "Content-Type", defaultValue = "application/json") String contentType, - @RequestBody LoginParam loginParam) { - _logger.info("用户请求登录获取Token"); - String username = loginParam.getUsername(); - String password = loginParam.getPassword(); - return new BaseResponse<>(true, "Login success", username + password); - } - - @PostMapping("/unbind") - public BaseResponse unbind(@RequestHeader(name = "Content-Type", defaultValue = "application/json") String contentType, - @RequestHeader(name = "Authorization", defaultValue = "token") String token, - @RequestBody UnbindParam unbindParam) { - _logger.info("解绑通知接口start"); - String imei = unbindParam.getImei(); - String location = unbindParam.getLocation(); - return new BaseResponse<>(true, "解绑通知发送成功", "unbind"); - } - -} diff --git a/jun_springboot_plugin/springboot_resttemplate/src/main/java/com/xncoding/pos/model/BaseResponse.java b/jun_springboot_plugin/springboot_resttemplate/src/main/java/com/xncoding/pos/model/BaseResponse.java deleted file mode 100644 index b7c3e5e00f..0000000000 --- a/jun_springboot_plugin/springboot_resttemplate/src/main/java/com/xncoding/pos/model/BaseResponse.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.xncoding.pos.model; - -/** - * Controller的基础返回类 - * - * @author XiongNeng - * @version 1.0 - * @since 2018/1/7 - */ -public class BaseResponse { - /** - * 是否成功 - */ - private boolean success; - - /** - * 说明 - */ - private String msg; - - /** - * 返回数据 - */ - private T data; - - public BaseResponse() { - - } - - public BaseResponse(boolean success, String msg, T data) { - this.success = success; - this.msg = msg; - this.data = data; - } - - public boolean isSuccess() { - return success; - } - - public void setSuccess(boolean success) { - this.success = success; - } - - public String getMsg() { - return msg; - } - - public void setMsg(String msg) { - this.msg = msg; - } - - public T getData() { - return data; - } - - public void setData(T data) { - this.data = data; - } - -} diff --git a/jun_springboot_plugin/springboot_resttemplate/src/main/java/com/xncoding/pos/model/LoginParam.java b/jun_springboot_plugin/springboot_resttemplate/src/main/java/com/xncoding/pos/model/LoginParam.java deleted file mode 100644 index 466e8e3cf3..0000000000 --- a/jun_springboot_plugin/springboot_resttemplate/src/main/java/com/xncoding/pos/model/LoginParam.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.xncoding.pos.model; - -/** - * 登录认证接口参数 - * - * @author XiongNeng - * @version 1.0 - * @since 2018/1/9 - */ -public class LoginParam { - /** - * 用户名 - */ - private String username; - /** - * 密码 - */ - private String password; - /** - * Application ID - */ - private String appid; - /** - * IMEI码 - */ - private String imei; - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getAppid() { - return appid; - } - - public void setAppid(String appid) { - this.appid = appid; - } - - public String getImei() { - return imei; - } - - public void setImei(String imei) { - this.imei = imei; - } -} diff --git a/jun_springboot_plugin/springboot_resttemplate/src/main/java/com/xncoding/pos/model/UnbindParam.java b/jun_springboot_plugin/springboot_resttemplate/src/main/java/com/xncoding/pos/model/UnbindParam.java deleted file mode 100644 index c8f5737b0b..0000000000 --- a/jun_springboot_plugin/springboot_resttemplate/src/main/java/com/xncoding/pos/model/UnbindParam.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.xncoding.pos.model; - -/** - * 解绑通知参数 - * - * @author XiongNeng - * @version 1.0 - * @since 2018/1/9 - */ -public class UnbindParam { - /** - * IMEI码 - */ - private String imei; - /** - * 网点 - */ - private String location; - - public String getImei() { - return imei; - } - - public void setImei(String imei) { - this.imei = imei; - } - - public String getLocation() { - return location; - } - - public void setLocation(String location) { - this.location = location; - } -} diff --git a/jun_springboot_plugin/springboot_resttemplate/src/main/resources/application.yml b/jun_springboot_plugin/springboot_resttemplate/src/main/resources/application.yml deleted file mode 100644 index ce23aa9274..0000000000 --- a/jun_springboot_plugin/springboot_resttemplate/src/main/resources/application.yml +++ /dev/null @@ -1,39 +0,0 @@ -########################################################## -################## 所有profile共有的配置 ################# -########################################################## - -################### 项目启动端口 ################### -server.port: 8092 - -################### spring配置 ################### -spring: - profiles: - active: dev - -logging: - level: - org.springframework.web.servlet: ERROR - ---- - -##################################################################### -######################## 开发环境profile ########################## -##################################################################### -spring: - profiles: dev - -httpclient: - connectTimeout: 20000 - requestTimeout: 20000 - socketTimeout: 30000 - defaultMaxPerRoute: 100 - maxTotalConnections: 300 - defaultKeepAliveTimeMillis: 20000 - closeIdleConnectionWaitTimeSecs: 30 - -logging: - level: - ROOT: INFO - com: - xncoding: DEBUG - file: D:/logs/app.log diff --git a/jun_springboot_plugin/springboot_resttemplate/src/test/java/com/xncoding/pos/ApplicationTests.java b/jun_springboot_plugin/springboot_resttemplate/src/test/java/com/xncoding/pos/ApplicationTests.java deleted file mode 100644 index 4941e98277..0000000000 --- a/jun_springboot_plugin/springboot_resttemplate/src/test/java/com/xncoding/pos/ApplicationTests.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.xncoding.pos; - -import com.xncoding.pos.model.LoginParam; -import com.xncoding.pos.model.UnbindParam; -import com.xncoding.pos.model.BaseResponse; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.http.MediaType; -import org.springframework.http.RequestEntity; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.client.RestTemplate; - -import java.net.URI; -import java.net.URISyntaxException; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; - -/** - * 测试任务 - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -public class ApplicationTests { - private static final Logger logger = LoggerFactory.getLogger(ApplicationTests.class); - /** - * @LocalServerPort 提供了 @Value("${local.server.port}") 的代替 - */ - @LocalServerPort - private int port; - @Autowired - private RestTemplate restTemplate; - - @Test - public void testRestTemplate() { - LoginParam param = new LoginParam(); - param.setUsername("admin"); - param.setPassword("12345678"); - String loginUrl = String.format("http://localhost:%d/login", port); - BaseResponse r = restTemplate.postForObject(loginUrl, param, BaseResponse.class); - assertThat(r.isSuccess(), is(true)); - - String token = (String) r.getData(); - UnbindParam unbindParam = new UnbindParam(); - unbindParam.setImei("imei"); - unbindParam.setLocation("location"); - // 设置HTTP Header信息 - String unbindUrl = String.format("http://localhost:%d/unbind", port); - URI uri; - try { - uri = new URI(unbindUrl); - } catch (URISyntaxException e) { - logger.error("URI构建失败", e); - throw new RuntimeException("URI构建失败"); - } - RequestEntity requestEntity = RequestEntity - .post(uri) - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON) - .header("Authorization", token) - .body(unbindParam); - ResponseEntity responseEntity = restTemplate.exchange(requestEntity, BaseResponse.class); - BaseResponse r2 = responseEntity.getBody(); - assertThat(r2.isSuccess(), is(true)); - assertThat(r2.getData(), is("unbind")); - } -} diff --git a/jun_springboot_plugin/springboot_schedule/.gitignore b/jun_springboot_plugin/springboot_schedule/.gitignore deleted file mode 100644 index 1e3c5bbc80..0000000000 --- a/jun_springboot_plugin/springboot_schedule/.gitignore +++ /dev/null @@ -1,14 +0,0 @@ -# 此为注释– 将被Git 忽略 -# /结尾表示是目录,忽略目录和目录下的所有件 -# /开头表示根目录,否则是.gitignore的相对目录 -# !开头表示反选 -.idea/ -target/ -*.iml -*.ipr -*.iws -*.log -.svn/ -.project -rebel.xml -.rebel-remote.xml.* diff --git a/jun_springboot_plugin/springboot_schedule/README.md b/jun_springboot_plugin/springboot_schedule/README.md deleted file mode 100644 index 16e45ec690..0000000000 --- a/jun_springboot_plugin/springboot_schedule/README.md +++ /dev/null @@ -1,17 +0,0 @@ -## 定时任务 - -定时任务非常简单,只需要写个配置类,然后定义定时任务类,使用注解定义某个方法定期执行 - -``` java -@Scheduled(cron = "0 26 19 * * ?") -public void checkState1() { - logger.info(">>>>> xxx检查开始...."); - logger.info(">>>>> xxx传检查完成...."); -} -``` - -## 许可证 - -Copyright (c) 2018 Xiong Neng - -基于 MIT 协议发布: diff --git a/jun_springboot_plugin/springboot_schedule/pom.xml b/jun_springboot_plugin/springboot_schedule/pom.xml deleted file mode 100644 index 5e3c182a2e..0000000000 --- a/jun_springboot_plugin/springboot_schedule/pom.xml +++ /dev/null @@ -1,75 +0,0 @@ - - - 4.0.0 - - io.github.wujun728 - springboot_schedule - 1.0 - jar - - 定时任务 - - - org.springframework.boot - spring-boot-starter-parent - 2.5.14 - - - - - UTF-8 - UTF-8 - 1.8 - - - - - org.springframework.boot - spring-boot-starter - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.6.1 - - - 1.8 - 1.8 - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.20 - - true - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - - - src/main/resources - - - src/main/java - - **/*.xml - - - - - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_schedule/run.sh b/jun_springboot_plugin/springboot_schedule/run.sh deleted file mode 100644 index 955efb1f86..0000000000 --- a/jun_springboot_plugin/springboot_schedule/run.sh +++ /dev/null @@ -1,72 +0,0 @@ -#!/bin/bash -# 项目自动更新脚本 -# 先clone相应的分支下来: -# git clone ssh://git@120.24.173.142:7999/xxx.git -# 远程调试启动: -# nohup java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005 -Xms512m -Xmx1024m -jar -Dspring.profiles.active=${profile} ${jarfile} >/dev/null 2>&1 & - -function start { - profile="$1" - echo "启动环境profile=${profile}" - jarfile=$(ls target/*.jar) - if [[ "$?" == "0" ]]; then - stop $profile $jarfile - fi - branch=$(git branch |awk '{print $2}') - git pull origin ${branch} - echo "更新完代码开始重新打包" - mvn clean && mvn clean && mvn package -DskipTests=true - if [[ "$?" != "0" ]]; then - echo "编译出错,退出!" - exit 1 - fi - echo "nohup java -Xms512m -Xmx1024m -jar -Dspring.profiles.active=${profile} ${jarfile} >/dev/null 2>&1 &" - nohup java -Xms512m -Xmx1024m -jar -Dspring.profiles.active=${profile} ${jarfile} >/dev/null 2>&1 & - echo "启动应用中,请查看日志文件..." -} - -function stop { - profile="$1" - jarfile="$2" - ps aux | grep "${jarfile}" | grep "spring.profiles.active=${profile}" | grep -v grep > /dev/null - if [[ "$?" == "0" ]]; then - echo "该应用还在跑,我先停了它" - pid=$(ps aux | grep "${jarfile}" | grep "spring.profiles.active=${profile}" | grep -v grep |awk '{print $2}') - if [[ "$pid" != "" ]]; then - kill -9 $pid - fi - echo "停止应用成功..." - fi -} - -if [[ "$1" == "start" ]]; then - if [[ "$#" < 2 ]]; then - echo "请输入正确参数:./epay.sh start {profile}" - exit 1 - fi - profile="$2" - if [[ "$profile" != "dev" && "$profile" != "test" && "$profile" != "show" && "$profile" != "production" ]]; then - echo "参数错误,请输入正确的profile参数,使用方法:" - echo "./epay.sh start {profile} ==> 启动应用,{profile}取值:dev|test|show|production" - exit 1 - fi - start "${profile}" -elif [[ "$1" == "stop" ]]; then - if [[ "$#" < 2 ]]; then - echo "请输入正确参数:./epay.sh stop {profile}" - exit 1 - fi - profile="$2" - if [[ "$profile" != "dev" && "$profile" != "test" && "$profile" != "show" && "$profile" != "production" ]]; then - echo "参数错误,请输入正确的profile参数,使用方法:" - echo "./epay.sh stop {profile} ==> 停止应用,{profile}取值:dev|test|show|production" - exit 1 - fi - jarfile=$(ls target/*.jar) - stop $profile $jarfile -else - echo "参数错误,使用方法:{}参数是必填的,[]参数可选" - echo "./epay.sh start {profile} ==> 启动应用,{profile}取值:dev|test|show|production" - echo "./epay.sh stop {profile} ==> 停止应用,{profile}取值:dev|test|show|production" - exit 1 -fi diff --git a/jun_springboot_plugin/springboot_schedule/src/main/java/com/xncoding/pos/Application.java b/jun_springboot_plugin/springboot_schedule/src/main/java/com/xncoding/pos/Application.java deleted file mode 100644 index adc4c48d75..0000000000 --- a/jun_springboot_plugin/springboot_schedule/src/main/java/com/xncoding/pos/Application.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.xncoding.pos; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class Application { - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} diff --git a/jun_springboot_plugin/springboot_schedule/src/main/java/com/xncoding/pos/config/ScheduleConfig.java b/jun_springboot_plugin/springboot_schedule/src/main/java/com/xncoding/pos/config/ScheduleConfig.java deleted file mode 100644 index 8c4316ea0c..0000000000 --- a/jun_springboot_plugin/springboot_schedule/src/main/java/com/xncoding/pos/config/ScheduleConfig.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.xncoding.pos.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.scheduling.annotation.EnableScheduling; -import org.springframework.scheduling.annotation.SchedulingConfigurer; -import org.springframework.scheduling.config.ScheduledTaskRegistrar; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * ScheduleConfig - * - * @author XiongNeng - * @version 1.0 - * @since 2017/9/13 - */ -@Configuration -@EnableScheduling -public class ScheduleConfig implements SchedulingConfigurer { - @Override - public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { - taskRegistrar.setScheduler(taskExecutor()); - } - - @Bean(destroyMethod="shutdown") - public ExecutorService taskExecutor() { - return Executors.newScheduledThreadPool(5); - } -} diff --git a/jun_springboot_plugin/springboot_schedule/src/main/java/com/xncoding/pos/jobs/HeartbeatJob.java b/jun_springboot_plugin/springboot_schedule/src/main/java/com/xncoding/pos/jobs/HeartbeatJob.java deleted file mode 100644 index e64063137e..0000000000 --- a/jun_springboot_plugin/springboot_schedule/src/main/java/com/xncoding/pos/jobs/HeartbeatJob.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.xncoding.pos.jobs; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Component; - -/** - * 定时任务 - * - * 第一位,表示秒,取值0-59 - * 第二位,表示分,取值0-59 - * 第三位,表示小时,取值0-23 - * 第四位,日期天/日,取值1-31 - * 第五位,日期月份,取值1-12 - * 第六位,星期,取值1-7,1表示星期天,2表示星期一 - * 第七位,年份,可以留空,取值1970-2099 - * - * @author XiongNeng - * @version 1.0 - * @since 2017/9/27 - */ -@Component -public class HeartbeatJob { - private static final Logger logger = LoggerFactory.getLogger(HeartbeatJob.class); - - /** - * 检查状态1 - */ - @Scheduled(cron = "0 30 12 * * ?") - public void checkState1() { - logger.info(">>>>> cron中午12:30上传检查开始...."); - logger.info(">>>>> cron中午12:30上传检查完成...."); - } - - /** - * 检查状态2 - */ - @Scheduled(cron = "0 0 18 * * ?") - public void checkState2() { - logger.info(">>>>> cron晚上18:00上传检查开始...."); - logger.info(">>>>> cron晚上18:00上传检查完成...."); - } - - -} diff --git a/jun_springboot_plugin/springboot_schedule/src/main/java/com/xncoding/pos/jobs/Scheduler2Task.java b/jun_springboot_plugin/springboot_schedule/src/main/java/com/xncoding/pos/jobs/Scheduler2Task.java deleted file mode 100644 index d167b9b8d3..0000000000 --- a/jun_springboot_plugin/springboot_schedule/src/main/java/com/xncoding/pos/jobs/Scheduler2Task.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.xncoding.pos.jobs; - -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Component; - -import java.text.SimpleDateFormat; -import java.util.Date; - -/** - * Created by summer on 2016/12/1. - */ - -@Component -public class Scheduler2Task { - - private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); - - @Scheduled(fixedRate = 6000) - public void reportCurrentTime() { - System.out.println("现在时间:" + dateFormat.format(new Date())); - } - -} diff --git a/jun_springboot_plugin/springboot_schedule/src/main/java/com/xncoding/pos/jobs/SchedulerTask.java b/jun_springboot_plugin/springboot_schedule/src/main/java/com/xncoding/pos/jobs/SchedulerTask.java deleted file mode 100644 index 572f6ca1ba..0000000000 --- a/jun_springboot_plugin/springboot_schedule/src/main/java/com/xncoding/pos/jobs/SchedulerTask.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.xncoding.pos.jobs; - -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Component; - -/** - * Created by summer on 2016/12/1. - */ - -@Component -public class SchedulerTask { - - private int count=0; - - @Scheduled(cron="*/6 * * * * ?") - private void process(){ - System.out.println("this is scheduler task runing "+(count++)); - } - -} diff --git a/jun_springboot_plugin/springboot_schedule/src/main/resources/application.yml b/jun_springboot_plugin/springboot_schedule/src/main/resources/application.yml deleted file mode 100644 index 79e29cad50..0000000000 --- a/jun_springboot_plugin/springboot_schedule/src/main/resources/application.yml +++ /dev/null @@ -1,24 +0,0 @@ -########################################################## -################## 所有profile共有的配置 ################# -########################################################## - -################### spring配置 ################### -spring: - profiles: - active: dev - ---- - -##################################################################### -######################## 开发环境profile ########################## -##################################################################### -spring: - profiles: dev - -logging: - level: - ROOT: INFO - com: - xncoding: DEBUG - file: D:/logs/app.log - diff --git a/jun_springboot_plugin/springboot_schedule/src/main/resources/banner.txt b/jun_springboot_plugin/springboot_schedule/src/main/resources/banner.txt deleted file mode 100644 index 2e697237e8..0000000000 --- a/jun_springboot_plugin/springboot_schedule/src/main/resources/banner.txt +++ /dev/null @@ -1,139 +0,0 @@ - :: :.:..... : ....: ..: ..: : : :..: ..:...:.... :..........:.... .:.: : :.::..:.:......:.:..: : :...:..:::..::.:::::::..::.:::::.::::::::::::::::::::::::::::::::::::::::::;:::::: -.::.:.:::...: ::.:.:.:.:::.::::.::.:.:.:::.:.:.::::.::::.:::.::.:.:.:::::::::::::::.::::::::::::::::::::.:::.:::::::::::::::::::::::;:;:;;;:;;:;:i::::;;,;,,;::;,i;:i;,;:;,;;,;;i:;: -::.::: :::::::::::::::::.:::::::::::::::.:::::::::::::.::::::::::::::::::::::::::::::::::::::::::::::::::::::::::;;:;;:::::;::::::ii,;,ii,,;,,:ii:ii,;::i:ii:i;,;;,i:,;,:i:::;,,;,,: -::::.::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::;:::;;:::::::::::::::::;::::::;::::::::;:::;::::::i:,;:::;,;:;i:;,,;i;i:i,;,;,:,;,::,;;,;,:,;:;,,;i:;,;::i:,;,,;:;, -:;;:;;:,i:,;:;::i:i:;:,;,,ii,,:;;,:i,;,,;,,i:,:::;:i::,;::,;,:,::i;,;::;:::::,:;:,::::,::i;:,::::::,:,:,,:ii:i::i:,;,;,:::;:;:;i:i;ii:i;,i;,;:::,:,::,::i:i:,::;,i,;ii;,,::;,:::i:i: -;ii:,:,;;,;,,:,:;,:,:,::ii;,;:i::;::,:::::::;::,;:,;,:i:,;:::;:i::::::::::::::;,;,;;:::;:::::,::;:::::;,:i::i:;,::::;::::::,::,:i:iiiiiiiiii::i:::;:;:::::::;::i:,;i,i:i:i:,;::::::: -,;;:;,;::;:::;:i::::::,;::i:i;::::,::;,::::,:::::;:i::;,:::;iifffjiii;i:::::i:,;;:,,:::,::::::::::::::::;,;;,;:;:,;,:;,::::;i:;;:iiiiii,i:,;::::;,:,:::;,;,:,:;,;;ii;,;i;::;::,:i::: -,i:i::::::::::::::::,::i:i;;ii::;::,::::::::,::::;:i:;,;ijffLffffGGGDDLGfii;;:,;:i::::::;::::::::::::;::;:i;,;:;::;::::::,;:i:;;i:i:iii,;ii:,;::::,:;::::,:;::;,;;,;ii:i;,:;:;:::::: -:ii:;;:,:;,:::::,;,:::::iiiii;,;,:;:i::::::::;::;;,;ii;ifGLGGLGDGGGDDEDGffijiiii;::;:::::::::::::::::,:;:,::::,:,:::,;:::::,::,i:i,ii;;i,;;,;:,::;::::::;:::,;:,;i:i:,;,,;:,:,:;:::: -i;;,:::::::::::::::::::i::i:ii:,::::::::::;:::,;:iii;ifLDGfDDDGDDEEEKEEDEGDDGLfi:,;::::::,::::::::::::::;:;:i:::;:;::::::::;i:;,;:i:ii,;i:::,,::::,;::::,::::::;,:i:i;,;:,::::::,::: -i:,;,,:::,:::::,::,::,:,;;,;i:i::;,:::::::,::,;,;i;ifLDGGDEKEDEEEKKDEDKEKEEDDDGfi;,::::::::::::::::::::::::::::::::::::::::::,:;:i;;i:;,;,,;::;:;:::::::::::;::,;i:;::;,,;:;;:i:;::: -i:,;::::::::::::;::::,:::;:i::;,,:,:::::::;:,;iiifGGGDGDEEDKEKEEWW#WKKEWKEW#KKEGj;i;,::::::::::::::::::::.::..::.::...: ::::::,;:;:,;i:i:;::;::;:;:::::::::::::,;;:;:::i,:;:,::::::: -:;;,::,:;:,::::::,::::,;,:::;,:;;:;:::::::::;,jjfGDGDGGGEDEEKKK#KWK#E#WWW#KWEWEDffii:;::::::.:::::::::::...;;:ijiii:::: :::::;:,:i,:;::;:::,:,::::::::::::,::::::::,::;::::::::::::: -,::;,::::::::::::::::::::::i:;:::,:,::::.:;,iifffffDGGfLDEKKWK#WKEEWWWEWKKWWWWKKDGGi;,::::::::::::::.:.:;:;;;jLfGGfji;:::::.:::;::;;,:::;,;::;::;:::::::::;::::;:;:;::::::;:::i::::: -::;::::::::::.:::::::::::::;:::::::,::::::i,ififLDGDDDDEKWEWWK##KWEWWWWKKKWKWWKWWKDGfi;::::::..:::::;,;ijLGjjjtjLGDDGDGGGi::::::::;:::::::::;::;,::::.:::::::::;::,:::;::::::::::::: -:;:::::::::::.:::::::::::;:::,:;::;::::.::ijtGDGDDDDDEEKWWWKWWWWE##KK##KKWKWK#KWK#EGfii:::: :::::::::iiifLGGGGjjtGGEDGEGDj;;:::;:::;::::;::::::,;:::::::::::::::::;::::::::;:,;::::: -:::;:::::::.::.:::::::::;:::::::::,::::::ifDGDKEKEDELDKKEKEK#WW#K#WWWWWEWWKK#KK#KKKGGi;::::::.:.::.:;ijfGGGEEDGGtjGGKDDEDG;;:.::::::::::::::::::::::::::::::::::::::;::::::::::::::: -:::::::::::::::::::::::::::::::::::::::;ifDEDDD#GDEDEWWKEW#W#E#WWWKKWKWWKK#EWK#KEKGjii;:::::::: ::iiLGDGKKKKKDKKEjjGEDKEEjjGfj;:::::::::;:;:::::::::.:::::::::::;:;:::.::::::::::::: -::::::::::::::::::::::::::;::::::::::::iiGKKDGEWEKEWWK#K#KWK#WW#KW#WK#WWKWKWK#KKKDj,;:::::... :::i;jGGDEEKDKKKKKKGjjGEKKDjGGGjf::::;::::::::::::::.::.::::::.::.:.::.::::::::::::::: -:::::::::.::: ::::::::::;,::;::::::::,;ifLEKEEDEK#KKKWE#WW##KWWK##KK#KWWKKKWEGKGGi:;::::.::.:::::ifGGGEKKKEKDKWKEGLjGD#EKGGGGGG;:.::::::::::::::::::::..:::::::::::::::::::::::::::: -:::.::: :::.:::::::::::,::::::::::::i;ifGDEKKEEKKK#KK#KWWWKWWW##EWW#E#WEWEWEEDGjLi::::::::.: .:;ijjLGEGDGGEKGEKK#KGGGKKWEDEKDGGi;::::::::::::::::.:..:..:..::.::.:.:::::::::::::.::. -:::::.::::.::::::.:::::::::::.:.::::iifGGDK#EWEKEWK#E#WKWWWKWKWWWKKKK#WEWDGGGLit;;:...:::. :.:;ijLjjjjLGGEEKDEEDGEKDGGEDKKKEEGGi;::: :...:: :::. : ::.::..:::..: .::.::..:::::..:.:. -::::::.::.::: :.::::::::::::..:.: ::iiGGDEEWKKKKEE#K#KWWWWW#K#EW#KWW#KWEKEGfLf;;;;;: ::: ::::ijLGjtjLLGGKEEEEEDKEDKDEGGGKKEKKDGj;;:;;::::..:....:.: ...:..:....:::...:..:.....::.::. -:::.:.:::.: ::.:::::.::.::..:: :::::iLGDGDKWKE#KK#WWEKWWWWWKWWWEWWWWKKKKKDDfjj;;,,..:...:.::;jGjjjjLGKEEGEKDDEGDDGGGGfLjGKKEEKGjj;;,;;: :.:.:::...:. :....::.. : ..:::::..:::: :::: -.:..:..:: : ..:::: :..:: :....: .::ijGDKDGEWEW#EW#EWKWWWWWWKWWWEWKK#KWKKEDGGi;;;,,::.:.: ::;i;t;LEGGDGEGKEGGGLjiji;j;;;;tjGGEKDGjt;.:.:: :: ::.:: : :.......:..:: :.:.:...:.:...::. -..: ::..: :..::...: :.: :: :::..:::ifLGEKEKEK##WWK##KKWWWKKKWWK#K#KKKWKWKEKGti;:.:.,.:. : ;ij;;jGGGLGEGGDEGLjj;t;;;;;;;;;;tjGEDGjt;:.. ;:..........::..:.......: :... :..: ... :... -..... : : :.. :.: .: .: :.. ::::;ifGEEKKE#KKWWWEWK#K#K#K##EWKEWKWWWW#EEEDGi;;;.:.:..:: :;ijitGGLLGEGEKGGGjj;;;;;;,;.;;:;;;LGKEGt;.: :. :..:: ::. :. :... .... :.....: : :::.....:: - :......:. ..: ...::..: ::.....:::;iDEEWEKKKKKKK#WK#KWKW#K##EWWWKW#EKEKWKKEDGj;;;.::.,: ;;ii;jjGGLGGDKGGjLjji;;;,::,:.;:,::,;tjGGLL;................:... : .:: ::....:..: :: :..... -. .::..: : . : :..: :..:: :..:.:::iGDKKKK#KK##E##WWWW#KWW#WK#EKWWKKKEEWEKGEGj;,.:...,..::;;jjLGLGLGEGLGLjjtjt;;;;;.;;.::,:.,;iGDGG;;.............. :..: ::.. :.. : : .: :. : :..: -.::..: :..:... ...:: :: :: : : ::,iGDEEKEK#EWKW#WW#KWK#KWWWWWKEWKKEWDDDKKKDGGi;.:.:,.;::;;itLGLfLGGGGGjjjt;i;;;.;,,::,:...::,;LGGGL;:: .. : ....... : : :....: :: .. :.....: :: :: - :..::.::.: . :: : :.....: :: :::ijDGDWEKWWK#KWWW#K#WW#WW#WWWKK#KWKEKKKDKEEGGj;.:...:.,:;;;jLjGLLGKELjLjjt;t;;;,,;:.:.:..:..:.iGGGLj:.:..... : : ::..... ... :.:......: : : : : -.. : :..: :. ::. :.......: :: :::;fGDDDEWKWW##WW#KWWWWWWWWWWE#KWKEWEKEKGDEDGGj;:.:..:.,;i;jjGGLLDKEGLjjjtjt;;;,,;,:..:.:.:.:.:;;LGt;j:.: .. :....:: :: : : . : . : :.: :.: :.: .: -. : .... .: : : :.....:......:::ijfDEEWKK#K##K#WW#KWWEWEWWWWWKWEWKEKGGDGEGGjj;.:..:.,;jEitiGGLjGKELjjtijii;;;,;..;:.:.::.:.:..;jGjtt.:: :....: : :.: :.: ::...... ::......:.:.:. -: : .........: : : : : :...::itGDDKEW#KWKW#KWWWEE##WWKWEWEK#KKEKKDGKGGGGf;,:..:..;jGK;jLGLGGEKEjLjtt;j;;;;,,,::::.;..:...::.jGLj;j ::: :: :: : : ......:: :: :.:....:.: :.:.:. -: ...................: :....:...:;fGDDKEKWEW##W##KWWWW#WW#K#KWK#KKKDKGfGGGGLj;::..:.;ijjjjGGGGDKKEGjLjjLjjji;;;;,;.::.:..:....:.;fGLijj.:: ::.::.... :: : : : :..:.. : ::..:..: - ....: :.............:: ...:..: :ijGDKEWWWWWEK#KK#WWWKWE#KKWWK#KWDEGGGGfjGji;...:..;;;;;iLjGLGKKKGLLjLLGGLLLj;;:;:.;:..::.::....:jDLijj.:............. :..: :: :: :.......:: :: ::. -: : ..: .. : : :: :: ::. :: :: ;fGDEDEWWWKWWWWWWW#WK##WKWWK#KKEDKEDGfGfjL;;.:.,:.:;...;GLLGDDKEGLGLGGLjfjfLj;;;;,..::.:.::.:...jKLt;j;.................. .. : .........: .....:: - :...: :: .. : : ....: .. ... :: ;fLGDDEKWWKKWWW#K#E#KKWKWKWK#EKEDEGDGGGjji..:.::;.:.:..;LGLGKKELLjjjttt;;;;;;;;;,;..:.:;;;i;::..;KGj;;j; : : .. :: .. : . .. . .. :: . .. ..: - .. . : .. :: : .. : ....: . :;ffDGEK#K#K#WW##WWWW#KWWWK#KWWEKGDDGfGfjj;.:...:..:..:;jGGGEWKGLfLjtjtttij;.;;;;;.:.::;;;iji;:..;KGf;;;; .. : ... .... .: . ..: : .. : :: :... : -. .. ... .... . . .... . :: :. :LGDDDEK#WE##WW#K#KK#EWWW#KKWKEKDDGDjGfij;.::...::..:;j;iLEDKKGjLjjjtjjLLGLj.;;;;;..:.,:;;;t;j::.EGj;;;;: .: .. . : .. .. : . :. ....... . - . . . .: ... . . :. . : .. . ..;jGDGDKKKKKWK#WKW#EK#WKK#KWWWKEDDGGGjGjjtj,:...:.;..:;;;;;GKKGLLtjjtjjGGEEKD;.,;;;.:.;;,;,:::;;.:DGL;;;;...... : .. : .: : : : ... : .. :..... - : . : . :.. : . ... : . .. ...iGDGDEKKWE##EWWK#K#KWWKKKWWWEDDDGGGjGfjji;::.:.....::,..:,DKLjtjttLLGELiiEGG;;i;;.:,;;;;jjj;: :.GGj;;;;... .. : .. : : .. .... : : : .. :....: -. : . .... :.. ... . . : . . ;GEGDDEE#KWW#KWKK#WE##K#K#KKDKGEGGGGjjjjj;:.,..:.:....;,:,;EGLjtjjjjLLLLjLGK;;;;,: ;;;jGDWKG;. .Gjt:,:;: .: ... : .. : : . .... :: ......... - . ... : . . : .. .. .. : . : :GGDEDEWKKWWWEWWKKWWEWWEWKKKDGGGGGjjGjjji;:;:::....::.,:.;;jGLtjttjtjtj;;;;j;;t;;..;;;jiifDW;:.:Ei; :.; : : .. .. :.........:... .. : :... : .: - .. ... . .. : : . .... . .: ..GDGEEKKK#KKKKWWWW#KWWWKEWKKGLL...;jjfjji;,;::.:.. ...:;:;;,;Gtjtj;j;;;;;;;;;jtt;:.:.;;itjjLL; .L::..;... : .. :: .. : : ..........: : : ....: -. . . ..: .... . ........ .... :....LKLKDKKKWWWWWEWWWK#W#WKKKEELL;:;..,;jjjt;;.;.:.:.:....:;;;;iLjtjiti;;;;,,.;;tji;;:.:;t;;;.;;;..j:. .:. : : ..... : .. ..... : .. : :: :...: - .. . ... .. : .. :. :: .... ...: :.iGGDEKKWEWWWKWWKWWK#EWKWEKGLt,tt...;;jjj;;:;;:... :. .;;,;;jGjttti;;,,,;.;;ijtt;...:;;;;;..:. .j: :; .... . ...: ...... : .. : :: :: .::..: :: - . : . . : .. :: ..: :: :: .. : ....;jGGDKDKKKWKKK#KWWWWK#KKGLLtt,tj,..:;;;;;;:,,:,:.. . ..;,;LKLttjt;t,.:,;:,;ttjt;:...:,.:.:.: . j: .:. : : .... : : :: .. ......: : :: :..:: -. . ....: : : . : :.. : ....: :: :.:;fGDKDEWWKWEEWK#KWWWWKEGGjf;,ti:,...;;;;;;;:,:..:..:..,;jKELjttt;;;;,,,.;;jtj;;::....:,,:...:.j:..:.. . .. : .. :: : ........: : ::....: : : - :....... :...: :.. :...... ....::iGEEEKEKKWKWKWWK#KEWWELjLj;,,,j;.:.,;;;:,::;:.:......;;KKGLtttt;,;,.;,;:;jjj;;.....:.::... . f;..: ::.........: :: .......: :.:.:: :.......:: -. .... .....: .. : : : : ..... : .::GGDKEDWWEWK#EWWWK#KWGLjjf;;.tLL. ..;;;;;:;:,:...:. .,jEWGLtttt;;;,;:..;tjLj;;:.:...,:.:..: .ii.:.......... : : : :: :: :::.::.::.....::.. : -....... : . ..... ..: ..:..... .: .:.iGGKKKKKKK#EW##K#WWKGLjtLt,.;ff; .:.;;;;;;:;;:..:.:.:,LEELtjti;;,,::.;ttjtj;,:...;,:::.: . .i;;:::.::.:...:....::: : :::..:.::::..: :..:: :.: -..: :: :: ... :... : :...:..:::..:...;DGEKKEWWWKWWWWWKKKKLjjLfj;.,;t;.:.;,,;,:;.,:,,...::,:jDELtttt;;;:,.;;Ljtjj;;..:.;;.... :.. ;;;::.:.....:..:.:.: :: : ::..::::::::.:.::.::... -.: :::...................:.:..: : :..:.:jGDEEWWKKK#K##W#WWKLjjjtjt....;..;.;;;;;;.,,..,.:...,;GELtjtt;,;,,:;;jjLLLj;,;..;,,:..: : :;:;:::::::.:.:..:.: :.::::..::.::.::.:.::.::::.:: -::::::.:.:.......:.: :.:.:::::::.:...:::.;GDDEKEWKWW#WW#KKKLLjtjtj;....:,,;;;;;;;.,,:.......;;LKLtjtt;;,,;;it;tiij;.:;: ,;;,..:.: .:.:;.::::...::.:....::.:.:::...: : :..: ::.::...: -::::::.:: :::: ...:.:.:.. :::.:..:.:.....:LGEDWWWWW#KWKWKEEjjtjjjLt;.. .;;;;;,:,::::..::..:.:jKELttt;;;;:;;ttt;t;;:,:...:;;;.:.. .:::..:: ::.::.:.:::...: .: :.:..:.:.::.:..:::.:.. -.::.:.: ::: : : :.:.:.:..::...::: :.:..:.:LGDDE#WWW##WWWKKGLjjtttjLt;:.:,;,;;;;,,;:::.:..:.:,LGEGjttt;;;;t;tj;ttt;;...:.:;;,:.... :...;..::: : :: : ...::.:: :....:....:.: :.: :... -....: : .: :.:...:..: : :::....:: ::..:: :jDWKWWWEWWWWKKDDGjtjttit;;;;;;tt;t;;;,;:,.:.. :..:,;LGLttjt;;,;tLLDDDGGDLff;..::;;:..:. ..: .: :..::: ... ..:: : ...: ::........ :: :.: .. -.....:.:: :.: :...:: ::.. : :..:: : ..::..fKWWKWWWKEKKKEDGGjji;;t;;;,;;;;ttt;;;;.;....:..:,,;tGLLtit;;;.;tGELLLGLfffLjt,.;;,..:. ::...;... : :: :. :.: ::: :............: : ..... - :: :....: :.: ..: :.....: :: ::.........iEWWWKWWKKKEKEGGGj;jt;i;,,:.;tijt;;;;;;.;.:..:...,:tGLjtti;;,;;;LGLjt;;;t;ffft;;,;:.... :: :: : ....: : .: .... : ............ :: :: :: -: : : :.........: ::...................;GKWEKEKEKEGGGGGjjti;;;;,,.;;;tttjt;;;,:...:...,:;;;LLtjttt;;.;;;DGL,;:...:tfLf;;:..: .. : :...............:: : : ...........: :: :: :: - :: ::.. :: : : :: :: :: : : : :: :...:iDKGGGGGGGLGjjjjti;i;,,;:;:,;jjttti;;,,,..:..,:,,;:.;jtttt;;,;;itLDGLfft,,,Lft;;,.... : :. : .. . : : :...: . .. : : :: :: : : : : -........: .....: : : : ...: :: : : : :LGGGGGGGLLjjjtj;jt;;,;,,.,;;tjtjt;;;;;:,::..::,:,:..;;;i;;;;;;ttjfGDLffjjjjt,;,;:.:.: .. : : .. :: :: .... : : : : :: .. : : .. :...: - :: :: ::.....: : :: :: :: : .......: :: :: ;i;ijjjjjjjj;jtt;i;;,,::,.;;;jjiit;;;,,:..,.,.:;,...:;tiit;;;;;itjfGGLffjti..;;..... .. :. ...: . : .. .. : .. .........: .. : ..... - :: :: :: : : : :...: ... :: :: : : : . ::.:,:i::::::;t;;;,,;;::,,:;itjitit;;;;,:,:,,:,; :..:,;ti;;t;;;;;,;;;,;....;.:..... :: : .. :: :: :.. :: ... : : .. :.. ..... .... -: .......... :: : : ..........: .. : .. :..::i;,:;::::.:;;;;,;:::..:.,;;ttt;;;;,;;;:,,,,,, : ...:;t;jiit;;;;;;;,;...:.:..: .: .. :.. ..: :........... . : .. ....... : :: :: :: - :: :.......... : :: :: :... .. : :: :: :itfGDGffjii;::.:. ::;;.;:,:.,::,;;tittt;;;;;;,,,:;.. : ...;;ti;t;;;,,:.::.:: .:.:.... ...: :: : ..: .. .... ..... :: :: :... : : : : - .: ...... :: :: ....... .. .. : :...:ifLDDDWDWWEWKWKWEDf;. : .;:::.,.,;,;;;;t;;;;;;;;;;. . : ..:.:.;;tit;;;:,:..... :.... : : :: : : . : : : :..... :.. : .. . : ...: :.. .. - :.. .. : :... ..... ....... .. .. .. ;tfGGDEEEKWK#W#KWWKKEGf:.. :,.:...:::;;;:.. ...: ...... .:. ..:;;itt;;:;.::.::. :...: . .. .. . ........ . :: ..: .. : : :: .. : .... :: - . : ..... .. ... . ..... : .. .. : : iffDDDDDWKKWWKEWWEW#KKKKi...:::,.::;,,:. .. ... .. ..: ...:.:::;;;;jit;;:;.: ...... ..: ..: ... :.. : : :: .... : : .. .....: : : : . . -..: . : . .........: :.. ..... :: ..: :jffLDEDEEKKKK##WWKKEEKKEDL: ..:,:::.::; :: :.. :.. ... . :.:.:,,;;;itj;;;.:.....:: .. :... ... .. : : : : . ..... : ....: : : :: .. .. - . .... ...: . : ... .... . . ....ijLfLGDDDDKKWWWWKWKKKWEKWEEEKD: ..,.:.::. :.. :.:.. .. : :.::.;.;;iititt;;;;:::... :......... : : ..... : : .. : .... :.. : .... : . - .. ... ... : .... : : .. .....: : itjfGDDDEEEKKKWEW#KWWKKWEWEEKDDGi :.::,: .. .... . . : : : .::.::;;tttjttiti;:;..... :.. . : . .. : : : ...... : : :: : :.... ...... -..: : .. : : . :: : . : : ..fLfDDDDEEDKDEEKKKWWWKWWWEWEEEEEEDj..::.;: :: . : . : .. :.:.:.;;;titjtit;;:;:...:.... :....: .... ...: : : . : ... : .. ... ... .... . - ....... . ....: :: . : : . : : tGfDDEWEWEWWW##WW###W###K#KKEEEEDEf:.,: : .. ... .. : ....:.,:,:;;tit;t;,,,.,...... .: .... . : . .: . . . . : ...: . : ... ... . . . - .. :: :: : . . : .... .........: :ifffDDEEWEK#KEW#WK#WWWW#W#WWEKEEEEKf.:. : . : : . .. .. . :,:;;;jttt;;;;,::....:. : : : .. : . ... ... . : ... .. . .. : .. . ..... .. . -........ : .. :. : . ....: ........:ffffGLDDDKKKWK#E##W##W#W####WKWDEEEEf ..: ... :.. .. : ... : ..::.;;;j;;i;;:;::.::.... . ........ : . ... ........ : .... . .. :... . . .. - .. :: : .... ... . .. : :: .:iiffffGDGDDEDKKKK#KK#WWK#KK#KKEW##WKDWDEi.... .... ... ..... : ...:,;;tti;i;;,;.:.,::.:,:. :. : .......: .. :... : ....: : : :: .. : : . -.... : ....: ... .: :.. : .::tifDGLfGDDDGDDWEWKWKWWWWWWK#WK#WEKK##KDEWEi : :.. .. :...: .: ...,;;;;iti;;;;,.;:..:.:::::.. : ::..: : : : ..... : : .........:. :...... ::..:. -..: :... ....... ........... iiiitfEDDDfGDGGDDEEWWWWWWKKWWWK#KKEWEEED#WEDDG: .... :: : ....... : . ,;;;;j;t;t;;,;..:::..:.;....: : ... : .. :: ....::..: : .....: : ....:. : . .. -... :: :: : ......:: :...: :ititifLDGDfLGDfGLDWEWWKKK#EWK#KKKK#KKKKEKDWKEDDf............. : : . :;;;;tt;tt;;;:,..;..::.;.;;.:: .:::..::. :..:.:.....:..:. :.....::..:::...::.:: .. - ::.:: ::... :. :....:...:tDLifjtfDEDGGDDffffDKWEEWEWWEWWEWWEKKWKKEWEKEDEEDG:.: .:::....:::.:.: . .;t;ttt;ttt;;:;..,.:.,.:;;;;;.:. ::..::.:.:::::.::::::::::..:::.::.::::::.:.::.::. -: .: : .:::.:.:: :: :: :iDDfifffGDEDLLDLLffLDKEKKEWEEWEKEKKKWKKWEKWEWWEKDDLL..:: :..::::.:: .: . ;t;itt;tt;t;;,;,,.,,,:,;,;,;;;:: ::::: ::..:::..:::.::.::.:.::::.:.:.:::::::::: -.: :::.::: .:.: ::..:.:;iGDLtfffLDGDfLGLGLffGDKEKEWEEEDEKKKKKKEEWWKK#KKKKEDDLfff;::.::.:.:.::: : .;;ti;ijit;;;,;:.,..,:;;;;;,;;:;::.. :.:::.::.::::::.:::::::::::.:.:::.::::.::.::: -.:.:..::::.::::::.:.::tfGGfftDffLDfDGfffLLfDKEEDEEDKEKKKKKKEWEKWKKEWEWWEWKEKDDLDi::::::.::::: . . .;;;;i;j;;t;;;;..:.::;;;;;;;i;;:.. :.. .:::::::;::::;;:::::;:;:;:::;:;::;;::;: -:.:::::.:.::::.:.:::iitDfGfGfLffGLDDfLGGffDEDKEDEEWKKWEWWEDWEKKKKKKKKKKKKWEEEDDLi::;::::::::. .....:;;t;;titit;,,,;.;,;,;;;;;t;;;::.:..::.::. ::;::;::;i;,:ii;i;i:i:::;;:::;:::;,,; -:::.:::::::.:::.:::iitfDfGDfDDfffDGDLDLLLGKDKEKEEKKKKKKKKKEEKKKK#KWKKEEKKEWEDEDLLi;:;:;:;::: . . .,;;;;j;tt;;;;;;:;::;;;;;;;;;.:;::.:::;;;:::..;,:ii,i,;iiii,iiiii:i:i::i:;i:ii;iii -;iii;;:;;:;::;:iiiijffKffGfLWGfLDGDLLDGDDEEEEDWEKKKKKKK#EKKKWE##WKKKKKKKEKDEDEWEEDDii;i:: : : .: :,;;;;j;t;;t;;:;;;;:;:;,;;;;;;;;:;,:;;;;::::.:.::ii:i,;,;;i:,i::i:i;,;:i:::;,,;ii, -,;,;,,ii;,;,,:iiittttGDtGDfD#LLGLDfDLDGDEEDEDWEWEKKKKKKEEKDKKKKEWW#KKWKEWDKKKWEWWEEEGt: :...:. ;;;;;;jtt;;;:;;;;,;;;;,;;;;;j;:,,:;,;;;;,::.:: :::;:;;;::,;;:i;,;:::,:::;::,:i::; -iiii;;;;:i,;;iG,itiffWLfDLDWEDfLGDDLDDDEKKEEEEEKKKKKKKKKEWEKKKKWKKKKKWWEEKKK#EWEEKDEEDG . ...:.:. :,;;;;t;;;;;,;;;;;;;;,;;;;itj;;;:;;;;;;;::....: ::,;::,;:;::;::::::;:::::;::::;i: -;,,;;,;ii:i:LEttijffDWffDDDWWDGLGDfDGDEEDEEEKEEWEKEWEKKKWEWWEWEE#WWEWEEWEKE#EWEKDEEDEDEi. ...::;:..;;;;t;;;;;;,;;;;;;;;;;;;;tij;;:;;,;i;;;;.:.:. .: ::::;:::::::::;::::::::::::;:::: -:::::::::::jGiittffDKWtLDEWKKDLDLLDLGDDEEDDKKEKEWWEWEKKKWEWWEWKWW#KWKKEKK#KKEWEWDEEDWDKEDj::..: : ;,;t;;;;;;;;;;;;;i;;;;;;;;;j;;,:;;;;;i;;,:..:.: : :::::::::::::::::::::::::::::::: -::::::::::tKjijtffjE#EffDKKKDDGfGLGLDDEKDEDEKKWEWEWEWWEKKKKW#E##KWEWKKEWWEWEKEEEKKEKDEDEED.:::.:.:;;;;:.;;t;;;;;;it;;;;;;i;it;;:;;,;;;;;,;:.:.. . . :::::::::::::::::::.:::::::::.:. -::::::::::D#iftffffWWDfGDKKKEDLDLLLLLDDDEEEWEKKEWWEWEKKKKKKKKW#WWKKKKKEWKEWEKKKKEEEKDEEDED::....:,;;;,:;;t;;t;;i;;;i;;;;;;;;j;;,;,;;;i;;;;;.::... : :::::::::::.:::.:.::::...::.:... -:::.:::::EKfffjfffGWWLjDDEWDEDGfLLGGGDDDEEKKEWWEWWEWEKKEEWEWW#KWWKKKWEWWKWEKKKEKEEDEDKEKDED;..;::.;,,;;;t;;;;;;;;;;;;;;;;;;;;;;;;:;;;i;;,;:.::.. . .:.::::::::::::::::.::.:..::::::. -..:.:.:.jWGfffffjfD#DDfDEKKEEDLDLLGLDDEDEKDEKKWKEEWEWWEWKKKKK#W#EWKWEWWK#WKKEKEEEEEEKDEDEDDt ::.;;,;:;;;;;;;;;;;;;;i;;;;;;;;,;,;:;;;i;;;;,.:.. :.:. :::.:::.:...:..:::.::.::::::..:. -:::.:::.DKfGfffffLEWDDfDEKKEEGfDLDLGDDEEKDKKDWWEWWWWKKWEE#W#WK#WWWWKK##EWWEKKKEKEEEDEKEKDEED:..;:;;,;;;;;;;;;;;;;;;;;;;;;;;,;;;;;;;;;;;;,;:.:.: ....:::: ::::::::::::::::::::::::.: -:::.::::WfDLLffDfGKEDDfDEEWEDGDDDGGLDEDEEKKKEKKEWWEWWEWEEW#E#WEWWWKWWWKKKEKKKEDKKEWDEKDDEEEDG,::,:;,;;;;;:;;,;;;;,;:;;;,;:;,;;;;;i;;;i;;;,:.::. .....::.:..::::.::::::::;::;:;:;:::: -: :::: iELDDfffGfDWDGEfDDEDKEDLDDfDDDEDKEDEDKKKKWE#KWWWW#KK#WE#WW#KK#E#EWWEWKKKKKDEEKDEEDKDED::;:i;;;;,;:;::;;;,;;,;;;:;;;;;;;;;;;;;i;;,:,.:...... .::.:::..:..:::::::;;:;,;i:i,;i;: -:::.:::fGDDDGffLjD#GDEfDDDKEDGDDLDGLEEEDKEDKKKKKKKKKKWEWWK#E#KK#WKW#KWKWEKKKKKKEKKKKEKDDEDDDD.:;GG;;:;;::;::;:;;:;;;;;;,;;;;;i;;i;;j;;;;;::.:: .. ..:.:.:.::::::.:::;;iiii;i;i;;i;i; -.:::...DGDEWLtGffD#LDDfGEEDEDLDDDfDDDEDKDEEKKEEWKKWE#WKKKWEWKK#K#W#K#W#K#WKKEWEWKEDDKDKEEDEDE::jWG;;;;:;,:;;,;;:;;:,;,;;;i;ii;;;;;i;i;;:.:... : : ...:..::..::::::;:iiiiiiiiiiiii;i -:.::..fWDKKKLfDtLKWLKDfDDDDDGLDDDGDDEWEDEKEWEKKKKE#EWWKWKWWKKKW#KEWK#KWW##KKKKKDKDEEEEEDEDDDD::;;it;;:;:;;::;;;;;:;,;;;;;;;;tji;;;iti;;:...: ...... ....: ::......::;;iiitijiiiii;i; -.:::.:GWEKKKDfDiDEWGKKfGDEDDEGDDDGDEKDEKKDKEEWWKKKKWEK#KWWKWWWWW#KWWWKWKKKKKEWEKKEWKKEKEKDDED;:::;;;;:;:::;;;,;:;;;;;;;;;i;;;jji;iti;;:;;::.:.. . ...:...: :.:.:::::iiiiiiii;iiii;i -:...:iKDEW#ELDDiDWEDEKfDDGDEEDDDDDDEEEKEDKKEWEWKWWKKW#EWWWKKWE##KWEWWWWW#WWKKKKKKEDEEDEKDEEDDi.:;;;;:;:;;:;;,;:;;;;;i;;;;;;;tLjj;;;t;;;::.. . : ...:: ::....: :.:.;:i;iiii;ii;;iii; -.....fWLW#WEDDDjDKDKKKfDEDEWDDDEEEKDEEKEDWKKK##EWWKKWW#WWKKKWW#WK#WKWW#KWWWWWEKKKKEKDEDKDEKDE;:;::;:::;:;:;;;:;;;;;;;;;;;,;;jLj;;i;i;;;,.:...: : :.::..: : ....:.::::;iiiii;i;ii;i,; -:..: GWLWWW#DDLfDDLKKKLGDEDEDEDDEDEKKDEWDEWEWKK#K#KWWWK#KKKKWWWEWWK#WKKK#KKEEKKKKDEEKDKEDEEDEi;:;;:;:;:;:;;;;;;;;i;i;;;;;;;;jGji;ti;;;,,:...:. .. .. : :.::......:::;iii;iii;i;i,i; - :..:DEDW#WELEffDDDWKKfDEEDKDGEDDWDKDKEEWEEWE#KKWWK#W#WWWEK#W#WK#KKK#KWEWWEWWKKKKKKEKEDEKDDDEj::;:;:;:;:;;;tLGGGLL;;;;;;:;,;LLLti;t;;;;:.:.. : :...::..: : t,....:::;:i;ii;i;,;i;i;, - :...EEK##WEDDfLDEEW#DfDEEKDGDDDDKDEDKEDKWWWWKKKKE#WEW#EEKEWWW#K#W#KKWKKKKWEWKKKKKEKEEEEEDDEDj;:;:::;,tLEEEEEEKEKEDj;;;:;;;;ELj;i;t;;,:.:... : . .:::....,D,: ...:::;ii,ii;,;,ii;i,: -: ..iWDE#K##EDffGDKKWELDDDEDDDEDKDEKKEEKKEEWWK#WW#KW#WW#WEKW#K#WWWWK#W#WEKKWKK#KKKEEEDEEEDEDEi:;::,;fGEEEEEEEEEEEEEDG;;;;;;;GGjtti;;;;;:.:: : : .... : .,jD..::...:::,;ii:iiii;:iii; - : iEDEWW#WEEDjfDEE#EDfDDEDGDDEDDKEDKEWWEWWEWKKEWK#WWW#WEKW#K#W#W##KK#EWWWWK#WEWWEKEDEDDEWEEGj;::;jLEEEEEEEEDDEEKWEEEf,;,;;;GLjt;;i;;,:.:. . . :.::..,iDL : : :::;ii;i;i:;,iii;;, -::iWWWEE#K#WDLfLEDKK#DGGDDGDEDEDKEEKKKKKWWKK#KWW##WWW#KWKK#W#W#W#KWW#EWKWWKWWE#KKEKDEEDEDEDEDi;,tLLDEEEEEEDEDEDEEKKEEDEf;;;iELjij;;,;;,:.::..: :: : . ;ijG, : :..:::i;,,;ii;i;,;ii; - :W#KWEEW##WKLfGDKKEWDLDDDDEDDEEKDKDKKKWKWKWWWE#KK#W#WWWWWWW#KWWWWWWWWE#WWWWK#K#KKEEDEKEEEKDEffLGEEEEEEEDEDDDDDDEEWKKEEDDf;fDjtiti;;:;.:...:. . ...:iijDi. : . ::::;ii;i;i;i;,i,;i: -:f##DWDWWWWKELfGDWWWEELDELDDEEWEDEKKWWWKWKKWKKWEWK#K##EKWW##K#EW#WEWWWWKK#KWKKWEKEKEEEEKEDEKDLDEEEEEEEKDDDDDDDDDDEEKEEEDDELLGLjt;;;:,::.:.. ..: ....,ijDf.... : :.::;iiiii,ii;;iii; -iEW#DWEEW##KDDfDEKKWKDLDDGDEDWEDKEWE#WKKWEKKKEWW#W#W##WKW#W#KWK#E##W#WW#WWWWWW#WKEDWDKEDWEEDEDDEDEEEDEDEEDDDDDDDDDEKKKKEDEEKLjj;i;;;;::.:..... : ::.jijDj.: :.: :::::i:ii:i;;iiiiii: -EWW#D#EEW#WWDDfDEKKWEDfDDDEDEWDEEKKKK#WKWKKKKKWWW#W#K#KWW#WWE#EWWW#E#W#WKWWWWKKKDEKEEKDDEEDWEDEEEEEEEDDEDDDDDDDDDDEEKKWKEDDWLjt;;;,;:,.:..... :.:.,tijLf. :.......::::;,:;,;,;;;,;;: -K###DWKK#W#EELfDK#KKKGGDEDDEWKKKKEW##WWWWWEKEW#K#WW#WKK##K#E#WKW#WWW#KW#KK#WKKKEKKDEDEEEWDKKDDEEEDEDDDDDDDDDGDDDDDDEEEKKEEDEGLt;;;;;.::... ... .,,iijjDi : ....::::::::i:::;::::;:: -EWW#D#WDWWW#DLLDKWEKKGGDDEDEKWEKKKWKWW#WWEEWEWWWWWWWWWE###WW#KKWWWW#E##K##WWWWEEDEEEDKDEEKKEEGEGEDDEDDDDDDDDDDGDGDDDEWKWKEEDLjt;;;;.,....::.....,t,ijfD,...: :.: .:.:::::::::::::::: -WEW#E#WEW#WWDGLDKKKWDLLDGDEDKWEKK#WW#W##WKEKEWW#KWWWKWWWW#W#WEW#W##K#WW#KW#WWEEEDEEDEEEKKKEEDKEDDDDDDDDDDGDGDDDGDGDDDEEKWWEELft;;,;;:...:....: .i,ijGDD.... .......: .:..:.:::.:.::: -E##WE#EWWWKWDDfD#W#WELDLGEEEKKKEK#W#WW#EWEWEWWWWW#WWKW#WW##WWWWWWWWWWWWW##KEEDKEKKKEEEEK#WWEEWWEDDDDDDGGGDGDDGDDGDDDDEKKEKEWDft;;,:.:.: .... . .i,jfDDf: ....::..: :.... ::...:::... -KE##W#WEW##WDGfDWWWKDLDfDEEEKKEKKWKW#W#WKWEWEWKK##EW#W#K##WW#EK#W##W#WWWWK#WEKEWEKEDEEKWWEEDK##WEDDDDGDDDGDGDDGDGDDDDEEEKWKEEEf;;;::.::.: ... ..iijLDDi: :..: : : ::.:: :.:. : :. -WE#KKWWD#KWEDGLEWWWEKfLDDDKKKKKK#W#WK#KWKKEWWKW#WK#WEW#WWW##WE##K###E##W#KKEEEEKWEWKEWKWWWEE###WKDGGGDGDGDGDDDDGGGDDDDEEKEKKEED;::;:.....:.. ..,iiLLDD;......::..:... ...: : ::: :: -#KK##WWEWWEWDDLEW#KEEfDDEKKKKWE##W#WK#KWKK#KW#WWWE#W##W#W#WW#EWWW##WWWW#KEKEEDEKKWEEWW#WEEDE####WEDGGGGDDGDGDGGDGGDDDDEEEKEWKEEf;::.:. .: . . .iijLDDi.: : ....:..: :: :..: ..:: ::. -###KW#WEW##WDDfKEW#WDLLDKKDKEWWKWW#K#W#K#KKWKKKWW#K#KK###W#W#K#W#KK#W##W#EKDKKEEKKKKK#KWWEDKWWW##WEDDGDGGDGDGGGDGDGDDDDEEKKKKKKD,.;:..: .......tjfGDD,....:: :.....: ....: :.: : .. -#WW#KWWDK#KWDDLD#W#EDfDDKWEWEKK#W#K##K#EWKWKK#KWWKW#KW#W#W###KKWWWW##W##WWEKDEEWKKKW#W#EKDEE###W#WKDGDGGGDGGDGGGDGDGDEEEEEKKEEKDf,,:.:.:. ... ,jjLDDf ::... :.:....:.:.:...:..::.... -#K####WD#E#EDDLEW#WEDfGEWEWEW#K##K#WW#EWKKWEWWWK##W#WW#W#WW#W#K#K###W#WKKEKDKEWK#W##W#WEDEKEW#WKWW#KDDGGDGGGGDDGGDDDDDEEKKEKEKEEEi;.:.:.. ....ijLLDD,.. :....::....:..:....:...: ::. -W#K#WW#EK#WEDDfK#E#WDfDDWWEKKW#KW#K#WW##KWWWKWE#KWWWKK##W##W#WW#W#WWW#KKWKEKKKKKWE##W#KEDEEEKW##WWW#DGDDGDGDGGGGDGGDDDEDKEKEWEEEDL,:.:. : . .,tjfDDD : : :: :: :: : : :....:: :. -######WE#WEKDELEWW#EDfLEWKKKWW#WWWW#W#KKKKE#WKWWKW#W###W#W##WWW#K####KWEKKKKKKW##W##KKKDEKKEKWWWW#WWEDDGGGGGGDGDGDGDDEEEEKEKKEKEEDt.:.:..... tjjfEDD : ... : :.............. ...: -#WWW#E#D#WEDEDLWWWWKDffKKWKK#W#WWWW##K##EWEW#K#K##W#W#W#W#WK#WEK##W#EKWEKWEW#K#WK#WKWKEEEDDEWWKWWWWWWKDDGGGGGDGDGDDDDEEEEEEEEEEEEDD :.:..:.: jjtDDDf. :.... : : :.... : ..... ....: -W###WW#EE#KEDDfEWWKKDfDDKKKWWK#WW#K##W#KKWWWWKKW#WWWKW#####W##W##W#KKKKKEEWWK#E##K##WWDDEDEDEWWEWWWWWKEDDGGGDGDGDGGDDEDEEKKKEEEEEED..:. . . .iijEDDj : .. ... . .. .: . .. . . -#WW###WKWWEDEDLKW#KEDfDEWKWK#W#KW#WWW#EWKKWWWWWKKK#W#W#W#K###W##W#KKKKKKKKWWWWW##W#KWEEEDEDEKKWKWWWWW#KDGDGGGGGGDGDDDDEEEEEEEEEEDEDi. :..::..jjjDDG,. . .. : .. : . :. ..: : : .. -W#K#W##EWWWEDDLKWKKEDfDEEEW#KWK#WW#WK#WKWEWWWWW#WK#WWW###W#K###W###EKKW#WWE#WWWWWWWWEWDDEDDEEWKKWK#KWWWEDGGGDGDGDGDDDEDKEKEEEEKEEDDf,:. . . .tijDDf.. .. .. .. : .. : . . . -#WWWW##EK#KEEDfKWKWEGfDEKKW#KKWW#K#KWWWWWEWW#E#K##K#KW###W#K#####KWEKKW#WWK##KKWKW#KKKDDDDDDDKWKKKKWW#WWDDGGDGDGGDDDDEDEEEKEEEDEDEDDL, .:...,jjGDDt : .: : ...... : ... : ....: .. -#W#W#W#WKKEDDDLKWW#EDfGKK#KW###WW#K#K#KKKWW#KWW#WW#K##K##K###W#W##EKKW#K#E#E#WWWWEKKWWEEDEEDEKKKKKWWKWWWEDDGGGGDDGDDDDEEEEEEKEEDEDDDDj.: ...tjDEDG,. .. . .: .: ....:.... : ... : .. -WWW#W###EWKEDDLKKWKDDfGKKKW#WK#KWWWW#W#KWWWWEWK#WKW#KW##W###W####WWEWWW#WWE#K#WK#KWKWWEDEDEDEWKWKKKKWWWWWEDGDGGGDGDDDEEDEEEEEEDDDDEDDD.... .tDEDDD, ... :......... : : .: :: ..... -WW###W##EWEEDDLKEWEKGfDEWW#W##WWW#KW#W#WE#WWWEW#WE#K###WK#WWK###WWEKWW#W#KWW#W#EEKKKW#WDDDDEDEKKKKKKKW#WWWWGGGGGDGDDDDEDEEEEEEDDDDDDDDj. ..;DEDDDL...:..:...:...::.........:..::..: -##W#KW##EKWDGDfKKKKEDfDKEWWWWW#WK#K#WWWKWKW#KKK#WW#W##W#######W##WW#K##K##KW#KW#WEK#KKEEDKEDEDEWKWKWWKWKW#WDDGGGDGDDDEEEEEEEEDDDDDDDDDL,.. tEEDDDf..: ::..:: ::.::.::::..:..:..:.::. -WWK#W###DEEEGDLEKKKKDfDEWK#K##W##W#EW#KWWW#KKW#W##WWWW##W#W#W##W#KEWKWW#KWK##W#KEEWW##KDEDDDEEDKWKWKWWWWWWWEDGDGGDDDDDEDEEEEDEDDDDDDDDGL .,tEDKDGf.:.:. :...:. : :..:.::..: :. :... -W#W#W###DEWEDGGEDKKEDLDKK#K#WW###W#WK#KWWW#EWW#W##W#K##WW#W#WW##WKKKKKWWWWWWK#KWKKK##KKEDEEDEEEDWKKKWKW#WWWWKDGGGDGDDDEDEEEEEDEDDDGDGDDDD.LDEEDDDj:..:::....::.:..: ::.:.... :...:.: -#KW#WW##EEKDGDfDEKWEDLEK#K#K##W##K#KWWWWW#K#KWK###WW#W##W####W#KWE#EW##WWWW##WKKKK#WWKKDEDKKEEDEKWWWWKWKWWW#KEGGGGGDDEDEEEDEDDDDDDDDDGGGDjGDEDDDGj.:: ::.::: ::..::...: :.:::.....: diff --git a/jun_springboot_plugin/springboot_security2/.gitignore b/jun_springboot_plugin/springboot_security2/.gitignore deleted file mode 100644 index df01468368..0000000000 --- a/jun_springboot_plugin/springboot_security2/.gitignore +++ /dev/null @@ -1,59 +0,0 @@ -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -nbproject/private/ -build/ -nbbuild/ -dist/ -nbdist/ -.nb-gradle/ - - -### Java template -# Compiled class file -*.class - -# Log file -*.log - -# BlueJ files -*.ctxt - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ - -# Package Files # -*.jar -*.war -*.ear -*.zip -*.tar.gz -*.rar - -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* -### Maven template -target/ -pom.xml.tag -pom.xml.releaseBackup -pom.xml.versionsBackup -pom.xml.next -release.properties -dependency-reduced-pom.xml -buildNumber.properties -.mvn/timing.properties - -# Avoid ignoring Maven wrapper jar file (.jar files are usually ignored) -!/.mvn/wrapper/maven-wrapper.jar \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_security2/LICENSE b/jun_springboot_plugin/springboot_security2/LICENSE deleted file mode 100644 index ef2edbae6c..0000000000 --- a/jun_springboot_plugin/springboot_security2/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2020 西西弗斯 - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/jun_springboot_plugin/springboot_security2/README.md b/jun_springboot_plugin/springboot_security2/README.md deleted file mode 100644 index e555fc405d..0000000000 --- a/jun_springboot_plugin/springboot_security2/README.md +++ /dev/null @@ -1,36 +0,0 @@ -# simple-security - -#### 项目介绍 -基于spring boot+spring security+jwt实现的基础auth机制。 - -#### 快速开始 -在SpringBootApplication上添加@EnableWebSecurityJwt。 -同时需要自己实现一个UserDetailsService。 - -登陆接口路径: /auth/token - -#### 属性配置项 -- jwt.filter.header 请求header内的key -- jwt.filter.tokenHead 请求header内的key对应value 的默认开头 如Bearer -- jwt.filter.exceptUrl 过滤路径 如 /auth/** -- jwt.payload.secret payload秘钥 -- jwt.payload.issuer jwt签发者名称 -- jwt.payload.audience 接收jwt的一方 -- jwt.payload.expirationMinute 过期时间 ( 分钟 ) 默认是一天 -- jwt.payload.notBeforeMinute NotBefore ( 分钟 ) 默认是15分钟 - -#### 常见问题 -##### jackson-databind发生冲突? -``` - - org.simple - web-security-jwt - 2.0.3.RELEASE - - - com.fasterxml.jackson.core - jackson-databind - - - -``` \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_security2/pom.xml b/jun_springboot_plugin/springboot_security2/pom.xml deleted file mode 100644 index 2725fbad3d..0000000000 --- a/jun_springboot_plugin/springboot_security2/pom.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - 4.0.0 - - org.simple.security - springboot_security2 - 1.0 - pom - - - simple-security-jwt - simple-security-jwt-demo - - - - diff --git a/jun_springboot_plugin/springboot_security2/simple-security-jwt-demo/pom.xml b/jun_springboot_plugin/springboot_security2/simple-security-jwt-demo/pom.xml deleted file mode 100644 index e07e40f441..0000000000 --- a/jun_springboot_plugin/springboot_security2/simple-security-jwt-demo/pom.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - 4.0.0 - - org.simple.security - simple-security-jwt-demo - 1.0.0 - - - org.springframework.boot - spring-boot-starter-parent - 2.0.3.RELEASE - - - - - - org.simple.security - simple-security-jwt - 1.0.0 - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-test - test - - - - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_security2/simple-security-jwt-demo/src/main/java/org/simple/web/security/jwt/demo/DemoApplication.java b/jun_springboot_plugin/springboot_security2/simple-security-jwt-demo/src/main/java/org/simple/web/security/jwt/demo/DemoApplication.java deleted file mode 100644 index 7fd350bdd1..0000000000 --- a/jun_springboot_plugin/springboot_security2/simple-security-jwt-demo/src/main/java/org/simple/web/security/jwt/demo/DemoApplication.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.simple.web.security.jwt.demo; - -import org.simple.web.jwt.annotation.EnableWebSecurityJwt; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -/** - * 项目名称:web-security-jwt - * 类名称:DemoApplication - * 类描述:DemoApplication - * 创建时间:2018/9/12 - * - * @author guihuo (E-mail:1620657419@qq.com) - * @version v1.0 - */ -@EnableWebSecurityJwt -@SpringBootApplication -public class DemoApplication { - - public static void main(String[] args) { - SpringApplication.run(DemoApplication.class, args); - } - -} - diff --git a/jun_springboot_plugin/springboot_security2/simple-security-jwt-demo/src/main/java/org/simple/web/security/jwt/demo/controller/IndexController.java b/jun_springboot_plugin/springboot_security2/simple-security-jwt-demo/src/main/java/org/simple/web/security/jwt/demo/controller/IndexController.java deleted file mode 100644 index 8c0ffa604c..0000000000 --- a/jun_springboot_plugin/springboot_security2/simple-security-jwt-demo/src/main/java/org/simple/web/security/jwt/demo/controller/IndexController.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.simple.web.security.jwt.demo.controller; - -import org.simple.web.security.jwt.demo.entity.User; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import java.security.Principal; - -/** - * 项目名称:web-security-jwt - * 类名称:IndexController - * 类描述:IndexController - * 创建时间:2018/9/12 - * - * @author guihuo (E-mail:1620657419@qq.com) - * @version v1.0 - */ -@RequestMapping("/index") -@RestController -public class IndexController { - - @RequestMapping("/index") - public String index(Principal principal) { - return "index"; - } - -} diff --git a/jun_springboot_plugin/springboot_security2/simple-security-jwt-demo/src/main/java/org/simple/web/security/jwt/demo/entity/User.java b/jun_springboot_plugin/springboot_security2/simple-security-jwt-demo/src/main/java/org/simple/web/security/jwt/demo/entity/User.java deleted file mode 100644 index 2dd81df93b..0000000000 --- a/jun_springboot_plugin/springboot_security2/simple-security-jwt-demo/src/main/java/org/simple/web/security/jwt/demo/entity/User.java +++ /dev/null @@ -1,63 +0,0 @@ -package org.simple.web.security.jwt.demo.entity; - -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.userdetails.UserDetails; - -import java.util.ArrayList; -import java.util.Collection; - -/** - * 项目名称:web-security-jwt - * 类名称:User - * 类描述:User - * 创建时间:2018/9/13 - * - * @author guihuo (E-mail:1620657419@qq.com) - * @version v1.0 - */ -public class User implements UserDetails { - - private String username; - - private String password; - - public User(String username, String password) { - this.username = username; - this.password = password; - } - - @Override - public Collection getAuthorities() { - return new ArrayList<>(); - } - - @Override - public String getPassword() { - return password; - } - - @Override - public String getUsername() { - return username; - } - - @Override - public boolean isAccountNonExpired() { - return true; - } - - @Override - public boolean isAccountNonLocked() { - return true; - } - - @Override - public boolean isCredentialsNonExpired() { - return true; - } - - @Override - public boolean isEnabled() { - return true; - } -} diff --git a/jun_springboot_plugin/springboot_security2/simple-security-jwt-demo/src/main/java/org/simple/web/security/jwt/demo/service/UserAuthService.java b/jun_springboot_plugin/springboot_security2/simple-security-jwt-demo/src/main/java/org/simple/web/security/jwt/demo/service/UserAuthService.java deleted file mode 100644 index 6a9586788f..0000000000 --- a/jun_springboot_plugin/springboot_security2/simple-security-jwt-demo/src/main/java/org/simple/web/security/jwt/demo/service/UserAuthService.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.simple.web.security.jwt.demo.service; - -import org.simple.web.security.jwt.demo.entity.User; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.core.userdetails.UsernameNotFoundException; -import org.springframework.security.crypto.password.MessageDigestPasswordEncoder; -import org.springframework.stereotype.Component; - -/** - * 项目名称:web-security-jwt - * 类名称:UserAuthService - * 类描述:UserAuthService - * 创建时间:2018/9/13 - * - * @author guihuo (E-mail:1620657419@qq.com) - * @version v1.0 - */ -@Component -public class UserAuthService implements UserDetailsService { - - @Override - public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { - return new User(username, "{md5}" + new MessageDigestPasswordEncoder("MD5").encode(username)); - } - -} diff --git a/jun_springboot_plugin/springboot_security2/simple-security-jwt-demo/src/main/resources/application.yml b/jun_springboot_plugin/springboot_security2/simple-security-jwt-demo/src/main/resources/application.yml deleted file mode 100644 index 88d6b85b1e..0000000000 --- a/jun_springboot_plugin/springboot_security2/simple-security-jwt-demo/src/main/resources/application.yml +++ /dev/null @@ -1,6 +0,0 @@ -jwt: - filter: - debug: true -simple: - security: - passwordEncoder: md5 diff --git a/jun_springboot_plugin/springboot_security2/simple-security-jwt/pom.xml b/jun_springboot_plugin/springboot_security2/simple-security-jwt/pom.xml deleted file mode 100644 index fc255bd6ce..0000000000 --- a/jun_springboot_plugin/springboot_security2/simple-security-jwt/pom.xml +++ /dev/null @@ -1,81 +0,0 @@ - - - 4.0.0 - - org.simple.security - simple-security-jwt - 1.0.0 - - simple-security-jwt - 一个应用于springboot项目的,基于JWT的一键集成Auth机制。 - - - org.springframework.boot - spring-boot-starter-parent - 2.0.3.RELEASE - - - - - UTF-8 - UTF-8 - 1.8 - - - - - org.springframework.boot - spring-boot-configuration-processor - true - - - - org.springframework.boot - spring-boot-starter-security - - - io.jsonwebtoken - jjwt - 0.9.1 - - - - - org.projectlombok - lombok - 1.18.20 - - - - javax.servlet - javax.servlet-api - provided - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - org.projectlombok - lombok-maven-plugin - 1.16.8.0 - - - generate-sources - - delombok - - - - - - - - diff --git a/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/annotation/EnableWebSecurityJwt.java b/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/annotation/EnableWebSecurityJwt.java deleted file mode 100644 index d5a1a81a24..0000000000 --- a/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/annotation/EnableWebSecurityJwt.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.simple.web.jwt.annotation; - -import org.simple.web.jwt.config.WebSecurityConfig; -import org.springframework.context.annotation.Import; - -import java.lang.annotation.*; - -/** - * 项目名称:web-security-jwt - * 类名称:EnableWebSecurityJwt - * 类描述:EnableWebSecurityJwt - * 创建时间:2018/7/19 - * - * @author guihuo (E-mail:1620657419@qq.com) - * @version v1.0 - */ -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Inherited -@Import({WebSecurityConfig.class}) -public @interface EnableWebSecurityJwt { - -} diff --git a/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/config/PasswordEncoderFactory.java b/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/config/PasswordEncoderFactory.java deleted file mode 100644 index ffea054f1b..0000000000 --- a/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/config/PasswordEncoderFactory.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.simple.web.jwt.config; - -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.*; -import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder; - -import java.util.HashMap; -import java.util.Map; - -/** - * 项目名称:simple-security-all - * 类名称:PasswordEncoderFactory - * 类描述:PasswordEncoderFactory - * 创建时间:2018/9/13 - * - * @author guihuo (E-mail:1620657419@qq.com) - * @version v1.0 - */ -public class PasswordEncoderFactory { - - public static final String PWD_ENCODER_PLAINTEXT = "plain"; - public static final String PWD_ENCODER_BCRYPT = "bcrypt"; - public static final String PWD_ENCODER_SCRYPT = "scrypt"; - public static final String PWD_ENCODER_PBKDF2 = "pbkdf2"; - public static final String PWD_ENCODER_MD5 = "md5"; - public static final String PWD_ENCODER_SHA = "sha"; - public static final String PWD_ENCODER_SHA_256 = "sha-256"; - public static final String PWD_ENCODER_SHA_512 = "sha-512"; - public static final String PWD_ENCODER_STANDARD = "standard"; - - private static final Map PASSWORD_ENCODERS = new HashMap<>(); - - static { - PASSWORD_ENCODERS.put(PWD_ENCODER_BCRYPT, new BCryptPasswordEncoder()); - PASSWORD_ENCODERS.put(PWD_ENCODER_SCRYPT, new SCryptPasswordEncoder()); - PASSWORD_ENCODERS.put(PWD_ENCODER_PBKDF2, new Pbkdf2PasswordEncoder()); - PASSWORD_ENCODERS.put(PWD_ENCODER_PLAINTEXT, NoOpPasswordEncoder.getInstance()); - PASSWORD_ENCODERS.put(PWD_ENCODER_MD5, new MessageDigestPasswordEncoder("MD5")); - PASSWORD_ENCODERS.put(PWD_ENCODER_SHA, new MessageDigestPasswordEncoder("SHA-1")); - PASSWORD_ENCODERS.put(PWD_ENCODER_SHA_256, new MessageDigestPasswordEncoder("SHA-256")); - PASSWORD_ENCODERS.put(PWD_ENCODER_SHA_512, new MessageDigestPasswordEncoder("SHA-512")); - PASSWORD_ENCODERS.put(PWD_ENCODER_STANDARD, new StandardPasswordEncoder()); - } - - private PasswordEncoderFactory() { - } - - public static PasswordEncoder getInstance(String encoderId) { - return new DelegatingPasswordEncoder(encoderId, PASSWORD_ENCODERS); - } - -} diff --git a/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/config/WebSecurityConfig.java b/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/config/WebSecurityConfig.java deleted file mode 100644 index 6ba3ecbc05..0000000000 --- a/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/config/WebSecurityConfig.java +++ /dev/null @@ -1,116 +0,0 @@ -package org.simple.web.jwt.config; - -import org.simple.web.jwt.filter.JwtAuthenticationTokenFilter; -import org.simple.web.jwt.filter.UserLoginFilter; -import org.simple.web.jwt.handler.SimpleAuthenticatingFailureHandler; -import org.simple.web.jwt.handler.SimpleAuthenticatingSuccessHandler; -import org.simple.web.jwt.property.JwtAuthFilterProperty; -import org.simple.web.jwt.property.SimpleSecurityProperty; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpMethod; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer; -import org.springframework.security.config.http.SessionCreationPolicy; -import org.springframework.security.crypto.password.NoOpPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; -import org.springframework.util.StringUtils; - -/** - * 项目名称:web-web-jwt - * 类名称:WebSecurityConfig - * 类描述:WebSecurityConfig Spring Security 配置 - * 创建时间:2018/4/11 16:48 - * - * @author guihuo (E-mail:1620657419@qq.com) - * @version v1.0 - */ -@Configuration -@EnableWebSecurity -@EnableGlobalMethodSecurity(prePostEnabled = true) -@ComponentScan(basePackages = {"org.simple.web.jwt"}) -public class WebSecurityConfig extends WebSecurityConfigurerAdapter { - - @Autowired - private JwtAuthFilterProperty jwtAuthFilterProperty; - - @Autowired - private SimpleSecurityProperty simpleSecurityProperty; - - @Autowired - private SimpleAuthenticatingSuccessHandler simpleAuthenticatingSuccessHandler; - - @Autowired - private SimpleAuthenticatingFailureHandler simpleAuthenticatingFailureHandler; - - private Logger logger = LoggerFactory.getLogger(this.getClass()); - - /** - * HTTP请求安全处理 - * token请求授权 - * - * @param httpSecurity . - * @throws Exception . - */ - @Override - protected void configure(HttpSecurity httpSecurity) throws Exception { - // 由于使用的是JWT,我们这里不需要csrf - httpSecurity.csrf().disable(); - // 基于token,所以不需要session - httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); - // 禁用缓存 - httpSecurity.headers().cacheControl(); - - // 设置允许匿名访问的路由 - ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry expressionInterceptUrlRegistry - = httpSecurity.authorizeRequests(); - String[] urls = jwtAuthFilterProperty.getExceptUrl().split(","); - for (String url : urls) { - if (!StringUtils.isEmpty(url)) { - expressionInterceptUrlRegistry.antMatchers(url).permitAll(); - } - } - expressionInterceptUrlRegistry - .antMatchers(HttpMethod.OPTIONS).permitAll() - // 除上面外的所有请求全部需要鉴权认证 - .anyRequest().authenticated(); - - // 添加JWT filter - //将token验证添加在密码验证前面 - httpSecurity.addFilterBefore(getJwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class); - httpSecurity.addFilterBefore(getUserLoginFilter(), JwtAuthenticationTokenFilter.class); - } - - @Bean - public PasswordEncoder passwordEncoder() { - return PasswordEncoderFactory.getInstance(simpleSecurityProperty.getPasswordEncoder()); - } - - @Bean - public AuthenticationManager getManagerBean() throws Exception { - return super.authenticationManagerBean(); - } - - @Bean - public JwtAuthenticationTokenFilter getJwtAuthenticationTokenFilter() throws Exception { - return new JwtAuthenticationTokenFilter(); - } - - @Bean - public UserLoginFilter getUserLoginFilter() throws Exception { - UserLoginFilter userLoginFilter = new UserLoginFilter(getManagerBean()); - userLoginFilter.setAuthenticationSuccessHandler(simpleAuthenticatingSuccessHandler); - userLoginFilter.setAuthenticationFailureHandler(simpleAuthenticatingFailureHandler); - return userLoginFilter; - } - -} diff --git a/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/filter/JwtAuthenticationTokenFilter.java b/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/filter/JwtAuthenticationTokenFilter.java deleted file mode 100644 index 9454ac65dd..0000000000 --- a/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/filter/JwtAuthenticationTokenFilter.java +++ /dev/null @@ -1,66 +0,0 @@ -package org.simple.web.jwt.filter; - -import org.simple.web.jwt.property.JwtAuthFilterProperty; -import org.simple.web.jwt.service.JwtService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; -import org.springframework.web.filter.OncePerRequestFilter; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - -/** - * 项目名称:web-web-jwt - * 类名称:JwtAuthenticationTokenFilter - * 类描述:JwtAuthenticationTokenFilter jwt认证过滤器 - * 创建时间:2018/4/11 16:40 - * - * @author guihuo (E-mail:1620657419@qq.com) - * @version v1.0 - */ -public class JwtAuthenticationTokenFilter extends OncePerRequestFilter { - - @Autowired - private JwtService jwtService; - - @Autowired - private UserDetailsService userDetailsService; - - @Autowired - private JwtAuthFilterProperty jwtAuthFilterProperty; - - /** - * 过滤器逻辑 - * - * @param request . - * @param response . - * @param chain . - * @throws ServletException . - * @throws IOException , - */ - @Override - protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { - String authHeader = request.getHeader(this.jwtAuthFilterProperty.getHeader()); - String tokenHead = this.jwtAuthFilterProperty.getTokenHead(); - if (authHeader != null && authHeader.startsWith(tokenHead)) { - String authToken = authHeader.substring(tokenHead.length()); - if (jwtService.validateToken(authToken)) { - String subject = jwtService.getSubjectFromToken(authToken); - UserDetails userDetails = userDetailsService.loadUserByUsername(subject); - UsernamePasswordAuthenticationToken authentication = - new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); - authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); - SecurityContextHolder.getContext().setAuthentication(authentication); - } - } - chain.doFilter(request, response); - } - -} diff --git a/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/filter/UserLoginFilter.java b/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/filter/UserLoginFilter.java deleted file mode 100644 index 5443dbf97b..0000000000 --- a/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/filter/UserLoginFilter.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.simple.web.jwt.filter; - -import org.springframework.http.HttpMethod; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.authentication.AuthenticationServiceException; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; -import org.springframework.security.web.util.matcher.AntPathRequestMatcher; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - -/** - * 项目名称:web-security-jwt - * 类名称:UserLoginFilter - * 类描述:UserLoginFilter - * 创建时间:2018/9/12 - * - * @author guihuo (E-mail:1620657419@qq.com) - * @version v1.0 - */ -public class UserLoginFilter extends AbstractAuthenticationProcessingFilter { - - private static final String DEFAULT_USERNAME_PARAMETER = "username"; - - private static final String DEFAULT_PASSWORD_PARAMETER = "password"; - - public UserLoginFilter(AuthenticationManager authenticationManager) { - super(new AntPathRequestMatcher("/auth/token", HttpMethod.POST.name())); - setAuthenticationManager(authenticationManager); - } - - @Override - public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { - return this.getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken( - obtainUsername(request), obtainPassword(request) - )); - } - - private String obtainUsername(HttpServletRequest request) { - String username = request.getParameter(DEFAULT_USERNAME_PARAMETER); - if (username == null) { - username = ""; - } - return username.trim(); - } - - private String obtainPassword(HttpServletRequest request) { - String password = request.getParameter(DEFAULT_PASSWORD_PARAMETER); - if (password == null) { - password = ""; - } - return password; - } - -} diff --git a/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/handler/SimpleAuthenticatingFailureHandler.java b/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/handler/SimpleAuthenticatingFailureHandler.java deleted file mode 100644 index 4182b65e1a..0000000000 --- a/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/handler/SimpleAuthenticatingFailureHandler.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.simple.web.jwt.handler; - -import io.jsonwebtoken.lang.Assert; -import org.springframework.beans.factory.InitializingBean; -import org.springframework.context.MessageSource; -import org.springframework.context.MessageSourceAware; -import org.springframework.context.support.MessageSourceAccessor; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.core.SpringSecurityMessageSource; -import org.springframework.security.web.authentication.AuthenticationFailureHandler; -import org.springframework.stereotype.Component; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - -@Component -public class SimpleAuthenticatingFailureHandler implements AuthenticationFailureHandler, InitializingBean, MessageSourceAware { - - private static String AUTH_FAILURE_MESSAGES = "k.security.authenticate.failure"; - - private MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); - - private static String buildExceptionMessageKey(AuthenticationException e) { - return AUTH_FAILURE_MESSAGES + "." + AuthenticationException.class.getSimpleName(); - } - - @Override - public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException { - response.setStatus(HttpStatus.UNAUTHORIZED.value()); - response.setContentType(MediaType.APPLICATION_JSON_VALUE); - - String defaultFailureMessage = messages.getMessage(AUTH_FAILURE_MESSAGES, "Authentication failed"); - String exceptionMessage = messages.getMessage(buildExceptionMessageKey(e), defaultFailureMessage); - - response.sendError(HttpServletResponse.SC_FORBIDDEN, exceptionMessage); - } - - @Override - public void afterPropertiesSet() throws Exception { - Assert.notNull(messages, "The message accessor can't be null!"); - } - - @Override - public void setMessageSource(MessageSource messageSource) { - this.messages = new MessageSourceAccessor(messageSource); - } -} - diff --git a/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/handler/SimpleAuthenticatingSuccessHandler.java b/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/handler/SimpleAuthenticatingSuccessHandler.java deleted file mode 100644 index 3bb25b62a2..0000000000 --- a/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/handler/SimpleAuthenticatingSuccessHandler.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.simple.web.jwt.handler; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.simple.web.jwt.service.JwtService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.security.core.Authentication; -import org.springframework.security.web.WebAttributes; -import org.springframework.security.web.authentication.AuthenticationSuccessHandler; -import org.springframework.stereotype.Component; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -@Component -public class SimpleAuthenticatingSuccessHandler implements AuthenticationSuccessHandler { - - private static ObjectMapper globalObjectMapper = new ObjectMapper(); - - @Autowired - private JwtService jwtService; - - static { - globalObjectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - } - - private Logger logger = LoggerFactory.getLogger(SimpleAuthenticatingSuccessHandler.class); - - private static void clearAuthenticationAttributes(HttpServletRequest request) { - HttpSession session = request.getSession(false); - if (session == null) { - return; - } - session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); - } - - @Override - public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { - Map result = new HashMap<>(); - result.put("token", jwtService.generateToken(authentication.getName())); - response.setStatus(HttpStatus.OK.value()); - response.setContentType(MediaType.APPLICATION_JSON_VALUE); - globalObjectMapper.writeValue(response.getWriter(), result); - clearAuthenticationAttributes(request); - } - -} - diff --git a/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/property/JwtAuthFilterProperty.java b/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/property/JwtAuthFilterProperty.java deleted file mode 100644 index 365fa60284..0000000000 --- a/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/property/JwtAuthFilterProperty.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.simple.web.jwt.property; - -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -/** - * 项目名称:moguding-components - * 类名称:JwtAuthFilterProperty - * 类描述:JwtAuthFilterProperty - * 创建时间:2018/4/23 9:46 - * - * @author guihuo (E-mail:1620657419@qq.com) - * @version v1.0 - */ -@Data -@Configuration -@ConfigurationProperties(prefix = "jwt.filter") -public class JwtAuthFilterProperty { - - /** - * 请求header内的key - */ - private String header = "Authorization"; - /** - * 请求header内的key对应value 的默认开头 - */ - private String tokenHead = "Bearer "; - /** - * 过滤路径 - * 如 登录接口不需要走校验过滤器 - */ - private String exceptUrl = ""; - - -} diff --git a/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/property/JwtPayloadProperty.java b/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/property/JwtPayloadProperty.java deleted file mode 100644 index 52ca0402a0..0000000000 --- a/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/property/JwtPayloadProperty.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.simple.web.jwt.property; - -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -/** - * 项目名称:web-web-jwt - * 类名称:JwtPayloadProperty - * 类描述:JwtPayloadProperty jwt配置属性 - * 创建时间:2018/4/11 18:41 - * - * @author guihuo (E-mail:1620657419@qq.com) - * @version v1.0 - */ -@Data -@Configuration -@ConfigurationProperties(prefix = "jwt.payload") -public class JwtPayloadProperty { - - /** - * 密钥 - */ - private String secret = "simple"; - /** - * jwt签发者名称 - */ - private String issuer = "simple-security-jwt"; - /** - * 接收jwt的一方 - */ - private String audience = "foo"; - /** - * 过期时间 ( 分钟 ) - * 默认是一天 - */ - private int expirationMinute = 24 * 60 * 60; - /** - * NotBefore ( 分钟 ) - * 默认是15分钟 - */ - private int notBeforeMinute = 15; - -} diff --git a/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/property/SimpleSecurityProperty.java b/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/property/SimpleSecurityProperty.java deleted file mode 100644 index a35f06bdf5..0000000000 --- a/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/property/SimpleSecurityProperty.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.simple.web.jwt.property; - -import lombok.Data; -import org.simple.web.jwt.config.PasswordEncoderFactory; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -/** - * 项目名称:simple-security-all - * 类名称:SimpleSecurityProperty - * 类描述:SimpleSecurityProperty - * 创建时间:2018/9/13 - * - * @author guihuo (E-mail:1620657419@qq.com) - * @version v1.0 - */ -@Data -@Configuration -@ConfigurationProperties(prefix = "simple.security") -public class SimpleSecurityProperty { - - private String passwordEncoder = PasswordEncoderFactory.PWD_ENCODER_MD5; - -} diff --git a/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/service/JwtService.java b/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/service/JwtService.java deleted file mode 100644 index b6a4d29a3a..0000000000 --- a/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/java/org/simple/web/jwt/service/JwtService.java +++ /dev/null @@ -1,100 +0,0 @@ -package org.simple.web.jwt.service; - -import io.jsonwebtoken.Claims; -import io.jsonwebtoken.Jwts; -import io.jsonwebtoken.SignatureAlgorithm; -import org.simple.web.jwt.property.JwtAuthFilterProperty; -import org.simple.web.jwt.property.JwtPayloadProperty; -import org.simple.web.jwt.property.SimpleSecurityProperty; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import java.util.Date; - -/** - * 项目名称:simple-framework - * 类名称:JWTService - * 类描述:JWTService - * 创建时间:2018/8/9 - * - * @author jiangjunjie (E-mail:1620657419@qq.com) - * @version v1.0 - */ -@Service -public class JwtService { - - private Logger logger = LoggerFactory.getLogger(this.getClass()); - - @Autowired - private JwtPayloadProperty jwtPayloadProperty; - - /** - * 从令牌中获取数据声明 - * - * @param token 令牌 - * @return 数据声明 - */ - private Claims getClaimsFromToken(String token) { - return Jwts.parser().setSigningKey(jwtPayloadProperty.getSecret()).parseClaimsJws(token).getBody(); - } - - /** - * 从令牌中获取认证的唯一标识 - * - * @param token 令牌 - * @return 用户id - */ - public String getSubjectFromToken(String token) { - String username; - try { - Claims claims = getClaimsFromToken(token); - username = claims.getSubject(); - } catch (Exception e) { - logger.error("", e); - username = null; - } - return username; - } - - /** - * 验证令牌是否时间有效 - * - * @param token 令牌 - * @return 是否有效 - */ - public Boolean validateToken(String token) { - try { - Claims claims = getClaimsFromToken(token); - Date expiration = claims.getExpiration(); - Date notBefore = claims.getNotBefore(); - return new Date().after(notBefore) && new Date().before(expiration); - } catch (Exception e) { - logger.error("", e); - return false; - } - } - - /** - * 生成令牌 - * - * @param userId . - * @return . - */ - public String generateToken(String userId) { - return Jwts.builder() - //jwt签发者 - .setIssuer(jwtPayloadProperty.getIssuer()) - // jwt所面向的用户 - .setSubject(userId) - //接收jwt的一方 - .setAudience(jwtPayloadProperty.getAudience()) - .setExpiration(new Date(System.currentTimeMillis() + jwtPayloadProperty.getExpirationMinute() * 60 * 1000)) - .setNotBefore(new Date(System.currentTimeMillis() - jwtPayloadProperty.getNotBeforeMinute() * 60 * 1000)) - .setIssuedAt(new Date()) - .signWith(SignatureAlgorithm.HS512, jwtPayloadProperty.getSecret()) - .compact(); - } - -} diff --git a/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/resources/application.properties b/jun_springboot_plugin/springboot_security2/simple-security-jwt/src/main/resources/application.properties deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/jun_springboot_plugin/springboot_session/README.md b/jun_springboot_plugin/springboot_session/README.md deleted file mode 100644 index 51187be235..0000000000 --- a/jun_springboot_plugin/springboot_session/README.md +++ /dev/null @@ -1,126 +0,0 @@ -# spring-boot-demo-session - -> 此 demo 主要演示了 Spring Boot 如何通过 Spring Session 实现Session共享、重启程序Session不失效。 - -## pom.xml - -```xml - - - 4.0.0 - - spring-boot-demo-session - 1.0.0-SNAPSHOT - - spring-boot-demo-session - Demo project for Spring Boot - - - io.github.wujun728 - spring-boot-demo - 1.0.0-SNAPSHOT - - - - UTF-8 - UTF-8 - 1.8 - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.session - spring-session-data-redis - - - - org.springframework.boot - spring-boot-starter-data-redis - - - - - org.apache.commons - commons-pool2 - - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - - org.springframework.boot - spring-boot-starter-test - test - - - - cn.hutool - hutool-all - - - - - spring-boot-demo-session - - - org.springframework.boot - spring-boot-maven-plugin - - - - - -``` - -## application.yml - -```yaml -server: - port: 8080 - servlet: - context-path: /demo -spring: - session: - store-type: redis - redis: - flush-mode: immediate - namespace: "spring:session" - redis: - host: localhost - port: 6379 - # 连接超时时间(记得添加单位,Duration) - timeout: 10000ms - # Redis默认情况下有16个分片,这里配置具体使用的分片 - # database: 0 - lettuce: - pool: - # 连接池最大连接数(使用负值表示没有限制) 默认 8 - max-active: 8 - # 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1 - max-wait: -1ms - # 连接池中的最大空闲连接 默认 8 - max-idle: 8 - # 连接池中的最小空闲连接 默认 0 - min-idle: 0 -``` - -## 测试 - -> 测试 重启程序,Session 不失效的场景 - -1. 打开浏览器,访问首页:http://localhost:8080/demo/page/index -2. 最开始未登录,所以会跳转到登录页:http://localhost:8080/demo/page/login?redirect=true 然后点击登录按钮 -3. 登录之后,跳转回首页,此时可以看到首页显示token信息。 -4. 重启程序。不关闭浏览器,直接刷新首页,此时不跳转到登录页。测试成功! - -## 参考 - -- Spring Session 官方文档:https://docs.spring.io/spring-session/docs/current/reference/html5/guides/boot-redis.html#updating-dependencies \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_session/pom.xml b/jun_springboot_plugin/springboot_session/pom.xml deleted file mode 100644 index bc09b158c7..0000000000 --- a/jun_springboot_plugin/springboot_session/pom.xml +++ /dev/null @@ -1,75 +0,0 @@ - - - 4.0.0 - - io.github.wujun728 - springboot_session - 1.0 - jar - - springboot_session - Demo project for Spring Boot - - - io.github.wujun728 - jun_springboot_plugin - 1.0 - - - - UTF-8 - UTF-8 - 1.8 - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.session - spring-session-data-redis - - - - org.springframework.boot - spring-boot-starter-data-redis - - - - - org.apache.commons - commons-pool2 - - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - - org.springframework.boot - spring-boot-starter-test - test - - - - cn.hutool - hutool-all - - - - - springboot_session - - - org.springframework.boot - spring-boot-maven-plugin - - - - - diff --git a/jun_springboot_plugin/springboot_session/src/main/java/com/jun/plugin/session/SpringBootDemoSessionApplication.java b/jun_springboot_plugin/springboot_session/src/main/java/com/jun/plugin/session/SpringBootDemoSessionApplication.java deleted file mode 100644 index c3e3c7ab4a..0000000000 --- a/jun_springboot_plugin/springboot_session/src/main/java/com/jun/plugin/session/SpringBootDemoSessionApplication.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.jun.plugin.session; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -/** - *

    - * 启动类 - *

    - * - * @package: com.xkcoding.session - * @description: 启动类 - * @author: yangkai.shen - * @date: Created in 2018-12-19 19:35 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@SpringBootApplication -public class SpringBootDemoSessionApplication { - - public static void main(String[] args) { - SpringApplication.run(SpringBootDemoSessionApplication.class, args); - } - -} - diff --git a/jun_springboot_plugin/springboot_session/src/main/java/com/jun/plugin/session/config/WebMvcConfig.java b/jun_springboot_plugin/springboot_session/src/main/java/com/jun/plugin/session/config/WebMvcConfig.java deleted file mode 100644 index 90f5d338ed..0000000000 --- a/jun_springboot_plugin/springboot_session/src/main/java/com/jun/plugin/session/config/WebMvcConfig.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.jun.plugin.session.config; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.InterceptorRegistration; -import org.springframework.web.servlet.config.annotation.InterceptorRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -import com.jun.plugin.session.interceptor.SessionInterceptor; - -/** - *

    - * WebMvc 配置类 - *

    - * - * @package: com.xkcoding.session.config - * @description: WebMvc 配置类 - * @author: yangkai.shen - * @date: Created in 2018-12-19 19:50 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Configuration -public class WebMvcConfig implements WebMvcConfigurer { - @Autowired - private SessionInterceptor sessionInterceptor; - - @Override - public void addInterceptors(InterceptorRegistry registry) { - InterceptorRegistration sessionInterceptorRegistry = registry.addInterceptor(sessionInterceptor); - // 排除不需要拦截的路径 - sessionInterceptorRegistry.excludePathPatterns("/page/login"); - sessionInterceptorRegistry.excludePathPatterns("/page/doLogin"); - sessionInterceptorRegistry.excludePathPatterns("/error"); - - // 需要拦截的路径 - sessionInterceptorRegistry.addPathPatterns("/**"); - } -} diff --git a/jun_springboot_plugin/springboot_session/src/main/java/com/jun/plugin/session/constants/Consts.java b/jun_springboot_plugin/springboot_session/src/main/java/com/jun/plugin/session/constants/Consts.java deleted file mode 100644 index b447213928..0000000000 --- a/jun_springboot_plugin/springboot_session/src/main/java/com/jun/plugin/session/constants/Consts.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jun.plugin.session.constants; - -/** - *

    - * 常量池 - *

    - * - * @package: com.xkcoding.session.constants - * @description: 常量池 - * @author: yangkai.shen - * @date: Created in 2018-12-19 19:42 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -public interface Consts { - /** - * session保存的key - */ - String SESSION_KEY = "key:session:token"; -} diff --git a/jun_springboot_plugin/springboot_session/src/main/java/com/jun/plugin/session/controller/PageController.java b/jun_springboot_plugin/springboot_session/src/main/java/com/jun/plugin/session/controller/PageController.java deleted file mode 100644 index 0d30da31a9..0000000000 --- a/jun_springboot_plugin/springboot_session/src/main/java/com/jun/plugin/session/controller/PageController.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.jun.plugin.session.controller; - -import cn.hutool.core.util.IdUtil; -import cn.hutool.core.util.ObjectUtil; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.servlet.ModelAndView; - -import com.jun.plugin.session.constants.Consts; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; - -/** - *

    - * 页面跳转 Controller - *

    - * - * @package: com.xkcoding.session.controller - * @description: 页面跳转 Controller - * @author: yangkai.shen - * @date: Created in 2018-12-19 19:57 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Controller -@RequestMapping("/page") -public class PageController { - /** - * 跳转到 首页 - * - * @param request 请求 - */ - @GetMapping("/index") - public ModelAndView index(HttpServletRequest request) { - ModelAndView mv = new ModelAndView(); - - String token = (String) request.getSession().getAttribute(Consts.SESSION_KEY); - mv.setViewName("index"); - mv.addObject("token", token); - return mv; - } - - /** - * 跳转到 登录页 - * - * @param redirect 是否是跳转回来的 - */ - @GetMapping("/login") - public ModelAndView login(Boolean redirect) { - ModelAndView mv = new ModelAndView(); - - if (ObjectUtil.isNotNull(redirect) && ObjectUtil.equal(true, redirect)) { - mv.addObject("message", "请先登录!"); - } - mv.setViewName("login"); - return mv; - } - - @GetMapping("/doLogin") - public String doLogin(HttpSession session) { - session.setAttribute(Consts.SESSION_KEY, IdUtil.fastUUID()); - - return "redirect:/page/index"; - } -} diff --git a/jun_springboot_plugin/springboot_session/src/main/java/com/jun/plugin/session/controller/SessionController.java b/jun_springboot_plugin/springboot_session/src/main/java/com/jun/plugin/session/controller/SessionController.java deleted file mode 100644 index d541c6d8d2..0000000000 --- a/jun_springboot_plugin/springboot_session/src/main/java/com/jun/plugin/session/controller/SessionController.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.jun.plugin.session.controller; - -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; - -/** - *

    - * session测试 - *

    - * - * @author MrWen - */ -@RestController -@RequestMapping("/session") -public class SessionController { - - @GetMapping("/save/{message}") - public String save(@PathVariable("message") String message, HttpServletRequest request) { - HttpSession session = request.getSession(); - session.setAttribute("test", message); - return "success"; - } - - - @GetMapping("/detail") - public String detail(HttpServletRequest request) { - HttpSession session = request.getSession(); - return (String) session.getAttribute("test"); - } - -} diff --git a/jun_springboot_plugin/springboot_session/src/main/java/com/jun/plugin/session/interceptor/SessionInterceptor.java b/jun_springboot_plugin/springboot_session/src/main/java/com/jun/plugin/session/interceptor/SessionInterceptor.java deleted file mode 100644 index 463d986b27..0000000000 --- a/jun_springboot_plugin/springboot_session/src/main/java/com/jun/plugin/session/interceptor/SessionInterceptor.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.jun.plugin.session.interceptor; - -import org.springframework.stereotype.Component; -import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; - -import com.jun.plugin.session.constants.Consts; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -/** - *

    - * 校验Session的拦截器 - *

    - * - * @package: com.xkcoding.session.interceptor - * @description: 校验Session的拦截器 - * @author: yangkai.shen - * @date: Created in 2018-12-19 19:40 - * @copyright: Copyright (c) 2018 - * @version: V1.0 - * @modified: yangkai.shen - */ -@Component -public class SessionInterceptor extends HandlerInterceptorAdapter { - @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - HttpSession session = request.getSession(); - if (session.getAttribute(Consts.SESSION_KEY) != null) { - return true; - } - // 跳转到登录页 - String url = "/page/login?redirect=true"; - response.sendRedirect(request.getContextPath() + url); - return false; - } -} diff --git a/jun_springboot_plugin/springboot_session/src/main/resources/application.yml b/jun_springboot_plugin/springboot_session/src/main/resources/application.yml deleted file mode 100644 index c0da8e602d..0000000000 --- a/jun_springboot_plugin/springboot_session/src/main/resources/application.yml +++ /dev/null @@ -1,27 +0,0 @@ -server: - port: 8080 - servlet: - context-path: /demo -spring: - session: - store-type: redis - redis: - flush-mode: immediate - namespace: "spring:session" - redis: - host: localhost - port: 6379 - # 连接超时时间(记得添加单位,Duration) - timeout: 10000ms - # Redis默认情况下有16个分片,这里配置具体使用的分片 - # database: 0 - lettuce: - pool: - # 连接池最大连接数(使用负值表示没有限制) 默认 8 - max-active: 8 - # 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1 - max-wait: -1ms - # 连接池中的最大空闲连接 默认 8 - max-idle: 8 - # 连接池中的最小空闲连接 默认 0 - min-idle: 0 \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_session/src/main/resources/templates/index.html b/jun_springboot_plugin/springboot_session/src/main/resources/templates/index.html deleted file mode 100644 index 843cf73408..0000000000 --- a/jun_springboot_plugin/springboot_session/src/main/resources/templates/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - - spring-boot-demo-session - - -token的值:

    - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_session/src/main/resources/templates/login.html b/jun_springboot_plugin/springboot_session/src/main/resources/templates/login.html deleted file mode 100644 index 3cb98a77c1..0000000000 --- a/jun_springboot_plugin/springboot_session/src/main/resources/templates/login.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - spring-boot-demo-session - - -

    - - - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_session/src/test/java/com/jun/plugin/session/SpringBootDemoSessionApplicationTests.java b/jun_springboot_plugin/springboot_session/src/test/java/com/jun/plugin/session/SpringBootDemoSessionApplicationTests.java deleted file mode 100644 index dcbc9dbd3c..0000000000 --- a/jun_springboot_plugin/springboot_session/src/test/java/com/jun/plugin/session/SpringBootDemoSessionApplicationTests.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.jun.plugin.session; - -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 SpringBootDemoSessionApplicationTests { - - @Test - public void contextLoads() { - } - -} - diff --git a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/.gitignore b/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/.gitignore deleted file mode 100644 index bfa6a22a52..0000000000 --- a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/.gitignore +++ /dev/null @@ -1 +0,0 @@ -# Created by .ignore support plugin (hsz.mobi) diff --git a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/README.md b/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/README.md deleted file mode 100644 index 1198a9ee90..0000000000 --- a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/README.md +++ /dev/null @@ -1,4 +0,0 @@ -## 技术 -SpringBoot2.2.6.RELEASE + shardingsphere4.0.0-RC1 + Mybatis Plus3.4.0 + Maven + MySQL + lombok(插件) - -默认库 + 分库分表 \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/doc/slave_user.sql b/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/doc/slave_user.sql deleted file mode 100644 index e820c8a6eb..0000000000 --- a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/doc/slave_user.sql +++ /dev/null @@ -1,48 +0,0 @@ --- 创建三个库 -CREATE DATABASE `ds` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci; -CREATE DATABASE `ds0` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci; -CREATE DATABASE `ds1` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci; - --- ds库创建 -DROP TABLE IF EXISTS `sys_dept`; -CREATE TABLE `sys_dept` ( - `id` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '主键', - `dept_no` varchar(18) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '部门编号(规则:父级关系编码+自己的编码)', - `name` varchar(300) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '部门名称', - `pid` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '父级id', - `status` tinyint(4) NULL DEFAULT NULL COMMENT '状态(1:正常;0:弃用)', - `relation_code` varchar(3000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '为了维护更深层级关系', - `dept_manager_id` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '部门经理user_id', - `manager_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '部门经理名称', - `phone` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '部门经理联系电话', - `create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间', - `update_time` datetime(0) NULL DEFAULT NULL COMMENT '更新时间', - `deleted` tinyint(4) NULL DEFAULT NULL COMMENT '是否删除(1未删除;0已删除)', - PRIMARY KEY (`id`) USING BTREE -) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '系统部门' ROW_FORMAT = Dynamic; - --- ds0与ds1库分别创建两个个表 -DROP TABLE IF EXISTS `tab_user0`; -CREATE TABLE `tab_user0` ( - `id` bigint(32) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', - `name` varchar(64) DEFAULT NULL COMMENT '姓名', - `sex` varchar(32) DEFAULT NULL COMMENT '性别', - `age` int(11) DEFAULT NULL COMMENT '年龄', - `create_time` datetime DEFAULT NULL COMMENT '创建时间', - `update_time` datetime DEFAULT NULL COMMENT '更新时间', - `deleted` tinyint(1) DEFAULT NULL COMMENT '是否删除 1删除 0未删除', - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; -DROP TABLE IF EXISTS `tab_user1`; -CREATE TABLE `tab_user1` ( - `id` bigint(32) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', - `name` varchar(64) DEFAULT NULL COMMENT '姓名', - `sex` varchar(32) DEFAULT NULL COMMENT '性别', - `age` int(11) DEFAULT NULL COMMENT '年龄', - `create_time` datetime DEFAULT NULL COMMENT '创建时间', - `update_time` datetime DEFAULT NULL COMMENT '更新时间', - `deleted` tinyint(1) DEFAULT NULL COMMENT '是否删除 1删除 0未删除', - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - - diff --git a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/pom.xml b/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/pom.xml deleted file mode 100644 index 364595a99b..0000000000 --- a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/pom.xml +++ /dev/null @@ -1,120 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - springboot_shardingsphere-mybatisplus - 1.0 - jar - - - 1.8 - 2.0.1 - 1.1.16 - UTF-8 - 3.4.0 - 4.1.1 - - - - org.springframework.boot - spring-boot-starter-parent - 2.2.6.RELEASE - - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.projectlombok - lombok - - - - - - com.alibaba - druid - 1.2.1 - - - - org.apache.shardingsphere - sharding-jdbc-spring-boot-starter - ${shardingsphere.version} - - - - mysql - mysql-connector-java - runtime - - - - org.mybatis.spring.boot - mybatis-spring-boot-starter - 2.1.2 - - - - com.github.pagehelper - pagehelper-spring-boot-starter - 1.2.13 - - - - com.baomidou - mybatis-plus-boot-starter - ${mybatisPlus.version} - - - - - com.baomidou - mybatis-plus-generator - ${mybatisPlus.version} - - - - - org.freemarker - freemarker - 2.3.30 - test - - - org.projectlombok - lombok - provided - - - - - ${artifactId} - - - org.springframework.boot - spring-boot-maven-plugin - - - maven-compiler-plugin - - ${java.version} - ${java.version} - UTF-8 - - - - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/Application.java b/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/Application.java deleted file mode 100644 index 2a3761473a..0000000000 --- a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/Application.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.frame; - -import org.mybatis.spring.annotation.MapperScan; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -/** - * @Description: 启动类 - * - * @author wenbin - * @date 2019/10/08 下午6:33 - */ -@SpringBootApplication -@MapperScan("com.frame.mapper") -public class Application { - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} diff --git a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/config/MetaObjectHandlerConfig.java b/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/config/MetaObjectHandlerConfig.java deleted file mode 100644 index 64429b63c8..0000000000 --- a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/config/MetaObjectHandlerConfig.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.frame.config; - -import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; -import org.apache.ibatis.reflection.MetaObject; -import org.springframework.stereotype.Component; - -import java.util.Arrays; -import java.util.Date; -import java.util.HashSet; - - -/** - * mybatis plus 默认值配置 - * - * @author wenbin - * @version V1.0 - * @date 2020年3月18日 - */ -@Component -public class MetaObjectHandlerConfig implements MetaObjectHandler { - - @Override - public void insertFill(MetaObject metaObject) { - Date currentDate = new Date(); - String[] setterNames = metaObject.getSetterNames(); - HashSet setterNameSet = new HashSet<>(Arrays.asList(setterNames)); - if (setterNameSet.contains("deleted")) { - //默认未删除 - setFieldValByName("deleted", 1, metaObject); - } - if (setterNameSet.contains("unableFlag")) { - //默认启用 - setFieldValByName("unableFlag", 1, metaObject); - } - if (setterNameSet.contains("createTime")) { - //创建时间默认当前时间 - setFieldValByName("createTime", currentDate, metaObject); - } - if (setterNameSet.contains("createDate")) { - //创建时间默认当前时间 - setFieldValByName("createDate", currentDate, metaObject); - } - if (setterNameSet.contains("updateTime")) { - //创建时间默认当前时间 - setFieldValByName("updateTime", currentDate, metaObject); - } - if (setterNameSet.contains("updateDate")) { - //创建时间默认当前时间 - setFieldValByName("updateDate", currentDate, metaObject); - } - - } - - @Override - public void updateFill(MetaObject metaObject) { - Date currentDate = new Date(); - String[] setterNames = metaObject.getSetterNames(); - HashSet setterNameSet = new HashSet<>(Arrays.asList(setterNames)); - if (setterNameSet.contains("updateTime")) { - //创建时间默认当前时间 - setFieldValByName("updateTime", currentDate, metaObject); - } - if (setterNameSet.contains("updateDate")) { - //创建时间默认当前时间 - setFieldValByName("updateDate", currentDate, metaObject); - } - } -} \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/config/MyBatisPlusConfig.java b/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/config/MyBatisPlusConfig.java deleted file mode 100644 index e1302bc6db..0000000000 --- a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/config/MyBatisPlusConfig.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.frame.config; - -import com.baomidou.mybatisplus.annotation.DbType; -import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; -import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * @ClassName MyBatisPlusConfig - * @Version 1.0 - **/ -@Configuration -public class MyBatisPlusConfig { - /** - * 配置mybatis-plus 拦截器 - */ - @Bean - public MybatisPlusInterceptor mybatisPlusInterceptor() { - MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); - //添加分页拦截器 - interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); - return interceptor; - } -} \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/controller/SysDeptController.java b/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/controller/SysDeptController.java deleted file mode 100644 index 4fa4e34405..0000000000 --- a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/controller/SysDeptController.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.frame.controller; - - -import com.frame.entity.SysDept; -import com.frame.service.ISysDeptService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RestController; - -/** - *

    - * 系统部门 前端控制器 - *

    - * - * @author 19047921 - * @since 2021-02-09 - */ -@RestController -public class SysDeptController { - @Autowired - private ISysDeptService iSysDeptService; - - /** - * @Description: 批量保存用户 - */ - @PostMapping("save-dept") - public Object saveUser() { - return iSysDeptService.save(new SysDept().setName("test部门")); - } -} diff --git a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/controller/UserController.java b/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/controller/UserController.java deleted file mode 100644 index 45a980ec32..0000000000 --- a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/controller/UserController.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.frame.controller; - - -import com.frame.entity.User; -import com.frame.service.UserService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RestController; - - -/** - * @Description: 接口测试 - * - * @author wenbin - * @date 2019/8/24 下午6:31 - */ -@RestController -public class UserController { - - @Autowired - private UserService userService; - - /** - * @Description: 批量保存用户 - */ - @PostMapping("save-user") - public Object saveUser() { - return userService.save(new User().setName("小李").setAge(11)); - } - - /** - * @Description: 批量保存用户 - */ - @PostMapping("delete-user") - public Object saveUser(Long id) { - return userService.removeById(id); - } - /** - * @Description: 获取用户列表 - */ - @GetMapping("list-user") - public Object listUser() { - return userService.list(); - } - - -} diff --git a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/entity/SysDept.java b/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/entity/SysDept.java deleted file mode 100644 index b90e78aba7..0000000000 --- a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/entity/SysDept.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.frame.entity; - -import java.util.Date; -import java.io.Serializable; - -import com.baomidou.mybatisplus.annotation.FieldFill; -import com.baomidou.mybatisplus.annotation.TableField; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.experimental.Accessors; - -/** - *

    - * 系统部门 - *

    - * - * @author 19047921 - * @since 2021-02-09 - */ -@Data -@EqualsAndHashCode(callSuper = false) -@Accessors(chain = true) -public class SysDept implements Serializable { - - private static final long serialVersionUID = 1L; - - /** - * 主键 - */ - private String id; - - /** - * 部门编号(规则:父级关系编码+自己的编码) - */ - private String deptNo; - - /** - * 部门名称 - */ - private String name; - - /** - * 父级id - */ - private String pid; - - /** - * 状态(1:正常;0:弃用) - */ - private Integer status; - - /** - * 为了维护更深层级关系 - */ - private String relationCode; - - /** - * 部门经理user_id - */ - private String deptManagerId; - - /** - * 部门经理名称 - */ - private String managerName; - - /** - * 部门经理联系电话 - */ - private String phone; - - /** - * - */ - @TableField(fill = FieldFill.INSERT) - private Date createTime; - - /** - * - */ - @TableField(fill = FieldFill.INSERT_UPDATE) - private Date updateTime; - - /** - * 是否删除 1删除 0未删除 - */ - @TableField(fill = FieldFill.INSERT) - private Integer deleted; - - - -} diff --git a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/entity/User.java b/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/entity/User.java deleted file mode 100644 index 386ca9c59f..0000000000 --- a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/entity/User.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.frame.entity; - -import com.baomidou.mybatisplus.annotation.FieldFill; -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.experimental.Accessors; - -import java.util.Date; - -/** - * user表 - */ -@Data -@TableName("tab_user") -@Accessors(chain = true) -public class User { - /** - * 主键 - */ - private Long id; - - /** - * 姓名 - */ - private String name; - - /** - * 性别 - */ - private String sex; - - /** - * 年龄 - */ - private Integer age; - - /** - * - */ - @TableField(fill = FieldFill.INSERT) - private Date createTime; - - /** - * - */ - @TableField(fill = FieldFill.INSERT_UPDATE) - private Date updateTime; - - /** - * 是否删除 1删除 0未删除 - */ - @TableField(fill = FieldFill.INSERT) - private Integer deleted; - -} \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/mapper/SysDeptMapper.java b/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/mapper/SysDeptMapper.java deleted file mode 100644 index 430aef1eee..0000000000 --- a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/mapper/SysDeptMapper.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.frame.mapper; - -import com.frame.entity.SysDept; -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import org.apache.ibatis.annotations.Mapper; - -/** - *

    - * 系统部门 Mapper 接口 - *

    - * - * @author 19047921 - * @since 2021-02-09 - */ -@Mapper -public interface SysDeptMapper extends BaseMapper { - -} diff --git a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/mapper/UserMapper.java b/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/mapper/UserMapper.java deleted file mode 100644 index 7fcc86226f..0000000000 --- a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/mapper/UserMapper.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.frame.mapper; - - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.frame.entity.User; -import org.apache.ibatis.annotations.Mapper; - -/** - * @Description: 用户mapper - * - * @author wenbin - * @date 2019/10/8 下午9:23 - */ -@Mapper -public interface UserMapper extends BaseMapper { - -} \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/service/ISysDeptService.java b/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/service/ISysDeptService.java deleted file mode 100644 index a82b4dd3bc..0000000000 --- a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/service/ISysDeptService.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.frame.service; - -import com.frame.entity.SysDept; -import com.baomidou.mybatisplus.extension.service.IService; - -/** - *

    - * 系统部门 服务类 - *

    - * - * @author 19047921 - * @since 2021-02-09 - */ -public interface ISysDeptService extends IService { - -} diff --git a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/service/UserService.java b/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/service/UserService.java deleted file mode 100644 index 79892d26d6..0000000000 --- a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/service/UserService.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.frame.service; - -import com.baomidou.mybatisplus.extension.service.IService; -import com.frame.entity.User; - -/** - * @Description: 用户相关接口 - * - * @author wenbin - * @date 2019/8/24 下午6:32 - */ -public interface UserService extends IService { - -} \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/service/impl/SysDeptServiceImpl.java b/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/service/impl/SysDeptServiceImpl.java deleted file mode 100644 index 213ea872e6..0000000000 --- a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/service/impl/SysDeptServiceImpl.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.frame.service.impl; - -import com.frame.entity.SysDept; -import com.frame.mapper.SysDeptMapper; -import com.frame.service.ISysDeptService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import org.springframework.stereotype.Service; - -/** - *

    - * 系统部门 服务实现类 - *

    - * - * @author 19047921 - * @since 2021-02-09 - */ -@Service -public class SysDeptServiceImpl extends ServiceImpl implements ISysDeptService { - -} diff --git a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/service/impl/UserServiceImpl.java b/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/service/impl/UserServiceImpl.java deleted file mode 100644 index 0ecdd9fd79..0000000000 --- a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/java/com/frame/service/impl/UserServiceImpl.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.frame.service.impl; - -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.frame.entity.User; -import com.frame.mapper.UserMapper; -import com.frame.service.UserService; -import org.springframework.stereotype.Service; - - -/** - * @author wenbin - * @Description: 用户实现类 - * @date 2019/8/8 上午9:13 - */ -@Service -public class UserServiceImpl extends ServiceImpl implements UserService { -} diff --git a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/resources/application.yml b/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/resources/application.yml deleted file mode 100644 index dbfaf59630..0000000000 --- a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/main/resources/application.yml +++ /dev/null @@ -1,53 +0,0 @@ -server: - port: 8088 - -mybatis-plus: - configuration: - log-impl: org.apache.ibatis.logging.stdout.StdOutImpl - global-config: - db-config: - logic-delete-field: deleted - logic-delete-value: 0 - logic-not-delete-value: 1 - mapper-locations: classpath:mapper/*.xml,classpath:mapper/**/*.xml - - -spring: - shardingsphere: - datasource: - names: ds,ds0,ds1 - ds: - driver-class-name: com.mysql.jdbc.Driver - password: root - type: com.alibaba.druid.pool.DruidDataSource - url: jdbc:mysql://localhost:3306/ds?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2b8&rewriteBatchedStatements=true&allowMultiQueries=true - username: root - ds0: - driver-class-name: com.mysql.jdbc.Driver - password: root - type: com.alibaba.druid.pool.DruidDataSource - url: jdbc:mysql://localhost:3306/ds0?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2b8&rewriteBatchedStatements=true&allowMultiQueries=true - username: root - ds1: - driver-class-name: com.mysql.jdbc.Driver - password: root - type: com.alibaba.druid.pool.DruidDataSource - url: jdbc:mysql://localhost:3306/ds1?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2b8&rewriteBatchedStatements=true&allowMultiQueries=true - username: root - props: - sql: - show: true - sharding: - # 默认数据源 - default-data-source-name: ds - default-database-strategy: - inline: - algorithm-expression: ds$->{id % 2} - sharding-column: id - tables: - tab_user: - actual-data-nodes: ds$->{0..1}.tab_user$->{0..1} - table-strategy: - inline: - algorithm-expression: tab_user$->{age % 2} - sharding-column: age diff --git a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/test/java/CodeGenerator.java b/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/test/java/CodeGenerator.java deleted file mode 100644 index 461dd1ba2b..0000000000 --- a/jun_springboot_plugin/springboot_shardingsphere-mybatisplus/src/test/java/CodeGenerator.java +++ /dev/null @@ -1,113 +0,0 @@ -import com.baomidou.mybatisplus.core.toolkit.StringPool; -import com.baomidou.mybatisplus.generator.AutoGenerator; -import com.baomidou.mybatisplus.generator.InjectionConfig; -import com.baomidou.mybatisplus.generator.config.*; -import com.baomidou.mybatisplus.generator.config.po.TableInfo; -import com.baomidou.mybatisplus.generator.config.rules.DateType; -import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; -import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; - -import java.util.ArrayList; -import java.util.List; - -// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中 -public class CodeGenerator { - - - //多个表逗号分隔 - static String tableName = "sys_dept"; - //逻辑删除字段名, 假如表没有逻辑删除字段,请忽视 - static String logicDeleteFieldName = "del_flag"; - - public static void main(String[] args) { - // 代码生成器 - AutoGenerator mpg = new AutoGenerator(); - - // 全局配置 - GlobalConfig gc = new GlobalConfig(); - String projectPath = System.getProperty("user.dir"); - gc.setOutputDir(projectPath + "/src/main/java"); - gc.setAuthor("19047921"); - gc.setOpen(false); - gc.setBaseColumnList(true); - gc.setBaseResultMap(true); - gc.setDateType(DateType.ONLY_DATE); - // gc.setSwagger2(true); 实体属性 Swagger2 注解 - mpg.setGlobalConfig(gc); - - // 数据源配置 - DataSourceConfig dsc = new DataSourceConfig(); - dsc.setUrl("jdbc:mysql://10.138.228.199:32938/ds?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC"); - // dsc.setSchemaName("public"); - dsc.setDriverName("com.mysql.cj.jdbc.Driver"); - dsc.setUsername("root"); - dsc.setPassword("Edn@ESR-3+"); - mpg.setDataSource(dsc); - - // 包配置 - PackageConfig pc = new PackageConfig(); - pc.setParent("com.frame"); - pc.setEntity("entity"); - pc.setMapper("mapper"); - pc.setController("controller"); - mpg.setPackageInfo(pc); - - // 自定义配置 - InjectionConfig cfg = new InjectionConfig() { - @Override - public void initMap() { - // to do nothing - } - }; - - // 如果模板引擎是 freemarker - String templatePath = "/templates/mapper.xml.ftl"; - // 如果模板引擎是 velocity - // String templatePath = "/templates/mapper.xml.vm"; - - // 自定义输出配置 - List focList = new ArrayList<>(); - // 自定义配置会被优先输出 - focList.add(new FileOutConfig(templatePath) { - @Override - public String outputFile(TableInfo tableInfo) { - // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!! - return projectPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; - } - }); - cfg.setFileOutConfigList(focList); - mpg.setCfg(cfg); - - // 配置模板 - TemplateConfig templateConfig = new TemplateConfig(); - - // 配置自定义输出模板 - //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别 -// templateConfig.setEntity("templates/entity.java"); - // templateConfig.setService(); -// templateConfig.setController("templates/controller.java"); - - templateConfig.setXml(null); - mpg.setTemplate(templateConfig); - - // 策略配置 - StrategyConfig strategy = new StrategyConfig(); - strategy.setNaming(NamingStrategy.underline_to_camel); - strategy.setColumnNaming(NamingStrategy.underline_to_camel); -// strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!"); - strategy.setEntityLombokModel(true); - strategy.setRestControllerStyle(true); - // 公共父类 -// strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!"); - // 写于父类中的公共字段 -// strategy.setSuperEntityColumns("id"); - strategy.setInclude(tableName.split(",")); - strategy.setControllerMappingHyphenStyle(true); - strategy.setLogicDeleteFieldName(logicDeleteFieldName); // 逻辑删除字段名称 - strategy.setTablePrefix(pc.getModuleName() + "_"); - mpg.setStrategy(strategy); - mpg.setTemplateEngine(new FreemarkerTemplateEngine()); - mpg.execute(); - } - -} \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_shiro/.gitignore b/jun_springboot_plugin/springboot_shiro/.gitignore deleted file mode 100644 index 1e3c5bbc80..0000000000 --- a/jun_springboot_plugin/springboot_shiro/.gitignore +++ /dev/null @@ -1,14 +0,0 @@ -# 此为注释– 将被Git 忽略 -# /结尾表示是目录,忽略目录和目录下的所有件 -# /开头表示根目录,否则是.gitignore的相对目录 -# !开头表示反选 -.idea/ -target/ -*.iml -*.ipr -*.iws -*.log -.svn/ -.project -rebel.xml -.rebel-remote.xml.* diff --git a/jun_springboot_plugin/springboot_shiro/README.md b/jun_springboot_plugin/springboot_shiro/README.md deleted file mode 100644 index a117cce0a2..0000000000 --- a/jun_springboot_plugin/springboot_shiro/README.md +++ /dev/null @@ -1,22 +0,0 @@ -## 集成Shiro权限管理 - -SpringBoot和Shiro集成,实现用户登录认证和授权访问页面。 - -## 数据库初始化 - -执行SQL文件`src/main/resources/sql/schema.sql` - -## 测试账号 - -1. admin/12345678 -2. aix/12345678 - -根据登录用户的不通角色可以看到不通的菜单 - -admin登录后可以看到用户管理菜单,aix登录后可以看到App管理、机具入网监控等业务系统菜单 - -## 许可证 - -Copyright (c) 2018 Xiong Neng - -基于 MIT 协议发布: diff --git a/jun_springboot_plugin/springboot_shiro/pom.xml b/jun_springboot_plugin/springboot_shiro/pom.xml deleted file mode 100644 index ce5e13f352..0000000000 --- a/jun_springboot_plugin/springboot_shiro/pom.xml +++ /dev/null @@ -1,177 +0,0 @@ - - - 4.0.0 - - io.github.wujun728 - springboot_shiro - 1.0 - jar - - 集成Shiro权限管理 - - - org.springframework.boot - spring-boot-starter-parent - 2.5.14 - - - - - UTF-8 - UTF-8 - 1.8 - 1.1.2 - 8.0.7-dmr - 2.1.8 - 1.0.5 - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - org.springframework.boot - spring-boot-starter-jetty - - - org.springframework.boot - spring-boot-starter-jdbc - - - mysql - mysql-connector-java - ${mysql-connector.version} - runtime - - - com.alibaba - druid - ${druid.version} - - - - com.baomidou - mybatis-plus - ${mybatis-plus.version} - - - com.baomidou - mybatisplus-spring-boot-starter - ${mybatisplus-spring-boot-starter.version} - - - - org.springframework.boot - spring-boot-starter-test - test - - - commons-io - commons-io - 2.5 - - - org.apache.commons - commons-lang3 - 3.7 - - - commons-codec - commons-codec - 1.11 - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - - com.github.theborakompanioni - thymeleaf-extras-shiro - 2.0.0 - - - - org.apache.shiro - shiro-spring - 1.4.0 - - - slf4j-api - org.slf4j - - - - - - org.apache.shiro - shiro-ehcache - 1.4.0 - - - slf4j-api - org.slf4j - - - - - - com.github.axet - kaptcha - 0.0.9 - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.6.1 - - - 1.8 - 1.8 - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.20 - - true - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - - - src/main/resources - - - src/main/java - - **/*.xml - - - - - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_shiro/run.sh b/jun_springboot_plugin/springboot_shiro/run.sh deleted file mode 100644 index 955efb1f86..0000000000 --- a/jun_springboot_plugin/springboot_shiro/run.sh +++ /dev/null @@ -1,72 +0,0 @@ -#!/bin/bash -# 项目自动更新脚本 -# 先clone相应的分支下来: -# git clone ssh://git@120.24.173.142:7999/xxx.git -# 远程调试启动: -# nohup java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005 -Xms512m -Xmx1024m -jar -Dspring.profiles.active=${profile} ${jarfile} >/dev/null 2>&1 & - -function start { - profile="$1" - echo "启动环境profile=${profile}" - jarfile=$(ls target/*.jar) - if [[ "$?" == "0" ]]; then - stop $profile $jarfile - fi - branch=$(git branch |awk '{print $2}') - git pull origin ${branch} - echo "更新完代码开始重新打包" - mvn clean && mvn clean && mvn package -DskipTests=true - if [[ "$?" != "0" ]]; then - echo "编译出错,退出!" - exit 1 - fi - echo "nohup java -Xms512m -Xmx1024m -jar -Dspring.profiles.active=${profile} ${jarfile} >/dev/null 2>&1 &" - nohup java -Xms512m -Xmx1024m -jar -Dspring.profiles.active=${profile} ${jarfile} >/dev/null 2>&1 & - echo "启动应用中,请查看日志文件..." -} - -function stop { - profile="$1" - jarfile="$2" - ps aux | grep "${jarfile}" | grep "spring.profiles.active=${profile}" | grep -v grep > /dev/null - if [[ "$?" == "0" ]]; then - echo "该应用还在跑,我先停了它" - pid=$(ps aux | grep "${jarfile}" | grep "spring.profiles.active=${profile}" | grep -v grep |awk '{print $2}') - if [[ "$pid" != "" ]]; then - kill -9 $pid - fi - echo "停止应用成功..." - fi -} - -if [[ "$1" == "start" ]]; then - if [[ "$#" < 2 ]]; then - echo "请输入正确参数:./epay.sh start {profile}" - exit 1 - fi - profile="$2" - if [[ "$profile" != "dev" && "$profile" != "test" && "$profile" != "show" && "$profile" != "production" ]]; then - echo "参数错误,请输入正确的profile参数,使用方法:" - echo "./epay.sh start {profile} ==> 启动应用,{profile}取值:dev|test|show|production" - exit 1 - fi - start "${profile}" -elif [[ "$1" == "stop" ]]; then - if [[ "$#" < 2 ]]; then - echo "请输入正确参数:./epay.sh stop {profile}" - exit 1 - fi - profile="$2" - if [[ "$profile" != "dev" && "$profile" != "test" && "$profile" != "show" && "$profile" != "production" ]]; then - echo "参数错误,请输入正确的profile参数,使用方法:" - echo "./epay.sh stop {profile} ==> 停止应用,{profile}取值:dev|test|show|production" - exit 1 - fi - jarfile=$(ls target/*.jar) - stop $profile $jarfile -else - echo "参数错误,使用方法:{}参数是必填的,[]参数可选" - echo "./epay.sh start {profile} ==> 启动应用,{profile}取值:dev|test|show|production" - echo "./epay.sh stop {profile} ==> 停止应用,{profile}取值:dev|test|show|production" - exit 1 -fi diff --git a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/Application.java b/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/Application.java deleted file mode 100644 index adc4c48d75..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/Application.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.xncoding.pos; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class Application { - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} diff --git a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/common/dao/entity/Manager.java b/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/common/dao/entity/Manager.java deleted file mode 100644 index 459d06af8d..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/common/dao/entity/Manager.java +++ /dev/null @@ -1,249 +0,0 @@ -package com.xncoding.pos.common.dao.entity; - -import java.util.Date; -import com.baomidou.mybatisplus.annotations.TableName; -import com.baomidou.mybatisplus.enums.IdType; -import com.baomidou.mybatisplus.annotations.TableId; -import com.baomidou.mybatisplus.activerecord.Model; -import java.io.Serializable; - -/** - * 后台管理用户表 - * - * @author 熊能 - * @version 1.0 - * @since 2018/01/02 - */ -@TableName(value = "t_manager") -public class Manager extends Model { - -private static final long serialVersionUID = 1L; - - /** - * 主键ID - */ - @TableId(value="id", type= IdType.AUTO) - private Integer id; - /** - * 账号 - */ - private String username; - /** - * 名字 - */ - private String name; - /** - * 密码 - */ - private String password; - /** - * md5密码盐 - */ - private String salt; - /** - * 联系电话 - */ - private String phone; - /** - * 备注 - */ - private String tips; - /** - * 状态 1:正常 2:禁用 - */ - private Integer state; - /** - * 创建时间 - */ - private Date createdTime; - /** - * 更新时间 - */ - private Date updatedTime; - - /** - * 获取 主键ID. - * - * @return 主键ID. - */ - public Integer getId() { - return id; - } - - /** - * 设置 主键ID. - * - * @param id 主键ID. - */ - public void setId(Integer id) { - this.id = id; - } - - /** - * 获取 账号. - * - * @return 账号. - */ - public String getUsername() { - return username; - } - - /** - * 设置 账号. - * - * @param username 账号. - */ - public void setUsername(String username) { - this.username = username; - } - - /** - * 获取 名字. - * - * @return 名字. - */ - public String getName() { - return name; - } - - /** - * 设置 名字. - * - * @param name 名字. - */ - public void setName(String name) { - this.name = name; - } - - /** - * 获取 密码. - * - * @return 密码. - */ - public String getPassword() { - return password; - } - - /** - * 设置 密码. - * - * @param password 密码. - */ - public void setPassword(String password) { - this.password = password; - } - - /** - * 获取 md5密码盐. - * - * @return md5密码盐. - */ - public String getSalt() { - return salt; - } - - /** - * 设置 md5密码盐. - * - * @param salt md5密码盐. - */ - public void setSalt(String salt) { - this.salt = salt; - } - - /** - * 获取 联系电话. - * - * @return 联系电话. - */ - public String getPhone() { - return phone; - } - - /** - * 设置 联系电话. - * - * @param phone 联系电话. - */ - public void setPhone(String phone) { - this.phone = phone; - } - - /** - * 获取 备注. - * - * @return 备注. - */ - public String getTips() { - return tips; - } - - /** - * 设置 备注. - * - * @param tips 备注. - */ - public void setTips(String tips) { - this.tips = tips; - } - - /** - * 获取 状态 1:正常 2:禁用. - * - * @return 状态 1:正常 2:禁用. - */ - public Integer getState() { - return state; - } - - /** - * 设置 状态 1:正常 2:禁用. - * - * @param state 状态 1:正常 2:禁用. - */ - public void setState(Integer state) { - this.state = state; - } - - /** - * 获取 创建时间. - * - * @return 创建时间. - */ - public Date getCreatedTime() { - return createdTime; - } - - /** - * 设置 创建时间. - * - * @param createdTime 创建时间. - */ - public void setCreatedTime(Date createdTime) { - this.createdTime = createdTime; - } - - /** - * 获取 更新时间. - * - * @return 更新时间. - */ - public Date getUpdatedTime() { - return updatedTime; - } - - /** - * 设置 更新时间. - * - * @param updatedTime 更新时间. - */ - public void setUpdatedTime(Date updatedTime) { - this.updatedTime = updatedTime; - } - - @Override - protected Serializable pkVal() { - return this.id; - } - -} diff --git a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/common/dao/entity/ManagerRole.java b/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/common/dao/entity/ManagerRole.java deleted file mode 100644 index 84904b6804..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/common/dao/entity/ManagerRole.java +++ /dev/null @@ -1,139 +0,0 @@ -package com.xncoding.pos.common.dao.entity; - -import java.util.Date; -import com.baomidou.mybatisplus.annotations.TableName; -import com.baomidou.mybatisplus.enums.IdType; -import com.baomidou.mybatisplus.annotations.TableId; -import com.baomidou.mybatisplus.activerecord.Model; -import java.io.Serializable; - -/** - * 用户角色关联表 - * - * @author 熊能 - * @version 1.0 - * @since 2018/01/02 - */ -@TableName(value = "t_manager_role") -public class ManagerRole extends Model { - -private static final long serialVersionUID = 1L; - - /** - * 主键ID - */ - @TableId(value="id", type= IdType.AUTO) - private Integer id; - /** - * 管理用户ID - */ - private Integer managerId; - /** - * 角色ID - */ - private Integer roleId; - /** - * 创建时间 - */ - private Date createdTime; - /** - * 更新时间 - */ - private Date updatedTime; - - /** - * 获取 主键ID. - * - * @return 主键ID. - */ - public Integer getId() { - return id; - } - - /** - * 设置 主键ID. - * - * @param id 主键ID. - */ - public void setId(Integer id) { - this.id = id; - } - - /** - * 获取 管理用户ID. - * - * @return 管理用户ID. - */ - public Integer getManagerId() { - return managerId; - } - - /** - * 设置 管理用户ID. - * - * @param managerId 管理用户ID. - */ - public void setManagerId(Integer managerId) { - this.managerId = managerId; - } - - /** - * 获取 角色ID. - * - * @return 角色ID. - */ - public Integer getRoleId() { - return roleId; - } - - /** - * 设置 角色ID. - * - * @param roleId 角色ID. - */ - public void setRoleId(Integer roleId) { - this.roleId = roleId; - } - - /** - * 获取 创建时间. - * - * @return 创建时间. - */ - public Date getCreatedTime() { - return createdTime; - } - - /** - * 设置 创建时间. - * - * @param createdTime 创建时间. - */ - public void setCreatedTime(Date createdTime) { - this.createdTime = createdTime; - } - - /** - * 获取 更新时间. - * - * @return 更新时间. - */ - public Date getUpdatedTime() { - return updatedTime; - } - - /** - * 设置 更新时间. - * - * @param updatedTime 更新时间. - */ - public void setUpdatedTime(Date updatedTime) { - this.updatedTime = updatedTime; - } - - @Override - protected Serializable pkVal() { - return this.id; - } - -} diff --git a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/common/dao/entity/Permission.java b/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/common/dao/entity/Permission.java deleted file mode 100644 index 1c79b9c030..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/common/dao/entity/Permission.java +++ /dev/null @@ -1,139 +0,0 @@ -package com.xncoding.pos.common.dao.entity; - -import java.util.Date; -import com.baomidou.mybatisplus.annotations.TableName; -import com.baomidou.mybatisplus.enums.IdType; -import com.baomidou.mybatisplus.annotations.TableId; -import com.baomidou.mybatisplus.activerecord.Model; -import java.io.Serializable; - -/** - * 权限表 - * - * @author 熊能 - * @version 1.0 - * @since 2018/01/02 - */ -@TableName(value = "t_permission") -public class Permission extends Model { - -private static final long serialVersionUID = 1L; - - /** - * 主键ID - */ - @TableId(value="id", type= IdType.AUTO) - private Integer id; - /** - * 权限名称 - */ - private String permission; - /** - * 权限说明 - */ - private String description; - /** - * 创建时间 - */ - private Date createdTime; - /** - * 更新时间 - */ - private Date updatedTime; - - /** - * 获取 主键ID. - * - * @return 主键ID. - */ - public Integer getId() { - return id; - } - - /** - * 设置 主键ID. - * - * @param id 主键ID. - */ - public void setId(Integer id) { - this.id = id; - } - - /** - * 获取 权限名称. - * - * @return 权限名称. - */ - public String getPermission() { - return permission; - } - - /** - * 设置 权限名称. - * - * @param permission 权限名称. - */ - public void setPermission(String permission) { - this.permission = permission; - } - - /** - * 获取 权限说明. - * - * @return 权限说明. - */ - public String getDescription() { - return description; - } - - /** - * 设置 权限说明. - * - * @param description 权限说明. - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * 获取 创建时间. - * - * @return 创建时间. - */ - public Date getCreatedTime() { - return createdTime; - } - - /** - * 设置 创建时间. - * - * @param createdTime 创建时间. - */ - public void setCreatedTime(Date createdTime) { - this.createdTime = createdTime; - } - - /** - * 获取 更新时间. - * - * @return 更新时间. - */ - public Date getUpdatedTime() { - return updatedTime; - } - - /** - * 设置 更新时间. - * - * @param updatedTime 更新时间. - */ - public void setUpdatedTime(Date updatedTime) { - this.updatedTime = updatedTime; - } - - @Override - protected Serializable pkVal() { - return this.id; - } - -} diff --git a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/common/dao/entity/Role.java b/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/common/dao/entity/Role.java deleted file mode 100644 index def68f81e5..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/common/dao/entity/Role.java +++ /dev/null @@ -1,139 +0,0 @@ -package com.xncoding.pos.common.dao.entity; - -import java.util.Date; -import com.baomidou.mybatisplus.annotations.TableName; -import com.baomidou.mybatisplus.enums.IdType; -import com.baomidou.mybatisplus.annotations.TableId; -import com.baomidou.mybatisplus.activerecord.Model; -import java.io.Serializable; - -/** - * 角色表 - * - * @author 熊能 - * @version 1.0 - * @since 2018/01/02 - */ -@TableName(value = "t_role") -public class Role extends Model { - -private static final long serialVersionUID = 1L; - - /** - * 主键ID - */ - @TableId(value="id", type= IdType.AUTO) - private Integer id; - /** - * 角色名称 - */ - private String role; - /** - * 角色说明 - */ - private String description; - /** - * 创建时间 - */ - private Date createdTime; - /** - * 更新时间 - */ - private Date updatedTime; - - /** - * 获取 主键ID. - * - * @return 主键ID. - */ - public Integer getId() { - return id; - } - - /** - * 设置 主键ID. - * - * @param id 主键ID. - */ - public void setId(Integer id) { - this.id = id; - } - - /** - * 获取 角色名称. - * - * @return 角色名称. - */ - public String getRole() { - return role; - } - - /** - * 设置 角色名称. - * - * @param role 角色名称. - */ - public void setRole(String role) { - this.role = role; - } - - /** - * 获取 角色说明. - * - * @return 角色说明. - */ - public String getDescription() { - return description; - } - - /** - * 设置 角色说明. - * - * @param description 角色说明. - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * 获取 创建时间. - * - * @return 创建时间. - */ - public Date getCreatedTime() { - return createdTime; - } - - /** - * 设置 创建时间. - * - * @param createdTime 创建时间. - */ - public void setCreatedTime(Date createdTime) { - this.createdTime = createdTime; - } - - /** - * 获取 更新时间. - * - * @return 更新时间. - */ - public Date getUpdatedTime() { - return updatedTime; - } - - /** - * 设置 更新时间. - * - * @param updatedTime 更新时间. - */ - public void setUpdatedTime(Date updatedTime) { - this.updatedTime = updatedTime; - } - - @Override - protected Serializable pkVal() { - return this.id; - } - -} diff --git a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/common/dao/entity/RolePermission.java b/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/common/dao/entity/RolePermission.java deleted file mode 100644 index 68be589a0a..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/common/dao/entity/RolePermission.java +++ /dev/null @@ -1,139 +0,0 @@ -package com.xncoding.pos.common.dao.entity; - -import java.util.Date; -import com.baomidou.mybatisplus.annotations.TableName; -import com.baomidou.mybatisplus.enums.IdType; -import com.baomidou.mybatisplus.annotations.TableId; -import com.baomidou.mybatisplus.activerecord.Model; -import java.io.Serializable; - -/** - * 角色权限关联表 - * - * @author 熊能 - * @version 1.0 - * @since 2018/01/02 - */ -@TableName(value = "t_role_permission") -public class RolePermission extends Model { - -private static final long serialVersionUID = 1L; - - /** - * 主键ID - */ - @TableId(value="id", type= IdType.AUTO) - private Integer id; - /** - * 角色ID - */ - private Integer roleId; - /** - * 权限ID - */ - private Integer permissionId; - /** - * 创建时间 - */ - private Date createdTime; - /** - * 更新时间 - */ - private Date updatedTime; - - /** - * 获取 主键ID. - * - * @return 主键ID. - */ - public Integer getId() { - return id; - } - - /** - * 设置 主键ID. - * - * @param id 主键ID. - */ - public void setId(Integer id) { - this.id = id; - } - - /** - * 获取 角色ID. - * - * @return 角色ID. - */ - public Integer getRoleId() { - return roleId; - } - - /** - * 设置 角色ID. - * - * @param roleId 角色ID. - */ - public void setRoleId(Integer roleId) { - this.roleId = roleId; - } - - /** - * 获取 权限ID. - * - * @return 权限ID. - */ - public Integer getPermissionId() { - return permissionId; - } - - /** - * 设置 权限ID. - * - * @param permissionId 权限ID. - */ - public void setPermissionId(Integer permissionId) { - this.permissionId = permissionId; - } - - /** - * 获取 创建时间. - * - * @return 创建时间. - */ - public Date getCreatedTime() { - return createdTime; - } - - /** - * 设置 创建时间. - * - * @param createdTime 创建时间. - */ - public void setCreatedTime(Date createdTime) { - this.createdTime = createdTime; - } - - /** - * 获取 更新时间. - * - * @return 更新时间. - */ - public Date getUpdatedTime() { - return updatedTime; - } - - /** - * 设置 更新时间. - * - * @param updatedTime 更新时间. - */ - public void setUpdatedTime(Date updatedTime) { - this.updatedTime = updatedTime; - } - - @Override - protected Serializable pkVal() { - return this.id; - } - -} diff --git a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/common/dao/repository/ManagerMapper.java b/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/common/dao/repository/ManagerMapper.java deleted file mode 100644 index 037d8a66a3..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/common/dao/repository/ManagerMapper.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.xncoding.pos.common.dao.repository; - -import com.xncoding.pos.common.dao.entity.Manager; -import com.baomidou.mybatisplus.mapper.BaseMapper; - -/** - * 后台管理用户表 Mapper - * - * @author 熊能 - * @version 1.0 - * @since 2018/01/02 - */ -public interface ManagerMapper extends BaseMapper { - -} diff --git a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/common/dao/repository/ManagerRoleMapper.java b/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/common/dao/repository/ManagerRoleMapper.java deleted file mode 100644 index 708c1f619e..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/common/dao/repository/ManagerRoleMapper.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.xncoding.pos.common.dao.repository; - -import com.xncoding.pos.common.dao.entity.ManagerRole; -import com.baomidou.mybatisplus.mapper.BaseMapper; - -/** - * 用户角色关联表 Mapper - * - * @author 熊能 - * @version 1.0 - * @since 2018/01/02 - */ -public interface ManagerRoleMapper extends BaseMapper { - -} diff --git a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/common/dao/repository/PermissionMapper.java b/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/common/dao/repository/PermissionMapper.java deleted file mode 100644 index e32d42a354..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/common/dao/repository/PermissionMapper.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.xncoding.pos.common.dao.repository; - -import com.xncoding.pos.common.dao.entity.Permission; -import com.baomidou.mybatisplus.mapper.BaseMapper; - -/** - * 权限表 Mapper - * - * @author 熊能 - * @version 1.0 - * @since 2018/01/02 - */ -public interface PermissionMapper extends BaseMapper { - -} diff --git a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/common/dao/repository/RoleMapper.java b/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/common/dao/repository/RoleMapper.java deleted file mode 100644 index effb8c00c4..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/common/dao/repository/RoleMapper.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.xncoding.pos.common.dao.repository; - -import com.xncoding.pos.common.dao.entity.Role; -import com.baomidou.mybatisplus.mapper.BaseMapper; - -/** - * 角色表 Mapper - * - * @author 熊能 - * @version 1.0 - * @since 2018/01/02 - */ -public interface RoleMapper extends BaseMapper { - -} diff --git a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/common/dao/repository/RolePermissionMapper.java b/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/common/dao/repository/RolePermissionMapper.java deleted file mode 100644 index 4f3506d6e8..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/common/dao/repository/RolePermissionMapper.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.xncoding.pos.common.dao.repository; - -import com.xncoding.pos.common.dao.entity.RolePermission; -import com.baomidou.mybatisplus.mapper.BaseMapper; - -/** - * 角色权限关联表 Mapper - * - * @author 熊能 - * @version 1.0 - * @since 2018/01/02 - */ -public interface RolePermissionMapper extends BaseMapper { - -} diff --git a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/config/MybatisPlusConfig.java b/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/config/MybatisPlusConfig.java deleted file mode 100644 index 1d92892d2e..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/config/MybatisPlusConfig.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.xncoding.pos.config; - -import com.alibaba.druid.pool.DruidDataSource; -import com.baomidou.mybatisplus.plugins.PaginationInterceptor; -import com.xncoding.pos.config.properties.DruidProperties; -import org.mybatis.spring.annotation.MapperScan; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -import javax.annotation.Resource; - -/** - * MybatisPlus配置 - * - * @author xiongneng - * @since 2017/5/20 21:58 - */ -@Configuration -@EnableTransactionManagement(order = 2) -@MapperScan(basePackages = { - "com.xncoding.pos.common.dao.repository", - "com.xncoding.pos.dao.repository"}) -public class MybatisPlusConfig { - - @Resource - private DruidProperties druidProperties; - - /** - * 单数据源连接池配置 - */ - @Bean - public DruidDataSource singleDatasource() { - DruidDataSource dataSource = new DruidDataSource(); - druidProperties.config(dataSource); - return dataSource; - } - - /** - * mybatis-plus分页插件 - */ - @Bean - public PaginationInterceptor paginationInterceptor() { - return new PaginationInterceptor(); - } -} diff --git a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/config/ShiroConfig.java b/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/config/ShiroConfig.java deleted file mode 100644 index d65c99aa28..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/config/ShiroConfig.java +++ /dev/null @@ -1,277 +0,0 @@ -package com.xncoding.pos.config; - -import at.pollux.thymeleaf.shiro.dialect.ShiroDialect; -import com.google.code.kaptcha.Constants; -import com.google.code.kaptcha.servlet.KaptchaServlet; -import com.xncoding.pos.shiro.KaptchaFilter; -import com.xncoding.pos.shiro.MyExceptionResolver; -import com.xncoding.pos.shiro.MyShiroRealm; -import org.apache.shiro.authc.credential.HashedCredentialsMatcher; -import org.apache.shiro.cache.ehcache.EhCacheManager; -import org.apache.shiro.mgt.SecurityManager; -import org.apache.shiro.session.mgt.ExecutorServiceSessionValidationScheduler; -import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; -import org.apache.shiro.spring.web.ShiroFilterFactoryBean; -import org.apache.shiro.web.mgt.CookieRememberMeManager; -import org.apache.shiro.web.mgt.DefaultWebSecurityManager; -import org.apache.shiro.web.servlet.SimpleCookie; -import org.apache.shiro.web.session.mgt.DefaultWebSessionManager; -import org.springframework.boot.web.servlet.ServletRegistrationBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.annotation.Order; - -import javax.servlet.Filter; -import java.util.LinkedHashMap; -import java.util.Map; - -/** - * Description : Apache Shiro 核心通过 Filter 来实现,就好像SpringMvc 通过DispachServlet 来主控制一样。 - * 既然是使用 Filter 一般也就能猜到,是通过URL规则来进行过滤和权限校验,所以我们需要定义一系列关于URL的规则和访问权限。 - */ - -@Configuration -@Order(1) -public class ShiroConfig { - - //配置kaptcha图片验证码框架提供的Servlet,,这是个坑,很多人忘记注册(注意) - @Bean - public ServletRegistrationBean kaptchaServlet() { - ServletRegistrationBean servlet = new ServletRegistrationBean(new KaptchaServlet(), "/kaptcha.jpg"); - servlet.addInitParameter(Constants.KAPTCHA_SESSION_CONFIG_KEY, Constants.KAPTCHA_SESSION_KEY);//session key - servlet.addInitParameter(Constants.KAPTCHA_TEXTPRODUCER_FONT_SIZE, "50");//字体大小 - servlet.addInitParameter(Constants.KAPTCHA_BORDER, "no"); - servlet.addInitParameter(Constants.KAPTCHA_BORDER_COLOR, "105,179,90"); - servlet.addInitParameter(Constants.KAPTCHA_TEXTPRODUCER_FONT_SIZE, "45"); - servlet.addInitParameter(Constants.KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "4"); - servlet.addInitParameter(Constants.KAPTCHA_TEXTPRODUCER_FONT_NAMES, "宋体,楷体,微软雅黑"); - servlet.addInitParameter(Constants.KAPTCHA_TEXTPRODUCER_FONT_COLOR, "blue"); - servlet.addInitParameter(Constants.KAPTCHA_IMAGE_WIDTH, "125"); - servlet.addInitParameter(Constants.KAPTCHA_IMAGE_HEIGHT, "60"); - //可以设置很多属性,具体看com.google.code.kaptcha.Constants -// kaptcha.border 是否有边框 默认为true 我们可以自己设置yes,no -// kaptcha.border.color 边框颜色 默认为Color.BLACK -// kaptcha.border.thickness 边框粗细度 默认为1 -// kaptcha.producer.impl 验证码生成器 默认为DefaultKaptcha -// kaptcha.textproducer.impl 验证码文本生成器 默认为DefaultTextCreator -// kaptcha.textproducer.char.string 验证码文本字符内容范围 默认为abcde2345678gfynmnpwx -// kaptcha.textproducer.char.length 验证码文本字符长度 默认为5 -// kaptcha.textproducer.font.names 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize) -// kaptcha.textproducer.font.size 验证码文本字符大小 默认为40 -// kaptcha.textproducer.font.color 验证码文本字符颜色 默认为Color.BLACK -// kaptcha.textproducer.char.space 验证码文本字符间距 默认为2 -// kaptcha.noise.impl 验证码噪点生成对象 默认为DefaultNoise -// kaptcha.noise.color 验证码噪点颜色 默认为Color.BLACK -// kaptcha.obscurificator.impl 验证码样式引擎 默认为WaterRipple -// kaptcha.word.impl 验证码文本字符渲染 默认为DefaultWordRenderer -// kaptcha.background.impl 验证码背景生成器 默认为DefaultBackground -// kaptcha.background.clear.from 验证码背景颜色渐进 默认为Color.LIGHT_GRAY -// kaptcha.background.clear.to 验证码背景颜色渐进 默认为Color.WHITE -// kaptcha.image.width 验证码图片宽度 默认为200 -// kaptcha.image.height 验证码图片高度 默认为50 - return servlet; - } - - //注入异常处理类 - @Bean - public MyExceptionResolver myExceptionResolver() { - return new MyExceptionResolver(); - } - - /** - * ShiroFilterFactoryBean 处理拦截资源文件问题。 - * 注意:单独一个ShiroFilterFactoryBean配置是或报错的,以为在 - * 初始化ShiroFilterFactoryBean的时候需要注入:SecurityManager Filter Chain定义说明 - * 1、一个URL可以配置多个Filter,使用逗号分隔 - * 2、当设置多个过滤器时,全部验证通过,才视为通过 - * 3、部分过滤器可指定参数,如perms,roles - */ - @Bean - public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) { - - ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); - // 必须设置 SecurityManager - shiroFilterFactoryBean.setSecurityManager(securityManager); - //验证码过滤器 - Map filtersMap = shiroFilterFactoryBean.getFilters(); - KaptchaFilter kaptchaFilter = new KaptchaFilter(); - filtersMap.put("kaptchaFilter", kaptchaFilter); - //实现自己规则roles,这是为了实现or的效果 - //RoleFilter roleFilter = new RoleFilter(); - //filtersMap.put("roles", roleFilter); - shiroFilterFactoryBean.setFilters(filtersMap); - // 拦截器 - //rest:比如/admins/user/**=rest[user],根据请求的方法,相当于/admins/user/**=perms[user:method] ,其中method为post,get,delete等。 - //port:比如/admins/user/**=port[8081],当请求的url的端口不是8081是跳转到schemal://serverName:8081?queryString,其中schmal是协议http或https等,serverName是你访问的host,8081是url配置里port的端口,queryString是你访问的url里的?后面的参数。 - //perms:比如/admins/user/**=perms[user:add:*],perms参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,比如/admins/user/**=perms["user:add:*,user:modify:*"],当有多个参数时必须每个参数都通过才通过,想当于isPermitedAll()方法。 - //roles:比如/admins/user/**=roles[admin],参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,当有多个参数时,比如/admins/user/**=roles["admin,guest"],每个参数通过才算通过,相当于hasAllRoles()方法。//要实现or的效果看http://zgzty.blog.163.com/blog/static/83831226201302983358670/ - //anon:比如/admins/**=anon 没有参数,表示可以匿名使用。 - //authc:比如/admins/user/**=authc表示需要认证才能使用,没有参数 - //authcBasic:比如/admins/user/**=authcBasic没有参数表示httpBasic认证 - //ssl:比如/admins/user/**=ssl没有参数,表示安全的url请求,协议为https - //user:比如/admins/user/**=user没有参数表示必须存在用户,当登入操作时不做检查 - Map filterChainDefinitionMap = new LinkedHashMap(); - // 配置退出过滤器,其中的具体的退出代码Shiro已经替我们实现了 - filterChainDefinitionMap.put("/logout", "logout"); - //配置记住我或认证通过可以访问的地址 - filterChainDefinitionMap.put("/index", "user"); - filterChainDefinitionMap.put("/", "user"); - filterChainDefinitionMap.put("/login", "kaptchaFilter"); - // :这是一个坑呢,一不小心代码就不好使了; - //这段是配合 actuator框架使用的,配置相应的角色才能访问 - // filterChainDefinitionMap.put("/health", "roles[aix]");//服务器健康状况页面 - // filterChainDefinitionMap.put("/info", "roles[aix]");//服务器信息页面 - // filterChainDefinitionMap.put("/env", "roles[aix]");//应用程序的环境变量 - // filterChainDefinitionMap.put("/metrics", "roles[aix]"); - // filterChainDefinitionMap.put("/configprops", "roles[aix]"); - //开放的静态资源 - filterChainDefinitionMap.put("/favicon.ico", "anon");//网站图标 - filterChainDefinitionMap.put("/static/**", "anon");//配置static文件下资源能被访问的,这是个例子 - filterChainDefinitionMap.put("/kaptcha.jpg", "anon");//图片验证码(kaptcha框架) - - filterChainDefinitionMap.put("/api/v1/**", "anon");//API接口 - - // swagger接口文档 - filterChainDefinitionMap.put("/v2/api-docs", "anon"); - filterChainDefinitionMap.put("/webjars/**", "anon"); - filterChainDefinitionMap.put("/swagger-resources/**", "anon"); - filterChainDefinitionMap.put("/swagger-ui.html", "anon"); - filterChainDefinitionMap.put("/doc.html", "anon"); - - // 其他的 - filterChainDefinitionMap.put("/**", "authc"); - - // 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面 - shiroFilterFactoryBean.setLoginUrl("/login"); - // 登录成功后要跳转的链接 - shiroFilterFactoryBean.setSuccessUrl("/index"); - // 未授权界面,不生效(详情原因看MyExceptionResolver) - shiroFilterFactoryBean.setUnauthorizedUrl("/errorView/403_error.html"); - shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); - return shiroFilterFactoryBean; - } - - @Bean - public SecurityManager securityManager() { - DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); - // 设置realm. - securityManager.setRealm(myShiroRealm()); - //注入缓存管理器 - securityManager.setCacheManager(ehCacheManager());//这个如果执行多次,也是同样的一个对象; - //注入记住我管理器; - securityManager.setRememberMeManager(rememberMeManager()); - return securityManager; - } - - /** - * 身份认证realm; (这个需要自己写,账号密码校验;权限等) - */ - @Bean - public MyShiroRealm myShiroRealm() { - MyShiroRealm myShiroRealm = new MyShiroRealm(); - myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher()); - return myShiroRealm; - } - - /** - * 凭证匹配器 (由于我们的密码校验交给Shiro的SimpleAuthenticationInfo进行处理了 - * 所以我们需要修改下doGetAuthenticationInfo中的代码; @return - */ - @Bean - public HashedCredentialsMatcher hashedCredentialsMatcher() { - HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher(); - hashedCredentialsMatcher.setHashAlgorithmName("md5");// 散列算法:这里使用MD5算法; - hashedCredentialsMatcher.setHashIterations(2);// 散列的次数,比如散列两次,相当于md5(md5("")); - hashedCredentialsMatcher.setStoredCredentialsHexEncoded(true);//表示是否存储散列后的密码为16进制,需要和生成密码时的一样,默认是base64; - return hashedCredentialsMatcher; - } - - /** - * 开启shiro aop注解支持. 使用代理方式; 所以需要开启代码支持; - * - * @param securityManager - * @return - */ - @Bean - public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) { - AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); - authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); - return authorizationAttributeSourceAdvisor; - } - - /** - * shiro缓存管理器; - * 需要注入对应的其它的实体类中: - * 1、安全管理器:securityManager - * 可见securityManager是整个shiro的核心; - * - * @return - */ - @Bean - public EhCacheManager ehCacheManager() { - EhCacheManager cacheManager = new EhCacheManager(); - cacheManager.setCacheManagerConfigFile("classpath:ehcache.xml"); - return cacheManager; - } - - /** - * cookie对象; - * - * @return - */ - @Bean - public SimpleCookie rememberMeCookie() { - //System.out.println("ShiroConfiguration.rememberMeCookie()"); - //这个参数是cookie的名称,对应前端的checkbox的name = rememberMe - SimpleCookie simpleCookie = new SimpleCookie("rememberMe"); - // - simpleCookie.setMaxAge(259200); - return simpleCookie; - } - - /** - * cookie管理对象; - * - * @return - */ - @Bean - public CookieRememberMeManager rememberMeManager() { - //System.out.println("ShiroConfiguration.rememberMeManager()"); - CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager(); - cookieRememberMeManager.setCookie(rememberMeCookie()); - return cookieRememberMeManager; - } - - @Bean(name = "sessionManager") - public DefaultWebSessionManager defaultWebSessionManager() { - DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); - sessionManager.setGlobalSessionTimeout(18000000); - // url中是否显示session Id - sessionManager.setSessionIdUrlRewritingEnabled(false); - // 删除失效的session - sessionManager.setDeleteInvalidSessions(true); - sessionManager.setSessionValidationSchedulerEnabled(true); - sessionManager.setSessionValidationInterval(18000000); - sessionManager.setSessionValidationScheduler(getExecutorServiceSessionValidationScheduler()); - //设置SessionIdCookie 导致认证不成功,不从新设置新的cookie,从sessionManager获取sessionIdCookie - //sessionManager.setSessionIdCookie(simpleIdCookie()); - sessionManager.getSessionIdCookie().setName("session-z-id"); - sessionManager.getSessionIdCookie().setPath("/"); - sessionManager.getSessionIdCookie().setMaxAge(60 * 60 * 24 * 7); - return sessionManager; - } - - @Bean(name = "sessionValidationScheduler") - public ExecutorServiceSessionValidationScheduler getExecutorServiceSessionValidationScheduler() { - ExecutorServiceSessionValidationScheduler scheduler = new ExecutorServiceSessionValidationScheduler(); - scheduler.setInterval(900000); - return scheduler; - } - - @Bean(name = "shiroDialect") - public ShiroDialect shiroDialect() { - return new ShiroDialect(); - } - - -} diff --git a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/config/properties/DruidProperties.java b/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/config/properties/DruidProperties.java deleted file mode 100644 index 7cb442496d..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/config/properties/DruidProperties.java +++ /dev/null @@ -1,249 +0,0 @@ -package com.xncoding.pos.config.properties; - -import com.alibaba.druid.pool.DruidDataSource; -import com.alibaba.druid.util.JdbcConstants; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; - -import java.sql.SQLException; - -/** - *

    数据库数据源配置

    - *

    说明:这个类中包含了许多默认配置,若这些配置符合您的情况,您可以不用管,若不符合,建议不要修改本类,建议直接在"application.yml"中配置即可

    - * - * @author xiongneng - * @since 2017-05-21 11:18 - */ -@Component -@ConfigurationProperties(prefix = "spring.datasource") -public class DruidProperties { - - private String url; - - private String username; - - private String password; - - private String driverClassName = "com.mysql.cj.jdbc.Driver"; - - private Integer initialSize = 10; - - private Integer minIdle = 3; - - private Integer maxActive = 60; - - private Integer maxWait = 60000; - - private Boolean removeAbandoned = true; - - private Integer removeAbandonedTimeout = 180; - - private Integer timeBetweenEvictionRunsMillis = 60000; - - private Integer minEvictableIdleTimeMillis = 300000; - - private String validationQuery = "SELECT 'x'"; - - private Boolean testWhileIdle = true; - - private Boolean testOnBorrow = false; - - private Boolean testOnReturn = false; - - private Boolean poolPreparedStatements = true; - - private Integer maxPoolPreparedStatementPerConnectionSize = 50; - - private String filters = "stat"; - - public void config(DruidDataSource dataSource) { - dataSource.setDbType(JdbcConstants.MYSQL); - dataSource.setUrl(url); - dataSource.setUsername(username); - dataSource.setPassword(password); - dataSource.setDriverClassName(driverClassName); - dataSource.setInitialSize(initialSize); // 定义初始连接数 - dataSource.setMinIdle(minIdle); // 最小空闲 - dataSource.setMaxActive(maxActive); // 定义最大连接数 - dataSource.setMaxWait(maxWait); // 获取连接等待超时的时间 - dataSource.setRemoveAbandoned(removeAbandoned); // 超过时间限制是否回收 - dataSource.setRemoveAbandonedTimeout(removeAbandonedTimeout); // 超过时间限制多长 - - // 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 - dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); - // 配置一个连接在池中最小生存的时间,单位是毫秒 - dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); - // 用来检测连接是否有效的sql,要求是一个查询语句 - dataSource.setValidationQuery(validationQuery); - // 申请连接的时候检测 - dataSource.setTestWhileIdle(testWhileIdle); - // 申请连接时执行validationQuery检测连接是否有效,配置为true会降低性能 - dataSource.setTestOnBorrow(testOnBorrow); - // 归还连接时执行validationQuery检测连接是否有效,配置为true会降低性能 - dataSource.setTestOnReturn(testOnReturn); - // 打开PSCache,并且指定每个连接上PSCache的大小 - dataSource.setPoolPreparedStatements(poolPreparedStatements); - dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize); - // 属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有: - // 监控统计用的filter:stat - // 日志用的filter:log4j - // 防御SQL注入的filter:wall - try { - dataSource.setFilters(filters); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getDriverClassName() { - return driverClassName; - } - - public void setDriverClassName(String driverClassName) { - this.driverClassName = driverClassName; - } - - public Integer getInitialSize() { - return initialSize; - } - - public void setInitialSize(Integer initialSize) { - this.initialSize = initialSize; - } - - public Integer getMinIdle() { - return minIdle; - } - - public void setMinIdle(Integer minIdle) { - this.minIdle = minIdle; - } - - public Integer getMaxActive() { - return maxActive; - } - - public void setMaxActive(Integer maxActive) { - this.maxActive = maxActive; - } - - public Integer getMaxWait() { - return maxWait; - } - - public void setMaxWait(Integer maxWait) { - this.maxWait = maxWait; - } - - public Integer getTimeBetweenEvictionRunsMillis() { - return timeBetweenEvictionRunsMillis; - } - - public void setTimeBetweenEvictionRunsMillis(Integer timeBetweenEvictionRunsMillis) { - this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; - } - - public Integer getMinEvictableIdleTimeMillis() { - return minEvictableIdleTimeMillis; - } - - public void setMinEvictableIdleTimeMillis(Integer minEvictableIdleTimeMillis) { - this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; - } - - public String getValidationQuery() { - return validationQuery; - } - - public void setValidationQuery(String validationQuery) { - this.validationQuery = validationQuery; - } - - public Boolean getTestWhileIdle() { - return testWhileIdle; - } - - public void setTestWhileIdle(Boolean testWhileIdle) { - this.testWhileIdle = testWhileIdle; - } - - public Boolean getTestOnBorrow() { - return testOnBorrow; - } - - public void setTestOnBorrow(Boolean testOnBorrow) { - this.testOnBorrow = testOnBorrow; - } - - public Boolean getTestOnReturn() { - return testOnReturn; - } - - public void setTestOnReturn(Boolean testOnReturn) { - this.testOnReturn = testOnReturn; - } - - public Boolean getPoolPreparedStatements() { - return poolPreparedStatements; - } - - public void setPoolPreparedStatements(Boolean poolPreparedStatements) { - this.poolPreparedStatements = poolPreparedStatements; - } - - public Integer getMaxPoolPreparedStatementPerConnectionSize() { - return maxPoolPreparedStatementPerConnectionSize; - } - - public void setMaxPoolPreparedStatementPerConnectionSize(Integer maxPoolPreparedStatementPerConnectionSize) { - this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize; - } - - public String getFilters() { - return filters; - } - - public void setFilters(String filters) { - this.filters = filters; - } - - public Boolean getRemoveAbandoned() { - return removeAbandoned; - } - - public void setRemoveAbandoned(Boolean removeAbandoned) { - this.removeAbandoned = removeAbandoned; - } - - public Integer getRemoveAbandonedTimeout() { - return removeAbandonedTimeout; - } - - public void setRemoveAbandonedTimeout(Integer removeAbandonedTimeout) { - this.removeAbandonedTimeout = removeAbandonedTimeout; - } -} diff --git a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/config/properties/MyProperties.java b/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/config/properties/MyProperties.java deleted file mode 100644 index f95f739a43..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/config/properties/MyProperties.java +++ /dev/null @@ -1,148 +0,0 @@ -package com.xncoding.pos.config.properties; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; - - -/** - * 本项目自定义配置 - * - * @author xiongneng - * @since 2018/01/06 21:09 - */ -@Component -@ConfigurationProperties(prefix = "xncoding") -public class MyProperties { - /** - * excel模板文件路径 - */ - private String excelPath = ""; - /** - * 文件保存路径 - */ - private String filesPath = ""; - /** - * 图片保存路径 - */ - private String picsPath = ""; - /** - * 图片访问URL前缀 - */ - private String picsUrlPrefix = ""; - /** - * 文件访问URL前缀 - */ - private String filesUrlPrefix = ""; - /** - * POS API接口前缀 - */ - private String posapiUrlPrefix = ""; - /** - * 是否验证码 - */ - private Boolean kaptchaOpen = false; - /** - * 是否开启Swaggr - */ - private Boolean swaggerOpen = false; - /** - * session 失效时间(默认为30分钟 单位:秒) - */ - private Integer sessionInvalidateTime = 30 * 60; - /** - * session 验证失效时间(默认为15分钟 单位:秒) - */ - private Integer sessionValidationInterval = 15 * 60; - /** - * 机具心跳报告超时时间 单位:分钟 - */ - private Integer heartbeatTimeout; - - public String getExcelPath() { - return excelPath; - } - - public void setExcelPath(String excelPath) { - this.excelPath = excelPath; - } - - public String getPicsUrlPrefix() { - return picsUrlPrefix; - } - - public void setPicsUrlPrefix(String picsUrlPrefix) { - this.picsUrlPrefix = picsUrlPrefix; - } - - public Boolean getKaptchaOpen() { - return kaptchaOpen; - } - - public void setKaptchaOpen(Boolean kaptchaOpen) { - this.kaptchaOpen = kaptchaOpen; - } - - public Boolean getSwaggerOpen() { - return swaggerOpen; - } - - public void setSwaggerOpen(Boolean swaggerOpen) { - this.swaggerOpen = swaggerOpen; - } - - public Integer getSessionInvalidateTime() { - return sessionInvalidateTime; - } - - public void setSessionInvalidateTime(Integer sessionInvalidateTime) { - this.sessionInvalidateTime = sessionInvalidateTime; - } - - public Integer getSessionValidationInterval() { - return sessionValidationInterval; - } - - public void setSessionValidationInterval(Integer sessionValidationInterval) { - this.sessionValidationInterval = sessionValidationInterval; - } - - public String getFilesUrlPrefix() { - return filesUrlPrefix; - } - - public void setFilesUrlPrefix(String filesUrlPrefix) { - this.filesUrlPrefix = filesUrlPrefix; - } - - public String getFilesPath() { - return filesPath; - } - - public void setFilesPath(String filesPath) { - this.filesPath = filesPath; - } - - public Integer getHeartbeatTimeout() { - return heartbeatTimeout; - } - - public void setHeartbeatTimeout(Integer heartbeatTimeout) { - this.heartbeatTimeout = heartbeatTimeout; - } - - public String getPicsPath() { - return picsPath; - } - - public void setPicsPath(String picsPath) { - this.picsPath = picsPath; - } - - public String getPosapiUrlPrefix() { - return posapiUrlPrefix; - } - - public void setPosapiUrlPrefix(String posapiUrlPrefix) { - this.posapiUrlPrefix = posapiUrlPrefix; - } -} diff --git a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/controller/LoginController.java b/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/controller/LoginController.java deleted file mode 100644 index 0acaa84104..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/controller/LoginController.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.xncoding.pos.controller; - -import com.xncoding.pos.config.properties.MyProperties; -import com.xncoding.pos.exception.ForbiddenUserException; -import com.xncoding.pos.service.ManagerInfoService; -import com.xncoding.pos.shiro.IncorrectCaptchaException; -import com.xncoding.pos.shiro.ShiroKit; -import org.apache.shiro.authc.IncorrectCredentialsException; -import org.apache.shiro.authc.UnknownAccountException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -import javax.annotation.Resource; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; -import java.util.Map; - -/** - * Description: 登录验证 - */ - -// 只用同时具有permission:view和permission:aix权限才能访问 -//@RequiresPermissions(value={"permission:view","permission:aix"}, logical= Logical.AND) -//@RequiresPermissions(value={"permission:view","permission:aix"}, logical= Logical.OR)一个就行 - -@Controller -public class LoginController { - - @Resource - private ManagerInfoService managerInfoService; - @Resource - private MyProperties myProperties; - - private static final Logger _logger = LoggerFactory.getLogger(LoginController.class); - - //登录页(shiro配置需要两个/login 接口,一个是get用来获取登陆页面,一个用post用于登录) - @RequestMapping(value = "/login", method = RequestMethod.GET) - public String login() { - if (ShiroKit.isAuthenticated()) { - return "redirect:/"; - } - return "login"; - } - - // 登录提交地址和applicationontext-shiro.xml配置的loginurl一致。 (配置文件方式的说法) - @RequestMapping(value = "/login", method = RequestMethod.POST) - public String login(HttpServletRequest request, Map map) { - _logger.info("登录方法start........."); - // 登录失败从request中获取shiro处理的异常信息。shiroLoginFailure:就是shiro异常类的全类名. - Object exception = request.getAttribute("shiroLoginFailure"); - String msg; - if (exception != null) { - if (UnknownAccountException.class.isInstance(exception)) { - msg = "用户名不正确,请重新输入"; - } else if (IncorrectCredentialsException.class.isInstance(exception)) { - msg = "密码错误,请重新输入"; - } else if (IncorrectCaptchaException.class.isInstance(exception)) { - msg = "验证码错误"; - } else if (ForbiddenUserException.class.isInstance(exception)) { - msg = "该用户已被禁用,如有疑问请联系系统管理员。"; - } else { - msg = "发生未知错误,请联系管理员。"; - } - map.put("username", request.getParameter("username")); - map.put("password", request.getParameter("password")); - map.put("msg", msg); - return "login"; - } - //如果已经登录,直接跳转主页面 - return "index"; - } - - /** - * 主页 - * @param session - * @param model - * @return - */ - @RequestMapping({"/", "/index"}) - public String index(HttpSession session, Model model) { - // _logger.info("访问首页start..."); - // 做一些其他事情,比如把项目的数量放到session中 - if (ShiroKit.hasRole("admin") && session.getAttribute("projectNum") == null) { - session.setAttribute("projectNum", 2); - } - if (session.getAttribute("picsUrlPrefix") == null) { - // 图片访问URL前缀 - session.setAttribute("picsUrlPrefix", myProperties.getPicsUrlPrefix()); - } - return "index"; - } - - /** - * 欢迎页面 - * @param request - * @param model - * @return - */ - @RequestMapping("/welcome") - public String welcome(HttpServletRequest request, Model model) { - return "modules/common/welcome"; - } - - -} diff --git a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/dao/entity/ManagerInfo.java b/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/dao/entity/ManagerInfo.java deleted file mode 100644 index c61c9e645d..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/dao/entity/ManagerInfo.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.xncoding.pos.dao.entity; - -import com.xncoding.pos.common.dao.entity.Manager; - -import java.io.Serializable; -import java.util.List; - -/** - * Description: 后台运维管理员信息 - */ -public class ManagerInfo extends Manager implements Serializable { - - private static final long serialVersionUID = 1L; - - /** - * 状态 - */ - private String stateStr; - /** - * 所属项目id列表(逗号分隔) - */ - private String pids; - /** - * 所属项目名列表(逗号分隔) - */ - private String pnames; - /** - * 所属项目id列表 - */ - private List pidsList; - - /** - * 一个管理员具有多个角色 - */ - private List roles;// 一个用户具有多个角色 - - public ManagerInfo() { - } - - public List getRoles() { - return roles; - } - - public void setRoles(List roles) { - this.roles = roles; - } - - /** - * 密码盐 - */ - public String getCredentialsSalt() { - return getUsername() + getSalt(); - } - - @Override - public String toString() { - return "username:" + getUsername() + "|name=" + getName(); - } - - public String getStateStr() { - return stateStr; - } - - public void setStateStr(String stateStr) { - this.stateStr = stateStr; - } - - public String getPids() { - return pids; - } - - public void setPids(String pids) { - this.pids = pids; - } - - public List getPidsList() { - return pidsList; - } - - public void setPidsList(List pidsList) { - this.pidsList = pidsList; - } - - public String getPnames() { - return pnames; - } - - public void setPnames(String pnames) { - this.pnames = pnames; - } - -} diff --git a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/dao/entity/SysRole.java b/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/dao/entity/SysRole.java deleted file mode 100644 index 9036cfc34e..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/dao/entity/SysRole.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.xncoding.pos.dao.entity; - -import com.xncoding.pos.common.dao.entity.Permission; -import com.xncoding.pos.common.dao.entity.Role; - -import java.io.Serializable; -import java.util.List; - -/** - * Description : 角色信息 - */ -public class SysRole extends Role implements Serializable { - - private static final long serialVersionUID = 1L; - - // 拥有的权限列表 - private List permissions; - - public SysRole() { - } - - public List getPermissions() { - return permissions; - } - - public void setPermissions(List permissions) { - this.permissions = permissions; - } -} diff --git a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/dao/repository/ManagerInfoDao.java b/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/dao/repository/ManagerInfoDao.java deleted file mode 100644 index 502dd7d823..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/dao/repository/ManagerInfoDao.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.xncoding.pos.dao.repository; - -import com.baomidou.mybatisplus.plugins.pagination.Pagination; -import com.xncoding.pos.common.dao.repository.ManagerMapper; -import com.xncoding.pos.dao.entity.ManagerInfo; - -import java.util.List; -import java.util.Map; - -/** - * Description : - */ -public interface ManagerInfoDao extends ManagerMapper { - ManagerInfo findByUsername(String username); -} diff --git a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/dao/repository/mapping/ManagerInfoDao.xml b/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/dao/repository/mapping/ManagerInfoDao.xml deleted file mode 100644 index b032fa46c9..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/dao/repository/mapping/ManagerInfoDao.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/exception/ForbiddenUserException.java b/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/exception/ForbiddenUserException.java deleted file mode 100644 index 654e795e43..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/exception/ForbiddenUserException.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.xncoding.pos.exception; - -import org.apache.shiro.authc.AuthenticationException; - -/** - * 禁用用户异常 - * - * @author XiongNeng - * @version 1.0 - * @since 2018/1/12 - */ -public class ForbiddenUserException extends AuthenticationException { - -} diff --git a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/model/BaseResponse.java b/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/model/BaseResponse.java deleted file mode 100644 index 882e0c7d19..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/model/BaseResponse.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.xncoding.pos.model; - -/** - * Controller的基础返回类 - * - * @author XiongNeng - * @version 1.0 - * @since 2018/1/7 - */ -public class BaseResponse { - /** - * 是否成功 - */ - private boolean success; - - /** - * 说明 - */ - private String msg; - - /** - * 返回数据 - */ - private T data; - - /** - * 分页时候的总数 - */ - private Integer total; - - public BaseResponse() { - - } - - public BaseResponse(boolean success, String msg, Integer total, T data) { - this.success = success; - this.msg = msg; - this.total = total; - this.data = data; - } - - public boolean isSuccess() { - return success; - } - - public void setSuccess(boolean success) { - this.success = success; - } - - public String getMsg() { - return msg; - } - - public void setMsg(String msg) { - this.msg = msg; - } - - public T getData() { - return data; - } - - public void setData(T data) { - this.data = data; - } - - public Integer getTotal() { - return total; - } - - public void setTotal(Integer total) { - this.total = total; - } -} diff --git a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/service/ManagerInfoService.java b/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/service/ManagerInfoService.java deleted file mode 100644 index 6b4d1f6f42..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/service/ManagerInfoService.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.xncoding.pos.service; - -import com.xncoding.pos.dao.entity.ManagerInfo; -import com.xncoding.pos.dao.repository.ManagerInfoDao; -import com.xncoding.pos.exception.ForbiddenUserException; -import org.apache.shiro.authc.UnknownAccountException; -import org.springframework.stereotype.Service; - -import javax.annotation.Resource; -import java.util.Collections; - -/** - * 后台用户管理 - */ - -@Service -public class ManagerInfoService { - - @Resource - private ManagerInfoDao managerInfoDao; - - /** - * 通过名称查找用户 - * @param username - * @return - */ - public ManagerInfo findByUsername(String username) { - ManagerInfo managerInfo = managerInfoDao.findByUsername(username); - if (managerInfo == null) { - throw new UnknownAccountException(); - } - if (managerInfo.getState() == 2) { - throw new ForbiddenUserException(); - } - if (managerInfo.getPidsList() == null) { - managerInfo.setPidsList(Collections.singletonList(0)); - } else if (managerInfo.getPidsList().size() == 0) { - managerInfo.getPidsList().add(0); - } - return managerInfo; - } -} diff --git a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/shiro/CaptchaUsernamePasswordToken.java b/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/shiro/CaptchaUsernamePasswordToken.java deleted file mode 100644 index 09028347fd..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/shiro/CaptchaUsernamePasswordToken.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.xncoding.pos.shiro; - -import org.apache.shiro.authc.UsernamePasswordToken; - -/** - * Description : 拓展登陆验证字段 - */ -public class CaptchaUsernamePasswordToken extends UsernamePasswordToken { - - private static final long serialVersionUID = 1L; - - //验证码字符串 - private String captcha; - - public CaptchaUsernamePasswordToken(String username, char[] password, - boolean rememberMe, String host, String captcha) { - super(username, password, rememberMe, host); - this.captcha = captcha; - } - - public String getCaptcha() { - return captcha; - } - - public void setCaptcha(String captcha) { - this.captcha = captcha; - } - -} diff --git a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/shiro/IncorrectCaptchaException.java b/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/shiro/IncorrectCaptchaException.java deleted file mode 100644 index 4c43e72424..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/shiro/IncorrectCaptchaException.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.xncoding.pos.shiro; - -import org.apache.shiro.authc.AuthenticationException; - -/** - * Description : 验证码错误异常 - */ -public class IncorrectCaptchaException extends AuthenticationException { - - private static final long serialVersionUID = 1L; - - public IncorrectCaptchaException() { - super(); - } - - public IncorrectCaptchaException(String message, Throwable cause) { - super(message, cause); - } - - public IncorrectCaptchaException(String message) { - super(message); - } - - public IncorrectCaptchaException(Throwable cause) { - super(cause); - } - -} diff --git a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/shiro/KaptchaFilter.java b/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/shiro/KaptchaFilter.java deleted file mode 100644 index 5862c6ff3e..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/shiro/KaptchaFilter.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.xncoding.pos.shiro; - -import com.xncoding.pos.dao.entity.ManagerInfo; -import org.apache.shiro.authc.AuthenticationException; -import org.apache.shiro.authc.AuthenticationToken; -import org.apache.shiro.subject.Subject; -import org.apache.shiro.web.filter.authc.FormAuthenticationFilter; -import org.apache.shiro.web.util.WebUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; - -/** - * Description: 验证码过滤器此过滤器已经在shiro中配置,这里不需要再次配置拦截路径 - */ -public class KaptchaFilter extends FormAuthenticationFilter { - - public static final String DEFAULT_CAPTCHA_PARAM = "captcha"; - - private String captchaParam = DEFAULT_CAPTCHA_PARAM; - - private static final Logger _logger = LoggerFactory.getLogger(KaptchaFilter.class); - - //登录验证 - @Override - protected boolean executeLogin(ServletRequest request, ServletResponse response) - throws Exception { - - CaptchaUsernamePasswordToken token = createToken(request, response); - try { - _logger.info("KaptchaFilter.executeLogin"); - /*图形验证码验证*/ - doCaptchaValidate((HttpServletRequest) request, token); - Subject subject = getSubject(request, response); - subject.login(token);//正常验证 - - //到这里就算验证成功了,把用户信息放到session中 - ManagerInfo user = ShiroKit.getUser(); - ((HttpServletRequest) request).getSession().setAttribute("user", user); - - return onLoginSuccess(token, subject, request, response); - - } catch (AuthenticationException e) { - return onLoginFailure(token, e, request, response); - } - } - - @Override - protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, - ServletRequest request, ServletResponse response) throws Exception { - issueSuccessRedirect(request, response); - //we handled the success redirect directly, prevent the chain from continuing: - return false; - } - - protected void issueSuccessRedirect(ServletRequest request, ServletResponse response) throws Exception { - WebUtils.issueRedirect(request, response, "/", null, true); - } - - // 验证码校验 - protected void doCaptchaValidate(HttpServletRequest request, CaptchaUsernamePasswordToken token) { - _logger.info("KaptchaFilter.doCaptchaValidate"); - //session中的图形码字符串 - String captcha = (String) request.getSession().getAttribute( - com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY); - _logger.info("session中的图形码字符串:" + captcha); - - //比对 - if (captcha == null || !captcha.equalsIgnoreCase(token.getCaptcha())) { - throw new IncorrectCaptchaException(); - } - } - - @Override - protected CaptchaUsernamePasswordToken createToken(ServletRequest request, ServletResponse response) { - - String username = getUsername(request); - String password = getPassword(request); - String captcha = getCaptcha(request); - boolean rememberMe = isRememberMe(request); - String host = getHost(request); - - return new CaptchaUsernamePasswordToken(username, password.toCharArray(), rememberMe, host, captcha); - } - - public String getCaptchaParam() { - return captchaParam; - } - - public void setCaptchaParam(String captchaParam) { - this.captchaParam = captchaParam; - } - - protected String getCaptcha(ServletRequest request) { - return WebUtils.getCleanParam(request, getCaptchaParam()); - } - - //保存异常对象到request - @Override - protected void setFailureAttribute(ServletRequest request, AuthenticationException ae) { - request.setAttribute(getFailureKeyAttribute(), ae); - } - -} diff --git a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/shiro/MyExceptionResolver.java b/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/shiro/MyExceptionResolver.java deleted file mode 100644 index de93d5f2c1..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/shiro/MyExceptionResolver.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.xncoding.pos.shiro; - -import org.apache.shiro.authz.UnauthorizedException; -import org.springframework.web.servlet.HandlerExceptionResolver; -import org.springframework.web.servlet.ModelAndView; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Description : 自定义异常处理类 - */ -public class MyExceptionResolver implements HandlerExceptionResolver { - - @Override - public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { - //如果是shiro无权操作,因为shiro 在操作auno等一部分不进行转发至无权限url - if (ex instanceof UnauthorizedException) { - return new ModelAndView("error/shiro_403"); - } - return null; - } - -} diff --git a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/shiro/MyShiroRealm.java b/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/shiro/MyShiroRealm.java deleted file mode 100644 index d3f505a4e2..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/shiro/MyShiroRealm.java +++ /dev/null @@ -1,126 +0,0 @@ -package com.xncoding.pos.shiro; - -import com.xncoding.pos.common.dao.entity.Permission; -import com.xncoding.pos.service.ManagerInfoService; -import com.xncoding.pos.dao.entity.ManagerInfo; -import com.xncoding.pos.dao.entity.SysRole; -import org.apache.shiro.authc.AuthenticationException; -import org.apache.shiro.authc.AuthenticationInfo; -import org.apache.shiro.authc.AuthenticationToken; -import org.apache.shiro.authc.SimpleAuthenticationInfo; -import org.apache.shiro.authc.credential.CredentialsMatcher; -import org.apache.shiro.authc.credential.HashedCredentialsMatcher; -import org.apache.shiro.authz.AuthorizationInfo; -import org.apache.shiro.authz.SimpleAuthorizationInfo; -import org.apache.shiro.realm.AuthorizingRealm; -import org.apache.shiro.subject.PrincipalCollection; -import org.apache.shiro.util.ByteSource; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; - -/** - * Description : 身份校验核心类 - */ - -public class MyShiroRealm extends AuthorizingRealm { - - private static final Logger _logger = LoggerFactory.getLogger(MyShiroRealm.class); - - @Autowired - ManagerInfoService managerInfoService; - - /** - * 认证信息.(身份验证) - * Authentication 是用来验证用户身份 - * - * @param token - * @return - * @throws AuthenticationException - */ - @Override - protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) - throws AuthenticationException { - - _logger.info("MyShiroRealm.doGetAuthenticationInfo()"); - - //获取用户的输入的账号. - String username = (String) token.getPrincipal(); - //_logger.info("用户的账号:"+username); - - //通过username从数据库中查找 ManagerInfo对象 - //实际项目中,这里可以根据实际情况做缓存,如果不做,Shiro自己也是有时间间隔机制,2分钟内不会重复执行该方法 - ManagerInfo managerInfo = managerInfoService.findByUsername(username); - - if (managerInfo == null) { - return null; - } - - //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配,如果觉得人家的不好可以自定义实现 - SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo( - managerInfo, //用户 - managerInfo.getPassword(), //密码 - ByteSource.Util.bytes(managerInfo.getCredentialsSalt()),//salt=username+salt - getName() //realm name - ); - - //明文: 若存在,将此用户存放到登录认证info中,无需自己做密码对比,Shiro会为我们进行密码对比校验 -// SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo( -// managerInfo, //用户名 -// managerInfo.getPassword(), //密码 -// getName() //realm name -// ); - return authenticationInfo; - } - - /** - * 此方法调用hasRole,hasPermission的时候才会进行回调. - *

    - * 权限信息.(授权): - * 1、如果用户正常退出,缓存自动清空; - * 2、如果用户非正常退出,缓存自动清空; - * 3、如果我们修改了用户的权限,而用户不退出系统,修改的权限无法立即生效。 - * (需要手动编程进行实现;放在service进行调用) - * 在权限修改后调用realm中的方法,realm已经由spring管理,所以从spring中获取realm实例,调用clearCached方法; - * :Authorization 是授权访问控制,用于对用户进行的操作授权,证明该用户是否允许进行当前操作,如访问某个链接,某个资源文件等。 - * - * @param principals - * @return - */ - @Override - protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { - /* - * 当没有使用缓存的时候,不断刷新页面的话,这个代码会不断执行, - * 当其实没有必要每次都重新设置权限信息,所以我们需要放到缓存中进行管理; - * 当放到缓存中时,这样的话,doGetAuthorizationInfo就只会执行一次了, - * 缓存过期之后会再次执行。 - */ - _logger.info("权限配置-->MyShiroRealm.doGetAuthorizationInfo()"); - SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); - ManagerInfo managerInfo = (ManagerInfo) principals.getPrimaryPrincipal(); - - //设置相应角色的权限信息 - for (SysRole role : managerInfo.getRoles()) { - //设置角色 - authorizationInfo.addRole(role.getRole()); - for (Permission p : role.getPermissions()) { - //设置权限 - authorizationInfo.addStringPermission(p.getPermission()); - } - } - - return authorizationInfo; - } - - /** - * 设置认证加密方式 - */ - @Override - public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) { - HashedCredentialsMatcher md5CredentialsMatcher = new HashedCredentialsMatcher(); - md5CredentialsMatcher.setHashAlgorithmName(ShiroKit.HASH_ALGORITHM_NAME); - md5CredentialsMatcher.setHashIterations(ShiroKit.HASH_ITERATIONS); - super.setCredentialsMatcher(md5CredentialsMatcher); - } - -} diff --git a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/shiro/RoleFilter.java b/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/shiro/RoleFilter.java deleted file mode 100644 index 9dbda1e4ac..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/shiro/RoleFilter.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.xncoding.pos.shiro; - -import org.apache.shiro.subject.Subject; -import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter; - -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import java.io.IOException; - -/** - * Description : 角色过滤器,为了实现or的效果就使用这个过滤器,shiro默认是and的效果 - */ -public class RoleFilter extends RolesAuthorizationFilter { - - public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) - throws IOException { - - Subject subject = getSubject(request, response); - String[] rolesArray = (String[]) mappedValue; - - if (rolesArray == null || rolesArray.length == 0) { - return true; - } - for (int i = 0; i < rolesArray.length; i++) { - if (subject.hasRole(rolesArray[i])) { - return true; - } - } - return false; - } - -} diff --git a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/shiro/ShiroKit.java b/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/shiro/ShiroKit.java deleted file mode 100644 index 9cfdd2b658..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/java/com/xncoding/pos/shiro/ShiroKit.java +++ /dev/null @@ -1,252 +0,0 @@ -/** - * Copyright (c) 2015-2017, Chill Zhuang 庄骞 (smallchill@163.com). - *

    - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

    - * http://www.apache.org/licenses/LICENSE-2.0 - *

    - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.xncoding.pos.shiro; - -import com.xncoding.pos.dao.entity.ManagerInfo; -import org.apache.shiro.SecurityUtils; -import org.apache.shiro.crypto.SecureRandomNumberGenerator; -import org.apache.shiro.crypto.hash.SimpleHash; -import org.apache.shiro.session.Session; -import org.apache.shiro.subject.Subject; - -/** - * shiro工具类 - * - * @author dafei, Chill Zhuang - */ -public class ShiroKit { - - private static final String NAMES_DELIMETER = ","; - - /** - * 散列算法 - */ - public final static String HASH_ALGORITHM_NAME = "MD5"; - - /** - * 循环次数 - */ - public final static int HASH_ITERATIONS = 2; - - /** - * shiro密码加密工具类 - * - * @param credentials 密码 - * @param saltSource 密码盐 - * @return - */ - public static String md5(String credentials, String saltSource) { - return new SimpleHash(HASH_ALGORITHM_NAME, credentials, saltSource, HASH_ITERATIONS).toHex(); - } - - /** - * 获取随机盐值 - * - * @param length 字节长度,一个字节2位16进制数表示 - * @return - */ - public static String getRandomSalt(int length) { - return new SecureRandomNumberGenerator().nextBytes(length).toHex(); - } - - /** - * 获取当前 Subject - * - * @return Subject - */ - public static Subject getSubject() { - return SecurityUtils.getSubject(); - } - - /** - * 获取封装的 ShiroUser - * - * @return ShiroUser - */ - public static ManagerInfo getUser() { - if (isGuest()) { - return null; - } else { - return (ManagerInfo) getSubject().getPrincipals().getPrimaryPrincipal(); - } - } - - /** - * 从shiro获取session - */ - public static Session getSession() { - return getSubject().getSession(); - } - - /** - * 获取shiro指定的sessionKey - */ - @SuppressWarnings("unchecked") - public static T getSessionAttr(String key) { - Session session = getSession(); - return session != null ? (T) session.getAttribute(key) : null; - } - - /** - * 设置shiro指定的sessionKey - */ - public static void setSessionAttr(String key, Object value) { - Session session = getSession(); - session.setAttribute(key, value); - } - - /** - * 移除shiro指定的sessionKey - */ - public static void removeSessionAttr(String key) { - Session session = getSession(); - if (session != null) - session.removeAttribute(key); - } - - /** - * 验证当前用户是否属于该角色?,使用时与lacksRole 搭配使用 - * - * @param roleName 角色名 - * @return 属于该角色:true,否则false - */ - public static boolean hasRole(String roleName) { - return getSubject() != null && roleName != null - && roleName.length() > 0 && getSubject().hasRole(roleName); - } - - /** - * 与hasRole标签逻辑相反,当用户不属于该角色时验证通过。 - * - * @param roleName 角色名 - * @return 不属于该角色:true,否则false - */ - public static boolean lacksRole(String roleName) { - return !hasRole(roleName); - } - - /** - * 验证当前用户是否属于以下任意一个角色。 - * - * @param roleNames 角色列表 - * @return 属于:true,否则false - */ - public static boolean hasAnyRoles(String roleNames) { - boolean hasAnyRole = false; - Subject subject = getSubject(); - if (subject != null && roleNames != null && roleNames.length() > 0) { - for (String role : roleNames.split(NAMES_DELIMETER)) { - if (subject.hasRole(role.trim())) { - hasAnyRole = true; - break; - } - } - } - return hasAnyRole; - } - - /** - * 验证当前用户是否属于以下所有角色。 - * - * @param roleNames 角色列表 - * @return 属于:true,否则false - */ - public static boolean hasAllRoles(String roleNames) { - boolean hasAllRole = true; - Subject subject = getSubject(); - if (subject != null && roleNames != null && roleNames.length() > 0) { - for (String role : roleNames.split(NAMES_DELIMETER)) { - if (!subject.hasRole(role.trim())) { - hasAllRole = false; - break; - } - } - } - return hasAllRole; - } - - /** - * 验证当前用户是否拥有指定权限,使用时与lacksPermission 搭配使用 - * - * @param permission 权限名 - * @return 拥有权限:true,否则false - */ - public static boolean hasPermission(String permission) { - return getSubject() != null && permission != null - && permission.length() > 0 - && getSubject().isPermitted(permission); - } - - /** - * 与hasPermission标签逻辑相反,当前用户没有制定权限时,验证通过。 - * - * @param permission 权限名 - * @return 拥有权限:true,否则false - */ - public static boolean lacksPermission(String permission) { - return !hasPermission(permission); - } - - /** - * 已认证通过的用户,不包含已记住的用户,这是与user标签的区别所在。与notAuthenticated搭配使用 - * - * @return 通过身份验证:true,否则false - */ - public static boolean isAuthenticated() { - return getSubject() != null && getSubject().isAuthenticated(); - } - - /** - * 未认证通过用户,与authenticated标签相对应。与guest标签的区别是,该标签包含已记住用户。。 - * - * @return 没有通过身份验证:true,否则false - */ - public static boolean notAuthenticated() { - return !isAuthenticated(); - } - - /** - * 认证通过或已记住的用户。与guset搭配使用。 - * - * @return 用户:true,否则 false - */ - public static boolean isUser() { - return getSubject() != null && getSubject().getPrincipal() != null; - } - - /** - * 验证当前用户是否为“访客”,即未认证(包含未记住)的用户。用user搭配使用 - * - * @return 访客:true,否则false - */ - public static boolean isGuest() { - return !isUser(); - } - - /** - * 输出当前用户信息,通常为登录帐号信息。 - * - * @return 当前用户信息 - */ - public static String principal() { - if (getSubject() != null) { - Object principal = getSubject().getPrincipal(); - return principal.toString(); - } - return ""; - } - -} diff --git a/jun_springboot_plugin/springboot_shiro/src/main/resources/application.yml b/jun_springboot_plugin/springboot_shiro/src/main/resources/application.yml deleted file mode 100644 index 0627a47274..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/resources/application.yml +++ /dev/null @@ -1,76 +0,0 @@ -########################################################## -################## 所有profile共有的配置 ################# -########################################################## - -################### 自定义项目配置 ################### -xncoding: - kaptcha-open: true #是否开启登录时验证码 (true/false) - session-open: false #是否开启session验证 (true/false) - session-invalidate-time: 7200 #session失效时间 单位:秒 - session-validation-interval: 3600 #多久检测一次失效的session 单位:秒 - heartbeat-timeout: 10 # 机具心跳报告超时时间 单位:分钟 - -################### 项目启动端口 ################### -server.port: 8092 - -################### spring配置 ################### -spring: - profiles: - active: dev - thymeleaf: - mode: HTML - cache: false - mvc: - view: - prefix: /templates - -################### mybatis-plus配置 ################### -mybatis-plus: - mapper-locations: classpath*:com/xncoding/pos/dao/repository/mapping/*.xml - typeAliasesPackage: > - com.xncoding.pos.api.model, - com.xncoding.pos.dao.entity, - com.xncoding.pos.common.dao.entity - global-config: - id-type: 0 # 0:数据库ID自增 1:用户输入id 2:全局唯一id(IdWorker) 3:全局唯一ID(uuid) - db-column-underline: false - refresh-mapper: true - configuration: - map-underscore-to-camel-case: true - cache-enabled: true #配置的缓存的全局开关 - lazyLoadingEnabled: true #延时加载的开关 - multipleResultSetsEnabled: true #开启的话,延时加载一个属性时会加载该对象全部属性,否则按需加载属性 - -logging: - level: - org.springframework.web.servlet: ERROR - ---- - -##################################################################### -######################## 开发环境profile ########################## -##################################################################### -spring: - profiles: dev - datasource: - url: jdbc:mysql://127.0.0.1:3306/pos?serverTimezone=UTC&useSSL=false&autoReconnect=true&tinyInt1isBit=false&useUnicode=true&characterEncoding=utf8 - username: root - password: 123456 - thymeleaf: - cache: false - -################### 自定义项目配置 ################### -xncoding: - excel-path: E:/home/ - files-path: E:/home/ - files-url-prefix: https://show.xncoding.net/files/ # 文件访问URL前缀 - pics-path: E:/home/ - pics-url-prefix: https://show.xncoding.net/pics/ # 图片访问URL前缀 - posapi-url-prefix: http://127.0.0.1:9095 - -logging: - level: - ROOT: INFO - com: - xncoding: DEBUG - file: D:/logs/app-manage.log diff --git a/jun_springboot_plugin/springboot_shiro/src/main/resources/banner.txt b/jun_springboot_plugin/springboot_shiro/src/main/resources/banner.txt deleted file mode 100644 index 2e697237e8..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/resources/banner.txt +++ /dev/null @@ -1,139 +0,0 @@ - :: :.:..... : ....: ..: ..: : : :..: ..:...:.... :..........:.... .:.: : :.::..:.:......:.:..: : :...:..:::..::.:::::::..::.:::::.::::::::::::::::::::::::::::::::::::::::::;:::::: -.::.:.:::...: ::.:.:.:.:::.::::.::.:.:.:::.:.:.::::.::::.:::.::.:.:.:::::::::::::::.::::::::::::::::::::.:::.:::::::::::::::::::::::;:;:;;;:;;:;:i::::;;,;,,;::;,i;:i;,;:;,;;,;;i:;: -::.::: :::::::::::::::::.:::::::::::::::.:::::::::::::.::::::::::::::::::::::::::::::::::::::::::::::::::::::::::;;:;;:::::;::::::ii,;,ii,,;,,:ii:ii,;::i:ii:i;,;;,i:,;,:i:::;,,;,,: -::::.::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::;:::;;:::::::::::::::::;::::::;::::::::;:::;::::::i:,;:::;,;:;i:;,,;i;i:i,;,;,:,;,::,;;,;,:,;:;,,;i:;,;::i:,;,,;:;, -:;;:;;:,i:,;:;::i:i:;:,;,,ii,,:;;,:i,;,,;,,i:,:::;:i::,;::,;,:,::i;,;::;:::::,:;:,::::,::i;:,::::::,:,:,,:ii:i::i:,;,;,:::;:;:;i:i;ii:i;,i;,;:::,:,::,::i:i:,::;,i,;ii;,,::;,:::i:i: -;ii:,:,;;,;,,:,:;,:,:,::ii;,;:i::;::,:::::::;::,;:,;,:i:,;:::;:i::::::::::::::;,;,;;:::;:::::,::;:::::;,:i::i:;,::::;::::::,::,:i:iiiiiiiiii::i:::;:;:::::::;::i:,;i,i:i:i:,;::::::: -,;;:;,;::;:::;:i::::::,;::i:i;::::,::;,::::,:::::;:i::;,:::;iifffjiii;i:::::i:,;;:,,:::,::::::::::::::::;,;;,;:;:,;,:;,::::;i:;;:iiiiii,i:,;::::;,:,:::;,;,:,:;,;;ii;,;i;::;::,:i::: -,i:i::::::::::::::::,::i:i;;ii::;::,::::::::,::::;:i:;,;ijffLffffGGGDDLGfii;;:,;:i::::::;::::::::::::;::;:i;,;:;::;::::::,;:i:;;i:i:iii,;ii:,;::::,:;::::,:;::;,;;,;ii:i;,:;:;:::::: -:ii:;;:,:;,:::::,;,:::::iiiii;,;,:;:i::::::::;::;;,;ii;ifGLGGLGDGGGDDEDGffijiiii;::;:::::::::::::::::,:;:,::::,:,:::,;:::::,::,i:i,ii;;i,;;,;:,::;::::::;:::,;:,;i:i:,;,,;:,:,:;:::: -i;;,:::::::::::::::::::i::i:ii:,::::::::::;:::,;:iii;ifLDGfDDDGDDEEEKEEDEGDDGLfi:,;::::::,::::::::::::::;:;:i:::;:;::::::::;i:;,;:i:ii,;i:::,,::::,;::::,::::::;,:i:i;,;:,::::::,::: -i:,;,,:::,:::::,::,::,:,;;,;i:i::;,:::::::,::,;,;i;ifLDGGDEKEDEEEKKDEDKEKEEDDDGfi;,::::::::::::::::::::::::::::::::::::::::::,:;:i;;i:;,;,,;::;:;:::::::::::;::,;i:;::;,,;:;;:i:;::: -i:,;::::::::::::;::::,:::;:i::;,,:,:::::::;:,;iiifGGGDGDEEDKEKEEWW#WKKEWKEW#KKEGj;i;,::::::::::::::::::::.::..::.::...: ::::::,;:;:,;i:i:;::;::;:;:::::::::::::,;;:;:::i,:;:,::::::: -:;;,::,:;:,::::::,::::,;,:::;,:;;:;:::::::::;,jjfGDGDGGGEDEEKKK#KWK#E#WWW#KWEWEDffii:;::::::.:::::::::::...;;:ijiii:::: :::::;:,:i,:;::;:::,:,::::::::::::,::::::::,::;::::::::::::: -,::;,::::::::::::::::::::::i:;:::,:,::::.:;,iifffffDGGfLDEKKWK#WKEEWWWEWKKWWWWKKDGGi;,::::::::::::::.:.:;:;;;jLfGGfji;:::::.:::;::;;,:::;,;::;::;:::::::::;::::;:;:;::::::;:::i::::: -::;::::::::::.:::::::::::::;:::::::,::::::i,ififLDGDDDDEKWEWWK##KWEWWWWKKKWKWWKWWKDGfi;::::::..:::::;,;ijLGjjjtjLGDDGDGGGi::::::::;:::::::::;::;,::::.:::::::::;::,:::;::::::::::::: -:;:::::::::::.:::::::::::;:::,:;::;::::.::ijtGDGDDDDDEEKWWWKWWWWE##KK##KKWKWK#KWK#EGfii:::: :::::::::iiifLGGGGjjtGGEDGEGDj;;:::;:::;::::;::::::,;:::::::::::::::::;::::::::;:,;::::: -:::;:::::::.::.:::::::::;:::::::::,::::::ifDGDKEKEDELDKKEKEK#WW#K#WWWWWEWWKK#KK#KKKGGi;::::::.:.::.:;ijfGGGEEDGGtjGGKDDEDG;;:.::::::::::::::::::::::::::::::::::::::;::::::::::::::: -:::::::::::::::::::::::::::::::::::::::;ifDEDDD#GDEDEWWKEW#W#E#WWWKKWKWWKK#EWK#KEKGjii;:::::::: ::iiLGDGKKKKKDKKEjjGEDKEEjjGfj;:::::::::;:;:::::::::.:::::::::::;:;:::.::::::::::::: -::::::::::::::::::::::::::;::::::::::::iiGKKDGEWEKEWWK#K#KWK#WW#KW#WK#WWKWKWK#KKKDj,;:::::... :::i;jGGDEEKDKKKKKKGjjGEKKDjGGGjf::::;::::::::::::::.::.::::::.::.:.::.::::::::::::::: -:::::::::.::: ::::::::::;,::;::::::::,;ifLEKEEDEK#KKKWE#WW##KWWK##KK#KWWKKKWEGKGGi:;::::.::.:::::ifGGGEKKKEKDKWKEGLjGD#EKGGGGGG;:.::::::::::::::::::::..:::::::::::::::::::::::::::: -:::.::: :::.:::::::::::,::::::::::::i;ifGDEKKEEKKK#KK#KWWWKWWW##EWW#E#WEWEWEEDGjLi::::::::.: .:;ijjLGEGDGGEKGEKK#KGGGKKWEDEKDGGi;::::::::::::::::.:..:..:..::.::.:.:::::::::::::.::. -:::::.::::.::::::.:::::::::::.:.::::iifGGDK#EWEKEWK#E#WKWWWKWKWWWKKKK#WEWDGGGLit;;:...:::. :.:;ijLjjjjLGGEEKDEEDGEKDGGEDKKKEEGGi;::: :...:: :::. : ::.::..:::..: .::.::..:::::..:.:. -::::::.::.::: :.::::::::::::..:.: ::iiGGDEEWKKKKEE#K#KWWWWW#K#EW#KWW#KWEKEGfLf;;;;;: ::: ::::ijLGjtjLLGGKEEEEEDKEDKDEGGGKKEKKDGj;;:;;::::..:....:.: ...:..:....:::...:..:.....::.::. -:::.:.:::.: ::.:::::.::.::..:: :::::iLGDGDKWKE#KK#WWEKWWWWWKWWWEWWWWKKKKKDDfjj;;,,..:...:.::;jGjjjjLGKEEGEKDDEGDDGGGGfLjGKKEEKGjj;;,;;: :.:.:::...:. :....::.. : ..:::::..:::: :::: -.:..:..:: : ..:::: :..:: :....: .::ijGDKDGEWEW#EW#EWKWWWWWWKWWWEWKK#KWKKEDGGi;;;,,::.:.: ::;i;t;LEGGDGEGKEGGGLjiji;j;;;;tjGGEKDGjt;.:.:: :: ::.:: : :.......:..:: :.:.:...:.:...::. -..: ::..: :..::...: :.: :: :::..:::ifLGEKEKEK##WWK##KKWWWKKKWWK#K#KKKWKWKEKGti;:.:.,.:. : ;ij;;jGGGLGEGGDEGLjj;t;;;;;;;;;;tjGEDGjt;:.. ;:..........::..:.......: :... :..: ... :... -..... : : :.. :.: .: .: :.. ::::;ifGEEKKE#KKWWWEWK#K#K#K##EWKEWKWWWW#EEEDGi;;;.:.:..:: :;ijitGGLLGEGEKGGGjj;;;;;;,;.;;:;;;LGKEGt;.: :. :..:: ::. :. :... .... :.....: : :::.....:: - :......:. ..: ...::..: ::.....:::;iDEEWEKKKKKKK#WK#KWKW#K##EWWWKW#EKEKWKKEDGj;;;.::.,: ;;ii;jjGGLGGDKGGjLjji;;;,::,:.;:,::,;tjGGLL;................:... : .:: ::....:..: :: :..... -. .::..: : . : :..: :..:: :..:.:::iGDKKKK#KK##E##WWWW#KWW#WK#EKWWKKKEEWEKGEGj;,.:...,..::;;jjLGLGLGEGLGLjjtjt;;;;;.;;.::,:.,;iGDGG;;.............. :..: ::.. :.. : : .: :. : :..: -.::..: :..:... ...:: :: :: : : ::,iGDEEKEK#EWKW#WW#KWK#KWWWWWKEWKKEWDDDKKKDGGi;.:.:,.;::;;itLGLfLGGGGGjjjt;i;;;.;,,::,:...::,;LGGGL;:: .. : ....... : : :....: :: .. :.....: :: :: - :..::.::.: . :: : :.....: :: :::ijDGDWEKWWK#KWWW#K#WW#WW#WWWKK#KWKEKKKDKEEGGj;.:...:.,:;;;jLjGLLGKELjLjjt;t;;;,,;:.:.:..:..:.iGGGLj:.:..... : : ::..... ... :.:......: : : : : -.. : :..: :. ::. :.......: :: :::;fGDDDEWKWW##WW#KWWWWWWWWWWE#KWKEWEKEKGDEDGGj;:.:..:.,;i;jjGGLLDKEGLjjjtjt;;;,,;,:..:.:.:.:.:;;LGt;j:.: .. :....:: :: : : . : . : :.: :.: :.: .: -. : .... .: : : :.....:......:::ijfDEEWKK#K##K#WW#KWWEWEWWWWWKWEWKEKGGDGEGGjj;.:..:.,;jEitiGGLjGKELjjtijii;;;,;..;:.:.::.:.:..;jGjtt.:: :....: : :.: :.: ::...... ::......:.:.:. -: : .........: : : : : :...::itGDDKEW#KWKW#KWWWEE##WWKWEWEK#KKEKKDGKGGGGf;,:..:..;jGK;jLGLGGEKEjLjtt;j;;;;,,,::::.;..:...::.jGLj;j ::: :: :: : : ......:: :: :.:....:.: :.:.:. -: ...................: :....:...:;fGDDKEKWEW##W##KWWWW#WW#K#KWK#KKKDKGfGGGGLj;::..:.;ijjjjGGGGDKKEGjLjjLjjji;;;;,;.::.:..:....:.;fGLijj.:: ::.::.... :: : : : :..:.. : ::..:..: - ....: :.............:: ...:..: :ijGDKEWWWWWEK#KK#WWWKWE#KKWWK#KWDEGGGGfjGji;...:..;;;;;iLjGLGKKKGLLjLLGGLLLj;;:;:.;:..::.::....:jDLijj.:............. :..: :: :: :.......:: :: ::. -: : ..: .. : : :: :: ::. :: :: ;fGDEDEWWWKWWWWWWW#WK##WKWWK#KKEDKEDGfGfjL;;.:.,:.:;...;GLLGDDKEGLGLGGLjfjfLj;;;;,..::.:.::.:...jKLt;j;.................. .. : .........: .....:: - :...: :: .. : : ....: .. ... :: ;fLGDDEKWWKKWWW#K#E#KKWKWKWK#EKEDEGDGGGjji..:.::;.:.:..;LGLGKKELLjjjttt;;;;;;;;;,;..:.:;;;i;::..;KGj;;j; : : .. :: .. : . .. . .. :: . .. ..: - .. . : .. :: : .. : ....: . :;ffDGEK#K#K#WW##WWWW#KWWWK#KWWEKGDDGfGfjj;.:...:..:..:;jGGGEWKGLfLjtjtttij;.;;;;;.:.::;;;iji;:..;KGf;;;; .. : ... .... .: . ..: : .. : :: :... : -. .. ... .... . . .... . :: :. :LGDDDEK#WE##WW#K#KK#EWWW#KKWKEKDDGDjGfij;.::...::..:;j;iLEDKKGjLjjjtjjLLGLj.;;;;;..:.,:;;;t;j::.EGj;;;;: .: .. . : .. .. : . :. ....... . - . . . .: ... . . :. . : .. . ..;jGDGDKKKKKWK#WKW#EK#WKK#KWWWKEDDGGGjGjjtj,:...:.;..:;;;;;GKKGLLtjjtjjGGEEKD;.,;;;.:.;;,;,:::;;.:DGL;;;;...... : .. : .: : : : ... : .. :..... - : . : . :.. : . ... : . .. ...iGDGDEKKWE##EWWK#K#KWWKKKWWWEDDDGGGjGfjji;::.:.....::,..:,DKLjtjttLLGELiiEGG;;i;;.:,;;;;jjj;: :.GGj;;;;... .. : .. : : .. .... : : : .. :....: -. : . .... :.. ... . . : . . ;GEGDDEE#KWW#KWKK#WE##K#K#KKDKGEGGGGjjjjj;:.,..:.:....;,:,;EGLjtjjjjLLLLjLGK;;;;,: ;;;jGDWKG;. .Gjt:,:;: .: ... : .. : : . .... :: ......... - . ... : . . : .. .. .. : . : :GGDEDEWKKWWWEWWKKWWEWWEWKKKDGGGGGjjGjjji;:;:::....::.,:.;;jGLtjttjtjtj;;;;j;;t;;..;;;jiifDW;:.:Ei; :.; : : .. .. :.........:... .. : :... : .: - .. ... . .. : : . .... . .: ..GDGEEKKK#KKKKWWWW#KWWWKEWKKGLL...;jjfjji;,;::.:.. ...:;:;;,;Gtjtj;j;;;;;;;;;jtt;:.:.;;itjjLL; .L::..;... : .. :: .. : : ..........: : : ....: -. . . ..: .... . ........ .... :....LKLKDKKKWWWWWEWWWK#W#WKKKEELL;:;..,;jjjt;;.;.:.:.:....:;;;;iLjtjiti;;;;,,.;;tji;;:.:;t;;;.;;;..j:. .:. : : ..... : .. ..... : .. : :: :...: - .. . ... .. : .. :. :: .... ...: :.iGGDEKKWEWWWKWWKWWK#EWKWEKGLt,tt...;;jjj;;:;;:... :. .;;,;;jGjttti;;,,,;.;;ijtt;...:;;;;;..:. .j: :; .... . ...: ...... : .. : :: :: .::..: :: - . : . . : .. :: ..: :: :: .. : ....;jGGDKDKKKWKKK#KWWWWK#KKGLLtt,tj,..:;;;;;;:,,:,:.. . ..;,;LKLttjt;t,.:,;:,;ttjt;:...:,.:.:.: . j: .:. : : .... : : :: .. ......: : :: :..:: -. . ....: : : . : :.. : ....: :: :.:;fGDKDEWWKWEEWK#KWWWWKEGGjf;,ti:,...;;;;;;;:,:..:..:..,;jKELjttt;;;;,,,.;;jtj;;::....:,,:...:.j:..:.. . .. : .. :: : ........: : ::....: : : - :....... :...: :.. :...... ....::iGEEEKEKKWKWKWWK#KEWWELjLj;,,,j;.:.,;;;:,::;:.:......;;KKGLtttt;,;,.;,;:;jjj;;.....:.::... . f;..: ::.........: :: .......: :.:.:: :.......:: -. .... .....: .. : : : : ..... : .::GGDKEDWWEWK#EWWWK#KWGLjjf;;.tLL. ..;;;;;:;:,:...:. .,jEWGLtttt;;;,;:..;tjLj;;:.:...,:.:..: .ii.:.......... : : : :: :: :::.::.::.....::.. : -....... : . ..... ..: ..:..... .: .:.iGGKKKKKKK#EW##K#WWKGLjtLt,.;ff; .:.;;;;;;:;;:..:.:.:,LEELtjti;;,,::.;ttjtj;,:...;,:::.: . .i;;:::.::.:...:....::: : :::..:.::::..: :..:: :.: -..: :: :: ... :... : :...:..:::..:...;DGEKKEWWWKWWWWWKKKKLjjLfj;.,;t;.:.;,,;,:;.,:,,...::,:jDELtttt;;;:,.;;Ljtjj;;..:.;;.... :.. ;;;::.:.....:..:.:.: :: : ::..::::::::.:.::.::... -.: :::...................:.:..: : :..:.:jGDEEWWKKK#K##W#WWKLjjjtjt....;..;.;;;;;;.,,..,.:...,;GELtjtt;,;,,:;;jjLLLj;,;..;,,:..: : :;:;:::::::.:.:..:.: :.::::..::.::.::.:.::.::::.:: -::::::.:.:.......:.: :.:.:::::::.:...:::.;GDDEKEWKWW#WW#KKKLLjtjtj;....:,,;;;;;;;.,,:.......;;LKLtjtt;;,,;;it;tiij;.:;: ,;;,..:.: .:.:;.::::...::.:....::.:.:::...: : :..: ::.::...: -::::::.:: :::: ...:.:.:.. :::.:..:.:.....:LGEDWWWWW#KWKWKEEjjtjjjLt;.. .;;;;;,:,::::..::..:.:jKELttt;;;;:;;ttt;t;;:,:...:;;;.:.. .:::..:: ::.::.:.:::...: .: :.:..:.:.::.:..:::.:.. -.::.:.: ::: : : :.:.:.:..::...::: :.:..:.:LGDDE#WWW##WWWKKGLjjtttjLt;:.:,;,;;;;,,;:::.:..:.:,LGEGjttt;;;;t;tj;ttt;;...:.:;;,:.... :...;..::: : :: : ...::.:: :....:....:.: :.: :... -....: : .: :.:...:..: : :::....:: ::..:: :jDWKWWWEWWWWKKDDGjtjttit;;;;;;tt;t;;;,;:,.:.. :..:,;LGLttjt;;,;tLLDDDGGDLff;..::;;:..:. ..: .: :..::: ... ..:: : ...: ::........ :: :.: .. -.....:.:: :.: :...:: ::.. : :..:: : ..::..fKWWKWWWKEKKKEDGGjji;;t;;;,;;;;ttt;;;;.;....:..:,,;tGLLtit;;;.;tGELLLGLfffLjt,.;;,..:. ::...;... : :: :. :.: ::: :............: : ..... - :: :....: :.: ..: :.....: :: ::.........iEWWWKWWKKKEKEGGGj;jt;i;,,:.;tijt;;;;;;.;.:..:...,:tGLjtti;;,;;;LGLjt;;;t;ffft;;,;:.... :: :: : ....: : .: .... : ............ :: :: :: -: : : :.........: ::...................;GKWEKEKEKEGGGGGjjti;;;;,,.;;;tttjt;;;,:...:...,:;;;LLtjttt;;.;;;DGL,;:...:tfLf;;:..: .. : :...............:: : : ...........: :: :: :: - :: ::.. :: : : :: :: :: : : : :: :...:iDKGGGGGGGLGjjjjti;i;,,;:;:,;jjttti;;,,,..:..,:,,;:.;jtttt;;,;;itLDGLfft,,,Lft;;,.... : :. : .. . : : :...: . .. : : :: :: : : : : -........: .....: : : : ...: :: : : : :LGGGGGGGLLjjjtj;jt;;,;,,.,;;tjtjt;;;;;:,::..::,:,:..;;;i;;;;;;ttjfGDLffjjjjt,;,;:.:.: .. : : .. :: :: .... : : : : :: .. : : .. :...: - :: :: ::.....: : :: :: :: : .......: :: :: ;i;ijjjjjjjj;jtt;i;;,,::,.;;;jjiit;;;,,:..,.,.:;,...:;tiit;;;;;itjfGGLffjti..;;..... .. :. ...: . : .. .. : .. .........: .. : ..... - :: :: :: : : : :...: ... :: :: : : : . ::.:,:i::::::;t;;;,,;;::,,:;itjitit;;;;,:,:,,:,; :..:,;ti;;t;;;;;,;;;,;....;.:..... :: : .. :: :: :.. :: ... : : .. :.. ..... .... -: .......... :: : : ..........: .. : .. :..::i;,:;::::.:;;;;,;:::..:.,;;ttt;;;;,;;;:,,,,,, : ...:;t;jiit;;;;;;;,;...:.:..: .: .. :.. ..: :........... . : .. ....... : :: :: :: - :: :.......... : :: :: :... .. : :: :: :itfGDGffjii;::.:. ::;;.;:,:.,::,;;tittt;;;;;;,,,:;.. : ...;;ti;t;;;,,:.::.:: .:.:.... ...: :: : ..: .. .... ..... :: :: :... : : : : - .: ...... :: :: ....... .. .. : :...:ifLDDDWDWWEWKWKWEDf;. : .;:::.,.,;,;;;;t;;;;;;;;;;. . : ..:.:.;;tit;;;:,:..... :.... : : :: : : . : : : :..... :.. : .. . : ...: :.. .. - :.. .. : :... ..... ....... .. .. .. ;tfGGDEEEKWK#W#KWWKKEGf:.. :,.:...:::;;;:.. ...: ...... .:. ..:;;itt;;:;.::.::. :...: . .. .. . ........ . :: ..: .. : : :: .. : .... :: - . : ..... .. ... . ..... : .. .. : : iffDDDDDWKKWWKEWWEW#KKKKi...:::,.::;,,:. .. ... .. ..: ...:.:::;;;;jit;;:;.: ...... ..: ..: ... :.. : : :: .... : : .. .....: : : : . . -..: . : . .........: :.. ..... :: ..: :jffLDEDEEKKKK##WWKKEEKKEDL: ..:,:::.::; :: :.. :.. ... . :.:.:,,;;;itj;;;.:.....:: .. :... ... .. : : : : . ..... : ....: : : :: .. .. - . .... ...: . : ... .... . . ....ijLfLGDDDDKKWWWWKWKKKWEKWEEEKD: ..,.:.::. :.. :.:.. .. : :.::.;.;;iititt;;;;:::... :......... : : ..... : : .. : .... :.. : .... : . - .. ... ... : .... : : .. .....: : itjfGDDDEEEKKKWEW#KWWKKWEWEEKDDGi :.::,: .. .... . . : : : .::.::;;tttjttiti;:;..... :.. . : . .. : : : ...... : : :: : :.... ...... -..: : .. : : . :: : . : : ..fLfDDDDEEDKDEEKKKWWWKWWWEWEEEEEEDj..::.;: :: . : . : .. :.:.:.;;;titjtit;;:;:...:.... :....: .... ...: : : . : ... : .. ... ... .... . - ....... . ....: :: . : : . : : tGfDDEWEWEWWW##WW###W###K#KKEEEEDEf:.,: : .. ... .. : ....:.,:,:;;tit;t;,,,.,...... .: .... . : . .: . . . . : ...: . : ... ... . . . - .. :: :: : . . : .... .........: :ifffDDEEWEK#KEW#WK#WWWW#W#WWEKEEEEKf.:. : . : : . .. .. . :,:;;;jttt;;;;,::....:. : : : .. : . ... ... . : ... .. . .. : .. . ..... .. . -........ : .. :. : . ....: ........:ffffGLDDDKKKWK#E##W##W#W####WKWDEEEEf ..: ... :.. .. : ... : ..::.;;;j;;i;;:;::.::.... . ........ : . ... ........ : .... . .. :... . . .. - .. :: : .... ... . .. : :: .:iiffffGDGDDEDKKKK#KK#WWK#KK#KKEW##WKDWDEi.... .... ... ..... : ...:,;;tti;i;;,;.:.,::.:,:. :. : .......: .. :... : ....: : : :: .. : : . -.... : ....: ... .: :.. : .::tifDGLfGDDDGDDWEWKWKWWWWWWK#WK#WEKK##KDEWEi : :.. .. :...: .: ...,;;;;iti;;;;,.;:..:.:::::.. : ::..: : : : ..... : : .........:. :...... ::..:. -..: :... ....... ........... iiiitfEDDDfGDGGDDEEWWWWWWKKWWWK#KKEWEEED#WEDDG: .... :: : ....... : . ,;;;;j;t;t;;,;..:::..:.;....: : ... : .. :: ....::..: : .....: : ....:. : . .. -... :: :: : ......:: :...: :ititifLDGDfLGDfGLDWEWWKKK#EWK#KKKK#KKKKEKDWKEDDf............. : : . :;;;;tt;tt;;;:,..;..::.;.;;.:: .:::..::. :..:.:.....:..:. :.....::..:::...::.:: .. - ::.:: ::... :. :....:...:tDLifjtfDEDGGDDffffDKWEEWEWWEWWEWWEKKWKKEWEKEDEEDG:.: .:::....:::.:.: . .;t;ttt;ttt;;:;..,.:.,.:;;;;;.:. ::..::.:.:::::.::::::::::..:::.::.::::::.:.::.::. -: .: : .:::.:.:: :: :: :iDDfifffGDEDLLDLLffLDKEKKEWEEWEKEKKKWKKWEKWEWWEKDDLL..:: :..::::.:: .: . ;t;itt;tt;t;;,;,,.,,,:,;,;,;;;:: ::::: ::..:::..:::.::.::.:.::::.:.:.:::::::::: -.: :::.::: .:.: ::..:.:;iGDLtfffLDGDfLGLGLffGDKEKEWEEEDEKKKKKKEEWWKK#KKKKEDDLfff;::.::.:.:.::: : .;;ti;ijit;;;,;:.,..,:;;;;;,;;:;::.. :.:::.::.::::::.:::::::::::.:.:::.::::.::.::: -.:.:..::::.::::::.:.::tfGGfftDffLDfDGfffLLfDKEEDEEDKEKKKKKKEWEKWKKEWEWWEWKEKDDLDi::::::.::::: . . .;;;;i;j;;t;;;;..:.::;;;;;;;i;;:.. :.. .:::::::;::::;;:::::;:;:;:::;:;::;;::;: -:.:::::.:.::::.:.:::iitDfGfGfLffGLDDfLGGffDEDKEDEEWKKWEWWEDWEKKKKKKKKKKKKWEEEDDLi::;::::::::. .....:;;t;;titit;,,,;.;,;,;;;;;t;;;::.:..::.::. ::;::;::;i;,:ii;i;i:i:::;;:::;:::;,,; -:::.:::::::.:::.:::iitfDfGDfDDfffDGDLDLLLGKDKEKEEKKKKKKKKKEEKKKK#KWKKEEKKEWEDEDLLi;:;:;:;::: . . .,;;;;j;tt;;;;;;:;::;;;;;;;;;.:;::.:::;;;:::..;,:ii,i,;iiii,iiiii:i:i::i:;i:ii;iii -;iii;;:;;:;::;:iiiijffKffGfLWGfLDGDLLDGDDEEEEDWEKKKKKKK#EKKKWE##WKKKKKKKEKDEDEWEEDDii;i:: : : .: :,;;;;j;t;;t;;:;;;;:;:;,;;;;;;;;:;,:;;;;::::.:.::ii:i,;,;;i:,i::i:i;,;:i:::;,,;ii, -,;,;,,ii;,;,,:iiittttGDtGDfD#LLGLDfDLDGDEEDEDWEWEKKKKKKEEKDKKKKEWW#KKWKEWDKKKWEWWEEEGt: :...:. ;;;;;;jtt;;;:;;;;,;;;;,;;;;;j;:,,:;,;;;;,::.:: :::;:;;;::,;;:i;,;:::,:::;::,:i::; -iiii;;;;:i,;;iG,itiffWLfDLDWEDfLGDDLDDDEKKEEEEEKKKKKKKKKEWEKKKKWKKKKKWWEEKKK#EWEEKDEEDG . ...:.:. :,;;;;t;;;;;,;;;;;;;;,;;;;itj;;;:;;;;;;;::....: ::,;::,;:;::;::::::;:::::;::::;i: -;,,;;,;ii:i:LEttijffDWffDDDWWDGLGDfDGDEEDEEEKEEWEKEWEKKKWEWWEWEE#WWEWEEWEKE#EWEKDEEDEDEi. ...::;:..;;;;t;;;;;;,;;;;;;;;;;;;;tij;;:;;,;i;;;;.:.:. .: ::::;:::::::::;::::::::::::;:::: -:::::::::::jGiittffDKWtLDEWKKDLDLLDLGDDEEDDKKEKEWWEWEKKKWEWWEWKWW#KWKKEKK#KKEWEWDEEDWDKEDj::..: : ;,;t;;;;;;;;;;;;;i;;;;;;;;;j;;,:;;;;;i;;,:..:.: : :::::::::::::::::::::::::::::::: -::::::::::tKjijtffjE#EffDKKKDDGfGLGLDDEKDEDEKKWEWEWEWWEKKKKW#E##KWEWKKEWWEWEKEEEKKEKDEDEED.:::.:.:;;;;:.;;t;;;;;;it;;;;;;i;it;;:;;,;;;;;,;:.:.. . . :::::::::::::::::::.:::::::::.:. -::::::::::D#iftffffWWDfGDKKKEDLDLLLLLDDDEEEWEKKEWWEWEKKKKKKKKW#WWKKKKKEWKEWEKKKKEEEKDEEDED::....:,;;;,:;;t;;t;;i;;;i;;;;;;;;j;;,;,;;;i;;;;;.::... : :::::::::::.:::.:.::::...::.:... -:::.:::::EKfffjfffGWWLjDDEWDEDGfLLGGGDDDEEKKEWWEWWEWEKKEEWEWW#KWWKKKWEWWKWEKKKEKEEDEDKEKDED;..;::.;,,;;;t;;;;;;;;;;;;;;;;;;;;;;;;:;;;i;;,;:.::.. . .:.::::::::::::::::.::.:..::::::. -..:.:.:.jWGfffffjfD#DDfDEKKEEDLDLLGLDDEDEKDEKKWKEEWEWWEWKKKKK#W#EWKWEWWK#WKKEKEEEEEEKDEDEDDt ::.;;,;:;;;;;;;;;;;;;;i;;;;;;;;,;,;:;;;i;;;;,.:.. :.:. :::.:::.:...:..:::.::.::::::..:. -:::.:::.DKfGfffffLEWDDfDEKKEEGfDLDLGDDEEKDKKDWWEWWWWKKWEE#W#WK#WWWWKK##EWWEKKKEKEEEDEKEKDEED:..;:;;,;;;;;;;;;;;;;;;;;;;;;;;,;;;;;;;;;;;;,;:.:.: ....:::: ::::::::::::::::::::::::.: -:::.::::WfDLLffDfGKEDDfDEEWEDGDDDGGLDEDEEKKKEKKEWWEWWEWEEW#E#WEWWWKWWWKKKEKKKEDKKEWDEKDDEEEDG,::,:;,;;;;;:;;,;;;;,;:;;;,;:;,;;;;;i;;;i;;;,:.::. .....::.:..::::.::::::::;::;:;:;:::: -: :::: iELDDfffGfDWDGEfDDEDKEDLDDfDDDEDKEDEDKKKKWE#KWWWW#KK#WE#WW#KK#E#EWWEWKKKKKDEEKDEEDKDED::;:i;;;;,;:;::;;;,;;,;;;:;;;;;;;;;;;;;i;;,:,.:...... .::.:::..:..:::::::;;:;,;i:i,;i;: -:::.:::fGDDDGffLjD#GDEfDDDKEDGDDLDGLEEEDKEDKKKKKKKKKKWEWWK#E#KK#WKW#KWKWEKKKKKKEKKKKEKDDEDDDD.:;GG;;:;;::;::;:;;:;;;;;;,;;;;;i;;i;;j;;;;;::.:: .. ..:.:.:.::::::.:::;;iiii;i;i;;i;i; -.:::...DGDEWLtGffD#LDDfGEEDEDLDDDfDDDEDKDEEKKEEWKKWE#WKKKWEWKK#K#W#K#W#K#WKKEWEWKEDDKDKEEDEDE::jWG;;;;:;,:;;,;;:;;:,;,;;;i;ii;;;;;i;i;;:.:... : : ...:..::..::::::;:iiiiiiiiiiiii;i -:.::..fWDKKKLfDtLKWLKDfDDDDDGLDDDGDDEWEDEKEWEKKKKE#EWWKWKWWKKKW#KEWK#KWW##KKKKKDKDEEEEEDEDDDD::;;it;;:;:;;::;;;;;:;,;;;;;;;;tji;;;iti;;:...: ...... ....: ::......::;;iiitijiiiii;i; -.:::.:GWEKKKDfDiDEWGKKfGDEDDEGDDDGDEKDEKKDKEEWWKKKKWEK#KWWKWWWWW#KWWWKWKKKKKEWEKKEWKKEKEKDDED;:::;;;;:;:::;;;,;:;;;;;;;;;i;;;jji;iti;;:;;::.:.. . ...:...: :.:.:::::iiiiiiii;iiii;i -:...:iKDEW#ELDDiDWEDEKfDDGDEEDDDDDDEEEKEDKKEWEWKWWKKW#EWWWKKWE##KWEWWWWW#WWKKKKKKEDEEDEKDEEDDi.:;;;;:;:;;:;;,;:;;;;;i;;;;;;;tLjj;;;t;;;::.. . : ...:: ::....: :.:.;:i;iiii;ii;;iii; -.....fWLW#WEDDDjDKDKKKfDEDEWDDDEEEKDEEKEDWKKK##EWWKKWW#WWKKKWW#WK#WKWW#KWWWWWEKKKKEKDEDKDEKDE;:;::;:::;:;:;;;:;;;;;;;;;;;,;;jLj;;i;i;;;,.:...: : :.::..: : ....:.::::;iiiii;i;ii;i,; -:..: GWLWWW#DDLfDDLKKKLGDEDEDEDDEDEKKDEWDEWEWKK#K#KWWWK#KKKKWWWEWWK#WKKK#KKEEKKKKDEEKDKEDEEDEi;:;;:;:;:;:;;;;;;;;i;i;;;;;;;;jGji;ti;;;,,:...:. .. .. : :.::......:::;iii;iii;i;i,i; - :..:DEDW#WELEffDDDWKKfDEEDKDGEDDWDKDKEEWEEWE#KKWWK#W#WWWEK#W#WK#KKK#KWEWWEWWKKKKKKEKEDEKDDDEj::;:;:;:;:;;;tLGGGLL;;;;;;:;,;LLLti;t;;;;:.:.. : :...::..: : t,....:::;:i;ii;i;,;i;i;, - :...EEK##WEDDfLDEEW#DfDEEKDGDDDDKDEDKEDKWWWWKKKKE#WEW#EEKEWWW#K#W#KKWKKKKWEWKKKKKEKEEEEEDDEDj;:;:::;,tLEEEEEEKEKEDj;;;:;;;;ELj;i;t;;,:.:... : . .:::....,D,: ...:::;ii,ii;,;,ii;i,: -: ..iWDE#K##EDffGDKKWELDDDEDDDEDKDEKKEEKKEEWWK#WW#KW#WW#WEKW#K#WWWWK#W#WEKKWKK#KKKEEEDEEEDEDEi:;::,;fGEEEEEEEEEEEEEDG;;;;;;;GGjtti;;;;;:.:: : : .... : .,jD..::...:::,;ii:iiii;:iii; - : iEDEWW#WEEDjfDEE#EDfDDEDGDDEDDKEDKEWWEWWEWKKEWK#WWW#WEKW#K#W#W##KK#EWWWWK#WEWWEKEDEDDEWEEGj;::;jLEEEEEEEEDDEEKWEEEf,;,;;;GLjt;;i;;,:.:. . . :.::..,iDL : : :::;ii;i;i:;,iii;;, -::iWWWEE#K#WDLfLEDKK#DGGDDGDEDEDKEEKKKKKWWKK#KWW##WWW#KWKK#W#W#W#KWW#EWKWWKWWE#KKEKDEEDEDEDEDi;,tLLDEEEEEEDEDEDEEKKEEDEf;;;iELjij;;,;;,:.::..: :: : . ;ijG, : :..:::i;,,;ii;i;,;ii; - :W#KWEEW##WKLfGDKKEWDLDDDDEDDEEKDKDKKKWKWKWWWE#KK#W#WWWWWWW#KWWWWWWWWE#WWWWK#K#KKEEDEKEEEKDEffLGEEEEEEEDEDDDDDDEEWKKEEDDf;fDjtiti;;:;.:...:. . ...:iijDi. : . ::::;ii;i;i;i;,i,;i: -:f##DWDWWWWKELfGDWWWEELDELDDEEWEDEKKWWWKWKKWKKWEWK#K##EKWW##K#EW#WEWWWWKK#KWKKWEKEKEEEEKEDEKDLDEEEEEEEKDDDDDDDDDDEEKEEEDDELLGLjt;;;:,::.:.. ..: ....,ijDf.... : :.::;iiiii,ii;;iii; -iEW#DWEEW##KDDfDEKKWKDLDDGDEDWEDKEWE#WKKWEKKKEWW#W#W##WKW#W#KWK#E##W#WW#WWWWWW#WKEDWDKEDWEEDEDDEDEEEDEDEEDDDDDDDDDEKKKKEDEEKLjj;i;;;;::.:..... : ::.jijDj.: :.: :::::i:ii:i;;iiiiii: -EWW#D#EEW#WWDDfDEKKWEDfDDDEDEWDEEKKKK#WKWKKKKKWWW#W#K#KWW#WWE#EWWW#E#W#WKWWWWKKKDEKEEKDDEEDWEDEEEEEEEDDEDDDDDDDDDDEEKKWKEDDWLjt;;;,;:,.:..... :.:.,tijLf. :.......::::;,:;,;,;;;,;;: -K###DWKK#W#EELfDK#KKKGGDEDDEWKKKKEW##WWWWWEKEW#K#WW#WKK##K#E#WKW#WWW#KW#KK#WKKKEKKDEDEEEWDKKDDEEEDEDDDDDDDDDGDDDDDDEEEKKEEDEGLt;;;;;.::... ... .,,iijjDi : ....::::::::i:::;::::;:: -EWW#D#WDWWW#DLLDKWEKKGGDDEDEKWEKKKWKWW#WWEEWEWWWWWWWWWE###WW#KKWWWW#E##K##WWWWEEDEEEDKDEEKKEEGEGEDDEDDDDDDDDDDGDGDDDEWKWKEEDLjt;;;;.,....::.....,t,ijfD,...: :.: .:.:::::::::::::::: -WEW#E#WEW#WWDGLDKKKWDLLDGDEDKWEKK#WW#W##WKEKEWW#KWWWKWWWW#W#WEW#W##K#WW#KW#WWEEEDEEDEEEKKKEEDKEDDDDDDDDDDGDGDDDGDGDDDEEKWWEELft;;,;;:...:....: .i,ijGDD.... .......: .:..:.:::.:.::: -E##WE#EWWWKWDDfD#W#WELDLGEEEKKKEK#W#WW#EWEWEWWWWW#WWKW#WW##WWWWWWWWWWWWW##KEEDKEKKKEEEEK#WWEEWWEDDDDDDGGGDGDDGDDGDDDDEKKEKEWDft;;,:.:.: .... . .i,jfDDf: ....::..: :.... ::...:::... -KE##W#WEW##WDGfDWWWKDLDfDEEEKKEKKWKW#W#WKWEWEWKK##EW#W#K##WW#EK#W##W#WWWWK#WEKEWEKEDEEKWWEEDK##WEDDDDGDDDGDGDDGDGDDDDEEEKWKEEEf;;;::.::.: ... ..iijLDDi: :..: : : ::.:: :.:. : :. -WE#KKWWD#KWEDGLEWWWEKfLDDDKKKKKK#W#WK#KWKKEWWKW#WK#WEW#WWW##WE##K###E##W#KKEEEEKWEWKEWKWWWEE###WKDGGGDGDGDGDDDDGGGDDDDEEKEKKEED;::;:.....:.. ..,iiLLDD;......::..:... ...: : ::: :: -#KK##WWEWWEWDDLEW#KEEfDDEKKKKWE##W#WK#KWKK#KW#WWWE#W##W#W#WW#EWWW##WWWW#KEKEEDEKKWEEWW#WEEDE####WEDGGGGDDGDGDGGDGGDDDDEEEKEWKEEf;::.:. .: . . .iijLDDi.: : ....:..: :: :..: ..:: ::. -###KW#WEW##WDDfKEW#WDLLDKKDKEWWKWW#K#W#K#KKWKKKWW#K#KK###W#W#K#W#KK#W##W#EKDKKEEKKKKK#KWWEDKWWW##WEDDGDGGDGDGGGDGDGDDDDEEKKKKKKD,.;:..: .......tjfGDD,....:: :.....: ....: :.: : .. -#WW#KWWDK#KWDDLD#W#EDfDDKWEWEKK#W#K##K#EWKWKK#KWWKW#KW#W#W###KKWWWW##W##WWEKDEEWKKKW#W#EKDEE###W#WKDGDGGGDGGDGGGDGDGDEEEEEKKEEKDf,,:.:.:. ... ,jjLDDf ::... :.:....:.:.:...:..::.... -#K####WD#E#EDDLEW#WEDfGEWEWEW#K##K#WW#EWKKWEWWWK##W#WW#W#WW#W#K#K###W#WKKEKDKEWK#W##W#WEDEKEW#WKWW#KDDGGDGGGGDDGGDDDDDEEKKEKEKEEEi;.:.:.. ....ijLLDD,.. :....::....:..:....:...: ::. -W#K#WW#EK#WEDDfK#E#WDfDDWWEKKW#KW#K#WW##KWWWKWE#KWWWKK##W##W#WW#W#WWW#KKWKEKKKKKWE##W#KEDEEEKW##WWW#DGDDGDGDGGGGDGGDDDEDKEKEWEEEDL,:.:. : . .,tjfDDD : : :: :: :: : : :....:: :. -######WE#WEKDELEWW#EDfLEWKKKWW#WWWW#W#KKKKE#WKWWKW#W###W#W##WWW#K####KWEKKKKKKW##W##KKKDEKKEKWWWW#WWEDDGGGGGGDGDGDGDDEEEEKEKKEKEEDt.:.:..... tjjfEDD : ... : :.............. ...: -#WWW#E#D#WEDEDLWWWWKDffKKWKK#W#WWWW##K##EWEW#K#K##W#W#W#W#WK#WEK##W#EKWEKWEW#K#WK#WKWKEEEDDEWWKWWWWWWKDDGGGGGDGDGDDDDEEEEEEEEEEEEDD :.:..:.: jjtDDDf. :.... : : :.... : ..... ....: -W###WW#EE#KEDDfEWWKKDfDDKKKWWK#WW#K##W#KKWWWWKKW#WWWKW#####W##W##W#KKKKKEEWWK#E##K##WWDDEDEDEWWEWWWWWKEDDGGGDGDGDGGDDEDEEKKKEEEEEED..:. . . .iijEDDj : .. ... . .. .: . .. . . -#WW###WKWWEDEDLKW#KEDfDEWKWK#W#KW#WWW#EWKKWWWWWKKK#W#W#W#K###W##W#KKKKKKKKWWWWW##W#KWEEEDEDEKKWKWWWWW#KDGDGGGGGGDGDDDDEEEEEEEEEEDEDi. :..::..jjjDDG,. . .. : .. : . :. ..: : : .. -W#K#W##EWWWEDDLKWKKEDfDEEEW#KWK#WW#WK#WKWEWWWWW#WK#WWW###W#K###W###EKKW#WWE#WWWWWWWWEWDDEDDEEWKKWK#KWWWEDGGGDGDGDGDDDEDKEKEEEEKEEDDf,:. . . .tijDDf.. .. .. .. : .. : . . . -#WWWW##EK#KEEDfKWKWEGfDEKKW#KKWW#K#KWWWWWEWW#E#K##K#KW###W#K#####KWEKKW#WWK##KKWKW#KKKDDDDDDDKWKKKKWW#WWDDGGDGDGGDDDDEDEEEKEEEDEDEDDL, .:...,jjGDDt : .: : ...... : ... : ....: .. -#W#W#W#WKKEDDDLKWW#EDfGKK#KW###WW#K#K#KKKWW#KWW#WW#K##K##K###W#W##EKKW#K#E#E#WWWWEKKWWEEDEEDEKKKKKWWKWWWEDDGGGGDDGDDDDEEEEEEKEEDEDDDDj.: ...tjDEDG,. .. . .: .: ....:.... : ... : .. -WWW#W###EWKEDDLKKWKDDfGKKKW#WK#KWWWW#W#KWWWWEWK#WKW#KW##W###W####WWEWWW#WWE#K#WK#KWKWWEDEDEDEWKWKKKKWWWWWEDGDGGGDGDDDEEDEEEEEEDDDDEDDD.... .tDEDDD, ... :......... : : .: :: ..... -WW###W##EWEEDDLKEWEKGfDEWW#W##WWW#KW#W#WE#WWWEW#WE#K###WK#WWK###WWEKWW#W#KWW#W#EEKKKW#WDDDDEDEKKKKKKKW#WWWWGGGGGDGDDDDEDEEEEEEDDDDDDDDj. ..;DEDDDL...:..:...:...::.........:..::..: -##W#KW##EKWDGDfKKKKEDfDKEWWWWW#WK#K#WWWKWKW#KKK#WW#W##W#######W##WW#K##K##KW#KW#WEK#KKEEDKEDEDEWKWKWWKWKW#WDDGGGDGDDDEEEEEEEEDDDDDDDDDL,.. tEEDDDf..: ::..:: ::.::.::::..:..:..:.::. -WWK#W###DEEEGDLEKKKKDfDEWK#K##W##W#EW#KWWW#KKW#W##WWWW##W#W#W##W#KEWKWW#KWK##W#KEEWW##KDEDDDEEDKWKWKWWWWWWWEDGDGGDDDDDEDEEEEDEDDDDDDDDGL .,tEDKDGf.:.:. :...:. : :..:.::..: :. :... -W#W#W###DEWEDGGEDKKEDLDKK#K#WW###W#WK#KWWW#EWW#W##W#K##WW#W#WW##WKKKKKWWWWWWK#KWKKK##KKEDEEDEEEDWKKKWKW#WWWWKDGGGDGDDDEDEEEEEDEDDDGDGDDDD.LDEEDDDj:..:::....::.:..: ::.:.... :...:.: -#KW#WW##EEKDGDfDEKWEDLEK#K#K##W##K#KWWWWW#K#KWK###WW#W##W####W#KWE#EW##WWWW##WKKKK#WWKKDEDKKEEDEKWWWWKWKWWW#KEGGGGGDDEDEEEDEDDDDDDDDDGGGDjGDEDDDGj.:: ::.::: ::..::...: :.:::.....: diff --git a/jun_springboot_plugin/springboot_shiro/src/main/resources/database/import.sql b/jun_springboot_plugin/springboot_shiro/src/main/resources/database/import.sql deleted file mode 100644 index 73a7f02a01..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/resources/database/import.sql +++ /dev/null @@ -1,12 +0,0 @@ -INSERT INTO `user_info` (`uid`,`username`,`name`,`password`,`salt`,`state`) VALUES ('1', 'admin', '管理员', 'd3c59d25033dbf980d29554025c23a75', '8d78869f470951332959580424d4bf4f', 0); -INSERT INTO `sys_permission` (`id`,`available`,`name`,`parent_id`,`parent_ids`,`permission`,`resource_type`,`url`) VALUES (1,0,'用户管理',0,'0/','userInfo:view','menu','userInfo/userList'); -INSERT INTO `sys_permission` (`id`,`available`,`name`,`parent_id`,`parent_ids`,`permission`,`resource_type`,`url`) VALUES (2,0,'用户添加',1,'0/1','userInfo:add','button','userInfo/userAdd'); -INSERT INTO `sys_permission` (`id`,`available`,`name`,`parent_id`,`parent_ids`,`permission`,`resource_type`,`url`) VALUES (3,0,'用户删除',1,'0/1','userInfo:del','button','userInfo/userDel'); -INSERT INTO `sys_role` (`id`,`available`,`description`,`role`) VALUES (1,0,'管理员','admin'); -INSERT INTO `sys_role` (`id`,`available`,`description`,`role`) VALUES (2,0,'VIP会员','vip'); -INSERT INTO `sys_role` (`id`,`available`,`description`,`role`) VALUES (3,1,'test','test'); -INSERT INTO `sys_role_permission` VALUES ('1', '1'); -INSERT INTO `sys_role_permission` (`permission_id`,`role_id`) VALUES (1,1); -INSERT INTO `sys_role_permission` (`permission_id`,`role_id`) VALUES (2,1); -INSERT INTO `sys_role_permission` (`permission_id`,`role_id`) VALUES (3,2); -INSERT INTO `sys_user_role` (`role_id`,`uid`) VALUES (1,1); \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_shiro/src/main/resources/ehcache.xml b/jun_springboot_plugin/springboot_shiro/src/main/resources/ehcache.xml deleted file mode 100644 index 4c585ea612..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/resources/ehcache.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/favicon.ico b/jun_springboot_plugin/springboot_shiro/src/main/resources/public/favicon.ico deleted file mode 100644 index fe6cf7a760..0000000000 Binary files a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/favicon.ico and /dev/null differ diff --git a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/css/404.css b/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/css/404.css deleted file mode 100644 index b2fe0bc68b..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/css/404.css +++ /dev/null @@ -1,36 +0,0 @@ -body, div { - margin: 0; - padding: 0; -} -body { - background: url("../img/error/error_bg.jpg") repeat-x scroll 0 0 #67ACE4; -} -#container { - margin: 0 auto; - padding-top: 50px; - text-align: center; - width: 560px; -} -#container img { - border: medium none; - margin-bottom: 50px; -} -#container .error { - height: 200px; - position: relative; -} -#container .error img { - bottom: -50px; - position: absolute; - right: -50px; -} -#container .msg { - margin-bottom: 65px; -} -#cloud { - background: url("../img/error/error_cloud.png") repeat-x scroll 0 0 transparent; - bottom: 0; - height: 170px; - position: absolute; - width: 100%; -} \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/css/bootstrap.min.css b/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/css/bootstrap.min.css deleted file mode 100644 index f7bca0ac07..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/css/bootstrap.min.css +++ /dev/null @@ -1,6 +0,0 @@ -/*! - * Bootstrap v3.3.6 (http://getbootstrap.com) - * Copyright 2011-2015 Twitter, Inc. - * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) - *//*! normalize.css v3.0.3 | MIT License | github.com/necolas/normalize.css */html{font-family:sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}body{margin:0}article,aside,details,figcaption,figure,footer,header,hgroup,main,menu,nav,section,summary{display:block}audio,canvas,progress,video{display:inline-block;vertical-align:baseline}audio:not([controls]){display:none;height:0}[hidden],template{display:none}a{background-color:transparent}a:active,a:hover{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:700}dfn{font-style:italic}h1{margin:.67em 0;font-size:2em}mark{color:#000;background:#ff0}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sup{top:-.5em}sub{bottom:-.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:1em 40px}hr{height:0;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box}pre{overflow:auto}code,kbd,pre,samp{font-family:monospace,monospace;font-size:1em}button,input,optgroup,select,textarea{margin:0;font:inherit;color:inherit}button{overflow:visible}button,select{text-transform:none}button,html input[type=button],input[type=reset],input[type=submit]{-webkit-appearance:button;cursor:pointer}button[disabled],html input[disabled]{cursor:default}button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0}input{line-height:normal}input[type=checkbox],input[type=radio]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:0}input[type=number]::-webkit-inner-spin-button,input[type=number]::-webkit-outer-spin-button{height:auto}input[type=search]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield}input[type=search]::-webkit-search-cancel-button,input[type=search]::-webkit-search-decoration{-webkit-appearance:none}fieldset{padding:.35em .625em .75em;margin:0 2px;border:1px solid silver}legend{padding:0;border:0}textarea{overflow:auto}optgroup{font-weight:700}table{border-spacing:0;border-collapse:collapse}td,th{padding:0}/*! Source: https://github.com/h5bp/html5-boilerplate/blob/master/src/css/main.css */@media print{*,:after,:before{color:#000!important;text-shadow:none!important;background:0 0!important;-webkit-box-shadow:none!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}a[href^="javascript:"]:after,a[href^="#"]:after{content:""}blockquote,pre{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}img,tr{page-break-inside:avoid}img{max-width:100%!important}h2,h3,p{orphans:3;widows:3}h2,h3{page-break-after:avoid}.navbar{display:none}.btn>.caret,.dropup>.btn>.caret{border-top-color:#000!important}.label{border:1px solid #000}.table{border-collapse:collapse!important}.table td,.table th{background-color:#fff!important}.table-bordered td,.table-bordered th{border:1px solid #ddd!important}}@font-face{font-family:'Glyphicons Halflings';src:url(../fonts/glyphicons-halflings-regular.eot);src:url(../fonts/glyphicons-halflings-regular.eot?#iefix) format('embedded-opentype'),url(../fonts/glyphicons-halflings-regular.woff2) format('woff2'),url(../fonts/glyphicons-halflings-regular.woff) format('woff'),url(../fonts/glyphicons-halflings-regular.ttf) format('truetype'),url(../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular) format('svg')}.glyphicon{position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';font-style:normal;font-weight:400;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.glyphicon-asterisk:before{content:"\002a"}.glyphicon-plus:before{content:"\002b"}.glyphicon-eur:before,.glyphicon-euro:before{content:"\20ac"}.glyphicon-minus:before{content:"\2212"}.glyphicon-cloud:before{content:"\2601"}.glyphicon-envelope:before{content:"\2709"}.glyphicon-pencil:before{content:"\270f"}.glyphicon-glass:before{content:"\e001"}.glyphicon-music:before{content:"\e002"}.glyphicon-search:before{content:"\e003"}.glyphicon-heart:before{content:"\e005"}.glyphicon-star:before{content:"\e006"}.glyphicon-star-empty:before{content:"\e007"}.glyphicon-user:before{content:"\e008"}.glyphicon-film:before{content:"\e009"}.glyphicon-th-large:before{content:"\e010"}.glyphicon-th:before{content:"\e011"}.glyphicon-th-list:before{content:"\e012"}.glyphicon-ok:before{content:"\e013"}.glyphicon-remove:before{content:"\e014"}.glyphicon-zoom-in:before{content:"\e015"}.glyphicon-zoom-out:before{content:"\e016"}.glyphicon-off:before{content:"\e017"}.glyphicon-signal:before{content:"\e018"}.glyphicon-cog:before{content:"\e019"}.glyphicon-trash:before{content:"\e020"}.glyphicon-home:before{content:"\e021"}.glyphicon-file:before{content:"\e022"}.glyphicon-time:before{content:"\e023"}.glyphicon-road:before{content:"\e024"}.glyphicon-download-alt:before{content:"\e025"}.glyphicon-download:before{content:"\e026"}.glyphicon-upload:before{content:"\e027"}.glyphicon-inbox:before{content:"\e028"}.glyphicon-play-circle:before{content:"\e029"}.glyphicon-repeat:before{content:"\e030"}.glyphicon-refresh:before{content:"\e031"}.glyphicon-list-alt:before{content:"\e032"}.glyphicon-lock:before{content:"\e033"}.glyphicon-flag:before{content:"\e034"}.glyphicon-headphones:before{content:"\e035"}.glyphicon-volume-off:before{content:"\e036"}.glyphicon-volume-down:before{content:"\e037"}.glyphicon-volume-up:before{content:"\e038"}.glyphicon-qrcode:before{content:"\e039"}.glyphicon-barcode:before{content:"\e040"}.glyphicon-tag:before{content:"\e041"}.glyphicon-tags:before{content:"\e042"}.glyphicon-book:before{content:"\e043"}.glyphicon-bookmark:before{content:"\e044"}.glyphicon-print:before{content:"\e045"}.glyphicon-camera:before{content:"\e046"}.glyphicon-font:before{content:"\e047"}.glyphicon-bold:before{content:"\e048"}.glyphicon-italic:before{content:"\e049"}.glyphicon-text-height:before{content:"\e050"}.glyphicon-text-width:before{content:"\e051"}.glyphicon-align-left:before{content:"\e052"}.glyphicon-align-center:before{content:"\e053"}.glyphicon-align-right:before{content:"\e054"}.glyphicon-align-justify:before{content:"\e055"}.glyphicon-list:before{content:"\e056"}.glyphicon-indent-left:before{content:"\e057"}.glyphicon-indent-right:before{content:"\e058"}.glyphicon-facetime-video:before{content:"\e059"}.glyphicon-picture:before{content:"\e060"}.glyphicon-map-marker:before{content:"\e062"}.glyphicon-adjust:before{content:"\e063"}.glyphicon-tint:before{content:"\e064"}.glyphicon-edit:before{content:"\e065"}.glyphicon-share:before{content:"\e066"}.glyphicon-check:before{content:"\e067"}.glyphicon-move:before{content:"\e068"}.glyphicon-step-backward:before{content:"\e069"}.glyphicon-fast-backward:before{content:"\e070"}.glyphicon-backward:before{content:"\e071"}.glyphicon-play:before{content:"\e072"}.glyphicon-pause:before{content:"\e073"}.glyphicon-stop:before{content:"\e074"}.glyphicon-forward:before{content:"\e075"}.glyphicon-fast-forward:before{content:"\e076"}.glyphicon-step-forward:before{content:"\e077"}.glyphicon-eject:before{content:"\e078"}.glyphicon-chevron-left:before{content:"\e079"}.glyphicon-chevron-right:before{content:"\e080"}.glyphicon-plus-sign:before{content:"\e081"}.glyphicon-minus-sign:before{content:"\e082"}.glyphicon-remove-sign:before{content:"\e083"}.glyphicon-ok-sign:before{content:"\e084"}.glyphicon-question-sign:before{content:"\e085"}.glyphicon-info-sign:before{content:"\e086"}.glyphicon-screenshot:before{content:"\e087"}.glyphicon-remove-circle:before{content:"\e088"}.glyphicon-ok-circle:before{content:"\e089"}.glyphicon-ban-circle:before{content:"\e090"}.glyphicon-arrow-left:before{content:"\e091"}.glyphicon-arrow-right:before{content:"\e092"}.glyphicon-arrow-up:before{content:"\e093"}.glyphicon-arrow-down:before{content:"\e094"}.glyphicon-share-alt:before{content:"\e095"}.glyphicon-resize-full:before{content:"\e096"}.glyphicon-resize-small:before{content:"\e097"}.glyphicon-exclamation-sign:before{content:"\e101"}.glyphicon-gift:before{content:"\e102"}.glyphicon-leaf:before{content:"\e103"}.glyphicon-fire:before{content:"\e104"}.glyphicon-eye-open:before{content:"\e105"}.glyphicon-eye-close:before{content:"\e106"}.glyphicon-warning-sign:before{content:"\e107"}.glyphicon-plane:before{content:"\e108"}.glyphicon-calendar:before{content:"\e109"}.glyphicon-random:before{content:"\e110"}.glyphicon-comment:before{content:"\e111"}.glyphicon-magnet:before{content:"\e112"}.glyphicon-chevron-up:before{content:"\e113"}.glyphicon-chevron-down:before{content:"\e114"}.glyphicon-retweet:before{content:"\e115"}.glyphicon-shopping-cart:before{content:"\e116"}.glyphicon-folder-close:before{content:"\e117"}.glyphicon-folder-open:before{content:"\e118"}.glyphicon-resize-vertical:before{content:"\e119"}.glyphicon-resize-horizontal:before{content:"\e120"}.glyphicon-hdd:before{content:"\e121"}.glyphicon-bullhorn:before{content:"\e122"}.glyphicon-bell:before{content:"\e123"}.glyphicon-certificate:before{content:"\e124"}.glyphicon-thumbs-up:before{content:"\e125"}.glyphicon-thumbs-down:before{content:"\e126"}.glyphicon-hand-right:before{content:"\e127"}.glyphicon-hand-left:before{content:"\e128"}.glyphicon-hand-up:before{content:"\e129"}.glyphicon-hand-down:before{content:"\e130"}.glyphicon-circle-arrow-right:before{content:"\e131"}.glyphicon-circle-arrow-left:before{content:"\e132"}.glyphicon-circle-arrow-up:before{content:"\e133"}.glyphicon-circle-arrow-down:before{content:"\e134"}.glyphicon-globe:before{content:"\e135"}.glyphicon-wrench:before{content:"\e136"}.glyphicon-tasks:before{content:"\e137"}.glyphicon-filter:before{content:"\e138"}.glyphicon-briefcase:before{content:"\e139"}.glyphicon-fullscreen:before{content:"\e140"}.glyphicon-dashboard:before{content:"\e141"}.glyphicon-paperclip:before{content:"\e142"}.glyphicon-heart-empty:before{content:"\e143"}.glyphicon-link:before{content:"\e144"}.glyphicon-phone:before{content:"\e145"}.glyphicon-pushpin:before{content:"\e146"}.glyphicon-usd:before{content:"\e148"}.glyphicon-gbp:before{content:"\e149"}.glyphicon-sort:before{content:"\e150"}.glyphicon-sort-by-alphabet:before{content:"\e151"}.glyphicon-sort-by-alphabet-alt:before{content:"\e152"}.glyphicon-sort-by-order:before{content:"\e153"}.glyphicon-sort-by-order-alt:before{content:"\e154"}.glyphicon-sort-by-attributes:before{content:"\e155"}.glyphicon-sort-by-attributes-alt:before{content:"\e156"}.glyphicon-unchecked:before{content:"\e157"}.glyphicon-expand:before{content:"\e158"}.glyphicon-collapse-down:before{content:"\e159"}.glyphicon-collapse-up:before{content:"\e160"}.glyphicon-log-in:before{content:"\e161"}.glyphicon-flash:before{content:"\e162"}.glyphicon-log-out:before{content:"\e163"}.glyphicon-new-window:before{content:"\e164"}.glyphicon-record:before{content:"\e165"}.glyphicon-save:before{content:"\e166"}.glyphicon-open:before{content:"\e167"}.glyphicon-saved:before{content:"\e168"}.glyphicon-import:before{content:"\e169"}.glyphicon-export:before{content:"\e170"}.glyphicon-send:before{content:"\e171"}.glyphicon-floppy-disk:before{content:"\e172"}.glyphicon-floppy-saved:before{content:"\e173"}.glyphicon-floppy-remove:before{content:"\e174"}.glyphicon-floppy-save:before{content:"\e175"}.glyphicon-floppy-open:before{content:"\e176"}.glyphicon-credit-card:before{content:"\e177"}.glyphicon-transfer:before{content:"\e178"}.glyphicon-cutlery:before{content:"\e179"}.glyphicon-header:before{content:"\e180"}.glyphicon-compressed:before{content:"\e181"}.glyphicon-earphone:before{content:"\e182"}.glyphicon-phone-alt:before{content:"\e183"}.glyphicon-tower:before{content:"\e184"}.glyphicon-stats:before{content:"\e185"}.glyphicon-sd-video:before{content:"\e186"}.glyphicon-hd-video:before{content:"\e187"}.glyphicon-subtitles:before{content:"\e188"}.glyphicon-sound-stereo:before{content:"\e189"}.glyphicon-sound-dolby:before{content:"\e190"}.glyphicon-sound-5-1:before{content:"\e191"}.glyphicon-sound-6-1:before{content:"\e192"}.glyphicon-sound-7-1:before{content:"\e193"}.glyphicon-copyright-mark:before{content:"\e194"}.glyphicon-registration-mark:before{content:"\e195"}.glyphicon-cloud-download:before{content:"\e197"}.glyphicon-cloud-upload:before{content:"\e198"}.glyphicon-tree-conifer:before{content:"\e199"}.glyphicon-tree-deciduous:before{content:"\e200"}.glyphicon-cd:before{content:"\e201"}.glyphicon-save-file:before{content:"\e202"}.glyphicon-open-file:before{content:"\e203"}.glyphicon-level-up:before{content:"\e204"}.glyphicon-copy:before{content:"\e205"}.glyphicon-paste:before{content:"\e206"}.glyphicon-alert:before{content:"\e209"}.glyphicon-equalizer:before{content:"\e210"}.glyphicon-king:before{content:"\e211"}.glyphicon-queen:before{content:"\e212"}.glyphicon-pawn:before{content:"\e213"}.glyphicon-bishop:before{content:"\e214"}.glyphicon-knight:before{content:"\e215"}.glyphicon-baby-formula:before{content:"\e216"}.glyphicon-tent:before{content:"\26fa"}.glyphicon-blackboard:before{content:"\e218"}.glyphicon-bed:before{content:"\e219"}.glyphicon-apple:before{content:"\f8ff"}.glyphicon-erase:before{content:"\e221"}.glyphicon-hourglass:before{content:"\231b"}.glyphicon-lamp:before{content:"\e223"}.glyphicon-duplicate:before{content:"\e224"}.glyphicon-piggy-bank:before{content:"\e225"}.glyphicon-scissors:before{content:"\e226"}.glyphicon-bitcoin:before{content:"\e227"}.glyphicon-btc:before{content:"\e227"}.glyphicon-xbt:before{content:"\e227"}.glyphicon-yen:before{content:"\00a5"}.glyphicon-jpy:before{content:"\00a5"}.glyphicon-ruble:before{content:"\20bd"}.glyphicon-rub:before{content:"\20bd"}.glyphicon-scale:before{content:"\e230"}.glyphicon-ice-lolly:before{content:"\e231"}.glyphicon-ice-lolly-tasted:before{content:"\e232"}.glyphicon-education:before{content:"\e233"}.glyphicon-option-horizontal:before{content:"\e234"}.glyphicon-option-vertical:before{content:"\e235"}.glyphicon-menu-hamburger:before{content:"\e236"}.glyphicon-modal-window:before{content:"\e237"}.glyphicon-oil:before{content:"\e238"}.glyphicon-grain:before{content:"\e239"}.glyphicon-sunglasses:before{content:"\e240"}.glyphicon-text-size:before{content:"\e241"}.glyphicon-text-color:before{content:"\e242"}.glyphicon-text-background:before{content:"\e243"}.glyphicon-object-align-top:before{content:"\e244"}.glyphicon-object-align-bottom:before{content:"\e245"}.glyphicon-object-align-horizontal:before{content:"\e246"}.glyphicon-object-align-left:before{content:"\e247"}.glyphicon-object-align-vertical:before{content:"\e248"}.glyphicon-object-align-right:before{content:"\e249"}.glyphicon-triangle-right:before{content:"\e250"}.glyphicon-triangle-left:before{content:"\e251"}.glyphicon-triangle-bottom:before{content:"\e252"}.glyphicon-triangle-top:before{content:"\e253"}.glyphicon-console:before{content:"\e254"}.glyphicon-superscript:before{content:"\e255"}.glyphicon-subscript:before{content:"\e256"}.glyphicon-menu-left:before{content:"\e257"}.glyphicon-menu-right:before{content:"\e258"}.glyphicon-menu-down:before{content:"\e259"}.glyphicon-menu-up:before{content:"\e260"}*{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}:after,:before{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}html{font-size:10px;-webkit-tap-highlight-color:rgba(0,0,0,0)}body{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.42857143;color:#333;background-color:#fff}button,input,select,textarea{font-family:inherit;font-size:inherit;line-height:inherit}a{color:#337ab7;text-decoration:none}a:focus,a:hover{color:#23527c;text-decoration:underline}a:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}figure{margin:0}img{vertical-align:middle}.carousel-inner>.item>a>img,.carousel-inner>.item>img,.img-responsive,.thumbnail a>img,.thumbnail>img{display:block;max-width:100%;height:auto}.img-rounded{border-radius:6px}.img-thumbnail{display:inline-block;max-width:100%;height:auto;padding:4px;line-height:1.42857143;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;-o-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.img-circle{border-radius:50%}hr{margin-top:20px;margin-bottom:20px;border:0;border-top:1px solid #eee}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);border:0}.sr-only-focusable:active,.sr-only-focusable:focus{position:static;width:auto;height:auto;margin:0;overflow:visible;clip:auto}[role=button]{cursor:pointer}.h1,.h2,.h3,.h4,.h5,.h6,h1,h2,h3,h4,h5,h6{font-family:inherit;font-weight:500;line-height:1.1;color:inherit}.h1 .small,.h1 small,.h2 .small,.h2 small,.h3 .small,.h3 small,.h4 .small,.h4 small,.h5 .small,.h5 small,.h6 .small,.h6 small,h1 .small,h1 small,h2 .small,h2 small,h3 .small,h3 small,h4 .small,h4 small,h5 .small,h5 small,h6 .small,h6 small{font-weight:400;line-height:1;color:#777}.h1,.h2,.h3,h1,h2,h3{margin-top:20px;margin-bottom:10px}.h1 .small,.h1 small,.h2 .small,.h2 small,.h3 .small,.h3 small,h1 .small,h1 small,h2 .small,h2 small,h3 .small,h3 small{font-size:65%}.h4,.h5,.h6,h4,h5,h6{margin-top:10px;margin-bottom:10px}.h4 .small,.h4 small,.h5 .small,.h5 small,.h6 .small,.h6 small,h4 .small,h4 small,h5 .small,h5 small,h6 .small,h6 small{font-size:75%}.h1,h1{font-size:36px}.h2,h2{font-size:30px}.h3,h3{font-size:24px}.h4,h4{font-size:18px}.h5,h5{font-size:14px}.h6,h6{font-size:12px}p{margin:0 0 10px}.lead{margin-bottom:20px;font-size:16px;font-weight:300;line-height:1.4}@media (min-width:768px){.lead{font-size:21px}}.small,small{font-size:85%}.mark,mark{padding:.2em;background-color:#fcf8e3}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}.text-justify{text-align:justify}.text-nowrap{white-space:nowrap}.text-lowercase{text-transform:lowercase}.text-uppercase{text-transform:uppercase}.text-capitalize{text-transform:capitalize}.text-muted{color:#777}.text-primary{color:#337ab7}a.text-primary:focus,a.text-primary:hover{color:#286090}.text-success{color:#3c763d}a.text-success:focus,a.text-success:hover{color:#2b542c}.text-info{color:#31708f}a.text-info:focus,a.text-info:hover{color:#245269}.text-warning{color:#8a6d3b}a.text-warning:focus,a.text-warning:hover{color:#66512c}.text-danger{color:#a94442}a.text-danger:focus,a.text-danger:hover{color:#843534}.bg-primary{color:#fff;background-color:#337ab7}a.bg-primary:focus,a.bg-primary:hover{background-color:#286090}.bg-success{background-color:#dff0d8}a.bg-success:focus,a.bg-success:hover{background-color:#c1e2b3}.bg-info{background-color:#d9edf7}a.bg-info:focus,a.bg-info:hover{background-color:#afd9ee}.bg-warning{background-color:#fcf8e3}a.bg-warning:focus,a.bg-warning:hover{background-color:#f7ecb5}.bg-danger{background-color:#f2dede}a.bg-danger:focus,a.bg-danger:hover{background-color:#e4b9b9}.page-header{padding-bottom:9px;margin:40px 0 20px;border-bottom:1px solid #eee}ol,ul{margin-top:0;margin-bottom:10px}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;margin-left:-5px;list-style:none}.list-inline>li{display:inline-block;padding-right:5px;padding-left:5px}dl{margin-top:0;margin-bottom:20px}dd,dt{line-height:1.42857143}dt{font-weight:700}dd{margin-left:0}@media (min-width:768px){.dl-horizontal dt{float:left;width:160px;overflow:hidden;clear:left;text-align:right;text-overflow:ellipsis;white-space:nowrap}.dl-horizontal dd{margin-left:180px}}abbr[data-original-title],abbr[title]{cursor:help;border-bottom:1px dotted #777}.initialism{font-size:90%;text-transform:uppercase}blockquote{padding:10px 20px;margin:0 0 20px;font-size:17.5px;border-left:5px solid #eee}blockquote ol:last-child,blockquote p:last-child,blockquote ul:last-child{margin-bottom:0}blockquote .small,blockquote footer,blockquote small{display:block;font-size:80%;line-height:1.42857143;color:#777}blockquote .small:before,blockquote footer:before,blockquote small:before{content:'\2014 \00A0'}.blockquote-reverse,blockquote.pull-right{padding-right:15px;padding-left:0;text-align:right;border-right:5px solid #eee;border-left:0}.blockquote-reverse .small:before,.blockquote-reverse footer:before,.blockquote-reverse small:before,blockquote.pull-right .small:before,blockquote.pull-right footer:before,blockquote.pull-right small:before{content:''}.blockquote-reverse .small:after,.blockquote-reverse footer:after,.blockquote-reverse small:after,blockquote.pull-right .small:after,blockquote.pull-right footer:after,blockquote.pull-right small:after{content:'\00A0 \2014'}address{margin-bottom:20px;font-style:normal;line-height:1.42857143}code,kbd,pre,samp{font-family:Menlo,Monaco,Consolas,"Courier New",monospace}code{padding:2px 4px;font-size:90%;color:#c7254e;background-color:#f9f2f4;border-radius:4px}kbd{padding:2px 4px;font-size:90%;color:#fff;background-color:#333;border-radius:3px;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,.25);box-shadow:inset 0 -1px 0 rgba(0,0,0,.25)}kbd kbd{padding:0;font-size:100%;font-weight:700;-webkit-box-shadow:none;box-shadow:none}pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:1.42857143;color:#333;word-break:break-all;word-wrap:break-word;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}pre code{padding:0;font-size:inherit;color:inherit;white-space:pre-wrap;background-color:transparent;border-radius:0}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}@media (min-width:768px){.container{width:750px}}@media (min-width:992px){.container{width:970px}}@media (min-width:1200px){.container{width:1170px}}.container-fluid{padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}.row{margin-right:-15px;margin-left:-15px}.col-lg-1,.col-lg-10,.col-lg-11,.col-lg-12,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-md-1,.col-md-10,.col-md-11,.col-md-12,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-sm-1,.col-sm-10,.col-sm-11,.col-sm-12,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-xs-1,.col-xs-10,.col-xs-11,.col-xs-12,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9{position:relative;min-height:1px;padding-right:15px;padding-left:15px}.col-xs-1,.col-xs-10,.col-xs-11,.col-xs-12,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9{float:left}.col-xs-12{width:100%}.col-xs-11{width:91.66666667%}.col-xs-10{width:83.33333333%}.col-xs-9{width:75%}.col-xs-8{width:66.66666667%}.col-xs-7{width:58.33333333%}.col-xs-6{width:50%}.col-xs-5{width:41.66666667%}.col-xs-4{width:33.33333333%}.col-xs-3{width:25%}.col-xs-2{width:16.66666667%}.col-xs-1{width:8.33333333%}.col-xs-pull-12{right:100%}.col-xs-pull-11{right:91.66666667%}.col-xs-pull-10{right:83.33333333%}.col-xs-pull-9{right:75%}.col-xs-pull-8{right:66.66666667%}.col-xs-pull-7{right:58.33333333%}.col-xs-pull-6{right:50%}.col-xs-pull-5{right:41.66666667%}.col-xs-pull-4{right:33.33333333%}.col-xs-pull-3{right:25%}.col-xs-pull-2{right:16.66666667%}.col-xs-pull-1{right:8.33333333%}.col-xs-pull-0{right:auto}.col-xs-push-12{left:100%}.col-xs-push-11{left:91.66666667%}.col-xs-push-10{left:83.33333333%}.col-xs-push-9{left:75%}.col-xs-push-8{left:66.66666667%}.col-xs-push-7{left:58.33333333%}.col-xs-push-6{left:50%}.col-xs-push-5{left:41.66666667%}.col-xs-push-4{left:33.33333333%}.col-xs-push-3{left:25%}.col-xs-push-2{left:16.66666667%}.col-xs-push-1{left:8.33333333%}.col-xs-push-0{left:auto}.col-xs-offset-12{margin-left:100%}.col-xs-offset-11{margin-left:91.66666667%}.col-xs-offset-10{margin-left:83.33333333%}.col-xs-offset-9{margin-left:75%}.col-xs-offset-8{margin-left:66.66666667%}.col-xs-offset-7{margin-left:58.33333333%}.col-xs-offset-6{margin-left:50%}.col-xs-offset-5{margin-left:41.66666667%}.col-xs-offset-4{margin-left:33.33333333%}.col-xs-offset-3{margin-left:25%}.col-xs-offset-2{margin-left:16.66666667%}.col-xs-offset-1{margin-left:8.33333333%}.col-xs-offset-0{margin-left:0}@media (min-width:768px){.col-sm-1,.col-sm-10,.col-sm-11,.col-sm-12,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9{float:left}.col-sm-12{width:100%}.col-sm-11{width:91.66666667%}.col-sm-10{width:83.33333333%}.col-sm-9{width:75%}.col-sm-8{width:66.66666667%}.col-sm-7{width:58.33333333%}.col-sm-6{width:50%}.col-sm-5{width:41.66666667%}.col-sm-4{width:33.33333333%}.col-sm-3{width:25%}.col-sm-2{width:16.66666667%}.col-sm-1{width:8.33333333%}.col-sm-pull-12{right:100%}.col-sm-pull-11{right:91.66666667%}.col-sm-pull-10{right:83.33333333%}.col-sm-pull-9{right:75%}.col-sm-pull-8{right:66.66666667%}.col-sm-pull-7{right:58.33333333%}.col-sm-pull-6{right:50%}.col-sm-pull-5{right:41.66666667%}.col-sm-pull-4{right:33.33333333%}.col-sm-pull-3{right:25%}.col-sm-pull-2{right:16.66666667%}.col-sm-pull-1{right:8.33333333%}.col-sm-pull-0{right:auto}.col-sm-push-12{left:100%}.col-sm-push-11{left:91.66666667%}.col-sm-push-10{left:83.33333333%}.col-sm-push-9{left:75%}.col-sm-push-8{left:66.66666667%}.col-sm-push-7{left:58.33333333%}.col-sm-push-6{left:50%}.col-sm-push-5{left:41.66666667%}.col-sm-push-4{left:33.33333333%}.col-sm-push-3{left:25%}.col-sm-push-2{left:16.66666667%}.col-sm-push-1{left:8.33333333%}.col-sm-push-0{left:auto}.col-sm-offset-12{margin-left:100%}.col-sm-offset-11{margin-left:91.66666667%}.col-sm-offset-10{margin-left:83.33333333%}.col-sm-offset-9{margin-left:75%}.col-sm-offset-8{margin-left:66.66666667%}.col-sm-offset-7{margin-left:58.33333333%}.col-sm-offset-6{margin-left:50%}.col-sm-offset-5{margin-left:41.66666667%}.col-sm-offset-4{margin-left:33.33333333%}.col-sm-offset-3{margin-left:25%}.col-sm-offset-2{margin-left:16.66666667%}.col-sm-offset-1{margin-left:8.33333333%}.col-sm-offset-0{margin-left:0}}@media (min-width:992px){.col-md-1,.col-md-10,.col-md-11,.col-md-12,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9{float:left}.col-md-12{width:100%}.col-md-11{width:91.66666667%}.col-md-10{width:83.33333333%}.col-md-9{width:75%}.col-md-8{width:66.66666667%}.col-md-7{width:58.33333333%}.col-md-6{width:50%}.col-md-5{width:41.66666667%}.col-md-4{width:33.33333333%}.col-md-3{width:25%}.col-md-2{width:16.66666667%}.col-md-1{width:8.33333333%}.col-md-pull-12{right:100%}.col-md-pull-11{right:91.66666667%}.col-md-pull-10{right:83.33333333%}.col-md-pull-9{right:75%}.col-md-pull-8{right:66.66666667%}.col-md-pull-7{right:58.33333333%}.col-md-pull-6{right:50%}.col-md-pull-5{right:41.66666667%}.col-md-pull-4{right:33.33333333%}.col-md-pull-3{right:25%}.col-md-pull-2{right:16.66666667%}.col-md-pull-1{right:8.33333333%}.col-md-pull-0{right:auto}.col-md-push-12{left:100%}.col-md-push-11{left:91.66666667%}.col-md-push-10{left:83.33333333%}.col-md-push-9{left:75%}.col-md-push-8{left:66.66666667%}.col-md-push-7{left:58.33333333%}.col-md-push-6{left:50%}.col-md-push-5{left:41.66666667%}.col-md-push-4{left:33.33333333%}.col-md-push-3{left:25%}.col-md-push-2{left:16.66666667%}.col-md-push-1{left:8.33333333%}.col-md-push-0{left:auto}.col-md-offset-12{margin-left:100%}.col-md-offset-11{margin-left:91.66666667%}.col-md-offset-10{margin-left:83.33333333%}.col-md-offset-9{margin-left:75%}.col-md-offset-8{margin-left:66.66666667%}.col-md-offset-7{margin-left:58.33333333%}.col-md-offset-6{margin-left:50%}.col-md-offset-5{margin-left:41.66666667%}.col-md-offset-4{margin-left:33.33333333%}.col-md-offset-3{margin-left:25%}.col-md-offset-2{margin-left:16.66666667%}.col-md-offset-1{margin-left:8.33333333%}.col-md-offset-0{margin-left:0}}@media (min-width:1200px){.col-lg-1,.col-lg-10,.col-lg-11,.col-lg-12,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9{float:left}.col-lg-12{width:100%}.col-lg-11{width:91.66666667%}.col-lg-10{width:83.33333333%}.col-lg-9{width:75%}.col-lg-8{width:66.66666667%}.col-lg-7{width:58.33333333%}.col-lg-6{width:50%}.col-lg-5{width:41.66666667%}.col-lg-4{width:33.33333333%}.col-lg-3{width:25%}.col-lg-2{width:16.66666667%}.col-lg-1{width:8.33333333%}.col-lg-pull-12{right:100%}.col-lg-pull-11{right:91.66666667%}.col-lg-pull-10{right:83.33333333%}.col-lg-pull-9{right:75%}.col-lg-pull-8{right:66.66666667%}.col-lg-pull-7{right:58.33333333%}.col-lg-pull-6{right:50%}.col-lg-pull-5{right:41.66666667%}.col-lg-pull-4{right:33.33333333%}.col-lg-pull-3{right:25%}.col-lg-pull-2{right:16.66666667%}.col-lg-pull-1{right:8.33333333%}.col-lg-pull-0{right:auto}.col-lg-push-12{left:100%}.col-lg-push-11{left:91.66666667%}.col-lg-push-10{left:83.33333333%}.col-lg-push-9{left:75%}.col-lg-push-8{left:66.66666667%}.col-lg-push-7{left:58.33333333%}.col-lg-push-6{left:50%}.col-lg-push-5{left:41.66666667%}.col-lg-push-4{left:33.33333333%}.col-lg-push-3{left:25%}.col-lg-push-2{left:16.66666667%}.col-lg-push-1{left:8.33333333%}.col-lg-push-0{left:auto}.col-lg-offset-12{margin-left:100%}.col-lg-offset-11{margin-left:91.66666667%}.col-lg-offset-10{margin-left:83.33333333%}.col-lg-offset-9{margin-left:75%}.col-lg-offset-8{margin-left:66.66666667%}.col-lg-offset-7{margin-left:58.33333333%}.col-lg-offset-6{margin-left:50%}.col-lg-offset-5{margin-left:41.66666667%}.col-lg-offset-4{margin-left:33.33333333%}.col-lg-offset-3{margin-left:25%}.col-lg-offset-2{margin-left:16.66666667%}.col-lg-offset-1{margin-left:8.33333333%}.col-lg-offset-0{margin-left:0}}table{background-color:transparent}caption{padding-top:8px;padding-bottom:8px;color:#777;text-align:left}th{text-align:left}.table{width:100%;max-width:100%;margin-bottom:20px}.table>tbody>tr>td,.table>tbody>tr>th,.table>tfoot>tr>td,.table>tfoot>tr>th,.table>thead>tr>td,.table>thead>tr>th{padding:8px;line-height:1.42857143;vertical-align:top;border-top:1px solid #ddd}.table>thead>tr>th{vertical-align:bottom;border-bottom:2px solid #ddd}.table>caption+thead>tr:first-child>td,.table>caption+thead>tr:first-child>th,.table>colgroup+thead>tr:first-child>td,.table>colgroup+thead>tr:first-child>th,.table>thead:first-child>tr:first-child>td,.table>thead:first-child>tr:first-child>th{border-top:0}.table>tbody+tbody{border-top:2px solid #ddd}.table .table{background-color:#fff}.table-condensed>tbody>tr>td,.table-condensed>tbody>tr>th,.table-condensed>tfoot>tr>td,.table-condensed>tfoot>tr>th,.table-condensed>thead>tr>td,.table-condensed>thead>tr>th{padding:5px}.table-bordered{border:1px solid #ddd}.table-bordered>tbody>tr>td,.table-bordered>tbody>tr>th,.table-bordered>tfoot>tr>td,.table-bordered>tfoot>tr>th,.table-bordered>thead>tr>td,.table-bordered>thead>tr>th{border:1px solid #ddd}.table-bordered>thead>tr>td,.table-bordered>thead>tr>th{border-bottom-width:2px}.table-striped>tbody>tr:nth-of-type(odd){background-color:#f9f9f9}.table-hover>tbody>tr:hover{background-color:#f5f5f5}table col[class*=col-]{position:static;display:table-column;float:none}table td[class*=col-],table th[class*=col-]{position:static;display:table-cell;float:none}.table>tbody>tr.active>td,.table>tbody>tr.active>th,.table>tbody>tr>td.active,.table>tbody>tr>th.active,.table>tfoot>tr.active>td,.table>tfoot>tr.active>th,.table>tfoot>tr>td.active,.table>tfoot>tr>th.active,.table>thead>tr.active>td,.table>thead>tr.active>th,.table>thead>tr>td.active,.table>thead>tr>th.active{background-color:#f5f5f5}.table-hover>tbody>tr.active:hover>td,.table-hover>tbody>tr.active:hover>th,.table-hover>tbody>tr:hover>.active,.table-hover>tbody>tr>td.active:hover,.table-hover>tbody>tr>th.active:hover{background-color:#e8e8e8}.table>tbody>tr.success>td,.table>tbody>tr.success>th,.table>tbody>tr>td.success,.table>tbody>tr>th.success,.table>tfoot>tr.success>td,.table>tfoot>tr.success>th,.table>tfoot>tr>td.success,.table>tfoot>tr>th.success,.table>thead>tr.success>td,.table>thead>tr.success>th,.table>thead>tr>td.success,.table>thead>tr>th.success{background-color:#dff0d8}.table-hover>tbody>tr.success:hover>td,.table-hover>tbody>tr.success:hover>th,.table-hover>tbody>tr:hover>.success,.table-hover>tbody>tr>td.success:hover,.table-hover>tbody>tr>th.success:hover{background-color:#d0e9c6}.table>tbody>tr.info>td,.table>tbody>tr.info>th,.table>tbody>tr>td.info,.table>tbody>tr>th.info,.table>tfoot>tr.info>td,.table>tfoot>tr.info>th,.table>tfoot>tr>td.info,.table>tfoot>tr>th.info,.table>thead>tr.info>td,.table>thead>tr.info>th,.table>thead>tr>td.info,.table>thead>tr>th.info{background-color:#d9edf7}.table-hover>tbody>tr.info:hover>td,.table-hover>tbody>tr.info:hover>th,.table-hover>tbody>tr:hover>.info,.table-hover>tbody>tr>td.info:hover,.table-hover>tbody>tr>th.info:hover{background-color:#c4e3f3}.table>tbody>tr.warning>td,.table>tbody>tr.warning>th,.table>tbody>tr>td.warning,.table>tbody>tr>th.warning,.table>tfoot>tr.warning>td,.table>tfoot>tr.warning>th,.table>tfoot>tr>td.warning,.table>tfoot>tr>th.warning,.table>thead>tr.warning>td,.table>thead>tr.warning>th,.table>thead>tr>td.warning,.table>thead>tr>th.warning{background-color:#fcf8e3}.table-hover>tbody>tr.warning:hover>td,.table-hover>tbody>tr.warning:hover>th,.table-hover>tbody>tr:hover>.warning,.table-hover>tbody>tr>td.warning:hover,.table-hover>tbody>tr>th.warning:hover{background-color:#faf2cc}.table>tbody>tr.danger>td,.table>tbody>tr.danger>th,.table>tbody>tr>td.danger,.table>tbody>tr>th.danger,.table>tfoot>tr.danger>td,.table>tfoot>tr.danger>th,.table>tfoot>tr>td.danger,.table>tfoot>tr>th.danger,.table>thead>tr.danger>td,.table>thead>tr.danger>th,.table>thead>tr>td.danger,.table>thead>tr>th.danger{background-color:#f2dede}.table-hover>tbody>tr.danger:hover>td,.table-hover>tbody>tr.danger:hover>th,.table-hover>tbody>tr:hover>.danger,.table-hover>tbody>tr>td.danger:hover,.table-hover>tbody>tr>th.danger:hover{background-color:#ebcccc}.table-responsive{min-height:.01%;overflow-x:auto}@media screen and (max-width:767px){.table-responsive{width:100%;margin-bottom:15px;overflow-y:hidden;-ms-overflow-style:-ms-autohiding-scrollbar;border:1px solid #ddd}.table-responsive>.table{margin-bottom:0}.table-responsive>.table>tbody>tr>td,.table-responsive>.table>tbody>tr>th,.table-responsive>.table>tfoot>tr>td,.table-responsive>.table>tfoot>tr>th,.table-responsive>.table>thead>tr>td,.table-responsive>.table>thead>tr>th{white-space:nowrap}.table-responsive>.table-bordered{border:0}.table-responsive>.table-bordered>tbody>tr>td:first-child,.table-responsive>.table-bordered>tbody>tr>th:first-child,.table-responsive>.table-bordered>tfoot>tr>td:first-child,.table-responsive>.table-bordered>tfoot>tr>th:first-child,.table-responsive>.table-bordered>thead>tr>td:first-child,.table-responsive>.table-bordered>thead>tr>th:first-child{border-left:0}.table-responsive>.table-bordered>tbody>tr>td:last-child,.table-responsive>.table-bordered>tbody>tr>th:last-child,.table-responsive>.table-bordered>tfoot>tr>td:last-child,.table-responsive>.table-bordered>tfoot>tr>th:last-child,.table-responsive>.table-bordered>thead>tr>td:last-child,.table-responsive>.table-bordered>thead>tr>th:last-child{border-right:0}.table-responsive>.table-bordered>tbody>tr:last-child>td,.table-responsive>.table-bordered>tbody>tr:last-child>th,.table-responsive>.table-bordered>tfoot>tr:last-child>td,.table-responsive>.table-bordered>tfoot>tr:last-child>th{border-bottom:0}}fieldset{min-width:0;padding:0;margin:0;border:0}legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:inherit;color:#333;border:0;border-bottom:1px solid #e5e5e5}label{display:inline-block;max-width:100%;margin-bottom:5px;font-weight:700}input[type=search]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}input[type=checkbox],input[type=radio]{margin:4px 0 0;margin-top:1px\9;line-height:normal}input[type=file]{display:block}input[type=range]{display:block;width:100%}select[multiple],select[size]{height:auto}input[type=file]:focus,input[type=checkbox]:focus,input[type=radio]:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}output{display:block;padding-top:7px;font-size:14px;line-height:1.42857143;color:#555}.form-control{display:block;width:100%;height:34px;padding:6px 12px;font-size:14px;line-height:1.42857143;color:#555;background-color:#fff;background-image:none;border:1px solid #ccc;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-webkit-transition:border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;-o-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.form-control:focus{border-color:#66afe9;outline:0;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}.form-control::-moz-placeholder{color:#999;opacity:1}.form-control:-ms-input-placeholder{color:#999}.form-control::-webkit-input-placeholder{color:#999}.form-control::-ms-expand{background-color:transparent;border:0}.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control{background-color:#eee;opacity:1}.form-control[disabled],fieldset[disabled] .form-control{cursor:not-allowed}textarea.form-control{height:auto}input[type=search]{-webkit-appearance:none}@media screen and (-webkit-min-device-pixel-ratio:0){input[type=date].form-control,input[type=time].form-control,input[type=datetime-local].form-control,input[type=month].form-control{line-height:34px}.input-group-sm input[type=date],.input-group-sm input[type=time],.input-group-sm input[type=datetime-local],.input-group-sm input[type=month],input[type=date].input-sm,input[type=time].input-sm,input[type=datetime-local].input-sm,input[type=month].input-sm{line-height:30px}.input-group-lg input[type=date],.input-group-lg input[type=time],.input-group-lg input[type=datetime-local],.input-group-lg input[type=month],input[type=date].input-lg,input[type=time].input-lg,input[type=datetime-local].input-lg,input[type=month].input-lg{line-height:46px}}.form-group{margin-bottom:15px}.checkbox,.radio{position:relative;display:block;margin-top:10px;margin-bottom:10px}.checkbox label,.radio label{min-height:20px;padding-left:20px;margin-bottom:0;font-weight:400;cursor:pointer}.checkbox input[type=checkbox],.checkbox-inline input[type=checkbox],.radio input[type=radio],.radio-inline input[type=radio]{position:absolute;margin-top:4px\9;margin-left:-20px}.checkbox+.checkbox,.radio+.radio{margin-top:-5px}.checkbox-inline,.radio-inline{position:relative;display:inline-block;padding-left:20px;margin-bottom:0;font-weight:400;vertical-align:middle;cursor:pointer}.checkbox-inline+.checkbox-inline,.radio-inline+.radio-inline{margin-top:0;margin-left:10px}fieldset[disabled] input[type=checkbox],fieldset[disabled] input[type=radio],input[type=checkbox].disabled,input[type=checkbox][disabled],input[type=radio].disabled,input[type=radio][disabled]{cursor:not-allowed}.checkbox-inline.disabled,.radio-inline.disabled,fieldset[disabled] .checkbox-inline,fieldset[disabled] .radio-inline{cursor:not-allowed}.checkbox.disabled label,.radio.disabled label,fieldset[disabled] .checkbox label,fieldset[disabled] .radio label{cursor:not-allowed}.form-control-static{min-height:34px;padding-top:7px;padding-bottom:7px;margin-bottom:0}.form-control-static.input-lg,.form-control-static.input-sm{padding-right:0;padding-left:0}.input-sm{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-sm{height:30px;line-height:30px}select[multiple].input-sm,textarea.input-sm{height:auto}.form-group-sm .form-control{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.form-group-sm select.form-control{height:30px;line-height:30px}.form-group-sm select[multiple].form-control,.form-group-sm textarea.form-control{height:auto}.form-group-sm .form-control-static{height:30px;min-height:32px;padding:6px 10px;font-size:12px;line-height:1.5}.input-lg{height:46px;padding:10px 16px;font-size:18px;line-height:1.3333333;border-radius:6px}select.input-lg{height:46px;line-height:46px}select[multiple].input-lg,textarea.input-lg{height:auto}.form-group-lg .form-control{height:46px;padding:10px 16px;font-size:18px;line-height:1.3333333;border-radius:6px}.form-group-lg select.form-control{height:46px;line-height:46px}.form-group-lg select[multiple].form-control,.form-group-lg textarea.form-control{height:auto}.form-group-lg .form-control-static{height:46px;min-height:38px;padding:11px 16px;font-size:18px;line-height:1.3333333}.has-feedback{position:relative}.has-feedback .form-control{padding-right:42.5px}.form-control-feedback{position:absolute;top:0;right:0;z-index:2;display:block;width:34px;height:34px;line-height:34px;text-align:center;pointer-events:none}.form-group-lg .form-control+.form-control-feedback,.input-group-lg+.form-control-feedback,.input-lg+.form-control-feedback{width:46px;height:46px;line-height:46px}.form-group-sm .form-control+.form-control-feedback,.input-group-sm+.form-control-feedback,.input-sm+.form-control-feedback{width:30px;height:30px;line-height:30px}.has-success .checkbox,.has-success .checkbox-inline,.has-success .control-label,.has-success .help-block,.has-success .radio,.has-success .radio-inline,.has-success.checkbox label,.has-success.checkbox-inline label,.has-success.radio label,.has-success.radio-inline label{color:#3c763d}.has-success .form-control{border-color:#3c763d;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-success .form-control:focus{border-color:#2b542c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168}.has-success .input-group-addon{color:#3c763d;background-color:#dff0d8;border-color:#3c763d}.has-success .form-control-feedback{color:#3c763d}.has-warning .checkbox,.has-warning .checkbox-inline,.has-warning .control-label,.has-warning .help-block,.has-warning .radio,.has-warning .radio-inline,.has-warning.checkbox label,.has-warning.checkbox-inline label,.has-warning.radio label,.has-warning.radio-inline label{color:#8a6d3b}.has-warning .form-control{border-color:#8a6d3b;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-warning .form-control:focus{border-color:#66512c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b}.has-warning .input-group-addon{color:#8a6d3b;background-color:#fcf8e3;border-color:#8a6d3b}.has-warning .form-control-feedback{color:#8a6d3b}.has-error .checkbox,.has-error .checkbox-inline,.has-error .control-label,.has-error .help-block,.has-error .radio,.has-error .radio-inline,.has-error.checkbox label,.has-error.checkbox-inline label,.has-error.radio label,.has-error.radio-inline label{color:#a94442}.has-error .form-control{border-color:#a94442;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-error .form-control:focus{border-color:#843534;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483}.has-error .input-group-addon{color:#a94442;background-color:#f2dede;border-color:#a94442}.has-error .form-control-feedback{color:#a94442}.has-feedback label~.form-control-feedback{top:25px}.has-feedback label.sr-only~.form-control-feedback{top:0}.help-block{display:block;margin-top:5px;margin-bottom:10px;color:#737373}@media (min-width:768px){.form-inline .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.form-inline .form-control{display:inline-block;width:auto;vertical-align:middle}.form-inline .form-control-static{display:inline-block}.form-inline .input-group{display:inline-table;vertical-align:middle}.form-inline .input-group .form-control,.form-inline .input-group .input-group-addon,.form-inline .input-group .input-group-btn{width:auto}.form-inline .input-group>.form-control{width:100%}.form-inline .control-label{margin-bottom:0;vertical-align:middle}.form-inline .checkbox,.form-inline .radio{display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}.form-inline .checkbox label,.form-inline .radio label{padding-left:0}.form-inline .checkbox input[type=checkbox],.form-inline .radio input[type=radio]{position:relative;margin-left:0}.form-inline .has-feedback .form-control-feedback{top:0}}.form-horizontal .checkbox,.form-horizontal .checkbox-inline,.form-horizontal .radio,.form-horizontal .radio-inline{padding-top:7px;margin-top:0;margin-bottom:0}.form-horizontal .checkbox,.form-horizontal .radio{min-height:27px}.form-horizontal .form-group{margin-right:-15px;margin-left:-15px}@media (min-width:768px){.form-horizontal .control-label{padding-top:7px;margin-bottom:0;text-align:right}}.form-horizontal .has-feedback .form-control-feedback{right:15px}@media (min-width:768px){.form-horizontal .form-group-lg .control-label{padding-top:11px;font-size:18px}}@media (min-width:768px){.form-horizontal .form-group-sm .control-label{padding-top:6px;font-size:12px}}.btn{display:inline-block;padding:6px 12px;margin-bottom:0;font-size:14px;font-weight:400;line-height:1.42857143;text-align:center;white-space:nowrap;vertical-align:middle;-ms-touch-action:manipulation;touch-action:manipulation;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;background-image:none;border:1px solid transparent;border-radius:4px}.btn.active.focus,.btn.active:focus,.btn.focus,.btn:active.focus,.btn:active:focus,.btn:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.focus,.btn:focus,.btn:hover{color:#333;text-decoration:none}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn.disabled,.btn[disabled],fieldset[disabled] .btn{cursor:not-allowed;filter:alpha(opacity=65);-webkit-box-shadow:none;box-shadow:none;opacity:.65}a.btn.disabled,fieldset[disabled] a.btn{pointer-events:none}.btn-default{color:#333;background-color:#fff;border-color:#ccc}.btn-default.focus,.btn-default:focus{color:#333;background-color:#e6e6e6;border-color:#8c8c8c}.btn-default:hover{color:#333;background-color:#e6e6e6;border-color:#adadad}.btn-default.active,.btn-default:active,.open>.dropdown-toggle.btn-default{color:#333;background-color:#e6e6e6;border-color:#adadad}.btn-default.active.focus,.btn-default.active:focus,.btn-default.active:hover,.btn-default:active.focus,.btn-default:active:focus,.btn-default:active:hover,.open>.dropdown-toggle.btn-default.focus,.open>.dropdown-toggle.btn-default:focus,.open>.dropdown-toggle.btn-default:hover{color:#333;background-color:#d4d4d4;border-color:#8c8c8c}.btn-default.active,.btn-default:active,.open>.dropdown-toggle.btn-default{background-image:none}.btn-default.disabled.focus,.btn-default.disabled:focus,.btn-default.disabled:hover,.btn-default[disabled].focus,.btn-default[disabled]:focus,.btn-default[disabled]:hover,fieldset[disabled] .btn-default.focus,fieldset[disabled] .btn-default:focus,fieldset[disabled] .btn-default:hover{background-color:#fff;border-color:#ccc}.btn-default .badge{color:#fff;background-color:#333}.btn-primary{color:#fff;background-color:#337ab7;border-color:#2e6da4}.btn-primary.focus,.btn-primary:focus{color:#fff;background-color:#286090;border-color:#122b40}.btn-primary:hover{color:#fff;background-color:#286090;border-color:#204d74}.btn-primary.active,.btn-primary:active,.open>.dropdown-toggle.btn-primary{color:#fff;background-color:#286090;border-color:#204d74}.btn-primary.active.focus,.btn-primary.active:focus,.btn-primary.active:hover,.btn-primary:active.focus,.btn-primary:active:focus,.btn-primary:active:hover,.open>.dropdown-toggle.btn-primary.focus,.open>.dropdown-toggle.btn-primary:focus,.open>.dropdown-toggle.btn-primary:hover{color:#fff;background-color:#204d74;border-color:#122b40}.btn-primary.active,.btn-primary:active,.open>.dropdown-toggle.btn-primary{background-image:none}.btn-primary.disabled.focus,.btn-primary.disabled:focus,.btn-primary.disabled:hover,.btn-primary[disabled].focus,.btn-primary[disabled]:focus,.btn-primary[disabled]:hover,fieldset[disabled] .btn-primary.focus,fieldset[disabled] .btn-primary:focus,fieldset[disabled] .btn-primary:hover{background-color:#337ab7;border-color:#2e6da4}.btn-primary .badge{color:#337ab7;background-color:#fff}.btn-success{color:#fff;background-color:#5cb85c;border-color:#4cae4c}.btn-success.focus,.btn-success:focus{color:#fff;background-color:#449d44;border-color:#255625}.btn-success:hover{color:#fff;background-color:#449d44;border-color:#398439}.btn-success.active,.btn-success:active,.open>.dropdown-toggle.btn-success{color:#fff;background-color:#449d44;border-color:#398439}.btn-success.active.focus,.btn-success.active:focus,.btn-success.active:hover,.btn-success:active.focus,.btn-success:active:focus,.btn-success:active:hover,.open>.dropdown-toggle.btn-success.focus,.open>.dropdown-toggle.btn-success:focus,.open>.dropdown-toggle.btn-success:hover{color:#fff;background-color:#398439;border-color:#255625}.btn-success.active,.btn-success:active,.open>.dropdown-toggle.btn-success{background-image:none}.btn-success.disabled.focus,.btn-success.disabled:focus,.btn-success.disabled:hover,.btn-success[disabled].focus,.btn-success[disabled]:focus,.btn-success[disabled]:hover,fieldset[disabled] .btn-success.focus,fieldset[disabled] .btn-success:focus,fieldset[disabled] .btn-success:hover{background-color:#5cb85c;border-color:#4cae4c}.btn-success .badge{color:#5cb85c;background-color:#fff}.btn-info{color:#fff;background-color:#5bc0de;border-color:#46b8da}.btn-info.focus,.btn-info:focus{color:#fff;background-color:#31b0d5;border-color:#1b6d85}.btn-info:hover{color:#fff;background-color:#31b0d5;border-color:#269abc}.btn-info.active,.btn-info:active,.open>.dropdown-toggle.btn-info{color:#fff;background-color:#31b0d5;border-color:#269abc}.btn-info.active.focus,.btn-info.active:focus,.btn-info.active:hover,.btn-info:active.focus,.btn-info:active:focus,.btn-info:active:hover,.open>.dropdown-toggle.btn-info.focus,.open>.dropdown-toggle.btn-info:focus,.open>.dropdown-toggle.btn-info:hover{color:#fff;background-color:#269abc;border-color:#1b6d85}.btn-info.active,.btn-info:active,.open>.dropdown-toggle.btn-info{background-image:none}.btn-info.disabled.focus,.btn-info.disabled:focus,.btn-info.disabled:hover,.btn-info[disabled].focus,.btn-info[disabled]:focus,.btn-info[disabled]:hover,fieldset[disabled] .btn-info.focus,fieldset[disabled] .btn-info:focus,fieldset[disabled] .btn-info:hover{background-color:#5bc0de;border-color:#46b8da}.btn-info .badge{color:#5bc0de;background-color:#fff}.btn-warning{color:#fff;background-color:#f0ad4e;border-color:#eea236}.btn-warning.focus,.btn-warning:focus{color:#fff;background-color:#ec971f;border-color:#985f0d}.btn-warning:hover{color:#fff;background-color:#ec971f;border-color:#d58512}.btn-warning.active,.btn-warning:active,.open>.dropdown-toggle.btn-warning{color:#fff;background-color:#ec971f;border-color:#d58512}.btn-warning.active.focus,.btn-warning.active:focus,.btn-warning.active:hover,.btn-warning:active.focus,.btn-warning:active:focus,.btn-warning:active:hover,.open>.dropdown-toggle.btn-warning.focus,.open>.dropdown-toggle.btn-warning:focus,.open>.dropdown-toggle.btn-warning:hover{color:#fff;background-color:#d58512;border-color:#985f0d}.btn-warning.active,.btn-warning:active,.open>.dropdown-toggle.btn-warning{background-image:none}.btn-warning.disabled.focus,.btn-warning.disabled:focus,.btn-warning.disabled:hover,.btn-warning[disabled].focus,.btn-warning[disabled]:focus,.btn-warning[disabled]:hover,fieldset[disabled] .btn-warning.focus,fieldset[disabled] .btn-warning:focus,fieldset[disabled] .btn-warning:hover{background-color:#f0ad4e;border-color:#eea236}.btn-warning .badge{color:#f0ad4e;background-color:#fff}.btn-danger{color:#fff;background-color:#d9534f;border-color:#d43f3a}.btn-danger.focus,.btn-danger:focus{color:#fff;background-color:#c9302c;border-color:#761c19}.btn-danger:hover{color:#fff;background-color:#c9302c;border-color:#ac2925}.btn-danger.active,.btn-danger:active,.open>.dropdown-toggle.btn-danger{color:#fff;background-color:#c9302c;border-color:#ac2925}.btn-danger.active.focus,.btn-danger.active:focus,.btn-danger.active:hover,.btn-danger:active.focus,.btn-danger:active:focus,.btn-danger:active:hover,.open>.dropdown-toggle.btn-danger.focus,.open>.dropdown-toggle.btn-danger:focus,.open>.dropdown-toggle.btn-danger:hover{color:#fff;background-color:#ac2925;border-color:#761c19}.btn-danger.active,.btn-danger:active,.open>.dropdown-toggle.btn-danger{background-image:none}.btn-danger.disabled.focus,.btn-danger.disabled:focus,.btn-danger.disabled:hover,.btn-danger[disabled].focus,.btn-danger[disabled]:focus,.btn-danger[disabled]:hover,fieldset[disabled] .btn-danger.focus,fieldset[disabled] .btn-danger:focus,fieldset[disabled] .btn-danger:hover{background-color:#d9534f;border-color:#d43f3a}.btn-danger .badge{color:#d9534f;background-color:#fff}.btn-link{font-weight:400;color:#337ab7;border-radius:0}.btn-link,.btn-link.active,.btn-link:active,.btn-link[disabled],fieldset[disabled] .btn-link{background-color:transparent;-webkit-box-shadow:none;box-shadow:none}.btn-link,.btn-link:active,.btn-link:focus,.btn-link:hover{border-color:transparent}.btn-link:focus,.btn-link:hover{color:#23527c;text-decoration:underline;background-color:transparent}.btn-link[disabled]:focus,.btn-link[disabled]:hover,fieldset[disabled] .btn-link:focus,fieldset[disabled] .btn-link:hover{color:#777;text-decoration:none}.btn-group-lg>.btn,.btn-lg{padding:10px 16px;font-size:18px;line-height:1.3333333;border-radius:6px}.btn-group-sm>.btn,.btn-sm{padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.btn-group-xs>.btn,.btn-xs{padding:1px 5px;font-size:12px;line-height:1.5;border-radius:3px}.btn-block{display:block;width:100%}.btn-block+.btn-block{margin-top:5px}input[type=button].btn-block,input[type=reset].btn-block,input[type=submit].btn-block{width:100%}.fade{opacity:0;-webkit-transition:opacity .15s linear;-o-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{display:none}.collapse.in{display:block}tr.collapse.in{display:table-row}tbody.collapse.in{display:table-row-group}.collapsing{position:relative;height:0;overflow:hidden;-webkit-transition-timing-function:ease;-o-transition-timing-function:ease;transition-timing-function:ease;-webkit-transition-duration:.35s;-o-transition-duration:.35s;transition-duration:.35s;-webkit-transition-property:height,visibility;-o-transition-property:height,visibility;transition-property:height,visibility}.caret{display:inline-block;width:0;height:0;margin-left:2px;vertical-align:middle;border-top:4px dashed;border-top:4px solid\9;border-right:4px solid transparent;border-left:4px solid transparent}.dropdown,.dropup{position:relative}.dropdown-toggle:focus{outline:0}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;font-size:14px;text-align:left;list-style:none;background-color:#fff;-webkit-background-clip:padding-box;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0,0,0,.15);border-radius:4px;-webkit-box-shadow:0 6px 12px rgba(0,0,0,.175);box-shadow:0 6px 12px rgba(0,0,0,.175)}.dropdown-menu.pull-right{right:0;left:auto}.dropdown-menu .divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:400;line-height:1.42857143;color:#333;white-space:nowrap}.dropdown-menu>li>a:focus,.dropdown-menu>li>a:hover{color:#262626;text-decoration:none;background-color:#f5f5f5}.dropdown-menu>.active>a,.dropdown-menu>.active>a:focus,.dropdown-menu>.active>a:hover{color:#fff;text-decoration:none;background-color:#337ab7;outline:0}.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:focus,.dropdown-menu>.disabled>a:hover{color:#777}.dropdown-menu>.disabled>a:focus,.dropdown-menu>.disabled>a:hover{text-decoration:none;cursor:not-allowed;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.open>.dropdown-menu{display:block}.open>a{outline:0}.dropdown-menu-right{right:0;left:auto}.dropdown-menu-left{right:auto;left:0}.dropdown-header{display:block;padding:3px 20px;font-size:12px;line-height:1.42857143;color:#777;white-space:nowrap}.dropdown-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:990}.pull-right>.dropdown-menu{right:0;left:auto}.dropup .caret,.navbar-fixed-bottom .dropdown .caret{content:"";border-top:0;border-bottom:4px dashed;border-bottom:4px solid\9}.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:2px}@media (min-width:768px){.navbar-right .dropdown-menu{right:0;left:auto}.navbar-right .dropdown-menu-left{right:auto;left:0}}.btn-group,.btn-group-vertical{position:relative;display:inline-block;vertical-align:middle}.btn-group-vertical>.btn,.btn-group>.btn{position:relative;float:left}.btn-group-vertical>.btn.active,.btn-group-vertical>.btn:active,.btn-group-vertical>.btn:focus,.btn-group-vertical>.btn:hover,.btn-group>.btn.active,.btn-group>.btn:active,.btn-group>.btn:focus,.btn-group>.btn:hover{z-index:2}.btn-group .btn+.btn,.btn-group .btn+.btn-group,.btn-group .btn-group+.btn,.btn-group .btn-group+.btn-group{margin-left:-1px}.btn-toolbar{margin-left:-5px}.btn-toolbar .btn,.btn-toolbar .btn-group,.btn-toolbar .input-group{float:left}.btn-toolbar>.btn,.btn-toolbar>.btn-group,.btn-toolbar>.input-group{margin-left:5px}.btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle){border-radius:0}.btn-group>.btn:first-child{margin-left:0}.btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn:last-child:not(:first-child),.btn-group>.dropdown-toggle:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.btn-group>.btn-group{float:left}.btn-group>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group>.btn-group:first-child:not(:last-child)>.btn:last-child,.btn-group>.btn-group:first-child:not(:last-child)>.dropdown-toggle{border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn-group:last-child:not(:first-child)>.btn:first-child{border-top-left-radius:0;border-bottom-left-radius:0}.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0}.btn-group>.btn+.dropdown-toggle{padding-right:8px;padding-left:8px}.btn-group>.btn-lg+.dropdown-toggle{padding-right:12px;padding-left:12px}.btn-group.open .dropdown-toggle{-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn-group.open .dropdown-toggle.btn-link{-webkit-box-shadow:none;box-shadow:none}.btn .caret{margin-left:0}.btn-lg .caret{border-width:5px 5px 0;border-bottom-width:0}.dropup .btn-lg .caret{border-width:0 5px 5px}.btn-group-vertical>.btn,.btn-group-vertical>.btn-group,.btn-group-vertical>.btn-group>.btn{display:block;float:none;width:100%;max-width:100%}.btn-group-vertical>.btn-group>.btn{float:none}.btn-group-vertical>.btn+.btn,.btn-group-vertical>.btn+.btn-group,.btn-group-vertical>.btn-group+.btn,.btn-group-vertical>.btn-group+.btn-group{margin-top:-1px;margin-left:0}.btn-group-vertical>.btn:not(:first-child):not(:last-child){border-radius:0}.btn-group-vertical>.btn:first-child:not(:last-child){border-top-left-radius:4px;border-top-right-radius:4px;border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn:last-child:not(:first-child){border-top-left-radius:0;border-top-right-radius:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}.btn-group-vertical>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group-vertical>.btn-group:first-child:not(:last-child)>.btn:last-child,.btn-group-vertical>.btn-group:first-child:not(:last-child)>.dropdown-toggle{border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn-group:last-child:not(:first-child)>.btn:first-child{border-top-left-radius:0;border-top-right-radius:0}.btn-group-justified{display:table;width:100%;table-layout:fixed;border-collapse:separate}.btn-group-justified>.btn,.btn-group-justified>.btn-group{display:table-cell;float:none;width:1%}.btn-group-justified>.btn-group .btn{width:100%}.btn-group-justified>.btn-group .dropdown-menu{left:auto}[data-toggle=buttons]>.btn input[type=checkbox],[data-toggle=buttons]>.btn input[type=radio],[data-toggle=buttons]>.btn-group>.btn input[type=checkbox],[data-toggle=buttons]>.btn-group>.btn input[type=radio]{position:absolute;clip:rect(0,0,0,0);pointer-events:none}.input-group{position:relative;display:table;border-collapse:separate}.input-group[class*=col-]{float:none;padding-right:0;padding-left:0}.input-group .form-control{position:relative;z-index:2;float:left;width:100%;margin-bottom:0}.input-group .form-control:focus{z-index:3}.input-group-lg>.form-control,.input-group-lg>.input-group-addon,.input-group-lg>.input-group-btn>.btn{height:46px;padding:10px 16px;font-size:18px;line-height:1.3333333;border-radius:6px}select.input-group-lg>.form-control,select.input-group-lg>.input-group-addon,select.input-group-lg>.input-group-btn>.btn{height:46px;line-height:46px}select[multiple].input-group-lg>.form-control,select[multiple].input-group-lg>.input-group-addon,select[multiple].input-group-lg>.input-group-btn>.btn,textarea.input-group-lg>.form-control,textarea.input-group-lg>.input-group-addon,textarea.input-group-lg>.input-group-btn>.btn{height:auto}.input-group-sm>.form-control,.input-group-sm>.input-group-addon,.input-group-sm>.input-group-btn>.btn{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-group-sm>.form-control,select.input-group-sm>.input-group-addon,select.input-group-sm>.input-group-btn>.btn{height:30px;line-height:30px}select[multiple].input-group-sm>.form-control,select[multiple].input-group-sm>.input-group-addon,select[multiple].input-group-sm>.input-group-btn>.btn,textarea.input-group-sm>.form-control,textarea.input-group-sm>.input-group-addon,textarea.input-group-sm>.input-group-btn>.btn{height:auto}.input-group .form-control,.input-group-addon,.input-group-btn{display:table-cell}.input-group .form-control:not(:first-child):not(:last-child),.input-group-addon:not(:first-child):not(:last-child),.input-group-btn:not(:first-child):not(:last-child){border-radius:0}.input-group-addon,.input-group-btn{width:1%;white-space:nowrap;vertical-align:middle}.input-group-addon{padding:6px 12px;font-size:14px;font-weight:400;line-height:1;color:#555;text-align:center;background-color:#eee;border:1px solid #ccc;border-radius:4px}.input-group-addon.input-sm{padding:5px 10px;font-size:12px;border-radius:3px}.input-group-addon.input-lg{padding:10px 16px;font-size:18px;border-radius:6px}.input-group-addon input[type=checkbox],.input-group-addon input[type=radio]{margin-top:0}.input-group .form-control:first-child,.input-group-addon:first-child,.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group>.btn,.input-group-btn:first-child>.dropdown-toggle,.input-group-btn:last-child>.btn-group:not(:last-child)>.btn,.input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.input-group-addon:first-child{border-right:0}.input-group .form-control:last-child,.input-group-addon:last-child,.input-group-btn:first-child>.btn-group:not(:first-child)>.btn,.input-group-btn:first-child>.btn:not(:first-child),.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group>.btn,.input-group-btn:last-child>.dropdown-toggle{border-top-left-radius:0;border-bottom-left-radius:0}.input-group-addon:last-child{border-left:0}.input-group-btn{position:relative;font-size:0;white-space:nowrap}.input-group-btn>.btn{position:relative}.input-group-btn>.btn+.btn{margin-left:-1px}.input-group-btn>.btn:active,.input-group-btn>.btn:focus,.input-group-btn>.btn:hover{z-index:2}.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group{margin-right:-1px}.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group{z-index:2;margin-left:-1px}.nav{padding-left:0;margin-bottom:0;list-style:none}.nav>li{position:relative;display:block}.nav>li>a{position:relative;display:block;padding:10px 15px}.nav>li>a:focus,.nav>li>a:hover{text-decoration:none;background-color:#eee}.nav>li.disabled>a{color:#777}.nav>li.disabled>a:focus,.nav>li.disabled>a:hover{color:#777;text-decoration:none;cursor:not-allowed;background-color:transparent}.nav .open>a,.nav .open>a:focus,.nav .open>a:hover{background-color:#eee;border-color:#337ab7}.nav .nav-divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.nav>li>a>img{max-width:none}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs>li{float:left;margin-bottom:-1px}.nav-tabs>li>a{margin-right:2px;line-height:1.42857143;border:1px solid transparent;border-radius:4px 4px 0 0}.nav-tabs>li>a:hover{border-color:#eee #eee #ddd}.nav-tabs>li.active>a,.nav-tabs>li.active>a:focus,.nav-tabs>li.active>a:hover{color:#555;cursor:default;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent}.nav-tabs.nav-justified{width:100%;border-bottom:0}.nav-tabs.nav-justified>li{float:none}.nav-tabs.nav-justified>li>a{margin-bottom:5px;text-align:center}.nav-tabs.nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media (min-width:768px){.nav-tabs.nav-justified>li{display:table-cell;width:1%}.nav-tabs.nav-justified>li>a{margin-bottom:0}}.nav-tabs.nav-justified>li>a{margin-right:0;border-radius:4px}.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:focus,.nav-tabs.nav-justified>.active>a:hover{border:1px solid #ddd}@media (min-width:768px){.nav-tabs.nav-justified>li>a{border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:focus,.nav-tabs.nav-justified>.active>a:hover{border-bottom-color:#fff}}.nav-pills>li{float:left}.nav-pills>li>a{border-radius:4px}.nav-pills>li+li{margin-left:2px}.nav-pills>li.active>a,.nav-pills>li.active>a:focus,.nav-pills>li.active>a:hover{color:#fff;background-color:#337ab7}.nav-stacked>li{float:none}.nav-stacked>li+li{margin-top:2px;margin-left:0}.nav-justified{width:100%}.nav-justified>li{float:none}.nav-justified>li>a{margin-bottom:5px;text-align:center}.nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media (min-width:768px){.nav-justified>li{display:table-cell;width:1%}.nav-justified>li>a{margin-bottom:0}}.nav-tabs-justified{border-bottom:0}.nav-tabs-justified>li>a{margin-right:0;border-radius:4px}.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:focus,.nav-tabs-justified>.active>a:hover{border:1px solid #ddd}@media (min-width:768px){.nav-tabs-justified>li>a{border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:focus,.nav-tabs-justified>.active>a:hover{border-bottom-color:#fff}}.tab-content>.tab-pane{display:none}.tab-content>.active{display:block}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-left-radius:0;border-top-right-radius:0}.navbar{position:relative;min-height:50px;margin-bottom:20px;border:1px solid transparent}@media (min-width:768px){.navbar{border-radius:4px}}@media (min-width:768px){.navbar-header{float:left}}.navbar-collapse{padding-right:15px;padding-left:15px;overflow-x:visible;-webkit-overflow-scrolling:touch;border-top:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1)}.navbar-collapse.in{overflow-y:auto}@media (min-width:768px){.navbar-collapse{width:auto;border-top:0;-webkit-box-shadow:none;box-shadow:none}.navbar-collapse.collapse{display:block!important;height:auto!important;padding-bottom:0;overflow:visible!important}.navbar-collapse.in{overflow-y:visible}.navbar-fixed-bottom .navbar-collapse,.navbar-fixed-top .navbar-collapse,.navbar-static-top .navbar-collapse{padding-right:0;padding-left:0}}.navbar-fixed-bottom .navbar-collapse,.navbar-fixed-top .navbar-collapse{max-height:340px}@media (max-device-width:480px) and (orientation:landscape){.navbar-fixed-bottom .navbar-collapse,.navbar-fixed-top .navbar-collapse{max-height:200px}}.container-fluid>.navbar-collapse,.container-fluid>.navbar-header,.container>.navbar-collapse,.container>.navbar-header{margin-right:-15px;margin-left:-15px}@media (min-width:768px){.container-fluid>.navbar-collapse,.container-fluid>.navbar-header,.container>.navbar-collapse,.container>.navbar-header{margin-right:0;margin-left:0}}.navbar-static-top{z-index:1000;border-width:0 0 1px}@media (min-width:768px){.navbar-static-top{border-radius:0}}.navbar-fixed-bottom,.navbar-fixed-top{position:fixed;right:0;left:0;z-index:1030}@media (min-width:768px){.navbar-fixed-bottom,.navbar-fixed-top{border-radius:0}}.navbar-fixed-top{top:0;border-width:0 0 1px}.navbar-fixed-bottom{bottom:0;margin-bottom:0;border-width:1px 0 0}.navbar-brand{float:left;height:50px;padding:15px 15px;font-size:18px;line-height:20px}.navbar-brand:focus,.navbar-brand:hover{text-decoration:none}.navbar-brand>img{display:block}@media (min-width:768px){.navbar>.container .navbar-brand,.navbar>.container-fluid .navbar-brand{margin-left:-15px}}.navbar-toggle{position:relative;float:right;padding:9px 10px;margin-top:8px;margin-right:15px;margin-bottom:8px;background-color:transparent;background-image:none;border:1px solid transparent;border-radius:4px}.navbar-toggle:focus{outline:0}.navbar-toggle .icon-bar{display:block;width:22px;height:2px;border-radius:1px}.navbar-toggle .icon-bar+.icon-bar{margin-top:4px}@media (min-width:768px){.navbar-toggle{display:none}}.navbar-nav{margin:7.5px -15px}.navbar-nav>li>a{padding-top:10px;padding-bottom:10px;line-height:20px}@media (max-width:767px){.navbar-nav .open .dropdown-menu{position:static;float:none;width:auto;margin-top:0;background-color:transparent;border:0;-webkit-box-shadow:none;box-shadow:none}.navbar-nav .open .dropdown-menu .dropdown-header,.navbar-nav .open .dropdown-menu>li>a{padding:5px 15px 5px 25px}.navbar-nav .open .dropdown-menu>li>a{line-height:20px}.navbar-nav .open .dropdown-menu>li>a:focus,.navbar-nav .open .dropdown-menu>li>a:hover{background-image:none}}@media (min-width:768px){.navbar-nav{float:left;margin:0}.navbar-nav>li{float:left}.navbar-nav>li>a{padding-top:15px;padding-bottom:15px}}.navbar-form{padding:10px 15px;margin-top:8px;margin-right:-15px;margin-bottom:8px;margin-left:-15px;border-top:1px solid transparent;border-bottom:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1)}@media (min-width:768px){.navbar-form .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.navbar-form .form-control{display:inline-block;width:auto;vertical-align:middle}.navbar-form .form-control-static{display:inline-block}.navbar-form .input-group{display:inline-table;vertical-align:middle}.navbar-form .input-group .form-control,.navbar-form .input-group .input-group-addon,.navbar-form .input-group .input-group-btn{width:auto}.navbar-form .input-group>.form-control{width:100%}.navbar-form .control-label{margin-bottom:0;vertical-align:middle}.navbar-form .checkbox,.navbar-form .radio{display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}.navbar-form .checkbox label,.navbar-form .radio label{padding-left:0}.navbar-form .checkbox input[type=checkbox],.navbar-form .radio input[type=radio]{position:relative;margin-left:0}.navbar-form .has-feedback .form-control-feedback{top:0}}@media (max-width:767px){.navbar-form .form-group{margin-bottom:5px}.navbar-form .form-group:last-child{margin-bottom:0}}@media (min-width:768px){.navbar-form{width:auto;padding-top:0;padding-bottom:0;margin-right:0;margin-left:0;border:0;-webkit-box-shadow:none;box-shadow:none}}.navbar-nav>li>.dropdown-menu{margin-top:0;border-top-left-radius:0;border-top-right-radius:0}.navbar-fixed-bottom .navbar-nav>li>.dropdown-menu{margin-bottom:0;border-top-left-radius:4px;border-top-right-radius:4px;border-bottom-right-radius:0;border-bottom-left-radius:0}.navbar-btn{margin-top:8px;margin-bottom:8px}.navbar-btn.btn-sm{margin-top:10px;margin-bottom:10px}.navbar-btn.btn-xs{margin-top:14px;margin-bottom:14px}.navbar-text{margin-top:15px;margin-bottom:15px}@media (min-width:768px){.navbar-text{float:left;margin-right:15px;margin-left:15px}}@media (min-width:768px){.navbar-left{float:left!important}.navbar-right{float:right!important;margin-right:-15px}.navbar-right~.navbar-right{margin-right:0}}.navbar-default{background-color:#f8f8f8;border-color:#e7e7e7}.navbar-default .navbar-brand{color:#777}.navbar-default .navbar-brand:focus,.navbar-default .navbar-brand:hover{color:#5e5e5e;background-color:transparent}.navbar-default .navbar-text{color:#777}.navbar-default .navbar-nav>li>a{color:#777}.navbar-default .navbar-nav>li>a:focus,.navbar-default .navbar-nav>li>a:hover{color:#333;background-color:transparent}.navbar-default .navbar-nav>.active>a,.navbar-default .navbar-nav>.active>a:focus,.navbar-default .navbar-nav>.active>a:hover{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav>.disabled>a,.navbar-default .navbar-nav>.disabled>a:focus,.navbar-default .navbar-nav>.disabled>a:hover{color:#ccc;background-color:transparent}.navbar-default .navbar-toggle{border-color:#ddd}.navbar-default .navbar-toggle:focus,.navbar-default .navbar-toggle:hover{background-color:#ddd}.navbar-default .navbar-toggle .icon-bar{background-color:#888}.navbar-default .navbar-collapse,.navbar-default .navbar-form{border-color:#e7e7e7}.navbar-default .navbar-nav>.open>a,.navbar-default .navbar-nav>.open>a:focus,.navbar-default .navbar-nav>.open>a:hover{color:#555;background-color:#e7e7e7}@media (max-width:767px){.navbar-default .navbar-nav .open .dropdown-menu>li>a{color:#777}.navbar-default .navbar-nav .open .dropdown-menu>li>a:focus,.navbar-default .navbar-nav .open .dropdown-menu>li>a:hover{color:#333;background-color:transparent}.navbar-default .navbar-nav .open .dropdown-menu>.active>a,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:focus,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:hover{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:focus,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:hover{color:#ccc;background-color:transparent}}.navbar-default .navbar-link{color:#777}.navbar-default .navbar-link:hover{color:#333}.navbar-default .btn-link{color:#777}.navbar-default .btn-link:focus,.navbar-default .btn-link:hover{color:#333}.navbar-default .btn-link[disabled]:focus,.navbar-default .btn-link[disabled]:hover,fieldset[disabled] .navbar-default .btn-link:focus,fieldset[disabled] .navbar-default .btn-link:hover{color:#ccc}.navbar-inverse{background-color:#222;border-color:#080808}.navbar-inverse .navbar-brand{color:#9d9d9d}.navbar-inverse .navbar-brand:focus,.navbar-inverse .navbar-brand:hover{color:#fff;background-color:transparent}.navbar-inverse .navbar-text{color:#9d9d9d}.navbar-inverse .navbar-nav>li>a{color:#9d9d9d}.navbar-inverse .navbar-nav>li>a:focus,.navbar-inverse .navbar-nav>li>a:hover{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.active>a:focus,.navbar-inverse .navbar-nav>.active>a:hover{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.disabled>a,.navbar-inverse .navbar-nav>.disabled>a:focus,.navbar-inverse .navbar-nav>.disabled>a:hover{color:#444;background-color:transparent}.navbar-inverse .navbar-toggle{border-color:#333}.navbar-inverse .navbar-toggle:focus,.navbar-inverse .navbar-toggle:hover{background-color:#333}.navbar-inverse .navbar-toggle .icon-bar{background-color:#fff}.navbar-inverse .navbar-collapse,.navbar-inverse .navbar-form{border-color:#101010}.navbar-inverse .navbar-nav>.open>a,.navbar-inverse .navbar-nav>.open>a:focus,.navbar-inverse .navbar-nav>.open>a:hover{color:#fff;background-color:#080808}@media (max-width:767px){.navbar-inverse .navbar-nav .open .dropdown-menu>.dropdown-header{border-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu .divider{background-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a{color:#9d9d9d}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:focus,.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:hover{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:focus,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:hover{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:focus,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:hover{color:#444;background-color:transparent}}.navbar-inverse .navbar-link{color:#9d9d9d}.navbar-inverse .navbar-link:hover{color:#fff}.navbar-inverse .btn-link{color:#9d9d9d}.navbar-inverse .btn-link:focus,.navbar-inverse .btn-link:hover{color:#fff}.navbar-inverse .btn-link[disabled]:focus,.navbar-inverse .btn-link[disabled]:hover,fieldset[disabled] .navbar-inverse .btn-link:focus,fieldset[disabled] .navbar-inverse .btn-link:hover{color:#444}.breadcrumb{padding:8px 15px;margin-bottom:20px;list-style:none;background-color:#f5f5f5;border-radius:4px}.breadcrumb>li{display:inline-block}.breadcrumb>li+li:before{padding:0 5px;color:#ccc;content:"/\00a0"}.breadcrumb>.active{color:#777}.pagination{display:inline-block;padding-left:0;margin:20px 0;border-radius:4px}.pagination>li{display:inline}.pagination>li>a,.pagination>li>span{position:relative;float:left;padding:6px 12px;margin-left:-1px;line-height:1.42857143;color:#337ab7;text-decoration:none;background-color:#fff;border:1px solid #ddd}.pagination>li:first-child>a,.pagination>li:first-child>span{margin-left:0;border-top-left-radius:4px;border-bottom-left-radius:4px}.pagination>li:last-child>a,.pagination>li:last-child>span{border-top-right-radius:4px;border-bottom-right-radius:4px}.pagination>li>a:focus,.pagination>li>a:hover,.pagination>li>span:focus,.pagination>li>span:hover{z-index:2;color:#23527c;background-color:#eee;border-color:#ddd}.pagination>.active>a,.pagination>.active>a:focus,.pagination>.active>a:hover,.pagination>.active>span,.pagination>.active>span:focus,.pagination>.active>span:hover{z-index:3;color:#fff;cursor:default;background-color:#337ab7;border-color:#337ab7}.pagination>.disabled>a,.pagination>.disabled>a:focus,.pagination>.disabled>a:hover,.pagination>.disabled>span,.pagination>.disabled>span:focus,.pagination>.disabled>span:hover{color:#777;cursor:not-allowed;background-color:#fff;border-color:#ddd}.pagination-lg>li>a,.pagination-lg>li>span{padding:10px 16px;font-size:18px;line-height:1.3333333}.pagination-lg>li:first-child>a,.pagination-lg>li:first-child>span{border-top-left-radius:6px;border-bottom-left-radius:6px}.pagination-lg>li:last-child>a,.pagination-lg>li:last-child>span{border-top-right-radius:6px;border-bottom-right-radius:6px}.pagination-sm>li>a,.pagination-sm>li>span{padding:5px 10px;font-size:12px;line-height:1.5}.pagination-sm>li:first-child>a,.pagination-sm>li:first-child>span{border-top-left-radius:3px;border-bottom-left-radius:3px}.pagination-sm>li:last-child>a,.pagination-sm>li:last-child>span{border-top-right-radius:3px;border-bottom-right-radius:3px}.pager{padding-left:0;margin:20px 0;text-align:center;list-style:none}.pager li{display:inline}.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;border-radius:15px}.pager li>a:focus,.pager li>a:hover{text-decoration:none;background-color:#eee}.pager .next>a,.pager .next>span{float:right}.pager .previous>a,.pager .previous>span{float:left}.pager .disabled>a,.pager .disabled>a:focus,.pager .disabled>a:hover,.pager .disabled>span{color:#777;cursor:not-allowed;background-color:#fff}.label{display:inline;padding:.2em .6em .3em;font-size:75%;font-weight:700;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25em}a.label:focus,a.label:hover{color:#fff;text-decoration:none;cursor:pointer}.label:empty{display:none}.btn .label{position:relative;top:-1px}.label-default{background-color:#777}.label-default[href]:focus,.label-default[href]:hover{background-color:#5e5e5e}.label-primary{background-color:#337ab7}.label-primary[href]:focus,.label-primary[href]:hover{background-color:#286090}.label-success{background-color:#5cb85c}.label-success[href]:focus,.label-success[href]:hover{background-color:#449d44}.label-info{background-color:#5bc0de}.label-info[href]:focus,.label-info[href]:hover{background-color:#31b0d5}.label-warning{background-color:#f0ad4e}.label-warning[href]:focus,.label-warning[href]:hover{background-color:#ec971f}.label-danger{background-color:#d9534f}.label-danger[href]:focus,.label-danger[href]:hover{background-color:#c9302c}.badge{display:inline-block;min-width:10px;padding:3px 7px;font-size:12px;font-weight:700;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:middle;background-color:#777;border-radius:10px}.badge:empty{display:none}.btn .badge{position:relative;top:-1px}.btn-group-xs>.btn .badge,.btn-xs .badge{top:0;padding:1px 5px}a.badge:focus,a.badge:hover{color:#fff;text-decoration:none;cursor:pointer}.list-group-item.active>.badge,.nav-pills>.active>a>.badge{color:#337ab7;background-color:#fff}.list-group-item>.badge{float:right}.list-group-item>.badge+.badge{margin-right:5px}.nav-pills>li>a>.badge{margin-left:3px}.jumbotron{padding-top:30px;padding-bottom:30px;margin-bottom:30px;color:inherit;background-color:#eee}.jumbotron .h1,.jumbotron h1{color:inherit}.jumbotron p{margin-bottom:15px;font-size:21px;font-weight:200}.jumbotron>hr{border-top-color:#d5d5d5}.container .jumbotron,.container-fluid .jumbotron{padding-right:15px;padding-left:15px;border-radius:6px}.jumbotron .container{max-width:100%}@media screen and (min-width:768px){.jumbotron{padding-top:48px;padding-bottom:48px}.container .jumbotron,.container-fluid .jumbotron{padding-right:60px;padding-left:60px}.jumbotron .h1,.jumbotron h1{font-size:63px}}.thumbnail{display:block;padding:4px;margin-bottom:20px;line-height:1.42857143;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:border .2s ease-in-out;-o-transition:border .2s ease-in-out;transition:border .2s ease-in-out}.thumbnail a>img,.thumbnail>img{margin-right:auto;margin-left:auto}a.thumbnail.active,a.thumbnail:focus,a.thumbnail:hover{border-color:#337ab7}.thumbnail .caption{padding:9px;color:#333}.alert{padding:15px;margin-bottom:20px;border:1px solid transparent;border-radius:4px}.alert h4{margin-top:0;color:inherit}.alert .alert-link{font-weight:700}.alert>p,.alert>ul{margin-bottom:0}.alert>p+p{margin-top:5px}.alert-dismissable,.alert-dismissible{padding-right:35px}.alert-dismissable .close,.alert-dismissible .close{position:relative;top:-2px;right:-21px;color:inherit}.alert-success{color:#3c763d;background-color:#dff0d8;border-color:#d6e9c6}.alert-success hr{border-top-color:#c9e2b3}.alert-success .alert-link{color:#2b542c}.alert-info{color:#31708f;background-color:#d9edf7;border-color:#bce8f1}.alert-info hr{border-top-color:#a6e1ec}.alert-info .alert-link{color:#245269}.alert-warning{color:#8a6d3b;background-color:#fcf8e3;border-color:#faebcc}.alert-warning hr{border-top-color:#f7e1b5}.alert-warning .alert-link{color:#66512c}.alert-danger{color:#a94442;background-color:#f2dede;border-color:#ebccd1}.alert-danger hr{border-top-color:#e4b9c0}.alert-danger .alert-link{color:#843534}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-o-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}.progress{height:20px;margin-bottom:20px;overflow:hidden;background-color:#f5f5f5;border-radius:4px;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,.1);box-shadow:inset 0 1px 2px rgba(0,0,0,.1)}.progress-bar{float:left;width:0;height:100%;font-size:12px;line-height:20px;color:#fff;text-align:center;background-color:#337ab7;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,.15);-webkit-transition:width .6s ease;-o-transition:width .6s ease;transition:width .6s ease}.progress-bar-striped,.progress-striped .progress-bar{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);-webkit-background-size:40px 40px;background-size:40px 40px}.progress-bar.active,.progress.active .progress-bar{-webkit-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.progress-bar-success{background-color:#5cb85c}.progress-striped .progress-bar-success{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-info{background-color:#5bc0de}.progress-striped .progress-bar-info{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-warning{background-color:#f0ad4e}.progress-striped .progress-bar-warning{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-danger{background-color:#d9534f}.progress-striped .progress-bar-danger{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.media{margin-top:15px}.media:first-child{margin-top:0}.media,.media-body{overflow:hidden;zoom:1}.media-body{width:10000px}.media-object{display:block}.media-object.img-thumbnail{max-width:none}.media-right,.media>.pull-right{padding-left:10px}.media-left,.media>.pull-left{padding-right:10px}.media-body,.media-left,.media-right{display:table-cell;vertical-align:top}.media-middle{vertical-align:middle}.media-bottom{vertical-align:bottom}.media-heading{margin-top:0;margin-bottom:5px}.media-list{padding-left:0;list-style:none}.list-group{padding-left:0;margin-bottom:20px}.list-group-item{position:relative;display:block;padding:10px 15px;margin-bottom:-1px;background-color:#fff;border:1px solid #ddd}.list-group-item:first-child{border-top-left-radius:4px;border-top-right-radius:4px}.list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}a.list-group-item,button.list-group-item{color:#555}a.list-group-item .list-group-item-heading,button.list-group-item .list-group-item-heading{color:#333}a.list-group-item:focus,a.list-group-item:hover,button.list-group-item:focus,button.list-group-item:hover{color:#555;text-decoration:none;background-color:#f5f5f5}button.list-group-item{width:100%;text-align:left}.list-group-item.disabled,.list-group-item.disabled:focus,.list-group-item.disabled:hover{color:#777;cursor:not-allowed;background-color:#eee}.list-group-item.disabled .list-group-item-heading,.list-group-item.disabled:focus .list-group-item-heading,.list-group-item.disabled:hover .list-group-item-heading{color:inherit}.list-group-item.disabled .list-group-item-text,.list-group-item.disabled:focus .list-group-item-text,.list-group-item.disabled:hover .list-group-item-text{color:#777}.list-group-item.active,.list-group-item.active:focus,.list-group-item.active:hover{z-index:2;color:#fff;background-color:#337ab7;border-color:#337ab7}.list-group-item.active .list-group-item-heading,.list-group-item.active .list-group-item-heading>.small,.list-group-item.active .list-group-item-heading>small,.list-group-item.active:focus .list-group-item-heading,.list-group-item.active:focus .list-group-item-heading>.small,.list-group-item.active:focus .list-group-item-heading>small,.list-group-item.active:hover .list-group-item-heading,.list-group-item.active:hover .list-group-item-heading>.small,.list-group-item.active:hover .list-group-item-heading>small{color:inherit}.list-group-item.active .list-group-item-text,.list-group-item.active:focus .list-group-item-text,.list-group-item.active:hover .list-group-item-text{color:#c7ddef}.list-group-item-success{color:#3c763d;background-color:#dff0d8}a.list-group-item-success,button.list-group-item-success{color:#3c763d}a.list-group-item-success .list-group-item-heading,button.list-group-item-success .list-group-item-heading{color:inherit}a.list-group-item-success:focus,a.list-group-item-success:hover,button.list-group-item-success:focus,button.list-group-item-success:hover{color:#3c763d;background-color:#d0e9c6}a.list-group-item-success.active,a.list-group-item-success.active:focus,a.list-group-item-success.active:hover,button.list-group-item-success.active,button.list-group-item-success.active:focus,button.list-group-item-success.active:hover{color:#fff;background-color:#3c763d;border-color:#3c763d}.list-group-item-info{color:#31708f;background-color:#d9edf7}a.list-group-item-info,button.list-group-item-info{color:#31708f}a.list-group-item-info .list-group-item-heading,button.list-group-item-info .list-group-item-heading{color:inherit}a.list-group-item-info:focus,a.list-group-item-info:hover,button.list-group-item-info:focus,button.list-group-item-info:hover{color:#31708f;background-color:#c4e3f3}a.list-group-item-info.active,a.list-group-item-info.active:focus,a.list-group-item-info.active:hover,button.list-group-item-info.active,button.list-group-item-info.active:focus,button.list-group-item-info.active:hover{color:#fff;background-color:#31708f;border-color:#31708f}.list-group-item-warning{color:#8a6d3b;background-color:#fcf8e3}a.list-group-item-warning,button.list-group-item-warning{color:#8a6d3b}a.list-group-item-warning .list-group-item-heading,button.list-group-item-warning .list-group-item-heading{color:inherit}a.list-group-item-warning:focus,a.list-group-item-warning:hover,button.list-group-item-warning:focus,button.list-group-item-warning:hover{color:#8a6d3b;background-color:#faf2cc}a.list-group-item-warning.active,a.list-group-item-warning.active:focus,a.list-group-item-warning.active:hover,button.list-group-item-warning.active,button.list-group-item-warning.active:focus,button.list-group-item-warning.active:hover{color:#fff;background-color:#8a6d3b;border-color:#8a6d3b}.list-group-item-danger{color:#a94442;background-color:#f2dede}a.list-group-item-danger,button.list-group-item-danger{color:#a94442}a.list-group-item-danger .list-group-item-heading,button.list-group-item-danger .list-group-item-heading{color:inherit}a.list-group-item-danger:focus,a.list-group-item-danger:hover,button.list-group-item-danger:focus,button.list-group-item-danger:hover{color:#a94442;background-color:#ebcccc}a.list-group-item-danger.active,a.list-group-item-danger.active:focus,a.list-group-item-danger.active:hover,button.list-group-item-danger.active,button.list-group-item-danger.active:focus,button.list-group-item-danger.active:hover{color:#fff;background-color:#a94442;border-color:#a94442}.list-group-item-heading{margin-top:0;margin-bottom:5px}.list-group-item-text{margin-bottom:0;line-height:1.3}.panel{margin-bottom:20px;background-color:#fff;border:1px solid transparent;border-radius:4px;-webkit-box-shadow:0 1px 1px rgba(0,0,0,.05);box-shadow:0 1px 1px rgba(0,0,0,.05)}.panel-body{padding:15px}.panel-heading{padding:10px 15px;border-bottom:1px solid transparent;border-top-left-radius:3px;border-top-right-radius:3px}.panel-heading>.dropdown .dropdown-toggle{color:inherit}.panel-title{margin-top:0;margin-bottom:0;font-size:16px;color:inherit}.panel-title>.small,.panel-title>.small>a,.panel-title>a,.panel-title>small,.panel-title>small>a{color:inherit}.panel-footer{padding:10px 15px;background-color:#f5f5f5;border-top:1px solid #ddd;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.list-group,.panel>.panel-collapse>.list-group{margin-bottom:0}.panel>.list-group .list-group-item,.panel>.panel-collapse>.list-group .list-group-item{border-width:1px 0;border-radius:0}.panel>.list-group:first-child .list-group-item:first-child,.panel>.panel-collapse>.list-group:first-child .list-group-item:first-child{border-top:0;border-top-left-radius:3px;border-top-right-radius:3px}.panel>.list-group:last-child .list-group-item:last-child,.panel>.panel-collapse>.list-group:last-child .list-group-item:last-child{border-bottom:0;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.panel-heading+.panel-collapse>.list-group .list-group-item:first-child{border-top-left-radius:0;border-top-right-radius:0}.panel-heading+.list-group .list-group-item:first-child{border-top-width:0}.list-group+.panel-footer{border-top-width:0}.panel>.panel-collapse>.table,.panel>.table,.panel>.table-responsive>.table{margin-bottom:0}.panel>.panel-collapse>.table caption,.panel>.table caption,.panel>.table-responsive>.table caption{padding-right:15px;padding-left:15px}.panel>.table-responsive:first-child>.table:first-child,.panel>.table:first-child{border-top-left-radius:3px;border-top-right-radius:3px}.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child,.panel>.table:first-child>thead:first-child>tr:first-child{border-top-left-radius:3px;border-top-right-radius:3px}.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:first-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child td:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child th:first-child,.panel>.table:first-child>thead:first-child>tr:first-child td:first-child,.panel>.table:first-child>thead:first-child>tr:first-child th:first-child{border-top-left-radius:3px}.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:last-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:last-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:last-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:last-child,.panel>.table:first-child>tbody:first-child>tr:first-child td:last-child,.panel>.table:first-child>tbody:first-child>tr:first-child th:last-child,.panel>.table:first-child>thead:first-child>tr:first-child td:last-child,.panel>.table:first-child>thead:first-child>tr:first-child th:last-child{border-top-right-radius:3px}.panel>.table-responsive:last-child>.table:last-child,.panel>.table:last-child{border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child,.panel>.table:last-child>tbody:last-child>tr:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child{border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:first-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:first-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:first-child,.panel>.table:last-child>tbody:last-child>tr:last-child td:first-child,.panel>.table:last-child>tbody:last-child>tr:last-child th:first-child,.panel>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.panel>.table:last-child>tfoot:last-child>tr:last-child th:first-child{border-bottom-left-radius:3px}.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:last-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:last-child,.panel>.table:last-child>tbody:last-child>tr:last-child td:last-child,.panel>.table:last-child>tbody:last-child>tr:last-child th:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child th:last-child{border-bottom-right-radius:3px}.panel>.panel-body+.table,.panel>.panel-body+.table-responsive,.panel>.table+.panel-body,.panel>.table-responsive+.panel-body{border-top:1px solid #ddd}.panel>.table>tbody:first-child>tr:first-child td,.panel>.table>tbody:first-child>tr:first-child th{border-top:0}.panel>.table-bordered,.panel>.table-responsive>.table-bordered{border:0}.panel>.table-bordered>tbody>tr>td:first-child,.panel>.table-bordered>tbody>tr>th:first-child,.panel>.table-bordered>tfoot>tr>td:first-child,.panel>.table-bordered>tfoot>tr>th:first-child,.panel>.table-bordered>thead>tr>td:first-child,.panel>.table-bordered>thead>tr>th:first-child,.panel>.table-responsive>.table-bordered>tbody>tr>td:first-child,.panel>.table-responsive>.table-bordered>tbody>tr>th:first-child,.panel>.table-responsive>.table-bordered>tfoot>tr>td:first-child,.panel>.table-responsive>.table-bordered>tfoot>tr>th:first-child,.panel>.table-responsive>.table-bordered>thead>tr>td:first-child,.panel>.table-responsive>.table-bordered>thead>tr>th:first-child{border-left:0}.panel>.table-bordered>tbody>tr>td:last-child,.panel>.table-bordered>tbody>tr>th:last-child,.panel>.table-bordered>tfoot>tr>td:last-child,.panel>.table-bordered>tfoot>tr>th:last-child,.panel>.table-bordered>thead>tr>td:last-child,.panel>.table-bordered>thead>tr>th:last-child,.panel>.table-responsive>.table-bordered>tbody>tr>td:last-child,.panel>.table-responsive>.table-bordered>tbody>tr>th:last-child,.panel>.table-responsive>.table-bordered>tfoot>tr>td:last-child,.panel>.table-responsive>.table-bordered>tfoot>tr>th:last-child,.panel>.table-responsive>.table-bordered>thead>tr>td:last-child,.panel>.table-responsive>.table-bordered>thead>tr>th:last-child{border-right:0}.panel>.table-bordered>tbody>tr:first-child>td,.panel>.table-bordered>tbody>tr:first-child>th,.panel>.table-bordered>thead>tr:first-child>td,.panel>.table-bordered>thead>tr:first-child>th,.panel>.table-responsive>.table-bordered>tbody>tr:first-child>td,.panel>.table-responsive>.table-bordered>tbody>tr:first-child>th,.panel>.table-responsive>.table-bordered>thead>tr:first-child>td,.panel>.table-responsive>.table-bordered>thead>tr:first-child>th{border-bottom:0}.panel>.table-bordered>tbody>tr:last-child>td,.panel>.table-bordered>tbody>tr:last-child>th,.panel>.table-bordered>tfoot>tr:last-child>td,.panel>.table-bordered>tfoot>tr:last-child>th,.panel>.table-responsive>.table-bordered>tbody>tr:last-child>td,.panel>.table-responsive>.table-bordered>tbody>tr:last-child>th,.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>td,.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>th{border-bottom:0}.panel>.table-responsive{margin-bottom:0;border:0}.panel-group{margin-bottom:20px}.panel-group .panel{margin-bottom:0;border-radius:4px}.panel-group .panel+.panel{margin-top:5px}.panel-group .panel-heading{border-bottom:0}.panel-group .panel-heading+.panel-collapse>.list-group,.panel-group .panel-heading+.panel-collapse>.panel-body{border-top:1px solid #ddd}.panel-group .panel-footer{border-top:0}.panel-group .panel-footer+.panel-collapse .panel-body{border-bottom:1px solid #ddd}.panel-default{border-color:#ddd}.panel-default>.panel-heading{color:#333;background-color:#f5f5f5;border-color:#ddd}.panel-default>.panel-heading+.panel-collapse>.panel-body{border-top-color:#ddd}.panel-default>.panel-heading .badge{color:#f5f5f5;background-color:#333}.panel-default>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#ddd}.panel-primary{border-color:#337ab7}.panel-primary>.panel-heading{color:#fff;background-color:#337ab7;border-color:#337ab7}.panel-primary>.panel-heading+.panel-collapse>.panel-body{border-top-color:#337ab7}.panel-primary>.panel-heading .badge{color:#337ab7;background-color:#fff}.panel-primary>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#337ab7}.panel-success{border-color:#d6e9c6}.panel-success>.panel-heading{color:#3c763d;background-color:#dff0d8;border-color:#d6e9c6}.panel-success>.panel-heading+.panel-collapse>.panel-body{border-top-color:#d6e9c6}.panel-success>.panel-heading .badge{color:#dff0d8;background-color:#3c763d}.panel-success>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#d6e9c6}.panel-info{border-color:#bce8f1}.panel-info>.panel-heading{color:#31708f;background-color:#d9edf7;border-color:#bce8f1}.panel-info>.panel-heading+.panel-collapse>.panel-body{border-top-color:#bce8f1}.panel-info>.panel-heading .badge{color:#d9edf7;background-color:#31708f}.panel-info>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#bce8f1}.panel-warning{border-color:#faebcc}.panel-warning>.panel-heading{color:#8a6d3b;background-color:#fcf8e3;border-color:#faebcc}.panel-warning>.panel-heading+.panel-collapse>.panel-body{border-top-color:#faebcc}.panel-warning>.panel-heading .badge{color:#fcf8e3;background-color:#8a6d3b}.panel-warning>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#faebcc}.panel-danger{border-color:#ebccd1}.panel-danger>.panel-heading{color:#a94442;background-color:#f2dede;border-color:#ebccd1}.panel-danger>.panel-heading+.panel-collapse>.panel-body{border-top-color:#ebccd1}.panel-danger>.panel-heading .badge{color:#f2dede;background-color:#a94442}.panel-danger>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#ebccd1}.embed-responsive{position:relative;display:block;height:0;padding:0;overflow:hidden}.embed-responsive .embed-responsive-item,.embed-responsive embed,.embed-responsive iframe,.embed-responsive object,.embed-responsive video{position:absolute;top:0;bottom:0;left:0;width:100%;height:100%;border:0}.embed-responsive-16by9{padding-bottom:56.25%}.embed-responsive-4by3{padding-bottom:75%}.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.05);box-shadow:inset 0 1px 1px rgba(0,0,0,.05)}.well blockquote{border-color:#ddd;border-color:rgba(0,0,0,.15)}.well-lg{padding:24px;border-radius:6px}.well-sm{padding:9px;border-radius:3px}.close{float:right;font-size:21px;font-weight:700;line-height:1;color:#000;text-shadow:0 1px 0 #fff;filter:alpha(opacity=20);opacity:.2}.close:focus,.close:hover{color:#000;text-decoration:none;cursor:pointer;filter:alpha(opacity=50);opacity:.5}button.close{-webkit-appearance:none;padding:0;cursor:pointer;background:0 0;border:0}.modal-open{overflow:hidden}.modal{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1050;display:none;overflow:hidden;-webkit-overflow-scrolling:touch;outline:0}.modal.fade .modal-dialog{-webkit-transition:-webkit-transform .3s ease-out;-o-transition:-o-transform .3s ease-out;transition:transform .3s ease-out;-webkit-transform:translate(0,-25%);-ms-transform:translate(0,-25%);-o-transform:translate(0,-25%);transform:translate(0,-25%)}.modal.in .modal-dialog{-webkit-transform:translate(0,0);-ms-transform:translate(0,0);-o-transform:translate(0,0);transform:translate(0,0)}.modal-open .modal{overflow-x:hidden;overflow-y:auto}.modal-dialog{position:relative;width:auto;margin:10px}.modal-content{position:relative;background-color:#fff;-webkit-background-clip:padding-box;background-clip:padding-box;border:1px solid #999;border:1px solid rgba(0,0,0,.2);border-radius:6px;outline:0;-webkit-box-shadow:0 3px 9px rgba(0,0,0,.5);box-shadow:0 3px 9px rgba(0,0,0,.5)}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000}.modal-backdrop.fade{filter:alpha(opacity=0);opacity:0}.modal-backdrop.in{filter:alpha(opacity=50);opacity:.5}.modal-header{padding:15px;border-bottom:1px solid #e5e5e5}.modal-header .close{margin-top:-2px}.modal-title{margin:0;line-height:1.42857143}.modal-body{position:relative;padding:15px}.modal-footer{padding:15px;text-align:right;border-top:1px solid #e5e5e5}.modal-footer .btn+.btn{margin-bottom:0;margin-left:5px}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}.modal-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}@media (min-width:768px){.modal-dialog{width:600px;margin:30px auto}.modal-content{-webkit-box-shadow:0 5px 15px rgba(0,0,0,.5);box-shadow:0 5px 15px rgba(0,0,0,.5)}.modal-sm{width:300px}}@media (min-width:992px){.modal-lg{width:900px}}.tooltip{position:absolute;z-index:1070;display:block;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:12px;font-style:normal;font-weight:400;line-height:1.42857143;text-align:left;text-align:start;text-decoration:none;text-shadow:none;text-transform:none;letter-spacing:normal;word-break:normal;word-spacing:normal;word-wrap:normal;white-space:normal;filter:alpha(opacity=0);opacity:0;line-break:auto}.tooltip.in{filter:alpha(opacity=90);opacity:.9}.tooltip.top{padding:5px 0;margin-top:-3px}.tooltip.right{padding:0 5px;margin-left:3px}.tooltip.bottom{padding:5px 0;margin-top:3px}.tooltip.left{padding:0 5px;margin-left:-3px}.tooltip-inner{max-width:200px;padding:3px 8px;color:#fff;text-align:center;background-color:#000;border-radius:4px}.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.top-left .tooltip-arrow{right:5px;bottom:0;margin-bottom:-5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.top-right .tooltip-arrow{bottom:0;left:5px;margin-bottom:-5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-width:5px 5px 5px 0;border-right-color:#000}.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-width:5px 0 5px 5px;border-left-color:#000}.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-width:0 5px 5px;border-bottom-color:#000}.tooltip.bottom-left .tooltip-arrow{top:0;right:5px;margin-top:-5px;border-width:0 5px 5px;border-bottom-color:#000}.tooltip.bottom-right .tooltip-arrow{top:0;left:5px;margin-top:-5px;border-width:0 5px 5px;border-bottom-color:#000}.popover{position:absolute;top:0;left:0;z-index:1060;display:none;max-width:276px;padding:1px;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;font-style:normal;font-weight:400;line-height:1.42857143;text-align:left;text-align:start;text-decoration:none;text-shadow:none;text-transform:none;letter-spacing:normal;word-break:normal;word-spacing:normal;word-wrap:normal;white-space:normal;background-color:#fff;-webkit-background-clip:padding-box;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0,0,0,.2);border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,.2);box-shadow:0 5px 10px rgba(0,0,0,.2);line-break:auto}.popover.top{margin-top:-10px}.popover.right{margin-left:10px}.popover.bottom{margin-top:10px}.popover.left{margin-left:-10px}.popover-title{padding:8px 14px;margin:0;font-size:14px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-radius:5px 5px 0 0}.popover-content{padding:9px 14px}.popover>.arrow,.popover>.arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.popover>.arrow{border-width:11px}.popover>.arrow:after{content:"";border-width:10px}.popover.top>.arrow{bottom:-11px;left:50%;margin-left:-11px;border-top-color:#999;border-top-color:rgba(0,0,0,.25);border-bottom-width:0}.popover.top>.arrow:after{bottom:1px;margin-left:-10px;content:" ";border-top-color:#fff;border-bottom-width:0}.popover.right>.arrow{top:50%;left:-11px;margin-top:-11px;border-right-color:#999;border-right-color:rgba(0,0,0,.25);border-left-width:0}.popover.right>.arrow:after{bottom:-10px;left:1px;content:" ";border-right-color:#fff;border-left-width:0}.popover.bottom>.arrow{top:-11px;left:50%;margin-left:-11px;border-top-width:0;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,.25)}.popover.bottom>.arrow:after{top:1px;margin-left:-10px;content:" ";border-top-width:0;border-bottom-color:#fff}.popover.left>.arrow{top:50%;right:-11px;margin-top:-11px;border-right-width:0;border-left-color:#999;border-left-color:rgba(0,0,0,.25)}.popover.left>.arrow:after{right:1px;bottom:-10px;content:" ";border-right-width:0;border-left-color:#fff}.carousel{position:relative}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-inner>.item{position:relative;display:none;-webkit-transition:.6s ease-in-out left;-o-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.carousel-inner>.item>a>img,.carousel-inner>.item>img{line-height:1}@media all and (transform-3d),(-webkit-transform-3d){.carousel-inner>.item{-webkit-transition:-webkit-transform .6s ease-in-out;-o-transition:-o-transform .6s ease-in-out;transition:transform .6s ease-in-out;-webkit-backface-visibility:hidden;backface-visibility:hidden;-webkit-perspective:1000px;perspective:1000px}.carousel-inner>.item.active.right,.carousel-inner>.item.next{left:0;-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0)}.carousel-inner>.item.active.left,.carousel-inner>.item.prev{left:0;-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}.carousel-inner>.item.active,.carousel-inner>.item.next.left,.carousel-inner>.item.prev.right{left:0;-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}}.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block}.carousel-inner>.active{left:0}.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%}.carousel-inner>.next{left:100%}.carousel-inner>.prev{left:-100%}.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0}.carousel-inner>.active.left{left:-100%}.carousel-inner>.active.right{left:100%}.carousel-control{position:absolute;top:0;bottom:0;left:0;width:15%;font-size:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6);background-color:rgba(0,0,0,0);filter:alpha(opacity=50);opacity:.5}.carousel-control.left{background-image:-webkit-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);background-image:-o-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);background-image:-webkit-gradient(linear,left top,right top,from(rgba(0,0,0,.5)),to(rgba(0,0,0,.0001)));background-image:linear-gradient(to right,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);background-repeat:repeat-x}.carousel-control.right{right:0;left:auto;background-image:-webkit-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);background-image:-o-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);background-image:-webkit-gradient(linear,left top,right top,from(rgba(0,0,0,.0001)),to(rgba(0,0,0,.5)));background-image:linear-gradient(to right,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);background-repeat:repeat-x}.carousel-control:focus,.carousel-control:hover{color:#fff;text-decoration:none;filter:alpha(opacity=90);outline:0;opacity:.9}.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next,.carousel-control .icon-prev{position:absolute;top:50%;z-index:5;display:inline-block;margin-top:-10px}.carousel-control .glyphicon-chevron-left,.carousel-control .icon-prev{left:50%;margin-left:-10px}.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next{right:50%;margin-right:-10px}.carousel-control .icon-next,.carousel-control .icon-prev{width:20px;height:20px;font-family:serif;line-height:1}.carousel-control .icon-prev:before{content:'\2039'}.carousel-control .icon-next:before{content:'\203a'}.carousel-indicators{position:absolute;bottom:10px;left:50%;z-index:15;width:60%;padding-left:0;margin-left:-30%;text-align:center;list-style:none}.carousel-indicators li{display:inline-block;width:10px;height:10px;margin:1px;text-indent:-999px;cursor:pointer;background-color:#000\9;background-color:rgba(0,0,0,0);border:1px solid #fff;border-radius:10px}.carousel-indicators .active{width:12px;height:12px;margin:0;background-color:#fff}.carousel-caption{position:absolute;right:15%;bottom:20px;left:15%;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6)}.carousel-caption .btn{text-shadow:none}@media screen and (min-width:768px){.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next,.carousel-control .icon-prev{width:30px;height:30px;margin-top:-10px;font-size:30px}.carousel-control .glyphicon-chevron-left,.carousel-control .icon-prev{margin-left:-10px}.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next{margin-right:-10px}.carousel-caption{right:20%;left:20%;padding-bottom:30px}.carousel-indicators{bottom:20px}}.btn-group-vertical>.btn-group:after,.btn-group-vertical>.btn-group:before,.btn-toolbar:after,.btn-toolbar:before,.clearfix:after,.clearfix:before,.container-fluid:after,.container-fluid:before,.container:after,.container:before,.dl-horizontal dd:after,.dl-horizontal dd:before,.form-horizontal .form-group:after,.form-horizontal .form-group:before,.modal-footer:after,.modal-footer:before,.modal-header:after,.modal-header:before,.nav:after,.nav:before,.navbar-collapse:after,.navbar-collapse:before,.navbar-header:after,.navbar-header:before,.navbar:after,.navbar:before,.pager:after,.pager:before,.panel-body:after,.panel-body:before,.row:after,.row:before{display:table;content:" "}.btn-group-vertical>.btn-group:after,.btn-toolbar:after,.clearfix:after,.container-fluid:after,.container:after,.dl-horizontal dd:after,.form-horizontal .form-group:after,.modal-footer:after,.modal-header:after,.nav:after,.navbar-collapse:after,.navbar-header:after,.navbar:after,.pager:after,.panel-body:after,.row:after{clear:both}.center-block{display:block;margin-right:auto;margin-left:auto}.pull-right{float:right!important}.pull-left{float:left!important}.hide{display:none!important}.show{display:block!important}.invisible{visibility:hidden}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.hidden{display:none!important}.affix{position:fixed}@-ms-viewport{width:device-width}.visible-lg,.visible-md,.visible-sm,.visible-xs{display:none!important}.visible-lg-block,.visible-lg-inline,.visible-lg-inline-block,.visible-md-block,.visible-md-inline,.visible-md-inline-block,.visible-sm-block,.visible-sm-inline,.visible-sm-inline-block,.visible-xs-block,.visible-xs-inline,.visible-xs-inline-block{display:none!important}@media (max-width:767px){.visible-xs{display:block!important}table.visible-xs{display:table!important}tr.visible-xs{display:table-row!important}td.visible-xs,th.visible-xs{display:table-cell!important}}@media (max-width:767px){.visible-xs-block{display:block!important}}@media (max-width:767px){.visible-xs-inline{display:inline!important}}@media (max-width:767px){.visible-xs-inline-block{display:inline-block!important}}@media (min-width:768px) and (max-width:991px){.visible-sm{display:block!important}table.visible-sm{display:table!important}tr.visible-sm{display:table-row!important}td.visible-sm,th.visible-sm{display:table-cell!important}}@media (min-width:768px) and (max-width:991px){.visible-sm-block{display:block!important}}@media (min-width:768px) and (max-width:991px){.visible-sm-inline{display:inline!important}}@media (min-width:768px) and (max-width:991px){.visible-sm-inline-block{display:inline-block!important}}@media (min-width:992px) and (max-width:1199px){.visible-md{display:block!important}table.visible-md{display:table!important}tr.visible-md{display:table-row!important}td.visible-md,th.visible-md{display:table-cell!important}}@media (min-width:992px) and (max-width:1199px){.visible-md-block{display:block!important}}@media (min-width:992px) and (max-width:1199px){.visible-md-inline{display:inline!important}}@media (min-width:992px) and (max-width:1199px){.visible-md-inline-block{display:inline-block!important}}@media (min-width:1200px){.visible-lg{display:block!important}table.visible-lg{display:table!important}tr.visible-lg{display:table-row!important}td.visible-lg,th.visible-lg{display:table-cell!important}}@media (min-width:1200px){.visible-lg-block{display:block!important}}@media (min-width:1200px){.visible-lg-inline{display:inline!important}}@media (min-width:1200px){.visible-lg-inline-block{display:inline-block!important}}@media (max-width:767px){.hidden-xs{display:none!important}}@media (min-width:768px) and (max-width:991px){.hidden-sm{display:none!important}}@media (min-width:992px) and (max-width:1199px){.hidden-md{display:none!important}}@media (min-width:1200px){.hidden-lg{display:none!important}}.visible-print{display:none!important}@media print{.visible-print{display:block!important}table.visible-print{display:table!important}tr.visible-print{display:table-row!important}td.visible-print,th.visible-print{display:table-cell!important}}.visible-print-block{display:none!important}@media print{.visible-print-block{display:block!important}}.visible-print-inline{display:none!important}@media print{.visible-print-inline{display:inline!important}}.visible-print-inline-block{display:none!important}@media print{.visible-print-inline-block{display:inline-block!important}}@media print{.hidden-print{display:none!important}} -/*# sourceMappingURL=bootstrap.min.css.map */ diff --git a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/css/login.css b/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/css/login.css deleted file mode 100644 index 12d62724de..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/css/login.css +++ /dev/null @@ -1,84 +0,0 @@ -html{height: 100%;} -body.signin { - background: #18c8f6; - height: auto; - -webkit-background-size: cover; - -moz-background-size: cover; - -o-background-size: cover; - background-size: cover; - color: rgba(255,255,255,.95); -} - -.signinpanel { - width: 750px; - margin: 10% auto 0 auto; -} - -.signinpanel .logopanel { - float: none; - width: auto; - padding: 0; - background: none; -} - -.signinpanel .signin-info ul { - list-style: none; - padding: 0; - margin: 20px 0; -} - -.signinpanel .form-control { - display: block; - margin-top: 15px; -} - -.signinpanel .btn { - margin-top: 15px; -} - -.signinpanel form { - background: rgba(255, 255, 255, 0.2); - border: 1px solid rgba(255,255,255,.3); - -moz-box-shadow: 0 3px 0 rgba(12, 12, 12, 0.03); - -webkit-box-shadow: 0 3px 0 rgba(12, 12, 12, 0.03); - box-shadow: 0 3px 0 rgba(12, 12, 12, 0.03); - -moz-border-radius: 3px; - -webkit-border-radius: 3px; - border-radius: 3px; - padding: 30px; -} - -.signup-footer{border-top: solid 1px rgba(255,255,255,.3);margin:20px 0;padding-top: 15px;} - -@media screen and (max-width: 768px) { - .signinpanel, - .signuppanel { - margin: 0 auto; - width: 420px!important; - padding: 20px; - } - .signinpanel form { - margin-top: 20px; - } - .signup-footer { - margin-bottom: 10px; - } - .signuppanel .form-control { - margin-bottom: 10px; - } - .signup-footer .pull-left, - .signup-footer .pull-right { - float: none !important; - text-align: center; - } - .signinpanel .signin-info ul { - display: none; - } -} -@media screen and (max-width: 320px) { - .signinpanel, - .signuppanel { - margin:0 20px; - width:auto; - } -} diff --git a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/css/patterns/header-profile-skin-1.png b/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/css/patterns/header-profile-skin-1.png deleted file mode 100644 index 41c5c089bb..0000000000 Binary files a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/css/patterns/header-profile-skin-1.png and /dev/null differ diff --git a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/css/patterns/header-profile-skin-3.png b/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/css/patterns/header-profile-skin-3.png deleted file mode 100644 index 7a80132da8..0000000000 Binary files a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/css/patterns/header-profile-skin-3.png and /dev/null differ diff --git a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/css/patterns/header-profile.png b/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/css/patterns/header-profile.png deleted file mode 100644 index 7dea7f2c76..0000000000 Binary files a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/css/patterns/header-profile.png and /dev/null differ diff --git a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/css/patterns/shattered.png b/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/css/patterns/shattered.png deleted file mode 100644 index 90ed42b85b..0000000000 Binary files a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/css/patterns/shattered.png and /dev/null differ diff --git a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/css/style.css b/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/css/style.css deleted file mode 100644 index 6cf461d024..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/css/style.css +++ /dev/null @@ -1,7928 +0,0 @@ -/* - * - * H+ - 后台主题UI框架 - * version 4.0 - * -*/ - -h1, -h2, -h3, -h4, -h5, -h6 { - font-weight: 100; -} - -h1 { - font-size: 30px; -} - -h2 { - font-size: 24px; -} - -h3 { - font-size: 16px; -} - -h4 { - font-size: 14px; -} - -h5 { - font-size: 12px; -} - -h6 { - font-size: 10px; -} - -h3, -h4, -h5 { - margin-top: 5px; - font-weight: 600; -} - -a:focus { - outline: none; -} - -.nav > li > a { - color: #a7b1c2; - font-weight: 600; - padding: 14px 20px 14px 25px; -} - -.nav li>a { - display: block; - /*white-space: nowrap;*/ -} - -.nav.navbar-right > li > a { - color: #999c9e; -} - -.nav > li.active > a { - color: #ffffff; -} - -.navbar-default .nav > li > a:hover, -.navbar-default .nav > li > a:focus { - background-color: #293846; - color: white; -} - -.nav .open > a, -.nav .open > a:hover, -.nav .open > a:focus { - background: #fff; -} - -.nav > li > a i { - margin-right: 6px; -} - -.navbar { - border: 0; -} - -.navbar-default { - background-color: transparent; - border-color: #2f4050; - position: relative; -} - -.navbar-top-links li { - display: inline-block; -} - -.navbar-top-links li:last-child { - margin-right: 30px; -} - -body.body-small .navbar-top-links li:last-child { - margin-right: 10px; -} - -.navbar-top-links li a { - padding: 20px 10px; - min-height: 50px; -} - -.dropdown-menu { - border: medium none; - display: none; - float: left; - font-size: 12px; - left: 0; - list-style: none outside none; - padding: 0; - position: absolute; - text-shadow: none; - top: 100%; - z-index: 1000; - border-radius: 0; - box-shadow: 0 0 3px rgba(86, 96, 117, 0.3); -} - -.dropdown-menu > li > a { - border-radius: 3px; - color: inherit; - line-height: 25px; - margin: 4px; - text-align: left; - font-weight: normal; -} - -.dropdown-menu > li > a.font-bold { - font-weight: 600; -} - -.navbar-top-links .dropdown-menu li { - display: block; -} - -.navbar-top-links .dropdown-menu li:last-child { - margin-right: 0; -} - -.navbar-top-links .dropdown-menu li a { - padding: 3px 20px; - min-height: 0; -} - -.navbar-top-links .dropdown-menu li a div { - white-space: normal; -} - -.navbar-top-links .dropdown-messages, -.navbar-top-links .dropdown-tasks, -.navbar-top-links .dropdown-alerts { - width: 310px; - min-width: 0; -} - -.navbar-top-links .dropdown-messages { - margin-left: 5px; -} - -.navbar-top-links .dropdown-tasks { - margin-left: -59px; -} - -.navbar-top-links .dropdown-alerts { - margin-left: -123px; -} - -.navbar-top-links .dropdown-user { - right: 0; - left: auto; -} - -.dropdown-messages, -.dropdown-alerts { - padding: 10px 10px 10px 10px; -} - -.dropdown-messages li a, -.dropdown-alerts li a { - font-size: 12px; -} - -.dropdown-messages li em, -.dropdown-alerts li em { - font-size: 10px; -} - -.nav.navbar-top-links .dropdown-alerts a { - font-size: 12px; -} - -.nav-header { - padding: 33px 25px; - background: url("patterns/header-profile.png") no-repeat; -} - -.pace-done .nav-header { - -webkit-transition: all 0.5s; - transition: all 0.5s; -} - -.nav > li.active { - border-left: 4px solid #19aa8d; - background: #293846; -} - -.nav.nav-second-level > li.active { - border: none; -} - -.nav.nav-second-level.collapse[style] { - height: auto !important; -} - -.nav-header a { - color: #DFE4ED; -} - -.nav-header .text-muted { - color: #8095a8; -} - -.minimalize-styl-2 { - padding: 4px 12px; - margin: 14px 5px 5px 20px; - font-size: 14px; - float: left; -} - -.navbar-form-custom { - float: left; - height: 50px; - padding: 0; - width: 200px; - display: inline-table; -} - -.navbar-form-custom .form-group { - margin-bottom: 0; -} - -.nav.navbar-top-links a { - font-size: 14px; -} - -.navbar-form-custom .form-control { - background: none repeat scroll 0 0 rgba(0, 0, 0, 0); - border: medium none; - font-size: 14px; - height: 60px; - margin: 0; - z-index: 2000; -} - -.count-info .label { - line-height: 12px; - padding: 1px 5px; - position: absolute; - right: 6px; - top: 12px; -} - -.arrow { - float: right; - margin-top: 2px; -} - -.fa.arrow:before { - content: "\f104"; -} - -.active > a > .fa.arrow:before { - content: "\f107"; -} - -.nav-second-level li, -.nav-third-level li { - border-bottom: none !important; -} - -.nav-second-level li a { - padding: 7px 15px 7px 10px; - padding-left: 52px; -} - -.nav-third-level li a { - padding-left: 62px; -} - -.nav-second-level li:last-child { - margin-bottom: 10px; -} - -body:not(.fixed-sidebar):not(.canvas-menu).mini-navbar .nav li:hover > .nav-second-level, -.mini-navbar .nav li:focus > .nav-second-level { - display: block; - border-radius: 0 2px 2px 0; - min-width: 140px; - height: auto; -} - -body.mini-navbar .navbar-default .nav > li > .nav-second-level li a { - font-size: 12px; - border-radius: 0 2px 2px 0; -} - -.fixed-nav .slimScrollDiv #side-menu { - padding-bottom: 60px; - position: relative; -} - -.slimScrollDiv >* { - overflow: hidden; -} - -.mini-navbar .nav-second-level li a { - padding: 10px 10px 10px 15px; -} - -.canvas-menu.mini-navbar .nav-second-level { - background: #293846; -} - -.mini-navbar li.active .nav-second-level { - left: 65px; -} - -.navbar-default .special_link a { - background: #1ab394; - color: white; -} - -.navbar-default .special_link a:hover { - background: #17987e !important; - color: white; -} - -.navbar-default .special_link a span.label { - background: #fff; - color: #1ab394; -} - -.navbar-default .landing_link a { - background: #1cc09f; - color: white; -} - -.navbar-default .landing_link a:hover { - background: #1ab394 !important; - color: white; -} - -.navbar-default .landing_link a span.label { - background: #fff; - color: #1cc09f; -} - -.logo-element { - text-align: center; - font-size: 18px; - font-weight: 600; - color: white; - display: none; - padding: 18px 0; -} - -.pace-done .navbar-static-side, -.pace-done .nav-header, -.pace-done li.active, -.pace-done #page-wrapper, -.pace-done .footer { - -webkit-transition: all 0.5s; - transition: all 0.5s; -} - -.navbar-fixed-top { - background: #fff; - -webkit-transition-duration: 0.5s; - transition-duration: 0.5s; - z-index: 2030; -} - -.navbar-fixed-top, -.navbar-static-top { - background: #f3f3f4; -} - -.fixed-nav #wrapper { - padding-top: 60px; - box-sizing: border-box; -} - -.fixed-nav .minimalize-styl-2 { - margin: 14px 5px 5px 15px; -} - -.body-small .navbar-fixed-top { - margin-left: 0px; -} - -body.mini-navbar .navbar-static-side { - width: 70px; -} - -body.mini-navbar .profile-element, -body.mini-navbar .nav-label, -body.mini-navbar .navbar-default .nav li a span { - display: none; -} - -body.canvas-menu .profile-element { - display: block; -} - -body:not(.fixed-sidebar):not(.canvas-menu).mini-navbar .nav-second-level { - display: none; -} - -body.mini-navbar .navbar-default .nav > li > a { - font-size: 16px; -} - -body.mini-navbar .logo-element { - display: block; -} - -body.canvas-menu .logo-element { - display: none; -} - -body.mini-navbar .nav-header { - padding: 0; - background-color: #1ab394; -} - -body.canvas-menu .nav-header { - padding: 33px 25px; -} - -body.mini-navbar #page-wrapper { - margin: 0 0 0 70px; -} - -body.canvas-menu.mini-navbar #page-wrapper, -body.canvas-menu.mini-navbar .footer { - margin: 0 0 0 0; -} - -body.fixed-sidebar .navbar-static-side, -body.canvas-menu .navbar-static-side { - position: fixed; - width: 220px; - z-index: 2001; - height: 100%; -} - -body.fixed-sidebar.mini-navbar .navbar-static-side { - width: 70px; -} - -body.fixed-sidebar.mini-navbar #page-wrapper { - margin: 0 0 0 70px; -} - -body.body-small.fixed-sidebar.mini-navbar #page-wrapper { - margin: 0 0 0 70px; -} - -body.body-small.fixed-sidebar.mini-navbar .navbar-static-side { - width: 70px; -} - -.fixed-sidebar.mini-navbar .nav li> .nav-second-level { - display: none; -} - -.fixed-sidebar.mini-navbar .nav li.active { - border-left-width: 0; -} - -.fixed-sidebar.mini-navbar .nav li:hover > .nav-second-level, -.canvas-menu.mini-navbar .nav li:hover > .nav-second-level { - position: absolute; - left: 70px; - top: 0px; - background-color: #2f4050; - padding: 10px 10px 0 10px; - font-size: 12px; - display: block; - min-width: 140px; - border-radius: 2px; -} - -body.fixed-sidebar.mini-navbar .navbar-default .nav > li > .nav-second-level li a { - font-size: 12px; - border-radius: 3px; -} - -body.canvas-menu.mini-navbar .navbar-default .nav > li > .nav-second-level li a { - font-size: 13px; - border-radius: 3px; -} - -.fixed-sidebar.mini-navbar .nav-second-level li a, -.canvas-menu.mini-navbar .nav-second-level li a { - padding: 10px 10px 10px 15px; -} - -.fixed-sidebar.mini-navbar .nav-second-level, -.canvas-menu.mini-navbar .nav-second-level { - position: relative; - padding: 0; - font-size: 13px; -} - -.fixed-sidebar.mini-navbar li.active .nav-second-level, -.canvas-menu.mini-navbar li.active .nav-second-level { - left: 0px; -} - -body.canvas-menu nav.navbar-static-side { - z-index: 2001; - background: #2f4050; - height: 100%; - position: fixed; - display: none; -} - -body.canvas-menu.mini-navbar nav.navbar-static-side { - display: block; - width: 70px; -} - -.top-navigation #page-wrapper { - margin-left: 0; -} - -.top-navigation .navbar-nav .dropdown-menu > .active > a { - background: white; - color: #1ab394; - font-weight: bold; -} - -.white-bg .navbar-fixed-top, -.white-bg .navbar-static-top { - background: #fff; -} - -.top-navigation .navbar { - margin-bottom: 0; -} - -.top-navigation .nav > li > a { - padding: 15px 20px; - color: #676a6c; -} - -.top-navigation .nav > li a:hover, -.top-navigation .nav > li a:focus { - background: #fff; - color: #1ab394; -} - -.top-navigation .nav > li.active { - background: #fff; - border: none; -} - -.top-navigation .nav > li.active > a { - color: #1ab394; -} - -.top-navigation .navbar-right { - padding-right: 10px; -} - -.top-navigation .navbar-nav .dropdown-menu { - box-shadow: none; - border: 1px solid #e7eaec; -} - -.top-navigation .dropdown-menu > li > a { - margin: 0; - padding: 7px 20px; -} - -.navbar .dropdown-menu { - margin-top: 0px; -} - -.top-navigation .navbar-brand { - background: #1ab394; - color: #fff; - padding: 15px 25px; -} - -.top-navigation .navbar-top-links li:last-child { - margin-right: 0; -} - -.top-navigation.mini-navbar #page-wrapper, -.top-navigation.body-small.fixed-sidebar.mini-navbar #page-wrapper, -.mini-navbar .top-navigation #page-wrapper, -.body-small.fixed-sidebar.mini-navbar .top-navigation #page-wrapper, -.canvas-menu #page-wrapper { - margin: 0; -} - -.top-navigation.fixed-nav #wrapper, -.fixed-nav #wrapper.top-navigation { - margin-top: 50px; -} - -.top-navigation .footer.fixed { - margin-left: 0 !important; -} - -.top-navigation .wrapper.wrapper-content { - padding: 40px; -} - -.top-navigation.body-small .wrapper.wrapper-content, -.body-small .top-navigation .wrapper.wrapper-content { - padding: 40px 0px 40px 0px; -} - -.navbar-toggle { - background-color: #1ab394; - color: #fff; - padding: 6px 12px; - font-size: 14px; -} - -.top-navigation .navbar-nav .open .dropdown-menu > li > a, -.top-navigation .navbar-nav .open .dropdown-menu .dropdown-header { - padding: 10px 15px 10px 20px; -} - -@media (max-width: 768px) { - .top-navigation .navbar-header { - display: block; - float: none; - } -} - -.menu-visible-lg, -.menu-visible-md { - display: none !important; -} - -@media (min-width: 1200px) { - .menu-visible-lg { - display: block !important; - } -} - -@media (min-width: 992px) { - .menu-visible-md { - display: block !important; - } -} - -@media (max-width: 767px) { - .menu-visible-md { - display: block !important; - } - .menu-visible-lg { - display: block !important; - } -} - -.btn { - border-radius: 3px; -} - -.float-e-margins .btn { - margin-bottom: 5px; -} - -.btn-w-m { - min-width: 120px; -} - -.btn-primary.btn-outline { - color: #1ab394; -} - -.btn-success.btn-outline { - color: #1c84c6; -} - -.btn-info.btn-outline { - color: #23c6c8; -} - -.btn-warning.btn-outline { - color: #f8ac59; -} - -.btn-danger.btn-outline { - color: #ed5565; -} - -.btn-primary.btn-outline:hover, -.btn-success.btn-outline:hover, -.btn-info.btn-outline:hover, -.btn-warning.btn-outline:hover, -.btn-danger.btn-outline:hover { - color: #fff; -} - -.btn-primary { - background-color: #1ab394; - border-color: #1ab394; - color: #FFFFFF; -} - -.btn-primary:hover, -.btn-primary:focus, -.btn-primary:active, -.btn-primary.active, -.open .dropdown-toggle.btn-primary { - background-color: #18a689; - border-color: #18a689; - color: #FFFFFF; -} - -.btn-primary:active, -.btn-primary.active, -.open .dropdown-toggle.btn-primary { - background-image: none; -} - -.btn-primary.disabled, -.btn-primary.disabled:hover, -.btn-primary.disabled:focus, -.btn-primary.disabled:active, -.btn-primary.disabled.active, -.btn-primary[disabled], -.btn-primary[disabled]:hover, -.btn-primary[disabled]:focus, -.btn-primary[disabled]:active, -.btn-primary.active[disabled], -fieldset[disabled] .btn-primary, -fieldset[disabled] .btn-primary:hover, -fieldset[disabled] .btn-primary:focus, -fieldset[disabled] .btn-primary:active, -fieldset[disabled] .btn-primary.active { - background-color: #1dc5a3; - border-color: #1dc5a3; -} - -.btn-success { - background-color: #1c84c6; - border-color: #1c84c6; - color: #FFFFFF; -} - -.btn-success:hover, -.btn-success:focus, -.btn-success:active, -.btn-success.active, -.open .dropdown-toggle.btn-success { - background-color: #1a7bb9; - border-color: #1a7bb9; - color: #FFFFFF; -} - -.btn-success:active, -.btn-success.active, -.open .dropdown-toggle.btn-success { - background-image: none; -} - -.btn-success.disabled, -.btn-success.disabled:hover, -.btn-success.disabled:focus, -.btn-success.disabled:active, -.btn-success.disabled.active, -.btn-success[disabled], -.btn-success[disabled]:hover, -.btn-success[disabled]:focus, -.btn-success[disabled]:active, -.btn-success.active[disabled], -fieldset[disabled] .btn-success, -fieldset[disabled] .btn-success:hover, -fieldset[disabled] .btn-success:focus, -fieldset[disabled] .btn-success:active, -fieldset[disabled] .btn-success.active { - background-color: #1f90d8; - border-color: #1f90d8; -} - -.btn-info { - background-color: #23c6c8; - border-color: #23c6c8; - color: #FFFFFF; -} - -.btn-info:hover, -.btn-info:focus, -.btn-info:active, -.btn-info.active, -.open .dropdown-toggle.btn-info { - background-color: #21b9bb; - border-color: #21b9bb; - color: #FFFFFF; -} - -.btn-info:active, -.btn-info.active, -.open .dropdown-toggle.btn-info { - background-image: none; -} - -.btn-info.disabled, -.btn-info.disabled:hover, -.btn-info.disabled:focus, -.btn-info.disabled:active, -.btn-info.disabled.active, -.btn-info[disabled], -.btn-info[disabled]:hover, -.btn-info[disabled]:focus, -.btn-info[disabled]:active, -.btn-info.active[disabled], -fieldset[disabled] .btn-info, -fieldset[disabled] .btn-info:hover, -fieldset[disabled] .btn-info:focus, -fieldset[disabled] .btn-info:active, -fieldset[disabled] .btn-info.active { - background-color: #26d7d9; - border-color: #26d7d9; -} - -.btn-default { - background-color: #c2c2c2; - border-color: #c2c2c2; - color: #FFFFFF; -} - -.btn-default:hover, -.btn-default:focus, -.btn-default:active, -.btn-default.active, -.open .dropdown-toggle.btn-default { - background-color: #bababa; - border-color: #bababa; - color: #FFFFFF; -} - -.btn-default:active, -.btn-default.active, -.open .dropdown-toggle.btn-default { - background-image: none; -} - -.btn-default.disabled, -.btn-default.disabled:hover, -.btn-default.disabled:focus, -.btn-default.disabled:active, -.btn-default.disabled.active, -.btn-default[disabled], -.btn-default[disabled]:hover, -.btn-default[disabled]:focus, -.btn-default[disabled]:active, -.btn-default.active[disabled], -fieldset[disabled] .btn-default, -fieldset[disabled] .btn-default:hover, -fieldset[disabled] .btn-default:focus, -fieldset[disabled] .btn-default:active, -fieldset[disabled] .btn-default.active { - background-color: #cccccc; - border-color: #cccccc; -} - -.btn-warning { - background-color: #f8ac59; - border-color: #f8ac59; - color: #FFFFFF; -} - -.btn-warning:hover, -.btn-warning:focus, -.btn-warning:active, -.btn-warning.active, -.open .dropdown-toggle.btn-warning { - background-color: #f7a54a; - border-color: #f7a54a; - color: #FFFFFF; -} - -.btn-warning:active, -.btn-warning.active, -.open .dropdown-toggle.btn-warning { - background-image: none; -} - -.btn-warning.disabled, -.btn-warning.disabled:hover, -.btn-warning.disabled:focus, -.btn-warning.disabled:active, -.btn-warning.disabled.active, -.btn-warning[disabled], -.btn-warning[disabled]:hover, -.btn-warning[disabled]:focus, -.btn-warning[disabled]:active, -.btn-warning.active[disabled], -fieldset[disabled] .btn-warning, -fieldset[disabled] .btn-warning:hover, -fieldset[disabled] .btn-warning:focus, -fieldset[disabled] .btn-warning:active, -fieldset[disabled] .btn-warning.active { - background-color: #f9b66d; - border-color: #f9b66d; -} - -.btn-danger { - background-color: #ed5565; - border-color: #ed5565; - color: #FFFFFF; -} - -.btn-danger:hover, -.btn-danger:focus, -.btn-danger:active, -.btn-danger.active, -.open .dropdown-toggle.btn-danger { - background-color: #ec4758; - border-color: #ec4758; - color: #FFFFFF; -} - -.btn-danger:active, -.btn-danger.active, -.open .dropdown-toggle.btn-danger { - background-image: none; -} - -.btn-danger.disabled, -.btn-danger.disabled:hover, -.btn-danger.disabled:focus, -.btn-danger.disabled:active, -.btn-danger.disabled.active, -.btn-danger[disabled], -.btn-danger[disabled]:hover, -.btn-danger[disabled]:focus, -.btn-danger[disabled]:active, -.btn-danger.active[disabled], -fieldset[disabled] .btn-danger, -fieldset[disabled] .btn-danger:hover, -fieldset[disabled] .btn-danger:focus, -fieldset[disabled] .btn-danger:active, -fieldset[disabled] .btn-danger.active { - background-color: #ef6776; - border-color: #ef6776; -} - -.btn-link { - color: inherit; -} - -.btn-link:hover, -.btn-link:focus, -.btn-link:active, -.btn-link.active, -.open .dropdown-toggle.btn-link { - color: #1ab394; - text-decoration: none; -} - -.btn-link:active, -.btn-link.active, -.open .dropdown-toggle.btn-link { - background-image: none; -} - -.btn-link.disabled, -.btn-link.disabled:hover, -.btn-link.disabled:focus, -.btn-link.disabled:active, -.btn-link.disabled.active, -.btn-link[disabled], -.btn-link[disabled]:hover, -.btn-link[disabled]:focus, -.btn-link[disabled]:active, -.btn-link.active[disabled], -fieldset[disabled] .btn-link, -fieldset[disabled] .btn-link:hover, -fieldset[disabled] .btn-link:focus, -fieldset[disabled] .btn-link:active, -fieldset[disabled] .btn-link.active { - color: #cacaca; -} - -.btn-white { - color: inherit; - background: white; - border: 1px solid #e7eaec; -} - -.btn-white:hover, -.btn-white:focus, -.btn-white:active, -.btn-white.active, -.open .dropdown-toggle.btn-white { - color: inherit; - border: 1px solid #d2d2d2; -} - -.btn-white:active, -.btn-white.active { - box-shadow: 0 2px 5px rgba(0, 0, 0, 0.15) inset; -} - -.btn-white:active, -.btn-white.active, -.open .dropdown-toggle.btn-white { - background-image: none; -} - -.btn-white.disabled, -.btn-white.disabled:hover, -.btn-white.disabled:focus, -.btn-white.disabled:active, -.btn-white.disabled.active, -.btn-white[disabled], -.btn-white[disabled]:hover, -.btn-white[disabled]:focus, -.btn-white[disabled]:active, -.btn-white.active[disabled], -fieldset[disabled] .btn-white, -fieldset[disabled] .btn-white:hover, -fieldset[disabled] .btn-white:focus, -fieldset[disabled] .btn-white:active, -fieldset[disabled] .btn-white.active { - color: #cacaca; -} - -.form-control, -.form-control:focus, -.has-error .form-control:focus, -.has-success .form-control:focus, -.has-warning .form-control:focus, -.navbar-collapse, -.navbar-form, -.navbar-form-custom .form-control:focus, -.navbar-form-custom .form-control:hover, -.open .btn.dropdown-toggle, -.panel, -.popover, -.progress, -.progress-bar { - box-shadow: none; -} - -.btn-outline { - color: inherit; - background-color: transparent; - -webkit-transition: all .5s; - transition: all .5s; -} - -.btn-rounded { - border-radius: 50px; -} - -.btn-large-dim { - width: 90px; - height: 90px; - font-size: 42px; -} - -button.dim { - display: inline-block; - color: #fff; - text-decoration: none; - text-transform: uppercase; - text-align: center; - padding-top: 6px; - margin-right: 10px; - position: relative; - cursor: pointer; - border-radius: 5px; - font-weight: 600; - margin-bottom: 20px !important; -} - -button.dim:active { - top: 3px; -} - -button.btn-primary.dim { - box-shadow: inset 0px 0px 0px #16987e, 0px 5px 0px 0px #16987e, 0px 10px 5px #999999; -} - -button.btn-primary.dim:active { - box-shadow: inset 0px 0px 0px #16987e, 0px 2px 0px 0px #16987e, 0px 5px 3px #999999; -} - -button.btn-default.dim { - box-shadow: inset 0px 0px 0px #b3b3b3, 0px 5px 0px 0px #b3b3b3, 0px 10px 5px #999999; -} - -button.btn-default.dim:active { - box-shadow: inset 0px 0px 0px #b3b3b3, 0px 2px 0px 0px #b3b3b3, 0px 5px 3px #999999; -} - -button.btn-warning.dim { - box-shadow: inset 0px 0px 0px #f79d3c, 0px 5px 0px 0px #f79d3c, 0px 10px 5px #999999; -} - -button.btn-warning.dim:active { - box-shadow: inset 0px 0px 0px #f79d3c, 0px 2px 0px 0px #f79d3c, 0px 5px 3px #999999; -} - -button.btn-info.dim { - box-shadow: inset 0px 0px 0px #1eacae, 0px 5px 0px 0px #1eacae, 0px 10px 5px #999999; -} - -button.btn-info.dim:active { - box-shadow: inset 0px 0px 0px #1eacae, 0px 2px 0px 0px #1eacae, 0px 5px 3px #999999; -} - -button.btn-success.dim { - box-shadow: inset 0px 0px 0px #1872ab, 0px 5px 0px 0px #1872ab, 0px 10px 5px #999999; -} - -button.btn-success.dim:active { - box-shadow: inset 0px 0px 0px #1872ab, 0px 2px 0px 0px #1872ab, 0px 5px 3px #999999; -} - -button.btn-danger.dim { - box-shadow: inset 0px 0px 0px #ea394c, 0px 5px 0px 0px #ea394c, 0px 10px 5px #999999; -} - -button.btn-danger.dim:active { - box-shadow: inset 0px 0px 0px #ea394c, 0px 2px 0px 0px #ea394c, 0px 5px 3px #999999; -} - -button.dim:before { - font-size: 50px; - line-height: 1em; - font-weight: normal; - color: #fff; - display: block; - padding-top: 10px; -} - -button.dim:active:before { - top: 7px; - font-size: 50px; -} - -.label { - background-color: #d1dade; - color: #5e5e5e; - font-size: 10px; - font-weight: 600; - padding: 3px 8px; - text-shadow: none; -} - -.badge { - background-color: #d1dade; - color: #5e5e5e; - font-size: 11px; - font-weight: 600; - padding-bottom: 4px; - padding-left: 6px; - padding-right: 6px; - text-shadow: none; -} - -.label-primary, -.badge-primary { - background-color: #1ab394; - color: #FFFFFF; -} - -.label-success, -.badge-success { - background-color: #1c84c6; - color: #FFFFFF; -} - -.label-warning, -.badge-warning { - background-color: #f8ac59; - color: #FFFFFF; -} - -.label-warning-light, -.badge-warning-light { - background-color: #f8ac59; - color: #ffffff; -} - -.label-danger, -.badge-danger { - background-color: #ed5565; - color: #FFFFFF; -} - -.label-info, -.badge-info { - background-color: #23c6c8; - color: #FFFFFF; -} - -.label-inverse, -.badge-inverse { - background-color: #262626; - color: #FFFFFF; -} - -.label-white, -.badge-white { - background-color: #FFFFFF; - color: #5E5E5E; -} - -.label-white, -.badge-disable { - background-color: #2A2E36; - color: #8B91A0; -} - - -/* TOOGLE SWICH */ - -.onoffswitch { - position: relative; - width: 64px; - -webkit-user-select: none; - -moz-user-select: none; - -ms-user-select: none; -} - -.onoffswitch-checkbox { - display: none; -} - -.onoffswitch-label { - display: block; - overflow: hidden; - cursor: pointer; - border: 2px solid #1ab394; - border-radius: 2px; -} - -.onoffswitch-inner { - width: 200%; - margin-left: -100%; - -webkit-transition: margin 0.3s ease-in 0s; - transition: margin 0.3s ease-in 0s; -} - -.onoffswitch-inner:before, -.onoffswitch-inner:after { - float: left; - width: 50%; - height: 20px; - padding: 0; - line-height: 20px; - font-size: 12px; - color: white; - font-family: Trebuchet, Arial, sans-serif; - font-weight: bold; - box-sizing: border-box; -} - -.onoffswitch-inner:before { - content: "ON"; - padding-left: 10px; - background-color: #1ab394; - color: #FFFFFF; -} - -.onoffswitch-inner:after { - content: "OFF"; - padding-right: 10px; - background-color: #FFFFFF; - color: #999999; - text-align: right; -} - -.onoffswitch-switch { - width: 20px; - margin: 0px; - background: #FFFFFF; - border: 2px solid #1ab394; - border-radius: 2px; - position: absolute; - top: 0; - bottom: 0; - right: 44px; - -webkit-transition: all 0.3s ease-in 0s; - transition: all 0.3s ease-in 0s; -} - -.onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-inner { - margin-left: 0; -} - -.onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-switch { - right: 0px; -} - - -/* CHOSEN PLUGIN */ - -.chosen-container-single .chosen-single { - background: #ffffff; - box-shadow: none; - -moz-box-sizing: border-box; - background-color: #FFFFFF; - border: 1px solid #CBD5DD; - border-radius: 2px; - cursor: text; - height: auto !important; - margin: 0; - min-height: 30px; - overflow: hidden; - padding: 4px 12px; - position: relative; - width: 100%; -} - -.chosen-container-multi .chosen-choices li.search-choice { - background: #f1f1f1; - border: 1px solid #ededed; - border-radius: 2px; - box-shadow: none; - color: #333333; - cursor: default; - line-height: 13px; - margin: 3px 0 3px 5px; - padding: 3px 20px 3px 5px; - position: relative; -} - - -/* PAGINATIN */ - -.pagination > .active > a, -.pagination > .active > span, -.pagination > .active > a:hover, -.pagination > .active > span:hover, -.pagination > .active > a:focus, -.pagination > .active > span:focus { - background-color: #f4f4f4; - border-color: #DDDDDD; - color: inherit; - cursor: default; - z-index: 2; -} - -.pagination > li > a, -.pagination > li > span { - background-color: #FFFFFF; - border: 1px solid #DDDDDD; - color: inherit; - float: left; - line-height: 1.42857; - margin-left: -1px; - padding: 4px 10px; - position: relative; - text-decoration: none; -} - - -/* TOOLTIPS */ - -.tooltip-inner { - background-color: #2F4050; -} - -.tooltip.top .tooltip-arrow { - border-top-color: #2F4050; -} - -.tooltip.right .tooltip-arrow { - border-right-color: #2F4050; -} - -.tooltip.bottom .tooltip-arrow { - border-bottom-color: #2F4050; -} - -.tooltip.left .tooltip-arrow { - border-left-color: #2F4050; -} - - -/* EASY PIE CHART*/ - -.easypiechart { - position: relative; - text-align: center; -} - -.easypiechart .h2 { - margin-left: 10px; - margin-top: 10px; - display: inline-block; -} - -.easypiechart canvas { - top: 0; - left: 0; -} - -.easypiechart .easypie-text { - line-height: 1; - position: absolute; - top: 33px; - width: 100%; - z-index: 1; -} - -.easypiechart img { - margin-top: -4px; -} - -.jqstooltip { - box-sizing: content-box; -} - - -/* FULLCALENDAR */ - -.fc-state-default { - background-color: #ffffff; - background-image: none; - background-repeat: repeat-x; - box-shadow: none; - color: #333333; - text-shadow: none; -} - -.fc-state-default { - border: 1px solid; -} - -.fc-button { - color: inherit; - border: 1px solid #e7eaec; - cursor: pointer; - display: inline-block; - height: 1.9em; - line-height: 1.9em; - overflow: hidden; - padding: 0 0.6em; - position: relative; - white-space: nowrap; -} - -.fc-state-active { - background-color: #1ab394; - border-color: #1ab394; - color: #ffffff; -} - -.fc-header-title h2 { - font-size: 16px; - font-weight: 600; - color: inherit; -} - -.fc-content .fc-widget-header, -.fc-content .fc-widget-content { - border-color: #e7eaec; - font-weight: normal; -} - -.fc-border-separate tbody { - background-color: #F8F8F8; -} - -.fc-state-highlight { - background: none repeat scroll 0 0 #FCF8E3; -} - -.external-event { - padding: 5px 10px; - border-radius: 2px; - cursor: pointer; - margin-bottom: 5px; -} - -.fc-ltr .fc-event-hori.fc-event-end, -.fc-rtl .fc-event-hori.fc-event-start { - border-radius: 2px; -} - -.fc-event, -.fc-agenda .fc-event-time, -.fc-event a { - padding: 4px 6px; - background-color: #1ab394; - /* background color */ - border-color: #1ab394; - /* border color */ -} - -.fc-event-time, -.fc-event-title { - color: #717171; - padding: 0 1px; -} - -.ui-calendar .fc-event-time, -.ui-calendar .fc-event-title { - color: #fff; -} - - -/* Chat */ - -.chat-activity-list .chat-element { - border-bottom: 1px solid #e7eaec; -} - -.chat-element:first-child { - margin-top: 0; -} - -.chat-element { - padding-bottom: 15px; -} - -.chat-element, -.chat-element .media { - margin-top: 15px; -} - -.chat-element, -.media-body { - overflow: hidden; -} - -.media-body { - display: block; - width: auto; -} - -.chat-element > .pull-left { - margin-right: 10px; -} - -.chat-element img.img-circle, -.dropdown-messages-box img.img-circle { - width: 38px; - height: 38px; -} - -.chat-element .well { - border: 1px solid #e7eaec; - box-shadow: none; - margin-top: 10px; - margin-bottom: 5px; - padding: 10px 20px; - font-size: 11px; - line-height: 16px; -} - -.chat-element .actions { - margin-top: 10px; -} - -.chat-element .photos { - margin: 10px 0; -} - -.right.chat-element > .pull-right { - margin-left: 10px; -} - -.chat-photo { - max-height: 180px; - border-radius: 4px; - overflow: hidden; - margin-right: 10px; - margin-bottom: 10px; -} - -.chat { - margin: 0; - padding: 0; - list-style: none; -} - -.chat li { - margin-bottom: 10px; - padding-bottom: 5px; - border-bottom: 1px dotted #B3A9A9; -} - -.chat li.left .chat-body { - margin-left: 60px; -} - -.chat li.right .chat-body { - margin-right: 60px; -} - -.chat li .chat-body p { - margin: 0; - color: #777777; -} - -.panel .slidedown .glyphicon, -.chat .glyphicon { - margin-right: 5px; -} - -.chat-panel .panel-body { - height: 350px; - overflow-y: scroll; -} - - -/* LIST GROUP */ - -a.list-group-item.active, -a.list-group-item.active:hover, -a.list-group-item.active:focus { - background-color: #1ab394; - border-color: #1ab394; - color: #FFFFFF; - z-index: 2; -} - -.list-group-item-heading { - margin-top: 10px; -} - -.list-group-item-text { - margin: 0 0 10px; - color: inherit; - font-size: 12px; - line-height: inherit; -} - -.no-padding .list-group-item { - border-left: none; - border-right: none; - border-bottom: none; -} - -.no-padding .list-group-item:first-child { - border-left: none; - border-right: none; - border-bottom: none; - border-top: none; -} - -.no-padding .list-group { - margin-bottom: 0; -} - -.list-group-item { - background-color: inherit; - border: 1px solid #e7eaec; - display: block; - margin-bottom: -1px; - padding: 10px 15px; - position: relative; -} - -.elements-list .list-group-item { - border-left: none; - border-right: none; - /*border-top: none;*/ - padding: 15px 25px; -} - -.elements-list .list-group-item:first-child { - border-left: none; - border-right: none; - border-top: none !important; -} - -.elements-list .list-group { - margin-bottom: 0; -} - -.elements-list a { - color: inherit; -} - -.elements-list .list-group-item.active, -.elements-list .list-group-item:hover { - background: #f3f3f4; - color: inherit; - border-color: #e7eaec; - /*border-bottom: 1px solid #e7eaec;*/ - /*border-top: 1px solid #e7eaec;*/ - border-radius: 0; -} - -.elements-list li.active { - -webkit-transition: none; - transition: none; -} - -.element-detail-box { - padding: 25px; -} - - -/* FLOT CHART */ - -.flot-chart { - display: block; - height: 200px; -} - -.widget .flot-chart.dashboard-chart { - display: block; - height: 120px; - margin-top: 40px; -} - -.flot-chart.dashboard-chart { - display: block; - height: 180px; - margin-top: 40px; -} - -.flot-chart-content { - width: 100%; - height: 100%; -} - -.flot-chart-pie-content { - width: 200px; - height: 200px; - margin: auto; -} - -.jqstooltip { - position: absolute; - display: block; - left: 0px; - top: 0px; - visibility: hidden; - background: #2b303a; - background-color: rgba(43, 48, 58, 0.8); - color: white; - text-align: left; - white-space: nowrap; - z-index: 10000; - padding: 5px 5px 5px 5px; - min-height: 22px; - border-radius: 3px; -} - -.jqsfield { - color: white; - text-align: left; -} - -.h-200 { - min-height: 200px; -} - -.legendLabel { - padding-left: 5px; -} - -.stat-list li:first-child { - margin-top: 0; -} - -.stat-list { - list-style: none; - padding: 0; - margin: 0; -} - -.stat-percent { - float: right; -} - -.stat-list li { - margin-top: 15px; - position: relative; -} - - -/* DATATABLES */ - -table.dataTable thead .sorting, -table.dataTable thead .sorting_asc:after, -table.dataTable thead .sorting_desc, -table.dataTable thead .sorting_asc_disabled, -table.dataTable thead .sorting_desc_disabled { - background: transparent; -} - -table.dataTable thead .sorting_asc:after { - float: right; - font-family: fontawesome; -} - -table.dataTable thead .sorting_desc:after { - content: "\f0dd"; - float: right; - font-family: fontawesome; -} - -table.dataTable thead .sorting:after { - content: "\f0dc"; - float: right; - font-family: fontawesome; - color: rgba(50, 50, 50, 0.5); -} - -.dataTables_wrapper { - padding-bottom: 30px; -} - - -/* CIRCLE */ - -.img-circle { - border-radius: 50%; -} - -.btn-circle { - width: 30px; - height: 30px; - padding: 6px 0; - border-radius: 15px; - text-align: center; - font-size: 12px; - line-height: 1.428571429; -} - -.btn-circle.btn-lg { - width: 50px; - height: 50px; - padding: 10px 16px; - border-radius: 25px; - font-size: 18px; - line-height: 1.33; -} - -.btn-circle.btn-xl { - width: 70px; - height: 70px; - padding: 10px 16px; - border-radius: 35px; - font-size: 24px; - line-height: 1.33; -} - -.show-grid [class^="col-"] { - padding-top: 10px; - padding-bottom: 10px; - border: 1px solid #ddd; - background-color: #eee !important; -} - -.show-grid { - margin: 15px 0; -} - - -/* ANIMATION */ - -.css-animation-box h1 { - font-size: 44px; -} - -.animation-efect-links a { - padding: 4px 6px; - font-size: 12px; -} - -#animation_box { - background-color: #f9f8f8; - border-radius: 16px; - width: 80%; - margin: 0 auto; - padding-top: 80px; -} - -.animation-text-box { - position: absolute; - margin-top: 40px; - left: 50%; - margin-left: -100px; - width: 200px; -} - -.animation-text-info { - position: absolute; - margin-top: -60px; - left: 50%; - margin-left: -100px; - width: 200px; - font-size: 10px; -} - -.animation-text-box h2 { - font-size: 54px; - font-weight: 600; - margin-bottom: 5px; -} - -.animation-text-box p { - font-size: 12px; - text-transform: uppercase; -} - - -/* PEACE */ - -.pace { - -webkit-pointer-events: none; - pointer-events: none; - -webkit-user-select: none; - -moz-user-select: none; - -ms-user-select: none; - user-select: none; -} - -.pace-inactive { - display: none; -} - -.pace .pace-progress { - background: #1ab394; - position: fixed; - z-index: 2000; - top: 0; - width: 100%; - height: 2px; -} - -.pace-inactive { - display: none; -} - - -/* WIDGETS */ - -.widget { - border-radius: 5px; - padding: 15px 20px; - margin-bottom: 10px; - margin-top: 10px; -} - -.widget.style1 h2 { - font-size: 30px; -} - -.widget h2, -.widget h3 { - margin-top: 5px; - margin-bottom: 0; -} - -.widget-text-box { - padding: 20px; - border: 1px solid #e7eaec; - background: #ffffff; -} - -.widget-head-color-box { - border-radius: 5px 5px 0px 0px; - margin-top: 10px; -} - -.widget .flot-chart { - height: 100px; -} - -.vertical-align div { - display: inline-block; - vertical-align: middle; -} - -.vertical-align h2, -.vertical-align h3 { - margin: 0; -} - -.todo-list { - list-style: none outside none; - margin: 0; - padding: 0; - font-size: 14px; -} - -.todo-list.small-list { - font-size: 12px; -} - -.todo-list.small-list > li { - background: #f3f3f4; - border-left: none; - border-right: none; - border-radius: 4px; - color: inherit; - margin-bottom: 2px; - padding: 6px 6px 6px 12px; -} - -.todo-list.small-list .btn-xs, -.todo-list.small-list .btn-group-xs > .btn { - border-radius: 5px; - font-size: 10px; - line-height: 1.5; - padding: 1px 2px 1px 5px; -} - -.todo-list > li { - background: #f3f3f4; - border-left: 6px solid #e7eaec; - border-right: 6px solid #e7eaec; - border-radius: 4px; - color: inherit; - margin-bottom: 2px; - padding: 10px; -} - -.todo-list .handle { - cursor: move; - display: inline-block; - font-size: 16px; - margin: 0 5px; -} - -.todo-list > li .label { - font-size: 9px; - margin-left: 10px; -} - -.check-link { - font-size: 16px; -} - -.todo-completed { - text-decoration: line-through; -} - -.geo-statistic h1 { - font-size: 36px; - margin-bottom: 0; -} - -.glyphicon.fa { - font-family: "FontAwesome"; -} - - -/* INPUTS */ - -.inline { - display: inline-block !important; -} - -.input-s-sm { - width: 120px; -} - -.input-s { - width: 200px; -} - -.input-s-lg { - width: 250px; -} - -.i-checks { - padding-left: 0; -} - -.form-control, -.single-line { - background-color: #FFFFFF; - background-image: none; - border: 1px solid #e5e6e7; - border-radius: 1px; - color: inherit; - display: block; - padding: 6px 12px; - -webkit-transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s; - transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s; - width: 100%; - font-size: 14px; -} - -.form-control:focus, -.single-line:focus { - border-color: #1ab394 !important; -} - -.has-success .form-control { - border-color: #1ab394; -} - -.has-warning .form-control { - border-color: #f8ac59; -} - -.has-error .form-control { - border-color: #ed5565; -} - -.has-success .control-label { - color: #1ab394; -} - -.has-warning .control-label { - color: #f8ac59; -} - -.has-error .control-label { - color: #ed5565; -} - -.input-group-addon { - background-color: #fff; - border: 1px solid #E5E6E7; - border-radius: 1px; - color: inherit; - font-size: 14px; - font-weight: 400; - line-height: 1; - padding: 6px 12px; - text-align: center; -} - -.spinner-buttons.input-group-btn .btn-xs { - line-height: 1.13; -} - -.spinner-buttons.input-group-btn { - width: 20%; -} - -.noUi-connect { - background: none repeat scroll 0 0 #1ab394; - box-shadow: none; -} - -.slider_red .noUi-connect { - background: none repeat scroll 0 0 #ed5565; - box-shadow: none; -} - - -/* UI Sortable */ - -.ui-sortable .ibox-title { - cursor: move; -} - -.ui-sortable-placeholder { - border: 1px dashed #cecece !important; - visibility: visible !important; - background: #e7eaec; -} - -.ibox.ui-sortable-placeholder { - margin: 0px 0px 23px !important; -} - - -/* Tabs */ - -.tabs-container .panel-body { - background: #fff; - border: 1px solid #e7eaec; - border-radius: 2px; - padding: 20px; - position: relative; -} - -.tabs-container .nav-tabs > li.active > a, -.tabs-container .nav-tabs > li.active > a:hover, -.tabs-container .nav-tabs > li.active > a:focus { - border: 1px solid #e7eaec; - border-bottom-color: transparent; - background-color: #fff; -} - -.tabs-container .nav-tabs > li { - float: left; - margin-bottom: -1px; -} - -.tabs-container .tab-pane .panel-body { - border-top: none; -} - -.tabs-container .nav-tabs > li.active > a, -.tabs-container .nav-tabs > li.active > a:hover, -.tabs-container .nav-tabs > li.active > a:focus { - border: 1px solid #e7eaec; - border-bottom-color: transparent; -} - -.tabs-container .nav-tabs { - border-bottom: 1px solid #e7eaec; -} - -.tabs-container .tab-pane .panel-body { - border-top: none; -} - -.tabs-container .tabs-left .tab-pane .panel-body, -.tabs-container .tabs-right .tab-pane .panel-body { - border-top: 1px solid #e7eaec; -} - -.tabs-container .nav-tabs > li a:hover { - background: transparent; - border-color: transparent; -} - -.tabs-container .tabs-below > .nav-tabs, -.tabs-container .tabs-right > .nav-tabs, -.tabs-container .tabs-left > .nav-tabs { - border-bottom: 0; -} - -.tabs-container .tabs-left .panel-body { - position: static; -} - -.tabs-container .tabs-left > .nav-tabs, -.tabs-container .tabs-right > .nav-tabs { - width: 20%; -} - -.tabs-container .tabs-left .panel-body { - width: 80%; - margin-left: 20%; -} - -.tabs-container .tabs-right .panel-body { - width: 80%; - margin-right: 20%; -} - -.tabs-container .tab-content > .tab-pane, -.tabs-container .pill-content > .pill-pane { - display: none; -} - -.tabs-container .tab-content > .active, -.tabs-container .pill-content > .active { - display: block; -} - -.tabs-container .tabs-below > .nav-tabs { - border-top: 1px solid #e7eaec; -} - -.tabs-container .tabs-below > .nav-tabs > li { - margin-top: -1px; - margin-bottom: 0; -} - -.tabs-container .tabs-below > .nav-tabs > li > a { - border-radius: 0 0 4px 4px; -} - -.tabs-container .tabs-below > .nav-tabs > li > a:hover, -.tabs-container .tabs-below > .nav-tabs > li > a:focus { - border-top-color: #e7eaec; - border-bottom-color: transparent; -} - -.tabs-container .tabs-left > .nav-tabs > li, -.tabs-container .tabs-right > .nav-tabs > li { - float: none; -} - -.tabs-container .tabs-left > .nav-tabs > li > a, -.tabs-container .tabs-right > .nav-tabs > li > a { - min-width: 74px; - margin-right: 0; - margin-bottom: 3px; -} - -.tabs-container .tabs-left > .nav-tabs { - float: left; - margin-right: 19px; -} - -.tabs-container .tabs-left > .nav-tabs > li > a { - margin-right: -1px; - border-radius: 4px 0 0 4px; -} - -.tabs-container .tabs-left > .nav-tabs .active > a, -.tabs-container .tabs-left > .nav-tabs .active > a:hover, -.tabs-container .tabs-left > .nav-tabs .active > a:focus { - border-color: #e7eaec transparent #e7eaec #e7eaec; - *border-right-color: #ffffff; -} - -.tabs-container .tabs-right > .nav-tabs { - float: right; - margin-left: 19px; -} - -.tabs-container .tabs-right > .nav-tabs > li > a { - margin-left: -1px; - border-radius: 0 4px 4px 0; -} - -.tabs-container .tabs-right > .nav-tabs .active > a, -.tabs-container .tabs-right > .nav-tabs .active > a:hover, -.tabs-container .tabs-right > .nav-tabs .active > a:focus { - border-color: #e7eaec #e7eaec #e7eaec transparent; - *border-left-color: #ffffff; - z-index: 1; -} - - -/* SWITCHES */ - -.onoffswitch { - position: relative; - width: 54px; - -webkit-user-select: none; - -moz-user-select: none; - -ms-user-select: none; -} - -.onoffswitch-checkbox { - display: none; -} - -.onoffswitch-label { - display: block; - overflow: hidden; - cursor: pointer; - border: 2px solid #1AB394; - border-radius: 3px; -} - -.onoffswitch-inner { - display: block; - width: 200%; - margin-left: -100%; - -webkit-transition: margin 0.3s ease-in 0s; - transition: margin 0.3s ease-in 0s; -} - -.onoffswitch-inner:before, -.onoffswitch-inner:after { - display: block; - float: left; - width: 50%; - height: 16px; - padding: 0; - line-height: 16px; - font-size: 10px; - color: white; - font-family: Trebuchet, Arial, sans-serif; - font-weight: bold; - box-sizing: border-box; -} - -.onoffswitch-inner:before { - content: "ON"; - padding-left: 7px; - background-color: #1AB394; - color: #FFFFFF; -} - -.onoffswitch-inner:after { - content: "OFF"; - padding-right: 7px; - background-color: #FFFFFF; - color: #919191; - text-align: right; -} - -.onoffswitch-switch { - display: block; - width: 18px; - margin: 0px; - background: #FFFFFF; - border: 2px solid #1AB394; - border-radius: 3px; - position: absolute; - top: 0; - bottom: 0; - right: 36px; - -webkit-transition: all 0.3s ease-in 0s; - transition: all 0.3s ease-in 0s; -} - -.onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-inner { - margin-left: 0; -} - -.onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-switch { - right: 0px; -} - - -/* Nestable list */ - -.dd { - position: relative; - display: block; - margin: 0; - padding: 0; - list-style: none; - font-size: 13px; - line-height: 20px; -} - -.dd-list { - display: block; - position: relative; - margin: 0; - padding: 0; - list-style: none; -} - -.dd-list .dd-list { - padding-left: 30px; -} - -.dd-collapsed .dd-list { - display: none; -} - -.dd-item, -.dd-empty, -.dd-placeholder { - display: block; - position: relative; - margin: 0; - padding: 0; - min-height: 20px; - font-size: 13px; - line-height: 20px; -} - -.dd-handle { - display: block; - margin: 5px 0; - padding: 5px 10px; - color: #333; - text-decoration: none; - border: 1px solid #e7eaec; - background: #f5f5f5; - border-radius: 3px; - box-sizing: border-box; - -moz-box-sizing: border-box; -} - -.dd-handle span { - font-weight: bold; -} - -.dd-handle:hover { - background: #f0f0f0; - cursor: pointer; - font-weight: bold; -} - -.dd-item > button { - display: block; - position: relative; - cursor: pointer; - float: left; - width: 25px; - height: 20px; - margin: 5px 0; - padding: 0; - text-indent: 100%; - white-space: nowrap; - overflow: hidden; - border: 0; - background: transparent; - font-size: 12px; - line-height: 1; - text-align: center; - font-weight: bold; -} - -.dd-item > button:before { - content: '+'; - display: block; - position: absolute; - width: 100%; - text-align: center; - text-indent: 0; -} - -.dd-item > button[data-action="collapse"]:before { - content: '-'; -} - -#nestable2 .dd-item > button { - font-family: FontAwesome; - height: 34px; - width: 33px; - color: #c1c1c1; -} - -#nestable2 .dd-item > button:before { - content: "\f067"; -} - -#nestable2 .dd-item > button[data-action="collapse"]:before { - content: "\f068"; -} - -.dd-placeholder, -.dd-empty { - margin: 5px 0; - padding: 0; - min-height: 30px; - background: #f2fbff; - border: 1px dashed #b6bcbf; - box-sizing: border-box; - -moz-box-sizing: border-box; -} - -.dd-empty { - border: 1px dashed #bbb; - min-height: 100px; - background-color: #e5e5e5; - background-image: -webkit-linear-gradient(45deg, #ffffff 25%, transparent 25%, transparent 75%, #ffffff 75%, #ffffff), -webkit-linear-gradient(45deg, #ffffff 25%, transparent 25%, transparent 75%, #ffffff 75%, #ffffff); - background-image: linear-gradient(45deg, #ffffff 25%, transparent 25%, transparent 75%, #ffffff 75%, #ffffff), linear-gradient(45deg, #ffffff 25%, transparent 25%, transparent 75%, #ffffff 75%, #ffffff); - background-size: 60px 60px; - background-position: 0 0, 30px 30px; -} - -.dd-dragel { - position: absolute; - z-index: 9999; - pointer-events: none; -} - -.dd-dragel > .dd-item .dd-handle { - margin-top: 0; -} - -.dd-dragel .dd-handle { - box-shadow: 2px 4px 6px 0 rgba(0, 0, 0, 0.1); -} - - -/** -* Nestable Extras -*/ - -.nestable-lists { - display: block; - clear: both; - padding: 30px 0; - width: 100%; - border: 0; - border-top: 2px solid #ddd; - border-bottom: 2px solid #ddd; -} - -#nestable-menu { - padding: 0; - margin: 10px 0 20px 0; -} - -#nestable-output, -#nestable2-output { - width: 100%; - font-size: 0.75em; - line-height: 1.333333em; - font-family: lucida grande, lucida sans unicode, helvetica, arial, sans-serif; - padding: 5px; - box-sizing: border-box; - -moz-box-sizing: border-box; -} - -#nestable2 .dd-handle { - color: inherit; - border: 1px dashed #e7eaec; - background: #f3f3f4; - padding: 10px; -} - -#nestable2 .dd-handle:hover { - /*background: #bbb;*/ -} - -#nestable2 span.label { - margin-right: 10px; -} - -#nestable-output, -#nestable2-output { - font-size: 12px; - padding: 25px; - box-sizing: border-box; - -moz-box-sizing: border-box; -} - - -/* CodeMirror */ - -.CodeMirror { - border: 1px solid #eee; - height: auto; -} - -.CodeMirror-scroll { - overflow-y: hidden; - overflow-x: auto; -} - - -/* Google Maps */ - -.google-map { - height: 300px; -} - - -/* Validation */ - -label.error { - color: #cc5965; - display: inline-block; - margin-left: 5px; -} - -.form-control.error { - border: 1px dotted #cc5965; -} - - -/* ngGrid */ - -.gridStyle { - border: 1px solid #d4d4d4; - width: 100%; - height: 400px; -} - -.gridStyle2 { - border: 1px solid #d4d4d4; - width: 500px; - height: 300px; -} - -.ngH eaderCell { - border-right: none; - border-bottom: 1px solid #e7eaec; -} - -.ngCell { - border-right: none; -} - -.ngTopPanel { - background: #F5F5F6; -} - -.ngRow.even { - background: #f9f9f9; -} - -.ngRow.selected { - background: #EBF2F1; -} - -.ngRow { - border-bottom: 1px solid #e7eaec; -} - -.ngCell { - background-color: transparent; -} - -.ngHeaderCell { - border-right: none; -} - - -/* Toastr custom style */ - -#toast-container > .toast { - background-image: none !important; -} - -#toast-container > .toast:before { - position: fixed; - font-family: FontAwesome; - font-size: 24px; - line-height: 24px; - float: left; - color: #FFF; - padding-right: 0.5em; - margin: auto 0.5em auto -1.5em; -} - -#toast-container > div { - box-shadow: 0 0 3px #999; - opacity: .9; - -ms-filter: alpha(opacity=90); - filter: alpha(opacity=90); -} - -#toast-container >:hover { - box-shadow: 0 0 4px #999; - opacity: 1; - -ms-filter: alpha(opacity=100); - filter: alpha(opacity=100); - cursor: pointer; -} - -.toast { - background-color: #1ab394; -} - -.toast-success { - background-color: #1ab394; -} - -.toast-error { - background-color: #ed5565; -} - -.toast-info { - background-color: #23c6c8; -} - -.toast-warning { - background-color: #f8ac59; -} - -.toast-top-full-width { - margin-top: 20px; -} - -.toast-bottom-full-width { - margin-bottom: 20px; -} - - -/* Image cropper style */ - -.img-container, -.img-preview { - overflow: hidden; - text-align: center; - width: 100%; -} - -.img-preview-sm { - height: 130px; - width: 200px; -} - - -/* Forum styles */ - -.forum-post-container .media { - margin: 10px 10px 10px 10px; - padding: 20px 10px 20px 10px; - border-bottom: 1px solid #f1f1f1; -} - -.forum-avatar { - float: left; - margin-right: 20px; - text-align: center; - width: 110px; -} - -.forum-avatar .img-circle { - height: 48px; - width: 48px; -} - -.author-info { - color: #676a6c; - font-size: 11px; - margin-top: 5px; - text-align: center; -} - -.forum-post-info { - padding: 9px 12px 6px 12px; - background: #f9f9f9; - border: 1px solid #f1f1f1; -} - -.media-body > .media { - background: #f9f9f9; - border-radius: 3px; - border: 1px solid #f1f1f1; -} - -.forum-post-container .media-body .photos { - margin: 10px 0; -} - -.forum-photo { - max-width: 140px; - border-radius: 3px; -} - -.media-body > .media .forum-avatar { - width: 70px; - margin-right: 10px; -} - -.media-body > .media .forum-avatar .img-circle { - height: 38px; - width: 38px; -} - -.mid-icon { - font-size: 66px; -} - -.forum-item { - margin: 10px 0; - padding: 10px 0 20px; - border-bottom: 1px solid #f1f1f1; -} - -.views-number { - font-size: 24px; - line-height: 18px; - font-weight: 400; -} - -.forum-container, -.forum-post-container { - padding: 30px !important; -} - -.forum-item small { - color: #999; -} - -.forum-item .forum-sub-title { - color: #999; - margin-left: 50px; -} - -.forum-title { - margin: 15px 0 15px 0; -} - -.forum-info { - text-align: center; -} - -.forum-desc { - color: #999; -} - -.forum-icon { - float: left; - width: 30px; - margin-right: 20px; - text-align: center; -} - -a.forum-item-title { - color: inherit; - display: block; - font-size: 18px; - font-weight: 600; -} - -a.forum-item-title:hover { - color: inherit; -} - -.forum-icon .fa { - font-size: 30px; - margin-top: 8px; - color: #9b9b9b; -} - -.forum-item.active .fa { - color: #1ab394; -} - -.forum-item.active a.forum-item-title { - color: #1ab394; -} - -@media (max-width: 992px) { - .forum-info { - margin: 15px 0 10px 0px; - /* Comment this is you want to show forum info in small devices */ - display: none; - } - .forum-desc { - float: none !important; - } -} - - -/* New Timeline style */ - -.vertical-container { - /* this class is used to give a max-width to the element it is applied to, and center it horizontally when it reaches that max-width */ - width: 90%; - max-width: 1170px; - margin: 0 auto; -} - -.vertical-container::after { - /* clearfix */ - content: ''; - display: table; - clear: both; -} - -#vertical-timeline { - position: relative; - padding: 0; - margin-top: 2em; - margin-bottom: 2em; -} - -#vertical-timeline::before { - content: ''; - position: absolute; - top: 0; - left: 18px; - height: 100%; - width: 4px; - background: #f1f1f1; -} - -.vertical-timeline-content .btn { - float: right; -} - -#vertical-timeline.light-timeline:before { - background: #e7eaec; -} - -.dark-timeline .vertical-timeline-content:before { - border-color: transparent #f5f5f5 transparent transparent; -} - -.dark-timeline.center-orientation .vertical-timeline-content:before { - border-color: transparent transparent transparent #f5f5f5; -} - -.dark-timeline .vertical-timeline-block:nth-child(2n) .vertical-timeline-content:before, -.dark-timeline.center-orientation .vertical-timeline-block:nth-child(2n) .vertical-timeline-content:before { - border-color: transparent #f5f5f5 transparent transparent; -} - -.dark-timeline .vertical-timeline-content, -.dark-timeline.center-orientation .vertical-timeline-content { - background: #f5f5f5; -} - -@media only screen and (min-width: 1170px) { - #vertical-timeline.center-orientation { - margin-top: 3em; - margin-bottom: 3em; - } - #vertical-timeline.center-orientation:before { - left: 50%; - margin-left: -2px; - } -} - -@media only screen and (max-width: 1170px) { - .center-orientation.dark-timeline .vertical-timeline-content:before { - border-color: transparent #f5f5f5 transparent transparent; - } -} - -.vertical-timeline-block { - position: relative; - margin: 2em 0; -} - -.vertical-timeline-block:after { - content: ""; - display: table; - clear: both; -} - -.vertical-timeline-block:first-child { - margin-top: 0; -} - -.vertical-timeline-block:last-child { - margin-bottom: 0; -} - -@media only screen and (min-width: 1170px) { - .center-orientation .vertical-timeline-block { - margin: 4em 0; - } - .center-orientation .vertical-timeline-block:first-child { - margin-top: 0; - } - .center-orientation .vertical-timeline-block:last-child { - margin-bottom: 0; - } -} - -.vertical-timeline-icon { - position: absolute; - top: 0; - left: 0; - width: 40px; - height: 40px; - border-radius: 50%; - font-size: 16px; - border: 3px solid #f1f1f1; - text-align: center; -} - -.vertical-timeline-icon i { - display: block; - width: 24px; - height: 24px; - position: relative; - left: 50%; - top: 50%; - margin-left: -12px; - margin-top: -9px; -} - -@media only screen and (min-width: 1170px) { - .center-orientation .vertical-timeline-icon { - width: 50px; - height: 50px; - left: 50%; - margin-left: -25px; - -webkit-transform: translateZ(0); - -webkit-backface-visibility: hidden; - font-size: 19px; - } - .center-orientation .vertical-timeline-icon i { - margin-left: -12px; - margin-top: -10px; - } - .center-orientation .cssanimations .vertical-timeline-icon.is-hidden { - visibility: hidden; - } -} - -.vertical-timeline-content { - position: relative; - margin-left: 60px; - background: white; - border-radius: 0.25em; - padding: 1em; -} - -.vertical-timeline-content:after { - content: ""; - display: table; - clear: both; -} - -.vertical-timeline-content h2 { - font-weight: 400; - margin-top: 4px; -} - -.vertical-timeline-content p { - margin: 1em 0; - line-height: 1.6; -} - -.vertical-timeline-content .vertical-date { - float: left; - font-weight: 500; -} - -.vertical-date small { - color: #1ab394; - font-weight: 400; -} - -.vertical-timeline-content::before { - content: ''; - position: absolute; - top: 16px; - right: 100%; - height: 0; - width: 0; - border: 7px solid transparent; - border-right: 7px solid white; -} - -@media only screen and (min-width: 768px) { - .vertical-timeline-content h2 { - font-size: 18px; - } - .vertical-timeline-content p { - font-size: 13px; - } -} - -@media only screen and (min-width: 1170px) { - .center-orientation .vertical-timeline-content { - margin-left: 0; - padding: 1.6em; - width: 45%; - } - .center-orientation .vertical-timeline-content::before { - top: 24px; - left: 100%; - border-color: transparent; - border-left-color: white; - } - .center-orientation .vertical-timeline-content .btn { - float: left; - } - .center-orientation .vertical-timeline-content .vertical-date { - position: absolute; - width: 100%; - left: 122%; - top: 2px; - font-size: 14px; - } - .center-orientation .vertical-timeline-block:nth-child(even) .vertical-timeline-content { - float: right; - } - .center-orientation .vertical-timeline-block:nth-child(even) .vertical-timeline-content::before { - top: 24px; - left: auto; - right: 100%; - border-color: transparent; - border-right-color: white; - } - .center-orientation .vertical-timeline-block:nth-child(even) .vertical-timeline-content .btn { - float: right; - } - .center-orientation .vertical-timeline-block:nth-child(even) .vertical-timeline-content .vertical-date { - left: auto; - right: 122%; - text-align: right; - } - .center-orientation .cssanimations .vertical-timeline-content.is-hidden { - visibility: hidden; - } -} - -.sidebard-panel { - width: 220px; - background: #ebebed; - padding: 10px 20px; - position: absolute; - right: 0; -} - -.sidebard-panel .feed-element img.img-circle { - width: 32px; - height: 32px; -} - -.sidebard-panel .feed-element, -.media-body, -.sidebard-panel p { - font-size: 12px; -} - -.sidebard-panel .feed-element { - margin-top: 20px; - padding-bottom: 0; -} - -.sidebard-panel .list-group { - margin-bottom: 10px; -} - -.sidebard-panel .list-group .list-group-item { - padding: 5px 0; - font-size: 12px; - border: 0; -} - -.sidebar-content .wrapper, -.wrapper.sidebar-content { - padding-right: 240px !important; -} - -#right-sidebar { - background-color: #fff; - border-left: 1px solid #e7eaec; - border-top: 1px solid #e7eaec; - overflow: hidden; - position: fixed; - top: 60px; - width: 260px !important; - z-index: 1009; - bottom: 0; - right: -260px; -} - -#right-sidebar.sidebar-open { - right: 0; -} - -#right-sidebar.sidebar-open.sidebar-top { - top: 0; - border-top: none; -} - -.sidebar-container ul.nav-tabs { - border: none; -} - -.sidebar-container ul.nav-tabs.navs-4 li { - width: 25%; -} - -.sidebar-container ul.nav-tabs.navs-3 li { - width: 33.3333%; -} - -.sidebar-container ul.nav-tabs.navs-2 li { - width: 50%; -} - -.sidebar-container ul.nav-tabs li { - border: none; -} - -.sidebar-container ul.nav-tabs li a { - border: none; - padding: 12px 10px; - margin: 0; - border-radius: 0; - background: #2f4050; - color: #fff; - text-align: center; - border-right: 1px solid #334556; -} - -.sidebar-container ul.nav-tabs li.active a { - border: none; - background: #f9f9f9; - color: #676a6c; - font-weight: bold; -} - -.sidebar-container .nav-tabs > li.active > a:hover, -.sidebar-container .nav-tabs > li.active > a:focus { - border: none; -} - -.sidebar-container ul.sidebar-list { - margin: 0; - padding: 0; -} - -.sidebar-container ul.sidebar-list li { - border-bottom: 1px solid #e7eaec; - padding: 15px 20px; - list-style: none; - font-size: 12px; -} - -.sidebar-container .sidebar-message:nth-child(2n+2) { - background: #f9f9f9; -} - -.sidebar-container ul.sidebar-list li a { - text-decoration: none; - color: inherit; -} - -.sidebar-container .sidebar-content { - padding: 15px 20px; - font-size: 12px; -} - -.sidebar-container .sidebar-title { - background: #f9f9f9; - padding: 20px; - border-bottom: 1px solid #e7eaec; -} - -.sidebar-container .sidebar-title h3 { - margin-bottom: 3px; - padding-left: 2px; -} - -.sidebar-container .tab-content h4 { - margin-bottom: 5px; -} - -.sidebar-container .sidebar-message > a > .pull-left { - margin-right: 10px; -} - -.sidebar-container .sidebar-message > a { - text-decoration: none; - color: inherit; -} - -.sidebar-container .sidebar-message { - padding: 15px 20px; -} - -.sidebar-container .sidebar-message .message-avatar { - height: 38px; - width: 38px; - border-radius: 50%; -} - -.sidebar-container .setings-item { - padding: 15px 20px; - border-bottom: 1px solid #e7eaec; -} - -body { - font-family: "open sans", "Helvetica Neue", Helvetica, Arial, sans-serif; - font-size: 13px; - color: #676a6c; - overflow-x: hidden; -} - -html, -body { - height: 100%; -} - -body.full-height-layout #wrapper, -body.full-height-layout #page-wrapper { - height: 100%; -} - -#page-wrapper { - min-height: auto; -} - -body.boxed-layout { - background: url('patterns/shattered.png'); -} - -body.boxed-layout #wrapper { - background-color: #2f4050; - max-width: 1200px; - margin: 0 auto; -} - -.top-navigation.boxed-layout #wrapper, -.boxed-layout #wrapper.top-navigation { - max-width: 1300px !important; -} - -.block { - display: block; -} - -.clear { - display: block; - overflow: hidden; -} - -a { - cursor: pointer; -} - -a:hover, -a:focus { - text-decoration: none; -} - -.border-bottom { - border-bottom: 1px solid #e7eaec !important; -} - -.font-bold { - font-weight: 600; -} - -.font-noraml { - font-weight: 400; -} - -.text-uppercase { - text-transform: uppercase; -} - -.b-r { - border-right: 1px solid #e7eaec; -} - -.hr-line-dashed { - border-top: 1px dashed #e7eaec; - color: #ffffff; - background-color: #ffffff; - height: 1px; - margin: 20px 0; -} - -.hr-line-solid { - border-bottom: 1px solid #e7eaec; - background-color: rgba(0, 0, 0, 0); - border-style: solid !important; - margin-top: 15px; - margin-bottom: 15px; -} - -video { - width: 100% !important; - height: auto !important; -} - - -/* GALLERY */ - -.gallery > .row > div { - margin-bottom: 15px; -} - -.fancybox img { - margin-bottom: 5px; - /* Only for demo */ - width: 24%; -} - - -/* Summernote text editor */ - -.note-editor { - height: auto!important; - min-height: 100px; - border: solid 1px #e5e6e7; -} - - -/* MODAL */ - -.modal-content { - background-clip: padding-box; - background-color: #FFFFFF; - border: 1px solid rgba(0, 0, 0, 0); - border-radius: 4px; - box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3); - outline: 0 none; -} - -.modal-dialog { - z-index: 1200; -} - -.modal-body { - padding: 20px 30px 30px 30px; -} - -.inmodal .modal-body { - background: #f8fafb; -} - -.inmodal .modal-header { - padding: 30px 15px; - text-align: center; -} - -.animated.modal.fade .modal-dialog { - -webkit-transform: none; - -ms-transform: none; - transform: none; -} - -.inmodal .modal-title { - font-size: 26px; -} - -.inmodal .modal-icon { - font-size: 84px; - color: #e2e3e3; -} - -.modal-footer { - margin-top: 0; -} - - -/* WRAPPERS */ - -#wrapper { - width: 100%; - overflow-x: hidden; - background-color: #2f4050; -} - -.wrapper { - padding: 0 20px; -} - -.wrapper-content { - padding: 20px; -} - -#page-wrapper { - padding: 0 15px; - position: inherit; - margin: 0 0 0 220px; -} - -.title-action { - text-align: right; - padding-top: 30px; -} - -.ibox-content h1, -.ibox-content h2, -.ibox-content h3, -.ibox-content h4, -.ibox-content h5, -.ibox-title h1, -.ibox-title h2, -.ibox-title h3, -.ibox-title h4, -.ibox-title h5 { - margin-top: 5px; -} - -ul.unstyled, -ol.unstyled { - list-style: none outside none; - margin-left: 0; -} - -.big-icon { - font-size: 160px; - color: #e5e6e7; -} - - -/* FOOTER */ - -.footer { - background: none repeat scroll 0 0 white; - border-top: 1px solid #e7eaec; - overflow: hidden; - padding: 10px 20px; - margin: 0 -15px; - height: 36px; -} - -.footer.fixed_full { - position: fixed; - bottom: 0; - left: 0; - right: 0; - z-index: 1000; - padding: 10px 20px; - background: white; - border-top: 1px solid #e7eaec; -} - -.footer.fixed { - position: fixed; - bottom: 0; - left: 0; - right: 0; - z-index: 1000; - padding: 10px 20px; - background: white; - border-top: 1px solid #e7eaec; - margin-left: 220px; -} - -body.mini-navbar .footer.fixed, -body.body-small.mini-navbar .footer.fixed { - margin: 0 0 0 70px; -} - -body.mini-navbar.canvas-menu .footer.fixed, -body.canvas-menu .footer.fixed { - margin: 0 !important; -} - -body.fixed-sidebar.body-small.mini-navbar .footer.fixed { - margin: 0 0 0 220px; -} - -body.body-small .footer.fixed { - margin-left: 0px; -} - - -/* PANELS */ - -.page-heading { - border-top: 0; - padding: 0px 20px 20px; -} - -.panel-heading h1, -.panel-heading h2 { - margin-bottom: 5px; -} - - -/*CONTENTTABS*/ - -.content-tabs { - position: relative; - height: 42px; - background: #fafafa; - line-height: 40px; -} - -.content-tabs .roll-nav, -.page-tabs-list { - position: absolute; - width: 40px; - height: 40px; - text-align: center; - color: #999; - z-index: 2; - top: 0; -} - -.content-tabs .roll-left { - left: 0; - border-right: solid 1px #eee; -} - -.content-tabs .roll-right { - right: 0; - border-left: solid 1px #eee; -} - -.content-tabs button { - background: #fff; - border: 0; - height: 40px; - width: 40px; - outline: none; -} - -.content-tabs button:hover { - background: #fafafa; -} - -nav.page-tabs { - margin-left: 40px; - width: 100000px; - height: 40px; - overflow: hidden; -} - -nav.page-tabs .page-tabs-content { - float: left; -} - -.page-tabs a { - display: block; - float: left; - border-right: solid 1px #eee; - padding: 0 15px; -} - -.page-tabs a i:hover { - color: #c00; -} - -.page-tabs a:hover, -.content-tabs .roll-nav:hover { - color: #777; - background: #f2f2f2; - cursor: pointer; -} - -.roll-right.J_tabRight { - right: 140px; -} - -.roll-right.btn-group { - right: 60px; - width: 80px; - padding: 0; -} - -.roll-right.btn-group button { - width: 80px; -} - -.roll-right.J_tabExit { - background: #fff; - height: 40px; - width: 60px; - outline: none; -} - -.dropdown-menu-right { - left: auto; -} - -#content-main { - height: calc(100% - 42px); - overflow: hidden; -} - -.fixed-nav #content-main { - height: calc(100% - 80px); - overflow: hidden; -} - - -/* TABLES */ - -.table-bordered { - border: 1px solid #EBEBEB; -} - -.table-bordered > thead > tr > th, -.table-bordered > thead > tr > td { - background-color: #F5F5F6; - border-bottom-width: 1px; -} - -.table-bordered > thead > tr > th, -.table-bordered > tbody > tr > th, -.table-bordered > tfoot > tr > th, -.table-bordered > thead > tr > td, -.table-bordered > tbody > tr > td, -.table-bordered > tfoot > tr > td { - border: 1px solid #e7e7e7; -} - -.table > thead > tr > th { - border-bottom: 1px solid #DDDDDD; - vertical-align: bottom; -} - -.table > thead > tr > th, -.table > tbody > tr > th, -.table > tfoot > tr > th, -.table > thead > tr > td, -.table > tbody > tr > td, -.table > tfoot > tr > td { - border-top: 1px solid #e7eaec; - line-height: 1.42857; - padding: 8px; - vertical-align: middle; -} - - -/* PANELS */ - -.panel.blank-panel { - background: none; - margin: 0; -} - -.blank-panel .panel-heading { - padding-bottom: 0; -} - -.nav-tabs > li.active > a, -.nav-tabs > li.active > a:hover, -.nav-tabs > li.active > a:focus { - -moz-border-bottom-colors: none; - -moz-border-left-colors: none; - -moz-border-right-colors: none; - -moz-border-top-colors: none; - background: none; - border-color: #dddddd #dddddd rgba(0, 0, 0, 0); - border-bottom: #f3f3f4; - -webkit-border-image: none; - -o-border-image: none; - border-image: none; - border-style: solid; - border-width: 1px; - color: #555555; - cursor: default; -} - -.nav.nav-tabs li { - background: none; - border: none; -} - -.nav-tabs > li > a { - color: #A7B1C2; - font-weight: 600; - padding: 10px 20px 10px 25px; -} - -.nav-tabs > li > a:hover, -.nav-tabs > li > a:focus { - background-color: #e6e6e6; - color: #676a6c; -} - -.ui-tab .tab-content { - padding: 20px 0px; -} - - -/* GLOBAL */ - -.no-padding { - padding: 0 !important; -} - -.no-borders { - border: none !important; -} - -.no-margins { - margin: 0 !important; -} - -.no-top-border { - border-top: 0 !important; -} - -.ibox-content.text-box { - padding-bottom: 0px; - padding-top: 15px; -} - -.border-left-right { - border-left: 1px solid #e7eaec; - border-right: 1px solid #e7eaec; - border-top: none; - border-bottom: none; -} - -.border-left { - border-left: 1px solid #e7eaec; - border-right: none; - border-top: none; - border-bottom: none; -} - -.border-right { - border-left: none; - border-right: 1px solid #e7eaec; - border-top: none; - border-bottom: none; -} - -.full-width { - width: 100% !important; -} - -.link-block { - font-size: 12px; - padding: 10px; -} - -.nav.navbar-top-links .link-block a { - font-size: 12px; -} - -.link-block a { - font-size: 10px; - color: inherit; -} - -body.mini-navbar .branding { - display: none; -} - -img.circle-border { - border: 6px solid #FFFFFF; - border-radius: 50%; -} - -.branding { - float: left; - color: #FFFFFF; - font-size: 18px; - font-weight: 600; - padding: 17px 20px; - text-align: center; - background-color: #1ab394; -} - -.login-panel { - margin-top: 25%; -} - -.page-header { - padding: 20px 0 9px; - margin: 0 0 20px; - border-bottom: 1px solid #eeeeee; -} - -.fontawesome-icon-list { - margin-top: 22px; -} - -.fontawesome-icon-list .fa-hover a { - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - display: block; - color: #222222; - line-height: 32px; - height: 32px; - padding-left: 10px; - border-radius: 4px; -} - -.fontawesome-icon-list .fa-hover a .fa { - width: 32px; - font-size: 14px; - display: inline-block; - text-align: right; - margin-right: 10px; -} - -.fontawesome-icon-list .fa-hover a:hover { - background-color: #1d9d74; - color: #ffffff; - text-decoration: none; -} - -.fontawesome-icon-list .fa-hover a:hover .fa { - font-size: 30px; - vertical-align: -6px; -} - -.fontawesome-icon-list .fa-hover a:hover .text-muted { - color: #bbe2d5; -} - -.feature-list .col-md-4 { - margin-bottom: 22px; -} - -.feature-list h4 .fa:before { - vertical-align: -10%; - font-size: 28px; - display: inline-block; - width: 1.07142857em; - text-align: center; - margin-right: 5px; -} - -.ui-draggable .ibox-title { - cursor: move; -} - -.breadcrumb { - background-color: #ffffff; - padding: 0; - margin-bottom: 0; -} - -.breadcrumb > li a { - color: inherit; -} - -.breadcrumb > .active { - color: inherit; -} - -code { - background-color: #F9F2F4; - border-radius: 4px; - color: #ca4440; - font-size: 90%; - padding: 2px 4px; - white-space: nowrap; -} - -.ibox { - clear: both; - margin-bottom: 25px; - margin-top: 0; - padding: 0; -} - -.ibox.collapsed .ibox-content { - display: none; -} - -.ibox.collapsed .fa.fa-chevron-up:before { - content: "\f078"; -} - -.ibox.collapsed .fa.fa-chevron-down:before { - content: "\f077"; -} - -.ibox:after, -.ibox:before { - display: table; -} - -.ibox-title { - -moz-border-bottom-colors: none; - -moz-border-left-colors: none; - -moz-border-right-colors: none; - -moz-border-top-colors: none; - background-color: #ffffff; - border-color: #e7eaec; - -webkit-border-image: none; - -o-border-image: none; - border-image: none; - border-style: solid solid none; - border-width: 4px 0px 0; - color: inherit; - margin-bottom: 0; - padding: 14px 15px 7px; - min-height: 48px; -} - -.ibox-content { - background-color: #ffffff; - color: inherit; - padding: 15px 20px 20px 20px; - border-color: #e7eaec; - -webkit-border-image: none; - -o-border-image: none; - border-image: none; - border-style: solid solid none; - border-width: 1px 0px; -} - -table.table-mail tr td { - padding: 12px; -} - -.table-mail .check-mail { - padding-left: 20px; -} - -.table-mail .mail-date { - padding-right: 20px; -} - -.star-mail, -.check-mail { - width: 40px; -} - -.unread td a, -.unread td { - font-weight: 600; - color: inherit; -} - -.read td a, -.read td { - font-weight: normal; - color: inherit; -} - -.unread td { - background-color: #f9f8f8; -} - -.ibox-content { - clear: both; -} - -.ibox-heading { - background-color: #f3f6fb; - border-bottom: none; -} - -.ibox-heading h3 { - font-weight: 200; - font-size: 24px; -} - -.ibox-title h5 { - display: inline-block; - font-size: 14px; - margin: 0 0 7px; - padding: 0; - text-overflow: ellipsis; - float: left; -} - -.ibox-title .label { - float: left; - margin-left: 4px; -} - -.ibox-tools { - display: inline-block; - float: right; - margin-top: 0; - position: relative; - padding: 0; -} - -.ibox-tools a { - cursor: pointer; - margin-left: 5px; - color: #c4c4c4; -} - -.ibox-tools a.btn-primary { - color: #fff; -} - -.ibox-tools .dropdown-menu > li > a { - padding: 4px 10px; - font-size: 12px; -} - -.ibox .open > .dropdown-menu { - left: auto; - right: 0; -} - - -/* BACKGROUNDS */ - -.gray-bg { - background-color: #f3f3f4; -} - -.white-bg { - background-color: #ffffff; -} - -.navy-bg { - background-color: #1ab394; - color: #ffffff; -} - -.blue-bg { - background-color: #1c84c6; - color: #ffffff; -} - -.lazur-bg { - background-color: #23c6c8; - color: #ffffff; -} - -.yellow-bg { - background-color: #f8ac59; - color: #ffffff; -} - -.red-bg { - background-color: #ed5565; - color: #ffffff; -} - -.black-bg { - background-color: #262626; -} - -.panel-primary { - border-color: #1ab394; -} - -.panel-primary > .panel-heading { - background-color: #1ab394; - border-color: #1ab394; -} - -.panel-success { - border-color: #1c84c6; -} - -.panel-success > .panel-heading { - background-color: #1c84c6; - border-color: #1c84c6; - color: #ffffff; -} - -.panel-info { - border-color: #23c6c8; -} - -.panel-info > .panel-heading { - background-color: #23c6c8; - border-color: #23c6c8; - color: #ffffff; -} - -.panel-warning { - border-color: #f8ac59; -} - -.panel-warning > .panel-heading { - background-color: #f8ac59; - border-color: #f8ac59; - color: #ffffff; -} - -.panel-danger { - border-color: #ed5565; -} - -.panel-danger > .panel-heading { - background-color: #ed5565; - border-color: #ed5565; - color: #ffffff; -} - -.progress-bar { - background-color: #1ab394; -} - -.progress-small, -.progress-small .progress-bar { - height: 10px; -} - -.progress-small, -.progress-mini { - margin-top: 5px; -} - -.progress-mini, -.progress-mini .progress-bar { - height: 5px; - margin-bottom: 0px; -} - -.progress-bar-navy-light { - background-color: #3dc7ab; -} - -.progress-bar-success { - background-color: #1c84c6; -} - -.progress-bar-info { - background-color: #23c6c8; -} - -.progress-bar-warning { - background-color: #f8ac59; -} - -.progress-bar-danger { - background-color: #ed5565; -} - -.panel-title { - font-size: inherit; -} - -.jumbotron { - border-radius: 6px; - padding: 40px; -} - -.jumbotron h1 { - margin-top: 0; -} - - -/* COLORS */ - -.text-navy { - color: #1ab394; -} - -.text-primary { - color: inherit; -} - -.text-success { - color: #1c84c6; -} - -.text-info { - color: #23c6c8; -} - -.text-warning { - color: #f8ac59; -} - -.text-danger { - color: #ed5565; -} - -.text-muted { - color: #888888; -} - -.simple_tag { - background-color: #f3f3f4; - border: 1px solid #e7eaec; - border-radius: 2px; - color: inherit; - font-size: 10px; - margin-right: 5px; - margin-top: 5px; - padding: 5px 12px; - display: inline-block; -} - -.img-shadow { - box-shadow: 0px 0px 3px 0px #919191; -} - - -/* For handle diferent bg color in AngularJS version */ - -.dashboards\.dashboard_2 nav.navbar, -.dashboards\.dashboard_3 nav.navbar, -.mailbox\.inbox nav.navbar, -.mailbox\.email_view nav.navbar, -.mailbox\.email_compose nav.navbar, -.dashboards\.dashboard_4_1 nav.navbar { - background: #fff; -} - - -/* For handle diferent bg color in MVC version */ - -.Dashboard_2 .navbar.navbar-static-top, -.Dashboard_3 .navbar.navbar-static-top, -.Dashboard_4_1 .navbar.navbar-static-top, -.ComposeEmail .navbar.navbar-static-top, -.EmailView .navbar.navbar-static-top, -.Inbox .navbar.navbar-static-top { - background: #fff; -} - -a.close-canvas-menu { - position: absolute; - top: 10px; - right: 15px; - z-index: 1011; - color: #a7b1c2; -} - -a.close-canvas-menu:hover { - color: #fff; -} - - -/* FULL HEIGHT */ - -.full-height { - height: 100%; -} - -.fh-breadcrumb { - height: calc(100% - 196px); - margin: 0 -15px; - position: relative; -} - -.fh-no-breadcrumb { - height: calc(100% - 99px); - margin: 0 -15px; - position: relative; -} - -.fh-column { - background: #fff; - height: 100%; - width: 240px; - float: left; -} - -.modal-backdrop { - z-index: 2040 !important; -} - -.modal { - z-index: 2050 !important; -} - -.spiner-example { - height: 200px; - padding-top: 70px; -} - - -/* MARGINS & PADDINGS */ - -.p-xxs { - padding: 5px; -} - -.p-xs { - padding: 10px; -} - -.p-sm { - padding: 15px; -} - -.p-m { - padding: 20px; -} - -.p-md { - padding: 25px; -} - -.p-lg { - padding: 30px; -} - -.p-xl { - padding: 40px; -} - -.m-xxs { - margin: 2px 4px; -} - -.m-xs { - margin: 5px; -} - -.m-sm { - margin: 10px; -} - -.m { - margin: 15px; -} - -.m-md { - margin: 20px; -} - -.m-lg { - margin: 30px; -} - -.m-xl { - margin: 50px; -} - -.m-n { - margin: 0 !important; -} - -.m-l-none { - margin-left: 0; -} - -.m-l-xs { - margin-left: 5px; -} - -.m-l-sm { - margin-left: 10px; -} - -.m-l { - margin-left: 15px; -} - -.m-l-md { - margin-left: 20px; -} - -.m-l-lg { - margin-left: 30px; -} - -.m-l-xl { - margin-left: 40px; -} - -.m-l-n-xxs { - margin-left: -1px; -} - -.m-l-n-xs { - margin-left: -5px; -} - -.m-l-n-sm { - margin-left: -10px; -} - -.m-l-n { - margin-left: -15px; -} - -.m-l-n-md { - margin-left: -20px; -} - -.m-l-n-lg { - margin-left: -30px; -} - -.m-l-n-xl { - margin-left: -40px; -} - -.m-t-none { - margin-top: 0; -} - -.m-t-xxs { - margin-top: 1px; -} - -.m-t-xs { - margin-top: 5px; -} - -.m-t-sm { - margin-top: 10px; -} - -.m-t { - margin-top: 15px; -} - -.m-t-md { - margin-top: 20px; -} - -.m-t-lg { - margin-top: 30px; -} - -.m-t-xl { - margin-top: 40px; -} - -.m-t-n-xxs { - margin-top: -1px; -} - -.m-t-n-xs { - margin-top: -5px; -} - -.m-t-n-sm { - margin-top: -10px; -} - -.m-t-n { - margin-top: -15px; -} - -.m-t-n-md { - margin-top: -20px; -} - -.m-t-n-lg { - margin-top: -30px; -} - -.m-t-n-xl { - margin-top: -40px; -} - -.m-r-none { - margin-right: 0; -} - -.m-r-xxs { - margin-right: 1px; -} - -.m-r-xs { - margin-right: 5px; -} - -.m-r-sm { - margin-right: 10px; -} - -.m-r { - margin-right: 15px; -} - -.m-r-md { - margin-right: 20px; -} - -.m-r-lg { - margin-right: 30px; -} - -.m-r-xl { - margin-right: 40px; -} - -.m-r-n-xxs { - margin-right: -1px; -} - -.m-r-n-xs { - margin-right: -5px; -} - -.m-r-n-sm { - margin-right: -10px; -} - -.m-r-n { - margin-right: -15px; -} - -.m-r-n-md { - margin-right: -20px; -} - -.m-r-n-lg { - margin-right: -30px; -} - -.m-r-n-xl { - margin-right: -40px; -} - -.m-b-none { - margin-bottom: 0; -} - -.m-b-xxs { - margin-bottom: 1px; -} - -.m-b-xs { - margin-bottom: 5px; -} - -.m-b-sm { - margin-bottom: 10px; -} - -.m-b { - margin-bottom: 15px; -} - -.m-b-md { - margin-bottom: 20px; -} - -.m-b-lg { - margin-bottom: 30px; -} - -.m-b-xl { - margin-bottom: 40px; -} - -.m-b-n-xxs { - margin-bottom: -1px; -} - -.m-b-n-xs { - margin-bottom: -5px; -} - -.m-b-n-sm { - margin-bottom: -10px; -} - -.m-b-n { - margin-bottom: -15px; -} - -.m-b-n-md { - margin-bottom: -20px; -} - -.m-b-n-lg { - margin-bottom: -30px; -} - -.m-b-n-xl { - margin-bottom: -40px; -} - -.space-15 { - margin: 15px 0; -} - -.space-20 { - margin: 20px 0; -} - -.space-25 { - margin: 25px 0; -} - -.space-30 { - margin: 30px 0; -} - -body.modal-open { - padding-right: inherit !important; -} - - -/* SEARCH PAGE */ - -.search-form { - margin-top: 10px; -} - -.search-result h3 { - margin-bottom: 0; - color: #1E0FBE; -} - -.search-result .search-link { - color: #006621; -} - -.search-result p { - font-size: 12px; - margin-top: 5px; -} - - -/* CONTACTS */ - -.contact-box { - background-color: #ffffff; - border: 1px solid #e7eaec; - padding: 20px; - margin-bottom: 20px; -} - -.contact-box a { - color: inherit; -} - - -/* INVOICE */ - -.invoice-table tbody > tr > td:last-child, -.invoice-table tbody > tr > td:nth-child(4), -.invoice-table tbody > tr > td:nth-child(3), -.invoice-table tbody > tr > td:nth-child(2) { - text-align: right; -} - -.invoice-table thead > tr > th:last-child, -.invoice-table thead > tr > th:nth-child(4), -.invoice-table thead > tr > th:nth-child(3), -.invoice-table thead > tr > th:nth-child(2) { - text-align: right; -} - -.invoice-total > tbody > tr > td:first-child { - text-align: right; -} - -.invoice-total > tbody > tr > td { - border: 0 none; -} - -.invoice-total > tbody > tr > td:last-child { - border-bottom: 1px solid #DDDDDD; - text-align: right; - width: 15%; -} - - -/* ERROR & LOGIN & LOCKSCREEN*/ - -.middle-box { - max-width: 400px; - z-index: 100; - margin: 0 auto; - padding-top: 40px; -} - -.lockscreen.middle-box { - width: 200px; - padding-top: 110px; -} - -.loginscreen.middle-box { - width: 300px; -} - -.loginColumns { - max-width: 800px; - margin: 0 auto; - padding: 100px 20px 20px 20px; -} - -.passwordBox { - max-width: 460px; - margin: 0 auto; - padding: 100px 20px 20px 20px; -} - -.logo-name { - color: #e6e6e6; - font-size: 180px; - font-weight: 800; - letter-spacing: -10px; - margin-bottom: 0px; -} - -.middle-box h1 { - font-size: 170px; -} - -.wrapper .middle-box { - margin-top: 140px; -} - -.lock-word { - z-index: 10; - position: absolute; - top: 110px; - left: 50%; - margin-left: -470px; -} - -.lock-word span { - font-size: 100px; - font-weight: 600; - color: #e9e9e9; - display: inline-block; -} - -.lock-word .first-word { - margin-right: 160px; -} - - -/* DASBOARD */ - -.dashboard-header { - border-top: 0; - padding: 20px 20px 20px 20px; -} - -.dashboard-header h2 { - margin-top: 10px; - font-size: 26px; -} - -.fist-item { - border-top: none !important; -} - -.statistic-box { - margin-top: 40px; -} - -.dashboard-header .list-group-item span.label { - margin-right: 10px; -} - -.list-group.clear-list .list-group-item { - border-top: 1px solid #e7eaec; - border-bottom: 0; - border-right: 0; - border-left: 0; - padding: 10px 0; -} - -ul.clear-list:first-child { - border-top: none !important; -} - - -/* Intimeline */ - -.timeline-item .date i { - position: absolute; - top: 0; - right: 0; - padding: 5px; - width: 30px; - text-align: center; - border-top: 1px solid #e7eaec; - border-bottom: 1px solid #e7eaec; - border-left: 1px solid #e7eaec; - background: #f8f8f8; -} - -.timeline-item .date { - text-align: right; - width: 110px; - position: relative; - padding-top: 30px; -} - -.timeline-item .content { - border-left: 1px solid #e7eaec; - border-top: 1px solid #e7eaec; - padding-top: 10px; - min-height: 100px; -} - -.timeline-item .content:hover { - background: #f6f6f6; -} - - -/* PIN BOARD */ - -ul.notes li, -ul.tag-list li { - list-style: none; -} - -ul.notes li h4 { - margin-top: 20px; - font-size: 16px; -} - -ul.notes li div { - text-decoration: none; - color: #000; - background: #ffc; - display: block; - height: 140px; - width: 140px; - padding: 1em; - position: relative; -} - -ul.notes li div small { - position: absolute; - top: 5px; - right: 5px; - font-size: 10px; -} - -ul.notes li div a { - position: absolute; - right: 10px; - bottom: 10px; - color: inherit; -} - -ul.notes li { - margin: 10px 40px 50px 0px; - float: left; -} - -ul.notes li div p { - font-size: 12px; -} - -ul.notes li div { - text-decoration: none; - color: #000; - background: #ffc; - display: block; - height: 140px; - width: 140px; - padding: 1em; - /* Firefox */ - /* Safari+Chrome */ - /* Opera */ - box-shadow: 5px 5px 2px rgba(33, 33, 33, 0.7); -} - -ul.notes li div { - -webkit-transform: rotate(-6deg); - -o-transform: rotate(-6deg); - -moz-transform: rotate(-6deg); -} - -ul.notes li:nth-child(even) div { - -o-transform: rotate(4deg); - -webkit-transform: rotate(4deg); - -moz-transform: rotate(4deg); - position: relative; - top: 5px; -} - -ul.notes li:nth-child(3n) div { - -o-transform: rotate(-3deg); - -webkit-transform: rotate(-3deg); - -moz-transform: rotate(-3deg); - position: relative; - top: -5px; -} - -ul.notes li:nth-child(5n) div { - -o-transform: rotate(5deg); - -webkit-transform: rotate(5deg); - -moz-transform: rotate(5deg); - position: relative; - top: -10px; -} - -ul.notes li div:hover, -ul.notes li div:focus { - -webkit-transform: scale(1.1); - -moz-transform: scale(1.1); - -o-transform: scale(1.1); - position: relative; - z-index: 5; -} - -ul.notes li div { - text-decoration: none; - color: #000; - background: #ffc; - display: block; - height: 210px; - width: 210px; - padding: 1em; - box-shadow: 5px 5px 7px rgba(33, 33, 33, 0.7); - -webkit-transition: -webkit-transform 0.15s linear; -} - - -/* FILE MANAGER */ - -.file-box { - float: left; - width: 220px; -} - -.file-manager h5 { - text-transform: uppercase; -} - -.file-manager { - list-style: none outside none; - margin: 0; - padding: 0; -} - -.folder-list li a { - color: #666666; - display: block; - padding: 5px 0; -} - -.folder-list li { - border-bottom: 1px solid #e7eaec; - display: block; -} - -.folder-list li i { - margin-right: 8px; - color: #3d4d5d; -} - -.category-list li a { - color: #666666; - display: block; - padding: 5px 0; -} - -.category-list li { - display: block; -} - -.category-list li i { - margin-right: 8px; - color: #3d4d5d; -} - -.category-list li a .text-navy { - color: #1ab394; -} - -.category-list li a .text-primary { - color: #1c84c6; -} - -.category-list li a .text-info { - color: #23c6c8; -} - -.category-list li a .text-danger { - color: #EF5352; -} - -.category-list li a .text-warning { - color: #F8AC59; -} - -.file-manager h5.tag-title { - margin-top: 20px; -} - -.tag-list li { - float: left; -} - -.tag-list li a { - font-size: 10px; - background-color: #f3f3f4; - padding: 5px 12px; - color: inherit; - border-radius: 2px; - border: 1px solid #e7eaec; - margin-right: 5px; - margin-top: 5px; - display: block; -} - -.file { - border: 1px solid #e7eaec; - padding: 0; - background-color: #ffffff; - position: relative; - margin-bottom: 20px; - margin-right: 20px; -} - -.file-manager .hr-line-dashed { - margin: 15px 0; -} - -.file .icon, -.file .image { - height: 100px; - overflow: hidden; -} - -.file .icon { - padding: 15px 10px; - text-align: center; -} - -.file-control { - color: inherit; - font-size: 11px; - margin-right: 10px; -} - -.file-control.active { - text-decoration: underline; -} - -.file .icon i { - font-size: 70px; - color: #dadada; -} - -.file .file-name { - padding: 10px; - background-color: #f8f8f8; - border-top: 1px solid #e7eaec; -} - -.file-name small { - color: #676a6c; -} - -.corner { - position: absolute; - display: inline-block; - width: 0; - height: 0; - line-height: 0; - border: 0.6em solid transparent; - border-right: 0.6em solid #f1f1f1; - border-bottom: 0.6em solid #f1f1f1; - right: 0em; - bottom: 0em; -} - -a.compose-mail { - padding: 8px 10px; -} - -.mail-search { - max-width: 300px; -} - - -/* PROFILE */ - -.profile-content { - border-top: none !important; -} - -.feed-activity-list .feed-element { - border-bottom: 1px solid #e7eaec; -} - -.feed-element:first-child { - margin-top: 0; -} - -.feed-element { - padding-bottom: 15px; -} - -.feed-element, -.feed-element .media { - margin-top: 15px; -} - -.feed-element, -.media-body { - overflow: hidden; -} - -.feed-element > .pull-left { - margin-right: 10px; -} - -.feed-element img.img-circle, -.dropdown-messages-box img.img-circle { - width: 38px; - height: 38px; -} - -.feed-element .well { - border: 1px solid #e7eaec; - box-shadow: none; - margin-top: 10px; - margin-bottom: 5px; - padding: 10px 20px; - font-size: 11px; - line-height: 16px; -} - -.feed-element .actions { - margin-top: 10px; -} - -.feed-element .photos { - margin: 10px 0; -} - -.feed-photo { - max-height: 180px; - border-radius: 4px; - overflow: hidden; - margin-right: 10px; - margin-bottom: 10px; -} - - -/* MAILBOX */ - -.mail-box { - background-color: #ffffff; - border: 1px solid #e7eaec; - border-top: 0; - padding: 0px; - margin-bottom: 20px; -} - -.mail-box-header { - background-color: #ffffff; - border: 1px solid #e7eaec; - border-bottom: 0; - padding: 30px 20px 20px 20px; -} - -.mail-box-header h2 { - margin-top: 0px; -} - -.mailbox-content .tag-list li a { - background: #ffffff; -} - -.mail-body { - border-top: 1px solid #e7eaec; - padding: 20px; -} - -.mail-text { - border-top: 1px solid #e7eaec; -} - -.mail-text .note-toolbar { - padding: 10px 15px; -} - -.mail-body .form-group { - margin-bottom: 5px; -} - -.mail-text .note-editor .note-toolbar { - background-color: #F9F8F8; -} - -.mail-attachment { - border-top: 1px solid #e7eaec; - padding: 20px; - font-size: 12px; -} - -.mailbox-content { - background: none; - border: none; - padding: 10px; -} - -.mail-ontact { - width: 23%; -} - - -/* PROJECTS */ - -.project-people, -.project-actions { - text-align: right; - vertical-align: middle; -} - -dd.project-people { - text-align: left; - margin-top: 5px; -} - -.project-people img { - width: 32px; - height: 32px; -} - -.project-title a { - font-size: 14px; - color: #676a6c; - font-weight: 600; -} - -.project-list table tr td { - border-top: none; - border-bottom: 1px solid #e7eaec; - padding: 15px 10px; - vertical-align: middle; -} - -.project-manager .tag-list li a { - font-size: 10px; - background-color: white; - padding: 5px 12px; - color: inherit; - border-radius: 2px; - border: 1px solid #e7eaec; - margin-right: 5px; - margin-top: 5px; - display: block; -} - -.project-files li a { - font-size: 11px; - color: #676a6c; - margin-left: 10px; - line-height: 22px; -} - - -/* FAQ */ - -.faq-item { - padding: 20px; - margin-bottom: 2px; - background: #fff; -} - -.faq-question { - font-size: 18px; - font-weight: 600; - color: #1ab394; - display: block; -} - -.faq-question:hover { - color: #179d82; -} - -.faq-answer { - margin-top: 10px; - background: #f3f3f4; - border: 1px solid #e7eaec; - border-radius: 3px; - padding: 15px; -} - -.faq-item .tag-item { - background: #f3f3f4; - padding: 2px 6px; - font-size: 10px; - text-transform: uppercase; -} - - -/* Chat view */ - -.message-input { - height: 90px !important; -} - -.chat-avatar { - white: 36px; - height: 36px; - float: left; - margin-right: 10px; -} - -.chat-user-name { - padding: 10px; -} - -.chat-user { - padding: 8px 10px; - border-bottom: 1px solid #e7eaec; -} - -.chat-user a { - color: inherit; -} - -.chat-view { - z-index: 20012; -} - -.chat-users, -.chat-statistic { - margin-left: -30px; -} - -@media (max-width: 992px) { - .chat-users, - .chat-statistic { - margin-left: 0px; - } -} - -.chat-view .ibox-content { - padding: 0; -} - -.chat-message { - padding: 10px 20px; -} - -.message-avatar { - height: 48px; - width: 48px; - border: 1px solid #e7eaec; - border-radius: 4px; - margin-top: 1px; -} - -.chat-discussion .chat-message:nth-child(2n+1) .message-avatar { - float: left; - margin-right: 10px; -} - -.chat-discussion .chat-message:nth-child(2n) .message-avatar { - float: right; - margin-left: 10px; -} - -.message { - background-color: #fff; - border: 1px solid #e7eaec; - text-align: left; - display: block; - padding: 10px 20px; - position: relative; - border-radius: 4px; -} - -.chat-discussion .chat-message:nth-child(2n+1) .message-date { - float: right; -} - -.chat-discussion .chat-message:nth-child(2n) .message-date { - float: left; -} - -.chat-discussion .chat-message:nth-child(2n+1) .message { - text-align: left; - margin-left: 55px; -} - -.chat-discussion .chat-message:nth-child(2n) .message { - text-align: right; - margin-right: 55px; -} - -.message-date { - font-size: 10px; - color: #888888; -} - -.message-content { - display: block; -} - -.chat-discussion { - background: #eee; - padding: 15px; - height: 400px; - overflow-y: auto; -} - -.chat-users { - overflow-y: auto; - height: 400px; -} - -.chat-message-form .form-group { - margin-bottom: 0; -} - - -/* jsTree */ - -.jstree-open > .jstree-anchor > .fa-folder:before { - content: "\f07c"; -} - -.jstree-default .jstree-icon.none { - width: 0; -} - - -/* CLIENTS */ - -.clients-list { - margin-top: 20px; -} - -.clients-list .tab-pane { - position: relative; - height: 600px; -} - -.client-detail { - position: relative; - height: 620px; -} - -.clients-list table tr td { - height: 46px; - vertical-align: middle; - border: none; -} - -.client-link { - font-weight: 600; - color: inherit; -} - -.client-link:hover { - color: inherit; -} - -.client-avatar { - width: 42px; -} - -.client-avatar img { - width: 28px; - height: 28px; - border-radius: 50%; -} - -.contact-type { - width: 20px; - color: #c1c3c4; -} - -.client-status { - text-align: left; -} - -.client-detail .vertical-timeline-content p { - margin: 0; -} - -.client-detail .vertical-timeline-icon.gray-bg { - color: #a7aaab; -} - -.clients-list .nav-tabs > li.active > a, -.clients-list .nav-tabs > li.active > a:hover, -.clients-list .nav-tabs > li.active > a:focus { - border-bottom: 1px solid #fff; -} - - -/* BLOG ARTICLE */ - -.blog h2 { - font-weight: 700; -} - -.blog h5 { - margin: 0 0 5px 0; -} - -.blog .btn { - margin: 0 0 5px 0; -} - -.article h1 { - font-size: 48px; - font-weight: 700; - color: #2F4050; -} - -.article p { - font-size: 15px; - line-height: 26px; -} - -.article-title { - text-align: center; - margin: 60px 0 40px 0; -} - -.article .ibox-content { - padding: 40px; -} - - -/* ISSUE TRACKER */ - -.issue-tracker .btn-link { - color: #1ab394; -} - -table.issue-tracker tbody tr td { - vertical-align: middle; - height: 50px; -} - -.issue-info { - width: 50%; -} - -.issue-info a { - font-weight: 600; - color: #676a6c; -} - -.issue-info small { - display: block; -} - - -/* TEAMS */ - -.team-members { - margin: 10px 0; -} - -.team-members img.img-circle { - width: 42px; - height: 42px; - margin-bottom: 5px; -} - - -/* AGILE BOARD */ - -.sortable-list { - padding: 10px 0; -} - -.agile-list { - list-style: none; - margin: 0; -} - -.agile-list li { - background: #FAFAFB; - border: 1px solid #e7eaec; - margin: 0px 0 10px 0; - padding: 10px; - border-radius: 2px; -} - -.agile-list li:hover { - cursor: pointer; - background: #fff; -} - -.agile-list li.warning-element { - border-left: 3px solid #f8ac59; -} - -.agile-list li.danger-element { - border-left: 3px solid #ed5565; -} - -.agile-list li.info-element { - border-left: 3px solid #1c84c6; -} - -.agile-list li.success-element { - border-left: 3px solid #1ab394; -} - -.agile-detail { - margin-top: 5px; - font-size: 12px; -} - - -/* DIFF */ - -ins { - background-color: #c6ffc6; - text-decoration: none; -} - -del { - background-color: #ffc6c6; -} - -#small-chat { - position: fixed; - bottom: 50px; - right: 26px; - z-index: 100; -} - -#small-chat .badge { - position: absolute; - top: -3px; - right: -4px; -} - -.open-small-chat { - height: 38px; - width: 38px; - display: block; - background: #1ab394; - padding: 9px 8px; - text-align: center; - color: #fff; - border-radius: 50%; -} - -.open-small-chat:hover { - color: white; - background: #1ab394; -} - -.small-chat-box { - display: none; - position: fixed; - bottom: 50px; - right: 80px; - background: #fff; - border: 1px solid #e7eaec; - width: 230px; - height: 320px; - border-radius: 4px; -} - -.small-chat-box.ng-small-chat { - display: block; -} - -.body-small .small-chat-box { - bottom: 70px; - right: 20px; -} - -.small-chat-box.active { - display: block; -} - -.small-chat-box .heading { - background: #2f4050; - padding: 8px 15px; - font-weight: bold; - color: #fff; -} - -.small-chat-box .chat-date { - opacity: 0.6; - font-size: 10px; - font-weight: normal; -} - -.small-chat-box .content { - padding: 15px 15px; -} - -.small-chat-box .content .author-name { - font-weight: bold; - margin-bottom: 3px; - font-size: 11px; -} - -.small-chat-box .content > div { - padding-bottom: 20px; -} - -.small-chat-box .content .chat-message { - padding: 5px 10px; - border-radius: 6px; - font-size: 11px; - line-height: 14px; - max-width: 80%; - background: #f3f3f4; - margin-bottom: 10px; -} - -.small-chat-box .content .chat-message.active { - background: #1ab394; - color: #fff; -} - -.small-chat-box .content .left { - text-align: left; - clear: both; -} - -.small-chat-box .content .left .chat-message { - float: left; -} - -.small-chat-box .content .right { - text-align: right; - clear: both; -} - -.small-chat-box .content .right .chat-message { - float: right; -} - -.small-chat-box .form-chat { - padding: 10px 10px; -} - - -/* - * Usage: - * - *

    - * - */ - -.sk-spinner-rotating-plane.sk-spinner { - width: 30px; - height: 30px; - background-color: #1ab394; - margin: 0 auto; - -webkit-animation: sk-rotatePlane 1.2s infinite ease-in-out; - animation: sk-rotatePlane 1.2s infinite ease-in-out; -} - -@-webkit-keyframes sk-rotatePlane { - 0% { - -webkit-transform: perspective(120px) rotateX(0deg) rotateY(0deg); - transform: perspective(120px) rotateX(0deg) rotateY(0deg); - } - 50% { - -webkit-transform: perspective(120px) rotateX(-180.1deg) rotateY(0deg); - transform: perspective(120px) rotateX(-180.1deg) rotateY(0deg); - } - 100% { - -webkit-transform: perspective(120px) rotateX(-180deg) rotateY(-179.9deg); - transform: perspective(120px) rotateX(-180deg) rotateY(-179.9deg); - } -} - -@keyframes sk-rotatePlane { - 0% { - -webkit-transform: perspective(120px) rotateX(0deg) rotateY(0deg); - transform: perspective(120px) rotateX(0deg) rotateY(0deg); - } - 50% { - -webkit-transform: perspective(120px) rotateX(-180.1deg) rotateY(0deg); - transform: perspective(120px) rotateX(-180.1deg) rotateY(0deg); - } - 100% { - -webkit-transform: perspective(120px) rotateX(-180deg) rotateY(-179.9deg); - transform: perspective(120px) rotateX(-180deg) rotateY(-179.9deg); - } -} - - -/* - * Usage: - * - *
    - *
    - *
    - *
    - * - */ - -.sk-spinner-double-bounce.sk-spinner { - width: 40px; - height: 40px; - position: relative; - margin: 0 auto; -} - -.sk-spinner-double-bounce .sk-double-bounce1, -.sk-spinner-double-bounce .sk-double-bounce2 { - width: 100%; - height: 100%; - border-radius: 50%; - background-color: #1ab394; - opacity: 0.6; - position: absolute; - top: 0; - left: 0; - -webkit-animation: sk-doubleBounce 2s infinite ease-in-out; - animation: sk-doubleBounce 2s infinite ease-in-out; -} - -.sk-spinner-double-bounce .sk-double-bounce2 { - -webkit-animation-delay: -1s; - animation-delay: -1s; -} - -@-webkit-keyframes sk-doubleBounce { - 0%, - 100% { - -webkit-transform: scale(0); - transform: scale(0); - } - 50% { - -webkit-transform: scale(1); - transform: scale(1); - } -} - -@keyframes sk-doubleBounce { - 0%, - 100% { - -webkit-transform: scale(0); - transform: scale(0); - } - 50% { - -webkit-transform: scale(1); - transform: scale(1); - } -} - - -/* - * Usage: - * - *
    - *
    - *
    - *
    - *
    - *
    - *
    - * - */ - -.sk-spinner-wave.sk-spinner { - margin: 0 auto; - width: 50px; - height: 30px; - text-align: center; - font-size: 10px; -} - -.sk-spinner-wave div { - background-color: #1ab394; - height: 100%; - width: 6px; - display: inline-block; - -webkit-animation: sk-waveStretchDelay 1.2s infinite ease-in-out; - animation: sk-waveStretchDelay 1.2s infinite ease-in-out; -} - -.sk-spinner-wave .sk-rect2 { - -webkit-animation-delay: -1.1s; - animation-delay: -1.1s; -} - -.sk-spinner-wave .sk-rect3 { - -webkit-animation-delay: -1s; - animation-delay: -1s; -} - -.sk-spinner-wave .sk-rect4 { - -webkit-animation-delay: -0.9s; - animation-delay: -0.9s; -} - -.sk-spinner-wave .sk-rect5 { - -webkit-animation-delay: -0.8s; - animation-delay: -0.8s; -} - -@-webkit-keyframes sk-waveStretchDelay { - 0%, - 40%, - 100% { - -webkit-transform: scaleY(0.4); - transform: scaleY(0.4); - } - 20% { - -webkit-transform: scaleY(1); - transform: scaleY(1); - } -} - -@keyframes sk-waveStretchDelay { - 0%, - 40%, - 100% { - -webkit-transform: scaleY(0.4); - transform: scaleY(0.4); - } - 20% { - -webkit-transform: scaleY(1); - transform: scaleY(1); - } -} - - -/* - * Usage: - * - *
    - *
    - *
    - *
    - * - */ - -.sk-spinner-wandering-cubes.sk-spinner { - margin: 0 auto; - width: 32px; - height: 32px; - position: relative; -} - -.sk-spinner-wandering-cubes .sk-cube1, -.sk-spinner-wandering-cubes .sk-cube2 { - background-color: #1ab394; - width: 10px; - height: 10px; - position: absolute; - top: 0; - left: 0; - -webkit-animation: sk-wanderingCubeMove 1.8s infinite ease-in-out; - animation: sk-wanderingCubeMove 1.8s infinite ease-in-out; -} - -.sk-spinner-wandering-cubes .sk-cube2 { - -webkit-animation-delay: -0.9s; - animation-delay: -0.9s; -} - -@-webkit-keyframes sk-wanderingCubeMove { - 25% { - -webkit-transform: translateX(42px) rotate(-90deg) scale(0.5); - transform: translateX(42px) rotate(-90deg) scale(0.5); - } - 50% { - /* Hack to make FF rotate in the right direction */ - -webkit-transform: translateX(42px) translateY(42px) rotate(-179deg); - transform: translateX(42px) translateY(42px) rotate(-179deg); - } - 50.1% { - -webkit-transform: translateX(42px) translateY(42px) rotate(-180deg); - transform: translateX(42px) translateY(42px) rotate(-180deg); - } - 75% { - -webkit-transform: translateX(0px) translateY(42px) rotate(-270deg) scale(0.5); - transform: translateX(0px) translateY(42px) rotate(-270deg) scale(0.5); - } - 100% { - -webkit-transform: rotate(-360deg); - transform: rotate(-360deg); - } -} - -@keyframes sk-wanderingCubeMove { - 25% { - -webkit-transform: translateX(42px) rotate(-90deg) scale(0.5); - transform: translateX(42px) rotate(-90deg) scale(0.5); - } - 50% { - /* Hack to make FF rotate in the right direction */ - -webkit-transform: translateX(42px) translateY(42px) rotate(-179deg); - transform: translateX(42px) translateY(42px) rotate(-179deg); - } - 50.1% { - -webkit-transform: translateX(42px) translateY(42px) rotate(-180deg); - transform: translateX(42px) translateY(42px) rotate(-180deg); - } - 75% { - -webkit-transform: translateX(0px) translateY(42px) rotate(-270deg) scale(0.5); - transform: translateX(0px) translateY(42px) rotate(-270deg) scale(0.5); - } - 100% { - -webkit-transform: rotate(-360deg); - transform: rotate(-360deg); - } -} - - -/* - * Usage: - * - *
    - * - */ - -.sk-spinner-pulse.sk-spinner { - width: 40px; - height: 40px; - margin: 0 auto; - background-color: #1ab394; - border-radius: 100%; - -webkit-animation: sk-pulseScaleOut 1s infinite ease-in-out; - animation: sk-pulseScaleOut 1s infinite ease-in-out; -} - -@-webkit-keyframes sk-pulseScaleOut { - 0% { - -webkit-transform: scale(0); - transform: scale(0); - } - 100% { - -webkit-transform: scale(1); - transform: scale(1); - opacity: 0; - } -} - -@keyframes sk-pulseScaleOut { - 0% { - -webkit-transform: scale(0); - transform: scale(0); - } - 100% { - -webkit-transform: scale(1); - transform: scale(1); - opacity: 0; - } -} - - -/* - * Usage: - * - *
    - *
    - *
    - *
    - * - */ - -.sk-spinner-chasing-dots.sk-spinner { - margin: 0 auto; - width: 40px; - height: 40px; - position: relative; - text-align: center; - -webkit-animation: sk-chasingDotsRotate 2s infinite linear; - animation: sk-chasingDotsRotate 2s infinite linear; -} - -.sk-spinner-chasing-dots .sk-dot1, -.sk-spinner-chasing-dots .sk-dot2 { - width: 60%; - height: 60%; - display: inline-block; - position: absolute; - top: 0; - background-color: #1ab394; - border-radius: 100%; - -webkit-animation: sk-chasingDotsBounce 2s infinite ease-in-out; - animation: sk-chasingDotsBounce 2s infinite ease-in-out; -} - -.sk-spinner-chasing-dots .sk-dot2 { - top: auto; - bottom: 0px; - -webkit-animation-delay: -1s; - animation-delay: -1s; -} - -@-webkit-keyframes sk-chasingDotsRotate { - 100% { - -webkit-transform: rotate(360deg); - transform: rotate(360deg); - } -} - -@keyframes sk-chasingDotsRotate { - 100% { - -webkit-transform: rotate(360deg); - transform: rotate(360deg); - } -} - -@-webkit-keyframes sk-chasingDotsBounce { - 0%, - 100% { - -webkit-transform: scale(0); - transform: scale(0); - } - 50% { - -webkit-transform: scale(1); - transform: scale(1); - } -} - -@keyframes sk-chasingDotsBounce { - 0%, - 100% { - -webkit-transform: scale(0); - transform: scale(0); - } - 50% { - -webkit-transform: scale(1); - transform: scale(1); - } -} - - -/* - * Usage: - * - *
    - *
    - *
    - *
    - *
    - * - */ - -.sk-spinner-three-bounce.sk-spinner { - margin: 0 auto; - width: 70px; - text-align: center; -} - -.sk-spinner-three-bounce div { - width: 18px; - height: 18px; - background-color: #1ab394; - border-radius: 100%; - display: inline-block; - -webkit-animation: sk-threeBounceDelay 1.4s infinite ease-in-out; - animation: sk-threeBounceDelay 1.4s infinite ease-in-out; - /* Prevent first frame from flickering when animation starts */ - -webkit-animation-fill-mode: both; - animation-fill-mode: both; -} - -.sk-spinner-three-bounce .sk-bounce1 { - -webkit-animation-delay: -0.32s; - animation-delay: -0.32s; -} - -.sk-spinner-three-bounce .sk-bounce2 { - -webkit-animation-delay: -0.16s; - animation-delay: -0.16s; -} - -@-webkit-keyframes sk-threeBounceDelay { - 0%, - 80%, - 100% { - -webkit-transform: scale(0); - transform: scale(0); - } - 40% { - -webkit-transform: scale(1); - transform: scale(1); - } -} - -@keyframes sk-threeBounceDelay { - 0%, - 80%, - 100% { - -webkit-transform: scale(0); - transform: scale(0); - } - 40% { - -webkit-transform: scale(1); - transform: scale(1); - } -} - - -/* - * Usage: - * - *
    - *
    - *
    - *
    - *
    - *
    - *
    - *
    - *
    - *
    - *
    - *
    - *
    - *
    - * - */ - -.sk-spinner-circle.sk-spinner { - margin: 0 auto; - width: 22px; - height: 22px; - position: relative; -} - -.sk-spinner-circle .sk-circle { - width: 100%; - height: 100%; - position: absolute; - left: 0; - top: 0; -} - -.sk-spinner-circle .sk-circle:before { - content: ''; - display: block; - margin: 0 auto; - width: 20%; - height: 20%; - background-color: #1ab394; - border-radius: 100%; - -webkit-animation: sk-circleBounceDelay 1.2s infinite ease-in-out; - animation: sk-circleBounceDelay 1.2s infinite ease-in-out; - /* Prevent first frame from flickering when animation starts */ - -webkit-animation-fill-mode: both; - animation-fill-mode: both; -} - -.sk-spinner-circle .sk-circle2 { - -webkit-transform: rotate(30deg); - -ms-transform: rotate(30deg); - transform: rotate(30deg); -} - -.sk-spinner-circle .sk-circle3 { - -webkit-transform: rotate(60deg); - -ms-transform: rotate(60deg); - transform: rotate(60deg); -} - -.sk-spinner-circle .sk-circle4 { - -webkit-transform: rotate(90deg); - -ms-transform: rotate(90deg); - transform: rotate(90deg); -} - -.sk-spinner-circle .sk-circle5 { - -webkit-transform: rotate(120deg); - -ms-transform: rotate(120deg); - transform: rotate(120deg); -} - -.sk-spinner-circle .sk-circle6 { - -webkit-transform: rotate(150deg); - -ms-transform: rotate(150deg); - transform: rotate(150deg); -} - -.sk-spinner-circle .sk-circle7 { - -webkit-transform: rotate(180deg); - -ms-transform: rotate(180deg); - transform: rotate(180deg); -} - -.sk-spinner-circle .sk-circle8 { - -webkit-transform: rotate(210deg); - -ms-transform: rotate(210deg); - transform: rotate(210deg); -} - -.sk-spinner-circle .sk-circle9 { - -webkit-transform: rotate(240deg); - -ms-transform: rotate(240deg); - transform: rotate(240deg); -} - -.sk-spinner-circle .sk-circle10 { - -webkit-transform: rotate(270deg); - -ms-transform: rotate(270deg); - transform: rotate(270deg); -} - -.sk-spinner-circle .sk-circle11 { - -webkit-transform: rotate(300deg); - -ms-transform: rotate(300deg); - transform: rotate(300deg); -} - -.sk-spinner-circle .sk-circle12 { - -webkit-transform: rotate(330deg); - -ms-transform: rotate(330deg); - transform: rotate(330deg); -} - -.sk-spinner-circle .sk-circle2:before { - -webkit-animation-delay: -1.1s; - animation-delay: -1.1s; -} - -.sk-spinner-circle .sk-circle3:before { - -webkit-animation-delay: -1s; - animation-delay: -1s; -} - -.sk-spinner-circle .sk-circle4:before { - -webkit-animation-delay: -0.9s; - animation-delay: -0.9s; -} - -.sk-spinner-circle .sk-circle5:before { - -webkit-animation-delay: -0.8s; - animation-delay: -0.8s; -} - -.sk-spinner-circle .sk-circle6:before { - -webkit-animation-delay: -0.7s; - animation-delay: -0.7s; -} - -.sk-spinner-circle .sk-circle7:before { - -webkit-animation-delay: -0.6s; - animation-delay: -0.6s; -} - -.sk-spinner-circle .sk-circle8:before { - -webkit-animation-delay: -0.5s; - animation-delay: -0.5s; -} - -.sk-spinner-circle .sk-circle9:before { - -webkit-animation-delay: -0.4s; - animation-delay: -0.4s; -} - -.sk-spinner-circle .sk-circle10:before { - -webkit-animation-delay: -0.3s; - animation-delay: -0.3s; -} - -.sk-spinner-circle .sk-circle11:before { - -webkit-animation-delay: -0.2s; - animation-delay: -0.2s; -} - -.sk-spinner-circle .sk-circle12:before { - -webkit-animation-delay: -0.1s; - animation-delay: -0.1s; -} - -@-webkit-keyframes sk-circleBounceDelay { - 0%, - 80%, - 100% { - -webkit-transform: scale(0); - transform: scale(0); - } - 40% { - -webkit-transform: scale(1); - transform: scale(1); - } -} - -@keyframes sk-circleBounceDelay { - 0%, - 80%, - 100% { - -webkit-transform: scale(0); - transform: scale(0); - } - 40% { - -webkit-transform: scale(1); - transform: scale(1); - } -} - - -/* - * Usage: - * - *
    - *
    - *
    - *
    - *
    - *
    - *
    - *
    - *
    - *
    - *
    - * - */ - -.sk-spinner-cube-grid { - /* - * Spinner positions - * 1 2 3 - * 4 5 6 - * 7 8 9 - */ -} - -.sk-spinner-cube-grid.sk-spinner { - width: 30px; - height: 30px; - margin: 0 auto; -} - -.sk-spinner-cube-grid .sk-cube { - width: 33%; - height: 33%; - background-color: #1ab394; - float: left; - -webkit-animation: sk-cubeGridScaleDelay 1.3s infinite ease-in-out; - animation: sk-cubeGridScaleDelay 1.3s infinite ease-in-out; -} - -.sk-spinner-cube-grid .sk-cube:nth-child(1) { - -webkit-animation-delay: 0.2s; - animation-delay: 0.2s; -} - -.sk-spinner-cube-grid .sk-cube:nth-child(2) { - -webkit-animation-delay: 0.3s; - animation-delay: 0.3s; -} - -.sk-spinner-cube-grid .sk-cube:nth-child(3) { - -webkit-animation-delay: 0.4s; - animation-delay: 0.4s; -} - -.sk-spinner-cube-grid .sk-cube:nth-child(4) { - -webkit-animation-delay: 0.1s; - animation-delay: 0.1s; -} - -.sk-spinner-cube-grid .sk-cube:nth-child(5) { - -webkit-animation-delay: 0.2s; - animation-delay: 0.2s; -} - -.sk-spinner-cube-grid .sk-cube:nth-child(6) { - -webkit-animation-delay: 0.3s; - animation-delay: 0.3s; -} - -.sk-spinner-cube-grid .sk-cube:nth-child(7) { - -webkit-animation-delay: 0s; - animation-delay: 0s; -} - -.sk-spinner-cube-grid .sk-cube:nth-child(8) { - -webkit-animation-delay: 0.1s; - animation-delay: 0.1s; -} - -.sk-spinner-cube-grid .sk-cube:nth-child(9) { - -webkit-animation-delay: 0.2s; - animation-delay: 0.2s; -} - -@-webkit-keyframes sk-cubeGridScaleDelay { - 0%, - 70%, - 100% { - -webkit-transform: scale3D(1, 1, 1); - transform: scale3D(1, 1, 1); - } - 35% { - -webkit-transform: scale3D(0, 0, 1); - transform: scale3D(0, 0, 1); - } -} - -@keyframes sk-cubeGridScaleDelay { - 0%, - 70%, - 100% { - -webkit-transform: scale3D(1, 1, 1); - transform: scale3D(1, 1, 1); - } - 35% { - -webkit-transform: scale3D(0, 0, 1); - transform: scale3D(0, 0, 1); - } -} - - -/* - * Usage: - * - *
    - * - *
    - * - */ - -.sk-spinner-wordpress.sk-spinner { - background-color: #1ab394; - width: 30px; - height: 30px; - border-radius: 30px; - position: relative; - margin: 0 auto; - -webkit-animation: sk-innerCircle 1s linear infinite; - animation: sk-innerCircle 1s linear infinite; -} - -.sk-spinner-wordpress .sk-inner-circle { - display: block; - background-color: #fff; - width: 8px; - height: 8px; - position: absolute; - border-radius: 8px; - top: 5px; - left: 5px; -} - -@-webkit-keyframes sk-innerCircle { - 0% { - -webkit-transform: rotate(0); - transform: rotate(0); - } - 100% { - -webkit-transform: rotate(360deg); - transform: rotate(360deg); - } -} - -@keyframes sk-innerCircle { - 0% { - -webkit-transform: rotate(0); - transform: rotate(0); - } - 100% { - -webkit-transform: rotate(360deg); - transform: rotate(360deg); - } -} - - -/* - * Usage: - * - *
    - *
    - *
    - *
    - *
    - *
    - *
    - *
    - *
    - *
    - *
    - *
    - *
    - *
    - * - */ - -.sk-spinner-fading-circle.sk-spinner { - margin: 0 auto; - width: 22px; - height: 22px; - position: relative; -} - -.sk-spinner-fading-circle .sk-circle { - width: 100%; - height: 100%; - position: absolute; - left: 0; - top: 0; -} - -.sk-spinner-fading-circle .sk-circle:before { - content: ''; - display: block; - margin: 0 auto; - width: 18%; - height: 18%; - background-color: #1ab394; - border-radius: 100%; - -webkit-animation: sk-circleFadeDelay 1.2s infinite ease-in-out; - animation: sk-circleFadeDelay 1.2s infinite ease-in-out; - /* Prevent first frame from flickering when animation starts */ - -webkit-animation-fill-mode: both; - animation-fill-mode: both; -} - -.sk-spinner-fading-circle .sk-circle2 { - -webkit-transform: rotate(30deg); - -ms-transform: rotate(30deg); - transform: rotate(30deg); -} - -.sk-spinner-fading-circle .sk-circle3 { - -webkit-transform: rotate(60deg); - -ms-transform: rotate(60deg); - transform: rotate(60deg); -} - -.sk-spinner-fading-circle .sk-circle4 { - -webkit-transform: rotate(90deg); - -ms-transform: rotate(90deg); - transform: rotate(90deg); -} - -.sk-spinner-fading-circle .sk-circle5 { - -webkit-transform: rotate(120deg); - -ms-transform: rotate(120deg); - transform: rotate(120deg); -} - -.sk-spinner-fading-circle .sk-circle6 { - -webkit-transform: rotate(150deg); - -ms-transform: rotate(150deg); - transform: rotate(150deg); -} - -.sk-spinner-fading-circle .sk-circle7 { - -webkit-transform: rotate(180deg); - -ms-transform: rotate(180deg); - transform: rotate(180deg); -} - -.sk-spinner-fading-circle .sk-circle8 { - -webkit-transform: rotate(210deg); - -ms-transform: rotate(210deg); - transform: rotate(210deg); -} - -.sk-spinner-fading-circle .sk-circle9 { - -webkit-transform: rotate(240deg); - -ms-transform: rotate(240deg); - transform: rotate(240deg); -} - -.sk-spinner-fading-circle .sk-circle10 { - -webkit-transform: rotate(270deg); - -ms-transform: rotate(270deg); - transform: rotate(270deg); -} - -.sk-spinner-fading-circle .sk-circle11 { - -webkit-transform: rotate(300deg); - -ms-transform: rotate(300deg); - transform: rotate(300deg); -} - -.sk-spinner-fading-circle .sk-circle12 { - -webkit-transform: rotate(330deg); - -ms-transform: rotate(330deg); - transform: rotate(330deg); -} - -.sk-spinner-fading-circle .sk-circle2:before { - -webkit-animation-delay: -1.1s; - animation-delay: -1.1s; -} - -.sk-spinner-fading-circle .sk-circle3:before { - -webkit-animation-delay: -1s; - animation-delay: -1s; -} - -.sk-spinner-fading-circle .sk-circle4:before { - -webkit-animation-delay: -0.9s; - animation-delay: -0.9s; -} - -.sk-spinner-fading-circle .sk-circle5:before { - -webkit-animation-delay: -0.8s; - animation-delay: -0.8s; -} - -.sk-spinner-fading-circle .sk-circle6:before { - -webkit-animation-delay: -0.7s; - animation-delay: -0.7s; -} - -.sk-spinner-fading-circle .sk-circle7:before { - -webkit-animation-delay: -0.6s; - animation-delay: -0.6s; -} - -.sk-spinner-fading-circle .sk-circle8:before { - -webkit-animation-delay: -0.5s; - animation-delay: -0.5s; -} - -.sk-spinner-fading-circle .sk-circle9:before { - -webkit-animation-delay: -0.4s; - animation-delay: -0.4s; -} - -.sk-spinner-fading-circle .sk-circle10:before { - -webkit-animation-delay: -0.3s; - animation-delay: -0.3s; -} - -.sk-spinner-fading-circle .sk-circle11:before { - -webkit-animation-delay: -0.2s; - animation-delay: -0.2s; -} - -.sk-spinner-fading-circle .sk-circle12:before { - -webkit-animation-delay: -0.1s; - animation-delay: -0.1s; -} - -@-webkit-keyframes sk-circleFadeDelay { - 0%, - 39%, - 100% { - opacity: 0; - } - 40% { - opacity: 1; - } -} - -@keyframes sk-circleFadeDelay { - 0%, - 39%, - 100% { - opacity: 0; - } - 40% { - opacity: 1; - } -} - -body.rtls { - /* Theme config */ -} - -body.rtls #page-wrapper { - margin: 0 220px 0 0; -} - -body.rtls .nav-second-level li a { - padding: 7px 35px 7px 10px; -} - -body.rtls .ibox-title h5 { - float: right; -} - -body.rtls .pull-right { - float: left !important; -} - -body.rtls .pull-left { - float: right !important; -} - -body.rtls .ibox-tools { - float: left; -} - -body.rtls .stat-percent { - float: left; -} - -body.rtls .navbar-right { - float: left !important; -} - -body.rtls .navbar-top-links li:last-child { - margin-left: 40px; - margin-right: 0; -} - -body.rtls .minimalize-styl-2 { - float: right; - margin: 14px 20px 5px 5px; -} - -body.rtls .feed-element > .pull-left { - margin-left: 10px; - margin-right: 0; -} - -body.rtls .timeline-item .date { - text-align: left; -} - -body.rtls .timeline-item .date i { - left: 0; - right: auto; -} - -body.rtls .timeline-item .content { - border-right: 1px solid #e7eaec; - border-left: none; -} - -body.rtls .toast-close-button { - float: left; -} - -body.rtls #toast-container > .toast:before { - margin: auto -1.5em auto 0.5em; -} - -body.rtls #toast-container > div { - padding: 15px 50px 15px 15px; -} - -body.rtls .center-orientation .vertical-timeline-icon i { - margin-left: 0; - margin-right: -12px; -} - -body.rtls .vertical-timeline-icon i { - right: 50%; - left: auto; - margin-left: auto; - margin-right: -12px; -} - -body.rtls .file-box { - float: right; -} - -body.rtls ul.notes li { - float: right; -} - -body.rtls .chat-users, -body.rtls .chat-statistic { - margin-right: -30px; - margin-left: auto; -} - -body.rtls .dropdown-menu > li > a { - text-align: right; -} - -body.rtls .b-r { - border-left: 1px solid #e7eaec; - border-right: none; -} - -body.rtls .dd-list .dd-list { - padding-right: 30px; - padding-left: 0; -} - -body.rtls .dd-item > button { - float: right; -} - -body.rtls .skin-setttings { - margin-right: 40px; - margin-left: 0; -} - -body.rtls .skin-setttings { - direction: ltr; -} - -body.rtls .footer.fixed { - margin-right: 220px; - margin-left: 0; -} - -@media (max-width: 992px) { - body.rtls .chat-users, - body.rtls .chat-statistic { - margin-right: 0px; - } -} - -body.rtls.mini-navbar .footer.fixed, -body.body-small.mini-navbar .footer.fixed { - margin: 0 70px 0 0; -} - -body.rtls.mini-navbar.fixed-sidebar .footer.fixed, -body.body-small.mini-navbar .footer.fixed { - margin: 0 0 0 0; -} - -body.rtls.top-navigation .navbar-toggle { - float: right; - margin-left: 15px; - margin-right: 15px; -} - -.body-small.rtls.top-navigation .navbar-header { - float: none; -} - -body.rtls.top-navigation #page-wrapper { - margin: 0; -} - -body.rtls.mini-navbar #page-wrapper { - margin: 0 70px 0 0; -} - -body.rtls.mini-navbar.fixed-sidebar #page-wrapper { - margin: 0 0 0 0; -} - -body.rtls.body-small.fixed-sidebar.mini-navbar #page-wrapper { - margin: 0 220px 0 0; -} - -body.rtls.body-small.fixed-sidebar.mini-navbar .navbar-static-side { - width: 220px; -} - -.body-small.rtls .navbar-fixed-top { - margin-right: 0px; -} - -.body-small.rtls .navbar-header { - float: right; -} - -body.rtls .navbar-top-links li:last-child { - margin-left: 20px; -} - -body.rtls .top-navigation #page-wrapper, -body.rtls.mini-navbar .top-navigation #page-wrapper, -body.rtls.mini-navbar.top-navigation #page-wrapper { - margin: 0; -} - -body.rtls .top-navigation .footer.fixed, -body.rtls.top-navigation .footer.fixed { - margin: 0; -} - -@media (max-width: 768px) { - body.rtls .navbar-top-links li:last-child { - margin-left: 20px; - } - .body-small.rtls #page-wrapper { - position: inherit; - margin: 0 0 0 0px; - min-height: 1000px; - } - .body-small.rtls .navbar-static-side { - display: none; - z-index: 2001; - position: absolute; - width: 70px; - } - .body-small.rtls.mini-navbar .navbar-static-side { - display: block; - } - .rtls.fixed-sidebar.body-small .navbar-static-side { - display: none; - z-index: 2001; - position: fixed; - width: 220px; - } - .rtls.fixed-sidebar.body-small.mini-navbar .navbar-static-side { - display: block; - } -} - -.rtls .ltr-support { - direction: ltr; -} - - -/* - * - * This is style for skin config - * Use only in demo theme - * -*/ - -.skin-setttings .title { - background: #efefef; - text-align: center; - text-transform: uppercase; - font-weight: 600; - display: block; - padding: 10px 15px; - font-size: 12px; -} - -.setings-item { - padding: 10px 30px; -} - -.setings-item.nb { - border: none; -} - -.setings-item.skin { - text-align: center; -} - -.setings-item .switch { - float: right; -} - -.skin-name a { - text-transform: uppercase; -} - -.setings-item a { - color: #fff; -} - -.default-skin, -.blue-skin, -.ultra-skin, -.yellow-skin { - text-align: center; -} - -.default-skin { - font-weight: 600; - background: #1ab394; -} - -.default-skin:hover { - background: #199d82; -} - -.blue-skin { - font-weight: 600; - background: url("patterns/header-profile-skin-1.png") repeat scroll 0 0; -} - -.blue-skin:hover { - background: #0d8ddb; -} - -.yellow-skin { - font-weight: 600; - background: url("patterns/header-profile-skin-3.png") repeat scroll 0 100%; -} - -.yellow-skin:hover { - background: #ce8735; -} - -.content-tabs { - border-bottom: solid 2px #2f4050; -} - -.page-tabs a { - color: #999; -} - -.page-tabs a i { - color: #ccc; -} - -.page-tabs a.active { - background: #2f4050; - color: #a7b1c2; -} - -.page-tabs a.active:hover, -.page-tabs a.active i:hover { - background: #293846; - color: #fff; -} - - -/* - * - * SKIN 1 - H+ - 后台主题UI框架 - * NAME - Blue light - * -*/ - -.skin-1 .minimalize-styl-2 { - margin: 14px 5px 5px 30px; -} - -.skin-1 .navbar-top-links li:last-child { - margin-right: 30px; -} - -.skin-1.fixed-nav .minimalize-styl-2 { - margin: 14px 5px 5px 15px; -} - -.skin-1 .spin-icon { - background: #0e9aef !important; -} - -.skin-1 .nav-header { - background: #0e9aef; - background: url('patterns/header-profile-skin-1.png'); -} - -.skin-1.mini-navbar .nav-second-level { - background: #3e495f; -} - -.skin-1 .breadcrumb { - background: transparent; -} - -.skin-1 .page-heading { - border: none; -} - -.skin-1 .nav > li.active { - background: #3a4459; -} - -.skin-1 .nav > li > a { - color: #9ea6b9; -} - -.skin-1 .nav > li.active > a { - color: #fff; -} - -.skin-1 .navbar-minimalize { - background: #0e9aef; - border-color: #0e9aef; -} - -body.skin-1 { - background: #3e495f; -} - -.skin-1 .navbar-static-top { - background: #ffffff; -} - -.skin-1 .dashboard-header { - background: transparent; - border-bottom: none !important; - border-top: none; - padding: 20px 30px 10px 30px; -} - -.fixed-nav.skin-1 .navbar-fixed-top { - background: #fff; -} - -.skin-1 .wrapper-content { - padding: 30px 15px; -} - -.skin-1 #page-wrapper { - background: #f4f6fa; -} - -.skin-1 .ibox-title, -.skin-1 .ibox-content { - border-width: 1px; -} - -.skin-1 .ibox-content:last-child { - border-style: solid solid solid solid; -} - -.skin-1 .nav > li.active { - border: none; -} - -.skin-1 .nav-header { - padding: 35px 25px 25px 25px; -} - -.skin-1 .nav-header a.dropdown-toggle { - color: #fff; - margin-top: 10px; -} - -.skin-1 .nav-header a.dropdown-toggle .text-muted { - color: #fff; - opacity: 0.8; -} - -.skin-1 .profile-element { - text-align: center; -} - -.skin-1 .img-circle { - border-radius: 5px; -} - -.skin-1 .navbar-default .nav > li > a:hover, -.skin-1 .navbar-default .nav > li > a:focus { - background: #39aef5; - color: #fff; -} - -.skin-1 .nav.nav-tabs > li.active > a { - color: #555; -} - -.skin-1 .content-tabs { - border-bottom: solid 2px #39aef5; -} - -.skin-1 .nav.nav-tabs > li.active { - background: transparent; -} - -.skin-1 .page-tabs a.active { - background: #39aef5; - color: #fff; -} - -.skin-1 .page-tabs a.active:hover, -.skin-1 .page-tabs a.active i:hover { - background: #0e9aef; - color: #fff; -} - - -/* - * - * SKIN 3 - H+ - 后台主题UI框架 - * NAME - Yellow/purple - * -*/ - -.skin-3 .minimalize-styl-2 { - margin: 14px 5px 5px 30px; -} - -.skin-3 .navbar-top-links li:last-child { - margin-right: 30px; -} - -.skin-3.fixed-nav .minimalize-styl-2 { - margin: 14px 5px 5px 15px; -} - -.skin-3 .spin-icon { - background: #ecba52 !important; -} - -body.boxed-layout.skin-3 #wrapper { - background: #3e2c42; -} - -.skin-3 .nav-header { - background: #ecba52; - background: url('patterns/header-profile-skin-3.png'); -} - -.skin-3.mini-navbar .nav-second-level { - background: #3e2c42; -} - -.skin-3 .breadcrumb { - background: transparent; -} - -.skin-3 .page-heading { - border: none; -} - -.skin-3 .nav > li.active { - background: #38283c; -} - -.fixed-nav.skin-3 .navbar-fixed-top { - background: #fff; -} - -.skin-3 .nav > li > a { - color: #948b96; -} - -.skin-3 .nav > li.active > a { - color: #fff; -} - -.skin-3 .navbar-minimalize { - background: #ecba52; - border-color: #ecba52; -} - -body.skin-3 { - background: #3e2c42; -} - -.skin-3 .navbar-static-top { - background: #ffffff; -} - -.skin-3 .dashboard-header { - background: transparent; - border-bottom: none !important; - border-top: none; - padding: 20px 30px 10px 30px; -} - -.skin-3 .wrapper-content { - padding: 30px 15px; -} - -.skin-3 #page-wrapper { - background: #f4f6fa; -} - -.skin-3 .ibox-title, -.skin-3 .ibox-content { - border-width: 1px; -} - -.skin-3 .ibox-content:last-child { - border-style: solid solid solid solid; -} - -.skin-3 .nav > li.active { - border: none; -} - -.skin-3 .nav-header { - padding: 35px 25px 25px 25px; -} - -.skin-3 .nav-header a.dropdown-toggle { - color: #fff; - margin-top: 10px; -} - -.skin-3 .nav-header a.dropdown-toggle .text-muted { - color: #fff; - opacity: 0.8; -} - -.skin-3 .profile-element { - text-align: center; -} - -.skin-3 .img-circle { - border-radius: 5px; -} - -.skin-3 .navbar-default .nav > li > a:hover, -.skin-3 .navbar-default .nav > li > a:focus { - background: #38283c; - color: #fff; -} - -.skin-3 .nav.nav-tabs > li.active > a { - color: #555; -} - -.skin-3 .nav.nav-tabs > li.active { - background: transparent; -} - -.skin-3 .content-tabs { - border-bottom: solid 2px #3e2c42; -} - -.skin-3 .nav.nav-tabs > li.active { - background: transparent; -} - -.skin-3 .page-tabs a.active { - background: #3e2c42; - color: #fff; -} - -.skin-3 .page-tabs a.active:hover, -.skin-3 .page-tabs a.active i:hover { - background: #38283c; - color: #fff; -} - -@media (min-width: 768px) { - .navbar-top-links .dropdown-messages, - .navbar-top-links .dropdown-tasks, - .navbar-top-links .dropdown-alerts { - margin-left: auto; - } -} - -@media (max-width: 768px) { - body.fixed-sidebar .navbar-static-side { - display: none; - } - body.fixed-sidebar.mini-navbar .navbar-static-side { - width: 70px; - } - .lock-word { - display: none; - } - .navbar-form-custom { - display: none; - } - .navbar-header { - display: inline; - float: left; - } - .sidebard-panel { - z-index: 2; - position: relative; - width: auto; - min-height: 100% !important; - } - .sidebar-content .wrapper { - padding-right: 0px; - z-index: 1; - } - .fixed-sidebar.body-small .navbar-static-side { - display: none; - z-index: 2001; - position: fixed; - width: 220px; - } - .fixed-sidebar.body-small.mini-navbar .navbar-static-side { - display: block; - } - .ibox-tools { - float: none; - text-align: right; - display: block; - } - .content-tabs { - display: none; - } - #content-main { - height: calc(100% - 100px); - } - .fixed-nav #content-main { - height: calc(100% - 38px); - } -} - -.navbar-static-side { - background: #2f4050; -} - -.nav-close { - padding: 10px; - display: block; - position: absolute; - right: 5px; - top: 5px; - font-size: 1.4em; - cursor: pointer; - z-index: 10; - display: none; - color: rgba(255, 255, 255, .3); -} - -@media (max-width: 350px) { - body.fixed-sidebar.mini-navbar .navbar-static-side { - width: 0; - } - .nav-close { - display: block; - } - #page-wrapper { - margin-left: 0!important; - } - .timeline-item .date { - text-align: left; - width: 110px; - position: relative; - padding-top: 30px; - } - .timeline-item .date i { - position: absolute; - top: 0; - left: 15px; - padding: 5px; - width: 30px; - text-align: center; - border: 1px solid #e7eaec; - background: #f8f8f8; - } - .timeline-item .content { - border-left: none; - border-top: 1px solid #e7eaec; - padding-top: 10px; - min-height: 100px; - } - .nav.navbar-top-links li.dropdown { - display: none; - } - .ibox-tools { - float: none; - text-align: left; - display: inline-block; - } -} - - -/*JQGRID*/ - -.ui-jqgrid-titlebar { - height: 40px; - line-height: 24px; - color: #676a6c; - background-color: #F9F9F9; - text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); -} - -.ui-jqgrid .ui-jqgrid-title { - float: left; - margin-left: 5px; - font-weight: 700; -} - -.ui-jqgrid .ui-jqgrid-titlebar { - position: relative; - border-left: 0px solid; - border-right: 0px solid; - border-top: 0px solid; -} - - -/* Social feed */ - -.social-feed-separated .social-feed-box { - margin-left: 62px; -} - -.social-feed-separated .social-avatar { - float: left; - padding: 0; -} - -.social-feed-separated .social-avatar img { - width: 52px; - height: 52px; - border: 1px solid #e7eaec; -} - -.social-feed-separated .social-feed-box .social-avatar { - padding: 15px 15px 0 15px; - float: none; -} - -.social-feed-box { - /*padding: 15px;*/ - border: 1px solid #e7eaec; - background: #fff; - margin-bottom: 15px; -} - -.article .social-feed-box { - margin-bottom: 0; - border-bottom: none; -} - -.article .social-feed-box:last-child { - margin-bottom: 0; - border-bottom: 1px solid #e7eaec; -} - -.article .social-feed-box p { - font-size: 13px; - line-height: 18px; -} - -.social-action { - margin: 15px; -} - -.social-avatar { - padding: 15px 15px 0 15px; -} - -.social-comment .social-comment { - margin-left: 45px; -} - -.social-avatar img { - height: 40px; - width: 40px; - margin-right: 10px; -} - -.social-avatar .media-body a { - font-size: 14px; - display: block; -} - -.social-body { - padding: 15px; -} - -.social-body img { - margin-bottom: 10px; -} - -.social-footer { - border-top: 1px solid #e7eaec; - padding: 10px 15px; - background: #f9f9f9; -} - -.social-footer .social-comment img { - width: 32px; - margin-right: 10px; -} - -.social-comment:first-child { - margin-top: 0; -} - -.social-comment { - margin-top: 15px; -} - -.social-comment textarea { - font-size: 12px; -} - -.checkbox input[type=checkbox], -.checkbox-inline input[type=checkbox], -.radio input[type=radio], -.radio-inline input[type=radio] { - margin-top: -4px; -} - - -/* Only demo */ - -@media (max-width: 1000px) { - .welcome-message { - display: none; - } -} - - -/* ECHARTS */ - -.echarts { - height: 240px; -} - -.checkbox-inline, -.radio-inline, -.checkbox-inline+.checkbox-inline, -.radio-inline+.radio-inline { - margin: 0 15px 0 0; -} - -.navbar-toggle { - background-color: #fff; -} - -.J_menuTab { - -webkit-transition: all .3s ease-out 0s; - transition: all .3s ease-out 0s; -} - -::-webkit-scrollbar-track { - background-color: #F5F5F5; -} - -::-webkit-scrollbar { - width: 6px; - background-color: #F5F5F5; -} - -::-webkit-scrollbar-thumb { - background-color: #999; -} - - -/*GO HOME*/ - -.gohome { - position: fixed; - top: 20px; - right: 20px; - z-index: 100; -} - -.gohome a { - height: 38px; - width: 38px; - display: block; - background: #2f4050; - padding: 9px 8px; - text-align: center; - color: #fff; - border-radius: 50%; - opacity: .5; -} - -.gohome a:hover { - opacity: 1; -} - -@media only screen and (-webkit-min-device-pixel-ratio : 2){ - #content-main { - -webkit-overflow-scrolling: touch; - } -} - -.navbar-header { - width: 60%; -} - -.bs-glyphicons { - margin: 0 -10px 20px; - overflow: hidden -} - -.bs-glyphicons-list { - padding-left: 0; - list-style: none -} - -.bs-glyphicons li { - float: left; - width: 25%; - height: 115px; - padding: 10px; - font-size: 10px; - line-height: 1.4; - text-align: center; - background-color: #f9f9f9; - border: 1px solid #fff -} - -.bs-glyphicons .glyphicon { - margin-top: 5px; - margin-bottom: 10px; - font-size: 24px -} - -.bs-glyphicons .glyphicon-class { - display: block; - text-align: center; - word-wrap: break-word -} - -.bs-glyphicons li:hover { - color: #fff; - background-color: #1ab394; -} - -@media (min-width: 768px) { - .bs-glyphicons { - margin-right: 0; - margin-left: 0 - } - .bs-glyphicons li { - width: 12.5%; - font-size: 12px - } -} -.table tr td { - word-break: break-all; - word-wrap: break-word; -} -.Validform_checktip{ - margin-left:8px; - line-height:20px; - height:20px; - display: inline-block; - color:#999; - font-size:12px; -} -.Validform_right{ - color:#71b83d; - padding-left:20px; - background:url(../img/right.png) no-repeat left center; -} -.Validform_wrong{ - color:red; - padding-left:20px; - white-space:nowrap; - background:url(../img/error.png) no-repeat left center; -} -.Validform_loading{ - padding-left:20px; - background:url(../img/onLoad.gif) no-repeat left center; -} -.Validform_error{ - background-color:#ffe7e7; -} -#Validform_msg{color:#7d8289; font: 12px/1.5 tahoma, arial, \5b8b\4f53, sans-serif; width:280px; -webkit-box-shadow:2px 2px 3px #aaa; -moz-box-shadow:2px 2px 3px #aaa; background:#fff; position:absolute; top:0px; right:50px; z-index:99999; display:none;filter: progid:DXImageTransform.Microsoft.Shadow(Strength=3, Direction=135, Color='#999999');} -#Validform_msg .iframe{position:absolute; left:0px; top:-1px; z-index:-1;} -#Validform_msg .Validform_title{line-height:25px; height:25px; text-align:left; font-weight:bold; padding:0 8px; color:#fff; position:relative; background-color:#000;} -#Validform_msg a.Validform_close:link,#Validform_msg a.Validform_close:visited{line-height:22px; position:absolute; right:8px; top:0px; color:#fff; text-decoration:none;} -#Validform_msg a.Validform_close:hover{color:#cc0;} -#Validform_msg .Validform_info{padding:8px;border:1px solid #000; border-top:none; text-align:left;} \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/img/bgblack.png b/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/img/bgblack.png deleted file mode 100644 index 83776557fe..0000000000 Binary files a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/img/bgblack.png and /dev/null differ diff --git a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/img/check_alt.png b/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/img/check_alt.png deleted file mode 100644 index 5be78b49af..0000000000 Binary files a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/img/check_alt.png and /dev/null differ diff --git a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/img/error.png b/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/img/error.png deleted file mode 100644 index aeff2a4381..0000000000 Binary files a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/img/error.png and /dev/null differ diff --git a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/img/error/404.png b/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/img/error/404.png deleted file mode 100644 index 600d6d8f5f..0000000000 Binary files a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/img/error/404.png and /dev/null differ diff --git a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/img/error/404_msg.png b/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/img/error/404_msg.png deleted file mode 100644 index ffc72d4c77..0000000000 Binary files a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/img/error/404_msg.png and /dev/null differ diff --git a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/img/error/404_to_index.png b/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/img/error/404_to_index.png deleted file mode 100644 index 34799f733b..0000000000 Binary files a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/img/error/404_to_index.png and /dev/null differ diff --git a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/img/error/error_bg.jpg b/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/img/error/error_bg.jpg deleted file mode 100644 index ab75e5caf4..0000000000 Binary files a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/img/error/error_bg.jpg and /dev/null differ diff --git a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/img/error/error_cloud.png b/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/img/error/error_cloud.png deleted file mode 100644 index 2c55284107..0000000000 Binary files a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/img/error/error_cloud.png and /dev/null differ diff --git a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/img/right.png b/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/img/right.png deleted file mode 100644 index 9b4d17f214..0000000000 Binary files a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/img/right.png and /dev/null differ diff --git a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/js/bootstrap.min.js b/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/js/bootstrap.min.js deleted file mode 100644 index e364a137eb..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/js/bootstrap.min.js +++ /dev/null @@ -1,7 +0,0 @@ -/*! - * Bootstrap v3.3.6 (http://getbootstrap.com) - * Copyright 2011-2015 Twitter, Inc. - * Licensed under the MIT license - */ -if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1||b[0]>2)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 3")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.6",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a(f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.6",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")?(c.prop("checked")&&(a=!1),b.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==c.prop("type")&&(c.prop("checked")!==this.$element.hasClass("active")&&(a=!1),this.$element.toggleClass("active")),c.prop("checked",this.$element.hasClass("active")),a&&c.trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),a(c.target).is('input[type="radio"]')||a(c.target).is('input[type="checkbox"]')||c.preventDefault()}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.6",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));return a>this.$items.length-1||0>a?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&/show|hide/.test(b)&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a('[data-toggle="collapse"][href="#'+b.id+'"],[data-toggle="collapse"][data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.6",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":e.data();c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function c(c){c&&3===c.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=b(d),f={relatedTarget:this};e.hasClass("open")&&(c&&"click"==c.type&&/input|textarea/i.test(c.target.tagName)&&a.contains(e[0],c.target)||(e.trigger(c=a.Event("hide.bs.dropdown",f)),c.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger(a.Event("hidden.bs.dropdown",f)))))}))}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.6",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=b(e),g=f.hasClass("open");if(c(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(a(this)).on("click",c);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger(a.Event("shown.bs.dropdown",h))}return!1}},g.prototype.keydown=function(c){if(/(38|40|27|32)/.test(c.which)&&!/input|textarea/i.test(c.target.tagName)){var d=a(this);if(c.preventDefault(),c.stopPropagation(),!d.is(".disabled, :disabled")){var e=b(d),g=e.hasClass("open");if(!g&&27!=c.which||g&&27==c.which)return 27==c.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.disabled):visible a",i=e.find(".dropdown-menu"+h);if(i.length){var j=i.index(c.target);38==c.which&&j>0&&j--,40==c.which&&jdocument.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){var a=window.innerWidth;if(!a){var b=document.documentElement.getBoundingClientRect();a=b.right-Math.abs(b.left)}this.bodyIsOverflowing=document.body.clientWidth
    ',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(a.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusin"==b.type?"focus":"hover"]=!0),c.tip().hasClass("in")||"in"==c.hoverState?void(c.hoverState="in"):(clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.isInStateTrue=function(){for(var a in this.inState)if(this.inState[a])return!0;return!1},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusout"==b.type?"focus":"hover"]=!1),c.isInStateTrue()?void 0:(clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide())},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.getPosition(this.$viewport);h="bottom"==h&&k.bottom+m>o.bottom?"top":"top"==h&&k.top-mo.width?"left":"left"==h&&k.left-lg.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;jg.right&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){if(!this.$tip&&(this.$tip=a(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),b?(c.inState.click=!c.inState.click,c.isInStateTrue()?c.enter(c):c.leave(c)):c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type),a.$tip&&a.$tip.detach(),a.$tip=null,a.$arrow=null,a.$viewport=null})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.6",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:''}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){this.$body=a(document.body),this.$scrollElement=a(a(c).is(document.body)?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",a.proxy(this.process,this)),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.6",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b=this,c="offset",d=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),a.isWindow(this.$scrollElement[0])||(c="position",d=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var b=a(this),e=b.data("target")||b.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[c]().top+d,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b=e[a]&&(void 0===e[a+1]||b .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu").length&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.6",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return c>e?"top":!1;if("bottom"==this.affixed)return null!=c?e+this.unpin<=f.top?!1:"bottom":a-d>=e+g?!1:"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&c>=e?"top":null!=d&&i+j>=a-d?"bottom":!1},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=Math.max(a(document).height(),a(document.body).height());"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery); diff --git a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/js/jquery.min.js b/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/js/jquery.min.js deleted file mode 100644 index 49990d6e14..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/resources/public/static/js/jquery.min.js +++ /dev/null @@ -1,4 +0,0 @@ -/*! jQuery v2.1.4 | (c) 2005, 2015 jQuery Foundation, Inc. | jquery.org/license */ -!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l=a.document,m="2.1.4",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(n.isPlainObject(d)||(e=n.isArray(d)))?(e?(e=!1,f=c&&n.isArray(c)?c:[]):f=c&&n.isPlainObject(c)?c:{},g[b]=n.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){return!n.isArray(a)&&a-parseFloat(a)+1>=0},isPlainObject:function(a){return"object"!==n.type(a)||a.nodeType||n.isWindow(a)?!1:a.constructor&&!j.call(a.constructor.prototype,"isPrototypeOf")?!1:!0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;a=n.trim(a),a&&(1===a.indexOf("use strict")?(b=l.createElement("script"),b.text=a,l.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:g.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(c=a[b],b=a,a=c),n.isFunction(a)?(e=d.call(arguments,2),f=function(){return a.apply(b||this,e.concat(d.call(arguments)))},f.guid=a.guid=a.guid||n.guid++,f):void 0},now:Date.now,support:k}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b="length"in a&&a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N=M.replace("w","w#"),O="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+N+"))|)"+L+"*\\]",P=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+O+")*)|.*)\\)|)",Q=new RegExp(L+"+","g"),R=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),S=new RegExp("^"+L+"*,"+L+"*"),T=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),U=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),V=new RegExp(P),W=new RegExp("^"+N+"$"),X={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+O),PSEUDO:new RegExp("^"+P),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,aa=/[+~]/,ba=/'|\\/g,ca=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),da=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ea=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(fa){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],k=b.nodeType,"string"!=typeof a||!a||1!==k&&9!==k&&11!==k)return d;if(!e&&p){if(11!==k&&(f=_.exec(a)))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return H.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName)return H.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=1!==k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(ba,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+ra(o[l]);w=aa.test(a)&&pa(b.parentNode)||b,x=o.join(",")}if(x)try{return H.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function pa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=g.documentElement,e=g.defaultView,e&&e!==e.top&&(e.addEventListener?e.addEventListener("unload",ea,!1):e.attachEvent&&e.attachEvent("onunload",ea)),p=!f(g),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(g.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(g.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!g.getElementsByName||!g.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(g.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){var b=g.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",P)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===g||a.ownerDocument===v&&t(v,a)?-1:b===g||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,h=[a],i=[b];if(!e||!f)return a===g?-1:b===g?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?la(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},g):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ca,da),a[3]=(a[3]||a[4]||a[5]||"").replace(ca,da),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ca,da).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(Q," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(ca,da),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return W.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(ca,da).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:oa(function(){return[0]}),last:oa(function(a,b){return[b-1]}),eq:oa(function(a,b,c){return[0>c?c+b:c]}),even:oa(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:oa(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:oa(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:oa(function(a,b,c){for(var d=0>c?c+b:c;++db;b++)d+=a[b].value;return d}function sa(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function ta(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ua(a,b,c){for(var d=0,e=b.length;e>d;d++)ga(a,b[d],c);return c}function va(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function wa(a,b,c,d,e,f){return d&&!d[u]&&(d=wa(d)),e&&!e[u]&&(e=wa(e,f)),ia(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ua(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:va(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=va(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=va(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function xa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=sa(function(a){return a===b},h,!0),l=sa(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[sa(ta(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return wa(i>1&&ta(m),i>1&&ra(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&xa(a.slice(i,e)),f>e&&xa(a=a.slice(e)),f>e&&ra(a))}m.push(c)}return ta(m)}function ya(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=F.call(i));s=va(s)}H.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&ga.uniqueSort(i)}return k&&(w=v,j=t),r};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=xa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,ya(e,d)),f.selector=a}return f},i=ga.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ca,da),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ca,da),aa.test(j[0].type)&&pa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&ra(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,aa.test(a)&&pa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ja(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return g.call(b,a)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;c>b;b++)if(n.contains(e[b],this))return!0}));for(b=0;c>b;b++)n.find(a,e[b],d);return d=this.pushStack(c>1?n.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:l,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}return d=l.getElementById(c[2]),d&&d.parentNode&&(this.length=1,this[0]=d),this.context=l,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};A.prototype=n.fn,y=n(l);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b=n(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(n.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?g.call(n(a),this[0]):g.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){while((a=a[b])&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return a.contentDocument||n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(C[a]||n.unique(e),B.test(a)&&e.reverse()),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return n.each(a.match(E)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(b=a.memory&&l,c=!0,g=e||0,e=0,f=h.length,d=!0;h&&f>g;g++)if(h[g].apply(l[0],l[1])===!1&&a.stopOnFalse){b=!1;break}d=!1,h&&(i?i.length&&j(i.shift()):b?h=[]:k.disable())},k={add:function(){if(h){var c=h.length;!function g(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&g(c)})}(arguments),d?f=h.length:b&&(e=c,j(b))}return this},remove:function(){return h&&n.each(arguments,function(a,b){var c;while((c=n.inArray(b,h,c))>-1)h.splice(c,1),d&&(f>=c&&f--,g>=c&&g--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],f=0,this},disable:function(){return h=i=b=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,b||k.disable(),this},locked:function(){return!i},fireWith:function(a,b){return!h||c&&!i||(b=b||[],b=[a,b.slice?b.slice():b],d?i.push(b):j(b)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!c}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&n.isFunction(a.promise)?e:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(a===!0?--n.readyWait:n.isReady)||(n.isReady=!0,a!==!0&&--n.readyWait>0||(H.resolveWith(l,[n]),n.fn.triggerHandler&&(n(l).triggerHandler("ready"),n(l).off("ready"))))}});function I(){l.removeEventListener("DOMContentLoaded",I,!1),a.removeEventListener("load",I,!1),n.ready()}n.ready.promise=function(b){return H||(H=n.Deferred(),"complete"===l.readyState?setTimeout(n.ready):(l.addEventListener("DOMContentLoaded",I,!1),a.addEventListener("load",I,!1))),H.promise(b)},n.ready.promise();var J=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f};n.acceptData=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function K(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=n.expando+K.uid++}K.uid=1,K.accepts=n.acceptData,K.prototype={key:function(a){if(!K.accepts(a))return 0;var b={},c=a[this.expando];if(!c){c=K.uid++;try{b[this.expando]={value:c},Object.defineProperties(a,b)}catch(d){b[this.expando]=c,n.extend(a,b)}}return this.cache[c]||(this.cache[c]={}),c},set:function(a,b,c){var d,e=this.key(a),f=this.cache[e];if("string"==typeof b)f[b]=c;else if(n.isEmptyObject(f))n.extend(this.cache[e],b);else for(d in b)f[d]=b[d];return f},get:function(a,b){var c=this.cache[this.key(a)];return void 0===b?c:c[b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,n.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=this.key(a),g=this.cache[f];if(void 0===b)this.cache[f]={};else{n.isArray(b)?d=b.concat(b.map(n.camelCase)):(e=n.camelCase(b),b in g?d=[b,e]:(d=e,d=d in g?[d]:d.match(E)||[])),c=d.length;while(c--)delete g[d[c]]}},hasData:function(a){return!n.isEmptyObject(this.cache[a[this.expando]]||{})},discard:function(a){a[this.expando]&&delete this.cache[a[this.expando]]}};var L=new K,M=new K,N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(O,"-$1").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}M.set(a,b,c)}else c=void 0;return c}n.extend({hasData:function(a){return M.hasData(a)||L.hasData(a)},data:function(a,b,c){ -return M.access(a,b,c)},removeData:function(a,b){M.remove(a,b)},_data:function(a,b,c){return L.access(a,b,c)},_removeData:function(a,b){L.remove(a,b)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=M.get(f),1===f.nodeType&&!L.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d])));L.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){M.set(this,a)}):J(this,function(b){var c,d=n.camelCase(a);if(f&&void 0===b){if(c=M.get(f,a),void 0!==c)return c;if(c=M.get(f,d),void 0!==c)return c;if(c=P(f,d,void 0),void 0!==c)return c}else this.each(function(){var c=M.get(this,d);M.set(this,d,b),-1!==a.indexOf("-")&&void 0!==c&&M.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){M.remove(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=L.get(a,b),c&&(!d||n.isArray(c)?d=L.access(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return L.get(a,c)||L.access(a,c,{empty:n.Callbacks("once memory").add(function(){L.remove(a,[b+"queue",c])})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.lengthx",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var U="undefined";k.focusinBubbles="onfocusin"in a;var V=/^key/,W=/^(?:mouse|pointer|contextmenu)|click/,X=/^(?:focusinfocus|focusoutblur)$/,Y=/^([^.]*)(?:\.(.+)|)$/;function Z(){return!0}function $(){return!1}function _(){try{return l.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=n.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return typeof n!==U&&n.event.triggered!==b.type?n.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(E)||[""],j=b.length;while(j--)h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o&&(l=n.event.special[o]||{},o=(e?l.delegateType:l.bindType)||o,l=n.event.special[o]||{},k=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[o])||(m=i[o]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,p,g)!==!1||a.addEventListener&&a.addEventListener(o,g,!1)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),n.event.global[o]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.hasData(a)&&L.get(a);if(r&&(i=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=i[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete i[o])}else for(o in i)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(i)&&(delete r.handle,L.remove(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,m,o,p=[d||l],q=j.call(b,"type")?b.type:b,r=j.call(b,"namespace")?b.namespace.split("."):[];if(g=h=d=d||l,3!==d.nodeType&&8!==d.nodeType&&!X.test(q+n.event.triggered)&&(q.indexOf(".")>=0&&(r=q.split("."),q=r.shift(),r.sort()),k=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=r.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),o=n.event.special[q]||{},e||!o.trigger||o.trigger.apply(d,c)!==!1)){if(!e&&!o.noBubble&&!n.isWindow(d)){for(i=o.delegateType||q,X.test(i+q)||(g=g.parentNode);g;g=g.parentNode)p.push(g),h=g;h===(d.ownerDocument||l)&&p.push(h.defaultView||h.parentWindow||a)}f=0;while((g=p[f++])&&!b.isPropagationStopped())b.type=f>1?i:o.bindType||q,m=(L.get(g,"events")||{})[b.type]&&L.get(g,"handle"),m&&m.apply(g,c),m=k&&g[k],m&&m.apply&&n.acceptData(g)&&(b.result=m.apply(g,c),b.result===!1&&b.preventDefault());return b.type=q,e||b.isDefaultPrevented()||o._default&&o._default.apply(p.pop(),c)!==!1||!n.acceptData(d)||k&&n.isFunction(d[q])&&!n.isWindow(d)&&(h=d[k],h&&(d[k]=null),n.event.triggered=q,d[q](),n.event.triggered=void 0,h&&(d[k]=h)),b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(L.get(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(g.namespace))&&(a.handleObj=g,a.data=g.data,e=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==e&&(a.result=e)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!==this;i=i.parentNode||this)if(i.disabled!==!0||"click"!==a.type){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>=0:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h]*)\/>/gi,ba=/<([\w:]+)/,ca=/<|&#?\w+;/,da=/<(?:script|style|link)/i,ea=/checked\s*(?:[^=]|=\s*.checked.)/i,fa=/^$|\/(?:java|ecma)script/i,ga=/^true\/(.*)/,ha=/^\s*\s*$/g,ia={option:[1,""],thead:[1,"","
    "],col:[2,"","
    "],tr:[2,"","
    "],td:[3,"","
    "],_default:[0,"",""]};ia.optgroup=ia.option,ia.tbody=ia.tfoot=ia.colgroup=ia.caption=ia.thead,ia.th=ia.td;function ja(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function ka(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function la(a){var b=ga.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function ma(a,b){for(var c=0,d=a.length;d>c;c++)L.set(a[c],"globalEval",!b||L.get(b[c],"globalEval"))}function na(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(L.hasData(a)&&(f=L.access(a),g=L.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)n.event.add(b,e,j[e][c])}M.hasData(a)&&(h=M.access(a),i=n.extend({},h),M.set(b,i))}}function oa(a,b){var c=a.getElementsByTagName?a.getElementsByTagName(b||"*"):a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&n.nodeName(a,b)?n.merge([a],c):c}function pa(a,b){var c=b.nodeName.toLowerCase();"input"===c&&T.test(a.type)?b.checked=a.checked:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}n.extend({clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=n.contains(a.ownerDocument,a);if(!(k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(g=oa(h),f=oa(a),d=0,e=f.length;e>d;d++)pa(f[d],g[d]);if(b)if(c)for(f=f||oa(a),g=g||oa(h),d=0,e=f.length;e>d;d++)na(f[d],g[d]);else na(a,h);return g=oa(h,"script"),g.length>0&&ma(g,!i&&oa(a,"script")),h},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k=b.createDocumentFragment(),l=[],m=0,o=a.length;o>m;m++)if(e=a[m],e||0===e)if("object"===n.type(e))n.merge(l,e.nodeType?[e]:e);else if(ca.test(e)){f=f||k.appendChild(b.createElement("div")),g=(ba.exec(e)||["",""])[1].toLowerCase(),h=ia[g]||ia._default,f.innerHTML=h[1]+e.replace(aa,"<$1>")+h[2],j=h[0];while(j--)f=f.lastChild;n.merge(l,f.childNodes),f=k.firstChild,f.textContent=""}else l.push(b.createTextNode(e));k.textContent="",m=0;while(e=l[m++])if((!d||-1===n.inArray(e,d))&&(i=n.contains(e.ownerDocument,e),f=oa(k.appendChild(e),"script"),i&&ma(f),c)){j=0;while(e=f[j++])fa.test(e.type||"")&&c.push(e)}return k},cleanData:function(a){for(var b,c,d,e,f=n.event.special,g=0;void 0!==(c=a[g]);g++){if(n.acceptData(c)&&(e=c[L.expando],e&&(b=L.cache[e]))){if(b.events)for(d in b.events)f[d]?n.event.remove(c,d):n.removeEvent(c,d,b.handle);L.cache[e]&&delete L.cache[e]}delete M.cache[c[M.expando]]}}}),n.fn.extend({text:function(a){return J(this,function(a){return void 0===a?n.text(this):this.empty().each(function(){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&(this.textContent=a)})},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=ja(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=ja(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(oa(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&ma(oa(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(n.cleanData(oa(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return J(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!da.test(a)&&!ia[(ba.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(aa,"<$1>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(oa(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(oa(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,m=this,o=l-1,p=a[0],q=n.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&ea.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(c=n.buildFragment(a,this[0].ownerDocument,!1,this),d=c.firstChild,1===c.childNodes.length&&(c=d),d)){for(f=n.map(oa(c,"script"),ka),g=f.length;l>j;j++)h=c,j!==o&&(h=n.clone(h,!0,!0),g&&n.merge(f,oa(h,"script"))),b.call(this[j],h,j);if(g)for(i=f[f.length-1].ownerDocument,n.map(f,la),j=0;g>j;j++)h=f[j],fa.test(h.type||"")&&!L.access(h,"globalEval")&&n.contains(i,h)&&(h.src?n._evalUrl&&n._evalUrl(h.src):n.globalEval(h.textContent.replace(ha,"")))}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=[],e=n(a),g=e.length-1,h=0;g>=h;h++)c=h===g?this:this.clone(!0),n(e[h])[b](c),f.apply(d,c.get());return this.pushStack(d)}});var qa,ra={};function sa(b,c){var d,e=n(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:n.css(e[0],"display");return e.detach(),f}function ta(a){var b=l,c=ra[a];return c||(c=sa(a,b),"none"!==c&&c||(qa=(qa||n(" - - - - - - - - - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_shiro/src/main/resources/templates/login.html b/jun_springboot_plugin/springboot_shiro/src/main/resources/templates/login.html deleted file mode 100644 index 23c03e8952..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/resources/templates/login.html +++ /dev/null @@ -1,77 +0,0 @@ - - - - - - SpringBoot Shiro测试 - - - - - - - -
    -
    -
    -

    -
    -

    欢迎使用XX管理平台

    -
    -
    -
    -
    - -
    -
    -
    - -
    -
    - -
    -
    -
    - -
    -
    - -
    -
    -
    - -
    - - - -
    -
    -
    - - - - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_shiro/src/main/resources/templates/modules/common/welcome.html b/jun_springboot_plugin/springboot_shiro/src/main/resources/templates/modules/common/welcome.html deleted file mode 100644 index cff4537579..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/resources/templates/modules/common/welcome.html +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - -
    -
    -

    欢迎您!

    -
    -
    - - diff --git a/jun_springboot_plugin/springboot_shiro/src/main/resources/templates/userInfo.html b/jun_springboot_plugin/springboot_shiro/src/main/resources/templates/userInfo.html deleted file mode 100644 index f835b3fc98..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/resources/templates/userInfo.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - - UserInfo - - -

    用户查询界面

    - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_shiro/src/main/resources/templates/userInfoAdd.html b/jun_springboot_plugin/springboot_shiro/src/main/resources/templates/userInfoAdd.html deleted file mode 100644 index 0716e44ff8..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/resources/templates/userInfoAdd.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - - Add - - -

    用户添加界面

    - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_shiro/src/main/resources/templates/userInfoDel.html b/jun_springboot_plugin/springboot_shiro/src/main/resources/templates/userInfoDel.html deleted file mode 100644 index 031e009495..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/main/resources/templates/userInfoDel.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - - Del - - -

    用户删除界面

    - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_shiro/src/test/java/com/xncoding/pos/SimpleTest.java b/jun_springboot_plugin/springboot_shiro/src/test/java/com/xncoding/pos/SimpleTest.java deleted file mode 100644 index 5120283c79..0000000000 --- a/jun_springboot_plugin/springboot_shiro/src/test/java/com/xncoding/pos/SimpleTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.xncoding.pos; - -import com.xncoding.pos.shiro.ShiroKit; -import org.junit.Test; - -import java.nio.file.*; - -/** - * SimpleTest - * - * @author XiongNeng - * @version 1.0 - * @since 2018/1/4 - */ -public class SimpleTest { - @Test - public void testMd5() { - //盐(用户名+随机数) - String username = "admin"; - String salt = ShiroKit.getRandomSalt(16); - //原密码 - String password = "12345678"; - String encodedPassword = ShiroKit.md5(password, username + salt); - System.out.println("这个是保存进数据库的密码:" + encodedPassword); - System.out.println("这个是保存进数据库的盐:" + salt); - } - - @Test - public void test1() throws Exception { - WatchService watchService - = FileSystems.getDefault().newWatchService(); - - Path path = Paths.get(System.getProperty("user.home")); - - path.register( - watchService, - StandardWatchEventKinds.ENTRY_CREATE, - StandardWatchEventKinds.ENTRY_DELETE, - StandardWatchEventKinds.ENTRY_MODIFY); - - WatchKey key; - while ((key = watchService.take()) != null) { - for (WatchEvent event : key.pollEvents()) { - System.out.println( - "Event kind:" + event.kind() - + ". File affected: " + event.context() + "."); - } - key.reset(); - } - } -} diff --git a/jun_springboot_plugin/springboot_snaker/.gitattributes b/jun_springboot_plugin/springboot_snaker/.gitattributes deleted file mode 100644 index 2959201f4e..0000000000 --- a/jun_springboot_plugin/springboot_snaker/.gitattributes +++ /dev/null @@ -1,3 +0,0 @@ -*.js linguist-language=java -*.css linguist-language=java -*.html linguist-language=java diff --git a/jun_springboot_plugin/springboot_snaker/Initial_commit.patch b/jun_springboot_plugin/springboot_snaker/Initial_commit.patch deleted file mode 100644 index 330d6cf8c4..0000000000 --- a/jun_springboot_plugin/springboot_snaker/Initial_commit.patch +++ /dev/null @@ -1,9 +0,0 @@ -Index: README.md -IDEA additional info: -Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP -<+>UTF-8 -=================================================================== ---- README.md (date 1545134171000) -+++ README.md (date 1545134171000) -@@ -0,0 +1,1 @@ -+#Springboot_snakerflow diff --git a/jun_springboot_plugin/springboot_snaker/README.md b/jun_springboot_plugin/springboot_snaker/README.md deleted file mode 100644 index a97342eaec..0000000000 --- a/jun_springboot_plugin/springboot_snaker/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# springboot-snakerflow -采用springboot2.0.5+snakerflow2.4.0搭建工作流微服务项目,集成mybatis-plus,并对外提供了restful风格的接口。 diff --git "a/jun_springboot_plugin/springboot_snaker/Spring Boot \351\233\206\346\210\220SnakerFlow\346\265\201\347\250\213\345\274\225\346\223\216\357\274\214\347\256\200\344\273\213\343\200\201\345\212\237\350\203\275\345\210\227\350\241\250\343\200\201\350\257\246\347\273\206\350\247\243\350\257\273\343\200\201\346\211\251\345\261\225\347\202\271\345\210\206\346\236\220.md" "b/jun_springboot_plugin/springboot_snaker/Spring Boot \351\233\206\346\210\220SnakerFlow\346\265\201\347\250\213\345\274\225\346\223\216\357\274\214\347\256\200\344\273\213\343\200\201\345\212\237\350\203\275\345\210\227\350\241\250\343\200\201\350\257\246\347\273\206\350\247\243\350\257\273\343\200\201\346\211\251\345\261\225\347\202\271\345\210\206\346\236\220.md" deleted file mode 100644 index 74d2d7859f..0000000000 --- "a/jun_springboot_plugin/springboot_snaker/Spring Boot \351\233\206\346\210\220SnakerFlow\346\265\201\347\250\213\345\274\225\346\223\216\357\274\214\347\256\200\344\273\213\343\200\201\345\212\237\350\203\275\345\210\227\350\241\250\343\200\201\350\257\246\347\273\206\350\247\243\350\257\273\343\200\201\346\211\251\345\261\225\347\202\271\345\210\206\346\236\220.md" +++ /dev/null @@ -1,1199 +0,0 @@ -Spring Boot 集成SnakerFlow流程引擎,简介、功能列表、详细解读、扩展点分析 - - -功能列表 -流程定义 -任务参与者 -参与者设置 -动态添加、删除参与者 -组支持 -详细解读 -Spring Boot集成 -表定义 -表详细说明: -字段详细说明: -常见操作 -常规API -综合查询 -模型操作 -流程模型 -Start节点 -name获取节点 -类型获取所有节点 -所有任务节点 -后续一级节点集合 -活动任务 -转派 -撤回 -提取 -驳回、跳转 -唤醒 -更新 -创建自由任务 -决策表达式 -decision的expr -transition的expr -自定义类 -子流程 -子流程模型 -父子流程的关联 -时限控制 -依赖包 -配置 -超时提醒 -超时自动完成 -实例抄送 -表结构 -创建抄送 -更新状态 -会签任务 -会签任务节点 -动态加签 -会签百分比 -串行会签 -Fork/Join -级联删除(历史数据清理) -扩展点 -自定义实例编号orderNo -任务、实例完成时触发的回调 -节点拦截器 -全局拦截器 -局部拦截器 -源码分析 -自定义处理节点 -基于用户或组的访问策略 -☎️ ☎️ ☎️ 已开源基于SnakerFlow轻量级工作流引擎的脚手架项目 easy-admin - -详情参见:终于写了个开源项目,easy-admin 为打造一款简单、轻量级的后台管理系统脚手架 - -简介 -SnakerFlow是一个基于Java的轻量级工作流引擎,适用于企业应用中常见的业务流程。本着轻量、简单、灵巧理念设计,定位于简单集成,多环境支持。 - -轻量: snaker-core.jar大小208K,代码行数约7000行,强大的扩展支持,不依赖于具体的ORM框架,默认支持以下框架: - -Spring、Jfinal、Nutz -Jdbc、SpringJdbc、Hibernate3、Hibernate4、Mybatis -简单: 表设计简单,七张核心表 - -表设计简单[核心表7张] -流程组件简单[start/end/task/custom/subprocess/decision/fork/join] -灵巧: 预留大量扩展接口,支持web流程设计器 - -暴露大量可扩展接口 -支持流程设计器、流程引擎的组件模型自定义[节点自定义、属性自定义、表单自定义] -相关网站如下: - -https://github.com/snakerflow-starter - -https://github.com/snakerflow-starter/snakerflow-spring-boot-starter - -https://yunmel.gitbooks.io/snakerflow/content/ - -https://github.com/snakerflow-starter/snaker-web - -功能列表 -流程定义 - -待办 - -已办 - -任务到达某节点发出sms email 创建任务、完成实例 - -催办 - -转办 - -会签 - -snaker的会签目前相对比较简单,仅仅是根据任务节点的performType属性值确定是否产生多个相同任务。 - -performType的值有两种,分别是ANY、ALL。 - -ANY多个参与者时,任何一个完成任务即继续流转 - -ALL多个参与者时,所有都需要完成任务才能继续流转 - -performType为0 ANY,则仅仅向wf_task_actor表中增加一条参与者信息performType为1ALL,则会在wf_task表中增加一条任务数据。 - -加签 - -engine.task().addTaskActor(String taskId, 1, String… actorIds) -审批环节 同意 拒绝 - -驳回到任意节点 - -流程图 - -撤回 - -任务参与者 - -流程定义 -支持Eclipse插件、web设计器。 - -已集成web设计器,具体详见我的开源项目Easy-Admin: https://gitee.com/lakernote/easy-admin - -任务参与者 -snaker的任务支持静态配置、动态传递、自定义类处理、动态设置、组等方式。 - -参与者设置 -动态添加、删除参与者 -组支持 -参与者设置 -直接设置静态参与者,即assignee值为用户、部门或角色的标识符 - -通过运行时动态传递,即assignee值为变量名称,在调用流程引擎的api时,通过map参数传递这个变量值 - -通过自定义类[继承Assignment类],设置assignmentHandler属性,assign方法返回值就是参与者 - -常用的动态添加、删除参与者示例 - -Order dm = snakerEngineFacets.startInstanceById(process.getId(), "张三", Dict.create() - .set("user1", "张三排") - .set("user2", "组长") - .set("approveBoss.operator", "部门经理")); -1 -2 -3 -4 - - - - - - - - - - - - - -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -源码:org.snaker.engine.core.TaskService - -/** - * 根据Task模型的assignee、assignmentHandler属性以及运行时数据,确定参与者 - * @param model 模型 - * @param execution 执行对象 - * @return 参与者数组 - */ -private String[] getTaskActors(TaskModel model, Execution execution) { - Object assigneeObject = null; - AssignmentHandler handler = model.getAssignmentHandlerObject(); - if(StringHelper.isNotEmpty(model.getAssignee())) { - // Args{user1:张三,user2:李四},model.getAssignee() user1 - assigneeObject = execution.getArgs().get(model.getAssignee()); - } else if(handler != null) { - if(handler instanceof Assignment) { - assigneeObject = ((Assignment)handler).assign(model, execution); - } else { - assigneeObject = handler.assign(execution); - } - } - return getTaskActors(assigneeObject == null ? model.getAssignee() : assigneeObject); -} -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -动态添加、删除参与者 -向指定任务动态添加参与者,同时支持设置参与类型 - -performType为0,则仅仅向wf_task_actor表中增加一条参与者信息performType为1,则会在wf_task表中增加一条任务数据。 - -engine.task().addTaskActor(String taskId, String... actors) -engine.task().addTaskActor(String taskId, Integer performType, String... actors) -1 -2 -对指定任务动态删除其中的参与者 - -engine.task().removeTaskActor(String taskId, String... actors) -1 -组支持 -由于snaker引擎与用户权限完全解耦的,所以对于组的支持,仅仅是你设置组作为参与者,你就要自定义一个任务的访问策略,能够根据操作人得到所有的组集合,这样流程引擎才能允许该操作人处理任务。 - -自定义任务访问策略类 -public class CustomAccessStrategy extends GeneralAccessStrategy { - protected List ensureGroup(String operator) { - //此处根据实际项目获取操作人对应的组列表 - return ShiroUtils.getGroups(); - } -} -1 -2 -3 -4 -5 -6 -配置 -在snaker.xml中增加下面的配置 - - -1 -详细解读 -Spring Boot集成 -1.pom.xml依赖 - - - com.github.snakerflow-starter - snakerflow-spring-boot-starter - 1.0.7 - -1 -2 -3 -4 -5 -2.新增配置项 - -mybatis-plus: - type-aliases-package: org.snaker.engine.entity -1 -2 -3.初始化sql脚本 - -具体详见我的开源项目Easy-Admin: https://gitee.com/lakernote/easy-admin - -表定义 -Snaker流程引擎核心共7张表,关系图如下所示: - -[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BIBnQoBD-1628575405791)(https://yunmel.gitbooks.io/snakerflow/content/assets/table_relations.png)] - -表详细说明: -表名称 描述 备注 -wf_process 流程定义表 -wf_order 活动实例表 -wf_task 活动任务表 -wf_task_actor 活动任务参与者表 -wf_hist_order 历史实例表 -wf_hist_task 历史任务表 -wf_hist_task_actor 历史任务参与者表 -wf_surrogate 委托代理管理表 一般业务用不到 -wf_cc_order 抄送实例表 一般业务用不到 -字段详细说明: -wf_process - -字段名称 字段描述 -id 主键ID -name 流程名称 -display_Name 流程显示名称 -type 流程类型 -instance_Url 实例url -state 流程是否可用 -content 流程模型定义 -version 版本 -create_Time 创建时间 -creator 创建人 -wf_order - -字段名称 字段描述 -id 主键ID -parent_Id 父流程ID -process_Id 流程定义ID -creator 发起人 -create_Time 发起时间 -expire_Time 期望完成时间 -last_Update_Time 上次更新时间 -last_Updator 上次更新人 -priority 优先级 -parent_Node_Name 父流程依赖的节点名称 -order_No 流程实例编号 -variable 附属变量json存储 -version 版本 -wf_hist_order - -字段名称 字段描述 -id 主键ID -parent_Id 父流程ID -process_Id 流程定义ID -creator 发起人 -create_Time 发起时间 -expire_Time 期望完成时间 -end_Time 完成时间 -priority 优先级 -order_No 流程实例编号 -variable 附属变量json存储 -order_State 状态 -wf_task - -字段名称 字段描述 -id 主键ID -order_Id 流程实例ID -task_Name 任务名称 -display_Name 任务显示名称 -task_Type 任务类型 -perform_Type 参与类型 -operator 任务处理人 -create_Time 任务创建时间 -finish_Time 任务完成时间 -expire_Time 任务期望完成时间 -action_Url 任务处理的url -parent_Task_Id 父任务ID -variable 附属变量json存储 -version 版本 -wf_hist_task - -字段名称 字段描述 -id 主键ID -order_Id 流程实例ID -task_Name 任务名称 -display_Name 任务显示名称 -task_Type 任务类型 -perform_Type 参与类型 -operator 任务处理人 -create_Time 任务创建时间 -finish_Time 任务完成时间 -expire_Time 任务期望完成时间 -action_Url 任务处理的url -parent_Task_Id 父任务ID -variable 附属变量json存储 -task_State 任务状态 -wf_task_actor - -字段名称 字段描述 -task_Id 任务ID -actor_Id 参与者ID -wf_hist_task_actor - -字段名称 字段描述 -task_Id 任务ID -actor_Id 参与者ID -wf_surrogate - -字段名称 字段描述 -id 主键ID -process_Name 流程名称 -operator 授权人 -surrogate 代理人 -odate 操作时间 -sdate 开始时间 -edate 结束时间 -state 状态 -wf_cc_order - -字段名称 字段描述 -order_Id 流程实例ID -actor_Id 参与者ID -create_Time 抄送时间 -finish_Time 完成时间 -creator 发起人 -status 状态 -常见操作 -常规API -参见SnakerEngineFacets.java - -综合查询 -综合查询服务不仅提供流程实例、活动/历史任务、待办任务的查询,同时支持原生SQL语句的查询服务。 - -org.snaker.engine.IQueryService -1 -根据流程实例ID获取流程实例对象 - -Order getOrder(String orderId); -1 -根据流程实例ID获取历史流程实例对象 - -HistoryOrder getHistOrder(String orderId); -1 -根据任务ID获取任务对象 - -Task getTask(String taskId); -1 -根据任务ID获取历史任务对象 - -HistoryTask getHistTask(String taskId); -1 -根据任务ID获取活动任务参与者数组 - -String[] getTaskActorsByTaskId(String taskId); -1 -根据任务ID获取历史任务参与者数组 - -String[] getHistoryTaskActorsByTaskId(String taskId); -1 -根据filter查询活动任务 - -List getActiveTasks(QueryFilter filter); -1 -根据filter分页查询活动任务 - -List getActiveTasks(Page page, QueryFilter filter); -1 -根据filter查询流程实例列表 - -List getActiveOrders(QueryFilter filter); -1 -根据filter分页查询流程实例列表 - -List getActiveOrders(Page page, QueryFilter filter); -1 -根据filter查询历史流程实例 - -List getHistoryOrders(QueryFilter filter); -1 -根据filter分页查询历史流程实例 - -List getHistoryOrders(Page page, QueryFilter filter); -1 -根据filter查询所有已完成的任务 - -List getHistoryTasks(QueryFilter filter); -1 -根据filter分页查询已完成的历史任务 - -List getHistoryTasks(Page page, QueryFilter filter); -1 -根据filter分页查询工作项(包含process、order、task三个实体的字段集合) - -List getWorkItems(Page page, QueryFilter filter); -1 -根据filter分页查询抄送工作项(包含process、order) - -List getCCWorks(Page page, QueryFilter filter); -1 -根据filter分页查询已完成的历史任务项 - -List getHistoryWorkItems(Page page, QueryFilter filter); -1 -根据类型T、Sql语句、参数查询单个对象 - -public T nativeQueryObject(Class T, String sql, Object... args); -1 -根据类型T、Sql语句、参数查询列表对象 - -public List nativeQueryList(Class T, String sql, Object... args); -1 -根据类型T、Sql语句、参数分页查询列表对象 - -public List nativeQueryList(Page page, Class T, String sql, Object... args); -1 -模型操作 -通过流程定义章节的查询接口可以轻松获取到Process实体对象,该实体中的model属性就是流程图的对象表达形式了,可通过getModel方法获取ProcessModel。 - -process.getModel() -1 -流程模型 -Start节点 -name获取节点 -类型获取所有节点 -所有任务节点 -后续一级节点集合 -流程模型 -org.snaker.engine.model.ProcessModel -1 -流程模型、流程定义的XML文件、流程图三种表现形式可互相转换,流程模型对象不仅包含了自身的属性(如:namedisplayNameinstanceUrlexpireTimeinstanceNoClass),同时也包含了所有节点模型对象以及它们的关系。 - -Start节点 -org.snaker.engine.model.StartModel -1 -Start节点作为流程启动的入口,只有输出路由,其输入路由为空,可通过getInputs方法进行验证 - -name获取节点 -NodeModel getNode(String nodeName) -1 -根据节点的name属性获取到节点模型对象 - -类型获取所有节点 -List getModels(Class clazz) -1 -根据节点类型获取所有该类型的模型对象集合。常用于如下方式: - -List taskModels = processModel.getModels(TaskModel.class) -1 -所有任务节点 -List getTaskModels() -1 -该方法获取有序的所有任务模型集合 - -后续一级节点集合 -List getNextModels(Class clazz) -1 -获取某个节点的后续一级节点集合,getNextModels是NodeModel的方法 - -活动任务 -任务服务主要配合流程引擎在调度过程中任务数据的操作。 - -org.snaker.engine.ITaskService -1 -转派 -撤回 -提取 -驳回跳转 -唤醒 -更新 -转派 -任务转派是向指定人创建新的任务。转派api支持主办、协办两种任务类型 - -createNewTask(String taskId, int taskType, String... actors) -1 -taskType:0 主办任务类型 - -taskType:1 协办任务类型 - -撤回 -根据历史任务id,撤回由该历史任务派发的所有活动任务,如果无活动任务,则不允许撤回,抛出unchecked异常:SnakerException - -withdrawTask(String taskId, String operator) -1 -提取 -任务提取一般发生在参与者为部门、角色等组的情况下,该组的某位成员提取任务后,不允许其它成员处理该任务。 - -take(String taskId, String operator) -1 -驳回、跳转 -任务驳回有两种场景:驳回至上一步;驳回至任意节点。 - -engine.executeAndJumpTask(String taskId, String operator, Map args, String nodeName); -1 -方法的参数nodeName决定驳回的方式: - -nodeName为空时,则驳回至上一步,不需要传递参与者数据 -nodeName不为空,则表示任意跳转,此时需要传递参与者数据。 -唤醒 -如果一个已经结束的任务,希望重新激活为活动状态,该如何操作呢。那么调用resume方法即可实现此功能。 - -Task resume(String taskId, String operator) -1 -更新 -如果一个活动任务,需要更新部分字段,则可以使用更新方法完成。 - -updateTask(Task task) -1 -可更新任务对象的finish_Time、operator、expire_Time、variable - -创建自由任务 -engine.createFreeTask(String orderId, String operator, Map args, TaskModel model); -1 -创建自由任务时,需要新建任务模型对象TaskModel,再根据此模型创建对应的任务数据。 - -决策表达式 -决策表达式主要用于decision(选择分支)节点,该节点支持三种路由选择方式 - -decision的expr -transition的expr -自定义类 -decision的expr -decision节点的expr有两种方式来设置 - -1.表达式中增加判断逻辑,如:${day >3 ? 't1' : 't2'},此时根据day的值决定走t1、或t2的路由,用于设置范围值的情况 - -2.表达式仅仅是一个变量,如:${tname},此时,传递tname的值为路由name即可,用于设置具体值的情况(如:同意、不同意) -1 -2 -3 -transition的expr -如果decision节点的expr为空,可设置输出路由的expr,必须返回boolean类型 - -路由1设置expr的值为:${content==1}, -路由2设置expr的值为:${content > 1}。 -1 -2 -自定义类 -自定义类需要实现DecisionHandler接口的decide方法 - -org.snaker.engine.DecisionHandler -1 -该方法返回字符串即表示输出路由的name - -Snaker默认支持Juel、SringEL两种表达式引擎,需要在snaker.xml中配置。配置如下: - - -1 -并且支持自定义表达式,实现Expression接口,同样修改一下配合即可。 - -Juel表达式引擎常用语法 -String expr1 = "${content}"; -Map args1 = new HashMap(); -args1.put("content", 1); -System.out.println(eval(String.class, expr1, args1)); - -String expr2 = "${content == 1 ? 'v1' : 'v2'}"; -Map args2 = new HashMap(); -//此处不仅支持数字类型,也支持字符串类型,但是值必须可转换为数字 -args2.put("content", "2"); -System.out.println(eval(String.class, expr2, args2)); - -String expr3 = "${content > 1 ? 'v1' : 'v2'}"; -Map args3 = new HashMap(); -//此处只要是数字类型即可,如1或0.5等 -args3.put("content", 4.2); -System.out.println(eval(String.class, expr3, args3)); - -//juel支持表达式为字符串类型而参数为数字类型 -String expr4 = "${content == '1' ? 'v1' : 'v2'}"; -Map args4 = new HashMap(); -//此处不仅可以写字符串"1",也可以写char类型'1',写数字类型1,浮点类型1.00 -args4.put("content", 1); -System.out.println(eval(String.class, expr4, args4)); - -//逻辑表达式与,使用&&表示 -String expr5 = "${content > 1 && content <= 10 ? 'v1' : 'v2'}"; -Map args5 = new HashMap(); -//此处不仅可以写字符串"1",也可以写char类型'1',写数字类型1,浮点类型1.00 -args5.put("content", "11"); -System.out.println(eval(String.class, expr5, args5)); - -//逻辑表达式或,使用||表示 -String expr6 = "${content < 1 || content > 10 ? 'v1' : 'v2'}"; -Map args6 = new HashMap(); -//此处不仅可以写字符串"1",也可以写char类型'1',写数字类型1,浮点类型1.00 -args6.put("content", "1"); -System.out.println(eval(String.class, expr6, args6)); - -//逻辑表达式 -String expr7 = "${content < 1 || content > 10 ? 'v1' : (content == 8 ? 'v2' : 'v3')}"; -Map args7 = new HashMap(); -//此处不仅可以写字符串"1",也可以写char类型'1',写数字类型1,浮点类型1.00 -args7.put("content", "8"); -System.out.println(eval(String.class, expr7, args7)); -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -Spring EL表达式引擎常用语法 -String expr1 = "#content"; -Map args1 = new HashMap(); -args1.put("content", "v2"); -System.out.println(expr1 + "====>" + eval(String.class, expr1, args1)); - -String expr2 = "#content == 1 ? 'v1' : 'v2'"; -Map args2 = new HashMap(); -//此处仅支持数字类型 -args2.put("content", 2.1); -System.out.println(expr2 + "====>" + eval(String.class, expr2, args2)); - -String expr3 = "#content > 1 ? 'v1' : 'v2'"; -Map args3 = new HashMap(); -//此处只要是数字类型即可,如1或0.5等 -args3.put("content", 4.2); -System.out.println(expr3 + "====>" + eval(String.class, expr3, args3)); - -//spel支持表达式为字符串类型而参数为数字类型 -String expr4 = "#content == '1' ? 'v1' : 'v2'"; -Map args4 = new HashMap(); -//此处仅支持字符串"1" -args4.put("content", "1"); -System.out.println(expr4 + "====>" + eval(String.class, expr4, args4)); - -//逻辑表达式与,使用and表示 -String expr5 = "#content > 1 and #content <= 10 ? 'v1' : 'v2'"; -Map args5 = new HashMap(); -//此处仅支持数字类型 -args5.put("content", 11); -System.out.println(expr5 + "====>" + eval(String.class, expr5, args5)); - -//逻辑表达式或,使用||表示 -String expr6 = "#content < 1 or #content > 10 ? 'v1' : 'v2'"; -Map args6 = new HashMap(); -//此处不仅可以写字符串"1",也可以写char类型'1',写数字类型1,浮点类型1.00 -args6.put("content", 1); -System.out.println(expr6 + "====>" + eval(String.class, expr6, args6)); - -//逻辑表达式 -String expr7 = "(#content < 1 or #content > 10) ? 'v1' : (#content == 8 ? 'v2' : 'v3')"; -Map args7 = new HashMap(); -//此处不仅可以写字符串"1",也可以写char类型'1',写数字类型1,浮点类型1.00 -args7.put("content", 8); -System.out.println(expr7 + "====>" + eval(String.class, expr7, args7)); -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -子流程 -子流程的作用是将一个复杂的业务流程进行细化拆分,提高流程的复用性。 - -子流程模型 -父子流程的关联 -子流程模型 -子流程模型类型为SubProcessModel,其主要属性为processName,根据流程的name进行关联,由于流程定义支持一个name多个版本同时运行,那么子流程关联只设置name,即表示与最新版本的子流程关联。 - -父子流程的关联 -对于表结构的设计中,父子流程的关联字段为 - -wf_order[parent_Id、parent_Node_Name] -wf_hist_order[parent_Id] -时限控制 -时限控制常用于流程平台中的超时处理(提醒、自动执行等)、以及任务监控的查询统计等功能。 - -依赖包 -配置 -实现提醒接口 -依赖包 -snaker默认支持quartz定时器调度框架,只需要依赖snaker-quartz的包即可。 - -配置 -在snaker.xml中配置时限控制的拦截器、定时调度的实现类 - - - -1 -2 -如果使用其它定时调度框架,需要实现IScheduler接口,并替换QuartzScheduler类配置 - -以上两步已经完成了时限的配置工作,下面就可以针对提醒、超时自动执行做自定义扩展了。 - -超时提醒 -编写自定义的提醒类,实现IReminder接口。并配置到snaker.xml中即可。 -任务节点配置超时提醒属性:reminderTime、reminderRepeat。 -reminderTime是一个变量,表示提醒开始时间,当你调用api时需要传递此变量值,值的类型为date。 -reminderRepeat是一个数字,表示重复提醒间隔时间,以分钟为单位 -1 -2 -默认提醒一次就结束,如果希望提醒多次,可通过 snaker.properties 中配置 scheduler.repeat 属性,该值是个数字,表示提醒次数。 -节假日配置 -#是否启用节假日,默认为false -scheduler.useCalendar=true/false -#节日配置,格式为yyyy-MM-dd,... -scheduler.holidays=2014-12-26,2014-12-27 -#工作日设置,格式为1,2,3...7,表示周一至周日 -scheduler.weeks=1,2,3,4,5 -#工作时间设置,格式为8:00-18:00 -scheduler.workTime=8:00-18:00 -1 -2 -3 -4 -5 -6 -7 -8 -超时自动完成 -任务节点配置超时处理属性: expireTime、autoExecute、callback -expireTime是一个变量,表示期望完成时间,当你调用api时需要传递此变量值,值的类型为date。 - -autoExecute的值为Y/N,表示超时是否自动执行 - -callback是一个字符串,表示自动执行的回调类路径配置 - -编写回调类 -通过实现JobCallback接口 - -org.snaker.engine.scheduling.JobCallback -1 -实例抄送 -实例的抄送类似于邮箱里面的抄送功能,一般用于将该流程实例抄送给领导查阅。 - -表结构 -创建抄送 -更新状态 -表结构 -抄送记录表主要保存抄送的记录信息 - -wf_cc_order -1 -创建抄送 -根据实例id、创建人、抄送人创建抄送记录 - -engine.order().createCCOrder(String orderId, String creator, String... actorIds) -1 -更新状态 -更新状态用于更新抄送记录为已经阅读 - -engine.order().updateCCStatus(String orderId, String... actorIds) -1 -会签任务 -snaker的会签目前相对比较简单,仅仅是根据任务节点的performType属性值确定是否产生多个相同任务。 - -performType的值有两种,分别是ANY、ALL。 - -ANY多个参与者时,任何一个完成任务即继续流转 - -ALL多个参与者时,所有都需要完成任务才能继续流转 - -会签任务节点 -动态加签 -会签百分比 -串行会签 -会签任务节点 -只需要在流程定义时,将任务节点的属性performType值设置为ALL即可,当调用api时传递多个参与者时,则自动派发与参与者数量相同的任务。会签任务必须等待所有参与者完成后,才继续流转 - -动态加签 -可调用任务服务的addTaskActor方法实现动态加签。 - -engine.task().addTaskActor(String taskId, 1, String... actorIds) -1 -会签百分比 -暂未实现 -1 -串行会签 -暂未实现 -1 -Fork/Join -snaker流程引擎中的所有节点模型都支持fork/join的并行流转。 - -建议fork/join配对使用,否则会造成流程数据不一致。 - -测试用例中的forkjoin流程图如下所示: - - - -级联删除(历史数据清理) -级联删除主要用于流程定义、流程实例的数据。一般情况下,不建议在正式环境里使用此功能,顾名思义,会删除所有的关联数据,谨慎使用。 - -流程定义 -engine.process().cascadeRemove(String processId) -1 -会删除流程定义以及该定义启动的所有流程实例、任务,谨慎使用。 - -流程实例 -engine.order().cascadeRemove(String orderId) -1 -会删除流程实例以及该实例创建的所有任务,谨慎使用。 - -扩展点 -自定义实例编号orderNo -源码:org.snaker.engine.core.OrderService - - /** - * 创建活动实例 - */ - public Order createOrder(Process process, String operator, Map args, - String parentId, String parentNodeName) { - ... - String orderNo = (String)args.get(SnakerEngine.ID); - if(StringHelper.isNotEmpty(orderNo)) { - order.setOrderNo(orderNo); - } else { - order.setOrderNo(model.getGenerator().generate(model)); - ... - } -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -有2种方式进行自定义 - -开启实例时,参数中加入SnakerEngine.ID -实现INoGenerator 接口,并在流程定义的xml中配置 -任务、实例完成时触发的回调 -Completion:所有任务和实例在完成时会回到Completion的实现类。 - -源码:org.snaker.engine.core.TaskService - -/** - * 完成指定任务 - * 该方法仅仅结束活动任务,并不能驱动流程继续执行 - */ -public Task complete(String taskId, String operator, Map args) { - Completion completion = getCompletion(); //completion = ServiceContext.find(Completion.class); - if(completion != null) { - completion.complete(history); - } - return task; -} -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -从completion = ServiceContext.find(Completion.class);这里看出,仅能使用一个Completion实现类。 - -默认的任务、实例完成时触发的动作 - -public class GeneralCompletion implements Completion { - private static final Logger log = LoggerFactory.getLogger(GeneralCompletion.class); - - public void complete(HistoryTask task) { - log.info("The task[{}] has been user[{}] has completed", task.getId(), task.getOperator()); - } - - public void complete(HistoryOrder order) { - log.info("The order[{}] has completed", order.getId()); - } -} -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -扩展示例如下: - -@Component -public class EasyAdminCompletion implements Completion { -1 -2 -节点拦截器 -snaker的拦截器支持所有的节点前后拦截,并且支持全局、局部拦截器。拦截器统一实现SnakerInterceptor接口 - -org.snaker.engine.SnakerInterceptor -1 -全局拦截器 -局部拦截器 -全局拦截器 -全局拦截器会拦截所有新产生的任务对象。自定义的全局拦截器需要配置到snaker.xml中。如默认支持的日志拦截器 - - -1 -例如: - -@Component -public class EasyGlobalCreateTaskInterceptor implements SnakerInterceptor { - @Override - public void intercept(Execution execution) { - // ... - } -} -1 -2 -3 -4 -5 -6 -7 -局部拦截器 -局部拦截器支持节点执行的前置、后置拦截。需要配置到task节点模型的preInterceptors[前置拦截]、postInterceptors[后置拦截]属性 - -源码分析 -这里仅看全局拦截器实现原理。 - -源码:org.snaker.engine.handlers.impl.CreateTaskHandler - -/** - * 根据任务模型、执行对象,创建下一个任务,并添加到execution对象的tasks集合中 - */ - public void handle(Execution execution) { - List tasks = execution.getEngine().task().createTask(model, execution); - execution.addTasks(tasks); - /** - * 从服务上下文中查找任务拦截器列表,依次对task集合进行拦截处理 - */ - List interceptors = ServiceContext.getContext().findList(SnakerInterceptor.class); - try { - for(SnakerInterceptor interceptor : interceptors) { - interceptor.intercept(execution); - } - } catch(Exception e) { - log.error("拦截器执行失败=" + e.getMessage()); - throw new SnakerException(e); - } - } -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -从List interceptors = ServiceContext.getContext().findList(SnakerInterceptor.class);这里看出可以存在多个全局拦截器。 - -自定义处理节点 -snaker的自定义节点可完成流程的全自动编排。只需要在自定义节点模型中配置处理类即可。 - -自定义节点的处理类有两种方式: - -实现IHandler接口 - -只需要配置clazz属性即可 - -普通java类 - -需要设置clazzmethodNameargsvar - -自定义节点的执行不需要外部触发,只要抵达节点立即执行绑定的类进行处理。并记录历史任务,处理类返回值保存在历史任务的变量字段中。 - -基于用户或组的访问策略 -策略类用于判断当前操作人operator是否允许执行taskId指定的任务 - -源码:org.snaker.engine.core.TaskService - -/** - * 判断当前操作人operator是否允许执行taskId指定的任务 - */ - public boolean isAllowed(Task task, String operator) { - if(StringHelper.isNotEmpty(operator)) { - if(SnakerEngine.ADMIN.equalsIgnoreCase(operator) - || SnakerEngine.AUTO.equalsIgnoreCase(operator)) { - return true; - } - if(StringHelper.isNotEmpty(task.getOperator())) { - return operator.equals(task.getOperator()); - } - } - List actors = access().getTaskActorsByTaskId(task.getId()); - if(actors == null || actors.isEmpty()) return true; - return !StringHelper.isEmpty(operator) - && getStrategy().isAllowed(operator, actors); // strategy = ServiceContext.find(TaskAccessStrategy.class); - } -==== - 调用方法:complete、take -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -从strategy = ServiceContext.find(TaskAccessStrategy.class);可得出,仅可存在一个实现类。 - -扩展示例 - -@Component -public class GeneralAccessStrategy implements TaskAccessStrategy { -———————————————— -版权声明:本文为CSDN博主「lakernote」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 -原文链接:https://blog.csdn.net/abu935009066/article/details/119568513 \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_snaker/mvnw b/jun_springboot_plugin/springboot_snaker/mvnw deleted file mode 100644 index 5551fde8e7..0000000000 --- a/jun_springboot_plugin/springboot_snaker/mvnw +++ /dev/null @@ -1,286 +0,0 @@ -#!/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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven2 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)`" - # TODO classpath? -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 - 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 wget ... using wget" - fi - wget "$jarUrl" -O "$wrapperJarPath" - elif command -v curl > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found curl ... using curl" - fi - curl -o "$wrapperJarPath" "$jarUrl" - else - 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 - 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 - -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/jun_springboot_plugin/springboot_snaker/mvnw.cmd b/jun_springboot_plugin/springboot_snaker/mvnw.cmd deleted file mode 100644 index e5cfb0ae9e..0000000000 --- a/jun_springboot_plugin/springboot_snaker/mvnw.cmd +++ /dev/null @@ -1,161 +0,0 @@ -@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 http://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 Maven2 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 key stroke 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 my 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.4.2/maven-wrapper-0.4.2.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% ( - echo Found %WRAPPER_JAR% -) else ( - echo Couldn't find %WRAPPER_JAR%, downloading it ... - echo Downloading from: %DOWNLOAD_URL% - powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" - echo Finished downloading %WRAPPER_JAR% -) -@REM End of extension - -%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/jun_springboot_plugin/springboot_snaker/pom.xml b/jun_springboot_plugin/springboot_snaker/pom.xml deleted file mode 100644 index 9550ca12d5..0000000000 --- a/jun_springboot_plugin/springboot_snaker/pom.xml +++ /dev/null @@ -1,261 +0,0 @@ - - - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 1.5.9.RELEASE - - - io.github.wujun728 - springboot_snaker - 1.0 - - - 1.8 - - - - - org.springframework.boot - spring-boot-starter - - - - - org.springframework.boot - spring-boot-starter-jdbc - 1.5.9.RELEASE - - - - org.apache.tomcat - tomcat-jdbc - - - - - org.springframework.boot - spring-boot-autoconfigure - 1.5.9.RELEASE - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - - org.springframework.boot - spring-boot-starter-tomcat - - - - org.springframework.boot - spring-boot-devtools - true - - - - org.springframework.boot - spring-boot-configuration-processor - true - - - - - - mysql - mysql-connector-java - 5.0.5 - - - - org.springframework.boot - spring-boot-starter-test - test - - - - com.github.snakerflow - snaker-core - 2.4.0 - - - org.slf4j - slf4j-api - - - - - com.github.snakerflow - snaker-spring - 2.4.0 - - - org.slf4j - slf4j-api - - - - - com.github.snakerflow - snaker-mybatis - 2.4.0 - - - - - - com.baomidou - mybatis-plus-boot-starter - 3.0.6 - - - - - - - org.apache.velocity - velocity-engine-core - 2.3 - - - - org.freemarker - freemarker - - - - - - commons-dbcp - commons-dbcp - 1.4 - runtime - - - - commons-dbutils - commons-dbutils - 1.6 - - - - org.springframework - spring-tx - 4.3.13.RELEASE - - - - - - develop - - develop - - - true - - - - local - - local - - - - preview - - preview - - - - release - - release - - - - test - - test - - - - - - - - - - src/main/resources/config/${profiles.active} - . - true - - - - src/main/resources - - snakerflow/** - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.7 - 1.7 - - - - org.springframework.boot - spring-boot-maven-plugin - 1.5.9.RELEASE - - - - repackage - - - - - - - - - diff --git a/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/DemoApplication.java b/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/DemoApplication.java deleted file mode 100644 index 7f922b1e8f..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/DemoApplication.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.snakerflow.demo; - -import org.mybatis.spring.annotation.MapperScan; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.ImportResource; - - -@SpringBootApplication -@MapperScan("com.snakerflow.demo.api.mapper") -@ImportResource(locations= {"classpath:applicationContext.xml"}) -public class DemoApplication { - public static void main(String[] args) { - SpringApplication.run(DemoApplication.class, args); - } - -} - diff --git a/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/DemoApplicationRunner.java b/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/DemoApplicationRunner.java deleted file mode 100644 index 748eaf83fd..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/DemoApplicationRunner.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.snakerflow.demo; - -import com.snakerflow.demo.utils.SnakerEngineFacadeImpl; -import org.apache.commons.lang.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.ApplicationArguments; -import org.springframework.boot.ApplicationRunner; -import org.springframework.core.annotation.Order; -import org.springframework.stereotype.Component; - - -/** - * 说明:在项目启动成功之后,立马部署工作流模板。 - * - * @author liuxzh - * @version 1.00 - * @since digibook2.0 - */ -@Component -@Order(value = 1) -public class DemoApplicationRunner implements ApplicationRunner { - @Autowired - private SnakerEngineFacadeImpl engineUtil; - //流程模板路径(配置文件读取) - @Value("${snaker.workflow.model.path}") - private String path; - - @Override - public void run(ApplicationArguments var1) throws Exception { - //System.out.println("项目部署成功,当前时间:" + new Date()); - String processId = engineUtil.deploy(path); - if (StringUtils.isNotBlank(processId)) { - //部署流程模板成功处理代码 - //System.out.println("部署流程模板成功,流程定义id:" + processId); - } else { - //部署流程模板失败处理代码 - } - } -} diff --git a/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/api/controller/SecUserController.java b/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/api/controller/SecUserController.java deleted file mode 100644 index 07fa64a9fa..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/api/controller/SecUserController.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.snakerflow.demo.api.controller; - - -import org.springframework.web.bind.annotation.RequestMapping; - -import org.springframework.web.bind.annotation.RestController; - -/** - *

    - * 前端控制器 - *

    - * - * @author liuxzh - * @since 2018-12-20 - */ -@RestController -@RequestMapping("/api/secUser") -public class SecUserController { - -} diff --git a/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/api/controller/TestController.java b/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/api/controller/TestController.java deleted file mode 100644 index 1280f4c725..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/api/controller/TestController.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.snakerflow.demo.api.controller; - -import com.snakerflow.demo.api.service.IWorkflowService; -import com.snakerflow.demo.utils.ResponseData; -import com.snakerflow.demo.utils.SnakerEngineFacadeImpl; -import org.apache.commons.lang.StringUtils; -import org.snaker.engine.SnakerEngine; -import org.snaker.engine.entity.Order; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@RestController -@RequestMapping("/api/wf") -public class TestController { - @Autowired - private IWorkflowService wfService; - @Autowired - private SnakerEngineFacadeImpl snakerEngineFacade; - @Autowired - private SnakerEngine engine; - - //流程模板路径(配置文件读取) - @Value("${snaker.workflow.model.path}") - private String MODEL_PATH; - //流程模板路径(常量类引入) - //public static final String MODEL_PATH = "snakerflow/examination.snaker"; - /* - * 部署流程模板 - * */ - @RequestMapping(value = "/deploy", method = RequestMethod.POST) - public ResponseData deployWf() { - String processId = snakerEngineFacade.deploy(MODEL_PATH); - if (StringUtils.isNotBlank(processId)) { - return ResponseData.ok().putDataValue("message", - "部署成功").putDataValue("prcessId", processId); - } else { - return ResponseData.notFound(); - } - } - - @RequestMapping(value = "/getProcess", method = RequestMethod.GET) - public ResponseData getProcess() { - String processId = "a6a45d2712a940c3a05c3bb83d0d21a4"; - String operator = "liuxzh_userId"; - Map args = new HashMap(); - args.put("quanju var", "全局变量"); - - Order order = snakerEngineFacade.startInstanceById(processId, operator, args); - if (StringUtils.isNotBlank(order.getId())) { - System.out.println(order.getId()); - return ResponseData.ok().putDataValue("message", - "启动流程实例成功"); - } else { - return ResponseData.notFound(); - } - } - - @RequestMapping(value = "/getAllProcessNames", method = RequestMethod.GET) - public ResponseData getAllProcessNames() { - - List names = snakerEngineFacade.getAllProcessNames(); - - if (StringUtils.isNotBlank(names.size()+"")) { - for (String name : names) { - System.out.println(name); - } - return ResponseData.ok().putDataValue("message", - "所有流程名称获取成功"); - } else { - return ResponseData.notFound(); - } - } -} - diff --git a/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/api/entity/SecUser.java b/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/api/entity/SecUser.java deleted file mode 100644 index dcfd04b768..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/api/entity/SecUser.java +++ /dev/null @@ -1,151 +0,0 @@ -package com.snakerflow.demo.api.entity; - -import com.baomidou.mybatisplus.extension.activerecord.Model; -import com.baomidou.mybatisplus.annotation.TableField; -import java.io.Serializable; - -/** - *

    - * - *

    - * - * @author liuxzh - * @since 2018-12-20 - */ -public class SecUser extends Model { - - private static final long serialVersionUID = 1L; - - private String address; - - private Integer age; - - private String email; - - private String enabled; - - private String fullname; - - private String password; - - @TableField("plainPassword") - private String plainPassword; - - private String salt; - - private String sex; - - private Integer type; - - private String username; - - private Integer org; - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; - } - public Integer getAge() { - return age; - } - - public void setAge(Integer age) { - this.age = age; - } - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - public String getEnabled() { - return enabled; - } - - public void setEnabled(String enabled) { - this.enabled = enabled; - } - public String getFullname() { - return fullname; - } - - public void setFullname(String fullname) { - this.fullname = fullname; - } - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - public String getPlainPassword() { - return plainPassword; - } - - public void setPlainPassword(String plainPassword) { - this.plainPassword = plainPassword; - } - public String getSalt() { - return salt; - } - - public void setSalt(String salt) { - this.salt = salt; - } - public String getSex() { - return sex; - } - - public void setSex(String sex) { - this.sex = sex; - } - public Integer getType() { - return type; - } - - public void setType(Integer type) { - this.type = type; - } - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - public Integer getOrg() { - return org; - } - - public void setOrg(Integer org) { - this.org = org; - } - - @Override - protected Serializable pkVal() { - return null; - } - - @Override - public String toString() { - return "SecUser{" + - "address=" + address + - ", age=" + age + - ", email=" + email + - ", enabled=" + enabled + - ", fullname=" + fullname + - ", password=" + password + - ", plainPassword=" + plainPassword + - ", salt=" + salt + - ", sex=" + sex + - ", type=" + type + - ", username=" + username + - ", org=" + org + - "}"; - } -} diff --git a/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/api/mapper/SecUserMapper.java b/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/api/mapper/SecUserMapper.java deleted file mode 100644 index 83e5676a50..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/api/mapper/SecUserMapper.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.snakerflow.demo.api.mapper; - -import com.snakerflow.demo.api.entity.SecUser; -import com.baomidou.mybatisplus.core.mapper.BaseMapper; - -/** - *

    - * Mapper 接口 - *

    - * - * @author liuxzh - * @since 2018-12-20 - */ -public interface SecUserMapper extends BaseMapper { - -} diff --git a/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/api/service/ISecUserService.java b/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/api/service/ISecUserService.java deleted file mode 100644 index 85ef344938..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/api/service/ISecUserService.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.snakerflow.demo.api.service; - -import com.snakerflow.demo.api.entity.SecUser; -import com.baomidou.mybatisplus.extension.service.IService; - -/** - *

    - * 服务类 - *

    - * - * @author liuxzh - * @since 2018-12-20 - */ -public interface ISecUserService extends IService { - -} diff --git a/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/api/service/IWorkflowService.java b/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/api/service/IWorkflowService.java deleted file mode 100644 index 14ae740e96..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/api/service/IWorkflowService.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.snakerflow.demo.api.service; - -public interface IWorkflowService { - public Integer deployWf(); -} - diff --git a/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/api/service/impl/SecUserServiceImpl.java b/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/api/service/impl/SecUserServiceImpl.java deleted file mode 100644 index d33a6fe0e5..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/api/service/impl/SecUserServiceImpl.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.snakerflow.demo.api.service.impl; - -import com.snakerflow.demo.api.entity.SecUser; -import com.snakerflow.demo.api.mapper.SecUserMapper; -import com.snakerflow.demo.api.service.ISecUserService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import org.springframework.stereotype.Service; - -/** - *

    - * 服务实现类 - *

    - * - * @author liuxzh - * @since 2018-12-20 - */ -@Service -public class SecUserServiceImpl extends ServiceImpl implements ISecUserService { - -} diff --git a/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/api/service/impl/WorkflowServiceImpl.java b/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/api/service/impl/WorkflowServiceImpl.java deleted file mode 100644 index 7acbdf6f45..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/api/service/impl/WorkflowServiceImpl.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.snakerflow.demo.api.service.impl; - -import com.snakerflow.demo.api.service.IWorkflowService; -import com.snakerflow.demo.utils.SnakerEngineFacadeImpl; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class WorkflowServiceImpl implements IWorkflowService { - @Autowired - private SnakerEngineFacadeImpl snakerEngineFacade; - @Override - public Integer deployWf() { - - return null; - } -} diff --git a/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/generator/CodeGenerator.java b/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/generator/CodeGenerator.java deleted file mode 100644 index 5fb8d3f542..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/generator/CodeGenerator.java +++ /dev/null @@ -1,158 +0,0 @@ -package com.snakerflow.demo.generator; - -import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException; -import com.baomidou.mybatisplus.core.toolkit.StringPool; -import com.baomidou.mybatisplus.core.toolkit.StringUtils; -import com.baomidou.mybatisplus.generator.AutoGenerator; -import com.baomidou.mybatisplus.generator.InjectionConfig; -import com.baomidou.mybatisplus.generator.config.*; -import com.baomidou.mybatisplus.generator.config.po.TableInfo; -import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; -import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; - -import java.util.ArrayList; -import java.util.List; -import java.util.Scanner; - -// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中 -public class CodeGenerator { - - /** - *

    - * 读取控制台内容 - *

    - */ - public static String scanner(String tip) { - Scanner scanner = new Scanner(System.in); - StringBuilder help = new StringBuilder(); - help.append("请输入" + tip + ":"); - System.out.println(help.toString()); - if (scanner.hasNext()) { - String ipt = scanner.next(); - if (StringUtils.isNotEmpty(ipt)) { - return ipt; - } - } - throw new MybatisPlusException("请输入正确的" + tip + "!"); - } - - public static void main(String[] args) { - // 代码生成器 - AutoGenerator mpg = new AutoGenerator(); - - // 全局配置 - GlobalConfig gc = new GlobalConfig(); - //当前工程路径 - final String projectPath = System.getProperty("user.dir"); - gc.setOutputDir(projectPath + "/src/main/java");//生成文件的输出目录【默认 D 盘根目录】 - gc.setAuthor("liuxzh");//开发人员 - gc.setOpen(false);//是否打开输出目录 - gc.setFileOverride(false);// 是否覆盖已有同名文件,默认是false - gc.setActiveRecord(true);// 开启 ActiveRecord 模式,默认是false - gc.setEnableCache(false);// 是否在xml中添加二级缓存配置,默认是false - gc.setBaseResultMap(true);// 开启 BaseResultMap,默认是false - gc.setBaseColumnList(true);// 开启 baseColumnList,默认是false - /* - * 各层文件名称方式,例如: %sAction 生成 UserAction - * %s 为占位符,注意 %s 会自动填充表实体属性! - */ - //gc.setMapperName("%sDao");//默认UserMapper.xml - //gc.setXmlName("%sDao");//默认UserMapper.xml - //gc.setServiceName("MP%sService");//默认IUserService.java - //gc.setServiceImplName("%sServiceDiy");//默认UserServiceImpl.java - //gc.setControllerName("%sAction");//默认UserController.java - mpg.setGlobalConfig(gc); - - // 数据源配置 - DataSourceConfig dsc = new DataSourceConfig(); - dsc.setUrl("jdbc:mysql://127.0.0.1:3306/snaker-web?useUnicode=true&useSSL=false&characterEncoding=utf8"); - //dsc.setSchemaName("public");//PostgreSQL schemaName - dsc.setDriverName("com.mysql.jdbc.Driver"); - dsc.setUsername("root"); - dsc.setPassword("123456"); - mpg.setDataSource(dsc); - - // 包配置 - final PackageConfig pc = new PackageConfig(); - pc.setModuleName(scanner("模块名"));//父包模块名,默认null - //父包名。如果为空,将下面子包名必须写全部, 否则就只需写子包名 - pc.setParent("com.snakerflow.demo");//默认com.baomidou - //pc.setController("liuxzhController");//默认controller - //pc.setService("liuxzhService");//默认service - //pc.setServiceImpl("liuxzhService.impl");//默认service.impl - //pc.setEntity("liuxzhEntity");//默认entity - //pc.setMapper("liuxzhMapper");//默认mapper - //pc.setXml("liuxzhMapper.xml");//默认mapper.xml - mpg.setPackageInfo(pc); - - // 自定义配置 - InjectionConfig cfg = new InjectionConfig() { - @Override - public void initMap() { - // to do nothing - } - }; - - // 如果模板引擎是 freemarker - String templatePath = "/templates/mapper.xml.ftl"; - // 如果模板引擎是 velocity -// String templatePath = "/templates/mapper.xml.vm"; - - // 自定义输出配置 - List focList = new ArrayList<>(); - // 自定义配置会被优先输出 - focList.add(new FileOutConfig(templatePath) { - @Override - public String outputFile(TableInfo tableInfo) { - // 自定义输出文件名 - return projectPath + "/src/main/resources/mapper/" + pc.getModuleName() - + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; - } - }); - - cfg.setFileOutConfigList(focList); - mpg.setCfg(cfg); - - // 配置模板 - TemplateConfig templateConfig = new TemplateConfig(); - - // 配置自定义输出模板 - // templateConfig.setEntity(); - // templateConfig.setService(); - // templateConfig.setController(); - - templateConfig.setXml(null); - mpg.setTemplate(templateConfig); - - // 策略配置 - StrategyConfig strategy = new StrategyConfig(); - //数据库表映射到实体的命名策略,默认:不做任何改变,原样输出 - strategy.setNaming(NamingStrategy.underline_to_camel); - //数据库表字段映射到实体的命名策略,未指定按照 naming 执行 - strategy.setColumnNaming(NamingStrategy.underline_to_camel); - //【实体】是否为lombok模型(默认 false) - //strategy.setEntityLombokModel(true); - //生成@RestController 控制器 - strategy.setRestControllerStyle(true); - //自定义继承的Controller类全称,带包名 - //strategy.setSuperControllerClass("com.mybatisplus.demo.common.BaseController"); - //strategy.setSuperServiceClass(); - //strategy.setSuperServiceImplClass(); - //strategy.setSuperMapperClass("com.mybatisplus.demo.common.BaseMapper"); - //strategy.setSuperEntityClass("com.mybatisplus.demo.common.BaseEntity");//自定义继承的Entity类全称,带包名 - - strategy.setInclude(scanner("表名"));//表明String数组 - strategy.setSuperEntityColumns("id"); - // 驼峰转连字符: - // @RequestMapping("/managerUserActionHistory")-->@RequestMapping("/manager-user-action-history") - strategy.setControllerMappingHyphenStyle(false); - strategy.setTablePrefix(pc.getModuleName() + "_");//表前缀 - - mpg.setStrategy(strategy);//数据库表配置 - mpg.setTemplateEngine(new FreemarkerTemplateEngine());// 选择 freemarker 引擎,默认 Veloctiy - - //生成代码 - mpg.execute(); - } - -} diff --git a/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/utils/ResponseData.java b/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/utils/ResponseData.java deleted file mode 100644 index 62534bf633..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/utils/ResponseData.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * @(#)ResponseData.java - * Copyright (C) 2018 Neusoft Corporation All rights reserved. - * - * VERSION DATE BY CHANGE/COMMENT - * ---------------------------------------------------------------------------- - * @version 1.00 2018-03-21 liubsh 初版 - * - */ - -package com.snakerflow.demo.utils; - -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.HttpServletResponse; - -/** - * TODO 类型描述。 - * - * @since inkstone-project-web v1.0 - * @version 1.00 - * @author liubsh - */ -public class ResponseData { - - public static final String ERRORS_KEY = "errors"; - - private final String message; - private final int code; - private final Map body = new HashMap<>(); - - public String getMessage() { - return message; - } - - public int getCode() { - return code; - } - - public Map getBody() { - return body; - } - - public ResponseData putDataValue(String key, Object value) { - body.put(key, value); - return this; - } - - private ResponseData(int code, String message) { - this.code = code; - this.message = message; - } - - /** - * TODO 方法说明。 - * [GET]:服务器成功返回用户请求的数据,该操作是幂等的(Idempotent)。 - * @return - */ - public static ResponseData ok() { - return new ResponseData(200, "OK"); - } - - /** - * TODO 方法说明。 - * [POST/PUT/PATCH]:用户新建或修改数据成功。 - * @return - */ - public static ResponseData createdOrUpdate() { - return new ResponseData(201, "CREATED"); - } - - /** - * TODO 方法说明。 - * [*]:表示一个请求已经进入后台排队(异步任务) - * @return - */ - public static ResponseData acceptedRequest() { - return new ResponseData(202, "Accepted"); - } - - /** - * TODO 方法说明。 - * [DELETE]:用户删除数据成功。 - * @return - */ - public static ResponseData deleteOk() { - return new ResponseData(204, "NO CONTENT"); - } - - /** - * TODO 方法说明。 - * 未授权访问,表示用户没有权限(令牌、用户名、密码错误) - * @return - */ - public static ResponseData unauthorized() { - return new ResponseData(401, "未授权访问!"); - } - - /** - * TODO 方法说明。 - * 越权访问,没有修改资源的访问权限 - * @return - */ - public static ResponseData outOfBounds() { - return new ResponseData(403, "您没有改资源的访问权限!"); - } - - - /** - * TODO 方法说明。 - * 没有找到对象 - * @return - */ - public static ResponseData notFound() { - return new ResponseData(404, "not found"); - } - - /** - * TODO 方法说明。 - * 方法错误 - * @return - */ - public static ResponseData serverInternalError() { - return new ResponseData(500, "Server Internal Error"); - } - - public static void setResponse(HttpServletResponse response){ - response.setContentType("application/json;charset=UTF-8"); - response.setHeader("Pragma", "No-cache"); - response.setHeader("Cache-Control", "no-cache"); - response.setDateHeader("Expires", 0); - response.setHeader("Access-Control-Allow-Origin", "*"); - response.setHeader("access-control-allow-methods", "POST, GET,HEAD, OPTIONS,PATCH, DELETE"); - response.setHeader("Access-Control-Max-Age", "3600"); - response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization"); - response.setHeader("access-control-allow-credentials", "true"); - } - - - /* - * 调用实例 - * @GetMapping - * @ResponseBody - * public Map index() { - * - * Map response = new HashMap<>(); - * response.put("code", 200); - * response.put("message", "Ok"); - * response.put("body", new HashMap()); - * return response; - * } - * - * @GetMapping("/test_response_data") - * @ResponseBody - * public ResponseData testResponseData() { - * - * return ResponseData.ok().putDataValue("token", "XXXXXXXXXXXXXXXXXXXXXXX"); - * - * } - * - */ - -} diff --git a/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/utils/SnakerEngineFacade.java b/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/utils/SnakerEngineFacade.java deleted file mode 100644 index 74d77e2552..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/utils/SnakerEngineFacade.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.snakerflow.demo.utils; - -import org.snaker.engine.access.Page; -import org.snaker.engine.access.QueryFilter; -import org.snaker.engine.entity.Order; -import org.snaker.engine.entity.Surrogate; -import org.snaker.engine.entity.Task; - -import java.util.List; -import java.util.Map; - -public interface SnakerEngineFacade { - public String deploy(String resourcesPath); - /** - * 得到所有流程定义的名称 - * - * @return - */ - public List getAllProcessNames(); - - public Order startInstanceById(String processId, String operator, Map args); - - public Order startInstanceByName(String name, Integer version, String operator, Map args); - - public Order startAndExecute(String name, Integer version, String operator, Map args); - - public Order startAndExecute(String processId, String operator, Map args); - - public List execute(String taskId, String operator, Map args); - - public List executeAndJump(String taskId, String operator, Map args, String nodeName); - - public List transferMajor(String taskId, String operator, String... actors); - - public List transferAidant(String taskId, String operator, String... actors); - - public Map flowData(String orderId, String taskName); - - public void addSurrogate(Surrogate entity) ; - - public void deleteSurrogate(String id); - - public Surrogate getSurrogate(String id); - - public List searchSurrogate(Page page, QueryFilter filter); - -} \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/utils/SnakerEngineFacadeImpl.java b/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/utils/SnakerEngineFacadeImpl.java deleted file mode 100644 index daa36c967a..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/java/com/snakerflow/demo/utils/SnakerEngineFacadeImpl.java +++ /dev/null @@ -1,170 +0,0 @@ -package com.snakerflow.demo.utils; -/* Copyright 2013-2015 www.snakerflow.com - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -import org.apache.commons.lang.StringUtils; -import org.snaker.engine.IProcessService; -import org.snaker.engine.SnakerEngine; -import org.snaker.engine.access.Page; -import org.snaker.engine.access.QueryFilter; -import org.snaker.engine.entity.*; -import org.snaker.engine.entity.Process; -import org.snaker.engine.helper.StreamHelper; -import org.snaker.engine.model.TaskModel.TaskType; -import org.springframework.beans.factory.InitializingBean; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * @Component(把普通pojo实例化到spring容器中,相当于配置文件中的 ) - * - */ -@Component("SnakerEngineFacade") -public class SnakerEngineFacadeImpl implements SnakerEngineFacade, InitializingBean { - - @Autowired - private SnakerEngine engine; - - private IProcessService process; - - public SnakerEngine getEngine() { - return engine; - } - @Override - public void afterPropertiesSet() throws Exception { - process = engine.process(); - } - - public IProcessService getProcess() { - return process; - } - - @Override - public String deploy(String resourcesPath) { - String processId = process.deploy(StreamHelper - .getStreamFromClasspath(resourcesPath)); - return processId; - } - - /** - * 得到所有流程定义的名称 - * - * @return - */ - public List getAllProcessNames() { - List list = engine.process().getProcesss(new QueryFilter()); - List names = new ArrayList(); - for (Process entity : list) { - if (names.contains(entity.getName())) { - continue; - } else { - names.add(entity.getName()); - } - } - return names; - } - - public Order startInstanceById(String processId, String operator, Map args) { - return engine.startInstanceById(processId, operator, args); - } - - public Order startInstanceByName(String name, Integer version, String operator, Map args) { - return engine.startInstanceByName(name, version, operator, args); - } - - public Order startAndExecute(String name, Integer version, String operator, Map args) { - Order order = engine.startInstanceByName(name, version, operator, args); - List tasks = engine.query().getActiveTasks(new QueryFilter().setOrderId(order.getId())); - List newTasks = new ArrayList(); - if (tasks != null && tasks.size() > 0) { - Task task = tasks.get(0); - newTasks.addAll(engine.executeTask(task.getId(), operator, args)); - } - return order; - } - - public Order startAndExecute(String processId, String operator, Map args) { - Order order = engine.startInstanceById(processId, operator, args); - List tasks = engine.query().getActiveTasks(new QueryFilter().setOrderId(order.getId())); - List newTasks = new ArrayList(); - if (tasks != null && tasks.size() > 0) { - Task task = tasks.get(0); - newTasks.addAll(engine.executeTask(task.getId(), operator, args)); - } - return order; - } - - public List execute(String taskId, String operator, Map args) { - return engine.executeTask(taskId, operator, args); - } - - public List executeAndJump(String taskId, String operator, Map args, String nodeName) { - return engine.executeAndJumpTask(taskId, operator, args, nodeName); - } - - public List transferMajor(String taskId, String operator, String... actors) { - List tasks = engine.task().createNewTask(taskId, TaskType.Major.ordinal(), actors); - engine.task().complete(taskId, operator); - return tasks; - } - - public List transferAidant(String taskId, String operator, String... actors) { - List tasks = engine.task().createNewTask(taskId, TaskType.Aidant.ordinal(), actors); - engine.task().complete(taskId, operator); - return tasks; - } - - public Map flowData(String orderId, String taskName) { - Map data = new HashMap(); - if (StringUtils.isNotEmpty(orderId) && StringUtils.isNotEmpty(taskName)) { - List histTasks = engine.query() - .getHistoryTasks( - new QueryFilter().setOrderId(orderId).setName( - taskName)); - List> vars = new ArrayList>(); - for (HistoryTask hist : histTasks) { - vars.add(hist.getVariableMap()); - } - data.put("vars", vars); - data.put("histTasks", histTasks); - } - return data; - } - - public void addSurrogate(Surrogate entity) { - if (entity.getState() == null) { - entity.setState(1); - } - engine.manager().saveOrUpdate(entity); - } - - public void deleteSurrogate(String id) { - engine.manager().deleteSurrogate(id); - } - - public Surrogate getSurrogate(String id) { - return engine.manager().getSurrogate(id); - } - - public List searchSurrogate(Page page, QueryFilter filter) { - return engine.manager().getSurrogate(page, filter); - } -} diff --git a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/develop/application.properties b/jun_springboot_plugin/springboot_snaker/src/main/resources/config/develop/application.properties deleted file mode 100644 index ded81da4b8..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/develop/application.properties +++ /dev/null @@ -1,17 +0,0 @@ -#debug=true -spring.datasource.url = jdbc:mysql://localhost:3306/snaker-web?useUnicode=true&characterEncoding=utf-8 -spring.datasource.username = root -spring.datasource.password = 123456 -spring.datasource.driverClassName = com.mysql.jdbc.Driver -spring.datasource.max-active=40 -spring.datasource.max-idle=8 -spring.datasource.min-idle=8 -spring.datasource.initial-size=10 - -#ȲЧ -spring.devtools.restart.enabled=true -#Ŀ¼ -spring.devtools.restart.additional-paths=src/main/java - -#TODO ģļ(Զ壩 -snaker.workflow.model.path=snakerflow/examination.snaker diff --git a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/develop/applicationContext.xml b/jun_springboot_plugin/springboot_snaker/src/main/resources/config/develop/applicationContext.xml deleted file mode 100644 index 0f6416c92d..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/develop/applicationContext.xml +++ /dev/null @@ -1,140 +0,0 @@ - - - - Spring公共配置 - - - - - - - - - - classpath*:/application.properties - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/develop/mybatis.cfg.xml b/jun_springboot_plugin/springboot_snaker/src/main/resources/config/develop/mybatis.cfg.xml deleted file mode 100644 index d3537e52f7..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/develop/mybatis.cfg.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/develop/snaker.properties b/jun_springboot_plugin/springboot_snaker/src/main/resources/config/develop/snaker.properties deleted file mode 100644 index cc1a8a52ff..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/develop/snaker.properties +++ /dev/null @@ -1,3 +0,0 @@ -#page must config -jdbc.pageSize=15 -#subprocessurl=snaker/subprocess/view \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/local/application.properties b/jun_springboot_plugin/springboot_snaker/src/main/resources/config/local/application.properties deleted file mode 100644 index ded81da4b8..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/local/application.properties +++ /dev/null @@ -1,17 +0,0 @@ -#debug=true -spring.datasource.url = jdbc:mysql://localhost:3306/snaker-web?useUnicode=true&characterEncoding=utf-8 -spring.datasource.username = root -spring.datasource.password = 123456 -spring.datasource.driverClassName = com.mysql.jdbc.Driver -spring.datasource.max-active=40 -spring.datasource.max-idle=8 -spring.datasource.min-idle=8 -spring.datasource.initial-size=10 - -#ȲЧ -spring.devtools.restart.enabled=true -#Ŀ¼ -spring.devtools.restart.additional-paths=src/main/java - -#TODO ģļ(Զ壩 -snaker.workflow.model.path=snakerflow/examination.snaker diff --git a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/local/applicationContext.xml b/jun_springboot_plugin/springboot_snaker/src/main/resources/config/local/applicationContext.xml deleted file mode 100644 index 0f6416c92d..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/local/applicationContext.xml +++ /dev/null @@ -1,140 +0,0 @@ - - - - Spring公共配置 - - - - - - - - - - classpath*:/application.properties - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/local/mybatis.cfg.xml b/jun_springboot_plugin/springboot_snaker/src/main/resources/config/local/mybatis.cfg.xml deleted file mode 100644 index d3537e52f7..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/local/mybatis.cfg.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/local/snaker.properties b/jun_springboot_plugin/springboot_snaker/src/main/resources/config/local/snaker.properties deleted file mode 100644 index cc1a8a52ff..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/local/snaker.properties +++ /dev/null @@ -1,3 +0,0 @@ -#page must config -jdbc.pageSize=15 -#subprocessurl=snaker/subprocess/view \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/preview/application.properties b/jun_springboot_plugin/springboot_snaker/src/main/resources/config/preview/application.properties deleted file mode 100644 index ded81da4b8..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/preview/application.properties +++ /dev/null @@ -1,17 +0,0 @@ -#debug=true -spring.datasource.url = jdbc:mysql://localhost:3306/snaker-web?useUnicode=true&characterEncoding=utf-8 -spring.datasource.username = root -spring.datasource.password = 123456 -spring.datasource.driverClassName = com.mysql.jdbc.Driver -spring.datasource.max-active=40 -spring.datasource.max-idle=8 -spring.datasource.min-idle=8 -spring.datasource.initial-size=10 - -#ȲЧ -spring.devtools.restart.enabled=true -#Ŀ¼ -spring.devtools.restart.additional-paths=src/main/java - -#TODO ģļ(Զ壩 -snaker.workflow.model.path=snakerflow/examination.snaker diff --git a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/preview/applicationContext.xml b/jun_springboot_plugin/springboot_snaker/src/main/resources/config/preview/applicationContext.xml deleted file mode 100644 index 0f6416c92d..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/preview/applicationContext.xml +++ /dev/null @@ -1,140 +0,0 @@ - - - - Spring公共配置 - - - - - - - - - - classpath*:/application.properties - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/preview/mybatis.cfg.xml b/jun_springboot_plugin/springboot_snaker/src/main/resources/config/preview/mybatis.cfg.xml deleted file mode 100644 index d3537e52f7..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/preview/mybatis.cfg.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/preview/snaker.properties b/jun_springboot_plugin/springboot_snaker/src/main/resources/config/preview/snaker.properties deleted file mode 100644 index cc1a8a52ff..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/preview/snaker.properties +++ /dev/null @@ -1,3 +0,0 @@ -#page must config -jdbc.pageSize=15 -#subprocessurl=snaker/subprocess/view \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/release/application.properties b/jun_springboot_plugin/springboot_snaker/src/main/resources/config/release/application.properties deleted file mode 100644 index ded81da4b8..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/release/application.properties +++ /dev/null @@ -1,17 +0,0 @@ -#debug=true -spring.datasource.url = jdbc:mysql://localhost:3306/snaker-web?useUnicode=true&characterEncoding=utf-8 -spring.datasource.username = root -spring.datasource.password = 123456 -spring.datasource.driverClassName = com.mysql.jdbc.Driver -spring.datasource.max-active=40 -spring.datasource.max-idle=8 -spring.datasource.min-idle=8 -spring.datasource.initial-size=10 - -#ȲЧ -spring.devtools.restart.enabled=true -#Ŀ¼ -spring.devtools.restart.additional-paths=src/main/java - -#TODO ģļ(Զ壩 -snaker.workflow.model.path=snakerflow/examination.snaker diff --git a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/release/applicationContext.xml b/jun_springboot_plugin/springboot_snaker/src/main/resources/config/release/applicationContext.xml deleted file mode 100644 index 0f6416c92d..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/release/applicationContext.xml +++ /dev/null @@ -1,140 +0,0 @@ - - - - Spring公共配置 - - - - - - - - - - classpath*:/application.properties - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/release/mybatis.cfg.xml b/jun_springboot_plugin/springboot_snaker/src/main/resources/config/release/mybatis.cfg.xml deleted file mode 100644 index d3537e52f7..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/release/mybatis.cfg.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/release/snaker.properties b/jun_springboot_plugin/springboot_snaker/src/main/resources/config/release/snaker.properties deleted file mode 100644 index cc1a8a52ff..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/release/snaker.properties +++ /dev/null @@ -1,3 +0,0 @@ -#page must config -jdbc.pageSize=15 -#subprocessurl=snaker/subprocess/view \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/test/application.properties b/jun_springboot_plugin/springboot_snaker/src/main/resources/config/test/application.properties deleted file mode 100644 index ded81da4b8..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/test/application.properties +++ /dev/null @@ -1,17 +0,0 @@ -#debug=true -spring.datasource.url = jdbc:mysql://localhost:3306/snaker-web?useUnicode=true&characterEncoding=utf-8 -spring.datasource.username = root -spring.datasource.password = 123456 -spring.datasource.driverClassName = com.mysql.jdbc.Driver -spring.datasource.max-active=40 -spring.datasource.max-idle=8 -spring.datasource.min-idle=8 -spring.datasource.initial-size=10 - -#ȲЧ -spring.devtools.restart.enabled=true -#Ŀ¼ -spring.devtools.restart.additional-paths=src/main/java - -#TODO ģļ(Զ壩 -snaker.workflow.model.path=snakerflow/examination.snaker diff --git a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/test/applicationContext.xml b/jun_springboot_plugin/springboot_snaker/src/main/resources/config/test/applicationContext.xml deleted file mode 100644 index 0f6416c92d..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/test/applicationContext.xml +++ /dev/null @@ -1,140 +0,0 @@ - - - - Spring公共配置 - - - - - - - - - - classpath*:/application.properties - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/test/mybatis.cfg.xml b/jun_springboot_plugin/springboot_snaker/src/main/resources/config/test/mybatis.cfg.xml deleted file mode 100644 index d3537e52f7..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/test/mybatis.cfg.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/test/snaker.properties b/jun_springboot_plugin/springboot_snaker/src/main/resources/config/test/snaker.properties deleted file mode 100644 index cc1a8a52ff..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/resources/config/test/snaker.properties +++ /dev/null @@ -1,3 +0,0 @@ -#page must config -jdbc.pageSize=15 -#subprocessurl=snaker/subprocess/view \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_snaker/src/main/resources/mapper/api/SecUserMapper.xml b/jun_springboot_plugin/springboot_snaker/src/main/resources/mapper/api/SecUserMapper.xml deleted file mode 100644 index 37072449cd..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/resources/mapper/api/SecUserMapper.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - id, - address, age, email, enabled, fullname, password, plainPassword, salt, sex, type, username, org - - - diff --git a/jun_springboot_plugin/springboot_snaker/src/main/resources/snakerflow/examination.snaker b/jun_springboot_plugin/springboot_snaker/src/main/resources/snakerflow/examination.snaker deleted file mode 100644 index 3c804ff50d..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/resources/snakerflow/examination.snaker +++ /dev/null @@ -1,72 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/jun_springboot_plugin/springboot_snaker/src/main/resources/temp/application.properties b/jun_springboot_plugin/springboot_snaker/src/main/resources/temp/application.properties deleted file mode 100644 index f283f7e941..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/resources/temp/application.properties +++ /dev/null @@ -1,27 +0,0 @@ -##mysql version database setting -#jdbc.driver=com.mysql.jdbc.Driver -#jdbc.url=jdbc:mysql://localhost:3306/snaker-web?useUnicode=true&characterEncoding=utf-8 -#jdbc.username=root -#jdbc.password=123456 -##dbcp settings -#dbcp.maxIdle=5 -#dbcp.maxActive=40 - -#debug=true -spring.datasource.url = jdbc:mysql://localhost:3306/snaker-web?useUnicode=true&characterEncoding=utf-8 -spring.datasource.username = root -spring.datasource.password = 123456 -spring.datasource.driverClassName = com.mysql.jdbc.Driver -spring.datasource.max-active=40 -spring.datasource.max-idle=8 -spring.datasource.min-idle=8 -spring.datasource.initial-size=10 -#snakerģ·(Զ壩 -snaker.workflow.model.path=snakerflow/examination.snaker - -#ȲЧ -spring.devtools.remote.restart.enabled=true -#Ŀ¼ -#spring.devtools.restart.additional-paths: src/main/java -#classpathĿ¼µWEB-INFļ޸IJ -spring.devtools.restart.additional-exclude=: WEB-INF/** diff --git a/jun_springboot_plugin/springboot_snaker/src/main/resources/temp/applicationContext-snaker.xml b/jun_springboot_plugin/springboot_snaker/src/main/resources/temp/applicationContext-snaker.xml deleted file mode 100644 index dea6d521cb..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/resources/temp/applicationContext-snaker.xml +++ /dev/null @@ -1,61 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_snaker/src/main/resources/temp/applicationContext.xml b/jun_springboot_plugin/springboot_snaker/src/main/resources/temp/applicationContext.xml deleted file mode 100644 index cc0fe93734..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/resources/temp/applicationContext.xml +++ /dev/null @@ -1,123 +0,0 @@ - - - - Spring公共配置 - - - - - - - - - - classpath*:/application.properties - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_snaker/src/main/resources/temp/mybatis.cfg.xml b/jun_springboot_plugin/springboot_snaker/src/main/resources/temp/mybatis.cfg.xml deleted file mode 100644 index 1d13db4195..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/resources/temp/mybatis.cfg.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_snaker/src/main/resources/temp/snaker.properties b/jun_springboot_plugin/springboot_snaker/src/main/resources/temp/snaker.properties deleted file mode 100644 index cc1a8a52ff..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/main/resources/temp/snaker.properties +++ /dev/null @@ -1,3 +0,0 @@ -#page must config -jdbc.pageSize=15 -#subprocessurl=snaker/subprocess/view \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_snaker/src/test/java/com/snakerflow/demo/DemoApplicationTests.java b/jun_springboot_plugin/springboot_snaker/src/test/java/com/snakerflow/demo/DemoApplicationTests.java deleted file mode 100644 index 42a96caae8..0000000000 --- a/jun_springboot_plugin/springboot_snaker/src/test/java/com/snakerflow/demo/DemoApplicationTests.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.snakerflow.demo; - -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 DemoApplicationTests { - - @Test - public void contextLoads() { - } - -} - diff --git a/jun_springboot_plugin/springboot_socketio/.gitignore b/jun_springboot_plugin/springboot_socketio/.gitignore deleted file mode 100644 index b71e0c47c1..0000000000 --- a/jun_springboot_plugin/springboot_socketio/.gitignore +++ /dev/null @@ -1,17 +0,0 @@ -# 此为注释– 将被Git 忽略 -# /结尾表示是目录,忽略目录和目录下的所有件 -# /开头表示根目录,否则是.gitignore的相对目录 -# !开头表示反选 -.idea/ -target/ -*.iml -*.ipr -*.iws -*.log -.svn/ -.project -rebel.xml -.rebel-remote.xml.* -swagger.json -swagger.adoc - diff --git a/jun_springboot_plugin/springboot_socketio/README.md b/jun_springboot_plugin/springboot_socketio/README.md deleted file mode 100644 index cd1b0985f4..0000000000 --- a/jun_springboot_plugin/springboot_socketio/README.md +++ /dev/null @@ -1,39 +0,0 @@ - -## 简介 - -在SpringBoot中有两种实现WebSocket实时通信的方式: - -1. 一个是使用WebSocket的一个子协议stomp -2. 另外一个是使用Socket.IO协议实现。 - -本项目演示如何通过Socket.IO协议实现 - -## WeSocket长连接 - -Socket.IO服务器端和客户端,使用Java语言实现,用于和浏览器或Android客户端进行长连接的WebSocket通信。 -服务器端可以实时将消息推送给客户端,以此来取代客户端轮询机制。 - -Sockt.io官网: - -服务器端使用 [netty-socketio](https://github.com/mrniko/netty-socketio) - -客户端使用 [socket.io-client-java](https://github.com/socketio/socket.io-client-java) - -### WebSocket js客户端测试 - -``` -/client/html/index.html -``` - -### WebSocket Java客户端测试 - -``` -com.xncoding.pos.socket.client.SocketClient -``` - -## 许可证 - -Copyright (c) 2018 Xiong Neng - -基于 MIT 协议发布: - diff --git a/jun_springboot_plugin/springboot_socketio/pom.xml b/jun_springboot_plugin/springboot_socketio/pom.xml deleted file mode 100644 index 21512a7a03..0000000000 --- a/jun_springboot_plugin/springboot_socketio/pom.xml +++ /dev/null @@ -1,135 +0,0 @@ - - - 4.0.0 - - io.github.wujun728 - springboot_socketio - 1.0 - jar - - 集成SocketIO实时通信 - - - org.springframework.boot - spring-boot-starter-parent - 2.5.14 - - - - UTF-8 - UTF-8 - 1.8 - 4.1.19.Final - - - - - org.springframework.boot - spring-boot-starter - - - - com.corundumstudio.socketio - netty-socketio - 1.7.13 - - - io.netty - netty-buffer - ${netty.version} - - - io.netty - netty-codec - ${netty.version} - - - io.netty - netty-codec-http - ${netty.version} - - - io.netty - netty-common - ${netty.version} - - - io.netty - netty-handler - ${netty.version} - - - io.netty - netty-resolver - ${netty.version} - - - io.netty - netty-transport - ${netty.version} - - - io.netty - netty-transport-native-epoll - ${netty.version} - - - io.netty - netty-transport-native-unix-common - ${netty.version} - - - io.socket - socket.io-client - 1.0.0 - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.6.1 - - - 1.8 - 1.8 - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.20 - - - ${project.basedir}/src/main/resources/swagger - ${project.basedir}/src/main/resources/swagger/swagger - - true - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - - - src/main/resources - - - src/main/java - - **/*.xml - - - - - - \ No newline at end of file diff --git a/jun_springboot_plugin/springboot_socketio/run.sh b/jun_springboot_plugin/springboot_socketio/run.sh deleted file mode 100644 index 955efb1f86..0000000000 --- a/jun_springboot_plugin/springboot_socketio/run.sh +++ /dev/null @@ -1,72 +0,0 @@ -#!/bin/bash -# 项目自动更新脚本 -# 先clone相应的分支下来: -# git clone ssh://git@120.24.173.142:7999/xxx.git -# 远程调试启动: -# nohup java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005 -Xms512m -Xmx1024m -jar -Dspring.profiles.active=${profile} ${jarfile} >/dev/null 2>&1 & - -function start { - profile="$1" - echo "启动环境profile=${profile}" - jarfile=$(ls target/*.jar) - if [[ "$?" == "0" ]]; then - stop $profile $jarfile - fi - branch=$(git branch |awk '{print $2}') - git pull origin ${branch} - echo "更新完代码开始重新打包" - mvn clean && mvn clean && mvn package -DskipTests=true - if [[ "$?" != "0" ]]; then - echo "编译出错,退出!" - exit 1 - fi - echo "nohup java -Xms512m -Xmx1024m -jar -Dspring.profiles.active=${profile} ${jarfile} >/dev/null 2>&1 &" - nohup java -Xms512m -Xmx1024m -jar -Dspring.profiles.active=${profile} ${jarfile} >/dev/null 2>&1 & - echo "启动应用中,请查看日志文件..." -} - -function stop { - profile="$1" - jarfile="$2" - ps aux | grep "${jarfile}" | grep "spring.profiles.active=${profile}" | grep -v grep > /dev/null - if [[ "$?" == "0" ]]; then - echo "该应用还在跑,我先停了它" - pid=$(ps aux | grep "${jarfile}" | grep "spring.profiles.active=${profile}" | grep -v grep |awk '{print $2}') - if [[ "$pid" != "" ]]; then - kill -9 $pid - fi - echo "停止应用成功..." - fi -} - -if [[ "$1" == "start" ]]; then - if [[ "$#" < 2 ]]; then - echo "请输入正确参数:./epay.sh start {profile}" - exit 1 - fi - profile="$2" - if [[ "$profile" != "dev" && "$profile" != "test" && "$profile" != "show" && "$profile" != "production" ]]; then - echo "参数错误,请输入正确的profile参数,使用方法:" - echo "./epay.sh start {profile} ==> 启动应用,{profile}取值:dev|test|show|production" - exit 1 - fi - start "${profile}" -elif [[ "$1" == "stop" ]]; then - if [[ "$#" < 2 ]]; then - echo "请输入正确参数:./epay.sh stop {profile}" - exit 1 - fi - profile="$2" - if [[ "$profile" != "dev" && "$profile" != "test" && "$profile" != "show" && "$profile" != "production" ]]; then - echo "参数错误,请输入正确的profile参数,使用方法:" - echo "./epay.sh stop {profile} ==> 停止应用,{profile}取值:dev|test|show|production" - exit 1 - fi - jarfile=$(ls target/*.jar) - stop $profile $jarfile -else - echo "参数错误,使用方法:{}参数是必填的,[]参数可选" - echo "./epay.sh start {profile} ==> 启动应用,{profile}取值:dev|test|show|production" - echo "./epay.sh stop {profile} ==> 停止应用,{profile}取值:dev|test|show|production" - exit 1 -fi diff --git a/jun_springboot_plugin/springboot_socketio/src/main/java/com/xncoding/jwt/Application.java b/jun_springboot_plugin/springboot_socketio/src/main/java/com/xncoding/jwt/Application.java deleted file mode 100644 index e180aef9b7..0000000000 --- a/jun_springboot_plugin/springboot_socketio/src/main/java/com/xncoding/jwt/Application.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.xncoding.jwt; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class Application { - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} diff --git a/jun_springboot_plugin/springboot_socketio/src/main/java/com/xncoding/jwt/common/JsonConverter.java b/jun_springboot_plugin/springboot_socketio/src/main/java/com/xncoding/jwt/common/JsonConverter.java deleted file mode 100644 index 07e3d9fa1a..0000000000 --- a/jun_springboot_plugin/springboot_socketio/src/main/java/com/xncoding/jwt/common/JsonConverter.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.xncoding.jwt.common; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.IOException; - -/** - * 对象和Json转换器 - * - * @author XiongNeng - * @version 1.0 - * @since 2018/1/18 - */ -public class JsonConverter { - public static JSONObject objectToJSONObject(Object object) { - try { - String jsonString = new ObjectMapper().writeValueAsString(object); - return new JSONObject(jsonString); - } catch (JSONException | JsonProcessingException e) { - e.printStackTrace(); - return null; - } - } - - public static JSONArray objectToJSONArray(Object object) { - try { - String jsonString = new ObjectMapper().writeValueAsString(object); - return new JSONArray(jsonString); - } catch (JSONException | JsonProcessingException e) { - e.printStackTrace(); - return null; - } - } - - public static T jsonObjectToObject(Object jsonObject, Class clazz) { - try { - // List listCar = objectMapper.readValue(jsonCarArray, new TypeReference>(){}); - return new ObjectMapper().readValue(jsonObject.toString(), clazz); - } catch (IOException e) { - return null; - } - } -} diff --git a/jun_springboot_plugin/springboot_socketio/src/main/java/com/xncoding/jwt/common/ServerRunner.java b/jun_springboot_plugin/springboot_socketio/src/main/java/com/xncoding/jwt/common/ServerRunner.java deleted file mode 100644 index 3fbe88c4ea..0000000000 --- a/jun_springboot_plugin/springboot_socketio/src/main/java/com/xncoding/jwt/common/ServerRunner.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.xncoding.jwt.common; - -import com.corundumstudio.socketio.SocketIOServer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.CommandLineRunner; -import org.springframework.core.annotation.Order; -import org.springframework.stereotype.Component; - -/** - * SpringBoot启动之后执行 - * - * @author XiongNeng - * @version 1.0 - * @since 2017/7/31 - */ -@Component -@Order(1) -public class ServerRunner implements CommandLineRunner { - private final SocketIOServer server; - private static final Logger logger = LoggerFactory.getLogger(ServerRunner.class); - - @Autowired - public ServerRunner(SocketIOServer server) { - this.server = server; - } - - @Override - public void run(String... args) { - logger.info("ServerRunner 开始启动啦..."); - server.start(); - } -} diff --git a/jun_springboot_plugin/springboot_socketio/src/main/java/com/xncoding/jwt/config/NettySocketConfig.java b/jun_springboot_plugin/springboot_socketio/src/main/java/com/xncoding/jwt/config/NettySocketConfig.java deleted file mode 100644 index 84767bc90e..0000000000 --- a/jun_springboot_plugin/springboot_socketio/src/main/java/com/xncoding/jwt/config/NettySocketConfig.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.xncoding.jwt.config; - -import com.corundumstudio.socketio.SocketIOServer; -import com.corundumstudio.socketio.annotation.SpringAnnotationScanner; -import com.xncoding.jwt.config.properties.MyProperties; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import javax.annotation.Resource; - -/** - * NettySocketConfig - * - * @author XiongNeng - * @version 1.0 - * @since 2018/1/19 - */ -@Configuration -public class NettySocketConfig { - - @Resource - private MyProperties myProperties; - - private static final Logger logger = LoggerFactory.getLogger(NettySocketConfig.class); - - @Bean - public SocketIOServer socketIOServer() { - /* - * 创建Socket,并设置监听端口 - */ - com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration(); - // 设置主机名,默认是0.0.0.0 - // config.setHostname("localhost"); - // 设置监听端口 - config.setPort(myProperties.getSocketPort()); - // 协议升级超时时间(毫秒),默认10000。HTTP握手升级为ws协议超时时间 - config.setUpgradeTimeout(10000); - // Ping消息间隔(毫秒),默认25000。客户端向服务器发送一条心跳消息间隔 - config.setPingInterval(myProperties.getPingInterval()); - // Ping消息超时时间(毫秒),默认60000,这个时间间隔内没有接收到心跳消息就会发送超时事件 - config.setPingTimeout(myProperties.getPingTimeout()); - // 握手协议参数使用JWT的Token认证方案 - config.setAuthorizationListener(data -> { - // 可以使用如下代码获取用户密码信息 - String token = data.getSingleUrlParam("token"); - return true; - }); - return new SocketIOServer(config); - } - - @Bean - public SpringAnnotationScanner springAnnotationScanner(SocketIOServer socketServer) { - return new SpringAnnotationScanner(socketServer); - } -} diff --git a/jun_springboot_plugin/springboot_socketio/src/main/java/com/xncoding/jwt/config/properties/MyProperties.java b/jun_springboot_plugin/springboot_socketio/src/main/java/com/xncoding/jwt/config/properties/MyProperties.java deleted file mode 100644 index 68bda9d191..0000000000 --- a/jun_springboot_plugin/springboot_socketio/src/main/java/com/xncoding/jwt/config/properties/MyProperties.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.xncoding.jwt.config.properties; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; - - -/** - * 本项目自定义配置 - * - * @author xiongneng - * @since 2018/01/06 21:09 - */ -@Component -@ConfigurationProperties(prefix = "xncoding") -public class MyProperties { - /** - * socket端口 - */ - private Integer socketPort; - /** - * Ping消息间隔(毫秒) - */ - private Integer pingInterval; - /** - * Ping消息超时时间(毫秒) - */ - private Integer pingTimeout; - /** - * APK文件访问URL前缀 - */ - private String apkUrlPrefix; - - public Integer getSocketPort() { - return socketPort; - } - - public void setSocketPort(Integer socketPort) { - this.socketPort = socketPort; - } - - public Integer getPingInterval() { - return pingInterval; - } - - public void setPingInterval(Integer pingInterval) { - this.pingInterval = pingInterval; - } - - public Integer getPingTimeout() { - return pingTimeout; - } - - public void setPingTimeout(Integer pingTimeout) { - this.pingTimeout = pingTimeout; - } - - public String getApkUrlPrefix() { - return apkUrlPrefix; - } - - public void setApkUrlPrefix(String apkUrlPrefix) { - this.apkUrlPrefix = apkUrlPrefix; - } -} diff --git a/jun_springboot_plugin/springboot_socketio/src/main/java/com/xncoding/jwt/handler/MessageEventHandler.java b/jun_springboot_plugin/springboot_socketio/src/main/java/com/xncoding/jwt/handler/MessageEventHandler.java deleted file mode 100644 index 2f302e0acb..0000000000 --- a/jun_springboot_plugin/springboot_socketio/src/main/java/com/xncoding/jwt/handler/MessageEventHandler.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.xncoding.jwt.handler; - -import com.corundumstudio.socketio.AckRequest; -import com.corundumstudio.socketio.SocketIOClient; -import com.corundumstudio.socketio.SocketIOServer; -import com.corundumstudio.socketio.annotation.OnConnect; -import com.corundumstudio.socketio.annotation.OnDisconnect; -import com.corundumstudio.socketio.annotation.OnEvent; -import com.xncoding.jwt.model.ChatMessage; -import com.xncoding.jwt.model.LoginRequest; -import io.socket.client.Socket; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -/** - * 消息事件处理器 - * - * @author XiongNeng - * @version 1.0 - * @since 2018/1/19 - */ -@Component -public class MessageEventHandler { - - private final SocketIOServer server; - - private static final Logger logger = LoggerFactory.getLogger(MessageEventHandler.class); - - @Autowired - public MessageEventHandler(SocketIOServer server) { - this.server = server; - } - - //添加connect事件,当客户端发起连接时调用 - @OnConnect - public void onConnect(SocketIOClient client) { - if (client != null) { - String username = client.getHandshakeData().getSingleUrlParam("username"); - String password = client.getHandshakeData().getSingleUrlParam("password"); - String sessionId = client.getSessionId().toString(); - logger.info("连接成功, username=" + username + ", password=" + password + ", sessionId=" + sessionId); - } else { - logger.error("客户端为空"); - } - } - - //添加@OnDisconnect事件,客户端断开连接时调用,刷新客户端信息 - @OnDisconnect - public void onDisconnect(SocketIOClient client) { - logger.info("客户端断开连接, sessionId=" + client.getSessionId().toString()); - client.disconnect(); - } - - // 消息接收入口 - @OnEvent(value = "chatevent") - public void onEvent(SocketIOClient client, AckRequest ackRequest, ChatMessage chat) { - logger.info("接收到客户端消息"); - if (ackRequest.isAckRequested()) { - // send ack response with data to client - ackRequest.sendAckData("服务器回答chatevent, userName=" + chat.getUserName() + ",message=" + chat.getMessage()); - } - } - - // 登录接口 - @OnEvent(value = "login") - public void onLogin(SocketIOClient client, AckRequest ackRequest, LoginRequest message) { - logger.info("接收到客户端登录消息"); - if (ackRequest.isAckRequested()) { - // send ack response with data to client - ackRequest.sendAckData("服务器回答login", message.getCode(), message.getBody()); - } - } -} diff --git a/jun_springboot_plugin/springboot_socketio/src/main/java/com/xncoding/jwt/model/ChatMessage.java b/jun_springboot_plugin/springboot_socketio/src/main/java/com/xncoding/jwt/model/ChatMessage.java deleted file mode 100644 index e67541e6c1..0000000000 --- a/jun_springboot_plugin/springboot_socketio/src/main/java/com/xncoding/jwt/model/ChatMessage.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.xncoding.jwt.model; - -/** - * ChatMessage - * - * @author XiongNeng - * @version 1.0 - * @since 2018/1/30 - */ -public class ChatMessage { - private String userName; - private String message; - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } -} diff --git a/jun_springboot_plugin/springboot_socketio/src/main/java/com/xncoding/jwt/model/LoginRequest.java b/jun_springboot_plugin/springboot_socketio/src/main/java/com/xncoding/jwt/model/LoginRequest.java deleted file mode 100644 index 2c31b59050..0000000000 --- a/jun_springboot_plugin/springboot_socketio/src/main/java/com/xncoding/jwt/model/LoginRequest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.xncoding.jwt.model; - -import java.io.Serializable; - -/** - * LoginRequest - * - * @author XiongNeng - * @version 1.0 - * @since 2018/1/18 - */ -public class LoginRequest implements Serializable { - private int code; - private String body; - - public LoginRequest() { - } - - public LoginRequest(int code, String body) { - super(); - this.code = code; - this.body = body; - } - - public int getCode() { - return code; - } - - public void setCode(int code) { - this.code = code; - } - - public String getBody() { - return body; - } - - public void setBody(String body) { - this.body = body; - } -} diff --git a/jun_springboot_plugin/springboot_socketio/src/main/resources/application.yml b/jun_springboot_plugin/springboot_socketio/src/main/resources/application.yml deleted file mode 100644 index 64c456f47b..0000000000 --- a/jun_springboot_plugin/springboot_socketio/src/main/resources/application.yml +++ /dev/null @@ -1,29 +0,0 @@ -########################################################## -################## 所有profile共有的配置 ################# -########################################################## - -################### 自定义项目配置 ################### -xncoding: - socket-port: 9099 #socket端口 - ping-interval: 60000 #Ping消息间隔(毫秒) - ping-timeout: 180000 #Ping消息超时时间(毫秒) - -################### spring配置 ################### -spring: - profiles: - active: dev - ---- - -##################################################################### -######################## 开发环境profile ########################## -##################################################################### -spring: - profiles: dev - -logging: - level: - ROOT: INFO - com: - xncoding: DEBUG - file: D:/logs/app.log diff --git a/jun_springboot_plugin/springboot_socketio/src/main/resources/banner.txt b/jun_springboot_plugin/springboot_socketio/src/main/resources/banner.txt deleted file mode 100644 index 2e697237e8..0000000000 --- a/jun_springboot_plugin/springboot_socketio/src/main/resources/banner.txt +++ /dev/null @@ -1,139 +0,0 @@ - :: :.:..... : ....: ..: ..: : : :..: ..:...:.... :..........:.... .:.: : :.::..:.:......:.:..: : :...:..:::..::.:::::::..::.:::::.::::::::::::::::::::::::::::::::::::::::::;:::::: -.::.:.:::...: ::.:.:.:.:::.::::.::.:.:.:::.:.:.::::.::::.:::.::.:.:.:::::::::::::::.::::::::::::::::::::.:::.:::::::::::::::::::::::;:;:;;;:;;:;:i::::;;,;,,;::;,i;:i;,;:;,;;,;;i:;: -::.::: :::::::::::::::::.:::::::::::::::.:::::::::::::.::::::::::::::::::::::::::::::::::::::::::::::::::::::::::;;:;;:::::;::::::ii,;,ii,,;,,:ii:ii,;::i:ii:i;,;;,i:,;,:i:::;,,;,,: -::::.::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::;:::;;:::::::::::::::::;::::::;::::::::;:::;::::::i:,;:::;,;:;i:;,,;i;i:i,;,;,:,;,::,;;,;,:,;:;,,;i:;,;::i:,;,,;:;, -:;;:;;:,i:,;:;::i:i:;:,;,,ii,,:;;,:i,;,,;,,i:,:::;:i::,;::,;,:,::i;,;::;:::::,:;:,::::,::i;:,::::::,:,:,,:ii:i::i:,;,;,:::;:;:;i:i;ii:i;,i;,;:::,:,::,::i:i:,::;,i,;ii;,,::;,:::i:i: -;ii:,:,;;,;,,:,:;,:,:,::ii;,;:i::;::,:::::::;::,;:,;,:i:,;:::;:i::::::::::::::;,;,;;:::;:::::,::;:::::;,:i::i:;,::::;::::::,::,:i:iiiiiiiiii::i:::;:;:::::::;::i:,;i,i:i:i:,;::::::: -,;;:;,;::;:::;:i::::::,;::i:i;::::,::;,::::,:::::;:i::;,:::;iifffjiii;i:::::i:,;;:,,:::,::::::::::::::::;,;;,;:;:,;,:;,::::;i:;;:iiiiii,i:,;::::;,:,:::;,;,:,:;,;;ii;,;i;::;::,:i::: -,i:i::::::::::::::::,::i:i;;ii::;::,::::::::,::::;:i:;,;ijffLffffGGGDDLGfii;;:,;:i::::::;::::::::::::;::;:i;,;:;::;::::::,;:i:;;i:i:iii,;ii:,;::::,:;::::,:;::;,;;,;ii:i;,:;:;:::::: -:ii:;;:,:;,:::::,;,:::::iiiii;,;,:;:i::::::::;::;;,;ii;ifGLGGLGDGGGDDEDGffijiiii;::;:::::::::::::::::,:;:,::::,:,:::,;:::::,::,i:i,ii;;i,;;,;:,::;::::::;:::,;:,;i:i:,;,,;:,:,:;:::: -i;;,:::::::::::::::::::i::i:ii:,::::::::::;:::,;:iii;ifLDGfDDDGDDEEEKEEDEGDDGLfi:,;::::::,::::::::::::::;:;:i:::;:;::::::::;i:;,;:i:ii,;i:::,,::::,;::::,::::::;,:i:i;,;:,::::::,::: -i:,;,,:::,:::::,::,::,:,;;,;i:i::;,:::::::,::,;,;i;ifLDGGDEKEDEEEKKDEDKEKEEDDDGfi;,::::::::::::::::::::::::::::::::::::::::::,:;:i;;i:;,;,,;::;:;:::::::::::;::,;i:;::;,,;:;;:i:;::: -i:,;::::::::::::;::::,:::;:i::;,,:,:::::::;:,;iiifGGGDGDEEDKEKEEWW#WKKEWKEW#KKEGj;i;,::::::::::::::::::::.::..::.::...: ::::::,;:;:,;i:i:;::;::;:;:::::::::::::,;;:;:::i,:;:,::::::: -:;;,::,:;:,::::::,::::,;,:::;,:;;:;:::::::::;,jjfGDGDGGGEDEEKKK#KWK#E#WWW#KWEWEDffii:;::::::.:::::::::::...;;:ijiii:::: :::::;:,:i,:;::;:::,:,::::::::::::,::::::::,::;::::::::::::: -,::;,::::::::::::::::::::::i:;:::,:,::::.:;,iifffffDGGfLDEKKWK#WKEEWWWEWKKWWWWKKDGGi;,::::::::::::::.:.:;:;;;jLfGGfji;:::::.:::;::;;,:::;,;::;::;:::::::::;::::;:;:;::::::;:::i::::: -::;::::::::::.:::::::::::::;:::::::,::::::i,ififLDGDDDDEKWEWWK##KWEWWWWKKKWKWWKWWKDGfi;::::::..:::::;,;ijLGjjjtjLGDDGDGGGi::::::::;:::::::::;::;,::::.:::::::::;::,:::;::::::::::::: -:;:::::::::::.:::::::::::;:::,:;::;::::.::ijtGDGDDDDDEEKWWWKWWWWE##KK##KKWKWK#KWK#EGfii:::: :::::::::iiifLGGGGjjtGGEDGEGDj;;:::;:::;::::;::::::,;:::::::::::::::::;::::::::;:,;::::: -:::;:::::::.::.:::::::::;:::::::::,::::::ifDGDKEKEDELDKKEKEK#WW#K#WWWWWEWWKK#KK#KKKGGi;::::::.:.::.:;ijfGGGEEDGGtjGGKDDEDG;;:.::::::::::::::::::::::::::::::::::::::;::::::::::::::: -:::::::::::::::::::::::::::::::::::::::;ifDEDDD#GDEDEWWKEW#W#E#WWWKKWKWWKK#EWK#KEKGjii;:::::::: ::iiLGDGKKKKKDKKEjjGEDKEEjjGfj;:::::::::;:;:::::::::.:::::::::::;:;:::.::::::::::::: -::::::::::::::::::::::::::;::::::::::::iiGKKDGEWEKEWWK#K#KWK#WW#KW#WK#WWKWKWK#KKKDj,;:::::... :::i;jGGDEEKDKKKKKKGjjGEKKDjGGGjf::::;::::::::::::::.::.::::::.::.:.::.::::::::::::::: -:::::::::.::: ::::::::::;,::;::::::::,;ifLEKEEDEK#KKKWE#WW##KWWK##KK#KWWKKKWEGKGGi:;::::.::.:::::ifGGGEKKKEKDKWKEGLjGD#EKGGGGGG;:.::::::::::::::::::::..:::::::::::::::::::::::::::: -:::.::: :::.:::::::::::,::::::::::::i;ifGDEKKEEKKK#KK#KWWWKWWW##EWW#E#WEWEWEEDGjLi::::::::.: .:;ijjLGEGDGGEKGEKK#KGGGKKWEDEKDGGi;::::::::::::::::.:..:..:..::.::.:.:::::::::::::.::. -:::::.::::.::::::.:::::::::::.:.::::iifGGDK#EWEKEWK#E#WKWWWKWKWWWKKKK#WEWDGGGLit;;:...:::. :.:;ijLjjjjLGGEEKDEEDGEKDGGEDKKKEEGGi;::: :...:: :::. : ::.::..:::..: .::.::..:::::..:.:. -::::::.::.::: :.::::::::::::..:.: ::iiGGDEEWKKKKEE#K#KWWWWW#K#EW#KWW#KWEKEGfLf;;;;;: ::: ::::ijLGjtjLLGGKEEEEEDKEDKDEGGGKKEKKDGj;;:;;::::..:....:.: ...:..:....:::...:..:.....::.::. -:::.:.:::.: ::.:::::.::.::..:: :::::iLGDGDKWKE#KK#WWEKWWWWWKWWWEWWWWKKKKKDDfjj;;,,..:...:.::;jGjjjjLGKEEGEKDDEGDDGGGGfLjGKKEEKGjj;;,;;: :.:.:::...:. :....::.. : ..:::::..:::: :::: -.:..:..:: : ..:::: :..:: :....: .::ijGDKDGEWEW#EW#EWKWWWWWWKWWWEWKK#KWKKEDGGi;;;,,::.:.: ::;i;t;LEGGDGEGKEGGGLjiji;j;;;;tjGGEKDGjt;.:.:: :: ::.:: : :.......:..:: :.:.:...:.:...::. -..: ::..: :..::...: :.: :: :::..:::ifLGEKEKEK##WWK##KKWWWKKKWWK#K#KKKWKWKEKGti;:.:.,.:. : ;ij;;jGGGLGEGGDEGLjj;t;;;;;;;;;;tjGEDGjt;:.. ;:..........::..:.......: :... :..: ... :... -..... : : :.. :.: .: .: :.. ::::;ifGEEKKE#KKWWWEWK#K#K#K##EWKEWKWWWW#EEEDGi;;;.:.:..:: :;ijitGGLLGEGEKGGGjj;;;;;;,;.;;:;;;LGKEGt;.: :. :..:: ::. :. :... .... :.....: : :::.....:: - :......:. ..: ...::..: ::.....:::;iDEEWEKKKKKKK#WK#KWKW#K##EWWWKW#EKEKWKKEDGj;;;.::.,: ;;ii;jjGGLGGDKGGjLjji;;;,::,:.;:,::,;tjGGLL;................:... : .:: ::....:..: :: :..... -. .::..: : . : :..: :..:: :..:.:::iGDKKKK#KK##E##WWWW#KWW#WK#EKWWKKKEEWEKGEGj;,.:...,..::;;jjLGLGLGEGLGLjjtjt;;;;;.;;.::,:.,;iGDGG;;.............. :..: ::.. :.. : : .: :. : :..: -.::..: :..:... ...:: :: :: : : ::,iGDEEKEK#EWKW#WW#KWK#KWWWWWKEWKKEWDDDKKKDGGi;.:.:,.;::;;itLGLfLGGGGGjjjt;i;;;.;,,::,:...::,;LGGGL;:: .. : ....... : : :....: :: .. :.....: :: :: - :..::.::.: . :: : :.....: :: :::ijDGDWEKWWK#KWWW#K#WW#WW#WWWKK#KWKEKKKDKEEGGj;.:...:.,:;;;jLjGLLGKELjLjjt;t;;;,,;:.:.:..:..:.iGGGLj:.:..... : : ::..... ... :.:......: : : : : -.. : :..: :. ::. :.......: :: :::;fGDDDEWKWW##WW#KWWWWWWWWWWE#KWKEWEKEKGDEDGGj;:.:..:.,;i;jjGGLLDKEGLjjjtjt;;;,,;,:..:.:.:.:.:;;LGt;j:.: .. :....:: :: : : . : . : :.: :.: :.: .: -. : .... .: : : :.....:......:::ijfDEEWKK#K##K#WW#KWWEWEWWWWWKWEWKEKGGDGEGGjj;.:..:.,;jEitiGGLjGKELjjtijii;;;,;..;:.:.::.:.:..;jGjtt.:: :....: : :.: :.: ::...... ::......:.:.:. -: : .........: : : : : :...::itGDDKEW#KWKW#KWWWEE##WWKWEWEK#KKEKKDGKGGGGf;,:..:..;jGK;jLGLGGEKEjLjtt;j;;;;,,,::::.;..:...::.jGLj;j ::: :: :: : : ......:: :: :.:....:.: :.:.:. -: ...................: :....:...:;fGDDKEKWEW##W##KWWWW#WW#K#KWK#KKKDKGfGGGGLj;::..:.;ijjjjGGGGDKKEGjLjjLjjji;;;;,;.::.:..:....:.;fGLijj.:: ::.::.... :: : : : :..:.. : ::..:..: - ....: :.............:: ...:..: :ijGDKEWWWWWEK#KK#WWWKWE#KKWWK#KWDEGGGGfjGji;...:..;;;;;iLjGLGKKKGLLjLLGGLLLj;;:;:.;:..::.::....:jDLijj.:............. :..: :: :: :.......:: :: ::. -: : ..: .. : : :: :: ::. :: :: ;fGDEDEWWWKWWWWWWW#WK##WKWWK#KKEDKEDGfGfjL;;.:.,:.:;...;GLLGDDKEGLGLGGLjfjfLj;;;;,..::.:.::.:...jKLt;j;.................. .. : .........: .....:: - :...: :: .. : : ....: .. ... :: ;fLGDDEKWWKKWWW#K#E#KKWKWKWK#EKEDEGDGGGjji..:.::;.:.:..;LGLGKKELLjjjttt;;;;;;;;;,;..:.:;;;i;::..;KGj;;j; : : .. :: .. : . .. . .. :: . .. ..: - .. . : .. :: : .. : ....: . :;ffDGEK#K#K#WW##WWWW#KWWWK#KWWEKGDDGfGfjj;.:...:..:..:;jGGGEWKGLfLjtjtttij;.;;;;;.:.::;;;iji;:..;KGf;;;; .. : ... .... .: . ..: : .. : :: :... : -. .. ... .... . . .... . :: :. :LGDDDEK#WE##WW#K#KK#EWWW#KKWKEKDDGDjGfij;.::...::..:;j;iLEDKKGjLjjjtjjLLGLj.;;;;;..:.,:;;;t;j::.EGj;;;;: .: .. . : .. .. : . :. ....... . - . . . .: ... . . :. . : .. . ..;jGDGDKKKKKWK#WKW#EK#WKK#KWWWKEDDGGGjGjjtj,:...:.;..:;;;;;GKKGLLtjjtjjGGEEKD;.,;;;.:.;;,;,:::;;.:DGL;;;;...... : .. : .: : : : ... : .. :..... - : . : . :.. : . ... : . .. ...iGDGDEKKWE##EWWK#K#KWWKKKWWWEDDDGGGjGfjji;::.:.....::,..:,DKLjtjttLLGELiiEGG;;i;;.:,;;;;jjj;: :.GGj;;;;... .. : .. : : .. .... : : : .. :....: -. : . .... :.. ... . . : . . ;GEGDDEE#KWW#KWKK#WE##K#K#KKDKGEGGGGjjjjj;:.,..:.:....;,:,;EGLjtjjjjLLLLjLGK;;;;,: ;;;jGDWKG;. .Gjt:,:;: .: ... : .. : : . .... :: ......... - . ... : . . : .. .. .. : . : :GGDEDEWKKWWWEWWKKWWEWWEWKKKDGGGGGjjGjjji;:;:::....::.,:.;;jGLtjttjtjtj;;;;j;;t;;..;;;jiifDW;:.:Ei; :.; : : .. .. :.........:... .. : :... : .: - .. ... . .. : : . .... . .: ..GDGEEKKK#KKKKWWWW#KWWWKEWKKGLL...;jjfjji;,;::.:.. ...:;:;;,;Gtjtj;j;;;;;;;;;jtt;:.:.;;itjjLL; .L::..;... : .. :: .. : : ..........: : : ....: -. . . ..: .... . ........ .... :....LKLKDKKKWWWWWEWWWK#W#WKKKEELL;:;..,;jjjt;;.;.:.:.:....:;;;;iLjtjiti;;;;,,.;;tji;;:.:;t;;;.;;;..j:. .:. : : ..... : .. ..... : .. : :: :...: - .. . ... .. : .. :. :: .... ...: :.iGGDEKKWEWWWKWWKWWK#EWKWEKGLt,tt...;;jjj;;:;;:... :. .;;,;;jGjttti;;,,,;.;;ijtt;...:;;;;;..:. .j: :; .... . ...: ...... : .. : :: :: .::..: :: - . : . . : .. :: ..: :: :: .. : ....;jGGDKDKKKWKKK#KWWWWK#KKGLLtt,tj,..:;;;;;;:,,:,:.. . ..;,;LKLttjt;t,.:,;:,;ttjt;:...:,.:.:.: . j: .:. : : .... : : :: .. ......: : :: :..:: -. . ....: : : . : :.. : ....: :: :.:;fGDKDEWWKWEEWK#KWWWWKEGGjf;,ti:,...;;;;;;;:,:..:..:..,;jKELjttt;;;;,,,.;;jtj;;::....:,,:...:.j:..:.. . .. : .. :: : ........: : ::....: : : - :....... :...: :.. :...... ....::iGEEEKEKKWKWKWWK#KEWWELjLj;,,,j;.:.,;;;:,::;:.:......;;KKGLtttt;,;,.;,;:;jjj;;.....:.::... . f;..: ::.........: :: .......: :.:.:: :.......:: -. .... .....: .. : : : : ..... : .::GGDKEDWWEWK#EWWWK#KWGLjjf;;.tLL. ..;;;;;:;:,:...:. .,jEWGLtttt;;;,;:..;tjLj;;:.:...,:.:..: .ii.:.......... : : : :: :: :::.::.::.....::.. : -....... : . ..... ..: ..:..... .: .:.iGGKKKKKKK#EW##K#WWKGLjtLt,.;ff; .:.;;;;;;:;;:..:.:.:,LEELtjti;;,,::.;ttjtj;,:...;,:::.: . .i;;:::.::.:...:....::: : :::..:.::::..: :..:: :.: -..: :: :: ... :... : :...:..:::..:...;DGEKKEWWWKWWWWWKKKKLjjLfj;.,;t;.:.;,,;,:;.,:,,...::,:jDELtttt;;;:,.;;Ljtjj;;..:.;;.... :.. ;;;::.:.....:..:.:.: :: : ::..::::::::.:.::.::... -.: :::...................:.:..: : :..:.:jGDEEWWKKK#K##W#WWKLjjjtjt....;..;.;;;;;;.,,..,.:...,;GELtjtt;,;,,:;;jjLLLj;,;..;,,:..: : :;:;:::::::.:.:..:.: :.::::..::.::.::.:.::.::::.:: -::::::.:.:.......:.: :.:.:::::::.:...:::.;GDDEKEWKWW#WW#KKKLLjtjtj;....:,,;;;;;;;.,,:.......;;LKLtjtt;;,,;;it;tiij;.:;: ,;;,..:.: .:.:;.::::...::.:....::.:.:::...: : :..: ::.::...: -::::::.:: :::: ...:.:.:.. :::.:..:.:.....:LGEDWWWWW#KWKWKEEjjtjjjLt;.. .;;;;;,:,::::..::..:.:jKELttt;;;;:;;ttt;t;;:,:...:;;;.:.. .:::..:: ::.::.:.:::...: .: :.:..:.:.::.:..:::.:.. -.::.:.: ::: : : :.:.:.:..::...::: :.:..:.:LGDDE#WWW##WWWKKGLjjtttjLt;:.:,;,;;;;,,;:::.:..:.:,LGEGjttt;;;;t;tj;ttt;;...:.:;;,:.... :...;..::: : :: : ...::.:: :....:....:.: :.: :... -....: : .: :.:...:..: : :::....:: ::..:: :jDWKWWWEWWWWKKDDGjtjttit;;;;;;tt;t;;;,;:,.:.. :..:,;LGLttjt;;,;tLLDDDGGDLff;..::;;:..:. ..: .: :..::: ... ..:: : ...: ::........ :: :.: .. -.....:.:: :.: :...:: ::.. : :..:: : ..::..fKWWKWWWKEKKKEDGGjji;;t;;;,;;;;ttt;;;;.;....:..:,,;tGLLtit;;;.;tGELLLGLfffLjt,.;;,..:. ::...;... : :: :. :.: ::: :............: : ..... - :: :....: :.: ..: :.....: :: ::.........iEWWWKWWKKKEKEGGGj;jt;i;,,:.;tijt;;;;;;.;.:..:...,:tGLjtti;;,;;;LGLjt;;;t;ffft;;,;:.... :: :: : ....: : .: .... : ............ :: :: :: -: : : :.........: ::...................;GKWEKEKEKEGGGGGjjti;;;;,,.;;;tttjt;;;,:...:...,:;;;LLtjttt;;.;;;DGL,;:...:tfLf;;:..: .. : :...............:: : : ...........: :: :: :: - :: ::.. :: : : :: :: :: : : : :: :...:iDKGGGGGGGLGjjjjti;i;,,;:;:,;jjttti;;,,,..:..,:,,;:.;jtttt;;,;;itLDGLfft,,,Lft;;,.... : :. : .. . : : :...: . .. : : :: :: : : : : -........: .....: : : : ...: :: : : : :LGGGGGGGLLjjjtj;jt;;,;,,.,;;tjtjt;;;;;:,::..::,:,:..;;;i;;;;;;ttjfGDLffjjjjt,;,;:.:.: .. : : .. :: :: .... : : : : :: .. : : .. :...: - :: :: ::.....: : :: :: :: : .......: :: :: ;i;ijjjjjjjj;jtt;i;;,,::,.;;;jjiit;;;,,:..,.,.:;,...:;tiit;;;;;itjfGGLffjti..;;..... .. :. ...: . : .. .. : .. .........: .. : ..... - :: :: :: : : : :...: ... :: :: : : : . ::.:,:i::::::;t;;;,,;;::,,:;itjitit;;;;,:,:,,:,; :..:,;ti;;t;;;;;,;;;,;....;.:..... :: : .. :: :: :.. :: ... : : .. :.. ..... .... -: .......... :: : : ..........: .. : .. :..::i;,:;::::.:;;;;,;:::..:.,;;ttt;;;;,;;;:,,,,,, : ...:;t;jiit;;;;;;;,;...:.:..: .: .. :.. ..: :........... . : .. ....... : :: :: :: - :: :.......... : :: :: :... .. : :: :: :itfGDGffjii;::.:. ::;;.;:,:.,::,;;tittt;;;;;;,,,:;.. : ...;;ti;t;;;,,:.::.:: .:.:.... ...: :: : ..: .. .... ..... :: :: :... : : : : - .: ...... :: :: ....... .. .. : :...:ifLDDDWDWWEWKWKWEDf;. : .;:::.,.,;,;;;;t;;;;;;;;;;. . : ..:.:.;;tit;;;:,:..... :.... : : :: : : . : : : :..... :.. : .. . : ...: :.. .. - :.. .. : :... ..... ....... .. .. .. ;tfGGDEEEKWK#W#KWWKKEGf:.. :,.:...:::;;;:.. ...: ...... .:. ..:;;itt;;:;.::.::. :...: . .. .. . ........ . :: ..: .. : : :: .. : .... :: - . : ..... .. ... . ..... : .. .. : : iffDDDDDWKKWWKEWWEW#KKKKi...:::,.::;,,:. .. ... .. ..: ...:.:::;;;;jit;;:;.: ...... ..: ..: ... :.. : : :: .... : : .. .....: : : : . . -..: . : . .........: :.. ..... :: ..: :jffLDEDEEKKKK##WWKKEEKKEDL: ..:,:::.::; :: :.. :.. ... . :.:.:,,;;;itj;;;.:.....:: .. :... ... .. : : : : . ..... : ....: : : :: .. .. - . .... ...: . : ... .... . . ....ijLfLGDDDDKKWWWWKWKKKWEKWEEEKD: ..,.:.::. :.. :.:.. .. : :.::.;.;;iititt;;;;:::... :......... : : ..... : : .. : .... :.. : .... : . - .. ... ... : .... : : .. .....: : itjfGDDDEEEKKKWEW#KWWKKWEWEEKDDGi :.::,: .. .... . . : : : .::.::;;tttjttiti;:;..... :.. . : . .. : : : ...... : : :: : :.... ...... -..: : .. : : . :: : . : : ..fLfDDDDEEDKDEEKKKWWWKWWWEWEEEEEEDj..::.;: :: . : . : .. :.:.:.;;;titjtit;;:;:...:.... :....: .... ...: : : . : ... : .. ... ... .... . - ....... . ....: :: . : : . : : tGfDDEWEWEWWW##WW###W###K#KKEEEEDEf:.,: : .. ... .. : ....:.,:,:;;tit;t;,,,.,...... .: .... . : . .: . . . . : ...: . : ... ... . . . - .. :: :: : . . : .... .........: :ifffDDEEWEK#KEW#WK#WWWW#W#WWEKEEEEKf.:. : . : : . .. .. . :,:;;;jttt;;;;,::....:. : : : .. : . ... ... . : ... .. . .. : .. . ..... .. . -........ : .. :. : . ....: ........:ffffGLDDDKKKWK#E##W##W#W####WKWDEEEEf ..: ... :.. .. : ... : ..::.;;;j;;i;;:;::.::.... . ........ : . ... ........ : .... . .. :... . . .. - .. :: : .... ... . .. : :: .:iiffffGDGDDEDKKKK#KK#WWK#KK#KKEW##WKDWDEi.... .... ... ..... : ...:,;;tti;i;;,;.:.,::.:,:. :. : .......: .. :... : ....: : : :: .. : : . -.... : ....: ... .: :.. : .::tifDGLfGDDDGDDWEWKWKWWWWWWK#WK#WEKK##KDEWEi : :.. .. :...: .: ...,;;;;iti;;;;,.;:..:.:::::.. : ::..: : : : ..... : : .........:. :...... ::..:. -..: :... ....... ........... iiiitfEDDDfGDGGDDEEWWWWWWKKWWWK#KKEWEEED#WEDDG: .... :: : ....... : . ,;;;;j;t;t;;,;..:::..:.;....: : ... : .. :: ....::..: : .....: : ....:. : . .. -... :: :: : ......:: :...: :ititifLDGDfLGDfGLDWEWWKKK#EWK#KKKK#KKKKEKDWKEDDf............. : : . :;;;;tt;tt;;;:,..;..::.;.;;.:: .:::..::. :..:.:.....:..:. :.....::..:::...::.:: .. - ::.:: ::... :. :....:...:tDLifjtfDEDGGDDffffDKWEEWEWWEWWEWWEKKWKKEWEKEDEEDG:.: .:::....:::.:.: . .;t;ttt;ttt;;:;..,.:.,.:;;;;;.:. ::..::.:.:::::.::::::::::..:::.::.::::::.:.::.::. -: .: : .:::.:.:: :: :: :iDDfifffGDEDLLDLLffLDKEKKEWEEWEKEKKKWKKWEKWEWWEKDDLL..:: :..::::.:: .: . ;t;itt;tt;t;;,;,,.,,,:,;,;,;;;:: ::::: ::..:::..:::.::.::.:.::::.:.:.:::::::::: -.: :::.::: .:.: ::..:.:;iGDLtfffLDGDfLGLGLffGDKEKEWEEEDEKKKKKKEEWWKK#KKKKEDDLfff;::.::.:.:.::: : .;;ti;ijit;;;,;:.,..,:;;;;;,;;:;::.. :.:::.::.::::::.:::::::::::.:.:::.::::.::.::: -.:.:..::::.::::::.:.::tfGGfftDffLDfDGfffLLfDKEEDEEDKEKKKKKKEWEKWKKEWEWWEWKEKDDLDi::::::.::::: . . .;;;;i;j;;t;;;;..:.::;;;;;;;i;;:.. :.. .:::::::;::::;;:::::;:;:;:::;:;::;;::;: -:.:::::.:.::::.:.:::iitDfGfGfLffGLDDfLGGffDEDKEDEEWKKWEWWEDWEKKKKKKKKKKKKWEEEDDLi::;::::::::. .....:;;t;;titit;,,,;.;,;,;;;;;t;;;::.:..::.::. ::;::;::;i;,:ii;i;i:i:::;;:::;:::;,,; -:::.:::::::.:::.:::iitfDfGDfDDfffDGDLDLLLGKDKEKEEKKKKKKKKKEEKKKK#KWKKEEKKEWEDEDLLi;:;:;:;::: . . .,;;;;j;tt;;;;;;:;::;;;;;;;;;.:;::.:::;;;:::..;,:ii,i,;iiii,iiiii:i:i::i:;i:ii;iii -;iii;;:;;:;::;:iiiijffKffGfLWGfLDGDLLDGDDEEEEDWEKKKKKKK#EKKKWE##WKKKKKKKEKDEDEWEEDDii;i:: : : .: :,;;;;j;t;;t;;:;;;;:;:;,;;;;;;;;:;,:;;;;::::.:.::ii:i,;,;;i:,i::i:i;,;:i:::;,,;ii, -,;,;,,ii;,;,,:iiittttGDtGDfD#LLGLDfDLDGDEEDEDWEWEKKKKKKEEKDKKKKEWW#KKWKEWDKKKWEWWEEEGt: :...:. ;;;;;;jtt;;;:;;;;,;;;;,;;;;;j;:,,:;,;;;;,::.:: :::;:;;;::,;;:i;,;:::,:::;::,:i::; -iiii;;;;:i,;;iG,itiffWLfDLDWEDfLGDDLDDDEKKEEEEEKKKKKKKKKEWEKKKKWKKKKKWWEEKKK#EWEEKDEEDG . ...:.:. :,;;;;t;;;;;,;;;;;;;;,;;;;itj;;;:;;;;;;;::....: ::,;::,;:;::;::::::;:::::;::::;i: -;,,;;,;ii:i:LEttijffDWffDDDWWDGLGDfDGDEEDEEEKEEWEKEWEKKKWEWWEWEE#WWEWEEWEKE#EWEKDEEDEDEi. ...::;:..;;;;t;;;;;;,;;;;;;;;;;;;;tij;;:;;,;i;;;;.:.:. .: ::::;:::::::::;::::::::::::;:::: -:::::::::::jGiittffDKWtLDEWKKDLDLLDLGDDEEDDKKEKEWWEWEKKKWEWWEWKWW#KWKKEKK#KKEWEWDEEDWDKEDj::..: : ;,;t;;;;;;;;;;;;;i;;;;;;;;;j;;,:;;;;;i;;,:..:.: : :::::::::::::::::::::::::::::::: -::::::::::tKjijtffjE#EffDKKKDDGfGLGLDDEKDEDEKKWEWEWEWWEKKKKW#E##KWEWKKEWWEWEKEEEKKEKDEDEED.:::.:.:;;;;:.;;t;;;;;;it;;;;;;i;it;;:;;,;;;;;,;:.:.. . . :::::::::::::::::::.:::::::::.:. -::::::::::D#iftffffWWDfGDKKKEDLDLLLLLDDDEEEWEKKEWWEWEKKKKKKKKW#WWKKKKKEWKEWEKKKKEEEKDEEDED::....:,;;;,:;;t;;t;;i;;;i;;;;;;;;j;;,;,;;;i;;;;;.::... : :::::::::::.:::.:.::::...::.:... -:::.:::::EKfffjfffGWWLjDDEWDEDGfLLGGGDDDEEKKEWWEWWEWEKKEEWEWW#KWWKKKWEWWKWEKKKEKEEDEDKEKDED;..;::.;,,;;;t;;;;;;;;;;;;;;;;;;;;;;;;:;;;i;;,;:.::.. . .:.::::::::::::::::.::.:..::::::. -..:.:.:.jWGfffffjfD#DDfDEKKEEDLDLLGLDDEDEKDEKKWKEEWEWWEWKKKKK#W#EWKWEWWK#WKKEKEEEEEEKDEDEDDt ::.;;,;:;;;;;;;;;;;;;;i;;;;;;;;,;,;:;;;i;;;;,.:.. :.:. :::.:::.:...:..:::.::.::::::..:. -:::.:::.DKfGfffffLEWDDfDEKKEEGfDLDLGDDEEKDKKDWWEWWWWKKWEE#W#WK#WWWWKK##EWWEKKKEKEEEDEKEKDEED:..;:;;,;;;;;;;;;;;;;;;;;;;;;;;,;;;;;;;;;;;;,;:.:.: ....:::: ::::::::::::::::::::::::.: -:::.::::WfDLLffDfGKEDDfDEEWEDGDDDGGLDEDEEKKKEKKEWWEWWEWEEW#E#WEWWWKWWWKKKEKKKEDKKEWDEKDDEEEDG,::,:;,;;;;;:;;,;;;;,;:;;;,;:;,;;;;;i;;;i;;;,:.::. .....::.:..::::.::::::::;::;:;:;:::: -: :::: iELDDfffGfDWDGEfDDEDKEDLDDfDDDEDKEDEDKKKKWE#KWWWW#KK#WE#WW#KK#E#EWWEWKKKKKDEEKDEEDKDED::;:i;;;;,;:;::;;;,;;,;;;:;;;;;;;;;;;;;i;;,:,.:...... .::.:::..:..:::::::;;:;,;i:i,;i;: -:::.:::fGDDDGffLjD#GDEfDDDKEDGDDLDGLEEEDKEDKKKKKKKKKKWEWWK#E#KK#WKW#KWKWEKKKKKKEKKKKEKDDEDDDD.:;GG;;:;;::;::;:;;:;;;;;;,;;;;;i;;i;;j;;;;;::.:: .. ..:.:.:.::::::.:::;;iiii;i;i;;i;i; -.:::...DGDEWLtGffD#LDDfGEEDEDLDDDfDDDEDKDEEKKEEWKKWE#WKKKWEWKK#K#W#K#W#K#WKKEWEWKEDDKDKEEDEDE::jWG;;;;:;,:;;,;;:;;:,;,;;;i;ii;;;;;i;i;;:.:... : : ...:..::..::::::;:iiiiiiiiiiiii;i -:.::..fWDKKKLfDtLKWLKDfDDDDDGLDDDGDDEWEDEKEWEKKKKE#EWWKWKWWKKKW#KEWK#KWW##KKKKKDKDEEEEEDEDDDD::;;it;;:;:;;::;;;;;:;,;;;;;;;;tji;;;iti;;:...: ...... ....: ::......::;;iiitijiiiii;i; -.:::.:GWEKKKDfDiDEWGKKfGDEDDEGDDDGDEKDEKKDKEEWWKKKKWEK#KWWKWWWWW#KWWWKWKKKKKEWEKKEWKKEKEKDDED;:::;;;;:;:::;;;,;:;;;;;;;;;i;;;jji;iti;;:;;::.:.. . ...:...: :.:.:::::iiiiiiii;iiii;i -:...:iKDEW#ELDDiDWEDEKfDDGDEEDDDDDDEEEKEDKKEWEWKWWKKW#EWWWKKWE##KWEWWWWW#WWKKKKKKEDEEDEKDEEDDi.:;;;;:;:;;:;;,;:;;;;;i;;;;;;;tLjj;;;t;;;::.. . : ...:: ::....: :.:.;:i;iiii;ii;;iii; -.....fWLW#WEDDDjDKDKKKfDEDEWDDDEEEKDEEKEDWKKK##EWWKKWW#WWKKKWW#WK#WKWW#KWWWWWEKKKKEKDEDKDEKDE;:;::;:::;:;:;;;:;;;;;;;;;;;,;;jLj;;i;i;;;,.:...: : :.::..: : ....:.::::;iiiii;i;ii;i,; -:..: GWLWWW#DDLfDDLKKKLGDEDEDEDDEDEKKDEWDEWEWKK#K#KWWWK#KKKKWWWEWWK#WKKK#KKEEKKKKDEEKDKEDEEDEi;:;;:;:;:;:;;;;;;;;i;i;;;;;;;;jGji;ti;;;,,:...:. .. .. : :.::......:::;iii;iii;i;i,i; - :..:DEDW#WELEffDDDWKKfDEEDKDGEDDWDKDKEEWEEWE#KKWWK#W#WWWEK#W#WK#KKK#KWEWWEWWKKKKKKEKEDEKDDDEj::;:;:;:;:;;;tLGGGLL;;;;;;:;,;LLLti;t;;;;:.:.. : :...::..: : t,....:::;:i;ii;i;,;i;i;, - :...EEK##WEDDfLDEEW#DfDEEKDGDDDDKDEDKEDKWWWWKKKKE#WEW#EEKEWWW#K#W#KKWKKKKWEWKKKKKEKEEEEEDDEDj;:;:::;,tLEEEEEEKEKEDj;;;:;;;;ELj;i;t;;,:.:... : . .:::....,D,: ...:::;ii,ii;,;,ii;i,: -: ..iWDE#K##EDffGDKKWELDDDEDDDEDKDEKKEEKKEEWWK#WW#KW#WW#WEKW#K#WWWWK#W#WEKKWKK#KKKEEEDEEEDEDEi:;::,;fGEEEEEEEEEEEEEDG;;;;;;;GGjtti;;;;;:.:: : : .... : .,jD..::...:::,;ii:iiii;:iii; - : iEDEWW#WEEDjfDEE#EDfDDEDGDDEDDKEDKEWWEWWEWKKEWK#WWW#WEKW#K#W#W##KK#EWWWWK#WEWWEKEDEDDEWEEGj;::;jLEEEEEEEEDDEEKWEEEf,;,;;;GLjt;;i;;,:.:. . . :.::..,iDL : : :::;ii;i;i:;,iii;;, -::iWWWEE#K#WDLfLEDKK#DGGDDGDEDEDKEEKKKKKWWKK#KWW##WWW#KWKK#W#W#W#KWW#EWKWWKWWE#KKEKDEEDEDEDEDi;,tLLDEEEEEEDEDEDEEKKEEDEf;;;iELjij;;,;;,:.::..: :: : . ;ijG, : :..:::i;,,;ii;i;,;ii; - :W#KWEEW##WKLfGDKKEWDLDDDDEDDEEKDKDKKKWKWKWWWE#KK#W#WWWWWWW#KWWWWWWWWE#WWWWK#K#KKEEDEKEEEKDEffLGEEEEEEEDEDDDDDDEEWKKEEDDf;fDjtiti;;:;.:...:. . ...:iijDi. : . ::::;ii;i;i;i;,i,;i: -:f##DWDWWWWKELfGDWWWEELDELDDEEWEDEKKWWWKWKKWKKWEWK#K##EKWW##K#EW#WEWWWWKK#KWKKWEKEKEEEEKEDEKDLDEEEEEEEKDDDDDDDDDDEEKEEEDDELLGLjt;;;:,::.:.. ..: ....,ijDf.... : :.::;iiiii,ii;;iii; -iEW#DWEEW##KDDfDEKKWKDLDDGDEDWEDKEWE#WKKWEKKKEWW#W#W##WKW#W#KWK#E##W#WW#WWWWWW#WKEDWDKEDWEEDEDDEDEEEDEDEEDDDDDDDDDEKKKKEDEEKLjj;i;;;;::.:..... : ::.jijDj.: :.: :::::i:ii:i;;iiiiii: -EWW#D#EEW#WWDDfDEKKWEDfDDDEDEWDEEKKKK#WKWKKKKKWWW#W#K#KWW#WWE#EWWW#E#W#WKWWWWKKKDEKEEKDDEEDWEDEEEEEEEDDEDDDDDDDDDDEEKKWKEDDWLjt;;;,;:,.:..... :.:.,tijLf. :.......::::;,:;,;,;;;,;;: -K###DWKK#W#EELfDK#KKKGGDEDDEWKKKKEW##WWWWWEKEW#K#WW#WKK##K#E#WKW#WWW#KW#KK#WKKKEKKDEDEEEWDKKDDEEEDEDDDDDDDDDGDDDDDDEEEKKEEDEGLt;;;;;.::... ... .,,iijjDi : ....::::::::i:::;::::;:: -EWW#D#WDWWW#DLLDKWEKKGGDDEDEKWEKKKWKWW#WWEEWEWWWWWWWWWE###WW#KKWWWW#E##K##WWWWEEDEEEDKDEEKKEEGEGEDDEDDDDDDDDDDGDGDDDEWKWKEEDLjt;;;;.,....::.....,t,ijfD,...: :.: .:.:::::::::::::::: -WEW#E#WEW#WWDGLDKKKWDLLDGDEDKWEKK#WW#W##WKEKEWW#KWWWKWWWW#W#WEW#W##K#WW#KW#WWEEEDEEDEEEKKKEEDKEDDDDDDDDDDGDGDDDGDGDDDEEKWWEELft;;,;;:...:....: .i,ijGDD.... .......: .:..:.:::.:.::: -E##WE#EWWWKWDDfD#W#WELDLGEEEKKKEK#W#WW#EWEWEWWWWW#WWKW#WW##WWWWWWWWWWWWW##KEEDKEKKKEEEEK#WWEEWWEDDDDDDGGGDGDDGDDGDDDDEKKEKEWDft;;,:.:.: .... . .i,jfDDf: ....::..: :.... ::...:::... -KE##W#WEW##WDGfDWWWKDLDfDEEEKKEKKWKW#W#WKWEWEWKK##EW#W#K##WW#EK#W##W#WWWWK#WEKEWEKEDEEKWWEEDK##WEDDDDGDDDGDGDDGDGDDDDEEEKWKEEEf;;;::.::.: ... ..iijLDDi: :..: : : ::.:: :.:. : :. -WE#KKWWD#KWEDGLEWWWEKfLDDDKKKKKK#W#WK#KWKKEWWKW#WK#WEW#WWW##WE##K###E##W#KKEEEEKWEWKEWKWWWEE###WKDGGGDGDGDGDDDDGGGDDDDEEKEKKEED;::;:.....:.. ..,iiLLDD;......::..:... ...: : ::: :: -#KK##WWEWWEWDDLEW#KEEfDDEKKKKWE##W#WK#KWKK#KW#WWWE#W##W#W#WW#EWWW##WWWW#KEKEEDEKKWEEWW#WEEDE####WEDGGGGDDGDGDGGDGGDDDDEEEKEWKEEf;::.:. .: . . .iijLDDi.: : ....:..: :: :..: ..:: ::. -###KW#WEW##WDDfKEW#WDLLDKKDKEWWKWW#K#W#K#KKWKKKWW#K#KK###W#W#K#W#KK#W##W#EKDKKEEKKKKK#KWWEDKWWW##WEDDGDGGDGDGGGDGDGDDDDEEKKKKKKD,.;:..: .......tjfGDD,....:: :.....: ....: :.: : .. -#WW#KWWDK#KWDDLD#W#EDfDDKWEWEKK#W#K##K#EWKWKK#KWWKW#KW#W#W###KKWWWW##W##WWEKDEEWKKKW#W#EKDEE###W#WKDGDGGGDGGDGGGDGDGDEEEEEKKEEKDf,,:.:.:. ... ,jjLDDf ::... :.:....:.:.:...:..::.... -#K####WD#E#EDDLEW#WEDfGEWEWEW#K##K#WW#EWKKWEWWWK##W#WW#W#WW#W#K#K###W#WKKEKDKEWK#W##W#WEDEKEW#WKWW#KDDGGDGGGGDDGGDDDDDEEKKEKEKEEEi;.:.:.. ....ijLLDD,.. :....::....:..:....:...: ::. -W#K#WW#EK#WEDDfK#E#WDfDDWWEKKW#KW#K#WW##KWWWKWE#KWWWKK##W##W#WW#W#WWW#KKWKEKKKKKWE##W#KEDEEEKW##WWW#DGDDGDGDGGGGDGGDDDEDKEKEWEEEDL,:.:. : . .,tjfDDD : : :: :: :: : : :....:: :. -######WE#WEKDELEWW#EDfLEWKKKWW#WWWW#W#KKKKE#WKWWKW#W###W#W##WWW#K####KWEKKKKKKW##W##KKKDEKKEKWWWW#WWEDDGGGGGGDGDGDGDDEEEEKEKKEKEEDt.:.:..... tjjfEDD : ... : :.............. ...: -#WWW#E#D#WEDEDLWWWWKDffKKWKK#W#WWWW##K##EWEW#K#K##W#W#W#W#WK#WEK##W#EKWEKWEW#K#WK#WKWKEEEDDEWWKWWWWWWKDDGGGGGDGDGDDDDEEEEEEEEEEEEDD :.:..:.: jjtDDDf. :.... : : :.... : ..... ....: -W###WW#EE#KEDDfEWWKKDfDDKKKWWK#WW#K##W#KKWWWWKKW#WWWKW#####W##W##W#KKKKKEEWWK#E##K##WWDDEDEDEWWEWWWWWKEDDGGGDGDGDGGDDEDEEKKKEEEEEED..:. . . .iijEDDj : .. ... . .. .: . .. . . -#WW###WKWWEDEDLKW#KEDfDEWKWK#W#KW#WWW#EWKKWWWWWKKK#W#W#W#K###W##W#KKKKKKKKWWWWW##W#KWEEEDEDEKKWKWWWWW#KDGDGGGGGGDGDDDDEEEEEEEEEEDEDi. :..::..jjjDDG,. . .. : .. : . :. ..: : : .. -W#K#W##EWWWEDDLKWKKEDfDEEEW#KWK#WW#WK#WKWEWWWWW#WK#WWW###W#K###W###EKKW#WWE#WWWWWWWWEWDDEDDEEWKKWK#KWWWEDGGGDGDGDGDDDEDKEKEEEEKEEDDf,:. . . .tijDDf.. .. .. .. : .. : . . . -#WWWW##EK#KEEDfKWKWEGfDEKKW#KKWW#K#KWWWWWEWW#E#K##K#KW###W#K#####KWEKKW#WWK##KKWKW#KKKDDDDDDDKWKKKKWW#WWDDGGDGDGGDDDDEDEEEKEEEDEDEDDL, .:...,jjGDDt : .: : ...... : ... : ....: .. -#W#W#W#WKKEDDDLKWW#EDfGKK#KW###WW#K#K#KKKWW#KWW#WW#K##K##K###W#W##EKKW#K#E#E#WWWWEKKWWEEDEEDEKKKKKWWKWWWEDDGGGGDDGDDDDEEEEEEKEEDEDDDDj.: ...tjDEDG,. .. . .: .: ....:.... : ... : .. -WWW#W###EWKEDDLKKWKDDfGKKKW#WK#KWWWW#W#KWWWWEWK#WKW#KW##W###W####WWEWWW#WWE#K#WK#KWKWWEDEDEDEWKWKKKKWWWWWEDGDGGGDGDDDEEDEEEEEEDDDDEDDD.... .tDEDDD, ... :......... : : .: :: ..... -WW###W##EWEEDDLKEWEKGfDEWW#W##WWW#KW#W#WE#WWWEW#WE#K###WK#WWK###WWEKWW#W#KWW#W#EEKKKW#WDDDDEDEKKKKKKKW#WWWWGGGGGDGDDDDEDEEEEEEDDDDDDDDj. ..;DEDDDL...:..:...:...::.........:..::..: -##W#KW##EKWDGDfKKKKEDfDKEWWWWW#WK#K#WWWKWKW#KKK#WW#W##W#######W##WW#K##K##KW#KW#WEK#KKEEDKEDEDEWKWKWWKWKW#WDDGGGDGDDDEEEEEEEEDDDDDDDDDL,.. tEEDDDf..: ::..:: ::.::.::::..:..:..:.::. -WWK#W###DEEEGDLEKKKKDfDEWK#K##W##W#EW#KWWW#KKW#W##WWWW##W#W#W##W#KEWKWW#KWK##W#KEEWW##KDEDDDEEDKWKWKWWWWWWWEDGDGGDDDDDEDEEEEDEDDDDDDDDGL .,tEDKDGf.:.:. :...:. : :..:.::..: :. :... -W#W#W###DEWEDGGEDKKEDLDKK#K#WW###W#WK#KWWW#EWW#W##W#K##WW#W#WW##WKKKKKWWWWWWK#KWKKK##KKEDEEDEEEDWKKKWKW#WWWWKDGGGDGDDDEDEEEEEDEDDDGDGDDDD.LDEEDDDj:..:::....::.:..: ::.:.... :...:.: -#KW#WW##EEKDGDfDEKWEDLEK#K#K##W##K#KWWWWW#K#KWK###WW#W##W####W#KWE#EW##WWWW##WKKKK#WWKKDEDKKEEDEKWWWWKWKWWW#KEGGGGGDDEDEEEDEDDDDDDDDDGGGDjGDEDDDGj.:: ::.::: ::..::...: :.:::.....: diff --git a/jun_springboot_plugin/springboot_socketio/src/test/java/com/xncoding/jwt/socket/client/SocketClient.java b/jun_springboot_plugin/springboot_socketio/src/test/java/com/xncoding/jwt/socket/client/SocketClient.java deleted file mode 100644 index 19dff6eda2..0000000000 --- a/jun_springboot_plugin/springboot_socketio/src/test/java/com/xncoding/jwt/socket/client/SocketClient.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.xncoding.jwt.socket.client; - -import com.xncoding.jwt.common.JsonConverter; -import com.xncoding.jwt.model.LoginRequest; -import io.socket.client.Ack; -import io.socket.client.IO; -import io.socket.client.Socket; -import io.socket.emitter.Emitter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.net.URISyntaxException; -import java.util.Arrays; -import java.util.stream.Collectors; - -/** - * SocketClient - * - * @author XiongNeng - * @version 1.0 - * @since 2018/1/18 - */ -public class SocketClient { - private static Socket socket; - private static final Logger logger = LoggerFactory.getLogger(SocketClient.class); - - public static void main(String[] args) throws URISyntaxException { - IO.Options options = new IO.Options(); - options.transports = new String[]{"websocket"}; - options.reconnectionAttempts = 2; - options.reconnectionDelay = 1000; // 失败重连的时间间隔(ms) - options.timeout = 20000; // 连接超时时间(ms) - options.forceNew = true; - options.query = "username=test1&password=test1"; - socket = IO.socket("http://localhost:9099/", options); - socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() { - @Override - public void call(Object... args) { - // 客户端一旦连接成功,开始发起登录请求 - LoginRequest message = new LoginRequest(12, "这是客户端消息体"); - socket.emit("login", JsonConverter.objectToJSONObject(message), (Ack) args1 -> { - logger.info("回执消息=" + Arrays.stream(args1).map(Object::toString).collect(Collectors.joining(","))); - }); - } - }).on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener() { - @Override - public void call(Object... args) { - logger.info("Socket.EVENT_CONNECT_ERROR"); - socket.disconnect(); - } - }).on(Socket.EVENT_CONNECT_TIMEOUT, new Emitter.Listener() { - @Override - public void call(Object... args) { - logger.info("Socket.EVENT_CONNECT_TIMEOUT"); - socket.disconnect(); - } - }).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() { - @Override - public void call(Object... args) { - logger.info("客户端断开连接啦。。。"); - socket.disconnect(); - } - }); - socket.connect(); - } -} diff --git a/jun_springboot_plugin/springboot_socketio/src/test/java/com/xncoding/jwt/socket/client/html/bootstrap.css b/jun_springboot_plugin/springboot_socketio/src/test/java/com/xncoding/jwt/socket/client/html/bootstrap.css deleted file mode 100644 index bb40c85f7d..0000000000 --- a/jun_springboot_plugin/springboot_socketio/src/test/java/com/xncoding/jwt/socket/client/html/bootstrap.css +++ /dev/null @@ -1,4983 +0,0 @@ -/*! - * Bootstrap v2.0.4 - * - * Copyright 2012 Twitter, Inc - * Licensed under the Apache License v2.0 - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Designed and built with all the love in the world @twitter by @mdo and @fat. - */ - -article, -aside, -details, -figcaption, -figure, -footer, -header, -hgroup, -nav, -section { - display: block; -} - -audio, -canvas, -video { - display: inline-block; - *display: inline; - *zoom: 1; -} - -audio:not([controls]) { - display: none; -} - -html { - font-size: 100%; - -webkit-text-size-adjust: 100%; - -ms-text-size-adjust: 100%; -} - -a:focus { - outline: thin dotted #333; - outline: 5px auto -webkit-focus-ring-color; - outline-offset: -2px; -} - -a:hover, -a:active { - outline: 0; -} - -sub, -sup { - position: relative; - font-size: 75%; - line-height: 0; - vertical-align: baseline; -} - -sup { - top: -0.5em; -} - -sub { - bottom: -0.25em; -} - -img { - max-width: 100%; - vertical-align: middle; - border: 0; - -ms-interpolation-mode: bicubic; -} - -#map_canvas img { - max-width: none; -} - -button, -input, -select, -textarea { - margin: 0; - font-size: 100%; - vertical-align: middle; -} - -button, -input { - *overflow: visible; - line-height: normal; -} - -button::-moz-focus-inner, -input::-moz-focus-inner { - padding: 0; - border: 0; -} - -button, -input[type="button"], -input[type="reset"], -input[type="submit"] { - cursor: pointer; - -webkit-appearance: button; -} - -input[type="search"] { - -webkit-box-sizing: content-box; - -moz-box-sizing: content-box; - box-sizing: content-box; - -webkit-appearance: textfield; -} - -input[type="search"]::-webkit-search-decoration, -input[type="search"]::-webkit-search-cancel-button { - -webkit-appearance: none; -} - -textarea { - overflow: auto; - vertical-align: top; -} - -.clearfix { - *zoom: 1; -} - -.clearfix:before, -.clearfix:after { - display: table; - content: ""; -} - -.clearfix:after { - clear: both; -} - -.hide-text { - font: 0/0 a; - color: transparent; - text-shadow: none; - background-color: transparent; - border: 0; -} - -.input-block-level { - display: block; - width: 100%; - min-height: 28px; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - -ms-box-sizing: border-box; - box-sizing: border-box; -} - -body { - margin: 0; - font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; - font-size: 13px; - line-height: 18px; - color: #333333; - background-color: #ffffff; -} - -a { - color: #0088cc; - text-decoration: none; -} - -a:hover { - color: #005580; - text-decoration: underline; -} - -.row { - margin-left: -20px; - *zoom: 1; -} - -.row:before, -.row:after { - display: table; - content: ""; -} - -.row:after { - clear: both; -} - -[class*="span"] { - float: left; - margin-left: 20px; -} - -.container, -.navbar-fixed-top .container, -.navbar-fixed-bottom .container { - width: 940px; -} - -.span12 { - width: 940px; -} - -.span11 { - width: 860px; -} - -.span10 { - width: 780px; -} - -.span9 { - width: 700px; -} - -.span8 { - width: 620px; -} - -.span7 { - width: 540px; -} - -.span6 { - width: 460px; -} - -.span5 { - width: 380px; -} - -.span4 { - width: 300px; -} - -.span3 { - width: 220px; -} - -.span2 { - width: 140px; -} - -.span1 { - width: 60px; -} - -.offset12 { - margin-left: 980px; -} - -.offset11 { - margin-left: 900px; -} - -.offset10 { - margin-left: 820px; -} - -.offset9 { - margin-left: 740px; -} - -.offset8 { - margin-left: 660px; -} - -.offset7 { - margin-left: 580px; -} - -.offset6 { - margin-left: 500px; -} - -.offset5 { - margin-left: 420px; -} - -.offset4 { - margin-left: 340px; -} - -.offset3 { - margin-left: 260px; -} - -.offset2 { - margin-left: 180px; -} - -.offset1 { - margin-left: 100px; -} - -.row-fluid { - width: 100%; - *zoom: 1; -} - -.row-fluid:before, -.row-fluid:after { - display: table; - content: ""; -} - -.row-fluid:after { - clear: both; -} - -.row-fluid [class*="span"] { - display: block; - float: left; - width: 100%; - min-height: 28px; - margin-left: 2.127659574%; - *margin-left: 2.0744680846382977%; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - -ms-box-sizing: border-box; - box-sizing: border-box; -} - -.row-fluid [class*="span"]:first-child { - margin-left: 0; -} - -.row-fluid .span12 { - width: 99.99999998999999%; - *width: 99.94680850063828%; -} - -.row-fluid .span11 { - width: 91.489361693%; - *width: 91.4361702036383%; -} - -.row-fluid .span10 { - width: 82.97872339599999%; - *width: 82.92553190663828%; -} - -.row-fluid .span9 { - width: 74.468085099%; - *width: 74.4148936096383%; -} - -.row-fluid .span8 { - width: 65.95744680199999%; - *width: 65.90425531263828%; -} - -.row-fluid .span7 { - width: 57.446808505%; - *width: 57.3936170156383%; -} - -.row-fluid .span6 { - width: 48.93617020799999%; - *width: 48.88297871863829%; -} - -.row-fluid .span5 { - width: 40.425531911%; - *width: 40.3723404216383%; -} - -.row-fluid .span4 { - width: 31.914893614%; - *width: 31.8617021246383%; -} - -.row-fluid .span3 { - width: 23.404255317%; - *width: 23.3510638276383%; -} - -.row-fluid .span2 { - width: 14.89361702%; - *width: 14.8404255306383%; -} - -.row-fluid .span1 { - width: 6.382978723%; - *width: 6.329787233638298%; -} - -.container { - margin-right: auto; - margin-left: auto; - *zoom: 1; -} - -.container:before, -.container:after { - display: table; - content: ""; -} - -.container:after { - clear: both; -} - -.container-fluid { - padding-right: 20px; - padding-left: 20px; - *zoom: 1; -} - -.container-fluid:before, -.container-fluid:after { - display: table; - content: ""; -} - -.container-fluid:after { - clear: both; -} - -p { - margin: 0 0 9px; -} - -p small { - font-size: 11px; - color: #999999; -} - -.lead { - margin-bottom: 18px; - font-size: 20px; - font-weight: 200; - line-height: 27px; -} - -h1, -h2, -h3, -h4, -h5, -h6 { - margin: 0; - font-family: inherit; - font-weight: bold; - color: inherit; - text-rendering: optimizelegibility; -} - -h1 small, -h2 small, -h3 small, -h4 small, -h5 small, -h6 small { - font-weight: normal; - color: #999999; -} - -h1 { - font-size: 30px; - line-height: 36px; -} - -h1 small { - font-size: 18px; -} - -h2 { - font-size: 24px; - line-height: 36px; -} - -h2 small { - font-size: 18px; -} - -h3 { - font-size: 18px; - line-height: 27px; -} - -h3 small { - font-size: 14px; -} - -h4, -h5, -h6 { - line-height: 18px; -} - -h4 { - font-size: 14px; -} - -h4 small { - font-size: 12px; -} - -h5 { - font-size: 12px; -} - -h6 { - font-size: 11px; - color: #999999; - text-transform: uppercase; -} - -.page-header { - padding-bottom: 17px; - margin: 18px 0; - border-bottom: 1px solid #eeeeee; -} - -.page-header h1 { - line-height: 1; -} - -ul, -ol { - padding: 0; - margin: 0 0 9px 25px; -} - -ul ul, -ul ol, -ol ol, -ol ul { - margin-bottom: 0; -} - -ul { - list-style: disc; -} - -ol { - list-style: decimal; -} - -li { - line-height: 18px; -} - -ul.unstyled, -ol.unstyled { - margin-left: 0; - list-style: none; -} - -dl { - margin-bottom: 18px; -} - -dt, -dd { - line-height: 18px; -} - -dt { - font-weight: bold; - line-height: 17px; -} - -dd { - margin-left: 9px; -} - -.dl-horizontal dt { - float: left; - width: 120px; - overflow: hidden; - clear: left; - text-align: right; - text-overflow: ellipsis; - white-space: nowrap; -} - -.dl-horizontal dd { - margin-left: 130px; -} - -hr { - margin: 18px 0; - border: 0; - border-top: 1px solid #eeeeee; - border-bottom: 1px solid #ffffff; -} - -strong { - font-weight: bold; -} - -em { - font-style: italic; -} - -.muted { - color: #999999; -} - -abbr[title] { - cursor: help; - border-bottom: 1px dotted #999999; -} - -abbr.initialism { - font-size: 90%; - text-transform: uppercase; -} - -blockquote { - padding: 0 0 0 15px; - margin: 0 0 18px; - border-left: 5px solid #eeeeee; -} - -blockquote p { - margin-bottom: 0; - font-size: 16px; - font-weight: 300; - line-height: 22.5px; -} - -blockquote small { - display: block; - line-height: 18px; - color: #999999; -} - -blockquote small:before { - content: '\2014 \00A0'; -} - -blockquote.pull-right { - float: right; - padding-right: 15px; - padding-left: 0; - border-right: 5px solid #eeeeee; - border-left: 0; -} - -blockquote.pull-right p, -blockquote.pull-right small { - text-align: right; -} - -q:before, -q:after, -blockquote:before, -blockquote:after { - content: ""; -} - -address { - display: block; - margin-bottom: 18px; - font-style: normal; - line-height: 18px; -} - -small { - font-size: 100%; -} - -cite { - font-style: normal; -} - -code, -pre { - padding: 0 3px 2px; - font-family: Menlo, Monaco, Consolas, "Courier New", monospace; - font-size: 12px; - color: #333333; - -webkit-border-radius: 3px; - -moz-border-radius: 3px; - border-radius: 3px; -} - -code { - padding: 2px 4px; - color: #d14; - background-color: #f7f7f9; - border: 1px solid #e1e1e8; -} - -pre { - display: block; - padding: 8.5px; - margin: 0 0 9px; - font-size: 12.025px; - line-height: 18px; - word-break: break-all; - word-wrap: break-word; - white-space: pre; - white-space: pre-wrap; - background-color: #f5f5f5; - border: 1px solid #ccc; - border: 1px solid rgba(0, 0, 0, 0.15); - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; -} - -pre.prettyprint { - margin-bottom: 18px; -} - -pre code { - padding: 0; - color: inherit; - background-color: transparent; - border: 0; -} - -.pre-scrollable { - max-height: 340px; - overflow-y: scroll; -} - -form { - margin: 0 0 18px; -} - -fieldset { - padding: 0; - margin: 0; - border: 0; -} - -legend { - display: block; - width: 100%; - padding: 0; - margin-bottom: 27px; - font-size: 19.5px; - line-height: 36px; - color: #333333; - border: 0; - border-bottom: 1px solid #e5e5e5; -} - -legend small { - font-size: 13.5px; - color: #999999; -} - -label, -input, -button, -select, -textarea { - font-size: 13px; - font-weight: normal; - line-height: 18px; -} - -input, -button, -select, -textarea { - font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; -} - -label { - display: block; - margin-bottom: 5px; -} - -select, -textarea, -input[type="text"], -input[type="password"], -input[type="datetime"], -input[type="datetime-local"], -input[type="date"], -input[type="month"], -input[type="time"], -input[type="week"], -input[type="number"], -input[type="email"], -input[type="url"], -input[type="search"], -input[type="tel"], -input[type="color"], -.uneditable-input { - display: inline-block; - height: 18px; - padding: 4px; - margin-bottom: 9px; - font-size: 13px; - line-height: 18px; - color: #555555; -} - -input, -textarea { - width: 210px; -} - -textarea { - height: auto; -} - -textarea, -input[type="text"], -input[type="password"], -input[type="datetime"], -input[type="datetime-local"], -input[type="date"], -input[type="month"], -input[type="time"], -input[type="week"], -input[type="number"], -input[type="email"], -input[type="url"], -input[type="search"], -input[type="tel"], -input[type="color"], -.uneditable-input { - background-color: #ffffff; - border: 1px solid #cccccc; - -webkit-border-radius: 3px; - -moz-border-radius: 3px; - border-radius: 3px; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); - -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); - box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); - -webkit-transition: border linear 0.2s, box-shadow linear 0.2s; - -moz-transition: border linear 0.2s, box-shadow linear 0.2s; - -ms-transition: border linear 0.2s, box-shadow linear 0.2s; - -o-transition: border linear 0.2s, box-shadow linear 0.2s; - transition: border linear 0.2s, box-shadow linear 0.2s; -} - -textarea:focus, -input[type="text"]:focus, -input[type="password"]:focus, -input[type="datetime"]:focus, -input[type="datetime-local"]:focus, -input[type="date"]:focus, -input[type="month"]:focus, -input[type="time"]:focus, -input[type="week"]:focus, -input[type="number"]:focus, -input[type="email"]:focus, -input[type="url"]:focus, -input[type="search"]:focus, -input[type="tel"]:focus, -input[type="color"]:focus, -.uneditable-input:focus { - border-color: rgba(82, 168, 236, 0.8); - outline: 0; - outline: thin dotted \9; - /* IE6-9 */ - - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6); - -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6); - box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6); -} - -input[type="radio"], -input[type="checkbox"] { - margin: 3px 0; - *margin-top: 0; - /* IE7 */ - - line-height: normal; - cursor: pointer; -} - -input[type="submit"], -input[type="reset"], -input[type="button"], -input[type="radio"], -input[type="checkbox"] { - width: auto; -} - -.uneditable-textarea { - width: auto; - height: auto; -} - -select, -input[type="file"] { - height: 28px; - /* In IE7, the height of the select element cannot be changed by height, only font-size */ - - *margin-top: 4px; - /* For IE7, add top margin to align select with labels */ - - line-height: 28px; -} - -select { - width: 220px; - border: 1px solid #bbb; -} - -select[multiple], -select[size] { - height: auto; -} - -select:focus, -input[type="file"]:focus, -input[type="radio"]:focus, -input[type="checkbox"]:focus { - outline: thin dotted #333; - outline: 5px auto -webkit-focus-ring-color; - outline-offset: -2px; -} - -.radio, -.checkbox { - min-height: 18px; - padding-left: 18px; -} - -.radio input[type="radio"], -.checkbox input[type="checkbox"] { - float: left; - margin-left: -18px; -} - -.controls > .radio:first-child, -.controls > .checkbox:first-child { - padding-top: 5px; -} - -.radio.inline, -.checkbox.inline { - display: inline-block; - padding-top: 5px; - margin-bottom: 0; - vertical-align: middle; -} - -.radio.inline + .radio.inline, -.checkbox.inline + .checkbox.inline { - margin-left: 10px; -} - -.input-mini { - width: 60px; -} - -.input-small { - width: 90px; -} - -.input-medium { - width: 150px; -} - -.input-large { - width: 210px; -} - -.input-xlarge { - width: 270px; -} - -.input-xxlarge { - width: 530px; -} - -input[class*="span"], -select[class*="span"], -textarea[class*="span"], -.uneditable-input[class*="span"], -.row-fluid input[class*="span"], -.row-fluid select[class*="span"], -.row-fluid textarea[class*="span"], -.row-fluid .uneditable-input[class*="span"] { - float: none; - margin-left: 0; -} - -.input-append input[class*="span"], -.input-append .uneditable-input[class*="span"], -.input-prepend input[class*="span"], -.input-prepend .uneditable-input[class*="span"], -.row-fluid .input-prepend [class*="span"], -.row-fluid .input-append [class*="span"] { - display: inline-block; -} - -input, -textarea, -.uneditable-input { - margin-left: 0; -} - -input.span12, -textarea.span12, -.uneditable-input.span12 { - width: 930px; -} - -input.span11, -textarea.span11, -.uneditable-input.span11 { - width: 850px; -} - -input.span10, -textarea.span10, -.uneditable-input.span10 { - width: 770px; -} - -input.span9, -textarea.span9, -.uneditable-input.span9 { - width: 690px; -} - -input.span8, -textarea.span8, -.uneditable-input.span8 { - width: 610px; -} - -input.span7, -textarea.span7, -.uneditable-input.span7 { - width: 530px; -} - -input.span6, -textarea.span6, -.uneditable-input.span6 { - width: 450px; -} - -input.span5, -textarea.span5, -.uneditable-input.span5 { - width: 370px; -} - -input.span4, -textarea.span4, -.uneditable-input.span4 { - width: 290px; -} - -input.span3, -textarea.span3, -.uneditable-input.span3 { - width: 210px; -} - -input.span2, -textarea.span2, -.uneditable-input.span2 { - width: 130px; -} - -input.span1, -textarea.span1, -.uneditable-input.span1 { - width: 50px; -} - -input[disabled], -select[disabled], -textarea[disabled], -input[readonly], -select[readonly], -textarea[readonly] { - cursor: not-allowed; - background-color: #eeeeee; - border-color: #ddd; -} - -input[type="radio"][disabled], -input[type="checkbox"][disabled], -input[type="radio"][readonly], -input[type="checkbox"][readonly] { - background-color: transparent; -} - -.control-group.warning > label, -.control-group.warning .help-block, -.control-group.warning .help-inline { - color: #c09853; -} - -.control-group.warning .checkbox, -.control-group.warning .radio, -.control-group.warning input, -.control-group.warning select, -.control-group.warning textarea { - color: #c09853; - border-color: #c09853; -} - -.control-group.warning .checkbox:focus, -.control-group.warning .radio:focus, -.control-group.warning input:focus, -.control-group.warning select:focus, -.control-group.warning textarea:focus { - border-color: #a47e3c; - -webkit-box-shadow: 0 0 6px #dbc59e; - -moz-box-shadow: 0 0 6px #dbc59e; - box-shadow: 0 0 6px #dbc59e; -} - -.control-group.warning .input-prepend .add-on, -.control-group.warning .input-append .add-on { - color: #c09853; - background-color: #fcf8e3; - border-color: #c09853; -} - -.control-group.error > label, -.control-group.error .help-block, -.control-group.error .help-inline { - color: #b94a48; -} - -.control-group.error .checkbox, -.control-group.error .radio, -.control-group.error input, -.control-group.error select, -.control-group.error textarea { - color: #b94a48; - border-color: #b94a48; -} - -.control-group.error .checkbox:focus, -.control-group.error .radio:focus, -.control-group.error input:focus, -.control-group.error select:focus, -.control-group.error textarea:focus { - border-color: #953b39; - -webkit-box-shadow: 0 0 6px #d59392; - -moz-box-shadow: 0 0 6px #d59392; - box-shadow: 0 0 6px #d59392; -} - -.control-group.error .input-prepend .add-on, -.control-group.error .input-append .add-on { - color: #b94a48; - background-color: #f2dede; - border-color: #b94a48; -} - -.control-group.success > label, -.control-group.success .help-block, -.control-group.success .help-inline { - color: #468847; -} - -.control-group.success .checkbox, -.control-group.success .radio, -.control-group.success input, -.control-group.success select, -.control-group.success textarea { - color: #468847; - border-color: #468847; -} - -.control-group.success .checkbox:focus, -.control-group.success .radio:focus, -.control-group.success input:focus, -.control-group.success select:focus, -.control-group.success textarea:focus { - border-color: #356635; - -webkit-box-shadow: 0 0 6px #7aba7b; - -moz-box-shadow: 0 0 6px #7aba7b; - box-shadow: 0 0 6px #7aba7b; -} - -.control-group.success .input-prepend .add-on, -.control-group.success .input-append .add-on { - color: #468847; - background-color: #dff0d8; - border-color: #468847; -} - -input:focus:required:invalid, -textarea:focus:required:invalid, -select:focus:required:invalid { - color: #b94a48; - border-color: #ee5f5b; -} - -input:focus:required:invalid:focus, -textarea:focus:required:invalid:focus, -select:focus:required:invalid:focus { - border-color: #e9322d; - -webkit-box-shadow: 0 0 6px #f8b9b7; - -moz-box-shadow: 0 0 6px #f8b9b7; - box-shadow: 0 0 6px #f8b9b7; -} - -.form-actions { - padding: 17px 20px 18px; - margin-top: 18px; - margin-bottom: 18px; - background-color: #f5f5f5; - border-top: 1px solid #e5e5e5; - *zoom: 1; -} - -.form-actions:before, -.form-actions:after { - display: table; - content: ""; -} - -.form-actions:after { - clear: both; -} - -.uneditable-input { - overflow: hidden; - white-space: nowrap; - cursor: not-allowed; - background-color: #ffffff; - border-color: #eee; - -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.025); - -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.025); - box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.025); -} - -:-moz-placeholder { - color: #999999; -} - -:-ms-input-placeholder { - color: #999999; -} - -::-webkit-input-placeholder { - color: #999999; -} - -.help-block, -.help-inline { - color: #555555; -} - -.help-block { - display: block; - margin-bottom: 9px; -} - -.help-inline { - display: inline-block; - *display: inline; - padding-left: 5px; - vertical-align: middle; - *zoom: 1; -} - -.input-prepend, -.input-append { - margin-bottom: 5px; -} - -.input-prepend input, -.input-append input, -.input-prepend select, -.input-append select, -.input-prepend .uneditable-input, -.input-append .uneditable-input { - position: relative; - margin-bottom: 0; - *margin-left: 0; - vertical-align: middle; - -webkit-border-radius: 0 3px 3px 0; - -moz-border-radius: 0 3px 3px 0; - border-radius: 0 3px 3px 0; -} - -.input-prepend input:focus, -.input-append input:focus, -.input-prepend select:focus, -.input-append select:focus, -.input-prepend .uneditable-input:focus, -.input-append .uneditable-input:focus { - z-index: 2; -} - -.input-prepend .uneditable-input, -.input-append .uneditable-input { - border-left-color: #ccc; -} - -.input-prepend .add-on, -.input-append .add-on { - display: inline-block; - width: auto; - height: 18px; - min-width: 16px; - padding: 4px 5px; - font-weight: normal; - line-height: 18px; - text-align: center; - text-shadow: 0 1px 0 #ffffff; - vertical-align: middle; - background-color: #eeeeee; - border: 1px solid #ccc; -} - -.input-prepend .add-on, -.input-append .add-on, -.input-prepend .btn, -.input-append .btn { - margin-left: -1px; - -webkit-border-radius: 0; - -moz-border-radius: 0; - border-radius: 0; -} - -.input-prepend .active, -.input-append .active { - background-color: #a9dba9; - border-color: #46a546; -} - -.input-prepend .add-on, -.input-prepend .btn { - margin-right: -1px; -} - -.input-prepend .add-on:first-child, -.input-prepend .btn:first-child { - -webkit-border-radius: 3px 0 0 3px; - -moz-border-radius: 3px 0 0 3px; - border-radius: 3px 0 0 3px; -} - -.input-append input, -.input-append select, -.input-append .uneditable-input { - -webkit-border-radius: 3px 0 0 3px; - -moz-border-radius: 3px 0 0 3px; - border-radius: 3px 0 0 3px; -} - -.input-append .uneditable-input { - border-right-color: #ccc; - border-left-color: #eee; -} - -.input-append .add-on:last-child, -.input-append .btn:last-child { - -webkit-border-radius: 0 3px 3px 0; - -moz-border-radius: 0 3px 3px 0; - border-radius: 0 3px 3px 0; -} - -.input-prepend.input-append input, -.input-prepend.input-append select, -.input-prepend.input-append .uneditable-input { - -webkit-border-radius: 0; - -moz-border-radius: 0; - border-radius: 0; -} - -.input-prepend.input-append .add-on:first-child, -.input-prepend.input-append .btn:first-child { - margin-right: -1px; - -webkit-border-radius: 3px 0 0 3px; - -moz-border-radius: 3px 0 0 3px; - border-radius: 3px 0 0 3px; -} - -.input-prepend.input-append .add-on:last-child, -.input-prepend.input-append .btn:last-child { - margin-left: -1px; - -webkit-border-radius: 0 3px 3px 0; - -moz-border-radius: 0 3px 3px 0; - border-radius: 0 3px 3px 0; -} - -.search-query { - padding-right: 14px; - padding-right: 4px \9; - padding-left: 14px; - padding-left: 4px \9; - /* IE7-8 doesn't have border-radius, so don't indent the padding */ - - margin-bottom: 0; - -webkit-border-radius: 14px; - -moz-border-radius: 14px; - border-radius: 14px; -} - -.form-search input, -.form-inline input, -.form-horizontal input, -.form-search textarea, -.form-inline textarea, -.form-horizontal textarea, -.form-search select, -.form-inline select, -.form-horizontal select, -.form-search .help-inline, -.form-inline .help-inline, -.form-horizontal .help-inline, -.form-search .uneditable-input, -.form-inline .uneditable-input, -.form-horizontal .uneditable-input, -.form-search .input-prepend, -.form-inline .input-prepend, -.form-horizontal .input-prepend, -.form-search .input-append, -.form-inline .input-append, -.form-horizontal .input-append { - display: inline-block; - *display: inline; - margin-bottom: 0; - *zoom: 1; -} - -.form-search .hide, -.form-inline .hide, -.form-horizontal .hide { - display: none; -} - -.form-search label, -.form-inline label { - display: inline-block; -} - -.form-search .input-append, -.form-inline .input-append, -.form-search .input-prepend, -.form-inline .input-prepend { - margin-bottom: 0; -} - -.form-search .radio, -.form-search .checkbox, -.form-inline .radio, -.form-inline .checkbox { - padding-left: 0; - margin-bottom: 0; - vertical-align: middle; -} - -.form-search .radio input[type="radio"], -.form-search .checkbox input[type="checkbox"], -.form-inline .radio input[type="radio"], -.form-inline .checkbox input[type="checkbox"] { - float: left; - margin-right: 3px; - margin-left: 0; -} - -.control-group { - margin-bottom: 9px; -} - -legend + .control-group { - margin-top: 18px; - -webkit-margin-top-collapse: separate; -} - -.form-horizontal .control-group { - margin-bottom: 18px; - *zoom: 1; -} - -.form-horizontal .control-group:before, -.form-horizontal .control-group:after { - display: table; - content: ""; -} - -.form-horizontal .control-group:after { - clear: both; -} - -.form-horizontal .control-label { - float: left; - width: 140px; - padding-top: 5px; - text-align: right; -} - -.form-horizontal .controls { - *display: inline-block; - *padding-left: 20px; - margin-left: 160px; - *margin-left: 0; -} - -.form-horizontal .controls:first-child { - *padding-left: 160px; -} - -.form-horizontal .help-block { - margin-top: 9px; - margin-bottom: 0; -} - -.form-horizontal .form-actions { - padding-left: 160px; -} - -table { - max-width: 100%; - background-color: transparent; - border-collapse: collapse; - border-spacing: 0; -} - -.table { - width: 100%; - margin-bottom: 18px; -} - -.table th, -.table td { - padding: 8px; - line-height: 18px; - text-align: left; - vertical-align: top; - border-top: 1px solid #dddddd; -} - -.table th { - font-weight: bold; -} - -.table thead th { - vertical-align: bottom; -} - -.table caption + thead tr:first-child th, -.table caption + thead tr:first-child td, -.table colgroup + thead tr:first-child th, -.table colgroup + thead tr:first-child td, -.table thead:first-child tr:first-child th, -.table thead:first-child tr:first-child td { - border-top: 0; -} - -.table tbody + tbody { - border-top: 2px solid #dddddd; -} - -.table-condensed th, -.table-condensed td { - padding: 4px 5px; -} - -.table-bordered { - border: 1px solid #dddddd; - border-collapse: separate; - *border-collapse: collapsed; - border-left: 0; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; -} - -.table-bordered th, -.table-bordered td { - border-left: 1px solid #dddddd; -} - -.table-bordered caption + thead tr:first-child th, -.table-bordered caption + tbody tr:first-child th, -.table-bordered caption + tbody tr:first-child td, -.table-bordered colgroup + thead tr:first-child th, -.table-bordered colgroup + tbody tr:first-child th, -.table-bordered colgroup + tbody tr:first-child td, -.table-bordered thead:first-child tr:first-child th, -.table-bordered tbody:first-child tr:first-child th, -.table-bordered tbody:first-child tr:first-child td { - border-top: 0; -} - -.table-bordered thead:first-child tr:first-child th:first-child, -.table-bordered tbody:first-child tr:first-child td:first-child { - -webkit-border-top-left-radius: 4px; - border-top-left-radius: 4px; - -moz-border-radius-topleft: 4px; -} - -.table-bordered thead:first-child tr:first-child th:last-child, -.table-bordered tbody:first-child tr:first-child td:last-child { - -webkit-border-top-right-radius: 4px; - border-top-right-radius: 4px; - -moz-border-radius-topright: 4px; -} - -.table-bordered thead:last-child tr:last-child th:first-child, -.table-bordered tbody:last-child tr:last-child td:first-child { - -webkit-border-radius: 0 0 0 4px; - -moz-border-radius: 0 0 0 4px; - border-radius: 0 0 0 4px; - -webkit-border-bottom-left-radius: 4px; - border-bottom-left-radius: 4px; - -moz-border-radius-bottomleft: 4px; -} - -.table-bordered thead:last-child tr:last-child th:last-child, -.table-bordered tbody:last-child tr:last-child td:last-child { - -webkit-border-bottom-right-radius: 4px; - border-bottom-right-radius: 4px; - -moz-border-radius-bottomright: 4px; -} - -.table-striped tbody tr:nth-child(odd) td, -.table-striped tbody tr:nth-child(odd) th { - background-color: #f9f9f9; -} - -.table tbody tr:hover td, -.table tbody tr:hover th { - background-color: #f5f5f5; -} - -table .span1 { - float: none; - width: 44px; - margin-left: 0; -} - -table .span2 { - float: none; - width: 124px; - margin-left: 0; -} - -table .span3 { - float: none; - width: 204px; - margin-left: 0; -} - -table .span4 { - float: none; - width: 284px; - margin-left: 0; -} - -table .span5 { - float: none; - width: 364px; - margin-left: 0; -} - -table .span6 { - float: none; - width: 444px; - margin-left: 0; -} - -table .span7 { - float: none; - width: 524px; - margin-left: 0; -} - -table .span8 { - float: none; - width: 604px; - margin-left: 0; -} - -table .span9 { - float: none; - width: 684px; - margin-left: 0; -} - -table .span10 { - float: none; - width: 764px; - margin-left: 0; -} - -table .span11 { - float: none; - width: 844px; - margin-left: 0; -} - -table .span12 { - float: none; - width: 924px; - margin-left: 0; -} - -table .span13 { - float: none; - width: 1004px; - margin-left: 0; -} - -table .span14 { - float: none; - width: 1084px; - margin-left: 0; -} - -table .span15 { - float: none; - width: 1164px; - margin-left: 0; -} - -table .span16 { - float: none; - width: 1244px; - margin-left: 0; -} - -table .span17 { - float: none; - width: 1324px; - margin-left: 0; -} - -table .span18 { - float: none; - width: 1404px; - margin-left: 0; -} - -table .span19 { - float: none; - width: 1484px; - margin-left: 0; -} - -table .span20 { - float: none; - width: 1564px; - margin-left: 0; -} - -table .span21 { - float: none; - width: 1644px; - margin-left: 0; -} - -table .span22 { - float: none; - width: 1724px; - margin-left: 0; -} - -table .span23 { - float: none; - width: 1804px; - margin-left: 0; -} - -table .span24 { - float: none; - width: 1884px; - margin-left: 0; -} - -[class^="icon-"], -[class*=" icon-"] { - display: inline-block; - width: 14px; - height: 14px; - *margin-right: .3em; - line-height: 14px; - vertical-align: text-top; - background-image: url("../img/glyphicons-halflings.png"); - background-position: 14px 14px; - background-repeat: no-repeat; -} - -[class^="icon-"]:last-child, -[class*=" icon-"]:last-child { - *margin-left: 0; -} - -.icon-white { - background-image: url("../img/glyphicons-halflings-white.png"); -} - -.icon-glass { - background-position: 0 0; -} - -.icon-music { - background-position: -24px 0; -} - -.icon-search { - background-position: -48px 0; -} - -.icon-envelope { - background-position: -72px 0; -} - -.icon-heart { - background-position: -96px 0; -} - -.icon-star { - background-position: -120px 0; -} - -.icon-star-empty { - background-position: -144px 0; -} - -.icon-user { - background-position: -168px 0; -} - -.icon-film { - background-position: -192px 0; -} - -.icon-th-large { - background-position: -216px 0; -} - -.icon-th { - background-position: -240px 0; -} - -.icon-th-list { - background-position: -264px 0; -} - -.icon-ok { - background-position: -288px 0; -} - -.icon-remove { - background-position: -312px 0; -} - -.icon-zoom-in { - background-position: -336px 0; -} - -.icon-zoom-out { - background-position: -360px 0; -} - -.icon-off { - background-position: -384px 0; -} - -.icon-signal { - background-position: -408px 0; -} - -.icon-cog { - background-position: -432px 0; -} - -.icon-trash { - background-position: -456px 0; -} - -.icon-home { - background-position: 0 -24px; -} - -.icon-file { - background-position: -24px -24px; -} - -.icon-time { - background-position: -48px -24px; -} - -.icon-road { - background-position: -72px -24px; -} - -.icon-download-alt { - background-position: -96px -24px; -} - -.icon-download { - background-position: -120px -24px; -} - -.icon-upload { - background-position: -144px -24px; -} - -.icon-inbox { - background-position: -168px -24px; -} - -.icon-play-circle { - background-position: -192px -24px; -} - -.icon-repeat { - background-position: -216px -24px; -} - -.icon-refresh { - background-position: -240px -24px; -} - -.icon-list-alt { - background-position: -264px -24px; -} - -.icon-lock { - background-position: -287px -24px; -} - -.icon-flag { - background-position: -312px -24px; -} - -.icon-headphones { - background-position: -336px -24px; -} - -.icon-volume-off { - background-position: -360px -24px; -} - -.icon-volume-down { - background-position: -384px -24px; -} - -.icon-volume-up { - background-position: -408px -24px; -} - -.icon-qrcode { - background-position: -432px -24px; -} - -.icon-barcode { - background-position: -456px -24px; -} - -.icon-tag { - background-position: 0 -48px; -} - -.icon-tags { - background-position: -25px -48px; -} - -.icon-book { - background-position: -48px -48px; -} - -.icon-bookmark { - background-position: -72px -48px; -} - -.icon-print { - background-position: -96px -48px; -} - -.icon-camera { - background-position: -120px -48px; -} - -.icon-font { - background-position: -144px -48px; -} - -.icon-bold { - background-position: -167px -48px; -} - -.icon-italic { - background-position: -192px -48px; -} - -.icon-text-height { - background-position: -216px -48px; -} - -.icon-text-width { - background-position: -240px -48px; -} - -.icon-align-left { - background-position: -264px -48px; -} - -.icon-align-center { - background-position: -288px -48px; -} - -.icon-align-right { - background-position: -312px -48px; -} - -.icon-align-justify { - background-position: -336px -48px; -} - -.icon-list { - background-position: -360px -48px; -} - -.icon-indent-left { - background-position: -384px -48px; -} - -.icon-indent-right { - background-position: -408px -48px; -} - -.icon-facetime-video { - background-position: -432px -48px; -} - -.icon-picture { - background-position: -456px -48px; -} - -.icon-pencil { - background-position: 0 -72px; -} - -.icon-map-marker { - background-position: -24px -72px; -} - -.icon-adjust { - background-position: -48px -72px; -} - -.icon-tint { - background-position: -72px -72px; -} - -.icon-edit { - background-position: -96px -72px; -} - -.icon-share { - background-position: -120px -72px; -} - -.icon-check { - background-position: -144px -72px; -} - -.icon-move { - background-position: -168px -72px; -} - -.icon-step-backward { - background-position: -192px -72px; -} - -.icon-fast-backward { - background-position: -216px -72px; -} - -.icon-backward { - background-position: -240px -72px; -} - -.icon-play { - background-position: -264px -72px; -} - -.icon-pause { - background-position: -288px -72px; -} - -.icon-stop { - background-position: -312px -72px; -} - -.icon-forward { - background-position: -336px -72px; -} - -.icon-fast-forward { - background-position: -360px -72px; -} - -.icon-step-forward { - background-position: -384px -72px; -} - -.icon-eject { - background-position: -408px -72px; -} - -.icon-chevron-left { - background-position: -432px -72px; -} - -.icon-chevron-right { - background-position: -456px -72px; -} - -.icon-plus-sign { - background-position: 0 -96px; -} - -.icon-minus-sign { - background-position: -24px -96px; -} - -.icon-remove-sign { - background-position: -48px -96px; -} - -.icon-ok-sign { - background-position: -72px -96px; -} - -.icon-question-sign { - background-position: -96px -96px; -} - -.icon-info-sign { - background-position: -120px -96px; -} - -.icon-screenshot { - background-position: -144px -96px; -} - -.icon-remove-circle { - background-position: -168px -96px; -} - -.icon-ok-circle { - background-position: -192px -96px; -} - -.icon-ban-circle { - background-position: -216px -96px; -} - -.icon-arrow-left { - background-position: -240px -96px; -} - -.icon-arrow-right { - background-position: -264px -96px; -} - -.icon-arrow-up { - background-position: -289px -96px; -} - -.icon-arrow-down { - background-position: -312px -96px; -} - -.icon-share-alt { - background-position: -336px -96px; -} - -.icon-resize-full { - background-position: -360px -96px; -} - -.icon-resize-small { - background-position: -384px -96px; -} - -.icon-plus { - background-position: -408px -96px; -} - -.icon-minus { - background-position: -433px -96px; -} - -.icon-asterisk { - background-position: -456px -96px; -} - -.icon-exclamation-sign { - background-position: 0 -120px; -} - -.icon-gift { - background-position: -24px -120px; -} - -.icon-leaf { - background-position: -48px -120px; -} - -.icon-fire { - background-position: -72px -120px; -} - -.icon-eye-open { - background-position: -96px -120px; -} - -.icon-eye-close { - background-position: -120px -120px; -} - -.icon-warning-sign { - background-position: -144px -120px; -} - -.icon-plane { - background-position: -168px -120px; -} - -.icon-calendar { - background-position: -192px -120px; -} - -.icon-random { - background-position: -216px -120px; -} - -.icon-comment { - background-position: -240px -120px; -} - -.icon-magnet { - background-position: -264px -120px; -} - -.icon-chevron-up { - background-position: -288px -120px; -} - -.icon-chevron-down { - background-position: -313px -119px; -} - -.icon-retweet { - background-position: -336px -120px; -} - -.icon-shopping-cart { - background-position: -360px -120px; -} - -.icon-folder-close { - background-position: -384px -120px; -} - -.icon-folder-open { - background-position: -408px -120px; -} - -.icon-resize-vertical { - background-position: -432px -119px; -} - -.icon-resize-horizontal { - background-position: -456px -118px; -} - -.icon-hdd { - background-position: 0 -144px; -} - -.icon-bullhorn { - background-position: -24px -144px; -} - -.icon-bell { - background-position: -48px -144px; -} - -.icon-certificate { - background-position: -72px -144px; -} - -.icon-thumbs-up { - background-position: -96px -144px; -} - -.icon-thumbs-down { - background-position: -120px -144px; -} - -.icon-hand-right { - background-position: -144px -144px; -} - -.icon-hand-left { - background-position: -168px -144px; -} - -.icon-hand-up { - background-position: -192px -144px; -} - -.icon-hand-down { - background-position: -216px -144px; -} - -.icon-circle-arrow-right { - background-position: -240px -144px; -} - -.icon-circle-arrow-left { - background-position: -264px -144px; -} - -.icon-circle-arrow-up { - background-position: -288px -144px; -} - -.icon-circle-arrow-down { - background-position: -312px -144px; -} - -.icon-globe { - background-position: -336px -144px; -} - -.icon-wrench { - background-position: -360px -144px; -} - -.icon-tasks { - background-position: -384px -144px; -} - -.icon-filter { - background-position: -408px -144px; -} - -.icon-briefcase { - background-position: -432px -144px; -} - -.icon-fullscreen { - background-position: -456px -144px; -} - -.dropup, -.dropdown { - position: relative; -} - -.dropdown-toggle { - *margin-bottom: -3px; -} - -.dropdown-toggle:active, -.open .dropdown-toggle { - outline: 0; -} - -.caret { - display: inline-block; - width: 0; - height: 0; - vertical-align: top; - border-top: 4px solid #000000; - border-right: 4px solid transparent; - border-left: 4px solid transparent; - content: ""; - opacity: 0.3; - filter: alpha(opacity=30); -} - -.dropdown .caret { - margin-top: 8px; - margin-left: 2px; -} - -.dropdown:hover .caret, -.open .caret { - opacity: 1; - filter: alpha(opacity=100); -} - -.dropdown-menu { - position: absolute; - top: 100%; - left: 0; - z-index: 1000; - display: none; - float: left; - min-width: 160px; - padding: 4px 0; - margin: 1px 0 0; - list-style: none; - background-color: #ffffff; - border: 1px solid #ccc; - border: 1px solid rgba(0, 0, 0, 0.2); - *border-right-width: 2px; - *border-bottom-width: 2px; - -webkit-border-radius: 5px; - -moz-border-radius: 5px; - border-radius: 5px; - -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); - -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); - box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); - -webkit-background-clip: padding-box; - -moz-background-clip: padding; - background-clip: padding-box; -} - -.dropdown-menu.pull-right { - right: 0; - left: auto; -} - -.dropdown-menu .divider { - *width: 100%; - height: 1px; - margin: 8px 1px; - *margin: -5px 0 5px; - overflow: hidden; - background-color: #e5e5e5; - border-bottom: 1px solid #ffffff; -} - -.dropdown-menu a { - display: block; - padding: 3px 15px; - clear: both; - font-weight: normal; - line-height: 18px; - color: #333333; - white-space: nowrap; -} - -.dropdown-menu li > a:hover, -.dropdown-menu .active > a, -.dropdown-menu .active > a:hover { - color: #ffffff; - text-decoration: none; - background-color: #0088cc; -} - -.open { - *z-index: 1000; -} - -.open > .dropdown-menu { - display: block; -} - -.pull-right > .dropdown-menu { - right: 0; - left: auto; -} - -.dropup .caret, -.navbar-fixed-bottom .dropdown .caret { - border-top: 0; - border-bottom: 4px solid #000000; - content: "\2191"; -} - -.dropup .dropdown-menu, -.navbar-fixed-bottom .dropdown .dropdown-menu { - top: auto; - bottom: 100%; - margin-bottom: 1px; -} - -.typeahead { - margin-top: 2px; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; -} - -.well { - min-height: 20px; - padding: 19px; - margin-bottom: 20px; - background-color: #f5f5f5; - border: 1px solid #eee; - border: 1px solid rgba(0, 0, 0, 0.05); - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05); - -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05); - box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05); -} - -.well blockquote { - border-color: #ddd; - border-color: rgba(0, 0, 0, 0.15); -} - -.well-large { - padding: 24px; - -webkit-border-radius: 6px; - -moz-border-radius: 6px; - border-radius: 6px; -} - -.well-small { - padding: 9px; - -webkit-border-radius: 3px; - -moz-border-radius: 3px; - border-radius: 3px; -} - -.fade { - opacity: 0; - -webkit-transition: opacity 0.15s linear; - -moz-transition: opacity 0.15s linear; - -ms-transition: opacity 0.15s linear; - -o-transition: opacity 0.15s linear; - transition: opacity 0.15s linear; -} - -.fade.in { - opacity: 1; -} - -.collapse { - position: relative; - height: 0; - overflow: hidden; - -webkit-transition: height 0.35s ease; - -moz-transition: height 0.35s ease; - -ms-transition: height 0.35s ease; - -o-transition: height 0.35s ease; - transition: height 0.35s ease; -} - -.collapse.in { - height: auto; -} - -.close { - float: right; - font-size: 20px; - font-weight: bold; - line-height: 18px; - color: #000000; - text-shadow: 0 1px 0 #ffffff; - opacity: 0.2; - filter: alpha(opacity=20); -} - -.close:hover { - color: #000000; - text-decoration: none; - cursor: pointer; - opacity: 0.4; - filter: alpha(opacity=40); -} - -button.close { - padding: 0; - cursor: pointer; - background: transparent; - border: 0; - -webkit-appearance: none; -} - -.btn { - display: inline-block; - *display: inline; - padding: 4px 10px 4px; - margin-bottom: 0; - *margin-left: .3em; - font-size: 13px; - line-height: 18px; - *line-height: 20px; - color: #333333; - text-align: center; - text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75); - vertical-align: middle; - cursor: pointer; - background-color: #f5f5f5; - *background-color: #e6e6e6; - background-image: -ms-linear-gradient(top, #ffffff, #e6e6e6); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#e6e6e6)); - background-image: -webkit-linear-gradient(top, #ffffff, #e6e6e6); - background-image: -o-linear-gradient(top, #ffffff, #e6e6e6); - background-image: linear-gradient(top, #ffffff, #e6e6e6); - background-image: -moz-linear-gradient(top, #ffffff, #e6e6e6); - background-repeat: repeat-x; - border: 1px solid #cccccc; - *border: 0; - border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); - border-color: #e6e6e6 #e6e6e6 #bfbfbf; - border-bottom-color: #b3b3b3; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; - filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ffffff', endColorstr='#e6e6e6', GradientType=0); - filter: progid:dximagetransform.microsoft.gradient(enabled=false); - *zoom: 1; - -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); - -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); - box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); -} - -.btn:hover, -.btn:active, -.btn.active, -.btn.disabled, -.btn[disabled] { - background-color: #e6e6e6; - *background-color: #d9d9d9; -} - -.btn:active, -.btn.active { - background-color: #cccccc \9; -} - -.btn:first-child { - *margin-left: 0; -} - -.btn:hover { - color: #333333; - text-decoration: none; - background-color: #e6e6e6; - *background-color: #d9d9d9; - /* Buttons in IE7 don't get borders, so darken on hover */ - - background-position: 0 -15px; - -webkit-transition: background-position 0.1s linear; - -moz-transition: background-position 0.1s linear; - -ms-transition: background-position 0.1s linear; - -o-transition: background-position 0.1s linear; - transition: background-position 0.1s linear; -} - -.btn:focus { - outline: thin dotted #333; - outline: 5px auto -webkit-focus-ring-color; - outline-offset: -2px; -} - -.btn.active, -.btn:active { - background-color: #e6e6e6; - background-color: #d9d9d9 \9; - background-image: none; - outline: 0; - -webkit-box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); - -moz-box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); - box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); -} - -.btn.disabled, -.btn[disabled] { - cursor: default; - background-color: #e6e6e6; - background-image: none; - opacity: 0.65; - filter: alpha(opacity=65); - -webkit-box-shadow: none; - -moz-box-shadow: none; - box-shadow: none; -} - -.btn-large { - padding: 9px 14px; - font-size: 15px; - line-height: normal; - -webkit-border-radius: 5px; - -moz-border-radius: 5px; - border-radius: 5px; -} - -.btn-large [class^="icon-"] { - margin-top: 1px; -} - -.btn-small { - padding: 5px 9px; - font-size: 11px; - line-height: 16px; -} - -.btn-small [class^="icon-"] { - margin-top: -1px; -} - -.btn-mini { - padding: 2px 6px; - font-size: 11px; - line-height: 14px; -} - -.btn-primary, -.btn-primary:hover, -.btn-warning, -.btn-warning:hover, -.btn-danger, -.btn-danger:hover, -.btn-success, -.btn-success:hover, -.btn-info, -.btn-info:hover, -.btn-inverse, -.btn-inverse:hover { - color: #ffffff; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); -} - -.btn-primary.active, -.btn-warning.active, -.btn-danger.active, -.btn-success.active, -.btn-info.active, -.btn-inverse.active { - color: rgba(255, 255, 255, 0.75); -} - -.btn { - border-color: #ccc; - border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); -} - -.btn-primary { - background-color: #0074cc; - *background-color: #0055cc; - background-image: -ms-linear-gradient(top, #0088cc, #0055cc); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0055cc)); - background-image: -webkit-linear-gradient(top, #0088cc, #0055cc); - background-image: -o-linear-gradient(top, #0088cc, #0055cc); - background-image: -moz-linear-gradient(top, #0088cc, #0055cc); - background-image: linear-gradient(top, #0088cc, #0055cc); - background-repeat: repeat-x; - border-color: #0055cc #0055cc #003580; - border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); - filter: progid:dximagetransform.microsoft.gradient(startColorstr='#0088cc', endColorstr='#0055cc', GradientType=0); - filter: progid:dximagetransform.microsoft.gradient(enabled=false); -} - -.btn-primary:hover, -.btn-primary:active, -.btn-primary.active, -.btn-primary.disabled, -.btn-primary[disabled] { - background-color: #0055cc; - *background-color: #004ab3; -} - -.btn-primary:active, -.btn-primary.active { - background-color: #004099 \9; -} - -.btn-warning { - background-color: #faa732; - *background-color: #f89406; - background-image: -ms-linear-gradient(top, #fbb450, #f89406); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406)); - background-image: -webkit-linear-gradient(top, #fbb450, #f89406); - background-image: -o-linear-gradient(top, #fbb450, #f89406); - background-image: -moz-linear-gradient(top, #fbb450, #f89406); - background-image: linear-gradient(top, #fbb450, #f89406); - background-repeat: repeat-x; - border-color: #f89406 #f89406 #ad6704; - border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); - filter: progid:dximagetransform.microsoft.gradient(startColorstr='#fbb450', endColorstr='#f89406', GradientType=0); - filter: progid:dximagetransform.microsoft.gradient(enabled=false); -} - -.btn-warning:hover, -.btn-warning:active, -.btn-warning.active, -.btn-warning.disabled, -.btn-warning[disabled] { - background-color: #f89406; - *background-color: #df8505; -} - -.btn-warning:active, -.btn-warning.active { - background-color: #c67605 \9; -} - -.btn-danger { - background-color: #da4f49; - *background-color: #bd362f; - background-image: -ms-linear-gradient(top, #ee5f5b, #bd362f); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ee5f5b), to(#bd362f)); - background-image: -webkit-linear-gradient(top, #ee5f5b, #bd362f); - background-image: -o-linear-gradient(top, #ee5f5b, #bd362f); - background-image: -moz-linear-gradient(top, #ee5f5b, #bd362f); - background-image: linear-gradient(top, #ee5f5b, #bd362f); - background-repeat: repeat-x; - border-color: #bd362f #bd362f #802420; - border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); - filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ee5f5b', endColorstr='#bd362f', GradientType=0); - filter: progid:dximagetransform.microsoft.gradient(enabled=false); -} - -.btn-danger:hover, -.btn-danger:active, -.btn-danger.active, -.btn-danger.disabled, -.btn-danger[disabled] { - background-color: #bd362f; - *background-color: #a9302a; -} - -.btn-danger:active, -.btn-danger.active { - background-color: #942a25 \9; -} - -.btn-success { - background-color: #5bb75b; - *background-color: #51a351; - background-image: -ms-linear-gradient(top, #62c462, #51a351); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#62c462), to(#51a351)); - background-image: -webkit-linear-gradient(top, #62c462, #51a351); - background-image: -o-linear-gradient(top, #62c462, #51a351); - background-image: -moz-linear-gradient(top, #62c462, #51a351); - background-image: linear-gradient(top, #62c462, #51a351); - background-repeat: repeat-x; - border-color: #51a351 #51a351 #387038; - border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); - filter: progid:dximagetransform.microsoft.gradient(startColorstr='#62c462', endColorstr='#51a351', GradientType=0); - filter: progid:dximagetransform.microsoft.gradient(enabled=false); -} - -.btn-success:hover, -.btn-success:active, -.btn-success.active, -.btn-success.disabled, -.btn-success[disabled] { - background-color: #51a351; - *background-color: #499249; -} - -.btn-success:active, -.btn-success.active { - background-color: #408140 \9; -} - -.btn-info { - background-color: #49afcd; - *background-color: #2f96b4; - background-image: -ms-linear-gradient(top, #5bc0de, #2f96b4); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#2f96b4)); - background-image: -webkit-linear-gradient(top, #5bc0de, #2f96b4); - background-image: -o-linear-gradient(top, #5bc0de, #2f96b4); - background-image: -moz-linear-gradient(top, #5bc0de, #2f96b4); - background-image: linear-gradient(top, #5bc0de, #2f96b4); - background-repeat: repeat-x; - border-color: #2f96b4 #2f96b4 #1f6377; - border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); - filter: progid:dximagetransform.microsoft.gradient(startColorstr='#5bc0de', endColorstr='#2f96b4', GradientType=0); - filter: progid:dximagetransform.microsoft.gradient(enabled=false); -} - -.btn-info:hover, -.btn-info:active, -.btn-info.active, -.btn-info.disabled, -.btn-info[disabled] { - background-color: #2f96b4; - *background-color: #2a85a0; -} - -.btn-info:active, -.btn-info.active { - background-color: #24748c \9; -} - -.btn-inverse { - background-color: #414141; - *background-color: #222222; - background-image: -ms-linear-gradient(top, #555555, #222222); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#555555), to(#222222)); - background-image: -webkit-linear-gradient(top, #555555, #222222); - background-image: -o-linear-gradient(top, #555555, #222222); - background-image: -moz-linear-gradient(top, #555555, #222222); - background-image: linear-gradient(top, #555555, #222222); - background-repeat: repeat-x; - border-color: #222222 #222222 #000000; - border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); - filter: progid:dximagetransform.microsoft.gradient(startColorstr='#555555', endColorstr='#222222', GradientType=0); - filter: progid:dximagetransform.microsoft.gradient(enabled=false); -} - -.btn-inverse:hover, -.btn-inverse:active, -.btn-inverse.active, -.btn-inverse.disabled, -.btn-inverse[disabled] { - background-color: #222222; - *background-color: #151515; -} - -.btn-inverse:active, -.btn-inverse.active { - background-color: #080808 \9; -} - -button.btn, -input[type="submit"].btn { - *padding-top: 2px; - *padding-bottom: 2px; -} - -button.btn::-moz-focus-inner, -input[type="submit"].btn::-moz-focus-inner { - padding: 0; - border: 0; -} - -button.btn.btn-large, -input[type="submit"].btn.btn-large { - *padding-top: 7px; - *padding-bottom: 7px; -} - -button.btn.btn-small, -input[type="submit"].btn.btn-small { - *padding-top: 3px; - *padding-bottom: 3px; -} - -button.btn.btn-mini, -input[type="submit"].btn.btn-mini { - *padding-top: 1px; - *padding-bottom: 1px; -} - -.btn-group { - position: relative; - *margin-left: .3em; - *zoom: 1; -} - -.btn-group:before, -.btn-group:after { - display: table; - content: ""; -} - -.btn-group:after { - clear: both; -} - -.btn-group:first-child { - *margin-left: 0; -} - -.btn-group + .btn-group { - margin-left: 5px; -} - -.btn-toolbar { - margin-top: 9px; - margin-bottom: 9px; -} - -.btn-toolbar .btn-group { - display: inline-block; - *display: inline; - /* IE7 inline-block hack */ - - *zoom: 1; -} - -.btn-group > .btn { - position: relative; - float: left; - margin-left: -1px; - -webkit-border-radius: 0; - -moz-border-radius: 0; - border-radius: 0; -} - -.btn-group > .btn:first-child { - margin-left: 0; - -webkit-border-bottom-left-radius: 4px; - border-bottom-left-radius: 4px; - -webkit-border-top-left-radius: 4px; - border-top-left-radius: 4px; - -moz-border-radius-bottomleft: 4px; - -moz-border-radius-topleft: 4px; -} - -.btn-group > .btn:last-child, -.btn-group > .dropdown-toggle { - -webkit-border-top-right-radius: 4px; - border-top-right-radius: 4px; - -webkit-border-bottom-right-radius: 4px; - border-bottom-right-radius: 4px; - -moz-border-radius-topright: 4px; - -moz-border-radius-bottomright: 4px; -} - -.btn-group > .btn.large:first-child { - margin-left: 0; - -webkit-border-bottom-left-radius: 6px; - border-bottom-left-radius: 6px; - -webkit-border-top-left-radius: 6px; - border-top-left-radius: 6px; - -moz-border-radius-bottomleft: 6px; - -moz-border-radius-topleft: 6px; -} - -.btn-group > .btn.large:last-child, -.btn-group > .large.dropdown-toggle { - -webkit-border-top-right-radius: 6px; - border-top-right-radius: 6px; - -webkit-border-bottom-right-radius: 6px; - border-bottom-right-radius: 6px; - -moz-border-radius-topright: 6px; - -moz-border-radius-bottomright: 6px; -} - -.btn-group > .btn:hover, -.btn-group > .btn:focus, -.btn-group > .btn:active, -.btn-group > .btn.active { - z-index: 2; -} - -.btn-group .dropdown-toggle:active, -.btn-group.open .dropdown-toggle { - outline: 0; -} - -.btn-group > .dropdown-toggle { - *padding-top: 4px; - padding-right: 8px; - *padding-bottom: 4px; - padding-left: 8px; - -webkit-box-shadow: inset 1px 0 0 rgba(255, 255, 255, 0.125), inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); - -moz-box-shadow: inset 1px 0 0 rgba(255, 255, 255, 0.125), inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); - box-shadow: inset 1px 0 0 rgba(255, 255, 255, 0.125), inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); -} - -.btn-group > .btn-mini.dropdown-toggle { - padding-right: 5px; - padding-left: 5px; -} - -.btn-group > .btn-small.dropdown-toggle { - *padding-top: 4px; - *padding-bottom: 4px; -} - -.btn-group > .btn-large.dropdown-toggle { - padding-right: 12px; - padding-left: 12px; -} - -.btn-group.open .dropdown-toggle { - background-image: none; - -webkit-box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); - -moz-box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); - box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); -} - -.btn-group.open .btn.dropdown-toggle { - background-color: #e6e6e6; -} - -.btn-group.open .btn-primary.dropdown-toggle { - background-color: #0055cc; -} - -.btn-group.open .btn-warning.dropdown-toggle { - background-color: #f89406; -} - -.btn-group.open .btn-danger.dropdown-toggle { - background-color: #bd362f; -} - -.btn-group.open .btn-success.dropdown-toggle { - background-color: #51a351; -} - -.btn-group.open .btn-info.dropdown-toggle { - background-color: #2f96b4; -} - -.btn-group.open .btn-inverse.dropdown-toggle { - background-color: #222222; -} - -.btn .caret { - margin-top: 7px; - margin-left: 0; -} - -.btn:hover .caret, -.open.btn-group .caret { - opacity: 1; - filter: alpha(opacity=100); -} - -.btn-mini .caret { - margin-top: 5px; -} - -.btn-small .caret { - margin-top: 6px; -} - -.btn-large .caret { - margin-top: 6px; - border-top-width: 5px; - border-right-width: 5px; - border-left-width: 5px; -} - -.dropup .btn-large .caret { - border-top: 0; - border-bottom: 5px solid #000000; -} - -.btn-primary .caret, -.btn-warning .caret, -.btn-danger .caret, -.btn-info .caret, -.btn-success .caret, -.btn-inverse .caret { - border-top-color: #ffffff; - border-bottom-color: #ffffff; - opacity: 0.75; - filter: alpha(opacity=75); -} - -.alert { - padding: 8px 35px 8px 14px; - margin-bottom: 18px; - color: #c09853; - text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); - background-color: #fcf8e3; - border: 1px solid #fbeed5; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; -} - -.alert-heading { - color: inherit; -} - -.alert .close { - position: relative; - top: -2px; - right: -21px; - line-height: 18px; -} - -.alert-success { - color: #468847; - background-color: #dff0d8; - border-color: #d6e9c6; -} - -.alert-danger, -.alert-error { - color: #b94a48; - background-color: #f2dede; - border-color: #eed3d7; -} - -.alert-info { - color: #3a87ad; - background-color: #d9edf7; - border-color: #bce8f1; -} - -.alert-block { - padding-top: 14px; - padding-bottom: 14px; -} - -.alert-block > p, -.alert-block > ul { - margin-bottom: 0; -} - -.alert-block p + p { - margin-top: 5px; -} - -.nav { - margin-bottom: 18px; - margin-left: 0; - list-style: none; -} - -.nav > li > a { - display: block; -} - -.nav > li > a:hover { - text-decoration: none; - background-color: #eeeeee; -} - -.nav > .pull-right { - float: right; -} - -.nav .nav-header { - display: block; - padding: 3px 15px; - font-size: 11px; - font-weight: bold; - line-height: 18px; - color: #999999; - text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); - text-transform: uppercase; -} - -.nav li + .nav-header { - margin-top: 9px; -} - -.nav-list { - padding-right: 15px; - padding-left: 15px; - margin-bottom: 0; -} - -.nav-list > li > a, -.nav-list .nav-header { - margin-right: -15px; - margin-left: -15px; - text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); -} - -.nav-list > li > a { - padding: 3px 15px; -} - -.nav-list > .active > a, -.nav-list > .active > a:hover { - color: #ffffff; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.2); - background-color: #0088cc; -} - -.nav-list [class^="icon-"] { - margin-right: 2px; -} - -.nav-list .divider { - *width: 100%; - height: 1px; - margin: 8px 1px; - *margin: -5px 0 5px; - overflow: hidden; - background-color: #e5e5e5; - border-bottom: 1px solid #ffffff; -} - -.nav-tabs, -.nav-pills { - *zoom: 1; -} - -.nav-tabs:before, -.nav-pills:before, -.nav-tabs:after, -.nav-pills:after { - display: table; - content: ""; -} - -.nav-tabs:after, -.nav-pills:after { - clear: both; -} - -.nav-tabs > li, -.nav-pills > li { - float: left; -} - -.nav-tabs > li > a, -.nav-pills > li > a { - padding-right: 12px; - padding-left: 12px; - margin-right: 2px; - line-height: 14px; -} - -.nav-tabs { - border-bottom: 1px solid #ddd; -} - -.nav-tabs > li { - margin-bottom: -1px; -} - -.nav-tabs > li > a { - padding-top: 8px; - padding-bottom: 8px; - line-height: 18px; - border: 1px solid transparent; - -webkit-border-radius: 4px 4px 0 0; - -moz-border-radius: 4px 4px 0 0; - border-radius: 4px 4px 0 0; -} - -.nav-tabs > li > a:hover { - border-color: #eeeeee #eeeeee #dddddd; -} - -.nav-tabs > .active > a, -.nav-tabs > .active > a:hover { - color: #555555; - cursor: default; - background-color: #ffffff; - border: 1px solid #ddd; - border-bottom-color: transparent; -} - -.nav-pills > li > a { - padding-top: 8px; - padding-bottom: 8px; - margin-top: 2px; - margin-bottom: 2px; - -webkit-border-radius: 5px; - -moz-border-radius: 5px; - border-radius: 5px; -} - -.nav-pills > .active > a, -.nav-pills > .active > a:hover { - color: #ffffff; - background-color: #0088cc; -} - -.nav-stacked > li { - float: none; -} - -.nav-stacked > li > a { - margin-right: 0; -} - -.nav-tabs.nav-stacked { - border-bottom: 0; -} - -.nav-tabs.nav-stacked > li > a { - border: 1px solid #ddd; - -webkit-border-radius: 0; - -moz-border-radius: 0; - border-radius: 0; -} - -.nav-tabs.nav-stacked > li:first-child > a { - -webkit-border-radius: 4px 4px 0 0; - -moz-border-radius: 4px 4px 0 0; - border-radius: 4px 4px 0 0; -} - -.nav-tabs.nav-stacked > li:last-child > a { - -webkit-border-radius: 0 0 4px 4px; - -moz-border-radius: 0 0 4px 4px; - border-radius: 0 0 4px 4px; -} - -.nav-tabs.nav-stacked > li > a:hover { - z-index: 2; - border-color: #ddd; -} - -.nav-pills.nav-stacked > li > a { - margin-bottom: 3px; -} - -.nav-pills.nav-stacked > li:last-child > a { - margin-bottom: 1px; -} - -.nav-tabs .dropdown-menu { - -webkit-border-radius: 0 0 5px 5px; - -moz-border-radius: 0 0 5px 5px; - border-radius: 0 0 5px 5px; -} - -.nav-pills .dropdown-menu { - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; -} - -.nav-tabs .dropdown-toggle .caret, -.nav-pills .dropdown-toggle .caret { - margin-top: 6px; - border-top-color: #0088cc; - border-bottom-color: #0088cc; -} - -.nav-tabs .dropdown-toggle:hover .caret, -.nav-pills .dropdown-toggle:hover .caret { - border-top-color: #005580; - border-bottom-color: #005580; -} - -.nav-tabs .active .dropdown-toggle .caret, -.nav-pills .active .dropdown-toggle .caret { - border-top-color: #333333; - border-bottom-color: #333333; -} - -.nav > .dropdown.active > a:hover { - color: #000000; - cursor: pointer; -} - -.nav-tabs .open .dropdown-toggle, -.nav-pills .open .dropdown-toggle, -.nav > li.dropdown.open.active > a:hover { - color: #ffffff; - background-color: #999999; - border-color: #999999; -} - -.nav li.dropdown.open .caret, -.nav li.dropdown.open.active .caret, -.nav li.dropdown.open a:hover .caret { - border-top-color: #ffffff; - border-bottom-color: #ffffff; - opacity: 1; - filter: alpha(opacity=100); -} - -.tabs-stacked .open > a:hover { - border-color: #999999; -} - -.tabbable { - *zoom: 1; -} - -.tabbable:before, -.tabbable:after { - display: table; - content: ""; -} - -.tabbable:after { - clear: both; -} - -.tab-content { - overflow: auto; -} - -.tabs-below > .nav-tabs, -.tabs-right > .nav-tabs, -.tabs-left > .nav-tabs { - border-bottom: 0; -} - -.tab-content > .tab-pane, -.pill-content > .pill-pane { - display: none; -} - -.tab-content > .active, -.pill-content > .active { - display: block; -} - -.tabs-below > .nav-tabs { - border-top: 1px solid #ddd; -} - -.tabs-below > .nav-tabs > li { - margin-top: -1px; - margin-bottom: 0; -} - -.tabs-below > .nav-tabs > li > a { - -webkit-border-radius: 0 0 4px 4px; - -moz-border-radius: 0 0 4px 4px; - border-radius: 0 0 4px 4px; -} - -.tabs-below > .nav-tabs > li > a:hover { - border-top-color: #ddd; - border-bottom-color: transparent; -} - -.tabs-below > .nav-tabs > .active > a, -.tabs-below > .nav-tabs > .active > a:hover { - border-color: transparent #ddd #ddd #ddd; -} - -.tabs-left > .nav-tabs > li, -.tabs-right > .nav-tabs > li { - float: none; -} - -.tabs-left > .nav-tabs > li > a, -.tabs-right > .nav-tabs > li > a { - min-width: 74px; - margin-right: 0; - margin-bottom: 3px; -} - -.tabs-left > .nav-tabs { - float: left; - margin-right: 19px; - border-right: 1px solid #ddd; -} - -.tabs-left > .nav-tabs > li > a { - margin-right: -1px; - -webkit-border-radius: 4px 0 0 4px; - -moz-border-radius: 4px 0 0 4px; - border-radius: 4px 0 0 4px; -} - -.tabs-left > .nav-tabs > li > a:hover { - border-color: #eeeeee #dddddd #eeeeee #eeeeee; -} - -.tabs-left > .nav-tabs .active > a, -.tabs-left > .nav-tabs .active > a:hover { - border-color: #ddd transparent #ddd #ddd; - *border-right-color: #ffffff; -} - -.tabs-right > .nav-tabs { - float: right; - margin-left: 19px; - border-left: 1px solid #ddd; -} - -.tabs-right > .nav-tabs > li > a { - margin-left: -1px; - -webkit-border-radius: 0 4px 4px 0; - -moz-border-radius: 0 4px 4px 0; - border-radius: 0 4px 4px 0; -} - -.tabs-right > .nav-tabs > li > a:hover { - border-color: #eeeeee #eeeeee #eeeeee #dddddd; -} - -.tabs-right > .nav-tabs .active > a, -.tabs-right > .nav-tabs .active > a:hover { - border-color: #ddd #ddd #ddd transparent; - *border-left-color: #ffffff; -} - -.navbar { - *position: relative; - *z-index: 2; - margin-bottom: 18px; - overflow: visible; -} - -.navbar-inner { - min-height: 40px; - padding-right: 20px; - padding-left: 20px; - background-color: #2c2c2c; - background-image: -moz-linear-gradient(top, #333333, #222222); - background-image: -ms-linear-gradient(top, #333333, #222222); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#333333), to(#222222)); - background-image: -webkit-linear-gradient(top, #333333, #222222); - background-image: -o-linear-gradient(top, #333333, #222222); - background-image: linear-gradient(top, #333333, #222222); - background-repeat: repeat-x; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; - filter: progid:dximagetransform.microsoft.gradient(startColorstr='#333333', endColorstr='#222222', GradientType=0); - -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25), inset 0 -1px 0 rgba(0, 0, 0, 0.1); - -moz-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25), inset 0 -1px 0 rgba(0, 0, 0, 0.1); - box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25), inset 0 -1px 0 rgba(0, 0, 0, 0.1); -} - -.navbar .container { - width: auto; -} - -.nav-collapse.collapse { - height: auto; -} - -.navbar { - color: #999999; -} - -.navbar .brand:hover { - text-decoration: none; -} - -.navbar .brand { - display: block; - float: left; - padding: 8px 20px 12px; - margin-left: -20px; - font-size: 20px; - font-weight: 200; - line-height: 1; - color: #999999; -} - -.navbar .navbar-text { - margin-bottom: 0; - line-height: 40px; -} - -.navbar .navbar-link { - color: #999999; -} - -.navbar .navbar-link:hover { - color: #ffffff; -} - -.navbar .btn, -.navbar .btn-group { - margin-top: 5px; -} - -.navbar .btn-group .btn { - margin: 0; -} - -.navbar-form { - margin-bottom: 0; - *zoom: 1; -} - -.navbar-form:before, -.navbar-form:after { - display: table; - content: ""; -} - -.navbar-form:after { - clear: both; -} - -.navbar-form input, -.navbar-form select, -.navbar-form .radio, -.navbar-form .checkbox { - margin-top: 5px; -} - -.navbar-form input, -.navbar-form select { - display: inline-block; - margin-bottom: 0; -} - -.navbar-form input[type="image"], -.navbar-form input[type="checkbox"], -.navbar-form input[type="radio"] { - margin-top: 3px; -} - -.navbar-form .input-append, -.navbar-form .input-prepend { - margin-top: 6px; - white-space: nowrap; -} - -.navbar-form .input-append input, -.navbar-form .input-prepend input { - margin-top: 0; -} - -.navbar-search { - position: relative; - float: left; - margin-top: 6px; - margin-bottom: 0; -} - -.navbar-search .search-query { - padding: 4px 9px; - font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; - font-size: 13px; - font-weight: normal; - line-height: 1; - color: #ffffff; - background-color: #626262; - border: 1px solid #151515; - -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 1px 0 rgba(255, 255, 255, 0.15); - -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 1px 0 rgba(255, 255, 255, 0.15); - box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 1px 0 rgba(255, 255, 255, 0.15); - -webkit-transition: none; - -moz-transition: none; - -ms-transition: none; - -o-transition: none; - transition: none; -} - -.navbar-search .search-query:-moz-placeholder { - color: #cccccc; -} - -.navbar-search .search-query:-ms-input-placeholder { - color: #cccccc; -} - -.navbar-search .search-query::-webkit-input-placeholder { - color: #cccccc; -} - -.navbar-search .search-query:focus, -.navbar-search .search-query.focused { - padding: 5px 10px; - color: #333333; - text-shadow: 0 1px 0 #ffffff; - background-color: #ffffff; - border: 0; - outline: 0; - -webkit-box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); - -moz-box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); - box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); -} - -.navbar-fixed-top, -.navbar-fixed-bottom { - position: fixed; - right: 0; - left: 0; - z-index: 1030; - margin-bottom: 0; -} - -.navbar-fixed-top .navbar-inner, -.navbar-fixed-bottom .navbar-inner { - padding-right: 0; - padding-left: 0; - -webkit-border-radius: 0; - -moz-border-radius: 0; - border-radius: 0; -} - -.navbar-fixed-top .container, -.navbar-fixed-bottom .container { - width: 940px; -} - -.navbar-fixed-top { - top: 0; -} - -.navbar-fixed-bottom { - bottom: 0; -} - -.navbar .nav { - position: relative; - left: 0; - display: block; - float: left; - margin: 0 10px 0 0; -} - -.navbar .nav.pull-right { - float: right; -} - -.navbar .nav > li { - display: block; - float: left; -} - -.navbar .nav > li > a { - float: none; - padding: 9px 10px 11px; - line-height: 19px; - color: #999999; - text-decoration: none; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); -} - -.navbar .btn { - display: inline-block; - padding: 4px 10px 4px; - margin: 5px 5px 6px; - line-height: 18px; -} - -.navbar .btn-group { - padding: 5px 5px 6px; - margin: 0; -} - -.navbar .nav > li > a:hover { - color: #ffffff; - text-decoration: none; - background-color: transparent; -} - -.navbar .nav .active > a, -.navbar .nav .active > a:hover { - color: #ffffff; - text-decoration: none; - background-color: #222222; -} - -.navbar .divider-vertical { - width: 1px; - height: 40px; - margin: 0 9px; - overflow: hidden; - background-color: #222222; - border-right: 1px solid #333333; -} - -.navbar .nav.pull-right { - margin-right: 0; - margin-left: 10px; -} - -.navbar .btn-navbar { - display: none; - float: right; - padding: 7px 10px; - margin-right: 5px; - margin-left: 5px; - background-color: #2c2c2c; - *background-color: #222222; - background-image: -ms-linear-gradient(top, #333333, #222222); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#333333), to(#222222)); - background-image: -webkit-linear-gradient(top, #333333, #222222); - background-image: -o-linear-gradient(top, #333333, #222222); - background-image: linear-gradient(top, #333333, #222222); - background-image: -moz-linear-gradient(top, #333333, #222222); - background-repeat: repeat-x; - border-color: #222222 #222222 #000000; - border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); - filter: progid:dximagetransform.microsoft.gradient(startColorstr='#333333', endColorstr='#222222', GradientType=0); - filter: progid:dximagetransform.microsoft.gradient(enabled=false); - -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.075); - -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.075); - box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.075); -} - -.navbar .btn-navbar:hover, -.navbar .btn-navbar:active, -.navbar .btn-navbar.active, -.navbar .btn-navbar.disabled, -.navbar .btn-navbar[disabled] { - background-color: #222222; - *background-color: #151515; -} - -.navbar .btn-navbar:active, -.navbar .btn-navbar.active { - background-color: #080808 \9; -} - -.navbar .btn-navbar .icon-bar { - display: block; - width: 18px; - height: 2px; - background-color: #f5f5f5; - -webkit-border-radius: 1px; - -moz-border-radius: 1px; - border-radius: 1px; - -webkit-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); - -moz-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); - box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); -} - -.btn-navbar .icon-bar + .icon-bar { - margin-top: 3px; -} - -.navbar .dropdown-menu:before { - position: absolute; - top: -7px; - left: 9px; - display: inline-block; - border-right: 7px solid transparent; - border-bottom: 7px solid #ccc; - border-left: 7px solid transparent; - border-bottom-color: rgba(0, 0, 0, 0.2); - content: ''; -} - -.navbar .dropdown-menu:after { - position: absolute; - top: -6px; - left: 10px; - display: inline-block; - border-right: 6px solid transparent; - border-bottom: 6px solid #ffffff; - border-left: 6px solid transparent; - content: ''; -} - -.navbar-fixed-bottom .dropdown-menu:before { - top: auto; - bottom: -7px; - border-top: 7px solid #ccc; - border-bottom: 0; - border-top-color: rgba(0, 0, 0, 0.2); -} - -.navbar-fixed-bottom .dropdown-menu:after { - top: auto; - bottom: -6px; - border-top: 6px solid #ffffff; - border-bottom: 0; -} - -.navbar .nav li.dropdown .dropdown-toggle .caret, -.navbar .nav li.dropdown.open .caret { - border-top-color: #ffffff; - border-bottom-color: #ffffff; -} - -.navbar .nav li.dropdown.active .caret { - opacity: 1; - filter: alpha(opacity=100); -} - -.navbar .nav li.dropdown.open > .dropdown-toggle, -.navbar .nav li.dropdown.active > .dropdown-toggle, -.navbar .nav li.dropdown.open.active > .dropdown-toggle { - background-color: transparent; -} - -.navbar .nav li.dropdown.active > .dropdown-toggle:hover { - color: #ffffff; -} - -.navbar .pull-right .dropdown-menu, -.navbar .dropdown-menu.pull-right { - right: 0; - left: auto; -} - -.navbar .pull-right .dropdown-menu:before, -.navbar .dropdown-menu.pull-right:before { - right: 12px; - left: auto; -} - -.navbar .pull-right .dropdown-menu:after, -.navbar .dropdown-menu.pull-right:after { - right: 13px; - left: auto; -} - -.breadcrumb { - padding: 7px 14px; - margin: 0 0 18px; - list-style: none; - background-color: #fbfbfb; - background-image: -moz-linear-gradient(top, #ffffff, #f5f5f5); - background-image: -ms-linear-gradient(top, #ffffff, #f5f5f5); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#f5f5f5)); - background-image: -webkit-linear-gradient(top, #ffffff, #f5f5f5); - background-image: -o-linear-gradient(top, #ffffff, #f5f5f5); - background-image: linear-gradient(top, #ffffff, #f5f5f5); - background-repeat: repeat-x; - border: 1px solid #ddd; - -webkit-border-radius: 3px; - -moz-border-radius: 3px; - border-radius: 3px; - filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ffffff', endColorstr='#f5f5f5', GradientType=0); - -webkit-box-shadow: inset 0 1px 0 #ffffff; - -moz-box-shadow: inset 0 1px 0 #ffffff; - box-shadow: inset 0 1px 0 #ffffff; -} - -.breadcrumb li { - display: inline-block; - *display: inline; - text-shadow: 0 1px 0 #ffffff; - *zoom: 1; -} - -.breadcrumb .divider { - padding: 0 5px; - color: #999999; -} - -.breadcrumb .active a { - color: #333333; -} - -.pagination { - height: 36px; - margin: 18px 0; -} - -.pagination ul { - display: inline-block; - *display: inline; - margin-bottom: 0; - margin-left: 0; - -webkit-border-radius: 3px; - -moz-border-radius: 3px; - border-radius: 3px; - *zoom: 1; - -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); - -moz-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); - box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); -} - -.pagination li { - display: inline; -} - -.pagination a { - float: left; - padding: 0 14px; - line-height: 34px; - text-decoration: none; - border: 1px solid #ddd; - border-left-width: 0; -} - -.pagination a:hover, -.pagination .active a { - background-color: #f5f5f5; -} - -.pagination .active a { - color: #999999; - cursor: default; -} - -.pagination .disabled span, -.pagination .disabled a, -.pagination .disabled a:hover { - color: #999999; - cursor: default; - background-color: transparent; -} - -.pagination li:first-child a { - border-left-width: 1px; - -webkit-border-radius: 3px 0 0 3px; - -moz-border-radius: 3px 0 0 3px; - border-radius: 3px 0 0 3px; -} - -.pagination li:last-child a { - -webkit-border-radius: 0 3px 3px 0; - -moz-border-radius: 0 3px 3px 0; - border-radius: 0 3px 3px 0; -} - -.pagination-centered { - text-align: center; -} - -.pagination-right { - text-align: right; -} - -.pager { - margin-bottom: 18px; - margin-left: 0; - text-align: center; - list-style: none; - *zoom: 1; -} - -.pager:before, -.pager:after { - display: table; - content: ""; -} - -.pager:after { - clear: both; -} - -.pager li { - display: inline; -} - -.pager a { - display: inline-block; - padding: 5px 14px; - background-color: #fff; - border: 1px solid #ddd; - -webkit-border-radius: 15px; - -moz-border-radius: 15px; - border-radius: 15px; -} - -.pager a:hover { - text-decoration: none; - background-color: #f5f5f5; -} - -.pager .next a { - float: right; -} - -.pager .previous a { - float: left; -} - -.pager .disabled a, -.pager .disabled a:hover { - color: #999999; - cursor: default; - background-color: #fff; -} - -.modal-open .dropdown-menu { - z-index: 2050; -} - -.modal-open .dropdown.open { - *z-index: 2050; -} - -.modal-open .popover { - z-index: 2060; -} - -.modal-open .tooltip { - z-index: 2070; -} - -.modal-backdrop { - position: fixed; - top: 0; - right: 0; - bottom: 0; - left: 0; - z-index: 1040; - background-color: #000000; -} - -.modal-backdrop.fade { - opacity: 0; -} - -.modal-backdrop, -.modal-backdrop.fade.in { - opacity: 0.8; - filter: alpha(opacity=80); -} - -.modal { - position: fixed; - top: 50%; - left: 50%; - z-index: 1050; - width: 560px; - margin: -250px 0 0 -280px; - overflow: auto; - background-color: #ffffff; - border: 1px solid #999; - border: 1px solid rgba(0, 0, 0, 0.3); - *border: 1px solid #999; - -webkit-border-radius: 6px; - -moz-border-radius: 6px; - border-radius: 6px; - -webkit-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); - -moz-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); - box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); - -webkit-background-clip: padding-box; - -moz-background-clip: padding-box; - background-clip: padding-box; -} - -.modal.fade { - top: -25%; - -webkit-transition: opacity 0.3s linear, top 0.3s ease-out; - -moz-transition: opacity 0.3s linear, top 0.3s ease-out; - -ms-transition: opacity 0.3s linear, top 0.3s ease-out; - -o-transition: opacity 0.3s linear, top 0.3s ease-out; - transition: opacity 0.3s linear, top 0.3s ease-out; -} - -.modal.fade.in { - top: 50%; -} - -.modal-header { - padding: 9px 15px; - border-bottom: 1px solid #eee; -} - -.modal-header .close { - margin-top: 2px; -} - -.modal-body { - max-height: 400px; - padding: 15px; - overflow-y: auto; -} - -.modal-form { - margin-bottom: 0; -} - -.modal-footer { - padding: 14px 15px 15px; - margin-bottom: 0; - text-align: right; - background-color: #f5f5f5; - border-top: 1px solid #ddd; - -webkit-border-radius: 0 0 6px 6px; - -moz-border-radius: 0 0 6px 6px; - border-radius: 0 0 6px 6px; - *zoom: 1; - -webkit-box-shadow: inset 0 1px 0 #ffffff; - -moz-box-shadow: inset 0 1px 0 #ffffff; - box-shadow: inset 0 1px 0 #ffffff; -} - -.modal-footer:before, -.modal-footer:after { - display: table; - content: ""; -} - -.modal-footer:after { - clear: both; -} - -.modal-footer .btn + .btn { - margin-bottom: 0; - margin-left: 5px; -} - -.modal-footer .btn-group .btn + .btn { - margin-left: -1px; -} - -.tooltip { - position: absolute; - z-index: 1020; - display: block; - padding: 5px; - font-size: 11px; - opacity: 0; - filter: alpha(opacity=0); - visibility: visible; -} - -.tooltip.in { - opacity: 0.8; - filter: alpha(opacity=80); -} - -.tooltip.top { - margin-top: -2px; -} - -.tooltip.right { - margin-left: 2px; -} - -.tooltip.bottom { - margin-top: 2px; -} - -.tooltip.left { - margin-left: -2px; -} - -.tooltip.top .tooltip-arrow { - bottom: 0; - left: 50%; - margin-left: -5px; - border-top: 5px solid #000000; - border-right: 5px solid transparent; - border-left: 5px solid transparent; -} - -.tooltip.left .tooltip-arrow { - top: 50%; - right: 0; - margin-top: -5px; - border-top: 5px solid transparent; - border-bottom: 5px solid transparent; - border-left: 5px solid #000000; -} - -.tooltip.bottom .tooltip-arrow { - top: 0; - left: 50%; - margin-left: -5px; - border-right: 5px solid transparent; - border-bottom: 5px solid #000000; - border-left: 5px solid transparent; -} - -.tooltip.right .tooltip-arrow { - top: 50%; - left: 0; - margin-top: -5px; - border-top: 5px solid transparent; - border-right: 5px solid #000000; - border-bottom: 5px solid transparent; -} - -.tooltip-inner { - max-width: 200px; - padding: 3px 8px; - color: #ffffff; - text-align: center; - text-decoration: none; - background-color: #000000; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; -} - -.tooltip-arrow { - position: absolute; - width: 0; - height: 0; -} - -.popover { - position: absolute; - top: 0; - left: 0; - z-index: 1010; - display: none; - padding: 5px; -} - -.popover.top { - margin-top: -5px; -} - -.popover.right { - margin-left: 5px; -} - -.popover.bottom { - margin-top: 5px; -} - -.popover.left { - margin-left: -5px; -} - -.popover.top .arrow { - bottom: 0; - left: 50%; - margin-left: -5px; - border-top: 5px solid #000000; - border-right: 5px solid transparent; - border-left: 5px solid transparent; -} - -.popover.right .arrow { - top: 50%; - left: 0; - margin-top: -5px; - border-top: 5px solid transparent; - border-right: 5px solid #000000; - border-bottom: 5px solid transparent; -} - -.popover.bottom .arrow { - top: 0; - left: 50%; - margin-left: -5px; - border-right: 5px solid transparent; - border-bottom: 5px solid #000000; - border-left: 5px solid transparent; -} - -.popover.left .arrow { - top: 50%; - right: 0; - margin-top: -5px; - border-top: 5px solid transparent; - border-bottom: 5px solid transparent; - border-left: 5px solid #000000; -} - -.popover .arrow { - position: absolute; - width: 0; - height: 0; -} - -.popover-inner { - width: 280px; - padding: 3px; - overflow: hidden; - background: #000000; - background: rgba(0, 0, 0, 0.8); - -webkit-border-radius: 6px; - -moz-border-radius: 6px; - border-radius: 6px; - -webkit-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); - -moz-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); - box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); -} - -.popover-title { - padding: 9px 15px; - line-height: 1; - background-color: #f5f5f5; - border-bottom: 1px solid #eee; - -webkit-border-radius: 3px 3px 0 0; - -moz-border-radius: 3px 3px 0 0; - border-radius: 3px 3px 0 0; -} - -.popover-content { - padding: 14px; - background-color: #ffffff; - -webkit-border-radius: 0 0 3px 3px; - -moz-border-radius: 0 0 3px 3px; - border-radius: 0 0 3px 3px; - -webkit-background-clip: padding-box; - -moz-background-clip: padding-box; - background-clip: padding-box; -} - -.popover-content p, -.popover-content ul, -.popover-content ol { - margin-bottom: 0; -} - -.thumbnails { - margin-left: -20px; - list-style: none; - *zoom: 1; -} - -.thumbnails:before, -.thumbnails:after { - display: table; - content: ""; -} - -.thumbnails:after { - clear: both; -} - -.row-fluid .thumbnails { - margin-left: 0; -} - -.thumbnails > li { - float: left; - margin-bottom: 18px; - margin-left: 20px; -} - -.thumbnail { - display: block; - padding: 4px; - line-height: 1; - border: 1px solid #ddd; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; - -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075); - -moz-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075); - box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075); -} - -a.thumbnail:hover { - border-color: #0088cc; - -webkit-box-shadow: 0 1px 4px rgba(0, 105, 214, 0.25); - -moz-box-shadow: 0 1px 4px rgba(0, 105, 214, 0.25); - box-shadow: 0 1px 4px rgba(0, 105, 214, 0.25); -} - -.thumbnail > img { - display: block; - max-width: 100%; - margin-right: auto; - margin-left: auto; -} - -.thumbnail .caption { - padding: 9px; -} - -.label, -.badge { - font-size: 10.998px; - font-weight: bold; - line-height: 14px; - color: #ffffff; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); - white-space: nowrap; - vertical-align: baseline; - background-color: #999999; -} - -.label { - padding: 1px 4px 2px; - -webkit-border-radius: 3px; - -moz-border-radius: 3px; - border-radius: 3px; -} - -.badge { - padding: 1px 9px 2px; - -webkit-border-radius: 9px; - -moz-border-radius: 9px; - border-radius: 9px; -} - -a.label:hover, -a.badge:hover { - color: #ffffff; - text-decoration: none; - cursor: pointer; -} - -.label-important, -.badge-important { - background-color: #b94a48; -} - -.label-important[href], -.badge-important[href] { - background-color: #953b39; -} - -.label-warning, -.badge-warning { - background-color: #f89406; -} - -.label-warning[href], -.badge-warning[href] { - background-color: #c67605; -} - -.label-success, -.badge-success { - background-color: #468847; -} - -.label-success[href], -.badge-success[href] { - background-color: #356635; -} - -.label-info, -.badge-info { - background-color: #3a87ad; -} - -.label-info[href], -.badge-info[href] { - background-color: #2d6987; -} - -.label-inverse, -.badge-inverse { - background-color: #333333; -} - -.label-inverse[href], -.badge-inverse[href] { - background-color: #1a1a1a; -} - -@-webkit-keyframes progress-bar-stripes { - from { - background-position: 40px 0; - } - to { - background-position: 0 0; - } -} - -@-moz-keyframes progress-bar-stripes { - from { - background-position: 40px 0; - } - to { - background-position: 0 0; - } -} - -@-ms-keyframes progress-bar-stripes { - from { - background-position: 40px 0; - } - to { - background-position: 0 0; - } -} - -@-o-keyframes progress-bar-stripes { - from { - background-position: 0 0; - } - to { - background-position: 40px 0; - } -} - -@keyframes progress-bar-stripes { - from { - background-position: 40px 0; - } - to { - background-position: 0 0; - } -} - -.progress { - height: 18px; - margin-bottom: 18px; - overflow: hidden; - background-color: #f7f7f7; - background-image: -moz-linear-gradient(top, #f5f5f5, #f9f9f9); - background-image: -ms-linear-gradient(top, #f5f5f5, #f9f9f9); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#f5f5f5), to(#f9f9f9)); - background-image: -webkit-linear-gradient(top, #f5f5f5, #f9f9f9); - background-image: -o-linear-gradient(top, #f5f5f5, #f9f9f9); - background-image: linear-gradient(top, #f5f5f5, #f9f9f9); - background-repeat: repeat-x; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; - filter: progid:dximagetransform.microsoft.gradient(startColorstr='#f5f5f5', endColorstr='#f9f9f9', GradientType=0); - -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); - -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); - box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); -} - -.progress .bar { - width: 0; - height: 18px; - font-size: 12px; - color: #ffffff; - text-align: center; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); - background-color: #0e90d2; - background-image: -moz-linear-gradient(top, #149bdf, #0480be); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#149bdf), to(#0480be)); - background-image: -webkit-linear-gradient(top, #149bdf, #0480be); - background-image: -o-linear-gradient(top, #149bdf, #0480be); - background-image: linear-gradient(top, #149bdf, #0480be); - background-image: -ms-linear-gradient(top, #149bdf, #0480be); - background-repeat: repeat-x; - filter: progid:dximagetransform.microsoft.gradient(startColorstr='#149bdf', endColorstr='#0480be', GradientType=0); - -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); - -moz-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); - box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - -ms-box-sizing: border-box; - box-sizing: border-box; - -webkit-transition: width 0.6s ease; - -moz-transition: width 0.6s ease; - -ms-transition: width 0.6s ease; - -o-transition: width 0.6s ease; - transition: width 0.6s ease; -} - -.progress-striped .bar { - background-color: #149bdf; - background-image: -o-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -webkit-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -moz-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -ms-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); - background-image: linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - -webkit-background-size: 40px 40px; - -moz-background-size: 40px 40px; - -o-background-size: 40px 40px; - background-size: 40px 40px; -} - -.progress.active .bar { - -webkit-animation: progress-bar-stripes 2s linear infinite; - -moz-animation: progress-bar-stripes 2s linear infinite; - -ms-animation: progress-bar-stripes 2s linear infinite; - -o-animation: progress-bar-stripes 2s linear infinite; - animation: progress-bar-stripes 2s linear infinite; -} - -.progress-danger .bar { - background-color: #dd514c; - background-image: -moz-linear-gradient(top, #ee5f5b, #c43c35); - background-image: -ms-linear-gradient(top, #ee5f5b, #c43c35); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ee5f5b), to(#c43c35)); - background-image: -webkit-linear-gradient(top, #ee5f5b, #c43c35); - background-image: -o-linear-gradient(top, #ee5f5b, #c43c35); - background-image: linear-gradient(top, #ee5f5b, #c43c35); - background-repeat: repeat-x; - filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ee5f5b', endColorstr='#c43c35', GradientType=0); -} - -.progress-danger.progress-striped .bar { - background-color: #ee5f5b; - background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); - background-image: -webkit-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -moz-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -ms-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -o-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); -} - -.progress-success .bar { - background-color: #5eb95e; - background-image: -moz-linear-gradient(top, #62c462, #57a957); - background-image: -ms-linear-gradient(top, #62c462, #57a957); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#62c462), to(#57a957)); - background-image: -webkit-linear-gradient(top, #62c462, #57a957); - background-image: -o-linear-gradient(top, #62c462, #57a957); - background-image: linear-gradient(top, #62c462, #57a957); - background-repeat: repeat-x; - filter: progid:dximagetransform.microsoft.gradient(startColorstr='#62c462', endColorstr='#57a957', GradientType=0); -} - -.progress-success.progress-striped .bar { - background-color: #62c462; - background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); - background-image: -webkit-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -moz-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -ms-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -o-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); -} - -.progress-info .bar { - background-color: #4bb1cf; - background-image: -moz-linear-gradient(top, #5bc0de, #339bb9); - background-image: -ms-linear-gradient(top, #5bc0de, #339bb9); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#339bb9)); - background-image: -webkit-linear-gradient(top, #5bc0de, #339bb9); - background-image: -o-linear-gradient(top, #5bc0de, #339bb9); - background-image: linear-gradient(top, #5bc0de, #339bb9); - background-repeat: repeat-x; - filter: progid:dximagetransform.microsoft.gradient(startColorstr='#5bc0de', endColorstr='#339bb9', GradientType=0); -} - -.progress-info.progress-striped .bar { - background-color: #5bc0de; - background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); - background-image: -webkit-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -moz-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -ms-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -o-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); -} - -.progress-warning .bar { - background-color: #faa732; - background-image: -moz-linear-gradient(top, #fbb450, #f89406); - background-image: -ms-linear-gradient(top, #fbb450, #f89406); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406)); - background-image: -webkit-linear-gradient(top, #fbb450, #f89406); - background-image: -o-linear-gradient(top, #fbb450, #f89406); - background-image: linear-gradient(top, #fbb450, #f89406); - background-repeat: repeat-x; - filter: progid:dximagetransform.microsoft.gradient(startColorstr='#fbb450', endColorstr='#f89406', GradientType=0); -} - -.progress-warning.progress-striped .bar { - background-color: #fbb450; - background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); - background-image: -webkit-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -moz-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -ms-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -o-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); -} - -.accordion { - margin-bottom: 18px; -} - -.accordion-group { - margin-bottom: 2px; - border: 1px solid #e5e5e5; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; -} - -.accordion-heading { - border-bottom: 0; -} - -.accordion-heading .accordion-toggle { - display: block; - padding: 8px 15px; -} - -.accordion-toggle { - cursor: pointer; -} - -.accordion-inner { - padding: 9px 15px; - border-top: 1px solid #e5e5e5; -} - -.carousel { - position: relative; - margin-bottom: 18px; - line-height: 1; -} - -.carousel-inner { - position: relative; - width: 100%; - overflow: hidden; -} - -.carousel .item { - position: relative; - display: none; - -webkit-transition: 0.6s ease-in-out left; - -moz-transition: 0.6s ease-in-out left; - -ms-transition: 0.6s ease-in-out left; - -o-transition: 0.6s ease-in-out left; - transition: 0.6s ease-in-out left; -} - -.carousel .item > img { - display: block; - line-height: 1; -} - -.carousel .active, -.carousel .next, -.carousel .prev { - display: block; -} - -.carousel .active { - left: 0; -} - -.carousel .next, -.carousel .prev { - position: absolute; - top: 0; - width: 100%; -} - -.carousel .next { - left: 100%; -} - -.carousel .prev { - left: -100%; -} - -.carousel .next.left, -.carousel .prev.right { - left: 0; -} - -.carousel .active.left { - left: -100%; -} - -.carousel .active.right { - left: 100%; -} - -.carousel-control { - position: absolute; - top: 40%; - left: 15px; - width: 40px; - height: 40px; - margin-top: -20px; - font-size: 60px; - font-weight: 100; - line-height: 30px; - color: #ffffff; - text-align: center; - background: #222222; - border: 3px solid #ffffff; - -webkit-border-radius: 23px; - -moz-border-radius: 23px; - border-radius: 23px; - opacity: 0.5; - filter: alpha(opacity=50); -} - -.carousel-control.right { - right: 15px; - left: auto; -} - -.carousel-control:hover { - color: #ffffff; - text-decoration: none; - opacity: 0.9; - filter: alpha(opacity=90); -} - -.carousel-caption { - position: absolute; - right: 0; - bottom: 0; - left: 0; - padding: 10px 15px 5px; - background: #333333; - background: rgba(0, 0, 0, 0.75); -} - -.carousel-caption h4, -.carousel-caption p { - color: #ffffff; -} - -.hero-unit { - padding: 60px; - margin-bottom: 30px; - background-color: #eeeeee; - -webkit-border-radius: 6px; - -moz-border-radius: 6px; - border-radius: 6px; -} - -.hero-unit h1 { - margin-bottom: 0; - font-size: 60px; - line-height: 1; - letter-spacing: -1px; - color: inherit; -} - -.hero-unit p { - font-size: 18px; - font-weight: 200; - line-height: 27px; - color: inherit; -} - -.pull-right { - float: right; -} - -.pull-left { - float: left; -} - -.hide { - display: none; -} - -.show { - display: block; -} - -.invisible { - visibility: hidden; -} diff --git a/jun_springboot_plugin/springboot_socketio/src/test/java/com/xncoding/jwt/socket/client/html/index.html b/jun_springboot_plugin/springboot_socketio/src/test/java/com/xncoding/jwt/socket/client/html/index.html deleted file mode 100644 index 2db254235a..0000000000 --- a/jun_springboot_plugin/springboot_socketio/src/test/java/com/xncoding/jwt/socket/client/html/index.html +++ /dev/null @@ -1,110 +0,0 @@ - - - - - - - Demo Chat - - - - - - - - - - - - - - - -

    Netty-socketio Demo Chat

    - -
    - -
    -
    - -
    - - - -
    - - - - - diff --git a/jun_springboot_plugin/springboot_socketio/src/test/java/com/xncoding/jwt/socket/client/html/js/jquery-1.10.1.min.js b/jun_springboot_plugin/springboot_socketio/src/test/java/com/xncoding/jwt/socket/client/html/js/jquery-1.10.1.min.js deleted file mode 100644 index 4009433eca..0000000000 --- a/jun_springboot_plugin/springboot_socketio/src/test/java/com/xncoding/jwt/socket/client/html/js/jquery-1.10.1.min.js +++ /dev/null @@ -1,6 +0,0 @@ -/*! jQuery v1.10.1 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license -//@ sourceMappingURL=jquery-1.10.1.min.map -*/ -(function(e,t){var n,r,i=typeof t,o=e.location,a=e.document,s=a.documentElement,l=e.jQuery,u=e.$,c={},p=[],f="1.10.1",d=p.concat,h=p.push,g=p.slice,m=p.indexOf,y=c.toString,v=c.hasOwnProperty,b=f.trim,x=function(e,t){return new x.fn.init(e,t,r)},w=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=/\S+/g,C=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,k=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,E=/^[\],:{}\s]*$/,S=/(?:^|:|,)(?:\s*\[)+/g,A=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,j=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,D=/^-ms-/,L=/-([\da-z])/gi,H=function(e,t){return t.toUpperCase()},q=function(e){(a.addEventListener||"load"===e.type||"complete"===a.readyState)&&(_(),x.ready())},_=function(){a.addEventListener?(a.removeEventListener("DOMContentLoaded",q,!1),e.removeEventListener("load",q,!1)):(a.detachEvent("onreadystatechange",q),e.detachEvent("onload",q))};x.fn=x.prototype={jquery:f,constructor:x,init:function(e,n,r){var i,o;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof x?n[0]:n,x.merge(this,x.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:a,!0)),k.test(i[1])&&x.isPlainObject(n))for(i in n)x.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(o=a.getElementById(i[2]),o&&o.parentNode){if(o.id!==i[2])return r.find(e);this.length=1,this[0]=o}return this.context=a,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):x.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),x.makeArray(e,this))},selector:"",length:0,toArray:function(){return g.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=x.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return x.each(this,e,t)},ready:function(e){return x.ready.promise().done(e),this},slice:function(){return this.pushStack(g.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(x.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:h,sort:[].sort,splice:[].splice},x.fn.init.prototype=x.fn,x.extend=x.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},l=2),"object"==typeof s||x.isFunction(s)||(s={}),u===l&&(s=this,--l);u>l;l++)if(null!=(o=arguments[l]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(x.isPlainObject(r)||(n=x.isArray(r)))?(n?(n=!1,a=e&&x.isArray(e)?e:[]):a=e&&x.isPlainObject(e)?e:{},s[i]=x.extend(c,a,r)):r!==t&&(s[i]=r));return s},x.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),noConflict:function(t){return e.$===x&&(e.$=u),t&&e.jQuery===x&&(e.jQuery=l),x},isReady:!1,readyWait:1,holdReady:function(e){e?x.readyWait++:x.ready(!0)},ready:function(e){if(e===!0?!--x.readyWait:!x.isReady){if(!a.body)return setTimeout(x.ready);x.isReady=!0,e!==!0&&--x.readyWait>0||(n.resolveWith(a,[x]),x.fn.trigger&&x(a).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===x.type(e)},isArray:Array.isArray||function(e){return"array"===x.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?c[y.call(e)]||"object":typeof e},isPlainObject:function(e){var n;if(!e||"object"!==x.type(e)||e.nodeType||x.isWindow(e))return!1;try{if(e.constructor&&!v.call(e,"constructor")&&!v.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(r){return!1}if(x.support.ownLast)for(n in e)return v.call(e,n);for(n in e);return n===t||v.call(e,n)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||a;var r=k.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=x.buildFragment([e],t,i),i&&x(i).remove(),x.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=x.trim(n),n&&E.test(n.replace(A,"@").replace(j,"]").replace(S,"")))?Function("return "+n)():(x.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||x.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&x.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(D,"ms-").replace(L,H)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:b&&!b.call("\ufeff\u00a0")?function(e){return null==e?"":b.call(e)}:function(e){return null==e?"":(e+"").replace(C,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?x.merge(n,"string"==typeof e?[e]:e):h.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(m)return m.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return d.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),x.isFunction(e)?(r=g.call(arguments,2),i=function(){return e.apply(n||this,r.concat(g.call(arguments)))},i.guid=e.guid=e.guid||x.guid++,i):t},access:function(e,n,r,i,o,a,s){var l=0,u=e.length,c=null==r;if("object"===x.type(r)){o=!0;for(l in r)x.access(e,n,l,r[l],!0,a,s)}else if(i!==t&&(o=!0,x.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(x(e),n)})),n))for(;u>l;l++)n(e[l],r,s?i:i.call(e[l],l,n(e[l],r)));return o?e:c?n.call(e):u?n(e[0],r):a},now:function(){return(new Date).getTime()},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),x.ready.promise=function(t){if(!n)if(n=x.Deferred(),"complete"===a.readyState)setTimeout(x.ready);else if(a.addEventListener)a.addEventListener("DOMContentLoaded",q,!1),e.addEventListener("load",q,!1);else{a.attachEvent("onreadystatechange",q),e.attachEvent("onload",q);var r=!1;try{r=null==e.frameElement&&a.documentElement}catch(i){}r&&r.doScroll&&function o(){if(!x.isReady){try{r.doScroll("left")}catch(e){return setTimeout(o,50)}_(),x.ready()}}()}return n.promise(t)},x.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){c["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=x.type(e);return x.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=x(a),function(e,t){var n,r,i,o,a,s,l,u,c,p,f,d,h,g,m,y,v,b="sizzle"+-new Date,w=e.document,T=0,C=0,N=lt(),k=lt(),E=lt(),S=!1,A=function(){return 0},j=typeof t,D=1<<31,L={}.hasOwnProperty,H=[],q=H.pop,_=H.push,M=H.push,O=H.slice,F=H.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},B="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",P="[\\x20\\t\\r\\n\\f]",R="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",W=R.replace("w","w#"),$="\\["+P+"*("+R+")"+P+"*(?:([*^$|!~]?=)"+P+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+W+")|)|)"+P+"*\\]",I=":("+R+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+$.replace(3,8)+")*)|.*)\\)|)",z=RegExp("^"+P+"+|((?:^|[^\\\\])(?:\\\\.)*)"+P+"+$","g"),X=RegExp("^"+P+"*,"+P+"*"),U=RegExp("^"+P+"*([>+~]|"+P+")"+P+"*"),V=RegExp(P+"*[+~]"),Y=RegExp("="+P+"*([^\\]'\"]*)"+P+"*\\]","g"),J=RegExp(I),G=RegExp("^"+W+"$"),Q={ID:RegExp("^#("+R+")"),CLASS:RegExp("^\\.("+R+")"),TAG:RegExp("^("+R.replace("w","w*")+")"),ATTR:RegExp("^"+$),PSEUDO:RegExp("^"+I),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+P+"*(even|odd|(([+-]|)(\\d*)n|)"+P+"*(?:([+-]|)"+P+"*(\\d+)|))"+P+"*\\)|)","i"),bool:RegExp("^(?:"+B+")$","i"),needsContext:RegExp("^"+P+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+P+"*((?:-\\d)?\\d*)"+P+"*\\)|)(?=[^-]|$)","i")},K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,et=/^(?:input|select|textarea|button)$/i,tt=/^h\d$/i,nt=/'|\\/g,rt=RegExp("\\\\([\\da-f]{1,6}"+P+"?|("+P+")|.)","ig"),it=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(55296|r>>10,56320|1023&r)};try{M.apply(H=O.call(w.childNodes),w.childNodes),H[w.childNodes.length].nodeType}catch(ot){M={apply:H.length?function(e,t){_.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function at(e,t,n,i){var o,a,s,l,u,c,d,m,y,x;if((t?t.ownerDocument||t:w)!==f&&p(t),t=t||f,n=n||[],!e||"string"!=typeof e)return n;if(1!==(l=t.nodeType)&&9!==l)return[];if(h&&!i){if(o=Z.exec(e))if(s=o[1]){if(9===l){if(a=t.getElementById(s),!a||!a.parentNode)return n;if(a.id===s)return n.push(a),n}else if(t.ownerDocument&&(a=t.ownerDocument.getElementById(s))&&v(t,a)&&a.id===s)return n.push(a),n}else{if(o[2])return M.apply(n,t.getElementsByTagName(e)),n;if((s=o[3])&&r.getElementsByClassName&&t.getElementsByClassName)return M.apply(n,t.getElementsByClassName(s)),n}if(r.qsa&&(!g||!g.test(e))){if(m=d=b,y=t,x=9===l&&e,1===l&&"object"!==t.nodeName.toLowerCase()){c=bt(e),(d=t.getAttribute("id"))?m=d.replace(nt,"\\$&"):t.setAttribute("id",m),m="[id='"+m+"'] ",u=c.length;while(u--)c[u]=m+xt(c[u]);y=V.test(e)&&t.parentNode||t,x=c.join(",")}if(x)try{return M.apply(n,y.querySelectorAll(x)),n}catch(T){}finally{d||t.removeAttribute("id")}}}return At(e.replace(z,"$1"),t,n,i)}function st(e){return K.test(e+"")}function lt(){var e=[];function t(n,r){return e.push(n+=" ")>o.cacheLength&&delete t[e.shift()],t[n]=r}return t}function ut(e){return e[b]=!0,e}function ct(e){var t=f.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function pt(e,t,n){e=e.split("|");var r,i=e.length,a=n?null:t;while(i--)(r=o.attrHandle[e[i]])&&r!==t||(o.attrHandle[e[i]]=a)}function ft(e,t){var n=e.getAttributeNode(t);return n&&n.specified?n.value:e[t]===!0?t.toLowerCase():null}function dt(e,t){return e.getAttribute(t,"type"===t.toLowerCase()?1:2)}function ht(e){return"input"===e.nodeName.toLowerCase()?e.defaultValue:t}function gt(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||D)-(~e.sourceIndex||D);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function mt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function yt(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function vt(e){return ut(function(t){return t=+t,ut(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}s=at.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},r=at.support={},p=at.setDocument=function(e){var n=e?e.ownerDocument||e:w,i=n.parentWindow;return n!==f&&9===n.nodeType&&n.documentElement?(f=n,d=n.documentElement,h=!s(n),i&&i.frameElement&&i.attachEvent("onbeforeunload",function(){p()}),r.attributes=ct(function(e){return e.innerHTML="",pt("type|href|height|width",dt,"#"===e.firstChild.getAttribute("href")),pt(B,ft,null==e.getAttribute("disabled")),e.className="i",!e.getAttribute("className")}),r.input=ct(function(e){return e.innerHTML="",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")}),pt("value",ht,r.attributes&&r.input),r.getElementsByTagName=ct(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),r.getElementsByClassName=ct(function(e){return e.innerHTML="
    ",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),r.getById=ct(function(e){return d.appendChild(e).id=b,!n.getElementsByName||!n.getElementsByName(b).length}),r.getById?(o.find.ID=function(e,t){if(typeof t.getElementById!==j&&h){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){return e.getAttribute("id")===t}}):(delete o.find.ID,o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){var n=typeof e.getAttributeNode!==j&&e.getAttributeNode("id");return n&&n.value===t}}),o.find.TAG=r.getElementsByTagName?function(e,n){return typeof n.getElementsByTagName!==j?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},o.find.CLASS=r.getElementsByClassName&&function(e,n){return typeof n.getElementsByClassName!==j&&h?n.getElementsByClassName(e):t},m=[],g=[],(r.qsa=st(n.querySelectorAll))&&(ct(function(e){e.innerHTML="",e.querySelectorAll("[selected]").length||g.push("\\["+P+"*(?:value|"+B+")"),e.querySelectorAll(":checked").length||g.push(":checked")}),ct(function(e){var t=n.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("t",""),e.querySelectorAll("[t^='']").length&&g.push("[*^$]="+P+"*(?:''|\"\")"),e.querySelectorAll(":enabled").length||g.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),g.push(",.*:")})),(r.matchesSelector=st(y=d.webkitMatchesSelector||d.mozMatchesSelector||d.oMatchesSelector||d.msMatchesSelector))&&ct(function(e){r.disconnectedMatch=y.call(e,"div"),y.call(e,"[s!='']:x"),m.push("!=",I)}),g=g.length&&RegExp(g.join("|")),m=m.length&&RegExp(m.join("|")),v=st(d.contains)||d.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},r.sortDetached=ct(function(e){return 1&e.compareDocumentPosition(n.createElement("div"))}),A=d.compareDocumentPosition?function(e,t){if(e===t)return S=!0,0;var i=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t);return i?1&i||!r.sortDetached&&t.compareDocumentPosition(e)===i?e===n||v(w,e)?-1:t===n||v(w,t)?1:c?F.call(c,e)-F.call(c,t):0:4&i?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return S=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:c?F.call(c,e)-F.call(c,t):0;if(o===a)return gt(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?gt(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},n):f},at.matches=function(e,t){return at(e,null,null,t)},at.matchesSelector=function(e,t){if((e.ownerDocument||e)!==f&&p(e),t=t.replace(Y,"='$1']"),!(!r.matchesSelector||!h||m&&m.test(t)||g&&g.test(t)))try{var n=y.call(e,t);if(n||r.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(i){}return at(t,f,null,[e]).length>0},at.contains=function(e,t){return(e.ownerDocument||e)!==f&&p(e),v(e,t)},at.attr=function(e,n){(e.ownerDocument||e)!==f&&p(e);var i=o.attrHandle[n.toLowerCase()],a=i&&L.call(o.attrHandle,n.toLowerCase())?i(e,n,!h):t;return a===t?r.attributes||!h?e.getAttribute(n):(a=e.getAttributeNode(n))&&a.specified?a.value:null:a},at.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},at.uniqueSort=function(e){var t,n=[],i=0,o=0;if(S=!r.detectDuplicates,c=!r.sortStable&&e.slice(0),e.sort(A),S){while(t=e[o++])t===e[o]&&(i=n.push(o));while(i--)e.splice(n[i],1)}return e},a=at.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=a(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=a(t);return n},o=at.selectors={cacheLength:50,createPseudo:ut,match:Q,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(rt,it),e[3]=(e[4]||e[5]||"").replace(rt,it),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||at.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&at.error(e[0]),e},PSEUDO:function(e){var n,r=!e[5]&&e[2];return Q.CHILD.test(e[0])?null:(e[3]&&e[4]!==t?e[2]=e[4]:r&&J.test(r)&&(n=bt(r,!0))&&(n=r.indexOf(")",r.length-n)-r.length)&&(e[0]=e[0].slice(0,n),e[2]=r.slice(0,n)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(rt,it).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=N[e+" "];return t||(t=RegExp("(^|"+P+")"+e+"("+P+"|$)"))&&N(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==j&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=at.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,l){var u,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!l&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[b]||(m[b]={}),u=c[e]||[],d=u[0]===T&&u[1],f=u[0]===T&&u[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[T,d,f];break}}else if(v&&(u=(t[b]||(t[b]={}))[e])&&u[0]===T)f=u[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[b]||(p[b]={}))[e]=[T,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=o.pseudos[e]||o.setFilters[e.toLowerCase()]||at.error("unsupported pseudo: "+e);return r[b]?r(t):r.length>1?(n=[e,e,"",t],o.setFilters.hasOwnProperty(e.toLowerCase())?ut(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=F.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:ut(function(e){var t=[],n=[],r=l(e.replace(z,"$1"));return r[b]?ut(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:ut(function(e){return function(t){return at(e,t).length>0}}),contains:ut(function(e){return function(t){return(t.textContent||t.innerText||a(t)).indexOf(e)>-1}}),lang:ut(function(e){return G.test(e||"")||at.error("unsupported lang: "+e),e=e.replace(rt,it).toLowerCase(),function(t){var n;do if(n=h?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===d},focus:function(e){return e===f.activeElement&&(!f.hasFocus||f.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!o.pseudos.empty(e)},header:function(e){return tt.test(e.nodeName)},input:function(e){return et.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:vt(function(){return[0]}),last:vt(function(e,t){return[t-1]}),eq:vt(function(e,t,n){return[0>n?n+t:n]}),even:vt(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:vt(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:vt(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:vt(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}};for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})o.pseudos[n]=mt(n);for(n in{submit:!0,reset:!0})o.pseudos[n]=yt(n);function bt(e,t){var n,r,i,a,s,l,u,c=k[e+" "];if(c)return t?0:c.slice(0);s=e,l=[],u=o.preFilter;while(s){(!n||(r=X.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),l.push(i=[])),n=!1,(r=U.exec(s))&&(n=r.shift(),i.push({value:n,type:r[0].replace(z," ")}),s=s.slice(n.length));for(a in o.filter)!(r=Q[a].exec(s))||u[a]&&!(r=u[a](r))||(n=r.shift(),i.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?at.error(e):k(e,l).slice(0)}function xt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function wt(e,t,n){var r=t.dir,o=n&&"parentNode"===r,a=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||o)return e(t,n,i)}:function(t,n,s){var l,u,c,p=T+" "+a;if(s){while(t=t[r])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[r])if(1===t.nodeType||o)if(c=t[b]||(t[b]={}),(u=c[r])&&u[0]===p){if((l=u[1])===!0||l===i)return l===!0}else if(u=c[r]=[p],u[1]=e(t,n,s)||i,u[1]===!0)return!0}}function Tt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function Ct(e,t,n,r,i){var o,a=[],s=0,l=e.length,u=null!=t;for(;l>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),u&&t.push(s));return a}function Nt(e,t,n,r,i,o){return r&&!r[b]&&(r=Nt(r)),i&&!i[b]&&(i=Nt(i,o)),ut(function(o,a,s,l){var u,c,p,f=[],d=[],h=a.length,g=o||St(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:Ct(g,f,e,s,l),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,l),r){u=Ct(y,d),r(u,[],s,l),c=u.length;while(c--)(p=u[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){u=[],c=y.length;while(c--)(p=y[c])&&u.push(m[c]=p);i(null,y=[],u,l)}c=y.length;while(c--)(p=y[c])&&(u=i?F.call(o,p):f[c])>-1&&(o[u]=!(a[u]=p))}}else y=Ct(y===a?y.splice(h,y.length):y),i?i(null,a,y,l):M.apply(a,y)})}function kt(e){var t,n,r,i=e.length,a=o.relative[e[0].type],s=a||o.relative[" "],l=a?1:0,c=wt(function(e){return e===t},s,!0),p=wt(function(e){return F.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==u)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;i>l;l++)if(n=o.relative[e[l].type])f=[wt(Tt(f),n)];else{if(n=o.filter[e[l].type].apply(null,e[l].matches),n[b]){for(r=++l;i>r;r++)if(o.relative[e[r].type])break;return Nt(l>1&&Tt(f),l>1&&xt(e.slice(0,l-1).concat({value:" "===e[l-2].type?"*":""})).replace(z,"$1"),n,r>l&&kt(e.slice(l,r)),i>r&&kt(e=e.slice(r)),i>r&&xt(e))}f.push(n)}return Tt(f)}function Et(e,t){var n=0,r=t.length>0,a=e.length>0,s=function(s,l,c,p,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,C=u,N=s||a&&o.find.TAG("*",d&&l.parentNode||l),k=T+=null==C?1:Math.random()||.1;for(w&&(u=l!==f&&l,i=n);null!=(h=N[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,l,c)){p.push(h);break}w&&(T=k,i=++n)}r&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,r&&b!==v){g=0;while(m=t[g++])m(x,y,l,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=q.call(p));y=Ct(y)}M.apply(p,y),w&&!s&&y.length>0&&v+t.length>1&&at.uniqueSort(p)}return w&&(T=k,u=C),x};return r?ut(s):s}l=at.compile=function(e,t){var n,r=[],i=[],o=E[e+" "];if(!o){t||(t=bt(e)),n=t.length;while(n--)o=kt(t[n]),o[b]?r.push(o):i.push(o);o=E(e,Et(i,r))}return o};function St(e,t,n){var r=0,i=t.length;for(;i>r;r++)at(e,t[r],n);return n}function At(e,t,n,i){var a,s,u,c,p,f=bt(e);if(!i&&1===f.length){if(s=f[0]=f[0].slice(0),s.length>2&&"ID"===(u=s[0]).type&&r.getById&&9===t.nodeType&&h&&o.relative[s[1].type]){if(t=(o.find.ID(u.matches[0].replace(rt,it),t)||[])[0],!t)return n;e=e.slice(s.shift().value.length)}a=Q.needsContext.test(e)?0:s.length;while(a--){if(u=s[a],o.relative[c=u.type])break;if((p=o.find[c])&&(i=p(u.matches[0].replace(rt,it),V.test(s[0].type)&&t.parentNode||t))){if(s.splice(a,1),e=i.length&&xt(s),!e)return M.apply(n,i),n;break}}}return l(e,f)(i,t,!h,n,V.test(e)),n}o.pseudos.nth=o.pseudos.eq;function jt(){}jt.prototype=o.filters=o.pseudos,o.setFilters=new jt,r.sortStable=b.split("").sort(A).join("")===b,p(),[0,0].sort(A),r.detectDuplicates=S,x.find=at,x.expr=at.selectors,x.expr[":"]=x.expr.pseudos,x.unique=at.uniqueSort,x.text=at.getText,x.isXMLDoc=at.isXML,x.contains=at.contains}(e);var O={};function F(e){var t=O[e]={};return x.each(e.match(T)||[],function(e,n){t[n]=!0}),t}x.Callbacks=function(e){e="string"==typeof e?O[e]||F(e):x.extend({},e);var n,r,i,o,a,s,l=[],u=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=l.length,n=!0;l&&o>a;a++)if(l[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,l&&(u?u.length&&c(u.shift()):r?l=[]:p.disable())},p={add:function(){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this},remove:function(){return l&&x.each(arguments,function(e,t){var r;while((r=x.inArray(t,l,r))>-1)l.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?x.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],o=0,this},disable:function(){return l=u=r=t,this},disabled:function(){return!l},lock:function(){return u=t,r||p.disable(),this},locked:function(){return!u},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!l||i&&!u||(n?u.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},x.extend({Deferred:function(e){var t=[["resolve","done",x.Callbacks("once memory"),"resolved"],["reject","fail",x.Callbacks("once memory"),"rejected"],["notify","progress",x.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return x.Deferred(function(n){x.each(t,function(t,o){var a=o[0],s=x.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&x.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?x.extend(e,r):r}},i={};return r.pipe=r.then,x.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=g.call(arguments),r=n.length,i=1!==r||e&&x.isFunction(e.promise)?r:0,o=1===i?e:x.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?g.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,l,u;if(r>1)for(s=Array(r),l=Array(r),u=Array(r);r>t;t++)n[t]&&x.isFunction(n[t].promise)?n[t].promise().done(a(t,u,n)).fail(o.reject).progress(a(t,l,s)):--i;return i||o.resolveWith(u,n),o.promise()}}),x.support=function(t){var n,r,o,s,l,u,c,p,f,d=a.createElement("div");if(d.setAttribute("className","t"),d.innerHTML="
    a",n=d.getElementsByTagName("*")||[],r=d.getElementsByTagName("a")[0],!r||!r.style||!n.length)return t;s=a.createElement("select"),u=s.appendChild(a.createElement("option")),o=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t.getSetAttribute="t"!==d.className,t.leadingWhitespace=3===d.firstChild.nodeType,t.tbody=!d.getElementsByTagName("tbody").length,t.htmlSerialize=!!d.getElementsByTagName("link").length,t.style=/top/.test(r.getAttribute("style")),t.hrefNormalized="/a"===r.getAttribute("href"),t.opacity=/^0.5/.test(r.style.opacity),t.cssFloat=!!r.style.cssFloat,t.checkOn=!!o.value,t.optSelected=u.selected,t.enctype=!!a.createElement("form").enctype,t.html5Clone="<:nav>"!==a.createElement("nav").cloneNode(!0).outerHTML,t.inlineBlockNeedsLayout=!1,t.shrinkWrapBlocks=!1,t.pixelPosition=!1,t.deleteExpando=!0,t.noCloneEvent=!0,t.reliableMarginRight=!0,t.boxSizingReliable=!0,o.checked=!0,t.noCloneChecked=o.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!u.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}o=a.createElement("input"),o.setAttribute("value",""),t.input=""===o.getAttribute("value"),o.value="t",o.setAttribute("type","radio"),t.radioValue="t"===o.value,o.setAttribute("checked","t"),o.setAttribute("name","t"),l=a.createDocumentFragment(),l.appendChild(o),t.appendChecked=o.checked,t.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip;for(f in x(t))break;return t.ownLast="0"!==f,x(function(){var n,r,o,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",l=a.getElementsByTagName("body")[0];l&&(n=a.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",l.appendChild(n).appendChild(d),d.innerHTML="
    t
    ",o=d.getElementsByTagName("td"),o[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===o[0].offsetHeight,o[0].style.display="",o[1].style.display="none",t.reliableHiddenOffsets=p&&0===o[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",x.swap(l,null!=l.style.zoom?{zoom:1}:{},function(){t.boxSizing=4===d.offsetWidth}),e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(a.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="
    ",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(l.style.zoom=1)),l.removeChild(n),n=d=o=r=null) -}),n=s=l=u=r=o=null,t}({});var B=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;function R(e,n,r,i){if(x.acceptData(e)){var o,a,s=x.expando,l=e.nodeType,u=l?x.cache:e,c=l?e[s]:e[s]&&s;if(c&&u[c]&&(i||u[c].data)||r!==t||"string"!=typeof n)return c||(c=l?e[s]=p.pop()||x.guid++:s),u[c]||(u[c]=l?{}:{toJSON:x.noop}),("object"==typeof n||"function"==typeof n)&&(i?u[c]=x.extend(u[c],n):u[c].data=x.extend(u[c].data,n)),a=u[c],i||(a.data||(a.data={}),a=a.data),r!==t&&(a[x.camelCase(n)]=r),"string"==typeof n?(o=a[n],null==o&&(o=a[x.camelCase(n)])):o=a,o}}function W(e,t,n){if(x.acceptData(e)){var r,i,o=e.nodeType,a=o?x.cache:e,s=o?e[x.expando]:x.expando;if(a[s]){if(t&&(r=n?a[s]:a[s].data)){x.isArray(t)?t=t.concat(x.map(t,x.camelCase)):t in r?t=[t]:(t=x.camelCase(t),t=t in r?[t]:t.split(" ")),i=t.length;while(i--)delete r[t[i]];if(n?!I(r):!x.isEmptyObject(r))return}(n||(delete a[s].data,I(a[s])))&&(o?x.cleanData([e],!0):x.support.deleteExpando||a!=a.window?delete a[s]:a[s]=null)}}}x.extend({cache:{},noData:{applet:!0,embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return e=e.nodeType?x.cache[e[x.expando]]:e[x.expando],!!e&&!I(e)},data:function(e,t,n){return R(e,t,n)},removeData:function(e,t){return W(e,t)},_data:function(e,t,n){return R(e,t,n,!0)},_removeData:function(e,t){return W(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&x.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),x.fn.extend({data:function(e,n){var r,i,o=null,a=0,s=this[0];if(e===t){if(this.length&&(o=x.data(s),1===s.nodeType&&!x._data(s,"parsedAttrs"))){for(r=s.attributes;r.length>a;a++)i=r[a].name,0===i.indexOf("data-")&&(i=x.camelCase(i.slice(5)),$(s,i,o[i]));x._data(s,"parsedAttrs",!0)}return o}return"object"==typeof e?this.each(function(){x.data(this,e)}):arguments.length>1?this.each(function(){x.data(this,e,n)}):s?$(s,e,x.data(s,e)):null},removeData:function(e){return this.each(function(){x.removeData(this,e)})}});function $(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(P,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:B.test(r)?x.parseJSON(r):r}catch(o){}x.data(e,n,r)}else r=t}return r}function I(e){var t;for(t in e)if(("data"!==t||!x.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}x.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=x._data(e,n),r&&(!i||x.isArray(r)?i=x._data(e,n,x.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=x.queue(e,t),r=n.length,i=n.shift(),o=x._queueHooks(e,t),a=function(){x.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return x._data(e,n)||x._data(e,n,{empty:x.Callbacks("once memory").add(function(){x._removeData(e,t+"queue"),x._removeData(e,n)})})}}),x.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?x.queue(this[0],e):n===t?this:this.each(function(){var t=x.queue(this,e,n);x._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&x.dequeue(this,e)})},dequeue:function(e){return this.each(function(){x.dequeue(this,e)})},delay:function(e,t){return e=x.fx?x.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=x.Deferred(),a=this,s=this.length,l=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=x._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(l));return l(),o.promise(n)}});var z,X,U=/[\t\r\n\f]/g,V=/\r/g,Y=/^(?:input|select|textarea|button|object)$/i,J=/^(?:a|area)$/i,G=/^(?:checked|selected)$/i,Q=x.support.getSetAttribute,K=x.support.input;x.fn.extend({attr:function(e,t){return x.access(this,x.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){x.removeAttr(this,e)})},prop:function(e,t){return x.access(this,x.prop,e,t,arguments.length>1)},removeProp:function(e){return e=x.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,l="string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).addClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=x.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,l=0===arguments.length||"string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).removeClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?x.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,r="boolean"==typeof t;return x.isFunction(e)?this.each(function(n){x(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,a=0,s=x(this),l=t,u=e.match(T)||[];while(o=u[a++])l=r?l:!s.hasClass(o),s[l?"addClass":"removeClass"](o)}else(n===i||"boolean"===n)&&(this.className&&x._data(this,"__className__",this.className),this.className=this.className||e===!1?"":x._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(U," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=x.isFunction(e),this.each(function(n){var o;1===this.nodeType&&(o=i?e.call(this,n,x(this).val()):e,null==o?o="":"number"==typeof o?o+="":x.isArray(o)&&(o=x.map(o,function(e){return null==e?"":e+""})),r=x.valHooks[this.type]||x.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=x.valHooks[o.type]||x.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(V,""):null==n?"":n)}}}),x.extend({valHooks:{option:{get:function(e){var t=x.find.attr(e,"value");return null!=t?t:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,l=0>i?s:o?i:0;for(;s>l;l++)if(n=r[l],!(!n.selected&&l!==i||(x.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&x.nodeName(n.parentNode,"optgroup"))){if(t=x(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n,r,i=e.options,o=x.makeArray(t),a=i.length;while(a--)r=i[a],(r.selected=x.inArray(x(r).val(),o)>=0)&&(n=!0);return n||(e.selectedIndex=-1),o}}},attr:function(e,n,r){var o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return typeof e.getAttribute===i?x.prop(e,n,r):(1===s&&x.isXMLDoc(e)||(n=n.toLowerCase(),o=x.attrHooks[n]||(x.expr.match.bool.test(n)?X:z)),r===t?o&&"get"in o&&null!==(a=o.get(e,n))?a:(a=x.find.attr(e,n),null==a?t:a):null!==r?o&&"set"in o&&(a=o.set(e,r,n))!==t?a:(e.setAttribute(n,r+""),r):(x.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(T);if(o&&1===e.nodeType)while(n=o[i++])r=x.propFix[n]||n,x.expr.match.bool.test(n)?K&&Q||!G.test(n)?e[r]=!1:e[x.camelCase("default-"+n)]=e[r]=!1:x.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!x.support.radioValue&&"radio"===t&&x.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!x.isXMLDoc(e),a&&(n=x.propFix[n]||n,o=x.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var t=x.find.attr(e,"tabindex");return t?parseInt(t,10):Y.test(e.nodeName)||J.test(e.nodeName)&&e.href?0:-1}}}}),X={set:function(e,t,n){return t===!1?x.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&x.propFix[n]||n,n):e[x.camelCase("default-"+n)]=e[n]=!0,n}},x.each(x.expr.match.bool.source.match(/\w+/g),function(e,n){var r=x.expr.attrHandle[n]||x.find.attr;x.expr.attrHandle[n]=K&&Q||!G.test(n)?function(e,n,i){var o=x.expr.attrHandle[n],a=i?t:(x.expr.attrHandle[n]=t)!=r(e,n,i)?n.toLowerCase():null;return x.expr.attrHandle[n]=o,a}:function(e,n,r){return r?t:e[x.camelCase("default-"+n)]?n.toLowerCase():null}}),K&&Q||(x.attrHooks.value={set:function(e,n,r){return x.nodeName(e,"input")?(e.defaultValue=n,t):z&&z.set(e,n,r)}}),Q||(z={set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},x.expr.attrHandle.id=x.expr.attrHandle.name=x.expr.attrHandle.coords=function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&""!==i.value?i.value:null},x.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&r.specified?r.value:t},set:z.set},x.attrHooks.contenteditable={set:function(e,t,n){z.set(e,""===t?!1:t,n)}},x.each(["width","height"],function(e,n){x.attrHooks[n]={set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}}})),x.support.hrefNormalized||x.each(["href","src"],function(e,t){x.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),x.support.style||(x.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),x.support.optSelected||(x.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}}),x.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){x.propFix[this.toLowerCase()]=this}),x.support.enctype||(x.propFix.enctype="encoding"),x.each(["radio","checkbox"],function(){x.valHooks[this]={set:function(e,n){return x.isArray(n)?e.checked=x.inArray(x(e).val(),n)>=0:t}},x.support.checkOn||(x.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}function at(){try{return a.activeElement}catch(e){}}x.event={global:{},add:function(e,n,r,o,a){var s,l,u,c,p,f,d,h,g,m,y,v=x._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=x.guid++),(l=v.events)||(l=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof x===i||e&&x.event.triggered===e.type?t:x.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(T)||[""],u=n.length;while(u--)s=rt.exec(n[u])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),g&&(p=x.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=x.event.special[g]||{},d=x.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&x.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=l[g])||(h=l[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),x.event.global[g]=!0);e=null}},remove:function(e,t,n,r,i){var o,a,s,l,u,c,p,f,d,h,g,m=x.hasData(e)&&x._data(e);if(m&&(c=m.events)){t=(t||"").match(T)||[""],u=t.length;while(u--)if(s=rt.exec(t[u])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=x.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));l&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||x.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)x.event.remove(e,d+t[u],n,r,!0);x.isEmptyObject(c)&&(delete m.handle,x._removeData(e,"events"))}},trigger:function(n,r,i,o){var s,l,u,c,p,f,d,h=[i||a],g=v.call(n,"type")?n.type:n,m=v.call(n,"namespace")?n.namespace.split("."):[];if(u=f=i=i||a,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+x.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),l=0>g.indexOf(":")&&"on"+g,n=n[x.expando]?n:new x.Event(g,"object"==typeof n&&n),n.isTrigger=o?2:3,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:x.makeArray(r,[n]),p=x.event.special[g]||{},o||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!o&&!p.noBubble&&!x.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(u=u.parentNode);u;u=u.parentNode)h.push(u),f=u;f===(i.ownerDocument||a)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((u=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(x._data(u,"events")||{})[n.type]&&x._data(u,"handle"),s&&s.apply(u,r),s=l&&u[l],s&&x.acceptData(u)&&s.apply&&s.apply(u,r)===!1&&n.preventDefault();if(n.type=g,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(h.pop(),r)===!1)&&x.acceptData(i)&&l&&i[g]&&!x.isWindow(i)){f=i[l],f&&(i[l]=null),x.event.triggered=g;try{i[g]()}catch(y){}x.event.triggered=t,f&&(i[l]=f)}return n.result}},dispatch:function(e){e=x.event.fix(e);var n,r,i,o,a,s=[],l=g.call(arguments),u=(x._data(this,"events")||{})[e.type]||[],c=x.event.special[e.type]||{};if(l[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=x.event.handlers.call(this,e,u),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((x.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,l),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],l=n.delegateCount,u=e.target;if(l&&u.nodeType&&(!e.button||"click"!==e.type))for(;u!=this;u=u.parentNode||this)if(1===u.nodeType&&(u.disabled!==!0||"click"!==e.type)){for(o=[],a=0;l>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?x(r,this).index(u)>=0:x.find(r,this,null,[u]).length),o[r]&&o.push(i);o.length&&s.push({elem:u,handlers:o})}return n.length>l&&s.push({elem:this,handlers:n.slice(l)}),s},fix:function(e){if(e[x.expando])return e;var t,n,r,i=e.type,o=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new x.Event(o),t=r.length;while(t--)n=r[t],e[n]=o[n];return e.target||(e.target=o.srcElement||a),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,o,s=n.button,l=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||a,o=i.documentElement,r=i.body,e.pageX=n.clientX+(o&&o.scrollLeft||r&&r.scrollLeft||0)-(o&&o.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(o&&o.scrollTop||r&&r.scrollTop||0)-(o&&o.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&l&&(e.relatedTarget=l===e.target?n.toElement:l),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==at()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===at()&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},click:{trigger:function(){return x.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t},_default:function(e){return x.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=x.extend(new x.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?x.event.trigger(i,null,t):x.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},x.removeEvent=a.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},x.Event=function(e,n){return this instanceof x.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&x.extend(this,n),this.timeStamp=e&&e.timeStamp||x.now(),this[x.expando]=!0,t):new x.Event(e,n)},x.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},x.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){x.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!x.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),x.support.submitBubbles||(x.event.special.submit={setup:function(){return x.nodeName(this,"form")?!1:(x.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=x.nodeName(n,"input")||x.nodeName(n,"button")?n.form:t;r&&!x._data(r,"submitBubbles")&&(x.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),x._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&x.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return x.nodeName(this,"form")?!1:(x.event.remove(this,"._submit"),t)}}),x.support.changeBubbles||(x.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(x.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),x.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),x.event.simulate("change",this,e,!0)})),!1):(x.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!x._data(t,"changeBubbles")&&(x.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||x.event.simulate("change",this.parentNode,e,!0)}),x._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return x.event.remove(this,"._change"),!Z.test(this.nodeName)}}),x.support.focusinBubbles||x.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){x.event.simulate(t,e.target,x.event.fix(e),!0)};x.event.special[t]={setup:function(){0===n++&&a.addEventListener(e,r,!0)},teardown:function(){0===--n&&a.removeEventListener(e,r,!0)}}}),x.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return x().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=x.guid++)),this.each(function(){x.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,x(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){x.event.remove(this,e,r,n)})},trigger:function(e,t){return this.each(function(){x.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?x.event.trigger(e,n,r,!0):t}});var st=/^.[^:#\[\.,]*$/,lt=/^(?:parents|prev(?:Until|All))/,ut=x.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};x.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(x(e).filter(function(){for(t=0;i>t;t++)if(x.contains(r[t],this))return!0}));for(t=0;i>t;t++)x.find(e,r[t],n);return n=this.pushStack(i>1?x.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},has:function(e){var t,n=x(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(x.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e||[],!0))},filter:function(e){return this.pushStack(ft(this,e||[],!1))},is:function(e){return!!ft(this,"string"==typeof e&&ut.test(e)?x(e):e||[],!1).length},closest:function(e,t){var n,r=0,i=this.length,o=[],a=ut.test(e)||"string"!=typeof e?x(e,t||this.context):0;for(;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(11>n.nodeType&&(a?a.index(n)>-1:1===n.nodeType&&x.find.matchesSelector(n,e))){n=o.push(n);break}return this.pushStack(o.length>1?x.unique(o):o)},index:function(e){return e?"string"==typeof e?x.inArray(this[0],x(e)):x.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?x(e,t):x.makeArray(e&&e.nodeType?[e]:e),r=x.merge(this.get(),n);return this.pushStack(x.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}x.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return x.dir(e,"parentNode")},parentsUntil:function(e,t,n){return x.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return x.dir(e,"nextSibling")},prevAll:function(e){return x.dir(e,"previousSibling")},nextUntil:function(e,t,n){return x.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return x.dir(e,"previousSibling",n)},siblings:function(e){return x.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return x.sibling(e.firstChild)},contents:function(e){return x.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:x.merge([],e.childNodes)}},function(e,t){x.fn[e]=function(n,r){var i=x.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=x.filter(r,i)),this.length>1&&(ct[e]||(i=x.unique(i)),lt.test(e)&&(i=i.reverse())),this.pushStack(i)}}),x.extend({filter:function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?x.find.matchesSelector(r,e)?[r]:[]:x.find.matches(e,x.grep(t,function(e){return 1===e.nodeType}))},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!x(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(x.isFunction(t))return x.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return x.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(st.test(t))return x.filter(t,e,n);t=x.filter(t,e)}return x.grep(e,function(e){return x.inArray(e,t)>=0!==n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/\s*$/g,At={option:[1,""],legend:[1,"
    ","
    "],area:[1,"",""],param:[1,"",""],thead:[1,"","
    "],tr:[2,"","
    "],col:[2,"","
    "],td:[3,"","
    "],_default:x.support.htmlSerialize?[0,"",""]:[1,"X
    ","
    "]},jt=dt(a),Dt=jt.appendChild(a.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,x.fn.extend({text:function(e){return x.access(this,function(e){return e===t?x.text(this):this.empty().append((this[0]&&this[0].ownerDocument||a).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=e?x.filter(e,this):this,i=0;for(;null!=(n=r[i]);i++)t||1!==n.nodeType||x.cleanData(Ft(n)),n.parentNode&&(t&&x.contains(n.ownerDocument,n)&&_t(Ft(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&x.cleanData(Ft(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&x.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return x.clone(this,e,t)})},html:function(e){return x.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!x.support.htmlSerialize&&mt.test(e)||!x.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(x.cleanData(Ft(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=x.map(this,function(e){return[e.nextSibling,e.parentNode]}),t=0;return this.domManip(arguments,function(n){var r=e[t++],i=e[t++];i&&(r&&r.parentNode!==i&&(r=this.nextSibling),x(this).remove(),i.insertBefore(n,r))},!0),t?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t,n){e=d.apply([],e);var r,i,o,a,s,l,u=0,c=this.length,p=this,f=c-1,h=e[0],g=x.isFunction(h);if(g||!(1>=c||"string"!=typeof h||x.support.checkClone)&&Nt.test(h))return this.each(function(r){var i=p.eq(r);g&&(e[0]=h.call(this,r,i.html())),i.domManip(e,t,n)});if(c&&(l=x.buildFragment(e,this[0].ownerDocument,!1,!n&&this),r=l.firstChild,1===l.childNodes.length&&(l=r),r)){for(a=x.map(Ft(l,"script"),Ht),o=a.length;c>u;u++)i=l,u!==f&&(i=x.clone(i,!0,!0),o&&x.merge(a,Ft(i,"script"))),t.call(this[u],i,u);if(o)for(s=a[a.length-1].ownerDocument,x.map(a,qt),u=0;o>u;u++)i=a[u],kt.test(i.type||"")&&!x._data(i,"globalEval")&&x.contains(s,i)&&(i.src?x._evalUrl(i.src):x.globalEval((i.text||i.textContent||i.innerHTML||"").replace(St,"")));l=r=null}return this}});function Lt(e,t){return x.nodeName(e,"table")&&x.nodeName(1===t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function Ht(e){return e.type=(null!==x.find.attr(e,"type"))+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function _t(e,t){var n,r=0;for(;null!=(n=e[r]);r++)x._data(n,"globalEval",!t||x._data(t[r],"globalEval"))}function Mt(e,t){if(1===t.nodeType&&x.hasData(e)){var n,r,i,o=x._data(e),a=x._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)x.event.add(t,n,s[n][r])}a.data&&(a.data=x.extend({},a.data))}}function Ot(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!x.support.noCloneEvent&&t[x.expando]){i=x._data(t);for(r in i.events)x.removeEvent(t,r,i.handle);t.removeAttribute(x.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),x.support.html5Clone&&e.innerHTML&&!x.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Ct.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}x.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){x.fn[e]=function(e){var n,r=0,i=[],o=x(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),x(o[r])[t](n),h.apply(i,n.get());return this.pushStack(i)}});function Ft(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||x.nodeName(o,n)?s.push(o):x.merge(s,Ft(o,n));return n===t||n&&x.nodeName(e,n)?x.merge([e],s):s}function Bt(e){Ct.test(e.type)&&(e.defaultChecked=e.checked)}x.extend({clone:function(e,t,n){var r,i,o,a,s,l=x.contains(e.ownerDocument,e);if(x.support.html5Clone||x.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(x.support.noCloneEvent&&x.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||x.isXMLDoc(e)))for(r=Ft(o),s=Ft(e),a=0;null!=(i=s[a]);++a)r[a]&&Ot(i,r[a]);if(t)if(n)for(s=s||Ft(e),r=r||Ft(o),a=0;null!=(i=s[a]);a++)Mt(i,r[a]);else Mt(e,o);return r=Ft(o,"script"),r.length>0&&_t(r,!l&&Ft(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,l,u,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===x.type(o))x.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),l=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[l]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!x.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!x.support.tbody){o="table"!==l||xt.test(o)?""!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)x.nodeName(u=o.childNodes[i],"tbody")&&!u.childNodes.length&&o.removeChild(u)}x.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),x.support.appendChecked||x.grep(Ft(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===x.inArray(o,r))&&(a=x.contains(o.ownerDocument,o),s=Ft(f.appendChild(o),"script"),a&&_t(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,l=x.expando,u=x.cache,c=x.support.deleteExpando,f=x.event.special;for(;null!=(n=e[s]);s++)if((t||x.acceptData(n))&&(o=n[l],a=o&&u[o])){if(a.events)for(r in a.events)f[r]?x.event.remove(n,r):x.removeEvent(n,r,a.handle); - u[o]&&(delete u[o],c?delete n[l]:typeof n.removeAttribute!==i?n.removeAttribute(l):n[l]=null,p.push(o))}},_evalUrl:function(e){return x.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})}}),x.fn.extend({wrapAll:function(e){if(x.isFunction(e))return this.each(function(t){x(this).wrapAll(e.call(this,t))});if(this[0]){var t=x(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return x.isFunction(e)?this.each(function(t){x(this).wrapInner(e.call(this,t))}):this.each(function(){var t=x(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=x.isFunction(e);return this.each(function(n){x(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){x.nodeName(this,"body")||x(this).replaceWith(this.childNodes)}).end()}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+w+")(.*)$","i"),Yt=RegExp("^("+w+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+w+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===x.css(e,"display")||!x.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=x._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=x._data(r,"olddisplay",ln(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&x._data(r,"olddisplay",i?n:x.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}x.fn.extend({css:function(e,n){return x.access(this,function(e,n,r){var i,o,a={},s=0;if(x.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=x.css(e,n[s],!1,o);return a}return r!==t?x.style(e,n,r):x.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){var t="boolean"==typeof e;return this.each(function(){(t?e:nn(this))?x(this).show():x(this).hide()})}}),x.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":x.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,l=x.camelCase(n),u=e.style;if(n=x.cssProps[l]||(x.cssProps[l]=tn(u,l)),s=x.cssHooks[n]||x.cssHooks[l],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:u[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(x.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||x.cssNumber[l]||(r+="px"),x.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(u[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{u[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,l=x.camelCase(n);return n=x.cssProps[l]||(x.cssProps[l]=tn(e.style,l)),s=x.cssHooks[n]||x.cssHooks[l],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||x.isNumeric(o)?o||0:a):a}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s.getPropertyValue(n)||s[n]:t,u=e.style;return s&&(""!==l||x.contains(e.ownerDocument,e)||(l=x.style(e,n)),Yt.test(l)&&Ut.test(n)&&(i=u.width,o=u.minWidth,a=u.maxWidth,u.minWidth=u.maxWidth=u.width=l,l=s.width,u.width=i,u.minWidth=o,u.maxWidth=a)),l}):a.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s[n]:t,u=e.style;return null==l&&u&&u[n]&&(l=u[n]),Yt.test(l)&&!zt.test(n)&&(i=u.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),u.left="fontSize"===n?"1em":l,l=u.pixelLeft+"px",u.left=i,a&&(o.left=a)),""===l?"auto":l});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=x.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=x.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=x.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=x.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=x.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(x.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function ln(e){var t=a,n=Gt[e];return n||(n=un(e,t),"none"!==n&&n||(Pt=(Pt||x("';break;case 3:delete a.title,delete a.closeBtn,-1===a.icon&&a.icon,h.closeAll("loading");break;case 4:s||(a.content=[a.content,"body"]),a.follow=a.content[1],a.content=a.content[0]+'',delete a.title,a.tips="object"==typeof a.tips?a.tips:[a.tips,!0],a.tipsMore||h.closeAll("tips")}n.vessel(s,function(e,t,i){l.append(e[0]),s?2==a.type||4==a.type?m("body").append(e[1]):r.parents("."+d[0])[0]||(r.data("display",r.css("display")).show().addClass("layui-layer-wrap").wrap(e[1]),m("#"+d[0]+o).find("."+d[5]).before(t)):l.append(e[1]),m("#"+d.MOVE)[0]||l.append(f.moveElem=i),n.layero=m("#"+d[0]+o),n.shadeo=m("#"+d.SHADE+o),a.scrollbar||d.html.css("overflow","hidden").attr("layer-full",o)}).auto(o),n.shadeo.css({"background-color":a.shade[1]||"#000",opacity:a.shade[0]||a.shade}),2==a.type&&6==h.ie&&n.layero.find("iframe").attr("src",r[0]),4==a.type?n.tips():(n.offset(),parseInt(f.getStyle(document.getElementById(d.MOVE),"z-index"))||(n.layero.css("visibility","hidden"),h.ready(function(){n.offset(),n.layero.css("visibility","visible")}))),!a.fixed||f.events.resize[n.index]||(f.events.resize[n.index]=function(){n.resize()},c.on("resize",f.events.resize[n.index])),a.time<=0||setTimeout(function(){h.close(n.index)},a.time),n.move().callback(),d.anim[a.anim]&&(e="layer-anim "+d.anim[a.anim],n.layero.addClass(e).one("webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend",function(){m(this).removeClass(e)})),a.isOutAnim&&n.layero.data({isOutAnim:!0,anim:a.anim})}},t.pt.resize=function(){var e=this,t=e.config;e.offset(),(/^\d+%$/.test(t.area[0])||/^\d+%$/.test(t.area[1]))&&e.auto(e.index),4==t.type&&e.tips()},t.pt.auto=function(e){var t=this.config,i=m("#"+d[0]+e),n=(""===t.area[0]&&0t.maxWidth&&i.width(t.maxWidth)),[i.innerWidth(),i.innerHeight()]),a=i.find(d[1]).outerHeight()||0,o=i.find("."+d[6]).outerHeight()||0,e=function(e){(e=i.find(e)).height(n[1]-a-o-2*(0|parseFloat(e.css("padding-top"))))};return 2===t.type?e("iframe"):""===t.area[1]?0t.maxHeight?(n[1]=t.maxHeight,e("."+d[5])):t.fixed&&n[1]>=c.height()&&(n[1]=c.height(),e("."+d[5])):e("."+d[5]),this},t.pt.offset=function(){var e=this,t=e.config,i=e.layero,n=[i.outerWidth(),i.outerHeight()],a="object"==typeof t.offset;e.offsetTop=(c.height()-n[1])/2,e.offsetLeft=(c.width()-n[0])/2,a?(e.offsetTop=t.offset[0],e.offsetLeft=t.offset[1]||e.offsetLeft):"auto"!==t.offset&&("t"===t.offset?e.offsetTop=0:"r"===t.offset?e.offsetLeft=c.width()-n[0]:"b"===t.offset?e.offsetTop=c.height()-n[1]:"l"===t.offset?e.offsetLeft=0:"lt"===t.offset?(e.offsetTop=0,e.offsetLeft=0):"lb"===t.offset?(e.offsetTop=c.height()-n[1],e.offsetLeft=0):"rt"===t.offset?(e.offsetTop=0,e.offsetLeft=c.width()-n[0]):"rb"===t.offset?(e.offsetTop=c.height()-n[1],e.offsetLeft=c.width()-n[0]):e.offsetTop=t.offset),t.fixed||(e.offsetTop=/%$/.test(e.offsetTop)?c.height()*parseFloat(e.offsetTop)/100:parseFloat(e.offsetTop),e.offsetLeft=/%$/.test(e.offsetLeft)?c.width()*parseFloat(e.offsetLeft)/100:parseFloat(e.offsetLeft),e.offsetTop+=c.scrollTop(),e.offsetLeft+=c.scrollLeft()),"min"===i.data("maxminStatus")&&(e.offsetTop=c.height()-(i.find(d[1]).outerHeight()||0),e.offsetLeft=i.css("left")),i.css({top:e.offsetTop,left:e.offsetLeft})},t.pt.tips=function(){var e=this.config,t=this.layero,i=[t.outerWidth(),t.outerHeight()],n=m(e.follow),a={width:(n=n[0]?n:m("body")).outerWidth(),height:n.outerHeight(),top:n.offset().top,left:n.offset().left},o=t.find(".layui-layer-TipsG"),n=e.tips[0];e.tips[1]||o.remove(),a.autoLeft=function(){0c.width()&&(a=c.width()-180-(f.minStackArr.edgeIndex=f.minStackArr.edgeIndex||0,f.minStackArr.edgeIndex+=3))<0&&(a=0),t.minStack&&(s.left=a,s.top=c.height()-i,n||f.minStackIndex++,l.attr("minLeft",a)),l.attr("position",o),h.style(e,s,!0),l.find(".layui-layer-min").hide(),"page"===l.attr("type")&&l.find(d[4]).hide(),f.rescollbar(e),r.hide())},h.restore=function(e){var t=m("#"+d[0]+e),i=m("#"+d.SHADE+e),n=t.attr("area").split(","),a=t.attr("type");t.removeData("maxminStatus"),h.style(e,{width:n[0],height:n[1],top:parseFloat(n[2]),left:parseFloat(n[3]),position:t.attr("position"),overflow:"visible"},!0),t.find(".layui-layer-max").removeClass("layui-layer-maxmin"),t.find(".layui-layer-min").show(),"page"===a&&t.find(d[4]).show(),f.rescollbar(e),i.show()},h.full=function(t){var i=m("#"+d[0]+t),e=i.data("maxminStatus");"max"!==e&&("min"===e&&h.restore(t),i.data("maxminStatus","max"),f.record(i),d.html.attr("layer-full")||d.html.css("overflow","hidden").attr("layer-full",t),clearTimeout(void 0),setTimeout(function(){var e="fixed"===i.css("position");h.style(t,{top:e?0:c.scrollTop(),left:e?0:c.scrollLeft(),width:"100%",height:"100%"},!0),i.find(".layui-layer-min").hide()},100))},h.title=function(e,t){m("#"+d[0]+(t||h.index)).find(d[1]).html(e)},h.close=function(a,o){var s,e,l=(t=m("."+d[0]).find("#"+a).closest("."+d[0]))[0]?(a=t.attr("times"),t):m("#"+d[0]+a),r=l.attr("type"),t=l.data()||{},i={slideDown:"layer-anim-slide-down-out",slideLeft:"layer-anim-slide-left-out",slideUp:"layer-anim-slide-up-out",slideRight:"layer-anim-slide-right-out"}[t.anim]||"layer-anim-close";l[0]&&(s="layui-layer-wrap",e=function(){if(r===f.type[1]&&"object"===l.attr("conType")){l.children(":not(."+d[5]+")").remove();for(var e=l.find("."+s),t=0;t<2;t++)e.unwrap();e.css("display",e.data("display")).removeClass(s)}else{if(r===f.type[2])try{var i=m("#"+d[4]+a)[0];i.contentWindow.document.write(""),i.contentWindow.close(),l.find("."+d[5])[0].removeChild(i)}catch(n){}l[0].innerHTML="",l.remove()}"function"==typeof f.end[a]&&f.end[a](),delete f.end[a],"function"==typeof o&&o(),f.events.resize[a]&&(c.off("resize",f.events.resize[a]),delete f.events.resize[a])},t.isOutAnim&&l.addClass("layer-anim "+i),m("#layui-layer-moves, #"+d.SHADE+a).remove(),6==h.ie&&f.reselect(),f.rescollbar(a),"string"==typeof l.attr("minLeft")&&(f.minStackIndex--,f.minStackArr.push(l.attr("minLeft"))),h.ie&&h.ie<10||!l.data("isOutAnim")?e():setTimeout(function(){e()},200))},h.closeAll=function(n,a){"function"==typeof n&&(a=n,n=null);var o=m("."+d[0]);m.each(o,function(e){var t=m(this),i=n?t.attr("type")===n:1;i&&h.close(t.attr("times"),e===o.length-1?a:null)}),0===o.length&&"function"==typeof a&&a()},h.closeLast=function(e){h.close(m(".layui-layer-"+(e=e||"page")+":last").attr("times"))},h.cache||{}),g=function(e){return i.skin?" "+i.skin+" "+i.skin+"-"+e:""};h.prompt=function(i,n){var e="",t="";"function"==typeof(i=i||{})&&(n=i),i.area&&(e='style="width: '+(o=i.area)[0]+"; height: "+o[1]+';"',delete i.area),i.placeholder&&(t=' placeholder="'+i.placeholder+'"');var a,o=2==i.formType?'":'",s=i.success;return delete i.success,h.open(m.extend({type:1,btn:["确定","取消"],content:o,skin:"layui-layer-prompt"+g("prompt"),maxWidth:c.width(),success:function(e){(a=e.find(".layui-layer-input")).val(i.value||"").focus(),"function"==typeof s&&s(e)},resize:!1,yes:function(e){var t=a.val();t.length>(i.maxlength||500)?h.tips("最多输入"+(i.maxlength||500)+"个字数",a,{tips:1}):n&&n(t,e,a)}},i))},h.tab=function(n){var a=(n=n||{}).tab||{},o="layui-this",s=n.success;return delete n.success,h.open(m.extend({type:1,skin:"layui-layer-tab"+g("tab"),resize:!1,title:function(){var e=a.length,t=1,i="";if(0'+a[0].title+"";t"+a[t].title+"";return i}(),content:'
      '+function(){var e=a.length,t=1,i="";if(0'+(a[0].content||"no content")+"";t'+(a[t].content||"no content")+"";return i}()+"
    ",success:function(e){var t=e.find(".layui-layer-title").children(),i=e.find(".layui-layer-tabmain").children();t.on("mousedown",function(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0;var e=m(this),t=e.index();e.addClass(o).siblings().removeClass(o),i.eq(t).show().siblings().hide(),"function"==typeof n.change&&n.change(t)}),"function"==typeof s&&s(e)}},n))},h.photos=function(n,e,a){var o={};if((n=n||{}).photos){var t=!("string"==typeof n.photos||n.photos instanceof m),i=t?n.photos:{},s=i.data||[],l=i.start||0,r=(o.imgIndex=1+(0|l),n.img=n.img||"img",n.success);if(delete n.success,t){if(0===s.length)return h.msg("没有图片")}else{var c=m(n.photos),f=function(){s=[],c.find(n.img).each(function(e){var t=m(this);t.attr("layer-index",e),s.push({alt:t.attr("alt"),pid:t.attr("layer-pid"),src:t.attr("lay-src")||t.attr("layer-src")||t.attr("src"),thumb:t.attr("src")})})};if(f(),0===s.length)return;if(e||c.on("click",n.img,function(){f();var e=m(this).attr("layer-index");h.photos(m.extend(n,{photos:{start:e,data:s,tab:n.tab},full:n.full}),!0)}),!e)return}o.imgprev=function(e){o.imgIndex--,o.imgIndex<1&&(o.imgIndex=s.length),o.tabimg(e)},o.imgnext=function(e,t){o.imgIndex++,o.imgIndex>s.length&&(o.imgIndex=1,t)||o.tabimg(e)},o.keyup=function(e){var t;o.end||(t=e.keyCode,e.preventDefault(),37===t?o.imgprev(!0):39===t?o.imgnext(!0):27===t&&h.close(o.index))},o.tabimg=function(e){if(!(s.length<=1))return i.start=o.imgIndex-1,h.close(o.index),h.photos(n,!0,e)},o.event=function(){o.bigimg.find(".layui-layer-imgprev").on("click",function(e){e.preventDefault(),o.imgprev(!0)}),o.bigimg.find(".layui-layer-imgnext").on("click",function(e){e.preventDefault(),o.imgnext(!0)}),m(document).on("keyup",o.keyup)},o.loadi=h.load(1,{shade:!("shade"in n)&&.9,scrollbar:!1});var t=s[l].src,d=function(e){h.close(o.loadi);var t,i=s[l].alt||"";a&&(n.anim=-1),o.index=h.open(m.extend({type:1,id:"layui-layer-photos",area:(e=[e.width,e.height],t=[m(p).width()-100,m(p).height()-100],!n.full&&(e[0]>t[0]||e[1]>t[1])&&((t=[e[0]/t[0],e[1]/t[1]])[1]'+i+''+(t=['
    '],1','','',"
    "].join("")),n.hideFooter||t.push(['
    ','
    ',"

    "+i+"

    ",""+o.imgIndex+" / "+s.length+"",'\u67e5\u770b\u539f\u56fe',"
    ","
    "].join("")),t.push(""),t.join(""))+"",success:function(e,t){o.bigimg=e.find(".layui-layer-phimg"),o.imgsee=e.find(".layui-layer-imgbar"),o.event(e),n.tab&&n.tab(s[l],e),"function"==typeof r&&r(e)},end:function(){o.end=!0,m(document).off("keyup",o.keyup)}},n))},u=function(){h.close(o.loadi),h.msg("当前图片地址异常
    是否继续查看下一张?",{time:3e4,btn:["下一张","不看了"],yes:function(){1").addClass(a));layui.each(i.bars,function(e,t){var n=s('
  • ');n.addClass(t.icon).attr({"lay-type":t.type,style:t.style||"background-color: "+i.bgcolor}).html(t.content),n.on("click",function(){var e=s(this).attr("lay-type");"top"===e&&("body"===i.target?s("html,body"):c).animate({scrollTop:0},i.duration),"function"==typeof i.click&&i.click.call(this,e)}),"object"===layui.type(i.on)&&layui.each(i.on,function(e,t){n.on(e,function(){var e=s(this).attr("lay-type");"function"==typeof t&&t.call(this,e)})}),"top"===t.type&&(n.addClass("layui-fixbar-top"),o=n),u.append(n)}),l.find("."+a).remove(),"object"==typeof i.css&&u.css(i.css),l.append(u),o&&(t=function t(){return c.scrollTop()>=i.margin?e||(o.show(),e=1):e&&(o.hide(),e=0),t}()),c.on("scroll",function(){t&&(clearTimeout(n),n=setTimeout(function(){t()},100))})},countdown:function(e,t,n){var i=this,o="function"==typeof t,a=new Date(e).getTime(),r=new Date(!t||o?(new Date).getTime():t).getTime(),a=a-r,l=[Math.floor(a/864e5),Math.floor(a/36e5)%24,Math.floor(a/6e4)%60,Math.floor(a/1e3)%60],o=(o&&(n=t),setTimeout(function(){i.countdown(e,r+1e3,n)},1e3));return n&&n(0]|&(?=#[a-zA-Z0-9]+)/g.test(e+="")?e.replace(/&(?!#?[a-zA-Z0-9]+;)/g,"&").replace(//g,">").replace(/'/g,"'").replace(/"/g,"""):e},unescape:function(e){return e!==undefined&&null!==e||(e=""),(e+="").replace(/\&/g,"&").replace(/\</g,"<").replace(/\>/g,">").replace(/\'/g,"'").replace(/\"/g,'"')},openWin:function(e){var t=(e=e||{}).window||window.open(e.url||"",e.target,e.specs);e.url||(t.document.open("text/html","replace"),t.document.write(e.content||""),t.document.close())},toVisibleArea:function(e){var t,n,i,o,a,r,l,c;(e=s.extend({margin:160,duration:200,type:"y"},e)).scrollElem[0]&&e.thisElem[0]&&(t=e.scrollElem,l=e.thisElem,i=(a="y"===e.type)?"top":"left",o=t[n=a?"scrollTop":"scrollLeft"](),a=t[a?"height":"width"](),r=t.offset()[i],c={},((l=l.offset()[i]-r)>a-e.margin||l."+h,k=function(e){var i=this;i.index=++p.index,i.config=s.extend({},i.config,p.config,e),i.init()};k.prototype.config={trigger:"click",content:"",className:"",style:"",show:!1,isAllowSpread:!0,isSpreadItem:!0,data:[],delay:300,shade:0},k.prototype.reload=function(e,i){var t=this;t.config=s.extend({},t.config,e),t.init(!0,i)},k.prototype.init=function(e,i){var t,n=this,a=n.config,l=s(a.elem);return 1');return 0No data
  • '),e},u=function(r,e){return layui.each(e,function(e,i){var t,n=i.child&&0",(t="href"in i?''+l+"":l,n?'
    '+t+("parent"===o?'':"group"===o&&d.isAllowSpread?'':"")+"
    ":'
    '+t+"
    "),""].join(""))).data("item",i),n&&(a=s('
    '),t=s("
      "),"parent"===o?(a.append(u(t,i.child)),l.append(a)):l.append(u(t,i.child))),r.append(l))}),r},a=['
      ',"
      "].join("");!(e="contextmenu"!==d.trigger&&!lay.isTopElem(d.elem[0])?e:!0)&&d.elem.data(m+"_opened")||(l.elemView=s("."+f+'[lay-id="'+d.id+'"]'),"reloadData"===i&&l.elemView.length?l.elemView.html(d.content||n()):(l.elemView=s(a),l.elemView.append(d.content||n()),d.className&&l.elemView.addClass(d.className),d.style&&l.elemView.attr("style",d.style),p.thisId=d.id,l.remove(),t.append(l.elemView),d.elem.data(m+"_opened",!0),e=d.shade?'
      ':"",l.elemView.before(e),"mouseenter"===d.trigger&&l.elemView.on("mouseenter",function(){clearTimeout(y.timer)}).on("mouseleave",function(){l.delayRemove()})),l.position(),(y.prevElem=l.elemView).data("prevElem",d.elem),l.elemView.find(".layui-menu").on(o,function(e){layui.stope(e)}),l.elemView.find(".layui-menu li").on("click",function(e){var i=s(this),t=i.data("item")||{},n=t.child&&0n.width()&&(t.addClass(V),(i=t[0].getBoundingClientRect()).left<0&&t.removeClass(V)),i.bottom>n.height()&&t.eq(0).css("margin-top",-(i.bottom-n.height()+5)))}).on("mouseleave",t,function(e){var i=s(this).children("."+C);i.removeClass(V),i.css("margin-top",0)}),p.close=function(e){e=y.getThis(e);return e?(e.remove(),y.call(e)):this},p.reload=function(e,i,t){e=y.getThis(e);return e?(e.reload(i,t),y.call(e)):this},p.reloadData=function(){var t=s.extend([],arguments),n=(t[2]="reloadData",new RegExp("^("+["data","templet","content"].join("|")+")$"));return layui.each(t[1],function(e,i){n.test(e)||delete t[1][e]}),p.reload.apply(null,t)},p.render=function(e){e=new k(e);return y.call(e)},e(r,p)});layui.define(["jquery","lay"],function(e){"use strict";var g=layui.$,c=layui.lay,m={config:{},index:layui.slider?layui.slider.index+1e4:0,set:function(e){var i=this;return i.config=g.extend({},i.config,e),i},on:function(e,i){return layui.onevent.call(this,t,e,i)}},t="slider",v="layui-disabled",x="layui-slider-bar",b="layui-slider-wrap",T="layui-slider-wrap-btn",w="layui-slider-tips",M="layui-slider-input-txt",L="layui-slider-hover",i=function(e){var i=this;i.index=++m.index,i.config=g.extend({},i.config,m.config,e),i.render()};i.prototype.config={type:"default",min:0,max:100,value:0,step:1,showstep:!1,tips:!0,input:!1,range:!1,height:200,disabled:!1,theme:"#16baaa"},i.prototype.render=function(){var a=this,n=a.config,e=g(n.elem);if(1n.min?e:n.min,n.value[1]=i>n.min?i:n.min,n.value[0]=n.value[0]>n.max?n.max:n.value[0],n.value[1]=n.value[1]>n.max?n.max:n.value[1],i=Math.floor((n.value[0]-n.min)/(n.max-n.min)*100),t=(s=Math.floor((n.value[1]-n.min)/(n.max-n.min)*100))-i+"%",i+="%",s+="%"):("object"==typeof n.value&&(n.value=Math.min.apply(null,n.value)),n.valuen.max&&(n.value=n.max),t=Math.floor((n.value-n.min)/(n.max-n.min)*100)+"%");var l,e=n.disabled?"#c2c2c2":n.theme,i='
      '+(n.tips?'
      ':"")+'
      '+(n.range?'
      ':"")+"
      ",t=g(n.elem),s=t.next(".layui-slider");if(s[0]&&s.remove(),a.elemTemp=g(i),n.range?(a.elemTemp.find("."+b).eq(0).data("value",n.value[0]),a.elemTemp.find("."+b).eq(1).data("value",n.value[1])):a.elemTemp.find("."+b).data("value",n.value),t.html(a.elemTemp),"vertical"===n.type&&a.elemTemp.height(n.height+"px"),n.showstep){for(var o=(n.max-n.min)/n.step,r="",u=1;u<1+o;u++){var d=100*u/o;d<100&&(r+='
      ')}a.elemTemp.append(r)}n.input&&!n.range&&(e=g('
      '),t.css("position","relative"),t.append(e),t.find("."+M).children("input").val(n.value),"vertical"===n.type?e.css({left:0,top:-48}):a.elemTemp.css("margin-right",e.outerWidth()+15)),n.disabled?(a.elemTemp.addClass(v),a.elemTemp.find("."+T).addClass(v)):a.slide(),a.elemTemp.find("."+T).on("mouseover",function(){var e="vertical"===n.type?n.height:a.elemTemp[0].offsetWidth,i=a.elemTemp.find("."+b),t=("vertical"===n.type?e-g(this).parent()[0].offsetTop-i.height():g(this).parent()[0].offsetLeft)/e*100,i=g(this).parent().data("value"),e=n.setTips?n.setTips(i):i;a.elemTemp.find("."+w).html(e),clearTimeout(l),l=setTimeout(function(){"vertical"===n.type?a.elemTemp.find("."+w).css({bottom:t+"%","margin-bottom":"20px",display:"inline-block"}):a.elemTemp.find("."+w).css({left:t+"%",display:"inline-block"})},300)}).on("mouseout",function(){clearTimeout(l),a.elemTemp.find("."+w).css("display","none")})},i.prototype.slide=function(e,i,t){var o=this,r=o.config,u=o.elemTemp,d=function(){return"vertical"===r.type?r.height:u[0].offsetWidth},c=u.find("."+b),m=u.next(".layui-slider-input"),v=m.children("."+M).children("input").val(),p=100/((r.max-r.min)/Math.ceil(r.step)),f=function(e,i,t){e=(e=100<(e=100a[1]&&a.reverse(),o.value=r.range?a:l,r.change&&r.change(o.value),"done"===t&&r.done&&r.done(o.value)},h=function(e){var i=e/d()*100/p,t=Math.round(i)*p;return t=e==d()?Math.ceil(i)*p:t},y=g(['
      d()?d():i)/d()*100/p;f(i,l),s.addClass(L),u.find("."+w).show(),e.preventDefault()},i=function(){s.removeClass(L),u.find("."+w).hide()},t=function(){i&&i(),y.remove(),r.done&&r.done(o.value)},g("#LAY-slider-moving")[0]||g("body").append(y),y.on("mousemove",e),y.on("mouseup",t).on("mouseleave",t)})}),u.on("click",function(e){var i=g("."+T),t=g(this);!i.is(event.target)&&0===i.has(event.target).length&&i.length&&(t=(i=(i=(i="vertical"===r.type?d()-e.clientY+t.offset().top-g(window).scrollTop():e.clientX-t.offset().left-g(window).scrollLeft())<0?0:i)>d()?d():i)/d()*100/p,i=r.range?"vertical"===r.type?Math.abs(i-parseInt(g(c[0]).css("bottom")))>Math.abs(i-parseInt(g(c[1]).css("bottom")))?1:0:Math.abs(i-c[0].offsetLeft)>Math.abs(i-c[1].offsetLeft)?1:0:0,f(t,i,"done"),e.preventDefault())}),m.children(".layui-slider-input-btn").children("i").each(function(i){g(this).on("click",function(){v=m.children("."+M).children("input").val();var e=((v=1==i?v-r.stepr.max?r.max:Number(v)+r.step)-r.min)/(r.max-r.min)*100/p;f(e,0,"done")})});var a=function(){var e=this.value,e=(e=(e=(e=isNaN(e)?0:e)r.max?r.max:e,((this.value=e)-r.min)/(r.max-r.min)*100/p);f(e,0,"done")};m.children("."+M).children("input").on("keydown",function(e){13===e.keyCode&&(e.preventDefault(),a.call(this))}).on("change",a)},i.prototype.events=function(){this.config},m.render=function(e){e=new i(e);return function(){var t=this,a=t.config;return{setValue:function(e,i){return e=(e=e>a.max?a.max:e)',"",'','',"","","
      "].join("")),r=i.elem=m(i.elem);i.size&&o.addClass("layui-colorpicker-"+i.size),r.addClass("layui-inline").html(e.elemColorBox=o),i.id="id"in i?i.id:r.attr("id")||e.index,e.color=e.elemColorBox.find("."+C)[0].style.background,e.events()},d.prototype.renderPicker=function(){var o,e=this,i=e.config,r=e.elemColorBox[0],t=e.elemPicker=m(['
      ','
      ','
      ','
      ','
      ','
      ',"
      ",'
      ','
      ',"
      ","
      ",'
      ','
      ','
      ',"
      ","
      ",i.predefine?(o=['
      '],layui.each(i.colors,function(e,i){o.push(['
      ','
      ',"
      "].join(""))}),o.push("
      "),o.join("")):"",'
      ','
      ','',"
      ",'
      ','','',"","
      "].join(""));e.elemColorBox.find("."+C)[0];m(a)[0]&&m(a).data("index")==e.index?e.removePicker(d.thisElemInd):(e.removePicker(d.thisElemInd),m("body").append(t)),n.thisId=i.id,d.thisElemInd=e.index,d.thisColor=r.style.background,e.position(),e.pickerEvents()},d.prototype.removePicker=function(e){var i=this.config,e=m("#layui-colorpicker"+(e||this.index));return e[0]&&(e.remove(),delete n.thisId,"function"==typeof i.close&&i.close(this.color)),this},d.prototype.position=function(){var e=this,i=e.config;return t.position(e.bindElem||e.elemColorBox[0],e.elemPicker[0],{position:i.position,align:"center"}),e},d.prototype.val=function(){var e,i=this,o=(i.config,i.elemColorBox.find("."+C)),r=i.elemPicker.find("."+T),t=o[0].style.backgroundColor;t?(e=Y(L(t)),o=o.attr("lay-type"),i.select(e.h,e.s,e.b),"torgb"===o?r.find("input").val(t):"rgba"===o?(o=L(t),3===(t.match(/[0-9]{1,3}/g)||[]).length?(r.find("input").val("rgba("+o.r+", "+o.g+", "+o.b+", 1)"),i.elemPicker.find("."+E).css("left",280)):(r.find("input").val(t),t=280*t.slice(t.lastIndexOf(",")+1,t.length-1),i.elemPicker.find("."+E).css("left",t)),i.elemPicker.find("."+D)[0].style.background="linear-gradient(to right, rgba("+o.r+", "+o.g+", "+o.b+", 0), rgb("+o.r+", "+o.g+", "+o.b+"))"):r.find("input").val("#"+F(e))):(i.select(0,100,100),r.find("input").val(""),i.elemPicker.find("."+D)[0].style.background="",i.elemPicker.find("."+E).css("left",280))},d.prototype.side=function(){var n=this,l=n.config,c=n.elemColorBox.find("."+C),a=c.attr("lay-type"),s=n.elemPicker.find(".layui-colorpicker-side"),e=n.elemPicker.find("."+B),d=n.elemPicker.find("."+I),r=n.elemPicker.find("."+M),f=n.elemPicker.find("."+D),u=n.elemPicker.find("."+E),g=e[0].offsetTop/180*360,h=100-(r[0].offsetTop+3)/180*100,p=(r[0].offsetLeft+3)/260*100,v=Math.round(u[0].offsetLeft/280*100)/100,b=n.elemColorBox.find("."+w),i=n.elemPicker.find(".layui-colorpicker-pre").children("div"),y=function(e,i,o,r){n.select(e,i,o);var t=j({h:e,s:i,b:o}),e=F({h:e,s:i,b:o}),i=n.elemPicker.find("."+T).find("input");b.addClass(x).removeClass(P),c[0].style.background="rgb("+t.r+", "+t.g+", "+t.b+")","torgb"===a?i.val("rgb("+t.r+", "+t.g+", "+t.b+")"):"rgba"===a?(u.css("left",280*r),i.val("rgba("+t.r+", "+t.g+", "+t.b+", "+r+")"),c[0].style.background="rgba("+t.r+", "+t.g+", "+t.b+", "+r+")",f[0].style.background="linear-gradient(to right, rgba("+t.r+", "+t.g+", "+t.b+", 0), rgb("+t.r+", "+t.g+", "+t.b+"))"):i.val("#"+e),l.change&&l.change(n.elemPicker.find("."+T).find("input").val())},o=m(['
      '].join("")),k=function(e){m("#LAY-colorpicker-moving")[0]||m("body").append(o),o.on("mousemove",e),o.on("mouseup",function(){o.remove()}).on("mouseleave",function(){o.remove()})};e.on("mousedown",function(e){var r=this.offsetTop,t=e.clientY;k(function(e){var i=r+(e.clientY-t),o=s[0].offsetHeight,o=(i=o<(i=i<0?0:i)?o:i)/180*360;y(g=o,p,h,v),e.preventDefault()}),e.preventDefault()}),s.on("click",function(e){var i=e.clientY-m(this).offset().top,i=(i=(i=i<0?0:i)>this.offsetHeight?this.offsetHeight:i)/180*360;y(g=i,p,h,v),e.preventDefault()}),r.on("mousedown",function(e){var n=this.offsetTop,l=this.offsetLeft,c=e.clientY,a=e.clientX;layui.stope(e),k(function(e){var i=n+(e.clientY-c),o=l+(e.clientX-a),r=d[0].offsetHeight-3,t=d[0].offsetWidth-3,t=((o=t<(o=o<-3?-3:o)?t:o)+3)/260*100,o=100-((i=r<(i=i<-3?-3:i)?r:i)+3)/180*100;y(g,p=t,h=o,v),e.preventDefault()}),e.preventDefault()}),d.on("mousedown",function(e){var i=e.clientY-m(this).offset().top-3+H.scrollTop(),o=e.clientX-m(this).offset().left-3+H.scrollLeft(),o=((i=i<-3?-3:i)>this.offsetHeight-3&&(i=this.offsetHeight-3),((o=(o=o<-3?-3:o)>this.offsetWidth-3?this.offsetWidth-3:o)+3)/260*100),i=100-(i+3)/180*100;y(g,p=o,h=i,v),layui.stope(e),e.preventDefault(),r.trigger(e,"mousedown")}),u.on("mousedown",function(e){var r=this.offsetLeft,t=e.clientX;k(function(e){var i=r+(e.clientX-t),o=f[0].offsetWidth,o=(o<(i=i<0?0:i)&&(i=o),Math.round(i/280*100)/100);y(g,p,h,v=o),e.preventDefault()}),e.preventDefault()}),f.on("click",function(e){var i=e.clientX-m(this).offset().left,i=((i=i<0?0:i)>this.offsetWidth&&(i=this.offsetWidth),Math.round(i/280*100)/100);y(g,p,h,v=i),e.preventDefault()}),i.each(function(){m(this).on("click",function(){m(this).parent(".layui-colorpicker-pre").addClass("selected").siblings().removeClass("selected");var e=this.style.backgroundColor,i=Y(L(e)),o=e.slice(e.lastIndexOf(",")+1,e.length-1);g=i.h,p=i.s,h=i.b,3===(e.match(/[0-9]{1,3}/g)||[]).length&&(o=1),v=o,y(i.h,i.s,i.b,o)})})},d.prototype.select=function(e,i,o,r){this.config;var t=F({h:e,s:100,b:100}),e=(F({h:e,s:i,b:o}),e/360*180),o=180-o/100*180-3,i=i/100*260-3;this.elemPicker.find("."+B).css("top",e),this.elemPicker.find("."+I)[0].style.background="#"+t,this.elemPicker.find("."+M).css({top:o,left:i})},d.prototype.pickerEvents=function(){var c=this,a=c.config,s=c.elemColorBox.find("."+C),d=c.elemPicker.find("."+T+" input"),o={clear:function(e){s[0].style.background="",c.elemColorBox.find("."+w).removeClass(x).addClass(P),c.color="",a.done&&a.done(""),c.removePicker()},confirm:function(e,i){var o,r,t,n,l=d.val();if(-1>16,g:(65280&t)>>8,b:255&t},r=Y(n),s[0].style.background=o="#"+F(r),c.elemColorBox.find("."+w).removeClass(P).addClass(x)),"change"===i)return c.select(r.h,r.s,r.b,i),void(a.change&&a.change(o));c.color=l,a.done&&a.done(l),c.removePicker()}};c.elemPicker.on("click","*[colorpicker-events]",function(){var e=m(this),i=e.attr("colorpicker-events");o[i]&&o[i].call(this,e)}),d.on("keyup",function(e){var i=m(this);o.confirm.call(this,i,13===e.keyCode?null:"change")})},d.prototype.events=function(){var e=this;e.config;e.elemColorBox.on("click",function(){e.renderPicker(),m(a)[0]&&(e.val(),e.side())})},s.on(i,function(e){var i,o,r;!n.thisId||(i=l.getThis(n.thisId))&&(o=i.config,r=i.elemColorBox.find("."+C),m(e.target).hasClass(c)||m(e.target).parents("."+c)[0]||m(e.target).hasClass(a.replace(/\./g,""))||m(e.target).parents(a)[0]||i.elemPicker&&(i.color?(e=Y(L(i.color)),i.select(e.h,e.s,e.b)):i.elemColorBox.find("."+w).removeClass(x).addClass(P),r[0].style.background=i.color||"","function"==typeof o.cancel&&o.cancel(i.color),i.removePicker()))}),H.on("resize",function(){if(n.thisId){var e=l.getThis(n.thisId);if(e)return!(!e.elemPicker||!m(a)[0])&&void e.position()}}),l.that={},l.getThis=function(e){var i=l.that[e];return i||o.error(e?r+" instance with ID '"+e+"' not found":"ID argument required"),i},n.render=function(e){e=new d(e);return l.call(e)},e(r,n)});layui.define("jquery",function(t){"use strict";var u=layui.$,d=(layui.hint(),layui.device()),o="element",c="layui-this",y="layui-show",s=".layui-tab-title",i=function(){this.config={}},h=(i.prototype.set=function(t){return u.extend(!0,this.config,t),this},i.prototype.on=function(t,i){return layui.onevent.call(this,o,t,i)},i.prototype.tabAdd=function(t,i){var a,t=u(".layui-tab[lay-filter="+t+"]"),e=t.children(s),l=e.children(".layui-tab-bar"),t=t.children(".layui-tab-content"),n=""+(i.title||"unnaming")+"";return l[0]?l.before(n):e.append(n),t.append('
      '+(i.content||"")+"
      "),C.hideTabMore(!0),C.tabAuto(),this},i.prototype.tabDelete=function(t,i){t=u(".layui-tab[lay-filter="+t+"]").children(s).find('>li[lay-id="'+i+'"]');return C.tabDelete(null,t),this},i.prototype.tabChange=function(t,i){t=u(".layui-tab[lay-filter="+t+"]").children(s).find('>li[lay-id="'+i+'"]');return C.tabClick.call(t[0],{liElem:t}),this},i.prototype.tab=function(a){a=a||{},e.on("click",a.headerElem,function(t){var i=u(this).index();C.tabClick.call(this,{index:i,options:a})})},i.prototype.progress=function(t,i){var a="layui-progress",t=u("."+a+"[lay-filter="+t+"]").find("."+a+"-bar"),a=t.find("."+a+"-text");return t.css("width",function(){return/^.+\/.+$/.test(i)?100*new Function("return "+i)()+"%":i}).attr("lay-percent",i),a.text(i),this},".layui-nav"),f="layui-nav-item",l="layui-nav-bar",p="layui-nav-tree",b="layui-nav-child",v="layui-nav-more",m="layui-anim layui-anim-upbit",C={tabClick:function(t){var i=(t=t||{}).options||{},a=t.liElem||u(this),e=i.headerElem?a.parent():a.parents(".layui-tab").eq(0),i=i.bodyElem?u(i.bodyElem):e.children(".layui-tab-content").children(".layui-tab-item"),l=a.find("a"),l="javascript:;"!==l.attr("href")&&"_blank"===l.attr("target"),n="string"==typeof a.attr("lay-unselect"),s=e.attr("lay-filter"),t="index"in t?t.index:a.parent().children("li").index(a);l||n||(a.addClass(c).siblings().removeClass(c),i.eq(t).addClass(y).siblings().removeClass(y)),layui.event.call(this,o,"tab("+s+")",{elem:e,index:t})},tabDelete:function(t,i){var i=i||u(this).parent(),a=i.index(),e=i.closest(".layui-tab"),l=e.children(".layui-tab-content").children(".layui-tab-item"),n=e.attr("lay-filter");i.hasClass(c)&&(i.next()[0]&&i.next().is("li")?C.tabClick.call(i.next()[0],{index:a+1}):i.prev()[0]&&i.prev().is("li")&&C.tabClick.call(i.prev()[0],null,a-1)),i.remove(),l.eq(a).remove(),setTimeout(function(){C.tabAuto()},50),layui.event.call(this,o,"tabDelete("+n+")",{elem:e,index:a})},tabAuto:function(){var e="layui-tab-bar",l="layui-tab-close",n=this;u(".layui-tab").each(function(){var t=u(this),i=t.children(".layui-tab-title"),a=(t.children(".layui-tab-content").children(".layui-tab-item"),'lay-stope="tabmore"'),a=u('');n===window&&8!=d.ie&&C.hideTabMore(!0),t.attr("lay-allowclose")&&i.find("li").each(function(){var t,i=u(this);i.find("."+l)[0]||((t=u('')).on("click",C.tabDelete),i.append(t))}),"string"!=typeof t.attr("lay-unauto")&&(i.prop("scrollWidth")>i.outerWidth()+1?i.find("."+e)[0]||(i.append(a),t.attr("overflow",""),a.on("click",function(t){i[this.title?"removeClass":"addClass"]("layui-tab-more"),this.title=this.title?"":"\u6536\u7f29"})):(i.find("."+e).remove(),t.removeAttr("overflow")))})},hideTabMore:function(t){var i=u(".layui-tab-title");!0!==t&&"tabmore"===u(t.target).attr("lay-stope")||(i.removeClass("layui-tab-more"),i.find(".layui-tab-bar").attr("title",""))},clickThis:function(){var t=u(this),i=t.parents(h),a=i.attr("lay-filter"),e=t.parent(),l=t.siblings("."+b),n="string"==typeof e.attr("lay-unselect");"javascript:;"!==t.attr("href")&&"_blank"===t.attr("target")||n||l[0]||(i.find("."+c).removeClass(c),e.addClass(c)),i.hasClass(p)&&(l.removeClass(m),l[0]&&(e["none"===l.css("display")?"addClass":"removeClass"](f+"ed"),"all"===i.attr("lay-shrink")&&e.siblings().removeClass(f+"ed"))),layui.event.call(this,o,"nav("+a+")",t)},collapse:function(){var t=u(this),i=t.find(".layui-colla-icon"),a=t.siblings(".layui-colla-content"),e=t.parents(".layui-collapse").eq(0),l=e.attr("lay-filter"),n="none"===a.css("display");"string"==typeof e.attr("lay-accordion")&&((e=e.children(".layui-colla-item").children("."+y)).siblings(".layui-colla-title").children(".layui-colla-icon").html(""),e.removeClass(y)),a[n?"addClass":"removeClass"](y),i.html(n?"":""),layui.event.call(this,o,"collapse("+l+")",{title:t,content:a,show:n})}},a=(i.prototype.render=i.prototype.init=function(t,i){var a=i?'[lay-filter="'+i+'"]':"",i={tab:function(){C.tabAuto.call({})},nav:function(){var s={},o={},c={},r="layui-nav-title";u(h+a).each(function(t){var i=u(this),a=u(''),e=i.find("."+f);i.find("."+l)[0]||(i.append(a),(i.hasClass(p)?e.find("dd,>."+r):e).on("mouseenter",function(){!function(t,i,a){var e,l=u(this),n=l.find("."+b);i.hasClass(p)?n[0]||(e=l.children("."+r),t.css({top:l.offset().top-i.offset().top,height:(e[0]?e:l).outerHeight(),opacity:1})):(n.addClass(m),n.hasClass("layui-nav-child-c")&&n.css({left:-(n.outerWidth()-l.width())/2}),n[0]?t.css({left:t.position().left+t.width()/2,width:0,opacity:0}):t.css({left:l.position().left+parseFloat(l.css("marginLeft")),top:l.position().top+l.height()-t.height()}),s[a]=setTimeout(function(){t.css({width:n[0]?0:l.width(),opacity:n[0]?0:1})},d.ie&&d.ie<10?0:200),clearTimeout(c[a]),"block"===n.css("display")&&clearTimeout(o[a]),o[a]=setTimeout(function(){n.addClass(y),l.find("."+v).addClass(v+"d")},300))}.call(this,a,i,t)}).on("mouseleave",function(){i.hasClass(p)?a.css({height:0,opacity:0}):(clearTimeout(o[t]),o[t]=setTimeout(function(){i.find("."+b).removeClass(y),i.find("."+v).removeClass(v+"d")},300))}),i.on("mouseleave",function(){clearTimeout(s[t]),c[t]=setTimeout(function(){i.hasClass(p)||a.css({width:0,left:a.position().left+a.width()/2,opacity:0})},200)})),e.find("a").each(function(){var t=u(this);t.parent();t.siblings("."+b)[0]&&!t.children("."+v)[0]&&t.append(''),t.off("click",C.clickThis).on("click",C.clickThis)})})},breadcrumb:function(){u(".layui-breadcrumb"+a).each(function(){var t=u(this),i="lay-separator",a=t.attr(i)||"/",e=t.find("a");e.next("span["+i+"]")[0]||(e.each(function(t){t!==e.length-1&&u(this).after(""+a+"")}),t.css("visibility","visible"))})},progress:function(){var e="layui-progress";u("."+e+a).each(function(){var t=u(this),i=t.find(".layui-progress-bar"),a=i.attr("lay-percent");i.css("width",function(){return/^.+\/.+$/.test(a)?100*new Function("return "+a)()+"%":a}),t.attr("lay-showpercent")&&setTimeout(function(){i.html(''+a+"")},350)})},collapse:function(){u(".layui-collapse"+a).each(function(){u(this).find(".layui-colla-item").each(function(){var t=u(this),i=t.find(".layui-colla-title"),t="none"===t.find(".layui-colla-content").css("display");i.find(".layui-colla-icon").remove(),i.append(''+(t?"":"")+""),i.off("click",C.collapse).on("click",C.collapse)})})}};return i[t]?i[t]():layui.each(i,function(t,i){i()})},new i),e=u(document);u(function(){a.render()}),e.on("click",".layui-tab-title li",C.tabClick),e.on("click",C.hideTabMore),u(window).on("resize",C.tabAuto),t(o,a)});layui.define(["lay","layer"],function(e){"use strict";var y=layui.$,t=layui.layer,F=layui.device(),i={config:{},set:function(e){var t=this;return t.config=y.extend({},t.config,e),t},on:function(e,t){return layui.onevent.call(this,n,e,t)}},n="upload",a="layui-upload-file",o="layui-upload-form",b="layui-upload-iframe",x="layui-upload-choose",w=function(e){var t=this;t.config=y.extend({},t.config,i.config,e),t.render()};w.prototype.config={accept:"images",exts:"",auto:!0,bindAction:"",url:"",force:"",field:"file",acceptMime:"",method:"post",data:{},drag:!0,size:0,number:0,multiple:!1},w.prototype.render=function(e){var t=this;(e=t.config).elem=y(e.elem),e.bindAction=y(e.bindAction),t.file(),t.events()},w.prototype.file=function(){var e=this,t=e.config,i=e.elemFile=y(['"].join("")),n=t.elem.next();(n.hasClass(a)||n.hasClass(o))&&n.remove(),F.ie&&F.ie<10&&t.elem.wrap('
      '),e.isFile()?(e.elemFile=t.elem,t.field=t.elem[0].name):t.elem.after(i),F.ie&&F.ie<10&&e.initIE()},w.prototype.initIE=function(){var i,e=this.config,t=y(''),n=y(['
      ',""].join(""));y("#"+b)[0]||y("body").append(t),e.elem.next().hasClass(o)||(this.elemFile.wrap(n),e.elem.next("."+o).append((i=[],layui.each(e.data,function(e,t){t="function"==typeof t?t():t,i.push('')}),i.join(""))))},w.prototype.msg=function(e){return t.msg(e,{icon:2,shift:6})},w.prototype.isFile=function(){var e=this.config.elem[0];if(e)return"input"===e.tagName.toLocaleLowerCase()&&"file"===e.type},w.prototype.preview=function(n){window.FileReader&&layui.each(this.chooseFiles,function(e,t){var i=new FileReader;i.readAsDataURL(t),i.onload=function(){n&&n(e,t,this.result)}})},w.prototype.upload=function(e,t){var i,n,a,o,l=this,r=l.config,u=l.elemFile[0],c=function(){return e||l.files||l.chooseFiles||u.files},s=function(){var t=0,a=0,e=c(),o=function(){r.multiple&&t+a===l.fileLength&&"function"==typeof r.allDone&&r.allDone({total:l.fileLength,successful:t,failed:a})};layui.each(e,function(i,e){var n=new FormData,e=(layui.each(r.data,function(e,t){t="function"==typeof t?t():t,n.append(e,t)}),n.append(r.field,e),{url:r.url,type:"post",data:n,contentType:!1,processData:!1,dataType:"json",headers:r.headers||{},success:function(e){t++,p(i,e),o()},error:function(e){a++,l.msg("Request URL is abnormal: "+(e.statusText||"error")),d(i),o()}});"function"==typeof r.progress&&(e.xhr=function(){var e=y.ajaxSettings.xhr();return e.upload.addEventListener("progress",function(e){var t;e.lengthComputable&&(t=Math.floor(e.loaded/e.total*100),r.progress(t,(r.item||r.elem)[0],e,i))}),e}),y.ajax(e)})},f=function(){var n=y("#"+b);l.elemFile.parent().submit(),clearInterval(w.timer),w.timer=setInterval(function(){var e,t=n.contents().find("body");try{e=t.text()}catch(i){l.msg("Cross-domain requests are not supported"),clearInterval(w.timer),d()}e&&(clearInterval(w.timer),t.html(""),p(0,e))},30)},p=function(e,t){if(l.elemFile.next("."+x).remove(),u.value="","json"===r.force&&"object"!=typeof t)try{t=JSON.parse(t)}catch(i){return t={},l.msg("Please return JSON data format")}"function"==typeof r.done&&r.done(t,e||0,function(e){l.upload(e)})},d=function(e){r.auto&&(u.value=""),"function"==typeof r.error&&r.error(e||0,function(e){l.upload(e)})},m=r.exts,h=(n=[],layui.each(e||l.chooseFiles,function(e,t){n.push(t.name)}),n),g={preview:function(e){l.preview(e)},upload:function(e,t){var i={};i[e]=t,l.upload(i)},pushFile:function(){return l.files=l.files||{},layui.each(l.chooseFiles,function(e,t){l.files[e]=t}),l.files},resetFile:function(e,t,i){t=new File([t],i);l.files=l.files||{},l.files[e]=t}},v={file:"\u6587\u4ef6",images:"\u56fe\u7247",video:"\u89c6\u9891",audio:"\u97f3\u9891"}[r.accept]||"\u6587\u4ef6",h=0===h.length?u.value.match(/[^\/\\]+\..+/g)||[]||"":h;if(0!==h.length){switch(r.accept){case"file":layui.each(h,function(e,t){if(m&&!RegExp(".\\.("+m+")$","i").test(escape(t)))return i=!0});break;case"video":layui.each(h,function(e,t){if(!RegExp(".\\.("+(m||"avi|mp4|wma|rmvb|rm|flash|3gp|flv")+")$","i").test(escape(t)))return i=!0});break;case"audio":layui.each(h,function(e,t){if(!RegExp(".\\.("+(m||"mp3|wav|mid")+")$","i").test(escape(t)))return i=!0});break;default:layui.each(h,function(e,t){if(!RegExp(".\\.("+(m||"jpg|png|gif|bmp|jpeg")+")$","i").test(escape(t)))return i=!0})}if(i)return l.msg("\u9009\u62e9\u7684"+v+"\u4e2d\u5305\u542b\u4e0d\u652f\u6301\u7684\u683c\u5f0f"),u.value="";if("choose"!==t&&!r.auto||(r.choose&&r.choose(g),"choose"!==t)){if(l.fileLength=(a=0,v=c(),layui.each(v,function(){a++}),a),r.number&&l.fileLength>r.number)return l.msg("\u540c\u65f6\u6700\u591a\u53ea\u80fd\u4e0a\u4f20: "+r.number+" \u4e2a\u6587\u4ef6
      \u60a8\u5f53\u524d\u5df2\u7ecf\u9009\u62e9\u4e86: "+l.fileLength+" \u4e2a\u6587\u4ef6");if(01024*r.size&&(t=1<=(t=r.size/1024)?t.toFixed(2)+"MB":r.size+"KB",u.value="",o=t)}),o)return l.msg("\u6587\u4ef6\u5927\u5c0f\u4e0d\u80fd\u8d85\u8fc7 "+o);if(!r.before||!1!==r.before(g))F.ie?(9'+e+"")},r=function(){var e=y(this);(e.attr("lay-data")||e.attr("lay-options"))&&(n.config=y.extend({},a,lay.options(this,{attr:e.attr("lay-data")?"lay-data":null})))};a.elem.off("upload.start").on("upload.start",function(){var e=y(this);r.call(this),n.config.item=e,n.elemFile[0].click()}),F.ie&&F.ie<10||a.elem.off("upload.over").on("upload.over",function(){y(this).attr("lay-over","")}).off("upload.leave").on("upload.leave",function(){y(this).removeAttr("lay-over")}).off("upload.drop").on("upload.drop",function(e,t){var i=y(this),t=t.originalEvent.dataTransfer.files||[];i.removeAttr("lay-over"),r.call(this),o(t),a.auto?n.upload():l(t)}),n.elemFile.off("upload.change").on("upload.change",function(){var e=this.files||[];r.call(this),o(e),a.auto?n.upload():l(e)}),a.bindAction.off("upload.action").on("upload.action",function(){n.upload()}),a.elem.data("haveEvents")||(n.elemFile.on("change",function(){y(this).trigger("upload.change")}),a.elem.on("click",function(){n.isFile()||y(this).trigger("upload.start")}),a.drag&&a.elem.on("dragover",function(e){e.preventDefault(),y(this).trigger("upload.over")}).on("dragleave",function(e){y(this).trigger("upload.leave")}).on("drop",function(e){e.preventDefault(),y(this).trigger("upload.drop",e)}),a.bindAction.on("click",function(){y(this).trigger("upload.action")}),a.elem.data("haveEvents",!0))},i.render=function(e){e=new w(e);return function(){var t=this;return{upload:function(e){t.upload.call(t,e)},reload:function(e){t.reload.call(t,e)},config:t.config}}.call(e)},e(n,i)});layui.define(["lay","layer","util"],function(e){"use strict";var b=layui.$,h=layui.layer,d=layui.util,l=layui.hint(),w=(layui.device(),"form"),o=".layui-form",T="layui-this",$="layui-hide",F="layui-disabled",t=function(){this.config={verify:{required:[/[\S]+/,"\u5fc5\u586b\u9879\u4e0d\u80fd\u4e3a\u7a7a"],phone:[/^1\d{10}$/,"\u8bf7\u8f93\u5165\u6b63\u786e\u7684\u624b\u673a\u53f7"],email:[/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/,"\u90ae\u7bb1\u683c\u5f0f\u4e0d\u6b63\u786e"],url:[/^(#|(http(s?)):\/\/|\/\/)[^\s]+\.[^\s]+$/,"\u94fe\u63a5\u683c\u5f0f\u4e0d\u6b63\u786e"],number:function(e){if(!e||isNaN(e))return"\u53ea\u80fd\u586b\u5199\u6570\u5b57"},date:[/^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$/,"\u65e5\u671f\u683c\u5f0f\u4e0d\u6b63\u786e"],identity:[/(^\d{15}$)|(^\d{17}(x|X|\d)$)/,"\u8bf7\u8f93\u5165\u6b63\u786e\u7684\u8eab\u4efd\u8bc1\u53f7"]},autocomplete:null}},i=(t.prototype.set=function(e){return b.extend(!0,this.config,e),this},t.prototype.verify=function(e){return b.extend(!0,this.config.verify,e),this},t.prototype.getFormElem=function(e){return b(o+(e?'[lay-filter="'+e+'"]':""))},t.prototype.on=function(e,t){return layui.onevent.call(this,w,e,t)},t.prototype.val=function(e,i){return this.getFormElem(e).each(function(e,t){var a=b(this);layui.each(i,function(e,t){var i,e=a.find('[name="'+e+'"]');e[0]&&("checkbox"===(i=e[0].type)?e[0].checked=t:"radio"===i?e.each(function(){this.checked=this.value==t}):e.val(t))})}),r.render(null,e),this.getValue(e)},t.prototype.getValue=function(e,t){t=t||this.getFormElem(e);var a={},n={},e=t.find("input,select,textarea");return layui.each(e,function(e,t){var i;b(this);t.name=(t.name||"").replace(/^\s*|\s*&/,""),t.name&&(/^.*\[\]$/.test(t.name)&&(i=t.name.match(/^(.*)\[\]$/g)[0],a[i]=0|a[i],i=t.name.replace(/^(.*)\[\]$/,"$1["+a[i]+++"]")),/^(checkbox|radio)$/.test(t.type)&&!t.checked||(n[i||t.name]=t.value))}),n},t.prototype.render=function(e,t){var i=this.config,a=b(o+(t?'[lay-filter="'+t+'"]':"")),n={input:function(e){e=e||a.find("input,textarea");i.autocomplete&&e.attr("autocomplete",i.autocomplete),a.find("input[lay-affix],textarea[lay-affix]").each(function(){var l=b(this),r=l.attr("lay-affix"),s="layui-input-suffix",o="layui-input-affix",e=l.is("[disabled]")||l.is("[readonly]"),c=function(e,t){(e=b(e))[0]&&e[b.trim(t)?"removeClass":"addClass"]($)},n=function(t){t=b.extend({},u[r]||{value:r},t,lay.options(l[0]));var i=b('
      '),e=b(''),a=(i.append(e),t.split&&i.addClass("layui-input-split"),l.next("."+o)),n=(a[0]&&a.remove(),l.next("."+s));n[0]?((a=n.find("."+o))[0]&&a.remove(),n.prepend(i),l.css("padding-right",function(){return(l.closest(".layui-input-group")[0]?0:n.outerWidth())+i.outerWidth()})):(i.addClass(s),l.after(i)),"auto"===t.show&&c(i,l.val()),l.on("input propertychange",function(){var e=this.value;"auto"===t.show&&c(i,e)}),e.on("click",function(){var e=l.attr("lay-filter");b(this).hasClass(F)||("function"==typeof t.click&&t.click.call(this,l,t),layui.event.call(this,w,"input-affix("+e+")",{elem:l[0],affix:r,options:t}))})},u={eye:{value:"eye-invisible",click:function(e,t){var i="LAY_FORM_INPUT_AFFIX_SHOW",a=e.data(i);e.attr("type",a?"password":"text").data(i,!a),n({value:a?"eye-invisible":"eye"})}},clear:{value:"clear",click:function(e){e.val("").focus(),c(b(this).parent(),null)},show:"auto",disabled:e}};n()})},select:function(e){var v,c="\u8bf7\u9009\u62e9",m="layui-form-select",g="layui-select-title",x="layui-select-none",k="",e=e||a.find("select"),C=function(e,t){b(e.target).parent().hasClass(g)&&!t||(b("."+m).removeClass(m+"ed "+m+"up"),v&&k&&v.val(k)),v=null},u=function(a,e,t){var s,r,i,n,o,l,c=b(this),u=a.find("."+g),d=u.find("input"),f=a.find("dl"),h=f.children("dd"),y=f.children("dt"),p=this.selectedIndex;e||(r=c.attr("lay-search"),i=function(){var e=a.offset().top+a.outerHeight()+5-q.scrollTop(),t=f.outerHeight();p=c[0].selectedIndex,a.addClass(m+"ed"),h.removeClass($),y.removeClass($),s=null,h.removeClass(T),0<=p&&h.eq(p).addClass(T),e+t>q.height()&&t<=e&&a.addClass(m+"up"),o()},n=function(e){a.removeClass(m+"ed "+m+"up"),d.blur(),s=null,e||l(d.val(),function(e){var t=c[0].selectedIndex;e&&(k=b(c[0].options[t]).html(),0===t&&k===d.attr("placeholder")&&(k=""),d.val(k||""))})},o=function(){var e,t,i=f.children("dd."+T);i[0]&&(e=i.position().top,t=f.height(),i=i.height(),t\u65e0\u5339\u914d\u9879

      '):f.find("."+x).remove()},"keyup"),""===t&&(c.val(""),f.find("."+T).removeClass(T),(c[0].options[0]||{}).value||f.children("dd:eq(0)").addClass(T),f.find("."+x).remove()),o()}).on("blur",function(e){var t=c[0].selectedIndex;v=d,k=b(c[0].options[t]).html(),0===t&&k===d.attr("placeholder")&&(k=""),setTimeout(function(){l(d.val(),function(e){k||d.val("")},"blur")},200)}),h.on("click",function(){var e=b(this),t=e.attr("lay-value"),i=c.attr("lay-filter");return e.hasClass(F)||(e.hasClass("layui-select-tips")?d.val(""):(d.val(e.text()),e.addClass(T)),e.siblings().removeClass(T),c.val(t).removeClass("layui-form-danger"),layui.event.call(this,w,"select("+i+")",{elem:c[0],value:t,othis:a}),n(!0)),!1}),a.find("dl>dt").on("click",function(e){return!1}),b(document).off("click",C).on("click",C))};e.each(function(e,t){var i=b(this),a=i.next("."+m),n=this.disabled,l=t.value,r=b(t.options[t.selectedIndex]),t=t.options[0];if("string"==typeof i.attr("lay-ignore"))return i.show();var s,o="string"==typeof i.attr("lay-search"),t=t&&!t.value&&t.innerHTML||c,r=b(['
      ','
      ','','
      ','
      ',(t=i.find("*"),s=[],layui.each(t,function(e,t){var i=t.tagName.toLowerCase();0!==e||t.value||"optgroup"===i?"optgroup"===i?s.push("
      "+t.label+"
      "):s.push('
      '+b.trim(t.innerHTML)+"
      "):s.push('
      '+b.trim(t.innerHTML||c)+"
      ")}),0===s.length&&s.push('
      \u6ca1\u6709\u9009\u9879
      '),s.join("")+"
      "),"
      "].join(""));a[0]&&a.remove(),i.after(r),u.call(this,r,n,o)})},checkbox:function(e){var o={checkbox:["layui-form-checkbox","layui-form-checked","checkbox"],"switch":["layui-form-switch","layui-form-onswitch","switch"],SUBTRA:"layui-icon-indeterminate"},e=e||a.find("input[type=checkbox]"),c={primary:!0,tag:!0,"switch":!0};e.each(function(e,t){var i=b(this),a=i.attr("lay-skin")||"primary",n=b.trim(t.title||(t.title=i.attr("lay-text")||"")),l=this.disabled,n="switch"===a?n.split("|"):[n],r=o[a=c[a]?a:"primary"]||o.checkbox;if("string"==typeof i.attr("lay-ignore"))return i.show();var s=i.next("."+r[0]),t=b(['
      ",(l={checkbox:[n[0]?""+d.escape(n[0])+"":"",''].join(""),"switch":""+((t.checked?n[0]:n[1])||"")+""})[a]||l.checkbox,"
      "].join(""));s[0]&&s.remove(),i.after(t),function(i,a){var n=b(this);i.on("click",function(){var e=n.attr("lay-filter"),t=(n.attr("title")||"").split("|");n[0].disabled||(n[0].indeterminate&&(n[0].indeterminate=!1,i.find(o.SUBTRA).removeClass(o.SUBTRA).addClass("layui-icon-ok")),n[0].checked?(n[0].checked=!1,i.removeClass(a[1]).find("em").text(t[1])):(n[0].checked=!0,i.addClass(a[1]).find("em").text(t[0])),layui.event.call(n[0],w,a[2]+"("+e+")",{elem:n[0],value:n[0].value,othis:i}))})}.call(this,t,r)})},radio:function(e){var r="layui-form-radio",s=["",""],e=e||a.find("input[type=radio]");e.each(function(e,t){var i=b(this),a=i.next("."+r),n=this.disabled;if("string"==typeof i.attr("lay-ignore"))return i.show();a[0]&&a.remove();n=b(['
      ',''+s[t.checked?0:1]+"","
      "+(a=d.escape(t.title||""),a="string"==typeof i.next().attr("lay-radio")?i.next().html():a)+"
      ","
      "].join(""));i.after(n),function(a){var n=b(this),l="layui-anim-scaleSpring";a.on("click",function(){var e=n[0].name,t=n.parents(o),i=n.attr("lay-filter"),e=t.find("input[name="+e.replace(/(\.|#|\[|\])/g,"\\$1")+"]");n[0].disabled||(layui.each(e,function(){var e=b(this).next("."+r);this.checked=!1,e.removeClass(r+"ed"),e.find(".layui-icon").removeClass(l).html(s[1])}),n[0].checked=!0,a.addClass(r+"ed"),a.find(".layui-icon").addClass(l).html(s[0]),layui.event.call(n[0],w,"radio("+i+")",{elem:n[0],value:n[0].value,othis:a}))})}.call(this,n)})}},t=function(){layui.each(n,function(e,t){t()})};return"object"===layui.type(e)?b(e).is(o)?(a=b(e),t()):e.each(function(e,t){var i=b(t);i.closest(o).length&&("SELECT"===t.tagName?n.select(i):"INPUT"===t.tagName&&("checkbox"===(t=t.type)||"radio"===t?n[t](i):n.input(i)))}):e?n[e]?n[e]():l.error('\u4e0d\u652f\u6301\u7684 "'+e+'" \u8868\u5355\u6e32\u67d3'):t(),this},t.prototype.validate=function(e){var u=null,d=r.config.verify,f="layui-form-danger";return!(e=b(e))[0]||(e.attr("lay-verify")!==undefined||!1!==this.validate(e.find("*[lay-verify]")))&&(layui.each(e,function(e,r){var s=b(this),t=(s.attr("lay-verify")||"").split("|"),o=s.attr("lay-vertype"),c=s.val();if(s.removeClass(f),layui.each(t,function(e,t){var i="",a=d[t];if(a){var n="function"==typeof a?i=a(c,r):!a[0].test(c),l="select"===r.tagName.toLowerCase()||/^(checkbox|radio)$/.test(r.type),i=i||a[1];if("required"===t&&(i=s.attr("lay-reqtext")||i),n)return"tips"===o?h.tips(i,"string"!=typeof s.attr("lay-ignore")&&l?s.next():s,{tips:1}):"alert"===o?h.alert(i,{title:"\u63d0\u793a",shadeClose:!0}):/\bstring|number\b/.test(typeof i)&&h.msg(i,{icon:5,shift:6}),setTimeout(function(){(l?s.next().find("input"):r).focus()},7),s.addClass(f),u=!0}}),u)return u}),!u)},t.prototype.submit=function(e,t){var i=b(this),e="string"==typeof e?e:i.attr("lay-filter"),a=this.getFormElem?this.getFormElem(e):i.parents(o).eq(0),n=a.find("*[lay-verify]");if(!r.validate(n))return!1;n=r.getValue(null,a),a={elem:this.getFormElem?window.event&&window.event.target:this,form:(this.getFormElem?a:i.parents("form"))[0],field:n};return"function"==typeof t&&t(a),layui.event.call(this,w,"submit("+e+")",a)}),r=new t,t=b(document),q=b(window);b(function(){r.render()}),t.on("reset",o,function(){var e=b(this).attr("lay-filter");setTimeout(function(){r.render(null,e)},50)}),t.on("submit",o,i).on("click","*[lay-submit]",i),e(w,r)});layui.define(["lay","laytpl","laypage","form","util"],function(e){"use strict";var p=layui.$,r=layui.lay,m=layui.laytpl,z=layui.laypage,h=layui.layer,f=layui.form,v=layui.util,u=layui.hint(),g=layui.device(),b={config:{checkName:"LAY_CHECKED",indexName:"LAY_INDEX",numbersName:"LAY_NUM",disabledName:"LAY_DISABLED"},cache:{},index:layui.table?layui.table.index+1e4:0,set:function(e){var t=this;return t.config=p.extend({},t.config,e),t},on:function(e,t){return layui.onevent.call(this,w,e,t)}},x=function(){var a=this,e=a.config,i=e.id||e.index;return{config:e,reload:function(e,t){a.reload.call(a,e,t)},reloadData:function(e,t){b.reloadData(i,e,t)},setColsWidth:function(){a.setColsWidth.call(a)},resize:function(){a.resize.call(a)}}},k=function(e){var t=x.that[e];return t||u.error(e?"The table instance with ID '"+e+"' not found":"ID argument required"),t||null},l=function(e){var t=x.config[e];return t||u.error(e?"The table instance with ID '"+e+"' not found":"ID argument required"),t||null},C=function(e){var t=this.config||{},a=(e=e||{}).item3,i=e.content,t=(("escape"in a?a:t).escape&&(i=v.escape(i)),e.text&&a.exportTemplet||a.templet||a.toolbar);return t&&(i="function"==typeof t?t.call(a,e.tplData,e.obj):m(p(t).html()||String(i)).render(p.extend({LAY_COL:a},e.tplData))),e.text?p("
      "+i+"
      ").text():i},w="table",t=".layui-table",T="layui-hide",L="layui-hide-v",N="layui-none",R="layui-table-view",o=".layui-table-header",_=".layui-table-body",A=".layui-table-pageview",D=".layui-table-sort",W="layui-table-edit",E="layui-table-hover",M="laytable-cell-group",j="layui-table-col-special",H="layui-table-tool-panel",S="LAY_TABLE_MOVE_DICT",a=function(e){return['
      ',"","{{# layui.each(d.data.cols, function(i1, item1){ }}","","{{# layui.each(item1, function(i2, item2){ }}",'{{# if(item2.fixed && item2.fixed !== "right"){ left = true; } }}','{{# if(item2.fixed === "right"){ right = true; } }}',(e=e||{}).fixed&&"right"!==e.fixed?'{{# if(item2.fixed && item2.fixed !== "right"){ }}':"right"===e.fixed?'{{# if(item2.fixed === "right"){ }}':"","{{# var isSort = !(item2.colGroup) && item2.sort; }}",'",e.fixed?"{{# }; }}":"","{{# }); }}","","{{# }); }}","","
      ','
      ','{{# if(item2.type === "checkbox"){ }}','',"{{# } else { }}",'{{-item2.title||""}}',"{{# if(isSort){ }}",'',"{{# } }}","{{# } }}","
      ","
      "].join("")},i=['',"","
      "].join(""),c=[,"{{# if(d.data.toolbar){ }}",'
      ','
      ','
      ',"
      ","{{# } }}",'
      ',"{{# if(d.data.loading){ }}",'
      ','',"
      ","{{# } }}","{{# var left, right; }}",'
      ',a(),"
      ",'
      ',i,"
      ","{{# if(left){ }}",'
      ','
      ',a({fixed:!0}),"
      ",'
      ',i,"
      ","
      ","{{# }; }}","{{# if(right){ }}",'
      ','
      ',a({fixed:"right"}),'
      ',"
      ",'
      ',i,"
      ","
      ","{{# }; }}","
      ","{{# if(d.data.totalRow){ }}",'
      ','','',"
      ","
      ","{{# } }}",'
      ','
      ',"
      ",""].join(""),I=p(window),F=p(document),n=function(e){this.index=++b.index,this.config=p.extend({},this.config,b.config,e),this.render()},d=(n.prototype.config={limit:10,loading:!0,escape:!0,cellMinWidth:60,cellMaxWidth:Number.MAX_VALUE,editTrigger:"click",defaultToolbar:["filter","exports","print"],defaultContextmenu:!0,autoSort:!0,text:{none:"\u65e0\u6570\u636e"},cols:[]},n.prototype.render=function(e){var t=this,a=t.config,i=(a.elem=p(a.elem),a.where=a.where||{},a.id="id"in a?a.id:a.elem.attr("id")||t.index);if(x.that[i]=t,(x.config[i]=a).request=p.extend({pageName:"page",limitName:"limit"},a.request),a.response=p.extend({statusName:"code",statusCode:0,msgName:"msg",dataName:"data",totalRowName:"totalRow",countName:"count"},a.response),null!==a.page&&"object"==typeof a.page&&(a.limit=a.page.limit||a.limit,a.limits=a.page.limits||a.limits,t.page=a.page.curr=a.page.curr||1,delete a.page.elem,delete a.page.jump),!a.elem[0])return t;if(a.elem.attr("lay-filter")||a.elem.attr("lay-filter",a.id),"reloadData"===e)return t.pullData(t.page,{type:"reloadData"});a.index=t.index,t.key=a.id||a.index,t.setInit(),a.height&&/^full-\d+$/.test(a.height)?(t.fullHeightGap=a.height.split("-")[1],a.height=I.height()-t.fullHeightGap):a.height&&/^#\w+\S*-\d+$/.test(a.height)&&(i=a.height.split("-"),t.parentHeightGap=i.pop(),t.parentDiv=i.join("-"),a.height=p(t.parentDiv).height()-t.parentHeightGap);var l,e=a.elem,i=e.next("."+R),n=t.elem=p("
      ");n.addClass((l=[R,R+"-"+t.index,"layui-form","layui-border-box"],a.className&&l.push(a.className),l.join(" "))).attr({"lay-filter":"LAY-TABLE-FORM-DF-"+t.index,"lay-id":a.id,style:(l=[],a.width&&l.push("width:"+a.width+"px;"),a.height&&l.push("height:"+a.height+"px;"),l.join(""))}).html(m(c,{open:"{{",close:"}}"}).render({data:a,index:t.index})),i[0]&&i.remove(),e.after(n),t.layTool=n.find(".layui-table-tool"),t.layBox=n.find(".layui-table-box"),t.layHeader=n.find(o),t.layMain=n.find(".layui-table-main"),t.layBody=n.find(_),t.layFixed=n.find(".layui-table-fixed"),t.layFixLeft=n.find(".layui-table-fixed-l"),t.layFixRight=n.find(".layui-table-fixed-r"),t.layTotal=n.find(".layui-table-total"),t.layPage=n.find(".layui-table-page"),t.renderToolbar(),t.renderPagebar(),t.fullSize(),t.pullData(t.page),t.events()},n.prototype.initOpts=function(e){this.config;e.checkbox&&(e.type="checkbox"),e.space&&(e.type="space"),e.type||(e.type="normal"),"normal"!==e.type&&(e.unresize=!0,e.width=e.width||{checkbox:50,radio:50,space:30,numbers:60}[e.type])},n.prototype.setInit=function(e){var l,a,d=this,r=d.config;if(r.clientWidth=r.width||(l=function(e){var t,a=(e=e||r.elem.parent()).width();try{t="none"===e.css("display")}catch(i){}return!e[0]||a&&!t?a:l(e.parent())})(),"width"===e)return r.clientWidth;r.height=r.maxHeight||r.height,r.css&&-1===r.css.indexOf(R)&&(a=r.css.split("}"),layui.each(a,function(e,t){t&&(a[e]="."+R+"-"+d.index+" "+t)}),r.css=a.join("}"));var c=function(a,e,i,l){var n,o;l?(l.key=[r.index,a,i].join("-"),l.hide=l.hide||!1,l.colspan=l.colspan||0,l.rowspan=l.rowspan||0,d.initOpts(l),(n=a+(parseInt(l.rowspan)||1))','
      ','
      '].join(""),a=this.layTool.find(".layui-table-tool-temp"),i=("default"===e.toolbar?a.html(t):"string"==typeof e.toolbar&&(t=p(e.toolbar).html()||"")&&a.html(m(t).render(e)),{filter:{title:"\u7b5b\u9009\u5217",layEvent:"LAYTABLE_COLS",icon:"layui-icon-cols"},exports:{title:"\u5bfc\u51fa",layEvent:"LAYTABLE_EXPORT",icon:"layui-icon-export"},print:{title:"\u6253\u5370",layEvent:"LAYTABLE_PRINT",icon:"layui-icon-print"}}),l=[];"object"==typeof e.defaultToolbar&&layui.each(e.defaultToolbar,function(e,t){t="string"==typeof t?i[t]:t;t&&l.push('
      ')}),this.layTool.find(".layui-table-tool-self").html(l.join(""))},n.prototype.renderPagebar=function(){var e,t=this.config,a=this.layPagebar=p('
      ');t.pagebar&&((e=p(t.pagebar).html()||"")&&a.append(m(e).render(t)),this.layPage.append(a))},n.prototype.setParentCol=function(e,t){var a=this.config,i=this.layHeader.find('th[data-key="'+t+'"]'),l=parseInt(i.attr("colspan"))||0;i[0]&&(t=t.split("-"),t=a.cols[t[1]][t[2]],e?l--:l++,i.attr("colspan",l),i[1<=l||!e?"removeClass":"addClass"](T),t.colspan=l,t.hide=1<=l||!e,(a=i.data("parentkey"))&&this.setParentCol(e,a))},n.prototype.setColsPatch=function(){var a=this,e=a.config;layui.each(e.cols,function(e,t){layui.each(t,function(e,t){t.hide&&a.setParentCol(t.hide,t.parentKey)})})},n.prototype.setGroupWidth=function(i){var e,l=this;l.config.cols.length<=1||((e=l.layHeader.find((i?"th[data-key="+i.data("parentkey")+"]>":"")+"."+M)).css("width",0),layui.each(e.get().reverse(),function(){var e=p(this),t=e.parent().data("key"),a=0;l.layHeader.eq(0).find("th[data-parentkey="+t+"]").width(function(e,t){p(this).hasClass(T)||0 tr:first-child > th:last-child")).data("field")&&e.prev()[0]?t(e.prev()):e})()).data("key"),n.getCssRule(e,function(e){var t=e.style.width||a.outerWidth();e.style.width=parseFloat(t)+l+"px",0'+(e||"Error")+"");a[0]&&(t.layNone.remove(),a.remove()),t.layFixed.addClass(T),t.layMain.find("tbody").html(""),t.layMain.append(t.layNone=e),t.layTotal.addClass(L),t.layPage.find(A).addClass(L),b.cache[t.key]=[],t.syncCheckAll(),t.renderForm(),t.setColsWidth()},n.prototype.page=1,n.prototype.pullData=function(t,a){var e,i,l=this,n=l.config,o=n.request,d=n.response,r=function(){"object"==typeof n.initSort&&l.sort({field:n.initSort.field,type:n.initSort.type,reloadType:a.type})};a=a||{},"function"==typeof n.before&&n.before(n),l.startTime=(new Date).getTime(),n.url?(e={},n.page&&(e[o.pageName]=t,e[o.limitName]=n.limit),o=p.extend(e,n.where),n.contentType&&0==n.contentType.indexOf("application/json")&&(o=JSON.stringify(o)),l.loading(),p.ajax({type:n.method||"get",url:n.url,contentType:n.contentType,data:o,dataType:n.dataType||"json",jsonpCallback:n.jsonpCallback,headers:n.headers||{},success:function(e){(e="function"==typeof n.parseData?n.parseData(e)||e:e)[d.statusName]!=d.statusCode?l.errorView(e[d.msgName]||'\u8fd4\u56de\u7684\u6570\u636e\u4e0d\u7b26\u5408\u89c4\u8303\uff0c\u6b63\u786e\u7684\u6210\u529f\u72b6\u6001\u7801\u5e94\u4e3a\uff1a"'+d.statusName+'": '+d.statusCode):(l.renderData({res:e,curr:t,count:e[d.countName],type:a.type}),r(),n.time=(new Date).getTime()-l.startTime+" ms"),l.setColsWidth(),"function"==typeof n.done&&n.done(e,t,e[d.countName])},error:function(e,t){l.errorView("\u8bf7\u6c42\u5f02\u5e38\uff0c\u9519\u8bef\u63d0\u793a\uff1a"+t),"function"==typeof n.error&&n.error(e,t)}})):"array"===layui.type(n.data)&&(e={},o=t*n.limit-n.limit,i=n.data.concat(),e[d.dataName]=n.page?i.splice(o,n.limit):i,e[d.countName]=n.data.length,"object"==typeof n.totalRow&&(e[d.totalRowName]=p.extend({},n.totalRow)),l.renderData({res:e,curr:t,count:e[d.countName],type:a.type}),r(),l.setColsWidth(),"function"==typeof n.done&&n.done(e,t,e[d.countName]))},n.prototype.eachCols=function(e){return b.eachCols(null,e,this.config.cols),this},n.prototype.col=function(e){try{return e=e.split("-"),this.config.cols[e[1]][e[2]]||{}}catch(t){return u.error(t),{}}},n.prototype.getTrHtml=function(t,a,l,e){var y=this,u=y.config,n=e&&e.trs||[],h=e&&e.trs_fixed||[],f=e&&e.trs_fixed_r||[];return l=l||1,layui.each(t,function(o,d){var i=[],r=[],c=[],s=o+u.limit*(l-1)+1;if("object"!=typeof d){t[o]=d={LAY_KEY:d};try{b.cache[y.key][o]=d}catch(e){}}"array"===layui.type(d)&&0===d.length||(d[b.config.numbersName]=s,a||(d[b.config.indexName]=o),y.eachCols(function(e,l){var t,e=l.field||e,a=l.key,n=d[e];n!==undefined&&null!==n||(n=""),l.colGroup||(t=['','
      "+function(){var e,t=p.extend(!0,{LAY_COL:l},d),a=b.config.checkName,i=b.config.disabledName;switch(l.type){case"checkbox":return'';case"radio":return t[a]&&(y.thisCheckedRowIndex=o),'';case"numbers":return s}return l.toolbar?m(p(l.toolbar).html()||"").render(t):C.call(y,{item3:l,content:n,tplData:t})}(),"
      "].join(""),i.push(t),l.fixed&&"right"!==l.fixed&&r.push(t),"right"===l.fixed&&c.push(t))}),n.push(''+i.join("")+""),h.push(''+r.join("")+""),f.push(''+c.join("")+""))}),{trs:n,trs_fixed:h,trs_fixed_r:f}},b.getTrHtml=function(e,t){return k(e).getTrHtml(t)},n.prototype.renderData=function(e){var a=this,i=a.config,t=e.res,l=e.curr,n=e.count,o=e.sort,d=t[i.response.dataName]||[],t=t[i.response.totalRowName],r=[],c=[],s=[],y=function(){if(i.HAS_SET_COLS_PATCH||a.setColsPatch(),i.HAS_SET_COLS_PATCH=!0,a.thisCheckedRowIndex="",!o&&a.sortKey)return a.sort({field:a.sortKey.field,type:a.sortKey.sort,pull:!0,reloadType:e.type});a.getTrHtml(d,o,l,{trs:r,trs_fixed:c,trs_fixed_r:s}),"fixed"===i.scrollPos&&"reloadData"===e.type||a.layBody.scrollTop(0),"reset"===i.scrollPos&&a.layBody.scrollLeft(0),a.layMain.find("."+N).remove(),a.layMain.find("tbody").html(r.join("")),a.layFixLeft.find("tbody").html(c.join("")),a.layFixRight.find("tbody").html(s.join("")),a.renderForm(),"number"==typeof a.thisCheckedRowIndex&&a.setRowChecked({type:"radio",index:a.thisCheckedRowIndex},!0),a.syncCheckAll(),a.fullSize(),a.haveInit?a.scrollPatch():setTimeout(function(){a.scrollPatch()},50),a.haveInit=!0,h.close(a.tipsIndex)};return b.cache[a.key]=d,a.layTotal[0==d.length?"addClass":"removeClass"](L),a.layPage[i.page||i.pagebar?"removeClass":"addClass"](T),a.layPage.find(A)[!i.page||0==n||0===d.length&&1==l?"addClass":"removeClass"](L),0===d.length?a.errorView(i.text.none):(a.layFixLeft.removeClass(T),o?y():(y(),a.renderTotal(d,t),a.layTotal&&a.layTotal.removeClass(T),void(i.page&&(i.page=p.extend({elem:"layui-table-page"+i.index,count:n,limit:i.limit,limits:i.limits||[10,20,30,40,50,60,70,80,90],groups:3,layout:["prev","page","next","skip","count","limit"],prev:'',next:'',jump:function(e,t){t||(a.page=e.curr,i.limit=e.limit,a.pullData(e.curr))}},i.page),i.page.count=n,z.render(i.page)))))},n.prototype.renderTotal=function(e,o){var d,r=this,c=r.config,s={};c.totalRow&&(layui.each(e,function(e,i){"array"===layui.type(i)&&0===i.length||r.eachCols(function(e,t){var e=t.field||e,a=i[e];t.totalRow&&(s[e]=(s[e]||0)+(parseFloat(a)||0))})}),r.dataTotal=[],d=[],r.eachCols(function(e,t){var a,e=t.field||e,i=o&&o[t.field],l="totalRowDecimals"in t?t.totalRowDecimals:2,l=s[e]?parseFloat(s[e]||0).toFixed(l):"",l=(a=t.totalRowText||"",(n={LAY_COL:t})[e]=l,n=t.totalRow&&C.call(r,{item3:t,content:l,tplData:n})||a,i||n),n=(t.field&&r.dataTotal.push({field:t.field,total:p("
      "+l+"
      ").text()}),['','
      "+("string"==typeof(a=t.totalRow||c.totalRow)?m(a).render(p.extend({TOTAL_NUMS:i||s[e],TOTAL_ROW:o||{},LAY_COL:t},t)):l),"
      "].join(""));d.push(n)}),e=r.layTotal.find(".layui-table-patch"),r.layTotal.find("tbody").html(""+d.join("")+(e.length?e.get(0).outerHTML:"")+""))},n.prototype.getColElem=function(e,t){this.config;return e.eq(0).find(".laytable-cell-"+t+":eq(0)")},n.prototype.renderForm=function(e){this.config;var t=this.elem.attr("lay-filter");f.render(e,t)},n.prototype.setRowChecked=function(a,e){var t=this,i=t.config,l="layui-table-click",n=t.layBody.find("tr"+("all"===a.index?"":'[data-index="'+a.index+'"]'));"checkbox"!==(a=p.extend({type:"checkbox",checked:!0},a)).type&&"all"!==a.index&&n.addClass(l).siblings("tr").removeClass(l),a.selectedStyle||e||(l=b.cache[t.key],layui.each(l,function(e,t){a.index===e||"all"===a.index?t[i.checkName]=a.checked:"radio"===a.type&&delete t[i.checkName]}),n.find('input[lay-type="'+({radio:"layTableRadio",checkbox:"layTableCheckbox"}[a.type]||"checkbox")+'"]').prop("checked",a.checked),t.syncCheckAll(),t.renderForm(a.type))},n.prototype.sort=function(l){var e,t=this,a={},i=t.config,n=i.elem.attr("lay-filter"),o=b.cache[t.key];"string"==typeof(l=l||{}).field&&(d=l.field,t.layHeader.find("th").each(function(e,t){var a=p(this),i=a.data("field");if(i===l.field)return l.field=a,d=i,!1}));try{var d=d||l.field.data("field"),r=l.field.data("key");if(t.sortKey&&!l.pull&&d===t.sortKey.field&&l.type===t.sortKey.sort)return;var c=t.layHeader.find("th .laytable-cell-"+r).find(D);t.layHeader.find("th").find(D).removeAttr("lay-sort"),c.attr("lay-sort",l.type||null),t.layFixed.find("th")}catch(s){u.error("Table modules: sort field '"+d+"' not matched")}t.sortKey={field:d,sort:l.type},i.autoSort&&("asc"===l.type?e=layui.sort(o,d):"desc"===l.type?e=layui.sort(o,d,!0):(e=layui.sort(o,b.config.indexName),delete t.sortKey,delete i.initSort)),a[i.response.dataName]=e||o,t.renderData({res:a,curr:t.page,count:t.count,sort:!0,type:l.reloadType}),l.fromEvent&&(i.initSort={field:d,type:l.type},layui.event.call(l.field,w,"sort("+n+")",p.extend({config:i},i.initSort)))},n.prototype.loading=function(e){var t=this;t.config.loading&&(e?(t.layInit&&t.layInit.remove(),delete t.layInit,t.layBox.find(".layui-table-init").remove()):(t.layInit=p(['
      ','',"
      "].join("")),t.layBox.append(t.layInit)))},n.prototype.setCheckData=function(e,t){var a=this.config,i=b.cache[this.key];i[e]&&"array"!==layui.type(i[e])&&(i[e][a.checkName]=t)},n.prototype.syncCheckAll=function(){var e=this,i=e.config,t=e.layHeader.find('input[name="layTableCheckbox"]'),a=function(a){return e.eachCols(function(e,t){"checkbox"===t.type&&(t[i.checkName]=a)}),a};t[0]&&(b.checkStatus(e.key).isAll?(t[0].checked||(t.prop("checked",!0),e.renderForm("checkbox")),a(!0)):(t[0].checked&&(t.prop("checked",!1),e.renderForm("checkbox")),a(!1)))},n.prototype.getCssRule=function(a,i){var e=this.elem.find("style")[0],e=e.sheet||e.styleSheet||{},e=e.cssRules||e.rules;layui.each(e,function(e,t){if(t.selectorText===".laytable-cell-"+a)return i(t),!0})},n.prototype.fullSize=function(){var e,a,i=this,t=i.config,l=t.height;i.fullHeightGap?(l=I.height()-i.fullHeightGap,i.elem.css("height",l=l<135?135:l)):i.parentDiv&&i.parentHeightGap&&(l=p(i.parentDiv).height()-i.parentHeightGap,i.elem.css("height",l=l<135?135:l)),1
      ')).find("div").css({width:a}),e.find("tr").append(t)):e.find(".layui-table-patch").remove()};n(e.layHeader),n(e.layTotal);n=e.layMain.height()-i;e.layFixed.find(_).css("height",t.height()>=n?n:"auto"),e.layFixRight[b.cache[e.key]&&b.cache[e.key].length&&0');a.html(t),y.height&&a.css("max-height",y.height-(s.layTool.outerHeight()||50)),i.find("."+H)[0]||i.append(a),s.renderForm(),a.on("click",function(e){layui.stope(e)}),e.done&&e.done(a,t)};switch(layui.stope(e),F.trigger("table.tool.panel.remove"),h.close(s.tipsIndex),t){case"LAYTABLE_COLS":l({list:(a=[],s.eachCols(function(e,t){t.field&&"normal"==t.type&&a.push('
    • "+(t.fieldTitle||t.title||t.field)+"").text())+'" lay-filter="LAY_TABLE_TOOL_COLS">
    • ')}),a.join("")),done:function(){f.on("checkbox(LAY_TABLE_TOOL_COLS)",function(e){var e=p(e.elem),t=this.checked,a=e.data("key"),i=s.col(a),l=i.hide,e=e.data("parentkey");i.key&&(i.hide=!t,s.elem.find('*[data-key="'+a+'"]')[t?"removeClass":"addClass"](T),l!=i.hide&&s.setParentCol(!t,e),s.resize(),layui.event.call(this,w,"colToggled("+r+")",{col:i,config:y}))})}});break;case"LAYTABLE_EXPORT":g.ie?h.tips("\u5bfc\u51fa\u529f\u80fd\u4e0d\u652f\u6301 IE\uff0c\u8bf7\u7528 Chrome \u7b49\u9ad8\u7ea7\u6d4f\u89c8\u5668\u5bfc\u51fa",this,{tips:3}):l({list:['
    • \u5bfc\u51fa csv \u683c\u5f0f\u6587\u4ef6
    • ','
    • \u5bfc\u51fa xls \u683c\u5f0f\u6587\u4ef6
    • '].join(""),done:function(e,t){t.on("click",function(){var e=p(this).data("type");b.exportFile.call(s,y.id,null,e)})}});break;case"LAYTABLE_PRINT":var n=window.open("about:blank","_blank"),o=[""].join(""),d=p(s.layHeader.html());d.append(s.layMain.find("table").html()),d.append(s.layTotal.find("table").html()),d.find("th.layui-table-patch").remove(),d.find("thead>tr>th."+j).filter(function(e,t){return!p(t).children("."+M).length}).remove(),d.find("tbody>tr>td."+j).remove(),n.document.write(o+d.prop("outerHTML")),n.document.close(),n.print(),n.close()}layui.event.call(this,w,"toolbar("+r+")",p.extend({event:t,config:y},{}))}),s.layPagebar.on("click","*[lay-event]",function(e){var t=p(this).attr("lay-event");layui.event.call(this,w,"pagebar("+r+")",p.extend({event:t,config:y},{}))}),e.on("mousemove",function(e){var t=p(this),a=t.offset().left,e=e.clientX-a;t.data("unresize")||x.eventMoveElem||(d.allowResize=t.width()-e<=10,o.css("cursor",d.allowResize?"col-resize":""))}).on("mouseleave",function(){p(this);x.eventMoveElem||o.css("cursor","")}).on("mousedown",function(e){var t,a=p(this);d.allowResize&&(t=a.data("key"),e.preventDefault(),d.offset=[e.clientX,e.clientY],s.getCssRule(t,function(e){var t=e.style.width||a.outerWidth();d.rule=e,d.ruleWidth=parseFloat(t),d.minWidth=a.data("minwidth")||y.cellMinWidth,d.maxWidth=a.data("maxwidth")||y.cellMaxWidth}),a.data(S,d),x.eventMoveElem=a)}),x.docEvent||F.on("mousemove",function(e){var t,a;x.eventMoveElem&&(t=x.eventMoveElem.data(S)||{},x.eventMoveElem.data("resizing",1),e.preventDefault(),t.rule&&(e=t.ruleWidth+e.clientX-t.offset[0],a=x.eventMoveElem.closest("."+R).attr("lay-id"),(a=k(a))&&((e=et.maxWidth&&(e=t.maxWidth),t.rule.style.width=e+"px",a.setGroupWidth(x.eventMoveElem),h.close(s.tipsIndex))))}).on("mouseup",function(e){var t,a,i,l,n;x.eventMoveElem&&(i=(t=x.eventMoveElem).closest("."+R).attr("lay-id"),(a=k(i))&&(i=t.data("key"),l=a.col(i),n=a.config.elem.attr("lay-filter"),d={},o.css("cursor",""),a.scrollPatch(),t.removeData(S),delete x.eventMoveElem,a.getCssRule(i,function(e){l.width=parseFloat(e.style.width),layui.event.call(t[0],w,"colResized("+n+")",{col:l,config:a.config})})))}),x.docEvent=!0,e.on("click",function(e){var t=p(this),a=t.find(D),i=a.attr("lay-sort");if(!a[0]||1===t.data("resizing"))return t.removeData("resizing");s.sort({field:t,type:"asc"===i?"desc":"desc"===i?null:"asc",fromEvent:!0})}).find(D+" .layui-edge ").on("click",function(e){var t=p(this),a=t.index(),t=t.parents("th").eq(0).data("field");layui.stope(e),0===a?s.sort({field:t,type:"asc",fromEvent:!0}):s.sort({field:t,type:"desc",fromEvent:!0})}),s.commonMember=function(e){var t=p(this).parents("tr").eq(0).data("index"),r=s.layBody.find('tr[data-index="'+t+'"]'),c=(c=b.cache[s.key]||[])[t]||{},a={tr:r,config:y,data:b.clearCacheKey(c),index:t,del:function(){b.cache[s.key][t]=[],r.remove(),s.scrollPatch()},update:function(e,d){e=e||{},layui.each(e,function(i,l){var n=r.children('td[data-field="'+i+'"]'),o=n.children(u);c[i]=a.data[i]=l,s.eachCols(function(e,t){var a;t.field==i?(o.html(C.call(s,{item3:t,content:l,tplData:p.extend({LAY_COL:t},c)})),n.data("content",l)):d&&(t.templet||t.toolbar)&&(e=r.children('td[data-field="'+(t.field||e)+'"]'),a=c[t.field],e.children(u).html(C.call(s,{item3:t,content:a,tplData:p.extend({LAY_COL:t},c)})),e.data("content",a))})}),s.renderForm()},setRowChecked:function(e){s.setRowChecked(p.extend({index:t},e))}};return p.extend(a,e)}),t=(s.elem.on("click",'input[name="layTableCheckbox"]+',function(){var e=p(this).prev(),t=s.layBody.find('input[name="layTableCheckbox"]'),a=e.parents("tr").eq(0).data("index"),i=e[0].checked,l="layTableAllChoose"===e.attr("lay-filter");e[0].disabled||(l?(t.each(function(e,t){t.checked=i,s.setCheckData(e,i)}),s.syncCheckAll(),s.renderForm("checkbox")):(s.setCheckData(a,i),s.syncCheckAll()),layui.event.call(e[0],w,"checkbox("+r+")",n.call(e[0],{checked:i,type:l?"all":"one"})))}),s.elem.on("click",'input[lay-type="layTableRadio"]+',function(){var e=p(this).prev(),t=e[0].checked,a=e.parents("tr").eq(0).data("index");e[0].disabled||(s.setRowChecked({type:"radio",index:a}),layui.event.call(e[0],w,"radio("+r+")",n.call(e[0],{checked:t})))}),s.layBody.on("mouseenter","tr",function(){var e=p(this),t=e.index();e.data("off")||s.layBody.find("tr:eq("+t+")").addClass(E)}).on("mouseleave","tr",function(){var e=p(this),t=e.index();e.data("off")||s.layBody.find("tr:eq("+t+")").removeClass(E)}).on("click","tr",function(){t.call(this,"row")}).on("dblclick","tr",function(){t.call(this,"rowDouble")}).on("contextmenu","tr",function(e){y.defaultContextmenu||e.preventDefault(),t.call(this,"rowContextmenu")}),function(e){var t=p(this);t.data("off")||layui.event.call(this,w,e+"("+r+")",n.call(t.children("td")[0]))}),c=function(e,t){var a,i,l,n;(e=p(e)).data("off")||(a=e.data("field"),n=e.data("key"),n=s.col(n),i=e.closest("tr").data("index"),i=b.cache[s.key][i],l=e.children(u),(n="function"==typeof n.edit?n.edit(i):n.edit)&&((n=p("textarea"===n?'':''))[0].value=e.data("content")||i[a]||l.text(),e.find("."+W)[0]||e.append(n),n.focus(),t&&layui.stope(t)))},i=(s.layBody.on("change","."+W,function(){var e=p(this),t=e.parent(),a=this.value,i=e.parent().data("field"),e=e.closest("tr").data("index"),e=b.cache[s.key][e],l=n.call(t[0],{value:a,field:i,oldValue:e[i],td:t,reedit:function(){setTimeout(function(){c(l.td);var e={};e[i]=l.oldValue,l.update(e)})},getCol:function(){return s.col(t.data("key"))}}),e={};e[i]=a,l.update(e),layui.event.call(t[0],w,"edit("+r+")",l)}).on("blur","."+W,function(){p(this).remove()}),s.layBody.on(y.editTrigger,"td",function(e){c(this,e)}).on("mouseenter","td",function(){a.call(this)}).on("mouseleave","td",function(){a.call(this,"hide")}),"layui-table-grid-down"),a=function(e){var t=p(this),a=t.children(u);t.data("off")||(e?t.find(".layui-table-grid-down").remove():!(a.prop("scrollWidth")>a.outerWidth()||0'))},l=(s.layBody.on("click","."+i,function(e){var t=p(this).parent().children(u);s.tipsIndex=h.tips(['
      ',t.html(),"
      ",''].join(""),t[0],{tips:[3,""],time:-1,anim:-1,maxWidth:g.ios||g.android?300:s.elem.width()/2,isOutAnim:!1,skin:"layui-table-tips",success:function(e,t){e.find(".layui-table-tips-c").on("click",function(){h.close(t)})}}),layui.stope(e)}),function(e){var t=p(this),a=t.parents("tr").eq(0).data("index");layui.event.call(this,w,(e||"tool")+"("+r+")",n.call(this,{event:t.attr("lay-event")})),s.setRowChecked({type:"radio",index:a},!0)});s.layBody.on("click","*[lay-event]",function(e){l.call(this),layui.stope(e)}).on("dblclick","*[lay-event]",function(e){l.call(this,"toolDouble"),layui.stope(e)}),s.layMain.on("scroll",function(){var e=p(this),t=e.scrollLeft(),e=e.scrollTop();s.layHeader.scrollLeft(t),s.layTotal.scrollLeft(t),s.layFixed.find(_).scrollTop(e),h.close(s.tipsIndex)}),I.on("resize",function(){s.resize()})},F.on("click",function(){F.trigger("table.remove.tool.panel")}),F.on("table.remove.tool.panel",function(){p("."+H).remove()}),b.init=function(i,o){o=o||{};var e="object"==typeof i?i:p("string"==typeof i?'table[lay-filter="'+i+'"]':t+"[lay-data], "+t+"[lay-options]"),d="Table element property lay-data configuration item has a syntax error: ";return e.each(function(){var l,e=p(this),t=e.attr("lay-data"),t=r.options(this,{attr:t?"lay-data":null,errorText:d+(t||e.attr("lay-options"))}),n=p.extend({elem:this,cols:[],data:[],skin:e.attr("lay-skin"),size:e.attr("lay-size"),even:"string"==typeof e.attr("lay-even")},b.config,o,t),a=(i&&e.hide(),e.find("thead>tr").each(function(i){n.cols[i]=[],p(this).children().each(function(e){var t=p(this),a=t.attr("lay-data"),a=r.options(this,{attr:a?"lay-data":null,errorText:d+(a||t.attr("lay-options"))}),t=p.extend({title:t.text(),colspan:parseInt(t.attr("colspan"))||0,rowspan:parseInt(t.attr("rowspan"))||0},a);n.cols[i].push(t)})}),e.find("tbody>tr")),t=b.render(n);!a.length||o.data||t.config.url||(l=0,b.eachCols(t.config.id,function(e,i){a.each(function(e){n.data[e]=n.data[e]||{};var t=p(this),a=i.field;n.data[e][a]=t.children("td").eq(l).html()}),l++}),t.reloadData({data:n.data}))}),this},x.that={},x.config={},function(a,i,e,l){var n,o;l.colGroup&&(n=0,a++,l.CHILD_COLS=[],o=e+(parseInt(l.rowspan)||1),layui.each(i[o],function(e,t){t.parentKey?t.parentKey===l.key&&(t.PARENT_COL_INDEX=a,l.CHILD_COLS.push(t),d(a,i,o,t)):t.PARENT_COL_INDEX||1<=n&&n==(l.colspan||1)||(t.PARENT_COL_INDEX=a,l.CHILD_COLS.push(t),n+=t.hide?0:parseInt(1td').filter('[data-field="'+e+'"]')}}})).replace(/"/g,'""'),n.push(a='"'+a+'"')))}),d.push(n.join(","))}),c&&layui.each(c.dataTotal,function(e,t){r[t.field]||i.push(t.total+"\t")}),o.join(",")+"\r\n"+d.join("\r\n")+"\r\n"+i.join(","))),y.download=(a.title||n.title||"table_"+(n.index||""))+"."+l,document.body.appendChild(y),y.click(),document.body.removeChild(y)},b.getOptions=l,b.hideCol=function(e,l){var n=k(e);n&&("boolean"===layui.type(l)?n.eachCols(function(e,t){var a=t.key,i=n.col(a),t=t.parentKey;i.hide!=l&&(i=i.hide=l,n.elem.find('*[data-key="'+a+'"]')[i?"addClass":"removeClass"](T),n.setParentCol(i,t))}):layui.each(l,function(e,l){n.eachCols(function(e,t){var a,i;l.field===t.field&&(a=t.key,i=n.col(a),t=t.parentKey,"hide"in l&&i.hide!=l.hide&&(i=i.hide=!!l.hide,n.elem.find('*[data-key="'+a+'"]')[i?"addClass":"removeClass"](T),n.setParentCol(i,t)))})}),p("."+H).remove(),n.resize())},b.reload=function(e,t,a,i){if(l(e))return e=k(e),e.reload(t,a,i),x.call(e)},b.reloadData=function(){var a=p.extend([],arguments),i=(a[3]="reloadData",new RegExp("^("+["elem","id","cols","width","height","maxHeight","toolbar","defaultToolbar","className","css","totalRow","page","pagebar"].join("|")+")$"));return layui.each(a[1],function(e,t){i.test(e)&&delete a[1][e]}),b.reload.apply(null,a)},b.render=function(e){e=new n(e);return x.call(e)},b.clearCacheKey=function(e){return delete(e=p.extend({},e))[b.config.checkName],delete e[b.config.indexName],delete e[b.config.numbersName],delete e[b.config.disabledName],e},p(function(){b.init()}),e(w,b)});layui.define(["table"],function(e){"use strict";var O=layui.$,y=layui.form,Y=layui.table,i=layui.hint(),p={config:{},on:Y.on,eachCols:Y.eachCols,index:Y.index,set:function(e){var t=this;return t.config=O.extend({},t.config,e),t},resize:Y.resize},o=function(){var a=this,e=a.config,n=e.id||e.index;return{config:e,reload:function(e,t){a.reload.call(a,e,t)},reloadData:function(e,t){p.reloadData(n,e,t)}}},E=function(e){var t=o.that[e];return t||i.error(e?"The treeTable instance with ID '"+e+"' not found":"ID argument required"),t||null},L=".layui-table-main",j=".layui-table-fixed-l",P=".layui-table-fixed-r",B="LAY_DATA_INDEX",h="LAY_DATA_INDEX_HISTORY",f="LAY_PARENT_INDEX",s="LAY_CHECKBOX_HALF",F="LAY_EXPAND",X="LAY_HAS_EXPANDED",t=function(e){var t=this;t.index=++p.index,t.config=O.extend(!0,{},t.config,p.config,e),t.init(),t.render()},c=function(n,i,e){var l=Y.cache[n];layui.each(e||l,function(e,t){var a=t[B];-1!==a.indexOf("-")&&(l[a]=t),t[i]&&c(n,i,t[i])})};t.prototype.init=function(){var i=this,e=i.config,t=Y.render(O.extend({},e,{data:[],url:"",done:null})),l=t.config.id,a=((o.that[l]=i).tableIns=t,e.tree),t=a.customName,r=(t.isParent,t.children),n=e.parseData,d=e.done;e.url?e.parseData=function(){var e=arguments,t=e[0],e=("function"===layui.type(n)&&(t=n.apply(this,e)||e[0]),this.response.dataName);return a.data.isSimpleData&&!a["async"].enable&&(t[e]=i.flatToTree(t[e])),i.initData(t[e]),t}:(e.data=e.data||[],a.data.isSimpleData&&(e.data=i.flatToTree(e.data)),e.initSort&&e.initSort.type&&(e.data=layui.sort(e.data,e.initSort.field,"desc"===e.initSort.type)),i.initData(e.data)),e.done=function(){var e,t=arguments,a=this.elem.next(),n=(i.updateStatus(null,{LAY_HAS_EXPANDED:!1}),c(l,r),a.find('[name="layTableCheckbox"][lay-filter="layTableAllChoose"]'));if(n.length&&(e=p.checkStatus(l),n.prop({checked:e.isAll&&e.data.length,indeterminate:!e.isAll&&e.data.length})),i.renderTreeTable(a),"function"===layui.type(d))return d.apply(this,t)}},t.prototype.config={tree:{customName:{children:"children",isParent:"isParent",name:"name",id:"id",pid:"parentId",rootId:null},view:{indent:14,flexIconClose:'',flexIconOpen:'',showIcon:!0,icon:"",iconClose:'',iconOpen:'',iconLeaf:'',showFlexIconIfNotParent:!1,dblClickExpand:!0},data:{isSimpleData:!1},"async":{enable:!1,url:"",type:null,contentType:null,headers:null,where:null,autoParam:[]},callback:{beforeExpand:null,onExpand:null}},autoSort:!1},t.prototype.getOptions=function(){return this.tableIns?Y.getOptions(this.tableIns.config.id):this.config},t.prototype.flatToTree=function(e){var a,n,i,t,l,r=this.getOptions(),d=r.tree.customName,r=r.id;return e=e||Y.cache[r],r=e,a=d.id,n=d.pid,i=d.children,t=d.rootId,a=a||"id",n=n||"parentId",i=i||"children",l={},layui.each(r,function(e,t){l[t[a]]=O.extend({},t),l[t[a]][i]=[]}),layui.each(l,function(e,t){t[n]&&l[t[n]]&&l[t[n]][i].push(t)}),Object.values(l).filter(function(e){return t?e[n]===t:!e[n]})},t.prototype.treeToFlat=function(e,n,i){var l=this,r=l.getOptions().tree.customName,d=r.children,o=r.pid,c=[];return layui.each(e,function(e,t){var e=(i?i+"-":"")+e,a=O.extend({},t);a[d]=null,a[o]=t[o]||n,c.push(a),c=c.concat(l.treeToFlat(t[d],t[r.id],e))}),c},t.prototype.getNodeDataByIndex=function(a,e,t){var n=this.getOptions(),i=n.tree,l=n.id,r=Y.cache[l][a];if("delete"!==t&&r)return e?O.extend({},r):r;for(var r=this.getTableData(),d=(a+="").split("-"),o=r,c=n.url||1'),O.ajax({type:C||"get",url:w,contentType:T,data:N,dataType:_||"json",jsonpCallback:A,headers:D||{},success:function(e){p.LAY_ASYNC_STATUS="success",(e="function"==typeof I?I.call(o,e)||e:e)[S.statusName]!=S.statusCode?(p.LAY_ASYNC_STATUS="error",v.html('')):(p[u.children]=e[S.dataName],y.initData(p[u.children],p[B]),U(t,!0,!x&&n,i,l))},error:function(e,t){p.LAY_ASYNC_STATUS="error","function"==typeof o.error&&o.error(e,t)}}),m;p[F]=e,b=p[X]=!0,f.length&&(o.initSort&&!o.url&&(f=(g=o.initSort).type?p[u.children]=layui.sort(f,g.field,"desc"===g.type):p[u.children]=layui.sort(f,Y.config.indexName)),y.initData(p[u.children],p[B]),C=Y.getTrHtml(d,f,null,null,s),k={trs:O(C.trs.join("")),trs_fixed:O(C.trs_fixed.join("")),trs_fixed_r:O(C.trs_fixed_r.join(""))},layui.each(f,function(e,t){k.trs.eq(e).attr({"data-index":t[B],"lay-data-index":t[B],"data-level":h}),k.trs_fixed.eq(e).attr({"data-index":t[B],"lay-data-index":t[B],"data-level":h}),k.trs_fixed_r.eq(e).attr({"data-index":t[B],"lay-data-index":t[B],"data-level":h})}),r.find(L).find('tbody tr[lay-data-index="'+s+'"]').after(k.trs),r.find(j).find('tbody tr[lay-data-index="'+s+'"]').after(k.trs_fixed),r.find(P).find('tbody tr[lay-data-index="'+s+'"]').after(k.trs_fixed_r),layui.each(k,function(e,t){y.renderTreeTable(t,h)}),n&&!x&&layui.each(f,function(e,t){U({trElem:r.find('tr[lay-data-index="'+t.LAY_DATA_INDEX+'"]').first()},a,n,i,l)}))}else p[F]=e,n&&!x?(layui.each(f,function(e,t){U({trElem:r.find('tr[lay-data-index="'+t.LAY_DATA_INDEX+'"]').first()},a,n,i,l)}),r.find(f.map(function(e,t,a){return'tr[lay-data-index="'+e[B]+'"]'}).join(",")).addClass("layui-hide")):(w=y.treeToFlat(f,p[u.id],s),r.find(w.map(function(e,t,a){return'tr[lay-data-index="'+e[B]+'"]'}).join(",")).addClass("layui-hide"));return Y.resize(d),l&&"loading"!==p.LAY_ASYNC_STATUS&&(T=c.callback.onExpand,"function"===layui.type(T)&&T(d,p,a)),m},l=(p.expandNode=function(e,t){var a,n,i,e=E(e);if(e)return a=(t=t||{}).index,n=t.expandFlag,i=t.inherit,t=t.callbackFlag,e=e.getOptions().elem.next(),U({trElem:e.find('tr[lay-data-index="'+a+'"]').first()},n,i,null,t)},p.expandAll=function(e,t){if("boolean"!==layui.type(t))return i.error("expandAll\u7684\u5c55\u5f00\u72b6\u6001\u53c2\u6570\u53ea\u63a5\u6536true/false");e=E(e);if(e){var a=e.getOptions(),n=a.tree,a=a.elem.next();if(t)return i.error("\u6682\u4e0d\u652f\u6301\u5c55\u5f00\u5168\u90e8");else{e.updateStatus(null,{LAY_EXPAND:!1}),a.find('tbody tr[data-level!="0"]').addClass("layui-hide");t=a.find('tbody tr[data-level="0"]');t.find(".layui-table-tree-flexIcon").html(n.view.flexIconClose),t.find(".layui-table-tree-nodeIcon").html(n.view.iconClose),p.resize()}}},t.prototype.renderTreeTable=function(e,l,t){var a=this.getOptions(),n=a.elem.next(),i=(n.addClass("layui-table-tree"),a.id),r=a.tree||{},d=(r.data,r.view||{}),a=r.customName||{},o=a.isParent,c=n.attr("lay-filter"),u=this,f=((l=l||0)||(n.find(".layui-table-body tr:not([data-level])").attr("data-level",l),layui.each(Y.cache[i],function(e,t){n.find('.layui-table-main tbody tr[data-level="0"]:eq('+e+")").attr("lay-data-index",t[B]),n.find('.layui-table-fixed-l tbody tr[data-level="0"]:eq('+e+")").attr("lay-data-index",t[B]),n.find('.layui-table-fixed-r tbody tr[data-level="0"]:eq('+e+")").attr("lay-data-index",t[B])})),{}),a=a.name,s=r.view.indent||14;layui.each(e.find('td[data-field="'+a+'"]'),function(e,t){var a,n=(t=O(t)).closest("tr"),i=t.children(".layui-table-cell");i.hasClass("layui-table-tree-item")||(i.addClass("layui-table-tree-item"),(i=n.attr("lay-data-index"))&&((a=u.getNodeDataByIndex(i))[F]&&(f[i]=!0),i=t.find("div.layui-table-cell").html(),t.find("div.layui-table-cell").html(['
      ',r.view.flexIconClose,"
      ",'
      ',r.view.showIcon&&(a.icon||r.view.icon||(a[o]?r.view.iconClose:r.view.iconLeaf))||"","
      ",i].join("")).find(".layui-table-tree-flexIcon").on("click",function(e){layui.stope(e),U({trElem:n},null,null,null,!0)})))}),!1!==t&&layui.each(f,function(e,t){e=n.find('tr[lay-data-index="'+e+'"]');e.find(".layui-table-tree-flexIcon").html(r.view.flexIconOpen),U({trElem:e.first()},!0)}),p.formatNumber(i),y.render(null,c)},p.formatNumber=function(e){var n,i,l=E(e);if(l)return n=l.getOptions().elem.next(),i=0,layui.each(l.treeToFlat(Y.cache[e]),function(e,t){var a;layui.isArray(t)||((a=l.getNodeDataByIndex(t.LAY_DATA_INDEX)).LAY_NUM=++i,n.find('tr[lay-data-index="'+t.LAY_DATA_INDEX+'"] .laytable-cell-numbers').html(a.LAY_NUM))}),p},t.prototype.render=function(e){var t=this;t.tableIns=Y["reloadData"===e?"reloadData":"reload"](t.tableIns.config.id,O.extend(!0,{},t.config)),t.config=t.tableIns.config},t.prototype.reload=function(e,t,a){var n=this;e=e||{},delete n.haveInit,layui.each(e,function(e,t){"array"===layui.type(t)&&delete n.config[e]}),n.config=O.extend(t,{},n.config,e,{autoSort:!1}),n.render(a)},p.reloadData=function(){var e=O.extend(!0,[],arguments);return e[3]="reloadData",p.reload.apply(null,e)},function(e,a,n){var i=[];return layui.each(e,function(e,t){"function"===layui.type(a)?a(t):O.extend(t,a),i.push(O.extend({},t)),i=i.concat(l(t[n],a,n))}),i}),n=(t.prototype.updateStatus=function(e,t){var a=this.getOptions(),n=a.tree;return e=e||Y.cache[a.id],l(e,t,n.customName.children)},t.prototype.getTableData=function(){var e=this.getOptions();return e.url?Y.cache[e.id]:e.data},p.updateStatus=function(e,t,a){var e=E(e),n=e.getOptions();return a=a||(n.url?Y.cache[n.id]:n.data),e.updateStatus(a,t)},p.sort=function(e){var t,a,n=E(e);n&&(a=(t=n.getOptions()).initSort,t.url||(a.type?t.data=layui.sort(t.data,a.field,"desc"===a.type):t.data=layui.sort(t.data,Y.config.indexName),n.initData(t.data),p.reloadData(e)))},function(t){var a=t.config.id,n=E(a),i=t.data=p.getNodeDataByIndex(a,t.index),l=i[B],r=(t.dataIndex=l,t.update);t.update=function(){var e=arguments,e=(O.extend(n.getNodeDataByIndex(l),e[0]),r.apply(this,e));return n.renderTreeTable(t.tr,t.tr.attr("data-level"),!1),e},t.del=function(){p.removeNode(a,i)},t.setRowChecked=function(e){p.setRowChecked(a,{index:i,checked:e})}}),u=(p.updateNode=function(e,a,t){var n,i,l,r,d=E(e);d&&((l=d.getOptions()).tree,l=(n=l.elem.next()).find('tr[lay-data-index="'+a+'"]'),i=l.attr("data-index"),l=l.attr("data-level"),t&&(t=d.getNodeDataByIndex(a,!1,t),r=Y.getTrHtml(e,[t]),layui.each(["main","fixed-l","fixed-r"],function(e,t){n.find(".layui-table-"+t+' tbody tr[lay-data-index="'+a+'"]').replaceWith(O(r[["trs","trs_fixed","trs_fixed_r"][e]].join("")).attr({"data-index":i,"lay-data-index":a}))}),d.renderTreeTable(n.find('tr[lay-data-index="'+a+'"]'),l)))},p.removeNode=function(e,t){var a,n,i,l,r=E(e);r&&(l=(i=r.getOptions()).tree,a=i.elem.next(),n=[],i=r.getNodeDataByIndex("string"===layui.type(t)?t:t[B],!1,"delete"),t=r.getNodeDataByIndex(i[f]),r.updateCheckStatus(t,!0),t=r.treeToFlat([i],i[l.customName.pid],i[f]),layui.each(t,function(e,t){n.push('tr[lay-data-index="'+t[B]+'"]')}),a.find(n.join(",")).remove(),l=r.initData(),layui.each(r.treeToFlat(l),function(e,t){t[h]&&t[h]!==t[B]&&a.find('tr[lay-data-index="'+t[h]+'"]').attr({"data-index":t[B],"lay-data-index":t[B]})}),layui.each(Y.cache[e],function(e,t){a.find('tr[data-level="0"][lay-data-index="'+t[B]+'"]').attr("data-index",e)}),p.formatNumber(e))},p.addNodes=function(e,t){var a,n,i,l,r,d,o,c,u,f,s,y=E(e);if(y)return u=y.getOptions(),f=u.tree,a=u.elem.next(),s=(t=t||{}).parentIndex,i=t.index,l=t.data,t=t.focus,n=(s="number"===layui.type(s)?s.toString():s)?y.getNodeDataByIndex(s):null,i="number"===layui.type(i)?i:-1,l=O.extend(!0,[],layui.isArray(l)?l:[l]),y.getTableData(),n?(r=f.customName.isParent,f=f.customName.children,n[r]=!0,c=(c=n[f])?(d=c.splice(-1===i?c.length:i),n[f]=c.concat(l,d)):n[f]=l,y.updateStatus(c,function(e){e[r]&&(e[X]=!1)}),f=y.treeToFlat(c),a.find(f.map(function(e){return'tr[lay-data-index="'+e[B]+'"]'}).join(",")).remove(),y.initData(),n[X]=!1,n.LAY_ASYNC_STATUS="local",U({trElem:a.find('tr[lay-data-index="'+s+'"]')},!0)):(d=Y.cache[e].splice(-1===i?Y.cache[e].length:i),Y.cache[e]=Y.cache[e].concat(l,d),u.url||(u.page?(c=u.page,u.data.splice.apply(u.data,[c.limit*(c.curr-1),c.limit].concat(Y.cache[e]))):u.data=Y.cache[e]),y.initData(),f=Y.getTrHtml(e,l),o={trs:O(f.trs.join("")),trs_fixed:O(f.trs_fixed.join("")),trs_fixed_r:O(f.trs_fixed_r.join(""))},layui.each(l,function(e,t){o.trs.eq(e).attr({"data-index":t[B],"lay-data-index":t[B],"data-level":"0"}),o.trs_fixed.eq(e).attr({"data-index":t[B],"lay-data-index":t[B],"data-level":"0"}),o.trs_fixed_r.eq(e).attr({"data-index":t[B],"lay-data-index":t[B],"data-level":"0"})}),s=parseInt(l[0][B])-1,c=a.find(L),u=a.find(j),f=a.find(P),-1==s?(c.find('tr[data-level="0"][data-index="0"]').before(o.trs),u.find('tr[data-level="0"][data-index="0"]').before(o.trs_fixed),f.find('tr[data-level="0"][data-index="0"]').before(o.trs_fixed_r)):-1===i?(c.find("tbody").append(o.trs),u.find("tbody").append(o.trs_fixed),f.find("tbody").append(o.trs_fixed_r)):(s=d[0][h],c.find('tr[data-level="0"][data-index="'+s+'"]').before(o.trs),u.find('tr[data-level="0"][data-index="'+s+'"]').before(o.trs_fixed),f.find('tr[data-level="0"][data-index="'+s+'"]').before(o.trs_fixed_r)),layui.each(Y.cache[e],function(e,t){a.find('tr[data-level="0"][lay-data-index="'+t[B]+'"]').attr("data-index",e)}),y.renderTreeTable(a.find(l.map(function(e,t,a){return'tr[lay-data-index="'+e[B]+'"]'}).join(",")))),y.updateCheckStatus(n,!0),p.resize(e),t&&a.find(L).find('tr[lay-data-index="'+l[0][B]+'"]').get(0).scrollIntoViewIfNeeded(),l},p.checkStatus=function(e){var t,a;if(E(e))return t=p.getData(e,!0).filter(function(e,t,a){return e[Y.config.checkName]}),a=!0,layui.each(Y.cache[e],function(e,t){if(!t[Y.config.checkName])return!(a=!1)}),{data:t,isAll:a}},p.on("sort",function(e){var e=e.config,t=e.elem.next(),e=e.id;t.hasClass("layui-table-tree")&&p.sort(e)}),p.on("row",function(e){e.config.elem.next().hasClass("layui-table-tree")&&n(e)}),p.on("rowDouble",function(e){var t=e.config,a=t.elem.next();t.id;a.hasClass("layui-table-tree")&&(n(e),(t.tree||{}).view.dblClickExpand&&U({trElem:e.tr.first()},null,null,null,!0))}),p.on("tool",function(e){var t=e.config,a=t.elem.next();t.id;a.hasClass("layui-table-tree")&&n(e)}),p.on("edit",function(e){var t=e.config,a=t.elem.next();t.id;a.hasClass("layui-table-tree")&&(n(e),e.field===t.tree.customName.name&&(e.tr.find('td[data-field="'+e.field+'"]').children("div.layui-table-cell").removeClass("layui-table-tree-item"),e.update({})))}),p.on("radio",function(e){var t=e.config,a=t.elem.next(),t=t.id,t=E(t);a.hasClass("layui-table-tree")&&(n(e),u.call(t,e.tr,e.checked))}),t.prototype.updateCheckStatus=function(e,t){var a=this.getOptions(),n=(a.tree,a.id),i=a.elem.next(),l=Y.config.checkName,r=(e&&(a=this.updateParentCheckStatus(e,t),layui.each(a,function(e,t){y.render(i.find('tr[lay-data-index="'+t[B]+'"] input[name="layTableCheckbox"]:not(:disabled)').prop({checked:t[l],indeterminate:t[s]}))})),!0),d=!1;return layui.each(Y.cache[n],function(e,t){(t[l]||t[s])&&(d=!0),t[l]||(r=!1)}),d=d&&!r,y.render(i.find('input[name="layTableCheckbox"][lay-filter="layTableAllChoose"]').prop({checked:r,indeterminate:d})),r},t.prototype.updateParentCheckStatus=function(a,n){var e=this.getOptions(),t=e.tree,e=e.id,i=Y.config.checkName,t=t.customName.children,l=[];return a[s]=!1,n?a[t].length?layui.each(a[t],function(e,t){if(!t[i])return n=!1,a[s]=!0}):n=!1:layui.each(a[t],function(e,t){if(t[i]||t[s])return a[s]=!0}),a[i]=n,l.push(O.extend({},a)),l=a[f]?l.concat(this.updateParentCheckStatus(Y.cache[e][a[f]],n)):l},function(e,t,a){var n=this,i=n.getOptions(),l=i.id,r=i.elem.next(),d=(e.length?e:r).find(".laytable-cell-radio, .laytable-cell-checkbox").children("input").last(),o="radio"===d.attr("type");if(a){a=function(){var e=function(e){layui.stope(e)};d.parent().on("click",e),d.next().click(),d.parent().off("click",e)};o?t&&!d.prop("checked")&&a():"boolean"===layui.type(t)&&d.prop("checked")===t||a()}else{var c,a=n.getNodeDataByIndex(e.attr("data-index")),u=Y.config.checkName;if(!o)return i.tree.customName.isParent,t="boolean"===layui.type(t)?t:!a[u],o=n.updateStatus(a?[a]:Y.cache[l],function(e){e[Y.config.disabledName]||(e[u]=t,e[s]=!1)}),y.render(r.find(o.map(function(e){return'tr[lay-data-index="'+e[B]+'"] input[name="layTableCheckbox"]:not(:disabled)'}).join(",")).prop({checked:t,indeterminate:!1})),a&&a[f]&&(c=n.getNodeDataByIndex(a[f])),n.updateCheckStatus(c,t);a&&(n.updateStatus(null,function(e){e[u]&&(e[u]=!1,y.render(r.find('tr[lay-data-index="'+e[B]+'"] input[type="radio"][lay-type="layTableRadio"]').prop("checked",!1)))}),a[u]=t,y.render(e.find('input[type="radio"][lay-type="layTableRadio"]').prop("checked",t)))}});p.on("checkbox",function(e){var t=e.config,a=t.elem.next(),t=t.id,t=E(t);a.hasClass("layui-table-tree")&&(n(e),a=e.checked,e.isAll=u.call(t,e.tr,a))}),p.setRowChecked=function(e,t){var a,n,i,l,r,d=E(e);d&&(a=d.getOptions().elem.next(),i=(t=t||{}).index,n=t.checked,t=t.callbackFlag,i="string"===layui.type(i)?i:i[B],(l=d.getNodeDataByIndex(i))&&((r=a.find('tr[lay-data-index="'+i+'"]')).length||(p.expandNode(e,{index:l[f],expandFlag:!0}),r=a.find('tr[lay-data-index="'+i+'"]')),u.call(d,r,n,t)))},p.checkAllNodes=function(e,t){var a,e=E(e);e&&(a=e.getOptions().elem.next(),u.call(e,a.find('tr[data-index="NONE"]'),!!t))},p.getData=function(e,t){var a=[];return layui.each(O.extend(!0,[],Y.cache[e]||[]),function(e,t){a.push(t)}),t?E(e).treeToFlat(a):a},o.that={},p.reload=function(e,t,a,n){if(a=!1!==a,E(e).config)return e=E(e),e.reload(t,a,n),o.call(e)},p.render=function(e){e=new t(e);return o.call(e)},e("treeTable",p)});layui.define("form",function(e){"use strict";var u=layui.$,i=layui.form,p=layui.layer,n="tree",a={config:{},index:layui[n]?layui[n].index+1e4:0,set:function(e){var i=this;return i.config=u.extend({},i.config,e),i},on:function(e,i){return layui.onevent.call(this,n,e,i)}},t=function(){var i=this,e=i.config,n=e.id||i.index;return t.that[n]=i,{config:t.config[n]=e,reload:function(e){i.reload.call(i,e)},getChecked:function(){return i.getChecked.call(i)},setChecked:function(e){return i.setChecked.call(i,e)}}},y="layui-hide",d="layui-disabled",f="layui-tree-set",C="layui-tree-iconClick",k="layui-icon-addition",v="layui-icon-subtraction",m="layui-tree-entry",x="layui-tree-main",b="layui-tree-txt",g="layui-tree-pack",w="layui-tree-spread",N="layui-tree-setLineShort",T="layui-tree-showLine",L="layui-tree-lineExtend",l=function(e){var i=this;i.index=++a.index,i.config=u.extend({},i.config,a.config,e),i.render()};l.prototype.config={data:[],showCheckbox:!1,showLine:!0,accordion:!1,onlyIconControl:!1,isJump:!1,edit:!1,text:{defaultNodeName:"\u672a\u547d\u540d",none:"\u65e0\u6570\u636e"}},l.prototype.reload=function(e){var n=this;layui.each(e,function(e,i){"array"===layui.type(i)&&delete n.config[e]}),n.config=u.extend(!0,{},n.config,e),n.render()},l.prototype.render=function(){var e=this,i=e.config,n=(e.checkids=[],u('
      ')),a=(e.tree(n),i.elem=u(i.elem));if(a[0]){if(e.key=i.id||e.index,e.elem=n,e.elemNone=u('
      '+i.text.none+"
      "),a.html(e.elem),0==e.elem.find(".layui-tree-set").length)return e.elem.append(e.elemNone);i.showCheckbox&&e.renderForm("checkbox"),e.elem.find(".layui-tree-set").each(function(){var e=u(this);e.parent(".layui-tree-pack")[0]||e.addClass("layui-tree-setHide"),!e.next()[0]&&e.parents(".layui-tree-pack").eq(1).hasClass("layui-tree-lineExtend")&&e.addClass(N),e.next()[0]||e.parents(".layui-tree-set").eq(0).next()[0]||e.addClass(N)}),e.events()}},l.prototype.renderForm=function(e){i.render(e,"LAY-tree-"+this.index)},l.prototype.tree=function(l,e){var r=this,c=r.config,e=e||c.data;layui.each(e,function(e,i){var n=i.children&&0"),t=u(['
      ','
      ','
      ',c.showLine?n?'':'':'',c.showCheckbox?'':"",c.isJump&&i.href?''+(i.title||i.label||c.text.defaultNodeName)+"":''+(i.title||i.label||c.text.defaultNodeName)+"","
      ",function(){if(!c.edit)return"";var n={add:'',update:'',del:''},a=['
      '];return!0===c.edit&&(c.edit=["update","del"]),"object"==typeof c.edit?(layui.each(c.edit,function(e,i){a.push(n[i]||"")}),a.join("")+"
      "):void 0}(),"
      "].join(""));n&&(t.append(a),r.tree(a,i.children)),l.append(t),t.prev("."+f)[0]&&t.prev().children(".layui-tree-pack").addClass("layui-tree-showLine"),n||t.parent(".layui-tree-pack").addClass("layui-tree-lineExtend"),r.spread(t,i),c.showCheckbox&&(i.checked&&r.checkids.push(i.id),r.checkClick(t,i)),c.edit&&r.operate(t,i)})},l.prototype.spread=function(a,e){var t=this.config,i=a.children("."+m),n=i.children("."+x),l=i.find("."+C),i=i.find("."+b),r=t.onlyIconControl?l:n,c="";r.on("click",function(e){var i=a.children("."+g),n=(r.children(".layui-icon")[0]?r:r.find(".layui-tree-icon")).children(".layui-icon");i[0]?a.hasClass(w)?(a.removeClass(w),i.slideUp(200),n.removeClass(v).addClass(k)):(a.addClass(w),i.slideDown(200),n.addClass(v).removeClass(k),t.accordion&&((i=a.siblings("."+f)).removeClass(w),i.children("."+g).slideUp(200),i.find(".layui-tree-icon").children(".layui-icon").removeClass(v).addClass(k))):c="normal"}),i.on("click",function(){u(this).hasClass(d)||(c=a.hasClass(w)?t.onlyIconControl?"open":"close":t.onlyIconControl?"close":"open",t.click&&t.click({elem:a,state:c,data:e}))})},l.prototype.setCheckbox=function(e,i,n){this.config;var t,l=n.prop("checked");n.prop("disabled")||("object"!=typeof i.children&&!e.find("."+g)[0]||e.find("."+g).find('input[same="layuiTreeCheck"]').each(function(){this.disabled||(this.checked=l)}),(t=function(e){var i,n,a;e.parents("."+f)[0]&&(n=(e=e.parent("."+g)).parent(),a=e.prev().find('input[same="layuiTreeCheck"]'),l?a.prop("checked",l):(e.find('input[same="layuiTreeCheck"]').each(function(){this.checked&&(i=!0)}),i||a.prop("checked",!1)),t(n))})(e),this.renderForm("checkbox"))},l.prototype.checkClick=function(n,a){var t=this,l=t.config;n.children("."+m).children("."+x).on("click",'input[same="layuiTreeCheck"]+',function(e){layui.stope(e);var e=u(this).prev(),i=e.prop("checked");e.prop("disabled")||(t.setCheckbox(n,a,e),l.oncheck&&l.oncheck({elem:n,checked:i,data:a}))})},l.prototype.operate=function(c,d){var s=this,o=s.config,e=c.children("."+m),h=e.children("."+x);e.children(".layui-tree-btnGroup").on("click",".layui-icon",function(e){layui.stope(e);var i,e=u(this).data("type"),a=c.children("."+g),t={data:d,type:e,elem:c};if("add"==e){a[0]||(o.showLine?(h.find("."+C).addClass("layui-tree-icon"),h.find("."+C).children(".layui-icon").addClass(k).removeClass("layui-icon-file")):h.find(".layui-tree-iconArrow").removeClass(y),c.append('
      '));var n,l=o.operate&&o.operate(t),r={};if(r.title=o.text.defaultNodeName,r.id=l,s.tree(c.children("."+g),[r]),o.showLine&&(a[0]?(a.hasClass(L)||a.addClass(L),c.find("."+g).each(function(){u(this).children("."+f).last().addClass(N)}),(a.children("."+f).last().prev().hasClass(N)?a.children("."+f).last().prev():a.children("."+f).last()).removeClass(N),!c.parent("."+g)[0]&&c.next()[0]&&a.children("."+f).last().removeClass(N)):(l=c.siblings("."+f),n=1,r=c.parent("."+g),layui.each(l,function(e,i){u(i).children("."+g)[0]||(n=0)}),1==n?(l.children("."+g).addClass(T),l.children("."+g).children("."+f).removeClass(N),c.children("."+g).addClass(T),r.removeClass(L),r.children("."+f).last().children("."+g).children("."+f).last().addClass(N)):c.children("."+g).children("."+f).addClass(N))),!o.showCheckbox)return;h.find('input[same="layuiTreeCheck"]')[0].checked&&(c.children("."+g).children("."+f).last().find('input[same="layuiTreeCheck"]')[0].checked=!0),s.renderForm("checkbox")}else"update"==e?(l=h.children("."+b).html(),h.children("."+b).html(""),h.append(''),h.children(".layui-tree-editInput").val(l).focus(),i=function(e){var i=(i=e.val().trim())||o.text.defaultNodeName;e.remove(),h.children("."+b).html(i),t.data.title=i,o.operate&&o.operate(t)},h.children(".layui-tree-editInput").blur(function(){i(u(this))}),h.children(".layui-tree-editInput").on("keydown",function(e){13===e.keyCode&&(e.preventDefault(),i(u(this)))})):p.confirm('\u786e\u8ba4\u5220\u9664\u8be5\u8282\u70b9 "'+(d.title||"")+'" \u5417\uff1f',function(e){if(o.operate&&o.operate(t),t.status="remove",p.close(e),!c.prev("."+f)[0]&&!c.next("."+f)[0]&&!c.parent("."+g)[0])return c.remove(),void s.elem.append(s.elemNone);var l,n,i;c.siblings("."+f).children("."+m)[0]?(o.showCheckbox&&(l=function(e){var i,n,a,t;e.parents("."+f)[0]&&(i=e.siblings("."+f).children("."+m),n=(e=e.parent("."+g).prev()).find('input[same="layuiTreeCheck"]')[0],a=1,(t=0)==n.checked&&(i.each(function(e,i){i=u(i).find('input[same="layuiTreeCheck"]')[0];0!=i.checked||i.disabled||(a=0),i.disabled||(t=1)}),1==a&&1==t&&(n.checked=!0,s.renderForm("checkbox"),l(e.parent("."+f)))))})(c),o.showLine&&(e=c.siblings("."+f),n=1,i=c.parent("."+g),layui.each(e,function(e,i){u(i).children("."+g)[0]||(n=0)}),1==n?(a[0]||(i.removeClass(L),e.children("."+g).addClass(T),e.children("."+g).children("."+f).removeClass(N)),(c.next()[0]?i.children("."+f).last():c.prev()).children("."+g).children("."+f).last().addClass(N),c.next()[0]||c.parents("."+f)[1]||c.parents("."+f).eq(0).next()[0]||c.prev("."+f).addClass(N)):!c.next()[0]&&c.hasClass(N)&&c.prev().addClass(N))):(e=c.parent("."+g).prev(),o.showLine?(e.find("."+C).removeClass("layui-tree-icon"),e.find("."+C).children(".layui-icon").removeClass(v).addClass("layui-icon-file"),(i=e.parents("."+g).eq(0)).addClass(L),i.children("."+f).each(function(){u(this).children("."+g).children("."+f).last().addClass(N)})):e.find(".layui-tree-iconArrow").addClass(y),c.parents("."+f).eq(0).removeClass(w),c.parent("."+g).remove()),c.remove()})})},l.prototype.events=function(){var i=this,t=i.config;i.elem.find(".layui-tree-checkedFirst");i.setChecked(i.checkids),i.elem.find(".layui-tree-search").on("keyup",function(){var e=u(this),n=e.val(),e=e.nextAll(),a=[];e.find("."+b).each(function(){var i,e=u(this).parents("."+m);-1!=u(this).html().indexOf(n)&&(a.push(u(this).parent()),(i=function(e){e.addClass("layui-tree-searchShow"),e.parent("."+g)[0]&&i(e.parent("."+g).parent("."+f))})(e.parent("."+f)))}),e.find("."+m).each(function(){var e=u(this).parent("."+f);e.hasClass("layui-tree-searchShow")||e.addClass(y)}),0==e.find(".layui-tree-searchShow").length&&i.elem.append(i.elemNone),t.onsearch&&t.onsearch({elem:a})}),i.elem.find(".layui-tree-search").on("keydown",function(){u(this).nextAll().find("."+m).each(function(){u(this).parent("."+f).removeClass("layui-tree-searchShow "+y)}),u(".layui-tree-emptyText")[0]&&u(".layui-tree-emptyText").remove()})},l.prototype.getChecked=function(){var e=this.config,i=[],n=[],t=(this.elem.find(".layui-form-checked").each(function(){i.push(u(this).prev()[0].value)}),function(e,a){layui.each(e,function(e,n){layui.each(i,function(e,i){if(n.id==i)return delete(i=u.extend({},n)).children,a.push(i),n.children&&(i.children=[],t(n.children,i.children)),!0})})});return t(u.extend({},e.data),n),n},l.prototype.setChecked=function(l){this.config;this.elem.find("."+f).each(function(e,i){var n=u(this).data("id"),a=u(i).children("."+m).find('input[same="layuiTreeCheck"]'),t=a.next();if("number"==typeof l){if(n.toString()==l.toString())return a[0].checked||t.click(),!1}else"object"==typeof l&&layui.each(l,function(e,i){if(i.toString()==n.toString()&&!a[0].checked)return t.click(),!0})})},t.that={},t.config={},a.reload=function(e,i){e=t.that[e];return e.reload(i),t.call(e)},a.getChecked=function(e){return t.that[e].getChecked()},a.setChecked=function(e,i){return t.that[e].setChecked(i)},a.render=function(e){e=new l(e);return t.call(e)},e(n,a)});layui.define(["laytpl","form"],function(e){"use strict";var d=layui.$,n=layui.laytpl,t=layui.form,a="transfer",i={config:{},index:layui[a]?layui[a].index+1e4:0,set:function(e){var t=this;return t.config=d.extend({},t.config,e),t},on:function(e,t){return layui.onevent.call(this,a,e,t)}},l=function(){var t=this,e=t.config,a=e.id||t.index;return l.that[a]=t,{config:l.config[a]=e,reload:function(e){t.reload.call(t,e)},getData:function(){return t.getData.call(t)}}},s="layui-hide",h="layui-btn-disabled",r="layui-none",c="layui-transfer-box",u="layui-transfer-header",o="layui-transfer-search",f="layui-transfer-data",y=function(e){return['
      ','
      ','","
      ","{{# if(d.data.showSearch){ }}",'","{{# } }}",'
        ',"
        "].join("")},p=['
        ',y({index:0,checkAllName:"layTransferLeftCheckAll"}),'
        ','",'","
        ",y({index:1,checkAllName:"layTransferRightCheckAll"}),"
        "].join(""),v=function(e){var t=this;t.index=++i.index,t.config=d.extend({},t.config,i.config,e),t.render()};v.prototype.config={title:["\u5217\u8868\u4e00","\u5217\u8868\u4e8c"],width:200,height:360,data:[],value:[],showSearch:!1,id:"",text:{none:"\u65e0\u6570\u636e",searchNone:"\u65e0\u5339\u914d\u6570\u636e"}},v.prototype.reload=function(e){var t=this;t.config=d.extend({},t.config,e),t.render()},v.prototype.render=function(){var e=this,t=e.config,a=e.elem=d(n(p,{open:"{{",close:"}}"}).render({data:t,index:e.index})),i=t.elem=d(t.elem);i[0]&&(t.data=t.data||[],t.value=t.value||[],t.id="id"in t?t.id:elem.attr("id")||e.index,e.key=t.id,i.html(e.elem),e.layBox=e.elem.find("."+c),e.layHeader=e.elem.find("."+u),e.laySearch=e.elem.find("."+o),e.layData=a.find("."+f),e.layBtn=a.find(".layui-transfer-active .layui-btn"),e.layBox.css({width:t.width,height:t.height}),e.layData.css({height:(i=t.height-e.layHeader.outerHeight(),t.showSearch&&(i-=e.laySearch.outerHeight()),i-2)}),e.renderData(),e.events())},v.prototype.renderData=function(){var e=this,i=(e.config,[{checkName:"layTransferLeftCheck",views:[]},{checkName:"layTransferRightCheck",views:[]}]);e.parseData(function(e){var t=e.selected?1:0,a=["
      • ",'',"
      • "].join("");i[t].views.push(a),delete e.selected}),e.layData.eq(0).html(i[0].views.join("")),e.layData.eq(1).html(i[1].views.join("")),e.renderCheckBtn()},v.prototype.renderForm=function(e){t.render(e,"LAY-transfer-"+this.index)},v.prototype.renderCheckBtn=function(r){var c=this,o=c.config;r=r||{},c.layBox.each(function(e){var t=d(this),a=t.find("."+f),t=t.find("."+u).find('input[type="checkbox"]'),i=a.find('input[type="checkbox"]'),n=0,l=!1;i.each(function(){var e=d(this).data("hide");(this.checked||this.disabled||e)&&n++,this.checked&&!e&&(l=!0)}),t.prop("checked",l&&n===i.length),c.layBtn.eq(e)[l?"removeClass":"addClass"](h),r.stopNone||(i=a.children("li:not(."+s+")").length,c.noneView(a,i?"":o.text.none))}),c.renderForm("checkbox")},v.prototype.noneView=function(e,t){var a=d('

        '+(t||"")+"

        ");e.find("."+r)[0]&&e.find("."+r).remove(),t.replace(/\s/g,"")&&e.append(a)},v.prototype.setValue=function(){var e=this.config,t=[];return this.layBox.eq(1).find("."+f+' input[type="checkbox"]').each(function(){d(this).data("hide")||t.push(this.value)}),e.value=t,this},v.prototype.parseData=function(t){var i=this.config,n=[];return layui.each(i.data,function(e,a){a=("function"==typeof i.parseData?i.parseData(a):a)||a,n.push(a=d.extend({},a)),layui.each(i.value,function(e,t){t==a.value&&(a.selected=!0)}),t&&t(a)}),i.data=n,this},v.prototype.getData=function(e){var t=this.config,i=[];return this.setValue(),layui.each(e||t.value,function(e,a){layui.each(t.data,function(e,t){delete t.selected,a==t.value&&i.push(t)})}),i},v.prototype.transfer=function(e,t){var a,i=this,n=i.config,l=i.layBox.eq(e),r=[],t=(t?((a=(t=t).find('input[type="checkbox"]'))[0].checked=!1,l.siblings("."+c).find("."+f).append(t.clone()),t.remove(),r.push(a[0].value),i.setValue()):l.each(function(e){d(this).find("."+f).children("li").each(function(){var e=d(this),t=e.find('input[type="checkbox"]'),a=t.data("hide");t[0].checked&&!a&&(t[0].checked=!1,l.siblings("."+c).find("."+f).append(e.clone()),e.remove(),r.push(t[0].value)),i.setValue()})}),i.renderCheckBtn(),l.siblings("."+c).find("."+o+" input"));""!==t.val()&&t.trigger("keyup"),n.onchange&&n.onchange(i.getData(r),e)},v.prototype.events=function(){var n=this,l=n.config;n.elem.on("click",'input[lay-filter="layTransferCheckbox"]+',function(){var e=d(this).prev(),t=e[0].checked,a=e.parents("."+c).eq(0).find("."+f);e[0].disabled||("all"===e.attr("lay-type")&&a.find('input[type="checkbox"]').each(function(){this.disabled||(this.checked=t)}),setTimeout(function(){n.renderCheckBtn({stopNone:!0})},0))}),n.elem.on("dblclick","."+f+">li",function(e){var t=d(this),a=t.children('input[type="checkbox"]'),i=t.parent().parent();a[0].disabled||n.transfer(i.data("index"),t)}),n.layBtn.on("click",function(){var e=d(this),t=e.data("index");e.hasClass(h)||n.transfer(t)}),n.laySearch.find("input").on("keyup",function(){var i=this.value,e=d(this).parents("."+o).eq(0).siblings("."+f),t=e.children("li"),t=(t.each(function(){var e=d(this),t=e.find('input[type="checkbox"]'),a=t[0].title,a=("cs"!==l.showSearch&&(a=a.toLowerCase(),i=i.toLowerCase()),-1!==a.indexOf(i));e[a?"removeClass":"addClass"](s),t.data("hide",!a)}),n.renderCheckBtn(),t.length===e.children("li."+s).length);n.noneView(e,t?l.text.searchNone:"")})},l.that={},l.config={},i.reload=function(e,t){e=l.that[e];return e.reload(t),l.call(e)},i.getData=function(e){return l.that[e].getData()},i.render=function(e){e=new v(e);return l.call(e)},e(a,i)});layui.define(["jquery","lay"],function(e){"use strict";var a=layui.$,t=layui.lay,o=(layui.hint(),layui.device(),{config:{},set:function(e){var i=this;return i.config=a.extend({},i.config,e),i},on:function(e,i){return layui.onevent.call(this,r,e,i)}}),r="carousel",d="layui-this",s="layui-carousel-left",u="layui-carousel-right",c="layui-carousel-prev",m="layui-carousel-next",l="layui-carousel-arrow",f="layui-carousel-ind",i=function(e){var i=this;i.config=a.extend({},i.config,o.config,e),i.render()};i.prototype.config={width:"600px",height:"280px",full:!1,arrow:"hover",indicator:"inside",autoplay:!0,interval:3e3,anim:"",trigger:"click",index:0},i.prototype.render=function(){var e=this,i=e.config,n=a(i.elem);if(1*[carousel-item]>*"),i.index<0&&(i.index=0),i.index>=e.elemItem.length&&(i.index=e.elemItem.length-1),i.interval<800&&(i.interval=800),i.full?i.elem.css({position:"fixed",width:"100%",height:"100%",zIndex:9999}):i.elem.css({width:i.width,height:i.height}),i.elem.attr("lay-anim",i.anim),e.elemItem.eq(i.index).addClass(d),e.elemItem.length<=1||(e.indicator(),e.arrow(),e.autoplay(),e.events()))},i.prototype.reload=function(e){var i=this;clearInterval(i.timer),i.config=a.extend({},i.config,e),i.render()},i.prototype.prevIndex=function(){var e=this.config.index-1;return e=e<0?this.elemItem.length-1:e},i.prototype.nextIndex=function(){var e=this.config.index+1;return e=e>=this.elemItem.length?0:e},i.prototype.addIndex=function(e){var i=this.config;i.index=i.index+(e=e||1),i.index>=this.elemItem.length&&(i.index=0)},i.prototype.subIndex=function(e){var i=this.config;i.index=i.index-(e=e||1),i.index<0&&(i.index=this.elemItem.length-1)},i.prototype.autoplay=function(){var e=this,i=e.config;i.autoplay&&(clearInterval(e.timer),e.timer=setInterval(function(){e.slide()},i.interval))},i.prototype.arrow=function(){var i=this,e=i.config,n=a(['",'"].join(""));e.elem.attr("lay-arrow",e.arrow),e.elem.find("."+l)[0]&&e.elem.find("."+l).remove(),e.elem.append(n),n.on("click",function(){var e=a(this).attr("lay-type");i.slide(e)})},i.prototype["goto"]=function(e){var i=this,n=i.config;e>n.index?i.slide("add",e-n.index):e
          ',(i=[],layui.each(e.elemItem,function(e){i.push("")}),i.join("")),"
        "].join(""));n.elem.attr("lay-indicator",n.indicator),n.elem.find("."+f)[0]&&n.elem.find("."+f).remove(),n.elem.append(t),"updown"===n.anim&&t.css("margin-top",-t.height()/2),t.find("li").on("hover"===n.trigger?"mouseover":n.trigger,function(){e["goto"](a(this).index())})},i.prototype.slide=function(e,i){var n=this,t=n.elemItem,a=n.config,o=a.index,l=a.elem.attr("lay-filter");n.haveSlide||("sub"===e?(n.subIndex(i),t.eq(a.index).addClass(c),setTimeout(function(){t.eq(o).addClass(u),t.eq(a.index).addClass(u)},50)):(n.addIndex(i),t.eq(a.index).addClass(m),setTimeout(function(){t.eq(o).addClass(s),t.eq(a.index).addClass(s)},50)),setTimeout(function(){t.removeClass(d+" "+c+" "+m+" "+s+" "+u),t.eq(a.index).addClass(d),n.haveSlide=!1},300),n.elemInd.find("li").eq(a.index).addClass(d).siblings().removeClass(d),n.haveSlide=!0,e={index:a.index,prevIndex:o,item:t.eq(a.index)},"function"==typeof a.change&&a.change(e),layui.event.call(this,r,"change("+l+")",e))},i.prototype.events=function(){var e=this,i=e.config;i.elem.data("haveEvents")||(i.elem.on("mouseenter",function(){"always"!==e.config.autoplay&&clearInterval(e.timer)}).on("mouseleave",function(){"always"!==e.config.autoplay&&e.autoplay()}),i.elem.data("haveEvents",!0))},o.render=function(e){return new i(e)},e(r,o)});layui.define(["jquery","lay"],function(e){"use strict";var s=layui.jquery,r=layui.lay,c={config:{},index:layui.rate?layui.rate.index+1e4:0,set:function(e){var a=this;return a.config=s.extend({},a.config,e),a},on:function(e,a){return layui.onevent.call(this,l,e,a)}},l="rate",f="layui-icon-rate",h="layui-icon-rate-solid",o="layui-icon-rate-half",u="layui-icon-rate-solid layui-icon-rate-half",v="layui-icon-rate layui-icon-rate-half",a=function(e){var a=this;a.index=++c.index,a.config=s.extend({},a.config,c.config,e),a.render()};a.prototype.config={length:5,text:!1,readonly:!1,half:!1,value:0,theme:""},a.prototype.render=function(){var e=this,a=e.config,l=s(a.elem);if(1a.length&&(a.value=a.length),parseInt(a.value)===a.value||a.half||(a.value=Math.ceil(a.value)-a.value<.5?Math.ceil(a.value):Math.floor(a.value)),'
          "),t=1;t<=a.length;t++){var o='
        • ";a.half&&parseInt(a.value)!==a.value&&t==Math.ceil(a.value)?n=n+'
        • ":n+=o}n+="
        "+(a.text?''+a.value+"\u661f":"")+"";var l=a.elem,u=l.next(".layui-rate");u[0]&&u.remove(),e.elemTemp=s(n),a.span=e.elemTemp.next("span"),a.setText&&a.setText(a.value),l.html(e.elemTemp),l.addClass("layui-inline"),a.readonly||e.action()},a.prototype.setvalue=function(e){this.config.value=e,this.render()},a.prototype.action=function(){var i=this.config,n=this.elemTemp,t=n.find("i").width();n.children("li").each(function(e){var a=e+1,l=s(this);l.on("click",function(e){i.value=a,i.half&&e.pageX-s(this).offset().left<=t/2&&(i.value=i.value-.5),i.text&&n.next("span").text(i.value+"\u661f"),i.choose&&i.choose(i.value),i.setText&&i.setText(i.value)}),l.on("mousemove",function(e){n.find("i").each(function(){s(this).addClass(f).removeClass(u)}),n.find("i:lt("+a+")").each(function(){s(this).addClass(h).removeClass(v)}),i.half&&e.pageX-s(this).offset().left<=t/2&&l.children("i").addClass(o).removeClass(h)}),l.on("mouseleave",function(){n.find("i").each(function(){s(this).addClass(f).removeClass(u)}),n.find("i:lt("+Math.floor(i.value)+")").each(function(){s(this).addClass(h).removeClass(v)}),i.half&&parseInt(i.value)!==i.value&&n.children("li:eq("+Math.floor(i.value)+")").children("i").addClass(o).removeClass("layui-icon-rate-solid layui-icon-rate")})})},a.prototype.events=function(){this.config},c.render=function(e){e=new a(e);return function(){var a=this;return{setvalue:function(e){a.setvalue.call(a,e)},config:a.config}}.call(e)},e(l,c)});layui.define("jquery",function(l){"use strict";var g=layui.$,e=function(l){};e.prototype.load=function(l){var t,i,n,e,r,o,a,c,m,s,u,f,y,d=this,p=0,h=g((l=l||{}).elem);if(h[0])return e=g(l.scrollElem||document),r=l.mb||50,o=!("isAuto"in l)||l.isAuto,a=l.end||"\u6ca1\u6709\u66f4\u591a\u4e86",c=l.scrollElem&&l.scrollElem!==document,m="\u52a0\u8f7d\u66f4\u591a",s=g('"),h.find(".layui-flow-more")[0]||h.append(s),u=function(l,e){l=g(l),s.before(l),(e=0==e||null)?s.html(a):s.find("a").html(m),i=e,t=null,y&&y()},f=function(){t=!0,s.find("a").html(''),"function"==typeof l.done&&l.done(++p,u)},f(),s.find("a").on("click",function(){g(this);i||t||f()}),l.isLazyimg&&(y=d.lazyimg({elem:l.elem+" img",scrollElem:l.scrollElem})),o&&e.on("scroll",function(){var e=g(this),o=e.scrollTop();n&&clearTimeout(n),!i&&h.width()&&(n=setTimeout(function(){var l=(c?e:g(window)).height();(c?e.prop("scrollHeight"):document.documentElement.scrollHeight)-o-l<=r&&(t||f())},100))}),d},e.prototype.lazyimg=function(l){var e,c=this,m=0,s=g((l=l||{}).scrollElem||document),u=l.elem||"img",f=l.scrollElem&&l.scrollElem!==document,y=function(e,l){var o,t=s.scrollTop(),l=t+l,i=f?e.offset().top-s.offset().top+t:e.offset().top;t<=i&&i<=l&&e.attr("lay-src")&&(o=e.attr("lay-src"),layui.img(o,function(){var l=c.lazyimg.elem.eq(m);e.attr("src",o).removeAttr("lay-src"),l[0]&&n(l),m++},function(){c.lazyimg.elem.eq(m);e.removeAttr("lay-src")}))},n=function(l,e){var o=(f?e||s:g(window)).height(),t=s.scrollTop(),i=t+o;if(c.lazyimg.elem=g(u),l)y(l,o);else for(var n=0;n"),preview:"Preview"}},I=function(e){return M.trim(e).replace(/^\n|\n$/,"")};e("code",function(e){var L=e=M.extend(!0,{},a,e);e.elem=M(e.elem),e.elem[0]&&layui.each(e.elem.get().reverse(),function(e,a){var i,l,t,s,o,n,d,c,r,u,E=M(a),y=M.extend(!0,{},L,lay.options(a),(i={},layui.each(["title","height","encode","skin","about"],function(e,a){var l=E.attr("lay-"+a);"string"==typeof l&&(i[a]=l)}),i)),v=E.data("code")||(l=[],E.children("textarea").each(function(){l.push(I(this.value))}),0===l.length&&l.push(I(E.html())),l),f=(E.data("code",v),y.preview&&(a="LAY-CODE-DF-"+e,t=y.layout||["code","preview"],s="iframe"===y.preview,h=M('
        '),u=M('
        '),o=M('
        '),n=M('
        '),d=M('
        '),m=E.parent("."+b.ELEM_PREVIEW),f=E.prev("."+b.ELEM_TAB),p=E.next("."+b.ELEM_ITEM+"-preview"),y.id&&h.attr("id",y.id),h.addClass(y.className),u.attr("lay-filter",a),layui.each(t,function(e,a){var l=M('
      • ');0===e&&l.addClass("layui-this"),l.html(y.text[a]),o.append(l)}),c={full:{className:"screen-full",title:["\u6700\u5927\u5316\u663e\u793a","\u8fd8\u539f\u663e\u793a"],event:function(e,a){var l=e.closest("."+b.ELEM_PREVIEW),i="layui-icon-"+this.className,t="layui-icon-screen-restore",s=this.title,o=M("html,body"),n="layui-scollbar-hide";e.hasClass(i)?(l.addClass(b.ELEM_FULL),e.removeClass(i).addClass(t),e.attr("title",s[1]),o.addClass(n)):(l.removeClass(b.ELEM_FULL),e.removeClass(t).addClass(i),e.attr("title",s[0]),o.removeClass(n))}},window:{className:"release",title:["\u5728\u65b0\u7a97\u53e3\u9884\u89c8"],event:function(e,a){_.openWin({content:v.join("")})}}},d.on("click",">i",function(){var e=M(this),a=e.data("type");"function"==typeof c[a].event&&c[a].event(e,a),"function"==typeof y.toolsEvent&&y.toolsEvent(e,a)}),layui.each(y.tools,function(e,a){var l=c[a]&&c[a].className||a,i=c[a].title||[""];d.append('')}),f[0]&&f.remove(),p[0]&&p.remove(),m[0]&&E.unwrap(),u.append(o),y.tools&&u.append(d),E.wrap(h).addClass(b.ELEM_ITEM).before(u),s&&n.html(""),r=function(e){var a=e.children("iframe")[0],l=(s&&a?a.srcdoc=v.join(""):e.html(v.join("")),{container:e,render:function(){C.render(e.find(".layui-form")),w.render()}});setTimeout(function(){"function"==typeof y.done&&y.done(l)},3)},"preview"===t[0]?(n.addClass(b.ELEM_SHOW),E.before(n),r(n)):E.addClass(b.ELEM_SHOW).after(n),y.codeStyle=[y.style,y.codeStyle].join(""),y.previewStyle=[y.style,y.previewStyle].join(""),n.attr("style",y.previewStyle),w.on("tab("+a+")",function(e){var a=M(this),l=M(e.elem).closest("."+b.ELEM_PREVIEW).find("."+b.ELEM_ITEM),e=l.eq(e.index);l.removeClass(b.ELEM_SHOW),e.addClass(b.ELEM_SHOW),"preview"===a.attr("lay-id")&&r(e)})),y.ln?"ol":"ul"),p=M("<"+f+' class="layui-code-'+f+'">'),m=M('
        '),h=(E.addClass("layui-code-view layui-box"),y.skin&&("notepad"===y.skin&&(y.skin="dark"),E.removeClass("layui-code-dark layui-code-light"),E.addClass("layui-code-"+y.skin)),_.escape(v.join(""))),h=(h=y.encode?_.escape(h):h).replace(/[\r\t\n]+/g,"
      • ");E.html(p.html("
      • "+h+"
      • ")),y.header&&!E.children("."+b.ELEM_TITLE)[0]&&(m.html(y.title+(y.about?'
        '+y.about+"
        ":"")),E.prepend(m)),y.elem.length===e+1&&"function"==typeof y.allDone&&y.allDone(),0<(u=Math.floor(p.find("li").length/100))&&p.css("margin-left",u+"px"),y.height&&p.css("max-height",y.height),p.attr("style",y.codeStyle)})})}),layui["layui.all"]||layui.addcss("modules/code.css?v=3","skincodecss"); \ No newline at end of file diff --git a/jun_springboot_starter/jun-onlineForm-spring-boot-starter/src/main/resources/static/online/form.html b/jun_springboot_starter/jun-onlineForm-spring-boot-starter/src/main/resources/static/online/form.html deleted file mode 100644 index e434acefb8..0000000000 --- a/jun_springboot_starter/jun-onlineForm-spring-boot-starter/src/main/resources/static/online/form.html +++ /dev/null @@ -1,491 +0,0 @@ - - - - - - 在线表单 - 数据管理 - - - - - -
        -
        -

        加载表单配置...

        - -
        - - -
        -
        -
        - -
        -
        -
        - - -
        -
        -
        -
        - - -
        - - -
        - - -
        -
        - - - - - - - - - - '; - - if ($('#dataTableBar').length === 0) { - $('body').append(toolbarHtml); - } - - // 监听行工具事件 - table.on('tool(dataTable)', function(obj) { - var data = obj.data; - if (obj.event === 'edit') { - openEditForm(data); - } else if (obj.event === 'del') { - deleteData([data.id]); - } - }); - } - - // 获取搜索参数 - function getSearchParams() { - var params = {page: 1, limit: 10}; - var formData = $('#searchForm').serializeArray(); - - $.each(formData, function(index, item) { - if (item.value) { - params[item.name] = item.value; - } - }); - - return params; - } - - // 搜索按钮事件 - $('#searchBtn').click(function() { - if (dataTable) { - dataTable.reload({ - where: getSearchParams(), - page: {curr: 1} - }); - } - }); - - // 重置搜索按钮事件 - $('#resetSearchBtn').click(function() { - $('#searchForm')[0].reset(); - form.render(); - }); - - // 添加按钮事件 - $('#addBtn').click(function() { - openEditForm(null); - }); - - // 删除按钮事件 - $('#deleteBtn').click(function() { - var checkStatus = table.checkStatus('dataTable'); - var data = checkStatus.data; - - if (data.length === 0) { - layer.msg('请选择要删除的数据', {icon: 5}); - return; - } - - var ids = []; - $.each(data, function(index, item) { - ids.push(item.id); - }); - - deleteData(ids); - }); - - // 打开编辑表单 - function openEditForm(data) { - if (!formConfig || !formConfig.formFields) return; - - var html = ''; - - $.each(formConfig.formFields, function(index, field) { - var inputHtml = ''; - switch (field.formInput) { - case 'text': - case 'input': - inputHtml = ''; - break; - case 'select': - inputHtml = ''; - break; - case 'checkbox': - inputHtml = ''; - if (field.dictOptions) { - var checkedValues = data && data[field.name] ? (Array.isArray(data[field.name]) ? data[field.name] : [data[field.name]]) : []; - $.each(field.dictOptions, function(key, value) { - var checked = checkedValues.indexOf(key) !== -1 ? 'checked' : ''; - inputHtml += ''; - }); - } - break; - case 'radio': - inputHtml = ''; - if (field.dictOptions) { - var checkedValue = data && data[field.name] ? data[field.name] : ''; - $.each(field.dictOptions, function(key, value) { - var checked = checkedValue === key ? 'checked' : ''; - inputHtml += ''; - }); - } - break; - default: - inputHtml = ''; - } - - var required = field.formRequired ? 'lay-verify="required"' : ''; - - html += '
        \n' + - ' \n' + - '
        \n' + - ' ' + inputHtml + '\n' + - '
        \n' + - '
        '; - }); - - // 添加隐藏字段存储ID(编辑时) - if (data && data.id) { - html += ''; - } - - $('#editForm').html(html); - form.render(); - - layer.open({ - type: 1, - title: data ? '编辑数据' : '添加数据', - content: $('#editFormDiv'), - area: ['600px', 'auto'], - btn: ['保存', '取消'], - yes: function(index, layero) { - form.on('submit(submitForm)', function(data) { - saveData(data.field, function() { - layer.close(index); - if (dataTable) { - dataTable.reload(); - } - }); - return false; - }); - $('#editForm').submit(); - } - }); - } - - // 保存数据 - function saveData(params, callback) { - var url = '/sys/online/form/' + tableId; - var method = params.id ? 'PUT' : 'POST'; - - $.ajax({ - url: url, - type: method, - data: JSON.stringify(params), - contentType: 'application/json', - success: function(res) { - if (res.code === 0) { - layer.msg(params.id ? '更新成功' : '添加成功', {icon: 6}); - if (callback) callback(); - } else { - layer.msg('操作失败:' + res.msg, {icon: 5}); - } - }, - error: function() { - layer.msg('网络错误,请检查接口连接', {icon: 5}); - } - }); - } - - // 删除数据 - function deleteData(ids) { - layer.confirm('确定要删除选中的数据吗?', { - icon: 3, - title: '确认删除' - }, function(index) { - $.ajax({ - url: '/sys/online/form/' + tableId, - type: 'DELETE', - data: JSON.stringify(ids), - contentType: 'application/json', - success: function(res) { - if (res.code === 0) { - layer.msg('删除成功', {icon: 6}); - if (dataTable) { - dataTable.reload(); - } - } else { - layer.msg('删除失败:' + res.msg, {icon: 5}); - } - }, - error: function() { - layer.msg('网络错误,请检查接口连接', {icon: 5}); - } - }); - layer.close(index); - }); - } - - // 返回按钮事件 - $('#backBtn').click(function() { - window.location.href = 'index.html'; - }); - - // 初始加载 - loadFormConfig(); - - // 监听表单提交事件 - form.on('submit(submitForm)', function(data) { - saveData(data.field, function() { - layer.closeAll('page'); - if (dataTable) { - dataTable.reload(); - } - }); - return false; - }); - }); - - - \ No newline at end of file diff --git a/jun_springboot_starter/jun-onlineForm-spring-boot-starter/src/main/resources/static/online/index.html b/jun_springboot_starter/jun-onlineForm-spring-boot-starter/src/main/resources/static/online/index.html deleted file mode 100644 index 65cc207d25..0000000000 --- a/jun_springboot_starter/jun-onlineForm-spring-boot-starter/src/main/resources/static/online/index.html +++ /dev/null @@ -1,149 +0,0 @@ - - - - - - 在线表单开发工具 - - - - - -
        -

        在线表单开发工具

        - -
        - - -
        - -
        -
        正在加载数据表...
        -
        -
        - - - - - - - - - \ No newline at end of file diff --git a/jun_springboot_starter/jun-onlineForm-spring-boot-starter/src/main/resources/static/online/test.html b/jun_springboot_starter/jun-onlineForm-spring-boot-starter/src/main/resources/static/online/test.html deleted file mode 100644 index 71b039714f..0000000000 --- a/jun_springboot_starter/jun-onlineForm-spring-boot-starter/src/main/resources/static/online/test.html +++ /dev/null @@ -1,285 +0,0 @@ - - - - - - 在线表单测试页面 - - - - - -
        -
        - -
        -
        -
        -
        -
        表单配置测试
        -
        -
        -
        - -
        - -
        -
        -
        -
        - -
        -
        -
        -
        -
        - - -
        -
        -
        - - '); - } - } - }); - - - \ No newline at end of file diff --git a/jun_springboot_starter/jun-onlineForm-spring-boot-starter/src/main/resources/templates/biztest/list.html b/jun_springboot_starter/jun-onlineForm-spring-boot-starter/src/main/resources/templates/biztest/list.html deleted file mode 100644 index 8339baa845..0000000000 --- a/jun_springboot_starter/jun-onlineForm-spring-boot-starter/src/main/resources/templates/biztest/list.html +++ /dev/null @@ -1,300 +0,0 @@ - - - - - Title - - - - - - -
        -
        -
        -
        - -
        - -
        - - -
        -
        - -
        -
        -
        - - - - - - - - \ No newline at end of file diff --git a/jun_springboot_starter/jun-oss-spring-boot-starter/pom.xml b/jun_springboot_starter/jun-oss-spring-boot-starter/pom.xml deleted file mode 100644 index 0d1db45b4d..0000000000 --- a/jun_springboot_starter/jun-oss-spring-boot-starter/pom.xml +++ /dev/null @@ -1,184 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun-oss-spring-boot-starter - 1.0.25 - jar - 对象存储通用组件 - - - 1.8 - UTF-8 - 1.8 - 1.8 - 1.0.25 - 2.5.14 - 2020.0.6 - 3.5.7 - 2.3.2 - - - - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - - - - - com.github.tobato - fastdfs-client - true - - - - com.amazonaws - aws-java-sdk-s3 - true - - - org.springframework - spring-web - - - - org.springframework.boot - spring-boot-configuration-processor - true - - - - - io.github.wujun728 - jun-common-base - ${jun.version} - - - io.github.wujun728 - jun-swagger2-spring-boot-starter - ${jun.version} - - - - - com.tencentcloudapi - tencentcloud-sdk-java-common - 3.1.838 - - - com.qiniu - qiniu-java-sdk - [7.7.0, 7.7.99] - - - - - - com.qiniu - happy-dns-java - 0.1.6 - test - - - junit - junit - 4.12 - test - - - - com.aliyun.oss - aliyun-sdk-oss - 3.17.1 - - - com.qcloud - cos_api - 4.4 - - - org.slf4j - slf4j-log4j12 - - - junit - junit - - - - - com.google.zxing - javase - 3.2.1 - - - com.deepoove - poi-tl - 1.9.1 - - - - com.alibaba - easyexcel - 3.0.5 - - - org.springframework.boot - spring-boot-starter-freemarker - - - - org.springframework.boot - spring-boot-configuration-processor - - - - com.baomidou - mybatis-plus-boot-starter - - - org.apache.tomcat.embed - tomcat-embed-core - - - net.dreamlu - mica-auto - - - commons-fileupload - commons-fileupload - 1.5 - compile - - - diff --git a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/config/FileAutoConfig.java b/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/config/FileAutoConfig.java deleted file mode 100644 index 87ead1a9ca..0000000000 --- a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/config/FileAutoConfig.java +++ /dev/null @@ -1,15 +0,0 @@ -package io.github.wujun728.file.config; - -import org.mybatis.spring.annotation.MapperScan; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -/** - * @author wujun - * @date 2021/3/19 - */ -@Configuration -@ComponentScan(basePackages = "io.github.wujun728.file") -@MapperScan(basePackages = "io.github.wujun728.file.mapper") -public class FileAutoConfig { -} diff --git a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/config/FileProperties.java b/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/config/FileProperties.java deleted file mode 100644 index 5f94c4c5f8..0000000000 --- a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/config/FileProperties.java +++ /dev/null @@ -1,55 +0,0 @@ -package io.github.wujun728.file.config; - -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Primary; -import org.springframework.stereotype.Component; -import org.springframework.util.StringUtils; - -/** - * 文件上传参数配置类 - * - * @author wujun - * @version V1.0 - * @date 2020年3月18日 - */ -@Primary -@Component -@Data -@ConfigurationProperties(prefix = "file") -public class FileProperties { - - - - private String path; - private String url; - private String accessUrl; - - private String qiniuAccessKey; - private String qiniuBucketName; - private String qiniuDomain; - private String qiniuPrefix; - private String qiniuSecretKey; - private String type; - - - - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - - this.url = url; - - //set accessUrl - if (StringUtils.isEmpty(url)) { - this.accessUrl = null; - } - this.accessUrl = url.substring(url.lastIndexOf("/")) + "/**"; - System.out.println("accessUrl=" + accessUrl); - } - - -} \ No newline at end of file diff --git a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/config/ResourcesConfig.java b/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/config/ResourcesConfig.java deleted file mode 100644 index acf382bc7e..0000000000 --- a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/config/ResourcesConfig.java +++ /dev/null @@ -1,63 +0,0 @@ -//package io.github.wujun728.file.config; -// -//import io.github.wujun728.common.constant.Constants; -//import io.github.wujun728.file.common.comfig.FileUploadProperties; -//import lombok.extern.slf4j.Slf4j; -//import org.springframework.context.annotation.Configuration; -//import org.springframework.web.servlet.config.annotation.*; -// -//import javax.annotation.Resource; -// -///** -// * 通用配置 -// * -// */ -//@Slf4j -//@Configuration -////@EnableConfigurationProperties(FileUploadProperties.class) -//public class ResourcesConfig implements WebMvcConfigurer { -// -// @Resource -// private FileUploadProperties fileUploadProperties; -// -// @Override -// public void addCorsMappings(CorsRegistry registry) { -// WebMvcConfigurer.super.addCorsMappings(registry); -// registry.addMapping("/**").allowedHeaders("*").allowedMethods("POST", "GET", "PUT", "DELETE") -// .allowedOrigins("*"); -// } -// -// /** -// * 默认首页的设置,当输入域名是可以自动跳转到默认指定的网页 -// */ -// @Override -// public void addViewControllers(ViewControllerRegistry registry) { -//// registry.addViewController("/").setViewName("forward:" + indexUrl); -// registry.addViewController("/").setViewName("forward:" + "login.html"); -// } -// -// /** -// * 发现如果继承了WebMvcConfigurationSupport,则在yml中配置的相关内容会失效。 需要重新指定静态资源 -// */ -// -// -// /** -// * @description: 访问静态文件 -// * @date: 2021/4/15 -// */ -// @Override -// public void addResourceHandlers(ResourceHandlerRegistry registry) { -// /** 本地文件上传路径 */ -// registry.addResourceHandler("/files/**").addResourceLocations("file:" + fileUploadProperties.getPath() + "/"); -// -// /** 文件下载映射配置,同下 */ -// registry.addResourceHandler(fileUploadProperties.getAccessUrl()).addResourceLocations("file:" + fileUploadProperties.getPath()); -// -// log.debug("System.getProperty(\"user.dir\")"); -// // 访问路径 -// registry.addResourceHandler("/api/upload/**") -// // 映射真实路径 -// .addResourceLocations("file:" + System.getProperty("user.dir") + "/");// 必须加"/",不然映射不到 -// } -// -//} diff --git a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/controller/FileControl.java b/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/controller/FileControl.java deleted file mode 100644 index 3f56a8e86a..0000000000 --- a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/controller/FileControl.java +++ /dev/null @@ -1,129 +0,0 @@ -package io.github.wujun728.file.controller; - - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import io.github.wujun728.file.service.FileService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; - -import com.alibaba.fastjson2.JSON; -import com.alibaba.fastjson2.JSONObject; -import com.google.zxing.BarcodeFormat; -import com.google.zxing.EncodeHintType; -import com.google.zxing.MultiFormatWriter; -import com.google.zxing.WriterException; -import com.google.zxing.client.j2se.MatrixToImageWriter; -import com.google.zxing.common.BitMatrix; -import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; - -@Controller -@RequestMapping(value = "/file") -public class FileControl { - @Autowired - private FileService fileService; - - @RequestMapping(value = "/Login") - public String index() { - return "login"; - } - - //http://localhost:8080/public//Qrcode?url=baidu.com&name=wujun - @RequestMapping(value = "/Qrcode") - public void test(HttpServletResponse response,HttpServletRequest request) throws IOException, WriterException { - //生成二维码 - int width = 150; - int height = 150; - String url = request.getParameter("url"); - String name = request.getParameter("name"); - System.out.println(url+"&name="+name); - String format = "png"; - String content = url+"&name="+name; - ServletOutputStream out = response.getOutputStream(); - Map config = new HashMap<>(); - config.put(EncodeHintType.CHARACTER_SET,"UTF-8"); - config.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); - config.put(EncodeHintType.MARGIN, 0); - BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE,width,height,config); - MatrixToImageWriter.writeToStream(bitMatrix,format,out); - System.out.println("二维码生成完毕,已经输出到页面中。"); - } - -// @RequestMapping(value = "/register") -// @ResponseBody -// public String register(HttpServletRequest request) { -//// 获取账号密码 -// String name = request.getParameter("name"); -// String pass = request.getParameter("pass"); -// //创建一个用户对象 -// User user = new User(name, pass); -// String s = registerService.addOne(user); -// return s; -// } - -// @RequestMapping(value = "/login") -// @ResponseBody -// public String login(HttpServletRequest request) { -// // 获取账号密码 -// String name = request.getParameter("name"); -// String pass = request.getParameter("pass"); -// User user = new User(name, pass); -// String s = loginService.loginService(user); -// return s; -// } - - - //文件上传 - @RequestMapping(value = "/upload") - @ResponseBody - public String upload(HttpServletRequest request, HttpServletResponse response) { - String s = fileService.uploadFile(request); - HashMap map = new HashMap<>(); - map.put("result", s); - //转为json - JSONObject jsonObject = new JSONObject(map); - String res = jsonObject.toString(); - return res; - } - - //文件列表 - @RequestMapping(value = "/filedir") - @ResponseBody - public JSONObject filedir(HttpServletRequest request) { - String res = fileService.fileList(request); - JSONObject jsonObject = JSON.parseObject(res); - jsonObject.remove("message"); - return jsonObject; - } - @RequestMapping(value = "/filelist") - @ResponseBody - public JSONObject filelist(HttpServletRequest request) { - String res = fileService.fileList(request); - JSONObject jsonObject = JSON.parseObject(res); - jsonObject.remove("message"); - return jsonObject; - } -// 文件下载 - @RequestMapping(value = "/filedown") - public void filedown(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException { - fileService.fileDown(request, response); - } - //文件删除 - @RequestMapping(value = "/filedel") - @ResponseBody - public String filedel(HttpServletRequest request,HttpServletResponse response){ - String msg = ""; - msg = fileService.fileDel(request,response); - return msg; - - } -} diff --git a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/controller/QiniuController.java b/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/controller/QiniuController.java deleted file mode 100644 index 4869629810..0000000000 --- a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/controller/QiniuController.java +++ /dev/null @@ -1,71 +0,0 @@ -package io.github.wujun728.file.controller; - -import java.io.File; - -import javax.security.auth.message.AuthException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import io.github.wujun728.file.utils.FileUtils; -import io.github.wujun728.file.utils.QiniuUtils; -import io.github.wujun728.file.utils.ExecuteResult; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Controller; -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.ResponseBody; -import org.springframework.web.multipart.MultipartFile; - -@Controller -@RequestMapping(value = "") -public class QiniuController { - - private static Logger logger = LoggerFactory.getLogger(QiniuController.class); - - - @RequestMapping("qiniuCommon") - private String qiniuCommon(HttpServletRequest request){ - return "qiniuCommon"; - } - - - /** - * @param request - * @param multipartFile - * @return - */ - @RequestMapping(value = "/qiniuUpload", method = RequestMethod.POST) - @ResponseBody - public String qiniuUpload(HttpServletRequest request, HttpServletResponse response, @RequestParam("imagefile") MultipartFile multipartFile) { - ExecuteResult executeResult = new ExecuteResult(); - - QiniuUtils QiniuUtils = new QiniuUtils(); - try { - /** - * 上传文件扩展名 - */ - String filenameExtension = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."), multipartFile.getOriginalFilename().length()); - - /** - * MultipartFile 转 file 类型 - */ - File file = FileUtils.multipartToFile(multipartFile); - - /** - * 七牛云文件上传 服务 file文件 以及 文件扩展名 - */ - executeResult = QiniuUtils.uploadFile2(file, filenameExtension); - if (!executeResult.isSuccess()) { - return "失败" + executeResult.getErrorMessages(); - } - - } catch (AuthException e) { - logger.error("AuthException", e); - } - - return executeResult.getResult(); - } - -} diff --git a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/controller/SysFilesController.java b/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/controller/SysFilesController.java deleted file mode 100644 index f7fabc00aa..0000000000 --- a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/controller/SysFilesController.java +++ /dev/null @@ -1,279 +0,0 @@ -package io.github.wujun728.file.controller; - -import com.alibaba.fastjson2.JSON; -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.baomidou.mybatisplus.core.metadata.IPage; -import com.baomidou.mybatisplus.core.toolkit.Wrappers; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.deepoove.poi.XWPFTemplate; -import com.deepoove.poi.data.PictureRenderData; -import io.github.wujun728.common.base.Result; -import io.github.wujun728.file.config.FileProperties; -import io.github.wujun728.file.utils.FileUtils; -import io.github.wujun728.file.entity.SysFilesEntity; -import io.github.wujun728.file.service.SysFilesService; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import lombok.extern.slf4j.Slf4j; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.io.DefaultResourceLoader; -import org.springframework.core.io.ResourceLoader; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.multipart.MultipartFile; - -import javax.annotation.Resource; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * 文件上传 - * - * @author wujun - * @version V1.0 - * @date 2020年3月18日 - */ -@RestController -@RequestMapping("/sysFiles") -@Api(tags = "文件管理") -@Slf4j -public class SysFilesController { - @Resource - private SysFilesService sysFilesService; - - - @Autowired - FileProperties fileUploadProperties; - - @ApiOperation(value = "新增") - @PostMapping("/upload") - //@RequiresPermissions(value = { "sysFiles:add", "sysContent:update", "sysContent:add" }, logical = Logical.OR) - public Result add(@RequestParam(value = "file") MultipartFile file, @RequestParam(value = "bizid",required = false) String bizid, - @RequestParam(value = "biztype",required = false) String biztype) { - log.info(biztype); - log.info(bizid); - // 判断文件是否空 - if (file == null || file.getOriginalFilename() == null - || "".equalsIgnoreCase(file.getOriginalFilename().trim())) { - return Result.fail("文件为空"); - } - return sysFilesService.saveFile(file, biztype, bizid); - } - - @ApiOperation(value = "删除") - @DeleteMapping("/delete") - //@RequiresPermissions("sysFiles:delete") - public Result delete(@RequestBody @ApiParam(value = "id集合") List ids) { - sysFilesService.removeByIdsAndFiles(ids); - return Result.success(); - } - -// @ApiOperation(value = "查询分页数据") -// @PostMapping("/listByPage") -// //@RequiresPermissions("sysFiles:list") -// public Result findListByPage(@RequestBody SysFilesEntity sysFiles) { -// Page page = new Page(sysFiles.getPage(), sysFiles.getLimit()); -// IPage iPage = sysFilesService.page(page, -// Wrappers.lambdaQuery().orderByDesc(SysFilesEntity::getCreateDate)); -// return Result.success(iPage); -// } - -// @SuppressWarnings({ "rawtypes", "unchecked" }) -// @ApiOperation(value = "查询分页数据") -// @PostMapping("/listByPageUser") -// //@RequiresPermissions("sysFiles:list") -// public Result listByPageUser(@RequestBody SysFilesEntity sysFiles) { -// Page page = new Page(sysFiles.getPage(), sysFiles.getLimit()); -// IPage iPage = sysFilesService.page(page, -// Wrappers.lambdaQuery() -// .eq(SysFilesEntity::getRefBizid, sysFiles.getRefBizid()) -// .eq(SysFilesEntity::getDictBiztype, sysFiles.getDictBiztype()) -// .orderByDesc(SysFilesEntity::getCreateDate)); -// return Result.success(iPage); -// } - - - - - @ApiOperation(value = "生成简历") - @PostMapping("/genResume") -// @RequiresPermissions(value = { "sysFiles:add", "sysContent:update", "sysContent:add" }, logical = Logical.OR) - public Result genResume(@RequestParam(value = "bizid",required = false) String bizid, - @RequestParam(value = "username",required = false) String username, - @RequestParam(value = "realName",required = false) String realName, - @RequestParam(value = "deptName",required = false) String deptName, - @RequestParam(value = "biztype",required = false) String biztype) throws IOException { - Map resume = new HashMap<>(); - Map data = new HashMap<>(); - ResourceLoader resourceLoader = new DefaultResourceLoader(); - org.springframework.core.io.Resource resource1 = resourceLoader.getResource("classpath:files/"+"logo_resume.jpg"); - data.put("pictures", new PictureRenderData(100, 120, resource1.getFile().getAbsolutePath())); - //SysUser user = userMapper.getUserByName(username); - Map m = null;//JSON.parseObject(JSON.toJSONString(user), Map.class); - data.putAll(m); - List> list11=new ArrayList<>(); - System.err.println(JSON.toJSON(data)); - list11.add(data); - resume.put("resume",list11); - org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:files/"+"简历模板2.docx"); - InputStream inputStream =resource.getInputStream() ; - XWPFTemplate template = XWPFTemplate.compile(inputStream).render( resume); - String newFile = fileUploadProperties.getPath()+realName+"简历"+username+".docx"; - File file = new File(newFile); - FileUtils.createFile(file); - template.writeAndClose(new FileOutputStream(newFile)); - log.info(bizid); - // 判断文件是否空 - if (file == null) { - return Result.fail("文件为空"); - } - return sysFilesService.saveFile(file, biztype, bizid); - } - - - - @SuppressWarnings("unchecked") - @ApiOperation(value = "查询分页数据") - @PostMapping("/listByPage") -// @RequiresPermissions("sysFiles:list") - public Result findListByPage(@RequestBody SysFilesEntity sysFiles) { - Page page = new Page(sysFiles.getPage(), sysFiles.getLimit()); - IPage iPage = sysFilesService.page(page, - Wrappers.lambdaQuery().orderByDesc(SysFilesEntity::getCreateDate)); - List records = iPage.getRecords(); - String userid = "sessionService.getCurrentUsername()"; - records.forEach(item -> { - if(userid.equalsIgnoreCase(item.getCreator())) { - item.setIsOwner(1); - } - }); - return Result.success(iPage); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @ApiOperation(value = "查询分页数据") - @PostMapping("/listByPageUser") -// @RequiresPermissions("sysFiles:list") - public Result listByPageUser(@RequestBody SysFilesEntity sysFiles) { - Page page = new Page(sysFiles.getPage(), sysFiles.getLimit()); - IPage iPage = sysFilesService.page(page, - Wrappers.lambdaQuery() - .eq(SysFilesEntity::getRefBizid, sysFiles.getRefBizid()) -// .eq(SysFilesEntity::getDictBiztype, sysFiles.getDictBiztype()) - .orderByDesc(SysFilesEntity::getCreateDate)); - List records = iPage.getRecords(); - String userid = "sessionService.getCurrentUsername()"; - records.forEach(item -> { - if(userid.equalsIgnoreCase(item.getCreator())) { - item.setIsOwner(1); - } - }); - return Result.success(iPage); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @ApiOperation(value = "查询分页数据") - @PostMapping("/listByPageUserProjectID") - public Result listByPageUserProjectID(@RequestBody SysFilesEntity sysFiles) { - String pid = sysFiles.getRefBizid(); - Page page = new Page(sysFiles.getPage(), sysFiles.getLimit()); - String tmpSQL = getProjectFilesRefIDS(pid); - IPage iPage = sysFilesService.page(page, - Wrappers.lambdaQuery() -// .eq(SysFilesEntity::getRefBizid, sysFiles.getRefBizid()) - .inSql(true, SysFilesEntity::getRefBizid, tmpSQL ) -// .eq(SysFilesEntity::getRefBizid, sysFiles.getRefBizid()) - .orderByDesc(SysFilesEntity::getCreateDate)); - List records = iPage.getRecords(); - String userid = "sessionService.getCurrentUsername()"; - records.forEach(item -> { - if(userid.equalsIgnoreCase(item.getCreator())) { - item.setIsOwner(1); - } - }); - return Result.success(iPage); - } - - @ApiOperation(value = "查询userLogo") - @PostMapping("/getImgByBizid") - public Result getImgByBizid(@RequestBody SysFilesEntity sysFiles) { - LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); - queryWrapper.eq(SysFilesEntity::getDictBiztype,sysFiles.getDictBiztype()); - queryWrapper.eq(SysFilesEntity::getRefBizid,sysFiles.getRefBizid()); - queryWrapper.orderByDesc(SysFilesEntity::getCreateDate); - queryWrapper.last(" limit 1 "); - List list = sysFilesService.list(queryWrapper); - String userid = "sessionService.getCurrentUsername()"; - if(list.size()>0){ - return Result.success(list.get(0)); - }else{ - return Result.success(); - } - } - - - private String getProjectFilesRefIDS(String pid) { - String tmpSQL = " select pjc.id -- ,pjc.*\r\n" - + " from pj_project t\r\n" - + " left join pj_contract pjc on t.project_code=pjc.refid_project_code_hide\r\n" - + " where t.id='"+pid+"' \r\n" - + "\r\n union SELECT '"+pid+"' from pj_project" - + " union \r\n" - + " select pjp.id -- ,pjp.*\r\n" - + " from pj_project t\r\n" - + " left join pj_project_plan pjp on t.project_code=pjp.ref_project_code\r\n" - + " where t.id='"+pid+"' \r\n" - + "\r\n" - + " union \r\n" - + " select pjd.id -- ,pjd.*\r\n" - + " from pj_project t\r\n" - + " left join pj_project_draft pjd on t.project_code=pjd.ref_project_code\r\n" - + " where t.id='"+pid+"' \r\n" - + "\r\n" - + " union \r\n" - + " select pjr.id -- ,pjr.*\r\n" - + " from pj_project t\r\n" - + " left join pj_project_recheck pjr on t.project_code=pjr.ref_pcode\r\n" - + " where t.id='"+pid+"' \r\n" - + " union \r\n" - + " select pja.id -- ,pja.*\r\n" - + " from pj_project t\r\n" - + " left join pj_project_appraise pja on t.project_code=pja.ref_project_code\r\n" - + " where t.id='"+pid+"' \r\n" - + " union \r\n" - + " select pji.id -- ,pji.*\r\n" - + " from pj_project t\r\n" - + " left join pj_project_invoice pji on t.project_code=pji.ref_project_code\r\n" - + " where t.id='"+pid+"' \r\n" - + " union \r\n" - + " select pjm.id -- ,pjm.*\r\n" - + " from pj_project t\r\n" - + " left join pj_project_member pjm on t.project_code=pjm.ref_project_code\r\n" - + " where t.id='"+pid+"' \r\n" - + " union \r\n" - + " select pjt.id -- ,pjt.*\r\n" - + " from pj_project t\r\n" - + " left join pj_project_prodess_task pjt on t.project_code=pjt.ref_project_code\r\n" - + " where t.id='"+pid+"' \r\n" - + " union \r\n" - + " select pjr1.id -- ,pjr1.*\r\n" - + " from pj_project t\r\n" - + " left join pj_project_report pjr1 on t.project_code=pjr1.ref_project_code\r\n" - + " where t.id='"+pid+"' \r\n" - + " union \r\n" - + " select pjrn.id -- ,pjrn.*\r\n" - + " from pj_project t\r\n" - + " left join pj_project_reportnumber pjrn on t.project_code=pjrn.ref_reportnumber_code\r\n" - + " where t.id='"+pid+"' "; - return tmpSQL; - } - -} diff --git a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/entity/SysFilesEntity.java b/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/entity/SysFilesEntity.java deleted file mode 100644 index 35e09a246f..0000000000 --- a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/entity/SysFilesEntity.java +++ /dev/null @@ -1,71 +0,0 @@ -package io.github.wujun728.file.entity; - -import com.baomidou.mybatisplus.annotation.FieldFill; -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableId; -import com.baomidou.mybatisplus.annotation.TableName; -import com.fasterxml.jackson.annotation.JsonFormat; - -import io.github.wujun728.common.base.BaseEntity; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.io.Serializable; -import java.util.Date; - -/** - * 文件上传 - * - * @author wujun - * @version V1.0 - * @date 2020年3月18日 - */ -@EqualsAndHashCode(callSuper = true) -@Data -@TableName("sys_files") -public class SysFilesEntity extends BaseEntity implements Serializable { - private static final long serialVersionUID = 1L; - - /** - * 主键 - */ - @TableId("id") - private String id; - - /** - * URL地址 - */ - @TableField("url") - private String url; - - /** - * 创建时间 - */ - @TableField(value = "create_date", fill = FieldFill.INSERT) - @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") - private Date createDate; - - @TableField("file_name") - private String fileName; - - @TableField("file_path") - private String filePath; - - @TableField("dict_biztype") - private String dictBiztype; - - @TableField("ref_bizid") - private String refBizid; - - /** - * 创建人 - */ - @TableField(value = "creator", fill = FieldFill.INSERT) - private String creator; - - @TableField("file_size") - private String fileSize; - - - -} diff --git a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/mapper/SysFilesMapper.java b/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/mapper/SysFilesMapper.java deleted file mode 100644 index 1ff0880b91..0000000000 --- a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/mapper/SysFilesMapper.java +++ /dev/null @@ -1,15 +0,0 @@ -package io.github.wujun728.file.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import io.github.wujun728.file.entity.SysFilesEntity; - -/** - * 文件上传 Mapper - * - * @author wujun - * @version V1.0 - * @date 2020年3月18日 - */ -public interface SysFilesMapper extends BaseMapper { - -} diff --git a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/service/FileService.java b/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/service/FileService.java deleted file mode 100644 index 3397ad5edd..0000000000 --- a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/service/FileService.java +++ /dev/null @@ -1,12 +0,0 @@ -package io.github.wujun728.file.service; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.UnsupportedEncodingException; - -public interface FileService { - String uploadFile(HttpServletRequest request); - String fileList(HttpServletRequest request); - void fileDown(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException; - String fileDel(HttpServletRequest request,HttpServletResponse response); -} diff --git a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/service/SysFilesService.java b/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/service/SysFilesService.java deleted file mode 100644 index 183db0289a..0000000000 --- a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/service/SysFilesService.java +++ /dev/null @@ -1,31 +0,0 @@ -package io.github.wujun728.file.service; - -import com.baomidou.mybatisplus.extension.service.IService; -import io.github.wujun728.common.base.Result; -import io.github.wujun728.file.entity.SysFilesEntity; - -import org.springframework.web.multipart.MultipartFile; - -import java.io.File; -import java.util.List; - -/** - * 文件上传 服务类 - * - * @author wujun - * @version V1.0 - * @date 2020年3月18日 - */ -public interface SysFilesService extends IService { - - Result saveFile(MultipartFile file); - - void removeByIdsAndFiles(List ids); - - Result saveFile(MultipartFile file, String biztype, String bizid); - - Result saveFile(File file, String biztype, String bizid); - - -} - diff --git a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/service/impl/FileServiceImpl.java b/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/service/impl/FileServiceImpl.java deleted file mode 100644 index 54428faba1..0000000000 --- a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/service/impl/FileServiceImpl.java +++ /dev/null @@ -1,363 +0,0 @@ -package io.github.wujun728.file.service.impl; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.HashMap; - -import javax.annotation.Resource; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import cn.hutool.core.date.DateUtil; -import io.github.wujun728.file.config.FileProperties; -import io.github.wujun728.file.entity.SysFilesEntity; -import io.github.wujun728.file.mapper.SysFilesMapper; -import io.github.wujun728.file.service.FileService; -import io.github.wujun728.file.utils.QiniuUtils; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; -import org.springframework.web.multipart.MultipartFile; -import org.springframework.web.multipart.MultipartHttpServletRequest; -import org.springframework.web.util.WebUtils; - -import com.alibaba.fastjson2.JSONObject; - -import lombok.extern.slf4j.Slf4j; - - -@Slf4j -@Service -public class FileServiceImpl implements FileService { - -// @Value("${filepath}") - @Value("${file.path}") - private String file_root; - - @Resource - private FileProperties fileUploadProperties; - - @Resource - SysFilesMapper sysFilesMapper; - - - @Override - public String uploadFile(HttpServletRequest request) { - String messagee = ""; - MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class); - MultipartFile file = multipartRequest.getFile("file"); - String filename = multipartRequest.getFile("file").getOriginalFilename(); - String username = multipartRequest.getParameter("name"); - if(!username.equals("")){ - //完整的文件路径 - File file1 = new File(file_root + username); - //文件路径不存在则刷新页面创建路径 - if(!file1.exists()){ - if(!file1.exists()){ - file1.mkdirs(); - log.info("用户:{}创建了文件夹{}",username,file); - } - // messagee="请刷新再上传"; - - } - //文件是否存在 - File file2 = new File(file_root + username+File.separator, filename); - if(file2.exists()){ - messagee = "文件已存在,无需上传"; - }else { - try{ - file.transferTo(file2); - log.info("用户:{}上传文件{}成功",username,filename); - messagee = "上传成功"; - } catch (IOException e) { - messagee = "上传失败"; - log.info("用户:{}上传文件{}失败",username,filename); - e.printStackTrace(); - } - } - }else { - Cookie[] cookies = request.getCookies(); - String username1 = ""; - if(cookies != null){ - //找到cookie,作为文件上传路径 - for (int i = 0; i <= cookies.length-1; i++) { - if(cookies[i].getName().equals("Junior_file")){ - username1 = cookies[i].getValue(); - break; - }else { - continue; - } - } - File file1 = new File(file_root + username1); - if(!file1.exists()){ - messagee = "请刷新再上传"; - }else { - File file2 = new File(file_root + username1+File.separator, filename); - if(file2.exists()){ - messagee = "文件已存在,无需上传"; - }else { - try { - file.transferTo(file2); - - saveSysFile(file2, filename, file2.getAbsolutePath(),username,"user",username); - messagee = "上传成功"; - log.info("临时用户上传文件{}成功",filename); - } catch (IOException e) { - messagee = "上传失败"; - log.info("临时用户上传文件{}失败",filename); - e.printStackTrace(); - } - } - } - }else { - messagee = "请刷新再上传"; - } - } - return messagee; - } - - private void saveSysFile(File file,String originalFilename,String newFilePathName, String username,String biztype,String bizid) throws IOException { - String createTime = DateUtil.now(); - String newPath = fileUploadProperties.getPath() + createTime + File.separator; - File uploadDirectory = new File(newPath); - if (uploadDirectory.exists()) { - if (!uploadDirectory.isDirectory()) { - uploadDirectory.delete(); - } - } else { - uploadDirectory.mkdir(); - } - String fileName = originalFilename; - String fileNameNew = QiniuUtils.getFileNameByDate(username,fileName); - // QiniuUtils.uploadFile(file, fileNameNew); - String downUrl = QiniuUtils.uploadFileV2(file, fileNameNew); - String URL = QiniuUtils.domain + "/" + fileName; - String url = fileUploadProperties.getUrl() + "/" + createTime + "/" + fileNameNew; - String filesize = QiniuUtils.FormetFileSize(file.length()); - this.saveFilesEntity(originalFilename, file.getAbsolutePath(),url,filesize,biztype, bizid); - } - - private void saveFilesEntity(String fileName, String newFilePathName, String url,String filesize, String biztype, String bizid) { - SysFilesEntity entity = new SysFilesEntity(); - entity.setFileName(fileName); - entity.setFilePath(newFilePathName); - entity.setUrl(url); - entity.setFileSize(filesize); - entity.setDictBiztype(biztype); - entity.setRefBizid(bizid); - sysFilesMapper.insert(entity); - } - - - //文件下载 - @Override - public void fileDown(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException { - String msg = ""; - //获得文件名 - String filename = request.getParameter("filename"); -// 获得文件路径 - String filepath = request.getParameter("name"); - if(!filepath.equals("")){ - File file = new File(file_root + filepath + File.separator+filename); - msg = fileDown(file, response, filename,filepath); - }else { - String filepath1 = getMyCookie(request); - File file = new File(file_root + filepath1 + File.separator + filename); - msg = fileDown(file, response, filename,filepath1); - } - - System.out.println(msg); - } - - //文件删除 - @Override - public String fileDel(HttpServletRequest request,HttpServletResponse response) { - String msg = ""; - String filename = request.getParameter("filename"); - String path = request.getParameter("name"); - if(!path.equals("")){ - File file = new File(file_root + path + File.separator + filename); - msg = fileDelOpt(file); - log.info("用户{}删除文件{}成功",path,filename); - }else { - String path1 = getMyCookie(request); - File file = new File(file_root + path1 + File.separator + filename); - msg = fileDelOpt(file); - log.info("临时用户删除文件{}成功",path,filename); - } - return msg; - } - - @Override - public String fileList(HttpServletRequest request) { - String message = ""; - ArrayList list = new ArrayList<>(); - String username = request.getParameter("name"); - if(!username.equals("")){ - //完整的文件路径 - File file1 = new File(file_root + username); - //文件路径不存在则刷新页面创建路径 - if(!file1.exists()){ - message="文件错误"; - }else { - File[] files = file1.listFiles(); - for (int i = 0; i <=files.length-1; i++) { - HashMap map = new HashMap<>(); - map.put("filename",files[i].getName()); - map.put("filetime",getModifiedTime(files[i])); - map.put("filesize",String.valueOf((((float)Math.round((getFileSize(files[i])/1048576)*100))/100))+" MB"); - list.add(map); - } - message = "文件存在"; - } - }else { - Cookie[] cookies = request.getCookies(); - String username1 = ""; - if(cookies != null){ - //找到cookie,作为文件上传路径 - for (int i = 0; i <= cookies.length-1; i++) { - if(cookies[i].getName().equals("Junior_file")){ - username1 = cookies[i].getValue(); - break; - }else { - continue; - } - } - File file = new File(file_root + username1); - if(!file.exists()){ - message="文件错误"; - }else { - File[] files = file.listFiles(); - for (int i = 0; i <=files.length-1; i++) { - HashMap map = new HashMap<>(); - map.put("filename",files[i].getName()); - map.put("filetime",getModifiedTime(files[i])); - map.put("filesize",String.valueOf((((float)Math.round((getFileSize(files[i])/1048576)*100))/100))+" MB"); - list.add(map); - } - message = "文件存在"; - } - }else { - message="文件错误"; - } - } - JSONObject jsonObject = new JSONObject(); - jsonObject.put("message",message); - if(message == "文件存在"){ - jsonObject.put("code",0); - }else { - jsonObject.put("code",404); - } - jsonObject.put("data",list); - String res = jsonObject.toJSONString(); - return res; - } - - //获取文件大小 - private static float getFileSize(File f) { - InputStream fis = null; - try { - fis = new FileInputStream(f); - return fis.available(); - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (fis != null) { - try { - fis.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - return 0; - } - - //获取文件创建时间 - public static String getModifiedTime(File f){ - Calendar cal = Calendar.getInstance(); - long time = f.lastModified(); - SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - cal.setTimeInMillis(time); - //输出:修改时间[2] 2009-08-17 10:32:38 - return formatter.format(cal.getTime()); - } - - //获取cookie - public static String getMyCookie(HttpServletRequest request) { - String cookie = ""; - Cookie[] cookies = request.getCookies(); - if (cookies != null) { - //找到cookie,作为文件上传路径 - for (int i = 0; i <= cookies.length - 1; i++) { - if (cookies[i].getName().equals("Junior_file")) { - cookie = cookies[i].getValue(); - break; - } else { - continue; - } - } - } - return cookie; - } - - //文件下载操作 - public static String fileDown(File file,HttpServletResponse response,String filename,String filepath) throws UnsupportedEncodingException { - String msg = ""; - if(file.exists()){ - //设置响应体,响应头 - response.setContentType("application/force-download;charset=UTF-8"); - //文件中含有逗号等,需要将文件名用引号包起来 - response.addHeader("Content-Disposition", "attachment;fileName=" + "\""+ URLEncoder.encode(filename,"utf-8") +"\""); - -// 通过文件流下载 - byte[] buffer = new byte[1024]; - try (FileInputStream fis = new FileInputStream(file); - BufferedInputStream bis = new BufferedInputStream(fis)) { - OutputStream os = response.getOutputStream(); - int i = bis.read(buffer); - while (i != -1) { - os.write(buffer, 0, i); - i = bis.read(buffer); - } - log.info("用户:{}下载文件{}成功",filepath,filename); - msg = "下载成功"; - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - }else { - log.info("临时用户下载文件{}失败",filename); - msg = "下载失败"; - } - return msg; - } - - //文件删除操作 - public static String fileDelOpt(File file){ - String msg = ""; - if(file.exists()){ - try { - file.delete(); - msg = "文件删除成功"; - }catch (Exception e){ - e.printStackTrace(); - msg = "文件删除错误"; - } - }else { - msg = "文件删除错误"; - } - return msg; - } -} diff --git a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/service/impl/SysFilesServiceImpl.java b/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/service/impl/SysFilesServiceImpl.java deleted file mode 100644 index b67c3294b5..0000000000 --- a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/service/impl/SysFilesServiceImpl.java +++ /dev/null @@ -1,223 +0,0 @@ -package io.github.wujun728.file.service.impl; - -import java.io.File; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import javax.annotation.Resource; - -import cn.hutool.core.date.DateUtil; -import cn.hutool.core.io.FileUtil; -import io.github.wujun728.common.base.Result; -import io.github.wujun728.common.exception.BusinessException; -import io.github.wujun728.file.entity.SysFilesEntity; -import io.github.wujun728.file.mapper.SysFilesMapper; -import io.github.wujun728.file.utils.QiniuUtils; -import org.apache.commons.io.FileUtils; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.stereotype.Service; -import org.springframework.web.multipart.MultipartFile; - -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import io.github.wujun728.file.config.FileProperties; -import io.github.wujun728.file.service.SysFilesService; - -/** - * 文件上传 服务类 - * - * @author wujun - * @version V1.0 - * @date 2020年3月18日 - */ -@EnableConfigurationProperties(FileProperties.class) -@Service("sysFilesService") -public class SysFilesServiceImpl extends ServiceImpl implements SysFilesService { - @Resource - private FileProperties fileUploadProperties; - - @Resource - private SysFilesMapper sysFilesMapper; - - @Override - public Result saveFile(MultipartFile file) { - //存储文件夹 -// String createTime = DateUtils.format(new Date(), DateUtils.DATEPATTERN); - String createTime = DateUtil.now(); - String newPath = fileUploadProperties.getPath() + createTime + File.separator; - File uploadDirectory = new File(newPath); - if (uploadDirectory.exists()) { - if (!uploadDirectory.isDirectory()) { - uploadDirectory.delete(); - } - } else { - uploadDirectory.mkdir(); - } - try { - String fileName = file.getOriginalFilename(); - //id与filename保持一直,删除文件 - String fileNameNew = UUID.randomUUID().toString().replace("-", "") + getFileType(fileName); - String newFilePathName = newPath + fileNameNew; - String url = fileUploadProperties.getUrl() + "/" + createTime + "/" + fileNameNew; - //创建输出文件对象 - File outFile = new File(newFilePathName); - //拷贝文件到输出文件对象 - FileUtils.copyInputStreamToFile(file.getInputStream(), outFile); - //保存文件记录 - saveFilesEntity(fileName, newFilePathName, url, "filemanager", "",""); - Map resultMap = new HashMap<>(); - resultMap.put("src", url); - return Result.success(resultMap); - } catch (Exception e) { - throw new BusinessException("上传文件失败"); - } - } - - - private void saveFilesEntity(String fileName, String newFilePathName, String url,String filesize, String biztype, String bizid) { - SysFilesEntity entity = new SysFilesEntity(); - entity.setFileName(fileName); - entity.setFilePath(newFilePathName); - entity.setUrl(url); - entity.setFileSize(filesize); - entity.setDictBiztype(biztype); - entity.setRefBizid(bizid); - this.save(entity); - } - - -// @Override -// public Result saveFile(MultipartFile file, String biztype, String bizid) { -//// Map map = Maps.newHashMap(); -//// map.put("biztype",biztype); -//// map.put("bizid", bizid); -// //this.saveOssFile(file); -// return this.saveFile(file,biztype,bizid); -// } - -// @Override -// public Result saveFile(MultipartFile file, String biztype, String bizid) { -// mapTmp.set(ImmutableMap.builder().put("biztype",biztype).put("bizid", bizid).build()); -//// this.saveOssFile(file); -// return this.saveOssFile(file); -// } - - - - - -// private static final ThreadLocal> mapTmp = new ThreadLocal(); - - - - -// @Override -// @Deprecated -// public Result saveOssFile(MultipartFile file) { -// try { -// String fileName = file.getOriginalFilename(); -// String fileNameNew = QiniuUtils.getFileNameByDate(fileName); -// QiniuUtils.uploadFile(file, fileNameNew); -// String URL = QiniuUtils.domain + "/" + fileName; -// String downUrl = QiniuUtils.downloadURL(fileNameNew);; -// //保存文件记录 -// saveFilesEntity(fileNameNew, URL, downUrl, "filemanager", ""); -// Map resultMap = new HashMap<>(); -// resultMap.put("src", URL); -// return Result.success(resultMap); -// } catch (Exception e) { -// throw new BusinessException("上传文件失败"); -// } -// } - - - @Override - public Result saveFile(MultipartFile file, String bizType, String bizid) { - try { - String username = "admin"; - String fileName = file.getOriginalFilename(); - String fileNameNew = QiniuUtils.getFileNameByDate(username,fileName); -// QiniuUtils.uploadFile(file, fileNameNew); - String downUrl = QiniuUtils.uploadFileV2(file, fileNameNew); - String URL = QiniuUtils.domain + "/" + fileName; -// String downUrl = QiniuUtils.download(fileNameNew);; - //保存文件记录 - saveFilesEntity(fileNameNew, downUrl, "filemanager", QiniuUtils.FormetFileSize(file.getSize()),bizType,bizid); - Map resultMap = new HashMap<>(); - resultMap.put("src", downUrl); - return Result.success(resultMap); - } catch (Exception e) { - e.printStackTrace(); - throw new BusinessException("上传文件失败"); - } - } - @Override - public Result saveFile(File file,String bizType,String bizid) { - try { - String username = "sessionService.getCurrentUsername()"; - String fileName = file.getName(); - String fileNameNew = QiniuUtils.getFileNameByDate(username,fileName); -// QiniuUtils.uploadFile(file, fileNameNew); - String downUrl = QiniuUtils.uploadFileV2(file, fileNameNew); - String URL = QiniuUtils.domain + "/" + fileName; -// String downUrl = QiniuUtils.download(fileNameNew);; - //保存文件记录 - saveFilesEntity(fileNameNew, downUrl, "filemanager", - QiniuUtils.FormetFileSize(FileUtil.size(file)),"",""); - Map resultMap = new HashMap<>(); - resultMap.put("src", downUrl); - return Result.success(resultMap); - } catch (Exception e) { - e.printStackTrace(); - throw new BusinessException("上传文件失败"); - } - } - - - @Override - public void removeByIdsAndFiles(List ids) { - List list = this.listByIds(ids); - list.forEach(entity -> { - QiniuUtils.deleteFileFromQiniu(entity.getFileName()); - //如果之前的文件存在,删除 - File file = new File(entity.getFilePath()); - if (file.exists()) { - file.delete(); - } - }); - this.removeByIds(ids); - - } - -// @Override -// public void removeByIdsAndFiles(List ids) { -// List list = this.listByIds(ids); -// list.forEach(entity -> { -// //如果之前的文件存在,删除 -// File file = new File(entity.getFilePath()); -// if (file.exists()) { -// file.delete(); -// } -// }); -// this.removeByIds(ids); -// -// } - - /** - * 获取文件后缀名 - * - * @param fileName 文件名 - * @return 后缀名 - */ - private String getFileType(String fileName) { - if (fileName != null && fileName.contains(".")) { - return fileName.substring(fileName.lastIndexOf(".")); - } - return ""; - } - - - - -} \ No newline at end of file diff --git a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/utils/ExecuteResult.java b/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/utils/ExecuteResult.java deleted file mode 100644 index f72a93acee..0000000000 --- a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/utils/ExecuteResult.java +++ /dev/null @@ -1,97 +0,0 @@ -package io.github.wujun728.file.utils; - - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Created by kzyuan on 2017/4/5. - * 业务类执行结果包装类 - * @param - */ -public class ExecuteResult implements Serializable { - private static final long serialVersionUID = 7365417829056921958L; - /** - * 返回结果数据 - */ - private T result; - /** - * 成功提示消息 - */ - private String successMessage; - /** - * 普通的错误信息 - */ - private List errorMessages = new ArrayList(); - /** - * 字段错误信息-以key-value的形式出现 - */ - private Map fieldErrors = new HashMap(); - /** - * 警告信息 - */ - private List warningMessages = new ArrayList(); - - public String getSuccessMessage() { - return successMessage; - } - public void setSuccessMessage(String successMessage) { - this.successMessage = successMessage; - } - /** - * 判断当前执行结果是否正确,如果errorMessages和fieldErrors都为空,则无错 - * @return - */ - public boolean isSuccess() { - return errorMessages.isEmpty() && fieldErrors.isEmpty(); - } - public T getResult() { - return result; - } - public void setResult(T result) { - this.result = result; - } - public List getErrorMessages() { - return errorMessages; - } - public void setErrorMessages(List errorMessages) { - this.errorMessages = errorMessages; - } - public Map getFieldErrors() { - return fieldErrors; - } - public void setFieldErrors(Map fieldErrors) { - this.fieldErrors = fieldErrors; - } - public List getWarningMessages() { - return warningMessages; - } - public void setWarningMessages(List warningMessages) { - this.warningMessages = warningMessages; - } - /** - * 添加一条错误消息到列表中 - * @param errorMessage - */ - public void addErrorMessage(String errorMessage) { - this.errorMessages.add(errorMessage); - } - /** - * 添加一条字段错误信息到列表中 - * @param field 字段名称-key - * @param errorMessage 该字段对应的错误信息-value - */ - public void addFieldError(String field, String errorMessage) { - this.fieldErrors.put(field, errorMessage); - } - /** - * 添加一条警告信息到列表中 - * @param warningMessage - */ - public void addWarningMessage(String warningMessage) { - this.warningMessages.add(warningMessage); - } -} diff --git a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/utils/FileUtils.java b/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/utils/FileUtils.java deleted file mode 100644 index fa39818e88..0000000000 --- a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/utils/FileUtils.java +++ /dev/null @@ -1,125 +0,0 @@ -package io.github.wujun728.file.utils; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.commons.fileupload.FileItem; -import org.apache.commons.fileupload.FileItemFactory; -import org.apache.commons.fileupload.disk.DiskFileItem; -import org.apache.commons.fileupload.disk.DiskFileItemFactory; -import org.apache.commons.io.FilenameUtils; -import org.springframework.web.multipart.MultipartFile; -import org.springframework.web.multipart.commons.CommonsMultipartFile; - -public class FileUtils { - - /** - * 判断文件是否存在,不存在就创建 - * @param file - */ - public static void createFile(File file) { - if (file.exists()) { - System.out.println("File exists"); - } else { - System.out.println("File not exists, create it ..."); - //getParentFile() 获取上级目录(包含文件名时无法直接创建目录的) - if (!file.getParentFile().exists()) { - System.out.println("not exists"); - //创建上级目录 - file.getParentFile().mkdirs(); - } - try { - //在上级目录里创建文件 - file.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - //file 转换为 MultipartFile - private MultipartFile getMulFileByFile(File file) - { - FileItemFactory factory = new DiskFileItemFactory(16, null); - String textFieldName = "textField"; - int num = file.getAbsolutePath().lastIndexOf("."); - String extFile =FilenameUtils.getExtension(file.getAbsolutePath());// filePath.substring(num); - FileItem item = factory.createItem(textFieldName, "text/plain", true, - "MyFileName" + extFile); - File newfile = file; - int bytesRead = 0; - byte[] buffer = new byte[8192]; - try - { - FileInputStream fis = new FileInputStream(newfile); - OutputStream os = item.getOutputStream(); - while ((bytesRead = fis.read(buffer, 0, 8192)) - != -1) - { - os.write(buffer, 0, bytesRead); - } - os.close(); - fis.close(); - } - catch (IOException e) - { - e.printStackTrace(); - } - MultipartFile mfile = new CommonsMultipartFile(item); - return mfile; - - } - - //file 转换为 MultipartFile - private MultipartFile getMulFileByPath(String filePath) - { - FileItemFactory factory = new DiskFileItemFactory(16, null); - String textFieldName = "textField"; - int num = filePath.lastIndexOf("."); - String extFile = filePath.substring(num); - FileItem item = factory.createItem(textFieldName, "text/plain", true, - "MyFileName" + extFile); - File newfile = new File(filePath); - int bytesRead = 0; - byte[] buffer = new byte[8192]; - try - { - FileInputStream fis = new FileInputStream(newfile); - OutputStream os = item.getOutputStream(); - while ((bytesRead = fis.read(buffer, 0, 8192)) - != -1) - { - os.write(buffer, 0, bytesRead); - } - os.close(); - fis.close(); - } - catch (IOException e) - { - e.printStackTrace(); - } - - MultipartFile mfile = new CommonsMultipartFile(item); - return mfile; - - } - - - /** - * MultipartFile 转换成File - * - * @param multfile 原文件类型 - * @return File - * @throws IOException - */ - public static File multipartToFile(MultipartFile multfile) { - - CommonsMultipartFile cf = (CommonsMultipartFile)multfile; - //这个myfile是MultipartFile的 - DiskFileItem fi = (DiskFileItem) cf.getFileItem(); - File file = fi.getStoreLocation(); - return file; - } -} diff --git a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/utils/QiniuUtils.java b/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/utils/QiniuUtils.java deleted file mode 100644 index 3352288e50..0000000000 --- a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/file/utils/QiniuUtils.java +++ /dev/null @@ -1,467 +0,0 @@ -package io.github.wujun728.file.utils; - -import java.io.*; -import java.text.DecimalFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.UUID; - -import org.apache.commons.io.IOUtils; -import org.json.JSONException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; -import org.springframework.web.multipart.MultipartFile; - -import com.qiniu.common.QiniuException; -import com.qiniu.common.Zone; -import com.qiniu.http.Response; -import com.qiniu.storage.BucketManager; -import com.qiniu.storage.Configuration; -import com.qiniu.storage.UploadManager; -import com.qiniu.util.Auth; - -import lombok.extern.slf4j.Slf4j; - -import javax.security.auth.message.AuthException; - - -@Component -@Slf4j -public class QiniuUtils { - - public static final String ACCESS_KEY = "ts0n9OF16ekFkDkZTTlpmyPI-tP3HKQDyw_GR4o2"; // 你的access_key - public static final String SECRET_KEY = "c-OjjwV3ZgzCQwxc6W_bsTFKuDg8qeyqohyJU0RL"; // 你的secret_key - public static final String BUCKET_NAME = "qixing-files"; // 你的bucket_name - public static final String domain = "http://qiniu.hbqxcpa.cn"; // 你的bucket_name - public static final long TOKEN_TIME = 3600 * 24 * 365 * 5; // 你的bucket_name - - public static void uploadFile(String filePath, String fileName) throws QiniuException { - com.qiniu.storage.Configuration cfg = new Configuration(); - UploadManager uploadManager = new UploadManager(cfg); - Auth auth = Auth.create(QiniuUtils.ACCESS_KEY, QiniuUtils.SECRET_KEY); - String token = auth.uploadToken(QiniuUtils.BUCKET_NAME); - Response r = uploadManager.put(filePath, fileName, token); - if (r.isOK()) { - log.info("上传成功!"); - log.info("上传文件路径:" + domain + r.url()); - } else { - log.info("上传失败!"); - } - System.out.println(token); // 输出上传凭证 - System.out.println(r.isOK()); // 输出上传到七牛云之后的文件名称 - System.out.println(r.toString()); // 输出上传到七牛云之后的文件名称 - System.out.println(r.url()); // 输出上传到七牛云之后的文件名称 - - } - - public static void uploadFile(File file, String fileName) throws QiniuException { - com.qiniu.storage.Configuration cfg = new Configuration(); - UploadManager uploadManager = new UploadManager(cfg); - Auth auth = Auth.create(QiniuUtils.ACCESS_KEY, QiniuUtils.SECRET_KEY); - String token = auth.uploadToken(QiniuUtils.BUCKET_NAME); - Response r = uploadManager.put(file, fileName, token); - if (r.isOK()) { - log.info("上传成功!"); - log.info("上传文件路径:" + domain + r.url()); - } else { - log.info("上传失败!"); - } - System.out.println(token); // 输出上传凭证 - System.out.println(r.isOK()); // 输出上传到七牛云之后的文件名称 - System.out.println(r.toString()); // 输出上传到七牛云之后的文件名称 - System.out.println(r.url()); // 输出上传到七牛云之后的文件名称 - - } - - public static void uploadFile(InputStream ins, String fileName) throws QiniuException { - com.qiniu.storage.Configuration cfg = new Configuration(); - UploadManager uploadManager = new UploadManager(cfg); - Auth auth = Auth.create(QiniuUtils.ACCESS_KEY, QiniuUtils.SECRET_KEY); - String token = auth.uploadToken(QiniuUtils.BUCKET_NAME); - Response r = uploadManager.put(chanageInputStream2byte(ins), fileName, token); - if (r.isOK()) { - log.info("上传成功!"); - log.info("上传文件路径:" + domain + r.url()); - } else { - log.info("上传失败!"); - } - System.out.println(token); // 输出上传凭证 - System.out.println(r.isOK()); // 输出上传到七牛云之后的文件名称 - System.out.println(r.toString()); // 输出上传到七牛云之后的文件名称 - System.out.println(r.url()); // 输出上传到七牛云之后的文件名称 - } - - public static void uploadFile(MultipartFile file, String fileName) throws IOException { - com.qiniu.storage.Configuration cfg = new Configuration(); - UploadManager uploadManager = new UploadManager(cfg); - Auth auth = Auth.create(QiniuUtils.ACCESS_KEY, QiniuUtils.SECRET_KEY); - String token = auth.uploadToken(QiniuUtils.BUCKET_NAME); -// try { - Response r = uploadManager.put(file.getBytes(), fileName, token); - if (r.isOK()) { - log.info("上传成功!"); - log.info("上传文件路径:" + domain + r.url()); - } else { - log.info("上传失败!"); - } - System.out.println(token); // 输出上传凭证 - System.out.println(r.isOK()); // 输出上传到七牛云之后的文件名称 - System.out.println(r.toString()); // 输出上传到七牛云之后的文件名称 - System.out.println(r.url()); // 输出上传到七牛云之后的文件名称 -// } catch (IOException e) { -// e.printStackTrace(); -// } - } - - public static String uploadFileV2(MultipartFile file, String fileName) throws IOException { - com.qiniu.storage.Configuration cfg = new Configuration(); - UploadManager uploadManager = new UploadManager(cfg); - Auth auth = Auth.create(QiniuUtils.ACCESS_KEY, QiniuUtils.SECRET_KEY); - String token = auth.uploadToken(QiniuUtils.BUCKET_NAME); - Response r = uploadManager.put(file.getBytes(), fileName, token); - if (r.isOK()) { - log.info("上传成功!"); - log.info("上传文件路径:" + domain + r.url()); - } else { - log.info("上传失败!"); - } - System.out.println(token); // 输出上传凭证 - System.out.println(r.isOK()); // 输出上传到七牛云之后的文件名称 - System.out.println(r.toString()); // 输出上传到七牛云之后的文件名称 - System.out.println(r.url()); // 输出上传到七牛云之后的文件名称 - String URL = QiniuUtils.domain + "/" + fileName; - String downloadRUL = auth.privateDownloadUrl(URL, TOKEN_TIME); - log.info("下载文件路径:" + downloadRUL); - return downloadRUL; - } - public static String uploadFileV2(File file, String fileName) throws IOException { - com.qiniu.storage.Configuration cfg = new Configuration(); - UploadManager uploadManager = new UploadManager(cfg); - Auth auth = Auth.create(QiniuUtils.ACCESS_KEY, QiniuUtils.SECRET_KEY); - String token = auth.uploadToken(QiniuUtils.BUCKET_NAME); - FileInputStream input = new FileInputStream(file); - Response r = uploadManager.put(IOUtils.toByteArray(input), fileName, token); - if (r.isOK()) { - log.info("上传成功!"); - log.info("上传文件路径:" + domain + r.url()); - } else { - log.info("上传失败!"); - } - System.out.println(token); // 输出上传凭证 - System.out.println(r.isOK()); // 输出上传到七牛云之后的文件名称 - System.out.println(r.toString()); // 输出上传到七牛云之后的文件名称 - System.out.println(r.url()); // 输出上传到七牛云之后的文件名称 - String URL = QiniuUtils.domain + "/" + fileName; - String downloadRUL = auth.privateDownloadUrl(URL, TOKEN_TIME); - log.info("下载文件路径:" + downloadRUL); - return downloadRUL; - } - - public static String downloadURL(String fileName) { - // 密钥配置 - Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY); - // 构造私有空间的需要生成的下载的链接 - String URL = QiniuUtils.domain + "/" + fileName; - log.info("下载原始文件路径:" + URL); - // 调用privateDownloadUrl方法生成下载链接,第二个参数可以设置Token的过期时间 - String downloadRUL = auth.privateDownloadUrl(URL, TOKEN_TIME); - log.info("下载文件路径:" + downloadRUL); - System.out.println(downloadRUL); - return downloadRUL; - } - - public static byte[] chanageInputStream2byte(InputStream fis) { - byte[] buffer = null; - try { - // FileInputStream fis = new FileInputStream(tradeFile); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - byte[] b = new byte[1024]; - int n; - while ((n = fis.read(b)) != -1) { - bos.write(b, 0, n); - } - fis.close(); - bos.close(); - buffer = bos.toByteArray(); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - return buffer; - } - - public static String FormetFileSize(Long fileLength) { - String fileSizeString = ""; - DecimalFormat df = new DecimalFormat("#.00"); - if (fileLength != null) { - if (fileLength < 1024) { - fileSizeString = df.format((double) fileLength) + "B"; - } else if (fileLength < 1048576) { - fileSizeString = df.format((double) fileLength / 1024) + "K"; - } else if (fileLength < 1073741824) { - fileSizeString = df.format((double) fileLength / 1048576) + "M"; - } else { - fileSizeString = df.format((double) fileLength / 1073741824) + "G"; - } - } - return fileSizeString; - } - - public static String getFileNameByDate(String filename) { - String filenameExtension = ""; - String filenamePre = ""; - if (filename.contains(".")) { - filenameExtension = filename.substring(filename.indexOf(".") + 1, filename.length()); - filenamePre = filename.substring(0, filename.indexOf(".")); - } else { - filenamePre = filename; - } - SimpleDateFormat time = new SimpleDateFormat("yyyyMMddHHmmss"); - String filenameNew = filenamePre + "-" + time.format(new Date()) + "." + filenameExtension; - log.info(filenameNew); - return filenameNew; - - } - - public static String getFileNameByDate(String username , String filename) { - String filenameExtension = ""; - String filenamePre = ""; - if (filename.contains(".")) { - filenameExtension = filename.substring(filename.indexOf(".") + 1, filename.length()); - filenamePre = filename.substring(0, filename.indexOf(".")); - } else { - filenamePre = filename; - } - SimpleDateFormat time = new SimpleDateFormat("yyyyMMddHHmmss"); - String filenameNew =username+"/" + filenamePre + "-" + time.format(new Date()) +"-"+ username+ "." + filenameExtension; - log.info(filenameNew); - return filenameNew; - - } - - // 删除文件 - public static int deleteFileFromQiniu(String fileName) { - // 构造一个带指定Zone对象的配置类 - @SuppressWarnings("deprecation") - Configuration cfg = new Configuration(Zone.zone0()); - String key = fileName; - Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY); - BucketManager bucketManager = new BucketManager(auth, cfg); - try { - Response delete = bucketManager.delete(BUCKET_NAME, key); - return delete.statusCode; - } catch (QiniuException ex) { - // 如果遇到异常,说明删除失败 - ex.printStackTrace(); - System.err.println(ex.code()); - System.err.println(ex.response.toString()); - } - return -1; - } - - - public static void main(String[] args) { - try { -// uploadFile("D:\\11111108599.zip", "11111108599.zip"); -// uploadFile(new File("D:\\quickstart-master.tar.gz"), "quickstart-master.tar.gz"); -// download("11111108599.zip"); -// getFileNameByDate("11111108599.tar.gz"); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - - // ***************************************************************************************************************** - // ***************************************************************************************************************** - // ***************************************************************************************************************** - - private static Logger logger = LoggerFactory.getLogger(QiniuUtils.class); - String bucketName = "bucketName"; -// private String bucketName = propertyUtil.getProperty("bucketName"); -// private String domain = propertyUtil.getProperty("domain"); -// private String ACCESS_KEY = propertyUtil.getProperty("ACCESS_KEY"); -// private String SECRET_KEY = propertyUtil.getProperty("SECRET_KEY"); - - //通过文件路径上传文件 - public ExecuteResult uploadFile(String localFile) throws AuthException, JSONException { - File file = new File(localFile); - /** - * 文件后缀名 文件扩展名 - */ - String filenameExtension = localFile.substring(localFile.lastIndexOf("."), localFile.length()); - return uploadFile2(file, filenameExtension); - } - - //通过File上传 - public ExecuteResult uploadFile2(File file, String filename) throws AuthException, JSONException { - ExecuteResult executeResult = new ExecuteResult(); -// String uptoken = getUpToken(); - // 可选的上传选项,具体说明请参见使用手册。 -// PutExtra extra = new PutExtra(); -// PutRet ret = IoApi.putFile(uptoken,filename , extra); - com.qiniu.storage.Configuration cfg = new Configuration(); - UploadManager uploadManager = new UploadManager(cfg); - Auth auth = Auth.create(ACCESS_KEY,SECRET_KEY); - String token = auth.uploadToken(bucketName); - Response r; - try { - r = uploadManager.put(file, filename, token); - System.out.println(token); //输出上传凭证 - System.out.println(r.isOK()); //输出上传到七牛云之后的文件名称 - System.out.println(r.toString()); //输出上传到七牛云之后的文件名称 - if (r.isOK()) { - executeResult.setSuccessMessage("上传成功!"); - executeResult.setResult(domain+r.url()); - } else { - executeResult.addErrorMessage("上传失败"); - } - } catch (QiniuException e) { - e.printStackTrace(); - } - - - return executeResult; - } - public String getFileNameByDateAndUUID(String filenameExtension) { - SimpleDateFormat time = new SimpleDateFormat("yyyy/MM/dd"); - String filename = time.format(new Date()) + "/" + UUID.randomUUID() + filenameExtension; - return filename; - - } - - /** - * 从 inputstream 中写入七牛 - * - * @param content 要写入的内容 - * @return - * @throws AuthException - * @throws JSONException - */ - public boolean uploadFile2(String content ,String fileName) throws AuthException, JSONException { - // 读取的时候按的二进制,所以这里要同一 - ByteArrayInputStream inputStream = new ByteArrayInputStream(content.getBytes()); - // 可选的上传选项,具体说明请参见使用手册。 - com.qiniu.storage.Configuration cfg = new Configuration(); - UploadManager uploadManager = new UploadManager(cfg); - Auth auth = Auth.create(ACCESS_KEY,SECRET_KEY); - String token = auth.uploadToken(bucketName); - - Response r; - try { - r = uploadManager.put(QiniuUtils.chanageInputStream2byte(inputStream), fileName, token); -// Response r = uploadManager.put(inputStream, key, token); - System.out.println(token); //输出上传凭证 - System.out.println(r.isOK()); //输出上传到七牛云之后的文件名称 - System.out.println(r.toString()); //输出上传到七牛云之后的文件名称 - if (r.isOK()) { - return true; - } else { - return false; - } - } catch (QiniuException e) { - e.printStackTrace(); - } - return false; - } - public boolean uploadFile2(InputStream ins,String fileName) throws AuthException, JSONException { - com.qiniu.storage.Configuration cfg = new Configuration(); - UploadManager uploadManager = new UploadManager(cfg); - Auth auth = Auth.create(ACCESS_KEY,SECRET_KEY); - String token = auth.uploadToken(bucketName); - Response r; - try { - r = uploadManager.put(QiniuUtils.chanageInputStream2byte(ins), fileName, token); - //Response r = uploadManager.put(inputStream, key, token); - System.out.println(token); //输出上传凭证 - System.out.println(r.isOK()); //输出上传到七牛云之后的文件名称 - System.out.println(r.toString()); //输出上传到七牛云之后的文件名称 - if (r.isOK()) { - return true; - } else { - return false; - } - } catch (QiniuException e) { - e.printStackTrace(); - } - return false; - } - - public static byte[] chanageInputStream2byte2(InputStream fis){ - byte[] buffer = null; - try - { -// FileInputStream fis = new FileInputStream(tradeFile); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - byte[] b = new byte[1024]; - int n; - while ((n = fis.read(b)) != -1) - { - bos.write(b, 0, n); - } - fis.close(); - bos.close(); - buffer = bos.toByteArray(); - }catch (FileNotFoundException e){ - e.printStackTrace(); - }catch (IOException e){ - e.printStackTrace(); - } - return buffer; - } - public static byte[] File2byte(File tradeFile){ - byte[] buffer = null; - try - { - FileInputStream fis = new FileInputStream(tradeFile); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - byte[] b = new byte[1024]; - int n; - while ((n = fis.read(b)) != -1) - { - bos.write(b, 0, n); - } - fis.close(); - bos.close(); - buffer = bos.toByteArray(); - }catch (FileNotFoundException e){ - e.printStackTrace(); - }catch (IOException e){ - e.printStackTrace(); - } - return buffer; - } - - //获得下载地址 -// public String getDownloadFileUrl(String filename) throws Exception { -// Mac mac = getMac(); -// String baseUrl = URLUtils.makeBaseUrl(domain, filename); -// GetPolicy getPolicy = new GetPolicy(); -// String downloadUrl = getPolicy.makeRequest(baseUrl, mac); -// return downloadUrl; -// } -// -// //删除文件 -// public void deleteFile(String filename) { -// Mac mac = getMac(); -// RSClient client = new RSClient(mac); -// client.delete(domain, filename); -// } -// -// //获取凭证 -// private String getUpToken() throws AuthException, JSONException { -// Mac mac = getMac(); -// PutPolicy putPolicy = new PutPolicy(bucketName); -// String uptoken = putPolicy.token(mac); -// return uptoken; -// } -// -// private Mac getMac() { -// Mac mac = new Mac(ACCESS_KEY, SECRET_KEY); -// return mac; -// } - -} diff --git a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/oss/config/OssAutoConfigure.java b/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/oss/config/OssAutoConfigure.java deleted file mode 100644 index 529ddf0607..0000000000 --- a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/oss/config/OssAutoConfigure.java +++ /dev/null @@ -1,15 +0,0 @@ -package io.github.wujun728.oss.config; - -import io.github.wujun728.oss.properties.FileServerProperties; -import io.github.wujun728.oss.template.FdfsTemplate; -import io.github.wujun728.oss.template.S3Template; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Import; - -/** - */ -@EnableConfigurationProperties(FileServerProperties.class) -@Import({FdfsTemplate.class, S3Template.class}) -public class OssAutoConfigure { - -} diff --git a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/oss/model/ObjectInfo.java b/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/oss/model/ObjectInfo.java deleted file mode 100644 index 01ad9aad2f..0000000000 --- a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/oss/model/ObjectInfo.java +++ /dev/null @@ -1,19 +0,0 @@ -package io.github.wujun728.oss.model; - -import lombok.Getter; -import lombok.Setter; - -/** - */ -@Setter -@Getter -public class ObjectInfo { - /** - * 对象查看路径 - */ - private String objectUrl; - /** - * 对象保存路径 - */ - private String objectPath; -} diff --git a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/oss/properties/FdfsProperties.java b/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/oss/properties/FdfsProperties.java deleted file mode 100644 index 4c47cb39a4..0000000000 --- a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/oss/properties/FdfsProperties.java +++ /dev/null @@ -1,17 +0,0 @@ -package io.github.wujun728.oss.properties; - -import lombok.Getter; -import lombok.Setter; - -/** - * fastdfs配置 - * - */ -@Setter -@Getter -public class FdfsProperties { - /** - * fastdfs的http访问地址 - */ - private String webUrl; -} diff --git a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/oss/properties/FileServerProperties.java b/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/oss/properties/FileServerProperties.java deleted file mode 100644 index bea9fe888a..0000000000 --- a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/oss/properties/FileServerProperties.java +++ /dev/null @@ -1,33 +0,0 @@ -package io.github.wujun728.oss.properties; - -import lombok.Getter; -import lombok.Setter; -import org.springframework.boot.context.properties.ConfigurationProperties; - -/** - */ -@Setter -@Getter -@ConfigurationProperties(prefix = FileServerProperties.PREFIX) -public class FileServerProperties { - public static final String PREFIX = "jun.file-server"; - public static final String TYPE_FDFS = "fastdfs"; - public static final String TYPE_S3 = "s3"; - - /** - * 为以下2个值,指定不同的自动化配置 - * s3:aws s3协议的存储(七牛oss、阿里云oss、minio等) - * fastdfs:本地部署的fastDFS - */ - private String type; - - /** - * aws s3配置 - */ - S3Properties s3 = new S3Properties(); - - /** - * fastDFS配置 - */ - FdfsProperties fdfs = new FdfsProperties(); -} diff --git a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/oss/properties/S3Properties.java b/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/oss/properties/S3Properties.java deleted file mode 100644 index cde3ee7485..0000000000 --- a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/oss/properties/S3Properties.java +++ /dev/null @@ -1,37 +0,0 @@ -package io.github.wujun728.oss.properties; - -import lombok.Getter; -import lombok.Setter; - -/** - * aws s3协议配置 - * - */ -@Setter -@Getter -public class S3Properties { - /** - * 用户名 - */ - private String accessKey; - /** - * 密码 - */ - private String accessKeySecret; - /** - * 访问端点 - */ - private String endpoint; - /** - * bucket名称 - */ - private String bucketName; - /** - * 区域 - */ - private String region; - /** - * path-style - */ - private Boolean pathStyleAccessEnabled = true; -} diff --git a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/oss/service/IOssService.java b/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/oss/service/IOssService.java deleted file mode 100644 index 411fd6e3fc..0000000000 --- a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/oss/service/IOssService.java +++ /dev/null @@ -1,37 +0,0 @@ -package io.github.wujun728.oss.service; - -import io.github.wujun728.oss.model.ObjectInfo; -import org.springframework.web.multipart.MultipartFile; - -import java.io.InputStream; -import java.io.OutputStream; - -/** - */ -public interface IOssService { - /** - * 上传对象 - * @param objectName 对象名 - * @param is 对象流 - */ - ObjectInfo upload(String objectName, InputStream is); - - /** - * 上传对象 - * @param file 对象 - */ - ObjectInfo upload(MultipartFile file); - - /** - * 删除对象 - * @param objectKey 对象标识 - */ - void delete(String objectKey); - - /** - * 查看文件 - * @param objectPath 对象路径 - * @param os 输出流 - */ - void view(String objectPath, OutputStream os); -} diff --git a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/oss/template/FdfsTemplate.java b/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/oss/template/FdfsTemplate.java deleted file mode 100644 index 779296b902..0000000000 --- a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/oss/template/FdfsTemplate.java +++ /dev/null @@ -1,78 +0,0 @@ -package io.github.wujun728.oss.template; - -import io.github.wujun728.oss.model.ObjectInfo; -import io.github.wujun728.oss.properties.FileServerProperties; -import com.github.tobato.fastdfs.domain.fdfs.StorePath; -import com.github.tobato.fastdfs.domain.proto.storage.DownloadCallback; -import com.github.tobato.fastdfs.service.FastFileStorageClient; -import lombok.SneakyThrows; -import org.apache.commons.io.FilenameUtils; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.util.StringUtils; -import org.springframework.web.multipart.MultipartFile; - -import javax.annotation.Resource; -import java.io.InputStream; - -/** - * FastDFS配置 - * - */ -@ConditionalOnClass(FastFileStorageClient.class) -@ConditionalOnProperty(prefix = FileServerProperties.PREFIX, name = "type", havingValue = FileServerProperties.TYPE_FDFS) -public class FdfsTemplate { - @Resource - private FileServerProperties fileProperties; - - @Resource - private FastFileStorageClient storageClient; - - @SneakyThrows - public ObjectInfo upload(String objectName, InputStream is) { - return upload(objectName, is, is.available()); - } - - @SneakyThrows - public ObjectInfo upload(MultipartFile file) { - return upload(file.getOriginalFilename(), file.getInputStream(), file.getSize()); - } - - /** - * 上传对象 - * @param objectName 对象名 - * @param is 对象流 - * @param size 大小 - */ - private ObjectInfo upload(String objectName, InputStream is, long size) { - StorePath storePath = storageClient.uploadFile(is, size, FilenameUtils.getExtension(objectName), null); - ObjectInfo obj = new ObjectInfo(); - obj.setObjectPath(storePath.getFullPath()); - obj.setObjectUrl("http://" + fileProperties.getFdfs().getWebUrl() + "/" + storePath.getFullPath()); - return obj; - } - - /** - * 删除对象 - * @param objectPath 对象路径 - */ - public void delete(String objectPath) { - if (!StringUtils.isEmpty(objectPath)) { - StorePath storePath = StorePath.parseFromUrl(objectPath); - storageClient.deleteFile(storePath.getGroup(), storePath.getPath()); - } - } - - /** - * 下载对象 - * @param objectPath 对象路径 - * @param callback 回调 - */ - public T download(String objectPath, DownloadCallback callback) { - if (!StringUtils.isEmpty(objectPath)) { - StorePath storePath = StorePath.parseFromUrl(objectPath); - return storageClient.downloadFile(storePath.getGroup(), storePath.getPath(), callback); - } - return null; - } -} diff --git a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/oss/template/S3Template.java b/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/oss/template/S3Template.java deleted file mode 100644 index ab19db594a..0000000000 --- a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/java/io/github/wujun728/oss/template/S3Template.java +++ /dev/null @@ -1,140 +0,0 @@ -package io.github.wujun728.oss.template; - -import com.amazonaws.ClientConfiguration; -import com.amazonaws.auth.AWSCredentials; -import com.amazonaws.auth.AWSCredentialsProvider; -import com.amazonaws.auth.AWSStaticCredentialsProvider; -import com.amazonaws.auth.BasicAWSCredentials; -import com.amazonaws.client.builder.AwsClientBuilder; -import com.amazonaws.services.s3.AmazonS3; -import com.amazonaws.services.s3.AmazonS3Client; -import com.amazonaws.services.s3.model.ObjectMetadata; -import com.amazonaws.services.s3.model.PutObjectRequest; -import com.amazonaws.services.s3.model.S3Object; -import com.amazonaws.services.s3.model.S3ObjectInputStream; -import com.amazonaws.util.IOUtils; -import io.github.wujun728.oss.model.ObjectInfo; -import io.github.wujun728.oss.properties.FileServerProperties; -import lombok.SneakyThrows; -import org.springframework.beans.factory.InitializingBean; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.web.multipart.MultipartFile; - -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URL; -import java.util.Calendar; - -/** - * aws s3配置 - * - */ -@ConditionalOnClass(AmazonS3.class) -@ConditionalOnProperty(prefix = FileServerProperties.PREFIX, name = "type", havingValue = FileServerProperties.TYPE_S3) -public class S3Template implements InitializingBean { - private static final String DEF_CONTEXT_TYPE = "application/octet-stream"; - private static final String PATH_SPLIT = "/"; - - @Autowired - private FileServerProperties fileProperties; - - private AmazonS3 amazonS3; - - @Override - public void afterPropertiesSet() { - ClientConfiguration config = new ClientConfiguration(); - AwsClientBuilder.EndpointConfiguration endpoint = new AwsClientBuilder.EndpointConfiguration(fileProperties.getS3().getEndpoint(), fileProperties.getS3().getRegion()); - AWSCredentials credentials = new BasicAWSCredentials(fileProperties.getS3().getAccessKey(), fileProperties.getS3().getAccessKeySecret()); - AWSCredentialsProvider awsCredentialsProvider = new AWSStaticCredentialsProvider(credentials); - this.amazonS3 = AmazonS3Client.builder() - .withEndpointConfiguration(endpoint) - .withClientConfiguration(config) - .withCredentials(awsCredentialsProvider) - .withPathStyleAccessEnabled(fileProperties.getS3().getPathStyleAccessEnabled()) - .disableChunkedEncoding() - .build(); - } - - @SneakyThrows - public ObjectInfo upload(String fileName, InputStream is) { - return upload(fileProperties.getS3().getBucketName(), fileName, is, is.available(), DEF_CONTEXT_TYPE); - } - - @SneakyThrows - public ObjectInfo upload(MultipartFile file) { - return upload(fileProperties.getS3().getBucketName(), file.getOriginalFilename(), file.getInputStream() - , ((Long)file.getSize()).intValue(), file.getContentType()); - } - - @SneakyThrows - public ObjectInfo upload(String bucketName, String fileName, InputStream is) { - return upload(bucketName, fileName, is, is.available(), DEF_CONTEXT_TYPE); - } - - /** - * 上传对象 - * @param bucketName bucket名称 - * @param objectName 对象名 - * @param is 对象流 - * @param size 大小 - * @param contentType 类型 - */ - private ObjectInfo upload(String bucketName, String objectName, InputStream is, int size, String contentType) { - ObjectMetadata objectMetadata = new ObjectMetadata(); - objectMetadata.setContentLength(size); - objectMetadata.setContentType(contentType); - PutObjectRequest putObjectRequest = new PutObjectRequest( - bucketName, objectName, is, objectMetadata); - putObjectRequest.getRequestClientOptions().setReadLimit(size + 1); - amazonS3.putObject(putObjectRequest); - - ObjectInfo obj = new ObjectInfo(); - obj.setObjectPath(bucketName + PATH_SPLIT + objectName); - obj.setObjectUrl(fileProperties.getS3().getEndpoint() + PATH_SPLIT + obj.getObjectPath()); - return obj; - } - - public void delete(String objectName) { - delete(fileProperties.getS3().getBucketName(), objectName); - } - - public void delete(String bucketName, String objectName) { - amazonS3.deleteObject(bucketName, objectName); - } - - /** - * 获取预览地址 - * @param bucketName bucket名称 - * @param objectName 对象名 - * @param expires 有效时间(分钟),最大7天有效 - * @return - */ - public String getViewUrl(String bucketName, String objectName, int expires) { - Calendar cal = Calendar.getInstance(); - cal.add(Calendar.MINUTE, expires); - URL url = amazonS3.generatePresignedUrl(bucketName, objectName, cal.getTime()); - return url.toString(); - } - - public void out(String objectName, OutputStream os) { - out(fileProperties.getS3().getBucketName(), objectName, os); - } - - /** - * 输出对象 - * @param bucketName bucket名称 - * @param objectName 对象名 - * @param os 输出流 - */ - @SneakyThrows - public void out(String bucketName, String objectName, OutputStream os) { - S3Object s3Object = amazonS3.getObject(bucketName, objectName); - try ( - S3ObjectInputStream s3is = s3Object.getObjectContent(); - ) { - IOUtils.copy(s3is, os); - } - } -} diff --git a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/resources/META-INF/spring.factories.bk b/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/resources/META-INF/spring.factories.bk deleted file mode 100644 index db41117b8f..0000000000 --- a/jun_springboot_starter/jun-oss-spring-boot-starter/src/main/resources/META-INF/spring.factories.bk +++ /dev/null @@ -1,3 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -io.github.wujun728.oss.config.OssAutoConfigure,\ -io.github.wujun728.file.config.FileAutoConfig \ No newline at end of file diff --git a/jun_springboot_starter/jun-p6spy-spring-boot-starter/.gitignore b/jun_springboot_starter/jun-p6spy-spring-boot-starter/.gitignore deleted file mode 100644 index c3f51279fd..0000000000 --- a/jun_springboot_starter/jun-p6spy-spring-boot-starter/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -/.idea -/target -/*.iml diff --git a/jun_springboot_starter/jun-p6spy-spring-boot-starter/README.md b/jun_springboot_starter/jun-p6spy-spring-boot-starter/README.md deleted file mode 100644 index 792de9f759..0000000000 --- a/jun_springboot_starter/jun-p6spy-spring-boot-starter/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# p6spy-spring-boot-starter -Spring boot application integrates p6spy print logs quickly - -## Quick start - -- 一、Import dependencies -``` - - com.github.klboke - p6spy-spring-boot-starter - 1.0 - -``` -- 二、Configure the application.properties -Configuration starts with "p6spy.config." compatible with p6spy's system properties configuration -``` -spring.datasource.url = jdbc:p6spy:mysql://xxx -spring.datasource.username = xxx -spring.datasource.password = xxx -spring.datasource.driver-class-name = com.p6spy.engine.spy.P6SpyDriver - -p6spy.config.appender = com.p6spy.engine.spy.appender.Slf4JLogger -p6spy.config.logMessageFormat = com.p6spy.engine.spy.appender.CustomLineFormat -p6spy.config.customLogMessageFormat = executionTime:%(executionTime)| 执行sql:%(sqlSingleLine) -``` -> By default import dependency, p6spy auto assembly will take effect, you can turn it off by "p6spy.config.enabled = false" -## Configuration description -- "Spring-configuration-metadata.json" has been added to the configuration description, and IDEA has good configuration tips -- More configurations are available:https://p6spy.readthedocs.io/en/latest/configandusage.html diff --git a/jun_springboot_starter/jun-p6spy-spring-boot-starter/pom.xml b/jun_springboot_starter/jun-p6spy-spring-boot-starter/pom.xml deleted file mode 100644 index 7f2edd03ab..0000000000 --- a/jun_springboot_starter/jun-p6spy-spring-boot-starter/pom.xml +++ /dev/null @@ -1,124 +0,0 @@ - - - 4.0.0 - - com.github.klboke - p6spy-spring-boot-starter - 1.0 - p6spy 的spring boot starter快速装配工程 - - - 2.2.0.RELEASE - UTF-8 - UTF-8 - 1.8 - 3.8.6 - - - - http://www.kailing.pub/ - https://github.com/klboke/p6spy-spring-boot-starter.git - - https://github.com/klboke/p6spy-spring-boot-starter - - - Apache 2 - http://www.apache.org/licenses/LICENSE-2.0.txt - - - - - kl - 632104866@qq.com - http://www.kailing.pub/ - - - - - - p6spy - p6spy - ${p6spy.version} - - - org.springframework.boot - spring-boot-autoconfigure - ${spring-boot.version} - true - - - org.springframework.boot - spring-boot-starter-test - ${spring-boot.version} - test - - - org.springframework.boot - spring-boot-starter-web - ${spring-boot.version} - true - test - - - org.springframework.boot - spring-boot-starter - ${spring-boot.version} - true - test - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.1 - - 1.8 - 1.8 - UTF-8 - - - - org.apache.maven.plugins - maven-source-plugin - - - attach-sources - - jar-no-fork - - - - - - maven-eclipse-plugin - - true - true - - org.eclipse.jdt.launching.JRE_CONTAINER - - - org.springframework.boot:spring-boot-starter-tomcat - - - - - - - - - releases - https://oss.sonatype.org/content/repositories/releases/ - - - snapshots - https://oss.sonatype.org/content/repositories/snapshots/ - - - - diff --git a/jun_springboot_starter/jun-p6spy-spring-boot-starter/src/main/java/com/github/klboke/springboot/autoconfigure/p6spy/P6spyAutoConfiguration.java b/jun_springboot_starter/jun-p6spy-spring-boot-starter/src/main/java/com/github/klboke/springboot/autoconfigure/p6spy/P6spyAutoConfiguration.java deleted file mode 100644 index c2f2f0363b..0000000000 --- a/jun_springboot_starter/jun-p6spy-spring-boot-starter/src/main/java/com/github/klboke/springboot/autoconfigure/p6spy/P6spyAutoConfiguration.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.github.klboke.springboot.autoconfigure.p6spy; - -import com.p6spy.engine.spy.option.SystemProperties; -import org.springframework.boot.ApplicationArguments; -import org.springframework.boot.ApplicationRunner; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Configuration; -import com.p6spy.engine.spy.*; -import org.springframework.core.env.Environment; - -import java.lang.reflect.Field; -import java.util.Map; - -/** - * @author: kl @kailing.pub - * @date: 2019/11/13 - */ -@Configuration(proxyBeanMethods = false) -@ConditionalOnClass(P6SpyDriver.class) -@EnableConfigurationProperties(P6spyProperties.class) -@ConditionalOnProperty(prefix = P6spyProperties.P6SPY_CONFIG_PREFIX, name = "enabled", havingValue = "true",matchIfMissing = true) -public class P6spyAutoConfiguration implements ApplicationRunner { - - private final Environment environment; - - public P6spyAutoConfiguration(Environment environment) { - this.environment = environment; - } - - @Override - public void run(ApplicationArguments args) { - P6spyAutoConfiguration.p6spyReload(environment); - } - - public static void p6spyReload(Environment p6spyProperties) { - Map defaults = P6SpyOptions.getActiveInstance().getDefaults(); - Field[] fields = P6spyProperties.class.getDeclaredFields(); - for (Field field : fields) { - String fieldName = field.getName(); - String propertiesName = SystemProperties.P6SPY_PREFIX.concat(fieldName); - if (p6spyProperties.containsProperty(propertiesName)) { - String systemPropertyValue = p6spyProperties.getProperty(propertiesName, defaults.get(fieldName)); - defaults.put(fieldName, systemPropertyValue); - } - } - P6SpyOptions.getActiveInstance().load(defaults); - P6ModuleManager.getInstance().reload(); - } -} - diff --git a/jun_springboot_starter/jun-p6spy-spring-boot-starter/src/main/java/com/github/klboke/springboot/autoconfigure/p6spy/P6spyProperties.java b/jun_springboot_starter/jun-p6spy-spring-boot-starter/src/main/java/com/github/klboke/springboot/autoconfigure/p6spy/P6spyProperties.java deleted file mode 100644 index 0ac06a5535..0000000000 --- a/jun_springboot_starter/jun-p6spy-spring-boot-starter/src/main/java/com/github/klboke/springboot/autoconfigure/p6spy/P6spyProperties.java +++ /dev/null @@ -1,462 +0,0 @@ -package com.github.klboke.springboot.autoconfigure.p6spy; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -import static com.github.klboke.springboot.autoconfigure.p6spy.P6spyProperties.P6SPY_CONFIG_PREFIX; - -/** - * @author: kl @kailing.pub - * @date: 2019/11/13 - */ -@ConfigurationProperties(prefix = P6SPY_CONFIG_PREFIX) -public class P6spyProperties { - - public static final String P6SPY_CONFIG_PREFIX= "p6spy.config"; - /** - * # for flushing per statement - * # (default is false) - */ - private String autoflush; - /** - * # A comma separated list of JDBC drivers to load and register. - * # (default is empty) - * # - * # Note: This is normally only needed when using P6Spy in an - * # application server environment with a JNDI data source or when - * # using a JDBC driver that does not implement the JDBC 4.0 API - * # (specifically automatic registration). - */ - private String driverlist; - /** - * # name of logfile to use, note Windows users should make sure to use forward slashes in their pathname (e:/test/spy.log) - * # (used for com.p6spy.engine.spy.appender.FileLogger only) - * # (default is spy.log) - */ - private String logfile; - /** - * # class to use for formatting log messages (default is: com.p6spy.engine.spy.appender.SingleLineFormat) - */ - private String logMessageFormat; - /** - * # append to the p6spy log file. if this is set to false the - * # log file is truncated every time. (file logger only) - * # (default is true) - */ - private String append; - /** - * # sets the date format using Java's SimpleDateFormat routine. - * # In case property is not set, milliseconds since 1.1.1970 (unix time) is used (default - */ - private String dateformat; - /** - * # specifies the appender to use for logging - * # Please note: reload means forgetting all the previously set - * # settings (even those set during runtime - via JMX) - * # and starting with the clean table - * # (only the properties read from the configuration file) - * # (default is com.p6spy.engine.spy.appender.FileLogger) - * #appender=com.p6spy.engine.spy.appender.Slf4JLogger - * #appender=com.p6spy.engine.spy.appender.StdoutLogger - * #appender=com.p6spy.engine.spy.appender.FileLogger - */ - private String appender; - /** - * # Module list adapts the modular functionality of P6Spy. - * # Only modules listed are active. - * # (default is com.p6spy.engine.logging.P6LogFactory and - * # com.p6spy.engine.spy.P6SpyFactory) - * # Please note that the core module (P6SpyFactory) can't be - * # deactivated. - * # Unlike the other properties, activation of the changes on - * # this one requires reload. - */ - private String modulelist; - /** - * # prints a stack trace for every statement logged - */ - private String stacktrace; - /** - * # if stacktrace=true, specifies the stack trace to print - */ - private String stacktraceclass; - - /** - * # determines if property file should be reloaded - * # Please note: reload means forgetting all the previously set - * # settings (even those set during runtime - via JMX) - * # and starting with the clean table - * # (default is false) - * #reloadproperties=false - */ - private String reloadproperties; - /** - * # determines how often should be reloaded in seconds - * # (default is 60) - * #reloadpropertiesinterval=60 - */ - private String reloadpropertiesinterval; - /** - * # JNDI DataSource lookup # - * # # - * # If you are using the DataSource support outside of an app # - * # server, you will probably need to define the JNDI Context # - * # environment. # - * # # - * # If the P6Spy code will be executing inside an app server then # - * # do not use these properties, and the DataSource lookup will # - * # use the naming context defined by the app server. # - * # # - * # The two standard elements of the naming environment are # - * # jndicontextfactory and jndicontextproviderurl. If you need # - * # additional elements, use the jndicontextcustom property. # - * # You can define multiple properties in jndicontextcustom, # - * # in name value pairs. Separate the name and value with a # - * # semicolon, and separate the pairs with commas. # - * # # - * # The example shown here is for a standalone program running on # - * # a machine that is also running JBoss, so the JNDI context # - * # is configured for JBoss (3.0.4). # - * # # - * # (by default all these are empty) # - * ################################################################# - * #jndicontextfactory=org.jnp.interfaces.NamingContextFactory - * #jndicontextproviderurl=localhost:1099 - * #jndicontextcustom=java.naming.factory.url.pkgs;org.jboss.naming:org.jnp.interfaces - */ - private String jndicontextfactory; - /** - * # JNDI DataSource lookup # - * # # - * # If you are using the DataSource support outside of an app # - * # server, you will probably need to define the JNDI Context # - * # environment. # - * # # - * # If the P6Spy code will be executing inside an app server then # - * # do not use these properties, and the DataSource lookup will # - * # use the naming context defined by the app server. # - * # # - * # The two standard elements of the naming environment are # - * # jndicontextfactory and jndicontextproviderurl. If you need # - * # additional elements, use the jndicontextcustom property. # - * # You can define multiple properties in jndicontextcustom, # - * # in name value pairs. Separate the name and value with a # - * # semicolon, and separate the pairs with commas. # - * # # - * # The example shown here is for a standalone program running on # - * # a machine that is also running JBoss, so the JNDI context # - * # is configured for JBoss (3.0.4). # - * # # - * # (by default all these are empty) # - * ################################################################# - * #jndicontextfactory=org.jnp.interfaces.NamingContextFactory - * #jndicontextproviderurl=localhost:1099 - * #jndicontextcustom=java.naming.factory.url.pkgs;org.jboss.naming:org.jnp.interfaces - */ - private String jndicontextproviderurl; - /** - * # JNDI DataSource lookup # - * # # - * # If you are using the DataSource support outside of an app # - * # server, you will probably need to define the JNDI Context # - * # environment. # - * # # - * # If the P6Spy code will be executing inside an app server then # - * # do not use these properties, and the DataSource lookup will # - * # use the naming context defined by the app server. # - * # # - * # The two standard elements of the naming environment are # - * # jndicontextfactory and jndicontextproviderurl. If you need # - * # additional elements, use the jndicontextcustom property. # - * # You can define multiple properties in jndicontextcustom, # - * # in name value pairs. Separate the name and value with a # - * # semicolon, and separate the pairs with commas. # - * # # - * # The example shown here is for a standalone program running on # - * # a machine that is also running JBoss, so the JNDI context # - * # is configured for JBoss (3.0.4). # - * # # - * # (by default all these are empty) # - * ################################################################# - * #jndicontextfactory=org.jnp.interfaces.NamingContextFactory - * #jndicontextproviderurl=localhost:1099 - * #jndicontextcustom=java.naming.factory.url.pkgs;org.jboss.naming:org.jnp.interfaces - */ - private String jndicontextcustom; - /** - * # DataSource replacement # - * # # - * # Replace the real DataSource class in your application server # - * # configuration with the name com.p6spy.engine.spy.P6DataSource # - * # (that provides also connection pooling and xa support). # - * # then add the JNDI name and class name of the real # - * # DataSource here # - * # # - * # Values set in this item cannot be reloaded using the # - * # reloadproperties variable. Once it is loaded, it remains # - * # in memory until the application is restarted. # - * # # - * ################################################################# - * #realdatasource=/RealMySqlDS - */ - private String realdatasource; - /** - * #realdatasourceclass=com.mysql.jdbc.jdbc2.optional.MysqlDataSource - */ - private String realdatasourceclass; - /** - * # DataSource properties # - * # # - * # If you are using the DataSource support to intercept calls # - * # to a DataSource that requires properties for proper setup, # - * # define those properties here. Use name value pairs, separate # - * # the name and value with a semicolon, and separate the # - * # pairs with commas. # - * # # - * # The example shown here is for mysql # - * # # - * ################################################################# - * #realdatasourceproperties=port;3306,serverName;myhost,databaseName;jbossdb,foo;bar - */ - private String realdatasourceproperties; - /** - * # Custom log message format used ONLY IF logMessageFormat is set to com.p6spy.engine.spy.appender.CustomLineFormat - * # default is %(currentTime)|%(executionTime)|%(category)|connection%(connectionId)|%(sqlSingleLine) - * # Available placeholders are: - * # %(connectionId) the id of the connection - * # %(currentTime) the current time expressing in milliseconds - * # %(executionTime) the time in milliseconds that the operation took to complete - * # %(category) the category of the operation - * # %(effectiveSql) the SQL statement as submitted to the driver - * # %(effectiveSqlSingleLine) the SQL statement as submitted to the driver, with all new lines removed - * # %(sql) the SQL statement with all bind variables replaced with actual values - * # %(sqlSingleLine) the SQL statement with all bind variables replaced with actual values, with all new lines removed - * #customLogMessageFormat=%(currentTime)|%(executionTime)|%(category)|connection%(connectionId)|%(sqlSingleLine) - */ - private String customLogMessageFormat; - /** - * # format that is used for logging of the java.util.Date implementations (has to be compatible with java.text.SimpleDateFormat) - * # (default is yyyy-MM-dd'T'HH:mm:ss.SSSZ) - * #databaseDialectDateFormat=yyyy-MM-dd'T'HH:mm:ss.SSSZ - */ - private String databaseDialectDateFormat; - /** - * # format that is used for logging of the java.sql.Timestamp implementations (has to be compatible with java.text.SimpleDateFormat) - * # (default is yyyy-MM-dd'T'HH:mm:ss.SSSZ) - * #databaseDialectTimestampFormat=yyyy-MM-dd'T'HH:mm:ss.SSSZ - */ - private String databaseDialectTimestampFormat; - /** - * # format that is used for logging booleans, possible values: boolean, numeric - * # (default is boolean) - * #databaseDialectBooleanFormat=boolean - */ - private String databaseDialectBooleanFormat; - /** - * # whether to expose options via JMX or not - * # (default is true) - * #jmx=true - */ - private String jmx; - /** - * # if exposing options via jmx (see option: jmx), what should be the prefix used? - * # jmx naming pattern constructed is: com.p6spy(.)?:name= - * # please note, if there is already such a name in use it would be unregistered first (the last registered wins) - * # (default is none) - * #jmxPrefix= - */ - private String jmxPrefix; - - - public String getAutoflush() { - return autoflush; - } - - public void setAutoflush(String autoflush) { - this.autoflush = autoflush; - } - - public String getDriverlist() { - return driverlist; - } - - public void setDriverlist(String driverlist) { - this.driverlist = driverlist; - } - - public String getLogfile() { - return logfile; - } - - public void setLogfile(String logfile) { - this.logfile = logfile; - } - - public String getLogMessageFormat() { - return logMessageFormat; - } - - public void setLogMessageFormat(String logMessageFormat) { - this.logMessageFormat = logMessageFormat; - } - - public String getAppend() { - return append; - } - - public void setAppend(String append) { - this.append = append; - } - - public String getDateformat() { - return dateformat; - } - - public void setDateformat(String dateformat) { - this.dateformat = dateformat; - } - - public String getAppender() { - return appender; - } - - public void setAppender(String appender) { - this.appender = appender; - } - - public String getModulelist() { - return modulelist; - } - - public void setModulelist(String modulelist) { - this.modulelist = modulelist; - } - - public String getStacktrace() { - return stacktrace; - } - - public void setStacktrace(String stacktrace) { - this.stacktrace = stacktrace; - } - - public String getStacktraceclass() { - return stacktraceclass; - } - - public void setStacktraceclass(String stacktraceclass) { - this.stacktraceclass = stacktraceclass; - } - - public String getReloadproperties() { - return reloadproperties; - } - - public void setReloadproperties(String reloadproperties) { - this.reloadproperties = reloadproperties; - } - - public String getReloadpropertiesinterval() { - return reloadpropertiesinterval; - } - - public void setReloadpropertiesinterval(String reloadpropertiesinterval) { - this.reloadpropertiesinterval = reloadpropertiesinterval; - } - - public String getJndicontextfactory() { - return jndicontextfactory; - } - - public void setJndicontextfactory(String jndicontextfactory) { - this.jndicontextfactory = jndicontextfactory; - } - - public String getJndicontextproviderurl() { - return jndicontextproviderurl; - } - - public void setJndicontextproviderurl(String jndicontextproviderurl) { - this.jndicontextproviderurl = jndicontextproviderurl; - } - - public String getJndicontextcustom() { - return jndicontextcustom; - } - - public void setJndicontextcustom(String jndicontextcustom) { - this.jndicontextcustom = jndicontextcustom; - } - - public String getRealdatasource() { - return realdatasource; - } - - public void setRealdatasource(String realdatasource) { - this.realdatasource = realdatasource; - } - - public String getRealdatasourceclass() { - return realdatasourceclass; - } - - public void setRealdatasourceclass(String realdatasourceclass) { - this.realdatasourceclass = realdatasourceclass; - } - - public String getRealdatasourceproperties() { - return realdatasourceproperties; - } - - public void setRealdatasourceproperties(String realdatasourceproperties) { - this.realdatasourceproperties = realdatasourceproperties; - } - - public String getCustomLogMessageFormat() { - return customLogMessageFormat; - } - - public void setCustomLogMessageFormat(String customLogMessageFormat) { - this.customLogMessageFormat = customLogMessageFormat; - } - - public String getDatabaseDialectDateFormat() { - return databaseDialectDateFormat; - } - - public void setDatabaseDialectDateFormat(String databaseDialectDateFormat) { - this.databaseDialectDateFormat = databaseDialectDateFormat; - } - - public String getDatabaseDialectTimestampFormat() { - return databaseDialectTimestampFormat; - } - - public void setDatabaseDialectTimestampFormat(String databaseDialectTimestampFormat) { - this.databaseDialectTimestampFormat = databaseDialectTimestampFormat; - } - - public String getDatabaseDialectBooleanFormat() { - return databaseDialectBooleanFormat; - } - - public void setDatabaseDialectBooleanFormat(String databaseDialectBooleanFormat) { - this.databaseDialectBooleanFormat = databaseDialectBooleanFormat; - } - - public String getJmx() { - return jmx; - } - - public void setJmx(String jmx) { - this.jmx = jmx; - } - - public String getJmxPrefix() { - return jmxPrefix; - } - - public void setJmxPrefix(String jmxPrefix) { - this.jmxPrefix = jmxPrefix; - } - -} diff --git a/jun_springboot_starter/jun-p6spy-spring-boot-starter/src/main/resources/META-INF/spring-configuration-metadata.json b/jun_springboot_starter/jun-p6spy-spring-boot-starter/src/main/resources/META-INF/spring-configuration-metadata.json deleted file mode 100644 index fe442bc8bb..0000000000 --- a/jun_springboot_starter/jun-p6spy-spring-boot-starter/src/main/resources/META-INF/spring-configuration-metadata.json +++ /dev/null @@ -1,161 +0,0 @@ -{ - "groups": [ - { - "name": "p6spy.config", - "type": "com.github.klboke.springboot.autoconfigure.p6spy.P6spyProperties", - "sourceType": "com.github.klboke.springboot.autoconfigure.p6spy.P6spyProperties" - } - ], - "properties": [ - { - "name": "p6spy.config.append", - "type": "java.lang.String", - "description": "# append to the p6spy log file. if this is set to false the # log file is truncated every time. (file logger only) # (default is true)", - "sourceType": "com.github.klboke.springboot.autoconfigure.p6spy.P6spyProperties" - }, - { - "name": "p6spy.config.enabled", - "type": "java.lang.Boolean", - "description": "Whether to enable p6spy" - }, - { - "name": "p6spy.config.appender", - "type": "java.lang.String", - "description": "# specifies the appender to use for logging # Please note: reload means forgetting all the previously set # settings (even those set during runtime - via JMX) # and starting with the clean table # (only the properties read from the configuration file) # (default is com.p6spy.engine.spy.appender.FileLogger) #appender=com.p6spy.engine.spy.appender.Slf4JLogger #appender=com.p6spy.engine.spy.appender.StdoutLogger #appender=com.p6spy.engine.spy.appender.FileLogger", - "sourceType": "com.github.klboke.springboot.autoconfigure.p6spy.P6spyProperties" - }, - { - "name": "p6spy.config.autoflush", - "type": "java.lang.String", - "description": "# for flushing per statement # (default is false)", - "sourceType": "com.github.klboke.springboot.autoconfigure.p6spy.P6spyProperties" - }, - { - "name": "p6spy.config.customLogMessageFormat", - "type": "java.lang.String", - "description": "# Custom log message format used ONLY IF logMessageFormat is set to com.p6spy.engine.spy.appender.CustomLineFormat # default is %(currentTime)|%(executionTime)|%(category)|connection%(connectionId)|%(sqlSingleLine) # Available placeholders are: # %(connectionId) the id of the connection # %(currentTime) the current time expressing in milliseconds # %(executionTime) the time in milliseconds that the operation took to complete # %(category) the category of the operation # %(effectiveSql) the SQL statement as submitted to the driver # %(effectiveSqlSingleLine) the SQL statement as submitted to the driver, with all new lines removed # %(sql) the SQL statement with all bind variables replaced with actual values # %(sqlSingleLine) the SQL statement with all bind variables replaced with actual values, with all new lines removed #customLogMessageFormat=%(currentTime)|%(executionTime)|%(category)|connection%(connectionId)|%(sqlSingleLine)", - "sourceType": "com.github.klboke.springboot.autoconfigure.p6spy.P6spyProperties" - }, - { - "name": "p6spy.config.databaseDialectBooleanFormat", - "type": "java.lang.String", - "description": "# format that is used for logging booleans, possible values: boolean, numeric # (default is boolean) #databaseDialectBooleanFormat=boolean", - "sourceType": "com.github.klboke.springboot.autoconfigure.p6spy.P6spyProperties" - }, - { - "name": "p6spy.config.databaseDialectDateFormat", - "type": "java.lang.String", - "description": "# format that is used for logging of the java.util.Date implementations (has to be compatible with java.text.SimpleDateFormat) # (default is yyyy-MM-dd'T'HH:mm:ss.SSSZ) #databaseDialectDateFormat=yyyy-MM-dd'T'HH:mm:ss.SSSZ", - "sourceType": "com.github.klboke.springboot.autoconfigure.p6spy.P6spyProperties" - }, - { - "name": "p6spy.config.databaseDialectTimestampFormat", - "type": "java.lang.String", - "description": "# format that is used for logging of the java.sql.Timestamp implementations (has to be compatible with java.text.SimpleDateFormat) # (default is yyyy-MM-dd'T'HH:mm:ss.SSSZ) #databaseDialectTimestampFormat=yyyy-MM-dd'T'HH:mm:ss.SSSZ", - "sourceType": "com.github.klboke.springboot.autoconfigure.p6spy.P6spyProperties" - }, - { - "name": "p6spy.config.dateformat", - "type": "java.lang.String", - "description": "# sets the date format using Java's SimpleDateFormat routine. # In case property is not set, milliseconds since 1.1.1970 (unix time) is used (default", - "sourceType": "com.github.klboke.springboot.autoconfigure.p6spy.P6spyProperties" - }, - { - "name": "p6spy.config.driverlist", - "type": "java.lang.String", - "description": "# A comma separated list of JDBC drivers to load and register. # (default is empty) # # Note: This is normally only needed when using P6Spy in an # application server environment with a JNDI data source or when # using a JDBC driver that does not implement the JDBC 4.0 API # (specifically automatic registration).", - "sourceType": "com.github.klboke.springboot.autoconfigure.p6spy.P6spyProperties" - }, - { - "name": "p6spy.config.jmx", - "type": "java.lang.String", - "description": "# whether to expose options via JMX or not # (default is true) #jmx=true", - "sourceType": "com.github.klboke.springboot.autoconfigure.p6spy.P6spyProperties" - }, - { - "name": "p6spy.config.jmxPrefix", - "type": "java.lang.String", - "description": "# if exposing options via jmx (see option: jmx), what should be the prefix used? # jmx naming pattern constructed is: com.p6spy(.)?:name= # please note, if there is already such a name in use it would be unregistered first (the last registered wins) # (default is none) #jmxPrefix=", - "sourceType": "com.github.klboke.springboot.autoconfigure.p6spy.P6spyProperties" - }, - { - "name": "p6spy.config.jndicontextcustom", - "type": "java.lang.String", - "description": "# JNDI DataSource lookup # # # # If you are using the DataSource support outside of an app # # server, you will probably need to define the JNDI Context # # environment. # # # # If the P6Spy code will be executing inside an app server then # # do not use these properties, and the DataSource lookup will # # use the naming context defined by the app server. # # # # The two standard elements of the naming environment are # # jndicontextfactory and jndicontextproviderurl. If you need # # additional elements, use the jndicontextcustom property. # # You can define multiple properties in jndicontextcustom, # # in name value pairs. Separate the name and value with a # # semicolon, and separate the pairs with commas. # # # # The example shown here is for a standalone program running on # # a machine that is also running JBoss, so the JNDI context # # is configured for JBoss (3.0.4). # # # # (by default all these are empty) # ################################################################# #jndicontextfactory=org.jnp.interfaces.NamingContextFactory #jndicontextproviderurl=localhost:1099 #jndicontextcustom=java.naming.factory.url.pkgs;org.jboss.naming:org.jnp.interfaces", - "sourceType": "com.github.klboke.springboot.autoconfigure.p6spy.P6spyProperties" - }, - { - "name": "p6spy.config.jndicontextfactory", - "type": "java.lang.String", - "description": "# JNDI DataSource lookup # # # # If you are using the DataSource support outside of an app # # server, you will probably need to define the JNDI Context # # environment. # # # # If the P6Spy code will be executing inside an app server then # # do not use these properties, and the DataSource lookup will # # use the naming context defined by the app server. # # # # The two standard elements of the naming environment are # # jndicontextfactory and jndicontextproviderurl. If you need # # additional elements, use the jndicontextcustom property. # # You can define multiple properties in jndicontextcustom, # # in name value pairs. Separate the name and value with a # # semicolon, and separate the pairs with commas. # # # # The example shown here is for a standalone program running on # # a machine that is also running JBoss, so the JNDI context # # is configured for JBoss (3.0.4). # # # # (by default all these are empty) # ################################################################# #jndicontextfactory=org.jnp.interfaces.NamingContextFactory #jndicontextproviderurl=localhost:1099 #jndicontextcustom=java.naming.factory.url.pkgs;org.jboss.naming:org.jnp.interfaces", - "sourceType": "com.github.klboke.springboot.autoconfigure.p6spy.P6spyProperties" - }, - { - "name": "p6spy.config.jndicontextproviderurl", - "type": "java.lang.String", - "description": "# JNDI DataSource lookup # # # # If you are using the DataSource support outside of an app # # server, you will probably need to define the JNDI Context # # environment. # # # # If the P6Spy code will be executing inside an app server then # # do not use these properties, and the DataSource lookup will # # use the naming context defined by the app server. # # # # The two standard elements of the naming environment are # # jndicontextfactory and jndicontextproviderurl. If you need # # additional elements, use the jndicontextcustom property. # # You can define multiple properties in jndicontextcustom, # # in name value pairs. Separate the name and value with a # # semicolon, and separate the pairs with commas. # # # # The example shown here is for a standalone program running on # # a machine that is also running JBoss, so the JNDI context # # is configured for JBoss (3.0.4). # # # # (by default all these are empty) # ################################################################# #jndicontextfactory=org.jnp.interfaces.NamingContextFactory #jndicontextproviderurl=localhost:1099 #jndicontextcustom=java.naming.factory.url.pkgs;org.jboss.naming:org.jnp.interfaces", - "sourceType": "com.github.klboke.springboot.autoconfigure.p6spy.P6spyProperties" - }, - { - "name": "p6spy.config.logMessageFormat", - "type": "java.lang.String", - "description": "# class to use for formatting log messages (default is: com.p6spy.engine.spy.appender.SingleLineFormat)", - "sourceType": "com.github.klboke.springboot.autoconfigure.p6spy.P6spyProperties" - }, - { - "name": "p6spy.config.logfile", - "type": "java.lang.String", - "description": "# name of logfile to use, note Windows users should make sure to use forward slashes in their pathname (e:\/test\/spy.log) # (used for com.p6spy.engine.spy.appender.FileLogger only) # (default is spy.log)", - "sourceType": "com.github.klboke.springboot.autoconfigure.p6spy.P6spyProperties" - }, - { - "name": "p6spy.config.modulelist", - "type": "java.lang.String", - "description": "# Module list adapts the modular functionality of P6Spy. # Only modules listed are active. # (default is com.p6spy.engine.logging.P6LogFactory and # com.p6spy.engine.spy.P6SpyFactory) # Please note that the core module (P6SpyFactory) can't be # deactivated. # Unlike the other properties, activation of the changes on # this one requires reload.", - "sourceType": "com.github.klboke.springboot.autoconfigure.p6spy.P6spyProperties" - }, - { - "name": "p6spy.config.realdatasource", - "type": "java.lang.String", - "description": "# DataSource replacement # # # # Replace the real DataSource class in your application server # # configuration with the name com.p6spy.engine.spy.P6DataSource # # (that provides also connection pooling and xa support). # # then add the JNDI name and class name of the real # # DataSource here # # # # Values set in this item cannot be reloaded using the # # reloadproperties variable. Once it is loaded, it remains # # in memory until the application is restarted. # # # ################################################################# #realdatasource=\/RealMySqlDS", - "sourceType": "com.github.klboke.springboot.autoconfigure.p6spy.P6spyProperties" - }, - { - "name": "p6spy.config.realdatasourceclass", - "type": "java.lang.String", - "description": "#realdatasourceclass=com.mysql.jdbc.jdbc2.optional.MysqlDataSource", - "sourceType": "com.github.klboke.springboot.autoconfigure.p6spy.P6spyProperties" - }, - { - "name": "p6spy.config.realdatasourceproperties", - "type": "java.lang.String", - "description": "# DataSource properties # # # # If you are using the DataSource support to intercept calls # # to a DataSource that requires properties for proper setup, # # define those properties here. Use name value pairs, separate # # the name and value with a semicolon, and separate the # # pairs with commas. # # # # The example shown here is for mysql # # # ################################################################# #realdatasourceproperties=port;3306,serverName;myhost,databaseName;jbossdb,foo;bar", - "sourceType": "com.github.klboke.springboot.autoconfigure.p6spy.P6spyProperties" - }, - { - "name": "p6spy.config.reloadproperties", - "type": "java.lang.String", - "description": "# determines if property file should be reloaded # Please note: reload means forgetting all the previously set # settings (even those set during runtime - via JMX) # and starting with the clean table # (default is false) #reloadproperties=false", - "sourceType": "com.github.klboke.springboot.autoconfigure.p6spy.P6spyProperties" - }, - { - "name": "p6spy.config.reloadpropertiesinterval", - "type": "java.lang.String", - "description": "# determines how often should be reloaded in seconds # (default is 60) #reloadpropertiesinterval=60", - "sourceType": "com.github.klboke.springboot.autoconfigure.p6spy.P6spyProperties" - }, - { - "name": "p6spy.config.stacktrace", - "type": "java.lang.String", - "description": "# prints a stack trace for every statement logged", - "sourceType": "com.github.klboke.springboot.autoconfigure.p6spy.P6spyProperties" - }, - { - "name": "p6spy.config.stacktraceclass", - "type": "java.lang.String", - "description": "# if stacktrace=true, specifies the stack trace to print", - "sourceType": "com.github.klboke.springboot.autoconfigure.p6spy.P6spyProperties" - } - ], - "hints": [] -} diff --git a/jun_springboot_starter/jun-p6spy-spring-boot-starter/src/main/resources/META-INF/spring.factories b/jun_springboot_starter/jun-p6spy-spring-boot-starter/src/main/resources/META-INF/spring.factories deleted file mode 100644 index a74fe02782..0000000000 --- a/jun_springboot_starter/jun-p6spy-spring-boot-starter/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,3 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -com.github.klboke.springboot.autoconfigure.p6spy.P6spyAutoConfiguration - diff --git a/jun_springboot_starter/jun-redis-spring-boot-starter/pom.xml b/jun_springboot_starter/jun-redis-spring-boot-starter/pom.xml deleted file mode 100644 index ce6e848a98..0000000000 --- a/jun_springboot_starter/jun-redis-spring-boot-starter/pom.xml +++ /dev/null @@ -1,78 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun-redis-spring-boot-starter - 1.0.25 - jar - redis通用组件 - - - 1.8 - UTF-8 - 1.8 - 1.8 - 1.0.25 - 2.5.14 - 2020.0.6 - 3.16.1 - 2.7 - 2.3.2 - - - - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - - - - io.github.wujun728 - jun-common-base - ${jun.version} - - - - org.redisson - redisson-spring-boot-starter - ${redisson.version} - - - - commons-io - commons-io - ${commons-io.version} - - - - org.apache.commons - commons-pool2 - - - - org.springframework.boot - spring-boot-configuration-processor - true - - - net.dreamlu - mica-auto - ${mica-auto.version} - - - diff --git a/jun_springboot_starter/jun-redis-spring-boot-starter/src/main/java/io/github/wujun728/common/redis/RedisAutoConfigure.java b/jun_springboot_starter/jun-redis-spring-boot-starter/src/main/java/io/github/wujun728/common/redis/RedisAutoConfigure.java deleted file mode 100644 index ed2d5da9af..0000000000 --- a/jun_springboot_starter/jun-redis-spring-boot-starter/src/main/java/io/github/wujun728/common/redis/RedisAutoConfigure.java +++ /dev/null @@ -1,102 +0,0 @@ -package io.github.wujun728.common.redis; - -import io.github.wujun728.common.redis.properties.CacheManagerProperties; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.cache.interceptor.KeyGenerator; -import org.springframework.boot.autoconfigure.data.redis.RedisProperties; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.cache.CacheManager; -import org.springframework.cache.annotation.EnableCaching; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Primary; -import org.springframework.data.redis.cache.RedisCacheConfiguration; -import org.springframework.data.redis.cache.RedisCacheManager; -import org.springframework.data.redis.connection.RedisConnectionFactory; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.serializer.*; - -import java.time.Duration; -import java.util.HashMap; -import java.util.Map; - -/** - * redis 配置类 - * - */ -@EnableConfigurationProperties({RedisProperties.class, CacheManagerProperties.class}) -@EnableCaching -public class RedisAutoConfigure { - @Autowired - private CacheManagerProperties cacheManagerProperties; - - @Bean - public RedisSerializer redisKeySerializer() { - return RedisSerializer.string(); - } - - @Bean - public RedisSerializer redisValueSerializer() { - return RedisSerializer.json(); - } - - /** - * RedisTemplate配置 - * @param factory - */ - @Bean - public RedisTemplate redisTemplate(RedisConnectionFactory factory - , RedisSerializer redisKeySerializer, RedisSerializer redisValueSerializer) { - RedisTemplate redisTemplate = new RedisTemplate<>(); - redisTemplate.setConnectionFactory(factory); - - redisTemplate.setDefaultSerializer(redisValueSerializer); - redisTemplate.setKeySerializer(redisKeySerializer); - redisTemplate.setHashKeySerializer(redisKeySerializer); - redisTemplate.afterPropertiesSet(); - return redisTemplate; - } - - @Bean(name = "cacheManager") - @Primary - public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory - , RedisSerializer redisKeySerializer, RedisSerializer redisValueSerializer) { - RedisCacheConfiguration difConf = getDefConf(redisKeySerializer, redisValueSerializer).entryTtl(Duration.ofHours(1)); - - //自定义的缓存过期时间配置 - int configSize = cacheManagerProperties.getConfigs() == null ? 0 : cacheManagerProperties.getConfigs().size(); - Map redisCacheConfigurationMap = new HashMap<>(configSize); - if (configSize > 0) { - cacheManagerProperties.getConfigs().forEach(e -> { - RedisCacheConfiguration conf = getDefConf(redisKeySerializer, redisValueSerializer).entryTtl(Duration.ofSeconds(e.getSecond())); - redisCacheConfigurationMap.put(e.getKey(), conf); - }); - } - - return RedisCacheManager.builder(redisConnectionFactory) - .cacheDefaults(difConf) - .withInitialCacheConfigurations(redisCacheConfigurationMap) - .build(); - } - - @Bean - public KeyGenerator keyGenerator() { - return (target, method, objects) -> { - StringBuilder sb = new StringBuilder(); - sb.append(target.getClass().getName()); - sb.append(":" + method.getName() + ":"); - for (Object obj : objects) { - sb.append(obj.toString()); - } - return sb.toString(); - }; - } - - private RedisCacheConfiguration getDefConf(RedisSerializer redisKeySerializer, RedisSerializer redisValueSerializer) { - return RedisCacheConfiguration.defaultCacheConfig() - .disableCachingNullValues() - .computePrefixWith(cacheName -> "cache".concat(":").concat(cacheName).concat(":")) - .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisKeySerializer)) - .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisValueSerializer)); - } -} diff --git a/jun_springboot_starter/jun-redis-spring-boot-starter/src/main/java/io/github/wujun728/common/redis/constant/RedisToolsConstant.java b/jun_springboot_starter/jun-redis-spring-boot-starter/src/main/java/io/github/wujun728/common/redis/constant/RedisToolsConstant.java deleted file mode 100644 index 7e665e4098..0000000000 --- a/jun_springboot_starter/jun-redis-spring-boot-starter/src/main/java/io/github/wujun728/common/redis/constant/RedisToolsConstant.java +++ /dev/null @@ -1,20 +0,0 @@ -package io.github.wujun728.common.redis.constant; - -/** - * redis 工具常量 - * - */ -public class RedisToolsConstant { - private RedisToolsConstant() { - throw new IllegalStateException("Utility class"); - } - /** - * single Redis - */ - public final static int SINGLE = 1 ; - - /** - * Redis cluster - */ - public final static int CLUSTER = 2 ; -} diff --git a/jun_springboot_starter/jun-redis-spring-boot-starter/src/main/java/io/github/wujun728/common/redis/lock/RedisDistributedLock.java b/jun_springboot_starter/jun-redis-spring-boot-starter/src/main/java/io/github/wujun728/common/redis/lock/RedisDistributedLock.java deleted file mode 100644 index b091a56d39..0000000000 --- a/jun_springboot_starter/jun-redis-spring-boot-starter/src/main/java/io/github/wujun728/common/redis/lock/RedisDistributedLock.java +++ /dev/null @@ -1,114 +0,0 @@ -package io.github.wujun728.common.redis.lock; - -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.data.redis.connection.RedisStringCommands; -import org.springframework.data.redis.connection.ReturnType; -import org.springframework.data.redis.core.RedisCallback; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.core.types.Expiration; - -import java.util.UUID; -import java.util.concurrent.TimeUnit; - -/** - * redis分布式锁实现 - * - * @deprecated 建议使用Redisson的实现方式 {@link RedissonDistributedLock} - */ -@Slf4j -@ConditionalOnClass(RedisTemplate.class) -@Deprecated -public class RedisDistributedLock { - @Autowired - private RedisTemplate redisTemplate; - - private ThreadLocal lockFlag = new ThreadLocal<>(); - - private static final String UNLOCK_LUA; - - /* - * 通过lua脚本释放锁,来达到释放锁的原子操作 - */ - static { - UNLOCK_LUA = "if redis.call(\"get\",KEYS[1]) == ARGV[1] " + - "then " + - " return redis.call(\"del\",KEYS[1]) " + - "else " + - " return 0 " + - "end "; - } - - public RedisDistributedLock(RedisTemplate redisTemplate) { - super(); - this.redisTemplate = redisTemplate; - } - - /** - * 获取锁 - * - * @param key 锁的key - * @param expire 获取锁超时时间 - * @param retryTimes 重试次数 - * @param sleepMillis 获取锁失败的重试间隔 - * @return 成功/失败 - */ - public boolean lock(String key, long expire, int retryTimes, long sleepMillis) { - boolean result = setRedis(key, expire); - // 如果获取锁失败,按照传入的重试次数进行重试 - while ((!result) && retryTimes-- > 0) { - try { - log.debug("get redisDistributeLock failed, retrying..." + retryTimes); - Thread.sleep(sleepMillis); - } catch (InterruptedException e) { - log.warn("Interrupted!", e); - Thread.currentThread().interrupt(); - } - result = setRedis(key, expire); - } - return result; - } - - private boolean setRedis(final String key, final long expire) { - try { - boolean status = redisTemplate.execute((RedisCallback) connection -> { - String uuid = UUID.randomUUID().toString(); - lockFlag.set(uuid); - byte[] keyByte = redisTemplate.getStringSerializer().serialize(key); - byte[] uuidByte = redisTemplate.getStringSerializer().serialize(uuid); - boolean result = connection.set(keyByte, uuidByte, Expiration.from(expire, TimeUnit.MILLISECONDS), RedisStringCommands.SetOption.ifAbsent()); - return result; - }); - return status; - } catch (Exception e) { - log.error("set redisDistributeLock occured an exception", e); - } - return false; - } - - /** - * 释放锁 - * @param key 锁的key - * @return 成功/失败 - */ - public boolean releaseLock(String key) { - // 释放锁的时候,有可能因为持锁之后方法执行时间大于锁的有效期,此时有可能已经被另外一个线程持有锁,所以不能直接删除 - try { - // 使用lua脚本删除redis中匹配value的key,可以避免由于方法执行时间过长而redis锁自动过期失效的时候误删其他线程的锁 - // spring自带的执行脚本方法中,集群模式直接抛出不支持执行脚本的异常,所以只能拿到原redis的connection来执行脚本 - Boolean result = redisTemplate.execute((RedisCallback) connection -> { - byte[] scriptByte = redisTemplate.getStringSerializer().serialize(UNLOCK_LUA); - return connection.eval(scriptByte, ReturnType.BOOLEAN, 1 - , redisTemplate.getStringSerializer().serialize(key) - , redisTemplate.getStringSerializer().serialize(lockFlag.get())); - }); - return result; - } catch (Exception e) { - log.error("release redisDistributeLock occured an exception", e); - } finally { - lockFlag.remove(); - } - return false; - } -} diff --git a/jun_springboot_starter/jun-redis-spring-boot-starter/src/main/java/io/github/wujun728/common/redis/lock/RedissonDistributedLock.java b/jun_springboot_starter/jun-redis-spring-boot-starter/src/main/java/io/github/wujun728/common/redis/lock/RedissonDistributedLock.java deleted file mode 100644 index 2c563d4aa7..0000000000 --- a/jun_springboot_starter/jun-redis-spring-boot-starter/src/main/java/io/github/wujun728/common/redis/lock/RedissonDistributedLock.java +++ /dev/null @@ -1,68 +0,0 @@ -package io.github.wujun728.common.redis.lock; - -import io.github.wujun728.common.constant.CommonConstant; -import io.github.wujun728.common.exception.LockException; -import io.github.wujun728.common.lock.DistributedLock; -import io.github.wujun728.common.lock.ZLock; -import org.redisson.api.RLock; -import org.redisson.api.RedissonClient; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; - -import java.util.concurrent.TimeUnit; - -/** - * redisson分布式锁实现,基本锁功能的抽象实现 - * 本接口能满足绝大部分的需求,高级的锁功能,请自行扩展或直接使用原生api - * https://gitbook.cn/gitchat/activity/5f02746f34b17609e14c7d5a - * - */ -@ConditionalOnClass(RedissonClient.class) -@ConditionalOnProperty(prefix = "jun.lock", name = "lockerType", havingValue = "REDIS", matchIfMissing = true) -public class RedissonDistributedLock implements DistributedLock { - @Autowired - private RedissonClient redisson; - - private ZLock getLock(String key, boolean isFair) { - RLock lock; - if (isFair) { - lock = redisson.getFairLock(CommonConstant.LOCK_KEY_PREFIX + ":" + key); - } else { - lock = redisson.getLock(CommonConstant.LOCK_KEY_PREFIX + ":" + key); - } - return new ZLock(lock, this); - } - - @Override - public ZLock lock(String key, long leaseTime, TimeUnit unit, boolean isFair) { - ZLock zLock = getLock(key, isFair); - RLock lock = (RLock)zLock.getLock(); - lock.lock(leaseTime, unit); - return zLock; - } - - @Override - public ZLock tryLock(String key, long waitTime, long leaseTime, TimeUnit unit, boolean isFair) throws InterruptedException { - ZLock zLock = getLock(key, isFair); - RLock lock = (RLock)zLock.getLock(); - if (lock.tryLock(waitTime, leaseTime, unit)) { - return zLock; - } - return null; - } - - @Override - public void unlock(Object lock) { - if (lock != null) { - if (lock instanceof RLock) { - RLock rLock = (RLock)lock; - if (rLock.isLocked()) { - rLock.unlock(); - } - } else { - throw new LockException("requires RLock type"); - } - } - } -} diff --git a/jun_springboot_starter/jun-redis-spring-boot-starter/src/main/java/io/github/wujun728/common/redis/properties/CacheManagerProperties.java b/jun_springboot_starter/jun-redis-spring-boot-starter/src/main/java/io/github/wujun728/common/redis/properties/CacheManagerProperties.java deleted file mode 100644 index 0d91a601f9..0000000000 --- a/jun_springboot_starter/jun-redis-spring-boot-starter/src/main/java/io/github/wujun728/common/redis/properties/CacheManagerProperties.java +++ /dev/null @@ -1,29 +0,0 @@ -package io.github.wujun728.common.redis.properties; - -import lombok.Getter; -import lombok.Setter; -import org.springframework.boot.context.properties.ConfigurationProperties; - -import java.util.List; - -/** - */ -@Setter -@Getter -@ConfigurationProperties(prefix = "jun.cache-manager") -public class CacheManagerProperties { - private List configs; - - @Setter - @Getter - public static class CacheConfig { - /** - * cache key - */ - private String key; - /** - * 过期时间,sec - */ - private long second = 60; - } -} diff --git a/jun_springboot_starter/jun-redis-spring-boot-starter/src/main/java/io/github/wujun728/common/redis/service/RedisService.java b/jun_springboot_starter/jun-redis-spring-boot-starter/src/main/java/io/github/wujun728/common/redis/service/RedisService.java deleted file mode 100644 index be62beae96..0000000000 --- a/jun_springboot_starter/jun-redis-spring-boot-starter/src/main/java/io/github/wujun728/common/redis/service/RedisService.java +++ /dev/null @@ -1,87 +0,0 @@ -package io.github.wujun728.common.redis.service; - -import io.github.wujun728.common.exception.BusinessException; -import io.github.wujun728.common.exception.code.BaseResponseCode; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.stereotype.Service; -import org.springframework.util.CollectionUtils; - -import java.util.Set; -import java.util.concurrent.TimeUnit; - - -/** - * redis - * - * @version V1.0 - * @date 2020年3月18日 - */ -@Service -public class RedisService { - private final StringRedisTemplate redisTemplate; - - public StringRedisTemplate getRedisTemplate() { - return redisTemplate; - } - - public RedisService(StringRedisTemplate redisTemplate) { - this.redisTemplate = redisTemplate; - } - - public boolean exists(String key) { - return this.redisTemplate.hasKey(key); - } - - public Long getExpire(String key) { - if (null == key) { - throw new BusinessException(BaseResponseCode.DATA_ERROR.getCode(), "key or TomeUnit 不能为空"); - } - return redisTemplate.getExpire(key, TimeUnit.SECONDS); - } - - - public void set(String key, String value) { - this.redisTemplate.opsForValue().set(key, value); - this.redisTemplate.expire(key, 60*60*24*7, TimeUnit.SECONDS); - } - - - public String get(String key) { - return this.redisTemplate.opsForValue().get(key); - } - - public void del(String key) { - if (this.exists(key)) { - this.redisTemplate.delete(key); - } - - } - - public void setAndExpire(String key, String value, long seconds) { - this.redisTemplate.opsForValue().set(key, value); - this.redisTemplate.expire(key, seconds, TimeUnit.SECONDS); - } -// public void setAndExpire(String key, String value, long seconds,TimeUnit timeUnit) { -// this.redisTemplate.opsForValue().set(key, value); -// this.redisTemplate.expire(key, seconds, timeUnit); -// } - - - public Set keys(String pattern) { - return redisTemplate.keys("*" + pattern); - } - - public void delKeys(String pattern) { - Set keys = redisTemplate.keys(pattern); - if (!CollectionUtils.isEmpty(keys)) { - this.redisTemplate.delete(keys); - } - } - - public void expire(String key, long seconds) { - this.redisTemplate.expire(key, seconds, TimeUnit.SECONDS); - } - - - -} diff --git a/jun_springboot_starter/jun-redis-spring-boot-starter/src/main/java/io/github/wujun728/common/redis/template/RedisRepository.java b/jun_springboot_starter/jun-redis-spring-boot-starter/src/main/java/io/github/wujun728/common/redis/template/RedisRepository.java deleted file mode 100644 index 4441dc3052..0000000000 --- a/jun_springboot_starter/jun-redis-spring-boot-starter/src/main/java/io/github/wujun728/common/redis/template/RedisRepository.java +++ /dev/null @@ -1,494 +0,0 @@ -package io.github.wujun728.common.redis.template; - -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.springframework.dao.DataAccessException; -import org.springframework.data.redis.connection.RedisClusterNode; -import org.springframework.data.redis.connection.RedisConnection; -import org.springframework.data.redis.connection.RedisConnectionFactory; -import org.springframework.data.redis.connection.RedisServerCommands; -import org.springframework.data.redis.core.*; -import org.springframework.data.redis.serializer.RedisSerializer; -import org.springframework.data.redis.serializer.SerializationUtils; -import org.springframework.util.Assert; - -import java.util.*; -import java.util.concurrent.TimeUnit; - -/** - * Redis Repository - * redis 基本操作 可扩展,基本够用了 - * - */ -@Slf4j -public class RedisRepository { - /** - * Spring Redis Template - */ - private RedisTemplate redisTemplate; - - public RedisRepository(RedisTemplate redisTemplate) { - this.redisTemplate = redisTemplate; - } - - /** - * 获取链接工厂 - */ - public RedisConnectionFactory getConnectionFactory() { - return this.redisTemplate.getConnectionFactory(); - } - - /** - * 获取 RedisTemplate对象 - */ - public RedisTemplate getRedisTemplate() { - return redisTemplate; - } - - /** - * 清空DB - * - * @param node redis 节点 - */ - public void flushDB(RedisClusterNode node) { - this.redisTemplate.opsForCluster().flushDb(node); - } - - /** - * 添加到带有 过期时间的 缓存 - * - * @param key redis主键 - * @param value 值 - * @param time 过期时间(单位秒) - */ - public void setExpire(final byte[] key, final byte[] value, final long time) { - redisTemplate.execute((RedisCallback) connection -> { - connection.setEx(key, time, value); - return 1L; - }); - } - - /** - * 添加到带有 过期时间的 缓存 - * - * @param key redis主键 - * @param value 值 - * @param time 过期时间 - * @param timeUnit 过期时间单位 - */ - public void setExpire(final String key, final Object value, final long time, final TimeUnit timeUnit) { - redisTemplate.opsForValue().set(key, value, time, timeUnit); - } - public void setExpire(final String key, final Object value, final long time) { - this.setExpire(key, value, time, TimeUnit.SECONDS); - } - public void setExpire(final String key, final Object value, final long time, final TimeUnit timeUnit, RedisSerializer valueSerializer) { - byte[] rawKey = rawKey(key); - byte[] rawValue = rawValue(value, valueSerializer); - - redisTemplate.execute(new RedisCallback() { - @Override - public Object doInRedis(RedisConnection connection) throws DataAccessException { - potentiallyUsePsetEx(connection); - return null; - } - public void potentiallyUsePsetEx(RedisConnection connection) { - if (!TimeUnit.MILLISECONDS.equals(timeUnit) || !failsafeInvokePsetEx(connection)) { - connection.setEx(rawKey, TimeoutUtils.toSeconds(time, timeUnit), rawValue); - } - } - private boolean failsafeInvokePsetEx(RedisConnection connection) { - boolean failed = false; - try { - connection.pSetEx(rawKey, time, rawValue); - } catch (UnsupportedOperationException e) { - failed = true; - } - return !failed; - } - }, true); - } - - /** - * 一次性添加数组到 过期时间的 缓存,不用多次连接,节省开销 - * - * @param keys redis主键数组 - * @param values 值数组 - * @param time 过期时间(单位秒) - */ - public void setExpire(final String[] keys, final Object[] values, final long time) { - for (int i = 0; i < keys.length; i++) { - redisTemplate.opsForValue().set(keys[i], values[i], time, TimeUnit.SECONDS); - } - } - - - /** - * 一次性添加数组到 过期时间的 缓存,不用多次连接,节省开销 - * - * @param keys the keys - * @param values the values - */ - public void set(final String[] keys, final Object[] values) { - for (int i = 0; i < keys.length; i++) { - redisTemplate.opsForValue().set(keys[i], values[i]); - } - } - - - /** - * 添加到缓存 - * - * @param key the key - * @param value the value - */ - public void set(final String key, final Object value) { - redisTemplate.opsForValue().set(key, value); - } - - /** - * 查询在以keyPatten的所有 key - * - * @param keyPatten the key patten - * @return the set - */ - public Set keys(final String keyPatten) { - return redisTemplate.keys(keyPatten + "*"); - } - - /** - * 根据key获取对象 - * - * @param key the key - * @return the byte [ ] - */ - public byte[] get(final byte[] key) { - return redisTemplate.execute((RedisCallback) connection -> connection.get(key)); - } - - /** - * 根据key获取对象 - * - * @param key the key - * @return the string - */ - public Object get(final String key) { - return redisTemplate.opsForValue().get(key); - } - - /** - *获取原来key键对应的值并重新赋新值。 - * @param key - * @param value - * @return - */ - public String getAndSet(final String key,String value) { - String result = null; - if (StringUtils.isEmpty(key)){ - log.error("非法入参"); - return null; - } - try { - Object object =redisTemplate.opsForValue().getAndSet(key, value); - if (object !=null){ - result = object.toString(); - } - }catch (Exception e){ - log.error("redisTemplate操作异常",e); - } - return result; - } - /** - * 根据key获取对象 - * - * @param key the key - * @param valueSerializer 序列化 - * @return the string - */ - public Object get(final String key, RedisSerializer valueSerializer) { - byte[] rawKey = rawKey(key); - return redisTemplate.execute(connection -> deserializeValue(connection.get(rawKey), valueSerializer), true); - } - - - /** - * Ops for hash hash operations. - * - * @return the hash operations - */ - public HashOperations opsForHash() { - return redisTemplate.opsForHash(); - } - - /** - * 对HashMap操作 - * - * @param key the key - * @param hashKey the hash key - * @param hashValue the hash value - */ - public void putHashValue(String key, String hashKey, Object hashValue) { - opsForHash().put(key, hashKey, hashValue); - } - - /** - * 获取单个field对应的值 - * - * @param key the key - * @param hashKey the hash key - * @return the hash values - */ - public Object getHashValues(String key, String hashKey) { - return opsForHash().get(key, hashKey); - } - - /** - * 根据key值删除 - * - * @param key the key - * @param hashKeys the hash keys - */ - public void delHashValues(String key, Object... hashKeys) { - opsForHash().delete(key, hashKeys); - } - - /** - * key只匹配map - * - * @param key the key - * @return the hash value - */ - public Map getHashValue(String key) { - return opsForHash().entries(key); - } - - /** - * 批量添加 - * - * @param key the key - * @param map the map - */ - public void putHashValues(String key, Map map) { - opsForHash().putAll(key, map); - } - - /** - * 集合数量 - * - * @return the long - */ - public long dbSize() { - return redisTemplate.execute(RedisServerCommands::dbSize); - } - - /** - * 清空redis存储的数据 - * - * @return the string - */ - public String flushDB() { - return redisTemplate.execute((RedisCallback) connection -> { - connection.flushDb(); - return "ok"; - }); - } - - /** - * 判断某个主键是否存在 - * - * @param key the key - * @return the boolean - */ - public boolean exists(final String key) { - return redisTemplate.hasKey(key); - } - - - /** - * 删除key - * - * @param keys the keys - * @return the long - */ - public boolean del(final String... keys) { - boolean result = false; - for (String key : keys) { - result = redisTemplate.delete(key); - } - return result; - } - - /** - * 对某个主键对应的值加一,value值必须是全数字的字符串 - * - * @param key the key - * @return the long - */ - public long incr(final String key) { - return redisTemplate.opsForValue().increment(key); - } - - /** - * redis List 引擎 - * - * @return the list operations - */ - public ListOperations opsForList() { - return redisTemplate.opsForList(); - } - - /** - * redis List数据结构 : 将一个或多个值 value 插入到列表 key 的表头 - * - * @param key the key - * @param value the value - * @return the long - */ - public Long leftPush(String key, Object value) { - return opsForList().leftPush(key, value); - } - - /** - * redis List数据结构 : 移除并返回列表 key 的头元素 - * - * @param key the key - * @return the string - */ - public Object leftPop(String key) { - return opsForList().leftPop(key); - } - - /** - * redis List数据结构 :将一个或多个值 value 插入到列表 key 的表尾(最右边)。 - * - * @param key the key - * @param value the value - * @return the long - */ - public Long in(String key, Object value) { - return opsForList().rightPush(key, value); - } - - /** - * redis List数据结构 : 移除并返回列表 key 的末尾元素 - * - * @param key the key - * @return the string - */ - public Object rightPop(String key) { - return opsForList().rightPop(key); - } - - - /** - * redis List数据结构 : 返回列表 key 的长度 ; 如果 key 不存在,则 key 被解释为一个空列表,返回 0 ; 如果 key 不是列表类型,返回一个错误。 - * - * @param key the key - * @return the long - */ - public Long length(String key) { - return opsForList().size(key); - } - - - /** - * redis List数据结构 : 根据参数 i 的值,移除列表中与参数 value 相等的元素 - * - * @param key the key - * @param i the - * @param value the value - */ - public void remove(String key, long i, Object value) { - opsForList().remove(key, i, value); - } - - /** - * redis List数据结构 : 将列表 key 下标为 index 的元素的值设置为 value - * - * @param key the key - * @param index the index - * @param value the value - */ - public void set(String key, long index, Object value) { - opsForList().set(key, index, value); - } - - /** - * redis List数据结构 : 返回列表 key 中指定区间内的元素,区间以偏移量 start 和 end 指定。 - * - * @param key the key - * @param start the start - * @param end the end - * @return the list - */ - public List getList(String key, int start, int end) { - return opsForList().range(key, start, end); - } - - /** - * redis List数据结构 : 返回列表 key 中指定区间内的元素,区间以偏移量 start 和 end 指定。 - * - * @param key the key - * @param start the start - * @param end the end - * @param valueSerializer 序列化 - * @return the list - */ - public List getList(String key, int start, int end, RedisSerializer valueSerializer) { - byte[] rawKey = rawKey(key); - return redisTemplate.execute(connection -> deserializeValues(connection.lRange(rawKey, start, end), valueSerializer), true); - } - - /** - * redis List数据结构 : 批量存储 - * - * @param key the key - * @param list the list - * @return the long - */ - public Long leftPushAll(String key, List list) { - return opsForList().leftPushAll(key, list); - } - - /** - * redis List数据结构 : 将值 value 插入到列表 key 当中,位于值 index 之前或之后,默认之后。 - * - * @param key the key - * @param index the index - * @param value the value - */ - public void insert(String key, long index, Object value) { - opsForList().set(key, index, value); - } - - private byte[] rawKey(Object key) { - Assert.notNull(key, "non null key required"); - - if (key instanceof byte[]) { - return (byte[]) key; - } - RedisSerializer redisSerializer = (RedisSerializer)redisTemplate.getKeySerializer(); - return redisSerializer.serialize(key); - } - private byte[] rawValue(Object value, RedisSerializer valueSerializer) { - if (value instanceof byte[]) { - return (byte[]) value; - } - - return valueSerializer.serialize(value); - } - - private List deserializeValues(List rawValues, RedisSerializer valueSerializer) { - if (valueSerializer == null) { - return rawValues; - } - return SerializationUtils.deserialize(rawValues, valueSerializer); - } - - private Object deserializeValue(byte[] value, RedisSerializer valueSerializer) { - if (valueSerializer == null) { - return value; - } - return valueSerializer.deserialize(value); - } -} diff --git a/jun_springboot_starter/jun-redis-spring-boot-starter/src/main/resources/META-INF/spring.factories.bk b/jun_springboot_starter/jun-redis-spring-boot-starter/src/main/resources/META-INF/spring.factories.bk deleted file mode 100644 index e36363bb30..0000000000 --- a/jun_springboot_starter/jun-redis-spring-boot-starter/src/main/resources/META-INF/spring.factories.bk +++ /dev/null @@ -1,4 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -io.github.wujun728.common.redis.RedisAutoConfigure,\ -io.github.wujun728.common.redis.lock.RedissonDistributedLock,\ -io.github.wujun728.common.redis.template.RedisRepository \ No newline at end of file diff --git a/jun_springboot_starter/jun-redis-spring-boot-starter/src/main/resources/limit.lua b/jun_springboot_starter/jun-redis-spring-boot-starter/src/main/resources/limit.lua deleted file mode 100644 index 3fbd2711f4..0000000000 --- a/jun_springboot_starter/jun-redis-spring-boot-starter/src/main/resources/limit.lua +++ /dev/null @@ -1,19 +0,0 @@ ---lua 下标从 1 开始 --- 限流 key -local key = KEYS[1] --- 限流大小 -local limit = tonumber(ARGV[1]) - --- 获取当前流量大小 -local curentLimit = tonumber(redis.call('get', key) or "0") - -if curentLimit + 1 > limit then - -- 达到限流大小 返回 - return 0; -else - -- 没有达到阈值 value + 1 - redis.call("INCRBY", key, 1) - redis.call("EXPIRE", key, 2) - return curentLimit + 1 -end - diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/README.md b/jun_springboot_starter/jun-security-spring-boot-starter/README.md deleted file mode 100644 index fd519a9fe9..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/README.md +++ /dev/null @@ -1,390 +0,0 @@ -

        jun-security-boot-starter

        - - - - -## 1、简介 - -jun-security-boot-starter是一个基于SpringBoot开发的轻量级权限控制框架,支持登录认证、权限认证;同时支持token验证和cookie验证; -支持redis、jdbc和单机session多种会话存储方式(亦可自行扩展存储方式);前后端分离项目、不分离项目均可使用,功能完善、使用简单,文档清晰,让认证鉴权这件事变得更加简单! - ---- - -## 2、使用 - -### 2.1、SpringBoot集成 - -#### 2.1.1、引入依赖 -```xml - - io.github.wujun728 - jun-security-spirng-boot-starter - 1.0.8 - -``` - -#### 2.1.2、yml参数配置项 - -```yaml -jun-security: - # 存储类型,目前支持jdbc和redis和单机内存三种(redis,jdbc,single),如不配置,则默认为single - store-type: redis - # token名称 (同时也是cookie名称,适配前后端不分离的模式) - token-name: token - # token有效期 (即会话时长),单位秒 默认1800秒(30分钟) - timeout: 1800 - # token风格,可配置uuid (默认风格),snowflake (纯数字风格),objectid (变种uuid),random128 (随机128位字符串),nanoid - token-style: uuid - # 当配置为jdbc时,存储token的表名字,默认为b_auth_token - table-name: b_auth_token -``` - -1. 如果使用jdbcAuthStore,需要导入框架提供的sql脚本并集成好jdbcTemplate, - 导入依赖 `spring-boot-starter-jdbc`,在yml里进行相应配置即可 -```xml - - org.springframework.boot - spring-boot-starter-jdbc - -``` -2. 如果使用redisAuthStore,需要集成好redisTemplate, - 导入依赖 `spring-boot-starter-data-redis` ,在yml里进行相应配置即可 -```xml - - org.springframework.boot - spring-boot-starter-data-redis - -``` - -#### 2.1.3、其他自定义配置 -1. 配置会话拦截器和权限角色拦截器,以`SpringBoot2.0`为例, 新建配置类`WebMvcConfig.java`,两个拦截器的拦截路由规则可自行配置 -```java -@Configuration -public class WebMvcConfig implements WebMvcConfigurer { - - @Autowired - private AuthenticeInterceptor authenticeInterceptor; - - // 按需要来,如果不需要角色权限控制,可以不配置此拦截器 - @Autowired - private PermissionInterceptor permissionInterceptor; - - @Override - public void addInterceptors(InterceptorRegistry registry) { - - // 注册会话拦截器 - registry.addInterceptor(authenticeInterceptor) - .addPathPatterns("/**") - .excludePathPatterns("/login"); - - // 注册权限拦截器 - registry.addInterceptor(permissionInterceptor) - .addPathPatterns("/**"); - } -} -``` -2. 如需权限角色拦截器进行权限控制的话,则需要实现`PermissionInfoInterface`接口,重写权限和角色编码列表获取的业务逻辑(框架没有对权限和角色编码进行缓存,如需缓存请自行处理),例如以下代码: -```java -@Component -public class PermissionInfoInterfaceImpl implements PermissionInfoInterface { - private final static Logger logger = LoggerFactory.getLogger(PermissionInfoInterfaceImpl.class); - - - /** - * 返回一个账号所拥有的权限码集合 - * @param loginId,账号id,即你在调用 authProvider.login(id) 时写入的标识值。 - */ - @Override - public Set getPermissionSet(Object loginId) { - if (logger.isInfoEnabled()) { - logger.info("PermissionInfoInterfaceImpl -- getPermissionSet -- loginId = {}", loginId); - } - // 自定义权限编码列表获取逻辑,下面的只是示例 - Set permissionSet = new HashSet() {{ - add("权限1"); - add("权限2"); - }}; - - return permissionSet; - } - - /** - * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验) - * @param loginId,账号id,即你在调用 authProvider.login(id) 时写入的标识值。 - */ - @Override - public Set getRoleSet(Object loginId) { - if (logger.isInfoEnabled()) { - logger.info("PermissionInfoInterfaceImpl -- getRoleSet -- loginId = {}", loginId); - } - // 自定义角色编码列表获取逻辑,下面的只是示例 - Set roleSet = new HashSet() {{ - add("角色1"); - add("角色2"); - }}; - return roleSet; - } -} -``` - ---- - -### 2.2、登录签发token,创建会话 - -```java -@Controller -public class IndexController { - final static Logger logger = LoggerFactory.getLogger(IndexController.class); - - @Autowired - private AuthProvider authProvider; - - @ResponseBody - @PostMapping("/login") - public Result login(@ApiParam(name = "username", required = true, value = "用户名") - @RequestParam("username") String username, - @ApiParam(name = "password", required = true, value = "用户密码") - @RequestParam("password") String password) { - // 你的登录验证逻辑 - // ...... - // 签发token - String token = authProvider.login(username); - - return Result.ok("登录成功!", token); - } -} -``` -login方法参数说明: -- loginId 登录的账号id,建议的数据类型:long | int | String,建议为用户id,不可以传入复杂类型,如:model.User、Admin 等等 - ---- - - -### 2.3、退出登录,注销会话 -```java -@Controller -public class IndexController { - final static Logger logger = LoggerFactory.getLogger(IndexController.class); - - @Autowired - private AuthProvider authProvider; - - @ResponseBody - @GetMapping("/logout") - public Result logout(HttpServletRequest request) { - // 退出登录,注销会话 - authProvider.logout(request); - - return Result.ok("退出登录成功!"); - } -} -``` ---- - -### 2.4、使用注解控制权限 - -**1.注解解释:** - -```text -// 需要有system权限才能访问 -@RequiresPermissions("system") - -// 需要有system和front权限才能访问, logical可以不写,默认是AND -@RequiresPermissions(value={"system","front"}, logical=Logical.AND) - -// 需要有system或front权限才能访问 -@RequiresPermissions(value={"system","front"}, logical=Logical.OR) - -// 需要有user角色才能访问 -@RequiresRoles(value="user") - -// 需要有admin和user角色才能访问 -@RequiresRoles(value={"admin","user"}, logical=Logical.AND) - -// 需要有admin或user角色才能访问 -@RequiresRoles(value={"admin","user"}, logical=Logical.OR) -``` - -> 注解加在Controller的方法或类上面。 - -**2.代码示例:** - -```java -@Controller -public class IndexController { - final static Logger logger = LoggerFactory.getLogger(IndexController.class); - - @Autowired - private AuthProvider authProvider; - - @RequiresPermissions("权限3") - @ResponseBody - @GetMapping("/testPermission3") - public Result testPermission3() { - - return Result.ok("testPermission3测试成功!"); - } - - @RequiresPermissions("权限2") - @ResponseBody - @GetMapping("/testPermission2") - public Result testPermission2() { - logger.info("IndexController - testPermission3 - authProvider.getLoginId() = {}", authProvider.getLoginId()); - logger.info("IndexController - testPermission3 - AuthUtil.getLoginId() = {}", AuthUtil.getLoginId()); - logger.info("IndexController - testPermission3 - token = {}", authProvider.getToken()); - - return Result.ok("testPermission2测试成功!", authProvider.getLoginId()); - } -} -``` - ---- - -### 2.5、使用代码控制权限 -**1.代码示例:** - -```java - -// 判断:当前账号是否含有指定角色, 返回 true 或 false -AuthUtil.hasRole("role1"); - -// 判断:当前账号是否含有指定角色 [指定多个,必须全部验证通过] -AuthUtil.hasAllRole("role1", "role2"); - -// 判断:当前账号是否含有指定角色 [指定多个,只要其一验证通过即可] -AuthUtil.hasAnyRole("role1", "role2"); - -// 判断:当前账号是否含有指定权限, 返回 true 或 false -AuthUtil.hasPermission("permission1"); - -// 判断:当前账号是否含有指定权限 [指定多个,必须全部验证通过] -AuthUtil.hasAllPermission("permission1", "permission2"); - -// 判断:当前账号是否含有指定权限 [指定多个,只要其一验证通过即可] -AuthUtil.hasAnyPermission("permission1", "permission2"); - -``` - ---- - -### 2.6、获取当前登录用户编码 -```java -// 注入authProvider -@Autowired -private AuthProvider authProvider; - -authProvider.getLoginId() - -或者直接调用静态方法 - -AuthUtil.getLoginId() -``` - ---- - -### 2.7、获取当前登录用户token -```java -// 注入authProvider -@Autowired -private AuthProvider authProvider; - -authProvider.getToken() -或者 -authProvider.getToken(HttpServletRequest request); -``` ---- - -### 2.8、异常处理 -bluewind-auth-client在会话验证失败和权限验证失败的时候会抛出自定义异常: - -| 自定义异常 | 描述 | 错误信息 | -|:----------------------|:-------------|:----------------------------------| -| UnAuthorizedException | 未登录或会话已失效 | 错误信息“未登录或会话已失效!”,错误码401 | -| NoPermissionException | 无权限访问(角色或者资源不匹配) | 错误信息“无权限访问!”,错误码403 | - -建议使用全局异常处理器来捕获异常并进行处理: -```java -@ControllerAdvice -public class GlobalExceptionHandler { - private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); - - // 捕捉运行时异常 - @ResponseBody - @ExceptionHandler(RuntimeException.class) - public Result handleRuntimeException(Exception e) { - logger.error("GlobalExceptionHandler -- RuntimeException = {e}", e); - return Result.create(HttpStatus.ERROR, e.getMessage()); - } - - // 缺少权限异常 - @ResponseBody - @ExceptionHandler(value = NoPermissionException.class) - public Result handleAuthorizationException() { - return Result.create(HttpStatus.FORBIDDEN, "接口无权限,请联系系统管理员", null); - } - - // 未登陆异常 - @ResponseBody - @ExceptionHandler(value = UnAuthorizedException.class) - public Result handleAuthenticationException() { - return Result.create(HttpStatus.UNAUTHORIZED, "会话已失效,请重新登录", null); - } -} -``` - ---- - -### 2.9、更多用法 - -#### 2.9.1、使用注解忽略会话验证`@Ignore` -在Controller的方法或类上面添加`@Ignore`注解可排除框架会话拦截,即表示调用接口不用传递token了。 - - -#### 2.9.2、主动让token失效 -```java -// 注入authProvider -@Autowired -private AuthProvider authProvider; - -// 根据token,使token失效 -authProvider.deleteToken(token); - -// 根据用户loginId,使该用户的全部token都失效 -authProvider.deleteTokenByLoginId(loginId); -``` - ---- - -### 2.10、前端传递token -1. 放在参数里面用`token`传递: -```javascript -$.get("/xxx", { "token": token }, function(data) { - -}); -``` -2. 放在header里面用`token`传递: -```javascript -$.ajax({ - url: "/xxx", - beforeSend: function(xhr) { - xhr.setRequestHeader("token", token); - }, - success: function(data){ } -}); -``` -3. 前后端不分离的项目会自动从cookie里获取`token` - ---- - -### 2.11、自定义AuthProvider -框架内置了JdbcAuthProvider、RedisAuthProvider和SingleAuthProvider三种会话实现, -如果仍然无法满足你的需求,或者你想存在其他什么地方,比如存在磁盘、MongoDB中,只需以下三步即可: -- 实现org.bluewind.authclient.provider.AuthProvider接口,或者继承org.bluewind.authclient.provider.AbstractAuthProvider抽象类, 实现里面的抽象方法, -- 注入bean,如下 -```java - @Component - public class MongoAuthProvider extends AbstractAuthProvider { - // ... - } -``` -- 删除store-type的配置 \ No newline at end of file diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/pom.xml b/jun_springboot_starter/jun-security-spring-boot-starter/pom.xml deleted file mode 100644 index 73ab98552c..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/pom.xml +++ /dev/null @@ -1,99 +0,0 @@ - - - 4.0.0 - - io.github.wujun728 - jun-security-spring-boot-starter - 1.0.8 - jar - - - 8 - 8 - 1.8 - - 2.3.12.RELEASE - 3.1.0 - - - - - org.springframework.boot - spring-boot-starter-web - ${springboot.version} - provided - - - - org.springframework.boot - spring-boot-starter-data-redis - ${springboot.version} - provided - - - - org.springframework.boot - spring-boot-starter-jdbc - ${springboot.version} - provided - - - - org.springframework.boot - spring-boot-autoconfigure - ${springboot.version} - true - - - - - javax.servlet - javax.servlet-api - ${servlet.version} - provided - - - - - ${project.artifactId}-${project.version} - - - src/main/java - false - - - src/main/resources - false - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.22.2 - - true - true - -Dfile.encoding=UTF-8 - - - - - org.apache.maven.plugins - maven-source-plugin - 2.4 - - - attach-sources - - jar - - - - - - - - \ No newline at end of file diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/AuthAutoConfiguration.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/AuthAutoConfiguration.java deleted file mode 100644 index cd5ce5df0a..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/AuthAutoConfiguration.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.jun.plugin.security; - -import com.jun.plugin.security.interceptor.AuthenticeInterceptor; -import com.jun.plugin.security.interceptor.PermissionInterceptor; -import com.jun.plugin.security.interfaces.PermissionInfoInterface; -import com.jun.plugin.security.provider.AuthProvider; -import com.jun.plugin.security.provider.JdbcAuthProvider; -import com.jun.plugin.security.provider.RedisAuthProvider; -import com.jun.plugin.security.provider.SingleAuthProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.jdbc.core.JdbcTemplate; - -/** - *

        - * 自动配置类 - *

        - * - * @since 2022-12-13 11:45 - **/ -@Configuration -@EnableConfigurationProperties(AuthProperties.class) -public class AuthAutoConfiguration { - final static Logger logger = LoggerFactory.getLogger(AuthAutoConfiguration.class); - - @Autowired - private AuthProperties authProperties; - - - /** - * 注入redisAuthProvider - */ - @ConditionalOnMissingBean(AuthProvider.class) - @ConditionalOnProperty(name = "jun-security.store-type", havingValue = "redis") - @Bean - public AuthProvider redisAuthProvider(StringRedisTemplate stringRedisTemplate) { - if (stringRedisTemplate == null) { - logger.error("AuthAutoConfiguration: Bean StringRedisTemplate is null!"); - return null; - } - logger.info("RedisAuthProvider is running!"); - return new RedisAuthProvider(stringRedisTemplate, authProperties); - } - - /** - * 注入jdbcAuthProvider - */ - @ConditionalOnMissingBean(AuthProvider.class) - @ConditionalOnProperty(name = "jun-security.store-type", havingValue = "jdbc") - @Bean - public AuthProvider jdbcAuthProvider(JdbcTemplate jdbcTemplate) { - if (jdbcTemplate == null) { - logger.error("AuthAutoConfiguration: Bean JdbcTemplate is null!"); - return null; - } - logger.info("JdbcAuthProvider is running!"); - return new JdbcAuthProvider(jdbcTemplate, authProperties); - } - - /** - * 注入singleAuthProvider - */ - @ConditionalOnMissingBean(AuthProvider.class) - @ConditionalOnProperty(name = "jun-security.store-type", havingValue = "single", matchIfMissing = true) - @Bean - public AuthProvider singleAuthProvider() { - logger.info("SingleAuthProvider is running!"); - return new SingleAuthProvider(authProperties); - } - - - /** - * 添加会话拦截器( 注入AuthStore(可能是redis的,也可能是jdbc的,根据配置来的)) - */ - @Bean - public AuthenticeInterceptor authenticeInterceptor(AuthProvider authProvider) { - if (authProvider != null) { - return new AuthenticeInterceptor(authProvider); - } else { - logger.error("AuthAutoConfiguration: Bean AuthProvider Not Defined!"); - return null; - } - } - - - /** - * 添加权限拦截器(当存在bean PermissionInfoInterface时,这个配置才生效) - * 注入PermissionInfoInterface - */ - @Bean - @ConditionalOnBean(PermissionInfoInterface.class) - public PermissionInterceptor permissionInterceptor(PermissionInfoInterface permissionInfoInterface) { - if (permissionInfoInterface != null) { - return new PermissionInterceptor(permissionInfoInterface); - } else { - logger.error("AuthAutoConfiguration: Bean PermissionInfoInterface Not Defined!"); - return null; - } - } - -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/AuthProperties.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/AuthProperties.java deleted file mode 100644 index b731841b0f..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/AuthProperties.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.jun.plugin.security; - -import org.springframework.boot.context.properties.ConfigurationProperties; - - -/** - * 映射配置类--映射yml里面的配置 - * @since 2023-01-06-9:33 - **/ -@ConfigurationProperties(prefix = "jun-security") -public class AuthProperties { - - private String storeType = "redis"; - - private String tokenName = "token"; - - private Integer timeout = 3600; - - private String tokenStyle = "uuid"; - - private String tokenPrefix; - - private String tableName = "s_auth_token"; - - public String getStoreType() { - return storeType; - } - - public void setStoreType(String storeType) { - this.storeType = storeType; - } - - public String getTokenName() { - return tokenName; - } - - public void setTokenName(String tokenName) { - this.tokenName = tokenName; - } - - public Integer getTimeout() { - return timeout; - } - - public void setTimeout(Integer timeout) { - this.timeout = timeout; - } - - public String getTokenStyle() { - return tokenStyle; - } - - public void setTokenStyle(String tokenStyle) { - this.tokenStyle = tokenStyle; - } - - public String getTokenPrefix() { - return tokenPrefix; - } - - public void setTokenPrefix(String tokenPrefix) { - this.tokenPrefix = tokenPrefix; - } - - public String getTableName() { - return tableName; - } - - public void setTableName(String tableName) { - this.tableName = tableName; - } -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/annotation/Ignore.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/annotation/Ignore.java deleted file mode 100644 index bb114070f0..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/annotation/Ignore.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.jun.plugin.security.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - - -/** - * 忽略权限验证注解 - * @version 2023-01-06-9:33 - **/ -@Target({ElementType.TYPE, ElementType.METHOD}) -@Retention(RetentionPolicy.RUNTIME) -public @interface Ignore { - -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/annotation/RequiresPermissions.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/annotation/RequiresPermissions.java deleted file mode 100644 index df83ddf365..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/annotation/RequiresPermissions.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.jun.plugin.security.annotation; - -import com.jun.plugin.security.enums.Logical; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * @date 2021-08-08-12:02 - * @description: 权限注解 - * @useintroduction 使用说明如下 - * 1、@RequiresPermissions("index:hello") 拥有index:hello权限 - * 2、@RequiresPermissions({"index:hello","index:world"}) 同时拥有index:hello和index:world权限 - * 3、@RequiresPermissions(value={"index:hello","index:world"},logical=Logical.OR) 拥有index:hello或index:world其一即可 - **/ -@Target({ElementType.TYPE, ElementType.METHOD}) -@Retention(RetentionPolicy.RUNTIME) -public @interface RequiresPermissions { - String[] value(); - Logical logical() default Logical.AND; -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/annotation/RequiresRoles.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/annotation/RequiresRoles.java deleted file mode 100644 index d491409763..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/annotation/RequiresRoles.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.jun.plugin.security.annotation; - -import com.jun.plugin.security.enums.Logical; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * @date 2021-08-08-12:02 - * @description: 角色注解 - * @useintroduction 使用说明如下 - * 1、@RequiresRoles("admin") 拥有admin角色(特别说明:如果数组只传一个值的话,直接这样写就可以,无需再写大括号;多个值的话,使用大括号传值) - * 2、@RequiresRoles({"admin","admin2"}) 同时拥有admin和admin2角色 - * 3、@RequiresRoles(value={"admin","admin2"},logical=Logical.OR) 拥有admin或admin2其一即可 - **/ -@Target({ElementType.TYPE, ElementType.METHOD}) -@Retention(RetentionPolicy.RUNTIME) -public @interface RequiresRoles { - String[] value(); - Logical logical() default Logical.AND; -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/consts/AuthConsts.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/consts/AuthConsts.java deleted file mode 100644 index 26e98f110f..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/consts/AuthConsts.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.jun.plugin.security.consts; - - -/** - * 系统常量类 - * @version 2023-01-06-9:33 - **/ -public class AuthConsts { - - /** - * 登录用户 令牌 Redis Key 前缀 - */ - public static final String AUTH_TOKEN_KEY = "jun-security:auth:token:"; - - // 无权限访问 - public static int CODE_NO_PERMISSION = 403; - - // 未登录或会话已失效 - public static int CODE_UNAUTHORIZED = 401; -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/enums/Logical.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/enums/Logical.java deleted file mode 100644 index 4fb49e6b45..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/enums/Logical.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.jun.plugin.security.enums; - -/** - * 权限枚举 - * @version 2023-01-06-9:33 - **/ -public enum Logical { - AND, - OR; - private Logical() { - } -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/exception/AuthException.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/exception/AuthException.java deleted file mode 100644 index b99a6ac9df..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/exception/AuthException.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jun.plugin.security.exception; - - -public abstract class AuthException extends RuntimeException { - private static final long serialVersionUID = 2413958299445359500L; - - private int code; - - public void setCode(int code) { - this.code = code; - } - - public int getCode() { - return code; - } - - public AuthException(int code, String message) { - super(message); - this.code = code; - } -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/exception/NoPermissionException.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/exception/NoPermissionException.java deleted file mode 100644 index 1a09db51de..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/exception/NoPermissionException.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.jun.plugin.security.exception; - - -import com.jun.plugin.security.consts.AuthConsts; - -/** - * 无权限访问-异常 - */ -public class NoPermissionException extends AuthException { - private static final long serialVersionUID = 8109117719383003895L; - - public NoPermissionException() { - super(AuthConsts.CODE_NO_PERMISSION, "无权限访问!"); - } -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/exception/UnAuthorizedException.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/exception/UnAuthorizedException.java deleted file mode 100644 index d3ddbe3967..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/exception/UnAuthorizedException.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.jun.plugin.security.exception; - -import com.jun.plugin.security.consts.AuthConsts; - -/** - * 未登录或会话已失效-异常 - */ -public class UnAuthorizedException extends AuthException { - private static final long serialVersionUID = 8109117719383003891L; - - public UnAuthorizedException() { - super(AuthConsts.CODE_UNAUTHORIZED, "未登录或会话已失效!"); - } -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/interceptor/AuthenticeInterceptor.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/interceptor/AuthenticeInterceptor.java deleted file mode 100644 index 60edb03d57..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/interceptor/AuthenticeInterceptor.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.jun.plugin.security.interceptor; - -import com.jun.plugin.security.exception.UnAuthorizedException; -import com.jun.plugin.security.interceptor.holder.AuthenticeHolder; -import com.jun.plugin.security.provider.AuthProvider; -import com.jun.plugin.security.util.AuthUtil; -import org.springframework.http.HttpMethod; -import org.springframework.web.method.HandlerMethod; -import org.springframework.web.servlet.ModelAndView; -import org.springframework.util.StringUtils; -import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.lang.reflect.Method; - -/** - * 用户会话验证拦截器 - * - * @version 2020-03-22-11:23 - **/ -public class AuthenticeInterceptor extends HandlerInterceptorAdapter { - - /** - * 存储会话的接口 - */ - private AuthProvider authProvider; - - public AuthProvider getAuthProvider() { - return this.authProvider; - } - - public void setAuthProvider(AuthProvider authProvider) { - this.authProvider = authProvider; - } - - - public AuthenticeInterceptor(AuthProvider authProvider) { - this.setAuthProvider(authProvider); - } - - - /* - * 进入controller层之前拦截请求 - * 返回值:表示是否将当前的请求拦截下来 false:拦截请求,请求别终止。true:请求不被拦截,继续执行 - * Object obj:表示被拦的请求的目标对象(controller中方法) - */ - @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - if (!(handler instanceof HandlerMethod)) { - return super.preHandle(request, response, handler); - } - - // 判断请求类型,如果是OPTIONS,直接返回 - String options = HttpMethod.OPTIONS.toString(); - if (options.equals(request.getMethod())) { - response.setStatus(HttpServletResponse.SC_OK); - return super.preHandle(request, response, handler); - } - - // 检查是否忽略会话验证 - Method method = ((HandlerMethod) handler).getMethod(); - if (AuthUtil.checkIgnore(method)) { - return super.preHandle(request, response, handler); - } - - // 第一步、先从请求的request里获取传来的token值,并且判断token值是否为空 - String token = this.getAuthProvider().getToken(request); - if (StringUtils.isEmpty(token)) { - // 直接抛出异常的话,就不需要return false了 - throw new UnAuthorizedException(); - } - - // 第二步、再判断此token值在会话存储器中是否存在,存在的话说明会话有效,并刷新会话时长 - if (!this.getAuthProvider().checkToken(token)) { - throw new UnAuthorizedException(); - } else { - this.getAuthProvider().refreshToken(token); - // 存入LoginId,以方便后续使用 - AuthenticeHolder.setLoginId(this.getAuthProvider().getLoginId(token)); - // 合格不需要拦截,放行 - return super.preHandle(request, response, handler); - } - } - - - /* - * 处理请求完成后视图渲染之前的处理操作 - * 通过ModelAndView参数改变显示的视图,或发往视图的方法 - */ - @Override - public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { - } - - /* - * 视图渲染之后的操作 - */ - @Override - public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { - AuthenticeHolder.clearLoginId(); - } -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/interceptor/PermissionInterceptor.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/interceptor/PermissionInterceptor.java deleted file mode 100644 index 9bf4fa3242..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/interceptor/PermissionInterceptor.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.jun.plugin.security.interceptor; - -import com.jun.plugin.security.exception.NoPermissionException; -import com.jun.plugin.security.interceptor.holder.AuthenticeHolder; -import com.jun.plugin.security.interceptor.holder.PermissionHolder; -import com.jun.plugin.security.interceptor.holder.RoleHolder; -import com.jun.plugin.security.interfaces.PermissionInfoInterface; -import com.jun.plugin.security.util.AuthUtil; -import org.springframework.http.HttpMethod; -import org.springframework.web.method.HandlerMethod; -import org.springframework.web.servlet.ModelAndView; -import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.lang.reflect.Method; -import java.util.Set; - -/** - * 用户权限验证拦截器 - * - * @version 2020-03-22-11:23 - **/ -public class PermissionInterceptor extends HandlerInterceptorAdapter { - - /** - * 权限角色信息 - */ - private PermissionInfoInterface permissionInfoInterface; - - public PermissionInfoInterface getPermissionInfoInterface() { - return this.permissionInfoInterface; - } - - public void setPermissionInfoInterface(PermissionInfoInterface permissionInfoInterface) { - this.permissionInfoInterface = permissionInfoInterface; - } - - public PermissionInterceptor(PermissionInfoInterface permissionInfoInterface) { - this.setPermissionInfoInterface(permissionInfoInterface); - } - - - /* - * 进入controller层之前拦截请求 - * 返回值:表示是否将当前的请求拦截下来 false:拦截请求,请求别终止。true:请求不被拦截,继续执行 - * Object obj:表示被拦的请求的目标对象(controller中方法) - */ - @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - if (!(handler instanceof HandlerMethod)) { - return super.preHandle(request, response, handler); - } - - // 判断请求类型,如果是OPTIONS,直接返回 - String options = HttpMethod.OPTIONS.toString(); - if (options.equals(request.getMethod())) { - response.setStatus(HttpServletResponse.SC_OK); - return super.preHandle(request, response, handler); - } - - Method method = ((HandlerMethod) handler).getMethod(); - Object loginId = AuthenticeHolder.getLoginId(); - Set roleSet = this.getPermissionInfoInterface().getRoleSet(loginId); - Set permissionSet = this.getPermissionInfoInterface().getPermissionSet(loginId); - - RoleHolder.setRoleSet(roleSet); - PermissionHolder.setPermissionSet(permissionSet); - - if (AuthUtil.checkPermission(method, permissionSet) && AuthUtil.checkRole(method, roleSet)) { - return super.preHandle(request, response, handler); - } else { - // 权限和角色校验不通过 - // 直接抛出异常的话,就不需要return false了 - throw new NoPermissionException(); - } - } - - - /* - * 处理请求完成后视图渲染之前的处理操作 - * 通过ModelAndView参数改变显示的视图,或发往视图的方法 - */ - @Override - public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { - // logger.info("PermissionInterceptor -- postHandle -- 执行了"); - } - - /* - * 视图渲染之后的操作 - */ - @Override - public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { - // logger.info("PermissionInterceptor -- afterCompletion -- 执行了"); - RoleHolder.clearRoleSet(); - PermissionHolder.clearPermissionSet(); - } - -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/interceptor/holder/AuthenticeHolder.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/interceptor/holder/AuthenticeHolder.java deleted file mode 100644 index 340e090256..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/interceptor/holder/AuthenticeHolder.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.jun.plugin.security.interceptor.holder; - -import java.util.Objects; - -/** - * 本地线程变量-缓存用户会话信息 - * - * @version 2022-06-14 13:58 - **/ -public class AuthenticeHolder { - private final static ThreadLocal authentice = new ThreadLocal<>(); - - public static Object getLoginId() { - Object loginId = authentice.get(); - if (Objects.isNull(loginId)) { - return null; - } else { - return loginId; - } - } - - public static void setLoginId(Object loginId) { - authentice.set(loginId); - } - - public static void clearLoginId() { - authentice.remove(); - } -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/interceptor/holder/PermissionHolder.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/interceptor/holder/PermissionHolder.java deleted file mode 100644 index 159b716aeb..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/interceptor/holder/PermissionHolder.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.jun.plugin.security.interceptor.holder; - -import java.util.HashSet; -import java.util.Objects; -import java.util.Set; - -/** - * 本地线程变量-缓存用户权限资源值信息 - * - * @since 2023-06-04 13:58 - **/ -public class PermissionHolder { - private final static ThreadLocal> permissionSetLocal = new ThreadLocal<>(); - - public static Set getPermissionSet() { - Set permissionSet = permissionSetLocal.get(); - if (Objects.isNull(permissionSet)) { - return new HashSet(); - } else { - return permissionSet; - } - } - - public static void setPermissionSet(Set loginId) { - permissionSetLocal.set(loginId); - } - - public static void clearPermissionSet() { - permissionSetLocal.remove(); - } -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/interceptor/holder/RoleHolder.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/interceptor/holder/RoleHolder.java deleted file mode 100644 index 0f1ee07a78..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/interceptor/holder/RoleHolder.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.jun.plugin.security.interceptor.holder; - -import java.util.HashSet; -import java.util.Objects; -import java.util.Set; - - -/** - * 本地线程变量-缓存用户角色资源值信息 - * - * @since 2023-06-04 13:58 - **/ -public class RoleHolder { - - private final static ThreadLocal> roleSetLocal = new ThreadLocal<>(); - - public static Set getRoleSet() { - Set roleSet = roleSetLocal.get(); - if (Objects.isNull(roleSet)) { - return new HashSet(); - } else { - return roleSet; - } - } - - public static void setRoleSet(Set loginId) { - roleSetLocal.set(loginId); - } - - public static void clearRoleSet() { - roleSetLocal.remove(); - } - -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/interfaces/PermissionInfoInterface.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/interfaces/PermissionInfoInterface.java deleted file mode 100644 index 45110a6a90..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/interfaces/PermissionInfoInterface.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.jun.plugin.security.interfaces; - -import java.util.Set; - -/** - * 自定义权限验证接口扩展,注意权限缓存需要自己控制,框架不处理缓存 - * @version 2023-01-06-9:33 - **/ -public interface PermissionInfoInterface { - - /** - * 返回一个账号所拥有的权限码集合 - */ - Set getPermissionSet(Object loginId); - - /** - * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验) - */ - Set getRoleSet(Object loginId); -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/provider/AbstractAuthProvider.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/provider/AbstractAuthProvider.java deleted file mode 100644 index cb291963f1..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/provider/AbstractAuthProvider.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.jun.plugin.security.provider; - -import com.jun.plugin.security.AuthProperties; -import com.jun.plugin.security.util.AuthUtil; -import com.jun.plugin.security.util.CookieUtil; - -import javax.servlet.http.HttpServletRequest; - -public abstract class AbstractAuthProvider implements AuthProvider { - - protected abstract AuthProperties getAuthProperties(); - - /** - * 获取token - * @return - */ - @Override - public String getToken() { - String token = AuthUtil.getToken(this.getAuthProperties().getTokenName()); - return token; - } - - /** - * 获取token - * @param request HttpServletRequest - * @return - */ - @Override - public String getToken(HttpServletRequest request) { - String token = AuthUtil.getToken(request, this.getAuthProperties().getTokenName()); - return token; - } - - /** - * 执行登录操作 - * - * @param loginId 会话登录:参数填写要登录的账号id,建议的数据类型:long | int | String, 不可以传入复杂类型,如:User、Admin 等等 - */ - @Override - public String login(Object loginId) { - String token = this.createToken(loginId); - // 设置 Cookie,通过 Cookie 上下文返回给前端 - CookieUtil.setCookie(AuthUtil.getResponse(), this.getAuthProperties().getTokenName(), token); - return token; - } - - /** - * 退出登录 - */ - @Override - public void logout(HttpServletRequest request) { - this.deleteToken(this.getToken(request)); - } - - /** - * 退出登录 - */ - @Override - public void logout() { - this.deleteToken(this.getToken()); - } - - /** - * 获取当前登录用户的loginId - * - * @return - */ - @Override - public Object getLoginId() { - return this.getLoginId(this.getToken()); - } - - /** - * 校验当前会话是否登录 - * @return true已登录,false未登录 - */ - @Override - public boolean isLogin() { - return this.checkToken(this.getToken()); - } -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/provider/AuthProvider.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/provider/AuthProvider.java deleted file mode 100644 index 0717779e35..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/provider/AuthProvider.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.jun.plugin.security.provider; - - -import javax.servlet.http.HttpServletRequest; - -/** - * 操作token和会话的接口 - * - * @version 2023-01-06-9:33 - **/ -public interface AuthProvider { - - /*============================操作token开始=============================*/ - - /** - * 获取token - * @return - */ - String getToken(); - - /** - * 获取token - * @param request HttpServletRequest - * @return - */ - String getToken(HttpServletRequest request); - - /** - * 刷新token - * @param token - * @return - */ - boolean refreshToken(String token); - - /** - * 检查token是否失效 - * @param token - * @return - */ - boolean checkToken(String token); - - /** - * 创建一个新的token - * @param loginId 会话登录:参数填写要登录的账号id,建议的数据类型:long | int | String, 不可以传入复杂类型,如:User、Admin 等等 - * @return - */ - String createToken(Object loginId); - - /** - * 根据token,获取loginId - * @param token - * @return - */ - Object getLoginId(String token); - - /** - * 删除token - * @param token - * @return - */ - boolean deleteToken(String token); - - /** - * 通过loginId删除token---常用于主动让某人下线 - * @param loginId - * @return - */ - boolean deleteTokenByLoginId(Object loginId); - - /*============================操作token结束=============================*/ - - - /*============================操作会话开始,此部分在AbstractAuthProvider里予以实现=============================*/ - - /** - * 执行登录操作 - * @param loginId 会话登录:参数填写要登录的账号id,建议的数据类型:long | int | String, 不可以传入复杂类型,如:User、Admin 等等 - */ - String login(Object loginId); - - /** - * 退出登录 - */ - void logout(); - - /** - * HttpServletRequest request - * @param request - */ - void logout(HttpServletRequest request); - - /** - * 获取当前登录用户的loginId - * @return - */ - Object getLoginId(); - - /** - * 校验当前会话是否登录 - * @return true已登录,false未登录 - */ - boolean isLogin(); - /*============================操作会话结束=============================*/ -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/provider/JdbcAuthProvider.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/provider/JdbcAuthProvider.java deleted file mode 100644 index 62ef7b75fb..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/provider/JdbcAuthProvider.java +++ /dev/null @@ -1,210 +0,0 @@ -package com.jun.plugin.security.provider; - -import org.springframework.util.Assert; -import com.jun.plugin.security.AuthProperties; -import com.jun.plugin.security.util.CommonUtil; -import com.jun.plugin.security.util.TokenGenUtil; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.jdbc.core.JdbcTemplate; - -import java.time.LocalDateTime; -import java.time.temporal.ChronoUnit; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -/** - * 操作token和会话的接口(通过jdbc实现) - *了 - * @version 2023-01-06-9:33 - **/ -public class JdbcAuthProvider extends AbstractAuthProvider implements AuthProvider { - final static Logger log = LoggerFactory.getLogger(JdbcAuthProvider.class); - - private final JdbcTemplate jdbcTemplate; - - private final AuthProperties authProperties; - - public JdbcAuthProvider(JdbcTemplate jdbcTemplate, AuthProperties authProperties) { - this.jdbcTemplate = jdbcTemplate; - this.authProperties = authProperties; - - // 同时初始化定时任务 - this.initCleanThread(); - } - - @Override - protected AuthProperties getAuthProperties() { - return this.authProperties; - } - - - /** - * 刷新token有效时间 - * - * @param token 令牌 - * @return true成功,false失败 - */ - @Override - public boolean refreshToken(String token) { - Assert.hasText(token, "The token cannot be empty!"); - try { - String sql = "update " + this.getAuthProperties().getTableName() + " set token_expire_time = ? where token_str = ?"; - int num = jdbcTemplate.update(sql, CommonUtil.currentTimePlusSeconds(this.getAuthProperties().getTimeout()), token); - return num > 0; - } catch (Exception e) { - log.error("JdbcAuthProvider refreshToken failed, Exception: {e}", e); - return false; - } - } - - /** - * 检查token是否失效 - * - * @param token 令牌 - * @return true未失效,false已失效 - */ - @Override - public boolean checkToken(String token) { - Assert.hasText(token, "The token cannot be empty!"); - try { - String sql = "select token_expire_time from " + this.getAuthProperties().getTableName() + " where token_str=?"; - List> resultList = jdbcTemplate.queryForList(sql, token); - if (Objects.nonNull(resultList) && !resultList.isEmpty()) { - String tokenExpireTime = resultList.get(0).get("token_expire_time").toString(); - return CommonUtil.timeCompare(tokenExpireTime); - } - return false; - } catch (Exception e) { - log.error("JdbcAuthProvider checkToken failed, Exception: {e}", e); - return false; - } - } - - /** - * 创建一个新的token - * - * @param loginId 会话登录:参数填写要登录的账号id,建议的数据类型:long | int | String, 不可以传入复杂类型,如:User、Admin 等等 - * @return token令牌 - */ - @Override - public String createToken(Object loginId) { - Assert.notNull(loginId, "The loginId cannot be null!"); - try { - String token = TokenGenUtil.genTokenStr(this.getAuthProperties().getTokenStyle()); - String sql = "insert into " + this.getAuthProperties().getTableName() + " (token_str,login_id,token_expire_time) values (?,?,?)"; - int num = jdbcTemplate.update(sql, token, String.valueOf(loginId), CommonUtil.currentTimePlusSeconds(this.getAuthProperties().getTimeout())); - return num > 0 ? token : null; - } catch (Exception e) { - log.error("JdbcAuthProvider createToken failed, Exception: {e}", e); - return null; - } - } - - /** - * 根据token,获取loginId - * - * @param token 令牌 - * @return loginId - */ - @Override - public Object getLoginId(String token) { - Assert.hasText(token, "The token cannot be empty!"); - try { - String sql = "select login_id from " + this.getAuthProperties().getTableName() + " where token_str=?"; - List> resultList = jdbcTemplate.queryForList(sql, token); - if (Objects.nonNull(resultList) && !resultList.isEmpty()) { - return resultList.get(0).get("login_id"); - } - return null; - } catch (Exception e) { - log.error("JdbcAuthProvider getLoginId failed, Exception: {e}", e); - return null; - } - } - - /** - * 删除token - * - * @param token 令牌 - * @return true成功,false失败 - */ - @Override - public boolean deleteToken(String token) { - Assert.hasText(token, "The token cannot be empty!"); - try { - String sql = "delete from " + this.getAuthProperties().getTableName() + " where token_str = ?"; - int num = jdbcTemplate.update(sql, token); - return num > 0; - } catch (Exception e) { - log.error("JdbcAuthProvider deleteToken failed, Exception: {e}", e); - return false; - } - } - - /** - * 通过loginId删除token - * - * @param loginId 会话id - * @return true成功,false失败 - */ - @Override - public boolean deleteTokenByLoginId(Object loginId) { - Assert.notNull(loginId, "The loginId cannot be null!"); - try { - String sql = "delete from " + this.getAuthProperties().getTableName() + " where login_id = ?"; - int num = jdbcTemplate.update(sql, loginId); - return num > 0; - } catch (Exception e) { - log.error("JdbcAuthProvider deleteTokenByLoginId failed, Exception: {e}", e); - return false; - } - } - - /** - * 用于定时执行数据清理的线程池 - */ - public ScheduledExecutorService executorService; - - /** - * 初始化清理任务,每天执行一次 - */ - private void initCleanThread() { - this.executorService = Executors.newScheduledThreadPool(1); - - // 获取当前时间 - LocalDateTime now = LocalDateTime.now(); - // 获取明天凌晨第一秒的时间,如2023-08-25 00:00:01:000 - LocalDateTime tomorrow = now.plusDays(1).withHour(0).withMinute(0).withSecond(1).withNano(0); - // 计算初始延迟时间(单位-毫秒) - long initialDelay = ChronoUnit.MILLIS.between(now, tomorrow); - - this.executorService.scheduleAtFixedRate(() -> { - log.info("JdbcAuthProvider clean execute at: {}", CommonUtil.getCurrentTime()); - try { - // 执行清理方法 - this.clean(); - } catch (Exception e2) { - log.error("JdbcAuthProvider cleanThread Exception: {e2}", e2); - } - }, initialDelay/*首次延迟多长时间后执行*/, 24 * 60 * 60 * 1000/*间隔时间*/, TimeUnit.MILLISECONDS); - log.info("JdbcAuthProvider cleanThread init successful!"); - } - - - private void clean() { - try { - String sql = "delete from " + this.getAuthProperties().getTableName() + " where token_expire_time < ?"; - String criticalTime = CommonUtil.currentTimeMinusSeconds(24 * 60 * 60); - int num = jdbcTemplate.update(sql, criticalTime); - log.info("JdbcAuthProvider clean num: {}", num); - } catch (Exception e) { - log.error("JdbcAuthProvider clean failed, Exception: {e}", e); - } - } -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/provider/RedisAuthProvider.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/provider/RedisAuthProvider.java deleted file mode 100644 index 0ce868e7e9..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/provider/RedisAuthProvider.java +++ /dev/null @@ -1,154 +0,0 @@ -package com.jun.plugin.security.provider; - - -import org.springframework.util.Assert; -import com.jun.plugin.security.AuthProperties; -import com.jun.plugin.security.consts.AuthConsts; -import com.jun.plugin.security.util.TokenGenUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.util.StringUtils; - -import java.util.Objects; -import java.util.Set; -import java.util.concurrent.TimeUnit; - - -/** - * 操作token和会话的接口(通过redis实现) - * - * @version 2023-01-06-9:33 - **/ -public class RedisAuthProvider extends AbstractAuthProvider implements AuthProvider { - final static Logger log = LoggerFactory.getLogger(RedisAuthProvider.class); - - private final StringRedisTemplate redisTemplate; - private final AuthProperties authProperties; - - public RedisAuthProvider(StringRedisTemplate redisTemplate, AuthProperties authProperties) { - this.redisTemplate = redisTemplate; - this.authProperties = authProperties; - } - - @Override - protected AuthProperties getAuthProperties() { - return this.authProperties; - } - - /** - * 刷新token - * - * @param token 令牌 - * @return true成功,false失败 - */ - @Override - public boolean refreshToken(String token) { - Assert.hasText(token, "The token cannot be empty!"); - try { - return redisTemplate.expire(AuthConsts.AUTH_TOKEN_KEY + token, authProperties.getTimeout(), TimeUnit.SECONDS); - } catch (Exception e) { - log.error("RedisAuthProvider refreshToken failed, Exception:{e}", e); - return false; - } - } - - /** - * 检查token是否失效 - * - * @param token 令牌 - * @return true未失效,false已失效 - */ - @Override - public boolean checkToken(String token) { - Assert.hasText(token, "The token cannot be empty!"); - try { - return redisTemplate.hasKey(AuthConsts.AUTH_TOKEN_KEY + token); - } catch (Exception e) { - log.error("RedisAuthProvider checkToken failed, Exception:{e}", e); - return false; - } - } - - - /** - * 创建一个新的token - * - * @param loginId 会话登录:参数填写要登录的账号id,建议的数据类型:long | int | String, 不可以传入复杂类型,如:User、Admin 等等 - * @return token令牌 - */ - @Override - public String createToken(Object loginId) { - Assert.notNull(loginId, "The loginId cannot be null!"); - try { - String token = TokenGenUtil.genTokenStr(getAuthProperties().getTokenStyle()); - redisTemplate.opsForValue().set(AuthConsts.AUTH_TOKEN_KEY + token, String.valueOf(loginId), getAuthProperties().getTimeout(), TimeUnit.SECONDS); - return token; - } catch (Exception e) { - log.error("RedisAuthProvider createToken failed, Exception:{e}", e); - return null; - } - } - - - /** - * 根据token,获取loginId - * - * @param token 令牌 - * @return loginId - */ - @Override - public Object getLoginId(String token) { - Assert.hasText(token, "The token cannot be empty!"); - try { - return redisTemplate.opsForValue().get(AuthConsts.AUTH_TOKEN_KEY + token); - } catch (Exception e) { - log.error("RedisAuthProvider getLoginId failed, Exception:{e}", e); - return null; - } - } - - /** - * 删除token - * - * @param token 令牌 - * @return true成功,false失败 - */ - @Override - public boolean deleteToken(String token) { - Assert.hasText(token, "The token cannot be empty!"); - try { - return redisTemplate.delete(AuthConsts.AUTH_TOKEN_KEY + token); - } catch (Exception e) { - log.error("RedisAuthProvider deleteToken failed, Exception:{e}", e); - return false; - } - } - - /** - * 通过loginId删除token(目前是通过keys命令模糊查询的,数据量特别大时会有性能问题,后续优化) - * - * @param loginId 身份唯一值 - * @return true成功,false失败 - */ - @Override - public boolean deleteTokenByLoginId(Object loginId) { - Assert.notNull(loginId, "The loginId cannot be null!"); - try { - Set keys = redisTemplate.keys(AuthConsts.AUTH_TOKEN_KEY.concat("*")); - if (Objects.nonNull(keys) && !keys.isEmpty()) { - for (String key : keys) { - String loginIdInRedis = redisTemplate.opsForValue().get(key); - if (!StringUtils.isEmpty(loginIdInRedis) && loginIdInRedis.equals(loginId)) { - redisTemplate.delete(key); - } - } - } - return true; - } catch (Exception e) { - log.error("RedisAuthProvider deleteToken failed, Exception:{e}", e); - return false; - } - } - -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/provider/SingleAuthProvider.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/provider/SingleAuthProvider.java deleted file mode 100644 index 967dd41bb6..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/provider/SingleAuthProvider.java +++ /dev/null @@ -1,421 +0,0 @@ -package com.jun.plugin.security.provider; - - -import org.springframework.util.Assert; -import com.jun.plugin.security.AuthProperties; -import com.jun.plugin.security.consts.AuthConsts; -import com.jun.plugin.security.util.CommonUtil; -import com.jun.plugin.security.util.TokenGenUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.*; -import java.util.concurrent.*; - -/** - * 操作token和会话的接口(通过单机内存Map实现,系统重启后数据会丢失) - * 部分代码实现参考自 https://gitee.com/dromara/sa-token/blob/dev/sa-token-core/src/main/java/cn/dev33/satoken/dao/SaTokenDaoDefaultImpl.java - * - * @version 2023-01-06-9:33 - **/ -public class SingleAuthProvider extends AbstractAuthProvider implements AuthProvider { - final static Logger log = LoggerFactory.getLogger(SingleAuthProvider.class); - - /** - * 常量,每次清理过期数据间隔的时间 (单位: 秒) ,默认值30秒,设置为-1代表不启动定时清理------这里暂时先写死 - */ - final static int DATA_REFRESH_PERIOD = 30; - - /** - * 常量,表示系统中不存在这个缓存 (在对不存在的key获取剩余存活时间时返回此值) - */ - final static long NOT_VALUE_EXPIRE = -1L; - - /** - * 数据存储集合 - */ - public final static Map dataMap = new ConcurrentHashMap<>(); - - /** - * 数据的过期时间存储集合 (单位: 毫秒) , 记录所有key的到期时间 [注意不是剩余存活时间] - */ - public final static Map expireMap = new ConcurrentHashMap<>(); - - - // ------------------------ String 读写操作开始 ------------------------ // - - /** - * 从缓存中获取数据(String) - * - * @param key 键 - * @return 值 - */ - public String get(String key) { - clearKeyByTimeout(key); - return (String) dataMap.get(key); - } - - /** - * 往缓存中存入数据(String) - * - * @param key 键 - * @param value 值 - * @param timeout 有效时间(秒) - */ - public void set(String key, String value, long timeout) { - if (timeout == 0) { - return; - } - dataMap.put(key, value); - expireMap.put(key, (System.currentTimeMillis() + timeout * 1000)); - } - - /** - * 更新缓存数据(String) - * - * @param key 键 - * @param value 值 - */ - public void update(String key, String value) { - if (getKeyTimeout(key) == SingleAuthProvider.NOT_VALUE_EXPIRE) { - return; - } - dataMap.put(key, value); - } - - /** - * 删除缓存 - * - * @param key 键 - */ - public void delete(String key) { - dataMap.remove(key); - expireMap.remove(key); - } - - /** - * 获取缓存剩余存活时间 (单位:秒) - * - * @param key 键 - * @return 剩余存活时间 (单位:秒) - */ - public long getTimeout(String key) { - return getKeyTimeout(key); - } - - /** - * 更新缓存剩余存活时间 (单位:秒) - * - * @param key 键 - * @param timeout 有效时间(秒) - */ - public void updateTimeout(String key, long timeout) { - expireMap.put(key, (System.currentTimeMillis() + timeout * 1000)); - } - - // ------------------------ Object 读写操作开始 ------------------------ // - - /** - * 从缓存中获取数据(Object) - * - * @param key 键 - * @return 值 - */ - public Object getObject(String key) { - clearKeyByTimeout(key); - return dataMap.get(key); - } - - /** - * 往缓存中存入数据(Object) - * - * @param key 键 - * @param object 值 - * @param timeout 有效时间(秒) - */ - public void setObject(String key, Object object, long timeout) { - if (timeout == 0) { - return; - } - dataMap.put(key, object); - expireMap.put(key, (System.currentTimeMillis() + timeout * 1000)); - } - - /** - * 更新缓存数据(Object) - * - * @param key 键 - * @param object 值 - */ - public void updateObject(String key, Object object) { - if (getKeyTimeout(key) == SingleAuthProvider.NOT_VALUE_EXPIRE) { - return; - } - dataMap.put(key, object); - } - - /** - * 删除缓存 - * - * @param key 键 - */ - public void deleteObject(String key) { - dataMap.remove(key); - expireMap.remove(key); - } - - /** - * 获取缓存剩余存活时间 (单位:秒) - * - * @param key 键 - * @return 剩余存活时间 (单位:秒) - */ - public long getObjectTimeout(String key) { - return getKeyTimeout(key); - } - - /** - * 更新缓存剩余存活时间 (单位:秒) - * - * @param key 键 - * @param timeout 有效时间(秒) - */ - public void updateObjectTimeout(String key, long timeout) { - expireMap.put(key, (System.currentTimeMillis() + timeout * 1000)); - } - - // ------------------------ 过期时间相关操作开始 ------------------------ // - - /** - * 如果指定key已经过期,则立即清除它 - * - * @param key 键 - */ - private void clearKeyByTimeout(String key) { - Long expirationTime = expireMap.get(key); - // 清除条件:如果不为空 && 已经超过过期时间 - if (expirationTime != null && expirationTime < System.currentTimeMillis()) { - dataMap.remove(key); - expireMap.remove(key); - } - } - - /** - * 获取指定key的剩余存活时间 (单位:秒) - * - * @param key 键 - */ - private long getKeyTimeout(String key) { - // 先检查是否已经过期 - clearKeyByTimeout(key); - // 获取过期时间 - Long expire = expireMap.get(key); - // 如果根本没有这个值,则直接返回NOT_VALUE_EXPIRE - if (expire == null) { - return SingleAuthProvider.NOT_VALUE_EXPIRE; - } - // 计算剩余时间并返回 - long timeout = (expire - System.currentTimeMillis()) / 1000; - // 小于零时,视为不存在,返回NOT_VALUE_EXPIRE - if (timeout < 0) { - dataMap.remove(key); - expireMap.remove(key); - return SingleAuthProvider.NOT_VALUE_EXPIRE; - } - return timeout; - } - - - // ------------------------ 定时清理过期数据 ------------------------ // - /** - * 线程池核心线程数最大值 - */ - public static final int corePoolSize = 5; - - /** - * 用于定时执行数据清理的线程池 - */ - public ScheduledExecutorService executorService; - - /** - * 是否继续执行数据清理的线程标记 - */ - public volatile boolean refreshFlag; - - /** - * 清理所有已经过期的key - */ - public void refreshDataMap() { - for (String key : expireMap.keySet()) { - clearKeyByTimeout(key); - } - } - - /** - * 初始化定时任务 - */ - public void initRefreshThread() { - // 如果配置了<=0的值,则不启动定时清理 - if (SingleAuthProvider.DATA_REFRESH_PERIOD <= 0) { - return; - } - // 启动定时刷新 - this.refreshFlag = true; - this.executorService = Executors.newScheduledThreadPool(corePoolSize); - this.executorService.scheduleWithFixedDelay(() -> { - log.info("SingleAuthProvider - refreshSession - at :{}", CommonUtil.getCurrentTime()); - try { - // 如果已经被标记为结束 - if (!refreshFlag) { - return; - } - // 执行清理方法 - refreshDataMap(); - } catch (Exception e2) { - log.error("SingleAuthProvider - refreshSession - Exception:{e2}", e2); - } - }, 10/*首次延迟多长时间后执行*/, DATA_REFRESH_PERIOD/*间隔时间*/, TimeUnit.SECONDS); - log.info("SingleAuthProvider - refreshThread - init successful!"); - } - - - /** - * 结束定时任务,不再定时清理过期数据 - */ - public void endRefreshThread() { - this.refreshFlag = false; - } - - - // ------------------------ 实现AuthProvider接口开始 ------------------------ // - private final AuthProperties authProperties; - - /** - * 构造函数 - */ - public SingleAuthProvider(AuthProperties authProperties) { - this.authProperties = authProperties; - // 同时初始化定时任务 - this.initRefreshThread(); - } - - @Override - protected AuthProperties getAuthProperties() { - return this.authProperties; - } - - /** - * 刷新token - * - * @param token 令牌 - * @return true成功,false失败 - */ - @Override - public boolean refreshToken(String token) { - Assert.hasText(token, "The token cannot be empty!"); - try { - this.updateTimeout(AuthConsts.AUTH_TOKEN_KEY + token, this.getAuthProperties().getTimeout()); - return true; - } catch (Exception e) { - log.error("SingleAuthProvider - refreshToken - failed,Exception:{e}", e); - return false; - } - } - - /** - * 检查token是否失效 - * - * @param token 令牌 - * @return true有效,false已失效 - */ - @Override - public boolean checkToken(String token) { - Assert.hasText(token, "The token cannot be empty!"); - try { - long timeout = this.getTimeout(AuthConsts.AUTH_TOKEN_KEY + token); - return timeout > 0; - } catch (Exception e) { - log.error("SingleAuthProvider - checkToken - failed,Exception:{e}", e); - return false; - } - } - - /** - * 创建一个新的token - * - * @param loginId 会话登录:参数填写要登录的账号id,建议的数据类型:long | int | String, 不可以传入复杂类型,如:User、Admin 等等 - * @return token - */ - @Override - public String createToken(Object loginId) { - Assert.notNull(loginId, "The loginId cannot be null!"); - try { - String token = TokenGenUtil.genTokenStr(this.getAuthProperties().getTokenStyle()); - this.set(AuthConsts.AUTH_TOKEN_KEY + token, String.valueOf(loginId), this.getAuthProperties().getTimeout()); - return token; - } catch (Exception e) { - log.error("SingleAuthProvider - createToken - failed,Exception:{e}", e); - return null; - } - } - - /** - * 根据token,获取loginId - * - * @param token 令牌 - * @return loginId - */ - @Override - public Object getLoginId(String token) { - Assert.hasText(token, "The token cannot be empty!"); - try { - return this.get(AuthConsts.AUTH_TOKEN_KEY + token); - } catch (Exception e) { - log.error("SingleAuthProvider - getLoginId - failed,Exception:{e}", e); - return null; - } - } - - /** - * 删除token - * - * @param token 令牌 - * @return true成功,false失败 - */ - @Override - public boolean deleteToken(String token) { - Assert.hasText(token, "The token cannot be empty!"); - try { - this.delete(AuthConsts.AUTH_TOKEN_KEY + token); - return true; - } catch (Exception e) { - log.error("SingleAuthProvider - deleteToken - failed,Exception:{e}", e); - return false; - } - } - - - /** - * 通过loginId删除token - * - * @param loginId 用户id - * @return true成功,false失败 - */ - @Override - public boolean deleteTokenByLoginId(Object loginId) { - Assert.notNull(loginId, "The loginId cannot be null!"); - try { - for (String key : expireMap.keySet()) { - if (loginId.equals(dataMap.get(key))) { - dataMap.remove(key); - expireMap.remove(key); - } - } - return true; - } catch (Exception e) { - log.error("SingleAuthProvider - deleteTokenByLoginId - failed,Exception:{e}", e); - return false; - } - } - -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/AuthUtil.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/AuthUtil.java deleted file mode 100644 index ee61136127..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/AuthUtil.java +++ /dev/null @@ -1,325 +0,0 @@ -package com.jun.plugin.security.util; - -import com.jun.plugin.security.annotation.Ignore; -import com.jun.plugin.security.annotation.RequiresPermissions; -import com.jun.plugin.security.annotation.RequiresRoles; -import com.jun.plugin.security.enums.Logical; -import com.jun.plugin.security.interceptor.holder.AuthenticeHolder; - -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; -import org.springframework.util.StringUtils; -import com.jun.plugin.security.interceptor.holder.PermissionHolder; -import com.jun.plugin.security.interceptor.holder.RoleHolder; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.lang.reflect.Method; -import java.util.HashSet; -import java.util.Set; - -public class AuthUtil { - - /** - * 获取当前请求对象 - * - * @return HttpServletRequest - */ - public static HttpServletRequest getRequest() { - HttpServletRequest request = null; - try { - request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest(); - return request; - } catch (Exception e) { - return null; - } - } - - /** - * 获取当前响应对象 - * - * @return HttpServletResponse - */ - public static HttpServletResponse getResponse() { - HttpServletResponse response = null; - try { - response = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getResponse(); - return response; - } catch (Exception e) { - return null; - } - } - - - /** - * 获取用户token - * - * @return token - */ - public static String getToken(String tokenName) { - HttpServletRequest request = null; - try { - request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest(); - // 从请求中获取token,先从Header里取,取不到的话再从cookie里取(适配前后端分离的模式) - String token = request.getHeader(tokenName); - if (StringUtils.isEmpty(token)) { - token = CookieUtil.getCookie(request, tokenName); - } - // cookie里取不到,再从请求参数里面取 - if (StringUtils.isEmpty(token)) { - token = request.getParameter(tokenName); - } - return token; - } catch (Exception e) { - return null; - } - } - - - /** - * 获取用户token - * - * @return token - */ - public static String getToken(HttpServletRequest request, String tokenName) { - // 从请求中获取token,先从Header里取,取不到的话再从cookie里取(适配前后端分离的模式) - String token = request.getHeader(tokenName); - if (StringUtils.isEmpty(token)) { - token = CookieUtil.getCookie(request, tokenName); - } - // cookie里取不到,再从请求参数里面取 - if (StringUtils.isEmpty(token)) { - token = request.getParameter(tokenName); - } - return token; - } - - - /** - * 检查Method上是否有@Ignore注解,决定是否忽略会话认证 - * - * @param method Method - * @return true or false - */ - public static boolean checkIgnore(Method method) { - // 先获取方法上的注解 - Ignore annotation = method.getAnnotation(Ignore.class); - // 方法上没有注解再检查类上面有没有注解 - if (annotation == null) { - annotation = method.getDeclaringClass().getAnnotation(Ignore.class); - } - return annotation != null; - } - - - /** - * 检查Method上是否有@RequiresPermissions注解,并检验其值,通过返回true,拒绝返回false - * - * @param method Method - * @param permissionSet 权限列表 - * @return true or false - */ - public static boolean checkPermission(Method method, Set permissionSet) { - // 当permissionSet为空时,赋初值,防止空指针错误 - if (permissionSet == null) { - permissionSet = new HashSet<>(); - } - - RequiresPermissions annotation = method.getAnnotation(RequiresPermissions.class); - // 方法上没有注解再检查类上面有没有注解 - if (annotation == null) { - annotation = method.getDeclaringClass().getAnnotation(RequiresPermissions.class); - } - // 接口上没有注解,说明这个接口无权限控制,直接通过 - if (annotation == null) { - return true; - } - - String[] permissions = annotation.value(); - Logical logical = annotation.logical(); - if (logical == Logical.OR) { - // 如果有任何一个权限,返回true,否则返回false(拥有其一) - for (String perm : permissions) { - if (permissionSet.contains(perm)) { - return true; - } - } - return false; - } else if (logical == Logical.AND) { - // 只要有一个权限不是true的,就返回false(同时拥有) - for (String perm : permissions) { - if (!permissionSet.contains(perm)) { - return false; - } - } - return true; - } else { - return false; - } - } - - - /** - * 检查Method上是否有@RequiresPermissions注解,并检验其值,通过返回true,拒绝返回false - * - * @param method Method - * @param roleSet 角色列表 - * @return true or false - */ - public static boolean checkRole(Method method, Set roleSet) { - // 当roleSet为空时,赋初值,防止空指针错误 - if (roleSet == null) { - roleSet = new HashSet<>(); - } - - RequiresRoles annotation = method.getAnnotation(RequiresRoles.class); - // 方法上没有注解再检查类上面有没有注解 - if (annotation == null) { - annotation = method.getDeclaringClass().getAnnotation(RequiresRoles.class); - } - // 接口上没有注解,说明这个接口无权限控制,直接通过 - if (annotation == null) { - return true; - } - - String[] roles = annotation.value(); - Logical logical = annotation.logical(); - - if (logical == Logical.OR) { - // 如果有任何一个角色,返回true,否则返回false(拥有其一) - for (String ro : roles) { - if (roleSet.contains(ro)) { - return true; - } - } - return false; - } else if (logical == Logical.AND) { - // 只要有一个角色不是true的,就返回false(同时拥有) - for (String ro : roles) { - if (!roleSet.contains(ro)) { - return false; - } - } - return true; - } else { - return false; - } - } - - - /** - * 获取当前登录用户的LoginId - * - * @return Object - */ - public static Object getLoginId() { - return AuthenticeHolder.getLoginId(); - } - - /** - * 判断拥有角色:role1 - * - * @return - */ - public static boolean hasRole(String role) { - Set roleSet = RoleHolder.getRoleSet(); - if (roleSet == null || roleSet.isEmpty()) { - return false; - } - return roleSet.contains(role); - } - - /** - * 判断拥有角色:role1 and role2 - * - * @param roles - * @return - */ - public static boolean hasAllRole(String... roles) { - Set roleSet = RoleHolder.getRoleSet(); - if (roleSet == null || roleSet.isEmpty()) { - return false; - } - // 只要有一个角色不是true的,就返回false(同时拥有) - for (String ro : roles) { - if (!roleSet.contains(ro)) { - return false; - } - } - return true; - } - - /** - * 判断拥有角色:role1 or role2 or role3 有其一即可 - * - * @param roles - * @return - */ - public static boolean hasAnyRole(String... roles) { - Set roleSet = RoleHolder.getRoleSet(); - if (roleSet == null || roleSet.isEmpty()) { - return false; - } - // 如果有任何一个角色,返回true,否则返回false(拥有其一) - for (String ro : roles) { - if (roleSet.contains(ro)) { - return true; - } - } - return false; - } - - - /** - * 判断拥有权限:permission1 - * - * @return - */ - public static boolean hasPermission(String permission) { - Set permissionSet = PermissionHolder.getPermissionSet(); - if (permissionSet == null || permissionSet.isEmpty()) { - return false; - } - return permissionSet.contains(permission); - } - - /** - * 判断拥有角色:permission1 and permission2 - * - * @param permissions - * @return - */ - public static boolean hasAllPermission(String... permissions) { - Set permissionSet = PermissionHolder.getPermissionSet(); - if (permissionSet == null || permissionSet.isEmpty()) { - return false; - } - // 只要有一个权限不是true的,就返回false(同时拥有) - for (String pe : permissions) { - if (!permissionSet.contains(pe)) { - return false; - } - } - return true; - } - - /** - * 判断拥有权限:permission1 or permission2 or permission3 有其一即可 - * - * @param permissions - * @return - */ - public static boolean hasAnyPermission(String... permissions) { - Set permissionSet = PermissionHolder.getPermissionSet(); - if (permissionSet == null || permissionSet.isEmpty()) { - return false; - } - // 如果有任何一个权限,返回true,否则返回false(拥有其一) - for (String pe : permissions) { - if (permissionSet.contains(pe)) { - return true; - } - } - return false; - } -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/CommonUtil.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/CommonUtil.java deleted file mode 100644 index c985998d16..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/CommonUtil.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.jun.plugin.security.util; - -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.concurrent.ThreadLocalRandom; - - -/** - * 一些公共的,不好分类的工具方法放在这里 - * - * @version 2023-01-06-9:33 - **/ -public class CommonUtil { - - private final static String TIME_FORMAT = "yyyyMMddHHmmss"; - - - /** - * 获取当前时间 比如 DateTool.getCurrentTime(); 返回值为 20120515234420 - * - * @return dateTimeStr yyyyMMddHHmmss - */ - public static String getCurrentTime() { - LocalDateTime dateTime = LocalDateTime.now(); - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(TIME_FORMAT); - return dateTimeFormatter.format(dateTime); - } - - /** - * 在当前时间上增加 若干秒 - * - * @param secondsCount 要增加的秒数 - * @return 固定格式 yyyyMMddHHmmss - */ - public static String currentTimePlusSeconds(int secondsCount) { - LocalDateTime time = LocalDateTime.now(); - LocalDateTime newTime = time.plusSeconds(secondsCount); // 增加几秒 - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(TIME_FORMAT); - return dateTimeFormatter.format(newTime); - } - - /** - * 在当前时间上减少 若干秒 - * - * @param secondsCount 要减少的秒数 - * @return 固定格式 yyyyMMddHHmmss - */ - public static String currentTimeMinusSeconds(int secondsCount) { - LocalDateTime time = LocalDateTime.now(); - LocalDateTime newTime = time.minusSeconds(secondsCount); // 减少几秒 - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(TIME_FORMAT); - return dateTimeFormatter.format(newTime); - } - - - /** - * 生成指定长度的随机字符串(包括大小写字母,数字和下划线) - * - * @param length 字符串的长度 - * @return 一个随机字符串 - */ - public static String getRandomString(int length) { - String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"; - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < length; i++) { - int number = ThreadLocalRandom.current().nextInt(63); - sb.append(str.charAt(number)); - } - return sb.toString(); - } - - /** - * 字符串转时间 然后比较大小 - * - * @param tempTime 要比较的时间字符串,格式为yyyyMMddHHmmss, - * @return true:输入时间大于当前时间 ,false:输入时间小于当前时间 - */ - public static boolean timeCompare(String tempTime) { - DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern(TIME_FORMAT); - LocalDateTime localDateTime = LocalDateTime.parse(tempTime, dtf2); - return localDateTime.isAfter(LocalDateTime.now()); - } - -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/CookieUtil.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/CookieUtil.java deleted file mode 100644 index 606dc1c649..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/CookieUtil.java +++ /dev/null @@ -1,162 +0,0 @@ -package com.jun.plugin.security.util; - -import org.springframework.util.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; -import java.net.URLEncoder; - -/** - * @date 2021-01-30-11:18 - * @description Cookie工具类 - **/ -public class CookieUtil { - private static Logger logger = LoggerFactory.getLogger(CookieUtil.class); - - /** - * 设置 Cookie(生成时间为1天) - * - * @param response 响应对象 - * @param name 名称 - * @param value 值 - */ - public static void setCookie(HttpServletResponse response, String name, String value) { - setCookie(response, name, value, 60 * 60 * 24); - } - - /** - * 设置 Cookie - * - * @param response 响应对象 - * @param name 名称 - * @param value 值 - * @param path 上下文路径 - */ - public static void setCookie(HttpServletResponse response, String name, String value, String path) { - setCookie(response, name, value, path, 60 * 60 * 24); - } - - /** - * 设置 Cookie - * - * @param response 响应对象 - * @param name 名称 - * @param value 值 - * @param maxAge 生存时间(单位秒) - */ - public static void setCookie(HttpServletResponse response, String name, String value, int maxAge) { - setCookie(response, name, value, "/", maxAge); - } - - /** - * 设置 Cookie - * - * @param response 响应对象 - * @param name 名称 - * @param value 值 - * @param maxAge 生存时间(单位秒) - * @param path 上下文路径 - */ - public static void setCookie(HttpServletResponse response, String name, String value, String path, int maxAge) { - if (!StringUtils.isEmpty(name)) { - Cookie cookie = new Cookie(name, null); - cookie.setPath(path); - cookie.setMaxAge(maxAge); - cookie.setHttpOnly(true); - try { - cookie.setValue(URLEncoder.encode(value, "utf-8")); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - response.addCookie(cookie); - } - } - - /** - * 获得指定Cookie的值 - * @param request 请求对象 - * @param name 名称 - * @return 值 - */ - public static String getCookie(HttpServletRequest request, String name) { - return getCookie(request, null, name, false); - } - - /** - * 获得指定Cookie的值,并删除。 - * - * @param request 请求对象 - * @param response 响应对象 - * @param name 名称 - * @return 值 - */ - public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name) { - return getCookie(request, response, name, false); - } - - /** - * 获得指定Cookie的值 - * - * @param request 请求对象 - * @param response 响应对象 - * @param name 名字 - * @param path 上下文路径 - * @return 值 - */ - public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name, String path) { - return getCookie(request, response, name, path, false); - } - - /** - * 获得指定Cookie的值 - * - * @param request 请求对象 - * @param response 响应对象 - * @param name 名字 - * @param isRemove 是否移除 - * @return 值 - */ - public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name, boolean isRemove) { - return getCookie(request, response, name, "/", isRemove); - } - - /** - * 获得指定Cookie的值 - * - * @param request 请求对象 - * @param response 响应对象 - * @param name 名字 - * @param isRemove 是否移除 - * @return 值 - */ - public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name, String path, boolean isRemove) { - String value = null; - if (!StringUtils.isEmpty(name)) { - Cookie[] cookies = request.getCookies(); - if (cookies != null) { - for (Cookie cookie : cookies) { - if (cookie.getName().equals(name)) { - try { - value = URLDecoder.decode(cookie.getValue(), "utf-8"); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - if (isRemove && response != null) { - cookie.setPath(path); - cookie.setMaxAge(0); - response.addCookie(cookie); - } - } - } - } - } - return value; - } - - -} \ No newline at end of file diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/JsonUtil.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/JsonUtil.java deleted file mode 100644 index 61bff1a5ba..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/JsonUtil.java +++ /dev/null @@ -1,142 +0,0 @@ -package com.jun.plugin.security.util; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -/** - * Json工具类(基于jackson) - * - * @version 2022-03-11-16:47 - **/ -public class JsonUtil { - - final static Logger log = LoggerFactory.getLogger(JsonUtil.class); - - - /** - * 对象转JSON字符串 - * @param value 待转换对象 - * @return JSON字符串 - */ - public static String writeValueAsString(Object value) { - if (value != null) { - try { - ObjectMapper objectMapper = new ObjectMapper(); - return objectMapper.writeValueAsString(value); - } catch (JsonProcessingException e) { - if (log.isErrorEnabled()) { - log.error("JsonUtil -- writeValueAsString -- Exception=", e); - } - } - } - return ""; - } - - - /** - * JSON字符串转对象 - * @param content JSON字符串 - * @param valueType 类型 - * @param 对象 - * @return 对象 - */ - public static T readValue(String content, Class valueType) { - if (content != null && !content.trim().isEmpty()) { - try { - ObjectMapper objectMapper = new ObjectMapper(); - return objectMapper.readValue(content, valueType); - } catch (IOException e) { - if (log.isErrorEnabled()) { - log.error("JsonUtil -- readValue -- Exception=", e); - } - } - } - - return null; - } - - /** - * JSON字符串转对象 - * @param content JSON字符串 - * @param valueTypeRef TypeReference - * @param 对象 - * @return 对象 - */ - public static T readValue(String content, TypeReference valueTypeRef) { - if (content != null && !content.trim().isEmpty()) { - try { - ObjectMapper objectMapper = new ObjectMapper(); - return objectMapper.readValue(content, valueTypeRef); - } catch (IOException e) { - if (log.isErrorEnabled()) { - log.error("JsonUtil -- readValue -- Exception=", e); - } - } - } - return null; - } - - - /** - * InputStream文件流转对象 - * @param src 输入流 - * @param valueType 类型 - * @param 对象 - * @return 对象 - */ - public static T readValue(InputStream src, Class valueType) { - if (src != null) { - try { - ObjectMapper objectMapper = new ObjectMapper(); - return objectMapper.readValue(src, valueType); - } catch (IOException e) { - if (log.isErrorEnabled()) { - log.error("JsonUtil -- readValue -- Exception=", e); - } - } - } - return null; - } - - /** - * JSON字符串转List - * @param content JSON字符串 - * @param clazz 类型 - * @param 对象 - * @return 对象 - */ - public static List readArrayValue(String content, Class clazz) { - if (content != null && !content.trim().isEmpty()) { - try { - ObjectMapper objectMapper = new ObjectMapper(); - return objectMapper.readValue(content, objectMapper.getTypeFactory().constructParametricType(ArrayList.class, clazz)); - } catch (Exception e) { - if (log.isErrorEnabled()) { - log.error("JsonUtil -- readArrayValue -- Exception=", e); - } - } - } - return null; - } - - /** - * 类型转换 - * @param fromValue - * @param toValueType - * @param - * @return - */ - public static T convertValue(Object fromValue, Class toValueType) { - ObjectMapper objectMapper = new ObjectMapper(); - return objectMapper.convertValue(fromValue, toValueType); - } - -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/LocalHostUtil.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/LocalHostUtil.java deleted file mode 100644 index 5d2809624b..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/LocalHostUtil.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.jun.plugin.security.util; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.net.Inet4Address; -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.SocketException; -import java.util.Enumeration; - -/** - *

        - * java获取本地虚拟机IP - *

        - * - * @since 2023-04-06 15:11:53 - */ -public class LocalHostUtil { - private static final Logger log = LoggerFactory.getLogger(LocalHostUtil.class); - - /** - * 获取本机ip - * - * @return String - */ - public static String getLocalHost() { - Enumeration allNetInterfaces; - String ipLocalHost = null; - InetAddress ip = null; - try { - allNetInterfaces = NetworkInterface.getNetworkInterfaces(); - while (allNetInterfaces.hasMoreElements()) { - NetworkInterface netInterface = allNetInterfaces.nextElement(); - Enumeration addresses = netInterface.getInetAddresses(); - while (addresses.hasMoreElements()) { - ip = (InetAddress) addresses.nextElement(); - if (ip instanceof Inet4Address) { - String hostAddress = ip.getHostAddress(); - if (!hostAddress.equals("127.0.0.1") && !hostAddress.equals("/127.0.0.1")) { - // 得到本地IP - ipLocalHost = ip.toString().split("[/]")[1]; - } - } - } - } - } catch (SocketException e) { - log.error("getLocalHost SocketException:", e); - } - return ipLocalHost; - } - - - /** - * 获取本机InetAddress - * - * @return String - */ - public static InetAddress getInetAddress() { - Enumeration allNetInterfaces; - InetAddress inetAddress = null; - try { - allNetInterfaces = NetworkInterface.getNetworkInterfaces(); - while (allNetInterfaces.hasMoreElements()) { - NetworkInterface netInterface = allNetInterfaces.nextElement(); - Enumeration addresses = netInterface.getInetAddresses(); - while (addresses.hasMoreElements()) { - InetAddress temp = addresses.nextElement(); - if (temp instanceof Inet4Address && !temp.isLoopbackAddress()) { - String host = temp.getHostAddress(); - if (host != null && !"0.0.0.0".equals(host) && !"127.0.0.1".equals(host)) { - inetAddress = temp; - } - } - } - } - } catch (SocketException e) { - log.error("getInetAddress SocketException:", e); - } - return inetAddress; - } - - - public static void main(String[] args) { - System.out.println(getLocalHost()); - System.out.println(getInetAddress().getHostAddress()); - } -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/TokenGenUtil.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/TokenGenUtil.java deleted file mode 100644 index 850badd51a..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/TokenGenUtil.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.jun.plugin.security.util; - -import com.jun.plugin.security.util.idgen.NanoId; -import com.jun.plugin.security.util.idgen.ObjectId; -import com.jun.plugin.security.util.idgen.Snowflake; - -import java.util.UUID; - -/** - * token字符串生成工具类 - * - * @version 2022-05-21 9:53 - **/ -public class TokenGenUtil { - - final static String TOKEN_STYLE_UUID = "uuid"; - - final static String TOKEN_STYLE_SNOWFLAKE = "snowflake"; - - final static String TOKEN_STYLE_OBJECTID = "objectid"; - - final static String TOKEN_STYLE_RANDOM128 = "random128"; - - final static String TOKEN_STYLE_NANOID = "nanoid"; - - /** - * 根据参数生存不同风格的token字符串 - * - * @param tokenStyle token风格 - * @return token字符串 - */ - public static String genTokenStr(String tokenStyle) { - String token; - switch (tokenStyle) { - case TOKEN_STYLE_UUID: - token = UUID.randomUUID().toString().replace("-", ""); - break; - case TOKEN_STYLE_SNOWFLAKE: - token = Snowflake.nextId(); - break; - case TOKEN_STYLE_OBJECTID: - token = ObjectId.nextId(); - break; - case TOKEN_STYLE_RANDOM128: - token = CommonUtil.getRandomString(128); - break; - case TOKEN_STYLE_NANOID: - token = NanoId.INSTANCE.randomNanoId(); - break; - default: - token = UUID.randomUUID().toString().replaceAll("-", ""); - break; - } - return token; - } - -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/idgen/NanoId.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/idgen/NanoId.java deleted file mode 100644 index 83575279b2..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/idgen/NanoId.java +++ /dev/null @@ -1,145 +0,0 @@ -package com.jun.plugin.security.util.idgen; - -import java.security.SecureRandom; -import java.util.Random; - -/** - * A class for generating unique String IDs. - *

        - * The implementations of the core logic in this class are based on NanoId, a JavaScript - * library by Andrey Sitnik released under the MIT license. (https://github.com/ai/nanoid) - *

        - * Referenced from (https://github.com/dph5199278/jnanoid) - *

        - * - * @version 2022-05-21 9:53 - */ -public enum NanoId { - - - /** - * NanoId instance. - */ - INSTANCE; - - /** - * The default random number generator used by this class. - * Creates cryptographically strong NanoId Strings. - */ - private final SecureRandom DEFAULT_NUMBER_GENERATOR = new SecureRandom(); - - /** - * The default alphabet used by this class. - * Creates url-friendly NanoId Strings using 64 unique symbols. - */ - private final char[] DEFAULT_ALPHABET = - "_-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray(); - - /** - * The default size used by this class. - * Creates NanoId Strings with slightly more unique values than UUID v4. - */ - private final int DEFAULT_SIZE = 21; - - /** - * Static factory to retrieve an url-friendly, pseudo randomly generated, NanoId String. - *

        - * The generated NanoId String will have 21 symbols. - *

        - * The NanoId String is generated using a cryptographically strong pseudo random number - * generator. - * - * @return A randomly generated NanoId String. - */ - public String randomNanoId() { - return randomNanoId(DEFAULT_NUMBER_GENERATOR, DEFAULT_ALPHABET, DEFAULT_SIZE); - } - - /** - * Static factory to retrieve an url-friendly, pseudo randomly generated, NanoId String. - *

        - * The NanoId String is generated using a cryptographically strong pseudo random number - * generator. - * - * @param size The number of symbols in the NanoId String. - * @return A randomly generated NanoId String. - */ - public String randomNanoId(final int size) { - return randomNanoId(DEFAULT_NUMBER_GENERATOR, DEFAULT_ALPHABET, size); - } - - /** - * Static factory to retrieve an url-friendly, pseudo randomly generated, NanoId String. - *

        - * The NanoId String is generated using a cryptographically strong pseudo random number - * generator. - * - * @param alphabet The symbols used in the NanoId String. - * @return A randomly generated NanoId String. - */ - public String randomNanoId(final char[] alphabet) { - return randomNanoId(DEFAULT_NUMBER_GENERATOR, alphabet, DEFAULT_SIZE); - } - - /** - * Static factory to retrieve an url-friendly, pseudo randomly generated, NanoId String. - *

        - * The NanoId String is generated using a cryptographically strong pseudo random number - * generator. - * - * @param alphabet The symbols used in the NanoId String. - * @param size The number of symbols in the NanoId String. - * @return A randomly generated NanoId String. - */ - public String randomNanoId(final char[] alphabet, final int size) { - return randomNanoId(DEFAULT_NUMBER_GENERATOR, alphabet, size); - } - - /** - * Static factory to retrieve a NanoId String. - *

        - * The string is generated using the given random number generator. - * - * @param random The random number generator. - * @param alphabet The symbols used in the NanoId String. - * @param size The number of symbols in the NanoId String. - * @return A randomly generated NanoId String. - */ - public String randomNanoId(final Random random, final char[] alphabet, final int size) { - if (random == null) { - throw new IllegalArgumentException("random cannot be null."); - } - if (alphabet == null) { - throw new IllegalArgumentException("alphabet cannot be null."); - } - if (alphabet.length == 0 || alphabet.length >= 256) { - throw new IllegalArgumentException("alphabet must contain between 1 and 255 symbols."); - } - if (size <= 0) { - throw new IllegalArgumentException("size must be greater than zero."); - } - - final int mask = (2 << (int) Math.floor(Math.log(alphabet.length - 1) / Math.log(2))) - 1; - final int step = (int) Math.ceil(1.6 * mask * size / alphabet.length); - - final StringBuilder idBuilder = new StringBuilder(size); - final byte[] bytes = new byte[step]; - - while (true) { - - random.nextBytes(bytes); - - for (int i = 0; i < step; i++) { - - final int alphabetIndex = bytes[i] & mask; - - if (alphabetIndex < alphabet.length) { - idBuilder.append(alphabet[alphabetIndex]); - if (idBuilder.length() == size) { - return idBuilder.toString(); - } - } - } - } - } -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/idgen/ObjectId.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/idgen/ObjectId.java deleted file mode 100644 index a6e97c244f..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/idgen/ObjectId.java +++ /dev/null @@ -1,294 +0,0 @@ -package com.jun.plugin.security.util.idgen; - - -import java.io.Serializable; -import java.nio.ByteBuffer; -import java.security.SecureRandom; -import java.util.Date; -import java.util.concurrent.atomic.AtomicInteger; - - -/** - * MongoDb ObjectId java版实现 - * - * @version 2022-05-21 9:53 - **/ -public final class ObjectId implements Comparable, Serializable { - private static final long serialVersionUID = 3670079982654483072L; - - private static final int RANDOM_VALUE1; - private static final short RANDOM_VALUE2; - private static final AtomicInteger NEXT_COUNTER = new AtomicInteger((new SecureRandom()).nextInt()); - private static final char[] HEX_CHARS = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; - private final int timestamp; - private final int counter; - private final int randomValue1; - private final short randomValue2; - - public static boolean isValid(String hexString) { - if (hexString == null) { - throw new IllegalArgumentException(); - } else { - int len = hexString.length(); - if (len != 24) { - return false; - } else { - for (int i = 0; i < len; ++i) { - char c = hexString.charAt(i); - if ((c < '0' || c > '9') && (c < 'a' || c > 'f') && (c < 'A' || c > 'F')) { - return false; - } - } - - return true; - } - } - } - - public ObjectId() { - this(new Date()); - } - - public ObjectId(Date date) { - this(dateToTimestampSeconds(date), NEXT_COUNTER.getAndIncrement() & 16777215, false); - } - - public ObjectId(Date date, int counter) { - this(dateToTimestampSeconds(date), counter, true); - } - - public ObjectId(int timestamp, int counter) { - this(timestamp, counter, true); - } - - private ObjectId(int timestamp, int counter, boolean checkCounter) { - this(timestamp, RANDOM_VALUE1, RANDOM_VALUE2, counter, checkCounter); - } - - private ObjectId(int timestamp, int randomValue1, short randomValue2, int counter, boolean checkCounter) { - if ((randomValue1 & -16777216) != 0) { - throw new IllegalArgumentException("The machine identifier must be between 0 and 16777215 (it must fit in three bytes)."); - } else if (checkCounter && (counter & -16777216) != 0) { - throw new IllegalArgumentException("The counter must be between 0 and 16777215 (it must fit in three bytes)."); - } else { - this.timestamp = timestamp; - this.counter = counter & 16777215; - this.randomValue1 = randomValue1; - this.randomValue2 = randomValue2; - } - } - - public ObjectId(String hexString) { - this(parseHexString(hexString)); - } - - public ObjectId(byte[] bytes) { - this(ByteBuffer.wrap((byte[]) isTrueArgument("bytes has length of 12", bytes, ((byte[]) notNull("bytes", bytes)).length == 12))); - } - - ObjectId(int timestamp, int machineAndProcessIdentifier, int counter) { - this(legacyToBytes(timestamp, machineAndProcessIdentifier, counter)); - } - - public ObjectId(ByteBuffer buffer) { - notNull("buffer", buffer); - isTrueArgument("buffer.remaining() >=12", buffer.remaining() >= 12); - this.timestamp = makeInt(buffer.get(), buffer.get(), buffer.get(), buffer.get()); - this.randomValue1 = makeInt((byte) 0, buffer.get(), buffer.get(), buffer.get()); - this.randomValue2 = makeShort(buffer.get(), buffer.get()); - this.counter = makeInt((byte) 0, buffer.get(), buffer.get(), buffer.get()); - } - - private static byte[] legacyToBytes(int timestamp, int machineAndProcessIdentifier, int counter) { - byte[] bytes = new byte[]{int3(timestamp), int2(timestamp), int1(timestamp), int0(timestamp), int3(machineAndProcessIdentifier), int2(machineAndProcessIdentifier), int1(machineAndProcessIdentifier), int0(machineAndProcessIdentifier), int3(counter), int2(counter), int1(counter), int0(counter)}; - return bytes; - } - - public byte[] toByteArray() { - ByteBuffer buffer = ByteBuffer.allocate(12); - this.putToByteBuffer(buffer); - return buffer.array(); - } - - public void putToByteBuffer(ByteBuffer buffer) { - notNull("buffer", buffer); - isTrueArgument("buffer.remaining() >=12", buffer.remaining() >= 12); - buffer.put(int3(this.timestamp)); - buffer.put(int2(this.timestamp)); - buffer.put(int1(this.timestamp)); - buffer.put(int0(this.timestamp)); - buffer.put(int2(this.randomValue1)); - buffer.put(int1(this.randomValue1)); - buffer.put(int0(this.randomValue1)); - buffer.put(short1(this.randomValue2)); - buffer.put(short0(this.randomValue2)); - buffer.put(int2(this.counter)); - buffer.put(int1(this.counter)); - buffer.put(int0(this.counter)); - } - - public int getTimestamp() { - return this.timestamp; - } - - public Date getDate() { - return new Date(((long) this.timestamp & 4294967295L) * 1000L); - } - - public String toHexString() { - char[] chars = new char[24]; - int i = 0; - byte[] var3 = this.toByteArray(); - int var4 = var3.length; - - for (int var5 = 0; var5 < var4; ++var5) { - byte b = var3[var5]; - chars[i++] = HEX_CHARS[b >> 4 & 15]; - chars[i++] = HEX_CHARS[b & 15]; - } - return new String(chars); - } - - public boolean equals(Object o) { - if (this == o) { - return true; - } else if (o != null && this.getClass() == o.getClass()) { - ObjectId objectId = (ObjectId) o; - if (this.counter != objectId.counter) { - return false; - } else if (this.timestamp != objectId.timestamp) { - return false; - } else if (this.randomValue1 != objectId.randomValue1) { - return false; - } else { - return this.randomValue2 == objectId.randomValue2; - } - } else { - return false; - } - } - - public int hashCode() { - int result = this.timestamp; - result = 31 * result + this.counter; - result = 31 * result + this.randomValue1; - result = 31 * result + this.randomValue2; - return result; - } - - public int compareTo(ObjectId other) { - if (other == null) { - throw new NullPointerException(); - } else { - byte[] byteArray = this.toByteArray(); - byte[] otherByteArray = other.toByteArray(); - - for (int i = 0; i < 12; ++i) { - if (byteArray[i] != otherByteArray[i]) { - return (byteArray[i] & 255) < (otherByteArray[i] & 255) ? -1 : 1; - } - } - - return 0; - } - } - - public String toString() { - return this.toHexString(); - } - - private static byte[] parseHexString(String s) { - if (!isValid(s)) { - throw new IllegalArgumentException("invalid hexadecimal representation of an ObjectId: [" + s + "]"); - } else { - byte[] b = new byte[12]; - - for (int i = 0; i < b.length; ++i) { - b[i] = (byte) Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16); - } - - return b; - } - } - - private static int dateToTimestampSeconds(Date time) { - return (int) (time.getTime() / 1000L); - } - - private static int makeInt(byte b3, byte b2, byte b1, byte b0) { - return b3 << 24 | (b2 & 255) << 16 | (b1 & 255) << 8 | b0 & 255; - } - - private static short makeShort(byte b1, byte b0) { - return (short) ((b1 & 255) << 8 | b0 & 255); - } - - private static byte int3(int x) { - return (byte) (x >> 24); - } - - private static byte int2(int x) { - return (byte) (x >> 16); - } - - private static byte int1(int x) { - return (byte) (x >> 8); - } - - private static byte int0(int x) { - return (byte) x; - } - - private static byte short1(short x) { - return (byte) (x >> 8); - } - - private static byte short0(short x) { - return (byte) x; - } - - static { - try { - SecureRandom secureRandom = new SecureRandom(); - RANDOM_VALUE1 = secureRandom.nextInt(16777216); - RANDOM_VALUE2 = (short) secureRandom.nextInt(32768); - } catch (Exception var1) { - throw new RuntimeException(var1); - } - } - - public static T notNull(String name, T value) { - if (value == null) { - throw new IllegalArgumentException(name + " can not be null"); - } else { - return value; - } - } - - public static void isTrueArgument(String name, boolean condition) { - if (!condition) { - throw new IllegalArgumentException("state should be: " + name); - } - } - - public static T isTrueArgument(String name, T value, boolean condition) { - if (!condition) { - throw new IllegalArgumentException("state should be: " + name); - } else { - return value; - } - } - - public static ObjectId get() { - return new ObjectId(); - } - - /** - * 生成 mongodb ObjectId - * @return 24长度的十六进制字符的字符串 - */ - public static String nextId() { - return ObjectId.get().toString(); - } - -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/idgen/Snowflake.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/idgen/Snowflake.java deleted file mode 100644 index 4359c54fca..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/idgen/Snowflake.java +++ /dev/null @@ -1,225 +0,0 @@ -package com.jun.plugin.security.util.idgen; - -import com.jun.plugin.security.util.LocalHostUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.lang.management.ManagementFactory; -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.util.Random; - -/** - * 雪花算法生成分布式ID - * - * @version 2022-05-21 9:53 - **/ -public class Snowflake { - final static Logger log = LoggerFactory.getLogger(Snowflake.class); - - // 时间起始标记点,一旦确定不能变动 - private final static long TWEPOCH = 1577811661657L; - - // 机器标识位数 - private final static long WORKER_ID_BITS = 5L; - - // 数据中心标识位数 - private final static long DATA_CENTER_ID_BITS = 5L; - - // 工作机器ID最大值 31 - private final static long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS); - - // 数据中心ID最大值 31 - private final static long MAX_DATA_CENTER_ID = ~(-1L << DATA_CENTER_ID_BITS); - - // 毫秒内自增位 - private final static long SEQUENCE_BITS = 12L; - - // 机器ID偏左移12位 - private final static long WORKER_ID_SHIFT = SEQUENCE_BITS; - - private final static long DATA_CENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS; - - // 时间毫秒左移22位 - private final static long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATA_CENTER_ID_BITS; - - // 序号掩码,用于与自增后的序列号进行位“与”操作,如果值为 0,则代表自增后的序列号超过了 4095。 - private final static long SEQUENCE_MASK = ~(-1L << SEQUENCE_BITS); - - private long lastTimestamp = -1L; - - private long sequence = 0L; - private final long workerId; - private final long dataCenterId; - - // 私有化示例要加上volatile,防止jvm重排序,导致空指针 - private static volatile Snowflake snowflake = null; - private static final Object lock = new Object(); - - // IP 地址信息,用来生成工作机器 ID 和数据中心 ID。 - private InetAddress address; - - - // 单例禁止new实例化 - private Snowflake(long workerId, long dataCenterId) { - if (workerId > MAX_WORKER_ID || workerId < 0) { - throw new IllegalArgumentException( - String.format("%s 工作机器ID最大值 必须是 %d 到 %d 之间", dataCenterId, 0, MAX_WORKER_ID)); - } - if (dataCenterId > MAX_DATA_CENTER_ID || dataCenterId < 0) { - throw new IllegalArgumentException( - String.format("%s 数据中心ID最大值 必须是 %d 到 %d 之间", dataCenterId, 0, MAX_DATA_CENTER_ID)); - } - this.workerId = workerId; - this.dataCenterId = dataCenterId; - } - - // 单例禁止new实例化 - private Snowflake(InetAddress address) { - this.address = address; - this.dataCenterId = getDataCenterId(MAX_DATA_CENTER_ID); - this.workerId = getWorkerId(dataCenterId, MAX_DATA_CENTER_ID); - } - - /** - * 雪花算法 ID 生成器。 - */ - private Snowflake() { - this(null); - } - - - /** - * 根据 MAC + PID 的 hashCode 获取 16 个低位生成工作机器 ID。 - */ - protected long getWorkerId(long dataCenterId, long maxWorkerId) { - StringBuilder mpId = new StringBuilder(); - mpId.append(dataCenterId); - String name = ManagementFactory.getRuntimeMXBean().getName(); - if (name != null && !name.isEmpty()) { - // GET jvmPid - mpId.append(name.split("@")[0]); - } - // MAC + PID 的 hashCode 获取16个低位 - return (mpId.toString().hashCode() & 0xffff) % (maxWorkerId + 1); - } - - - /** - * 根据网卡 MAC 地址计算余数作为数据中心 ID。 - */ - protected long getDataCenterId(long maxDataCenterId) { - long id = 0L; - try { - if (address == null) { - address = InetAddress.getLocalHost(); - } - NetworkInterface network = NetworkInterface.getByInetAddress(address); - if (null == network) { - id = 1L; - } else { - byte[] mac = network.getHardwareAddress(); - if (null != mac) { - id = ((0x000000FF & (long) mac[mac.length - 2]) | (0x0000FF00 & (((long) mac[mac.length - 1]) << 8))) >> 6; - id = id % (maxDataCenterId + 1); - } - } - } catch (Exception e) { - throw new RuntimeException("dataCenterId generate fail", e); - } - return id; - } - - - /** - * 获取单例(懒汉式单例,有线程安全问题,所以加锁) - * - * @return - */ - public static Snowflake getInstance() { - if (snowflake == null) { - synchronized (lock) { - if (snowflake == null) { - snowflake = new Snowflake(LocalHostUtil.getInetAddress()); - } - } - } - return snowflake; - } - - /** - * 生成1-31之间的随机数(用于随机生成机器id和数据中心id) - * - * @return long - */ - private static long getRandom(long maxId) { - int max = (int) (maxId); - int min = 1; - Random random = new Random(); - long result = random.nextInt(max - min) + min; - return result; - } - - /** - * 根据算法,生成下一个ID - * - * @return - */ - private synchronized long generateId() { - long timestamp = time(); - if (timestamp < lastTimestamp) { - log.error("时钟向后移动,拒绝生成id " + (lastTimestamp - timestamp) + " milliseconds"); - } - if (lastTimestamp == timestamp) { - // 当前毫秒内,则+1 - sequence = (sequence + 1) & SEQUENCE_MASK; - if (sequence == 0) { - // 当前毫秒内计数满了,则等待下一秒 - timestamp = tilNextMillis(lastTimestamp); - } - } else { - sequence = 0; - } - lastTimestamp = timestamp; - - // ID偏移组合生成最终的ID,并返回ID - long nextId = ((timestamp - TWEPOCH) << TIMESTAMP_LEFT_SHIFT) | (dataCenterId << DATA_CENTER_ID_SHIFT) - | (workerId << WORKER_ID_SHIFT) | sequence; - - return nextId; - } - - private long tilNextMillis(final long lastTimestamp) { - long timestamp = this.time(); - while (timestamp <= lastTimestamp) { - timestamp = this.time(); - } - return timestamp; - } - - private long time() { - return System.currentTimeMillis(); - } - - - /** - * 获取雪花算法ID,返回String类型 - * - * @return - */ - public static String nextId() { - return String.valueOf(Snowflake.getInstance().generateId()); - } - - - /** - * 获取雪花算法ID,返回String类型 - * - * @return - */ - public static long nextLongId() { - return Snowflake.getInstance().generateId(); - } - -} - diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/secure/AESUtil.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/secure/AESUtil.java deleted file mode 100644 index c6beca96ed..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/secure/AESUtil.java +++ /dev/null @@ -1,195 +0,0 @@ -package com.jun.plugin.security.util.secure; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.crypto.Cipher; -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.SecretKeySpec; -import java.nio.charset.StandardCharsets; -import java.util.Base64; - -/** - * AESUtil工具类,使用Builder模式构造 - * - * @version 2021-09-09-9:43 - **/ -public class AESUtil { - final static Logger logger = LoggerFactory.getLogger(AESUtil.class); - - /** - * 算法/加密模式/填充方式 - */ - private final static String ALGORITHMSTR = "AES/CBC/PKCS5Padding"; - - /** - * 密钥key(可以16或32字节)(128位密钥/256位密钥,设置256位密钥更难破解) - */ - private String secretKey; - - /** - * 偏移量(16字节) - */ - private String ivParameter; - - /** - * 是否使用base64编码(默认false,默认使用hex) - */ - private boolean ifBase64; - - - public String getSecretKey() { - return secretKey; - } - - public void setSecretKey(String secretKey) { - this.secretKey = secretKey; - } - - public String getIvParameter() { - return ivParameter; - } - - public void setIvParameter(String ivParameter) { - this.ivParameter = ivParameter; - } - - public boolean isIfBase64() { - return ifBase64; - } - - public void setIfBase64(boolean ifBase64) { - this.ifBase64 = ifBase64; - } - - - private AESUtil(AESUtilBuilder builder) { - this.secretKey = builder.secretKey; - this.ivParameter = builder.ivParameter; - this.ifBase64 = builder.ifBase64; - } - - - public static AESUtilBuilder builder() { - return new AESUtilBuilder(); - } - - - - /** - * 2020-08-13-14:07--liuxingyu01 - * AES加密 - * - * @param content 要加密的字符串 - * @return 430301102072 / d086af4d68888097504e536e5cfe351c / Hex字符串展示 - */ - public String encrypt(String content) { - try { - byte[] raw = secretKey.getBytes(StandardCharsets.UTF_8); - SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); - Cipher cipher = Cipher.getInstance(ALGORITHMSTR); - // 使用CBC模式,需要一个向量iv,可增加加密算法的强度 - IvParameterSpec ips = new IvParameterSpec(ivParameter.getBytes(StandardCharsets.UTF_8)); - cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ips); - byte[] encrypted = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8)); - - if (ifBase64) { // 此处使用BASE64做编码 - return Base64.getEncoder().encodeToString(encrypted); - } else { // 此处使用Hex做编码 - return HexUtil.bytesToHex(encrypted); - } - } catch (Exception e) { - logger.error("AESUtils -- encrypt -- Exception=", e); - return null; - } - } - - - /** - * AES解密 - * - * @param content 要解密的字符串 - * @return 解密后的结果 - */ - public String decrypt(String content) { - try { - Cipher cipher = Cipher.getInstance(ALGORITHMSTR); - byte[] raw = secretKey.getBytes(StandardCharsets.UTF_8); - SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); - // 使用CBC模式,需要一个向量iv,可增加加密算法的强度 - IvParameterSpec ips = new IvParameterSpec(ivParameter.getBytes(StandardCharsets.UTF_8)); - cipher.init(Cipher.DECRYPT_MODE, skeySpec, ips); - byte[] result; - if (ifBase64) { // 此处使用BASE64做编码 - result = cipher.doFinal(Base64.getDecoder().decode(content)); - } else { // 此处使用Hex做编码 - result = cipher.doFinal(HexUtil.hexToBytes(content)); - } - return new String(result, StandardCharsets.UTF_8); - } catch (Exception e) { - logger.error("AESUtils -- decrypt -- Exception=", e); - return null; - } - } - - - /** - * AESUtilsBuilder - */ - public static final class AESUtilBuilder { - private String secretKey = "1G78Av#yej%WZJ3uiSZRz9oy%UAv4!EG"; - private String ivParameter = "E%BJuDUTvXfwSuGQ"; - private boolean ifBase64 = false; - - public AESUtilBuilder() { - this.secretKey = secretKey; - this.ivParameter = ivParameter; - this.ifBase64 = ifBase64; - } - - public AESUtilBuilder secretKey(String secretKey) { - this.secretKey = secretKey; - return this; - } - - public AESUtilBuilder ivParameter(String ivParameter) { - this.ivParameter = ivParameter; - return this; - } - - public AESUtilBuilder ifBase64(boolean ifBase64) { - this.ifBase64 = ifBase64; - return this; - } - - public AESUtil build() { - AESUtil aesUtil = new AESUtil(this); - return aesUtil; - } - } - - - /** - * 测试 - * @param args - * @throws Exception - */ - public static void main(String[] args) throws Exception { - // 原文: - String message = "Helloworld!"; - System.out.println("Message: " + message); - - // 使用方法 - AESUtil aesUtils = AESUtil.builder().secretKey("1G78Av#yej%WZJ3uiSZRz9oy%UAv4AAA").ivParameter("E%BAAAUTvXfwSuGQ").build(); - - // 加密: - String encrypted = aesUtils.encrypt(message); - System.out.println("加密: " + encrypted); - - // 解密: - String decrypted = aesUtils.decrypt(encrypted); - System.out.println("解密: " + decrypted); - } - - -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/secure/HexUtil.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/secure/HexUtil.java deleted file mode 100644 index 56968aacb0..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/secure/HexUtil.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.jun.plugin.security.util.secure; - -public class HexUtil { - - /** - * 字节数组转16进制 - * - * @param bytes 需要转换的byte数组 - * @return 转换后的Hex字符串 - */ - public static String bytesToHex(byte[] bytes) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < bytes.length; i++) { - String hex = Integer.toHexString(bytes[i] & 0xFF); - if (hex.length() < 2) { - sb.append(0); - } - sb.append(hex); - } - return sb.toString(); - } - - /** - * hex字符串转byte字节数组 - * - * @param inHex 待转换的Hex字符串 - * @return 转换后的byte数组结果 - */ - public static byte[] hexToBytes(String inHex) { - int hexlen = inHex.length(); - byte[] result; - if (hexlen % 2 == 1) { - // 奇数 - hexlen++; - result = new byte[(hexlen / 2)]; - inHex = "0" + inHex; - } else { - // 偶数 - result = new byte[(hexlen / 2)]; - } - int j = 0; - for (int i = 0; i < hexlen; i += 2) { - result[j] = hexToByte(inHex.substring(i, i + 2)); - j++; - } - return result; - } - - /** - * Hex字符串转byte - * - * @param inHex 待转换的Hex字符串 - * @return 转换后的byte - */ - public static byte hexToByte(String inHex) { - return (byte) Integer.parseInt(inHex, 16); - } - -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/secure/MD5Hash.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/secure/MD5Hash.java deleted file mode 100644 index 07d52e6125..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/secure/MD5Hash.java +++ /dev/null @@ -1,159 +0,0 @@ -package com.jun.plugin.security.util.secure; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.util.Base64; - - -/** - * MD5-Hsah算法加密 - * - * @version 2020-05-28-23:34 - **/ -public class MD5Hash { - final static Logger log = LoggerFactory.getLogger(MD5Hash.class); - - /** - * 原始值 - */ - private String source; - - /** - * 颜值 - */ - private String salt = ""; - - /** - * 迭代次数(默认1次) - */ - private int iterations = 1; - - public String getSource() { - return this.source; - } - - public void setSource(String source) { - this.source = source; - } - - public String getSalt() { - return this.salt; - } - - public void setSalt(String salt) { - this.salt = salt; - } - - public int getIterations() { - return this.iterations; - } - - public void setIterations(int iterations) { - this.iterations = iterations; - } - - public MD5Hash(String source, String salt, int iterations) { - this.source = source; - this.salt = salt; - this.iterations = iterations; - } - - public MD5Hash(String source, String salt) { - this.source = source; - this.salt = salt; - } - - public MD5Hash(String source) { - this.source = source; - } - - public MD5Hash(String source, int iterations) { - this.source = source; - this.iterations = iterations; - } - - - /** - * 返回小写MD5 - * - * @param source 原始值字符串 - * @return hash后的字节数组 - */ - private byte[] MD5Encode(String source, String salt, int hashIterations) { - MessageDigest messageDigest = null; - byte[] hashedBytes = null; - try { - messageDigest = MessageDigest.getInstance("MD5"); - // 先加盐 - if (salt != null) { - messageDigest.reset(); - messageDigest.update(salt.getBytes(StandardCharsets.UTF_8)); - } - // 再放需要被hash的数据 - hashedBytes = messageDigest.digest(source.getBytes(StandardCharsets.UTF_8)); - // 最少迭代一次 - if (hashIterations < 1) { - hashIterations = 1; - } - // 迭代继续hash - for (int i = 0; i < hashIterations - 1; i++) { - messageDigest.reset(); - hashedBytes = messageDigest.digest(hashedBytes); - } - } catch (Exception e) { - if (log.isErrorEnabled()) { - log.error("MD5Utils -- MD5Encode -- Exception= {e}", e); - } - } - return hashedBytes; - } - - - /** - * 将将byte[]转为16进制字符串 - * - * @return 16进制字符串 - */ - public String toHex() { - byte[] resultBytes = this.MD5Encode(this.source, this.salt, this.iterations); - return HexUtil.bytesToHex(resultBytes); - } - - - /** - * 将将byte[]转为Base64字符串 - * - * @return Base64字符串 - */ - public String toBase64() { - byte[] resultBytes = this.MD5Encode(this.source, this.salt, this.iterations); - return Base64.getEncoder().encodeToString(resultBytes); - } - - - /** - * 将将byte[]转为16进制字符串 - * - * @return 16进制字符串 - */ - @Override - public String toString() { - return this.toHex(); - } - - - public static void main(String[] args) { - System.out.println(new MD5Hash("123456", "323@#@$1234da", 1).toHex()); - System.out.println(new MD5Hash("123456", "323@#@$1234da").toHex()); - System.out.println(new MD5Hash("123456").toHex()); - - System.out.println(new MD5Hash("123456", "323@#@$1234da", 2).toHex()); - - System.out.println(new MD5Hash("123456", "323@#@$1234da", 3).toHex()); - - System.out.println(new MD5Hash("123456", "323@#@$1234da", 3).toBase64()); - } -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/secure/RSAUtil.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/secure/RSAUtil.java deleted file mode 100644 index 9d34c37a19..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/secure/RSAUtil.java +++ /dev/null @@ -1,127 +0,0 @@ -package com.jun.plugin.security.util.secure; - -import javax.crypto.Cipher; -import java.security.*; -import java.security.interfaces.RSAPrivateKey; -import java.security.interfaces.RSAPublicKey; -import java.security.spec.PKCS8EncodedKeySpec; -import java.security.spec.X509EncodedKeySpec; -import java.util.Base64; -import java.util.HashMap; -import java.util.Map; - -/** - * RSA 加密工具类 用于前后端密码密文传输 - * RSA非对称加密算法,如果是公钥加密,就得用私钥解密,反过来也一样,私钥加密的就用公钥解密。 - * @version 2022-03-29 10:35 - **/ -public class RSAUtil { - /** - * 公钥解密 - * - * @param publicKeyString 公钥 - * @param text 待解密的信息 - * @return 解密后的文本 - */ - public static String decryptByPublicKey(String publicKeyString, String text) throws Exception { - X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyString)); - KeyFactory keyFactory = KeyFactory.getInstance("RSA"); - PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec); - Cipher cipher = Cipher.getInstance("RSA"); - cipher.init(Cipher.DECRYPT_MODE, publicKey); - byte[] result = cipher.doFinal(Base64.getDecoder().decode(text)); - return new String(result); - } - - /** - * 私钥加密 - * - * @param privateKeyString 私钥 - * @param text 待加密的信息 - * @return 加密后的文本 - */ - public static String encryptByPrivateKey(String privateKeyString, String text) throws Exception { - PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyString)); - KeyFactory keyFactory = KeyFactory.getInstance("RSA"); - PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec); - Cipher cipher = Cipher.getInstance("RSA"); - cipher.init(Cipher.ENCRYPT_MODE, privateKey); - byte[] result = cipher.doFinal(text.getBytes()); - return Base64.getEncoder().encodeToString(result); - } - - /** - * 私钥解密 - * - * @param privateKeyString 私钥 - * @param text 待解密的文本 - * @return 解密后的文本 - */ - public static String decryptByPrivateKey(String privateKeyString, String text) throws Exception { - PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyString)); - KeyFactory keyFactory = KeyFactory.getInstance("RSA"); - PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5); - Cipher cipher = Cipher.getInstance("RSA"); - cipher.init(Cipher.DECRYPT_MODE, privateKey); - byte[] result = cipher.doFinal(Base64.getDecoder().decode(text)); - return new String(result); - } - - /** - * 公钥加密 - * - * @param publicKeyString 公钥 - * @param text 待加密的文本 - * @return 加密后的文本 - */ - public static String encryptByPublicKey(String publicKeyString, String text) throws Exception { - X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyString)); - KeyFactory keyFactory = KeyFactory.getInstance("RSA"); - PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2); - Cipher cipher = Cipher.getInstance("RSA"); - cipher.init(Cipher.ENCRYPT_MODE, publicKey); - byte[] result = cipher.doFinal(text.getBytes()); - return Base64.getEncoder().encodeToString(result); - } - - /** - * 构建RSA密钥对 - * - * @return 生成后的公私钥信息 - */ - public static Map generateKeyPair() throws NoSuchAlgorithmException { - KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); - keyPairGenerator.initialize(2048); - KeyPair keyPair = keyPairGenerator.generateKeyPair(); - RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic(); - RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate(); - String publicKeyString = Base64.getEncoder().encodeToString(rsaPublicKey.getEncoded()); - String privateKeyString = Base64.getEncoder().encodeToString(rsaPrivateKey.getEncoded()); - return new HashMap(){{ - put("publicKey", publicKeyString); - put("privateKey", privateKeyString); - }}; - } - - - /** - * 测试 - * @param args - * @throws NoSuchAlgorithmException - */ - public static void main(String[] args) throws Exception { - Map pair = generateKeyPair(); - String publicKey = pair.get("publicKey"); - String privateKey = pair.get("privateKey"); - - // 使用公钥加密 - String encryptedValue = encryptByPublicKey(publicKey, "abcdefg"); - - System.out.println(encryptedValue); - - // 使用私钥解密 - String decryptedValue = decryptByPrivateKey(privateKey, encryptedValue); - - System.out.println(decryptedValue); - } -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/secure/SM3Hash.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/secure/SM3Hash.java deleted file mode 100644 index e8581586e3..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/secure/SM3Hash.java +++ /dev/null @@ -1,173 +0,0 @@ -package com.jun.plugin.security.util.secure; - -import com.jun.plugin.security.util.secure.sm3.SM3Digest; - -import java.nio.charset.StandardCharsets; -import java.util.Base64; - -public class SM3Hash { - - /** - * 原始值 - */ - private String source; - - /** - * 盐值 - */ - private String salt = ""; - - /** - * 迭代次数(默认1次) - */ - private int iterations = 1; - - public String getSource() { - return this.source; - } - - public void setSource(String source) { - this.source = source; - } - - public String getSalt() { - return this.salt; - } - - public void setSalt(String salt) { - this.salt = salt; - } - - public int getIterations() { - return this.iterations; - } - - public void setIterations(int iterations) { - this.iterations = iterations; - } - - public SM3Hash(String source, String salt, int iterations) { - this.source = source; - this.salt = salt; - this.iterations = iterations; - } - - public SM3Hash(String source, String salt) { - this.source = source; - this.salt = salt; - } - - public SM3Hash(String source) { - this.source = source; - } - - public SM3Hash(String source, int iterations) { - this.source = source; - this.iterations = iterations; - } - - /** - * 返回小写SM3 hash串 - * - * @param source 原始值字符串 - * @return hash后的字节数组 - */ - private byte[] SM3Encode(String source, String salt) { - byte[] hashedBytes = new byte[32]; - try { - byte[] msgBytes = (source + salt).getBytes(StandardCharsets.UTF_8); - SM3Digest sm3Digest = new SM3Digest(); - sm3Digest.update(msgBytes, 0, msgBytes.length); - sm3Digest.doFinal(hashedBytes, 0); - } catch (Exception e) { - e.printStackTrace(); - } - return hashedBytes; - } - - - /** - * 返回小写SM3 hash串 - * - * @param msgBytes 原始值-字节数组 - * @return hash后的字节数组 - */ - private byte[] SM3Encode(byte[] msgBytes) { - byte[] hashedBytes = new byte[32]; - try { - SM3Digest sm3Digest = new SM3Digest(); - sm3Digest.update(msgBytes, 0, msgBytes.length); - sm3Digest.doFinal(hashedBytes, 0); - } catch (Exception e) { - e.printStackTrace(); - } - return hashedBytes; - } - - - /** - * 返回小写SM3 hash串 - * - * @param source 原始值字符串 - * @return hash后的字节数组 - */ - private byte[] SM3Encode(String source, String salt, int hashIterations) { - byte[] hashedBytes; - // 最少迭代一次 - if (hashIterations < 1) { - hashIterations = 1; - } - hashedBytes = this.SM3Encode(source, salt); - for (int i = 0; i < hashIterations - 1; i++) { - hashedBytes = this.SM3Encode(hashedBytes); - } - return hashedBytes; - } - - - /** - * 将将byte[]转为16进制字符串 - * - * @return 16进制字符串 - */ - public String toHex() { - byte[] resultBytes = this.SM3Encode(this.source, this.salt, this.iterations); - return HexUtil.bytesToHex(resultBytes); - } - - - /** - * 将将byte[]转为Base64字符串 - * - * @return Base64字符串 - */ - public String toBase64() { - byte[] resultBytes = this.SM3Encode(this.source, this.salt, this.iterations); - return Base64.getEncoder().encodeToString(resultBytes); - } - - - /** - * 将将byte[]转为16进制字符串 - * - * @return 16进制字符串 - */ - @Override - public String toString() { - return this.toHex(); - } - - - public static void main(String[] args) { - System.out.println(new SM3Hash("123456", "323@#@$1234da", 1).toHex()); - System.out.println(new SM3Hash("123456", "323@#@$1234da").toHex()); - System.out.println(new SM3Hash("123456").toHex()); - - System.out.println(new SM3Hash("123456", "323@#@$1234da", 2).toHex()); - - System.out.println(new SM3Hash("123456", "323@#@$1234da", 4).toHex()); - - System.out.println(new SM3Hash("123456", "323@#@$1234da").toBase64()); - } - -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/secure/Sha256Hash.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/secure/Sha256Hash.java deleted file mode 100644 index 4267c0c9f5..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/secure/Sha256Hash.java +++ /dev/null @@ -1,153 +0,0 @@ -package com.jun.plugin.security.util.secure; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.util.Base64; - -public class Sha256Hash { - final static Logger log = LoggerFactory.getLogger(MD5Hash.class); - - - /** - * 原始值 - */ - private String source; - - /** - * 颜值 - */ - private String salt = ""; - - /** - * 迭代次数(默认1次) - */ - private int iterations = 1; - - public String getSource() { - return this.source; - } - - public void setSource(String source) { - this.source = source; - } - - public String getSalt() { - return this.salt; - } - - public void setSalt(String salt) { - this.salt = salt; - } - - public int getIterations() { - return this.iterations; - } - - public void setIterations(int iterations) { - this.iterations = iterations; - } - - public Sha256Hash(String source, String salt, int iterations) { - this.source = source; - this.salt = salt; - this.iterations = iterations; - } - - public Sha256Hash(String source) { - this.source = source; - } - - public Sha256Hash(String source, String salt) { - this.source = source; - this.salt = salt; - } - - public Sha256Hash(String source, int iterations) { - this.source = source; - this.iterations = iterations; - } - - /** - * 返回小写SHA-256 - * - * @param source 原始值字符串 - * @return hash后的字节数组 - */ - private byte[] Sha256Encode(String source, String salt, int hashIterations) { - MessageDigest messageDigest = null; - byte[] hashedBytes = null; - try { - messageDigest = MessageDigest.getInstance("SHA-256"); - // 先加盐 - if (salt != null) { - messageDigest.reset(); - messageDigest.update(salt.getBytes(StandardCharsets.UTF_8)); - } - // 再放需要被hash的数据 - hashedBytes = messageDigest.digest(source.getBytes(StandardCharsets.UTF_8)); - // 最少迭代一次 - if (hashIterations < 1) { - hashIterations = 1; - } - // 迭代继续hash - for (int i = 0; i < hashIterations - 1; i++) { - messageDigest.reset(); - hashedBytes = messageDigest.digest(hashedBytes); - } - } catch (Exception e) { - if (log.isErrorEnabled()) { - log.error("MD5Utils -- MD5Encode -- Exception= {e}", e); - } - } - return hashedBytes; - } - - - /** - * 将将byte[]转为16进制字符串 - * - * @return 16进制字符串 - */ - public String toHex() { - byte[] resultBytes = this.Sha256Encode(this.source, this.salt, this.iterations); - return HexUtil.bytesToHex(resultBytes); - } - - - /** - * 将将byte[]转为Base64字符串 - * - * @return Base64字符串 - */ - public String toBase64() { - byte[] resultBytes = this.Sha256Encode(this.source, this.salt, this.iterations); - return Base64.getEncoder().encodeToString(resultBytes); - } - - - /** - * 将将byte[]转为16进制字符串 - * - * @return 16进制字符串 - */ - @Override - public String toString() { - return this.toHex(); - } - - - public static void main(String[] args) { - System.out.println(new Sha256Hash("123456", "323@#@$1234da", 10).toBase64()); - System.out.println(new Sha256Hash("123456", "323@#@$1234da").toHex()); - System.out.println(new Sha256Hash("123456").toHex()); - - System.out.println(new Sha256Hash("123456", "323@#@$1234da", 2).toHex()); - - System.out.println(new Sha256Hash("123456", "323@#@$1234da", 3).toHex()); - - System.out.println(new Sha256Hash("123456", "323@#@$1234da", 3).toBase64()); - } -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/secure/sm3/SM3.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/secure/sm3/SM3.java deleted file mode 100644 index 226b2542da..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/secure/sm3/SM3.java +++ /dev/null @@ -1,256 +0,0 @@ -package com.jun.plugin.security.util.secure.sm3; - -/** - * - * @version 2021-01-02-14:45 - **/ -public class SM3 { - public static final byte[] iv = { 0x73, (byte) 0x80, 0x16, 0x6f, 0x49, 0x14, (byte) 0xb2, (byte) 0xb9, 0x17, 0x24, - 0x42, (byte) 0xd7, (byte) 0xda, (byte) 0x8a, 0x06, 0x00, (byte) 0xa9, 0x6f, 0x30, (byte) 0xbc, (byte) 0x16, - 0x31, 0x38, (byte) 0xaa, (byte) 0xe3, (byte) 0x8d, (byte) 0xee, 0x4d, (byte) 0xb0, (byte) 0xfb, 0x0e, - 0x4e }; - - public static int[] Tj = new int[64]; - - static { - for (int i = 0; i < 16; i++) { - Tj[i] = 0x79cc4519; - } - - for (int i = 16; i < 64; i++) { - Tj[i] = 0x7a879d8a; - } - } - - public static byte[] CF(byte[] V, byte[] B) { - int[] v, b; - v = convert(V); - b = convert(B); - return convert(CF(v, b)); - } - - private static int[] convert(byte[] arr) { - int[] out = new int[arr.length / 4]; - byte[] tmp = new byte[4]; - for (int i = 0; i < arr.length; i += 4) { - System.arraycopy(arr, i, tmp, 0, 4); - out[i / 4] = bigEndianByteToInt(tmp); - } - return out; - } - - private static byte[] convert(int[] arr) { - byte[] out = new byte[arr.length * 4]; - byte[] tmp = null; - for (int i = 0; i < arr.length; i++) { - tmp = bigEndianIntToByte(arr[i]); - System.arraycopy(tmp, 0, out, i * 4, 4); - } - return out; - } - - public static int[] CF(int[] V, int[] B) { - int a, b, c, d, e, f, g, h; - int ss1, ss2, tt1, tt2; - a = V[0]; - b = V[1]; - c = V[2]; - d = V[3]; - e = V[4]; - f = V[5]; - g = V[6]; - h = V[7]; - - int[][] arr = expand(B); - int[] w = arr[0]; - int[] w1 = arr[1]; - - for (int j = 0; j < 64; j++) { - ss1 = (bitCycleLeft(a, 12) + e + bitCycleLeft(Tj[j], j)); - ss1 = bitCycleLeft(ss1, 7); - ss2 = ss1 ^ bitCycleLeft(a, 12); - tt1 = FFj(a, b, c, j) + d + ss2 + w1[j]; - tt2 = GGj(e, f, g, j) + h + ss1 + w[j]; - d = c; - c = bitCycleLeft(b, 9); - b = a; - a = tt1; - h = g; - g = bitCycleLeft(f, 19); - f = e; - e = P0(tt2); - - } - - int[] out = new int[8]; - out[0] = a ^ V[0]; - out[1] = b ^ V[1]; - out[2] = c ^ V[2]; - out[3] = d ^ V[3]; - out[4] = e ^ V[4]; - out[5] = f ^ V[5]; - out[6] = g ^ V[6]; - out[7] = h ^ V[7]; - - return out; - } - - private static int[][] expand(int[] B) { - int[] W = new int[68]; - int[] W1 = new int[64]; - for (int i = 0; i < B.length; i++) { - W[i] = B[i]; - } - - for (int i = 16; i < 68; i++) { - W[i] = P1(W[i - 16] ^ W[i - 9] ^ bitCycleLeft(W[i - 3], 15)) ^ bitCycleLeft(W[i - 13], 7) ^ W[i - 6]; - } - - for (int i = 0; i < 64; i++) { - W1[i] = W[i] ^ W[i + 4]; - } - - int[][] arr = new int[][] { W, W1 }; - return arr; - } - - private static byte[] bigEndianIntToByte(int num) { - return back(SM3ConvertUtil.intToBytes(num)); - } - - private static int bigEndianByteToInt(byte[] bytes) { - return SM3ConvertUtil.byteToInt(back(bytes)); - } - - private static int FFj(int X, int Y, int Z, int j) { - if (j >= 0 && j <= 15) { - return FF1j(X, Y, Z); - } else { - return FF2j(X, Y, Z); - } - } - - private static int GGj(int X, int Y, int Z, int j) { - if (j >= 0 && j <= 15) { - return GG1j(X, Y, Z); - } else { - return GG2j(X, Y, Z); - } - } - - // 逻辑位运算函数 - private static int FF1j(int X, int Y, int Z) { - int tmp = X ^ Y ^ Z; - return tmp; - } - - private static int FF2j(int X, int Y, int Z) { - int tmp = ((X & Y) | (X & Z) | (Y & Z)); - return tmp; - } - - private static int GG1j(int X, int Y, int Z) { - int tmp = X ^ Y ^ Z; - return tmp; - } - - private static int GG2j(int X, int Y, int Z) { - int tmp = (X & Y) | (~X & Z); - return tmp; - } - - private static int P0(int X) { - int y = rotateLeft(X, 9); - y = bitCycleLeft(X, 9); - int z = rotateLeft(X, 17); - z = bitCycleLeft(X, 17); - int t = X ^ y ^ z; - return t; - } - - private static int P1(int X) { - int t = X ^ bitCycleLeft(X, 15) ^ bitCycleLeft(X, 23); - return t; - } - - /** - * 对最后一个分组字节数据padding - * - * @param in - * @param bLen 分组个数 - * @return - */ - public static byte[] padding(byte[] in, int bLen) { - int k = 448 - (8 * in.length + 1) % 512; - if (k < 0) { - k = 960 - (8 * in.length + 1) % 512; - } - k += 1; - byte[] padd = new byte[k / 8]; - padd[0] = (byte) 0x80; - long n = in.length * 8 + bLen * 512; - byte[] out = new byte[in.length + k / 8 + 64 / 8]; - int pos = 0; - System.arraycopy(in, 0, out, 0, in.length); - pos += in.length; - System.arraycopy(padd, 0, out, pos, padd.length); - pos += padd.length; - byte[] tmp = back(SM3ConvertUtil.longToBytes(n)); - System.arraycopy(tmp, 0, out, pos, tmp.length); - return out; - } - - /** - * 字节数组逆序 - * - * @param in - * @return - */ - private static byte[] back(byte[] in) { - byte[] out = new byte[in.length]; - for (int i = 0; i < out.length; i++) { - out[i] = in[out.length - i - 1]; - } - - return out; - } - - public static int rotateLeft(int x, int n) { - return (x << n) | (x >> (32 - n)); - } - - private static int bitCycleLeft(int n, int bitLen) { - bitLen %= 32; - byte[] tmp = bigEndianIntToByte(n); - int byteLen = bitLen / 8; - int len = bitLen % 8; - if (byteLen > 0) { - tmp = byteCycleLeft(tmp, byteLen); - } - - if (len > 0) { - tmp = bitSmall8CycleLeft(tmp, len); - } - - return bigEndianByteToInt(tmp); - } - - private static byte[] bitSmall8CycleLeft(byte[] in, int len) { - byte[] tmp = new byte[in.length]; - int t1, t2, t3; - for (int i = 0; i < tmp.length; i++) { - t1 = (byte) ((in[i] & 0x000000ff) << len); - t2 = (byte) ((in[(i + 1) % tmp.length] & 0x000000ff) >> (8 - len)); - t3 = (byte) (t1 | t2); - tmp[i] = (byte) t3; - } - return tmp; - } - - private static byte[] byteCycleLeft(byte[] in, int byteLen) { - byte[] tmp = new byte[in.length]; - System.arraycopy(in, byteLen, tmp, 0, in.length - byteLen); - System.arraycopy(in, 0, tmp, in.length - byteLen, byteLen); - return tmp; - } -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/secure/sm3/SM3ConvertUtil.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/secure/sm3/SM3ConvertUtil.java deleted file mode 100644 index 3bd1d81e5d..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/secure/sm3/SM3ConvertUtil.java +++ /dev/null @@ -1,615 +0,0 @@ -package com.jun.plugin.security.util.secure.sm3; - -import java.math.BigInteger; - -/** - * @version 2021-01-02-14:19 - **/ -public class SM3ConvertUtil { - /** - * 整形转换成网络传输的字节流(字节数组)型数据 - * - * @param num 一个整型数据 - * @return 4个字节的自己数组 - */ - public static byte[] intToBytes(int num) { - byte[] bytes = new byte[4]; - bytes[0] = (byte) (0xff & (num >> 0)); - bytes[1] = (byte) (0xff & (num >> 8)); - bytes[2] = (byte) (0xff & (num >> 16)); - bytes[3] = (byte) (0xff & (num >> 24)); - return bytes; - } - - /** - * 四个字节的字节数据转换成一个整形数据 - * - * @param bytes 4个字节的字节数组 - * @return 一个整型数据 - */ - public static int byteToInt(byte[] bytes) { - int num = 0; - int temp; - temp = (0x000000ff & (bytes[0])) << 0; - num = num | temp; - temp = (0x000000ff & (bytes[1])) << 8; - num = num | temp; - temp = (0x000000ff & (bytes[2])) << 16; - num = num | temp; - temp = (0x000000ff & (bytes[3])) << 24; - num = num | temp; - return num; - } - - /** - * 长整形转换成网络传输的字节流(字节数组)型数据 - * - * @param num 一个长整型数据 - * @return 4个字节的自己数组 - */ - public static byte[] longToBytes(long num) { - byte[] bytes = new byte[8]; - for (int i = 0; i < 8; i++) { - bytes[i] = (byte) (0xff & (num >> (i * 8))); - } - - return bytes; - } - - /** - * 大数字转换字节流(字节数组)型数据 - * - * @param n 大数字 - * @return 字节数组 - */ - public static byte[] byteConvert32Bytes(BigInteger n) { - byte tmpd[] = (byte[]) null; - if (n == null) { - return null; - } - - if (n.toByteArray().length == 33) { - tmpd = new byte[32]; - System.arraycopy(n.toByteArray(), 1, tmpd, 0, 32); - } else if (n.toByteArray().length == 32) { - tmpd = n.toByteArray(); - } else { - tmpd = new byte[32]; - for (int i = 0; i < 32 - n.toByteArray().length; i++) { - tmpd[i] = 0; - } - System.arraycopy(n.toByteArray(), 0, tmpd, 32 - n.toByteArray().length, n.toByteArray().length); - } - return tmpd; - } - - /** - * 换字节流(字节数组)型数据转大数字 - * - * @param b 字节数组 - * @return 大数字 - */ - public static BigInteger byteConvertInteger(byte[] b) { - if (b[0] < 0) { - byte[] temp = new byte[b.length + 1]; - temp[0] = 0; - System.arraycopy(b, 0, temp, 1, b.length); - return new BigInteger(temp); - } - return new BigInteger(b); - } - - /** - * 根据字节数组获得值(十六进制数字) - * - * @param bytes 字节数组 - * @return - */ - public static String getHexString(byte[] bytes) { - return getHexString(bytes, true); - } - - /** - * 根据字节数组获得值(十六进制数字) - * - * @param bytes 字节数组 - * @param upperCase 是否返回大写 - * @return 十六进制数字-字符串 - */ - public static String getHexString(byte[] bytes, boolean upperCase) { - String ret = ""; - for (int i = 0; i < bytes.length; i++) { - ret += Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1); - } - return upperCase ? ret.toUpperCase() : ret; - } - - /** - * 打印十六进制字符串 - * - * @param bytes 字节数组 - */ - public static void printHexString(byte[] bytes) { - for (int i = 0; i < bytes.length; i++) { - String hex = Integer.toHexString(bytes[i] & 0xFF); - if (hex.length() == 1) { - hex = '0' + hex; - } - System.out.print("0x" + hex.toUpperCase() + ","); - } - System.out.println(""); - } - - /** - * Convert hex string to byte[] - * - * @param hexString the hex string - * @return byte[] - */ - public static byte[] hexStringToBytes(String hexString) { - if (hexString == null || hexString.equals("")) { - return null; - } - - hexString = hexString.toUpperCase(); - int length = hexString.length() / 2; - char[] hexChars = hexString.toCharArray(); - byte[] d = new byte[length]; - for (int i = 0; i < length; i++) { - int pos = i * 2; - d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1])); - } - return d; - } - - /** - * Convert char to byte - * - * @param c char - * @return byte - */ - public static byte charToByte(char c) { - return (byte) "0123456789ABCDEF".indexOf(c); - } - - /** - * 用于建立十六进制字符的输出的小写字符数组 - */ - private static final char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', - 'e', 'f'}; - - /** - * 用于建立十六进制字符的输出的大写字符数组 - */ - private static final char[] DIGITS_UPPER = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', - 'E', 'F'}; - - /** - * 将字节数组转换为十六进制字符数组 - * - * @param data byte[] - * @return 十六进制char[] - */ - public static char[] encodeHex(byte[] data) { - return encodeHex(data, true); - } - - /** - * 将字节数组转换为十六进制字符数组 - * - * @param data byte[] - * @param toLowerCase true 传换成小写格式 , false 传换成大写格式 - * @return 十六进制char[] - */ - public static char[] encodeHex(byte[] data, boolean toLowerCase) { - return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER); - } - - /** - * 将字节数组转换为十六进制字符数组 - * - * @param data byte[] - * @param toDigits 用于控制输出的char[] - * @return 十六进制char[] - */ - protected static char[] encodeHex(byte[] data, char[] toDigits) { - int l = data.length; - char[] out = new char[l << 1]; - // two characters form the hex value. - for (int i = 0, j = 0; i < l; i++) { - out[j++] = toDigits[(0xF0 & data[i]) >>> 4]; - out[j++] = toDigits[0x0F & data[i]]; - } - return out; - } - - /** - * 将字节数组转换为十六进制字符串 - * - * @param data byte[] - * @return 十六进制String - */ - public static String encodeHexString(byte[] data) { - return encodeHexString(data, true); - } - - /** - * 将字节数组转换为十六进制字符串 - * - * @param data byte[] - * @param toLowerCase true 传换成小写格式 , false 传换成大写格式 - * @return 十六进制String - */ - public static String encodeHexString(byte[] data, boolean toLowerCase) { - return encodeHexString(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER); - } - - /** - * 将字节数组转换为十六进制字符串 - * - * @param data byte[] - * @param toDigits 用于控制输出的char[] - * @return 十六进制String - */ - protected static String encodeHexString(byte[] data, char[] toDigits) { - return new String(encodeHex(data, toDigits)); - } - - /** - * 将十六进制字符数组转换为字节数组 - * - * @param data 十六进制char[] - * @return byte[] - * @throws RuntimeException 如果源十六进制字符数组是一个奇怪的长度,将抛出运行时异常 - */ - public static byte[] decodeHex(char[] data) { - int len = data.length; - - if ((len & 0x01) != 0) { - throw new RuntimeException("Odd number of characters."); - } - - byte[] out = new byte[len >> 1]; - - // two characters form the hex value. - for (int i = 0, j = 0; j < len; i++) { - int f = toDigit(data[j], j) << 4; - j++; - f = f | toDigit(data[j], j); - j++; - out[i] = (byte) (f & 0xFF); - } - - return out; - } - - /** - * 将十六进制字符转换成一个整数 - * - * @param ch 十六进制char - * @param index 十六进制字符在字符数组中的位置 - * @return 一个整数 - * @throws RuntimeException 当ch不是一个合法的十六进制字符时,抛出运行时异常 - */ - protected static int toDigit(char ch, int index) { - int digit = Character.digit(ch, 16); - if (digit == -1) { - throw new RuntimeException("Illegal hexadecimal character " + ch + " at index " + index); - } - return digit; - } - - /** - * 数字字符串转ASCII码字符串 - * - * @param content 字符串 - * @return ASCII字符串 - */ - public static String StringToAsciiString(String content) { - String result = ""; - int max = content.length(); - for (int i = 0; i < max; i++) { - char c = content.charAt(i); - String b = Integer.toHexString(c); - result = result + b; - } - return result; - } - - /** - * 十六进制转字符串 - * - * @param hexString 十六进制字符串 - * @param encodeType 编码类型4:Unicode,2:普通编码 - * @return 字符串 - */ - public static String hexStringToString(String hexString, int encodeType) { - String result = ""; - int max = hexString.length() / encodeType; - for (int i = 0; i < max; i++) { - char c = (char) hexStringToAlgorism(hexString.substring(i * encodeType, (i + 1) * encodeType)); - result += c; - } - return result; - } - - /** - * 十六进制字符串 转 十进制 - * - * @param hex 十六进制字符串 - * @return 十进制数值 - */ - public static int hexStringToAlgorism(String hex) { - hex = hex.toUpperCase(); - int max = hex.length(); - int result = 0; - for (int i = max; i > 0; i--) { - char c = hex.charAt(i - 1); - int algorism = 0; - if (c >= '0' && c <= '9') { - algorism = c - '0'; - } else { - algorism = c - 55; - } - result += Math.pow(16, max - i) * algorism; - } - return result; - } - - /** - * 十六转二进制 - * - * @param hex 十六进制字符串 - * @return 二进制字符串 - */ - public static String hexStringToBinary(String hex) { - hex = hex.toUpperCase(); - String result = ""; - int max = hex.length(); - for (int i = 0; i < max; i++) { - char c = hex.charAt(i); - switch (c) { - case '0': - result += "0000"; - break; - case '1': - result += "0001"; - break; - case '2': - result += "0010"; - break; - case '3': - result += "0011"; - break; - case '4': - result += "0100"; - break; - case '5': - result += "0101"; - break; - case '6': - result += "0110"; - break; - case '7': - result += "0111"; - break; - case '8': - result += "1000"; - break; - case '9': - result += "1001"; - break; - case 'A': - result += "1010"; - break; - case 'B': - result += "1011"; - break; - case 'C': - result += "1100"; - break; - case 'D': - result += "1101"; - break; - case 'E': - result += "1110"; - break; - case 'F': - result += "1111"; - break; - } - } - return result; - } - - /** - * ASCII码字符串转数字字符串 - * - * @param content ASCII字符串 - * @return 字符串 - */ - public static String AsciiStringToString(String content) { - String result = ""; - int length = content.length() / 2; - for (int i = 0; i < length; i++) { - String c = content.substring(i * 2, i * 2 + 2); - int a = hexStringToAlgorism(c); - char b = (char) a; - String d = String.valueOf(b); - result += d; - } - return result; - } - - /** - * 将十进制转换为指定长度的十六进制字符串 - * - * @param algorism int 十进制数字 - * @param maxLength int 转换后的十六进制字符串长度 - * @return String 转换后的十六进制字符串 - */ - public static String algorismToHexString(int algorism, int maxLength) { - String result = ""; - result = Integer.toHexString(algorism); - - if (result.length() % 2 == 1) { - result = "0" + result; - } - return patchHexString(result.toUpperCase(), maxLength); - } - - /** - * 字节数组转为普通字符串(ASCII对应的字符) - * - * @param bytearray byte[] - * @return String - */ - public static String byteToString(byte[] bytearray) { - String result = ""; - char temp; - - int length = bytearray.length; - for (int i = 0; i < length; i++) { - temp = (char) bytearray[i]; - result += temp; - } - return result; - } - - /** - * 二进制字符串 转 十进制 - * - * @param binary 二进制字符串 - * @return 十进制数值 - */ - public static int binaryToAlgorism(String binary) { - int max = binary.length(); - int result = 0; - for (int i = max; i > 0; i--) { - char c = binary.charAt(i - 1); - int algorism = c - '0'; - result += Math.pow(2, max - i) * algorism; - } - return result; - } - - /** - * 十进制 转换为 十六进制字符串 - * - * @param algorism int 十进制的数字 - * @return String 对应的十六进制字符串 - */ - public static String algorismToHEXString(int algorism) { - String result = ""; - result = Integer.toHexString(algorism); - - if (result.length() % 2 == 1) { - result = "0" + result; - - } - result = result.toUpperCase(); - - return result; - } - - /** - * HEX字符串前补0,主要用于长度位数不足。 - * - * @param str String 需要补充长度的十六进制字符串 - * @param maxLength int 补充后十六进制字符串的长度 - * @return 补充结果 - */ - static public String patchHexString(String str, int maxLength) { - String temp = ""; - for (int i = 0; i < maxLength - str.length(); i++) { - temp = "0" + temp; - } - str = (temp + str).substring(0, maxLength); - return str; - } - - /** - * 将一个字符串转换为int - * - * @param s String 要转换的字符串 - * @param defaultInt int 如果出现异常,默认返回的数字 - * @param radix int 要转换的字符串是什么进制的,如16 8 10. - * @return int 转换后的数字 - */ - public static int parseToInt(String s, int defaultInt, int radix) { - int i = 0; - try { - i = Integer.parseInt(s, radix); - } catch (NumberFormatException ex) { - i = defaultInt; - } - return i; - } - - /** - * 将一个十进制形式的数字字符串转换为int - * - * @param s String 要转换的字符串 - * @param defaultInt int 如果出现异常,默认返回的数字 - * @return int 转换后的数字 - */ - public static int parseToInt(String s, int defaultInt) { - int i = 0; - try { - i = Integer.parseInt(s); - } catch (NumberFormatException ex) { - i = defaultInt; - } - return i; - } - - /** - * 十六进制串转化为byte数组 - * - * @return the array of byte - */ - public static byte[] hexToByte(String hex) throws IllegalArgumentException { - if (hex.length() % 2 != 0) { - throw new IllegalArgumentException(); - } - char[] arr = hex.toCharArray(); - byte[] b = new byte[hex.length() / 2]; - for (int i = 0, j = 0, l = hex.length(); i < l; i++, j++) { - String swap = "" + arr[i++] + arr[i]; - int byteint = Integer.parseInt(swap, 16) & 0xFF; - b[j] = new Integer(byteint).byteValue(); - } - return b; - } - - /** - * 字节数组转换为十六进制字符串 - * - * @param b byte[] 需要转换的字节数组 - * @return String 十六进制字符串 - */ - public static String byteToHex(byte b[]) { - if (b == null) { - throw new IllegalArgumentException("Argument b ( byte array ) is null! "); - } - String hs = ""; - String stmp = ""; - for (int n = 0; n < b.length; n++) { - stmp = Integer.toHexString(b[n] & 0xff); - if (stmp.length() == 1) { - hs = hs + "0" + stmp; - } else { - hs = hs + stmp; - } - } - return hs.toUpperCase(); - } - - public static byte[] subByte(byte[] input, int startIndex, int length) { - byte[] bt = new byte[length]; - for (int i = 0; i < length; i++) { - bt[i] = input[i + startIndex]; - } - return bt; - } -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/secure/sm3/SM3Digest.java b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/secure/sm3/SM3Digest.java deleted file mode 100644 index e6af766c6f..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/java/com/jun/plugin/security/util/secure/sm3/SM3Digest.java +++ /dev/null @@ -1,132 +0,0 @@ -package com.jun.plugin.security.util.secure.sm3; - -/** - * 国密3加密算法工具类 - * - * @version 2021-01-02-14:20 - **/ -public class SM3Digest { - /** - * SM3值的长度 - */ - private static final int BYTE_LENGTH = 32; - - /** - * SM3分组长度 - */ - private static final int BLOCK_LENGTH = 64; - - /** - * 缓冲区长度 - */ - private static final int BUFFER_LENGTH = BLOCK_LENGTH * 1; - - /** - * 缓冲区 - */ - private byte[] xBuf = new byte[BUFFER_LENGTH]; - - /** - * 缓冲区偏移量 - */ - private int xBufOff; - - /** - * 初始向量 - */ - private byte[] V = SM3.iv.clone(); - - private int cntBlock = 0; - - public SM3Digest() { - } - - public SM3Digest(SM3Digest t) { - System.arraycopy(t.xBuf, 0, this.xBuf, 0, t.xBuf.length); - this.xBufOff = t.xBufOff; - System.arraycopy(t.V, 0, this.V, 0, t.V.length); - } - - /** - * SM3结果输出 - * - * @param out 保存SM3结构的缓冲区 - * @param outOff 缓冲区偏移量 - * @return - */ - public int doFinal(byte[] out, int outOff) { - byte[] tmp = doFinal(); - System.arraycopy(tmp, 0, out, 0, tmp.length); - return BYTE_LENGTH; - } - - public void reset() { - xBufOff = 0; - cntBlock = 0; - V = SM3.iv.clone(); - } - - /** - * 明文输入 - * - * @param in 明文输入缓冲区 - * @param inOff 缓冲区偏移量 - * @param len 明文长度 - */ - public void update(byte[] in, int inOff, int len) { - int partLen = BUFFER_LENGTH - xBufOff; - int inputLen = len; - int dPos = inOff; - if (partLen < inputLen) { - System.arraycopy(in, dPos, xBuf, xBufOff, partLen); - inputLen -= partLen; - dPos += partLen; - doUpdate(); - while (inputLen > BUFFER_LENGTH) { - System.arraycopy(in, dPos, xBuf, 0, BUFFER_LENGTH); - inputLen -= BUFFER_LENGTH; - dPos += BUFFER_LENGTH; - doUpdate(); - } - } - - System.arraycopy(in, dPos, xBuf, xBufOff, inputLen); - xBufOff += inputLen; - } - - private void doUpdate() { - byte[] B = new byte[BLOCK_LENGTH]; - for (int i = 0; i < BUFFER_LENGTH; i += BLOCK_LENGTH) { - System.arraycopy(xBuf, i, B, 0, B.length); - doHash(B); - } - xBufOff = 0; - } - - private void doHash(byte[] B) { - byte[] tmp = SM3.CF(V, B); - System.arraycopy(tmp, 0, V, 0, V.length); - cntBlock++; - } - - private byte[] doFinal() { - byte[] B = new byte[BLOCK_LENGTH]; - byte[] buffer = new byte[xBufOff]; - System.arraycopy(xBuf, 0, buffer, 0, buffer.length); - byte[] tmp = SM3.padding(buffer, cntBlock); - for (int i = 0; i < tmp.length; i += BLOCK_LENGTH) { - System.arraycopy(tmp, i, B, 0, B.length); - doHash(B); - } - return V; - } - - public void update(byte in) { - byte[] buffer = new byte[]{in}; - update(buffer, 0, 1); - } - - public int getDigestSize() { - return BYTE_LENGTH; - } -} diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/resources/META-INF/spring.factories b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 1f03e10c64..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,2 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -com.jun.plugin.security.AuthAutoConfiguration \ No newline at end of file diff --git a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/resources/sql/s_auth_token.sql b/jun_springboot_starter/jun-security-spring-boot-starter/src/main/resources/sql/s_auth_token.sql deleted file mode 100644 index 1a668ec65f..0000000000 --- a/jun_springboot_starter/jun-security-spring-boot-starter/src/main/resources/sql/s_auth_token.sql +++ /dev/null @@ -1,20 +0,0 @@ - -SET NAMES utf8mb4; -SET FOREIGN_KEY_CHECKS = 0; - --- ---------------------------- --- Table structure for b_auth_token --- ---------------------------- -DROP TABLE IF EXISTS `s_auth_token`; -CREATE TABLE `s_auth_token` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增主键', - `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - `updated_at` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', - `token_str` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT 'token', - `login_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '用户id', - `token_expire_time` char(14) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT 'token过期时间', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `s_auth_token_unique_token_str`(`token_str`) USING BTREE COMMENT 'token_str不可重复' -) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; - -SET FOREIGN_KEY_CHECKS = 1; diff --git a/jun_springboot_starter/jun-sentinel-spring-boot-starter/pom.xml b/jun_springboot_starter/jun-sentinel-spring-boot-starter/pom.xml deleted file mode 100644 index b37877fb47..0000000000 --- a/jun_springboot_starter/jun-sentinel-spring-boot-starter/pom.xml +++ /dev/null @@ -1,90 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun-sentinel-spring-boot-starter - 1.0.25 - jar - 服务降级、熔断和限流通用组件 - - - 1.8 - UTF-8 - 1.8 - 1.8 - 1.0.25 - 2.5.14 - 2020.0.6 - 2021.1 - 2.3.2 - - - - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - com.alibaba.cloud - spring-cloud-alibaba-dependencies - ${spring-cloud-alibaba.version} - pom - import - - - - - - io.github.wujun728 - jun-common-base - ${jun.version} - - - com.alibaba.cloud - spring-cloud-starter-alibaba-sentinel - - - com.alibaba.csp - sentinel-datasource-nacos - - - org.springframework.cloud - spring-cloud-starter-openfeign - true - - - org.springframework.boot - spring-boot-starter-web - provided - - - - org.springframework.boot - spring-boot-configuration-processor - true - - - - org.springframework - spring-webflux - true - - - net.dreamlu - mica-auto - - - diff --git a/jun_springboot_starter/jun-sentinel-spring-boot-starter/src/main/java/io/github/wujun728/sentinel/config/SentinelAutoConfigure.java b/jun_springboot_starter/jun-sentinel-spring-boot-starter/src/main/java/io/github/wujun728/sentinel/config/SentinelAutoConfigure.java deleted file mode 100644 index fcada34052..0000000000 --- a/jun_springboot_starter/jun-sentinel-spring-boot-starter/src/main/java/io/github/wujun728/sentinel/config/SentinelAutoConfigure.java +++ /dev/null @@ -1,53 +0,0 @@ -package io.github.wujun728.sentinel.config; - -import cn.hutool.json.JSONUtil; -import com.alibaba.csp.sentinel.adapter.spring.webflux.callback.BlockRequestHandler; -import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler; -import io.github.wujun728.common.base.Result; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.web.reactive.function.BodyInserters; -import org.springframework.web.reactive.function.server.ServerResponse; - -import javax.servlet.http.HttpServletRequest; - -/** - * Sentinel配置类 - * - */ -public class SentinelAutoConfigure { - /** - * 限流、熔断统一处理类 - */ - @Configuration - @ConditionalOnClass(HttpServletRequest.class) - public static class WebmvcHandler { - @Bean - public BlockExceptionHandler webmvcBlockExceptionHandler() { - return (request, response, e) -> { - response.setStatus(429); - Result result = Result.error(e.getMessage()); - response.getWriter().print(JSONUtil.toJsonStr(result)); - }; - } - } - - - /** - * 限流、熔断统一处理类 - */ - @Configuration - @ConditionalOnClass(ServerResponse.class) - public static class WebfluxHandler { - @Bean - public BlockRequestHandler webfluxBlockExceptionHandler() { - return (exchange, t) -> - ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS) - .contentType(MediaType.APPLICATION_JSON) - .body(BodyInserters.fromValue(Result.error(t.getMessage()))); - } - } -} diff --git a/jun_springboot_starter/jun-sentinel-spring-boot-starter/src/main/resources/META-INF/spring.factories.bk b/jun_springboot_starter/jun-sentinel-spring-boot-starter/src/main/resources/META-INF/spring.factories.bk deleted file mode 100644 index 8ffa225373..0000000000 --- a/jun_springboot_starter/jun-sentinel-spring-boot-starter/src/main/resources/META-INF/spring.factories.bk +++ /dev/null @@ -1,2 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -io.github.wujun728.sentinel.config.SentinelAutoConfigure diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/pom.xml b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/pom.xml deleted file mode 100644 index c89a950794..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/pom.xml +++ /dev/null @@ -1,105 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun-snakerflow-spring-boot-starter - 1.0.25 - jar - 数据库通用组件 - - - 1.8 - UTF-8 - 1.8 - 1.8 - 1.0.25 - 2.5.14 - 2020.0.6 - 3.5.7 - 1.2.6 - 1.0.8 - 1.6.6 - 2.3.2 - - - - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - - - - io.github.wujun728 - jun-common-base - ${jun.version} - - - - - com.baomidou - mybatis-plus-boot-starter - - - - com.alibaba - druid-spring-boot-starter - - - - org.springframework.boot - spring-boot-configuration-processor - true - - - - - - - com.github.snakerflow-starter - snakerflow-spring-boot-starter - ${snakerflow.version} - - - mybatis-plus-boot-starter - com.baomidou - - - - - com.baomidou - mybatis-plus-boot-starter - - - net.dreamlu - mica-auto - - - io.swagger - swagger-annotations - ${swagger-annotations.version} - compile - - - diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/SnakerflowFacetsController.java b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/SnakerflowFacetsController.java deleted file mode 100644 index da17c00e4d..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/SnakerflowFacetsController.java +++ /dev/null @@ -1,550 +0,0 @@ -package io.github.wujun728.snakerflow; - -import static org.snaker.engine.access.QueryFilter.DESC; - -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -import javax.servlet.http.HttpServletResponse; - -//import io.github.wujun728.bizservice.service.BizCommonService; -import io.github.wujun728.snakerflow.ext.mapper.ExtLogMapper; -import io.github.wujun728.snakerflow.module.PageResponse; -import io.github.wujun728.snakerflow.module.Response; -import io.github.wujun728.snakerflow.process.SnakerEngineFacets; -import io.github.wujun728.snakerflow.process.SnakerHelper; -import org.apache.commons.lang.StringUtils; -import org.snaker.engine.SnakerEngine; -import org.snaker.engine.access.Page; -import org.snaker.engine.access.QueryFilter; -import org.snaker.engine.entity.HistoryOrder; -import org.snaker.engine.entity.HistoryTask; -import org.snaker.engine.entity.Order; -import org.snaker.engine.entity.Process; -import org.snaker.engine.entity.Task; -import org.snaker.engine.entity.WorkItem; -import org.snaker.engine.helper.AssertHelper; -import org.snaker.engine.helper.StreamHelper; -import org.snaker.engine.helper.StringHelper; -import org.snaker.engine.model.ProcessModel; -import org.snaker.engine.model.TaskModel; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; - -//import io.github.wujun728.system.entity.SysUser; -//import io.github.wujun728.system.mapper.SysUserMapper; -//import io.github.wujun728.system.service.HttpSessionService; -//import com.laker.admin.framework.aop.Metrics; -//import com.laker.admin.module.flow.SnakerflowFacetsController; -//import com.laker.admin.module.sys.entity.SysUser; -//import com.laker.admin.module.sys.service.ISysUserService; -//import io.github.wujun728.system.service.UserService; - -//import cn.dev33.satoken.annotation.SaCheckPermission; -//import cn.dev33.satoken.stp.StpUtil; -//import cn.dev33.satoken.annotation.SaCheckPermission; -//import cn.dev33.satoken.stp.StpUtil; -import cn.hutool.core.collection.CollUtil; -import cn.hutool.core.lang.Dict; -import cn.hutool.core.map.MapUtil; -import cn.hutool.core.util.StrUtil; -import cn.hutool.json.JSONUtil; -//import com.laker.admin.framework.aop.Metrics; -//import com.laker.admin.framework.model.PageResponse; -//import com.laker.admin.framework.model.Response; -//import com.laker.admin.module.flow.process.SnakerEngineFacets; -//import com.laker.admin.module.flow.process.SnakerHelper; -//import com.laker.admin.module.sys.entity.SysUser; -//import com.laker.admin.module.sys.service.ISysUserService; -import io.swagger.annotations.ApiOperation; -import lombok.extern.slf4j.Slf4j; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; - -@RestController -@RequestMapping("/flow") -@Slf4j -public class SnakerflowFacetsController { - -// @Resource -// HttpSessionService sessionService; - - @Autowired - private SnakerEngineFacets snakerEngineFacets; - -// @Resource -// private UserService sysUserService; - -// @Autowired -// private SysUserMapper sysuer; - - @Autowired - private ExtLogMapper bizCommonMapper; -// @Autowired -// private BizCommonService bizCommonService; - - /** - * ---------------------------------------------流程定义-------------------------------------------- - */ - /** - * 根据流程文件名称,在线部署流程 http://qixing.vip321.vip/flow/process/deploy/leave.snaker - * http://localhost:8081/flow/process/deploy/leave.snaker - * - * @return - */ - @ApiOperation(value = "根据流程文件名称,在线部署流程", tags = "流程引擎-流程部署") - @RequestMapping(value = "/process/deploy/{filename}", method = RequestMethod.GET) - // @Metrics - public Response processdeploy(@PathVariable("filename") String filename) { - snakerEngineFacets.initFlowsByName(filename); - return Response.ok(); - } - - /** - * 获取流程定义,获取流程定义的XML,根据流程ID - */ - @GetMapping("/getXml") - public Response processEdit(String id) { - Process process = snakerEngineFacets.getEngine().process().getProcessById(id); - if (process.getDBContent() != null) { - try { - return Response.ok(new String(process.getDBContent(), "UTF-8")); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - } - return Response.error("500", "xml异常"); - } - - /** - * 获取流程定义JOSN,根据流程定义的名称 - * - * @param processId - * @return - */ - @GetMapping(value = "/process/modelJson"/*, produces = "application/json;charset=UTF-8"*/) -// @GetMapping(value = "/process/modelJson", produces = "text/plain;charset=UTF-8") - @ApiOperation(value = "根据流程定义名称获取流程定义json", tags = "流程引擎-流程") - // @Metrics - public void getProcess(@RequestParam(required = false) String processId) throws IOException { - HttpServletResponse response = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse(); - assert response != null; - String json = ""; - if (StrUtil.isBlank(processId)) { - json = ""; - } - Process process = snakerEngineFacets.getEngine().process().getProcessById(processId); - AssertHelper.notNull(process); - ProcessModel processModel = process.getModel(); - if (processModel != null) { - json = SnakerHelper.getModelJson(processModel); - -// return json; - } - response.setStatus(200); - response.setContentType("application/json"); - response.setCharacterEncoding("utf-8"); - response.getWriter().print(json); -// return null; - } - - /** - * 流程定义清单,查询列表 - */ - @ApiOperation(value = "根据给定的参数列表args分页查询process", tags = "流程引擎-流程") - @RequestMapping(value = "/process/list", method = RequestMethod.GET) - public Response processList(Page page, String displayName, String limit) { - QueryFilter filter = new QueryFilter(); - if (StringHelper.isNotEmpty(displayName)) { - filter.setDisplayName(displayName); - } - if (StringHelper.isNotEmpty(limit)) { - page.setPageSize(Integer.valueOf(limit)); - } - filter.orderBy("create_Time").order(DESC); - snakerEngineFacets.getEngine().process().getProcesss(page, filter); - return PageResponse.ok(JSONUtil.parse(page.getResult()), page.getTotalCount()); - } - - /** - * 根据流程定义ID,删除流程定义 - * - * @param id - * @return - */ - @ApiOperation(value = "根据流程定义ID,删除流程定义", tags = "流程引擎-流程") - @RequestMapping(value = "/process/delete/{id}", method = RequestMethod.GET) - // @Metrics - // @SaCheckPermission("flow.delete") - public Response processDelete(@PathVariable("id") String id) { - snakerEngineFacets.getEngine().process().undeploy(id); - return Response.ok(); - } - - /** - * 保存流程定义[web流程设计器] - * - * @param model - * @return - */ - @ApiOperation(value = "保存流程定义[web流程设计器]", tags = "流程引擎-流程") - @RequestMapping(value = "/process/deployXml", method = RequestMethod.POST) - // @SaCheckPermission("flow.update") - public boolean processDeploy(String model, String id, - @RequestParam(required = false, defaultValue = "false") boolean xmlHearder) { - InputStream input = null; - try { - String xml = ""; - if (!xmlHearder) { - xml = "\n"; - } - xml = xml + SnakerHelper.convertXml(model); - System.out.println("model xml=\n" + xml); - input = StreamHelper.getStreamFromString(xml); - if (StringUtils.isNotEmpty(id)) { - snakerEngineFacets.getEngine().process().redeploy(id, input); - } else { - snakerEngineFacets.getEngine().process().deploy(input); - } - } catch (Exception e) { - e.printStackTrace(); - return false; - } finally { - if (input != null) { - try { - input.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - return true; - } - - /** - * - * @param processId - * @param orderId - * @return - */ - @ApiOperation(value = "流程定义+流程状态", tags = "流程引擎-流程") - @RequestMapping(value = "/process/json", method = RequestMethod.GET) - // @Metrics - public Object json(String processId, String orderId) { - if (StrUtil.isBlank(processId)) { - processId = snakerEngineFacets.getEngine().query().getHistOrder(orderId).getProcessId(); - } - Process process = snakerEngineFacets.getEngine().process().getProcessById(processId); - AssertHelper.notNull(process); - ProcessModel model = process.getModel(); - Map jsonMap = new HashMap(); - if (model != null) { - jsonMap.put("process", SnakerHelper.getModelJson(model)); - } - - if (StringUtils.isNotEmpty(orderId)) { - List tasks = snakerEngineFacets.getEngine().query() - .getActiveTasks(new QueryFilter().setOrderId(orderId)); - List historyTasks = snakerEngineFacets.getEngine().query() - .getHistoryTasks(new QueryFilter().setOrderId(orderId)); - jsonMap.put("state", SnakerHelper.getStateJson(model, tasks, historyTasks)); - } - log.info(jsonMap.get("state")); - // {"historyRects":{"rects":[{"paths":["TO 任务1"],"name":"开始"},{"paths":["TO - // 分支"],"name":"任务1"},{"paths":["TO 任务3","TO 任务4","TO 任务2"],"name":"分支"}]}} - return jsonMap; - } - - /** - * --------------------------------------------- 任务相关 - * --------------------------------------------- - */ - /** - * 根据当前用户查询待办任务列表 - */ - @GetMapping("/task/todoList") - @ApiOperation(value = "根据当前用户查询待办任务列表", tags = "流程引擎-任务") - public PageResponse userTaskTodoList(String username) { - if (org.springframework.util.StringUtils.isEmpty(username)) { - username = "sessionService.getCurrentUsername()"; - } - String usercode = "sessionService.getCurrentUsername()"; - Page page = new Page<>(30); - snakerEngineFacets.getEngine().query().getWorkItems(page, new QueryFilter().setOperator(username)); - return PageResponse.ok(page.getResult(), page.getTotalCount()); - } - - /** - * 根据当前用户查询待办任务列表 - */ - @GetMapping("/task/doneList") - @ApiOperation(value = "根据当前用户查询已办任务列表", tags = "流程引擎-任务") - public PageResponse userTaskdoneList() { - Page page = new Page<>(30); - snakerEngineFacets.getEngine().query().getHistoryWorkItems(page, - new QueryFilter().setOperator("sessionService.getCurrentUsername()")); - List items = page.getResult(); - return PageResponse.ok(page.getResult(), page.getTotalCount()); - } - - @GetMapping("/task/actor/add") - @ApiOperation(value = "根据流程实例id和任务名称,增加任务参与者", tags = "流程引擎-任务") - public Response addTaskActor(@RequestParam("orderId") String orderId, @RequestParam("taskName") String taskName, - @RequestParam("operator") String operator) { - List tasks = snakerEngineFacets.getEngine().query().getActiveTasks(new QueryFilter().setOrderId(orderId)); - for (Task task : tasks) { - if (task.getTaskName().equalsIgnoreCase(taskName) && StringUtils.isNotEmpty(operator)) { - snakerEngineFacets.getEngine().task().addTaskActor(task.getId(), operator); - } - } - return Response.ok(); - } - - @GetMapping("/task/tip") - @ApiOperation(value = "根据流程实例id和任务名称,查找当前任务的到达时间和待执行人", tags = "流程引擎-任务") - public Response taskTip(String orderId, String taskName) { - List tasks = snakerEngineFacets.getEngine().query().getActiveTasks(new QueryFilter().setOrderId(orderId)); - StringBuilder builder = new StringBuilder(); - String createTime = ""; - String finishTime = ""; - String taskOperatorFlag = ""; - String taskOperatorMsg = ""; - boolean find = false; - for (Task task : tasks) { - if (task.getTaskName().equalsIgnoreCase(taskName)) { - String[] actors = snakerEngineFacets.getEngine().query().getTaskActorsByTaskId(task.getId()); - String.join(",",actors); - for (String actor : actors) { -// SysUser sysUser = sysuer.getUserByName(actor); -// if (sysUser!=null) { -// String name = sysUser.getRealName(); -// if (!builder.toString().contains(name)) { -// builder.append(name).append(","); -// } -// }else{ -// //builder.append("用户【"+actor+"】不存在 ").append(","); -// -// } - find = true; - } - createTime = task.getCreateTime(); - taskOperatorFlag = String.valueOf(task.getVariableMap().get("taskOperatorFlag")); - taskOperatorMsg = String.valueOf(task.getVariableMap().get("taskOperatorMsg")); - } - } - if (!find) { - List historyTasks = snakerEngineFacets.getEngine().query() - .getHistoryTasks(new QueryFilter().setOrderId(orderId)); - for (HistoryTask task : historyTasks) { - if (task.getTaskName().equalsIgnoreCase(taskName)) { - String[] actors = snakerEngineFacets.getEngine().query().getHistoryTaskActorsByTaskId(task.getId()); - for (String actor : actors) { -// // SysUser sysUser = sysUserService.getById(String.valueOf(actor)); -// SysUser sysUser = sysuer.getUserByName(actor); -// if (sysUser != null) { -// String nickName = sysUser.getRealName(); -// if (!builder.toString().contains(nickName)) { -// builder.append(nickName).append(","); -// } -// } - } - createTime = task.getCreateTime(); - finishTime = task.getFinishTime(); - taskOperatorFlag = String.valueOf(task.getVariableMap().get("taskOperatorFlag")); - taskOperatorMsg = String.valueOf(task.getVariableMap().get("taskOperatorMsg")); - } - } - } - if (builder.length() > 0) { - builder.deleteCharAt(builder.length() - 1); - } - Map data = new HashMap(); - data.put("actors", builder.toString()); - data.put("createTime", createTime); - data.put("finishTime", finishTime); - data.put("taskOperatorFlag", taskOperatorFlag); - data.put("taskOperatorMsg", taskOperatorMsg); - return Response.ok(data); - } - - /** - * 活动任务的驳回 - */ - @GetMapping("/task/reject") - @ApiOperation(value = "\t 【审批任务】驳回,根据任务主键ID,操作人ID,参数列表执行任务,并且根据nodeName跳转到任意节点\n" - + "\t 1、nodeName为null时,则跳转至上一步处理\n" + "\t 2、nodeName不为null时,则任意跳转,即动态创建转移", tags = "流程引擎-任务") - public Response activeTaskReject(String taskId, String nodeName, String reason) { - Dict rejectReason = Dict.create() - // 拒绝原因,建议单独搞个 审核表 审核的comment file单独存储 - .set("rejectReason", reason); - Map args = new HashMap(8); - args.put("taskOperator", "sessionService.getCurrentUsername()"); - args.put("taskOperatorMsg", "驳回原因,填写有问题,不能XXX,需要XXX!"); - args.put("taskOperatorFlag", "处理结果:驳回"); - snakerEngineFacets.executeAndJump(taskId, "sessionService.getCurrentUsername()", args, nodeName); - return Response.ok(); - } - - /** - * 活动任务的驳回-驳回到发起人 - */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - @GetMapping("/task/rejectToCreate") - @ApiOperation(value = "【任务驳回】驳回到发起人", tags = "流程引擎-任务") - public Response activeTaskReject(String taskId, String taskOperatorFlag, String taskOperatorMsg, - String operatorNextid, String operatorNext) { - List workItems = snakerEngineFacets.getEngine().query().getWorkItems(null, - new QueryFilter().setTaskId(taskId)); - if (CollUtil.isEmpty(workItems)) { - Response.error("500", "不存在任务喽"); - } - WorkItem workItem = workItems.get(0); - Process process = snakerEngineFacets.getEngine().process().getProcessById(workItem.getProcessId()); - ProcessModel model = process.getModel(); - // 获取开始节点下面的第一个节点 - String name = model.getStart().getOutputs().get(0).getTarget().getName(); - Map args = new HashMap(8); - args.put("taskOperator", "sessionService.getCurrentUsername()"); - args.put("taskOperatorName", operatorNext); - args.put("taskOperatorMsg", taskOperatorMsg); - args.put("taskOperatorFlag", taskOperatorFlag); - snakerEngineFacets.executeAndJump(taskId, "sessionService.getCurrentUsername()", args, name); - return Response.ok(); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @RequestMapping(value = "/task/approval", method = RequestMethod.GET) - @ApiOperation(value = "【审批任务】同意", tags = "流程引擎-任务") - public Response doApproval(String taskId, String flag, String taskOperatorFlag, String taskOperatorMsg, - String operatorNextid, String operatorNext, String processName, String processId) { - Task task1 = snakerEngineFacets.getEngine().query().getTask(taskId);// 查询当前任务节点信息 - String orderId = task1.getOrderId(); - String taskName = task1.getTaskName(); - String processNameEn = String.valueOf(task1.getVariableMap().get("processName"));// 获取流程名称 - String businessId = String.valueOf(task1.getVariableMap().get("businessId"));// 获取流程名称 - Process process = snakerEngineFacets.getEngine().process().getProcessByName(processNameEn);// 获取流程实例信息 - List tm = process.getModel().getNode(task1.getTaskName()).getNextModels(TaskModel.class);// 获取流程下一环节节点信息 - if (!"0".equals(flag) && tm.size() > 0 && operatorNextid != null && operatorNextid.length() < 1) {// flag:0|1,判断节点的分支属性;下一环节处理人 - return Response.error("1010", "流程审批人不能为空(驳回及非最终环节)!"); - } - if (tm == null || tm.size() == 0) { - log.info("流程结束!" + processNameEn, "orderId=" + orderId); - //@TODO wujun 改定时任务处理 - String errMsg = ""; - //bizCommonService.doAfterFlowFinish(processNameEn, orderId, businessId, taskName); - if (errMsg.length() > 0) { - Response.error("2022", errMsg); - } - } - Map args = new HashMap(8); - args.put("taskOperator", "sessionService.getCurrentUsername()"); - args.put("taskOperatorName", operatorNext); - args.put("taskOperatorMsg", taskOperatorMsg); - args.put("taskOperatorFlag", taskOperatorFlag); - try { - args.put("flag", Integer.valueOf(flag)); - } catch (NumberFormatException e) { - log.error("flag Integer.valueOf(flag) NumberFormatException 暂不处理 "); - e.printStackTrace(); - } - List tasks = snakerEngineFacets.execute(taskId, "sessionService.getCurrentUsername()", args); - for (Task task : tasks) { - snakerEngineFacets.getEngine().task().addTaskActor(task.getId(), operatorNextid.split(",")); - } - return Response.ok(); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @RequestMapping(value = "/task/submit", method = { RequestMethod.GET, RequestMethod.POST }) - @ApiOperation(value = "【提交任务】", tags = "流程引擎-任务") - public Response doSubmitTask(@RequestBody Map param) { - String processName = MapUtil.getStr(param, "processName"); - String taskNewName = MapUtil.getStr(param, "taskNewName"); - String taskOperatorMsg = MapUtil.getStr(param, "taskOperatorMsg"); - String operatorNextid = MapUtil.getStr(param, "operatorNextid"); - String operatorNext = MapUtil.getStr(param, "operatorNext"); - String taskOperatorFlag = MapUtil.getStr(param, "taskOperatorFlag"); - String businessId = MapUtil.getStr(param, "businessId"); -// SysUser user = sysUserService.getById(sessionService.getCurrentUserId()); - // - String orderName = taskNewName; - List> list = WorkflowsConfig.getList(); - for (Map item : list) { - if (processName.equalsIgnoreCase(item.get("processName"))) { -// String step1 = item.get("step1"); -// String step2 = item.get("step2"); - String tname = item.get("tname"); -// String process = item.get("process"); - String taskName = item.get("taskName"); - if (orderName == null || orderName.length() < 1) { - //@TODO wujun -// orderName = user.getRealName() + taskName /* + PrimaryKeyService.getOrderIdPrefix(new Date()) */; - } - Map args = new HashMap(8); - args.put("taskOperator", "sessionService.getCurrentUsername()"); - args.put("step1", "sessionService.getCurrentUsername()"); - args.put("step2", operatorNextid.split(",")); - args.put("processName", processName); - args.put("tname", tname); - args.put("businessId", businessId); - args.put("taskOperatorMsg", taskOperatorMsg); - args.put("taskOperatorFlag", taskOperatorFlag); - args.put(SnakerEngine.ID, orderName); - Order order = snakerEngineFacets.startAndExecute(processName, null, "sessionService.getCurrentUsername()", - args); - if (businessId.contains(",")) { - for (String id : businessId.split(",")) { - bizCommonMapper.updateRecordByColumnValue(tname, "order_id", order.getId(), id); - } - } else { - bizCommonMapper.updateRecordByColumnValue(tname, "order_id", order.getId(), businessId); - } - return Response.ok(); - } - } - return Response.error("2010", "流程配置有问题!"); - } - - /** - * 历史任务撤回,这玩意只能撤回刚发出的且没有被处理的 - * - * @param taskId - * @return - */ - @GetMapping("/task/undo") - @ApiOperation(value = "根据任务主键id、操作人撤回任务", tags = "流程引擎-任务") - public Response historyTaskUndo(String taskId) { - snakerEngineFacets.getEngine().task().withdrawTask(taskId, "sessionService.getCurrentUsername()"); - return Response.ok(); - } - - @GetMapping("/task/transferMajor") - @ApiOperation(value = "转办", tags = "流程引擎-任务") - public Response transferMajor(String taskId, String nextOperator) { - snakerEngineFacets.transferMajor(taskId, "sessionService.getCurrentUsername()", nextOperator.split(",")); - return Response.ok(); - } - - /** - * ------------------ 流程 - */ - /** - * 流程实例管理 - */ - @ApiOperation(value = "流程分页查询", tags = "流程引擎-流程实例") - @RequestMapping(value = "/order/list", method = RequestMethod.GET) - public Response orderList(Page page, String displayName) { - QueryFilter filter = new QueryFilter(); - if (StringHelper.isNotEmpty(displayName)) { - filter.setDisplayName(displayName); - } - filter.orderBy("create_Time").order(DESC); - snakerEngineFacets.getEngine().query().getHistoryOrders(page, filter); - return PageResponse.ok(JSONUtil.parse(page.getResult()), page.getTotalCount()); - } -} \ No newline at end of file diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/StatisticsController.java b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/StatisticsController.java deleted file mode 100644 index 0ac3d04e7b..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/StatisticsController.java +++ /dev/null @@ -1,47 +0,0 @@ -package io.github.wujun728.snakerflow; - -import java.util.List; - -import io.github.wujun728.snakerflow.module.Response; -import io.github.wujun728.snakerflow.process.SnakerEngineFacets; -import org.snaker.engine.access.QueryFilter; -import org.snaker.engine.entity.HistoryTask; -import org.snaker.engine.entity.Task; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -//import com.laker.admin.module.ext.mapper.ExtLogMapper; -//import io.github.wujun728.system.service.HttpSessionService; - -//import cn.dev33.satoken.stp.StpUtil; -//import cn.dev33.satoken.stp.StpUtil; -import cn.hutool.core.lang.Dict; - -@RestController -@RequestMapping("/sys/statistics") -public class StatisticsController { - @Autowired - private SnakerEngineFacets snakerEngineFacets; -// @Resource -// HttpSessionService sessionService; -// @Autowired -// ExtLogMapper extLogMapper; - - - @GetMapping("/console") - public Response get() { - //获取当前登陆人 - String userId = "admin";//sessionService.getCurrentUsername(); - List activeTasks = snakerEngineFacets.getEngine().query() - .getActiveTasks(new QueryFilter().setOperator(userId)); - List historyTasks = snakerEngineFacets.getEngine().query() - .getHistoryTasks(new QueryFilter().setOperator(userId)); - Dict res = Dict.create().set("todo", activeTasks.size()) - .set("done", historyTasks.size()) - .set("ip", "IP地址") - .set("online", 0); - return Response.ok(res); - } -} diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/WorkflowsConfig.java b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/WorkflowsConfig.java deleted file mode 100644 index 08bf189ed1..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/WorkflowsConfig.java +++ /dev/null @@ -1,23 +0,0 @@ -package io.github.wujun728.snakerflow; - -import java.util.List; -import java.util.Map; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ConfigurationProperties(prefix = "workflows") -public class WorkflowsConfig { - - public static List> list; //static 才能拿配置值 - - public static List> getList() { - return list; - } - - public void setList(List> list) { - WorkflowsConfig.list = list; - } - -} diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/config/SankerflowAutoConfig.java b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/config/SankerflowAutoConfig.java deleted file mode 100644 index 9d7f496001..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/config/SankerflowAutoConfig.java +++ /dev/null @@ -1,15 +0,0 @@ -package io.github.wujun728.snakerflow.config; - -import org.mybatis.spring.annotation.MapperScan; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -/** - * @author wujun - * @date 2021/3/19 - */ -@Configuration -@ComponentScan(basePackages = "io.github.wujun728.snakerflow") -@MapperScan(basePackages = "io.github.wujun728.snakerflow.**.mapper") -public class SankerflowAutoConfig { -} diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/controller/ExtLeaveController.java b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/controller/ExtLeaveController.java deleted file mode 100644 index ff94cc7ec9..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/controller/ExtLeaveController.java +++ /dev/null @@ -1,129 +0,0 @@ -package io.github.wujun728.snakerflow.ext.controller; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import io.github.wujun728.snakerflow.ext.entity.ExtLeave; -import io.github.wujun728.snakerflow.ext.service.IExtLeaveService; -import io.github.wujun728.snakerflow.module.PageResponse; -import io.github.wujun728.snakerflow.module.Response; -import io.github.wujun728.snakerflow.process.BaseFlowController; -import org.snaker.engine.SnakerEngine; -import org.snaker.engine.entity.Order; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.transaction.annotation.Transactional; -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.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import io.github.wujun728.snakerflow.process.SnakerEngineFacets; -//import io.github.wujun728.system.entity.SysUser; -//import io.github.wujun728.system.service.HttpSessionService; -//import io.github.wujun728.system.service.UserService; -import cn.hutool.core.collection.CollUtil; -import cn.hutool.core.date.DateUtil; -import io.swagger.annotations.ApiOperation; - -/** - *

        - * 前端控制器 - *

        - * - * - * @since 2021-08-19 - */ -@RestController -@RequestMapping("/ext/leave") -//@Metrics -public class ExtLeaveController extends BaseFlowController { -// @Resource -// HttpSessionService sessionService; - @Autowired -IExtLeaveService extLeaveService; - @Autowired - private SnakerEngineFacets snakerEngineFacets; -// @Autowired -// private UserService sysUserService; - - @GetMapping - @ApiOperation(value = "分页查询") - public PageResponse pageAll(@RequestParam(required = false, defaultValue = "1") long page, - @RequestParam(required = false, defaultValue = "10") long limit) { - Page roadPage = new Page<>(page, limit); - LambdaQueryWrapper queryWrapper = new QueryWrapper().lambda(); - queryWrapper.orderByDesc(ExtLeave::getCreateTime); - Page pageList = extLeaveService.page(roadPage, queryWrapper); - List records = pageList.getRecords(); - records.forEach(extLeave -> { - if(extLeave.getOrderId()!=null && extLeave.getOrderId().length()>0) { - //extLeave.setCreateUser(sysUserService.getById(extLeave.getCreateBy())); - this.setFlowStatusInfo(extLeave); - } - - }); - return PageResponse.ok(records, pageList.getTotal()); - } - - @SuppressWarnings("unchecked") - @PostMapping - @ApiOperation(value = "发起请假") - @Transactional(rollbackFor = Exception.class) - public Response saveOrUpdate(@RequestBody ExtLeave param) { - if (param.getLeaveId() == null) { - param.setLeaveUserId(String.valueOf("sessionService.getCurrentUsername()")); - Map args = new HashMap(8); - args.put("day", param.getLeaveDay()); - Order leave = this.doCreateTask("leave", args); - param.setOrderId(leave.getId()); - extLeaveService.saveOrUpdate(param); - } else { - extLeaveService.saveOrUpdate(param); - } - return Response.ok(); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public Order doCreateTask(String processName, Map map) { - Map args = new HashMap(8); - args.putAll(map); - // 当前登录人 - args.put("step1", "sessionService.getCurrentUsername()"); - // 部门经理岗位的人 去用户表查询当前登录人同部门 and 岗位 = 部门经理 - args.put("step2", new String[]{"admin","wangwei"}); - // 总经理岗位的人 去用户表查询当前登录人同部门 and 岗位 = 总经理 -// args.put("step3", "admin"); - - args.put("process", "admin"); - //SysUser user = sysUserService.getById(sessionService.getCurrentUserId()); - args.put(SnakerEngine.ID, /*user.getRealName()*/ "admin" + "-" + DateUtil.now() + "的请假申请!!!"); - Order order = snakerEngineFacets.startAndExecute(processName, 0, "sessionService.getCurrentUsername()", args); - return order; - } - - @GetMapping("/{id}") - @ApiOperation(value = "根据id查询") - public Response get(@PathVariable Long id) { - return Response.ok(extLeaveService.getById(id)); - } - - @DeleteMapping("/{id}") - @ApiOperation(value = "根据id删除") - public Response delete(@PathVariable Long id) { - return Response.ok(extLeaveService.removeById(id)); - } - - @DeleteMapping("/batch/{ids}") - @ApiOperation(value = "根据批量删除ids删除") - public Response batchRemove(@PathVariable Long[] ids) { - return Response.ok(extLeaveService.removeByIds(CollUtil.toList(ids))); - } -} \ No newline at end of file diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/controller/ExtLogController.java b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/controller/ExtLogController.java deleted file mode 100644 index 899d218765..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/controller/ExtLogController.java +++ /dev/null @@ -1,85 +0,0 @@ -package io.github.wujun728.snakerflow.ext.controller; - -import java.util.List; - -import io.github.wujun728.snakerflow.ext.entity.ExtLog; -import io.github.wujun728.snakerflow.ext.service.IExtLogService; -import io.github.wujun728.snakerflow.module.PageResponse; -import io.github.wujun728.snakerflow.module.Response; -import io.github.wujun728.snakerflow.ext.mapper.ExtLogMapper; -import io.github.wujun728.snakerflow.ext.vo.LogStatisticsTop10Vo; -import io.github.wujun728.snakerflow.ext.vo.LogStatisticsVo; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; - -import cn.hutool.core.util.StrUtil; -import io.swagger.annotations.ApiOperation; - -/** - *

        - * 日志 前端控制器 - *

        - * - * - * @since 2021-08-16 - */ -@RestController -@RequestMapping("/ext/log") -//@Metrics -public class ExtLogController { - @Autowired - IExtLogService extLogService; - - @Autowired - ExtLogMapper extLogMapper; - -// @Autowired -// ISysUserService sysUserService; - - @GetMapping - @ApiOperation(value = "日志分页查询") - //@SaCheckPermission("log.list") - public PageResponse pageAll(@RequestParam(required = false, defaultValue = "1") long page, - @RequestParam(required = false, defaultValue = "10") long limit, - String keyWord) { - Page roadPage = new Page<>(page, limit); - LambdaQueryWrapper queryWrapper = new QueryWrapper().lambda(); - if (StrUtil.isNotBlank(keyWord)) { - queryWrapper.like(ExtLog::getRequest, keyWord); - } - queryWrapper.orderByDesc(ExtLog::getCreateTime); - Page pageList = extLogService.page(roadPage, queryWrapper); - List records = pageList.getRecords(); - records.forEach(extLog -> { - if (extLog.getUserId() != null) { -// 设置日志用户名称 -// SysUser sysUser = sysUserService.getById(extLog.getUserId()); -// extLog.setUser(sysUser); - } - - }); - return PageResponse.ok(records, pageList.getTotal()); - } - - - @GetMapping("/visits7day") - @ApiOperation(value = "7天访问量") - public Response visits7day() { - List logStatisticsVo = extLogMapper.selectStatistics7Day(); - return Response.ok(logStatisticsVo); - } - - @GetMapping("/visitsTop10IP") - @ApiOperation(value = "visitsTop10IP") - public PageResponse visitsTop10IP() { - List logStatisticsVo = extLogMapper.selectStatisticsVisitsTop10IP(); - return PageResponse.ok(logStatisticsVo, 10L); - } -} \ No newline at end of file diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/entity/ExtLeave.java b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/entity/ExtLeave.java deleted file mode 100644 index a082247feb..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/entity/ExtLeave.java +++ /dev/null @@ -1,71 +0,0 @@ -package io.github.wujun728.snakerflow.ext.entity; - -import java.io.Serializable; -import java.util.Date; - -import com.baomidou.mybatisplus.annotation.FieldFill; -import com.baomidou.mybatisplus.annotation.IdType; -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableId; -import com.fasterxml.jackson.annotation.JsonFormat; -import io.github.wujun728.snakerflow.process.BaseFlowStatus; -//import io.github.wujun728.system.entity.SysUser; - -import lombok.Data; -import lombok.EqualsAndHashCode; - -/** - *

        - * - *

        - * - * - * @since 2021-08-19 - */ -@Data -@EqualsAndHashCode(callSuper = false) -public class ExtLeave extends BaseFlowStatus implements Serializable { - - private static final long serialVersionUID = 1L; - - @TableId(value = "leave_id", type = IdType.AUTO) - private Long leaveId; - - /** - * 请假天数 - */ - private Integer leaveDay; - - /** - * 请假原因 - */ - private String leaveReason; - - /** - * 请假人id - */ - private String leaveUserId; - -// @TableField(exist = false) -// private SysUser createUser; - - /** - * 创建人 - */ - @TableField(value = "create_by" ,fill = FieldFill.INSERT) - private Long createBy; - - /** - * 创建人部门 - */ - @TableField(value = "create_dept_id" ,fill = FieldFill.INSERT) - private Long createDeptId; - - /** - * 创建时间 - */ -// @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") - @TableField(value = "create_time" ,fill = FieldFill.INSERT) - @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") - private Date createTime; -} diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/entity/ExtLog.java b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/entity/ExtLog.java deleted file mode 100644 index 018b96fcb5..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/entity/ExtLog.java +++ /dev/null @@ -1,80 +0,0 @@ -package io.github.wujun728.snakerflow.ext.entity; - -import java.io.Serializable; -import java.time.LocalDateTime; - -import com.baomidou.mybatisplus.annotation.IdType; -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableId; -import com.fasterxml.jackson.annotation.JsonFormat; -//import io.github.wujun728.system.entity.SysUser; - -import lombok.Data; -import lombok.EqualsAndHashCode; - -/** - *

        - * 日志 - *

        - * - * - * @since 2021-08-16 - */ -@Data -@EqualsAndHashCode(callSuper = false) -public class ExtLog implements Serializable { - - private static final long serialVersionUID = 1L; - - /** - * 主键 - */ - @TableId(value = "log_id", type = IdType.AUTO) - private Long logId; - - /** - * 用户id - */ - private Long userId; -// @TableField(exist = false) -// private SysUser user; - - /** - * ip地址 - */ - private String ip; - - private String city; - - /** - * 浏览器或者app信息 - */ - private String client; - private String uri; - private String method; - - /** - * 请求 - */ - private String request; - - /** - * 响应 - */ - private String response; - - private Boolean status; - - /** - * 耗时ms - */ - private Integer cost; - - /** - * 创建时间 - */ - @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") - private LocalDateTime createTime; - - -} diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/mapper/ExtLeaveMapper.java b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/mapper/ExtLeaveMapper.java deleted file mode 100644 index e01a47c846..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/mapper/ExtLeaveMapper.java +++ /dev/null @@ -1,16 +0,0 @@ -package io.github.wujun728.snakerflow.ext.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import io.github.wujun728.snakerflow.ext.entity.ExtLeave; - -/** - *

        - * Mapper 接口 - *

        - * - * - * @since 2021-08-19 - */ -public interface ExtLeaveMapper extends BaseMapper { - -} diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/mapper/ExtLogMapper.java b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/mapper/ExtLogMapper.java deleted file mode 100644 index c018bff566..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/mapper/ExtLogMapper.java +++ /dev/null @@ -1,55 +0,0 @@ -package io.github.wujun728.snakerflow.ext.mapper; - -import java.util.List; - -import io.github.wujun728.snakerflow.ext.entity.ExtLog; -import io.github.wujun728.snakerflow.ext.vo.LogStatisticsTop10Vo; -import io.github.wujun728.snakerflow.ext.vo.LogStatisticsVo; -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Select; -import org.apache.ibatis.annotations.Update; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; - -/** - *

        - * 日志 Mapper 接口 - *

        - * - * - * @since 2021-08-16 - */ -@Mapper -public interface ExtLogMapper extends BaseMapper { - - - @Select("select DATE_FORMAT(create_time,'%Y-%m-%d') date,count(*) value from ext_log where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= create_time group by date ORDER BY create_time ") - List selectStatistics7Day(); - - @Select("SELECT\n" + - "\tw.ip,\n" + - "\tcity,\n" + - "\tcount( * ) \n" + - "\tVALUE\t\n" + - "FROM\n" + - "\text_log w \n" + - "WHERE\n" + - "\tDATE_SUB( CURDATE( ), INTERVAL 1 day ) <= w.create_time \n" + - "GROUP BY\n" + - "\tw.ip \n" + - "ORDER BY\n" + - "\t\n" + - "VALUE\n" + - "DESC \n" + - "LIMIT 10") - List selectStatisticsVisitsTop10IP(); - - @Select("SELECT count(DISTINCT ip) from ext_log") - int selectDistinctIp(); - - @Update(" update ${tableName} set ${columnName} = #{columnValue} where id = #{id} ") - int updateRecordByColumnValue(@Param("tableName") String tableName, @Param("columnName") String columnName, - @Param("columnValue") String columnValue, @Param("id") String id); - -} diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/service/IExtLeaveService.java b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/service/IExtLeaveService.java deleted file mode 100644 index b825b2c892..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/service/IExtLeaveService.java +++ /dev/null @@ -1,16 +0,0 @@ -package io.github.wujun728.snakerflow.ext.service; - -import com.baomidou.mybatisplus.extension.service.IService; -import io.github.wujun728.snakerflow.ext.entity.ExtLeave; - -/** - *

        - * 服务类 - *

        - * - * - * @since 2021-08-19 - */ -public interface IExtLeaveService extends IService { - -} diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/service/IExtLogService.java b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/service/IExtLogService.java deleted file mode 100644 index 0203abec2e..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/service/IExtLogService.java +++ /dev/null @@ -1,16 +0,0 @@ -package io.github.wujun728.snakerflow.ext.service; - -import com.baomidou.mybatisplus.extension.service.IService; -import io.github.wujun728.snakerflow.ext.entity.ExtLog; - -/** - *

        - * 日志 服务类 - *

        - * - * - * @since 2021-08-16 - */ -public interface IExtLogService extends IService { - -} diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/service/impl/ExtLeaveServiceImpl.java b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/service/impl/ExtLeaveServiceImpl.java deleted file mode 100644 index e239da9e9b..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/service/impl/ExtLeaveServiceImpl.java +++ /dev/null @@ -1,21 +0,0 @@ -package io.github.wujun728.snakerflow.ext.service.impl; - -import io.github.wujun728.snakerflow.ext.entity.ExtLeave; -import io.github.wujun728.snakerflow.ext.mapper.ExtLeaveMapper; -import io.github.wujun728.snakerflow.ext.service.IExtLeaveService; -import org.springframework.stereotype.Service; - -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; - -/** - *

        - * 服务实现类 - *

        - * - * - * @since 2021-08-19 - */ -@Service -public class ExtLeaveServiceImpl extends ServiceImpl implements IExtLeaveService { - -} diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/service/impl/ExtLogServiceImpl.java b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/service/impl/ExtLogServiceImpl.java deleted file mode 100644 index 26e53335af..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/service/impl/ExtLogServiceImpl.java +++ /dev/null @@ -1,21 +0,0 @@ -package io.github.wujun728.snakerflow.ext.service.impl; - -import io.github.wujun728.snakerflow.ext.entity.ExtLog; -import io.github.wujun728.snakerflow.ext.mapper.ExtLogMapper; -import io.github.wujun728.snakerflow.ext.service.IExtLogService; -import org.springframework.stereotype.Service; - -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; - -/** - *

        - * 日志 服务实现类 - *

        - * - * - * @since 2021-08-16 - */ -@Service -public class ExtLogServiceImpl extends ServiceImpl implements IExtLogService { - -} diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/vo/LogStatisticsTop10Vo.java b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/vo/LogStatisticsTop10Vo.java deleted file mode 100644 index bb029633bd..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/vo/LogStatisticsTop10Vo.java +++ /dev/null @@ -1,11 +0,0 @@ -package io.github.wujun728.snakerflow.ext.vo; - -import lombok.Data; - -@Data -public class LogStatisticsTop10Vo { - - private String ip; - private String city; - private Integer value; -} diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/vo/LogStatisticsVo.java b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/vo/LogStatisticsVo.java deleted file mode 100644 index c867dde5e9..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/ext/vo/LogStatisticsVo.java +++ /dev/null @@ -1,10 +0,0 @@ -package io.github.wujun728.snakerflow.ext.vo; - -import lombok.Data; - -@Data -public class LogStatisticsVo { - - private String date; - private Integer value; -} diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/module/EasyCustomHandler.java b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/module/EasyCustomHandler.java deleted file mode 100644 index abb3d8d29e..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/module/EasyCustomHandler.java +++ /dev/null @@ -1,29 +0,0 @@ -package io.github.wujun728.snakerflow.module; - -import lombok.extern.slf4j.Slf4j; -import org.snaker.engine.core.Execution; -import org.snaker.engine.entity.Task; -import org.snaker.engine.handlers.IHandler; - -import java.util.List; -import java.util.Map; - -/** - * 自定义模型操作处理类,用于完成流程的全自动编排 - * https://yunmel.gitbooks.io/snakerflow/content/4xiang-xi-shuo-ming/418-zi-ding-yi-jie-dian.html - */ -@Slf4j -public class EasyCustomHandler implements IHandler { - @Override - public void handle(Execution execution) { - // 获取参数 - Map args = execution.getArgs(); - args.forEach((s, o) -> System.out.println(s + ":" + o)); - List tasks = execution.getTasks(); - tasks.forEach(task -> { - System.out.println(task.getTaskName()); - }); - - - } -} diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/module/EasyGlobalCreateTaskInterceptor.java b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/module/EasyGlobalCreateTaskInterceptor.java deleted file mode 100644 index 5a204a2154..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/module/EasyGlobalCreateTaskInterceptor.java +++ /dev/null @@ -1,37 +0,0 @@ - -package io.github.wujun728.snakerflow.module; - -import lombok.extern.slf4j.Slf4j; -import org.snaker.engine.SnakerInterceptor; -import org.snaker.engine.core.Execution; -import org.snaker.engine.entity.Task; -import org.springframework.stereotype.Component; - -/** - * Easy Admin 全局拦截器(只拦截创建任务) 可用于任务到达时的短信提醒 - * 无需其他配置 - */ -@Component -@Slf4j -public class EasyGlobalCreateTaskInterceptor implements SnakerInterceptor { - /** - * 拦截产生的任务对象,打印日志 - */ - @Override - public void intercept(Execution execution) { - for (Task task : execution.getTasks()) { - StringBuffer buffer = new StringBuffer(100); - buffer.append("创建任务[标识=").append(task.getId()); - buffer.append(",名称=").append(task.getDisplayName()); - buffer.append(",创建时间=").append(task.getCreateTime()); - buffer.append(",参与者={"); - if (task.getActorIds() != null) { - for (String actor : task.getActorIds()) { - buffer.append(actor).append(";"); - } - } - buffer.append("}]"); - log.info(buffer.toString()); - } - } -} diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/module/EasyPartEndProcessInterceptor.java b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/module/EasyPartEndProcessInterceptor.java deleted file mode 100644 index bb65b837cd..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/module/EasyPartEndProcessInterceptor.java +++ /dev/null @@ -1,37 +0,0 @@ - -package io.github.wujun728.snakerflow.module; - -import lombok.extern.slf4j.Slf4j; -import org.snaker.engine.SnakerInterceptor; -import org.snaker.engine.core.Execution; -import org.snaker.engine.entity.Task; - -/** - * Easy Admin 局部拦截器,这里需要配置在 xml中,postInterceptors = com.laker.admin.framework.ext.snakerflow.EasyPartEndProcessInterceptor - * 这里以流程结束拦截为例,例如配置 某些流程结束 短信通知报告发起人 - * 不需要注解了,反射实例化的 - */ -@Slf4j -public class EasyPartEndProcessInterceptor implements SnakerInterceptor { - /** - * 拦截产生的任务对象,打印日志 - */ - @Override - public void intercept(Execution execution) { - - for (Task task : execution.getTasks()) { - StringBuffer buffer = new StringBuffer(100); - buffer.append("创建任务[标识=").append(task.getId()); - buffer.append(",名称=").append(task.getDisplayName()); - buffer.append(",创建时间=").append(task.getCreateTime()); - buffer.append(",参与者={"); - if (task.getActorIds() != null) { - for (String actor : task.getActorIds()) { - buffer.append(actor).append(";"); - } - } - buffer.append("}]"); - log.info(buffer.toString()); - } - } -} diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/module/GeneralCompletion.java b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/module/GeneralCompletion.java deleted file mode 100644 index bc3613e157..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/module/GeneralCompletion.java +++ /dev/null @@ -1,28 +0,0 @@ -package io.github.wujun728.snakerflow.module; - -import lombok.extern.slf4j.Slf4j; -import org.snaker.engine.Completion; -import org.snaker.engine.entity.HistoryOrder; -import org.snaker.engine.entity.HistoryTask; -import org.springframework.stereotype.Component; - -/** - * 任务、实例完成时触发动作的接口 - */ -@Component -@Slf4j -public class GeneralCompletion implements Completion { - - @Override - public void complete(HistoryTask task) { - - log.info("The task[{}] has been user[{}] has completed", task, task.getOperator()); - } - - @Override - public void complete(HistoryOrder order) { - - - log.info("The order[{}] has completed", order); - } -} \ No newline at end of file diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/module/PageResponse.java b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/module/PageResponse.java deleted file mode 100644 index 1e7d0b2619..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/module/PageResponse.java +++ /dev/null @@ -1,31 +0,0 @@ -package io.github.wujun728.snakerflow.module; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * @author longli - */ -@ApiModel -public class PageResponse extends Response { - - @ApiModelProperty(notes = "数量") - private Long count; - - public PageResponse(String code, String msg, T data, Long count) { - super(code, msg, data); - this.count = count; - } - - public static PageResponse ok(T data, Long count) { - return new PageResponse<>("0", "", data, count); - } - - public Long getCount() { - return count; - } - - public void setCount(Long count) { - this.count = count; - } -} diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/module/Response.java b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/module/Response.java deleted file mode 100644 index 8da34d24ce..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/module/Response.java +++ /dev/null @@ -1,58 +0,0 @@ -package io.github.wujun728.snakerflow.module; - -import cn.hutool.core.util.StrUtil; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import org.slf4j.MDC; -import org.springframework.context.annotation.DependsOn; - -/** - * @author longli - */ -@Data -@AllArgsConstructor -@ApiModel -@DependsOn -public class Response { - @ApiModelProperty(notes = "响应码,非0 即为异常", example = "0") - private final String code; - @ApiModelProperty(notes = "响应消息", example = "提交成功") - private final String msg; - @ApiModelProperty(notes = "响应数据") - private final T data; - @ApiModelProperty(notes = "请求id") - private final String requestId; - - @ApiModelProperty(notes = "请求id") - private final Boolean success; - - public Response(String code, String msg, T data) { - this.code = code; - this.msg = msg; - this.data = data; - this.success = StrUtil.equals("0", code); - this.requestId = MDC.get("requestId"); - } - - public static Response ok(T data) { - return new Response<>("0", "操作成功", data); - } - - public static Response ok() { - return new Response("0", "操作成功", null); - } - - public static Response error(T data) { - return new Response<>("400", "", data); - } - - public static Response error(String code, String msg, T data) { - return new Response<>(code, msg, data); - } - - public static Response error(String code, String msg) { - return new Response<>(code, msg, null); - } -} diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/process/BaseFlowController.java b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/process/BaseFlowController.java deleted file mode 100644 index fa534fa2dd..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/process/BaseFlowController.java +++ /dev/null @@ -1,113 +0,0 @@ -package io.github.wujun728.snakerflow.process; - -import java.util.Arrays; -import java.util.List; - -import org.snaker.engine.access.QueryFilter; -import org.snaker.engine.entity.HistoryOrder; -import org.snaker.engine.entity.WorkItem; -import org.springframework.beans.factory.annotation.Autowired; - -//import io.github.wujun728.module.ext.mapper.BizCommonMapper; -import io.github.wujun728.common.base.BaseFlowEntity; -//import io.github.wujun728.system.mapper.SysUserMapper; -//import io.github.wujun728.system.service.HttpSessionService; - -//import cn.dev33.satoken.stp.StpUtil; -import cn.hutool.core.collection.CollUtil; -import cn.hutool.core.util.ArrayUtil; -import cn.hutool.core.util.StrUtil; - -public class BaseFlowController { -// @Resource -// HttpSessionService sessionService; - @Autowired - private SnakerEngineFacets snakerEngineFacets; -// @Autowired -// private UserService sysUserService; -// @Autowired -// private SysUserMapper sysuer; - -// @Autowired -// private BizCommonMapper bizCommonMapper; - - protected void setFlowStatusInfo(BaseFlowStatus baseFlowStatus) { - String orderId = baseFlowStatus.getOrderId(); - // 流程实例状态 - HistoryOrder histOrder = snakerEngineFacets.getEngine().query().getHistOrder(orderId); - if(histOrder!=null) { - baseFlowStatus.setOrderState(histOrder.getOrderState()); - } - List workItems = snakerEngineFacets.getEngine().query().getWorkItems(null, new QueryFilter().setOrderId(orderId)); - if (CollUtil.isNotEmpty(workItems)) { - WorkItem workItem = workItems.get(0); - // 当前流程实例任务节点名称 - baseFlowStatus.setTaskName(workItem.getTaskName()); -// List historyTasks = snakerEngineFacets.getEngine().query().getHistoryTasks(new QueryFilter() -// .setOrderId(orderId) -// .setOperator(sessionService.getCurrentUsername()) -// .orderBy("create_time") -// .order(QueryFilter.DESC)); -// if (CollUtil.isNotEmpty(historyTasks)) { -// baseFlowStatus.setCreateTaskId(historyTasks.get(0).getId()); -// } - // 当前流程实例任务操作人 - String[] actors = snakerEngineFacets.getEngine().query().getTaskActorsByTaskId(workItem.getTaskId()); - if (ArrayUtil.isNotEmpty(actors)) { -// List res = new ArrayList<>(); -// for (String actor : actors) { -// //SysUser user = sysUserService.getById(Long.valueOf(actor)); -// SysUser user = sysuer.getUserByName(actor); -// if (user != null) { -// res.add(user.getRealName()); -// } -// } - String taskOperatorName = StrUtil.join(",", Arrays.asList(actors)); - baseFlowStatus.setTaskOperatorName(taskOperatorName); - if(taskOperatorName.contains("sessionService.getCurrentUserRealname())")) { - baseFlowStatus.setIsOwner(1); - } - } - } - } - - protected void setFlowStatusInfo(BaseFlowEntity baseFlowEntity) { - String orderId = baseFlowEntity.getOrderId(); - // 流程实例状态 - HistoryOrder histOrder = snakerEngineFacets.getEngine().query().getHistOrder(orderId); - if(histOrder!=null) { - baseFlowEntity.setOrderState(histOrder.getOrderState()); - } - List workItems = snakerEngineFacets.getEngine().query().getWorkItems(null, new QueryFilter().setOrderId(orderId)); - if (CollUtil.isNotEmpty(workItems)) { - WorkItem workItem = workItems.get(0); - // 当前流程实例任务节点名称 - baseFlowEntity.setTaskName(workItem.getTaskName()); -// List historyTasks = snakerEngineFacets.getEngine().query().getHistoryTasks(new QueryFilter() -// .setOrderId(orderId) -// .setOperator(sessionService.getCurrentUsername()) -// .orderBy("create_time") -// .order(QueryFilter.DESC)); -// if (CollUtil.isNotEmpty(historyTasks)) { -// baseFlowEntity.setCreateTaskId(historyTasks.get(0).getId()); -// } - // 当前流程实例任务操作人 - String[] actors = snakerEngineFacets.getEngine().query().getTaskActorsByTaskId(workItem.getTaskId()); - if (ArrayUtil.isNotEmpty(actors)) { -// List res = new ArrayList<>(); -// for (String actor : actors) { -// //SysUser user = sysUserService.getById(Long.valueOf(actor)); -// SysUser user = sysuer.getUserByName(actor); -// if (user != null) { -// res.add(user.getRealName()); -// } -// } - String taskOperatorName = StrUtil.join(",", Arrays.asList(actors)); - baseFlowEntity.setTaskOperatorName(taskOperatorName); - if(taskOperatorName.contains("sessionService.getCurrentUserRealname()")) { // 这个可能有问题,必须要是自己创建的数据 -// baseFlowEntity.setIsOwner(1); - } - } - } - } -} diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/process/BaseFlowStatus.java b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/process/BaseFlowStatus.java deleted file mode 100644 index 7316f0f916..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/process/BaseFlowStatus.java +++ /dev/null @@ -1,50 +0,0 @@ -package io.github.wujun728.snakerflow.process; - -import com.baomidou.mybatisplus.annotation.TableField; -import lombok.Data; - -/** - * - */ -@Data -public class BaseFlowStatus { - /** - * 当前流程实例id - */ - private String orderId; - /** - * 当前流程所处任务节点名称 - */ - @TableField(exist = false) - private String taskName; - - /** - * 第一个任务id,用于撤回流程 - */ - @TableField(exist = false) - private String createTaskId; - /** - * 当前流程所处任务操作人名称 - */ - @TableField(exist = false) - private String taskOperatorName; - /** - * 当前流程所处任务操作人 - */ - @TableField(exist = false) - private String taskOperatorId; - /** - * 流程实例状态(0:结束;1:活动) --工作流逻辑状态,这个是实时到工作流里面去查询的 - */ - @TableField(exist = false) - private Integer orderState; - - /** - * 流程实例状态(0:结束;1:活动) --数据库里面的流程状态,主要是标记已完成的工作流 - */ - @TableField(value = "order_status") - private Integer orderStatus; - - @TableField(exist = false) - private Integer isOwner; -} diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/process/SnakerEngineFacets.java b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/process/SnakerEngineFacets.java deleted file mode 100644 index 8458127060..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/process/SnakerEngineFacets.java +++ /dev/null @@ -1,224 +0,0 @@ -package io.github.wujun728.snakerflow.process; - -import org.snaker.engine.SnakerEngine; -import org.snaker.engine.access.QueryFilter; -import org.snaker.engine.entity.Order; -import org.snaker.engine.entity.Process; -import org.snaker.engine.entity.Task; -import org.snaker.engine.model.TaskModel; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * SnakerEngineFacets封装snakerflow基本操作,可以直接使用 - * - * @author zhaoguoqing - * @since 0.1 - */ -@Component -public class SnakerEngineFacets { - @Autowired - private SnakerEngine engine; - - /** - * 初始化状态机流程 - * - * @return 流程主键 - */ - public String initFlows() { - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - InputStream stream = classLoader.getResourceAsStream("flows/leave.snaker"); - String deploy = engine.process().deploy(stream); - return deploy; - } - - /** - * 初始化状态机流程 - * - * @return 流程主键 - */ - public String initFlowsByName(String filename) { - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - InputStream stream = classLoader.getResourceAsStream("flows/"+filename); - String deploy = engine.process().deploy(stream); - return deploy; - } - - /** - * 获得所有有效流程 - * - * @return List - */ - public List getAllProcess() { - QueryFilter filter = new QueryFilter(); - return engine.process().getProcesss(filter); - } - - /** - * 通过orderId 获得流程 - * - * @param orderId 流程实例Id - * @return List - */ - public List getProcessByOrderId(String orderId) { - QueryFilter filter = new QueryFilter(); - filter.setOrderId(orderId); - return engine.process().getProcesss(filter); - } - - /** - * 获得执行引擎 - * - * @return SnakerEngine - */ - public SnakerEngine getEngine() { - return engine; - } - - /** - * 获得所有流程的名字 - * - * @return List - */ - public List getAllProcessNames() { - List list = engine.process().getProcesss(new QueryFilter()); - List names = new ArrayList<>(); - for (Process entity : list) { - if (names.contains(entity.getName())) { - continue; - } else { - names.add(entity.getName()); - } - } - return names; - } - - /** - * 通过processId发起一个流程实例 - * - * @param processId 流程ID - * @param operator 操作人 - * @param args 自定义参数 - * @return Order流程实例 - */ - public Order startInstanceById(String processId, String operator, Map args) { - return engine.startInstanceById(processId, operator, args); - } - - /** - * 通过process name发起一个流程实例 - * - * @param name 流程 name - * @param operator 操作人 - * @param args 自定义参数 - * @return Order流程实例 - */ - public Order startInstanceByName(String name, Integer version, String operator, Map args) { - return engine.startInstanceByName(name, version, operator, args); - } - - /** - * 执行流程实例 - * - * @param name 流程 name - * @param version 版本 - * @param operator 操作人 - * @param args 自定义参数 - * @return Order流程实例 - */ - public Order startAndExecute(String name, Integer version, String operator, Map args) { - Order order = engine.startInstanceByName(name, version, operator, args); - List tasks = engine.query().getActiveTasks(new QueryFilter().setOrderId(order.getId())); - List newTasks = new ArrayList(); - if (tasks != null && tasks.size() > 0) { - Task task = tasks.get(0); - newTasks.addAll(engine.executeTask(task.getId(), operator, args)); - } - return order; - } - - /** - * 执行流程实例 - * - * @param processId 流程Id - * @param operator 操作人 - * @param args 自定义参数 - * @return Order流程实例 - */ - public Order startAndExecute(String processId, String operator, Map args) { - Order order = engine.startInstanceById(processId, operator, args); - List tasks = engine.query().getActiveTasks(new QueryFilter().setOrderId(order.getId())); - List newTasks = new ArrayList(); - if (tasks != null && tasks.size() > 0) { - Task task = tasks.get(0); - newTasks.addAll(engine.executeTask(task.getId(), operator, args)); - } - return order; - } - - /** - * 通过taskId执行 - * - * @param taskId 任务Id - * @param operator 操作人 - * @param args 自定义参数 - * @return List - */ - public List execute(String taskId, String operator, Map args) { - return engine.executeTask(taskId, operator, args); - } - - /** - * 流程跳转 - * - * @param taskId 任务Id - * @param operator 操作人 - * @param args 自定义参数 - * @param nodeName 跳转到的节点名称 - * @return List - */ - public List executeAndJump(String taskId, String operator, Map args, String nodeName) { - return engine.executeAndJumpTask(taskId, operator, args, nodeName); - } - - /** - * 通过orderId获取对应的流程task - * - * @param orderId 流程实例Id - * @return List - */ - public List getTasks(String orderId) { - return engine.query().getActiveTasks(new QueryFilter().setOrderId(orderId)); - } - - /** - * 转办 主办 - * @param taskId - * @param operator - * @param actors - * @return - */ - public List transferMajor(String taskId, String operator, String... actors) { - List tasks = engine.task().createNewTask(taskId, TaskModel.TaskType.Major.ordinal(), actors); - engine.task().complete(taskId, operator); - return tasks; - } - - /** - * 转办 协办 - * @param taskId - * @param operator - * @param actors - * @return - */ - public List transferAidant(String taskId, String operator, String... actors) { - List tasks = engine.task().createNewTask(taskId, TaskModel.TaskType.Aidant.ordinal(), actors); - engine.task().complete(taskId, operator); - return tasks; - } -} \ No newline at end of file diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/process/SnakerHelper.java b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/process/SnakerHelper.java deleted file mode 100644 index 8ea5e4e377..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/process/SnakerHelper.java +++ /dev/null @@ -1,269 +0,0 @@ -/* - * Copyright 2014-2015 snakerflow.com - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * - */ -package io.github.wujun728.snakerflow.process; - -import org.apache.commons.beanutils.BeanUtils; -import org.apache.commons.beanutils.PropertyUtils; -import org.apache.commons.lang.StringUtils; -import org.snaker.engine.entity.HistoryTask; -import org.snaker.engine.entity.Task; -import org.snaker.engine.model.*; - -import java.beans.PropertyDescriptor; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Snaker的帮助类 - * - * @author yuqs - * @since 0.1 - */ -public class SnakerHelper { - private static Map, String> mapper = new HashMap, String>(); - - static { - mapper.put(TaskModel.class, "task"); - mapper.put(CustomModel.class, "custom"); - mapper.put(DecisionModel.class, "decision"); - mapper.put(EndModel.class, "end"); - mapper.put(ForkModel.class, "fork"); - mapper.put(JoinModel.class, "join"); - mapper.put(StartModel.class, "start"); - mapper.put(SubProcessModel.class, "subprocess"); - } - - public static String getStateJson(ProcessModel model, List activeTasks, List historyTasks) { - StringBuffer buffer = new StringBuffer(); - buffer.append("{'activeRects':{'rects':["); - if (activeTasks != null && activeTasks.size() > 0) { - for (Task task : activeTasks) { - buffer.append("{'paths':[],'name':'"); - buffer.append(task.getTaskName()); - buffer.append("'},"); - } - buffer.deleteCharAt(buffer.length() - 1); - } - buffer.append("]}, 'historyRects':{'rects':["); - if (historyTasks != null && historyTasks.size() > 0) { - for (HistoryTask historyTask : historyTasks) { - NodeModel parentModel = model.getNode(historyTask.getTaskName()); - if (parentModel == null) continue; - buffer.append("{'name':'").append(parentModel.getName()).append("','paths':["); - buffer.append("]},"); - } - buffer.deleteCharAt(buffer.length() - 1); - } - buffer.append("]}}"); - return buffer.toString(); - } - - public static String getModelJson(ProcessModel model) { - StringBuffer buffer = new StringBuffer(); - List tms = new ArrayList(); - for (NodeModel node : model.getNodes()) { - for (TransitionModel tm : node.getOutputs()) { - tms.add(tm); - } - } - buffer.append("{"); - buffer.append(getNodeJson(model.getNodes())); - buffer.append(getPathJson(tms)); - buffer.append("props:{props:{name:{name:'name',value:'"); - buffer.append(convert(model.getName())); - buffer.append("'},displayName:{name:'displayName',value:'"); - buffer.append(convert(model.getDisplayName())); - buffer.append("'},expireTime:{name:'expireTime',value:'"); - buffer.append(convert(model.getExpireTime())); - buffer.append("'},instanceUrl:{name:'instanceUrl',value:'"); - buffer.append(convert(model.getInstanceUrl())); - buffer.append("'},instanceNoClass:{name:'instanceNoClass',value:'"); - buffer.append(convert(model.getInstanceNoClass())); - buffer.append("'}}}}"); - return buffer.toString(); - } - - public static String getNodeJson(List nodes) { - StringBuffer buffer = new StringBuffer(); - buffer.append("states: {"); - for (NodeModel node : nodes) { - buffer.append(node.getName()); - buffer.append(getBase(node)); - buffer.append(getLayout(node)); - buffer.append(getProperty(node)); - buffer.append(","); - } - buffer.deleteCharAt(buffer.length() - 1); - buffer.append("},"); - return buffer.toString(); - } - - public static String getPathJson(List tms) { - StringBuffer buffer = new StringBuffer(); - buffer.append("paths:{"); - for (TransitionModel tm : tms) { - buffer.append(tm.getName()); - buffer.append(":{from:'"); - buffer.append(tm.getSource().getName()); - buffer.append("',to:'"); - buffer.append(tm.getTarget().getName()); - buffer.append("', dots:["); - if (StringUtils.isNotEmpty(tm.getG())) { - String[] bendpoints = tm.getG().split(";"); - for (String bendpoint : bendpoints) { - buffer.append("{"); - String[] xy = bendpoint.split(","); - buffer.append("x:").append(getNumber(xy[0])); - buffer.append(",y:").append(xy[1]); - buffer.append("},"); - } - buffer.deleteCharAt(buffer.length() - 1); - } - buffer.append("],text:{text:'"); - buffer.append(tm.getDisplayName()); - buffer.append("'},textPos:{"); - if (StringUtils.isNotEmpty(tm.getOffset())) { - String[] values = tm.getOffset().split(","); - buffer.append("x:").append(values[0]).append(","); - buffer.append("y:").append(values[1]).append(""); - } - buffer.append("}, props:{name:{value:'" + tm.getName() + "'},expr:{value:'" + tm.getExpr() + "'}}}"); - buffer.append(","); - } - buffer.deleteCharAt(buffer.length() - 1); - buffer.append("},"); - return buffer.toString(); - } - - private static String getBase(NodeModel node) { - StringBuffer buffer = new StringBuffer(); - buffer.append(":{type:'"); - buffer.append(mapper.get(node.getClass())); - buffer.append("',text:{text:'"); - buffer.append(node.getDisplayName()); - buffer.append("'},"); - return buffer.toString(); - } - - private static String getProperty(NodeModel node) { - StringBuffer buffer = new StringBuffer(); - buffer.append("props:{"); - try { - PropertyDescriptor[] beanProperties = PropertyUtils.getPropertyDescriptors(node); - for (PropertyDescriptor propertyDescriptor : beanProperties) { - if (propertyDescriptor.getReadMethod() == null || propertyDescriptor.getWriteMethod() == null) - continue; - String name = propertyDescriptor.getName(); - String value = ""; - if (propertyDescriptor.getPropertyType() == String.class) { - value = (String) BeanUtils.getProperty(node, name); - } else { - continue; - } - if (value == null || value.equals("")) continue; - buffer.append(name); - buffer.append(":{value:'"); - buffer.append(convert(value)); - buffer.append("'},"); - } - } catch (Exception e) { - e.printStackTrace(); - } - buffer.deleteCharAt(buffer.length() - 1); - buffer.append("}}"); - return buffer.toString(); - } - - private static String getLayout(NodeModel node) { - StringBuffer buffer = new StringBuffer(); - buffer.append("attr:{"); - String[] values = node.getLayout().split(","); - buffer.append("x:").append(getNumber(values[0])).append(","); - buffer.append("y:").append(values[1]).append(","); - if ("-1".equals(values[2])) { - if (node instanceof TaskModel || node instanceof CustomModel || node instanceof SubProcessModel) { - values[2] = "100"; - } else { - values[2] = "50"; - } - } - if ("-1".equals(values[3])) { - values[3] = "50"; - } - buffer.append("width:").append(values[2]).append(","); - buffer.append("height:").append(values[3]); - buffer.append("},"); - return buffer.toString(); - } - - private static String convert(String value) { - if (StringUtils.isEmpty(value)) - return ""; - if (value.indexOf("'") != -1) { - value = value.replaceAll("'", "#1"); - } - if (value.indexOf("\"") != -1) { - value = value.replaceAll("\"", "#2"); - } - if (value.indexOf("\r\n") != -1) { - value = value.replaceAll("\r\n", "#3"); - } - if (value.indexOf("\n") != -1) { - value = value.replaceAll("\n", "#4"); - } - if (value.indexOf(">") != -1) { - value = value.replaceAll(">", "#5"); - } - if (value.indexOf("<") != -1) { - value = value.replaceAll("<", "#6"); - } - if (value.indexOf("&") != -1) { - value = value.replaceAll("&", "#7"); - } - return value; - } - - public static String convertXml(String value) { - if (value.indexOf("#1") != -1) { - value = value.replaceAll("#1", "'"); - } - if (value.indexOf("#2") != -1) { - value = value.replaceAll("#2", "\""); - } - if (value.indexOf("#5") != -1) { - value = value.replaceAll("#5", ">"); - } - if (value.indexOf("#6") != -1) { - value = value.replaceAll("#6", "<"); - } - if (value.indexOf("&") != -1) { - value = value.replaceAll("#7", "&"); - } - return value; - } - - private static int getNumber(String value) { - if (value == null) return 0; - try { - return Integer.parseInt(value) + 180; - } catch (Exception e) { - return 0; - } - } -} diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/process/SnakerflowTestService.java b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/process/SnakerflowTestService.java deleted file mode 100644 index 9e7e4e1b19..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/java/io/github/wujun728/snakerflow/process/SnakerflowTestService.java +++ /dev/null @@ -1,52 +0,0 @@ -package io.github.wujun728.snakerflow.process; - -import java.util.List; - -import org.snaker.engine.entity.Order; -import org.snaker.engine.entity.Process; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import cn.hutool.core.collection.CollUtil; -import cn.hutool.json.JSONUtil; - -/** - * description: SnakerflowTestService - * - * @author guoqing.zhao - * Date: 2020-03-23 9:20 下午 - */ -@Service -public class SnakerflowTestService { - @Autowired - private SnakerEngineFacets snakerEngineFacets; - - - /** - * 主要用于测试snakerflow是否正常加载 - * - * @return String - */ - @Transactional - public String getProcess() { - snakerEngineFacets.initFlows(); - List allProcess = snakerEngineFacets.getAllProcess(); - return JSONUtil.toJsonStr(allProcess); - } - - /** - * 主要用于测试snakerflow是否正常加载 - * - * @return String - */ - @Transactional - public String start() { - List allProcess = snakerEngineFacets.getAllProcess(); - if (CollUtil.isEmpty(allProcess)) { - return "请先初始化process,http://localhost:8080/getProcessList"; - } - Order order = snakerEngineFacets.startInstanceById(allProcess.get(0).getId(), "zhaoguoqing", null); - return JSONUtil.toJsonStr(order); - } -} \ No newline at end of file diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/META-INF/spring.factories.bk b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/META-INF/spring.factories.bk deleted file mode 100644 index 115d6a3831..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/META-INF/spring.factories.bk +++ /dev/null @@ -1,2 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -io.github.wujun728.snakerflow.config.SankerflowAutoConfig \ No newline at end of file diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/assessment.snaker b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/assessment.snaker deleted file mode 100644 index fb90a22e7d..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/assessment.snaker +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/becomemember.snaker b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/becomemember.snaker deleted file mode 100644 index a9ad7ed0a7..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/becomemember.snaker +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/borrow.snaker b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/borrow.snaker deleted file mode 100644 index 37c489b2d1..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/borrow.snaker +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/contract.snaker b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/contract.snaker deleted file mode 100644 index 973bb54366..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/contract.snaker +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/customer.snaker b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/customer.snaker deleted file mode 100644 index 9748ee586f..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/customer.snaker +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/daily.snaker b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/daily.snaker deleted file mode 100644 index 1cb0fbeba8..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/daily.snaker +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/daily_old.snaker b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/daily_old.snaker deleted file mode 100644 index b34944b8e5..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/daily_old.snaker +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/dimission.snaker b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/dimission.snaker deleted file mode 100644 index afc059a500..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/dimission.snaker +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/draft.snaker b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/draft.snaker deleted file mode 100644 index 5aaae99512..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/draft.snaker +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/draft2.snaker b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/draft2.snaker deleted file mode 100644 index 41e6db1549..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/draft2.snaker +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/entryJob.snaker b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/entryJob.snaker deleted file mode 100644 index 9f0ca0c524..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/entryJob.snaker +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/examination.snaker b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/examination.snaker deleted file mode 100644 index 3c804ff50d..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/examination.snaker +++ /dev/null @@ -1,72 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/expense.snaker b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/expense.snaker deleted file mode 100644 index 8326493d12..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/expense.snaker +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/hire.snaker b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/hire.snaker deleted file mode 100644 index 8ef5356f76..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/hire.snaker +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/invoice.snaker b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/invoice.snaker deleted file mode 100644 index 46dca29b3b..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/invoice.snaker +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/leave.snaker b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/leave.snaker deleted file mode 100644 index 6028559717..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/leave.snaker +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/leaveNew.snaker b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/leaveNew.snaker deleted file mode 100644 index e9e7446cd9..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/leaveNew.snaker +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/member.snaker b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/member.snaker deleted file mode 100644 index 07f3257223..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/member.snaker +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/money.snaker b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/money.snaker deleted file mode 100644 index ced4dabaa7..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/money.snaker +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/office.snaker b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/office.snaker deleted file mode 100644 index ec7f2c1551..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/office.snaker +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/office2.snaker b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/office2.snaker deleted file mode 100644 index 635fbc2dbf..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/office2.snaker +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/outsite.snaker b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/outsite.snaker deleted file mode 100644 index d18723deaf..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/outsite.snaker +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/plan.snaker b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/plan.snaker deleted file mode 100644 index 040be8b0b8..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/plan.snaker +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/project.snaker b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/project.snaker deleted file mode 100644 index b96dca2e40..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/project.snaker +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/projectCheck.snaker b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/projectCheck.snaker deleted file mode 100644 index 35c6df0d40..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/projectCheck.snaker +++ /dev/null @@ -1,72 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/project_old.snaker b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/project_old.snaker deleted file mode 100644 index dfcb8d2d06..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/project_old.snaker +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/recheck.snaker b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/recheck.snaker deleted file mode 100644 index 2b28944f8b..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/recheck.snaker +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/weekly.snaker b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/weekly.snaker deleted file mode 100644 index d20a7d57db..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/flows/weekly.snaker +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/templates/biztest/list.html b/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/templates/biztest/list.html deleted file mode 100644 index 8339baa845..0000000000 --- a/jun_springboot_starter/jun-snakerflow-spring-boot-starter/src/main/resources/templates/biztest/list.html +++ /dev/null @@ -1,300 +0,0 @@ - - - - - Title - - - - - - -
        -
        -
        -
        - -
        - -
        - - -
        -
        - -
        -
        -
        - - - - - - - - \ No newline at end of file diff --git a/jun_springboot_starter/jun-swagger2-spring-boot-starter/pom.xml b/jun_springboot_starter/jun-swagger2-spring-boot-starter/pom.xml deleted file mode 100644 index 7adf6f3067..0000000000 --- a/jun_springboot_starter/jun-swagger2-spring-boot-starter/pom.xml +++ /dev/null @@ -1,73 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun-swagger2-spring-boot-starter - 1.0.25 - jar - swagger通用组件 - - - 1.8 - UTF-8 - 1.8 - 1.8 - 1.0.25 - 2.5.14 - 2020.0.6 - 2.0.5 - 1.18.20 - 2.3.2 - - - - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - - - - org.springframework.boot - spring-boot-starter - - - com.github.xiaoymin - knife4j-micro-spring-boot-starter - ${knife4j.version} - - - org.springframework.boot - spring-boot-configuration-processor - true - - - - net.dreamlu - mica-auto - ${mica-auto.version} - - - org.projectlombok - lombok - ${lombok.version} - - - diff --git a/jun_springboot_starter/jun-swagger2-spring-boot-starter/src/main/java/io/github/wujun728/common/swagger2/SwaggerAutoConfiguration.java b/jun_springboot_starter/jun-swagger2-spring-boot-starter/src/main/java/io/github/wujun728/common/swagger2/SwaggerAutoConfiguration.java deleted file mode 100644 index 834bf9ee5a..0000000000 --- a/jun_springboot_starter/jun-swagger2-spring-boot-starter/src/main/java/io/github/wujun728/common/swagger2/SwaggerAutoConfiguration.java +++ /dev/null @@ -1,266 +0,0 @@ -package io.github.wujun728.common.swagger2; - -import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j; -import com.google.common.base.Predicate; -import com.google.common.base.Predicates; -import com.google.common.collect.Lists; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.BeanFactoryAware; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration; -import springfox.documentation.builders.ApiInfoBuilder; -import springfox.documentation.builders.ParameterBuilder; -import springfox.documentation.builders.PathSelectors; -import springfox.documentation.builders.RequestHandlerSelectors; -import springfox.documentation.schema.ModelRef; -import springfox.documentation.service.ApiInfo; -import springfox.documentation.service.ApiKey; -import springfox.documentation.service.AuthorizationScope; -import springfox.documentation.service.Contact; -import springfox.documentation.service.Parameter; -import springfox.documentation.service.SecurityReference; -import springfox.documentation.spi.DocumentationType; -import springfox.documentation.spi.service.contexts.SecurityContext; -import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger2.annotations.EnableSwagger2; - -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import java.util.Objects; -import java.util.Set; -import java.util.stream.Collectors; - -/** - */ -@Configuration -@EnableSwagger2 -@EnableKnife4j -@Import(BeanValidatorPluginsConfiguration.class) -public class SwaggerAutoConfiguration implements BeanFactoryAware { - private static final String AUTH_KEY = "Authorization"; - - private BeanFactory beanFactory; - - @Bean - @ConditionalOnMissingBean - public SwaggerProperties swaggerProperties() { - return new SwaggerProperties(); - } - - @Bean - @ConditionalOnMissingBean - @ConditionalOnProperty(name = "jun.swagger.enabled", matchIfMissing = true) - public List createRestApi(SwaggerProperties swaggerProperties) { - ConfigurableBeanFactory configurableBeanFactory = (ConfigurableBeanFactory) beanFactory; - List docketList = new LinkedList<>(); - - // 没有分组 - if (swaggerProperties.getDocket().size() == 0) { - final Docket docket = createDocket(swaggerProperties); - configurableBeanFactory.registerSingleton("defaultDocket", docket); - docketList.add(docket); - return docketList; - } - - // 分组创建 - for (String groupName : swaggerProperties.getDocket().keySet()) { - SwaggerProperties.DocketInfo docketInfo = swaggerProperties.getDocket().get(groupName); - - ApiInfo apiInfo = new ApiInfoBuilder() - .title(docketInfo.getTitle().isEmpty() ? swaggerProperties.getTitle() : docketInfo.getTitle()) - .description(docketInfo.getDescription().isEmpty() ? swaggerProperties.getDescription() : docketInfo.getDescription()) - .version(docketInfo.getVersion().isEmpty() ? swaggerProperties.getVersion() : docketInfo.getVersion()) - .license(docketInfo.getLicense().isEmpty() ? swaggerProperties.getLicense() : docketInfo.getLicense()) - .licenseUrl(docketInfo.getLicenseUrl().isEmpty() ? swaggerProperties.getLicenseUrl() : docketInfo.getLicenseUrl()) - .contact( - new Contact( - docketInfo.getContact().getName().isEmpty() ? swaggerProperties.getContact().getName() : docketInfo.getContact().getName(), - docketInfo.getContact().getUrl().isEmpty() ? swaggerProperties.getContact().getUrl() : docketInfo.getContact().getUrl(), - docketInfo.getContact().getEmail().isEmpty() ? swaggerProperties.getContact().getEmail() : docketInfo.getContact().getEmail() - ) - ) - .termsOfServiceUrl(docketInfo.getTermsOfServiceUrl().isEmpty() ? swaggerProperties.getTermsOfServiceUrl() : docketInfo.getTermsOfServiceUrl()) - .build(); - - // base-path处理 - // 当没有配置任何path的时候,解析/** - if (docketInfo.getBasePath().isEmpty()) { - docketInfo.getBasePath().add("/**"); - } - List> basePath = new ArrayList<>(docketInfo.getBasePath().size()); - for (String path : docketInfo.getBasePath()) { - basePath.add(PathSelectors.ant(path)); - } - - // exclude-path处理 - List> excludePath = new ArrayList<>(docketInfo.getExcludePath().size()); - for (String path : docketInfo.getExcludePath()) { - excludePath.add(PathSelectors.ant(path)); - } - - Docket docket = new Docket(DocumentationType.SWAGGER_2) - .host(swaggerProperties.getHost()) - .apiInfo(apiInfo) - .globalOperationParameters(assemblyGlobalOperationParameters(swaggerProperties.getGlobalOperationParameters(), - docketInfo.getGlobalOperationParameters())) - .groupName(groupName) - .select() - .apis(RequestHandlerSelectors.basePackage(docketInfo.getBasePackage())) - .paths( - Predicates.and( - Predicates.not(Predicates.or(excludePath)), - Predicates.or(basePath) - ) - ) - .build() - .securitySchemes(securitySchemes()) - .securityContexts(securityContexts()); - - configurableBeanFactory.registerSingleton(groupName, docket); - docketList.add(docket); - } - return docketList; - } - - /** - * 创建 Docket对象 - * - * @param swaggerProperties swagger配置 - * @return Docket - */ - private Docket createDocket(final SwaggerProperties swaggerProperties) { - ApiInfo apiInfo = new ApiInfoBuilder() - .title(swaggerProperties.getTitle()) - .description(swaggerProperties.getDescription()) - .version(swaggerProperties.getVersion()) - .license(swaggerProperties.getLicense()) - .licenseUrl(swaggerProperties.getLicenseUrl()) - .contact(new Contact(swaggerProperties.getContact().getName(), - swaggerProperties.getContact().getUrl(), - swaggerProperties.getContact().getEmail())) - .termsOfServiceUrl(swaggerProperties.getTermsOfServiceUrl()) - .build(); - - // base-path处理 - // 当没有配置任何path的时候,解析/** - if (swaggerProperties.getBasePath().isEmpty()) { - swaggerProperties.getBasePath().add("/**"); - } - List> basePath = new ArrayList<>(); - for (String path : swaggerProperties.getBasePath()) { - basePath.add(PathSelectors.ant(path)); - } - - // exclude-path处理 - List> excludePath = new ArrayList<>(); - for (String path : swaggerProperties.getExcludePath()) { - excludePath.add(PathSelectors.ant(path)); - } - - return new Docket(DocumentationType.SWAGGER_2) - .host(swaggerProperties.getHost()) - .apiInfo(apiInfo) - .globalOperationParameters(buildGlobalOperationParametersFromSwaggerProperties( - swaggerProperties.getGlobalOperationParameters())) - .select() - .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage())) - .paths( - Predicates.and( - Predicates.not(Predicates.or(excludePath)), - Predicates.or(basePath) - ) - ) - .build() - .securitySchemes(securitySchemes()) - .securityContexts(securityContexts()); - } - - @Override - public void setBeanFactory(BeanFactory beanFactory) { - this.beanFactory = beanFactory; - } - - private List securityContexts() { - List contexts = new ArrayList<>(1); - SecurityContext securityContext = SecurityContext.builder() - .securityReferences(defaultAuth()) - //.forPaths(PathSelectors.regex("^(?!auth).*$")) - .build(); - contexts.add(securityContext); - return contexts; - } - - private List defaultAuth() { - AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything"); - AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; - authorizationScopes[0] = authorizationScope; - List references = new ArrayList<>(1); - references.add(new SecurityReference(AUTH_KEY, authorizationScopes)); - return references; - } - - private List securitySchemes() { - List apiKeys = new ArrayList<>(1); - ApiKey apiKey = new ApiKey(AUTH_KEY, AUTH_KEY, "header"); - apiKeys.add(apiKey); - return apiKeys; - } - - private List buildGlobalOperationParametersFromSwaggerProperties( - List globalOperationParameters) { - List parameters = Lists.newArrayList(); - - if (Objects.isNull(globalOperationParameters)) { - return parameters; - } - for (SwaggerProperties.GlobalOperationParameter globalOperationParameter : globalOperationParameters) { - parameters.add(new ParameterBuilder() - .name(globalOperationParameter.getName()) - .description(globalOperationParameter.getDescription()) - .modelRef(new ModelRef(globalOperationParameter.getModelRef())) - .parameterType(globalOperationParameter.getParameterType()) - .required(Boolean.parseBoolean(globalOperationParameter.getRequired())) - .build()); - } - return parameters; - } - - /** - * 局部参数按照name覆盖局部参数 - * - * @param globalOperationParameters - * @param docketOperationParameters - * @return - */ - private List assemblyGlobalOperationParameters( - List globalOperationParameters, - List docketOperationParameters) { - - if (Objects.isNull(docketOperationParameters) || docketOperationParameters.isEmpty()) { - return buildGlobalOperationParametersFromSwaggerProperties(globalOperationParameters); - } - - Set docketNames = docketOperationParameters.stream() - .map(SwaggerProperties.GlobalOperationParameter::getName) - .collect(Collectors.toSet()); - - List resultOperationParameters = Lists.newArrayList(); - - if (Objects.nonNull(globalOperationParameters)) { - for (SwaggerProperties.GlobalOperationParameter parameter : globalOperationParameters) { - if (!docketNames.contains(parameter.getName())) { - resultOperationParameters.add(parameter); - } - } - } - - resultOperationParameters.addAll(docketOperationParameters); - return buildGlobalOperationParametersFromSwaggerProperties(resultOperationParameters); - } -} diff --git a/jun_springboot_starter/jun-swagger2-spring-boot-starter/src/main/java/io/github/wujun728/common/swagger2/SwaggerProperties.java b/jun_springboot_starter/jun-swagger2-spring-boot-starter/src/main/java/io/github/wujun728/common/swagger2/SwaggerProperties.java deleted file mode 100644 index 259e6eb146..0000000000 --- a/jun_springboot_starter/jun-swagger2-spring-boot-starter/src/main/java/io/github/wujun728/common/swagger2/SwaggerProperties.java +++ /dev/null @@ -1,110 +0,0 @@ -package io.github.wujun728.common.swagger2; - -import lombok.Data; -import lombok.Getter; -import lombok.Setter; -import org.springframework.boot.context.properties.ConfigurationProperties; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - * swagger2 属性配置 - * - */ -@Data -@ConfigurationProperties("jun.swagger") -public class SwaggerProperties { - /**是否开启swagger**/ - private Boolean enabled; - /**标题**/ - private String title = ""; - /**描述**/ - private String description = ""; - /**版本**/ - private String version = ""; - /**许可证**/ - private String license = ""; - /**许可证URL**/ - private String licenseUrl = ""; - /**服务条款URL**/ - private String termsOfServiceUrl = ""; - /**联系人**/ - private Contact contact = new Contact(); - - /**swagger会解析的包路径**/ - private String basePackage = ""; - - /**swagger会解析的url规则**/ - private List basePath = new ArrayList<>(); - /**在basePath基础上需要排除的url规则**/ - private List excludePath = new ArrayList<>(); - - /**分组文档**/ - private Map docket = new LinkedHashMap<>(); - - /**host信息**/ - private String host = ""; - - /**全局参数配置**/ - private List globalOperationParameters; - - @Setter - @Getter - public static class GlobalOperationParameter{ - /**参数名**/ - private String name; - - /**描述信息**/ - private String description; - - /**指定参数类型**/ - private String modelRef; - - /**参数放在哪个地方:header,query,path,body.form**/ - private String parameterType; - - /**参数是否必须传**/ - private String required; - } - - @Data - public static class DocketInfo { - /**标题**/ - private String title = ""; - /**描述**/ - private String description = ""; - /**版本**/ - private String version = ""; - /**许可证**/ - private String license = ""; - /**许可证URL**/ - private String licenseUrl = ""; - /**服务条款URL**/ - private String termsOfServiceUrl = ""; - - private Contact contact = new Contact(); - - /**swagger会解析的包路径**/ - private String basePackage = ""; - - /**swagger会解析的url规则**/ - private List basePath = new ArrayList<>(); - /**在basePath基础上需要排除的url规则**/ - private List excludePath = new ArrayList<>(); - - private List globalOperationParameters; - } - - @Data - public static class Contact { - /**联系人**/ - private String name = ""; - /**联系人url**/ - private String url = ""; - /**联系人email**/ - private String email = ""; - } -} diff --git a/jun_springboot_starter/jun-swagger2-spring-boot-starter/src/main/resources/META-INF/spring.factories.bk b/jun_springboot_starter/jun-swagger2-spring-boot-starter/src/main/resources/META-INF/spring.factories.bk deleted file mode 100644 index 942aa3450e..0000000000 --- a/jun_springboot_starter/jun-swagger2-spring-boot-starter/src/main/resources/META-INF/spring.factories.bk +++ /dev/null @@ -1,2 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -io.github.wujun728.common.swagger2.SwaggerAutoConfiguration \ No newline at end of file diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/doc/cacheline_padding.png b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/doc/cacheline_padding.png deleted file mode 100644 index ed921c96f6..0000000000 Binary files a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/doc/cacheline_padding.png and /dev/null differ diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/doc/imgimage.png b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/doc/imgimage.png deleted file mode 100644 index 3ec845668f..0000000000 Binary files a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/doc/imgimage.png and /dev/null differ diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/doc/ringbuffer.png b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/doc/ringbuffer.png deleted file mode 100644 index d1a88a270d..0000000000 Binary files a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/doc/ringbuffer.png and /dev/null differ diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/doc/snowflake.png b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/doc/snowflake.png deleted file mode 100644 index d9d0890622..0000000000 Binary files a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/doc/snowflake.png and /dev/null differ diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/doc/throughput1.png b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/doc/throughput1.png deleted file mode 100644 index 41c7cfd15e..0000000000 Binary files a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/doc/throughput1.png and /dev/null differ diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/doc/throughput2.png b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/doc/throughput2.png deleted file mode 100644 index 2e89c13509..0000000000 Binary files a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/doc/throughput2.png and /dev/null differ diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/doc/throughput3.png b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/doc/throughput3.png deleted file mode 100644 index 15271354b0..0000000000 Binary files a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/doc/throughput3.png and /dev/null differ diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/doc/uidgenerator.png b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/doc/uidgenerator.png deleted file mode 100644 index e56af54cb1..0000000000 Binary files a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/doc/uidgenerator.png and /dev/null differ diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/pom.xml b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/pom.xml deleted file mode 100644 index d7f909e75b..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/pom.xml +++ /dev/null @@ -1,225 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun-uidgenerator-spring-boot-starter - 1.0.25 - jar - jun-uidgenerator-spring-boot-starter - 百度uidgenerator升级修改版,自用,具体见readme - https://github.com/wujun728/jun-spring-boot-starter/jun-uidgenerator-spring-boot-starter - - - 8 - UTF-8 - UTF-8 - UTF-8 - 8 - 8 - 8 - true - 1.0.25 - 2.5.14 - 2020.0.6 - 1.18.30 - 8.0.33 - 5.8.25 - 2.3.2 - - - - - io.github.wujun728 - jun-common-base - ${jun.version} - - - org.springframework.boot - spring-boot-starter - provided - - - org.springframework.boot - spring-boot-starter-jdbc - provided - - - - commons-collections - commons-collections - 3.2.2 - - - commons-lang - commons-lang - 2.6 - - - org.projectlombok - lombok - 1.18.30 - true - compile - - - com.mysql - mysql-connector-j - 8.0.33 - runtime - - - org.springframework.boot - spring-boot-starter-test - - - - junit - junit - test - - - cn.hutool - hutool-all - compile - - - net.dreamlu - mica-auto - - - - - - - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - - - - - wujun728 - wujun728@163.com - https://github.com/wujun728/jun-spring-boot-starter/jun-uidgenerator-spring-boot-starter - - - - - https://github.com/wujun728/jun-spring-boot-starter/jun-uidgenerator-spring-boot-starter.git - scm:git:https://github.com/wujun728/jun-spring-boot-starter/jun-uidgenerator-spring-boot-starter.git - scm:git:https://github.com/wujun728/jun-spring-boot-starter/jun-uidgenerator-spring-boot-starter.git - - - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - - oss - https://s01.oss.sonatype.org/content/repositories/snapshots - - - oss - https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/ - - - - - - - - org.apache.maven.plugins - maven-source-plugin - - - package - - jar-no-fork - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.9.1 - - private - true - UTF-8 - UTF-8 - UTF-8 - -Xdoclint:none - - - - - package - - jar - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.0 - - 1.8 - 1.8 - true - true - UTF-8 - - - - - org.apache.maven.plugins - maven-release-plugin - 2.5.1 - - - - - diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/readme.md b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/readme.md deleted file mode 100644 index 487de8b150..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/readme.md +++ /dev/null @@ -1,82 +0,0 @@ -# jun-uidgenerator-spring-boot-starter - -#### 介绍 -生成全局唯一ID之UidGenerator,from 百度,原ID生成依赖Spring4.x及ibatis,6年没有更新了,特升级springboot-stater不再依赖ibatis了,改为了jdbctemplate查询插入WORKER_NODE,即插即用,自用 - -#### 软件架构 -软件架构说明 -- UidGenerator是Java实现的, 基于Snowflake算法的唯一ID生成器。UidGenerator以组件形式工作在应用项目中, 支持自定义workerId位数和初始化策略, 从而适用于docker等虚拟化环境下实例自动重启、漂移等场景。 在实现上, UidGenerator通过借用未来时间来解决sequence天然存在的并发限制; 采用RingBuffer来缓存已生成的UID, 并行化UID的生产和消费, 同时对CacheLine补齐,避免了由RingBuffer带来的硬件级「伪共享」问题. - - -#### 安装教程 - -1. 第一次使用需要建数据库表 -```sql -DROP TABLE IF EXISTS WORKER_NODE; -CREATE TABLE WORKER_NODE -( -ID BIGINT unsigned NOT NULL AUTO_INCREMENT COMMENT 'auto increment id', -HOST_NAME VARCHAR(64) NOT NULL COMMENT 'host name', -PORT VARCHAR(64) NOT NULL COMMENT 'port', -TYPE INT NOT NULL COMMENT 'node type: ACTUAL or CONTAINER', -LAUNCH_DATE DATE NOT NULL COMMENT 'launch date', -MODIFIED TIMESTAMP NOT NULL COMMENT 'modified time', -CREATED TIMESTAMP NOT NULL COMMENT 'created time', -PRIMARY KEY(ID) -) -COMMENT='DB WorkerID Assigner for UID Generator'; -``` - - -#### 使用说明 - -1. 引入依赖 -```xml - - io.github.wujun728 - jun-uidgenerator-springboot-starter - 1.0.1 - - - org.projectlombok - lombok - true - compile - -``` -2. 增加配置(任选其一) - -```yaml -spring: - datasource: - driver-class-name: com.mysql.cj.jdbc.Driver - url: jdbc:mysql://localhost:3306/DB_BASE?useSSL=false&characterEncoding=UTF-8&allowMultiQueries=true - username: root - password: root -uid: - gen: - boostPower: 3 - epochStr: '2022-11-11' - scheduleInterval: 60 - seqBits: 11 - timeBits: 32 - workerBits: 20 -server: - tomcat: - threads: - max: 200 - min-spare: 100 - accept-count: 100 -``` -3. 获取id -```java -#启动类无需添加 -#@ComponentScan(basePackages = {"io.github.wujun728.uidgenerator","io.github.wujun728"}) -#使用 -@Resource -private UidGenerator uidGenerator; - -Long uid=uidGenerator.getUID() - -``` - diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/scripts/WORKER_NODE.sql b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/scripts/WORKER_NODE.sql deleted file mode 100644 index 8fefa70ae9..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/scripts/WORKER_NODE.sql +++ /dev/null @@ -1,13 +0,0 @@ -DROP TABLE IF EXISTS WORKER_NODE; -CREATE TABLE WORKER_NODE -( - ID BIGINT unsigned NOT NULL AUTO_INCREMENT COMMENT 'auto increment id', - HOST_NAME VARCHAR(64) NOT NULL COMMENT 'host name', - PORT VARCHAR(64) NOT NULL COMMENT 'port', - TYPE INT NOT NULL COMMENT 'node type: ACTUAL or CONTAINER', - LAUNCH_DATE DATE NOT NULL COMMENT 'launch date', - MODIFIED TIMESTAMP NOT NULL COMMENT 'modified time', - CREATED TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'created time', - PRIMARY KEY(ID) -) - COMMENT='DB WorkerID Assigner for UID Generator'; \ No newline at end of file diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/scripts/uid_info.sql b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/scripts/uid_info.sql deleted file mode 100644 index 7c69515760..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/scripts/uid_info.sql +++ /dev/null @@ -1,8 +0,0 @@ -create table uid_info -( - id bigint(11) UNSIGNED not null primary key auto_increment comment '主键', - uid bigint UNSIGNED not null default 0 comment 'uid', - create_time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间' -) - DEFAULT CHARSET = utf8 comment 'uid表'; -create index idx_uid on uid_info (uid); \ No newline at end of file diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/BitsAllocator.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/BitsAllocator.java deleted file mode 100644 index e5776b4dbb..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/BitsAllocator.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package io.github.wujun728.uidgenerator; - -import org.apache.commons.lang.builder.ToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; -import org.springframework.util.Assert; - -/** - * Allocate 64 bits for the UID(long)
        - * sign (fixed 1bit) -> deltaSecond -> workerId -> sequence(within the same second) - * - * - */ -public class BitsAllocator { - /** - * Total 64 bits - */ - public static final int TOTAL_BITS = 1 << 6; - - /** - * Bits for [sign-> second-> workId-> sequence] - */ - private int signBits = 1; - private final int timestampBits; - private final int workerIdBits; - private final int sequenceBits; - - /** - * Max value for workId & sequence - */ - private final long maxDeltaSeconds; - private final long maxWorkerId; - private final long maxSequence; - - /** - * Shift for timestamp & workerId - */ - private final int timestampShift; - private final int workerIdShift; - - /** - * Constructor with timestampBits, workerIdBits, sequenceBits
        - * The highest bit used for sign, so 63 bits for timestampBits, workerIdBits, sequenceBits - */ - public BitsAllocator(int timestampBits, int workerIdBits, int sequenceBits) { - // make sure allocated 64 bits - int allocateTotalBits = signBits + timestampBits + workerIdBits + sequenceBits; - Assert.isTrue(allocateTotalBits == TOTAL_BITS, "allocate not enough 64 bits"); - - // initialize bits - this.timestampBits = timestampBits; - this.workerIdBits = workerIdBits; - this.sequenceBits = sequenceBits; - - // initialize max value - this.maxDeltaSeconds = ~(-1L << timestampBits); - this.maxWorkerId = ~(-1L << workerIdBits); - this.maxSequence = ~(-1L << sequenceBits); - - // initialize shift - this.timestampShift = workerIdBits + sequenceBits; - this.workerIdShift = sequenceBits; - } - - /** - * Allocate bits for UID according to delta seconds & workerId & sequence
        - * Note that: The highest bit will always be 0 for sign - * - * @param deltaSeconds - * @param workerId - * @param sequence - * @return - */ - public long allocate(long deltaSeconds, long workerId, long sequence) { - return (deltaSeconds << timestampShift) | (workerId << workerIdShift) | sequence; - } - - /** - * Getters - */ - public int getSignBits() { - return signBits; - } - - public int getTimestampBits() { - return timestampBits; - } - - public int getWorkerIdBits() { - return workerIdBits; - } - - public int getSequenceBits() { - return sequenceBits; - } - - public long getMaxDeltaSeconds() { - return maxDeltaSeconds; - } - - public long getMaxWorkerId() { - return maxWorkerId; - } - - public long getMaxSequence() { - return maxSequence; - } - - public int getTimestampShift() { - return timestampShift; - } - - public int getWorkerIdShift() { - return workerIdShift; - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); - } - -} \ No newline at end of file diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/UidGenerator.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/UidGenerator.java deleted file mode 100644 index 45b1a36d93..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/UidGenerator.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package io.github.wujun728.uidgenerator; - -import io.github.wujun728.uidgenerator.exception.UidGenerateException; - -/** - * Represents a unique id generator. - * @Use 启动类添加@MapperScan("com.houger") - * 配置文件添加: - * spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver - * spring.datasource.url=jdbc:mysql://127.0.0.1:3306/DB_BASE?useSSL=false&characterEncoding=UTF-8&allowMultiQueries=true - * spring.datasource.username=root - * spring.datasource.password=root - * - * # mybatis configure - * mybatis.mapper-locations=classpath:mapper/*.xml - * mybatis.type-aliases-package=com.houger.worker.entity - * - * uid.gen.timeBits=32 - * uid.gen.workerBits=22 - * uid.gen.seqBits=9 - * uid.gen.epochStr=2022-11-11 - * uid.gen.boostPower=3 - * uid.gen.scheduleInterval=60 - */ -public interface UidGenerator { - - /** - * Get a unique ID - * - * @return UID - * @throws UidGenerateException - */ - long getUID() throws UidGenerateException; - - /** - * Parse the UID into elements which are used to generate the UID.
        - * Such as timestamp & workerId & sequence... - * - * @param uid - * @return Parsed info - */ - String parseUID(long uid); - -} diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/UidgeneratorApplication.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/UidgeneratorApplication.java deleted file mode 100644 index d82e8225fa..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/UidgeneratorApplication.java +++ /dev/null @@ -1,14 +0,0 @@ -package io.github.wujun728.uidgenerator; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class UidgeneratorApplication { - - - public static void main(String[] args) { - SpringApplication.run(UidgeneratorApplication.class, args); - } - -} diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/buffer/BufferPaddingExecutor.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/buffer/BufferPaddingExecutor.java deleted file mode 100644 index 7d45fe463e..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/buffer/BufferPaddingExecutor.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package io.github.wujun728.uidgenerator.buffer; - -import io.github.wujun728.uidgenerator.utils.NamingThreadFactory; -import io.github.wujun728.uidgenerator.utils.PaddedAtomicLong; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.util.Assert; - -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * Represents an executor for padding {@link RingBuffer}
        - * There are two kinds of executors: one for scheduled padding, the other for padding immediately. - * - * - */ -public class BufferPaddingExecutor { - private static final Logger LOGGER = LoggerFactory.getLogger(RingBuffer.class); - - /** Constants */ - private static final String WORKER_NAME = "RingBuffer-Padding-Worker"; - private static final String SCHEDULE_NAME = "RingBuffer-Padding-Schedule"; - private static final long DEFAULT_SCHEDULE_INTERVAL = 5 * 60L; // 5 minutes - - /** Whether buffer padding is running */ - private final AtomicBoolean running; - - /** We can borrow UIDs from the future, here store the last second we have consumed */ - private final PaddedAtomicLong lastSecond; - - /** RingBuffer & BufferUidProvider */ - private final RingBuffer ringBuffer; - private final BufferedUidProvider uidProvider; - - /** Padding immediately by the thread pool */ - private final ExecutorService bufferPadExecutors; - /** Padding schedule thread */ - private final ScheduledExecutorService bufferPadSchedule; - - /** Schedule interval Unit as seconds */ - private long scheduleInterval = DEFAULT_SCHEDULE_INTERVAL; - - /** - * Constructor with {@link RingBuffer} and {@link BufferedUidProvider}, default use schedule - * - * @param ringBuffer {@link RingBuffer} - * @param uidProvider {@link BufferedUidProvider} - */ - public BufferPaddingExecutor(RingBuffer ringBuffer, BufferedUidProvider uidProvider) { - this(ringBuffer, uidProvider, true); - } - - /** - * Constructor with {@link RingBuffer}, {@link BufferedUidProvider}, and whether use schedule padding - * - * @param ringBuffer {@link RingBuffer} - * @param uidProvider {@link BufferedUidProvider} - * @param usingSchedule - */ - public BufferPaddingExecutor(RingBuffer ringBuffer, BufferedUidProvider uidProvider, boolean usingSchedule) { - this.running = new AtomicBoolean(false); - this.lastSecond = new PaddedAtomicLong(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis())); - this.ringBuffer = ringBuffer; - this.uidProvider = uidProvider; - - // initialize thread pool - int cores = Runtime.getRuntime().availableProcessors(); - bufferPadExecutors = Executors.newFixedThreadPool(cores * 2, new NamingThreadFactory(WORKER_NAME)); - - // initialize schedule thread - if (usingSchedule) { - bufferPadSchedule = Executors.newSingleThreadScheduledExecutor(new NamingThreadFactory(SCHEDULE_NAME)); - } else { - bufferPadSchedule = null; - } - } - - /** - * Start executors such as schedule - */ - public void start() { - if (bufferPadSchedule != null) { - bufferPadSchedule.scheduleWithFixedDelay(() -> paddingBuffer(), scheduleInterval, scheduleInterval, TimeUnit.SECONDS); - } - } - - /** - * Shutdown executors - */ - public void shutdown() { - if (!bufferPadExecutors.isShutdown()) { - bufferPadExecutors.shutdownNow(); - } - - if (bufferPadSchedule != null && !bufferPadSchedule.isShutdown()) { - bufferPadSchedule.shutdownNow(); - } - } - - /** - * Whether is padding - * - * @return - */ - public boolean isRunning() { - return running.get(); - } - - /** - * Padding buffer in the thread pool - */ - public void asyncPadding() { - bufferPadExecutors.submit(this::paddingBuffer); - } - - /** - * Padding buffer fill the slots until to catch the cursor - */ - public void paddingBuffer() { - LOGGER.info("Ready to padding buffer lastSecond:{}. {}", lastSecond.get(), ringBuffer); - - // is still running - if (!running.compareAndSet(false, true)) { - LOGGER.info("Padding buffer is still running. {}", ringBuffer); - return; - } - - // fill the rest slots until to catch the cursor - boolean isFullRingBuffer = false; - while (!isFullRingBuffer) { - List uidList = uidProvider.provide(lastSecond.incrementAndGet()); - for (Long uid : uidList) { - isFullRingBuffer = !ringBuffer.put(uid); - if (isFullRingBuffer) { - break; - } - } - } - - // not running now - running.compareAndSet(true, false); - LOGGER.info("End to padding buffer lastSecond:{}. {}", lastSecond.get(), ringBuffer); - } - - /** - * Setters - */ - public void setScheduleInterval(long scheduleInterval) { - Assert.isTrue(scheduleInterval > 0, "Schedule interval must positive!"); - this.scheduleInterval = scheduleInterval; - } - -} diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/buffer/BufferedUidProvider.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/buffer/BufferedUidProvider.java deleted file mode 100644 index f5f3573fc2..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/buffer/BufferedUidProvider.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package io.github.wujun728.uidgenerator.buffer; - -import java.util.List; - -/** - * Buffered UID provider(Lambda supported), which provides UID in the same one second - * - * - */ -@FunctionalInterface -public interface BufferedUidProvider { - - /** - * Provides UID in one second - * - * @param momentInSecond - * @return - */ - List provide(long momentInSecond); -} diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/buffer/RejectedPutBufferHandler.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/buffer/RejectedPutBufferHandler.java deleted file mode 100644 index 2487d038e7..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/buffer/RejectedPutBufferHandler.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package io.github.wujun728.uidgenerator.buffer; - -/** - * If tail catches the cursor it means that the ring buffer is full, any more buffer put request will be rejected. - * Specify the policy to handle the reject. This is a Lambda supported interface - * - * - */ -@FunctionalInterface -public interface RejectedPutBufferHandler { - - /** - * Reject put buffer request - * - * @param ringBuffer - * @param uid - */ - void rejectPutBuffer(RingBuffer ringBuffer, long uid); -} diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/buffer/RejectedTakeBufferHandler.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/buffer/RejectedTakeBufferHandler.java deleted file mode 100644 index d91144e9d0..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/buffer/RejectedTakeBufferHandler.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package io.github.wujun728.uidgenerator.buffer; - -/** - * If cursor catches the tail it means that the ring buffer is empty, any more buffer take request will be rejected. - * Specify the policy to handle the reject. This is a Lambda supported interface - * - * - */ -@FunctionalInterface -public interface RejectedTakeBufferHandler { - - /** - * Reject take buffer request - * - * @param ringBuffer - */ - void rejectTakeBuffer(RingBuffer ringBuffer); -} diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/buffer/RingBuffer.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/buffer/RingBuffer.java deleted file mode 100644 index 566ebbfb3b..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/buffer/RingBuffer.java +++ /dev/null @@ -1,260 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package io.github.wujun728.uidgenerator.buffer; - -import io.github.wujun728.uidgenerator.utils.PaddedAtomicLong; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.util.Assert; - -import java.util.concurrent.atomic.AtomicLong; - -/** - * Represents a ring buffer based on array.
        - * Using array could improve read element performance due to the CUP cache line. To prevent - * the side effect of False Sharing, {@link PaddedAtomicLong} is using on 'tail' and 'cursor'

        - * - * A ring buffer is consisted of: - *

      • slots: each element of the array is a slot, which is be set with a UID - *
      • flags: flag array corresponding the same index with the slots, indicates whether can take or put slot - *
      • tail: a sequence of the max slot position to produce - *
      • cursor: a sequence of the min slot position to consume - * - * - */ -public class RingBuffer { - private static final Logger LOGGER = LoggerFactory.getLogger(RingBuffer.class); - - /** Constants */ - private static final int START_POINT = -1; - private static final long CAN_PUT_FLAG = 0L; - private static final long CAN_TAKE_FLAG = 1L; - public static final int DEFAULT_PADDING_PERCENT = 50; - - /** The size of RingBuffer's slots, each slot hold a UID */ - private final int bufferSize; - private final long indexMask; - private final long[] slots; - private final PaddedAtomicLong[] flags; - - /** Tail: last position sequence to produce */ - private final AtomicLong tail = new PaddedAtomicLong(START_POINT); - - /** Cursor: current position sequence to consume */ - private final AtomicLong cursor = new PaddedAtomicLong(START_POINT); - - /** Threshold for trigger padding buffer*/ - private final int paddingThreshold; - - /** Reject put/take buffer handle policy */ - private RejectedPutBufferHandler rejectedPutHandler = this::discardPutBuffer; - private RejectedTakeBufferHandler rejectedTakeHandler = this::exceptionRejectedTakeBuffer; - - /** Executor of padding buffer */ - private BufferPaddingExecutor bufferPaddingExecutor; - - /** - * Constructor with buffer size, paddingFactor default as {@value #DEFAULT_PADDING_PERCENT} - * - * @param bufferSize must be positive & a power of 2 - */ - public RingBuffer(int bufferSize) { - this(bufferSize, DEFAULT_PADDING_PERCENT); - } - - /** - * Constructor with buffer size & padding factor - * - * @param bufferSize must be positive & a power of 2 - * @param paddingFactor percent in (0 - 100). When the count of rest available UIDs reach the threshold, it will trigger padding buffer
        - * Sample: paddingFactor=20, bufferSize=1000 -> threshold=1000 * 20 /100, - * padding buffer will be triggered when tail-cursor 0L, "RingBuffer size must be positive"); - Assert.isTrue(Integer.bitCount(bufferSize) == 1, "RingBuffer size must be a power of 2"); - Assert.isTrue(paddingFactor > 0 && paddingFactor < 100, "RingBuffer size must be positive"); - - this.bufferSize = bufferSize; - this.indexMask = bufferSize - 1; - this.slots = new long[bufferSize]; - this.flags = initFlags(bufferSize); - - this.paddingThreshold = bufferSize * paddingFactor / 100; - } - - /** - * Put an UID in the ring & tail moved
        - * We use 'synchronized' to guarantee the UID fill in slot & publish new tail sequence as atomic operations
        - * - * Note that: It is recommended to put UID in a serialize way, cause we once batch generate a series UIDs and put - * the one by one into the buffer, so it is unnecessary put in multi-threads - * - * @param uid - * @return false means that the buffer is full, apply {@link RejectedPutBufferHandler} - */ - public synchronized boolean put(long uid) { - long currentTail = tail.get(); - long currentCursor = cursor.get(); - - // tail catches the cursor, means that you can't put any cause of RingBuffer is full - long distance = currentTail - (currentCursor == START_POINT ? 0 : currentCursor); - if (distance == bufferSize - 1) { - rejectedPutHandler.rejectPutBuffer(this, uid); - return false; - } - - // 1. pre-check whether the flag is CAN_PUT_FLAG - int nextTailIndex = calSlotIndex(currentTail + 1); - if (flags[nextTailIndex].get() != CAN_PUT_FLAG) { - rejectedPutHandler.rejectPutBuffer(this, uid); - return false; - } - - // 2. put UID in the next slot - // 3. update next slot' flag to CAN_TAKE_FLAG - // 4. publish tail with sequence increase by one - slots[nextTailIndex] = uid; - flags[nextTailIndex].set(CAN_TAKE_FLAG); - tail.incrementAndGet(); - - // The atomicity of operations above, guarantees by 'synchronized'. In another word, - // the take operation can't consume the UID we just put, until the tail is published(tail.incrementAndGet()) - return true; - } - - /** - * Take an UID of the ring at the next cursor, this is a lock free operation by using atomic cursor

        - * - * Before getting the UID, we also check whether reach the padding threshold, - * the padding buffer operation will be triggered in another thread
        - * If there is no more available UID to be taken, the specified {@link RejectedTakeBufferHandler} will be applied
        - * - * @return UID - * @throws IllegalStateException if the cursor moved back - */ - public long take() { - // spin get next available cursor - long currentCursor = cursor.get(); - long nextCursor = cursor.updateAndGet(old -> old == tail.get() ? old : old + 1); - - // check for safety consideration, it never occurs - Assert.isTrue(nextCursor >= currentCursor, "Curosr can't move back"); - - // trigger padding in an async-mode if reach the threshold - long currentTail = tail.get(); - if (currentTail - nextCursor < paddingThreshold) { - LOGGER.info("Reach the padding threshold:{}. tail:{}, cursor:{}, rest:{}", paddingThreshold, currentTail, - nextCursor, currentTail - nextCursor); - bufferPaddingExecutor.asyncPadding(); - } - - // cursor catch the tail, means that there is no more available UID to take - if (nextCursor == currentCursor) { - rejectedTakeHandler.rejectTakeBuffer(this); - } - - // 1. check next slot flag is CAN_TAKE_FLAG - int nextCursorIndex = calSlotIndex(nextCursor); - Assert.isTrue(flags[nextCursorIndex].get() == CAN_TAKE_FLAG, "Curosr not in can take status"); - - // 2. get UID from next slot - // 3. set next slot flag as CAN_PUT_FLAG. - long uid = slots[nextCursorIndex]; - flags[nextCursorIndex].set(CAN_PUT_FLAG); - - // Note that: Step 2,3 can not swap. If we set flag before get value of slot, the producer may overwrite the - // slot with a new UID, and this may cause the consumer take the UID twice after walk a round the ring - return uid; - } - - /** - * Calculate slot index with the slot sequence (sequence % bufferSize) - */ - protected int calSlotIndex(long sequence) { - return (int) (sequence & indexMask); - } - - /** - * Discard policy for {@link RejectedPutBufferHandler}, we just do logging - */ - protected void discardPutBuffer(RingBuffer ringBuffer, long uid) { - LOGGER.warn("Rejected putting buffer for uid:{}. {}", uid, ringBuffer); - } - - /** - * Policy for {@link RejectedTakeBufferHandler}, throws {@link RuntimeException} after logging - */ - protected void exceptionRejectedTakeBuffer(RingBuffer ringBuffer) { - LOGGER.warn("Rejected take buffer. {}", ringBuffer); - throw new RuntimeException("Rejected take buffer. " + ringBuffer); - } - - /** - * Initialize flags as CAN_PUT_FLAG - */ - private PaddedAtomicLong[] initFlags(int bufferSize) { - PaddedAtomicLong[] flags = new PaddedAtomicLong[bufferSize]; - for (int i = 0; i < bufferSize; i++) { - flags[i] = new PaddedAtomicLong(CAN_PUT_FLAG); - } - - return flags; - } - - /** - * Getters - */ - public long getTail() { - return tail.get(); - } - - public long getCursor() { - return cursor.get(); - } - - public int getBufferSize() { - return bufferSize; - } - - /** - * Setters - */ - public void setBufferPaddingExecutor(BufferPaddingExecutor bufferPaddingExecutor) { - this.bufferPaddingExecutor = bufferPaddingExecutor; - } - - public void setRejectedPutHandler(RejectedPutBufferHandler rejectedPutHandler) { - this.rejectedPutHandler = rejectedPutHandler; - } - - public void setRejectedTakeHandler(RejectedTakeBufferHandler rejectedTakeHandler) { - this.rejectedTakeHandler = rejectedTakeHandler; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("RingBuffer [bufferSize=").append(bufferSize) - .append(", tail=").append(tail) - .append(", cursor=").append(cursor) - .append(", paddingThreshold=").append(paddingThreshold).append("]"); - - return builder.toString(); - } - -} diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/config/UidAutoConfig.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/config/UidAutoConfig.java deleted file mode 100644 index 9f21f1a45e..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/config/UidAutoConfig.java +++ /dev/null @@ -1,76 +0,0 @@ -package io.github.wujun728.uidgenerator.config; - -import cn.hutool.core.lang.ClassScanner; -import cn.hutool.core.text.NamingCase; -import cn.hutool.core.util.StrUtil; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.InitializingBean; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.support.BeanDefinitionBuilder; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.stereotype.Component; -import org.springframework.stereotype.Controller; -import org.springframework.stereotype.Repository; -import org.springframework.stereotype.Service; - -import javax.script.ScriptEngineManager; -import java.util.Arrays; -import java.util.List; -import java.util.Set; - -@Configuration -@ComponentScan(basePackages = "io.github.wujun728.uidgenerator") -public class UidAutoConfig implements ApplicationContextAware, InitializingBean { - private ConfigurableApplicationContext applicationContext; - - private BeanDefinitionRegistry registry; - - /** - * //以下五个的结果都是为spring容器为这个类创建Bean. - * @Bean 注解告诉Spring这个方法将会返回一个对象,这个对象要注册为Spring应用上下文中的bean。 通常方法体中包含了最终产生bean实例的逻辑 - * @Component 注解表明一个类会作为组件类,并告知Spring要为这个类创建bean - * @return - */ - List annotationClasss = Arrays.asList(Configuration.class,/*Mapper.class,*/ Service.class, Component.class, Repository.class, Controller.class,ConfigurationProperties.class); - @Override - public void afterPropertiesSet() throws Exception { - annotationClasss.forEach(clazz->{ - Set> mappers = ClassScanner.scanPackageByAnnotation("io.github.wujun728.uidgenerator", clazz); - mappers.forEach(c->{ - String beanName = NamingCase.toCamelCase(c.getSimpleName()); - beanName = StrUtil.lowerFirst(beanName); - if(!applicationContext.containsBean(beanName) && !applicationContext.containsBeanDefinition(beanName) ){ - registerBean(beanName,c); - } - }); - }); - //applicationContext.refresh(); - } - - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - this.applicationContext = (ConfigurableApplicationContext) applicationContext; - } - - public void registerBean(String beanName, Class clazz) { - this.registry = (BeanDefinitionRegistry) applicationContext.getAutowireCapableBeanFactory(); - BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(clazz); - BeanDefinition beanDefinition = builder.getBeanDefinition(); - registry.registerBeanDefinition(beanName, beanDefinition); - } - - @Bean - @ConditionalOnMissingBean - public ScriptEngineManager scriptEngineManager() { - return new ScriptEngineManager(); - } - -} \ No newline at end of file diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/config/UidDbConfiguration.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/config/UidDbConfiguration.java deleted file mode 100644 index a373c94f75..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/config/UidDbConfiguration.java +++ /dev/null @@ -1,52 +0,0 @@ -//package io.github.wujun728.uidgenerator.config; -// -//import io.github.wujun728.uidgenerator.worker.repository.DbWorkerNodeResposity; -//import io.github.wujun728.uidgenerator.worker.repository.WorkerNodeResposity; -//import com.zaxxer.hikari.HikariDataSource; -//import org.apache.commons.lang.StringUtils; -//import org.springframework.beans.factory.ObjectProvider; -//import org.springframework.beans.factory.annotation.Value; -//import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -//import org.springframework.context.annotation.Bean; -//import org.springframework.context.annotation.Configuration; -//import org.springframework.context.annotation.Primary; -//import org.springframework.jdbc.core.JdbcTemplate; -//import org.springframework.stereotype.Component; -// -//import javax.sql.DataSource; -// -//@Configuration -//@Component -//public class UidDbConfiguration { -// @Value("${spring.datasource.driver-class-name:}") -// private String driverClassName; -// @Value("${spring.datasource.url:}") -// private String url; -// @Value("${spring.datasource.username:}") -// private String username; -// @Value("${spring.datasource.password:}") -// private String password; -// -// @Bean -// @ConditionalOnMissingBean(WorkerNodeResposity.class) -// public WorkerNodeResposity workerNodeResposity(ObjectProvider dataSourcePvd) { -// DataSource dataSource = null; -// if (StringUtils.isNotBlank(this.driverClassName) && -// StringUtils.isNotBlank(this.url) && -// StringUtils.isNotBlank(this.username) && -// StringUtils.isNotBlank(this.password)) { -// -// HikariDataSource hds = new HikariDataSource(); -// hds.setDriverClassName(this.driverClassName); -// hds.setJdbcUrl(this.url); -// hds.setUsername(this.username); -// hds.setPassword(this.password); -// dataSource = hds; -// } else { -// dataSource = dataSourcePvd.getIfAvailable(); -// } -// -// JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); -// return new DbWorkerNodeResposity(jdbcTemplate); -// } -//} diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/config/UidGeneratorConfig.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/config/UidGeneratorConfig.java deleted file mode 100644 index e0d46407ef..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/config/UidGeneratorConfig.java +++ /dev/null @@ -1,47 +0,0 @@ -package io.github.wujun728.uidgenerator.config; - -import io.github.wujun728.uidgenerator.UidGenerator; -import io.github.wujun728.uidgenerator.impl.CachedUidGenerator; -import io.github.wujun728.uidgenerator.impl.DefaultUidGenerator; -import io.github.wujun728.uidgenerator.worker.WorkerIdAssigner; -import org.apache.commons.lang.StringUtils; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; - -import javax.annotation.Resource; - -@Configuration -//@Import({UidGeneratorProperties.class, UidGenerator.class, CachedUidGenerator.class, DefaultUidGenerator.class, UidDbConfiguration.class,}) -@ComponentScan(basePackages = {"io.github.wujun728.uidgenerator"}) -@EnableConfigurationProperties(UidGeneratorProperties.class) -public class UidGeneratorConfig { - - @Resource - UidGeneratorProperties uidGeneratorProperties; - - @Bean - public CachedUidGenerator cachedUidGenerator(WorkerIdAssigner disposableWorkerIdAssigner) { - CachedUidGenerator cachedUidGenerator = new CachedUidGenerator(); - cachedUidGenerator.setWorkerIdAssigner(disposableWorkerIdAssigner); - setBaseProp(cachedUidGenerator); - setCachedProp(cachedUidGenerator); - return cachedUidGenerator; - } - - void setBaseProp(DefaultUidGenerator defaultUidGenerator) { - if (uidGeneratorProperties == null) return; - if (uidGeneratorProperties.getTimeBits() != null) defaultUidGenerator.setTimeBits(uidGeneratorProperties.getTimeBits()); - if (uidGeneratorProperties.getWorkerBits() != null) defaultUidGenerator.setWorkerBits(uidGeneratorProperties.getWorkerBits()); - if (uidGeneratorProperties.getSeqBits() != null) defaultUidGenerator.setSeqBits(uidGeneratorProperties.getSeqBits()); - if (StringUtils.isNotBlank(uidGeneratorProperties.getEpochStr())) defaultUidGenerator.setEpochStr(uidGeneratorProperties.getEpochStr()); - } - void setCachedProp(CachedUidGenerator cachedUidGenerator) { - if (uidGeneratorProperties == null) return; - if (uidGeneratorProperties.getBoostPower() != null) cachedUidGenerator.setBoostPower(uidGeneratorProperties.getBoostPower()); - if (uidGeneratorProperties.getScheduleInterval() != null) cachedUidGenerator.setScheduleInterval(uidGeneratorProperties.getScheduleInterval()); - } -} - diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/config/UidGeneratorProperties.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/config/UidGeneratorProperties.java deleted file mode 100644 index ec57dabbf4..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/config/UidGeneratorProperties.java +++ /dev/null @@ -1,27 +0,0 @@ -package io.github.wujun728.uidgenerator.config; - -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; - -@Data -@ConfigurationProperties(prefix = "uid.gen") -public class UidGeneratorProperties { - - //相对于时间基点"2016-05-20"的增量值,单位:秒,可使用的时间为2^timeBis 秒例如:timeBits=30,则可使用230秒,约34年,timeBits=31,则可使用231秒,约68年 - private Integer timeBits; - - //机器id,最多可支持2^22约420w次机器启动。内置实现为在启动时由数据库分配,默认分配策略为用后即弃,每次启动都会重新生成一批ID,因此重启次数也是会有限制的,后续可提供复用策略。 - private Integer workerBits; - - //每秒下的并发序列,9 bits可支持每台服务器每秒512个并发。 - private Integer seqBits; - - //指集成UidGenerator生成分布式ID服务第一次上线的时间,可配置,也一定要根据你的上线时间进行配置,因为默认的epoch时间可是2016-09-20,不配置的话,会浪费好几年的可用时间。 - private String epochStr; - - //RingBuffer size扩容参数, 可提高UID生成的吞吐量默认:3, 原bufferSize=8192, 扩容后bufferSize= 8192 << 3 = 65536 - private Integer boostPower; - - //另外一种RingBuffer填充时机, 在Schedule线程中, 周期性检查填充默认:不配置此项, 即不实用Schedule线程. 如需使用, 请指定Schedule线程时间间隔, 单位:秒 - private Long scheduleInterval; -} diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/exception/UidGenerateException.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/exception/UidGenerateException.java deleted file mode 100644 index b5be0d990f..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/exception/UidGenerateException.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package io.github.wujun728.uidgenerator.exception; - -/** - * UidGenerateException - * - * - */ -public class UidGenerateException extends RuntimeException { - - /** - * Serial Version UID - */ - private static final long serialVersionUID = -27048199131316992L; - - /** - * Default constructor - */ - public UidGenerateException() { - super(); - } - - /** - * Constructor with message & cause - * - * @param message - * @param cause - */ - public UidGenerateException(String message, Throwable cause) { - super(message, cause); - } - - /** - * Constructor with message - * - * @param message - */ - public UidGenerateException(String message) { - super(message); - } - - /** - * Constructor with message format - * - * @param msgFormat - * @param args - */ - public UidGenerateException(String msgFormat, Object... args) { - super(String.format(msgFormat, args)); - } - - /** - * Constructor with cause - * - * @param cause - */ - public UidGenerateException(Throwable cause) { - super(cause); - } - -} diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/impl/CachedUidGenerator.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/impl/CachedUidGenerator.java deleted file mode 100644 index aabf6e3a25..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/impl/CachedUidGenerator.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package io.github.wujun728.uidgenerator.impl; - -import io.github.wujun728.uidgenerator.BitsAllocator; -import io.github.wujun728.uidgenerator.UidGenerator; -import io.github.wujun728.uidgenerator.buffer.BufferPaddingExecutor; -import io.github.wujun728.uidgenerator.buffer.RejectedPutBufferHandler; -import io.github.wujun728.uidgenerator.buffer.RejectedTakeBufferHandler; -import io.github.wujun728.uidgenerator.buffer.RingBuffer; -import io.github.wujun728.uidgenerator.exception.UidGenerateException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.DisposableBean; -import org.springframework.util.Assert; - -import java.util.ArrayList; -import java.util.List; - -/** - * Represents a cached implementation of {@link UidGenerator} extends - * from {@link DefaultUidGenerator}, based on a lock free {@link RingBuffer}

        - * - * The spring properties you can specified as below:
        - *

      • boostPower: RingBuffer size boost for a power of 2, Sample: boostPower is 3, it means the buffer size - * will be ({@link BitsAllocator#getMaxSequence()} + 1) << - * {@link #boostPower}, Default as {@value #DEFAULT_BOOST_POWER} - *
      • paddingFactor: Represents a percent value of (0 - 100). When the count of rest available UIDs reach the - * threshold, it will trigger padding buffer. Default as{@link RingBuffer#DEFAULT_PADDING_PERCENT} - * Sample: paddingFactor=20, bufferSize=1000 -> threshold=1000 * 20 /100, padding buffer will be triggered when tail-cursorscheduleInterval: Padding buffer in a schedule, specify padding buffer interval, Unit as second - *
      • rejectedPutBufferHandler: Policy for rejected put buffer. Default as discard put request, just do logging - *
      • rejectedTakeBufferHandler: Policy for rejected take buffer. Default as throwing up an exception - * - * - */ -public class CachedUidGenerator extends DefaultUidGenerator implements DisposableBean { - private static final Logger LOGGER = LoggerFactory.getLogger(CachedUidGenerator.class); - private static final int DEFAULT_BOOST_POWER = 3; - - /** Spring properties */ - private int boostPower = DEFAULT_BOOST_POWER; - private int paddingFactor = RingBuffer.DEFAULT_PADDING_PERCENT; - private Long scheduleInterval; - - private RejectedPutBufferHandler rejectedPutBufferHandler; - private RejectedTakeBufferHandler rejectedTakeBufferHandler; - - /** RingBuffer */ - private RingBuffer ringBuffer; - private BufferPaddingExecutor bufferPaddingExecutor; - - @Override - public void afterPropertiesSet() throws Exception { - // initialize workerId & bitsAllocator - super.afterPropertiesSet(); - - // initialize RingBuffer & RingBufferPaddingExecutor - this.initRingBuffer(); - LOGGER.info("Initialized RingBuffer successfully."); - } - - @Override - public long getUID() { - try { - return ringBuffer.take(); - } catch (Exception e) { - LOGGER.error("Generate unique id exception. ", e); - throw new UidGenerateException(e); - } - } - - @Override - public String parseUID(long uid) { - return super.parseUID(uid); - } - - @Override - public void destroy() throws Exception { - bufferPaddingExecutor.shutdown(); - } - - /** - * Get the UIDs in the same specified second under the max sequence - * - * @param currentSecond - * @return UID list, size of {@link BitsAllocator#getMaxSequence()} + 1 - */ - protected List nextIdsForOneSecond(long currentSecond) { - // Initialize result list size of (max sequence + 1) - int listSize = (int) bitsAllocator.getMaxSequence() + 1; - List uidList = new ArrayList<>(listSize); - - // Allocate the first sequence of the second, the others can be calculated with the offset - long firstSeqUid = bitsAllocator.allocate(currentSecond - epochSeconds, workerId, 0L); - for (int offset = 0; offset < listSize; offset++) { - uidList.add(firstSeqUid + offset); - } - - return uidList; - } - - /** - * Initialize RingBuffer & RingBufferPaddingExecutor - */ - private void initRingBuffer() { - // initialize RingBuffer - int bufferSize = ((int) bitsAllocator.getMaxSequence() + 1) << boostPower; - this.ringBuffer = new RingBuffer(bufferSize, paddingFactor); - LOGGER.info("Initialized ring buffer size:{}, paddingFactor:{}", bufferSize, paddingFactor); - - // initialize RingBufferPaddingExecutor - boolean usingSchedule = (scheduleInterval != null); - this.bufferPaddingExecutor = new BufferPaddingExecutor(ringBuffer, this::nextIdsForOneSecond, usingSchedule); - if (usingSchedule) { - bufferPaddingExecutor.setScheduleInterval(scheduleInterval); - } - - LOGGER.info("Initialized BufferPaddingExecutor. Using schdule:{}, interval:{}", usingSchedule, scheduleInterval); - - // set rejected put/take handle policy - this.ringBuffer.setBufferPaddingExecutor(bufferPaddingExecutor); - if (rejectedPutBufferHandler != null) { - this.ringBuffer.setRejectedPutHandler(rejectedPutBufferHandler); - } - if (rejectedTakeBufferHandler != null) { - this.ringBuffer.setRejectedTakeHandler(rejectedTakeBufferHandler); - } - - // fill in all slots of the RingBuffer - bufferPaddingExecutor.paddingBuffer(); - - // start buffer padding threads - bufferPaddingExecutor.start(); - } - - /** - * Setters for spring property - */ - public void setBoostPower(int boostPower) { - Assert.isTrue(boostPower > 0, "Boost power must be positive!"); - this.boostPower = boostPower; - } - - public void setRejectedPutBufferHandler(RejectedPutBufferHandler rejectedPutBufferHandler) { - Assert.notNull(rejectedPutBufferHandler, "RejectedPutBufferHandler can't be null!"); - this.rejectedPutBufferHandler = rejectedPutBufferHandler; - } - - public void setRejectedTakeBufferHandler(RejectedTakeBufferHandler rejectedTakeBufferHandler) { - Assert.notNull(rejectedTakeBufferHandler, "RejectedTakeBufferHandler can't be null!"); - this.rejectedTakeBufferHandler = rejectedTakeBufferHandler; - } - - public void setScheduleInterval(long scheduleInterval) { - Assert.isTrue(scheduleInterval > 0, "Schedule interval must positive!"); - this.scheduleInterval = scheduleInterval; - } - -} diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/impl/DefaultUidGenerator.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/impl/DefaultUidGenerator.java deleted file mode 100644 index cf0ec36862..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/impl/DefaultUidGenerator.java +++ /dev/null @@ -1,217 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package io.github.wujun728.uidgenerator.impl; - -import io.github.wujun728.uidgenerator.BitsAllocator; -import io.github.wujun728.uidgenerator.UidGenerator; -import io.github.wujun728.uidgenerator.exception.UidGenerateException; -import io.github.wujun728.uidgenerator.utils.DateUtils; -import io.github.wujun728.uidgenerator.worker.WorkerIdAssigner; -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.InitializingBean; - -import java.util.Date; -import java.util.concurrent.TimeUnit; - -/** - * Represents an implementation of {@link UidGenerator} - * - * The unique id has 64bits (long), default allocated as blow:
        - *
      • sign: The highest bit is 0 - *
      • delta seconds: The next 28 bits, represents delta seconds since a customer epoch(2016-05-20 00:00:00.000). - * Supports about 8.7 years until to 2024-11-20 21:24:16 - *
      • worker id: The next 22 bits, represents the worker's id which assigns based on database, max id is about 420W - *
      • sequence: The next 13 bits, represents a sequence within the same second, max for 8192/s

        - * - * The {@link DefaultUidGenerator#parseUID(long)} is a tool method to parse the bits - * - *
        {@code
        - * +------+----------------------+----------------+-----------+
        - * | sign |     delta seconds    | worker node id | sequence  |
        - * +------+----------------------+----------------+-----------+
        - *   1bit          28bits              22bits         13bits
        - * }
        - * - * You can also specified the bits by Spring property setting. - *
      • timeBits: default as 28 - *
      • workerBits: default as 22 - *
      • seqBits: default as 13 - *
      • epochStr: Epoch date string format 'yyyy-MM-dd'. Default as '2016-05-20'

        - * - * Note that: The total bits must be 64 -1 - * - * - */ -public class DefaultUidGenerator implements UidGenerator, InitializingBean { - private static final Logger LOGGER = LoggerFactory.getLogger(DefaultUidGenerator.class); - - /** Bits allocate */ - protected int timeBits = 28; - protected int workerBits = 22; - protected int seqBits = 13; - - /** Customer epoch, unit as second. For example 2016-05-20 (ms: 1463673600000)*/ - protected String epochStr = "2016-05-20"; - protected long epochSeconds = TimeUnit.MILLISECONDS.toSeconds(1463673600000L); - - /** Stable fields after spring bean initializing */ - protected BitsAllocator bitsAllocator; - protected long workerId; - - /** Volatile fields caused by nextId() */ - protected long sequence = 0L; - protected long lastSecond = -1L; - - /** Spring property */ - protected WorkerIdAssigner workerIdAssigner; - - @Override - public void afterPropertiesSet() throws Exception { - // initialize bits allocator - bitsAllocator = new BitsAllocator(timeBits, workerBits, seqBits); - - // initialize worker id - workerId = workerIdAssigner.assignWorkerId(); - if (workerId > bitsAllocator.getMaxWorkerId()) { - throw new RuntimeException("Worker id " + workerId + " exceeds the max " + bitsAllocator.getMaxWorkerId()); - } - - LOGGER.info("Initialized bits(1, {}, {}, {}) for workerID:{}", timeBits, workerBits, seqBits, workerId); - } - - @Override - public long getUID() throws UidGenerateException { - try { - return nextId(); - } catch (Exception e) { - LOGGER.error("Generate unique id exception. ", e); - throw new UidGenerateException(e); - } - } - - @Override - public String parseUID(long uid) { - long totalBits = BitsAllocator.TOTAL_BITS; - long signBits = bitsAllocator.getSignBits(); - long timestampBits = bitsAllocator.getTimestampBits(); - long workerIdBits = bitsAllocator.getWorkerIdBits(); - long sequenceBits = bitsAllocator.getSequenceBits(); - - // parse UID - long sequence = (uid << (totalBits - sequenceBits)) >>> (totalBits - sequenceBits); - long workerId = (uid << (timestampBits + signBits)) >>> (totalBits - workerIdBits); - long deltaSeconds = uid >>> (workerIdBits + sequenceBits); - - Date thatTime = new Date(TimeUnit.SECONDS.toMillis(epochSeconds + deltaSeconds)); - String thatTimeStr = DateUtils.formatByDateTimePattern(thatTime); - - // format as string - return String.format("{\"UID\":\"%d\",\"timestamp\":\"%s\",\"workerId\":\"%d\",\"sequence\":\"%d\"}", - uid, thatTimeStr, workerId, sequence); - } - - /** - * Get UID - * - * @return UID - * @throws UidGenerateException in the case: Clock moved backwards; Exceeds the max timestamp - */ - protected synchronized long nextId() { - long currentSecond = getCurrentSecond(); - - // Clock moved backwards, refuse to generate uid - if (currentSecond < lastSecond) { - long refusedSeconds = lastSecond - currentSecond; - throw new UidGenerateException("Clock moved backwards. Refusing for %d seconds", refusedSeconds); - } - - // At the same second, increase sequence - if (currentSecond == lastSecond) { - sequence = (sequence + 1) & bitsAllocator.getMaxSequence(); - // Exceed the max sequence, we wait the next second to generate uid - if (sequence == 0) { - currentSecond = getNextSecond(lastSecond); - } - - // At the different second, sequence restart from zero - } else { - sequence = 0L; - } - - lastSecond = currentSecond; - - // Allocate bits for UID - return bitsAllocator.allocate(currentSecond - epochSeconds, workerId, sequence); - } - - /** - * Get next millisecond - */ - private long getNextSecond(long lastTimestamp) { - long timestamp = getCurrentSecond(); - while (timestamp <= lastTimestamp) { - timestamp = getCurrentSecond(); - } - - return timestamp; - } - - /** - * Get current second - */ - private long getCurrentSecond() { - long currentSecond = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()); - if (currentSecond - epochSeconds > bitsAllocator.getMaxDeltaSeconds()) { - throw new UidGenerateException("Timestamp bits is exhausted. Refusing UID generate. Now: " + currentSecond); - } - - return currentSecond; - } - - /** - * Setters for spring property - */ - public void setWorkerIdAssigner(WorkerIdAssigner workerIdAssigner) { - this.workerIdAssigner = workerIdAssigner; - } - - public void setTimeBits(int timeBits) { - if (timeBits > 0) { - this.timeBits = timeBits; - } - } - - public void setWorkerBits(int workerBits) { - if (workerBits > 0) { - this.workerBits = workerBits; - } - } - - public void setSeqBits(int seqBits) { - if (seqBits > 0) { - this.seqBits = seqBits; - } - } - - public void setEpochStr(String epochStr) { - if (StringUtils.isNotBlank(epochStr)) { - this.epochStr = epochStr; - this.epochSeconds = TimeUnit.MILLISECONDS.toSeconds(DateUtils.parseByDayPattern(epochStr).getTime()); - } - } -} diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/utils/DateUtils.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/utils/DateUtils.java deleted file mode 100644 index cac10c7f93..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/utils/DateUtils.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package io.github.wujun728.uidgenerator.utils; - -import org.apache.commons.lang.time.DateFormatUtils; - -import java.text.ParseException; -import java.util.Calendar; -import java.util.Date; - -/** - * DateUtils provides date formatting, parsing - * - * - */ -public abstract class DateUtils extends org.apache.commons.lang.time.DateUtils { - /** - * Patterns - */ - public static final String DAY_PATTERN = "yyyy-MM-dd"; - public static final String DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss"; - public static final String DATETIME_MS_PATTERN = "yyyy-MM-dd HH:mm:ss.SSS"; - - public static final Date DEFAULT_DATE = DateUtils.parseByDayPattern("1970-01-01"); - - /** - * Parse date by 'yyyy-MM-dd' pattern - * - * @param str - * @return - */ - public static Date parseByDayPattern(String str) { - return parseDate(str, DAY_PATTERN); - } - - /** - * Parse date by 'yyyy-MM-dd HH:mm:ss' pattern - * - * @param str - * @return - */ - public static Date parseByDateTimePattern(String str) { - return parseDate(str, DATETIME_PATTERN); - } - - /** - * Parse date without Checked exception - * - * @param str - * @param pattern - * @return - * @throws RuntimeException when ParseException occurred - */ - public static Date parseDate(String str, String pattern) { - try { - return parseDate(str, new String[]{pattern}); - } catch (ParseException e) { - throw new RuntimeException(e); - } - } - - /** - * Format date into string - * - * @param date - * @param pattern - * @return - */ - public static String formatDate(Date date, String pattern) { - return DateFormatUtils.format(date, pattern); - } - - /** - * Format date by 'yyyy-MM-dd' pattern - * - * @param date - * @return - */ - public static String formatByDayPattern(Date date) { - if (date != null) { - return DateFormatUtils.format(date, DAY_PATTERN); - } else { - return null; - } - } - - /** - * Format date by 'yyyy-MM-dd HH:mm:ss' pattern - * - * @param date - * @return - */ - public static String formatByDateTimePattern(Date date) { - return DateFormatUtils.format(date, DATETIME_PATTERN); - } - - /** - * Get current day using format date by 'yyyy-MM-dd HH:mm:ss' pattern - * - * @return - */ - public static String getCurrentDayByDayPattern() { - Calendar cal = Calendar.getInstance(); - return formatByDayPattern(cal.getTime()); - } - -} diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/utils/DockerUtils.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/utils/DockerUtils.java deleted file mode 100644 index f2baf6e301..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/utils/DockerUtils.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package io.github.wujun728.uidgenerator.utils; - -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * DockerUtils - * - * - */ -public abstract class DockerUtils { - private static final Logger LOGGER = LoggerFactory.getLogger(DockerUtils.class); - - /** Environment param keys */ - private static final String ENV_KEY_HOST = "JPAAS_HOST"; - private static final String ENV_KEY_PORT = "JPAAS_HTTP_PORT"; - private static final String ENV_KEY_PORT_ORIGINAL = "JPAAS_HOST_PORT_8080"; - - /** Docker host & port */ - private static String DOCKER_HOST = ""; - private static String DOCKER_PORT = ""; - - /** Whether is docker */ - private static boolean IS_DOCKER; - - static { - retrieveFromEnv(); - } - - /** - * Retrieve docker host - * - * @return empty string if not a docker - */ - public static String getDockerHost() { - return DOCKER_HOST; - } - - /** - * Retrieve docker port - * - * @return empty string if not a docker - */ - public static String getDockerPort() { - return DOCKER_PORT; - } - - /** - * Whether a docker - * - * @return - */ - public static boolean isDocker() { - return IS_DOCKER; - } - - /** - * Retrieve host & port from environment - */ - private static void retrieveFromEnv() { - // retrieve host & port from environment - DOCKER_HOST = System.getenv(ENV_KEY_HOST); - DOCKER_PORT = System.getenv(ENV_KEY_PORT); - - // not found from 'JPAAS_HTTP_PORT', then try to find from 'JPAAS_HOST_PORT_8080' - if (StringUtils.isBlank(DOCKER_PORT)) { - DOCKER_PORT = System.getenv(ENV_KEY_PORT_ORIGINAL); - } - - boolean hasEnvHost = StringUtils.isNotBlank(DOCKER_HOST); - boolean hasEnvPort = StringUtils.isNotBlank(DOCKER_PORT); - - // docker can find both host & port from environment - if (hasEnvHost && hasEnvPort) { - IS_DOCKER = true; - - // found nothing means not a docker, maybe an actual machine - } else if (!hasEnvHost && !hasEnvPort) { - IS_DOCKER = false; - - } else { - LOGGER.error("Missing host or port from env for Docker. host:{}, port:{}", DOCKER_HOST, DOCKER_PORT); - throw new RuntimeException( - "Missing host or port from env for Docker. host:" + DOCKER_HOST + ", port:" + DOCKER_PORT); - } - } - -} diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/utils/EnumUtils.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/utils/EnumUtils.java deleted file mode 100644 index d42c9175b7..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/utils/EnumUtils.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package io.github.wujun728.uidgenerator.utils; - -import org.springframework.util.Assert; - -/** - * EnumUtils provides the operations for {@link ValuedEnum} such as Parse, value of... - * - * - */ -public abstract class EnumUtils { - - /** - * Parse the bounded value into ValuedEnum - * - * @param clz - * @param value - * @return - */ - public static , V> T parse(Class clz, V value) { - Assert.notNull(clz, "clz can not be null"); - if (value == null) { - return null; - } - - for (T t : clz.getEnumConstants()) { - if (value.equals(t.value())) { - return t; - } - } - return null; - } - - /** - * Null-safe valueOf function - * - * @param - * @param enumType - * @param name - * @return - */ - public static > T valueOf(Class enumType, String name) { - if (name == null) { - return null; - } - - return Enum.valueOf(enumType, name); - } - -} diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/utils/NamingThreadFactory.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/utils/NamingThreadFactory.java deleted file mode 100644 index 1a793f1824..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/utils/NamingThreadFactory.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package io.github.wujun728.uidgenerator.utils; - -import org.apache.commons.lang.ClassUtils; -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.lang.Thread.UncaughtExceptionHandler; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.atomic.AtomicLong; - -/** - * Named thread in ThreadFactory. If there is no specified name for thread, it - * will auto detect using the invoker classname instead. - * - * - */ -public class NamingThreadFactory implements ThreadFactory { - private static final Logger LOGGER = LoggerFactory.getLogger(NamingThreadFactory.class); - - /** - * Thread name pre - */ - private String name; - /** - * Is daemon thread - */ - private boolean daemon; - /** - * UncaughtExceptionHandler - */ - private UncaughtExceptionHandler uncaughtExceptionHandler; - /** - * Sequences for multi thread name prefix - */ - private final ConcurrentHashMap sequences; - - /** - * Constructors - */ - public NamingThreadFactory() { - this(null, false, null); - } - - public NamingThreadFactory(String name) { - this(name, false, null); - } - - public NamingThreadFactory(String name, boolean daemon) { - this(name, daemon, null); - } - - public NamingThreadFactory(String name, boolean daemon, UncaughtExceptionHandler handler) { - this.name = name; - this.daemon = daemon; - this.uncaughtExceptionHandler = handler; - this.sequences = new ConcurrentHashMap(); - } - - @Override - public Thread newThread(Runnable r) { - Thread thread = new Thread(r); - thread.setDaemon(this.daemon); - - // If there is no specified name for thread, it will auto detect using the invoker classname instead. - // Notice that auto detect may cause some performance overhead - String prefix = this.name; - if (StringUtils.isBlank(prefix)) { - prefix = getInvoker(2); - } - thread.setName(prefix + "-" + getSequence(prefix)); - - // no specified uncaughtExceptionHandler, just do logging. - if (this.uncaughtExceptionHandler != null) { - thread.setUncaughtExceptionHandler(this.uncaughtExceptionHandler); - } else { - thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { - public void uncaughtException(Thread t, Throwable e) { - LOGGER.error("unhandled exception in thread: " + t.getId() + ":" + t.getName(), e); - } - }); - } - - return thread; - } - - /** - * Get the method invoker's class name - * - * @param depth - * @return - */ - private String getInvoker(int depth) { - Exception e = new Exception(); - StackTraceElement[] stes = e.getStackTrace(); - if (stes.length > depth) { - return ClassUtils.getShortClassName(stes[depth].getClassName()); - } - return getClass().getSimpleName(); - } - - /** - * Get sequence for different naming prefix - * - * @param invoker - * @return - */ - private long getSequence(String invoker) { - AtomicLong r = this.sequences.get(invoker); - if (r == null) { - r = new AtomicLong(0); - AtomicLong previous = this.sequences.putIfAbsent(invoker, r); - if (previous != null) { - r = previous; - } - } - - return r.incrementAndGet(); - } - - /** - * Getters & Setters - */ - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public boolean isDaemon() { - return daemon; - } - - public void setDaemon(boolean daemon) { - this.daemon = daemon; - } - - public UncaughtExceptionHandler getUncaughtExceptionHandler() { - return uncaughtExceptionHandler; - } - - public void setUncaughtExceptionHandler(UncaughtExceptionHandler handler) { - this.uncaughtExceptionHandler = handler; - } - -} diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/utils/NetUtils.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/utils/NetUtils.java deleted file mode 100644 index bb8badae09..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/utils/NetUtils.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package io.github.wujun728.uidgenerator.utils; - -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.SocketException; -import java.util.Enumeration; - -/** - * NetUtils - * - * - */ -public abstract class NetUtils { - - /** - * Pre-loaded local address - */ - public static InetAddress localAddress; - - static { - try { - localAddress = getLocalInetAddress(); - } catch (SocketException e) { - throw new RuntimeException("fail to get local ip."); - } - } - - /** - * Retrieve the first validated local ip address(the Public and LAN ip addresses are validated). - * - * @return the local address - * @throws SocketException the socket exception - */ - public static InetAddress getLocalInetAddress() throws SocketException { - // enumerates all network interfaces - Enumeration enu = NetworkInterface.getNetworkInterfaces(); - - while (enu.hasMoreElements()) { - NetworkInterface ni = enu.nextElement(); - if (ni.isLoopback()) { - continue; - } - - Enumeration addressEnumeration = ni.getInetAddresses(); - while (addressEnumeration.hasMoreElements()) { - InetAddress address = addressEnumeration.nextElement(); - - // ignores all invalidated addresses - if (address.isLinkLocalAddress() || address.isLoopbackAddress() || address.isAnyLocalAddress()) { - continue; - } - - return address; - } - } - - throw new RuntimeException("No validated local address!"); - } - - /** - * Retrieve local address - * - * @return the string local address - */ - public static String getLocalAddress() { - return localAddress.getHostAddress(); - } - -} diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/utils/PaddedAtomicLong.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/utils/PaddedAtomicLong.java deleted file mode 100644 index b6df430dc0..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/utils/PaddedAtomicLong.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package io.github.wujun728.uidgenerator.utils; - -import java.util.concurrent.atomic.AtomicLong; - -/** - * Represents a padded {@link AtomicLong} to prevent the FalseSharing problem

        - * - * The CPU cache line commonly be 64 bytes, here is a sample of cache line after padding:
        - * 64 bytes = 8 bytes (object reference) + 6 * 8 bytes (padded long) + 8 bytes (a long value) - * - * - */ -public class PaddedAtomicLong extends AtomicLong { - private static final long serialVersionUID = -3415778863941386253L; - - /** Padded 6 long (48 bytes) */ - public volatile long p1, p2, p3, p4, p5, p6 = 7L; - - /** - * Constructors from {@link AtomicLong} - */ - public PaddedAtomicLong() { - super(); - } - - public PaddedAtomicLong(long initialValue) { - super(initialValue); - } - - /** - * To prevent GC optimizations for cleaning unused padded references - */ - public long sumPaddingToPreventOptimization() { - return p1 + p2 + p3 + p4 + p5 + p6; - } - -} \ No newline at end of file diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/utils/ValuedEnum.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/utils/ValuedEnum.java deleted file mode 100644 index 597e0405ae..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/utils/ValuedEnum.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package io.github.wujun728.uidgenerator.utils; - -/** - * {@code ValuedEnum} defines an enumeration which is bounded to a value, you - * may implements this interface when you defines such kind of enumeration, that - * you can use {@link EnumUtils} to simplify parse and valueOf operation. - * - * - */ -public interface ValuedEnum { - T value(); -} diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/worker/DisposableWorkerIdAssigner.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/worker/DisposableWorkerIdAssigner.java deleted file mode 100644 index 549b2264ba..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/worker/DisposableWorkerIdAssigner.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package io.github.wujun728.uidgenerator.worker; - -//import com.baidu.fsg.uid.worker.dao.WorkerNodeDAO; -import cn.hutool.extra.spring.SpringUtil; -import io.github.wujun728.uidgenerator.utils.DockerUtils; -import io.github.wujun728.uidgenerator.utils.NetUtils; -import io.github.wujun728.uidgenerator.worker.entity.WorkerNodeEntity; -import io.github.wujun728.uidgenerator.worker.repository.WorkerNodeResposity; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang.math.RandomUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.springframework.transaction.annotation.Transactional; - -import javax.annotation.Resource; - - -/** - * Represents an implementation of {@link WorkerIdAssigner}, - * the worker id will be discarded after assigned to the UidGenerator - * - * - */ -@Slf4j -@Component -public class DisposableWorkerIdAssigner implements WorkerIdAssigner { - -// @Autowired -// private WorkerNodeResposity workerNodeResposity; - -// @Resource -// private WorkerNodeDAO workerNodeDAO; - - /** - * Assign worker id base on database.

        - * If there is host name & port in the environment, we considered that the node runs in Docker container
        - * Otherwise, the node runs on an actual machine. - * - * @return assigned worker id - */ - @Transactional - public long assignWorkerId() { - // build worker node entity - WorkerNodeEntity workerNodeEntity = buildWorkerNode(); - - // add worker node for new (ignore the same IP + PORT) - // workerId可自定义实现,比如mysql自增主键,redis递增数,zk,uuid - WorkerNodeResposity workerNodeResposity = SpringUtil.getBean(WorkerNodeResposity.class); - workerNodeResposity.addWorkerNode(workerNodeEntity); - log.info("Add worker node:" + workerNodeEntity); - - return workerNodeEntity.getId(); - } - - /** - * Build worker node entity by IP and PORT - */ - private WorkerNodeEntity buildWorkerNode() { - WorkerNodeEntity workerNodeEntity = new WorkerNodeEntity(); - if (DockerUtils.isDocker()) { - workerNodeEntity.setType(WorkerNodeType.CONTAINER.value()); - workerNodeEntity.setHostName(DockerUtils.getDockerHost()); - workerNodeEntity.setPort(DockerUtils.getDockerPort()); - - } else { - workerNodeEntity.setType(WorkerNodeType.ACTUAL.value()); - workerNodeEntity.setHostName(NetUtils.getLocalAddress()); - workerNodeEntity.setPort(System.currentTimeMillis() + "-" + RandomUtils.nextInt(100000)); - } - - return workerNodeEntity; - } - -} diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/worker/WorkerIdAssigner.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/worker/WorkerIdAssigner.java deleted file mode 100644 index 555713fe95..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/worker/WorkerIdAssigner.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package io.github.wujun728.uidgenerator.worker; - - -import io.github.wujun728.uidgenerator.impl.DefaultUidGenerator; - -/** - * Represents a worker id assigner for {@link DefaultUidGenerator} - * - * - */ -public interface WorkerIdAssigner { - - /** - * Assign worker id for {@link DefaultUidGenerator} - * - * @return assigned worker id - */ - long assignWorkerId(); - -} diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/worker/WorkerNodeType.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/worker/WorkerNodeType.java deleted file mode 100644 index 0e692f1dde..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/worker/WorkerNodeType.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package io.github.wujun728.uidgenerator.worker; - - -import io.github.wujun728.uidgenerator.utils.ValuedEnum; - -/** - * WorkerNodeType - *

      • CONTAINER: Such as Docker - *
      • ACTUAL: Actual machine - * - * - */ -public enum WorkerNodeType implements ValuedEnum { - - CONTAINER(1), ACTUAL(2); - - /** - * Lock type - */ - private final Integer type; - - /** - * Constructor with field of type - */ - private WorkerNodeType(Integer type) { - this.type = type; - } - - @Override - public Integer value() { - return type; - } - -} diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/worker/dao/WorkerNodeDAO.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/worker/dao/WorkerNodeDAO.java deleted file mode 100644 index 682ec4913f..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/worker/dao/WorkerNodeDAO.java +++ /dev/null @@ -1,46 +0,0 @@ -///* -// * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. -// * -// * Licensed under the Apache License, Version 2.0 (the "License"); -// * you may not use this file except in compliance with the License. -// * You may obtain a copy of the License at -// * -// * http://www.apache.org/licenses/LICENSE-2.0 -// * -// * Unless required by applicable law or agreed to in writing, software -// * distributed under the License is distributed on an "AS IS" BASIS, -// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// * See the License for the specific language governing permissions and -// * limitations under the License. -// */ -//package io.github.wujun728.uidgenerator.worker.dao; -// -//import com.baidu.fsg.uid.worker.entity.WorkerNodeEntity; -//import org.apache.ibatis.annotations.Param; -//import org.springframework.stereotype.Repository; -// -///** -// * DAO for M_WORKER_NODE -// * -// * -// */ -//@Repository -//public interface WorkerNodeDAO { -// -// /** -// * Get {@link WorkerNodeEntity} by node host -// * -// * @param host -// * @param port -// * @return -// */ -// WorkerNodeEntity getWorkerNodeByHostPort(@Param("host") String host, @Param("port") String port); -// -// /** -// * Add {@link WorkerNodeEntity} -// * -// * @param workerNodeEntity -// */ -// void addWorkerNode(WorkerNodeEntity workerNodeEntity); -// -//} diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/worker/entity/WorkerNodeEntity.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/worker/entity/WorkerNodeEntity.java deleted file mode 100644 index 374e129f1f..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/worker/entity/WorkerNodeEntity.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package io.github.wujun728.uidgenerator.worker.entity; - -import io.github.wujun728.uidgenerator.worker.WorkerNodeType; -import org.apache.commons.lang.builder.ReflectionToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; - -import java.util.Date; - -/** - * Entity for M_WORKER_NODE - * - * - */ -public class WorkerNodeEntity { - - /** - * Entity unique id (table unique) - */ - private long id; - - /** - * Type of CONTAINER: HostName, ACTUAL : IP. - */ - private String hostName; - - /** - * Type of CONTAINER: Port, ACTUAL : Timestamp + Random(0-10000) - */ - private String port; - - /** - * type of {@link WorkerNodeType} - */ - private int type; - - /** - * Worker launch date, default now - */ - private Date launchDate = new Date(); - - /** - * Created time - */ - private Date created; - - /** - * Last modified - */ - private Date modified; - - /** - * Getters & Setters - */ - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getHostName() { - return hostName; - } - - public void setHostName(String hostName) { - this.hostName = hostName; - } - - public String getPort() { - return port; - } - - public void setPort(String port) { - this.port = port; - } - - public int getType() { - return type; - } - - public void setType(int type) { - this.type = type; - } - - public Date getLaunchDate() { - return launchDate; - } - - public void setLaunchDateDate(Date launchDate) { - this.launchDate = launchDate; - } - - public Date getCreated() { - return created; - } - - public void setCreated(Date created) { - this.created = created; - } - - public Date getModified() { - return modified; - } - - public void setModified(Date modified) { - this.modified = modified; - } - - @Override - public String toString() { - return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); - } - -} diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/worker/repository/DbWorkerNodeResposity.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/worker/repository/DbWorkerNodeResposity.java deleted file mode 100644 index e8bb7d8b0a..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/worker/repository/DbWorkerNodeResposity.java +++ /dev/null @@ -1,95 +0,0 @@ -package io.github.wujun728.uidgenerator.worker.repository; - -import io.github.wujun728.uidgenerator.worker.entity.WorkerNodeEntity; -import org.springframework.dao.DataAccessException; -import org.springframework.jdbc.BadSqlGrammarException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.PreparedStatementCreator; -import org.springframework.jdbc.support.GeneratedKeyHolder; -import org.springframework.jdbc.support.KeyHolder; -import org.springframework.stereotype.Repository; - -import java.sql.PreparedStatement; -import java.sql.Statement; -import java.util.Objects; - -@Repository -public class DbWorkerNodeResposity implements WorkerNodeResposity { - private static final String GET_WORKER_NODE_BY_HOST_PORT_SQL = "SELECT ID,HOST_NAME,PORT,TYPE,LAUNCH_DATE,MODIFIED,CREATED FROM worker_node WHERE HOST_NAME = ? AND PORT = ?"; - private static final String ADD_WORKER_NODE_SQL = "INSERT INTO worker_node (HOST_NAME,PORT,TYPE,LAUNCH_DATE,MODIFIED,CREATED) VALUES (?,?,?,?,NOW(),NOW())"; - private static final String DROP_WORKER_NODE_SQL = "DROP TABLE IF EXISTS `worker_node`"; - private static final String CREATE_WORKER_NODE_SQL = "CREATE TABLE `worker_node` (\n" + - " `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'auto increment id',\n" + - " `HOST_NAME` varchar(64) COLLATE utf8mb4_german2_ci NOT NULL COMMENT 'host name',\n" + - " `PORT` varchar(64) COLLATE utf8mb4_german2_ci NOT NULL COMMENT 'port',\n" + - " `TYPE` int(11) NOT NULL COMMENT 'node type: ACTUAL or CONTAINER',\n" + - " `LAUNCH_DATE` date NOT NULL COMMENT 'launch date',\n" + - " `MODIFIED` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'modified time',\n" + - " `CREATED` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'created time',\n" + - " PRIMARY KEY (`ID`) USING BTREE\n" + - ") ENGINE=InnoDB AUTO_INCREMENT=269 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_german2_ci COMMENT='DB WorkerID Assigner for UID Generator'"; - - private final JdbcTemplate jdbcTemplate; - - public DbWorkerNodeResposity(JdbcTemplate jdbcTemplate) { - this.jdbcTemplate = jdbcTemplate; - } - - /** - * @param host - * @param port - * @return - */ - @Override - public WorkerNodeEntity getWorkerNodeByHostPort(String host, String port) { - return this.jdbcTemplate.queryForObject(GET_WORKER_NODE_BY_HOST_PORT_SQL, (rs, rowNum) -> { - WorkerNodeEntity entity = new WorkerNodeEntity(); - entity.setId(rs.getLong("ID")); - entity.setHostName(rs.getString("HOST_NAME")); - entity.setPort(rs.getString("PORT")); - entity.setType(rs.getInt("TYPE")); - entity.setLaunchDateDate(rs.getDate("LAUNCH_DATE")); - entity.setModified(rs.getTimestamp("MODIFIED")); - entity.setCreated(rs.getTime("CREATED")); - return entity; - }, new String[]{host, port}); - } - - /** - * Add {@link WorkerNodeEntity} - * - * @param entity - */ - @Override - public void addWorkerNode(WorkerNodeEntity entity) { - WorkerNodeEntity nodeEntity= getWorkerNodeByHostPort(entity.getHostName(), entity.getPort()); - if(nodeEntity!=null && nodeEntity.getId()>0){ - entity.setId(nodeEntity.getId()); - }else{ - try { - KeyHolder keyHolder = new GeneratedKeyHolder(); - PreparedStatementCreator preparedStatementCreator = con -> { - PreparedStatement ps = con.prepareStatement(ADD_WORKER_NODE_SQL, Statement.RETURN_GENERATED_KEYS); - ps.setString(1, entity.getHostName()); - ps.setString(2, entity.getPort()); - ps.setInt(3, entity.getType()); - ps.setObject(4, entity.getLaunchDate()); - return ps; - }; - this.jdbcTemplate.update(preparedStatementCreator, keyHolder); - entity.setId(Objects.requireNonNull(keyHolder.getKey()).longValue()); - } catch (BadSqlGrammarException e) { - if(e.getMessage().contains("doesn't exist")){ - this.jdbcTemplate.update(DROP_WORKER_NODE_SQL); - this.jdbcTemplate.update(CREATE_WORKER_NODE_SQL); - this.addWorkerNode(entity);//如果表没有,见建表 - }else{ - e.printStackTrace(); - } - }catch (Exception e){ - e.printStackTrace(); - } - } - } - -} diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/worker/repository/WorkerNodeResposity.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/worker/repository/WorkerNodeResposity.java deleted file mode 100644 index e0b28643fb..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/java/io/github/wujun728/uidgenerator/worker/repository/WorkerNodeResposity.java +++ /dev/null @@ -1,10 +0,0 @@ -package io.github.wujun728.uidgenerator.worker.repository; - - -import io.github.wujun728.uidgenerator.worker.entity.WorkerNodeEntity; - -public interface WorkerNodeResposity { - WorkerNodeEntity getWorkerNodeByHostPort(String host, String port); - - void addWorkerNode(WorkerNodeEntity entity); -} diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/resources/META-INF/spring.factories.bk b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/resources/META-INF/spring.factories.bk deleted file mode 100644 index 4909933e5f..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/resources/META-INF/spring.factories.bk +++ /dev/null @@ -1,2 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -io.github.wujun728.uidgenerator.config.UidAutoConfig \ No newline at end of file diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/resources/META-INF/spring/spring-boot/starters/spring-boot-starter-uid.properties b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/resources/META-INF/spring/spring-boot/starters/spring-boot-starter-uid.properties deleted file mode 100644 index df93932ac9..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/resources/META-INF/spring/spring-boot/starters/spring-boot-starter-uid.properties +++ /dev/null @@ -1,3 +0,0 @@ -spring.boot.starter.group=io.github.wujun728.uidgenerator -spring.boot.starter.artifact=jun-uidgenerator-spring-boot-starter -spring.boot.starter.version=1.0.8 \ No newline at end of file diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/resources/application.yml b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/resources/application.yml deleted file mode 100644 index 251ff05fd6..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/main/resources/application.yml +++ /dev/null @@ -1,20 +0,0 @@ -server: - tomcat: - threads: - max: 200 - min-spare: 100 - accept-count: 100 -spring: - datasource: - driver-class-name: com.mysql.cj.jdbc.Driver - url: jdbc:mysql://127.0.0.1:3306/db_test666?useSSL=false&characterEncoding=UTF-8&allowMultiQueries=true - username: root - password: -uid: - gen: - boostPower: 3 - epochStr: '2023-11-27' - scheduleInterval: 60 - seqBits: 12 #单机4096并发' - timeBits: 31 #运行时长约68年' - workerBits: 20 #1048576次机器启动 整个配置支持5个节点,重启频率6/天,以4000并发持续运行68年,id用尽后会重复,必须调整epochStr及重启服务' diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/test/java/io/github/wujun728/uidgenerator/CachedUidGeneratorTest.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/test/java/io/github/wujun728/uidgenerator/CachedUidGeneratorTest.java deleted file mode 100644 index 9bf77a3b0d..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/test/java/io/github/wujun728/uidgenerator/CachedUidGeneratorTest.java +++ /dev/null @@ -1,125 +0,0 @@ -package io.github.wujun728.uidgenerator; - -import io.github.wujun728.uidgenerator.UidGenerator; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang.StringUtils; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import javax.annotation.Resource; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.ConcurrentSkipListSet; -import java.util.concurrent.atomic.AtomicInteger; - -@RunWith(SpringJUnit4ClassRunner.class) -@Slf4j -@SpringBootTest(properties = {"test.prop=testValue2"}) -public class CachedUidGeneratorTest { - private static final int SIZE = 7000000; // 700w - private static final boolean VERBOSE = false; - private static final int THREADS = Runtime.getRuntime().availableProcessors() << 1; - - @Resource - private UidGenerator uidGenerator; - - /** - * Test for serially generate - * - * @throws IOException - */ - @Test - public void testSerialGenerate() throws IOException { - // Generate UID serially - Set uidSet = new HashSet<>(SIZE); - for (int i = 0; i < SIZE; i++) { - doGenerate(uidSet, i); - } - - // Check UIDs are all unique - checkUniqueID(uidSet); - } - - /** - * Test for parallel generate - * - * @throws InterruptedException - * @throws IOException - */ - @Test - public void testParallelGenerate() throws InterruptedException, IOException { - AtomicInteger control = new AtomicInteger(-1); - Set uidSet = new ConcurrentSkipListSet<>(); - - // Initialize threads - List threadList = new ArrayList<>(THREADS); - for (int i = 0; i < THREADS; i++) { - Thread thread = new Thread(() -> workerRun(uidSet, control)); - thread.setName("UID-generator-" + i); - - threadList.add(thread); - thread.start(); - } - - // Wait for worker done - for (Thread thread : threadList) { - thread.join(); - } - - // Check generate 700w times - Assert.assertEquals(SIZE, control.get()); - - // Check UIDs are all unique - checkUniqueID(uidSet); - } - - /** - * Woker run - */ - private void workerRun(Set uidSet, AtomicInteger control) { - for (;;) { - int myPosition = control.updateAndGet(old -> (old == SIZE ? SIZE : old + 1)); - if (myPosition == SIZE) { - return; - } - - doGenerate(uidSet, myPosition); - } - } - - /** - * Do generating - */ - private void doGenerate(Set uidSet, int index) { - long uid = uidGenerator.getUID(); - String parsedInfo = uidGenerator.parseUID(uid); - boolean existed = !uidSet.add(uid); - if (existed) { - System.out.println("Found duplicate UID " + uid); - } - - // Check UID is positive, and can be parsed - Assert.assertTrue(uid > 0L); - Assert.assertTrue(StringUtils.isNotBlank(parsedInfo)); - - if (VERBOSE) { - System.out.println(Thread.currentThread().getName() + " No." + index + " >>> " + parsedInfo); - } - } - - /** - * Check UIDs are all unique - */ - private void checkUniqueID(Set uidSet) throws IOException { - System.out.println(uidSet.size()); - Assert.assertEquals(SIZE, uidSet.size()); - } - -} diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/test/java/io/github/wujun728/uidgenerator/DefaultUidGeneratorTest.java b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/test/java/io/github/wujun728/uidgenerator/DefaultUidGeneratorTest.java deleted file mode 100644 index 5138aa4aec..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/test/java/io/github/wujun728/uidgenerator/DefaultUidGeneratorTest.java +++ /dev/null @@ -1,119 +0,0 @@ -package io.github.wujun728.uidgenerator; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.ConcurrentSkipListSet; -import java.util.concurrent.atomic.AtomicInteger; - -import javax.annotation.Resource; - -import io.github.wujun728.uidgenerator.UidGenerator; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang.StringUtils; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@Slf4j -@SpringBootTest(properties = {"test.prop=testValue2"}) -public class DefaultUidGeneratorTest { - private static final int SIZE = 100000; // 10w - private static final boolean VERBOSE = true; - private static final int THREADS = Runtime.getRuntime().availableProcessors() << 1; - - @Resource - private UidGenerator uidGenerator; - - /** - * Test for serially generate - */ - @Test - public void testSerialGenerate() { - // Generate UID serially - Set uidSet = new HashSet<>(SIZE); - for (int i = 0; i < SIZE; i++) { - doGenerate(uidSet, i); - } - - // Check UIDs are all unique - checkUniqueID(uidSet); - } - - /** - * Test for parallel generate - * - * @throws InterruptedException - */ - @Test - public void testParallelGenerate() throws InterruptedException { - AtomicInteger control = new AtomicInteger(-1); - Set uidSet = new ConcurrentSkipListSet<>(); - - // Initialize threads - List threadList = new ArrayList<>(THREADS); - for (int i = 0; i < THREADS; i++) { - Thread thread = new Thread(() -> workerRun(uidSet, control)); - thread.setName("UID-generator-" + i); - - threadList.add(thread); - thread.start(); - } - - // Wait for worker done - for (Thread thread : threadList) { - thread.join(); - } - - // Check generate 10w times - Assert.assertEquals(SIZE, control.get()); - - // Check UIDs are all unique - checkUniqueID(uidSet); - } - - /** - * Worker run - */ - private void workerRun(Set uidSet, AtomicInteger control) { - for (;;) { - int myPosition = control.updateAndGet(old -> (old == SIZE ? SIZE : old + 1)); - if (myPosition == SIZE) { - return; - } - - doGenerate(uidSet, myPosition); - } - } - - /** - * Do generating - */ - private void doGenerate(Set uidSet, int index) { - long uid = uidGenerator.getUID(); - String parsedInfo = uidGenerator.parseUID(uid); - uidSet.add(uid); - - // Check UID is positive, and can be parsed - Assert.assertTrue(uid > 0L); - Assert.assertTrue(StringUtils.isNotBlank(parsedInfo)); - - if (VERBOSE) { - System.out.println(Thread.currentThread().getName() + " No." + index + " >>> " + parsedInfo); - } - } - - /** - * Check UIDs are all unique - */ - private void checkUniqueID(Set uidSet) { - System.out.println(uidSet.size()); - Assert.assertEquals(SIZE, uidSet.size()); - } - -} diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/test/resources/uid/cached-uid-spring.xml b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/test/resources/uid/cached-uid-spring.xml deleted file mode 100644 index 7f81032f36..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/test/resources/uid/cached-uid-spring.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/test/resources/uid/default-uid-spring.xml b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/test/resources/uid/default-uid-spring.xml deleted file mode 100644 index 188be7f269..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/test/resources/uid/default-uid-spring.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/test/resources/uid/mybatis-spring.xml b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/test/resources/uid/mybatis-spring.xml deleted file mode 100644 index 6339e9e5f7..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/test/resources/uid/mybatis-spring.xml +++ /dev/null @@ -1,80 +0,0 @@ - - - - - - - - - - - - classpath:/uid/*.properties - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/test/resources/uid/mysql.properties b/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/test/resources/uid/mysql.properties deleted file mode 100644 index 98a4927308..0000000000 --- a/jun_springboot_starter/jun-uidgenerator-spring-boot-starter/src/test/resources/uid/mysql.properties +++ /dev/null @@ -1,23 +0,0 @@ -#datasource db info -mysql.driver=com.mysql.jdbc.Driver -jdbc.url=jdbc:mysql://localhost:xxxx/xxxx -jdbc.username=xxxx -jdbc.password=xxxx -jdbc.maxActive=2 - -#datasource base -datasource.defaultAutoCommit=true -datasource.initialSize=2 -datasource.minIdle=0 -datasource.maxWait=5000 -datasource.testWhileIdle=true -datasource.testOnBorrow=true -datasource.testOnReturn=false -datasource.validationQuery=SELECT 1 FROM DUAL -datasource.timeBetweenEvictionRunsMillis=30000 -datasource.minEvictableIdleTimeMillis=60000 -datasource.logAbandoned=true -datasource.removeAbandoned=true -datasource.removeAbandonedTimeout=120 -datasource.filters=stat - diff --git a/jun_springboot_starter/pom.xml b/jun_springboot_starter/pom.xml deleted file mode 100644 index ff422e7ee5..0000000000 --- a/jun_springboot_starter/pom.xml +++ /dev/null @@ -1,650 +0,0 @@ - - 4.0.0 - - io.github.wujun728 - jun_springboot_starter - 1.0.25 - pom - - jun_springcloud_starter - https://github.com/wujun728/jun_java_plugin/jjun_springcloud_starter - SpringBoot-SpirngCloud通用组件、工具、stater - - - jun-activerecord - jun-mybatis-sql-engine - jun-db-activerecord - jun-common-base - jun-groovy-api - jun-groovy-api-spring-boot-starter - jun-uidgenerator-spring-boot-starter - jun-onlineForm-spring-boot-starter - jun-snakerflow-spring-boot-starter - jun-db-spring-boot-starter - jun-log-spring-boot-starter - jun-oss-spring-boot-starter - jun-swagger2-spring-boot-starter - jun-sentinel-spring-boot-starter - jun-job-spring-boot-starter - jun-encrypt-body-spring-boot-starter - jun-minio-spring-boot-starter - - - - - 1.0.25 - 1.8 - 1.8 - UTF-8 - 8 - 1.3.2 - 2021.1 - 2.5.14 - 2020.0.6 - 4.4 - 2.0.1 - 0.9.1 - 1.2.6 - - 3.1.0 - 2.3.8.RELEASE - 1.1.0.RELEASE - 3.16.1 - 1.6.2 - 5.8.25 - 3.5.7 - 3.8.1 - 7.2.28 - 4.1.3 - 4.1.1 - 2.5.6 - 1.7 - 2.7 - 5.0.2.RELEASE - 1.27.2 - 1.21 - 2.12.1 - 1.0.2 - 1.9.4 - 1.1.6.RELEASE - 2.7 - 4.0.1 - 4.2.3 - 7.13.4 - 2.0.5 - 6.2.0.Final - 2.7.8 - 5.1.0 - 2.13.4 - 1.10 - 2.2.9.RELEASE - 1.12.40 - 2.2.5.RELEASE - 1.2.2 - jun-job/**/*, jun-register/**/*, jun-web/**/* - openjdk:8-jre-alpine - /tmp - hub.docker.com:8080/jun-microservices - -Djava.security.egd=file:/dev/./urandom - -Xms128m -Xmx128m - 33.2.1-jre - - - - - - - - - - io.github.wujun728 - jun-db-activerecord - ${jun.version} - - - io.github.wujun728 - jun-uidgenerator-spring-boot-starter - ${jun.version} - - - io.github.wujun728 - jun-mybatis-sql-engine - ${jun.version} - - - io.github.wujun728 - jun-groovy-api-spring-boot-starter - ${jun.version} - - - io.github.wujun728 - jun-groovy-api - ${jun.version} - - - io.github.wujun728 - jun-common-base - ${jun.version} - - - io.github.wujun728 - jun-db-spring-boot-starter - ${jun.version} - - - io.github.wujun728 - jun-log-spring-boot-starter - ${jun.version} - - - io.github.wujun728 - jun-redis-spring-boot-starter - ${jun.version} - - - io.github.wujun728 - jun-swagger2-spring-boot-starter - ${jun.version} - - - io.github.wujun728 - jun-loadbalancer-spring-boot-starter - ${jun.version} - - - io.github.wujun728 - jun-auth-client-spring-boot-starter - ${jun.version} - - - io.github.wujun728 - jun-sentinel-spring-boot-starter - ${jun.version} - - - io.github.wujun728 - jun-config - ${jun.version} - - - io.github.wujun728 - jun-elasticsearch-spring-boot-starter - ${jun.version} - - - io.github.wujun728 - jun-oss-spring-boot-starter - ${project.version} - - - io.github.wujun728 - jun-zookeeper-spring-boot-starter - ${project.version} - - - io.github.wujun728 - search-client - ${project.version} - - - - javax.annotation - javax.annotation-api - ${javax.annotation-api.version} - - - io.jsonwebtoken - jjwt - ${jjwt.version} - - - - com.alibaba - druid-spring-boot-starter - ${druid-starter} - - - - com.baomidou - mybatis-plus-boot-starter - ${mybatis-plus-boot-starter.version} - - - com.baomidou - mybatis-plus-extension - ${mybatis-plus-boot-starter.version} - - - com.baomidou - mybatis-plus - ${mybatis-plus-boot-starter.version} - - - com.baomidou - mybatis-plus-generator - ${mybatis-plus-boot-starter.version} - - - com.baomidou - mybatis-plus-core - ${mybatis-plus-boot-starter.version} - - - - org.springframework.security.oauth - spring-security-oauth2 - ${security-oauth2.version} - - - org.springframework.security - spring-security-jwt - ${security-jwt.version} - - - - org.redisson - redisson-spring-boot-starter - ${redisson-starter.version} - - - - com.github.zlt2000 - swagger-butler-core - ${swagger.butler.version} - - - - com.github.whvcse - easy-captcha - ${easyCaptcha.version} - - - - cn.hutool - hutool-all - ${hutool.version} - - - com.aliyun.oss - aliyun-sdk-oss - ${aliyun-sdk-oss} - - - - com.qiniu - qiniu-java-sdk - ${qiniu-java-sdk} - - - org.apache.poi - poi - ${poi.version} - - - org.apache.poi - poi-ooxml - ${poi.version} - - - - cn.afterturn - easypoi-base - ${easypoi.version} - - - de.codecentric - spring-boot-admin-starter-server - ${spring-boot-admin.version} - - - org.apache.velocity - velocity - ${velocity.version} - - - org.apache.commons - commons-configuration2 - ${commons-configuration2.version} - - - com.codingapi.txlcn - txlcn-tm - ${txlcn.version} - - - com.codingapi.txlcn - txlcn-tc - ${txlcn.version} - - - com.codingapi.txlcn - txlcn-txmsg-netty - ${txlcn.version} - - - io.shardingsphere - sharding-jdbc-spring-boot-starter - ${sharding-sphere.version} - - - com.github.tobato - fastdfs-client - ${fastdfs-client.version} - - - eu.bitwalker - UserAgentUtils - ${userAgent.version} - - - com.alibaba - transmittable-thread-local - ${transmittable.version} - - - com.nepxion - banner - ${banner.version} - - - org.springframework.social - spring-social-security - ${spring-social-security.version} - - - commons-io - commons-io - ${commons-io.version} - - - javax.servlet - javax.servlet-api - ${servlet-api.version} - - - org.springframework.data - spring-data-elasticsearch - ${spring-data-elasticsearch.version} - - - org.elasticsearch.client - elasticsearch-rest-high-level-client - ${elasticsearch.version} - - - org.elasticsearch - elasticsearch-x-content - ${elasticsearch.version} - - - org.elasticsearch.client - elasticsearch-rest-client - ${elasticsearch.version} - - - org.elasticsearch - elasticsearch - ${elasticsearch.version} - - - com.github.xiaoymin - knife4j-spring-boot-starter - ${knife4j.version} - - - com.github.xiaoymin - knife4j-micro-spring-boot-starter - ${knife4j.version} - - - org.hibernate - hibernate-validator - ${hibernate-validator.version} - - - org.apache.dubbo - dubbo - ${dubbo.version} - - - org.apache.curator - curator-recipes - ${curator.version} - - - org.apache.curator - curator-framework - ${curator.version} - - - com.fasterxml.jackson.core - jackson-databind - ${jackson-databind.version} - - - org.springframework.cloud - spring-cloud-starter-oauth2 - ${spring-cloud-starter-oauth2.version} - - - com.amazonaws - aws-java-sdk-s3 - ${aws-java-sdk-s3.version} - - - org.springframework.cloud - spring-cloud-starter-netflix-zuul - ${zuul.version} - - - commons-configuration - commons-configuration - ${commons-configuration.version} - - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot-dependencies.version} - pom - import - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud-dependencies.version} - pom - import - - - com.alibaba.cloud - spring-cloud-alibaba-dependencies - ${spring-cloud-alibaba-dependencies.version} - pom - import - - - com.google.guava - guava - ${guava.version} - - - com.fasterxml.jackson.core - jackson-core - ${jackson-databind.version} - - - com.jfinal - activerecord - 5.1.2 - - - com.jfinal - enjoy - 5.1.2 - - - org.freemarker - freemarker - 2.3.32 - - - com.alibaba.fastjson2 - fastjson2 - 2.0.37 - - - com.mysql - mysql-connector-j - 8.0.33 - runtime - - - com.alibaba - druid - 1.2.16 - - - dom4j - dom4j - 1.6.1 - - - ognl - ognl - 2.7.3 - - - - org.apache.commons - commons-lang3 - 3.10 - - - junit - junit - 4.12 - test - - - cn.hutool - hutool-all - 5.8.21 - compile - - - - net.dreamlu - mica-auto - 2.3.2 - - - - - - - - - - oss - https://s01.oss.sonatype.org/content/repositories/snapshots - - - oss - https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/ - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.1 - - 1.8 - 1.8 - UTF-8 - - - - - - - - - - - wujun728 - wujun728@163.com - https://github.com/wujun728 - - - - - https://github.com/wujun728/jun-spring-boot-starter.git - scm:git:github.com/wujun728/jun-spring-boot-starter.git - scm:git:github.com/wujun728/jun-spring-boot-starter.git - - - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - \ No newline at end of file diff --git a/jun_springboot_starter/pom2.xml b/jun_springboot_starter/pom2.xml deleted file mode 100644 index e9ebd7e9fd..0000000000 --- a/jun_springboot_starter/pom2.xml +++ /dev/null @@ -1,92 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_springboot_starter - 1.0.20 - - pom - - - UTF-8 - 1.8 - 1.8 - - - - - - - - - - - - org.springframework.boot - spring-boot-devtools - runtime - true - - - - - - - - - org.springframework.boot - spring-boot-dependencies - - - - 2.5.14 - pom - import - - - - - - - jdk-1.8 - - true - 1.8 - - - 1.8 - 1.8 - 1.8 - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.0 - - 1.8 - 1.8 - - - - - \ No newline at end of file diff --git a/jun_springboot_starter/replay_pid8756.log b/jun_springboot_starter/replay_pid8756.log deleted file mode 100644 index 4009a43a0d..0000000000 --- a/jun_springboot_starter/replay_pid8756.log +++ /dev/null @@ -1,5517 +0,0 @@ -JvmtiExport can_access_local_variables 0 -JvmtiExport can_hotswap_or_post_breakpoint 0 -JvmtiExport can_post_on_exceptions 0 -# 280 ciObject found -instanceKlass org/apache/maven/artifact/handler/DefaultArtifactHandler$__sisu14$$FastClassByGuice$$325591648 -instanceKlass org/codehaus/plexus/archiver/zip/AsiExtraField -instanceKlass org/codehaus/plexus/archiver/UnixStat -instanceKlass org/codehaus/plexus/archiver/zip/ExtraFieldUtils -instanceKlass org/codehaus/plexus/archiver/zip/ZipExtraField -instanceKlass org/codehaus/plexus/archiver/util/ResourceUtils -instanceKlass org/codehaus/plexus/archiver/zip/ZipShort -instanceKlass org/codehaus/plexus/archiver/jar/JdkManifestFactory -instanceKlass org/codehaus/plexus/util/IOUtil -instanceKlass org/codehaus/plexus/archiver/zip/ZipLong -instanceKlass org/codehaus/plexus/util/StringUtils -instanceKlass org/codehaus/plexus/archiver/jar/Manifest$Section -instanceKlass org/apache/maven/archiver/ManifestConfiguration -instanceKlass org/codehaus/plexus/components/io/resources/AbstractPlexusIoResource -instanceKlass org/codehaus/plexus/components/io/resources/PlexusIoResourceWithAttributes -instanceKlass org/codehaus/plexus/util/Os -instanceKlass org/codehaus/plexus/util/SelectorUtils -instanceKlass org/codehaus/plexus/util/MatchPattern -instanceKlass org/codehaus/plexus/util/MatchPatterns -instanceKlass org/codehaus/plexus/archiver/AbstractArchiver$1 -instanceKlass org/codehaus/plexus/util/cli/StreamConsumer -instanceKlass org/codehaus/plexus/components/io/attributes/PlexusIoResourceAttributeUtils -instanceKlass org/codehaus/plexus/archiver/util/AbstractFileSet -instanceKlass org/codehaus/plexus/util/AbstractScanner -instanceKlass org/codehaus/plexus/util/Scanner -instanceKlass org/codehaus/plexus/util/io/InputStreamFacade -instanceKlass org/codehaus/plexus/util/FileUtils -instanceKlass org/codehaus/plexus/interpolation/RecursionInterceptor -instanceKlass org/codehaus/plexus/interpolation/Interpolator -instanceKlass org/codehaus/plexus/archiver/jar/Manifest$BaseAttribute -instanceKlass org/codehaus/plexus/archiver/manager/DefaultArchiverManager$$FastClassByGuice$$324017995 -instanceKlass org/codehaus/plexus/archiver/jar/JarArchiver$$FastClassByGuice$$323627938 -instanceKlass org/apache/maven/plugin/source/SourceJarNoForkMojo$$FastClassByGuice$$322775282 -instanceKlass org/codehaus/plexus/archiver/manager/DefaultArchiverManager -instanceKlass org/codehaus/plexus/archiver/filters/JarSecurityFileSelector -instanceKlass org/codehaus/plexus/archiver/tar/TarArchiver$TarOptions -instanceKlass org/codehaus/plexus/components/io/fileselectors/IncludeExcludeFileSelector -instanceKlass org/codehaus/plexus/archiver/bzip2/BZip2Constants -instanceKlass org/codehaus/plexus/components/interactivity/DefaultOutputHandler -instanceKlass org/codehaus/plexus/components/io/filemappers/AbstractFileMapper -instanceKlass org/codehaus/plexus/components/interactivity/DefaultPrompter -instanceKlass org/codehaus/plexus/components/io/fileselectors/AllFilesFileSelector -instanceKlass org/codehaus/plexus/components/io/attributes/FileAttributes -instanceKlass org/codehaus/plexus/components/io/attributes/PlexusIoResourceAttributes -instanceKlass org/codehaus/plexus/components/io/resources/PlexusIOResourceCollectionWithAttributes -instanceKlass org/codehaus/plexus/archiver/zip/ZipFile -instanceKlass org/codehaus/plexus/archiver/ArchiveFile$Entry -instanceKlass org/codehaus/plexus/components/io/resources/PlexusIoCompressedFileResourceCollection -instanceKlass org/codehaus/plexus/archiver/ArchiveEntry -instanceKlass org/codehaus/plexus/archiver/ResourceIterator -instanceKlass org/codehaus/plexus/archiver/FileSet -instanceKlass org/codehaus/plexus/archiver/ArchivedFileSet -instanceKlass org/codehaus/plexus/archiver/BaseFileSet -instanceKlass org/codehaus/plexus/archiver/util/EnumeratedAttribute -instanceKlass org/codehaus/plexus/archiver/ArchiveFinalizer -instanceKlass org/codehaus/plexus/archiver/util/FilterSupport -instanceKlass org/codehaus/plexus/archiver/tar/TarFile -instanceKlass org/codehaus/plexus/archiver/ArchiveFile -instanceKlass org/codehaus/plexus/components/io/resources/PlexusIoResource -instanceKlass org/codehaus/plexus/components/io/fileselectors/FileInfo -instanceKlass org/codehaus/plexus/components/io/resources/AbstractPlexusIoResourceCollection -instanceKlass org/codehaus/plexus/components/io/resources/PlexusIoArchivedResourceCollection -instanceKlass org/apache/maven/archiver/MavenArchiver -instanceKlass org/apache/maven/archiver/MavenArchiveConfiguration -instanceKlass org/codehaus/plexus/archiver/FinalizerEnabled -instanceKlass org/codehaus/plexus/archiver/FilterEnabled -instanceKlass org/codehaus/plexus/components/io/filemappers/FileMapper -instanceKlass org/codehaus/plexus/components/io/resources/PlexusIoResourceCollection -instanceKlass org/codehaus/plexus/components/io/fileselectors/FileSelector -instanceKlass org/codehaus/plexus/archiver/manager/ArchiverManager -instanceKlass org/codehaus/plexus/archiver/UnArchiver -instanceKlass org/codehaus/plexus/archiver/Archiver -instanceKlass org/codehaus/plexus/components/interactivity/Prompter -instanceKlass org/codehaus/plexus/components/interactivity/OutputHandler -instanceKlass org/codehaus/plexus/components/interactivity/InputHandler -instanceKlass org/apache/commons/compress/archivers/zip/ScatterZipOutputStream$ZipEntryWriter -instanceKlass java/util/concurrent/ConcurrentLinkedDeque$AbstractItr -instanceKlass org/apache/commons/compress/archivers/zip/ZipArchiveOutputStream$EntryMetaData -instanceKlass org/apache/commons/compress/archivers/zip/ZipArchiveOutputStream$CurrentEntry -instanceKlass org/apache/commons/compress/archivers/zip/ExtraFieldUtils$UnparseableExtraField -instanceKlass java/util/concurrent/ConcurrentLinkedQueue$Itr -instanceKlass org/apache/commons/compress/archivers/zip/ParallelScatterZipCreator$$Lambda$485 -instanceKlass org/codehaus/plexus/archiver/zip/ConcurrentJarCreator$$Lambda$484 -instanceKlass org/apache/commons/compress/archivers/zip/ZipArchiveEntryRequestSupplier -instanceKlass org/codehaus/plexus/archiver/zip/AbstractZipArchiver$$Lambda$483 -instanceKlass org/codehaus/plexus/archiver/util/ResourceUtils -instanceKlass org/codehaus/plexus/archiver/zip/ConcurrentJarCreator$$Lambda$482 -instanceKlass org/codehaus/plexus/components/io/functions/SymlinkDestinationSupplier -instanceKlass org/codehaus/plexus/archiver/jar/JarArchiver$$Lambda$481 -instanceKlass org/apache/commons/compress/archivers/zip/ScatterZipOutputStream$CompressedEntry -instanceKlass org/apache/commons/compress/archivers/zip/ZipArchiveEntryRequest -instanceKlass org/codehaus/plexus/archiver/zip/AbstractZipArchiver$$Lambda$480 -instanceKlass org/apache/commons/compress/archivers/zip/ExtraFieldUtils$$Lambda$479 -instanceKlass org/apache/commons/compress/archivers/zip/ResourceAlignmentExtraField -instanceKlass org/apache/commons/compress/archivers/zip/ExtraFieldUtils$$Lambda$478 -instanceKlass org/apache/commons/compress/archivers/zip/ExtraFieldUtils$$Lambda$477 -instanceKlass org/apache/commons/compress/archivers/zip/ExtraFieldUtils$$Lambda$476 -instanceKlass org/apache/commons/compress/archivers/zip/ExtraFieldUtils$$Lambda$475 -instanceKlass org/apache/commons/compress/archivers/zip/ExtraFieldUtils$$Lambda$474 -instanceKlass org/apache/commons/compress/archivers/zip/PKWareExtraHeader -instanceKlass org/apache/commons/compress/archivers/zip/ExtraFieldUtils$$Lambda$473 -instanceKlass org/apache/commons/compress/archivers/zip/ExtraFieldUtils$$Lambda$472 -instanceKlass org/apache/commons/compress/archivers/zip/Zip64ExtendedInformationExtraField -instanceKlass org/apache/commons/compress/archivers/zip/ExtraFieldUtils$$Lambda$471 -instanceKlass org/apache/commons/compress/archivers/zip/ExtraFieldUtils$$Lambda$470 -instanceKlass org/apache/commons/compress/archivers/zip/ExtraFieldUtils$$Lambda$469 -instanceKlass org/apache/commons/compress/archivers/zip/JarMarker -instanceKlass org/apache/commons/compress/archivers/zip/ExtraFieldUtils$$Lambda$468 -instanceKlass org/apache/commons/compress/archivers/zip/X7875_NewUnix -instanceKlass org/apache/commons/compress/archivers/zip/ExtraFieldUtils$$Lambda$467 -instanceKlass org/apache/commons/compress/archivers/zip/ExtraFieldUtils$$Lambda$466 -instanceKlass org/apache/commons/compress/archivers/zip/AsiExtraField -instanceKlass org/apache/commons/compress/archivers/zip/UnixStat -instanceKlass org/apache/commons/compress/archivers/zip/ExtraFieldUtils -instanceKlass org/apache/commons/compress/archivers/zip/X000A_NTFS -instanceKlass org/apache/commons/compress/archivers/zip/ZipShort -instanceKlass org/apache/commons/compress/archivers/zip/X5455_ExtendedTimestamp -instanceKlass org/apache/commons/compress/archivers/zip/AbstractUnicodeExtraField -instanceKlass org/apache/commons/compress/archivers/zip/ZipUtil -instanceKlass org/apache/commons/compress/archivers/zip/GeneralPurposeBit -instanceKlass org/apache/commons/compress/archivers/zip/ExtraFieldParsingBehavior -instanceKlass org/apache/commons/compress/archivers/zip/UnparseableExtraFieldBehavior -instanceKlass org/codehaus/plexus/archiver/jar/JdkManifestFactory -instanceKlass java/util/concurrent/ConcurrentLinkedDeque$Node -instanceKlass org/apache/commons/compress/archivers/zip/ParallelScatterZipCreator -instanceKlass org/apache/commons/compress/archivers/zip/ScatterZipOutputStream -instanceKlass org/apache/commons/io/function/IOConsumer$$Lambda$465 -instanceKlass org/apache/commons/io/function/IOConsumer -instanceKlass org/apache/commons/io/output/ThresholdingOutputStream$$Lambda$464 -instanceKlass org/apache/commons/io/function/IOFunction -instanceKlass org/codehaus/plexus/archiver/zip/DeferredScatterOutputStream -instanceKlass org/apache/commons/compress/parallel/ScatterGatherBackingStore -instanceKlass org/codehaus/plexus/archiver/zip/ConcurrentJarCreator$DeferredSupplier -instanceKlass org/apache/commons/compress/parallel/ScatterGatherBackingStoreSupplier -instanceKlass org/apache/commons/compress/archivers/zip/StreamCompressor -instanceKlass java/util/zip/Deflater$DeflaterZStreamRef -instanceKlass java/util/zip/Deflater -instanceKlass org/apache/commons/io/Charsets -instanceKlass org/apache/commons/compress/archivers/zip/NioZipEncoding -instanceKlass org/apache/commons/compress/archivers/zip/CharsetAccessor -instanceKlass org/apache/commons/compress/archivers/zip/ZipEncoding -instanceKlass org/apache/commons/compress/archivers/zip/ZipEncodingHelper -instanceKlass org/codehaus/plexus/archiver/util/Streams -instanceKlass org/apache/commons/compress/utils/ByteUtils -instanceKlass org/apache/commons/compress/archivers/zip/ZipLong -instanceKlass org/apache/commons/compress/archivers/zip/ZipExtraField -instanceKlass org/codehaus/plexus/archiver/AbstractArchiver$1 -instanceKlass org/codehaus/plexus/archiver/jar/Manifest$ExistingSection -instanceKlass java/util/Vector$Itr -instanceKlass org/codehaus/plexus/archiver/jar/Manifest$Section -instanceKlass org/apache/maven/archiver/ManifestConfiguration -instanceKlass org/apache/maven/archiver/PomPropertiesUtil -instanceKlass org/codehaus/plexus/components/io/resources/PlexusIoFileResource$$Lambda$463 -instanceKlass org/codehaus/plexus/components/io/resources/AbstractPlexusIoResource -instanceKlass org/codehaus/plexus/components/io/functions/FileSupplier -instanceKlass org/codehaus/plexus/components/io/functions/ResourceAttributeSupplier -instanceKlass org/codehaus/plexus/components/io/resources/ResourceFactory -instanceKlass sun/nio/fs/WindowsUserPrincipals$User -instanceKlass java/nio/file/attribute/GroupPrincipal -instanceKlass java/nio/file/attribute/UserPrincipal -instanceKlass sun/nio/fs/WindowsUserPrincipals -instanceKlass sun/nio/fs/FileOwnerAttributeViewImpl -instanceKlass sun/nio/fs/AbstractBasicFileAttributeView$AttributesBuilder -instanceKlass org/codehaus/plexus/components/io/attributes/FileAttributes -instanceKlass org/codehaus/plexus/components/io/attributes/PlexusIoResourceAttributeUtils -instanceKlass org/codehaus/plexus/components/io/attributes/SimpleResourceAttributes -instanceKlass org/codehaus/plexus/util/StringUtils -instanceKlass org/codehaus/plexus/components/io/resources/AbstractPlexusIoResourceCollection$IdentityTransformer -instanceKlass org/codehaus/plexus/archiver/util/AbstractFileSet -instanceKlass org/apache/maven/archiver/MavenArchiver$$Lambda$462 -instanceKlass org/apache/maven/archiver/MavenArchiver$$Lambda$461 -instanceKlass org/apache/maven/plugins/jar/AbstractJarMojo$$Lambda$460 -instanceKlass java/time/temporal/TemporalQueries$7 -instanceKlass java/time/temporal/TemporalQueries$6 -instanceKlass java/time/temporal/TemporalQueries$5 -instanceKlass java/time/temporal/TemporalQueries$4 -instanceKlass java/time/temporal/TemporalQueries$3 -instanceKlass java/time/temporal/TemporalQueries$2 -instanceKlass java/time/temporal/TemporalQueries$1 -instanceKlass java/time/temporal/TemporalQueries -instanceKlass java/util/regex/Pattern$$Lambda$459 -instanceKlass java/time/format/Parsed -instanceKlass java/time/format/DateTimeParseContext -instanceKlass java/text/ParsePosition -instanceKlass java/time/Instant$$Lambda$458 -instanceKlass java/time/Instant -instanceKlass org/codehaus/plexus/archiver/jar/Manifest$BaseAttribute -instanceKlass org/codehaus/plexus/interpolation/RecursionInterceptor -instanceKlass org/codehaus/plexus/interpolation/Interpolator -instanceKlass org/codehaus/plexus/interpolation/BasicInterpolator -instanceKlass org/apache/maven/plugins/jar/AbstractJarMojo$$Lambda$457 -instanceKlass org/apache/maven/plugins/jar/AbstractJarMojo$$Lambda$456 -instanceKlass org/codehaus/plexus/util/NioFiles -instanceKlass org/codehaus/plexus/util/SelectorUtils -instanceKlass org/codehaus/plexus/util/MatchPattern -instanceKlass org/codehaus/plexus/util/AbstractScanner -instanceKlass org/codehaus/plexus/util/Scanner -instanceKlass org/apache/maven/shared/model/fileset/Mapper -instanceKlass org/apache/maven/shared/model/fileset/SetBase -instanceKlass org/apache/maven/shared/model/fileset/util/FileSetManager -instanceKlass org/apache/maven/project/DefaultMavenProjectHelper$$FastClassByGuice$$321696457 -instanceKlass org/apache/maven/plugins/jar/JarMojo$$FastClassByGuice$$320354415 -instanceKlass org/codehaus/plexus/components/io/resources/PlexusIoFileResourceCollection$$FastClassByGuice$$319204354 -instanceKlass org/codehaus/plexus/components/io/resources/DefaultPlexusIoFileResourceCollection$$FastClassByGuice$$317907236 -instanceKlass org/codehaus/plexus/components/io/fileselectors/IncludeExcludeFileSelector$$FastClassByGuice$$316890601 -instanceKlass org/codehaus/plexus/components/io/fileselectors/DefaultFileSelector$$FastClassByGuice$$316062179 -instanceKlass org/codehaus/plexus/components/io/fileselectors/AllFilesFileSelector$$FastClassByGuice$$315190076 -instanceKlass org/codehaus/plexus/components/io/filemappers/SuffixFileMapper$$FastClassByGuice$$314402006 -instanceKlass org/codehaus/plexus/components/io/filemappers/RegExpFileMapper$$FastClassByGuice$$313089435 -instanceKlass org/codehaus/plexus/components/io/filemappers/PrefixFileMapper$$FastClassByGuice$$311897602 -instanceKlass org/codehaus/plexus/components/io/filemappers/MergeFileMapper$$FastClassByGuice$$310623073 -instanceKlass org/codehaus/plexus/components/io/filemappers/IdentityMapper$$FastClassByGuice$$309401903 -instanceKlass org/codehaus/plexus/components/io/filemappers/FlattenFileMapper$$FastClassByGuice$$308945089 -instanceKlass org/codehaus/plexus/components/io/filemappers/FileExtensionMapper$$FastClassByGuice$$307488013 -instanceKlass org/codehaus/plexus/components/io/filemappers/DefaultFileMapper$$FastClassByGuice$$306645479 -instanceKlass org/codehaus/plexus/archiver/zstd/ZstdUnArchiver$$FastClassByGuice$$305719940 -instanceKlass org/codehaus/plexus/archiver/zstd/ZstdArchiver$$FastClassByGuice$$304596227 -instanceKlass org/codehaus/plexus/archiver/zstd/PlexusIoZstdResourceCollection$$FastClassByGuice$$303300873 -instanceKlass org/codehaus/plexus/archiver/zip/ZipUnArchiver$$FastClassByGuice$$302443043 -instanceKlass org/codehaus/plexus/archiver/zip/ZipArchiver$$FastClassByGuice$$301369557 -instanceKlass org/codehaus/plexus/archiver/zip/PlexusArchiverZipFileResourceCollection$$FastClassByGuice$$300773344 -instanceKlass org/codehaus/plexus/archiver/xz/XZUnArchiver$$FastClassByGuice$$299292197 -instanceKlass org/codehaus/plexus/archiver/xz/XZArchiver$$FastClassByGuice$$298820445 -instanceKlass org/codehaus/plexus/archiver/xz/PlexusIoXZResourceCollection$$FastClassByGuice$$297311811 -instanceKlass org/codehaus/plexus/archiver/war/WarUnArchiver$$FastClassByGuice$$296076085 -instanceKlass org/codehaus/plexus/archiver/war/WarArchiver$$FastClassByGuice$$294779710 -instanceKlass org/codehaus/plexus/archiver/war/PlexusIoWarFileResourceCollection$$FastClassByGuice$$294295113 -instanceKlass org/codehaus/plexus/archiver/tar/TarZstdUnArchiver$$FastClassByGuice$$292787202 -instanceKlass org/codehaus/plexus/archiver/tar/TarZstdArchiver$$FastClassByGuice$$292129510 -instanceKlass org/codehaus/plexus/archiver/tar/TarXZUnArchiver$$FastClassByGuice$$291115000 -instanceKlass org/codehaus/plexus/archiver/tar/TarXZArchiver$$FastClassByGuice$$289991980 -instanceKlass org/codehaus/plexus/archiver/tar/TarUnArchiver$$FastClassByGuice$$289354997 -instanceKlass org/codehaus/plexus/archiver/tar/TarSnappyUnArchiver$$FastClassByGuice$$287997952 -instanceKlass org/codehaus/plexus/archiver/tar/TarSnappyArchiver$$FastClassByGuice$$286584072 -instanceKlass org/codehaus/plexus/archiver/tar/TarGZipUnArchiver$$FastClassByGuice$$285907760 -instanceKlass org/codehaus/plexus/archiver/tar/TarGZipArchiver$$FastClassByGuice$$284563405 -instanceKlass org/codehaus/plexus/archiver/tar/TarBZip2UnArchiver$$FastClassByGuice$$283580909 -instanceKlass org/codehaus/plexus/archiver/tar/TarBZip2Archiver$$FastClassByGuice$$283092344 -instanceKlass org/codehaus/plexus/archiver/tar/TarArchiver$$FastClassByGuice$$281624227 -instanceKlass org/codehaus/plexus/archiver/tar/TZstdUnArchiver$$FastClassByGuice$$280670818 -instanceKlass org/codehaus/plexus/archiver/tar/TZstdArchiver$$FastClassByGuice$$279591956 -instanceKlass org/codehaus/plexus/archiver/tar/TXZUnArchiver$$FastClassByGuice$$277892334 -instanceKlass org/codehaus/plexus/archiver/tar/TXZArchiver$$FastClassByGuice$$277657725 -instanceKlass org/codehaus/plexus/archiver/tar/TGZUnArchiver$$FastClassByGuice$$276322032 -instanceKlass org/codehaus/plexus/archiver/tar/TGZArchiver$$FastClassByGuice$$275091758 -instanceKlass org/codehaus/plexus/archiver/tar/TBZ2UnArchiver$$FastClassByGuice$$274560814 -instanceKlass org/codehaus/plexus/archiver/tar/TBZ2Archiver$$FastClassByGuice$$273294391 -instanceKlass org/codehaus/plexus/archiver/tar/PlexusIoTarZstdFileResourceCollection$$FastClassByGuice$$272577250 -instanceKlass org/codehaus/plexus/archiver/tar/PlexusIoTarXZFileResourceCollection$$FastClassByGuice$$271106891 -instanceKlass org/codehaus/plexus/archiver/tar/PlexusIoTarSnappyFileResourceCollection$$FastClassByGuice$$270159449 -instanceKlass org/codehaus/plexus/archiver/tar/PlexusIoTarGZipFileResourceCollection$$FastClassByGuice$$268643046 -instanceKlass org/codehaus/plexus/archiver/tar/PlexusIoTarFileResourceCollection$$FastClassByGuice$$267955549 -instanceKlass org/codehaus/plexus/archiver/tar/PlexusIoTarBZip2FileResourceCollection$$FastClassByGuice$$267350868 -instanceKlass org/codehaus/plexus/archiver/tar/PlexusIoTZstdFileResourceCollection$$FastClassByGuice$$265887665 -instanceKlass org/codehaus/plexus/archiver/tar/PlexusIoTXZFileResourceCollection$$FastClassByGuice$$264425778 -instanceKlass org/codehaus/plexus/archiver/tar/PlexusIoTGZFileResourceCollection$$FastClassByGuice$$263196108 -instanceKlass org/codehaus/plexus/archiver/tar/PlexusIoTBZ2FileResourceCollection$$FastClassByGuice$$262472314 -instanceKlass org/codehaus/plexus/archiver/swc/SwcUnArchiver$$FastClassByGuice$$261891913 -instanceKlass org/codehaus/plexus/archiver/swc/PlexusIoSwcFileResourceCollection$$FastClassByGuice$$260653141 -instanceKlass org/codehaus/plexus/archiver/snappy/SnappyUnArchiver$$FastClassByGuice$$259721836 -instanceKlass org/codehaus/plexus/archiver/snappy/SnappyArchiver$$FastClassByGuice$$258553347 -instanceKlass org/codehaus/plexus/archiver/snappy/PlexusIoSnappyResourceCollection$$FastClassByGuice$$257679583 -instanceKlass org/codehaus/plexus/archiver/sar/SarUnArchiver$$FastClassByGuice$$256542024 -instanceKlass org/codehaus/plexus/archiver/sar/PlexusIoSarFileResourceCollection$$FastClassByGuice$$255436074 -instanceKlass org/codehaus/plexus/archiver/rar/RarUnArchiver$$FastClassByGuice$$254421227 -instanceKlass org/codehaus/plexus/archiver/rar/RarArchiver$$FastClassByGuice$$253519508 -instanceKlass org/codehaus/plexus/archiver/rar/PlexusIoRarFileResourceCollection$$FastClassByGuice$$252442844 -instanceKlass org/codehaus/plexus/archiver/par/PlexusIoJarFileResourceCollection$$FastClassByGuice$$250644648 -instanceKlass org/codehaus/plexus/archiver/par/ParUnArchiver$$FastClassByGuice$$250552259 -instanceKlass org/codehaus/plexus/archiver/nar/PlexusIoNarFileResourceCollection$$FastClassByGuice$$249467033 -instanceKlass org/codehaus/plexus/archiver/nar/NarUnArchiver$$FastClassByGuice$$247527733 -instanceKlass org/codehaus/plexus/archiver/manager/DefaultArchiverManager$$FastClassByGuice$$246589197 -instanceKlass org/codehaus/plexus/archiver/jar/PlexusIoJarFileResourceCollection$$FastClassByGuice$$246305074 -instanceKlass org/codehaus/plexus/archiver/jar/JarUnArchiver$$FastClassByGuice$$244319964 -instanceKlass org/codehaus/plexus/archiver/jar/JarToolModularJarArchiver$$FastClassByGuice$$243972851 -instanceKlass org/codehaus/plexus/archiver/jar/JarArchiver$$FastClassByGuice$$242404611 -instanceKlass org/codehaus/plexus/archiver/gzip/PlexusIoGzipResourceCollection$$FastClassByGuice$$241179733 -instanceKlass org/codehaus/plexus/archiver/gzip/PlexusIoGzResourceCollection$$FastClassByGuice$$240125494 -instanceKlass org/codehaus/plexus/archiver/gzip/GZipUnArchiver$$FastClassByGuice$$239159142 -instanceKlass org/codehaus/plexus/archiver/gzip/GZipArchiver$$FastClassByGuice$$239074900 -instanceKlass org/codehaus/plexus/archiver/filters/JarSecurityFileSelector$$FastClassByGuice$$237386385 -instanceKlass org/codehaus/plexus/archiver/esb/PlexusIoEsbFileResourceCollection$$FastClassByGuice$$236106276 -instanceKlass org/codehaus/plexus/archiver/esb/EsbUnArchiver$$FastClassByGuice$$235060947 -instanceKlass org/codehaus/plexus/archiver/ear/PlexusIoEarFileResourceCollection$$FastClassByGuice$$234103274 -instanceKlass org/codehaus/plexus/archiver/ear/EarUnArchiver$$FastClassByGuice$$233715924 -instanceKlass org/codehaus/plexus/archiver/ear/EarArchiver$$FastClassByGuice$$232647764 -instanceKlass org/codehaus/plexus/archiver/dir/DirectoryArchiver$$FastClassByGuice$$231171695 -instanceKlass org/codehaus/plexus/archiver/car/PlexusIoCarFileResourceCollection$$FastClassByGuice$$230049461 -instanceKlass org/codehaus/plexus/archiver/car/CarUnArchiver$$FastClassByGuice$$229520623 -instanceKlass org/codehaus/plexus/archiver/bzip2/PlexusIoBzip2ResourceCollection$$FastClassByGuice$$228119845 -instanceKlass org/codehaus/plexus/archiver/bzip2/PlexusIoBz2ResourceCollection$$FastClassByGuice$$227074148 -instanceKlass org/codehaus/plexus/archiver/bzip2/BZip2UnArchiver$$FastClassByGuice$$225481706 -instanceKlass org/codehaus/plexus/archiver/bzip2/BZip2Archiver$$FastClassByGuice$$225312410 -instanceKlass org/apache/maven/plugins/jar/ToolchainsJdkSpecification$$FastClassByGuice$$223708375 -instanceKlass org/eclipse/sisu/wire/BeanProviders$2 -instanceKlass org/codehaus/plexus/util/MatchPatterns -instanceKlass org/codehaus/plexus/archiver/tar/TarArchiver$TarOptions -instanceKlass org/codehaus/plexus/archiver/tar/TarFile -instanceKlass org/codehaus/plexus/archiver/ArchiveFile -instanceKlass org/apache/commons/compress/parallel/InputStreamSupplier -instanceKlass org/apache/commons/compress/archivers/zip/ZipArchiveOutputStream$UnicodeExtraFieldPolicy -instanceKlass org/codehaus/plexus/archiver/zip/ConcurrentJarCreator -instanceKlass org/codehaus/plexus/archiver/zip/AddedDirs -instanceKlass org/codehaus/plexus/components/io/functions/PlexusIoResourceConsumer -instanceKlass org/apache/commons/compress/archivers/EntryStreamOffsets -instanceKlass org/apache/commons/compress/archivers/ArchiveEntry -instanceKlass org/apache/commons/compress/archivers/zip/ZipFile -instanceKlass org/codehaus/plexus/components/io/functions/InputStreamTransformer -instanceKlass org/codehaus/plexus/components/io/resources/Stream -instanceKlass org/apache/commons/compress/utils/InputStreamStatistics -instanceKlass org/apache/commons/compress/compressors/bzip2/BZip2Constants -instanceKlass org/codehaus/plexus/archiver/util/Compressor -instanceKlass org/codehaus/plexus/archiver/ArchivedFileSet -instanceKlass org/codehaus/plexus/archiver/ArchiveEntry -instanceKlass org/codehaus/plexus/components/io/resources/PlexusIoResource -instanceKlass org/codehaus/plexus/components/io/functions/ContentSupplier -instanceKlass org/codehaus/plexus/components/io/functions/SizeSupplier -instanceKlass org/codehaus/plexus/components/io/fileselectors/FileInfo -instanceKlass org/codehaus/plexus/components/io/functions/NameSupplier -instanceKlass org/codehaus/plexus/archiver/AbstractArchiver$AddedResourceCollection -instanceKlass org/codehaus/plexus/archiver/ArchiveFinalizer -instanceKlass org/codehaus/plexus/components/io/attributes/PlexusIoResourceAttributes -instanceKlass org/codehaus/plexus/archiver/ResourceIterator -instanceKlass org/codehaus/plexus/util/cli/StreamConsumer -instanceKlass org/apache/maven/archiver/MavenArchiver -instanceKlass org/apache/maven/archiver/MavenArchiveConfiguration -instanceKlass org/codehaus/plexus/archiver/FileSet -instanceKlass org/codehaus/plexus/archiver/BaseFileSet -instanceKlass org/codehaus/plexus/components/io/fileselectors/IncludeExcludeFileSelector -instanceKlass org/codehaus/plexus/components/io/fileselectors/AllFilesFileSelector -instanceKlass org/codehaus/plexus/components/io/filemappers/AbstractFileMapper -instanceKlass org/codehaus/plexus/components/io/filemappers/FileMapper -instanceKlass org/codehaus/plexus/archiver/manager/DefaultArchiverManager -instanceKlass org/codehaus/plexus/archiver/manager/ArchiverManager -instanceKlass org/codehaus/plexus/archiver/filters/JarSecurityFileSelector -instanceKlass org/codehaus/plexus/components/io/fileselectors/FileSelector -instanceKlass org/codehaus/plexus/components/io/resources/AbstractPlexusIoResourceCollection -instanceKlass org/codehaus/plexus/components/io/resources/EncodingSupported -instanceKlass org/codehaus/plexus/components/io/resources/PlexusIoCompressedFileResourceCollection -instanceKlass org/codehaus/plexus/components/io/resources/PlexusIoArchivedResourceCollection -instanceKlass org/codehaus/plexus/components/io/resources/PlexusIoResourceCollection -instanceKlass org/codehaus/plexus/archiver/AbstractUnArchiver -instanceKlass org/codehaus/plexus/archiver/UnArchiver -instanceKlass org/codehaus/plexus/archiver/AbstractArchiver -instanceKlass org/codehaus/plexus/archiver/FinalizerEnabled -instanceKlass org/codehaus/plexus/archiver/Archiver -instanceKlass org/apache/maven/plugins/jar/ToolchainsJdkSpecification -instanceKlass java/util/concurrent/SynchronousQueue$TransferStack$SNode -instanceKlass java/util/concurrent/SynchronousQueue$Transferer -instanceKlass java/lang/invoke/LambdaForm$MH -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass java/lang/ProcessHandleImpl$$Lambda$455 -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass java/lang/ProcessHandleImpl$$Lambda$454 -instanceKlass java/lang/ProcessHandleImpl -instanceKlass java/util/concurrent/CompletableFuture -instanceKlass java/util/concurrent/CompletionStage -instanceKlass java/lang/ProcessHandle$Info -instanceKlass java/lang/ProcessHandle -instanceKlass org/apache/maven/plugin/lifecycle/Lifecycle -instanceKlass org/apache/maven/surefire/api/util/ReflectionUtils -instanceKlass org/apache/maven/surefire/shared/lang3/math/NumberUtils -instanceKlass org/apache/maven/plugin/internal/AbstractMavenPluginDescriptorSourcedParametersValidator$$Lambda$453 -instanceKlass org/apache/maven/surefire/booter/SystemUtils -instanceKlass java/util/concurrent/Executors$DefaultThreadFactory -instanceKlass java/util/concurrent/Executors -instanceKlass org/apache/maven/surefire/api/util/internal/DaemonThreadFactory -instanceKlass org/apache/maven/plugin/surefire/booterclient/Platform$1 -instanceKlass java/util/concurrent/FutureTask$WaitNode -instanceKlass java/util/concurrent/FutureTask -instanceKlass java/util/concurrent/RunnableFuture -instanceKlass org/apache/maven/plugin/surefire/SurefirePlugin$$FastClassByGuice$$222502495 -instanceKlass org/codehaus/plexus/languages/java/jpms/LocationManager$$FastClassByGuice$$221709556 -instanceKlass org/apache/maven/plugin/surefire/SurefireDependencyResolver$$FastClassByGuice$$221129914 -instanceKlass org/apache/maven/surefire/providerapi/ProviderDetector$$FastClassByGuice$$219792332 -instanceKlass org/apache/maven/surefire/providerapi/ServiceLoader$$FastClassByGuice$$218566869 -instanceKlass org/codehaus/plexus/languages/java/jpms/JavaModuleDescriptor -instanceKlass org/codehaus/plexus/languages/java/jpms/ResolvePathsResult -instanceKlass org/codehaus/plexus/languages/java/jpms/ResolvePathsRequest -instanceKlass org/codehaus/plexus/languages/java/jpms/ResolvePathResult -instanceKlass org/codehaus/plexus/languages/java/jpms/ResolvePathRequest -instanceKlass org/codehaus/plexus/languages/java/jpms/ManifestModuleNameExtractor -instanceKlass org/codehaus/plexus/languages/java/jpms/SourceModuleInfoParser -instanceKlass org/codehaus/plexus/languages/java/jpms/ModuleInfoParser -instanceKlass org/codehaus/plexus/languages/java/jpms/ModuleNameExtractor -instanceKlass org/apache/maven/plugin/surefire/booterclient/ChecksumCalculator -instanceKlass org/apache/maven/plugin/surefire/InPluginVMSurefireStarter -instanceKlass org/apache/maven/plugin/surefire/StartupReportConfiguration -instanceKlass org/apache/maven/surefire/booter/Classpath -instanceKlass org/apache/maven/surefire/booter/StartupConfiguration -instanceKlass org/apache/maven/surefire/booter/ProviderConfiguration -instanceKlass org/apache/maven/plugin/surefire/JdkAttributes -instanceKlass org/apache/maven/plugin/surefire/booterclient/ForkStarter -instanceKlass org/apache/maven/surefire/api/testset/RunOrderParameters -instanceKlass org/apache/maven/surefire/booter/ClassLoaderConfiguration -instanceKlass org/apache/maven/plugin/surefire/ResolvePathResultWrapper -instanceKlass org/apache/maven/plugin/surefire/TestClassPath -instanceKlass org/apache/maven/surefire/api/util/DefaultScanResult -instanceKlass org/apache/maven/surefire/api/util/ScanResult -instanceKlass org/apache/maven/surefire/api/suite/RunResult -instanceKlass org/apache/maven/plugin/surefire/log/PluginConsoleLogger -instanceKlass org/apache/maven/surefire/api/testset/TestListResolver -instanceKlass org/apache/maven/surefire/api/testset/GenericTestPattern -instanceKlass org/apache/maven/surefire/api/testset/TestFilter -instanceKlass org/apache/maven/surefire/extensions/StatelessTestsetInfoReporter -instanceKlass org/apache/maven/surefire/extensions/ConsoleOutputReporter -instanceKlass org/apache/maven/surefire/extensions/StatelessReporter -instanceKlass org/apache/maven/plugin/surefire/AbstractSurefireMojo$ClasspathCache -instanceKlass org/apache/maven/plugin/surefire/booterclient/Platform -instanceKlass org/apache/maven/plugin/surefire/booterclient/ForkConfiguration -instanceKlass org/apache/maven/surefire/booter/AbstractPathConfiguration -instanceKlass org/apache/maven/surefire/extensions/ForkNodeFactory -instanceKlass org/apache/maven/plugin/surefire/log/api/ConsoleLogger -instanceKlass org/apache/maven/surefire/providerapi/ConfigurableProviderInfo -instanceKlass org/apache/maven/surefire/providerapi/ProviderInfo -instanceKlass org/apache/maven/surefire/booter/KeyValueSource -instanceKlass org/codehaus/plexus/languages/java/jpms/LocationManager -instanceKlass org/apache/maven/plugin/surefire/SurefireDependencyResolver -instanceKlass org/apache/maven/surefire/providerapi/ServiceLoader -instanceKlass org/apache/maven/surefire/providerapi/ProviderDetector -instanceKlass org/apache/maven/plugin/surefire/SurefireExecutionParameters -instanceKlass org/apache/maven/plugin/surefire/SurefireReportParameters -instanceKlass org/apache/maven/model/merge/ModelMerger$1 -instanceKlass com/sun/tools/javac/code/Scope$$Lambda$452 -instanceKlass lombok/bytecode/ClassFileMetaData -instanceKlass lombok/bytecode/SneakyThrowsRemover -instanceKlass org/lombokweb/asm/ClassVisitor -instanceKlass lombok/bytecode/PreventNullAnalysisRemover -instanceKlass lombok/core/PostCompilerTransformation -instanceKlass lombok/core/PostCompiler -instanceKlass lombok/javac/apt/InterceptingJavaFileObject -instanceKlass org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessor$AbstractValueExtractor -instanceKlass org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessor$ValueExtractor -instanceKlass org/springframework/boot/configurationprocessor/fieldvalues/javac/ReflectionWrapper -instanceKlass org/springframework/boot/configurationprocessor/fieldvalues/javac/TreeVisitor -instanceKlass org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesParser -instanceKlass org/springframework/boot/configurationprocessor/fieldvalues/FieldValuesParser -instanceKlass org/springframework/boot/configurationprocessor/MetadataGenerationEnvironment -instanceKlass org/springframework/boot/configurationprocessor/TypeUtils$$Lambda$451 -instanceKlass org/springframework/boot/configurationprocessor/TypeUtils$$Lambda$450 -instanceKlass org/springframework/boot/configurationprocessor/TypeUtils -instanceKlass org/springframework/boot/configurationprocessor/MetadataCollector -instanceKlass org/springframework/boot/configurationprocessor/MetadataStore -instanceKlass net/dreamlu/mica/auto/annotation/AutoService -instanceKlass net/dreamlu/mica/auto/annotation/AutoLoggingSystemFactory -instanceKlass net/dreamlu/mica/auto/annotation/AutoDependsOnDatabaseInitializationDetector -instanceKlass net/dreamlu/mica/auto/annotation/AutoDatabaseInitializerDetector -instanceKlass net/dreamlu/mica/auto/annotation/AutoConfigDataLoader -instanceKlass net/dreamlu/mica/auto/annotation/AutoConfigDataLocationResolver -instanceKlass net/dreamlu/mica/auto/annotation/AutoEnableCircuitBreaker -instanceKlass net/dreamlu/mica/auto/annotation/AutoTemplateProvider -instanceKlass net/dreamlu/mica/auto/annotation/AutoConfigImportFilter -instanceKlass net/dreamlu/mica/auto/annotation/AutoFailureAnalyzer -instanceKlass net/dreamlu/mica/auto/annotation/AutoEnvPostProcessor -instanceKlass net/dreamlu/mica/auto/annotation/AutoRunListener -instanceKlass net/dreamlu/mica/auto/annotation/AutoListener -instanceKlass net/dreamlu/mica/auto/annotation/AutoContextInitializer -instanceKlass net/dreamlu/mica/auto/annotation/AutoIgnore -instanceKlass net/dreamlu/mica/auto/factories/AutoFactoriesProcessor$$Lambda$449 -instanceKlass net/dreamlu/mica/auto/factories/AutoFactoriesProcessor$$Lambda$448 -instanceKlass net/dreamlu/mica/auto/factories/AutoFactoriesProcessor$$Lambda$447 -instanceKlass net/dreamlu/mica/auto/common/MultiSetMap -instanceKlass lombok/core/handlers/InclusionExclusionUtils$1 -instanceKlass lombok/ToString$Exclude -instanceKlass lombok/ToString$Include -instanceKlass lombok/javac/handlers/JavacHandlerUtil$JCAnnotatedTypeReflect -instanceKlass lombok/javac/handlers/JavacHandlerUtil$GetterMethod -instanceKlass lombok/EqualsAndHashCode$AnyAnnotation -instanceKlass lombok/core/handlers/InclusionExclusionUtils$2 -instanceKlass lombok/core/handlers/InclusionExclusionUtils$Included -instanceKlass lombok/EqualsAndHashCode$Exclude -instanceKlass lombok/EqualsAndHashCode$Include -instanceKlass lombok/core/handlers/InclusionExclusionUtils -instanceKlass lombok/javac/handlers/JavacHandlerUtil$CopyJavadoc$6 -instanceKlass lombok/core/CleanupRegistry$CleanupKey -instanceKlass lombok/javac/handlers/JavacHandlerUtil$CopyJavadoc$2$1 -instanceKlass lombok/javac/Javac$JavadocOps_8 -instanceKlass lombok/core/CleanupTask -instanceKlass lombok/javac/handlers/JavacHandlerUtil$EnterReflect -instanceKlass lombok/javac/handlers/JavacHandlerUtil$ClassSymbolMembersField -instanceKlass lombok/core/AnnotationValues$1 -instanceKlass lombok/delombok/FormatPreferences -instanceKlass lombok/delombok/LombokOptionsFactory -instanceKlass lombok/core/configuration/AllowHelper -instanceKlass lombok/experimental/FieldDefaults -instanceKlass lombok/core/handlers/HandlerUtil -instanceKlass lombok/core/AnnotationValues -instanceKlass lombok/core/AnnotationValues$AnnotationValue -instanceKlass lombok/core/FieldAugment -instanceKlass lombok/javac/JavacAugments -instanceKlass lombok/core/TypeResolver -instanceKlass lombok/core/AST$FieldAccess -instanceKlass lombok/core/LombokImmutableList$1 -instanceKlass lombok/javac/JavacImportList -instanceKlass lombok/javac/PackageName -instanceKlass lombok/core/configuration/FileSystemSourceCache$Content -instanceKlass lombok/core/configuration/ConfigurationFile -instanceKlass lombok/core/configuration/BubblingConfigurationResolver -instanceKlass lombok/core/LombokConfiguration$3 -instanceKlass lombok/core/configuration/FileSystemSourceCache$1 -instanceKlass lombok/core/configuration/ConfigurationProblemReporter$1 -instanceKlass lombok/core/configuration/ConfigurationProblemReporter -instanceKlass lombok/core/configuration/ConfigurationParser -instanceKlass lombok/core/configuration/ConfigurationFileToSource -instanceKlass lombok/core/configuration/FileSystemSourceCache -instanceKlass lombok/core/LombokConfiguration$1 -instanceKlass lombok/core/configuration/ConfigurationResolverFactory -instanceKlass lombok/core/configuration/ConfigurationResolver -instanceKlass lombok/core/LombokConfiguration -instanceKlass lombok/core/ImportList -instanceKlass lombok/javac/JavacAST$ErrorLog -instanceKlass lombok/javac/HandlerLibrary$VisitorContainer -instanceKlass lombok/experimental/WithBy -instanceKlass lombok/With -instanceKlass lombok/Value -instanceKlass lombok/javac/JavacASTAdapter -instanceKlass lombok/experimental/UtilityClass -instanceKlass lombok/ToString -instanceKlass lombok/Synchronized -instanceKlass lombok/experimental/SuperBuilder -instanceKlass lombok/javac/handlers/JavacSingularsRecipes$StatementMaker -instanceKlass lombok/javac/handlers/JavacSingularsRecipes$ExpressionMaker -instanceKlass lombok/javac/handlers/HandleBuilder$BuilderJob -instanceKlass lombok/experimental/StandardException -instanceKlass lombok/SneakyThrows -instanceKlass lombok/Singular -instanceKlass lombok/Setter -instanceKlass lombok/core/PrintAST -instanceKlass lombok/NonNull -instanceKlass lombok/extern/slf4j/XSlf4j -instanceKlass lombok/extern/slf4j/Slf4j -instanceKlass lombok/extern/log4j/Log4j -instanceKlass lombok/extern/log4j/Log4j2 -instanceKlass lombok/extern/java/Log -instanceKlass lombok/extern/jbosslog/JBossLog -instanceKlass lombok/extern/flogger/Flogger -instanceKlass lombok/CustomLog -instanceKlass lombok/extern/apachecommons/CommonsLog -instanceKlass lombok/extern/jackson/Jacksonized -instanceKlass lombok/experimental/Helper -instanceKlass lombok/Getter -instanceKlass lombok/experimental/FieldNameConstants -instanceKlass lombok/core/LombokImmutableList -instanceKlass lombok/core/JavaIdentifiers -instanceKlass lombok/experimental/ExtensionMethod -instanceKlass lombok/EqualsAndHashCode -instanceKlass lombok/experimental/Delegate -instanceKlass lombok/Data -instanceKlass lombok/RequiredArgsConstructor -instanceKlass lombok/NoArgsConstructor -instanceKlass lombok/AllArgsConstructor -instanceKlass lombok/Cleanup -instanceKlass lombok/Builder$Default -instanceKlass lombok/Builder -instanceKlass lombok/javac/handlers/HandleConstructor -instanceKlass lombok/core/LombokInternalAliasing -instanceKlass lombok/core/AlreadyHandledAnnotations -instanceKlass lombok/javac/ResolutionResetNeeded -instanceKlass lombok/core/HandlerPriority -instanceKlass lombok/javac/HandlerLibrary$AnnotationHandlerContainer -instanceKlass lombok/experimental/Accessors -instanceKlass lombok/javac/JavacAnnotationHandler -instanceKlass lombok/core/SpiLoadUtil$1$1 -instanceKlass lombok/core/SpiLoadUtil$1 -instanceKlass lombok/core/SpiLoadUtil -instanceKlass lombok/core/configuration/ConfigurationKeysLoader -instanceKlass lombok/core/configuration/CheckerFrameworkVersion -instanceKlass lombok/core/configuration/TypeName -instanceKlass lombok/core/configuration/LogDeclaration -instanceKlass lombok/core/configuration/IdentifierName -instanceKlass lombok/core/configuration/ConfigurationDataType$6 -instanceKlass lombok/core/configuration/ConfigurationDataType$7 -instanceKlass lombok/core/configuration/NullAnnotationLibrary -instanceKlass lombok/core/configuration/ConfigurationValueType -instanceKlass lombok/core/configuration/ConfigurationDataType$5 -instanceKlass lombok/core/configuration/ConfigurationDataType$4 -instanceKlass lombok/core/configuration/ConfigurationDataType$3 -instanceKlass lombok/core/configuration/ConfigurationDataType$2 -instanceKlass lombok/core/configuration/ConfigurationDataType$1 -instanceKlass lombok/core/configuration/ConfigurationValueParser -instanceKlass lombok/core/configuration/ConfigurationDataType -instanceKlass lombok/core/configuration/ConfigurationKey -instanceKlass lombok/ConfigurationKeys -instanceKlass lombok/core/configuration/ConfigurationKeysLoader$LoaderLoader -instanceKlass lombok/core/TypeLibrary -instanceKlass lombok/javac/HandlerLibrary -instanceKlass lombok/javac/JavacASTVisitor -instanceKlass lombok/javac/JavacTransformer -instanceKlass lombok/core/AST -instanceKlass lombok/core/LombokNode -instanceKlass lombok/javac/handlers/JavacHandlerUtil -instanceKlass lombok/javac/JavacTreeMaker$FieldId -instanceKlass lombok/javac/JavacTreeMaker$MethodId -instanceKlass lombok/javac/JavacTreeMaker -instanceKlass lombok/javac/JavacTreeMaker$SchroedingerType -instanceKlass lombok/javac/Javac -instanceKlass lombok/javac/apt/Java9Compiler -instanceKlass lombok/javac/apt/LombokFileObjects$Compiler -instanceKlass lombok/javac/apt/LombokFileObject -instanceKlass lombok/javac/apt/LombokFileObjects -instanceKlass lombok/javac/apt/MessagerDiagnosticsReceiver -instanceKlass lombok/permit/dummy/Parent -instanceKlass lombok/core/CleanupRegistry -instanceKlass lombok/permit/Permit -instanceKlass lombok/core/DiagnosticsReceiver -instanceKlass lombok/launch/AnnotationProcessorHider$AstModificationNotifierData -instanceKlass lombok/core/AnnotationProcessor$ProcessorDescriptor -instanceKlass lombok/launch/ClassFileMetaData -instanceKlass lombok/launch/PackageShader -instanceKlass lombok/launch/Main -instanceKlass com/sun/tools/javac/comp/TypeEnter$$Lambda$446 -instanceKlass com/sun/tools/javac/code/Scope$ImportScope$1 -instanceKlass org/apache/maven/plugin/compiler/TestCompilerMojo$$FastClassByGuice$$217965170 -instanceKlass org/apache/maven/plugins/resources/TestResourcesMojo$$FastClassByGuice$$216493200 -instanceKlass java/io/FileOutputStream$1 -instanceKlass org/apache/maven/shared/utils/io/IOUtil -instanceKlass org/apache/maven/shared/utils/io/DirectoryScanResult -instanceKlass org/apache/maven/shared/utils/io/SelectorUtils -instanceKlass org/apache/maven/shared/utils/io/MatchPattern -instanceKlass org/apache/maven/shared/utils/io/MatchPatterns -instanceKlass com/sun/tools/javac/util/JCDiagnostic$SourcePosition -instanceKlass com/sun/tools/javac/api/ClientCodeWrapper$WrappedFileObject -instanceKlass com/sun/tools/javac/api/ClientCodeWrapper$DiagnosticSourceUnwrapper -instanceKlass com/sun/tools/javac/comp/Attr$$Lambda$445 -instanceKlass com/sun/tools/javac/comp/InferenceContext$ReachabilityVisitor$$Lambda$444 -instanceKlass com/sun/tools/javac/comp/Check$$Lambda$443 -instanceKlass com/sun/tools/javac/comp/Check$$Lambda$442 -instanceKlass com/sun/tools/javac/code/DeferredLintHandler$LintLogger -instanceKlass com/sun/tools/javac/comp/Attr$$Lambda$441 -instanceKlass com/sun/tools/javac/comp/Attr$$Lambda$440 -instanceKlass com/sun/tools/javac/comp/Attr$$Lambda$439 -instanceKlass com/sun/tools/javac/comp/Attr$$Lambda$438 -instanceKlass com/sun/tools/javac/comp/Attr$$Lambda$437 -instanceKlass com/sun/tools/javac/comp/Attr$$Lambda$436 -instanceKlass com/sun/tools/javac/comp/Attr$$Lambda$435 -instanceKlass java/lang/invoke/LambdaForm$MH -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass com/sun/tools/javac/comp/Attr$$Lambda$434 -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass java/util/stream/ReduceOps$2ReducingSink -instanceKlass com/sun/tools/javac/comp/Resolve$ReferenceLookupResult$$Lambda$433 -instanceKlass com/sun/tools/javac/comp/Resolve$ReferenceLookupResult$$Lambda$432 -instanceKlass com/sun/tools/javac/comp/Resolve$ReferenceLookupResult$$Lambda$431 -instanceKlass com/sun/tools/javac/comp/Attr$$Lambda$430 -instanceKlass java/lang/invoke/LambdaForm$MH -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass com/sun/tools/javac/comp/Check$$Lambda$429 -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass com/sun/tools/javac/comp/Infer$$Lambda$428 -instanceKlass com/sun/tools/javac/comp/InferenceContext$$Lambda$427 -instanceKlass com/sun/tools/javac/comp/ArgumentAttr$$Lambda$426 -instanceKlass com/sun/tools/javac/jvm/Pool$DynamicMethod$BootstrapMethodsValue -instanceKlass com/sun/tools/javac/jvm/Pool$MethodHandle$$Lambda$425 -instanceKlass com/sun/tools/javac/jvm/Pool$MethodHandle$$Lambda$424 -instanceKlass com/sun/tools/javac/jvm/Pool$MethodHandle -instanceKlass com/sun/tools/javac/comp/LambdaToMethod$$Lambda$423 -instanceKlass com/sun/tools/javac/comp/LambdaToMethod$$Lambda$422 -instanceKlass com/sun/tools/javac/comp/LambdaToMethod$$Lambda$421 -instanceKlass com/sun/tools/javac/comp/LambdaToMethod$KlassInfo -instanceKlass com/sun/tools/javac/comp/LambdaToMethod$1 -instanceKlass com/sun/tools/javac/comp/LambdaToMethod$LambdaAnalyzerPreprocessor$Frame -instanceKlass com/sun/tools/javac/comp/LambdaToMethod$LambdaAnalyzerPreprocessor$SyntheticMethodNameCounter -instanceKlass com/sun/tools/javac/comp/LambdaToMethod$LambdaAnalyzerPreprocessor$TranslationContext -instanceKlass com/sun/tools/javac/tree/TreeInfo$1 -instanceKlass com/sun/tools/javac/code/Types$DescriptorCache$$Lambda$420 -instanceKlass com/sun/tools/javac/code/Types$DescriptorCache$$Lambda$419 -instanceKlass com/sun/tools/javac/code/Types$DescriptorCache$$Lambda$418 -instanceKlass com/sun/tools/javac/comp/Attr$TargetInfo -instanceKlass com/sun/tools/javac/comp/DeferredAttr$DeferredType$SpeculativeCache$Entry -instanceKlass com/sun/tools/javac/comp/DeferredAttr$DeferredAttrNode -instanceKlass com/sun/tools/javac/code/Types$$Lambda$417 -instanceKlass com/sun/tools/javac/code/Types$DescriptorCache$Entry -instanceKlass com/sun/tools/javac/code/Types$DescriptorCache$FunctionDescriptor -instanceKlass com/sun/tools/javac/comp/DeferredAttr$$Lambda$416 -instanceKlass com/sun/tools/javac/comp/ArgumentAttr$LocalCacheContext -instanceKlass com/sun/tools/javac/comp/Operators$UnaryOperatorHelper$$Lambda$415 -instanceKlass com/sun/tools/javac/comp/Operators$$Lambda$414 -instanceKlass com/sun/tools/javac/comp/Operators$$Lambda$413 -instanceKlass com/sun/tools/javac/comp/Operators$$Lambda$412 -instanceKlass lombok/bytecode/ClassFileMetaData -instanceKlass lombok/bytecode/SneakyThrowsRemover -instanceKlass org/lombokweb/asm/ClassVisitor -instanceKlass lombok/bytecode/PreventNullAnalysisRemover -instanceKlass lombok/core/PostCompilerTransformation -instanceKlass com/sun/tools/javac/jvm/ClassFile$NameAndType -instanceKlass com/sun/tools/javac/jvm/ClassWriter$1 -instanceKlass lombok/core/PostCompiler -instanceKlass lombok/javac/apt/InterceptingJavaFileObject -instanceKlass com/sun/tools/javac/code/Kinds$1 -instanceKlass com/sun/tools/javac/code/Kinds -instanceKlass com/sun/tools/javac/code/Types$MethodFilter -instanceKlass com/sun/tools/javac/code/Types$CandidatesCache$Entry -instanceKlass com/sun/tools/javac/code/Types$DescriptorFilter -instanceKlass com/sun/tools/javac/comp/Resolve$MostSpecificCheck -instanceKlass com/sun/tools/javac/tree/TreeInfo$PosKind$$Lambda$411 -instanceKlass com/sun/tools/javac/tree/TreeInfo$PosKind$$Lambda$410 -instanceKlass com/sun/tools/javac/tree/TreeInfo$PosKind$$Lambda$409 -instanceKlass com/sun/tools/javac/jvm/ClassWriter$StackMapTableFrame -instanceKlass com/sun/tools/javac/jvm/Code$StackMapFrame -instanceKlass com/sun/tools/javac/jvm/Code$Chain -instanceKlass com/sun/tools/javac/model/FilteredMemberList$$Lambda$408 -instanceKlass com/sun/tools/javac/jvm/Code$LocalVar$Range -instanceKlass com/sun/tools/javac/jvm/Items -instanceKlass com/sun/tools/javac/jvm/Code$LocalVar -instanceKlass com/sun/tools/javac/jvm/Code$State -instanceKlass com/sun/tools/javac/jvm/Gen$GenContext -instanceKlass com/sun/tools/javac/jvm/Gen$3 -instanceKlass com/sun/tools/javac/comp/Lower$2 -instanceKlass com/sun/tools/javac/comp/Flow$1 -instanceKlass com/sun/tools/javac/resources/CompilerProperties$Errors -instanceKlass com/sun/tools/javac/util/Bits$1 -instanceKlass com/sun/tools/javac/util/Bits -instanceKlass com/sun/tools/javac/comp/Flow$BaseAnalyzer$PendingExit -instanceKlass com/sun/tools/javac/comp/InferenceContext$$Lambda$407 -instanceKlass com/sun/tools/javac/code/Type$UndetVar$$Lambda$406 -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass com/sun/tools/javac/comp/Infer$BoundFilter -instanceKlass com/sun/tools/javac/util/GraphUtils$Tarjan -instanceKlass com/sun/tools/javac/util/GraphUtils -instanceKlass com/sun/tools/javac/util/GraphUtils$AbstractNode -instanceKlass com/sun/tools/javac/util/GraphUtils$DottableNode -instanceKlass com/sun/tools/javac/util/GraphUtils$Node -instanceKlass com/sun/tools/javac/comp/InferenceContext$$Lambda$405 -instanceKlass com/sun/tools/javac/comp/Infer$GraphSolver$InferenceGraph -instanceKlass com/sun/tools/javac/code/Types$$Lambda$404 -instanceKlass com/sun/tools/javac/code/Types$$Lambda$403 -instanceKlass com/sun/tools/javac/code/Types$$Lambda$402 -instanceKlass java/lang/invoke/LambdaForm$MH -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass com/sun/tools/javac/code/Types$$Lambda$401 -instanceKlass com/sun/tools/javac/code/Types$ClosureHolder -instanceKlass com/sun/tools/javac/comp/Infer$CheckUpperBounds$$Lambda$400 -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass com/sun/tools/javac/comp/Infer$IncorporationBinaryOp -instanceKlass com/sun/tools/javac/comp/Infer$GraphSolver -instanceKlass com/sun/tools/javac/comp/Infer$LeafSolver -instanceKlass com/sun/tools/javac/comp/Check$$Lambda$399 -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass java/util/ArrayDeque$$Lambda$398 -instanceKlass com/sun/tools/javac/comp/Infer$CheckBounds$$Lambda$397 -instanceKlass com/sun/tools/javac/comp/Infer$IncorporationAction -instanceKlass com/sun/tools/javac/code/Types$MembersClosureCache$MembersScope$$Lambda$396 -instanceKlass com/sun/tools/javac/comp/Resolve$17 -instanceKlass com/sun/tools/javac/comp/DeferredAttr$6 -instanceKlass com/sun/tools/javac/comp/DeferredAttr$FilterScanner$$Lambda$395 -instanceKlass com/sun/tools/javac/comp/Infer$FreeTypeListener -instanceKlass com/sun/tools/javac/comp/DeferredAttr$DeferredType$SpeculativeCache -instanceKlass com/sun/tools/javac/comp/DeferredAttr$DeferredAttrDiagHandler$$Lambda$394 -instanceKlass com/sun/tools/javac/comp/DeferredAttr$$Lambda$393 -instanceKlass com/sun/tools/javac/comp/ArgumentAttr$$Lambda$392 -instanceKlass com/sun/tools/javac/comp/ArgumentAttr$UniquePos -instanceKlass com/sun/tools/javac/comp/ArgumentAttr$$Lambda$391 -instanceKlass com/sun/tools/javac/comp/Operators$1 -instanceKlass com/sun/tools/javac/util/List$$Lambda$390 -instanceKlass com/sun/tools/javac/util/List$$Lambda$389 -instanceKlass com/sun/tools/javac/util/List$$Lambda$388 -instanceKlass com/sun/tools/javac/util/List$$Lambda$387 -instanceKlass com/sun/tools/javac/comp/Operators$$Lambda$386 -instanceKlass com/sun/tools/javac/comp/Operators$OperatorHelper$$Lambda$385 -instanceKlass com/sun/tools/javac/comp/Operators$OperatorHelper$$Lambda$384 -instanceKlass com/sun/tools/javac/comp/Operators$OperatorHelper$$Lambda$383 -instanceKlass com/sun/tools/javac/comp/Operators$BinaryOperatorHelper$$Lambda$382 -instanceKlass com/sun/tools/javac/comp/Operators$$Lambda$381 -instanceKlass com/sun/tools/javac/comp/Operators$$Lambda$380 -instanceKlass com/sun/tools/javac/comp/Operators$$Lambda$379 -instanceKlass com/sun/tools/javac/comp/Resolve$MethodCheckContext -instanceKlass com/sun/tools/javac/comp/Check$ClashFilter -instanceKlass com/sun/tools/javac/code/Scope$CompoundScope$$Lambda$378 -instanceKlass com/sun/tools/javac/code/Scope$CompoundScope$$Lambda$377 -instanceKlass com/sun/tools/javac/comp/Check$DefaultMethodClashFilter -instanceKlass com/sun/tools/javac/main/JavaCompiler$2 -instanceKlass org/springframework/boot/configurationprocessor/json/JSONStringer -instanceKlass org/springframework/boot/configurationprocessor/json/JSON -instanceKlass java/util/stream/SortedOps$RefSortingSink$$Lambda$376 -instanceKlass org/springframework/boot/configurationprocessor/metadata/JsonConverter$$Lambda$375 -instanceKlass org/springframework/boot/configurationprocessor/json/JSONArray -instanceKlass org/springframework/boot/configurationprocessor/metadata/JsonConverter$ItemMetadataComparator$$Lambda$374 -instanceKlass org/springframework/boot/configurationprocessor/metadata/JsonConverter$ItemMetadataComparator$$Lambda$373 -instanceKlass org/springframework/boot/configurationprocessor/metadata/JsonConverter$ItemMetadataComparator$$Lambda$372 -instanceKlass java/util/Comparators$NullComparator -instanceKlass org/springframework/boot/configurationprocessor/metadata/JsonConverter$ItemMetadataComparator$$Lambda$371 -instanceKlass org/springframework/boot/configurationprocessor/metadata/JsonConverter$ItemMetadataComparator$$Lambda$370 -instanceKlass org/springframework/boot/configurationprocessor/metadata/JsonConverter$ItemMetadataComparator -instanceKlass org/springframework/boot/configurationprocessor/metadata/JsonConverter -instanceKlass org/springframework/boot/configurationprocessor/json/JSONObject$1 -instanceKlass org/springframework/boot/configurationprocessor/json/JSONObject -instanceKlass org/springframework/boot/configurationprocessor/metadata/JsonMarshaller -instanceKlass java/util/ComparableTimSort -instanceKlass org/springframework/boot/configurationprocessor/metadata/ConfigurationMetadata$$Lambda$369 -instanceKlass net/dreamlu/mica/auto/service/ServicesFiles -instanceKlass net/dreamlu/mica/auto/common/MultiSetMap$$Lambda$368 -instanceKlass java/nio/file/Path$1 -instanceKlass net/dreamlu/mica/auto/factories/FactoriesFiles -instanceKlass com/sun/tools/javac/code/Symtab$$Lambda$367 -instanceKlass com/sun/tools/javac/code/Symtab$$Lambda$366 -instanceKlass com/sun/tools/javac/processing/JavacProcessingEnvironment$ImplicitCompleter -instanceKlass com/sun/tools/javac/processing/JavacProcessingEnvironment$2 -instanceKlass org/springframework/boot/autoconfigureprocessor/Elements -instanceKlass org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessor$AbstractValueExtractor -instanceKlass org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessor$ValueExtractor -instanceKlass org/springframework/boot/configurationprocessor/MetadataGenerationEnvironment$$Lambda$365 -instanceKlass org/springframework/boot/configurationprocessor/MetadataGenerationEnvironment$$Lambda$364 -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass java/util/stream/Collectors$$Lambda$363 -instanceKlass java/util/stream/Collectors$$Lambda$362 -instanceKlass java/util/stream/Collectors$$Lambda$361 -instanceKlass java/util/stream/Collectors$$Lambda$360 -instanceKlass org/springframework/boot/configurationprocessor/TypeUtils$TypeExtractor$$Lambda$359 -instanceKlass org/springframework/boot/configurationprocessor/metadata/ConfigurationMetadata -instanceKlass org/springframework/boot/configurationprocessor/MetadataGenerationEnvironment$$Lambda$358 -instanceKlass org/springframework/boot/configurationprocessor/fieldvalues/javac/Tree$TreeVisitorInvocationHandler -instanceKlass java/lang/Short$ShortCache -instanceKlass org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesParser$FieldCollector -instanceKlass org/springframework/boot/configurationprocessor/MetadataGenerationEnvironment$$Lambda$357 -instanceKlass org/springframework/boot/configurationprocessor/TypeUtils$TypeDescriptor -instanceKlass org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessor$$Lambda$356 -instanceKlass org/springframework/boot/configurationprocessor/TypeElementMembers$$Lambda$355 -instanceKlass org/springframework/boot/configurationprocessor/PropertyDescriptorResolver$$Lambda$354 -instanceKlass org/springframework/boot/configurationprocessor/TypeElementMembers$$Lambda$353 -instanceKlass org/springframework/boot/configurationprocessor/PropertyDescriptorResolver$$Lambda$352 -instanceKlass org/springframework/boot/configurationprocessor/PropertyDescriptorResolver$ConfigurationPropertiesTypeElement$$Lambda$351 -instanceKlass org/springframework/boot/configurationprocessor/PropertyDescriptorResolver$ConfigurationPropertiesTypeElement -instanceKlass org/springframework/boot/configurationprocessor/TypeElementMembers$$Lambda$350 -instanceKlass org/springframework/boot/configurationprocessor/TypeElementMembers$$Lambda$349 -instanceKlass com/sun/tools/javac/code/Type$5 -instanceKlass org/springframework/boot/configurationprocessor/TypeElementMembers$$Lambda$348 -instanceKlass org/springframework/boot/configurationprocessor/TypeElementMembers$$Lambda$347 -instanceKlass org/springframework/boot/configurationprocessor/TypeElementMembers -instanceKlass org/springframework/boot/configurationprocessor/PropertyDescriptor -instanceKlass org/springframework/boot/configurationprocessor/PropertyDescriptorResolver -instanceKlass org/springframework/boot/configurationprocessor/metadata/ItemMetadata -instanceKlass com/sun/tools/javac/util/Constants -instanceKlass org/springframework/boot/configurationprocessor/MetadataGenerationEnvironment$$Lambda$346 -instanceKlass org/springframework/boot/configurationprocessor/fieldvalues/javac/ReflectionWrapper -instanceKlass org/springframework/boot/configurationprocessor/fieldvalues/javac/TreeVisitor -instanceKlass org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesParser -instanceKlass org/springframework/boot/configurationprocessor/fieldvalues/FieldValuesParser -instanceKlass org/springframework/boot/configurationprocessor/MetadataGenerationEnvironment -instanceKlass com/sun/tools/javac/model/JavacTypes$1 -instanceKlass org/springframework/boot/configurationprocessor/TypeUtils$$Lambda$345 -instanceKlass javax/lang/model/util/AbstractTypeVisitor6 -instanceKlass java/util/EnumMap$EntryIterator$Entry -instanceKlass java/util/EnumMap$EnumMapIterator -instanceKlass org/springframework/boot/configurationprocessor/TypeUtils$$Lambda$344 -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass org/springframework/boot/configurationprocessor/TypeUtils -instanceKlass javax/tools/ForwardingFileObject -instanceKlass com/sun/tools/javac/processing/JavacFiler$Tuple3 -instanceKlass org/springframework/boot/configurationprocessor/MetadataCollector -instanceKlass org/springframework/boot/configurationprocessor/MetadataStore -instanceKlass net/dreamlu/mica/auto/service/AutoServiceProcessor$1$$Lambda$343 -instanceKlass javax/lang/model/util/AbstractAnnotationValueVisitor6 -instanceKlass javax/lang/model/util/ElementFilter -instanceKlass net/dreamlu/mica/auto/service/AutoServiceProcessor$$Lambda$342 -instanceKlass net/dreamlu/mica/auto/service/AutoServiceProcessor$$Lambda$341 -instanceKlass net/dreamlu/mica/auto/service/AutoServiceProcessor$$Lambda$340 -instanceKlass net/dreamlu/mica/auto/annotation/AutoService -instanceKlass javax/lang/model/element/AnnotationValueVisitor -instanceKlass net/dreamlu/mica/auto/common/MultiSetMap$$Lambda$339 -instanceKlass net/dreamlu/mica/auto/annotation/AutoLoggingSystemFactory -instanceKlass net/dreamlu/mica/auto/annotation/AutoDependsOnDatabaseInitializationDetector -instanceKlass net/dreamlu/mica/auto/annotation/AutoDatabaseInitializerDetector -instanceKlass net/dreamlu/mica/auto/annotation/AutoConfigDataLoader -instanceKlass net/dreamlu/mica/auto/annotation/AutoConfigDataLocationResolver -instanceKlass net/dreamlu/mica/auto/annotation/AutoEnableCircuitBreaker -instanceKlass net/dreamlu/mica/auto/annotation/AutoTemplateProvider -instanceKlass net/dreamlu/mica/auto/annotation/AutoConfigImportFilter -instanceKlass net/dreamlu/mica/auto/annotation/AutoFailureAnalyzer -instanceKlass net/dreamlu/mica/auto/annotation/AutoEnvPostProcessor -instanceKlass net/dreamlu/mica/auto/annotation/AutoRunListener -instanceKlass net/dreamlu/mica/auto/annotation/AutoListener -instanceKlass net/dreamlu/mica/auto/annotation/AutoContextInitializer -instanceKlass net/dreamlu/mica/auto/annotation/AutoIgnore -instanceKlass net/dreamlu/mica/auto/factories/AutoFactoriesProcessor$$Lambda$338 -instanceKlass net/dreamlu/mica/auto/factories/AutoFactoriesProcessor$$Lambda$337 -instanceKlass net/dreamlu/mica/auto/factories/AutoFactoriesProcessor$$Lambda$336 -instanceKlass net/dreamlu/mica/auto/common/MultiSetMap -instanceKlass lombok/javac/handlers/JavacHandlerUtil$ClassSymbolMembersField -instanceKlass lombok/RequiredArgsConstructor$AnyAnnotation -instanceKlass lombok/javac/handlers/HandleLog -instanceKlass lombok/core/handlers/LoggingFramework -instanceKlass lombok/javac/handlers/JavacHandlerUtil$CopyJavadoc$6 -instanceKlass lombok/Setter$AnyAnnotation -instanceKlass lombok/javac/Javac$JavadocOps_8$1 -instanceKlass lombok/core/configuration/ConfigurationSource -instanceKlass com/sun/tools/javac/tree/Pretty$1 -instanceKlass com/sun/tools/javac/code/DeferredCompletionFailureHandler$DeferredCompleter -instanceKlass com/sun/tools/javac/comp/Annotate$AnnotationContext -instanceKlass lombok/javac/handlers/JavacHandlerUtil$EnterReflect -instanceKlass lombok/core/CleanupRegistry$CleanupKey -instanceKlass lombok/javac/handlers/JavacHandlerUtil$CopyJavadoc$2$1 -instanceKlass lombok/javac/Javac$JavadocOps_8 -instanceKlass lombok/core/CleanupTask -instanceKlass lombok/core/AnnotationValues$1 -instanceKlass lombok/delombok/FormatPreferences -instanceKlass lombok/delombok/LombokOptionsFactory -instanceKlass lombok/core/configuration/AllowHelper -instanceKlass java/util/regex/Pattern$$Lambda$335 -instanceKlass lombok/experimental/FieldDefaults -instanceKlass lombok/core/handlers/HandlerUtil -instanceKlass lombok/core/AnnotationValues -instanceKlass lombok/core/AnnotationValues$AnnotationValue -instanceKlass lombok/Getter$AnyAnnotation -instanceKlass lombok/core/FieldAugment -instanceKlass lombok/javac/JavacAugments -instanceKlass lombok/core/TypeResolver -instanceKlass lombok/core/LombokImmutableList$1 -instanceKlass lombok/core/AST$FieldAccess -instanceKlass lombok/javac/JavacImportList -instanceKlass lombok/javac/PackageName -instanceKlass lombok/core/configuration/FileSystemSourceCache$Content -instanceKlass lombok/core/configuration/ConfigurationFile -instanceKlass lombok/core/configuration/BubblingConfigurationResolver -instanceKlass lombok/core/LombokConfiguration$3 -instanceKlass lombok/core/configuration/FileSystemSourceCache$1 -instanceKlass lombok/core/configuration/ConfigurationProblemReporter$1 -instanceKlass lombok/core/configuration/ConfigurationProblemReporter -instanceKlass lombok/core/configuration/ConfigurationParser -instanceKlass lombok/core/configuration/ConfigurationFileToSource -instanceKlass lombok/core/configuration/FileSystemSourceCache -instanceKlass lombok/core/LombokConfiguration$1 -instanceKlass lombok/core/configuration/ConfigurationResolverFactory -instanceKlass lombok/core/configuration/ConfigurationResolver -instanceKlass lombok/core/LombokConfiguration -instanceKlass sun/nio/fs/WindowsUriSupport -instanceKlass lombok/core/ImportList -instanceKlass lombok/javac/JavacAST$ErrorLog -instanceKlass java/util/IdentityHashMap$EntryIterator$Entry -instanceKlass com/sun/tools/javac/model/JavacElements$1 -instanceKlass javax/annotation/processing/SupportedOptions -instanceKlass com/sun/tools/javac/util/MatchingUtils -instanceKlass javax/annotation/processing/SupportedAnnotationTypes -instanceKlass lombok/javac/HandlerLibrary$VisitorContainer -instanceKlass lombok/experimental/WithBy -instanceKlass lombok/With -instanceKlass lombok/Value -instanceKlass lombok/javac/JavacASTAdapter -instanceKlass lombok/experimental/UtilityClass -instanceKlass lombok/ToString -instanceKlass lombok/Synchronized -instanceKlass lombok/experimental/SuperBuilder -instanceKlass lombok/javac/handlers/JavacSingularsRecipes$StatementMaker -instanceKlass lombok/javac/handlers/JavacSingularsRecipes$ExpressionMaker -instanceKlass lombok/javac/handlers/HandleBuilder$BuilderJob -instanceKlass lombok/experimental/StandardException -instanceKlass lombok/SneakyThrows -instanceKlass lombok/Singular -instanceKlass lombok/Setter -instanceKlass lombok/core/PrintAST -instanceKlass lombok/NonNull -instanceKlass lombok/extern/slf4j/XSlf4j -instanceKlass lombok/extern/slf4j/Slf4j -instanceKlass lombok/extern/log4j/Log4j -instanceKlass lombok/extern/log4j/Log4j2 -instanceKlass lombok/extern/java/Log -instanceKlass lombok/extern/jbosslog/JBossLog -instanceKlass lombok/extern/flogger/Flogger -instanceKlass lombok/CustomLog -instanceKlass lombok/extern/apachecommons/CommonsLog -instanceKlass lombok/extern/jackson/Jacksonized -instanceKlass lombok/experimental/Helper -instanceKlass lombok/Getter -instanceKlass lombok/experimental/FieldNameConstants -instanceKlass lombok/core/LombokImmutableList -instanceKlass lombok/core/JavaIdentifiers -instanceKlass lombok/experimental/ExtensionMethod -instanceKlass lombok/EqualsAndHashCode -instanceKlass lombok/experimental/Delegate -instanceKlass lombok/Data -instanceKlass lombok/RequiredArgsConstructor -instanceKlass lombok/NoArgsConstructor -instanceKlass lombok/AllArgsConstructor -instanceKlass lombok/Cleanup -instanceKlass lombok/Builder$Default -instanceKlass lombok/Builder -instanceKlass lombok/javac/handlers/HandleConstructor -instanceKlass lombok/core/LombokInternalAliasing -instanceKlass lombok/core/AlreadyHandledAnnotations -instanceKlass lombok/javac/ResolutionResetNeeded -instanceKlass lombok/core/HandlerPriority -instanceKlass lombok/javac/HandlerLibrary$AnnotationHandlerContainer -instanceKlass lombok/experimental/Accessors -instanceKlass lombok/javac/JavacAnnotationHandler -instanceKlass lombok/core/SpiLoadUtil$1$1 -instanceKlass lombok/core/SpiLoadUtil$1 -instanceKlass java/util/Vector$1 -instanceKlass lombok/core/SpiLoadUtil -instanceKlass lombok/core/configuration/ConfigurationKeysLoader -instanceKlass lombok/core/configuration/CheckerFrameworkVersion -instanceKlass lombok/core/configuration/TypeName -instanceKlass lombok/core/configuration/LogDeclaration -instanceKlass lombok/core/configuration/IdentifierName -instanceKlass lombok/core/configuration/ConfigurationDataType$6 -instanceKlass lombok/core/configuration/ConfigurationDataType$7 -instanceKlass lombok/core/configuration/NullAnnotationLibrary -instanceKlass lombok/core/configuration/ConfigurationValueType -instanceKlass lombok/core/configuration/ConfigurationDataType$5 -instanceKlass lombok/core/configuration/ConfigurationDataType$4 -instanceKlass lombok/core/configuration/ConfigurationDataType$3 -instanceKlass lombok/core/configuration/ConfigurationDataType$2 -instanceKlass lombok/core/configuration/ConfigurationDataType$1 -instanceKlass lombok/core/configuration/ConfigurationValueParser -instanceKlass lombok/core/configuration/ConfigurationDataType -instanceKlass lombok/core/configuration/ConfigurationKey -instanceKlass lombok/ConfigurationKeys -instanceKlass lombok/core/configuration/ConfigurationKeysLoader$LoaderLoader -instanceKlass lombok/core/TypeLibrary -instanceKlass lombok/javac/HandlerLibrary -instanceKlass lombok/javac/JavacASTVisitor -instanceKlass lombok/javac/JavacTransformer -instanceKlass java/text/BreakIterator -instanceKlass com/sun/source/util/DocTreePath -instanceKlass com/sun/tools/javac/api/JavacScope -instanceKlass com/sun/source/util/TreePath -instanceKlass lombok/core/AST -instanceKlass lombok/core/LombokNode -instanceKlass lombok/javac/handlers/JavacHandlerUtil -instanceKlass lombok/javac/JavacTreeMaker$FieldId -instanceKlass lombok/javac/JavacTreeMaker$MethodId -instanceKlass lombok/javac/JavacTreeMaker -instanceKlass javax/lang/model/type/TypeVisitor -instanceKlass lombok/javac/JavacTreeMaker$SchroedingerType -instanceKlass lombok/javac/Javac -instanceKlass lombok/javac/apt/Java9Compiler -instanceKlass lombok/javac/apt/LombokFileObjects$Compiler -instanceKlass lombok/javac/apt/LombokFileObject -instanceKlass lombok/javac/apt/LombokFileObjects -instanceKlass lombok/javac/apt/MessagerDiagnosticsReceiver -instanceKlass javax/tools/ForwardingJavaFileManager -instanceKlass lombok/permit/dummy/Parent -instanceKlass java/lang/Class$EnclosingMethodInfo -instanceKlass lombok/core/CleanupRegistry -instanceKlass lombok/permit/Permit -instanceKlass lombok/core/DiagnosticsReceiver -instanceKlass lombok/launch/AnnotationProcessorHider$AstModificationNotifierData -instanceKlass lombok/core/AnnotationProcessor$ProcessorDescriptor -instanceKlass lombok/launch/ClassFileMetaData -instanceKlass java/util/zip/ZipFile$ZipEntryIterator -instanceKlass java/util/jar/JarFile$$Lambda$334 -instanceKlass java/net/URLEncoder -instanceKlass java/net/URLDecoder -instanceKlass lombok/launch/PackageShader -instanceKlass lombok/launch/Main -instanceKlass com/sun/tools/javac/processing/JavacProcessingEnvironment$ProcessorState -instanceKlass com/sun/tools/javac/processing/JavacRoundEnvironment -instanceKlass javax/lang/model/util/AbstractElementVisitor6 -instanceKlass javax/lang/model/element/ElementVisitor -instanceKlass com/sun/tools/javac/processing/JavacProcessingEnvironment$Round -instanceKlass com/sun/tools/javac/code/TypeAnnotationPosition$TypePathEntry -instanceKlass com/sun/tools/javac/code/TypeAnnotations$$Lambda$333 -instanceKlass com/sun/tools/javac/code/TypeAnnotations$$Lambda$332 -instanceKlass com/sun/tools/javac/code/TypeAnnotations$$Lambda$331 -instanceKlass com/sun/tools/javac/code/TypeAnnotations$1 -instanceKlass com/sun/tools/javac/code/TypeAnnotationPosition -instanceKlass com/sun/tools/javac/code/Types$TypePair -instanceKlass com/sun/tools/javac/code/Symtab$$Lambda$330 -instanceKlass com/sun/tools/javac/code/Types$UniqueType -instanceKlass com/sun/tools/javac/code/Flags -instanceKlass com/sun/tools/javac/comp/Resolve$MethodResolutionContext$Candidate -instanceKlass com/sun/tools/javac/code/Types$ImplementationCache$Entry -instanceKlass com/sun/tools/javac/code/Types$$Lambda$329 -instanceKlass com/sun/tools/javac/comp/Resolve$LookupFilter -instanceKlass com/sun/tools/javac/comp/Resolve$5 -instanceKlass com/sun/tools/javac/comp/Resolve$$Lambda$328 -instanceKlass com/sun/tools/javac/comp/Resolve$MethodResolutionContext -instanceKlass com/sun/tools/javac/code/Types$25 -instanceKlass com/sun/tools/javac/tree/TreeMaker$1 -instanceKlass com/sun/tools/javac/jvm/ClassReader$ParameterAnnotations -instanceKlass com/sun/tools/javac/comp/Annotate$$Lambda$327 -instanceKlass com/sun/tools/javac/comp/Annotate$$Lambda$326 -instanceKlass com/sun/tools/javac/code/Types$TypeMapping$$Lambda$325 -instanceKlass com/sun/tools/javac/code/Symbol$VarSymbol$$Lambda$324 -instanceKlass com/sun/tools/javac/comp/TypeEnter$1 -instanceKlass com/sun/tools/javac/comp/Check$$Lambda$323 -instanceKlass com/sun/tools/javac/comp/Check$$Lambda$322 -instanceKlass com/sun/tools/javac/comp/TypeEnter$$Lambda$321 -instanceKlass com/sun/tools/javac/code/TypeAnnotations$$Lambda$320 -instanceKlass com/sun/tools/javac/code/TypeAnnotations$$Lambda$319 -instanceKlass com/sun/tools/javac/util/Iterators$2 -instanceKlass com/sun/tools/javac/code/Scope$FilterImportScope$$Lambda$318 -instanceKlass com/sun/tools/javac/code/Scope$FilterImportScope$$Lambda$317 -instanceKlass com/sun/tools/javac/code/Scope$FilterImportScope$$Lambda$316 -instanceKlass com/sun/tools/javac/code/Scope$CompoundScope$$Lambda$315 -instanceKlass com/sun/tools/javac/code/Scope$CompoundScope$$Lambda$314 -instanceKlass com/sun/tools/javac/comp/Annotate$$Lambda$313 -instanceKlass com/sun/tools/javac/comp/Annotate$$Lambda$312 -instanceKlass com/sun/tools/javac/comp/Annotate$$Lambda$311 -instanceKlass com/sun/tools/javac/code/SymbolMetadata -instanceKlass com/sun/tools/javac/code/Scope$NamedImportScope$$Lambda$310 -instanceKlass com/sun/tools/javac/code/Scope$NamedImportScope$$Lambda$309 -instanceKlass com/sun/tools/javac/code/Scope$ScopeImpl$$Lambda$308 -instanceKlass com/sun/tools/javac/jvm/ClassReader$CompleterDeproxy -instanceKlass com/sun/tools/javac/jvm/ClassReader$AnnotationDeproxy -instanceKlass com/sun/tools/javac/jvm/ClassReader$ProxyVisitor -instanceKlass com/sun/tools/javac/code/TypeTag$1 -instanceKlass com/sun/tools/javac/jvm/ClassReader$26 -instanceKlass com/sun/tools/javac/jvm/Code$1 -instanceKlass com/sun/tools/javac/jvm/ClassReader$SourceFileObject -instanceKlass com/sun/tools/javac/code/ClassFinder$$Lambda$307 -instanceKlass java/nio/file/FileTreeWalker$1 -instanceKlass com/sun/tools/javac/comp/Attr$10 -instanceKlass com/sun/tools/javac/code/Scope$FilterImportScope$SymbolImporter -instanceKlass jdk/internal/jrtfs/JrtFileAttributes -instanceKlass java/util/stream/StreamSpliterators$WrappingSpliterator$$Lambda$306 -instanceKlass java/util/function/BooleanSupplier -instanceKlass java/util/stream/StreamSpliterators$WrappingSpliterator$$Lambda$305 -instanceKlass java/util/stream/AbstractSpinedBuffer -instanceKlass jdk/internal/jrtfs/JrtDirectoryStream$1 -instanceKlass java/util/stream/StreamSpliterators$AbstractWrappingSpliterator -instanceKlass java/util/stream/AbstractPipeline$$Lambda$304 -instanceKlass jdk/internal/jrtfs/JrtFileSystem$$Lambda$303 -instanceKlass jdk/internal/jrtfs/JrtFileSystem$$Lambda$302 -instanceKlass jdk/internal/jrtfs/JrtDirectoryStream -instanceKlass com/sun/tools/javac/comp/TypeEnter$ImportsPhase$$Lambda$301 -instanceKlass com/sun/tools/javac/comp/TypeEnter$ImportsPhase$$Lambda$300 -instanceKlass com/sun/tools/javac/code/Scope$ImportFilter -instanceKlass com/sun/tools/javac/code/Scope$ScopeImpl$2 -instanceKlass com/sun/tools/javac/code/Scope$ScopeImpl$$Lambda$299 -instanceKlass com/sun/tools/javac/comp/Check$5 -instanceKlass com/sun/tools/javac/util/Pair -instanceKlass com/sun/tools/javac/comp/AttrContext -instanceKlass com/sun/tools/javac/comp/Enter$$Lambda$298 -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass com/sun/tools/javac/comp/Enter$$Lambda$297 -instanceKlass com/sun/tools/javac/code/Scope$ScopeImpl$1 -instanceKlass com/sun/tools/javac/code/Scope$ScopeImpl$$Lambda$296 -instanceKlass com/sun/tools/javac/code/ClassFinder$2 -instanceKlass java/nio/file/Files$$Lambda$295 -instanceKlass java/nio/file/Files$2 -instanceKlass sun/nio/fs/WindowsDirectoryStream$WindowsDirectoryIterator -instanceKlass jdk/nio/zipfs/JarFileSystem$$Lambda$294 -instanceKlass jdk/nio/zipfs/JarFileSystem$$Lambda$293 -instanceKlass sun/nio/fs/BasicFileAttributesHolder -instanceKlass java/nio/file/Files$3 -instanceKlass java/nio/file/FileTreeWalker$Event -instanceKlass jdk/nio/zipfs/ZipDirectoryStream$1 -instanceKlass java/nio/file/FileTreeWalker$DirectoryNode -instanceKlass jdk/nio/zipfs/ZipDirectoryStream -instanceKlass java/nio/file/Files$AcceptAllFilter -instanceKlass java/nio/file/FileTreeWalker -instanceKlass java/nio/file/SimpleFileVisitor -instanceKlass jdk/nio/zipfs/ZipUtils -instanceKlass jdk/nio/zipfs/JarFileSystem$$Lambda$292 -instanceKlass jdk/internal/util/ArraysSupport -instanceKlass jdk/nio/zipfs/ZipFileSystem$END -instanceKlass jdk/nio/zipfs/ZipConstants -instanceKlass jdk/nio/zipfs/ZipPath -instanceKlass jdk/nio/zipfs/ZipCoder -instanceKlass sun/nio/fs/WindowsSecurity -instanceKlass sun/nio/fs/AbstractAclFileAttributeView -instanceKlass java/nio/file/attribute/AclFileAttributeView -instanceKlass java/nio/file/attribute/FileOwnerAttributeView -instanceKlass jdk/nio/zipfs/ZipFileSystem$$Lambda$291 -instanceKlass jdk/nio/zipfs/ZipFileSystem$$Lambda$290 -instanceKlass java/nio/file/PathMatcher -instanceKlass jdk/nio/zipfs/ZipFileAttributes -instanceKlass jdk/nio/zipfs/ZipFileSystem$IndexNode -instanceKlass java/nio/file/FileVisitor -instanceKlass com/sun/tools/javac/file/JavacFileManager$ArchiveContainer -instanceKlass com/sun/tools/javac/file/JavacFileManager$DirectoryContainer -instanceKlass com/sun/tools/javac/code/ClassFinder$1 -instanceKlass com/sun/tools/javac/code/ClassFinder$$Lambda$289 -instanceKlass com/sun/tools/javac/file/JRTIndex$CtSym -instanceKlass com/sun/tools/javac/file/JRTIndex$Entry -instanceKlass jdk/internal/jimage/ImageReader$SharedImageReader$$Lambda$288 -instanceKlass jdk/internal/jimage/ImageReader$SharedImageReader$$Lambda$287 -instanceKlass jdk/internal/jimage/ImageReader$SharedImageReader$LocationVisitor -instanceKlass com/sun/tools/javac/file/JavacFileManager$JRTImageContainer -instanceKlass com/sun/tools/javac/code/ClassFinder$$Lambda$286 -instanceKlass com/sun/tools/javac/comp/Modules$$Lambda$285 -instanceKlass com/sun/tools/javac/tree/JCTree$1 -instanceKlass java/util/stream/Collectors$$Lambda$284 -instanceKlass java/util/stream/Collectors$$Lambda$283 -instanceKlass java/util/stream/Collectors$$Lambda$282 -instanceKlass java/util/stream/Collectors$$Lambda$281 -instanceKlass com/sun/tools/javac/parser/JavacParser$$Lambda$280 -instanceKlass java/util/BitSet -instanceKlass com/sun/tools/javac/util/Position$LineMapImpl -instanceKlass com/sun/tools/javac/util/Position$LineMap -instanceKlass com/sun/tools/javac/util/Position -instanceKlass com/sun/tools/javac/tree/TreeMaker$$Lambda$279 -instanceKlass com/sun/tools/javac/parser/LazyDocCommentTable$Entry -instanceKlass com/sun/tools/javac/tree/TreeInfo$2 -instanceKlass com/sun/tools/javac/tree/TreeInfo -instanceKlass com/sun/tools/javac/parser/JavacParser$1 -instanceKlass com/sun/tools/javac/util/IntHashTable -instanceKlass com/sun/tools/javac/parser/LazyDocCommentTable -instanceKlass com/sun/tools/javac/parser/JavaTokenizer$1 -instanceKlass com/sun/tools/javac/parser/JavaTokenizer$BasicComment -instanceKlass com/sun/tools/javac/parser/JavacParser$$Lambda$278 -instanceKlass com/sun/tools/javac/parser/JavacParser$AbstractEndPosTable -instanceKlass com/sun/tools/javac/parser/JavacParser$ErrorRecoveryAction -instanceKlass com/sun/tools/javac/tree/EndPosTable -instanceKlass com/sun/tools/javac/parser/JavacParser -instanceKlass com/sun/tools/javac/parser/UnicodeReader -instanceKlass java/util/regex/CharPredicates$$Lambda$277 -instanceKlass java/util/regex/CharPredicates$$Lambda$276 -instanceKlass jdk/internal/math/FloatingDecimal$HexFloatPattern -instanceKlass com/sun/tools/javac/parser/Scanner -instanceKlass com/sun/source/tree/LineMap -instanceKlass com/sun/tools/javac/file/BaseFileManager$ContentCacheEntry -instanceKlass com/sun/tools/javac/util/DiagnosticSource -instanceKlass javax/annotation/processing/AbstractProcessor -instanceKlass com/sun/tools/javac/processing/JavacProcessingEnvironment$DiscoveredProcessors$ProcessorStateIterator -instanceKlass com/sun/tools/javac/processing/JavacProcessingEnvironment$DiscoveredProcessors -instanceKlass com/sun/tools/javac/util/Iterators$CompoundIterator -instanceKlass com/sun/tools/javac/util/Iterators$1 -instanceKlass com/sun/tools/javac/util/Iterators -instanceKlass com/sun/tools/javac/processing/JavacProcessingEnvironment$$Lambda$275 -instanceKlass javax/annotation/processing/Processor -instanceKlass com/sun/tools/javac/processing/JavacProcessingEnvironment$ServiceIterator -instanceKlass com/sun/tools/javac/file/JavacFileManager$3 -instanceKlass com/sun/tools/javac/file/JavacFileManager$$Lambda$274 -instanceKlass javax/tools/StandardLocation$2 -instanceKlass com/sun/tools/javac/model/JavacTypes -instanceKlass com/sun/tools/javac/processing/JavacMessager -instanceKlass com/sun/tools/javac/processing/JavacFiler -instanceKlass java/util/regex/Pattern$$Lambda$273 -instanceKlass javax/annotation/processing/Messager -instanceKlass javax/annotation/processing/RoundEnvironment -instanceKlass javax/annotation/processing/Filer -instanceKlass com/sun/tools/javac/processing/JavacProcessingEnvironment -instanceKlass javax/annotation/processing/ProcessingEnvironment -instanceKlass com/sun/tools/javac/util/ForwardingDiagnosticFormatter$ForwardingConfiguration -instanceKlass com/sun/tools/javac/code/Types$DefaultSymbolVisitor -instanceKlass com/sun/tools/javac/util/ForwardingDiagnosticFormatter -instanceKlass com/sun/tools/javac/main/JavaCompiler$$Lambda$272 -instanceKlass com/sun/tools/javac/code/ModuleFinder$ModuleNameFromSourceReader -instanceKlass com/sun/tools/javac/main/JavaCompiler$$Lambda$271 -instanceKlass com/sun/tools/javac/comp/Modules$PackageNameFinder -instanceKlass com/sun/tools/javac/api/MultiTaskListener -instanceKlass com/sun/tools/javac/jvm/Code -instanceKlass com/sun/tools/javac/jvm/Pool -instanceKlass com/sun/tools/javac/jvm/StringConcat -instanceKlass com/sun/tools/javac/jvm/Gen$GenFinalizer -instanceKlass com/sun/tools/javac/jvm/Items$Item -instanceKlass com/sun/tools/javac/parser/JavaTokenizer -instanceKlass com/sun/tools/javac/parser/ScannerFactory -instanceKlass com/sun/tools/javac/parser/Tokens$Token -instanceKlass com/sun/tools/javac/parser/Tokens -instanceKlass com/sun/tools/javac/parser/ReferenceParser -instanceKlass com/sun/tools/javac/model/JavacElements -instanceKlass com/sun/tools/javac/tree/DocCommentTable -instanceKlass com/sun/source/util/DocSourcePositions -instanceKlass com/sun/source/doctree/DocTreeVisitor -instanceKlass com/sun/source/tree/Scope -instanceKlass com/sun/source/util/SourcePositions -instanceKlass com/sun/source/util/Trees -instanceKlass com/sun/source/doctree/UsesTree -instanceKlass com/sun/source/doctree/ValueTree -instanceKlass com/sun/source/doctree/VersionTree -instanceKlass com/sun/source/doctree/ProvidesTree -instanceKlass com/sun/source/doctree/ErroneousTree -instanceKlass com/sun/source/doctree/HiddenTree -instanceKlass com/sun/source/doctree/SerialDataTree -instanceKlass com/sun/source/doctree/SerialTree -instanceKlass com/sun/source/doctree/DocRootTree -instanceKlass com/sun/source/doctree/SeeTree -instanceKlass com/sun/source/doctree/ReturnTree -instanceKlass com/sun/source/doctree/DocCommentTree -instanceKlass com/sun/tools/javac/parser/Tokens$Comment -instanceKlass com/sun/source/doctree/DeprecatedTree -instanceKlass com/sun/source/doctree/ReferenceTree -instanceKlass com/sun/source/doctree/EntityTree -instanceKlass com/sun/source/doctree/InheritDocTree -instanceKlass com/sun/source/doctree/LinkTree -instanceKlass com/sun/source/doctree/ThrowsTree -instanceKlass com/sun/source/doctree/IndexTree -instanceKlass com/sun/source/doctree/DocTypeTree -instanceKlass com/sun/source/doctree/TextTree -instanceKlass com/sun/source/doctree/SummaryTree -instanceKlass com/sun/source/doctree/IdentifierTree -instanceKlass com/sun/source/doctree/ParamTree -instanceKlass com/sun/source/doctree/EndElementTree -instanceKlass com/sun/source/doctree/SinceTree -instanceKlass com/sun/source/doctree/SerialFieldTree -instanceKlass com/sun/source/doctree/LiteralTree -instanceKlass com/sun/source/doctree/AuthorTree -instanceKlass com/sun/source/doctree/CommentTree -instanceKlass com/sun/source/doctree/AttributeTree -instanceKlass com/sun/source/doctree/StartElementTree -instanceKlass com/sun/source/doctree/UnknownInlineTagTree -instanceKlass com/sun/source/doctree/InlineTagTree -instanceKlass com/sun/source/doctree/UnknownBlockTagTree -instanceKlass com/sun/source/doctree/BlockTagTree -instanceKlass com/sun/source/doctree/DocTree -instanceKlass com/sun/tools/javac/tree/DocTreeMaker -instanceKlass com/sun/source/util/DocTreeFactory -instanceKlass com/sun/tools/javac/parser/Lexer -instanceKlass com/sun/tools/javac/parser/ParserFactory -instanceKlass jdk/internal/jimage/ImageReader$Node -instanceKlass jdk/internal/jrtfs/SystemImage$2 -instanceKlass jdk/internal/jrtfs/SystemImage$$Lambda$270 -instanceKlass jdk/internal/jrtfs/SystemImage -instanceKlass jdk/internal/jrtfs/JrtPath -instanceKlass com/sun/tools/javac/file/JRTIndex -instanceKlass com/sun/tools/javac/main/DelegatingJavaFileManager -instanceKlass com/sun/tools/javac/jvm/ClassReader$AttributeReader -instanceKlass com/sun/tools/javac/comp/ConstFold -instanceKlass com/sun/tools/javac/comp/Analyzer$2 -instanceKlass com/sun/tools/javac/comp/Analyzer$1 -instanceKlass com/sun/tools/javac/comp/Analyzer$StatementAnalyzer -instanceKlass com/sun/tools/javac/comp/Analyzer$DeferredAnalysisHelper -instanceKlass com/sun/tools/javac/comp/Analyzer -instanceKlass com/sun/tools/javac/comp/Operators$$Lambda$269 -instanceKlass com/sun/tools/javac/comp/Operators$$Lambda$268 -instanceKlass com/sun/tools/javac/comp/Operators$$Lambda$267 -instanceKlass com/sun/tools/javac/comp/Operators$BinaryNumericOperator$$Lambda$266 -instanceKlass java/lang/invoke/LambdaForm$MH -instanceKlass com/sun/tools/javac/comp/Operators$BinaryOperatorHelper$$Lambda$265 -instanceKlass com/sun/tools/javac/comp/Operators$$Lambda$264 -instanceKlass com/sun/tools/javac/comp/Operators$UnaryOperatorHelper$$Lambda$263 -instanceKlass com/sun/tools/javac/comp/Operators$OperatorType$$Lambda$262 -instanceKlass com/sun/tools/javac/comp/Operators$OperatorType$$Lambda$261 -instanceKlass com/sun/tools/javac/comp/Operators$OperatorType$$Lambda$260 -instanceKlass com/sun/tools/javac/comp/Operators$OperatorType$$Lambda$259 -instanceKlass com/sun/tools/javac/comp/Operators$OperatorType$$Lambda$258 -instanceKlass com/sun/tools/javac/comp/Operators$OperatorType$$Lambda$257 -instanceKlass com/sun/tools/javac/comp/Operators$OperatorType$$Lambda$256 -instanceKlass com/sun/tools/javac/comp/Operators$OperatorType$$Lambda$255 -instanceKlass com/sun/tools/javac/comp/Operators$OperatorType$$Lambda$254 -instanceKlass com/sun/tools/javac/comp/Operators$OperatorType$$Lambda$253 -instanceKlass com/sun/tools/javac/comp/Operators$OperatorType$$Lambda$252 -instanceKlass com/sun/tools/javac/comp/Operators$UnaryNumericOperator$$Lambda$251 -instanceKlass com/sun/tools/javac/comp/Operators$OperatorHelper -instanceKlass com/sun/tools/javac/comp/Operators -instanceKlass com/sun/tools/javac/code/Symtab$2 -instanceKlass com/sun/tools/javac/code/Symtab$1 -instanceKlass com/sun/tools/javac/code/Symbol$MethodSymbol$$Lambda$250 -instanceKlass com/sun/tools/javac/code/Symtab$$Lambda$249 -instanceKlass com/sun/tools/javac/code/Symtab$$Lambda$248 -instanceKlass com/sun/tools/javac/code/Symtab$$Lambda$247 -instanceKlass com/sun/tools/javac/jvm/JNIWriter -instanceKlass com/sun/tools/javac/code/Types$SignatureGenerator -instanceKlass com/sun/tools/javac/code/Preview -instanceKlass com/sun/tools/javac/jvm/ClassWriter$AttributeWriter -instanceKlass com/sun/tools/javac/util/ByteBuffer -instanceKlass com/sun/tools/javac/jvm/ClassFile -instanceKlass com/sun/tools/javac/util/MandatoryWarningHandler -instanceKlass com/sun/tools/javac/code/ModuleFinder$ModuleLocationIterator -instanceKlass com/sun/tools/javac/code/ModuleFinder -instanceKlass com/sun/tools/javac/comp/Flow -instanceKlass com/sun/tools/javac/comp/Infer$GraphStrategy -instanceKlass com/sun/tools/javac/comp/InferenceContext -instanceKlass javax/lang/model/element/TypeParameterElement -instanceKlass com/sun/tools/javac/comp/Infer$AbstractIncorporationEngine -instanceKlass com/sun/tools/javac/code/Type$UndetVar$UndetVarListener -instanceKlass com/sun/tools/javac/comp/Infer -instanceKlass com/sun/tools/javac/util/Dependencies -instanceKlass com/sun/tools/javac/comp/TypeEnvs -instanceKlass com/sun/tools/javac/code/Lint$AugmentVisitor -instanceKlass com/sun/tools/javac/code/TypeAnnotations -instanceKlass com/sun/tools/javac/code/DeferredLintHandler$1 -instanceKlass com/sun/tools/javac/code/DeferredLintHandler -instanceKlass com/sun/tools/javac/comp/TypeEnter$ImportsPhase$$Lambda$246 -instanceKlass com/sun/tools/javac/util/GraphUtils$DependencyKind -instanceKlass com/sun/tools/javac/comp/TypeEnter$Phase -instanceKlass com/sun/tools/javac/comp/TypeEnter -instanceKlass com/sun/tools/javac/code/Types$$Lambda$245 -instanceKlass com/sun/tools/javac/code/Types$CandidatesCache -instanceKlass com/sun/tools/javac/code/Types$ImplementationCache -instanceKlass com/sun/tools/javac/code/Types$3 -instanceKlass com/sun/tools/javac/code/Types$DescriptorCache -instanceKlass com/sun/tools/javac/code/Types -instanceKlass com/sun/tools/javac/tree/TreeMaker$AnnotationBuilder -instanceKlass com/sun/tools/javac/code/Attribute$Visitor -instanceKlass com/sun/tools/javac/tree/TreeMaker -instanceKlass com/sun/tools/javac/tree/JCTree$Factory -instanceKlass com/sun/tools/javac/comp/DeferredAttr$5 -instanceKlass com/sun/tools/javac/comp/DeferredAttr$4 -instanceKlass com/sun/tools/javac/tree/TreeCopier -instanceKlass com/sun/tools/javac/comp/DeferredAttr$DeferredAttrContext -instanceKlass com/sun/tools/javac/comp/DeferredAttr$DeferredStuckPolicy -instanceKlass com/sun/tools/javac/comp/DeferredAttr$DeferredTypeCompleter -instanceKlass com/sun/tools/javac/comp/Resolve$ReferenceLookupResult -instanceKlass com/sun/tools/javac/api/Formattable$LocalizedString -instanceKlass com/sun/tools/javac/comp/Resolve$8 -instanceKlass com/sun/tools/javac/comp/Resolve$7 -instanceKlass com/sun/tools/javac/comp/Resolve$$Lambda$244 -instanceKlass com/sun/tools/javac/comp/Resolve$$Lambda$243 -instanceKlass com/sun/tools/javac/comp/Resolve$6 -instanceKlass com/sun/tools/javac/comp/Resolve$$Lambda$242 -instanceKlass com/sun/tools/javac/comp/Env -instanceKlass com/sun/tools/javac/comp/Resolve$AbstractMethodCheck -instanceKlass com/sun/tools/javac/comp/Resolve$2 -instanceKlass com/sun/tools/javac/code/Scope$ScopeListener -instanceKlass com/sun/tools/javac/comp/Resolve$LookupHelper -instanceKlass com/sun/tools/javac/comp/Resolve$ReferenceChooser -instanceKlass com/sun/tools/javac/comp/Resolve$LogResolveHelper -instanceKlass com/sun/tools/javac/comp/Resolve$RecoveryLoadClass -instanceKlass com/sun/tools/javac/comp/Resolve -instanceKlass com/sun/tools/javac/comp/Check$$Lambda$241 -instanceKlass com/sun/tools/javac/comp/Check$1 -instanceKlass com/sun/tools/javac/util/Warner -instanceKlass com/sun/tools/javac/util/Filter -instanceKlass com/sun/tools/javac/comp/Check -instanceKlass com/sun/tools/javac/comp/Modules$1 -instanceKlass com/sun/tools/javac/comp/Modules$$Lambda$240 -instanceKlass com/sun/tools/javac/resources/CompilerProperties$Fragments -instanceKlass com/sun/tools/javac/code/Directive -instanceKlass javax/lang/model/element/ModuleElement$RequiresDirective -instanceKlass javax/lang/model/element/ModuleElement$Directive -instanceKlass com/sun/tools/javac/code/Symtab$$Lambda$239 -instanceKlass com/sun/tools/javac/code/Symtab$$Lambda$238 -instanceKlass com/sun/tools/javac/code/Symtab$$Lambda$237 -instanceKlass com/sun/tools/javac/code/Scope$ScopeListenerList -instanceKlass com/sun/tools/javac/code/Scope$Entry -instanceKlass com/sun/tools/javac/comp/Annotate$AnnotationTypeMetadata -instanceKlass com/sun/tools/javac/api/Formattable -instanceKlass com/sun/tools/javac/code/Kinds$KindSelector -instanceKlass com/sun/tools/javac/code/TypeMetadata -instanceKlass javax/lang/model/type/NullType -instanceKlass com/sun/tools/javac/code/Symtab -instanceKlass com/sun/source/util/SimpleTreeVisitor -instanceKlass com/sun/tools/javac/comp/Check$NestedCheckContext -instanceKlass com/sun/tools/javac/comp/Resolve$MethodCheck -instanceKlass javax/lang/model/type/UnionType -instanceKlass javax/lang/model/type/IntersectionType -instanceKlass com/sun/tools/javac/comp/Attr$ResultInfo -instanceKlass com/sun/tools/javac/code/Types$DefaultTypeVisitor -instanceKlass com/sun/source/tree/IntersectionTypeTree -instanceKlass com/sun/source/tree/MemberReferenceTree -instanceKlass com/sun/source/tree/UnionTypeTree -instanceKlass com/sun/source/tree/ArrayAccessTree -instanceKlass com/sun/source/tree/ModuleTree -instanceKlass com/sun/source/tree/ArrayTypeTree -instanceKlass com/sun/source/tree/PrimitiveTypeTree -instanceKlass com/sun/source/tree/ParameterizedTypeTree -instanceKlass com/sun/source/tree/LabeledStatementTree -instanceKlass com/sun/source/tree/VariableTree -instanceKlass com/sun/source/tree/EmptyStatementTree -instanceKlass com/sun/source/tree/PackageTree -instanceKlass com/sun/source/tree/ExpressionStatementTree -instanceKlass com/sun/source/tree/MethodTree -instanceKlass com/sun/source/tree/InstanceOfTree -instanceKlass com/sun/source/tree/CompoundAssignmentTree -instanceKlass com/sun/source/tree/EnhancedForLoopTree -instanceKlass com/sun/source/tree/AssignmentTree -instanceKlass com/sun/source/tree/MethodInvocationTree -instanceKlass com/sun/source/tree/ParenthesizedTree -instanceKlass com/sun/source/tree/LambdaExpressionTree -instanceKlass com/sun/source/tree/ConditionalExpressionTree -instanceKlass com/sun/source/tree/DoWhileLoopTree -instanceKlass com/sun/source/tree/ExportsTree -instanceKlass com/sun/source/tree/OpensTree -instanceKlass com/sun/source/tree/ErroneousTree -instanceKlass com/sun/source/tree/UsesTree -instanceKlass com/sun/source/tree/RequiresTree -instanceKlass com/sun/source/tree/ProvidesTree -instanceKlass com/sun/source/tree/DirectiveTree -instanceKlass com/sun/source/tree/TypeParameterTree -instanceKlass com/sun/source/tree/LiteralTree -instanceKlass com/sun/source/tree/ModifiersTree -instanceKlass com/sun/source/tree/AnnotatedTypeTree -instanceKlass com/sun/source/tree/NewClassTree -instanceKlass com/sun/source/tree/WhileLoopTree -instanceKlass com/sun/source/tree/BlockTree -instanceKlass com/sun/source/tree/AssertTree -instanceKlass com/sun/source/tree/ReturnTree -instanceKlass com/sun/source/tree/SynchronizedTree -instanceKlass com/sun/source/tree/ThrowTree -instanceKlass com/sun/source/tree/ForLoopTree -instanceKlass com/sun/source/tree/BreakTree -instanceKlass com/sun/source/tree/TypeCastTree -instanceKlass com/sun/source/tree/BinaryTree -instanceKlass com/sun/source/tree/IfTree -instanceKlass com/sun/source/tree/ImportTree -instanceKlass com/sun/source/tree/TryTree -instanceKlass com/sun/source/tree/CatchTree -instanceKlass com/sun/source/tree/SwitchTree -instanceKlass com/sun/source/tree/ContinueTree -instanceKlass com/sun/source/tree/UnaryTree -instanceKlass com/sun/source/tree/CaseTree -instanceKlass com/sun/source/tree/WildcardTree -instanceKlass com/sun/source/tree/AnnotationTree -instanceKlass com/sun/tools/javac/comp/Annotate$2 -instanceKlass com/sun/tools/javac/code/TypeMetadata$Entry -instanceKlass com/sun/tools/javac/comp/Check$CheckContext -instanceKlass com/sun/tools/javac/tree/JCTree$Visitor -instanceKlass com/sun/source/tree/NewArrayTree -instanceKlass javax/lang/model/element/AnnotationMirror -instanceKlass com/sun/tools/javac/comp/Annotate -instanceKlass com/sun/tools/javac/code/Attribute -instanceKlass javax/lang/model/element/AnnotationValue -instanceKlass javax/lang/model/type/PrimitiveType -instanceKlass com/sun/tools/javac/comp/Annotate$AnnotationTypeCompleter -instanceKlass com/sun/tools/javac/jvm/ClassReader -instanceKlass com/sun/tools/javac/code/ClassFinder$$Lambda$236 -instanceKlass com/sun/tools/javac/code/Scope -instanceKlass com/sun/tools/javac/code/ClassFinder -instanceKlass com/sun/tools/javac/util/Convert -instanceKlass com/sun/tools/javac/util/ArrayUtils -instanceKlass com/sun/tools/javac/util/Name -instanceKlass javax/lang/model/element/Name -instanceKlass com/sun/tools/javac/util/Name$Table -instanceKlass com/sun/tools/javac/util/Names -instanceKlass com/sun/tools/javac/code/Symbol$Completer$1 -instanceKlass com/sun/tools/javac/main/JavaCompiler$$Lambda$235 -instanceKlass javax/lang/model/element/ModuleElement -instanceKlass com/sun/source/tree/ClassTree -instanceKlass com/sun/source/tree/StatementTree -instanceKlass com/sun/source/tree/MemberSelectTree -instanceKlass com/sun/source/tree/IdentifierTree -instanceKlass javax/lang/model/element/TypeElement -instanceKlass com/sun/source/tree/CompilationUnitTree -instanceKlass javax/lang/model/element/PackageElement -instanceKlass javax/lang/model/element/QualifiedNameable -instanceKlass com/sun/tools/javac/main/JavaCompiler -instanceKlass com/sun/tools/javac/platform/PlatformDescription -instanceKlass com/sun/tools/javac/code/Source$1 -instanceKlass com/sun/tools/javac/main/Arguments$$Lambda$234 -instanceKlass com/sun/tools/javac/main/Arguments$$Lambda$233 -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass com/sun/tools/javac/main/Arguments$$Lambda$232 -instanceKlass com/sun/tools/javac/main/Arguments$$Lambda$231 -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass com/sun/tools/javac/util/Log$1 -instanceKlass com/sun/tools/javac/util/JCDiagnostic$1 -instanceKlass java/util/stream/ReferencePipeline$$Lambda$230 -instanceKlass com/sun/tools/javac/util/JCDiagnostic$Factory$$Lambda$229 -instanceKlass com/sun/tools/javac/util/JCDiagnostic -instanceKlass com/sun/tools/javac/resources/CompilerProperties$Warnings -instanceKlass com/sun/tools/javac/code/DeferredCompletionFailureHandler$1$$Lambda$228 -instanceKlass com/sun/tools/javac/api/JavacTaskImpl$$Lambda$227 -instanceKlass java/util/WeakHashMap$HashIterator -instanceKlass com/sun/tools/javac/code/DeferredCompletionFailureHandler$1$$Lambda$226 -instanceKlass com/sun/tools/javac/code/DeferredCompletionFailureHandler$FlipSymbolDescription -instanceKlass com/sun/tools/javac/code/DeferredCompletionFailureHandler$2 -instanceKlass com/sun/tools/javac/code/Symbol$Completer -instanceKlass com/sun/tools/javac/code/DeferredCompletionFailureHandler$1 -instanceKlass com/sun/tools/javac/code/DeferredCompletionFailureHandler$Handler -instanceKlass com/sun/tools/javac/code/DeferredCompletionFailureHandler -instanceKlass com/sun/tools/javac/parser/Parser -instanceKlass com/sun/tools/javac/api/JavacTaskImpl$Filter -instanceKlass javax/lang/model/util/Types -instanceKlass javax/lang/model/util/Elements -instanceKlass com/sun/tools/javac/main/Arguments$$Lambda$225 -instanceKlass com/sun/tools/javac/main/Arguments$ErrorReporter -instanceKlass java/lang/invoke/LambdaForm$MH -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass com/sun/tools/javac/main/Arguments$$Lambda$224 -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass jdk/internal/jimage/ImageBufferCache$2 -instanceKlass jdk/internal/jimage/ImageBufferCache -instanceKlass sun/net/www/protocol/jrt/JavaRuntimeURLConnection$$Lambda$223 -instanceKlass java/nio/file/FileStore -instanceKlass java/nio/channels/AsynchronousFileChannel -instanceKlass java/nio/channels/AsynchronousChannel -instanceKlass java/nio/file/DirectoryStream$Filter -instanceKlass java/nio/file/spi/FileSystemProvider$1 -instanceKlass com/sun/tools/javac/util/StringUtils -instanceKlass sun/nio/fs/WindowsDirectoryStream -instanceKlass java/nio/file/DirectoryStream -instanceKlass com/sun/tools/javac/file/BaseFileManager$3 -instanceKlass com/sun/source/util/TreeScanner -instanceKlass com/sun/source/tree/TreeVisitor -instanceKlass com/sun/tools/doclint/DocLint -instanceKlass com/sun/source/util/Plugin -instanceKlass com/sun/tools/javac/util/ListBuffer$1 -instanceKlass com/sun/tools/javac/main/Arguments -instanceKlass com/sun/tools/javac/api/ClientCodeWrapper$WrappedDiagnosticListener -instanceKlass com/sun/tools/javac/api/ClientCodeWrapper$Trusted -instanceKlass com/sun/source/util/TaskListener -instanceKlass com/sun/tools/javac/api/ClientCodeWrapper -instanceKlass com/sun/tools/javac/file/PathFileObject -instanceKlass com/sun/tools/javac/file/CacheFSInfo$Entry -instanceKlass com/sun/tools/javac/util/Log$$Lambda$222 -instanceKlass com/sun/tools/javac/util/JCDiagnostic$Factory$$Lambda$221 -instanceKlass javax/lang/model/element/VariableElement -instanceKlass javax/lang/model/type/NoType -instanceKlass javax/lang/model/type/TypeVariable -instanceKlass javax/lang/model/type/ErrorType -instanceKlass javax/lang/model/type/DeclaredType -instanceKlass javax/lang/model/type/ArrayType -instanceKlass javax/lang/model/type/ReferenceType -instanceKlass javax/lang/model/type/WildcardType -instanceKlass javax/lang/model/type/ExecutableType -instanceKlass javax/lang/model/type/TypeMirror -instanceKlass javax/lang/model/element/ExecutableElement -instanceKlass javax/lang/model/element/Parameterizable -instanceKlass com/sun/tools/javac/code/AnnoConstruct -instanceKlass javax/lang/model/element/Element -instanceKlass javax/lang/model/AnnotatedConstruct -instanceKlass com/sun/tools/javac/util/AbstractDiagnosticFormatter$SimpleConfiguration -instanceKlass com/sun/source/tree/ExpressionTree -instanceKlass com/sun/tools/javac/tree/JCTree -instanceKlass com/sun/source/tree/Tree -instanceKlass com/sun/tools/javac/api/DiagnosticFormatter$Configuration -instanceKlass com/sun/tools/javac/code/Printer -instanceKlass com/sun/tools/javac/code/Symbol$Visitor -instanceKlass com/sun/tools/javac/code/Type$Visitor -instanceKlass com/sun/tools/javac/util/AbstractDiagnosticFormatter -instanceKlass com/sun/tools/javac/util/Options -instanceKlass jdk/internal/module/SystemModuleFinders$SystemModuleReader$$Lambda$220 -instanceKlass java/util/ResourceBundle$ResourceBundleProviderHelper$$Lambda$219 -instanceKlass java/util/ResourceBundle$ResourceBundleProviderHelper$$Lambda$218 -instanceKlass java/util/ResourceBundle$3 -instanceKlass java/util/ResourceBundle$CacheKeyReference -instanceKlass java/util/ResourceBundle$CacheKey -instanceKlass java/util/ResourceBundle$$Lambda$217 -instanceKlass com/sun/tools/javac/util/List$3 -instanceKlass com/sun/tools/javac/util/JavacMessages$$Lambda$216 -instanceKlass com/sun/tools/javac/util/JavacMessages$ResourceBundleHelper -instanceKlass com/sun/tools/javac/util/List$2 -instanceKlass com/sun/tools/javac/util/JavacMessages -instanceKlass com/sun/tools/javac/api/Messages -instanceKlass com/sun/tools/javac/util/JCDiagnostic$DiagnosticInfo -instanceKlass com/sun/tools/javac/util/JCDiagnostic$Factory -instanceKlass com/sun/tools/javac/file/JavacFileManager$$Lambda$215 -instanceKlass java/util/JumboEnumSet$EnumSetIterator -instanceKlass com/sun/tools/javac/file/Locations$ModuleTable -instanceKlass com/sun/tools/javac/file/Locations$ModuleSourcePathLocationHandler$$Lambda$214 -instanceKlass com/sun/tools/javac/file/Locations$$Lambda$213 -instanceKlass javax/tools/StandardJavaFileManager$PathFactory -instanceKlass com/sun/tools/javac/file/Locations$LocationHandler -instanceKlass com/sun/tools/javac/file/Locations -instanceKlass com/sun/tools/javac/file/BaseFileManager$ByteBufferCache -instanceKlass com/sun/tools/javac/file/JavacFileManager$1 -instanceKlass java/util/stream/Collectors$$Lambda$212 -instanceKlass java/util/stream/Collectors$$Lambda$211 -instanceKlass com/sun/tools/javac/main/Option$$Lambda$210 -instanceKlass com/sun/tools/javac/main/Option$$Lambda$209 -instanceKlass com/sun/tools/javac/code/Lint -instanceKlass com/sun/tools/javac/util/Assert -instanceKlass javax/tools/JavaFileManager$Location -instanceKlass com/sun/tools/javac/file/RelativePath -instanceKlass javax/tools/JavaFileObject -instanceKlass javax/tools/FileObject -instanceKlass com/sun/tools/javac/file/JavacFileManager$Container -instanceKlass com/sun/tools/javac/main/OptionHelper -instanceKlass com/sun/tools/javac/file/CacheFSInfo$$Lambda$208 -instanceKlass com/sun/tools/javac/file/FSInfo -instanceKlass javax/tools/Diagnostic -instanceKlass com/sun/tools/javac/api/DiagnosticFormatter -instanceKlass com/sun/tools/javac/util/Log$DiagnosticHandler -instanceKlass com/sun/tools/javac/util/JCDiagnostic$DiagnosticPosition -instanceKlass com/sun/tools/javac/util/AbstractLog -instanceKlass com/sun/tools/javac/util/Context$Factory -instanceKlass com/sun/tools/javac/util/Context$Key -instanceKlass javax/tools/DiagnosticCollector -instanceKlass org/codehaus/plexus/compiler/javac/JavaxToolsCompiler$1 -instanceKlass javax/tools/ToolProvider$$Lambda$207 -instanceKlass com/sun/tools/javac/file/BaseFileManager -instanceKlass com/sun/tools/javac/util/Context -instanceKlass javax/tools/StandardJavaFileManager -instanceKlass com/sun/source/util/JavacTask -instanceKlass javax/tools/JavaCompiler$CompilationTask -instanceKlass com/sun/tools/javac/api/JavacTool -instanceKlass javax/tools/JavaCompiler -instanceKlass javax/tools/Tool -instanceKlass javax/tools/JavaFileManager -instanceKlass javax/tools/OptionChecker -instanceKlass javax/tools/DiagnosticListener -instanceKlass org/codehaus/plexus/compiler/javac/JavaxToolsCompiler -instanceKlass org/codehaus/plexus/util/StringUtils -instanceKlass javax/tools/ToolProvider -instanceKlass org/apache/maven/shared/utils/io/DirectoryScanner -instanceKlass org/apache/maven/shared/utils/io/FileUtils -instanceKlass org/apache/maven/monitor/event/EventDispatcher -instanceKlass org/apache/maven/artifact/repository/RepositoryCache -instanceKlass org/apache/maven/shared/incremental/IncrementalBuildHelperRequest -instanceKlass org/codehaus/plexus/util/SelectorUtils -instanceKlass org/codehaus/plexus/util/DirectoryScanner -instanceKlass org/codehaus/plexus/compiler/util/scan/AbstractSourceInclusionScanner -instanceKlass org/apache/maven/shared/incremental/IncrementalBuildHelper -instanceKlass org/apache/maven/shared/utils/StringUtils -instanceKlass org/codehaus/plexus/compiler/javac/JavacCompiler$$FastClassByGuice$$215514589 -instanceKlass org/codehaus/plexus/compiler/manager/DefaultCompilerManager$$FastClassByGuice$$214433503 -instanceKlass org/apache/maven/toolchain/DefaultToolchainManager$$FastClassByGuice$$213828397 -instanceKlass org/apache/maven/plugin/compiler/CompilerMojo$$FastClassByGuice$$212329334 -instanceKlass org/codehaus/plexus/compiler/CompilerMessage -instanceKlass org/codehaus/plexus/util/cli/StreamConsumer -instanceKlass org/codehaus/plexus/compiler/CompilerOutputStyle -instanceKlass org/codehaus/plexus/compiler/CompilerResult -instanceKlass org/codehaus/plexus/compiler/util/scan/SourceInclusionScanner -instanceKlass org/codehaus/plexus/compiler/CompilerConfiguration -instanceKlass org/codehaus/plexus/compiler/util/scan/mapping/SingleTargetSourceMapping -instanceKlass org/codehaus/plexus/compiler/util/scan/mapping/SuffixMapping -instanceKlass org/codehaus/plexus/compiler/util/scan/mapping/SourceMapping -instanceKlass org/codehaus/plexus/compiler/Compiler -instanceKlass org/codehaus/plexus/compiler/manager/CompilerManager -instanceKlass org/eclipse/aether/util/graph/selector/ExclusionDependencySelector$ExclusionComparator -instanceKlass org/apache/maven/artifact/resolver/filter/AbstractScopeArtifactFilter -instanceKlass org/codehaus/plexus/interpolation/RecursionInterceptor -instanceKlass org/codehaus/plexus/interpolation/AbstractValueSource -instanceKlass org/apache/maven/plugins/resources/MavenBuildTimestamp -instanceKlass org/apache/maven/shared/filtering/FilterWrapper -instanceKlass java/util/regex/CharPredicates$$Lambda$206 -instanceKlass java/lang/Character$Subset -instanceKlass org/apache/commons/lang3/StringUtils -instanceKlass org/eclipse/sisu/plexus/TypeArguments -instanceKlass org/sonatype/plexus/build/incremental/DefaultBuildContext$$FastClassByGuice$$211603510 -instanceKlass org/apache/maven/plugins/resources/ResourcesMojo$$FastClassByGuice$$210107692 -instanceKlass org/apache/maven/shared/filtering/DefaultMavenResourcesFiltering$$FastClassByGuice$$209475617 -instanceKlass org/apache/maven/shared/filtering/DefaultMavenReaderFilter$$FastClassByGuice$$208267592 -instanceKlass org/apache/maven/shared/filtering/DefaultMavenFileFilter$$FastClassByGuice$$207530591 -instanceKlass org/codehaus/plexus/interpolation/Interpolator -instanceKlass org/codehaus/plexus/interpolation/BasicInterpolator -instanceKlass org/codehaus/plexus/interpolation/ValueSource -instanceKlass org/codehaus/plexus/util/Scanner -instanceKlass org/apache/maven/shared/filtering/AbstractMavenFilteringRequest -instanceKlass org/apache/maven/shared/filtering/DefaultMavenResourcesFiltering -instanceKlass org/apache/maven/shared/filtering/MavenResourcesFiltering -instanceKlass org/apache/maven/shared/filtering/MavenReaderFilter -instanceKlass org/apache/maven/shared/filtering/BaseFilter -instanceKlass org/apache/maven/shared/filtering/MavenFileFilter -instanceKlass org/apache/maven/shared/filtering/DefaultFilterInfo -instanceKlass org/sonatype/plexus/build/incremental/BuildContext -instanceKlass org/apache/maven/plugins/clean/Cleaner$Result -instanceKlass org/apache/maven/utils/Os$$Lambda$205 -instanceKlass org/apache/maven/utils/Os -instanceKlass org/apache/maven/model/building/DefaultModelBuilder$$Lambda$204 -instanceKlass org/apache/maven/model/building/DefaultModelBuilder$$Lambda$203 -instanceKlass org/apache/maven/model/building/DefaultModelBuilder$$Lambda$202 -instanceKlass org/apache/maven/model/building/DefaultModelBuilder$$Lambda$201 -instanceKlass org/apache/maven/model/building/DefaultModelBuilder$$Lambda$200 -instanceKlass org/eclipse/aether/collection/DependencyManagement -instanceKlass org/eclipse/aether/graph/Dependency$Exclusions$1 -instanceKlass org/eclipse/aether/util/graph/manager/ClassicDependencyManager$$Lambda$199 -instanceKlass org/apache/maven/artifact/handler/DefaultArtifactHandler$__sisu12$$FastClassByGuice$$205946515 -instanceKlass org/apache/maven/RepositoryUtils$$Lambda$198 -instanceKlass org/apache/maven/RepositoryUtils$$Lambda$197 -instanceKlass org/apache/maven/project/DefaultDependencyResolutionRequest -instanceKlass org/apache/maven/lifecycle/internal/LifecycleDependencyResolver$ReactorDependencyFilter -instanceKlass org/apache/maven/lifecycle/internal/DefaultMojoExecutionConfigurator$$Lambda$196 -instanceKlass org/apache/maven/lifecycle/internal/DefaultMojoExecutionConfigurator$$Lambda$195 -instanceKlass org/apache/maven/lifecycle/internal/DefaultMojoExecutionConfigurator$$Lambda$194 -instanceKlass org/apache/maven/lifecycle/internal/DefaultMojoExecutionConfigurator$$Lambda$193 -instanceKlass org/apache/maven/plugin/internal/DefaultPluginValidationManager$PluginValidationIssues$$Lambda$192 -instanceKlass org/apache/maven/plugin/internal/DefaultPluginValidationManager$$Lambda$191 -instanceKlass org/apache/maven/plugin/internal/DefaultPluginValidationManager$$Lambda$190 -instanceKlass org/apache/maven/plugins/install/InstallMojo$$Lambda$189 -instanceKlass org/eclipse/aether/repository/LocalMetadataRegistration -instanceKlass org/apache/maven/artifact/repository/metadata/io/xpp3/MetadataXpp3Writer -instanceKlass org/codehaus/plexus/util/WriterFactory -instanceKlass org/apache/maven/artifact/repository/metadata/io/xpp3/MetadataXpp3Reader$1 -instanceKlass org/apache/maven/artifact/repository/metadata/io/xpp3/MetadataXpp3Reader$ContentTransformer -instanceKlass org/apache/maven/artifact/repository/metadata/io/xpp3/MetadataXpp3Reader -instanceKlass org/eclipse/aether/metadata/AbstractMetadata -instanceKlass org/eclipse/aether/metadata/MergeableMetadata -instanceKlass sun/util/cldr/CLDRBaseLocaleDataMetaInfo$TZCanonicalIDMapHolder -instanceKlass sun/util/resources/provider/NonBaseLocaleDataMetaInfo -instanceKlass sun/util/locale/provider/JRELocaleProviderAdapter$$Lambda$188 -instanceKlass sun/util/locale/provider/BaseLocaleDataMetaInfo -instanceKlass sun/util/locale/provider/JRELocaleProviderAdapter$$Lambda$187 -instanceKlass sun/util/cldr/CLDRLocaleProviderAdapter$$Lambda$186 -instanceKlass sun/util/locale/provider/TimeZoneNameUtility$TimeZoneNameGetter -instanceKlass sun/util/locale/provider/TimeZoneNameUtility -instanceKlass sun/nio/cs/Surrogate -instanceKlass sun/nio/cs/Surrogate$Parser -instanceKlass org/eclipse/aether/repository/LocalArtifactRegistration -instanceKlass org/eclipse/aether/util/FileUtils$2 -instanceKlass org/eclipse/aether/util/FileUtils$CollocatedTempFile -instanceKlass org/eclipse/aether/util/FileUtils$TempFile -instanceKlass org/eclipse/aether/util/FileUtils -instanceKlass org/apache/maven/repository/internal/PluginsMetadataGenerator -instanceKlass org/apache/maven/repository/internal/VersionsMetadataGenerator -instanceKlass org/apache/maven/repository/internal/LocalSnapshotMetadataGenerator -instanceKlass org/eclipse/aether/internal/impl/Utils -instanceKlass org/apache/maven/project/artifact/ProjectArtifact$PomArtifactHandler -instanceKlass org/apache/maven/project/artifact/ArtifactWithDependencies -instanceKlass org/apache/maven/plugins/install/InstallMojo$$Lambda$185 -instanceKlass org/apache/maven/plugins/install/InstallMojo$$Lambda$184 -instanceKlass org/apache/maven/plugins/install/InstallMojo$$Lambda$183 -instanceKlass org/apache/maven/plugins/install/InstallMojo$$FastClassByGuice$$204982143 -instanceKlass org/eclipse/sisu/plexus/ComponentDescriptorBeanModule$ComponentMetadata -instanceKlass org/apache/maven/plugins/clean/Cleaner$$Lambda$182 -instanceKlass org/apache/maven/plugins/clean/Cleaner$$Lambda$181 -instanceKlass org/apache/maven/plugins/clean/Cleaner$Logger -instanceKlass org/apache/maven/shared/utils/Os -instanceKlass org/apache/maven/plugins/clean/Cleaner -instanceKlass org/eclipse/sisu/plexus/CompositeBeanHelper$1 -instanceKlass org/codehaus/plexus/util/introspection/MethodMap -instanceKlass org/codehaus/plexus/util/introspection/ClassMap$CacheMiss -instanceKlass org/codehaus/plexus/util/introspection/ClassMap -instanceKlass org/codehaus/plexus/util/introspection/ReflectionValueExtractor$Tokenizer -instanceKlass org/codehaus/plexus/util/introspection/ReflectionValueExtractor -instanceKlass org/eclipse/sisu/plexus/CompositeBeanHelper -instanceKlass org/apache/maven/plugin/internal/ValidatingConfigurationListener -instanceKlass org/apache/maven/plugin/DebugConfigurationListener -instanceKlass org/eclipse/sisu/inject/MildKeys -instanceKlass java/time/LocalTime -instanceKlass java/time/LocalDate -instanceKlass java/time/chrono/ChronoLocalDate -instanceKlass java/time/zone/ZoneOffsetTransition -instanceKlass java/time/LocalDateTime -instanceKlass java/time/chrono/ChronoLocalDateTime -instanceKlass java/time/temporal/TemporalAdjuster -instanceKlass java/time/zone/ZoneOffsetTransitionRule -instanceKlass java/time/zone/ZoneRules -instanceKlass java/time/zone/Ser -instanceKlass java/io/Externalizable -instanceKlass java/time/zone/ZoneRulesProvider$1 -instanceKlass java/time/zone/ZoneRulesProvider -instanceKlass java/time/format/DateTimeFormatter$$Lambda$180 -instanceKlass java/time/format/DateTimeFormatter$$Lambda$179 -instanceKlass java/time/Period -instanceKlass java/time/chrono/ChronoPeriod -instanceKlass java/time/format/DateTimeFormatterBuilder$TextPrinterParser -instanceKlass java/time/format/DateTimeTextProvider$1 -instanceKlass java/time/format/DateTimeTextProvider -instanceKlass java/time/format/DateTimeTextProvider$LocaleStore -instanceKlass java/time/format/DateTimeFormatterBuilder$InstantPrinterParser -instanceKlass java/time/format/DateTimeFormatterBuilder$StringLiteralPrinterParser -instanceKlass java/time/format/DateTimeFormatterBuilder$ZoneIdPrinterParser -instanceKlass java/time/format/DateTimeFormatterBuilder$OffsetIdPrinterParser -instanceKlass java/time/format/DecimalStyle -instanceKlass java/time/format/DateTimeFormatterBuilder$CompositePrinterParser -instanceKlass java/time/chrono/AbstractChronology -instanceKlass java/time/chrono/Chronology -instanceKlass java/time/format/DateTimeFormatterBuilder$CharLiteralPrinterParser -instanceKlass java/time/format/DateTimeFormatterBuilder$NumberPrinterParser -instanceKlass java/time/format/DateTimeFormatterBuilder$DateTimePrinterParser -instanceKlass java/time/format/DateTimeFormatterBuilder$2 -instanceKlass java/time/temporal/JulianFields -instanceKlass java/time/temporal/IsoFields -instanceKlass java/time/temporal/ValueRange -instanceKlass java/time/temporal/TemporalField -instanceKlass java/time/format/DateTimeFormatterBuilder$$Lambda$178 -instanceKlass java/time/temporal/TemporalQuery -instanceKlass java/time/ZoneId -instanceKlass java/time/format/DateTimeFormatterBuilder -instanceKlass java/time/format/DateTimeFormatter -instanceKlass java/time/temporal/Temporal -instanceKlass java/time/temporal/TemporalAccessor -instanceKlass org/codehaus/plexus/component/configurator/converters/ParameterizedConfigurationConverter -instanceKlass org/codehaus/plexus/component/configurator/converters/AbstractConfigurationConverter -instanceKlass org/codehaus/plexus/component/configurator/converters/ConfigurationConverter -instanceKlass org/codehaus/plexus/component/configurator/converters/lookup/DefaultConverterLookup -instanceKlass org/codehaus/plexus/component/configurator/expression/DefaultExpressionEvaluator -instanceKlass org/apache/maven/plugin/internal/ReadOnlyPluginParametersValidator$$Lambda$177 -instanceKlass org/apache/maven/plugin/internal/ReadOnlyPluginParametersValidator$$Lambda$176 -instanceKlass org/apache/maven/plugin/internal/DeprecatedPluginValidator$$Lambda$175 -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass org/apache/maven/plugin/internal/DeprecatedPluginValidator$$Lambda$174 -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass org/apache/maven/plugin/internal/DeprecatedPluginValidator$$Lambda$173 -instanceKlass org/apache/maven/plugin/internal/DeprecatedCoreExpressionValidator$$Lambda$172 -instanceKlass org/apache/maven/plugin/internal/DeprecatedCoreExpressionValidator$$Lambda$171 -instanceKlass org/apache/maven/plugin/internal/DeprecatedCoreExpressionValidator$$Lambda$170 -instanceKlass org/apache/maven/plugin/PluginParameterExpressionEvaluator -instanceKlass org/codehaus/plexus/component/configurator/expression/TypeAwareExpressionEvaluator -instanceKlass org/apache/maven/monitor/logging/DefaultLog -instanceKlass org/apache/maven/plugins/clean/CleanMojo$$FastClassByGuice$$204306465 -instanceKlass com/google/inject/internal/Messages$Converter -instanceKlass com/google/inject/internal/Messages -instanceKlass java/util/StringJoiner -instanceKlass org/apache/maven/plugins/clean/Fileset -instanceKlass org/apache/maven/plugins/clean/Selector -instanceKlass org/w3c/dom/Element -instanceKlass org/w3c/dom/Document -instanceKlass org/w3c/dom/Node -instanceKlass java/security/CodeSigner -instanceKlass java/util/jar/JarVerifier -instanceKlass org/eclipse/sisu/space/FileEntryIterator -instanceKlass org/eclipse/sisu/space/ResourceEnumeration -instanceKlass org/eclipse/sisu/plexus/ComponentDescriptorBeanModule$PlexusDescriptorBeanSource -instanceKlass org/apache/maven/plugin/AbstractMojo -instanceKlass org/apache/maven/plugin/ContextEnabled -instanceKlass org/apache/maven/plugin/Mojo -instanceKlass org/eclipse/sisu/plexus/ComponentDescriptorBeanModule -instanceKlass org/apache/maven/classrealm/ArtifactClassRealmConstituent -instanceKlass org/apache/maven/RepositoryUtils$$Lambda$169 -instanceKlass org/eclipse/aether/util/graph/visitor/TreeDependencyVisitor -instanceKlass org/eclipse/aether/util/graph/visitor/FilteringDependencyVisitor -instanceKlass org/eclipse/aether/internal/impl/ArtifactRequestBuilder -instanceKlass org/eclipse/aether/util/graph/transformer/ConflictResolver$NodeInfo -instanceKlass org/eclipse/aether/util/artifact/ArtifactIdUtils -instanceKlass org/eclipse/aether/util/graph/transformer/NearestVersionSelector$ConflictGroup -instanceKlass org/eclipse/aether/util/graph/transformer/ConflictResolver$ConflictItem -instanceKlass org/eclipse/aether/util/graph/transformer/ConflictResolver$ScopeContext -instanceKlass org/eclipse/aether/util/graph/transformer/ConflictResolver$ConflictContext -instanceKlass org/eclipse/aether/util/graph/transformer/ConflictResolver$State -instanceKlass org/eclipse/aether/util/graph/transformer/ConflictIdSorter$RootQueue -instanceKlass org/eclipse/aether/util/graph/transformer/ConflictIdSorter$ConflictId -instanceKlass org/eclipse/aether/util/graph/transformer/ConflictMarker$ConflictGroup -instanceKlass org/eclipse/aether/util/graph/transformer/ConflictMarker$Key -instanceKlass org/eclipse/aether/util/graph/transformer/ConflictMarker -instanceKlass org/eclipse/aether/util/graph/transformer/ConflictIdSorter -instanceKlass org/eclipse/aether/util/graph/transformer/TransformationContextKeys -instanceKlass org/eclipse/aether/internal/impl/collect/DefaultDependencyGraphTransformationContext -instanceKlass org/eclipse/aether/internal/impl/collect/DataPool$GraphKey -instanceKlass org/eclipse/aether/internal/impl/collect/DefaultDependencyCycle -instanceKlass org/eclipse/aether/internal/impl/collect/DataPool$HardInternPool$$Lambda$168 -instanceKlass org/eclipse/aether/internal/impl/collect/DataPool$Descriptor -instanceKlass org/eclipse/aether/internal/impl/collect/DataPool$Constraint$VersionRepo -instanceKlass org/eclipse/aether/internal/impl/collect/DataPool$Constraint -instanceKlass org/eclipse/aether/internal/impl/collect/DataPool$ConstraintKey -instanceKlass org/eclipse/aether/internal/impl/collect/CollectStepDataImpl -instanceKlass org/eclipse/aether/collection/CollectStepData -instanceKlass org/eclipse/aether/util/graph/manager/ClassicDependencyManager$Key -instanceKlass org/eclipse/aether/internal/impl/collect/df/NodeStack -instanceKlass org/eclipse/aether/graph/DependencyCycle -instanceKlass org/eclipse/aether/internal/impl/collect/DataPool$HardInternPool -instanceKlass org/eclipse/aether/internal/impl/collect/DataPool$WeakInternPool -instanceKlass org/eclipse/aether/internal/impl/collect/DataPool$InternPool -instanceKlass org/eclipse/aether/internal/impl/collect/CachingArtifactTypeRegistry -instanceKlass org/apache/maven/plugin/internal/WagonExcluder -instanceKlass org/eclipse/aether/util/filter/ScopeDependencyFilter -instanceKlass org/eclipse/aether/util/filter/AndDependencyFilter -instanceKlass org/apache/maven/plugin/DefaultPluginRealmCache$$Lambda$167 -instanceKlass java/lang/invoke/LambdaForm$MH -instanceKlass org/apache/maven/plugin/internal/DefaultMavenPluginManager$$Lambda$166 -instanceKlass org/apache/maven/plugin/CacheUtils -instanceKlass org/apache/maven/plugin/DefaultPluginRealmCache$CacheKey -instanceKlass java/lang/Character$CharacterCache -instanceKlass org/apache/maven/lifecycle/internal/MojoExecutor$ProjectLock -instanceKlass org/apache/maven/project/artifact/DefaultProjectArtifactsCache$CacheKey -instanceKlass org/apache/maven/lifecycle/internal/MojoExecutor$1 -instanceKlass org/apache/maven/lifecycle/internal/ExecutionPlanItem -instanceKlass org/codehaus/plexus/component/repository/ComponentRequirement -instanceKlass org/apache/maven/lifecycle/internal/DefaultMojoExecutionConfigurator$$FastClassByGuice$$203223572 -instanceKlass org/apache/maven/plugin/MavenPluginValidator -instanceKlass java/io/RandomAccessFile$1 -instanceKlass org/codehaus/plexus/component/repository/ComponentDependency -instanceKlass org/codehaus/plexus/configuration/DefaultPlexusConfiguration -instanceKlass java/util/stream/MatchOps$$Lambda$165 -instanceKlass java/util/stream/MatchOps$BooleanTerminalSink -instanceKlass java/util/stream/MatchOps$MatchOp -instanceKlass java/util/stream/MatchOps -instanceKlass org/apache/maven/plugin/internal/PlexusContainerDefaultDependenciesValidator$$Lambda$164 -instanceKlass org/apache/maven/plugin/internal/PlexusContainerDefaultDependenciesValidator$$Lambda$163 -instanceKlass org/apache/maven/plugin/internal/MavenScopeDependenciesValidator$$Lambda$162 -instanceKlass org/apache/maven/plugin/internal/MavenScopeDependenciesValidator$$Lambda$161 -instanceKlass org/apache/maven/plugin/internal/MavenScopeDependenciesValidator$$Lambda$160 -instanceKlass org/apache/maven/plugin/internal/MavenScopeDependenciesValidator$$Lambda$159 -instanceKlass org/apache/maven/plugin/internal/MavenScopeDependenciesValidator$$Lambda$158 -instanceKlass org/apache/maven/plugin/internal/MavenScopeDependenciesValidator$$Lambda$157 -instanceKlass org/apache/maven/plugin/internal/MavenMixedDependenciesValidator$$Lambda$156 -instanceKlass org/apache/maven/plugin/internal/MavenMixedDependenciesValidator$$Lambda$155 -instanceKlass org/apache/maven/plugin/internal/MavenMixedDependenciesValidator$$Lambda$154 -instanceKlass org/apache/maven/plugin/internal/MavenMixedDependenciesValidator$$Lambda$153 -instanceKlass java/util/stream/Collectors$$Lambda$152 -instanceKlass java/util/stream/Collectors$$Lambda$151 -instanceKlass java/util/stream/Collectors$$Lambda$150 -instanceKlass org/apache/maven/plugin/internal/Maven2DependenciesValidator$$Lambda$149 -instanceKlass org/apache/maven/plugin/internal/Maven2DependenciesValidator$$Lambda$148 -instanceKlass org/apache/maven/plugin/internal/Maven2DependenciesValidator$$Lambda$147 -instanceKlass org/apache/maven/plugin/internal/Maven2DependenciesValidator$$Lambda$146 -instanceKlass org/apache/maven/plugin/internal/Maven2DependenciesValidator$$Lambda$145 -instanceKlass org/apache/maven/model/io/xpp3/MavenXpp3Reader$1 -instanceKlass org/apache/maven/model/io/xpp3/MavenXpp3Reader$ContentTransformer -instanceKlass org/apache/maven/model/io/xpp3/MavenXpp3Reader -instanceKlass org/apache/maven/repository/internal/DefaultModelResolver -instanceKlass org/apache/maven/plugin/DefaultPluginDescriptorCache$$Lambda$144 -instanceKlass org/apache/maven/plugin/internal/DefaultMavenPluginManager$$Lambda$143 -instanceKlass org/apache/maven/plugin/DefaultPluginDescriptorCache$CacheKey -instanceKlass org/apache/maven/lifecycle/internal/GoalTask -instanceKlass org/apache/maven/execution/ProjectExecutionEvent -instanceKlass org/apache/maven/lifecycle/internal/CompoundProjectExecutionListener -instanceKlass org/apache/maven/lifecycle/internal/DefaultLifecycleMappingDelegate$$FastClassByGuice$$201734650 -instanceKlass org/apache/maven/lifecycle/internal/DefaultLifecycleExecutionPlanCalculator$$FastClassByGuice$$201080415 -instanceKlass org/apache/maven/project/artifact/DefaultProjectArtifactsCache$$FastClassByGuice$$199848658 -instanceKlass org/apache/maven/lifecycle/internal/builder/singlethreaded/SingleThreadedBuilder$$FastClassByGuice$$199220097 -instanceKlass org/apache/maven/graph/DefaultProjectDependencyGraph$MavenProjectComparator -instanceKlass org/apache/maven/lifecycle/internal/LifecycleTask -instanceKlass org/slf4j/helpers/FormattingTuple -instanceKlass org/slf4j/helpers/MessageFormatter -instanceKlass org/apache/maven/plugin/internal/DefaultPluginValidationManager$$Lambda$142 -instanceKlass org/apache/maven/plugin/internal/DefaultPluginValidationManager$$Lambda$141 -instanceKlass org/apache/maven/internal/aether/MavenChainedWorkspaceReader -instanceKlass java/util/stream/Collectors$$Lambda$140 -instanceKlass java/util/stream/Collectors$$Lambda$139 -instanceKlass java/util/stream/Collectors$$Lambda$138 -instanceKlass org/apache/maven/ReactorReader$$Lambda$137 -instanceKlass org/apache/maven/ReactorReader$$Lambda$136 -instanceKlass org/apache/maven/session/scope/internal/SessionScope$ScopeState$$Lambda$135 -instanceKlass org/apache/maven/execution/MavenSession$$Lambda$134 -instanceKlass org/apache/maven/execution/MavenSession$$Lambda$133 -instanceKlass org/codehaus/plexus/util/dag/TopologicalSorter -instanceKlass org/codehaus/plexus/util/dag/CycleDetector -instanceKlass org/codehaus/plexus/util/dag/Vertex -instanceKlass org/codehaus/plexus/util/dag/DAG -instanceKlass org/apache/maven/project/ProjectSorter -instanceKlass org/apache/maven/graph/DefaultProjectDependencyGraph -instanceKlass org/apache/maven/project/DefaultProjectBuildingResult -instanceKlass org/apache/maven/lifecycle/mapping/DefaultLifecycleMapping$__sisu1$$FastClassByGuice$$197143457 -instanceKlass org/apache/maven/model/Site -instanceKlass org/apache/maven/model/merge/ModelMerger$NotifierKeyComputer -instanceKlass org/apache/maven/model/building/DefaultModelBuilder$$Lambda$132 -instanceKlass org/apache/maven/model/building/DefaultModelBuilder$$Lambda$131 -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass org/apache/maven/model/building/DefaultModelBuilder$$Lambda$130 -instanceKlass org/apache/maven/model/Notifier -instanceKlass org/apache/maven/model/building/DefaultModelBuilder$$Lambda$129 -instanceKlass org/apache/maven/model/building/DefaultModelBuilder$$Lambda$128 -instanceKlass org/eclipse/aether/util/version/GenericVersion$Item -instanceKlass org/eclipse/aether/util/version/GenericVersion$Tokenizer -instanceKlass org/eclipse/aether/util/version/GenericVersion -instanceKlass org/eclipse/aether/util/version/GenericVersionConstraint -instanceKlass org/eclipse/aether/version/VersionConstraint -instanceKlass org/eclipse/aether/version/VersionRange -instanceKlass org/eclipse/aether/util/version/GenericVersionScheme -instanceKlass java/util/Formattable -instanceKlass java/util/Formatter$Conversion -instanceKlass java/util/Formatter$Flags -instanceKlass java/util/Formatter$FormatSpecifier -instanceKlass java/util/Formatter$FixedString -instanceKlass java/util/Formatter$FormatString -instanceKlass java/util/Formatter -instanceKlass org/eclipse/aether/named/support/NamedLockFactorySupport$$Lambda$127 -instanceKlass java/util/AbstractMap$2$1 -instanceKlass java/nio/channels/spi/AbstractInterruptibleChannel$1 -instanceKlass sun/nio/ch/Interruptible -instanceKlass sun/nio/ch/FileKey -instanceKlass sun/nio/ch/FileLockTable -instanceKlass sun/nio/fs/WindowsFileSystemProvider$1 -instanceKlass org/eclipse/aether/repository/LocalArtifactRequest -instanceKlass org/apache/maven/repository/internal/DefaultVersionResolver$Key -instanceKlass org/eclipse/aether/internal/impl/DefaultRepositoryEventDispatcher$1 -instanceKlass org/eclipse/aether/RepositoryEvent$Builder -instanceKlass org/eclipse/aether/internal/impl/filter/RemoteRepositoryFilterSourceSupport$SimpleResult -instanceKlass org/eclipse/aether/internal/impl/filter/DefaultRemoteRepositoryFilterManager$$Lambda$126 -instanceKlass org/eclipse/aether/named/support/ReadWriteLockNamedLock$$Lambda$125 -instanceKlass org/eclipse/aether/named/support/Retry$DoNotRetry -instanceKlass org/eclipse/aether/named/support/NamedLockFactorySupport$$Lambda$124 -instanceKlass org/eclipse/aether/internal/impl/synccontext/named/NamedLockFactoryAdapter$AdaptedLockSyncContext -instanceKlass org/eclipse/aether/internal/impl/synccontext/named/GAVNameMapper -instanceKlass org/eclipse/aether/internal/impl/synccontext/named/NameMappers -instanceKlass org/eclipse/sisu/wire/NamedIterableAdapter$NamedEntry -instanceKlass org/eclipse/sisu/wire/NamedIterableAdapter$NamedIterator -instanceKlass org/eclipse/aether/DefaultSessionData$$Lambda$123 -instanceKlass org/eclipse/aether/internal/impl/synccontext/DefaultSyncContextFactory$$Lambda$122 -instanceKlass org/eclipse/aether/artifact/AbstractArtifact -instanceKlass org/apache/maven/lifecycle/Lifecycle$__sisu8$$FastClassByGuice$$196539390 -instanceKlass org/apache/maven/lifecycle/Lifecycle$__sisu7$$FastClassByGuice$$195763892 -instanceKlass org/apache/maven/lifecycle/mapping/LifecycleMojo -instanceKlass org/apache/maven/lifecycle/mapping/DefaultLifecycleMapping$$FastClassByGuice$$194395579 -instanceKlass org/apache/maven/lifecycle/mapping/Lifecycle -instanceKlass org/apache/maven/model/building/DefaultModelBuildingEvent -instanceKlass org/apache/maven/model/building/ModelBuildingEventCatapult$1 -instanceKlass org/apache/maven/project/ReactorModelPool$CacheKey -instanceKlass org/apache/maven/model/Exclusion -instanceKlass org/apache/maven/artifact/versioning/ComparableVersion$StringItem -instanceKlass org/apache/maven/artifact/handler/DefaultArtifactHandler$__sisu9$$FastClassByGuice$$193548775 -instanceKlass org/apache/maven/repository/internal/DefaultModelCache$Key -instanceKlass org/apache/maven/model/building/ModelCacheTag$2 -instanceKlass org/apache/maven/model/building/ModelCacheTag$1 -instanceKlass org/apache/maven/project/DefaultProjectBuilder$InterimResult -instanceKlass org/eclipse/aether/repository/AuthenticationContext -instanceKlass org/apache/maven/artifact/handler/DefaultArtifactHandler$__sisu13$$FastClassByGuice$$192831898 -instanceKlass org/apache/maven/artifact/versioning/Restriction -instanceKlass org/apache/maven/artifact/ArtifactUtils -instanceKlass org/apache/maven/artifact/DefaultArtifact -instanceKlass org/apache/maven/artifact/handler/DefaultArtifactHandler$$FastClassByGuice$$191574430 -instanceKlass org/apache/maven/artifact/versioning/ComparableVersion$IntItem -instanceKlass org/apache/maven/artifact/versioning/ComparableVersion$Item -instanceKlass org/apache/maven/artifact/versioning/ComparableVersion -instanceKlass org/apache/maven/artifact/versioning/DefaultArtifactVersion -instanceKlass org/apache/maven/repository/internal/ArtifactDescriptorUtils -instanceKlass org/apache/maven/model/Extension -instanceKlass org/codehaus/plexus/interpolation/util/StringUtils -instanceKlass org/apache/maven/model/Organization -instanceKlass org/apache/maven/model/IssueManagement -instanceKlass org/apache/maven/model/CiManagement -instanceKlass org/apache/maven/model/MailingList -instanceKlass org/apache/maven/model/Prerequisites -instanceKlass org/apache/maven/model/Parent -instanceKlass org/codehaus/plexus/interpolation/reflection/MethodMap -instanceKlass org/codehaus/plexus/interpolation/reflection/ClassMap$CacheMiss -instanceKlass org/codehaus/plexus/interpolation/reflection/ClassMap -instanceKlass org/codehaus/plexus/interpolation/reflection/ReflectionValueExtractor$Tokenizer -instanceKlass org/codehaus/plexus/interpolation/reflection/ReflectionValueExtractor -instanceKlass org/codehaus/plexus/interpolation/util/ValueSourceUtils -instanceKlass org/apache/maven/model/interpolation/StringVisitorModelInterpolator$ModelVisitor -instanceKlass org/apache/maven/model/interpolation/StringVisitorModelInterpolator$1 -instanceKlass org/codehaus/plexus/interpolation/PrefixAwareRecursionInterceptor -instanceKlass org/apache/maven/model/interpolation/UrlNormalizingPostProcessor -instanceKlass org/apache/maven/model/interpolation/PathTranslatingPostProcessor -instanceKlass java/text/DontCareFieldPosition$1 -instanceKlass java/text/Format$FieldDelegate -instanceKlass sun/util/resources/Bundles$2 -instanceKlass sun/util/resources/LocaleData$LocaleDataResourceBundleProvider -instanceKlass java/util/spi/ResourceBundleProvider -instanceKlass org/apache/maven/model/interpolation/MavenBuildTimestamp -instanceKlass org/apache/maven/model/interpolation/ProblemDetectingValueSource -instanceKlass org/codehaus/plexus/interpolation/PrefixedValueSourceWrapper -instanceKlass org/codehaus/plexus/interpolation/FeedbackEnabledValueSource -instanceKlass org/codehaus/plexus/interpolation/AbstractDelegatingValueSource -instanceKlass org/codehaus/plexus/interpolation/QueryEnabledValueSource -instanceKlass org/apache/maven/model/merge/ModelMerger$ExtensionKeyComputer -instanceKlass org/apache/maven/model/merge/ModelMerger$ResourceKeyComputer -instanceKlass org/apache/maven/model/building/DefaultModelBuilder$$Lambda$121 -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass org/apache/maven/model/building/DefaultModelBuilder$$Lambda$120 -instanceKlass org/apache/maven/model/building/DefaultModelBuilder$$Lambda$119 -instanceKlass org/apache/maven/model/building/DefaultModelBuilder$$Lambda$118 -instanceKlass org/apache/maven/model/building/DefaultModelBuilder$$Lambda$117 -instanceKlass org/apache/maven/model/building/DefaultModelBuilder$InterpolateString -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass org/apache/maven/model/building/DefaultModelBuilder$1Interpolation -instanceKlass org/apache/maven/model/building/DefaultModelBuilder$$Lambda$116 -instanceKlass org/apache/maven/model/building/DefaultModelBuilder$$Lambda$115 -instanceKlass org/apache/maven/model/building/DefaultModelBuilder$$Lambda$114 -instanceKlass org/apache/maven/model/building/DefaultModelBuilder$$Lambda$113 -instanceKlass org/apache/maven/model/building/DefaultModelBuilder$$Lambda$112 -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass org/apache/maven/model/building/DefaultModelBuilder$$Lambda$111 -instanceKlass org/apache/maven/model/merge/ModelMerger$SourceDominant -instanceKlass org/apache/maven/model/merge/ModelMerger$DependencyKeyComputer -instanceKlass org/apache/maven/model/profile/DefaultProfileActivationContext$$Lambda$110 -instanceKlass org/apache/maven/model/profile/DefaultProfileActivationContext$$Lambda$109 -instanceKlass org/apache/maven/model/profile/DefaultProfileActivationContext$$Lambda$108 -instanceKlass java/util/Spliterators$IteratorSpliterator -instanceKlass org/apache/maven/model/building/DefaultModelBuilder$$Lambda$107 -instanceKlass org/apache/maven/model/building/DefaultModelProblem -instanceKlass org/apache/maven/model/building/ModelProblemCollectorRequest -instanceKlass org/apache/maven/model/building/ModelProblemUtils -instanceKlass org/apache/maven/model/License -instanceKlass org/apache/maven/model/Scm -instanceKlass org/apache/maven/model/io/xpp3/MavenXpp3ReaderEx$Xpp3DomBuilderInputLocationBuilder -instanceKlass org/apache/maven/model/DistributionManagement -instanceKlass org/apache/maven/model/DependencyManagement -instanceKlass org/apache/maven/model/io/xpp3/MavenXpp3ReaderEx$1 -instanceKlass org/codehaus/plexus/util/xml/Xpp3DomBuilder$InputLocationBuilder -instanceKlass org/apache/maven/model/io/xpp3/MavenXpp3ReaderEx$ContentTransformer -instanceKlass org/apache/maven/model/io/xpp3/MavenXpp3ReaderEx -instanceKlass org/apache/maven/model/building/ModelSource2 -instanceKlass org/apache/maven/model/building/DefaultModelBuildingResult -instanceKlass org/apache/maven/model/building/AbstractModelBuildingListener -instanceKlass org/apache/maven/project/ProjectModelResolver -instanceKlass org/apache/maven/model/building/DefaultModelBuildingRequest -instanceKlass org/apache/maven/artifact/repository/LegacyLocalRepositoryManager -instanceKlass org/apache/maven/repository/internal/DefaultModelCache -instanceKlass org/apache/maven/project/DefaultProjectBuildingRequest -instanceKlass org/apache/maven/shared/utils/logging/AnsiMessageBuilder -instanceKlass org/apache/maven/lifecycle/internal/DefaultExecutionEventCatapult$1 -instanceKlass org/apache/maven/lifecycle/internal/DefaultExecutionEvent -instanceKlass org/apache/maven/AbstractMavenLifecycleParticipant -instanceKlass java/util/concurrent/atomic/AtomicReference -instanceKlass org/apache/maven/session/scope/internal/SessionScope$CachingProvider -instanceKlass org/apache/maven/session/scope/internal/SessionScope$$Lambda$106 -instanceKlass org/apache/maven/settings/RuntimeInfo -instanceKlass org/eclipse/aether/internal/impl/LocalPathPrefixComposerFactorySupport$LocalPathPrefixComposerSupport -instanceKlass org/eclipse/aether/internal/impl/SimpleLocalRepositoryManager -instanceKlass java/util/ArrayList$SubList$1 -instanceKlass org/eclipse/aether/internal/impl/PrioritizedComponent -instanceKlass org/eclipse/sisu/wire/EntrySetAdapter$ValueIterator -instanceKlass org/eclipse/aether/internal/impl/PrioritizedComponents -instanceKlass org/apache/maven/RepositoryUtils$$Lambda$105 -instanceKlass java/util/Collections$2 -instanceKlass org/eclipse/aether/repository/RemoteRepository$Builder -instanceKlass org/eclipse/aether/util/ConfigUtils -instanceKlass org/eclipse/aether/AbstractRepositoryListener -instanceKlass org/eclipse/aether/util/repository/ChainedAuthentication -instanceKlass org/eclipse/aether/util/repository/SecretAuthentication -instanceKlass org/eclipse/aether/util/repository/StringAuthentication -instanceKlass org/eclipse/aether/repository/Authentication -instanceKlass org/eclipse/aether/util/repository/AuthenticationBuilder -instanceKlass org/eclipse/aether/util/repository/DefaultAuthenticationSelector -instanceKlass org/eclipse/aether/util/repository/DefaultProxySelector -instanceKlass org/eclipse/aether/util/repository/DefaultMirrorSelector$MirrorDef -instanceKlass org/eclipse/aether/util/repository/DefaultMirrorSelector -instanceKlass org/apache/maven/settings/crypto/DefaultSettingsDecryptionResult -instanceKlass java/util/regex/Pattern$2 -instanceKlass org/apache/maven/settings/crypto/DefaultSettingsDecryptionRequest -instanceKlass org/apache/maven/RepositoryUtils$MavenArtifactTypeRegistry -instanceKlass org/apache/maven/RepositoryUtils -instanceKlass org/eclipse/aether/util/repository/SimpleResolutionErrorPolicy -instanceKlass java/util/stream/Collectors$$Lambda$104 -instanceKlass java/util/stream/Collectors$$Lambda$103 -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass java/util/stream/Collectors$$Lambda$102 -instanceKlass org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactory$$Lambda$101 -instanceKlass org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactory$$Lambda$100 -instanceKlass org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactory$$Lambda$99 -instanceKlass org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactory$$Lambda$98 -instanceKlass org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactory$$Lambda$97 -instanceKlass org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactory$$Lambda$96 -instanceKlass org/eclipse/aether/util/repository/SimpleArtifactDescriptorPolicy -instanceKlass org/eclipse/aether/artifact/DefaultArtifactType -instanceKlass org/eclipse/aether/util/artifact/SimpleArtifactTypeRegistry -instanceKlass org/eclipse/aether/util/graph/transformer/JavaDependencyContextRefiner -instanceKlass org/eclipse/aether/util/graph/transformer/ChainedDependencyGraphTransformer -instanceKlass org/eclipse/aether/util/graph/transformer/ConflictResolver -instanceKlass org/eclipse/aether/graph/Exclusion -instanceKlass org/eclipse/aether/util/graph/selector/ExclusionDependencySelector -instanceKlass org/eclipse/aether/util/graph/selector/OptionalDependencySelector -instanceKlass org/eclipse/aether/util/graph/selector/ScopeDependencySelector -instanceKlass org/eclipse/aether/util/graph/selector/AndDependencySelector -instanceKlass org/eclipse/aether/util/graph/manager/ClassicDependencyManager -instanceKlass org/eclipse/aether/util/graph/traverser/FatArtifactTraverser -instanceKlass org/eclipse/aether/DefaultSessionData -instanceKlass org/eclipse/aether/DefaultRepositorySystemSession$NullFileTransformerManager -instanceKlass org/eclipse/aether/transform/FileTransformerManager -instanceKlass org/eclipse/aether/DefaultRepositorySystemSession$NullArtifactTypeRegistry -instanceKlass org/eclipse/aether/DefaultRepositorySystemSession$NullAuthenticationSelector -instanceKlass org/eclipse/aether/DefaultRepositorySystemSession$NullProxySelector -instanceKlass org/eclipse/aether/DefaultRepositorySystemSession$NullMirrorSelector -instanceKlass org/eclipse/aether/SessionData -instanceKlass org/eclipse/aether/artifact/ArtifactTypeRegistry -instanceKlass org/eclipse/aether/collection/DependencyGraphTransformer -instanceKlass org/eclipse/aether/util/graph/transformer/ConflictResolver$VersionSelector -instanceKlass org/eclipse/aether/util/graph/transformer/ConflictResolver$ScopeSelector -instanceKlass org/eclipse/aether/util/graph/transformer/ConflictResolver$OptionalitySelector -instanceKlass org/eclipse/aether/util/graph/transformer/ConflictResolver$ScopeDeriver -instanceKlass org/apache/maven/repository/internal/MavenRepositorySystemUtils -instanceKlass org/apache/maven/execution/DefaultMavenExecutionResult -instanceKlass org/apache/maven/artifact/repository/MavenArtifactRepository -instanceKlass org/apache/maven/artifact/repository/layout/ArtifactRepositoryLayout2 -instanceKlass org/apache/maven/artifact/repository/layout/DefaultRepositoryLayout$$FastClassByGuice$$190080347 -instanceKlass org/apache/maven/execution/AbstractExecutionListener -instanceKlass org/apache/maven/cli/transfer/SimplexTransferListener$$Lambda$95 -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass org/apache/maven/cli/transfer/SimplexTransferListener$Exchange -instanceKlass org/eclipse/aether/transfer/AbstractTransferListener -instanceKlass org/apache/maven/toolchain/building/DefaultToolchainsBuildingResult -instanceKlass org/apache/maven/toolchain/building/DefaultToolchainsBuilder$1 -instanceKlass org/apache/maven/toolchain/model/io/xpp3/MavenToolchainsXpp3Writer -instanceKlass org/apache/maven/toolchain/model/io/xpp3/MavenToolchainsXpp3Reader$1 -instanceKlass org/apache/maven/toolchain/model/io/xpp3/MavenToolchainsXpp3Reader$ContentTransformer -instanceKlass org/apache/maven/toolchain/model/io/xpp3/MavenToolchainsXpp3Reader -instanceKlass org/apache/maven/building/DefaultProblemCollector -instanceKlass org/apache/maven/building/ProblemCollectorFactory -instanceKlass org/apache/maven/toolchain/building/DefaultToolchainsBuildingRequest -instanceKlass org/apache/maven/settings/SettingsUtils -instanceKlass org/apache/maven/settings/building/DefaultSettingsBuildingResult -instanceKlass org/apache/maven/settings/building/DefaultSettingsBuilder$1 -instanceKlass org/codehaus/plexus/interpolation/os/OperatingSystemUtils$DefaultEnvVarSource -instanceKlass org/codehaus/plexus/interpolation/os/OperatingSystemUtils$EnvVarSource -instanceKlass org/codehaus/plexus/interpolation/os/OperatingSystemUtils -instanceKlass org/codehaus/plexus/util/xml/pull/MXSerializer -instanceKlass org/codehaus/plexus/util/xml/pull/XmlSerializer -instanceKlass org/apache/maven/settings/io/xpp3/SettingsXpp3Writer -instanceKlass org/apache/maven/settings/Activation -instanceKlass org/codehaus/plexus/util/xml/pull/EntityReplacementMap -instanceKlass org/apache/maven/settings/io/xpp3/SettingsXpp3Reader$1 -instanceKlass org/apache/maven/settings/io/xpp3/SettingsXpp3Reader$ContentTransformer -instanceKlass org/apache/maven/settings/io/xpp3/SettingsXpp3Reader -instanceKlass org/apache/maven/building/FileSource -instanceKlass org/apache/maven/settings/building/DefaultSettingsBuildingRequest -instanceKlass java/util/regex/CharPredicates$$Lambda$94 -instanceKlass org/apache/maven/graph/DefaultGraphBuilder$$FastClassByGuice$$189094917 -instanceKlass jdk/internal/math/FDBigInteger -instanceKlass org/apache/maven/plugin/prefix/internal/DefaultPluginPrefixResolver$$FastClassByGuice$$188430346 -instanceKlass org/apache/maven/plugin/CompoundMojoExecutionListener -instanceKlass org/apache/maven/plugin/DefaultBuildPluginManager$$FastClassByGuice$$187389510 -instanceKlass org/apache/maven/lifecycle/internal/DefaultLifecycleTaskSegmentCalculator$$FastClassByGuice$$186284209 -instanceKlass org/apache/maven/lifecycle/internal/DefaultExecutionEventCatapult$$FastClassByGuice$$185288206 -instanceKlass org/apache/maven/project/DefaultProjectDependenciesResolver$$FastClassByGuice$$184068796 -instanceKlass org/apache/maven/project/RepositorySessionDecorator -instanceKlass org/apache/maven/plugin/DefaultPluginArtifactsCache$$FastClassByGuice$$182528964 -instanceKlass com/google/inject/internal/DelegatingInvocationHandler -instanceKlass org/apache/maven/artifact/repository/metadata/io/DefaultMetadataReader$$FastClassByGuice$$182114011 -instanceKlass org/apache/maven/plugin/version/internal/DefaultPluginVersionResolver$$FastClassByGuice$$180538479 -instanceKlass org/apache/maven/plugin/DefaultExtensionRealmCache$$FastClassByGuice$$180249423 -instanceKlass org/apache/maven/rtinfo/internal/DefaultRuntimeInformation$$FastClassByGuice$$178611274 -instanceKlass org/apache/maven/plugin/DefaultPluginRealmCache$$FastClassByGuice$$177300156 -instanceKlass org/apache/maven/plugin/DefaultPluginDescriptorCache$$FastClassByGuice$$176445409 -instanceKlass org/apache/maven/plugin/internal/DefaultMavenPluginManager$$FastClassByGuice$$175219054 -instanceKlass sun/security/jca/GetInstance$Instance -instanceKlass sun/security/provider/AbstractDrbg$$Lambda$93 -instanceKlass sun/security/provider/EntropySource -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass sun/security/provider/AbstractDrbg -instanceKlass java/security/DrbgParameters$Instantiation -instanceKlass java/security/DrbgParameters -instanceKlass sun/security/provider/MoreDrbgParameters -instanceKlass sun/security/provider/DRBG$$Lambda$92 -instanceKlass java/security/SecureRandomParameters -instanceKlass sun/security/jca/GetInstance -instanceKlass java/security/SecureRandomSpi -instanceKlass java/security/Provider$UString -instanceKlass java/security/Provider$Service -instanceKlass sun/security/provider/NativePRNG$NonBlocking -instanceKlass sun/security/provider/NativePRNG$Blocking -instanceKlass sun/security/provider/NativePRNG -instanceKlass sun/security/provider/SunEntries$1 -instanceKlass sun/security/provider/SunEntries -instanceKlass java/security/Security$1 -instanceKlass java/security/Security -instanceKlass sun/security/jca/ProviderList$2 -instanceKlass jdk/internal/math/FloatingDecimal$ASCIIToBinaryBuffer -instanceKlass jdk/internal/math/FloatingDecimal$PreparedASCIIToBinaryBuffer -instanceKlass jdk/internal/math/FloatingDecimal$ASCIIToBinaryConverter -instanceKlass jdk/internal/math/FloatingDecimal$BinaryToASCIIBuffer -instanceKlass jdk/internal/math/FloatingDecimal$ExceptionalBinaryToASCIIBuffer -instanceKlass jdk/internal/math/FloatingDecimal$BinaryToASCIIConverter -instanceKlass jdk/internal/math/FloatingDecimal -instanceKlass java/security/Provider$EngineDescription -instanceKlass java/security/Provider$ServiceKey -instanceKlass sun/security/jca/ProviderConfig -instanceKlass sun/security/jca/ProviderList -instanceKlass sun/security/jca/Providers -instanceKlass java/security/Key -instanceKlass java/security/spec/AlgorithmParameterSpec -instanceKlass org/apache/maven/repository/DefaultMirrorSelector$$FastClassByGuice$$175050506 -instanceKlass org/apache/maven/repository/legacy/repository/DefaultArtifactRepositoryFactory$$FastClassByGuice$$173778212 -instanceKlass org/eclipse/aether/artifact/ArtifactType -instanceKlass org/eclipse/aether/internal/impl/synccontext/named/NamedLockFactoryAdapterFactoryImpl$$Lambda$91 -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass org/eclipse/sisu/wire/NamedIterableAdapter -instanceKlass org/eclipse/aether/internal/impl/DefaultUpdateCheckManager$1 -instanceKlass org/apache/maven/project/artifact/DefaultMavenMetadataCache$$FastClassByGuice$$172681823 -instanceKlass org/apache/maven/repository/legacy/DefaultUpdateCheckManager$$FastClassByGuice$$171245858 -instanceKlass org/apache/maven/repository/legacy/DefaultWagonManager$$FastClassByGuice$$170033660 -instanceKlass org/apache/maven/artifact/repository/metadata/DefaultRepositoryMetadataManager$$FastClassByGuice$$169830119 -instanceKlass org/apache/maven/project/artifact/DefaultMetadataSource$$FastClassByGuice$$168498235 -instanceKlass org/apache/maven/artifact/resolver/DefaultResolutionErrorHandler$$FastClassByGuice$$166754180 -instanceKlass org/apache/maven/plugin/internal/DefaultLegacySupport$$FastClassByGuice$$165965299 -instanceKlass org/apache/maven/repository/legacy/resolver/conflict/NearestConflictResolver$$FastClassByGuice$$165478117 -instanceKlass org/apache/maven/artifact/resolver/DefaultArtifactCollector$$FastClassByGuice$$164484260 -instanceKlass org/apache/maven/artifact/resolver/DefaultArtifactResolver$DaemonThreadCreator -instanceKlass java/util/concurrent/ThreadPoolExecutor$AbortPolicy -instanceKlass java/util/concurrent/RejectedExecutionHandler -instanceKlass java/util/concurrent/AbstractExecutorService -instanceKlass java/util/concurrent/ExecutorService -instanceKlass org/apache/maven/artifact/resolver/DefaultArtifactResolver$$FastClassByGuice$$162726236 -instanceKlass org/apache/maven/artifact/handler/manager/DefaultArtifactHandlerManager$$FastClassByGuice$$162507178 -instanceKlass org/apache/maven/artifact/factory/DefaultArtifactFactory$$FastClassByGuice$$161297155 -instanceKlass org/apache/maven/repository/legacy/LegacyRepositorySystem$$FastClassByGuice$$159649744 -instanceKlass org/apache/maven/project/DefaultProjectRealmCache$$FastClassByGuice$$158631616 -instanceKlass org/codehaus/plexus/classworlds/realm/Entry -instanceKlass java/util/Random -instanceKlass org/eclipse/sisu/inject/Guice4$2 -instanceKlass org/apache/maven/project/DefaultProjectBuildingHelper$$FastClassByGuice$$157304212 -instanceKlass org/apache/maven/lifecycle/internal/DefaultLifecyclePluginAnalyzer$$FastClassByGuice$$156384582 -instanceKlass org/apache/maven/model/plugin/DefaultLifecycleBindingsInjector$$FastClassByGuice$$155942646 -instanceKlass org/apache/maven/model/merge/ModelMerger$KeyComputer -instanceKlass org/apache/maven/model/PatternSet -instanceKlass org/apache/maven/model/Contributor -instanceKlass org/apache/maven/model/merge/ModelMerger$Remapping -instanceKlass org/apache/maven/project/DefaultProjectBuilder$$FastClassByGuice$$154855803 -instanceKlass org/apache/maven/DefaultMaven$$FastClassByGuice$$153194125 -instanceKlass org/apache/maven/cli/event/DefaultEventSpyContext -instanceKlass org/eclipse/sisu/wire/EntryListAdapter$ValueIterator -instanceKlass org/apache/maven/cli/logging/Slf4jLogger -instanceKlass org/eclipse/sisu/inject/LazyBeanEntry$JsrNamed -instanceKlass org/eclipse/sisu/inject/LazyBeanEntry -instanceKlass javax/annotation/Priority -instanceKlass org/eclipse/sisu/inject/Implementations -instanceKlass org/eclipse/sisu/plexus/LazyPlexusBean -instanceKlass org/eclipse/sisu/inject/RankedSequence$Itr -instanceKlass org/eclipse/sisu/inject/RankedBindings$Itr -instanceKlass org/eclipse/sisu/inject/LocatedBeans$Itr -instanceKlass org/eclipse/sisu/plexus/RealmFilteredBeans$FilteredItr -instanceKlass org/eclipse/sisu/plexus/DefaultPlexusBeans$Itr -instanceKlass org/eclipse/sisu/plexus/DefaultPlexusBeans -instanceKlass org/eclipse/sisu/plexus/RealmFilteredBeans -instanceKlass org/eclipse/sisu/inject/BeanCache -instanceKlass org/eclipse/sisu/inject/LocatedBeans -instanceKlass org/eclipse/sisu/inject/MildElements$Indexable -instanceKlass com/google/inject/internal/ProviderInternalFactory$1 -instanceKlass com/google/inject/internal/ConstructorInjector$1 -instanceKlass org/eclipse/sisu/inject/WatchedBeans -instanceKlass org/eclipse/sisu/inject/MildValues$ValueItr -instanceKlass org/eclipse/sisu/inject/InjectorBindings -instanceKlass com/google/inject/spi/ProvisionListener$ProvisionInvocation -instanceKlass com/google/inject/internal/MembersInjectorImpl$1 -instanceKlass com/google/inject/internal/InternalContext -instanceKlass com/google/inject/internal/Initializer$1 -instanceKlass com/google/common/collect/AbstractMapBasedMultimap$AsMap$AsMapIterator -instanceKlass org/codehaus/plexus/DefaultPlexusContainer$$FastClassByGuice$$152868334 -instanceKlass org/eclipse/sisu/wire/TypeConverterCache$$FastClassByGuice$$151829900 -instanceKlass com/google/inject/internal/SingleMethodInjector$1 -instanceKlass org/eclipse/sisu/inject/DefaultBeanLocator$$FastClassByGuice$$150706837 -instanceKlass com/google/inject/internal/InjectorImpl$MethodInvoker -instanceKlass com/google/inject/internal/SingleMethodInjector -instanceKlass org/eclipse/sisu/plexus/PlexusXmlBeanConverter$$FastClassByGuice$$149079024 -instanceKlass org/sonatype/plexus/components/sec/dispatcher/DefaultSecDispatcher$$FastClassByGuice$$148520941 -instanceKlass org/sonatype/plexus/components/cipher/DefaultPlexusCipher$$FastClassByGuice$$147739503 -instanceKlass org/codehaus/plexus/component/configurator/MapOrientedComponentConfigurator$$FastClassByGuice$$146240209 -instanceKlass org/codehaus/plexus/component/configurator/BasicComponentConfigurator$$FastClassByGuice$$144821603 -instanceKlass org/apache/maven/settings/validation/DefaultSettingsValidator$$FastClassByGuice$$144694485 -instanceKlass org/apache/maven/settings/io/DefaultSettingsWriter$$FastClassByGuice$$143526408 -instanceKlass org/apache/maven/settings/io/DefaultSettingsReader$$FastClassByGuice$$142529765 -instanceKlass org/apache/maven/settings/crypto/DefaultSettingsDecrypter$$FastClassByGuice$$141277246 -instanceKlass org/apache/maven/settings/building/DefaultSettingsBuilder$$FastClassByGuice$$139747136 -instanceKlass org/eclipse/aether/transport/wagon/WagonTransporterFactory$$FastClassByGuice$$138733899 -instanceKlass org/eclipse/aether/internal/transport/wagon/PlexusWagonProvider$$FastClassByGuice$$137948504 -instanceKlass org/eclipse/aether/internal/transport/wagon/PlexusWagonConfigurator$$FastClassByGuice$$136963755 -instanceKlass org/eclipse/aether/transport/http/XChecksumChecksumExtractor$$FastClassByGuice$$135447688 -instanceKlass org/eclipse/aether/transport/http/Nexus2ChecksumExtractor$$FastClassByGuice$$134613402 -instanceKlass org/eclipse/aether/transport/http/HttpTransporterFactory$$FastClassByGuice$$133947060 -instanceKlass org/eclipse/aether/transport/file/FileTransporterFactory$$FastClassByGuice$$133097624 -instanceKlass org/apache/maven/repository/internal/VersionsMetadataGeneratorFactory$$FastClassByGuice$$131661045 -instanceKlass org/apache/maven/repository/internal/SnapshotMetadataGeneratorFactory$$FastClassByGuice$$130970677 -instanceKlass org/apache/maven/repository/internal/PluginsMetadataGeneratorFactory$$FastClassByGuice$$129584490 -instanceKlass org/apache/maven/repository/internal/DefaultVersionResolver$$FastClassByGuice$$127927416 -instanceKlass org/apache/maven/repository/internal/DefaultVersionRangeResolver$$FastClassByGuice$$126910179 -instanceKlass org/apache/maven/repository/internal/DefaultModelCacheFactory$$FastClassByGuice$$125963662 -instanceKlass org/apache/maven/repository/internal/DefaultArtifactDescriptorReader$$FastClassByGuice$$125489822 -instanceKlass org/eclipse/aether/named/providers/NoopNamedLockFactory$$FastClassByGuice$$124778737 -instanceKlass org/eclipse/aether/named/providers/LocalSemaphoreNamedLockFactory$$FastClassByGuice$$122690098 -instanceKlass org/eclipse/aether/named/providers/LocalReadWriteLockNamedLockFactory$$FastClassByGuice$$121861520 -instanceKlass org/eclipse/aether/named/providers/FileLockNamedLockFactory$$FastClassByGuice$$120880729 -instanceKlass org/eclipse/aether/internal/impl/synccontext/named/providers/StaticNameMapperProvider$$FastClassByGuice$$120393761 -instanceKlass org/eclipse/aether/internal/impl/synccontext/named/providers/GAVNameMapperProvider$$FastClassByGuice$$118627387 -instanceKlass org/eclipse/aether/internal/impl/synccontext/named/providers/FileStaticNameMapperProvider$$FastClassByGuice$$118036912 -instanceKlass org/eclipse/aether/internal/impl/synccontext/named/providers/FileHashingGAVNameMapperProvider$$FastClassByGuice$$117023182 -instanceKlass org/eclipse/aether/internal/impl/synccontext/named/providers/FileGAVNameMapperProvider$$FastClassByGuice$$115699963 -instanceKlass org/eclipse/aether/internal/impl/synccontext/named/providers/DiscriminatingNameMapperProvider$$FastClassByGuice$$114468496 -instanceKlass org/eclipse/aether/internal/impl/synccontext/named/NamedLockFactoryAdapterFactoryImpl$$FastClassByGuice$$114129160 -instanceKlass org/eclipse/aether/internal/impl/synccontext/legacy/DefaultSyncContextFactory$$FastClassByGuice$$112896315 -instanceKlass org/eclipse/aether/internal/impl/synccontext/DefaultSyncContextFactory$$FastClassByGuice$$111210038 -instanceKlass org/eclipse/aether/internal/impl/slf4j/Slf4jLoggerFactory$$FastClassByGuice$$110660156 -instanceKlass org/eclipse/aether/internal/impl/resolution/TrustedChecksumsArtifactResolverPostProcessor$$FastClassByGuice$$109263607 -instanceKlass org/eclipse/aether/internal/impl/filter/PrefixesRemoteRepositoryFilterSource$$FastClassByGuice$$108766362 -instanceKlass org/eclipse/aether/internal/impl/filter/GroupIdRemoteRepositoryFilterSource$$FastClassByGuice$$107619452 -instanceKlass org/eclipse/aether/internal/impl/filter/DefaultRemoteRepositoryFilterManager$$FastClassByGuice$$106513089 -instanceKlass org/eclipse/aether/internal/impl/collect/df/DfDependencyCollector$$FastClassByGuice$$105483252 -instanceKlass org/eclipse/aether/internal/impl/collect/bf/BfDependencyCollector$$FastClassByGuice$$104388190 -instanceKlass org/eclipse/aether/internal/impl/collect/DefaultDependencyCollector$$FastClassByGuice$$102892241 -instanceKlass org/eclipse/aether/internal/impl/checksum/TrustedToProvidedChecksumsSourceAdapter$$FastClassByGuice$$102516310 -instanceKlass org/eclipse/aether/internal/impl/checksum/SummaryFileTrustedChecksumsSource$$FastClassByGuice$$101074147 -instanceKlass org/eclipse/aether/internal/impl/checksum/SparseDirectoryTrustedChecksumsSource$$FastClassByGuice$$100404195 -instanceKlass org/eclipse/aether/internal/impl/checksum/Sha512ChecksumAlgorithmFactory$$FastClassByGuice$$99284345 -instanceKlass org/eclipse/aether/internal/impl/checksum/Sha256ChecksumAlgorithmFactory$$FastClassByGuice$$97645913 -instanceKlass org/eclipse/aether/internal/impl/checksum/Sha1ChecksumAlgorithmFactory$$FastClassByGuice$$97070265 -instanceKlass com/google/inject/internal/aop/ImmutableStringTrie$$Lambda$90 -instanceKlass org/eclipse/aether/internal/impl/checksum/Md5ChecksumAlgorithmFactory$$FastClassByGuice$$95479553 -instanceKlass org/eclipse/aether/internal/impl/checksum/DefaultChecksumAlgorithmFactorySelector$$FastClassByGuice$$94450423 -instanceKlass org/eclipse/aether/internal/impl/SimpleLocalRepositoryManagerFactory$$FastClassByGuice$$93827759 -instanceKlass org/eclipse/aether/internal/impl/Maven2RepositoryLayoutFactory$$FastClassByGuice$$92680442 -instanceKlass org/eclipse/aether/internal/impl/LoggerFactoryProvider$$FastClassByGuice$$91640461 -instanceKlass org/eclipse/aether/internal/impl/EnhancedLocalRepositoryManagerFactory$$FastClassByGuice$$90515932 -instanceKlass org/eclipse/aether/internal/impl/DefaultUpdatePolicyAnalyzer$$FastClassByGuice$$89433434 -instanceKlass org/eclipse/aether/internal/impl/DefaultUpdateCheckManager$$FastClassByGuice$$88997461 -instanceKlass org/eclipse/aether/internal/impl/DefaultTransporterProvider$$FastClassByGuice$$87769951 -instanceKlass org/eclipse/aether/internal/impl/DefaultTrackingFileManager$$FastClassByGuice$$85989381 -instanceKlass org/eclipse/aether/internal/impl/DefaultRepositorySystemLifecycle$$FastClassByGuice$$85953367 -instanceKlass org/eclipse/aether/internal/impl/DefaultRepositorySystem$$FastClassByGuice$$84536390 -instanceKlass org/eclipse/aether/internal/impl/DefaultRepositoryLayoutProvider$$FastClassByGuice$$82907475 -instanceKlass org/eclipse/aether/internal/impl/DefaultRepositoryEventDispatcher$$FastClassByGuice$$81970250 -instanceKlass org/eclipse/aether/internal/impl/DefaultRepositoryConnectorProvider$$FastClassByGuice$$80815137 -instanceKlass org/eclipse/aether/internal/impl/DefaultRemoteRepositoryManager$$FastClassByGuice$$80600150 -instanceKlass org/eclipse/aether/internal/impl/DefaultOfflineController$$FastClassByGuice$$79480105 -instanceKlass org/eclipse/aether/internal/impl/DefaultMetadataResolver$$FastClassByGuice$$77894508 -instanceKlass org/eclipse/aether/internal/impl/DefaultLocalRepositoryProvider$$FastClassByGuice$$77147489 -instanceKlass org/eclipse/aether/internal/impl/DefaultLocalPathPrefixComposerFactory$$FastClassByGuice$$76027952 -instanceKlass org/eclipse/aether/internal/impl/DefaultLocalPathComposer$$FastClassByGuice$$75361344 -instanceKlass org/eclipse/aether/internal/impl/DefaultInstaller$$FastClassByGuice$$73950733 -instanceKlass org/eclipse/aether/internal/impl/DefaultFileProcessor$$FastClassByGuice$$72470031 -instanceKlass org/eclipse/aether/internal/impl/DefaultDeployer$$FastClassByGuice$$71375188 -instanceKlass org/eclipse/aether/internal/impl/DefaultChecksumPolicyProvider$$FastClassByGuice$$70939713 -instanceKlass org/eclipse/aether/internal/impl/DefaultArtifactResolver$$FastClassByGuice$$69937042 -instanceKlass org/eclipse/aether/connector/basic/BasicRepositoryConnectorFactory$$FastClassByGuice$$68716032 -instanceKlass org/apache/maven/model/validation/DefaultModelValidator$$FastClassByGuice$$67791041 -instanceKlass org/apache/maven/model/superpom/DefaultSuperPomProvider$$FastClassByGuice$$66226097 -instanceKlass org/apache/maven/model/profile/activation/PropertyProfileActivator$$FastClassByGuice$$65835517 -instanceKlass org/apache/maven/model/profile/activation/OperatingSystemProfileActivator$$FastClassByGuice$$64441927 -instanceKlass org/apache/maven/model/profile/activation/JdkVersionProfileActivator$$FastClassByGuice$$63194836 -instanceKlass org/apache/maven/model/profile/activation/FileProfileActivator$$FastClassByGuice$$62902457 -instanceKlass org/apache/maven/model/profile/DefaultProfileSelector$$FastClassByGuice$$60890497 -instanceKlass org/apache/maven/model/profile/DefaultProfileInjector$$FastClassByGuice$$60378694 -instanceKlass org/apache/maven/model/plugin/DefaultReportingConverter$$FastClassByGuice$$59412528 -instanceKlass org/apache/maven/model/plugin/DefaultReportConfigurationExpander$$FastClassByGuice$$57820132 -instanceKlass org/apache/maven/model/plugin/DefaultPluginConfigurationExpander$$FastClassByGuice$$57062996 -instanceKlass org/apache/maven/model/path/ProfileActivationFilePathInterpolator$$FastClassByGuice$$55962024 -instanceKlass org/apache/maven/model/path/DefaultUrlNormalizer$$FastClassByGuice$$55145175 -instanceKlass org/apache/maven/model/path/DefaultPathTranslator$$FastClassByGuice$$53501660 -instanceKlass org/apache/maven/model/path/DefaultModelUrlNormalizer$$FastClassByGuice$$52962818 -instanceKlass org/apache/maven/model/path/DefaultModelPathTranslator$$FastClassByGuice$$52100706 -instanceKlass org/apache/maven/model/normalization/DefaultModelNormalizer$$FastClassByGuice$$50581811 -instanceKlass org/apache/maven/model/management/DefaultPluginManagementInjector$$FastClassByGuice$$49673461 -instanceKlass org/apache/maven/model/management/DefaultDependencyManagementInjector$$FastClassByGuice$$48887397 -instanceKlass org/apache/maven/model/locator/DefaultModelLocator$$FastClassByGuice$$47448711 -instanceKlass org/apache/maven/model/io/DefaultModelWriter$$FastClassByGuice$$46151661 -instanceKlass org/apache/maven/model/io/DefaultModelReader$$FastClassByGuice$$45704370 -instanceKlass org/apache/maven/model/interpolation/StringVisitorModelInterpolator$$FastClassByGuice$$44690750 -instanceKlass org/apache/maven/model/interpolation/DefaultModelVersionProcessor$$FastClassByGuice$$43950269 -instanceKlass org/apache/maven/model/inheritance/DefaultInheritanceAssembler$$FastClassByGuice$$42623475 -instanceKlass org/apache/maven/model/composition/DefaultDependencyManagementImporter$$FastClassByGuice$$41244873 -instanceKlass org/apache/maven/model/building/DefaultModelProcessor$$FastClassByGuice$$40784961 -instanceKlass org/apache/maven/model/building/DefaultModelBuilder$$FastClassByGuice$$39558938 -instanceKlass org/apache/maven/cli/internal/BootstrapCoreExtensionManager$$FastClassByGuice$$37838463 -instanceKlass org/apache/maven/cli/configuration/SettingsXmlConfigurationProcessor$$FastClassByGuice$$37033859 -instanceKlass org/apache/maven/toolchain/io/DefaultToolchainsWriter$$FastClassByGuice$$36496134 -instanceKlass org/apache/maven/toolchain/io/DefaultToolchainsReader$$FastClassByGuice$$35249980 -instanceKlass org/apache/maven/toolchain/building/DefaultToolchainsBuilder$$FastClassByGuice$$34439568 -instanceKlass org/apache/maven/plugin/internal/ReadOnlyPluginParametersValidator$$FastClassByGuice$$33464054 -instanceKlass org/apache/maven/plugin/internal/PlexusContainerDefaultDependenciesValidator$$FastClassByGuice$$32420335 -instanceKlass org/apache/maven/plugin/internal/MavenScopeDependenciesValidator$$FastClassByGuice$$31053205 -instanceKlass org/apache/maven/plugin/internal/MavenMixedDependenciesValidator$$FastClassByGuice$$29930126 -instanceKlass org/apache/maven/plugin/internal/Maven3CompatDependenciesValidator$$FastClassByGuice$$28493337 -instanceKlass org/apache/maven/plugin/internal/Maven2DependenciesValidator$$FastClassByGuice$$27868184 -instanceKlass org/apache/maven/plugin/internal/DeprecatedPluginValidator$$FastClassByGuice$$26931918 -instanceKlass org/apache/maven/plugin/internal/DeprecatedCoreExpressionValidator$$FastClassByGuice$$26183502 -instanceKlass org/apache/maven/plugin/internal/DefaultPluginValidationManager$$FastClassByGuice$$25142511 -instanceKlass org/apache/maven/plugin/DefaultMojosExecutionStrategy$$FastClassByGuice$$23908594 -instanceKlass org/apache/maven/lifecycle/internal/LifecycleDependencyResolver$$FastClassByGuice$$22554587 -instanceKlass org/apache/maven/lifecycle/internal/DefaultProjectArtifactFactory$$FastClassByGuice$$21181153 -instanceKlass org/apache/maven/internal/aether/ResolverLifecycle$$FastClassByGuice$$20573653 -instanceKlass com/google/inject/internal/InjectorImpl$SyntheticProviderBindingImpl$1 -instanceKlass com/google/inject/internal/InjectorImpl$1 -instanceKlass org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactory$$FastClassByGuice$$19105736 -instanceKlass com/google/inject/internal/SingleFieldInjector -instanceKlass org/apache/maven/extension/internal/CoreExportsProvider$$FastClassByGuice$$18135296 -instanceKlass org/apache/maven/execution/DefaultMavenExecutionRequestPopulator$$FastClassByGuice$$17198213 -instanceKlass org/apache/maven/classrealm/DefaultClassRealmManager$$FastClassByGuice$$16264463 -instanceKlass org/apache/maven/ReactorReader$$FastClassByGuice$$15242928 -instanceKlass org/apache/maven/DefaultArtifactFilterManager$$FastClassByGuice$$13720657 -instanceKlass com/google/inject/internal/SingleParameterInjector -instanceKlass org/apache/maven/lifecycle/DefaultLifecycles$$FastClassByGuice$$12828198 -instanceKlass org/apache/maven/lifecycle/internal/builder/BuilderCommon$$FastClassByGuice$$11638180 -instanceKlass org/apache/maven/lifecycle/Lifecycle$$FastClassByGuice$$10914199 -instanceKlass org/eclipse/sisu/plexus/PlexusConfigurations$ConfigurationProvider -instanceKlass org/apache/maven/lifecycle/internal/MojoDescriptorCreator$$FastClassByGuice$$9728791 -instanceKlass org/apache/maven/lifecycle/internal/MojoExecutor$$FastClassByGuice$$9347000 -instanceKlass org/apache/maven/bridge/MavenRepositorySystem$$FastClassByGuice$$7960476 -instanceKlass org/apache/maven/lifecycle/internal/LifecycleStarter$$FastClassByGuice$$6295052 -instanceKlass org/apache/maven/lifecycle/internal/LifecycleModuleBuilder$$FastClassByGuice$$5688002 -instanceKlass org/apache/maven/lifecycle/internal/BuildListCalculator$$FastClassByGuice$$4317441 -instanceKlass org/apache/maven/lifecycle/internal/LifecyclePluginResolver$$FastClassByGuice$$3771845 -instanceKlass org/apache/maven/eventspy/internal/EventSpyDispatcher$$FastClassByGuice$$3017675 -instanceKlass org/eclipse/sisu/bean/BeanPropertySetter -instanceKlass org/eclipse/sisu/PreDestroy -instanceKlass org/eclipse/sisu/PostConstruct -instanceKlass org/apache/maven/lifecycle/internal/LifecycleDebugLogger$$FastClassByGuice$$1364887 -instanceKlass com/google/inject/internal/ProxyFactory -instanceKlass com/google/common/collect/TransformedIterator -instanceKlass com/google/inject/internal/ConstructorInjectorStore$$Lambda$89 -instanceKlass com/google/inject/spi/InterceptorBinding -instanceKlass com/google/inject/internal/MethodAspect -instanceKlass com/google/inject/internal/MembersInjectorImpl -instanceKlass org/eclipse/sisu/bean/BeanInjector -instanceKlass org/eclipse/sisu/plexus/PlexusLifecycleManager$2 -instanceKlass org/eclipse/sisu/bean/PropertyBinder$1 -instanceKlass org/eclipse/sisu/plexus/ProvidedPropertyBinding -instanceKlass org/eclipse/sisu/plexus/PlexusRequirements$AbstractRequirementProvider -instanceKlass org/eclipse/sisu/bean/BeanPropertyField -instanceKlass org/eclipse/sisu/bean/DeclaredMembers$MemberIterator -instanceKlass org/eclipse/sisu/bean/BeanPropertyIterator -instanceKlass org/eclipse/sisu/bean/DeclaredMembers -instanceKlass org/eclipse/sisu/bean/IgnoreSetters -instanceKlass org/eclipse/sisu/bean/BeanProperties -instanceKlass org/eclipse/sisu/plexus/PlexusRequirements -instanceKlass org/eclipse/sisu/plexus/PlexusConfigurations -instanceKlass org/eclipse/sisu/plexus/PlexusPropertyBinder -instanceKlass org/eclipse/sisu/bean/BeanLifecycle -instanceKlass com/google/inject/internal/EncounterImpl -instanceKlass com/google/inject/internal/AbstractBindingProcessor$Processor$$Lambda$88 -instanceKlass org/apache/maven/session/scope/internal/SessionScope$$Lambda$87 -instanceKlass org/apache/maven/execution/scope/internal/MojoExecutionScope$2 -instanceKlass com/google/inject/internal/ProviderInternalFactory -instanceKlass com/google/inject/internal/InternalProviderInstanceBindingImpl$Factory -instanceKlass com/google/inject/internal/FactoryProxy -instanceKlass com/google/inject/internal/InternalFactoryToProviderAdapter -instanceKlass com/google/inject/internal/ConstructionContext -instanceKlass com/google/inject/internal/SingletonScope$1 -instanceKlass com/google/inject/internal/ProviderToInternalFactoryAdapter -instanceKlass com/google/inject/internal/CycleDetectingLock$CycleDetectingLockFactory$ReentrantCycleDetectingLock -instanceKlass com/google/inject/internal/Initializer$InjectableReference -instanceKlass com/google/inject/internal/ProvisionListenerStackCallback -instanceKlass com/google/common/cache/LocalCache$AbstractReferenceEntry -instanceKlass com/google/inject/internal/ProvisionListenerCallbackStore$KeyBinding -instanceKlass com/google/inject/internal/util/Classes -instanceKlass com/google/inject/spi/ExposedBinding -instanceKlass com/google/inject/internal/CreationListener -instanceKlass com/google/inject/internal/InjectorShell$LoggerFactory -instanceKlass com/google/inject/internal/InjectorShell$InjectorFactory -instanceKlass com/google/inject/internal/Initializables$1 -instanceKlass com/google/inject/internal/Initializables -instanceKlass com/google/inject/internal/ConstantFactory -instanceKlass com/google/inject/internal/InjectorShell -instanceKlass com/google/inject/internal/ProvisionListenerCallbackStore -instanceKlass com/google/inject/spi/TypeEncounter -instanceKlass com/google/inject/internal/SingleMemberInjector -instanceKlass com/google/inject/internal/MembersInjectorStore -instanceKlass com/google/inject/internal/TypeConverterBindingProcessor$4 -instanceKlass com/google/inject/internal/TypeConverterBindingProcessor$2 -instanceKlass com/google/inject/internal/TypeConverterBindingProcessor$1 -instanceKlass com/google/inject/internal/TypeConverterBindingProcessor$5 -instanceKlass com/google/inject/internal/FailableCache -instanceKlass com/google/inject/internal/ConstructorInjectorStore -instanceKlass com/google/inject/internal/DeferredLookups -instanceKlass com/google/inject/spi/ProviderBinding -instanceKlass com/google/inject/spi/ConvertedConstantBinding -instanceKlass com/google/inject/internal/InjectorImpl -instanceKlass com/google/inject/internal/Lookups -instanceKlass com/google/inject/internal/InjectorImpl$InjectorOptions -instanceKlass com/google/inject/internal/AbstractProcessor$$Lambda$86 -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass com/google/inject/spi/BindingSourceRestriction$$Lambda$85 -instanceKlass org/eclipse/sisu/wire/BeanProviders$3 -instanceKlass org/sonatype/inject/BeanEntry -instanceKlass org/eclipse/sisu/BeanEntry -instanceKlass org/eclipse/sisu/wire/BeanProviders$4 -instanceKlass com/google/inject/internal/ProvisionListenerStackCallback$ProvisionCallback -instanceKlass com/google/inject/internal/ConstructorInjector -instanceKlass com/google/inject/internal/DefaultConstructionProxyFactory$FastClassProxy -instanceKlass java/lang/invoke/LambdaForm$MH -instanceKlass com/google/inject/internal/aop/AbstractGlueGenerator$$Lambda$84 -instanceKlass com/google/inject/internal/aop/ImmutableStringTrie -instanceKlass java/util/function/ToIntFunction -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass org/apache/maven/plugin/internal/DefaultPluginDependenciesResolver$$FastClassByGuice$$1034782 -instanceKlass com/google/inject/internal/aop/GeneratedClassDefiner -instanceKlass java/lang/ClassLoader$$DefineAccessByGuice$$ -instanceKlass java/lang/WeakPairMap$$Lambda$83 -instanceKlass java/lang/Module$$Lambda$82 -instanceKlass java/util/RegularEnumSet$EnumSetIterator -instanceKlass java/lang/module/ModuleDescriptor$Builder$$Lambda$81 -instanceKlass jdk/internal/module/Checks -instanceKlass java/lang/module/ModuleDescriptor$Builder -instanceKlass java/lang/reflect/Proxy$ProxyBuilder$$Lambda$80 -instanceKlass jdk/internal/vm/annotation/ForceInline -instanceKlass java/lang/reflect/AccessibleObject$$Lambda$79 -instanceKlass com/google/inject/internal/aop/UnsafeClassDefiner$ClassLoaderDefineClassHolder$$Lambda$78 -instanceKlass com/google/inject/internal/aop/UnsafeClassDefiner$ClassLoaderDefineClassHolder -instanceKlass com/google/inject/internal/asm/$Handler -instanceKlass com/google/inject/internal/asm/$Attribute -instanceKlass com/google/inject/internal/aop/BytecodeTasks -instanceKlass com/google/inject/internal/aop/AbstractGlueGenerator$$Lambda$77 -instanceKlass com/google/inject/internal/asm/$Handle -instanceKlass com/google/inject/internal/asm/$Label -instanceKlass com/google/inject/internal/asm/$Frame -instanceKlass com/google/inject/internal/asm/$ByteVector -instanceKlass com/google/inject/internal/asm/$Symbol -instanceKlass com/google/inject/internal/asm/$SymbolTable -instanceKlass com/google/inject/internal/asm/$MethodVisitor -instanceKlass com/google/inject/internal/asm/$ModuleVisitor -instanceKlass com/google/inject/internal/asm/$AnnotationVisitor -instanceKlass com/google/inject/internal/asm/$FieldVisitor -instanceKlass com/google/inject/internal/asm/$RecordComponentVisitor -instanceKlass com/google/inject/internal/asm/$ClassVisitor -instanceKlass com/google/inject/internal/aop/AbstractGlueGenerator -instanceKlass com/google/inject/internal/aop/ClassBuilding$$Lambda$76 -instanceKlass com/google/inject/internal/aop/ClassBuilding$$Lambda$75 -instanceKlass com/google/inject/internal/asm/$Type -instanceKlass com/google/inject/internal/aop/UnsafeClassDefiner$$Lambda$74 -instanceKlass com/google/inject/internal/aop/AnonymousClassDefiner -instanceKlass com/google/inject/internal/aop/UnsafeClassDefiner -instanceKlass com/google/inject/internal/aop/ClassDefining$ClassDefinerHolder -instanceKlass com/google/inject/internal/aop/ClassDefiner -instanceKlass com/google/inject/internal/aop/ClassDefining -instanceKlass com/google/inject/internal/aop/ClassBuilding$$Lambda$73 -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass com/google/inject/internal/BytecodeGen$$Lambda$72 -instanceKlass com/google/inject/internal/BytecodeGen$EnhancerBuilder -instanceKlass com/google/inject/internal/aop/ClassBuilding -instanceKlass com/google/common/collect/MapMakerInternalMap$StrongValueEntry -instanceKlass com/google/common/collect/MapMakerInternalMap$WeakKeyStrongValueEntry$Helper -instanceKlass com/google/common/collect/MapMakerInternalMap$InternalEntry -instanceKlass com/google/common/collect/MapMakerInternalMap$1 -instanceKlass com/google/common/collect/MapMakerInternalMap$InternalEntryHelper -instanceKlass com/google/common/collect/MapMakerInternalMap$WeakValueReference -instanceKlass com/google/common/collect/MapMaker -instanceKlass com/google/inject/internal/BytecodeGen -instanceKlass com/google/inject/internal/ConstructionProxy -instanceKlass com/google/inject/internal/DefaultConstructionProxyFactory -instanceKlass com/google/inject/internal/ConstructionProxyFactory -instanceKlass com/google/inject/internal/ConstructorBindingImpl$Factory -instanceKlass org/eclipse/sisu/inject/TypeArguments$Implicit -instanceKlass org/eclipse/sisu/wire/PlaceholderBeanProvider -instanceKlass org/eclipse/sisu/wire/BeanProviders$6 -instanceKlass org/eclipse/sisu/wire/BeanProviders$7 -instanceKlass org/eclipse/sisu/wire/BeanProviders$1 -instanceKlass com/google/inject/spi/ProviderLookup$1 -instanceKlass com/google/inject/spi/ProviderWithDependencies -instanceKlass com/google/inject/spi/ProviderLookup -instanceKlass org/eclipse/sisu/wire/BeanProviders -instanceKlass org/eclipse/sisu/inject/HiddenSource -instanceKlass org/eclipse/sisu/wire/LocatorWiring -instanceKlass com/google/inject/ProvidedBy -instanceKlass com/google/inject/ImplementedBy -instanceKlass org/sonatype/plexus/components/cipher/PBECipher -instanceKlass org/codehaus/classworlds/ClassRealm -instanceKlass org/apache/maven/settings/crypto/SettingsDecryptionResult -instanceKlass org/apache/maven/settings/building/DefaultSettingsProblemCollector -instanceKlass org/apache/maven/settings/merge/MavenSettingsMerger -instanceKlass org/apache/maven/settings/building/SettingsBuildingResult -instanceKlass org/apache/maven/settings/building/SettingsProblemCollector -instanceKlass org/eclipse/aether/impl/MetadataGenerator -instanceKlass org/apache/maven/model/Relocation -instanceKlass org/apache/maven/repository/internal/ArtifactDescriptorReaderDelegate -instanceKlass org/eclipse/aether/named/support/AdaptedSemaphoreNamedLock$AdaptedSemaphore -instanceKlass org/eclipse/aether/named/support/NamedLockFactorySupport$NamedLockHolder -instanceKlass org/eclipse/aether/named/support/NamedLockSupport -instanceKlass org/eclipse/aether/named/NamedLock -instanceKlass org/eclipse/aether/internal/impl/synccontext/named/NamedLockFactoryAdapter -instanceKlass org/eclipse/aether/spi/log/Logger -instanceKlass org/eclipse/aether/internal/impl/filter/PrefixesRemoteRepositoryFilterSource$Node -instanceKlass org/eclipse/aether/spi/connector/filter/RemoteRepositoryFilter$Result -instanceKlass org/eclipse/aether/spi/connector/filter/RemoteRepositoryFilter -instanceKlass org/eclipse/aether/collection/DependencyTraverser -instanceKlass org/eclipse/aether/collection/DependencyManager -instanceKlass org/eclipse/aether/internal/impl/collect/df/DfDependencyCollector$Args -instanceKlass org/eclipse/aether/internal/impl/collect/bf/BfDependencyCollector$DescriptorResolutionResult -instanceKlass org/eclipse/aether/internal/impl/collect/bf/BfDependencyCollector$Args -instanceKlass org/eclipse/aether/internal/impl/collect/bf/DependencyProcessingContext -instanceKlass org/eclipse/aether/internal/impl/collect/bf/DependencyResolutionSkipper -instanceKlass org/eclipse/aether/internal/impl/collect/DependencyCollectorDelegate$Results -instanceKlass org/eclipse/aether/internal/impl/collect/DefaultDependencyCollectionContext -instanceKlass org/eclipse/aether/collection/DependencyCollectionContext -instanceKlass org/eclipse/aether/graph/DefaultDependencyNode -instanceKlass org/eclipse/aether/version/Version -instanceKlass org/eclipse/aether/internal/impl/collect/PremanagedDependency -instanceKlass org/eclipse/aether/internal/impl/collect/DataPool -instanceKlass org/eclipse/aether/internal/impl/collect/DefaultVersionFilterContext -instanceKlass org/eclipse/aether/collection/VersionFilter -instanceKlass org/eclipse/aether/collection/DependencyGraphTransformationContext -instanceKlass org/eclipse/aether/collection/VersionFilter$VersionFilterContext -instanceKlass org/eclipse/aether/spi/connector/Transfer -instanceKlass org/eclipse/aether/internal/impl/checksum/SummaryFileTrustedChecksumsSource$SummaryFileWriter -instanceKlass org/eclipse/aether/internal/impl/checksum/SparseDirectoryTrustedChecksumsSource$SparseDirectoryWriter -instanceKlass org/eclipse/aether/spi/checksums/TrustedChecksumsSource$Writer -instanceKlass org/eclipse/aether/spi/connector/checksum/ChecksumAlgorithm -instanceKlass org/eclipse/aether/impl/UpdateCheck -instanceKlass org/eclipse/aether/spi/connector/transport/Transporter -instanceKlass org/eclipse/aether/resolution/ArtifactDescriptorRequest -instanceKlass org/eclipse/aether/resolution/DependencyResult -instanceKlass org/eclipse/aether/resolution/DependencyRequest -instanceKlass org/eclipse/aether/resolution/VersionRangeResult -instanceKlass org/eclipse/aether/resolution/VersionRangeRequest -instanceKlass org/eclipse/aether/collection/CollectResult -instanceKlass org/eclipse/aether/collection/CollectRequest -instanceKlass org/eclipse/aether/resolution/VersionRequest -instanceKlass org/eclipse/aether/spi/connector/layout/RepositoryLayout -instanceKlass org/eclipse/aether/RepositoryEvent -instanceKlass org/eclipse/aether/repository/LocalRepository -instanceKlass org/eclipse/aether/internal/impl/LocalPathPrefixComposer -instanceKlass org/eclipse/aether/transform/FileTransformer -instanceKlass org/eclipse/aether/installation/InstallResult -instanceKlass org/eclipse/aether/installation/InstallRequest -instanceKlass org/eclipse/aether/spi/io/FileProcessor$ProgressListener -instanceKlass org/eclipse/aether/deployment/DeployResult -instanceKlass org/eclipse/aether/deployment/DeployRequest -instanceKlass org/eclipse/aether/internal/impl/DefaultDeployer$EventCatapult -instanceKlass org/eclipse/aether/repository/RepositoryPolicy -instanceKlass org/eclipse/aether/transfer/TransferResource -instanceKlass org/eclipse/aether/spi/connector/checksum/ChecksumPolicy -instanceKlass org/eclipse/aether/internal/impl/DefaultArtifactResolver$ResolutionGroup -instanceKlass org/eclipse/aether/resolution/VersionResult -instanceKlass org/eclipse/aether/repository/LocalArtifactResult -instanceKlass org/eclipse/aether/resolution/ArtifactResult -instanceKlass org/eclipse/aether/resolution/ArtifactRequest -instanceKlass org/eclipse/aether/SyncContext -instanceKlass org/eclipse/aether/spi/locator/ServiceLocator -instanceKlass org/eclipse/aether/repository/RemoteRepository -instanceKlass org/eclipse/aether/spi/connector/RepositoryConnector -instanceKlass org/apache/maven/model/validation/DefaultModelValidator$1ActivationFrame -instanceKlass org/apache/maven/model/profile/activation/JdkVersionProfileActivator$RangeValue -instanceKlass org/apache/maven/model/InputLocation -instanceKlass org/apache/maven/model/InputSource -instanceKlass org/apache/maven/model/interpolation/StringVisitorModelInterpolator$InnerInterpolator -instanceKlass org/apache/maven/model/ActivationOS -instanceKlass org/apache/maven/model/ActivationFile -instanceKlass org/apache/maven/model/Activation -instanceKlass org/apache/maven/model/ActivationProperty -instanceKlass org/codehaus/plexus/interpolation/RegexBasedInterpolator -instanceKlass org/apache/maven/model/profile/DefaultProfileActivationContext -instanceKlass org/apache/maven/model/building/ModelData -instanceKlass org/apache/maven/model/building/ModelBuildingEventCatapult -instanceKlass org/apache/maven/model/building/DefaultModelProblemCollector -instanceKlass org/apache/maven/model/building/ModelCacheTag -instanceKlass org/apache/maven/model/building/ModelBuildingEvent -instanceKlass org/apache/maven/model/building/ModelProblemCollectorExt -instanceKlass org/apache/maven/model/profile/ProfileActivationContext -instanceKlass org/apache/maven/cli/internal/extension/model/CoreExtension -instanceKlass org/apache/maven/building/ProblemCollector -instanceKlass org/apache/maven/toolchain/merge/MavenToolchainMerger -instanceKlass org/codehaus/plexus/interpolation/InterpolationPostProcessor -instanceKlass org/apache/maven/toolchain/building/ToolchainsBuildingResult -instanceKlass org/eclipse/aether/graph/Dependency -instanceKlass org/eclipse/aether/resolution/ArtifactDescriptorResult -instanceKlass org/apache/maven/plugin/internal/DefaultPluginValidationManager$PluginValidationIssues -instanceKlass com/google/inject/util/Types -instanceKlass org/eclipse/sisu/Nullable -instanceKlass org/eclipse/aether/repository/AuthenticationSelector -instanceKlass org/eclipse/aether/repository/ProxySelector -instanceKlass org/eclipse/aether/repository/MirrorSelector -instanceKlass org/eclipse/aether/resolution/ResolutionErrorPolicy -instanceKlass org/eclipse/aether/repository/LocalRepositoryManager -instanceKlass org/apache/maven/classrealm/ClassRealmManagerDelegate -instanceKlass org/apache/maven/classrealm/ClassRealmConstituent -instanceKlass org/apache/maven/classrealm/ClassRealmRequest -instanceKlass org/eclipse/aether/repository/WorkspaceRepository -instanceKlass org/apache/maven/ArtifactFilterManagerDelegate -instanceKlass org/apache/maven/plugin/internal/DefaultPluginManager -instanceKlass org/apache/maven/repository/ArtifactTransferListener -instanceKlass org/apache/maven/repository/legacy/LegacyRepositorySystem -instanceKlass org/eclipse/aether/util/graph/visitor/AbstractDepthFirstNodeListGenerator -instanceKlass org/apache/maven/plugin/descriptor/PluginDescriptorBuilder -instanceKlass org/apache/maven/plugin/logging/Log -instanceKlass org/codehaus/plexus/component/configurator/ConfigurationListener -instanceKlass org/apache/maven/plugin/internal/DefaultMavenPluginManager -instanceKlass org/apache/maven/artifact/resolver/DefaultResolutionErrorHandler -instanceKlass org/apache/maven/plugin/PluginDescriptorCache$PluginDescriptorSupplier -instanceKlass org/apache/maven/plugin/PluginDescriptorCache$Key -instanceKlass org/apache/maven/plugin/DefaultPluginDescriptorCache -instanceKlass org/apache/maven/execution/DefaultRuntimeInformation -instanceKlass org/apache/maven/repository/metadata/MetadataGraphVertex -instanceKlass org/apache/maven/repository/metadata/DefaultGraphConflictResolver -instanceKlass org/apache/maven/lifecycle/internal/builder/singlethreaded/SingleThreadedBuilder -instanceKlass org/apache/maven/configuration/BeanConfigurationRequest -instanceKlass org/codehaus/plexus/component/configurator/expression/ExpressionEvaluator -instanceKlass org/codehaus/plexus/configuration/PlexusConfiguration -instanceKlass org/codehaus/plexus/component/configurator/converters/lookup/ConverterLookup -instanceKlass org/apache/maven/configuration/internal/DefaultBeanConfigurator -instanceKlass org/apache/maven/repository/legacy/resolver/conflict/OldestConflictResolver -instanceKlass org/apache/maven/rtinfo/internal/DefaultRuntimeInformation -instanceKlass org/apache/maven/artifact/factory/DefaultArtifactFactory -instanceKlass org/apache/maven/repository/metadata/ClasspathContainer -instanceKlass org/apache/maven/repository/metadata/MetadataGraph -instanceKlass org/apache/maven/repository/metadata/DefaultClasspathTransformation -instanceKlass org/codehaus/plexus/component/repository/ComponentSetDescriptor -instanceKlass org/apache/maven/plugin/DefaultBuildPluginManager -instanceKlass org/apache/maven/plugin/PluginRealmCache$CacheRecord -instanceKlass org/apache/maven/plugin/PluginRealmCache$PluginRealmSupplier -instanceKlass org/apache/maven/plugin/PluginRealmCache$Key -instanceKlass org/apache/maven/plugin/DefaultPluginRealmCache -instanceKlass org/apache/maven/DefaultProjectDependenciesResolver -instanceKlass org/apache/maven/model/Reporting -instanceKlass org/apache/maven/model/PluginContainer -instanceKlass org/apache/maven/project/inheritance/DefaultModelInheritanceAssembler -instanceKlass org/apache/maven/repository/legacy/repository/DefaultArtifactRepositoryFactory -instanceKlass org/apache/maven/plugin/version/internal/DefaultPluginVersionResult -instanceKlass org/apache/maven/plugin/version/internal/DefaultPluginVersionResolver$Versions -instanceKlass org/apache/maven/plugin/version/internal/DefaultPluginVersionResolver$Key -instanceKlass org/apache/maven/plugin/version/PluginVersionResult -instanceKlass org/eclipse/aether/version/VersionScheme -instanceKlass org/apache/maven/plugin/version/internal/DefaultPluginVersionResolver -instanceKlass org/apache/maven/exception/ExceptionSummary -instanceKlass org/apache/maven/exception/DefaultExceptionHandler -instanceKlass org/apache/maven/project/validation/ModelValidationResult -instanceKlass org/apache/maven/project/validation/DefaultModelValidator -instanceKlass org/apache/maven/plugin/descriptor/Parameter -instanceKlass org/apache/maven/lifecycle/internal/DefaultMojoExecutionConfigurator -instanceKlass org/apache/maven/lifecycle/mapping/LifecyclePhase -instanceKlass org/apache/maven/lifecycle/internal/DefaultLifecyclePluginAnalyzer$GoalSpec -instanceKlass org/apache/maven/lifecycle/internal/DefaultLifecyclePluginAnalyzer -instanceKlass org/apache/maven/model/building/ModelProblem -instanceKlass org/apache/maven/project/artifact/MavenMetadataSource$ProjectRelocation -instanceKlass org/apache/maven/project/artifact/MavenMetadataSource -instanceKlass org/apache/maven/repository/legacy/resolver/conflict/NearestConflictResolver -instanceKlass org/apache/maven/repository/legacy/resolver/transform/DefaultArtifactTransformationManager -instanceKlass org/apache/maven/profiles/ProfileManager -instanceKlass org/apache/maven/project/DefaultMavenProjectBuilder -instanceKlass org/apache/maven/plugin/PluginArtifactsCache$CacheRecord -instanceKlass org/apache/maven/plugin/PluginArtifactsCache$Key -instanceKlass org/apache/maven/plugin/DefaultPluginArtifactsCache -instanceKlass org/apache/maven/artifact/repository/DefaultArtifactRepositoryFactory -instanceKlass org/sonatype/plexus/components/sec/dispatcher/PasswordDecryptor -instanceKlass sun/reflect/generics/tree/MethodTypeSignature -instanceKlass sun/reflect/generics/tree/VoidDescriptor -instanceKlass org/sonatype/plexus/components/sec/dispatcher/model/SettingsSecurity -instanceKlass org/eclipse/aether/graph/DependencyNode -instanceKlass org/eclipse/aether/collection/DependencySelector -instanceKlass org/eclipse/aether/artifact/Artifact -instanceKlass org/eclipse/aether/resolution/ArtifactDescriptorPolicy -instanceKlass org/apache/maven/plugin/internal/DefaultPluginDependenciesResolver -instanceKlass org/apache/maven/artifact/repository/layout/DefaultRepositoryLayout -instanceKlass org/apache/maven/toolchain/DefaultToolchain -instanceKlass org/apache/maven/toolchain/ToolchainPrivate -instanceKlass org/apache/maven/toolchain/java/JavaToolchain -instanceKlass org/apache/maven/toolchain/java/JavaToolchainFactory -instanceKlass org/apache/maven/toolchain/Toolchain -instanceKlass org/apache/maven/toolchain/DefaultToolchainManager -instanceKlass org/apache/maven/artifact/repository/layout/FlatRepositoryLayout -instanceKlass org/apache/maven/lifecycle/internal/builder/multithreaded/ConcurrencyDependencyGraph -instanceKlass org/apache/maven/lifecycle/internal/builder/multithreaded/ThreadOutputMuxer -instanceKlass org/apache/maven/lifecycle/internal/ProjectSegment -instanceKlass org/apache/maven/lifecycle/internal/ReactorBuildStatus -instanceKlass java/util/concurrent/CompletionService -instanceKlass org/apache/maven/lifecycle/internal/builder/multithreaded/MultiThreadedBuilder -instanceKlass org/apache/maven/settings/building/SettingsBuildingRequest -instanceKlass org/apache/maven/artifact/handler/DefaultArtifactHandler -instanceKlass org/apache/maven/project/ProjectRealmCache$Key -instanceKlass org/apache/maven/project/DefaultProjectRealmCache -instanceKlass org/apache/maven/project/artifact/DefaultMavenMetadataCache$CacheKey -instanceKlass org/apache/maven/repository/legacy/metadata/ResolutionGroup -instanceKlass org/apache/maven/project/artifact/DefaultMavenMetadataCache -instanceKlass org/apache/maven/artifact/resolver/DefaultArtifactResolver -instanceKlass org/apache/maven/lifecycle/internal/PhaseRecorder -instanceKlass org/apache/maven/lifecycle/internal/DependencyContext -instanceKlass org/apache/maven/lifecycle/internal/ProjectIndex -instanceKlass org/apache/maven/plugin/MojoExecutionRunner -instanceKlass org/apache/maven/plugin/internal/DefaultLegacySupport -instanceKlass org/apache/maven/repository/DefaultMirrorSelector -instanceKlass org/apache/maven/repository/legacy/resolver/conflict/FarthestConflictResolver -instanceKlass org/apache/maven/repository/metadata/MetadataGraphEdge -instanceKlass org/apache/maven/artifact/versioning/ArtifactVersion -instanceKlass org/apache/maven/repository/metadata/DefaultGraphConflictResolutionPolicy -instanceKlass org/apache/maven/project/ReactorModelPool -instanceKlass org/apache/maven/model/building/ModelBuildingResult -instanceKlass org/apache/maven/project/DefaultProjectBuilder$InternalConfig -instanceKlass org/apache/maven/model/resolution/ModelResolver -instanceKlass org/apache/maven/project/ProjectBuildingResult -instanceKlass org/apache/maven/model/building/ModelBuildingListener -instanceKlass org/apache/maven/model/building/ModelCache -instanceKlass org/apache/maven/project/DefaultProjectBuilder -instanceKlass org/apache/maven/project/ProjectBuilderConfiguration -instanceKlass org/apache/maven/artifact/resolver/ArtifactResolutionResult -instanceKlass org/apache/maven/artifact/resolver/ArtifactResolutionRequest -instanceKlass org/apache/maven/repository/legacy/metadata/MetadataResolutionRequest -instanceKlass org/apache/maven/repository/legacy/resolver/DefaultLegacyArtifactCollector -instanceKlass org/apache/maven/lifecycle/internal/DefaultLifecycleExecutionPlanCalculator -instanceKlass org/apache/maven/profiles/ProfilesRoot -instanceKlass org/apache/maven/artifact/repository/metadata/Metadata -instanceKlass org/apache/maven/artifact/repository/metadata/io/DefaultMetadataReader -instanceKlass org/apache/maven/execution/ProjectDependencyGraph -instanceKlass org/apache/maven/model/building/ModelSource -instanceKlass org/apache/maven/graph/DefaultGraphBuilder -instanceKlass org/apache/maven/repository/legacy/resolver/conflict/DefaultConflictResolverFactory -instanceKlass org/apache/maven/artifact/repository/Authentication -instanceKlass org/apache/maven/settings/TrackableBase -instanceKlass org/apache/maven/repository/Proxy -instanceKlass org/apache/maven/settings/RepositoryPolicy -instanceKlass org/apache/maven/model/RepositoryPolicy -instanceKlass org/apache/maven/artifact/versioning/VersionRange -instanceKlass org/apache/maven/settings/RepositoryBase -instanceKlass org/apache/maven/model/RepositoryBase -instanceKlass org/apache/maven/model/ConfigurationContainer -instanceKlass org/apache/maven/model/Dependency -instanceKlass org/apache/maven/artifact/repository/ArtifactRepositoryPolicy -instanceKlass org/apache/maven/artifact/resolver/filter/ArtifactFilter -instanceKlass org/apache/maven/project/artifact/ProjectArtifactsCache$CacheRecord -instanceKlass org/apache/maven/project/artifact/ProjectArtifactsCache$Key -instanceKlass org/apache/maven/project/artifact/DefaultProjectArtifactsCache -instanceKlass org/apache/maven/lifecycle/DefaultLifecycleExecutor -instanceKlass org/apache/maven/artifact/resolver/ResolutionNode -instanceKlass org/apache/maven/repository/legacy/resolver/conflict/NewestConflictResolver -instanceKlass org/apache/maven/lifecycle/internal/TaskSegment -instanceKlass org/apache/maven/lifecycle/internal/ReactorContext -instanceKlass org/apache/maven/execution/ProjectExecutionListener -instanceKlass org/apache/maven/execution/BuildSummary -instanceKlass org/apache/maven/lifecycle/internal/DefaultLifecycleMappingDelegate -instanceKlass org/apache/maven/plugin/ExtensionRealmCache$CacheRecord -instanceKlass org/apache/maven/plugin/ExtensionRealmCache$Key -instanceKlass org/apache/maven/plugin/DefaultExtensionRealmCache -instanceKlass org/apache/maven/lifecycle/internal/DefaultLifecycleTaskSegmentCalculator -instanceKlass org/apache/maven/project/DefaultDependencyResolutionResult -instanceKlass org/apache/maven/project/DependencyResolutionRequest -instanceKlass org/eclipse/aether/graph/DependencyVisitor -instanceKlass org/apache/maven/project/DependencyResolutionResult -instanceKlass org/apache/maven/project/DefaultProjectDependenciesResolver -instanceKlass org/apache/maven/toolchain/model/TrackableBase -instanceKlass org/apache/maven/toolchain/DefaultToolchainsBuilder -instanceKlass org/apache/maven/settings/crypto/SettingsDecryptionRequest -instanceKlass org/apache/maven/wagon/observers/ChecksumObserver -instanceKlass org/apache/maven/repository/legacy/DefaultWagonManager -instanceKlass org/eclipse/aether/RequestTrace -instanceKlass org/apache/maven/plugin/prefix/PluginPrefixRequest -instanceKlass org/eclipse/aether/metadata/Metadata -instanceKlass org/eclipse/aether/repository/ArtifactRepository -instanceKlass org/apache/maven/plugin/prefix/PluginPrefixResult -instanceKlass org/apache/maven/plugin/prefix/internal/DefaultPluginPrefixResolver -instanceKlass org/eclipse/aether/DefaultRepositorySystemSession -instanceKlass org/apache/maven/model/building/Result -instanceKlass org/eclipse/aether/RepositorySystemSession -instanceKlass org/apache/maven/execution/MavenExecutionResult -instanceKlass org/apache/maven/DefaultMaven -instanceKlass org/apache/maven/artifact/repository/metadata/Versioning -instanceKlass org/apache/maven/artifact/repository/ArtifactRepository -instanceKlass org/apache/maven/artifact/Artifact -instanceKlass org/apache/maven/artifact/repository/RepositoryRequest -instanceKlass org/apache/maven/artifact/repository/metadata/RepositoryMetadata -instanceKlass org/apache/maven/artifact/metadata/ArtifactMetadata -instanceKlass org/apache/maven/repository/legacy/metadata/ArtifactMetadata -instanceKlass org/codehaus/plexus/logging/AbstractLogEnabled -instanceKlass org/apache/maven/execution/ExecutionEvent -instanceKlass org/apache/maven/lifecycle/internal/DefaultExecutionEventCatapult -instanceKlass org/apache/maven/project/path/DefaultPathTranslator -instanceKlass org/apache/maven/plugin/version/PluginVersionRequest -instanceKlass org/eclipse/aether/RepositoryListener -instanceKlass org/apache/maven/lifecycle/internal/ProjectBuildList -instanceKlass org/apache/maven/lifecycle/MavenExecutionPlan -instanceKlass org/apache/maven/model/building/ModelProblemCollector -instanceKlass org/apache/maven/model/building/ModelBuildingRequest -instanceKlass org/apache/maven/model/merge/ModelMerger -instanceKlass org/apache/maven/model/plugin/DefaultLifecycleBindingsInjector -instanceKlass org/apache/maven/artifact/handler/manager/DefaultArtifactHandlerManager -instanceKlass org/apache/maven/project/ProjectRealmCache$CacheRecord -instanceKlass org/apache/maven/model/ModelBase -instanceKlass org/apache/maven/model/InputLocationTracker -instanceKlass org/eclipse/aether/graph/DependencyFilter -instanceKlass org/apache/maven/project/DefaultProjectBuildingHelper -instanceKlass org/apache/http/config/Registry -instanceKlass org/apache/http/impl/conn/PoolingHttpClientConnectionManager -instanceKlass org/apache/http/pool/ConnPoolControl -instanceKlass org/apache/http/client/methods/CloseableHttpResponse -instanceKlass org/apache/http/HttpResponse -instanceKlass org/apache/maven/wagon/shared/http/BasicAuthScope -instanceKlass org/apache/maven/wagon/shared/http/HttpConfiguration -instanceKlass org/apache/http/impl/client/CloseableHttpClient -instanceKlass org/apache/http/client/HttpClient -instanceKlass org/apache/http/auth/Credentials -instanceKlass org/apache/http/client/AuthCache -instanceKlass org/apache/http/client/CredentialsProvider -instanceKlass org/apache/http/Header -instanceKlass org/apache/http/NameValuePair -instanceKlass org/apache/http/client/RedirectStrategy -instanceKlass org/apache/http/config/Lookup -instanceKlass org/apache/http/client/HttpRequestRetryHandler -instanceKlass org/apache/http/conn/ssl/TrustStrategy -instanceKlass org/apache/http/ssl/TrustStrategy -instanceKlass org/apache/http/client/ServiceUnavailableRetryStrategy -instanceKlass org/apache/http/protocol/HttpContext -instanceKlass org/apache/http/client/methods/HttpUriRequest -instanceKlass org/apache/http/HttpRequest -instanceKlass org/apache/http/HttpMessage -instanceKlass org/apache/http/auth/AuthScheme -instanceKlass org/apache/http/HttpEntity -instanceKlass org/apache/http/conn/HttpClientConnectionManager -instanceKlass org/apache/maven/wagon/InputData -instanceKlass org/apache/maven/wagon/OutputData -instanceKlass java/util/EventObject -instanceKlass org/apache/maven/wagon/events/SessionListener -instanceKlass org/apache/maven/wagon/events/TransferListener -instanceKlass org/apache/maven/wagon/resource/Resource -instanceKlass org/apache/maven/wagon/repository/RepositoryPermissions -instanceKlass org/apache/maven/wagon/proxy/ProxyInfo -instanceKlass org/apache/maven/wagon/authentication/AuthenticationInfo -instanceKlass org/apache/maven/wagon/events/TransferEventSupport -instanceKlass org/apache/maven/wagon/events/SessionEventSupport -instanceKlass org/apache/maven/wagon/repository/Repository -instanceKlass org/apache/maven/wagon/proxy/ProxyInfoProvider -instanceKlass org/apache/maven/wagon/AbstractWagon -instanceKlass org/apache/maven/wagon/StreamingWagon -instanceKlass org/apache/maven/lifecycle/mapping/DefaultLifecycleMapping -instanceKlass org/eclipse/sisu/space/asm/Handler -instanceKlass org/eclipse/sisu/space/asm/Frame -instanceKlass org/eclipse/sisu/space/asm/ByteVector -instanceKlass org/eclipse/sisu/space/asm/Symbol -instanceKlass org/eclipse/sisu/space/asm/SymbolTable -instanceKlass org/eclipse/sisu/space/asm/RecordComponentVisitor -instanceKlass org/eclipse/sisu/space/asm/FieldVisitor -instanceKlass org/eclipse/sisu/space/asm/ModuleVisitor -instanceKlass org/eclipse/sisu/space/asm/MethodVisitor -instanceKlass com/google/inject/spi/ProviderWithExtensionVisitor -instanceKlass com/google/common/collect/Iterables -instanceKlass java/util/stream/ForEachOps$ForEachOp -instanceKlass java/util/stream/ForEachOps -instanceKlass com/google/inject/spi/InjectionPoint$$Lambda$71 -instanceKlass com/google/inject/spi/InjectionPoint$$Lambda$70 -instanceKlass com/google/inject/spi/InjectionPoint$$Lambda$69 -instanceKlass com/google/inject/spi/InjectionPoint$$Lambda$68 -instanceKlass org/eclipse/sisu/plexus/PlexusBean -instanceKlass org/codehaus/plexus/component/repository/ComponentDescriptor -instanceKlass com/google/inject/spi/ProvidesMethodBinding -instanceKlass org/eclipse/sisu/inject/Guice4 -instanceKlass com/google/inject/internal/GuiceInternal -instanceKlass org/sonatype/inject/Parameters -instanceKlass org/eclipse/sisu/plexus/PlexusXmlBeanConverter -instanceKlass org/eclipse/sisu/plexus/PlexusBeanConverter -instanceKlass com/google/inject/spi/TypeConverterBinding -instanceKlass java/lang/reflect/AnnotatedParameterizedType -instanceKlass sun/reflect/generics/tree/Wildcard -instanceKlass sun/reflect/generics/tree/BottomSignature -instanceKlass org/eclipse/sisu/inject/DefaultRankingFunction -instanceKlass com/google/inject/spi/ProvisionListenerBinding -instanceKlass com/google/inject/spi/TypeListenerBinding -instanceKlass org/eclipse/sisu/bean/BeanListener -instanceKlass com/google/inject/matcher/Matchers -instanceKlass org/eclipse/sisu/bean/PropertyBinder -instanceKlass org/eclipse/sisu/plexus/PlexusBeanBinder -instanceKlass com/google/inject/spi/InjectionListener -instanceKlass org/sonatype/plexus/components/sec/dispatcher/DefaultSecDispatcher -instanceKlass org/sonatype/plexus/components/cipher/DefaultPlexusCipher -instanceKlass org/sonatype/plexus/components/cipher/PlexusCipher -instanceKlass org/codehaus/plexus/component/configurator/AbstractComponentConfigurator -instanceKlass org/codehaus/plexus/component/configurator/ComponentConfigurator -instanceKlass org/apache/maven/settings/validation/DefaultSettingsValidator -instanceKlass org/apache/maven/settings/validation/SettingsValidator -instanceKlass org/apache/maven/settings/io/DefaultSettingsWriter -instanceKlass org/apache/maven/settings/io/SettingsWriter -instanceKlass org/apache/maven/settings/io/DefaultSettingsReader -instanceKlass org/apache/maven/settings/io/SettingsReader -instanceKlass org/apache/maven/settings/crypto/DefaultSettingsDecrypter -instanceKlass org/apache/maven/settings/crypto/SettingsDecrypter -instanceKlass org/apache/maven/settings/building/DefaultSettingsBuilder -instanceKlass org/apache/maven/settings/building/SettingsBuilder -instanceKlass org/eclipse/aether/transport/wagon/WagonTransporterFactory -instanceKlass org/eclipse/aether/internal/transport/wagon/PlexusWagonProvider -instanceKlass org/eclipse/aether/transport/wagon/WagonProvider -instanceKlass org/eclipse/aether/internal/transport/wagon/PlexusWagonConfigurator -instanceKlass org/eclipse/aether/transport/wagon/WagonConfigurator -instanceKlass org/eclipse/aether/transport/http/ChecksumExtractor -instanceKlass org/eclipse/aether/transport/http/HttpTransporterFactory -instanceKlass org/eclipse/aether/transport/file/FileTransporterFactory -instanceKlass org/eclipse/aether/spi/connector/transport/TransporterFactory -instanceKlass org/apache/maven/repository/internal/VersionsMetadataGeneratorFactory -instanceKlass org/apache/maven/repository/internal/SnapshotMetadataGeneratorFactory -instanceKlass org/apache/maven/repository/internal/PluginsMetadataGeneratorFactory -instanceKlass org/eclipse/aether/impl/MetadataGeneratorFactory -instanceKlass org/apache/maven/repository/internal/DefaultVersionResolver -instanceKlass org/eclipse/aether/impl/VersionResolver -instanceKlass org/apache/maven/repository/internal/DefaultVersionRangeResolver -instanceKlass org/eclipse/aether/impl/VersionRangeResolver -instanceKlass org/apache/maven/repository/internal/DefaultModelCacheFactory -instanceKlass org/apache/maven/repository/internal/ModelCacheFactory -instanceKlass org/apache/maven/repository/internal/DefaultArtifactDescriptorReader -instanceKlass org/eclipse/aether/impl/ArtifactDescriptorReader -instanceKlass org/eclipse/aether/named/support/NamedLockFactorySupport -instanceKlass org/eclipse/aether/named/NamedLockFactory -instanceKlass org/eclipse/aether/internal/impl/synccontext/named/providers/StaticNameMapperProvider -instanceKlass org/eclipse/aether/internal/impl/synccontext/named/providers/GAVNameMapperProvider -instanceKlass org/eclipse/aether/internal/impl/synccontext/named/providers/FileStaticNameMapperProvider -instanceKlass org/eclipse/aether/internal/impl/synccontext/named/providers/FileHashingGAVNameMapperProvider -instanceKlass org/eclipse/aether/internal/impl/synccontext/named/providers/FileGAVNameMapperProvider -instanceKlass org/eclipse/aether/internal/impl/synccontext/named/NameMapper -instanceKlass org/eclipse/aether/internal/impl/synccontext/named/providers/DiscriminatingNameMapperProvider -instanceKlass org/eclipse/aether/internal/impl/synccontext/named/NamedLockFactoryAdapterFactoryImpl -instanceKlass org/eclipse/aether/internal/impl/synccontext/named/NamedLockFactoryAdapterFactory -instanceKlass org/eclipse/aether/internal/impl/synccontext/legacy/DefaultSyncContextFactory -instanceKlass org/eclipse/aether/impl/SyncContextFactory -instanceKlass org/eclipse/aether/internal/impl/synccontext/DefaultSyncContextFactory -instanceKlass org/eclipse/aether/spi/synccontext/SyncContextFactory -instanceKlass java/lang/Deprecated -instanceKlass org/eclipse/aether/internal/impl/slf4j/Slf4jLoggerFactory -instanceKlass org/eclipse/aether/internal/impl/resolution/ArtifactResolverPostProcessorSupport -instanceKlass org/eclipse/aether/internal/impl/filter/RemoteRepositoryFilterSourceSupport -instanceKlass org/eclipse/aether/spi/connector/filter/RemoteRepositoryFilterSource -instanceKlass org/eclipse/aether/spi/resolution/ArtifactResolverPostProcessor -instanceKlass org/eclipse/aether/internal/impl/filter/DefaultRemoteRepositoryFilterManager -instanceKlass org/eclipse/aether/impl/RemoteRepositoryFilterManager -instanceKlass org/eclipse/aether/internal/impl/collect/DependencyCollectorDelegate -instanceKlass org/eclipse/aether/internal/impl/collect/DefaultDependencyCollector -instanceKlass org/eclipse/aether/impl/DependencyCollector -instanceKlass org/eclipse/aether/internal/impl/checksum/TrustedToProvidedChecksumsSourceAdapter -instanceKlass org/eclipse/aether/spi/checksums/ProvidedChecksumsSource -instanceKlass org/eclipse/aether/internal/impl/checksum/FileTrustedChecksumsSourceSupport -instanceKlass org/eclipse/aether/spi/checksums/TrustedChecksumsSource -instanceKlass org/eclipse/aether/spi/connector/checksum/ChecksumAlgorithmFactorySupport -instanceKlass org/eclipse/aether/spi/connector/checksum/ChecksumAlgorithmFactory -instanceKlass org/eclipse/aether/internal/impl/checksum/DefaultChecksumAlgorithmFactorySelector -instanceKlass org/eclipse/aether/spi/connector/checksum/ChecksumAlgorithmFactorySelector -instanceKlass org/eclipse/aether/internal/impl/SimpleLocalRepositoryManagerFactory -instanceKlass org/eclipse/aether/internal/impl/Maven2RepositoryLayoutFactory -instanceKlass org/eclipse/aether/spi/connector/layout/RepositoryLayoutFactory -instanceKlass org/eclipse/aether/spi/log/LoggerFactory -instanceKlass org/eclipse/aether/internal/impl/LoggerFactoryProvider -instanceKlass org/eclipse/aether/internal/impl/EnhancedLocalRepositoryManagerFactory -instanceKlass org/eclipse/aether/spi/localrepo/LocalRepositoryManagerFactory -instanceKlass org/eclipse/aether/internal/impl/DefaultUpdatePolicyAnalyzer -instanceKlass org/eclipse/aether/impl/UpdatePolicyAnalyzer -instanceKlass org/eclipse/aether/internal/impl/DefaultUpdateCheckManager -instanceKlass org/eclipse/aether/impl/UpdateCheckManager -instanceKlass java/lang/Long$LongCache -instanceKlass org/eclipse/aether/internal/impl/DefaultTransporterProvider -instanceKlass org/eclipse/aether/spi/connector/transport/TransporterProvider -instanceKlass org/eclipse/aether/internal/impl/DefaultTrackingFileManager -instanceKlass org/eclipse/aether/internal/impl/TrackingFileManager -instanceKlass org/eclipse/aether/internal/impl/DefaultRepositorySystemLifecycle -instanceKlass org/eclipse/aether/impl/RepositorySystemLifecycle -instanceKlass org/eclipse/aether/internal/impl/DefaultRepositorySystem -instanceKlass org/eclipse/aether/RepositorySystem -instanceKlass org/eclipse/aether/internal/impl/DefaultRepositoryLayoutProvider -instanceKlass org/eclipse/aether/spi/connector/layout/RepositoryLayoutProvider -instanceKlass org/eclipse/aether/internal/impl/DefaultRepositoryEventDispatcher -instanceKlass org/eclipse/aether/impl/RepositoryEventDispatcher -instanceKlass org/eclipse/aether/internal/impl/DefaultRepositoryConnectorProvider -instanceKlass org/eclipse/aether/impl/RepositoryConnectorProvider -instanceKlass org/eclipse/aether/internal/impl/DefaultRemoteRepositoryManager -instanceKlass org/eclipse/aether/impl/RemoteRepositoryManager -instanceKlass org/eclipse/aether/internal/impl/DefaultOfflineController -instanceKlass org/eclipse/aether/impl/OfflineController -instanceKlass org/eclipse/aether/internal/impl/DefaultMetadataResolver -instanceKlass org/eclipse/aether/impl/MetadataResolver -instanceKlass org/eclipse/aether/internal/impl/DefaultLocalRepositoryProvider -instanceKlass org/eclipse/aether/impl/LocalRepositoryProvider -instanceKlass org/eclipse/aether/internal/impl/LocalPathPrefixComposerFactorySupport -instanceKlass org/eclipse/aether/internal/impl/LocalPathPrefixComposerFactory -instanceKlass org/eclipse/aether/internal/impl/DefaultLocalPathComposer -instanceKlass org/eclipse/aether/internal/impl/LocalPathComposer -instanceKlass org/eclipse/aether/internal/impl/DefaultInstaller -instanceKlass org/eclipse/aether/impl/Installer -instanceKlass org/eclipse/aether/internal/impl/DefaultFileProcessor -instanceKlass org/eclipse/aether/spi/io/FileProcessor -instanceKlass org/eclipse/aether/internal/impl/DefaultDeployer -instanceKlass org/eclipse/aether/impl/Deployer -instanceKlass org/eclipse/aether/internal/impl/DefaultChecksumPolicyProvider -instanceKlass org/eclipse/aether/spi/connector/checksum/ChecksumPolicyProvider -instanceKlass org/eclipse/aether/internal/impl/DefaultArtifactResolver -instanceKlass org/eclipse/aether/impl/ArtifactResolver -instanceKlass org/eclipse/aether/connector/basic/BasicRepositoryConnectorFactory -instanceKlass org/eclipse/aether/spi/locator/Service -instanceKlass org/eclipse/aether/spi/connector/RepositoryConnectorFactory -instanceKlass org/apache/maven/model/validation/DefaultModelValidator -instanceKlass org/apache/maven/model/validation/ModelValidator -instanceKlass org/apache/maven/model/superpom/DefaultSuperPomProvider -instanceKlass org/apache/maven/model/superpom/SuperPomProvider -instanceKlass org/apache/maven/model/profile/activation/PropertyProfileActivator -instanceKlass org/apache/maven/model/profile/activation/OperatingSystemProfileActivator -instanceKlass org/apache/maven/model/profile/activation/JdkVersionProfileActivator -instanceKlass org/apache/maven/model/profile/activation/FileProfileActivator -instanceKlass org/apache/maven/model/profile/activation/ProfileActivator -instanceKlass org/apache/maven/model/profile/DefaultProfileSelector -instanceKlass org/apache/maven/model/profile/ProfileSelector -instanceKlass org/apache/maven/model/profile/DefaultProfileInjector -instanceKlass org/apache/maven/model/profile/ProfileInjector -instanceKlass org/apache/maven/model/plugin/DefaultReportingConverter -instanceKlass org/apache/maven/model/plugin/ReportingConverter -instanceKlass org/apache/maven/model/plugin/DefaultReportConfigurationExpander -instanceKlass org/apache/maven/model/plugin/ReportConfigurationExpander -instanceKlass org/apache/maven/model/plugin/DefaultPluginConfigurationExpander -instanceKlass org/apache/maven/model/plugin/PluginConfigurationExpander -instanceKlass org/apache/maven/model/path/ProfileActivationFilePathInterpolator -instanceKlass org/apache/maven/model/path/DefaultUrlNormalizer -instanceKlass org/apache/maven/model/path/UrlNormalizer -instanceKlass org/apache/maven/model/path/DefaultPathTranslator -instanceKlass org/apache/maven/model/path/PathTranslator -instanceKlass org/apache/maven/model/path/DefaultModelUrlNormalizer -instanceKlass org/apache/maven/model/path/ModelUrlNormalizer -instanceKlass org/apache/maven/model/path/DefaultModelPathTranslator -instanceKlass org/apache/maven/model/path/ModelPathTranslator -instanceKlass org/apache/maven/model/normalization/DefaultModelNormalizer -instanceKlass org/apache/maven/model/normalization/ModelNormalizer -instanceKlass org/apache/maven/model/management/DefaultPluginManagementInjector -instanceKlass org/apache/maven/model/management/PluginManagementInjector -instanceKlass org/apache/maven/model/management/DefaultDependencyManagementInjector -instanceKlass org/apache/maven/model/management/DependencyManagementInjector -instanceKlass org/apache/maven/model/locator/DefaultModelLocator -instanceKlass org/apache/maven/model/io/DefaultModelWriter -instanceKlass org/apache/maven/model/io/ModelWriter -instanceKlass org/apache/maven/model/io/DefaultModelReader -instanceKlass org/apache/maven/model/interpolation/AbstractStringBasedModelInterpolator -instanceKlass org/apache/maven/model/interpolation/ModelInterpolator -instanceKlass org/apache/maven/model/interpolation/DefaultModelVersionProcessor -instanceKlass org/apache/maven/model/interpolation/ModelVersionProcessor -instanceKlass org/apache/maven/model/inheritance/DefaultInheritanceAssembler -instanceKlass org/apache/maven/model/inheritance/InheritanceAssembler -instanceKlass org/apache/maven/model/composition/DefaultDependencyManagementImporter -instanceKlass org/apache/maven/model/composition/DependencyManagementImporter -instanceKlass sun/reflect/annotation/AnnotationParser$$Lambda$67 -instanceKlass org/apache/maven/model/building/DefaultModelProcessor -instanceKlass org/apache/maven/model/building/ModelProcessor -instanceKlass org/apache/maven/model/io/ModelReader -instanceKlass org/apache/maven/model/locator/ModelLocator -instanceKlass org/apache/maven/model/building/DefaultModelBuilder -instanceKlass org/apache/maven/model/building/ModelBuilder -instanceKlass org/apache/maven/cli/internal/BootstrapCoreExtensionManager -instanceKlass org/apache/maven/cli/configuration/SettingsXmlConfigurationProcessor -instanceKlass org/apache/maven/cli/configuration/ConfigurationProcessor -instanceKlass org/apache/maven/toolchain/io/DefaultToolchainsWriter -instanceKlass org/apache/maven/toolchain/io/ToolchainsWriter -instanceKlass org/apache/maven/toolchain/io/DefaultToolchainsReader -instanceKlass org/apache/maven/toolchain/io/ToolchainsReader -instanceKlass org/apache/maven/toolchain/building/DefaultToolchainsBuilder -instanceKlass org/apache/maven/toolchain/building/ToolchainsBuilder -instanceKlass java/lang/invoke/LambdaForm$Hidden -instanceKlass org/apache/maven/execution/MavenSession -instanceKlass org/apache/maven/session/scope/internal/SessionScope$ScopeState -instanceKlass org/apache/maven/session/scope/internal/SessionScope$$Lambda$66 -instanceKlass org/apache/maven/session/scope/internal/SessionScope -instanceKlass jdk/internal/reflect/ClassDefiner$1 -instanceKlass jdk/internal/reflect/ClassDefiner -instanceKlass jdk/internal/reflect/MethodAccessorGenerator$1 -instanceKlass jdk/internal/reflect/Label$PatchInfo -instanceKlass jdk/internal/reflect/Label -instanceKlass jdk/internal/reflect/UTF8 -instanceKlass jdk/internal/reflect/ClassFileAssembler -instanceKlass jdk/internal/reflect/ByteVectorImpl -instanceKlass jdk/internal/reflect/ByteVector -instanceKlass jdk/internal/reflect/ByteVectorFactory -instanceKlass jdk/internal/reflect/AccessorGenerator -instanceKlass jdk/internal/reflect/ClassFileConstants -instanceKlass org/apache/maven/plugin/internal/AbstractMavenPluginDependenciesValidator -instanceKlass org/apache/maven/plugin/internal/MavenPluginDependenciesValidator -instanceKlass org/apache/maven/plugin/internal/AbstractMavenPluginParametersValidator -instanceKlass org/apache/maven/plugin/internal/MavenPluginConfigurationValidator -instanceKlass org/apache/maven/eventspy/AbstractEventSpy -instanceKlass org/apache/maven/eventspy/EventSpy -instanceKlass org/apache/maven/plugin/PluginValidationManager -instanceKlass org/apache/maven/plugin/DefaultMojosExecutionStrategy -instanceKlass org/apache/maven/plugin/MojosExecutionStrategy -instanceKlass org/apache/maven/lifecycle/internal/LifecycleDependencyResolver -instanceKlass org/apache/maven/lifecycle/internal/DefaultProjectArtifactFactory -instanceKlass org/apache/maven/lifecycle/internal/ProjectArtifactFactory -instanceKlass org/apache/maven/internal/aether/ResolverLifecycle -instanceKlass org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactory -instanceKlass org/apache/maven/extension/internal/CoreExportsProvider -instanceKlass org/apache/maven/plugin/MojoExecution -instanceKlass org/apache/maven/project/MavenProject -instanceKlass org/apache/maven/execution/MojoExecutionEvent -instanceKlass org/apache/maven/execution/scope/internal/MojoExecutionScope$ScopeState -instanceKlass org/apache/maven/execution/scope/MojoExecutionScoped -instanceKlass com/google/inject/RestrictedBindingSource$Permit -instanceKlass org/apache/maven/execution/scope/internal/MojoExecutionScope$1 -instanceKlass org/apache/maven/execution/scope/internal/MojoExecutionScope -instanceKlass org/apache/maven/execution/MojoExecutionListener -instanceKlass org/eclipse/sisu/space/QualifiedTypeBinder$1 -instanceKlass org/apache/maven/execution/DefaultMavenExecutionRequestPopulator -instanceKlass org/apache/maven/execution/MavenExecutionRequestPopulator -instanceKlass org/apache/maven/classrealm/DefaultClassRealmManager -instanceKlass org/apache/maven/classrealm/ClassRealmManager -instanceKlass org/apache/maven/SessionScoped -instanceKlass org/apache/maven/ReactorReader -instanceKlass org/apache/maven/repository/internal/MavenWorkspaceReader -instanceKlass org/eclipse/aether/repository/WorkspaceReader -instanceKlass org/eclipse/sisu/space/WildcardKey$QualifiedImpl -instanceKlass org/eclipse/sisu/space/WildcardKey$Qualified -instanceKlass org/eclipse/sisu/space/WildcardKey -instanceKlass org/eclipse/sisu/Typed -instanceKlass org/sonatype/inject/EagerSingleton -instanceKlass org/eclipse/sisu/EagerSingleton -instanceKlass org/sonatype/inject/Mediator -instanceKlass org/eclipse/sisu/inject/TypeArguments -instanceKlass org/apache/maven/DefaultArtifactFilterManager -instanceKlass org/apache/maven/ArtifactFilterManager -instanceKlass org/eclipse/sisu/space/asm/Context -instanceKlass org/eclipse/sisu/space/asm/Attribute -instanceKlass org/eclipse/sisu/space/asm/AnnotationVisitor -instanceKlass org/eclipse/sisu/space/asm/ClassReader -instanceKlass org/eclipse/sisu/space/IndexedClassFinder$1 -instanceKlass org/eclipse/sisu/inject/Logs$SLF4JSink -instanceKlass org/eclipse/sisu/inject/Logs$Sink -instanceKlass org/eclipse/sisu/inject/Logs -instanceKlass org/eclipse/sisu/space/QualifierCache -instanceKlass org/eclipse/sisu/space/QualifiedTypeVisitor -instanceKlass org/eclipse/sisu/plexus/PlexusTypeVisitor$ComponentAnnotationVisitor -instanceKlass org/eclipse/sisu/space/AnnotationVisitor -instanceKlass org/eclipse/sisu/plexus/PlexusTypeVisitor -instanceKlass org/eclipse/sisu/space/ClassVisitor -instanceKlass org/eclipse/sisu/plexus/PlexusXmlBeanModule$PlexusXmlBeanSource -instanceKlass org/eclipse/sisu/inject/DescriptionSource -instanceKlass org/eclipse/sisu/inject/AnnotatedSource -instanceKlass org/eclipse/sisu/Description -instanceKlass org/eclipse/sisu/Hidden -instanceKlass org/eclipse/sisu/Priority -instanceKlass org/eclipse/sisu/inject/Sources -instanceKlass com/google/inject/internal/MoreTypes$ParameterizedTypeImpl -instanceKlass sun/reflect/generics/reflectiveObjects/ParameterizedTypeImpl -instanceKlass sun/reflect/generics/reflectiveObjects/LazyReflectiveObjectGenerator -instanceKlass com/google/inject/Key$AnnotationInstanceStrategy -instanceKlass com/google/inject/name/NamedImpl -instanceKlass com/google/inject/name/Named -instanceKlass com/google/inject/name/Names -instanceKlass org/apache/maven/wagon/Wagon -instanceKlass org/apache/maven/toolchain/ToolchainsBuilder -instanceKlass org/apache/maven/toolchain/ToolchainManagerPrivate -instanceKlass org/apache/maven/toolchain/ToolchainManager -instanceKlass org/apache/maven/toolchain/ToolchainFactory -instanceKlass org/apache/maven/settings/MavenSettingsBuilder -instanceKlass org/apache/maven/rtinfo/RuntimeInformation -instanceKlass org/apache/maven/project/artifact/ProjectArtifactsCache -instanceKlass org/apache/maven/project/artifact/MavenMetadataCache -instanceKlass org/apache/maven/project/ProjectRealmCache -instanceKlass org/apache/maven/project/ProjectDependenciesResolver -instanceKlass org/apache/maven/project/ProjectBuildingHelper -instanceKlass org/apache/maven/project/ProjectBuilder -instanceKlass org/apache/maven/project/MavenProjectHelper -instanceKlass org/apache/maven/plugin/version/PluginVersionResolver -instanceKlass org/apache/maven/plugin/prefix/PluginPrefixResolver -instanceKlass org/apache/maven/plugin/internal/PluginDependenciesResolver -instanceKlass org/apache/maven/plugin/PluginRealmCache -instanceKlass org/apache/maven/plugin/PluginManager -instanceKlass org/apache/maven/plugin/PluginDescriptorCache -instanceKlass org/apache/maven/plugin/PluginArtifactsCache -instanceKlass org/apache/maven/plugin/MavenPluginManager -instanceKlass org/apache/maven/plugin/LegacySupport -instanceKlass org/apache/maven/plugin/ExtensionRealmCache -instanceKlass org/apache/maven/plugin/BuildPluginManager -instanceKlass org/apache/maven/model/plugin/LifecycleBindingsInjector -instanceKlass org/apache/maven/lifecycle/internal/builder/BuilderCommon -instanceKlass org/apache/maven/lifecycle/internal/builder/Builder -instanceKlass org/apache/maven/lifecycle/internal/MojoExecutor -instanceKlass org/apache/maven/lifecycle/internal/MojoDescriptorCreator -instanceKlass org/apache/maven/lifecycle/internal/LifecycleTaskSegmentCalculator -instanceKlass org/apache/maven/lifecycle/internal/LifecycleStarter -instanceKlass org/apache/maven/lifecycle/internal/LifecyclePluginResolver -instanceKlass org/apache/maven/lifecycle/internal/LifecycleModuleBuilder -instanceKlass org/apache/maven/lifecycle/internal/LifecycleExecutionPlanCalculator -instanceKlass org/apache/maven/lifecycle/internal/LifecycleDebugLogger -instanceKlass org/apache/maven/lifecycle/internal/ExecutionEventCatapult -instanceKlass org/apache/maven/lifecycle/internal/BuildListCalculator -instanceKlass org/apache/maven/lifecycle/MojoExecutionConfigurator -instanceKlass org/apache/maven/lifecycle/LifecycleMappingDelegate -instanceKlass org/apache/maven/lifecycle/LifecycleExecutor -instanceKlass org/apache/maven/lifecycle/LifeCyclePluginAnalyzer -instanceKlass org/apache/maven/lifecycle/DefaultLifecycles -instanceKlass org/apache/maven/graph/GraphBuilder -instanceKlass org/apache/maven/eventspy/internal/EventSpyDispatcher -instanceKlass org/apache/maven/configuration/BeanConfigurator -instanceKlass org/apache/maven/bridge/MavenRepositorySystem -instanceKlass org/apache/maven/artifact/resolver/ResolutionErrorHandler -instanceKlass org/apache/maven/artifact/repository/metadata/io/MetadataReader -instanceKlass org/apache/maven/artifact/metadata/ArtifactMetadataSource -instanceKlass org/apache/maven/repository/legacy/metadata/ArtifactMetadataSource -instanceKlass org/apache/maven/artifact/handler/manager/ArtifactHandlerManager -instanceKlass org/apache/maven/artifact/factory/ArtifactFactory -instanceKlass org/apache/maven/ProjectDependenciesResolver -instanceKlass org/apache/maven/Maven -instanceKlass org/apache/maven/artifact/handler/ArtifactHandler -instanceKlass org/sonatype/plexus/components/sec/dispatcher/SecDispatcher -instanceKlass org/apache/maven/lifecycle/Lifecycle -instanceKlass org/eclipse/sisu/space/CloningClassSpace$1 -instanceKlass org/apache/maven/lifecycle/mapping/LifecycleMapping -instanceKlass org/apache/maven/repository/metadata/GraphConflictResolver -instanceKlass org/apache/maven/repository/metadata/GraphConflictResolutionPolicy -instanceKlass org/eclipse/sisu/plexus/ConfigurationImpl -instanceKlass org/apache/maven/repository/metadata/ClasspathTransformation -instanceKlass org/apache/maven/repository/legacy/resolver/transform/ArtifactTransformationManager -instanceKlass org/apache/maven/repository/legacy/resolver/transform/ArtifactTransformation -instanceKlass org/apache/maven/repository/legacy/resolver/conflict/ConflictResolverFactory -instanceKlass org/apache/maven/repository/legacy/resolver/conflict/ConflictResolver -instanceKlass org/apache/maven/repository/legacy/repository/ArtifactRepositoryFactory -instanceKlass org/apache/maven/repository/legacy/UpdateCheckManager -instanceKlass org/apache/maven/repository/RepositorySystem -instanceKlass org/apache/maven/repository/MirrorSelector -instanceKlass org/apache/maven/project/validation/ModelValidator -instanceKlass org/apache/maven/project/path/PathTranslator -instanceKlass org/apache/maven/project/interpolation/ModelInterpolator -instanceKlass org/apache/maven/project/inheritance/ModelInheritanceAssembler -instanceKlass org/apache/maven/project/MavenProjectBuilder -instanceKlass org/apache/maven/profiles/MavenProfilesBuilder -instanceKlass org/apache/maven/execution/RuntimeInformation -instanceKlass org/apache/maven/artifact/resolver/ArtifactResolver -instanceKlass org/apache/maven/artifact/resolver/ArtifactCollector -instanceKlass org/apache/maven/repository/legacy/resolver/LegacyArtifactCollector -instanceKlass org/apache/maven/artifact/repository/metadata/RepositoryMetadataManager -instanceKlass org/apache/maven/artifact/repository/layout/ArtifactRepositoryLayout -instanceKlass org/apache/maven/artifact/repository/ArtifactRepositoryFactory -instanceKlass org/apache/maven/artifact/manager/WagonManager -instanceKlass org/apache/maven/repository/legacy/WagonManager -instanceKlass org/apache/maven/artifact/installer/ArtifactInstaller -instanceKlass org/eclipse/sisu/plexus/PlexusXmlMetadata -instanceKlass org/eclipse/sisu/plexus/Roles -instanceKlass org/apache/maven/artifact/deployer/ArtifactDeployer -instanceKlass org/eclipse/sisu/plexus/Hints -instanceKlass org/eclipse/sisu/space/AbstractDeferredClass -instanceKlass org/eclipse/sisu/plexus/RequirementImpl -instanceKlass org/codehaus/plexus/component/annotations/Requirement -instanceKlass org/eclipse/sisu/space/Streams -instanceKlass org/eclipse/sisu/plexus/ComponentImpl -instanceKlass org/codehaus/plexus/component/annotations/Component -instanceKlass org/eclipse/sisu/plexus/PlexusTypeRegistry -instanceKlass org/eclipse/sisu/plexus/PlexusXmlScanner -instanceKlass org/eclipse/sisu/space/QualifiedTypeBinder -instanceKlass org/eclipse/sisu/plexus/PlexusTypeBinder -instanceKlass com/google/inject/spi/InjectionRequest -instanceKlass org/eclipse/sisu/bean/BeanProperty -instanceKlass com/google/common/collect/ObjectArrays -instanceKlass com/google/inject/internal/Nullability -instanceKlass com/google/inject/internal/KotlinSupport$KotlinUnsupported$$Lambda$65 -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass com/google/inject/internal/KotlinSupport$KotlinUnsupported -instanceKlass com/google/inject/internal/KotlinSupport$KotlinSupportHolder -instanceKlass com/google/inject/internal/KotlinSupportInterface -instanceKlass com/google/inject/internal/KotlinSupport -instanceKlass com/google/inject/spi/InjectionPoint$OverrideIndex -instanceKlass org/eclipse/sisu/inject/RankedBindings -instanceKlass org/eclipse/sisu/Mediator -instanceKlass sun/reflect/generics/tree/TypeVariableSignature -instanceKlass com/google/inject/Inject -instanceKlass javax/inject/Inject -instanceKlass com/google/inject/internal/DeclaredMembers$$Lambda$64 -instanceKlass com/google/inject/internal/DeclaredMembers$$Lambda$63 -instanceKlass com/google/inject/internal/DeclaredMembers$$Lambda$62 -instanceKlass com/google/inject/internal/DeclaredMembers$$Lambda$61 -instanceKlass java/lang/reflect/WildcardType -instanceKlass java/lang/reflect/TypeVariable -instanceKlass com/google/inject/spi/InjectionPoint$InjectableMembers -instanceKlass com/google/inject/spi/InjectionPoint$InjectableMember -instanceKlass com/google/inject/spi/InjectionPoint -instanceKlass java/lang/reflect/ParameterizedType -instanceKlass com/google/inject/internal/MoreTypes$GenericArrayTypeImpl -instanceKlass com/google/inject/internal/MoreTypes$CompositeType -instanceKlass com/google/inject/Key$AnnotationTypeStrategy -instanceKlass com/google/common/cache/LocalCache$StrongValueReference -instanceKlass com/google/common/util/concurrent/AbstractFuture$Failure -instanceKlass com/google/common/util/concurrent/AbstractFuture$Cancellation -instanceKlass com/google/common/util/concurrent/AbstractFuture$SetFuture -instanceKlass com/google/common/util/concurrent/Uninterruptibles -instanceKlass com/google/common/util/concurrent/AbstractFuture$Waiter -instanceKlass com/google/common/util/concurrent/AbstractFuture$Listener -instanceKlass jdk/internal/reflect/UnsafeFieldAccessorFactory -instanceKlass java/lang/reflect/AccessibleObject$$Lambda$60 -instanceKlass com/google/common/util/concurrent/AbstractFuture$UnsafeAtomicHelper$1 -instanceKlass sun/misc/Unsafe -instanceKlass com/google/common/util/concurrent/LazyLogger -instanceKlass java/util/concurrent/Executor -instanceKlass com/google/common/util/concurrent/AbstractFuture$AtomicHelper -instanceKlass com/google/common/util/concurrent/internal/InternalFutureFailureAccess -instanceKlass com/google/common/util/concurrent/AbstractFuture$Trusted -instanceKlass com/google/common/util/concurrent/ListenableFuture -instanceKlass sun/reflect/annotation/AnnotationParser$$Lambda$59 -instanceKlass java/lang/annotation/Documented -instanceKlass java/lang/annotation/Target -instanceKlass javax/inject/Named -instanceKlass javax/inject/Qualifier -instanceKlass com/google/inject/BindingAnnotation -instanceKlass javax/inject/Scope -instanceKlass com/google/inject/ScopeAnnotation -instanceKlass com/google/inject/internal/Annotations$AnnotationChecker -instanceKlass java/lang/reflect/Proxy$ProxyBuilder$1 -instanceKlass java/lang/reflect/ProxyGenerator$ExceptionTableEntry -instanceKlass java/lang/reflect/ProxyGenerator$PrimitiveTypeInfo -instanceKlass java/lang/reflect/ProxyGenerator$FieldInfo -instanceKlass java/lang/reflect/ProxyGenerator$ConstantPool$Entry -instanceKlass java/lang/reflect/ProxyGenerator$MethodInfo -instanceKlass java/lang/reflect/ProxyGenerator$ProxyMethod -instanceKlass java/lang/reflect/ProxyGenerator$ConstantPool -instanceKlass java/lang/reflect/ProxyGenerator -instanceKlass java/lang/reflect/Proxy$$Lambda$58 -instanceKlass java/lang/PublicMethods -instanceKlass java/util/Collections$1 -instanceKlass java/lang/reflect/Proxy$ProxyBuilder -instanceKlass java/lang/reflect/Proxy$$Lambda$57 -instanceKlass java/lang/reflect/Proxy -instanceKlass sun/reflect/annotation/AnnotationInvocationHandler -instanceKlass sun/reflect/annotation/AnnotationParser$1 -instanceKlass sun/reflect/annotation/ExceptionProxy -instanceKlass java/lang/annotation/Inherited -instanceKlass java/lang/annotation/Retention -instanceKlass sun/reflect/annotation/AnnotationType$1 -instanceKlass sun/reflect/annotation/AnnotationType -instanceKlass java/lang/reflect/GenericArrayType -instanceKlass sun/reflect/generics/visitor/Reifier -instanceKlass sun/reflect/generics/visitor/TypeTreeVisitor -instanceKlass sun/reflect/generics/factory/CoreReflectionFactory -instanceKlass sun/reflect/generics/factory/GenericsFactory -instanceKlass sun/reflect/generics/scope/AbstractScope -instanceKlass sun/reflect/generics/scope/Scope -instanceKlass com/google/inject/internal/Annotations$TestAnnotation -instanceKlass com/google/inject/internal/Annotations$AnnotationToStringConfig -instanceKlass com/google/common/base/Joiner$MapJoiner -instanceKlass com/google/common/base/Joiner -instanceKlass java/lang/reflect/InvocationHandler -instanceKlass com/google/inject/internal/Annotations -instanceKlass org/eclipse/sisu/Parameters -instanceKlass org/eclipse/sisu/wire/ParameterKeys -instanceKlass com/google/inject/internal/util/StackTraceElements$InMemoryStackTraceElement -instanceKlass com/google/inject/internal/util/StackTraceElements -instanceKlass org/eclipse/sisu/wire/TypeConverterCache -instanceKlass com/google/inject/internal/Scoping -instanceKlass com/google/inject/internal/InternalFactory -instanceKlass java/lang/StackTraceElement$HashedModules -instanceKlass com/google/inject/internal/InternalFlags$1 -instanceKlass com/google/inject/internal/InternalFlags -instanceKlass com/google/inject/spi/ConstructorBinding -instanceKlass com/google/inject/internal/DelayedInitialize -instanceKlass com/google/inject/spi/ProviderKeyBinding -instanceKlass com/google/inject/spi/ProviderInstanceBinding -instanceKlass com/google/inject/spi/InstanceBinding -instanceKlass com/google/inject/spi/HasDependencies -instanceKlass com/google/inject/spi/LinkedKeyBinding -instanceKlass com/google/inject/spi/UntargettedBinding -instanceKlass com/google/inject/internal/BindingImpl -instanceKlass com/google/inject/Key$AnnotationStrategy -instanceKlass org/eclipse/sisu/wire/ElementAnalyzer$1 -instanceKlass com/google/inject/util/Modules$EmptyModule -instanceKlass com/google/inject/util/Modules$OverriddenModuleBuilder -instanceKlass com/google/inject/util/Modules -instanceKlass java/util/stream/Nodes$ArrayNode -instanceKlass java/util/stream/Node$Builder -instanceKlass java/util/stream/Node$OfDouble -instanceKlass java/util/stream/Node$OfLong -instanceKlass java/util/stream/Node$OfInt -instanceKlass java/util/stream/Node$OfPrimitive -instanceKlass java/util/stream/Nodes$EmptyNode -instanceKlass java/util/stream/Node -instanceKlass java/util/stream/Nodes -instanceKlass com/google/inject/internal/DeclaredMembers$$Lambda$56 -instanceKlass java/util/function/IntFunction -instanceKlass java/util/stream/SortedOps -instanceKlass com/google/common/collect/Ordering -instanceKlass com/google/inject/internal/DeclaredMembers$$Lambda$55 -instanceKlass com/google/inject/internal/DeclaredMembers$$Lambda$54 -instanceKlass java/util/Comparator$$Lambda$53 -instanceKlass java/util/Comparator$$Lambda$52 -instanceKlass com/google/inject/internal/DeclaredMembers$$Lambda$51 -instanceKlass com/google/inject/internal/DeclaredMembers$$Lambda$50 -instanceKlass java/util/Comparator$$Lambda$49 -instanceKlass com/google/inject/internal/DeclaredMembers$$Lambda$48 -instanceKlass com/google/inject/internal/DeclaredMembers -instanceKlass com/google/common/base/ExtraObjectsMethodsForWeb -instanceKlass com/google/common/collect/ImmutableMap$Builder -instanceKlass com/google/inject/internal/MoreTypes -instanceKlass com/google/inject/multibindings/ProvidesIntoOptional -instanceKlass com/google/inject/multibindings/ProvidesIntoMap -instanceKlass com/google/inject/multibindings/ProvidesIntoSet -instanceKlass com/google/inject/Provides -instanceKlass javax/inject/Singleton -instanceKlass com/google/inject/spi/ElementSource -instanceKlass com/google/inject/spi/ScopeBinding -instanceKlass com/google/inject/Scopes$2 -instanceKlass com/google/inject/Scopes$1 -instanceKlass com/google/inject/internal/SingletonScope -instanceKlass com/google/inject/Scopes -instanceKlass com/google/inject/Singleton -instanceKlass com/google/inject/spi/Elements$ModuleInfo -instanceKlass com/google/inject/PrivateModule -instanceKlass java/util/stream/Collectors$$Lambda$47 -instanceKlass java/util/stream/Collectors$$Lambda$46 -instanceKlass java/util/stream/Collectors$$Lambda$45 -instanceKlass com/google/inject/spi/BindingSourceRestriction$PermitMapConstruction$$Lambda$44 -instanceKlass com/google/inject/spi/BindingSourceRestriction$$Lambda$43 -instanceKlass com/google/inject/spi/BindingSourceRestriction$$Lambda$42 -instanceKlass java/util/stream/Streams$2 -instanceKlass java/util/stream/Streams$ConcatSpliterator -instanceKlass sun/reflect/annotation/AnnotatedTypeFactory$AnnotatedTypeBaseImpl -instanceKlass java/lang/reflect/AnnotatedType -instanceKlass sun/reflect/annotation/AnnotatedTypeFactory -instanceKlass sun/reflect/annotation/TypeAnnotation$LocationInfo$Location -instanceKlass sun/reflect/annotation/TypeAnnotation$LocationInfo -instanceKlass sun/reflect/generics/tree/ClassSignature -instanceKlass sun/reflect/generics/tree/Signature -instanceKlass sun/reflect/generics/tree/ClassTypeSignature -instanceKlass sun/reflect/generics/tree/SimpleClassTypeSignature -instanceKlass sun/reflect/generics/tree/FieldTypeSignature -instanceKlass sun/reflect/generics/tree/BaseType -instanceKlass sun/reflect/generics/tree/TypeSignature -instanceKlass sun/reflect/generics/tree/ReturnType -instanceKlass sun/reflect/generics/tree/TypeArgument -instanceKlass sun/reflect/generics/tree/FormalTypeParameter -instanceKlass sun/reflect/generics/tree/TypeTree -instanceKlass sun/reflect/generics/tree/Tree -instanceKlass sun/reflect/generics/parser/SignatureParser -instanceKlass sun/reflect/generics/repository/AbstractRepository -instanceKlass sun/reflect/annotation/TypeAnnotation -instanceKlass sun/reflect/annotation/TypeAnnotationParser -instanceKlass java/lang/Class$AnnotationData -instanceKlass com/google/inject/RestrictedBindingSource -instanceKlass com/google/inject/spi/BindingSourceRestriction -instanceKlass com/google/inject/spi/ModuleSource -instanceKlass com/google/inject/internal/ProviderMethodsModule -instanceKlass com/google/inject/spi/BindingSourceRestriction$PermitMapConstruction$PermitMapImpl -instanceKlass com/google/inject/spi/BindingSourceRestriction$PermitMap -instanceKlass com/google/inject/spi/BindingSourceRestriction$PermitMapConstruction -instanceKlass com/google/common/collect/Hashing -instanceKlass com/google/common/math/IntMath$1 -instanceKlass com/google/common/math/MathPreconditions -instanceKlass com/google/common/math/IntMath -instanceKlass com/google/inject/internal/AbstractBindingBuilder -instanceKlass com/google/inject/binder/ConstantBindingBuilder -instanceKlass com/google/inject/binder/AnnotatedElementBuilder -instanceKlass com/google/inject/spi/Elements$RecordingBinder -instanceKlass com/google/inject/Binding -instanceKlass com/google/inject/spi/DefaultBindingTargetVisitor -instanceKlass com/google/inject/spi/BindingTargetVisitor -instanceKlass com/google/inject/spi/Elements -instanceKlass com/google/inject/internal/InjectorShell$RootModule -instanceKlass com/google/common/collect/ListMultimap -instanceKlass com/google/inject/internal/InjectorBindingData -instanceKlass java/util/concurrent/atomic/AtomicReferenceArray -instanceKlass java/util/concurrent/Future -instanceKlass com/google/common/cache/LocalCache$LoadingValueReference -instanceKlass java/util/concurrent/ConcurrentLinkedQueue$Node -instanceKlass com/google/common/cache/Weigher -instanceKlass com/google/common/base/Predicate -instanceKlass com/google/common/base/Equivalence -instanceKlass java/util/function/BiPredicate -instanceKlass com/google/common/base/MoreObjects -instanceKlass com/google/common/cache/LocalCache$1 -instanceKlass com/google/common/cache/ReferenceEntry -instanceKlass com/google/common/cache/CacheLoader -instanceKlass com/google/common/cache/LocalCache$LocalManualCache -instanceKlass com/google/inject/internal/WeakKeySet$$Lambda$41 -instanceKlass com/google/common/cache/RemovalListener -instanceKlass java/util/AbstractMap$SimpleImmutableEntry -instanceKlass com/google/common/cache/LocalCache$ValueReference -instanceKlass com/google/common/cache/CacheBuilder$2 -instanceKlass com/google/common/cache/CacheStats -instanceKlass com/google/common/base/Suppliers$SupplierOfInstance -instanceKlass com/google/common/base/Suppliers -instanceKlass com/google/common/cache/CacheBuilder$1 -instanceKlass com/google/common/cache/AbstractCache$StatsCounter -instanceKlass com/google/common/cache/LoadingCache -instanceKlass com/google/common/cache/Cache -instanceKlass com/google/common/base/Supplier -instanceKlass com/google/common/cache/CacheBuilder -instanceKlass com/google/inject/internal/WeakKeySet -instanceKlass com/google/common/collect/Sets -instanceKlass com/google/inject/internal/InjectorJitBindingData -instanceKlass com/google/inject/internal/ProcessedBindingData -instanceKlass com/google/inject/spi/DefaultElementVisitor -instanceKlass com/google/inject/internal/InjectorShell$Builder -instanceKlass com/google/common/collect/Lists -instanceKlass com/google/common/collect/AbstractMapEntry -instanceKlass com/google/common/collect/LinkedHashMultimap$ValueSetLink -instanceKlass com/google/common/collect/CollectPreconditions -instanceKlass java/lang/StrictMath -instanceKlass com/google/common/collect/Platform -instanceKlass com/google/common/collect/Multiset -instanceKlass com/google/common/collect/AbstractMultimap -instanceKlass com/google/common/collect/SetMultimap -instanceKlass com/google/common/collect/Maps$EntryTransformer -instanceKlass com/google/common/collect/BiMap -instanceKlass com/google/common/base/Converter -instanceKlass com/google/common/base/Function -instanceKlass com/google/common/collect/ImmutableMap -instanceKlass com/google/common/collect/SortedMapDifference -instanceKlass com/google/common/collect/MapDifference -instanceKlass com/google/common/collect/Maps -instanceKlass com/google/inject/internal/CycleDetectingLock -instanceKlass com/google/common/collect/Multimap -instanceKlass com/google/inject/internal/CycleDetectingLock$CycleDetectingLockFactory -instanceKlass com/google/inject/internal/Initializable -instanceKlass com/google/inject/internal/Initializer -instanceKlass com/google/common/collect/PeekingIterator -instanceKlass com/google/common/collect/UnmodifiableIterator -instanceKlass com/google/common/collect/Iterators -instanceKlass com/google/common/collect/ImmutableCollection$Builder -instanceKlass com/google/common/collect/ImmutableSet$SetBuilderImpl -instanceKlass com/google/inject/internal/util/SourceProvider -instanceKlass com/google/inject/spi/ErrorDetail -instanceKlass com/google/inject/internal/Errors -instanceKlass com/google/common/base/Preconditions -instanceKlass java/time/Duration -instanceKlass java/time/temporal/TemporalAmount -instanceKlass java/time/temporal/TemporalUnit -instanceKlass java/util/concurrent/TimeUnit$1 -instanceKlass jdk/internal/logger/DefaultLoggerFinder$1 -instanceKlass java/util/logging/Logger$SystemLoggerHelper$1 -instanceKlass java/util/logging/Logger$SystemLoggerHelper -instanceKlass java/util/logging/LogManager$4 -instanceKlass jdk/internal/logger/BootstrapLogger$BootstrapExecutors -instanceKlass jdk/internal/logger/BootstrapLogger$RedirectedLoggers -instanceKlass java/lang/ModuleLayer$$Lambda$40 -instanceKlass java/lang/WeakPairMap$Pair$Lookup -instanceKlass java/lang/WeakPairMap$Pair -instanceKlass java/lang/WeakPairMap -instanceKlass java/lang/Module$ReflectionData -instanceKlass java/util/Spliterators$1Adapter -instanceKlass java/util/Spliterators$ArraySpliterator -instanceKlass java/util/Spliterator$OfDouble -instanceKlass java/util/Spliterator$OfLong -instanceKlass java/util/Spliterator$OfInt -instanceKlass java/util/Spliterator$OfPrimitive -instanceKlass java/util/Spliterators$EmptySpliterator -instanceKlass java/util/Spliterators -instanceKlass jdk/internal/logger/BootstrapLogger$DetectBackend$1 -instanceKlass jdk/internal/logger/BootstrapLogger$DetectBackend -instanceKlass jdk/internal/logger/BootstrapLogger -instanceKlass sun/util/logging/PlatformLogger$ConfigurableBridge -instanceKlass sun/util/logging/PlatformLogger$Bridge -instanceKlass java/lang/System$Logger -instanceKlass java/util/stream/Streams -instanceKlass java/util/stream/Streams$AbstractStreamBuilderImpl -instanceKlass java/util/stream/Stream$Builder -instanceKlass java/util/stream/Sink$ChainedReference -instanceKlass java/util/stream/FindOps$FindSink$OfRef$$Lambda$39 -instanceKlass java/util/stream/FindOps$FindSink$OfRef$$Lambda$38 -instanceKlass java/util/stream/FindOps$FindSink$OfRef$$Lambda$37 -instanceKlass java/util/stream/FindOps$FindSink$OfRef$$Lambda$36 -instanceKlass java/util/stream/FindOps$FindOp -instanceKlass java/util/stream/FindOps$FindSink -instanceKlass java/util/stream/FindOps -instanceKlass java/util/logging/Level$KnownLevel$$Lambda$35 -instanceKlass java/util/ArrayList$ArrayListSpliterator -instanceKlass java/util/logging/Level$$Lambda$34 -instanceKlass java/util/Hashtable$Enumerator -instanceKlass java/util/logging/LogManager$LoggerContext$1 -instanceKlass java/util/logging/LogManager$VisitedLoggers -instanceKlass java/util/function/Predicate -instanceKlass java/lang/invoke/LambdaForm$MH -instanceKlass java/lang/invoke/LambdaForm$MH -instanceKlass sun/invoke/util/ValueConversions$WrapperCache -instanceKlass java/lang/invoke/LambdaForm$MH -instanceKlass java/lang/invoke/MethodHandles$1 -instanceKlass java/lang/Byte$ByteCache -instanceKlass java/lang/invoke/LambdaForm$MH -instanceKlass java/lang/invoke/LambdaForm$MH -instanceKlass java/lang/invoke/LambdaForm$MH -instanceKlass java/lang/invoke/LambdaForm$MH -instanceKlass java/lang/invoke/LambdaForm$MH -instanceKlass java/lang/invoke/LambdaForm$MH -instanceKlass java/lang/invoke/LambdaForm$MH -instanceKlass java/lang/invoke/LambdaForm$MH -instanceKlass java/lang/invoke/LambdaForm$MH -instanceKlass java/lang/invoke/LambdaForm$MH -instanceKlass java/lang/ClassValue$Version -instanceKlass java/lang/ClassValue$Identity -instanceKlass java/lang/ClassValue -instanceKlass java/lang/invoke/StringConcatFactory$Stringifiers -instanceKlass java/lang/StringConcatHelper -instanceKlass java/lang/invoke/StringConcatFactory$MethodHandleInlineCopyStrategy$3 -instanceKlass java/lang/invoke/StringConcatFactory$MethodHandleInlineCopyStrategy$2 -instanceKlass java/lang/invoke/StringConcatFactory$MethodHandleInlineCopyStrategy$1 -instanceKlass java/lang/invoke/StringConcatFactory$MethodHandleInlineCopyStrategy -instanceKlass java/lang/invoke/StringConcatFactory$RecipeElement -instanceKlass java/lang/invoke/StringConcatFactory$Recipe -instanceKlass java/lang/invoke/StringConcatFactory$1 -instanceKlass java/lang/invoke/StringConcatFactory -instanceKlass java/util/logging/LogManager$2 -instanceKlass java/lang/System$LoggerFinder -instanceKlass sun/security/util/SecurityConstants -instanceKlass java/security/AccessController$1 -instanceKlass java/util/logging/LogManager$LoggingProviderAccess -instanceKlass sun/util/logging/internal/LoggingProviderImpl$LogManagerAccess -instanceKlass java/util/Collections$SynchronizedMap -instanceKlass java/util/logging/LogManager$LogNode -instanceKlass java/util/logging/LogManager$LoggerContext -instanceKlass java/util/logging/LogManager$1 -instanceKlass java/util/logging/LogManager -instanceKlass java/util/logging/Logger$ConfigurationData -instanceKlass java/util/logging/Logger$LoggerBundle -instanceKlass java/util/logging/Level -instanceKlass java/util/logging/Handler -instanceKlass java/util/logging/Logger -instanceKlass com/google/common/base/Ticker -instanceKlass com/google/common/base/Stopwatch -instanceKlass com/google/inject/internal/util/ContinuousStopwatch -instanceKlass com/google/inject/Injector -instanceKlass com/google/inject/internal/InternalInjectorCreator -instanceKlass com/google/inject/Guice -instanceKlass org/eclipse/sisu/wire/Wiring -instanceKlass org/eclipse/sisu/wire/WireModule$Strategy$1 -instanceKlass org/eclipse/sisu/wire/WireModule$Strategy -instanceKlass org/eclipse/sisu/wire/AbstractTypeConverter -instanceKlass com/google/inject/spi/ElementVisitor -instanceKlass org/eclipse/sisu/wire/WireModule -instanceKlass org/eclipse/sisu/bean/BeanBinder -instanceKlass org/eclipse/sisu/plexus/PlexusBindingModule -instanceKlass org/codehaus/plexus/DefaultPlexusContainer$BootModule -instanceKlass org/codehaus/plexus/component/annotations/Configuration -instanceKlass org/eclipse/sisu/plexus/PlexusAnnotatedMetadata -instanceKlass org/eclipse/sisu/plexus/PlexusBeanMetadata -instanceKlass org/eclipse/sisu/plexus/PlexusAnnotatedBeanModule$PlexusAnnotatedBeanSource -instanceKlass org/eclipse/sisu/space/SpaceModule$2 -instanceKlass org/eclipse/sisu/space/SpaceModule$Strategy$2 -instanceKlass org/eclipse/sisu/space/SpaceModule$Strategy$1 -instanceKlass org/eclipse/sisu/space/DefaultClassFinder -instanceKlass org/eclipse/sisu/space/asm/ClassVisitor -instanceKlass org/eclipse/sisu/space/SpaceScanner -instanceKlass org/eclipse/sisu/space/IndexedClassFinder -instanceKlass org/eclipse/sisu/space/ClassFinder -instanceKlass org/eclipse/sisu/space/SpaceModule -instanceKlass org/eclipse/sisu/space/SpaceVisitor -instanceKlass org/eclipse/sisu/plexus/PlexusTypeListener -instanceKlass org/eclipse/sisu/space/QualifiedTypeListener -instanceKlass org/eclipse/sisu/plexus/PlexusAnnotatedBeanModule$1 -instanceKlass org/eclipse/sisu/space/SpaceModule$Strategy -instanceKlass org/eclipse/sisu/plexus/PlexusAnnotatedBeanModule -instanceKlass org/eclipse/sisu/plexus/PlexusBeanSource -instanceKlass org/eclipse/sisu/plexus/PlexusXmlBeanModule -instanceKlass org/eclipse/sisu/plexus/PlexusBeanModule -instanceKlass org/eclipse/sisu/space/URLClassSpace -instanceKlass org/codehaus/plexus/DefaultPlexusContainer$SLF4JLoggerFactoryProvider -instanceKlass com/google/inject/util/Providers$ConstantProvider -instanceKlass com/google/inject/util/Providers -instanceKlass org/codehaus/plexus/personality/plexus/lifecycle/phase/Disposable -instanceKlass org/codehaus/plexus/personality/plexus/lifecycle/phase/Startable -instanceKlass org/codehaus/plexus/personality/plexus/lifecycle/phase/Initializable -instanceKlass org/codehaus/plexus/personality/plexus/lifecycle/phase/Contextualizable -instanceKlass org/codehaus/plexus/logging/LogEnabled -instanceKlass org/eclipse/sisu/bean/PropertyBinding -instanceKlass javax/annotation/PreDestroy -instanceKlass javax/annotation/PostConstruct -instanceKlass org/eclipse/sisu/bean/LifecycleBuilder -instanceKlass org/eclipse/sisu/bean/BeanScheduler$1 -instanceKlass com/google/inject/spi/DefaultBindingScopingVisitor -instanceKlass com/google/inject/spi/BindingScopingVisitor -instanceKlass org/eclipse/sisu/bean/BeanScheduler$CycleActivator -instanceKlass com/google/inject/PrivateBinder -instanceKlass com/google/inject/MembersInjector -instanceKlass com/google/inject/spi/TypeListener -instanceKlass org/aopalliance/intercept/MethodInterceptor -instanceKlass org/aopalliance/intercept/Interceptor -instanceKlass org/aopalliance/aop/Advice -instanceKlass com/google/inject/spi/Message -instanceKlass com/google/inject/spi/Element -instanceKlass com/google/inject/binder/AnnotatedConstantBindingBuilder -instanceKlass com/google/inject/Scope -instanceKlass com/google/inject/spi/ModuleAnnotatedMethodScanner -instanceKlass com/google/inject/spi/Dependency -instanceKlass com/google/inject/Key -instanceKlass com/google/inject/binder/AnnotatedBindingBuilder -instanceKlass com/google/inject/binder/LinkedBindingBuilder -instanceKlass com/google/inject/binder/ScopedBindingBuilder -instanceKlass com/google/inject/TypeLiteral -instanceKlass com/google/inject/spi/ProvisionListener -instanceKlass com/google/inject/Binder -instanceKlass org/eclipse/sisu/bean/BeanScheduler -instanceKlass org/eclipse/sisu/plexus/DefaultPlexusBeanLocator -instanceKlass org/eclipse/sisu/plexus/RealmManager -instanceKlass org/codehaus/plexus/context/ContextMapAdapter -instanceKlass org/codehaus/plexus/context/DefaultContext -instanceKlass org/codehaus/plexus/logging/AbstractLogger -instanceKlass org/codehaus/plexus/logging/AbstractLoggerManager -instanceKlass java/util/Date -instanceKlass java/text/DigitList -instanceKlass java/text/FieldPosition -instanceKlass sun/util/locale/provider/JRELocaleProviderAdapter$$Lambda$33 -instanceKlass java/text/DecimalFormatSymbols -instanceKlass sun/util/locale/provider/JRELocaleProviderAdapter$$Lambda$32 -instanceKlass sun/util/locale/provider/JRELocaleProviderAdapter$$Lambda$31 -instanceKlass java/text/DateFormatSymbols -instanceKlass sun/util/calendar/CalendarUtils -instanceKlass sun/util/calendar/CalendarDate -instanceKlass sun/util/resources/Bundles$CacheKeyReference -instanceKlass java/util/ResourceBundle$ResourceBundleProviderHelper$$Lambda$30 -instanceKlass java/util/ResourceBundle$ResourceBundleProviderHelper -instanceKlass sun/util/resources/Bundles$CacheKey -instanceKlass java/util/ResourceBundle$1 -instanceKlass jdk/internal/misc/JavaUtilResourceBundleAccess -instanceKlass sun/util/resources/Bundles -instanceKlass sun/util/resources/LocaleData$LocaleDataStrategy -instanceKlass sun/util/resources/Bundles$Strategy -instanceKlass sun/util/resources/LocaleData$1 -instanceKlass sun/util/cldr/CLDRLocaleProviderAdapter$$Lambda$29 -instanceKlass sun/util/locale/provider/CalendarDataUtility$CalendarWeekParameterGetter -instanceKlass sun/util/locale/provider/LocaleServiceProviderPool$LocalizedObjectGetter -instanceKlass sun/util/locale/provider/LocaleServiceProviderPool -instanceKlass sun/util/locale/provider/CalendarDataUtility -instanceKlass sun/util/calendar/CalendarSystem -instanceKlass java/util/Calendar$Builder -instanceKlass java/util/StringTokenizer -instanceKlass sun/util/locale/provider/AvailableLanguageTags -instanceKlass sun/util/locale/provider/JRELocaleProviderAdapter$$Lambda$28 -instanceKlass java/util/ServiceLoader$ProviderImpl -instanceKlass java/util/ServiceLoader$Provider -instanceKlass java/util/ServiceLoader$1 -instanceKlass sun/util/resources/cldr/provider/CLDRLocaleDataMetaInfo -instanceKlass jdk/internal/module/ModulePatcher$PatchedModuleReader -instanceKlass java/util/ServiceLoader$3 -instanceKlass java/util/ServiceLoader$2 -instanceKlass java/util/ServiceLoader$LazyClassPathLookupIterator -instanceKlass java/util/concurrent/CopyOnWriteArrayList$COWIterator -instanceKlass jdk/internal/loader/AbstractClassLoaderValue$Memoizer -instanceKlass java/util/ServiceLoader$ModuleServicesLookupIterator -instanceKlass java/util/ServiceLoader -instanceKlass sun/util/cldr/CLDRLocaleProviderAdapter$1 -instanceKlass sun/util/locale/StringTokenIterator -instanceKlass sun/util/locale/ParseStatus -instanceKlass sun/util/cldr/CLDRBaseLocaleDataMetaInfo -instanceKlass sun/util/locale/provider/LocaleDataMetaInfo -instanceKlass sun/util/locale/provider/LocaleProviderAdapter$1 -instanceKlass java/util/ResourceBundle -instanceKlass java/util/ResourceBundle$Control -instanceKlass sun/util/resources/LocaleData -instanceKlass sun/util/locale/provider/LocaleResources -instanceKlass sun/util/locale/LanguageTag -instanceKlass sun/util/locale/provider/ResourceBundleBasedAdapter -instanceKlass sun/util/locale/provider/LocaleProviderAdapter -instanceKlass java/util/spi/LocaleServiceProvider -instanceKlass java/util/zip/Checksum$1 -instanceKlass java/util/zip/CRC32 -instanceKlass java/util/zip/Checksum -instanceKlass sun/util/calendar/ZoneInfoFile$ZoneOffsetTransitionRule -instanceKlass sun/util/calendar/ZoneInfoFile$1 -instanceKlass sun/util/calendar/ZoneInfoFile -instanceKlass java/util/TimeZone -instanceKlass java/util/Calendar -instanceKlass java/text/AttributedCharacterIterator$Attribute -instanceKlass com/google/inject/matcher/AbstractMatcher -instanceKlass com/google/inject/matcher/Matcher -instanceKlass com/google/inject/spi/TypeConverter -instanceKlass org/codehaus/plexus/DefaultPlexusContainer$LoggerProvider -instanceKlass org/codehaus/plexus/DefaultPlexusContainer$DefaultsModule -instanceKlass org/codehaus/plexus/DefaultPlexusContainer$ContainerModule -instanceKlass java/util/concurrent/locks/ReentrantReadWriteLock$WriteLock -instanceKlass java/util/concurrent/locks/ReentrantReadWriteLock$ReadLock -instanceKlass java/util/concurrent/locks/ReentrantReadWriteLock -instanceKlass java/util/concurrent/locks/ReadWriteLock -instanceKlass org/eclipse/sisu/inject/ImplicitBindings -instanceKlass org/eclipse/sisu/inject/MildValues$InverseMapping -instanceKlass org/eclipse/sisu/inject/MildValues -instanceKlass org/eclipse/sisu/inject/Weak -instanceKlass java/util/concurrent/atomic/AtomicReferenceFieldUpdater$AtomicReferenceFieldUpdaterImpl$1 -instanceKlass java/util/concurrent/atomic/AtomicReferenceFieldUpdater -instanceKlass org/eclipse/sisu/inject/RankedSequence$Content -instanceKlass org/eclipse/sisu/inject/RankedSequence -instanceKlass org/eclipse/sisu/inject/BindingSubscriber -instanceKlass org/eclipse/sisu/inject/DefaultBeanLocator -instanceKlass org/eclipse/sisu/inject/DeferredClass -instanceKlass org/codehaus/plexus/DefaultPlexusContainer$LoggerManagerProvider -instanceKlass org/eclipse/sisu/inject/DeferredProvider -instanceKlass com/google/inject/Provider -instanceKlass com/google/inject/AbstractModule -instanceKlass org/codehaus/plexus/context/Context -instanceKlass org/eclipse/sisu/inject/BindingPublisher -instanceKlass org/eclipse/sisu/inject/RankingFunction -instanceKlass org/eclipse/sisu/space/ClassSpace -instanceKlass javax/inject/Provider -instanceKlass org/eclipse/sisu/bean/BeanManager -instanceKlass org/eclipse/sisu/plexus/PlexusBeanLocator -instanceKlass org/codehaus/plexus/classworlds/ClassWorldListener -instanceKlass com/google/inject/Module -instanceKlass org/eclipse/sisu/inject/MutableBeanLocator -instanceKlass org/eclipse/sisu/inject/BeanLocator -instanceKlass org/codehaus/plexus/DefaultPlexusContainer -instanceKlass org/codehaus/plexus/MutablePlexusContainer -instanceKlass java/util/stream/ReduceOps$Box -instanceKlass java/util/stream/ReduceOps$AccumulatingSink -instanceKlass java/util/stream/TerminalSink -instanceKlass java/util/stream/Sink -instanceKlass java/util/stream/ReduceOps$ReduceOp -instanceKlass java/util/stream/TerminalOp -instanceKlass java/util/stream/ReduceOps -instanceKlass java/util/function/Function$$Lambda$27 -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass org/apache/maven/extension/internal/CoreExports$$Lambda$26 -instanceKlass java/util/stream/Collectors$$Lambda$25 -instanceKlass java/util/stream/Collectors$$Lambda$24 -instanceKlass java/util/function/BinaryOperator -instanceKlass java/util/stream/Collectors$$Lambda$23 -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass java/util/stream/Collectors$$Lambda$22 -instanceKlass java/util/stream/Collectors$CollectorImpl -instanceKlass java/util/stream/Collector -instanceKlass java/util/stream/Collectors -instanceKlass org/apache/maven/extension/internal/CoreExports$$Lambda$21 -instanceKlass sun/invoke/util/VerifyAccess$1 -instanceKlass java/util/function/Function$$Lambda$20 -instanceKlass java/lang/Class$3 -instanceKlass java/util/EnumMap$1 -instanceKlass java/util/stream/StreamOpFlag$MaskBuilder -instanceKlass java/util/stream/PipelineHelper -instanceKlass java/util/stream/Stream -instanceKlass java/util/stream/BaseStream -instanceKlass java/util/stream/StreamSupport -instanceKlass java/util/HashMap$HashMapSpliterator -instanceKlass java/util/Spliterator -instanceKlass org/apache/maven/extension/internal/CoreExports -instanceKlass org/codehaus/plexus/DefaultContainerConfiguration -instanceKlass org/codehaus/plexus/ContainerConfiguration -instanceKlass org/codehaus/plexus/util/BaseIOUtil -instanceKlass org/codehaus/plexus/util/xml/XMLWriter -instanceKlass org/codehaus/plexus/util/xml/Xpp3Dom -instanceKlass org/codehaus/plexus/util/xml/pull/MXParser -instanceKlass org/codehaus/plexus/util/xml/pull/XmlPullParser -instanceKlass org/codehaus/plexus/util/xml/Xpp3DomBuilder -instanceKlass java/util/regex/ASCII -instanceKlass java/util/Locale$1 -instanceKlass java/util/regex/CharPredicates$$Lambda$19 -instanceKlass java/util/regex/Pattern$$Lambda$18 -instanceKlass java/util/regex/Pattern$CharPredicate$$Lambda$17 -instanceKlass org/codehaus/plexus/util/ReaderFactory -instanceKlass org/apache/maven/project/ExtensionDescriptor -instanceKlass org/apache/maven/project/ExtensionDescriptorBuilder -instanceKlass org/apache/maven/extension/internal/CoreExtensionEntry -instanceKlass org/codehaus/plexus/logging/Logger -instanceKlass org/apache/maven/cli/logging/Slf4jLoggerManager -instanceKlass org/slf4j/impl/MavenSlf4jSimpleFriend -instanceKlass org/slf4j/MavenSlf4jFriend -instanceKlass org/apache/commons/cli/CommandLine$$Lambda$16 -instanceKlass org/apache/maven/cli/logging/BaseSlf4jConfiguration -instanceKlass org/codehaus/plexus/util/PropertyUtils -instanceKlass org/apache/maven/cli/logging/Slf4jConfiguration -instanceKlass org/apache/maven/cli/logging/Slf4jConfigurationFactory -instanceKlass java/lang/invoke/VarHandle$AccessDescriptor -instanceKlass org/slf4j/impl/OutputChoice -instanceKlass java/io/FileInputStream$1 -instanceKlass sun/net/DefaultProgressMeteringPolicy -instanceKlass sun/net/ProgressMeteringPolicy -instanceKlass sun/net/ProgressMonitor -instanceKlass org/slf4j/impl/SimpleLoggerConfiguration$1 -instanceKlass java/text/Format -instanceKlass org/slf4j/impl/SimpleLoggerConfiguration -instanceKlass org/slf4j/helpers/NamedLoggerBase -instanceKlass org/slf4j/impl/SimpleLoggerFactory -instanceKlass org/slf4j/impl/StaticLoggerBinder -instanceKlass org/slf4j/spi/LoggerFactoryBinder -instanceKlass java/util/Collections$3 -instanceKlass java/net/URLClassLoader$3$1 -instanceKlass java/net/URLClassLoader$3 -instanceKlass jdk/internal/loader/URLClassPath$1 -instanceKlass java/lang/CompoundEnumeration -instanceKlass jdk/internal/loader/BuiltinClassLoader$1 -instanceKlass java/util/Collections$EmptyEnumeration -instanceKlass org/slf4j/helpers/Util -instanceKlass org/slf4j/helpers/NOPLoggerFactory -instanceKlass java/util/concurrent/LinkedBlockingQueue$Node -instanceKlass java/util/concurrent/locks/AbstractQueuedSynchronizer$ConditionObject -instanceKlass java/util/concurrent/locks/Condition -instanceKlass java/util/concurrent/locks/AbstractQueuedSynchronizer$Node -instanceKlass java/util/concurrent/BlockingQueue -instanceKlass org/slf4j/helpers/SubstituteLoggerFactory -instanceKlass org/slf4j/ILoggerFactory -instanceKlass org/slf4j/event/LoggingEvent -instanceKlass org/slf4j/LoggerFactory -instanceKlass java/util/LinkedList$ListItr -instanceKlass org/codehaus/plexus/util/StringUtils -instanceKlass org/apache/maven/cli/CLIReportingUtils -instanceKlass org/apache/maven/cli/MavenCli$$Lambda$15 -instanceKlass java/util/function/BiConsumer -instanceKlass org/codehaus/plexus/interpolation/SimpleRecursionInterceptor -instanceKlass org/codehaus/plexus/interpolation/AbstractValueSource -instanceKlass org/codehaus/plexus/interpolation/RecursionInterceptor -instanceKlass org/codehaus/plexus/interpolation/StringSearchInterpolator -instanceKlass org/codehaus/plexus/interpolation/Interpolator -instanceKlass org/codehaus/plexus/interpolation/BasicInterpolator -instanceKlass org/apache/maven/properties/internal/SystemProperties -instanceKlass java/util/Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableEntry -instanceKlass java/util/Collections$UnmodifiableMap$UnmodifiableEntrySet$1 -instanceKlass org/codehaus/plexus/util/Os -instanceKlass org/apache/maven/properties/internal/EnvironmentUtils -instanceKlass java/util/LinkedList$Node -instanceKlass java/util/AbstractList$Itr -instanceKlass org/apache/commons/cli/DefaultParser -instanceKlass org/apache/commons/cli/Util -instanceKlass org/apache/commons/cli/CommandLine$Builder$$Lambda$14 -instanceKlass java/util/function/Consumer -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass org/apache/commons/cli/CommandLine$Builder -instanceKlass org/apache/commons/cli/CommandLine -instanceKlass java/util/LinkedHashMap$LinkedHashIterator -instanceKlass org/apache/commons/cli/Parser -instanceKlass org/apache/maven/cli/CleanArgument -instanceKlass org/apache/commons/cli/OptionValidator -instanceKlass org/apache/commons/cli/Option$Builder -instanceKlass org/apache/commons/cli/Option -instanceKlass org/apache/commons/cli/Options -instanceKlass org/apache/commons/cli/CommandLineParser -instanceKlass org/apache/maven/cli/CLIManager -instanceKlass org/apache/maven/cli/logging/Slf4jStdoutLogger -instanceKlass sun/nio/fs/WindowsPath$1 -instanceKlass sun/nio/fs/WindowsLinkSupport -instanceKlass java/util/IdentityHashMap$IdentityHashMapIterator -instanceKlass org/eclipse/aether/DefaultRepositoryCache -instanceKlass org/apache/maven/project/ProjectBuildingRequest -instanceKlass org/eclipse/aether/RepositoryCache -instanceKlass org/apache/maven/execution/DefaultMavenExecutionRequest -instanceKlass java/util/regex/IntHashSet -instanceKlass java/util/regex/Matcher -instanceKlass java/util/regex/MatchResult -instanceKlass java/util/Properties$LineReader -instanceKlass org/apache/maven/execution/MavenExecutionRequest -instanceKlass java/lang/Shutdown$Lock -instanceKlass java/lang/Shutdown -instanceKlass java/lang/ApplicationShutdownHooks$1 -instanceKlass java/lang/ApplicationShutdownHooks -instanceKlass sun/net/www/protocol/jar/URLJarFileCallBack -instanceKlass sun/net/www/protocol/jar/JarFileFactory -instanceKlass sun/net/www/protocol/jar/URLJarFile$URLJarFileCloseController -instanceKlass java/net/URLClassLoader$2 -instanceKlass jdk/internal/jimage/ImageLocation -instanceKlass org/fusesource/jansi/AnsiConsole$$Lambda$13 -instanceKlass jdk/internal/jimage/decompressor/Decompressor -instanceKlass jdk/internal/jimage/ImageStringsReader -instanceKlass jdk/internal/jimage/ImageStrings -instanceKlass java/lang/invoke/LambdaForm$MH -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass jdk/internal/jimage/ImageHeader -instanceKlass org/fusesource/jansi/AnsiConsole$$Lambda$12 -instanceKlass sun/nio/ch/Util$4 -instanceKlass org/fusesource/jansi/io/AnsiOutputStream$IoRunnable -instanceKlass sun/nio/ch/FileChannelImpl$Unmapper -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass sun/reflect/annotation/AnnotationParser -instanceKlass java/nio/channels/FileChannel$MapMode -instanceKlass java/nio/channels/FileLock -instanceKlass jdk/internal/jimage/BasicImageReader$2 -instanceKlass sun/nio/fs/WindowsChannelFactory$2 -instanceKlass org/fusesource/jansi/AnsiConsole$1 -instanceKlass jdk/internal/jimage/NativeImageBuffer$1 -instanceKlass jdk/internal/jimage/NativeImageBuffer -instanceKlass jdk/internal/jimage/BasicImageReader$1 -instanceKlass org/fusesource/jansi/internal/Kernel32 -instanceKlass jdk/internal/jimage/BasicImageReader -instanceKlass jdk/internal/jimage/ImageReader -instanceKlass jdk/internal/jimage/ImageReaderFactory$1 -instanceKlass jdk/internal/jimage/ImageReaderFactory -instanceKlass java/lang/ClassLoader$NativeLibrary$Unloader -instanceKlass jdk/internal/module/SystemModuleFinders$SystemImage -instanceKlass jdk/internal/module/SystemModuleFinders$SystemModuleReader -instanceKlass java/lang/module/ModuleReader -instanceKlass jdk/internal/loader/BuiltinClassLoader$5 -instanceKlass jdk/internal/loader/BuiltinClassLoader$2 -instanceKlass jdk/internal/module/Resources -instanceKlass org/fusesource/jansi/internal/JansiLoader$1 -instanceKlass org/fusesource/jansi/internal/OSInfo -instanceKlass org/fusesource/jansi/internal/JansiLoader$$Lambda$11 -instanceKlass org/fusesource/jansi/internal/JansiLoader -instanceKlass org/fusesource/jansi/internal/CLibrary -instanceKlass java/util/TreeMap$Entry -instanceKlass java/lang/ProcessEnvironment$CheckedEntry -instanceKlass java/lang/ProcessEnvironment$CheckedEntrySet$1 -instanceKlass java/lang/ProcessEnvironment$EntryComparator -instanceKlass java/lang/ProcessEnvironment$NameComparator -instanceKlass org/fusesource/jansi/io/AnsiProcessor -instanceKlass org/fusesource/jansi/io/AnsiOutputStream$WidthSupplier -instanceKlass org/fusesource/jansi/AnsiConsole -instanceKlass org/fusesource/jansi/Ansi$$Lambda$10 -instanceKlass java/util/concurrent/Callable -instanceKlass org/fusesource/jansi/Ansi -instanceKlass org/apache/maven/shared/utils/logging/LoggerLevelRenderer -instanceKlass org/apache/maven/shared/utils/logging/MessageBuilder -instanceKlass org/apache/maven/shared/utils/logging/MessageUtils -instanceKlass java/util/regex/Pattern$CharPredicate$$Lambda$9 -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass java/util/regex/Pattern$$Lambda$8 -instanceKlass java/util/regex/Pattern$BmpCharPredicate$$Lambda$7 -instanceKlass java/util/regex/CharPredicates$$Lambda$6 -instanceKlass java/util/regex/CharPredicates -instanceKlass java/util/regex/Pattern$$Lambda$5 -instanceKlass java/util/regex/Pattern$BitClass$$Lambda$4 -instanceKlass java/util/regex/Pattern$TreeInfo -instanceKlass java/util/regex/Pattern$$Lambda$3 -instanceKlass java/util/regex/Pattern$BmpCharPredicate -instanceKlass java/util/regex/Pattern$CharPredicate -instanceKlass java/util/regex/Pattern$Node -instanceKlass java/util/regex/Pattern -instanceKlass org/apache/maven/cli/CliRequest -instanceKlass org/codehaus/plexus/interpolation/ValueSource -instanceKlass org/apache/maven/toolchain/building/ToolchainsBuildingRequest -instanceKlass org/apache/maven/building/Source -instanceKlass org/slf4j/Logger -instanceKlass org/codehaus/plexus/logging/LoggerManager -instanceKlass org/apache/maven/execution/ExecutionListener -instanceKlass org/apache/maven/eventspy/EventSpy$Context -instanceKlass org/codehaus/plexus/PlexusContainer -instanceKlass org/eclipse/aether/transfer/TransferListener -instanceKlass org/apache/maven/exception/ExceptionHandler -instanceKlass org/apache/maven/cli/MavenCli -instanceKlass java/net/URLClassLoader$1 -instanceKlass java/util/TreeMap$PrivateEntryIterator -instanceKlass java/util/TimSort -instanceKlass sun/security/action/GetBooleanAction -instanceKlass java/util/Arrays$LegacyMergeSort -instanceKlass java/lang/invoke/LambdaForm$MH -instanceKlass java/lang/invoke/LambdaFormBuffer -instanceKlass java/lang/invoke/LambdaFormEditor -instanceKlass java/lang/invoke/DelegatingMethodHandle$Holder -instanceKlass sun/invoke/util/Wrapper$1 -instanceKlass java/lang/invoke/DirectMethodHandle$1 -instanceKlass java/lang/invoke/ClassSpecializer$Factory -instanceKlass java/lang/invoke/ClassSpecializer$SpeciesData -instanceKlass java/lang/invoke/ClassSpecializer$1 -instanceKlass java/lang/invoke/ClassSpecializer -instanceKlass java/lang/invoke/InnerClassLambdaMetafactory$1 -instanceKlass org/codehaus/plexus/classworlds/launcher/Configurator$$Lambda$2 -instanceKlass org/codehaus/plexus/classworlds/launcher/ConfigurationParser$$Lambda$1 -instanceKlass jdk/internal/org/objectweb/asm/FieldVisitor -instanceKlass java/lang/invoke/InfoFromMemberName -instanceKlass java/lang/invoke/MethodHandleInfo -instanceKlass java/lang/invoke/AbstractValidatingLambdaMetafactory -instanceKlass java/lang/invoke/MethodHandleImpl$1 -instanceKlass jdk/internal/misc/JavaLangInvokeAccess -instanceKlass java/lang/invoke/Invokers$Holder -instanceKlass java/lang/invoke/BootstrapMethodInvoker -instanceKlass java/io/FilenameFilter -instanceKlass java/lang/invoke/LambdaForm$DMH -instanceKlass sun/reflect/misc/ReflectUtil -instanceKlass sun/invoke/empty/Empty -instanceKlass sun/invoke/util/VerifyType -instanceKlass java/lang/invoke/InvokerBytecodeGenerator$CpPatch -instanceKlass jdk/internal/org/objectweb/asm/AnnotationVisitor -instanceKlass jdk/internal/org/objectweb/asm/Frame -instanceKlass jdk/internal/org/objectweb/asm/Label -instanceKlass jdk/internal/org/objectweb/asm/Type -instanceKlass jdk/internal/org/objectweb/asm/MethodVisitor -instanceKlass sun/invoke/util/BytecodeDescriptor -instanceKlass jdk/internal/org/objectweb/asm/Item -instanceKlass jdk/internal/org/objectweb/asm/ByteVector -instanceKlass jdk/internal/org/objectweb/asm/ClassVisitor -instanceKlass java/lang/invoke/InvokerBytecodeGenerator$2 -instanceKlass java/lang/invoke/InvokerBytecodeGenerator -instanceKlass java/lang/invoke/LambdaForm$Holder -instanceKlass java/lang/invoke/LambdaForm$Name -instanceKlass java/lang/invoke/Invokers -instanceKlass java/lang/invoke/MethodHandleImpl -instanceKlass sun/invoke/util/ValueConversions -instanceKlass java/lang/invoke/DirectMethodHandle$Holder -instanceKlass java/lang/invoke/LambdaForm$NamedFunction -instanceKlass java/lang/invoke/LambdaMetafactory -instanceKlass org/codehaus/plexus/classworlds/strategy/AbstractStrategy -instanceKlass org/codehaus/plexus/classworlds/strategy/Strategy -instanceKlass org/codehaus/plexus/classworlds/strategy/StrategyFactory -instanceKlass java/util/NavigableMap -instanceKlass java/util/SortedMap -instanceKlass java/util/NavigableSet -instanceKlass java/net/URLClassLoader$7 -instanceKlass jdk/internal/misc/JavaNetURLClassLoaderAccess -instanceKlass java/util/SortedSet -instanceKlass sun/nio/ch/IOStatus -instanceKlass java/nio/DirectByteBuffer$Deallocator -instanceKlass sun/nio/ch/Util$BufferCache -instanceKlass sun/nio/ch/Util -instanceKlass sun/nio/ch/NativeThread -instanceKlass java/io/Reader -instanceKlass org/codehaus/plexus/classworlds/launcher/ConfigurationParser -instanceKlass org/codehaus/plexus/classworlds/launcher/Configurator -instanceKlass org/codehaus/plexus/classworlds/launcher/ConfigurationHandler -instanceKlass java/nio/channels/Channels -instanceKlass sun/nio/ch/FileChannelImpl$Closer -instanceKlass sun/nio/ch/NativeDispatcher -instanceKlass sun/nio/ch/NativeThreadSet -instanceKlass sun/nio/ch/IOUtil$1 -instanceKlass sun/nio/ch/IOUtil -instanceKlass java/nio/channels/spi/AbstractInterruptibleChannel -instanceKlass java/nio/channels/InterruptibleChannel -instanceKlass java/nio/channels/ScatteringByteChannel -instanceKlass java/nio/channels/GatheringByteChannel -instanceKlass java/nio/channels/SeekableByteChannel -instanceKlass java/nio/channels/ByteChannel -instanceKlass java/nio/channels/WritableByteChannel -instanceKlass java/nio/channels/ReadableByteChannel -instanceKlass java/nio/channels/Channel -instanceKlass java/util/Collections$EmptyIterator -instanceKlass sun/nio/fs/WindowsChannelFactory$Flags -instanceKlass sun/nio/fs/WindowsChannelFactory$1 -instanceKlass sun/nio/fs/WindowsChannelFactory -instanceKlass sun/nio/fs/WindowsSecurityDescriptor -instanceKlass java/nio/file/attribute/FileAttribute -instanceKlass java/nio/file/Paths -instanceKlass java/lang/PublicMethods$Key -instanceKlass java/lang/PublicMethods$MethodList -instanceKlass org/codehaus/plexus/classworlds/ClassWorld -instanceKlass org/codehaus/plexus/classworlds/launcher/Launcher -instanceKlass sun/security/util/Debug -instanceKlass java/security/SecureClassLoader$DebugHolder -instanceKlass java/io/FilePermissionCollection$1 -instanceKlass java/security/Permissions$1 -instanceKlass sun/security/util/FilePermCompat -instanceKlass java/io/FilePermission$1 -instanceKlass jdk/internal/misc/JavaIOFilePermissionAccess -instanceKlass sun/net/www/MessageHeader -instanceKlass java/net/URLConnection -instanceKlass java/security/PermissionCollection -instanceKlass java/security/SecureClassLoader$1 -instanceKlass java/security/SecureClassLoader$CodeSourceKey -instanceKlass sun/nio/ByteBuffered -instanceKlass java/lang/Package$VersionInfo -instanceKlass java/lang/NamedPackage -instanceKlass java/util/jar/Attributes$Name -instanceKlass java/util/jar/Attributes -instanceKlass jdk/internal/loader/Resource -instanceKlass java/util/zip/ZipFile$InflaterCleanupAction -instanceKlass java/util/zip/Inflater$InflaterZStreamRef -instanceKlass java/util/zip/Inflater -instanceKlass java/util/zip/ZipEntry -instanceKlass java/util/jar/JarFile$1 -instanceKlass jdk/internal/util/jar/JarIndex -instanceKlass java/nio/Bits$1 -instanceKlass jdk/internal/misc/JavaNioAccess$BufferPool -instanceKlass java/nio/Bits -instanceKlass sun/nio/ch/DirectBuffer -instanceKlass jdk/internal/perf/PerfCounter$CoreCounters -instanceKlass jdk/internal/perf/Perf -instanceKlass jdk/internal/perf/Perf$GetPerfAction -instanceKlass jdk/internal/perf/PerfCounter -instanceKlass java/util/zip/ZipUtils -instanceKlass java/util/zip/ZipFile$Source$End -instanceKlass sun/invoke/util/Wrapper$Format -instanceKlass java/lang/invoke/MethodTypeForm -instanceKlass java/lang/invoke/MethodType$ConcurrentWeakInternSet -instanceKlass java/lang/Void -instanceKlass java/lang/invoke/VarForm -instanceKlass java/lang/invoke/VarHandleGuards -instanceKlass jdk/internal/util/Preconditions$1 -instanceKlass java/util/function/BiFunction -instanceKlass java/lang/invoke/VarHandle$1 -instanceKlass java/lang/invoke/VarHandles -instanceKlass sun/invoke/util/VerifyAccess -instanceKlass java/lang/invoke/MethodHandles$Lookup -instanceKlass java/security/Permission -instanceKlass java/security/Guard -instanceKlass java/lang/invoke/MemberName$Factory -instanceKlass java/lang/invoke/MethodHandles -instanceKlass java/util/concurrent/atomic/AtomicBoolean -instanceKlass java/io/RandomAccessFile$2 -instanceKlass jdk/internal/misc/JavaIORandomAccessFileAccess -instanceKlass java/io/RandomAccessFile -instanceKlass java/io/DataInput -instanceKlass java/io/DataOutput -instanceKlass java/nio/file/attribute/FileTime -instanceKlass sun/nio/fs/WindowsNativeDispatcher$CompletionStatus -instanceKlass sun/nio/fs/WindowsNativeDispatcher$AclInformation -instanceKlass sun/nio/fs/WindowsNativeDispatcher$Account -instanceKlass sun/nio/fs/WindowsNativeDispatcher$DiskFreeSpace -instanceKlass sun/nio/fs/WindowsNativeDispatcher$VolumeInformation -instanceKlass sun/nio/fs/WindowsNativeDispatcher$FirstStream -instanceKlass sun/nio/fs/WindowsNativeDispatcher$FirstFile -instanceKlass java/util/Enumeration -instanceKlass java/util/ArrayDeque$DeqIterator -instanceKlass java/lang/ClassLoader$NativeLibrary -instanceKlass java/lang/ClassLoader$2 -instanceKlass java/lang/StringCoding$StringEncoder -instanceKlass sun/nio/fs/WindowsNativeDispatcher$1 -instanceKlass sun/nio/fs/WindowsNativeDispatcher -instanceKlass sun/nio/fs/NativeBuffer$Deallocator -instanceKlass sun/nio/fs/NativeBuffer -instanceKlass sun/nio/fs/NativeBuffers -instanceKlass sun/nio/fs/WindowsFileAttributes -instanceKlass java/nio/file/attribute/DosFileAttributes -instanceKlass sun/nio/fs/AbstractBasicFileAttributeView -instanceKlass sun/nio/fs/DynamicFileAttributeView -instanceKlass sun/nio/fs/WindowsFileAttributeViews -instanceKlass sun/nio/fs/Util -instanceKlass java/nio/file/attribute/BasicFileAttributeView -instanceKlass java/nio/file/attribute/FileAttributeView -instanceKlass java/nio/file/attribute/AttributeView -instanceKlass java/nio/file/Files -instanceKlass java/nio/file/CopyOption -instanceKlass java/nio/file/attribute/BasicFileAttributes -instanceKlass sun/nio/fs/WindowsPath -instanceKlass java/nio/file/Path -instanceKlass java/nio/file/Watchable -instanceKlass java/net/URI$Parser -instanceKlass java/nio/file/FileSystems$DefaultFileSystemHolder$1 -instanceKlass java/nio/file/FileSystems$DefaultFileSystemHolder -instanceKlass sun/nio/fs/WindowsPathParser$Result -instanceKlass sun/nio/fs/WindowsPathParser -instanceKlass java/util/Arrays$ArrayItr -instanceKlass java/nio/file/FileSystem -instanceKlass java/nio/file/OpenOption -instanceKlass java/nio/file/spi/FileSystemProvider -instanceKlass sun/nio/fs/DefaultFileSystemProvider -instanceKlass java/nio/file/FileSystems -instanceKlass java/util/zip/ZipFile$Source$Key -instanceKlass java/util/zip/ZipFile$Source -instanceKlass jdk/internal/misc/InnocuousThread$2 -instanceKlass jdk/internal/misc/InnocuousThread$3 -instanceKlass jdk/internal/ref/CleanerFactory$1$1 -instanceKlass java/lang/ref/Cleaner$Cleanable -instanceKlass jdk/internal/ref/CleanerImpl -instanceKlass java/lang/ref/Cleaner$1 -instanceKlass java/lang/ref/Cleaner -instanceKlass jdk/internal/ref/CleanerFactory$1 -instanceKlass java/util/concurrent/ThreadFactory -instanceKlass jdk/internal/ref/CleanerFactory -instanceKlass java/util/zip/ZipFile$CleanableResource -instanceKlass java/util/zip/ZipCoder -instanceKlass java/lang/Runtime$Version -instanceKlass java/util/jar/JavaUtilJarAccessImpl -instanceKlass jdk/internal/misc/JavaUtilJarAccess -instanceKlass jdk/internal/loader/FileURLMapper -instanceKlass jdk/internal/loader/URLClassPath$JarLoader$1 -instanceKlass java/util/zip/ZipFile$1 -instanceKlass jdk/internal/misc/JavaUtilZipFileAccess -instanceKlass java/util/zip/ZipFile -instanceKlass java/util/zip/ZipConstants -instanceKlass jdk/internal/loader/URLClassPath$Loader -instanceKlass jdk/internal/loader/URLClassPath$3 -instanceKlass java/security/PrivilegedExceptionAction -instanceKlass sun/util/locale/InternalLocaleBuilder$CaseInsensitiveChar -instanceKlass sun/util/locale/InternalLocaleBuilder -instanceKlass sun/util/locale/LocaleUtils -instanceKlass sun/util/locale/BaseLocale$Key -instanceKlass sun/util/locale/BaseLocale -instanceKlass sun/util/locale/LocaleObjectCache -instanceKlass java/util/Locale -instanceKlass sun/net/util/URLUtil -instanceKlass sun/launcher/LauncherHelper -instanceKlass jdk/jfr/internal/EventWriter -instanceKlass jdk/internal/module/IllegalAccessLogger -instanceKlass jdk/internal/module/ModuleBootstrap$2 -instanceKlass jdk/internal/module/IllegalAccessLogger$Builder -instanceKlass java/lang/ModuleLayer$Controller -instanceKlass java/util/HashMap$HashIterator -instanceKlass jdk/internal/module/ServicesCatalog$ServiceProvider -instanceKlass java/util/concurrent/CopyOnWriteArrayList -instanceKlass java/util/Collections$UnmodifiableCollection$1 -instanceKlass java/util/Collections$UnmodifiableCollection -instanceKlass java/util/ArrayList$Itr -instanceKlass java/util/ImmutableCollections$ListItr -instanceKlass java/util/ListIterator -instanceKlass java/lang/ModuleLayer -instanceKlass jdk/internal/module/ModuleLoaderMap$Mapper -instanceKlass java/util/function/Function -instanceKlass jdk/internal/module/ModuleLoaderMap -instanceKlass java/util/ImmutableCollections$Set12$1 -instanceKlass java/util/ImmutableCollections$MapN$MapNIterator -instanceKlass java/util/AbstractMap$1$1 -instanceKlass java/lang/module/ResolvedModule -instanceKlass java/lang/module/Configuration -instanceKlass java/util/ImmutableCollections$SetN$SetNIterator -instanceKlass jdk/internal/loader/BuiltinClassLoader$LoadedModule -instanceKlass jdk/internal/util/Preconditions -instanceKlass java/util/Deque -instanceKlass java/util/Queue -instanceKlass java/net/URLStreamHandler -instanceKlass sun/net/www/ParseUtil -instanceKlass java/io/ExpiringCache$Entry -instanceKlass java/net/URL$3 -instanceKlass jdk/internal/misc/JavaNetURLAccess -instanceKlass java/net/URL$DefaultFactory -instanceKlass java/net/URLStreamHandlerFactory -instanceKlass jdk/internal/loader/URLClassPath -instanceKlass java/security/Principal -instanceKlass java/security/ProtectionDomain$Key -instanceKlass java/security/ProtectionDomain$JavaSecurityAccessImpl -instanceKlass jdk/internal/misc/JavaSecurityAccess -instanceKlass java/lang/ClassLoader$ParallelLoaders -instanceKlass jdk/internal/loader/AbstractClassLoaderValue -instanceKlass jdk/internal/module/ServicesCatalog -instanceKlass jdk/internal/loader/BootLoader -instanceKlass java/util/Optional -instanceKlass jdk/internal/module/ModuleBootstrap$Counters -instanceKlass jdk/internal/module/SystemModuleFinders$SystemModuleFinder -instanceKlass java/lang/module/ModuleFinder -instanceKlass jdk/internal/module/SystemModuleFinders$3 -instanceKlass jdk/internal/module/ModuleHashes$HashSupplier -instanceKlass java/util/KeyValueHolder -instanceKlass jdk/internal/module/SystemModuleFinders$2 -instanceKlass java/util/function/Supplier -instanceKlass java/lang/module/ModuleReference -instanceKlass jdk/internal/module/ModuleResolution -instanceKlass java/util/Collections$UnmodifiableMap -instanceKlass jdk/internal/module/ModuleHashes$Builder -instanceKlass jdk/internal/module/ModuleHashes -instanceKlass jdk/internal/module/ModuleTarget -instanceKlass java/lang/Enum -instanceKlass java/lang/module/ModuleDescriptor$Version -instanceKlass java/lang/module/ModuleDescriptor$Provides -instanceKlass java/lang/module/ModuleDescriptor$Opens -instanceKlass java/lang/module/ModuleDescriptor$Exports -instanceKlass java/util/ImmutableCollections -instanceKlass java/lang/module/ModuleDescriptor$Requires -instanceKlass jdk/internal/module/Builder -instanceKlass jdk/internal/module/SystemModules$default -instanceKlass jdk/internal/module/SystemModules -instanceKlass jdk/internal/module/SystemModulesMap -instanceKlass java/net/URI$1 -instanceKlass jdk/internal/misc/JavaNetUriAccess -instanceKlass java/net/URI -instanceKlass jdk/internal/module/SystemModuleFinders -instanceKlass jdk/internal/module/ModulePatcher -instanceKlass java/io/ExpiringCache -instanceKlass java/io/FileSystem -instanceKlass java/io/DefaultFileSystem -instanceKlass java/io/File -instanceKlass java/lang/module/ModuleDescriptor$1 -instanceKlass jdk/internal/misc/JavaLangModuleAccess -instanceKlass java/lang/module/ModuleDescriptor -instanceKlass jdk/internal/module/ModuleBootstrap -instanceKlass java/lang/CharacterData -instanceKlass sun/security/action/GetPropertyAction -instanceKlass java/lang/invoke/MethodHandleStatics -instanceKlass java/lang/System$2 -instanceKlass jdk/internal/misc/JavaLangAccess -instanceKlass sun/io/Win32ErrorMode -instanceKlass jdk/internal/misc/OSEnvironment -instanceKlass java/lang/Integer$IntegerCache -instanceKlass jdk/internal/misc/Signal$NativeHandler -instanceKlass java/util/Hashtable$Entry -instanceKlass jdk/internal/misc/Signal -instanceKlass java/lang/Terminator$1 -instanceKlass jdk/internal/misc/Signal$Handler -instanceKlass java/lang/Terminator -instanceKlass java/nio/charset/CoderResult -instanceKlass java/lang/Readable -instanceKlass java/nio/ByteOrder -instanceKlass java/nio/Buffer$1 -instanceKlass jdk/internal/misc/JavaNioAccess -instanceKlass java/nio/charset/CharsetEncoder -instanceKlass sun/nio/cs/ArrayEncoder -instanceKlass java/io/Writer -instanceKlass java/io/OutputStream -instanceKlass java/io/Flushable -instanceKlass java/io/FileDescriptor$1 -instanceKlass jdk/internal/misc/JavaIOFileDescriptorAccess -instanceKlass java/io/FileDescriptor -instanceKlass java/lang/VersionProps -instanceKlass jdk/internal/util/StaticProperty -instanceKlass java/util/concurrent/ConcurrentHashMap$MapEntry -instanceKlass java/util/concurrent/ConcurrentHashMap$Traverser -instanceKlass java/util/Iterator -instanceKlass java/lang/reflect/Array -instanceKlass java/util/Collections$SynchronizedCollection -instanceKlass java/util/List -instanceKlass java/util/RandomAccess -instanceKlass java/util/Collections -instanceKlass java/util/concurrent/ConcurrentHashMap$CollectionView -instanceKlass java/util/Properties$EntrySet -instanceKlass java/lang/StringCoding$Result -instanceKlass java/nio/charset/CodingErrorAction -instanceKlass java/nio/charset/CharsetDecoder -instanceKlass sun/nio/cs/ArrayDecoder -instanceKlass sun/nio/cs/DelegatableDecoder -instanceKlass java/lang/StringUTF16 -instanceKlass sun/nio/cs/DoubleByte -instanceKlass java/lang/StringCoding$StringDecoder -instanceKlass java/lang/ThreadLocal$ThreadLocalMap -instanceKlass java/lang/StringCoding -instanceKlass java/util/HashMap$Node -instanceKlass jdk/internal/reflect/Reflection -instanceKlass java/lang/Class$1 -instanceKlass java/lang/reflect/ReflectAccess -instanceKlass jdk/internal/reflect/LangReflectAccess -instanceKlass java/lang/reflect/Modifier -instanceKlass java/lang/Class$Atomic -instanceKlass java/lang/Class$ReflectionData -instanceKlass java/nio/charset/StandardCharsets -instanceKlass sun/nio/cs/HistoricallyNamedCharset -instanceKlass java/lang/Math -instanceKlass java/util/Arrays -instanceKlass java/lang/ThreadLocal -instanceKlass java/nio/charset/spi/CharsetProvider -instanceKlass java/nio/charset/Charset -instanceKlass java/lang/StringLatin1 -instanceKlass jdk/internal/misc/VM -instanceKlass jdk/internal/misc/SharedSecrets -instanceKlass java/lang/ref/Reference$1 -instanceKlass jdk/internal/misc/JavaLangRefAccess -instanceKlass java/lang/ref/ReferenceQueue$Lock -instanceKlass java/lang/ref/ReferenceQueue -instanceKlass jdk/internal/reflect/ReflectionFactory -instanceKlass java/util/concurrent/locks/LockSupport -instanceKlass java/util/concurrent/ConcurrentHashMap$Node -instanceKlass java/util/Map$Entry -instanceKlass java/util/concurrent/ConcurrentHashMap$CounterCell -instanceKlass java/util/concurrent/locks/ReentrantLock -instanceKlass java/util/concurrent/locks/Lock -instanceKlass java/lang/Runtime -instanceKlass java/util/concurrent/ConcurrentMap -instanceKlass java/util/AbstractMap -instanceKlass java/security/cert/Certificate -instanceKlass jdk/internal/reflect/ReflectionFactory$GetReflectionFactoryAction -instanceKlass java/security/PrivilegedAction -instanceKlass java/util/Objects -instanceKlass java/util/AbstractCollection -instanceKlass java/util/Set -instanceKlass java/util/Collection -instanceKlass java/lang/Iterable -instanceKlass java/security/AccessController -instanceKlass java/lang/String$CaseInsensitiveComparator -instanceKlass java/util/Comparator -instanceKlass java/io/ObjectStreamField -instanceKlass java/lang/Number -instanceKlass java/lang/Character -instanceKlass java/lang/Boolean -instanceKlass java/util/concurrent/locks/AbstractOwnableSynchronizer -instanceKlass java/lang/LiveStackFrame -instanceKlass java/lang/StackFrameInfo -instanceKlass java/lang/StackWalker$StackFrame -instanceKlass java/lang/StackStreamFactory$AbstractStackWalker -instanceKlass java/lang/StackWalker -instanceKlass java/nio/Buffer -instanceKlass java/lang/StackTraceElement -instanceKlass java/security/CodeSource -instanceKlass jdk/internal/loader/ClassLoaders -instanceKlass java/util/jar/Manifest -instanceKlass java/net/URL -instanceKlass java/io/InputStream -instanceKlass java/io/Closeable -instanceKlass java/lang/AutoCloseable -instanceKlass jdk/internal/module/Modules -instanceKlass jdk/internal/misc/Unsafe -instanceKlass java/lang/AbstractStringBuilder -instanceKlass java/lang/Appendable -instanceKlass java/lang/AssertionStatusDirectives -instanceKlass java/lang/invoke/MethodHandleNatives$CallSiteContext -instanceKlass java/lang/invoke/CallSite -instanceKlass java/lang/invoke/MethodType -instanceKlass java/lang/invoke/LambdaForm -instanceKlass java/lang/invoke/MethodHandleNatives -instanceKlass java/lang/invoke/ResolvedMethodName -instanceKlass java/lang/invoke/MemberName -instanceKlass java/lang/invoke/VarHandle -instanceKlass java/lang/invoke/MethodHandle -instanceKlass jdk/internal/reflect/CallerSensitive -instanceKlass java/lang/annotation/Annotation -instanceKlass jdk/internal/reflect/FieldAccessor -instanceKlass jdk/internal/reflect/ConstantPool -instanceKlass jdk/internal/reflect/ConstructorAccessor -instanceKlass jdk/internal/reflect/MethodAccessor -instanceKlass jdk/internal/reflect/MagicAccessorImpl -instanceKlass java/lang/reflect/Parameter -instanceKlass java/lang/reflect/Member -instanceKlass java/lang/reflect/AccessibleObject -instanceKlass java/lang/Module -instanceKlass java/util/Dictionary -instanceKlass java/util/Map -instanceKlass java/lang/ThreadGroup -instanceKlass java/lang/Thread$UncaughtExceptionHandler -instanceKlass java/lang/Thread -instanceKlass java/lang/Runnable -instanceKlass java/lang/ref/Reference -instanceKlass java/security/AccessControlContext -instanceKlass java/security/ProtectionDomain -instanceKlass java/lang/SecurityManager -instanceKlass java/lang/Throwable -instanceKlass java/lang/System -instanceKlass java/lang/ClassLoader -instanceKlass java/lang/Cloneable -instanceKlass java/lang/Class -instanceKlass java/lang/reflect/Type -instanceKlass java/lang/reflect/GenericDeclaration -instanceKlass java/lang/reflect/AnnotatedElement -instanceKlass java/lang/String -instanceKlass java/lang/CharSequence -instanceKlass java/lang/Comparable -instanceKlass java/io/Serializable -ciInstanceKlass java/lang/Object 1 1 92 7 10 10 10 10 8 10 10 10 10 100 8 10 3 8 10 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 7 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 12 12 7 12 12 1 12 7 12 12 12 1 1 12 1 12 1 1 1 1 1 1 1 1 1 1 1 1 -ciInstanceKlass java/io/Serializable 1 0 7 100 100 1 1 1 1 -ciInstanceKlass java/lang/String 1 1 876 10 8 9 9 9 10 10 10 9 10 7 10 10 10 10 10 100 8 10 10 9 9 8 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 100 10 10 100 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 100 100 10 10 11 11 10 10 10 10 10 10 9 11 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 11 10 10 10 10 10 10 100 10 7 10 10 10 10 10 8 10 10 100 3 3 7 10 10 10 10 10 11 7 10 10 100 10 10 10 11 11 11 7 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 100 100 10 100 10 10 100 10 10 10 7 10 10 10 10 8 10 10 10 8 8 10 10 10 10 10 10 10 100 10 8 10 10 10 7 3 8 8 8 10 10 10 10 10 10 8 8 10 8 8 8 8 8 10 10 10 8 7 10 10 10 7 9 7 10 100 100 1 1 1 1 1 1 1 1 1 1 1 1 1 5 0 1 1 1 1 1 1 1 1 1 3 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 7 1 1 1 100 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 100 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 1 12 12 12 12 12 12 12 7 12 1 7 7 12 12 12 12 1 12 7 12 12 12 12 12 12 12 12 12 12 12 12 12 12 1 12 12 1 12 12 12 12 100 12 12 12 12 12 12 12 12 12 12 1 1 12 12 12 12 12 12 12 12 12 7 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 7 12 12 12 12 7 12 12 12 12 7 12 12 7 12 1 1 12 12 12 1 12 1 1 12 12 12 12 7 12 12 12 1 12 12 100 12 12 12 1 12 7 12 12 12 12 12 12 12 12 12 12 12 1 1 1 12 1 100 12 1 1 12 1 12 12 1 12 12 1 1 12 12 12 100 12 7 12 100 12 1 1 12 12 1 1 1 1 12 12 12 12 1 1 1 1 1 1 1 12 12 12 1 1 12 12 12 1 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield java/lang/String COMPACT_STRINGS Z 1 -staticfield java/lang/String serialPersistentFields [Ljava/io/ObjectStreamField; 0 [Ljava/io/ObjectStreamField; -staticfield java/lang/String CASE_INSENSITIVE_ORDER Ljava/util/Comparator; java/lang/String$CaseInsensitiveComparator -ciInstanceKlass java/lang/Class 1 1 1435 10 9 9 7 10 10 8 10 8 8 10 10 10 10 10 10 10 10 10 10 10 8 10 8 8 10 7 8 8 8 10 11 10 10 8 10 10 10 10 9 10 10 10 18 10 7 10 10 10 100 10 9 7 7 8 10 10 10 10 7 10 7 7 10 10 9 10 10 7 10 100 10 10 10 9 10 10 10 9 10 10 100 10 10 10 10 9 8 10 10 10 10 10 10 9 10 7 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 100 8 10 10 100 10 100 11 10 10 10 10 10 10 8 10 10 8 9 10 10 10 10 100 9 10 9 10 10 10 8 10 10 10 10 100 10 10 10 10 10 10 10 7 10 10 10 10 10 10 10 10 10 7 10 10 11 10 10 10 10 10 10 100 10 10 10 100 7 10 10 10 10 10 10 10 10 11 10 10 9 10 9 7 10 9 10 7 10 9 10 10 10 10 10 10 10 8 10 10 9 9 10 7 9 10 10 7 10 10 10 10 9 10 9 10 10 9 9 10 10 9 7 10 10 7 10 7 11 9 9 7 10 9 9 10 10 9 7 10 10 10 10 10 10 10 9 10 10 10 10 8 7 10 7 8 8 8 8 10 9 9 10 7 9 7 10 7 10 10 9 8 10 7 10 7 10 9 100 8 10 7 4 10 10 11 10 100 10 10 8 8 10 9 11 7 11 9 10 10 10 9 9 10 10 10 10 10 11 11 11 11 7 11 10 10 7 11 10 10 10 11 11 7 10 10 9 9 10 10 10 10 100 10 10 7 9 100 7 100 100 1 1 1 7 1 1 1 1 1 3 1 3 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 100 100 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 12 1 12 1 12 1 1 12 12 12 12 12 12 7 12 12 12 12 1 12 1 1 12 1 1 1 1 12 12 12 1 7 12 12 12 7 12 7 12 12 7 12 12 1 15 16 15 16 12 7 12 1 12 12 7 1 12 12 1 1 1 12 12 12 12 1 12 1 1 12 12 12 12 1 100 12 12 12 12 12 12 12 12 12 1 12 12 12 12 1 12 12 12 12 12 12 12 7 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 1 1 12 1 12 1 12 100 12 12 12 12 12 1 12 12 1 12 12 12 12 12 1 12 12 12 12 12 1 12 12 12 12 1 12 12 12 12 12 12 12 1 12 12 12 12 12 12 12 1 7 12 12 12 12 100 12 12 12 1 12 12 1 1 12 12 12 12 12 12 100 12 7 12 12 12 12 12 12 1 12 12 1 12 12 100 12 12 12 100 12 12 12 12 1 12 12 12 12 12 1 12 12 12 1 12 12 7 12 7 12 12 12 12 12 12 12 12 12 12 12 1 12 1 12 7 12 12 1 12 12 12 12 12 12 1 12 12 12 12 12 12 12 12 12 1 7 1 1 1 1 12 12 12 12 1 12 1 1 1 12 7 12 12 1 12 1 12 12 1 1 1 12 12 12 1 12 1 1 12 12 12 1 12 12 100 12 7 12 12 12 12 12 12 12 12 12 12 12 12 1 12 7 12 12 1 12 100 12 12 12 12 1 12 12 12 7 12 12 7 12 12 12 1 12 12 1 12 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 10 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 12 1 1 100 1 1 100 1 1 -staticfield java/lang/Class EMPTY_CLASS_ARRAY [Ljava/lang/Class; 0 [Ljava/lang/Class; -staticfield java/lang/Class serialPersistentFields [Ljava/io/ObjectStreamField; 0 [Ljava/io/ObjectStreamField; -ciInstanceKlass java/lang/Cloneable 1 0 7 100 100 1 1 1 1 -instanceKlass lombok/javac/apt/LombokProcessor$1 -instanceKlass lombok/launch/ShadowClassLoader -instanceKlass lombok/javac/apt/LombokProcessor$1 -instanceKlass lombok/launch/ShadowClassLoader -instanceKlass org/eclipse/sisu/space/CloningClassSpace$CloningClassLoader -instanceKlass jdk/internal/reflect/DelegatingClassLoader -instanceKlass java/security/SecureClassLoader -ciInstanceKlass java/lang/ClassLoader 1 1 1189 9 10 9 10 7 10 10 9 10 100 10 10 10 100 8 10 10 10 10 7 10 7 7 7 10 10 9 7 10 9 9 9 9 9 7 10 9 10 10 9 9 7 9 7 10 10 9 10 7 10 8 10 10 10 7 10 10 8 10 10 10 10 10 10 10 10 7 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 100 10 100 10 10 10 10 10 100 8 10 8 10 10 100 8 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 8 11 9 11 10 8 8 10 100 10 10 10 10 10 10 10 10 10 7 10 10 10 7 10 100 18 10 10 10 7 10 10 10 100 10 10 10 10 8 100 10 10 9 10 10 100 8 10 10 8 8 10 10 7 10 10 100 100 10 100 100 10 10 10 10 10 10 9 10 10 10 10 10 8 10 7 18 10 10 10 10 8 10 10 18 11 100 10 10 10 11 10 18 10 11 18 11 10 9 7 10 10 8 10 9 8 10 9 8 7 10 10 100 8 10 10 10 8 8 10 10 10 8 8 10 10 10 7 10 10 10 10 10 11 11 11 11 11 7 10 9 9 9 10 10 100 10 100 10 10 10 9 9 9 9 9 9 8 10 10 10 10 10 11 10 100 10 10 10 7 7 10 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 12 12 12 12 1 12 12 12 12 1 12 12 12 1 1 12 7 12 12 1 1 1 12 12 12 1 12 12 12 12 12 1 12 12 12 12 12 12 1 12 1 12 12 12 1 1 12 12 1 12 7 12 1 12 12 12 12 12 12 12 12 1 12 100 12 12 12 12 12 12 12 12 12 100 12 12 12 12 1 12 1 12 7 12 12 12 1 1 1 12 12 1 1 12 12 12 12 12 12 12 12 12 12 12 12 7 12 12 12 12 12 12 12 12 12 12 12 1 12 12 12 1 1 12 1 12 12 12 12 12 7 12 12 7 1 12 12 1 12 1 1 15 16 15 16 12 100 12 7 12 7 12 1 12 12 12 1 12 12 7 12 12 1 1 12 12 7 12 12 1 1 12 1 1 12 12 1 12 100 12 1 1 12 1 1 12 12 12 12 12 12 100 12 12 12 12 12 12 1 12 1 16 15 16 12 12 12 12 12 1 12 12 16 15 16 12 12 1 12 12 12 15 12 7 12 16 15 16 12 12 12 12 1 12 12 1 12 12 1 12 12 1 1 12 1 1 12 12 1 1 12 12 100 12 1 1 100 12 12 1 12 12 12 12 12 12 12 12 1 12 12 12 12 12 12 1 1 12 12 12 12 12 12 12 12 12 12 7 12 12 12 12 12 100 12 1 12 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 10 1 10 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 10 1 1 1 1 1 1 1 1 10 1 1 1 1 1 10 1 1 1 10 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 12 12 12 12 12 12 1 1 100 1 1 100 1 1 -staticfield java/lang/ClassLoader nocerts [Ljava/security/cert/Certificate; 0 [Ljava/security/cert/Certificate; -staticfield java/lang/ClassLoader loadedLibraryNames Ljava/util/Set; java/util/HashSet -staticfield java/lang/ClassLoader $assertionsDisabled Z 1 -ciInstanceKlass java/lang/System 1 1 622 10 10 10 10 10 9 7 10 11 10 10 10 100 8 10 10 9 100 8 10 8 10 100 10 8 10 10 100 10 10 10 9 9 7 10 10 10 10 10 10 100 100 8 10 10 7 10 100 8 10 8 10 100 8 10 100 10 8 10 10 10 8 10 10 10 100 8 10 10 10 100 18 100 9 10 100 10 10 10 10 10 10 10 10 7 7 10 10 100 10 10 100 8 10 9 9 10 10 10 10 8 10 10 8 10 10 8 10 10 7 9 10 7 9 10 9 7 10 8 10 8 10 10 10 10 10 10 10 10 9 100 8 10 8 10 10 8 100 10 10 10 10 100 10 10 10 10 10 8 10 10 10 10 8 10 10 10 7 10 10 10 9 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 100 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 100 12 12 12 12 12 12 1 7 12 100 12 100 12 12 12 1 1 12 12 12 1 1 12 1 12 1 12 12 12 1 12 100 12 12 12 12 1 12 12 12 12 12 1 1 1 12 12 1 12 1 1 1 12 1 1 1 1 12 12 7 12 1 12 100 12 7 12 1 1 12 100 12 1 1 15 16 15 16 12 1 12 12 1 12 12 7 12 12 12 12 12 12 1 1 12 12 1 12 7 12 1 1 12 12 12 12 12 12 1 12 12 1 12 12 1 7 12 7 12 1 7 12 12 1 12 12 1 12 1 12 1 7 12 12 7 12 12 7 12 12 12 7 12 12 1 1 12 1 12 1 1 12 7 12 12 1 12 12 12 100 12 1 12 12 1 12 12 12 1 12 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 10 1 10 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 12 12 1 1 100 1 1 100 1 1 -staticfield java/lang/System in Ljava/io/InputStream; java/io/BufferedInputStream -staticfield java/lang/System out Ljava/io/PrintStream; org/fusesource/jansi/AnsiPrintStream -staticfield java/lang/System err Ljava/io/PrintStream; org/fusesource/jansi/AnsiPrintStream -instanceKlass lombok/javac/handlers/HandleDelegate$DelegateRecursion -instanceKlass lombok/javac/handlers/HandleDelegate$DelegateRecursion -instanceKlass org/apache/maven/artifact/repository/metadata/RepositoryMetadataDeploymentException -instanceKlass org/apache/maven/artifact/repository/metadata/RepositoryMetadataInstallationException -instanceKlass java/lang/Exception -instanceKlass java/lang/Error -ciInstanceKlass java/lang/Throwable 1 1 364 10 9 9 9 9 9 10 9 10 10 100 100 10 8 10 8 10 10 10 100 8 10 10 10 10 8 9 10 100 10 10 100 10 10 11 10 10 10 8 10 10 7 8 8 10 10 8 8 9 10 100 10 11 8 8 10 8 10 8 100 10 9 10 10 7 9 10 10 100 8 10 10 11 100 10 11 11 11 8 8 10 11 10 9 8 10 9 10 9 11 100 10 7 10 7 100 1 1 1 100 1 100 1 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 100 1 100 100 1 1 1 1 1 1 1 1 1 1 1 1 12 12 12 12 12 12 12 12 12 12 1 1 1 12 1 100 12 12 1 1 12 7 12 12 1 100 12 12 1 12 12 1 7 12 12 12 12 12 1 12 12 1 1 1 12 12 1 1 12 100 12 1 12 1 1 12 1 12 1 1 12 12 12 7 12 12 12 7 1 1 12 100 12 12 1 12 12 12 12 1 1 100 12 1 100 12 100 12 12 12 12 1 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield java/lang/Throwable UNASSIGNED_STACK [Ljava/lang/StackTraceElement; 0 [Ljava/lang/StackTraceElement; -staticfield java/lang/Throwable SUPPRESSED_SENTINEL Ljava/util/List; java/util/Collections$EmptyList -staticfield java/lang/Throwable EMPTY_THROWABLE_ARRAY [Ljava/lang/Throwable; 0 [Ljava/lang/Throwable; -staticfield java/lang/Throwable $assertionsDisabled Z 1 -instanceKlass com/sun/tools/javac/tree/Pretty$UncheckedIOException -instanceKlass com/sun/source/util/TreePath$1Result -instanceKlass com/sun/tools/javac/file/PathFileObject$CannotCreateUriError -instanceKlass com/sun/tools/javac/tree/TreeInfo$1Result -instanceKlass com/sun/tools/javac/processing/ServiceProxy$ServiceConfigurationError -instanceKlass com/sun/tools/javac/util/Abort -instanceKlass com/sun/tools/javac/processing/AnnotationProcessingError -instanceKlass com/sun/tools/javac/util/FatalError -instanceKlass java/util/ServiceConfigurationError -instanceKlass com/google/common/util/concurrent/ExecutionError -instanceKlass java/lang/AssertionError -instanceKlass java/io/IOError -instanceKlass org/apache/maven/BuildAbort -instanceKlass java/lang/VirtualMachineError -instanceKlass java/lang/LinkageError -instanceKlass java/lang/ThreadDeath -ciInstanceKlass java/lang/Error 1 1 40 10 10 10 10 10 100 7 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 12 12 12 1 1 -ciInstanceKlass java/lang/ThreadDeath 0 0 21 10 100 100 1 1 1 5 0 1 1 1 1 1 1 1 1 1 12 1 1 -instanceKlass org/codehaus/plexus/util/cli/CommandLineException -instanceKlass org/codehaus/plexus/interpolation/InterpolationException -instanceKlass org/codehaus/plexus/components/interactivity/PrompterException -instanceKlass org/codehaus/plexus/archiver/manager/NoSuchArchiverException -instanceKlass org/codehaus/plexus/archiver/ArchiveFilterException -instanceKlass org/codehaus/plexus/archiver/jar/ManifestException -instanceKlass org/codehaus/plexus/interpolation/InterpolationException -instanceKlass org/codehaus/plexus/archiver/jar/ManifestException -instanceKlass org/codehaus/plexus/archiver/manager/NoSuchArchiverException -instanceKlass org/codehaus/plexus/util/cli/CommandLineException -instanceKlass org/apache/maven/surefire/api/testset/TestSetFailedException -instanceKlass org/apache/maven/surefire/booter/SurefireExecutionException -instanceKlass org/apache/maven/surefire/booter/SurefireBooterForkException -instanceKlass lombok/javac/handlers/HandleDelegate$CantMakeDelegates -instanceKlass lombok/javac/JavacResolution$TypeNotConvertibleException -instanceKlass org/springframework/boot/configurationprocessor/json/JSONException -instanceKlass lombok/javac/handlers/HandleDelegate$CantMakeDelegates -instanceKlass lombok/javac/JavacResolution$TypeNotConvertibleException -instanceKlass com/sun/tools/javac/parser/ReferenceParser$ParseException -instanceKlass com/sun/tools/javac/jvm/JNIWriter$TypeSignature$SignatureException -instanceKlass com/sun/tools/javac/jvm/ModuleNameReader$BadClassFile -instanceKlass com/sun/tools/javac/jvm/ClassWriter$StringOverflow -instanceKlass com/sun/tools/javac/jvm/ClassWriter$PoolOverflow -instanceKlass com/sun/tools/doclint/DocLint$BadArgs -instanceKlass com/sun/tools/javac/main/Option$InvalidValueException -instanceKlass org/codehaus/plexus/util/cli/CommandLineException -instanceKlass org/codehaus/plexus/compiler/manager/NoSuchCompilerException -instanceKlass org/codehaus/plexus/compiler/CompilerException -instanceKlass org/codehaus/plexus/compiler/util/scan/InclusionScanException -instanceKlass org/apache/maven/shared/filtering/MavenFilteringException -instanceKlass org/apache/maven/artifact/DependencyResolutionRequiredException -instanceKlass org/codehaus/plexus/util/introspection/MethodMap$AmbiguousException -instanceKlass java/net/URISyntaxException -instanceKlass org/xml/sax/SAXException -instanceKlass javax/xml/parsers/ParserConfigurationException -instanceKlass org/codehaus/plexus/interpolation/reflection/MethodMap$AmbiguousException -instanceKlass org/apache/maven/model/resolution/UnresolvableModelException -instanceKlass org/apache/maven/model/resolution/InvalidRepositoryException -instanceKlass org/apache/maven/cli/internal/ExtensionResolutionException -instanceKlass org/apache/maven/toolchain/building/ToolchainsBuildingException -instanceKlass org/apache/maven/execution/MavenExecutionRequestPopulationException -instanceKlass org/apache/maven/plugin/version/PluginVersionNotFoundException -instanceKlass org/apache/maven/plugin/InvalidPluginException -instanceKlass org/apache/maven/repository/ArtifactDoesNotExistException -instanceKlass org/apache/maven/repository/ArtifactTransferFailedException -instanceKlass org/codehaus/plexus/configuration/PlexusConfigurationException -instanceKlass org/codehaus/plexus/component/composition/CycleDetectedInComponentGraphException -instanceKlass org/codehaus/plexus/component/configurator/expression/ExpressionEvaluationException -instanceKlass org/apache/maven/repository/metadata/MetadataResolutionException -instanceKlass org/apache/maven/configuration/BeanConfigurationException -instanceKlass org/codehaus/plexus/component/configurator/ComponentConfigurationException -instanceKlass org/apache/maven/repository/metadata/MetadataGraphTransformationException -instanceKlass org/apache/maven/repository/metadata/GraphConflictResolutionException -instanceKlass org/apache/maven/artifact/installer/ArtifactInstallationException -instanceKlass org/sonatype/plexus/components/sec/dispatcher/SecDispatcherException -instanceKlass org/sonatype/plexus/components/cipher/PlexusCipherException -instanceKlass org/apache/maven/settings/building/SettingsBuildingException -instanceKlass org/apache/maven/artifact/repository/metadata/RepositoryMetadataReadException -instanceKlass org/apache/maven/artifact/repository/metadata/RepositoryMetadataStoreException -instanceKlass org/apache/maven/plugin/PluginConfigurationException -instanceKlass org/apache/maven/artifact/deployer/ArtifactDeploymentException -instanceKlass org/apache/maven/model/building/ModelBuildingException -instanceKlass org/codehaus/plexus/personality/plexus/lifecycle/phase/InitializationException -instanceKlass org/apache/maven/project/interpolation/ModelInterpolationException -instanceKlass org/apache/maven/repository/legacy/metadata/ArtifactMetadataRetrievalException -instanceKlass org/apache/maven/BuildFailureException -instanceKlass org/codehaus/plexus/util/dag/CycleDetectedException -instanceKlass org/apache/maven/project/DuplicateProjectException -instanceKlass org/apache/maven/project/ProjectBuildingException -instanceKlass org/apache/maven/repository/legacy/resolver/conflict/ConflictResolverNotFoundException -instanceKlass org/apache/maven/artifact/versioning/InvalidVersionSpecificationException -instanceKlass org/apache/maven/lifecycle/LifecycleExecutionException -instanceKlass org/apache/maven/lifecycle/internal/builder/BuilderNotFoundException -instanceKlass org/apache/maven/lifecycle/NoGoalSpecifiedException -instanceKlass org/apache/maven/lifecycle/MissingProjectException -instanceKlass org/apache/maven/lifecycle/LifecycleNotFoundException -instanceKlass org/apache/maven/lifecycle/LifecyclePhaseNotFoundException -instanceKlass org/apache/maven/plugin/InvalidPluginDescriptorException -instanceKlass org/apache/maven/plugin/MojoNotFoundException -instanceKlass org/apache/maven/plugin/PluginDescriptorParsingException -instanceKlass org/apache/maven/project/DependencyResolutionException -instanceKlass org/eclipse/aether/RepositoryException -instanceKlass org/apache/maven/toolchain/MisconfiguredToolchainException -instanceKlass java/security/GeneralSecurityException -instanceKlass org/codehaus/plexus/component/repository/exception/ComponentLifecycleException -instanceKlass org/apache/maven/plugin/prefix/NoPluginFoundForPrefixException -instanceKlass org/apache/maven/MavenExecutionException -instanceKlass org/apache/maven/artifact/resolver/AbstractArtifactResolutionException -instanceKlass org/apache/maven/artifact/repository/metadata/RepositoryMetadataResolutionException -instanceKlass org/apache/maven/plugin/PluginManagerException -instanceKlass org/apache/maven/plugin/version/PluginVersionResolutionException -instanceKlass org/apache/maven/plugin/PluginResolutionException -instanceKlass org/apache/maven/artifact/InvalidRepositoryException -instanceKlass org/apache/http/HttpException -instanceKlass org/apache/maven/wagon/WagonException -instanceKlass org/apache/maven/plugin/AbstractMojoExecutionException -instanceKlass java/security/PrivilegedActionException -instanceKlass java/util/concurrent/TimeoutException -instanceKlass com/google/common/collect/RegularImmutableMap$BucketOverflowException -instanceKlass java/util/concurrent/ExecutionException -instanceKlass java/lang/InterruptedException -instanceKlass com/google/inject/internal/ErrorsException -instanceKlass com/google/inject/internal/InternalProvisionException -instanceKlass org/codehaus/plexus/context/ContextException -instanceKlass java/text/ParseException -instanceKlass org/codehaus/plexus/PlexusContainerException -instanceKlass org/codehaus/plexus/component/repository/exception/ComponentLookupException -instanceKlass org/codehaus/plexus/util/xml/pull/XmlPullParserException -instanceKlass java/lang/CloneNotSupportedException -instanceKlass sun/nio/fs/WindowsException -instanceKlass org/apache/commons/cli/ParseException -instanceKlass org/codehaus/plexus/interpolation/InterpolationException -instanceKlass org/apache/maven/cli/MavenCli$ExitException -instanceKlass org/codehaus/plexus/classworlds/launcher/ConfigurationException -instanceKlass java/io/IOException -instanceKlass org/codehaus/plexus/classworlds/ClassWorldException -instanceKlass java/lang/ReflectiveOperationException -instanceKlass java/lang/RuntimeException -ciInstanceKlass java/lang/Exception 1 1 40 10 10 10 10 10 100 7 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 12 12 12 1 1 -instanceKlass org/codehaus/plexus/archiver/ArchiverException -instanceKlass org/codehaus/plexus/archiver/ArchiverException -instanceKlass org/apache/maven/surefire/api/util/SurefireReflectionException -instanceKlass org/springframework/boot/configurationprocessor/metadata/InvalidConfigurationMetadataException -instanceKlass lombok/core/AnnotationValues$AnnotationValueDecodeFail -instanceKlass org/springframework/boot/configurationprocessor/metadata/InvalidConfigurationMetadataException -instanceKlass lombok/core/AnnotationValues$AnnotationValueDecodeFail -instanceKlass java/lang/LayerInstantiationException -instanceKlass javax/lang/model/UnknownEntityException -instanceKlass com/sun/tools/javac/jvm/Gen$CodeSizeOverflow -instanceKlass com/sun/tools/javac/code/Types$SignatureGenerator$InvalidSignatureException -instanceKlass com/sun/tools/javac/comp/Infer$GraphStrategy$NodeNotFoundException -instanceKlass com/sun/tools/javac/code/Types$AdaptFailure -instanceKlass com/sun/tools/javac/comp/Attr$BreakAttr -instanceKlass com/sun/tools/javac/code/Types$FunctionDescriptorLookupError -instanceKlass com/sun/tools/javac/comp/Resolve$InapplicableMethodException -instanceKlass com/sun/tools/javac/code/Symbol$CompletionFailure -instanceKlass java/nio/file/FileSystemAlreadyExistsException -instanceKlass java/util/MissingResourceException -instanceKlass java/nio/file/FileSystemNotFoundException -instanceKlass java/nio/file/ProviderNotFoundException -instanceKlass com/sun/tools/javac/util/ClientCodeException -instanceKlass com/sun/tools/javac/util/PropagatedException -instanceKlass org/apache/maven/project/DuplicateArtifactAttachmentException -instanceKlass java/time/DateTimeException -instanceKlass org/eclipse/aether/named/support/LockUpgradeNotSupportedException -instanceKlass java/util/ConcurrentModificationException -instanceKlass com/google/inject/internal/aop/GlueException -instanceKlass java/io/UncheckedIOException -instanceKlass org/apache/maven/artifact/InvalidArtifactRTException -instanceKlass com/google/inject/OutOfScopeException -instanceKlass java/lang/annotation/IncompleteAnnotationException -instanceKlass java/lang/reflect/UndeclaredThrowableException -instanceKlass com/google/common/util/concurrent/UncheckedExecutionException -instanceKlass com/google/common/cache/CacheLoader$InvalidCacheLoadException -instanceKlass java/util/NoSuchElementException -instanceKlass com/google/inject/CreationException -instanceKlass com/google/inject/ConfigurationException -instanceKlass com/google/inject/ProvisionException -instanceKlass java/lang/TypeNotPresentException -instanceKlass java/lang/IndexOutOfBoundsException -instanceKlass java/lang/UnsupportedOperationException -instanceKlass java/lang/SecurityException -instanceKlass java/lang/IllegalStateException -instanceKlass java/lang/IllegalArgumentException -instanceKlass java/lang/ArithmeticException -instanceKlass java/lang/NullPointerException -instanceKlass java/lang/IllegalMonitorStateException -instanceKlass java/lang/ArrayStoreException -instanceKlass java/lang/ClassCastException -ciInstanceKlass java/lang/RuntimeException 1 1 40 10 10 10 10 10 100 7 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 12 12 12 1 1 -ciInstanceKlass java/lang/SecurityManager 0 0 572 10 9 100 10 100 8 10 10 10 10 100 10 100 10 9 10 10 10 100 8 10 9 9 8 9 100 10 8 10 10 10 100 10 10 100 100 8 10 8 8 8 8 8 8 10 8 8 8 8 8 10 10 8 100 8 10 8 8 8 8 8 10 8 100 8 8 10 8 8 10 100 8 10 10 100 10 10 10 10 10 10 11 18 11 18 11 18 18 11 18 11 9 9 9 9 100 10 10 10 18 18 10 18 10 18 18 8 10 9 11 8 100 10 10 10 9 10 10 8 100 10 9 8 8 100 10 10 10 9 11 10 11 10 100 100 10 10 10 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 12 12 1 100 12 1 1 12 12 100 12 1 1 12 100 12 12 12 1 1 12 12 1 12 1 1 12 12 12 1 12 1 1 1 12 1 1 1 1 1 1 12 1 1 1 1 1 12 12 1 1 1 1 1 1 1 1 100 12 1 1 1 1 1 1 12 1 1 12 1 12 12 12 100 12 12 100 12 100 12 1 15 16 15 16 12 100 12 16 15 16 12 12 15 16 15 16 12 16 15 16 12 12 12 12 12 12 1 100 12 12 12 15 16 12 15 16 100 12 15 12 12 15 16 15 16 1 12 12 100 12 1 1 12 12 12 12 12 12 1 1 12 1 1 1 12 100 12 12 12 12 12 1 1 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 10 1 10 1 1 1 1 1 1 10 1 1 1 1 1 10 11 1 1 1 10 1 1 1 1 1 1 10 1 10 1 1 1 11 1 1 10 10 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 12 100 12 12 12 100 12 12 12 12 12 1 1 100 1 1 1 1 1 1 1 1 100 1 1 -ciInstanceKlass java/security/ProtectionDomain 1 1 331 10 9 7 10 9 9 9 10 7 9 9 7 9 9 10 100 10 10 10 10 9 9 10 7 10 100 10 9 8 100 8 10 10 10 10 8 11 8 10 8 8 10 10 10 10 8 10 8 8 10 9 10 9 10 100 100 10 10 7 10 100 10 10 11 11 100 11 10 10 11 11 10 10 10 11 10 8 8 10 7 10 10 7 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 7 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 100 100 100 1 1 1 1 1 100 12 12 1 12 12 12 12 12 1 12 12 1 12 12 100 12 100 12 12 12 12 100 12 12 1 1 12 100 12 1 1 1 12 12 12 1 1 12 1 1 12 12 12 12 1 12 1 1 100 12 12 12 12 12 1 1 100 12 1 1 12 12 12 12 1 12 12 12 12 12 12 100 12 12 12 1 1 7 12 1 7 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield java/security/ProtectionDomain filePermCompatInPD Z 0 -ciInstanceKlass java/security/AccessControlContext 1 1 367 9 9 10 8 10 10 9 9 9 10 7 100 10 11 11 11 11 7 11 10 10 9 10 11 10 7 100 8 10 10 7 10 9 9 9 9 9 9 9 10 9 10 10 8 10 10 10 100 10 10 10 10 8 10 8 10 8 8 10 8 10 8 10 10 10 8 8 100 10 10 100 10 8 10 10 10 8 10 10 10 7 10 10 10 10 10 10 10 10 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 100 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 100 12 1 100 12 12 12 12 12 7 12 1 12 12 12 12 12 1 12 12 7 12 100 12 12 12 1 1 1 12 12 1 7 12 12 12 12 12 12 12 12 7 12 12 12 12 1 12 12 100 12 1 12 100 12 1 12 1 100 12 1 1 12 1 12 1 12 12 12 1 1 1 12 12 1 12 1 12 12 1 12 12 12 1 12 12 12 12 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -instanceKlass jdk/internal/loader/Loader -instanceKlass java/net/URLClassLoader -instanceKlass jdk/internal/loader/BuiltinClassLoader -ciInstanceKlass java/security/SecureClassLoader 1 1 127 10 7 10 9 10 10 9 10 10 10 10 10 10 7 10 7 10 7 10 11 7 100 8 10 10 7 7 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 1 12 12 7 12 12 12 12 12 12 12 12 12 1 1 12 1 12 7 12 1 1 1 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -instanceKlass java/lang/InstantiationException -instanceKlass java/lang/IllegalAccessException -instanceKlass java/lang/reflect/InvocationTargetException -instanceKlass java/lang/NoSuchMethodException -instanceKlass java/lang/NoSuchFieldException -instanceKlass java/lang/ClassNotFoundException -ciInstanceKlass java/lang/ReflectiveOperationException 1 1 34 10 10 10 10 100 7 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 12 12 1 1 -ciInstanceKlass java/lang/ClassNotFoundException 1 1 37 100 10 10 9 100 7 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 12 1 1 1 -instanceKlass java/lang/ExceptionInInitializerError -instanceKlass java/lang/UnsatisfiedLinkError -instanceKlass java/lang/IncompatibleClassChangeError -instanceKlass java/lang/BootstrapMethodError -instanceKlass java/lang/NoClassDefFoundError -ciInstanceKlass java/lang/LinkageError 1 1 31 10 10 10 100 7 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 12 1 1 -ciInstanceKlass java/lang/NoClassDefFoundError 1 1 26 10 10 100 7 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 12 12 1 1 -ciInstanceKlass java/lang/ClassCastException 1 1 26 10 10 100 100 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 12 12 1 1 -ciInstanceKlass java/lang/ArrayStoreException 1 1 26 10 10 100 100 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 12 12 1 1 -instanceKlass java/lang/InternalError -instanceKlass java/lang/StackOverflowError -instanceKlass java/lang/OutOfMemoryError -ciInstanceKlass java/lang/VirtualMachineError 1 1 34 10 10 10 10 100 100 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 12 12 1 1 -ciInstanceKlass java/lang/OutOfMemoryError 1 1 26 10 10 100 100 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 12 12 1 1 -ciInstanceKlass java/lang/StackOverflowError 1 1 26 10 10 100 100 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 12 12 1 1 -ciInstanceKlass java/lang/IllegalMonitorStateException 1 1 26 10 10 100 100 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 12 12 1 1 -instanceKlass java/lang/ref/PhantomReference -instanceKlass java/lang/ref/FinalReference -instanceKlass java/lang/ref/WeakReference -instanceKlass java/lang/ref/SoftReference -ciInstanceKlass java/lang/ref/Reference 1 1 159 10 9 10 9 9 7 10 10 9 9 10 10 10 9 9 100 10 10 10 7 10 10 10 7 8 10 7 10 10 10 7 10 10 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 7 1 1 1 1 12 12 12 12 12 1 12 12 12 12 12 12 12 12 12 1 12 12 1 12 12 12 1 1 12 1 12 12 12 1 7 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield java/lang/ref/Reference processPendingLock Ljava/lang/Object; java/lang/Object -instanceKlass java/util/ResourceBundle$BundleReference -instanceKlass org/eclipse/sisu/inject/MildElements$Soft -instanceKlass sun/util/locale/provider/LocaleResources$ResourceReference -instanceKlass sun/util/resources/Bundles$BundleReference -instanceKlass org/eclipse/sisu/inject/MildKeys$Soft -instanceKlass java/lang/invoke/LambdaFormEditor$Transform -instanceKlass jdk/internal/ref/SoftCleanable -instanceKlass sun/util/locale/LocaleObjectCache$CacheEntry -ciInstanceKlass java/lang/ref/SoftReference 1 1 47 10 9 9 10 10 7 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 12 12 12 12 12 1 1 1 -instanceKlass jdk/internal/jimage/ImageBufferCache$BufferReference -instanceKlass java/util/ResourceBundle$KeyElementReference -instanceKlass sun/nio/ch/FileLockTable$FileLockReference -instanceKlass org/eclipse/sisu/inject/MildElements$Weak -instanceKlass java/lang/WeakPairMap$WeakRefPeer -instanceKlass com/google/common/collect/MapMakerInternalMap$AbstractWeakKeyEntry -instanceKlass com/google/common/cache/LocalCache$WeakEntry -instanceKlass java/lang/ClassValue$Entry -instanceKlass java/util/logging/LogManager$LoggerWeakRef -instanceKlass java/util/logging/Level$KnownLevel -instanceKlass org/eclipse/sisu/inject/MildKeys$Weak -instanceKlass java/lang/invoke/MethodType$ConcurrentWeakInternSet$WeakEntry -instanceKlass jdk/internal/ref/WeakCleanable -instanceKlass java/util/WeakHashMap$Entry -instanceKlass java/lang/ThreadLocal$ThreadLocalMap$Entry -ciInstanceKlass java/lang/ref/WeakReference 1 1 31 10 10 100 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 1 1 -instanceKlass java/lang/ref/Finalizer -ciInstanceKlass java/lang/ref/FinalReference 1 1 36 10 100 8 10 100 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 1 1 12 1 1 1 -instanceKlass jdk/internal/ref/PhantomCleanable -instanceKlass jdk/internal/ref/Cleaner -ciInstanceKlass java/lang/ref/PhantomReference 1 1 30 10 100 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 1 1 -ciInstanceKlass java/lang/ref/Finalizer 1 1 139 9 10 9 9 9 9 7 10 10 7 11 100 10 100 10 10 10 100 10 10 7 10 7 10 10 10 10 7 10 7 10 10 10 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 12 12 12 12 12 12 1 12 12 1 7 12 1 12 1 12 100 12 100 12 1 12 12 1 1 12 12 12 1 12 1 12 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield java/lang/ref/Finalizer lock Ljava/lang/Object; java/lang/Object -instanceKlass com/sun/tools/javac/file/BaseFileManager$1 -instanceKlass java/util/logging/LogManager$Cleaner -instanceKlass org/apache/maven/shared/utils/logging/MessageUtils$1 -instanceKlass jdk/internal/misc/InnocuousThread -instanceKlass java/lang/ref/Finalizer$FinalizerThread -instanceKlass java/lang/ref/Reference$ReferenceHandler -ciInstanceKlass java/lang/Thread 1 1 592 9 9 10 9 9 100 8 10 3 8 3 10 10 9 9 9 9 7 100 8 10 9 10 10 10 10 10 10 9 10 10 9 10 10 9 10 9 10 9 9 10 10 9 10 9 100 10 7 10 8 10 10 10 10 10 10 9 100 10 10 10 10 100 11 9 10 10 10 9 10 9 10 100 10 10 10 11 10 10 10 7 10 10 10 10 10 10 10 10 10 10 100 8 10 10 10 8 10 8 10 8 8 10 10 100 8 10 9 9 10 10 10 9 10 100 10 11 9 9 10 100 10 11 100 10 10 11 10 100 10 10 10 8 9 10 11 10 11 10 7 7 1 1 100 1 100 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 3 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 7 100 100 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 100 1 1 1 1 1 1 1 1 1 100 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 12 12 12 12 12 1 1 12 1 12 12 12 12 12 12 1 1 1 12 7 12 12 12 12 12 100 12 12 12 12 12 12 12 12 12 7 12 12 12 12 7 12 12 12 12 1 1 1 12 12 12 12 12 12 12 1 12 12 12 1 12 7 12 12 12 12 12 12 12 1 12 12 12 12 12 12 1 12 12 12 12 12 12 12 12 12 1 1 12 12 1 12 1 1 1 100 12 100 12 1 12 12 12 12 12 12 1 12 12 12 12 12 1 12 100 12 1 12 12 12 12 1 12 12 100 12 12 12 12 100 12 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield java/lang/Thread EMPTY_STACK_TRACE [Ljava/lang/StackTraceElement; 0 [Ljava/lang/StackTraceElement; -ciInstanceKlass java/lang/ThreadGroup 1 1 289 10 9 8 9 7 9 9 10 10 10 10 10 9 10 10 9 10 9 9 10 100 10 10 10 9 10 10 9 10 10 10 10 10 10 10 10 10 10 10 100 10 10 10 7 10 7 10 9 10 8 10 10 10 10 11 100 9 100 10 8 10 10 8 10 10 10 10 8 10 8 10 8 7 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 1 12 1 12 12 12 12 12 12 12 12 12 12 12 100 12 12 12 7 12 12 7 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 1 12 12 1 12 12 12 12 1 12 12 12 12 1 12 1 1 12 12 1 12 12 12 100 1 1 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -ciInstanceKlass java/util/Map 1 1 258 11 11 10 11 11 11 11 7 11 11 100 100 10 11 11 11 11 10 11 11 10 100 10 7 7 10 7 10 100 11 100 11 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 7 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 7 12 12 7 12 12 12 1 12 12 1 1 12 12 12 12 12 12 12 100 12 100 12 1 1 12 1 1 1 12 1 1 1 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -instanceKlass java/util/Hashtable -ciInstanceKlass java/util/Dictionary 1 1 36 10 100 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 1 1 -instanceKlass java/util/Properties -ciInstanceKlass java/util/Hashtable 1 1 488 100 10 9 100 100 10 8 10 10 10 10 10 8 10 9 7 9 7 4 10 9 4 10 11 10 10 9 10 100 10 9 10 9 10 10 3 9 9 3 10 10 10 11 11 11 11 100 11 11 10 10 10 9 9 9 10 100 100 10 10 8 10 10 8 10 8 10 7 10 10 100 10 10 100 10 100 10 10 100 11 11 100 10 10 10 11 100 10 11 11 10 10 10 10 10 10 10 100 10 10 8 10 10 100 11 10 10 10 7 100 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 3 1 3 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 100 100 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 12 12 1 1 1 12 12 12 12 7 12 1 12 12 1 12 1 7 12 12 12 12 12 12 12 12 1 12 12 12 12 12 12 12 12 12 12 12 100 12 12 12 1 12 12 12 12 12 12 12 12 1 1 12 1 12 1 1 100 12 1 12 12 1 12 12 1 1 12 1 12 12 1 100 12 12 1 12 12 12 12 12 12 12 12 100 12 1 12 1 12 100 12 1 100 12 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -instanceKlass org/apache/maven/plugin/surefire/SurefireProperties -instanceKlass java/security/Provider -ciInstanceKlass java/util/Properties 1 1 636 10 100 10 7 10 9 9 9 10 10 8 10 7 10 10 8 10 10 9 10 100 3 100 8 10 7 10 10 7 10 10 10 10 10 8 10 10 10 10 10 100 7 10 10 7 8 10 10 10 10 7 10 10 10 11 11 11 7 11 11 10 8 10 10 100 10 10 10 8 10 10 10 100 100 100 10 8 8 10 10 10 7 10 10 10 100 10 10 11 10 8 10 11 8 10 11 9 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 7 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 7 10 100 10 11 4 11 10 10 11 10 10 10 100 8 10 10 10 100 6 0 10 11 10 10 1 1 1 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 100 7 100 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 100 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 100 1 1 1 1 100 1 1 1 1 1 12 1 12 1 12 12 12 12 7 12 12 1 7 12 1 12 12 1 12 12 12 12 1 1 1 12 1 12 12 1 12 12 12 12 1 12 12 12 12 12 1 1 12 12 1 1 12 12 12 12 1 12 7 12 12 12 1 12 12 12 1 12 12 1 12 100 12 1 12 100 12 12 1 1 1 1 1 12 12 12 1 12 12 1 12 12 7 12 1 12 1 12 12 12 12 12 12 12 12 12 12 12 12 12 12 1 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 1 12 1 12 12 12 12 12 100 12 12 1 1 12 100 12 1 12 100 12 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield java/util/Properties UNSAFE Ljdk/internal/misc/Unsafe; jdk/internal/misc/Unsafe -staticfield java/util/Properties hexDigit [C 16 -ciInstanceKlass java/lang/Module 1 1 910 10 9 10 9 9 9 10 10 10 10 7 10 10 7 11 7 10 10 9 10 10 8 10 10 10 9 11 9 10 9 10 10 100 100 10 10 8 10 10 10 10 10 10 9 10 10 9 10 10 9 11 7 10 9 9 10 7 7 10 100 8 10 10 10 8 10 10 10 10 8 8 10 10 10 18 10 11 9 11 10 100 8 10 7 10 10 11 11 9 11 10 10 9 10 10 10 10 18 11 10 11 10 11 4 10 7 10 11 7 10 11 7 10 7 8 10 10 7 10 10 7 7 10 9 100 10 10 10 10 10 11 7 10 11 10 11 10 10 10 10 10 10 10 10 18 11 11 18 10 10 10 7 10 10 10 9 7 10 10 10 10 10 10 10 10 10 9 18 10 7 100 8 10 10 10 100 10 100 8 100 10 100 100 3 10 100 10 10 10 100 10 10 100 100 10 8 10 10 10 10 10 10 10 7 10 10 10 100 8 10 10 8 10 8 10 10 10 8 10 7 10 10 10 11 100 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 7 7 7 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 100 100 1 7 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 12 12 12 12 12 12 12 12 12 12 1 7 12 12 1 12 12 7 12 100 12 12 12 1 12 12 12 12 12 12 7 12 12 7 12 12 1 1 12 1 12 12 12 12 12 12 12 12 12 12 12 12 12 12 1 12 12 12 12 1 1 12 1 1 12 12 1 12 12 12 12 1 1 12 12 12 1 15 16 15 16 12 12 12 12 12 7 12 1 1 1 12 12 12 12 12 12 12 12 12 12 7 12 16 15 16 12 12 100 12 12 12 12 12 1 12 1 12 1 7 12 100 1 1 1 12 12 1 12 12 1 1 12 12 1 7 12 12 12 12 1 12 12 12 12 12 12 12 12 12 12 12 16 15 16 12 12 12 15 16 12 12 12 12 1 12 12 12 12 1 12 12 12 12 12 12 12 16 15 16 12 100 12 1 1 1 12 12 12 1 12 1 1 1 1 1 12 1 12 12 12 1 12 12 1 1 12 1 12 12 7 12 12 12 12 12 1 12 12 1 1 12 100 12 1 12 1 12 12 12 1 1 12 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 10 10 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 10 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 10 1 1 1 1 1 1 10 1 1 1 1 1 1 10 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 12 12 100 12 12 12 1 1 100 1 1 1 100 1 1 -staticfield java/lang/Module ALL_UNNAMED_MODULE Ljava/lang/Module; java/lang/Module -staticfield java/lang/Module ALL_UNNAMED_MODULE_SET Ljava/util/Set; java/util/ImmutableCollections$Set12 -staticfield java/lang/Module EVERYONE_MODULE Ljava/lang/Module; java/lang/Module -staticfield java/lang/Module EVERYONE_SET Ljava/util/Set; java/util/ImmutableCollections$Set12 -staticfield java/lang/Module $assertionsDisabled Z 1 -instanceKlass java/lang/reflect/Executable -instanceKlass java/lang/reflect/Field -ciInstanceKlass java/lang/reflect/AccessibleObject 1 1 405 10 9 10 10 10 10 7 10 10 9 100 10 11 7 100 10 7 100 10 10 7 10 10 7 10 7 10 10 10 10 10 10 10 10 10 10 8 100 10 10 8 10 10 8 8 8 8 8 8 100 10 10 9 10 10 10 18 10 10 10 11 100 100 8 10 10 10 8 10 8 10 10 100 8 10 11 10 10 10 10 10 9 100 10 10 9 10 8 10 8 10 9 100 10 7 10 10 7 9 7 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 12 100 12 12 12 7 12 7 12 12 12 12 1 12 12 1 1 12 1 1 12 12 1 12 12 1 12 1 7 12 12 12 12 12 12 12 12 1 1 12 1 12 12 1 1 1 1 1 1 1 12 12 12 12 12 7 12 1 15 16 15 16 12 12 12 1 1 1 12 12 1 12 1 12 1 1 12 12 12 12 12 12 12 12 12 12 100 12 1 100 12 1 12 12 1 1 1 1 7 12 1 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 10 10 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 12 12 1 1 100 1 1 100 1 1 -staticfield java/lang/reflect/AccessibleObject reflectionFactory Ljdk/internal/reflect/ReflectionFactory; jdk/internal/reflect/ReflectionFactory -ciInstanceKlass java/lang/reflect/Field 1 1 433 9 10 10 10 9 10 10 10 10 9 9 9 9 9 9 9 100 8 10 7 10 9 9 10 10 10 10 10 10 7 10 10 10 10 10 10 10 100 10 8 10 10 8 10 10 8 8 10 11 9 10 10 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 10 10 10 10 10 9 10 10 10 10 11 10 7 10 10 9 10 11 10 10 9 10 10 7 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 100 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 100 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 100 1 1 1 1 1 1 1 1 12 12 100 12 100 12 12 12 12 7 12 12 12 12 12 12 12 12 12 1 1 12 1 12 12 12 12 7 12 12 12 12 12 1 12 12 12 12 12 12 1 1 12 12 1 12 12 1 1 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 7 12 12 7 12 12 12 1 100 12 7 12 12 7 12 7 12 12 12 7 12 7 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 -ciInstanceKlass java/lang/reflect/Parameter 1 1 226 10 9 9 9 9 7 10 10 10 100 10 10 11 10 10 10 10 10 8 8 10 10 10 8 10 8 10 9 10 9 10 10 10 10 10 10 10 10 11 10 100 10 10 10 10 10 9 100 10 11 11 7 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 100 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 12 12 12 12 12 1 12 12 100 12 1 12 12 12 100 12 12 12 12 1 1 12 12 12 1 1 12 12 12 12 12 12 12 12 12 100 12 12 100 12 12 1 100 12 12 12 12 12 12 1 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -instanceKlass java/lang/reflect/Constructor -instanceKlass java/lang/reflect/Method -ciInstanceKlass java/lang/reflect/Executable 1 1 458 10 10 10 11 10 10 10 10 10 7 8 7 10 10 10 100 8 10 10 10 10 8 8 10 10 100 8 10 8 10 8 11 10 10 11 10 8 8 10 10 100 10 10 10 10 10 10 7 10 10 10 10 10 7 10 7 8 10 10 3 100 8 10 10 10 10 10 8 8 8 9 10 100 8 9 10 10 10 10 10 10 7 10 10 100 10 7 10 10 11 10 10 10 9 10 7 10 10 9 10 10 9 10 9 10 9 7 100 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 100 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 100 100 1 1 1 1 1 1 1 1 1 1 1 1 12 7 12 12 7 12 7 12 12 12 12 12 1 1 1 12 12 1 1 12 7 12 12 12 1 1 12 1 1 12 1 12 1 100 12 12 12 1 1 12 12 1 12 12 7 12 12 12 1 12 12 12 12 7 12 12 1 1 12 12 1 1 12 12 12 12 1 1 1 12 12 1 1 12 12 12 12 12 12 12 12 12 1 100 12 1 7 12 12 12 12 100 12 12 12 12 1 12 12 7 12 7 12 12 12 12 12 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -ciInstanceKlass java/lang/reflect/Method 1 1 441 9 10 10 9 10 10 10 10 9 9 9 9 9 9 9 9 9 9 9 100 8 10 7 10 9 8 10 10 10 10 10 10 10 7 10 10 10 7 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 100 8 10 100 8 10 10 10 10 10 10 10 11 9 10 10 10 10 11 10 7 10 10 10 10 9 10 10 10 10 10 11 10 7 100 100 10 10 10 100 10 8 10 10 10 10 10 8 10 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 100 100 7 1 100 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 7 12 7 12 12 12 12 7 12 12 12 12 12 12 12 12 12 12 12 12 12 1 1 12 1 12 12 1 7 12 7 12 12 12 12 12 12 1 12 12 7 12 12 7 12 12 12 12 12 100 12 12 12 12 12 12 12 1 1 1 1 12 12 12 12 12 12 12 100 12 12 12 12 12 12 12 1 12 12 12 12 12 7 12 12 7 12 7 12 7 12 7 12 7 12 1 1 1 12 12 12 1 1 12 12 12 12 1 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -ciInstanceKlass java/lang/reflect/Constructor 1 1 415 10 10 9 10 10 10 9 10 9 9 9 9 9 9 9 9 100 8 10 7 10 9 10 10 10 10 10 7 100 8 10 10 10 10 10 100 10 7 10 10 10 10 10 10 10 10 10 100 8 10 10 100 8 10 10 10 10 10 10 10 9 10 10 100 8 10 11 10 10 10 9 10 10 10 10 10 10 10 10 10 100 8 10 10 10 10 10 10 10 11 9 10 10 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 100 100 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 12 7 12 12 12 12 7 12 12 12 12 12 12 12 12 12 12 12 1 1 12 1 12 12 7 12 7 12 12 12 12 1 1 1 12 12 12 12 1 7 12 12 7 12 12 7 12 12 12 12 12 1 1 12 1 1 12 12 12 12 12 12 12 12 12 12 1 1 12 12 12 12 12 12 7 12 12 12 12 12 12 12 12 12 1 1 12 12 12 12 100 12 100 12 100 12 100 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 -instanceKlass jdk/internal/reflect/FieldAccessorImpl -instanceKlass jdk/internal/reflect/ConstructorAccessorImpl -instanceKlass jdk/internal/reflect/MethodAccessorImpl -ciInstanceKlass jdk/internal/reflect/MagicAccessorImpl 1 1 16 10 100 7 1 1 1 1 1 1 1 1 1 12 1 1 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor49 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor48 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor47 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor46 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor45 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor44 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor43 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor42 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor41 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor40 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor39 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor38 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor37 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor36 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor35 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor34 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor33 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor32 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor31 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor30 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor29 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor28 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor27 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor26 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor25 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor24 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor23 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor22 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor21 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor20 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor19 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor18 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor17 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor16 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor15 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor14 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor13 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor12 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor11 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor10 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor9 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor8 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor7 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor6 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor5 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor4 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor3 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor2 -instanceKlass jdk/internal/reflect/GeneratedMethodAccessor1 -instanceKlass jdk/internal/reflect/DelegatingMethodAccessorImpl -instanceKlass jdk/internal/reflect/NativeMethodAccessorImpl -ciInstanceKlass jdk/internal/reflect/MethodAccessorImpl 1 1 25 10 100 7 100 1 1 1 1 1 1 1 1 1 1 100 100 1 1 12 1 1 1 1 1 -instanceKlass jdk/internal/reflect/GeneratedConstructorAccessor10 -instanceKlass jdk/internal/reflect/GeneratedConstructorAccessor9 -instanceKlass jdk/internal/reflect/GeneratedConstructorAccessor8 -instanceKlass jdk/internal/reflect/GeneratedConstructorAccessor7 -instanceKlass jdk/internal/reflect/GeneratedConstructorAccessor6 -instanceKlass jdk/internal/reflect/GeneratedConstructorAccessor5 -instanceKlass jdk/internal/reflect/GeneratedConstructorAccessor4 -instanceKlass jdk/internal/reflect/GeneratedConstructorAccessor3 -instanceKlass jdk/internal/reflect/GeneratedConstructorAccessor2 -instanceKlass jdk/internal/reflect/BootstrapConstructorAccessorImpl -instanceKlass jdk/internal/reflect/GeneratedConstructorAccessor1 -instanceKlass jdk/internal/reflect/DelegatingConstructorAccessorImpl -instanceKlass jdk/internal/reflect/NativeConstructorAccessorImpl -ciInstanceKlass jdk/internal/reflect/ConstructorAccessorImpl 1 1 27 10 100 7 100 1 1 1 1 1 1 1 1 1 1 100 100 100 1 1 12 1 1 1 1 1 1 -ciInstanceKlass jdk/internal/reflect/DelegatingClassLoader 1 1 18 10 100 7 1 1 1 1 1 1 1 1 1 1 1 12 1 1 -ciInstanceKlass jdk/internal/reflect/ConstantPool 1 1 138 10 9 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 7 7 8 10 100 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 1 1 7 12 1 1 1 1 1 1 1 -instanceKlass jdk/internal/reflect/UnsafeFieldAccessorImpl -ciInstanceKlass jdk/internal/reflect/FieldAccessorImpl 1 1 59 10 100 7 100 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 1 1 1 1 1 -instanceKlass jdk/internal/reflect/UnsafeIntegerFieldAccessorImpl -instanceKlass jdk/internal/reflect/UnsafeBooleanFieldAccessorImpl -instanceKlass jdk/internal/reflect/UnsafeQualifiedFieldAccessorImpl -instanceKlass jdk/internal/reflect/UnsafeObjectFieldAccessorImpl -instanceKlass jdk/internal/reflect/UnsafeStaticFieldAccessorImpl -ciInstanceKlass jdk/internal/reflect/UnsafeFieldAccessorImpl 1 1 253 10 9 10 10 9 10 9 10 10 9 10 10 10 10 100 10 10 10 8 10 10 100 8 10 8 10 8 10 100 10 10 8 10 8 10 8 10 8 10 8 10 8 10 8 10 8 10 8 10 10 8 8 8 8 8 8 10 8 8 8 10 10 7 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 12 7 12 12 7 12 12 12 12 12 12 12 7 12 12 1 12 12 1 12 1 1 12 1 12 1 12 1 12 1 12 1 100 12 1 100 12 1 100 12 1 100 12 1 100 12 1 100 12 1 100 12 1 100 12 12 1 1 1 1 1 1 12 1 1 1 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield jdk/internal/reflect/UnsafeFieldAccessorImpl unsafe Ljdk/internal/misc/Unsafe; jdk/internal/misc/Unsafe -instanceKlass jdk/internal/reflect/UnsafeQualifiedStaticFieldAccessorImpl -ciInstanceKlass jdk/internal/reflect/UnsafeStaticFieldAccessorImpl 1 1 43 10 9 10 9 7 7 8 10 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 7 12 12 1 1 7 12 1 1 1 1 1 1 1 1 1 -ciInstanceKlass jdk/internal/reflect/CallerSensitive 0 0 17 100 100 100 1 1 1 1 1 1 1 1 1 1 1 1 1 -instanceKlass java/lang/invoke/DelegatingMethodHandle -instanceKlass java/lang/invoke/BoundMethodHandle -instanceKlass java/lang/invoke/DirectMethodHandle -ciInstanceKlass java/lang/invoke/MethodHandle 1 1 489 9 10 10 7 7 10 9 10 10 10 10 10 10 11 10 10 10 9 10 100 100 10 8 10 10 8 10 10 10 10 10 10 10 10 10 10 7 10 10 10 8 10 8 10 10 10 10 8 10 8 10 8 10 9 100 10 9 9 8 10 10 10 10 10 10 10 10 10 10 10 8 10 8 10 10 10 10 10 9 8 10 10 8 10 10 10 10 10 100 8 10 10 9 10 7 10 10 9 10 10 8 9 9 9 10 10 10 10 7 10 8 10 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 7 12 1 1 12 12 12 12 12 100 12 12 12 100 12 12 12 12 12 12 1 1 1 12 12 1 12 12 7 12 12 12 12 12 12 12 100 12 1 12 12 12 1 7 12 1 12 12 12 12 1 12 1 12 1 100 12 12 1 100 12 100 1 12 12 12 12 12 12 12 12 12 12 12 1 12 1 12 12 12 12 12 12 1 12 12 1 12 12 7 12 12 1 1 12 12 12 1 100 12 12 12 12 12 1 12 12 12 7 12 12 12 12 1 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield java/lang/invoke/MethodHandle FORM_OFFSET J 20 -staticfield java/lang/invoke/MethodHandle $assertionsDisabled Z 1 -instanceKlass java/lang/invoke/DirectMethodHandle$Interface -instanceKlass java/lang/invoke/DirectMethodHandle$Constructor -instanceKlass java/lang/invoke/DirectMethodHandle$Special -instanceKlass java/lang/invoke/DirectMethodHandle$Accessor -ciInstanceKlass java/lang/invoke/DirectMethodHandle 1 1 922 7 7 100 7 7 10 10 100 10 10 10 10 10 10 7 7 10 10 10 10 10 10 9 100 10 9 10 10 10 10 10 10 7 10 10 10 8 10 7 10 7 10 10 10 10 10 10 100 10 10 7 10 10 10 10 8 10 10 10 10 10 9 7 10 10 10 100 10 8 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 8 9 8 9 9 8 9 9 8 9 9 8 10 10 7 9 7 10 100 10 10 10 10 7 10 10 10 7 10 10 10 10 10 9 10 9 9 10 10 7 7 7 9 10 10 10 10 9 10 100 10 100 10 10 8 9 9 10 9 10 9 9 10 10 10 10 10 10 10 9 10 10 10 10 10 9 10 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 8 9 9 10 100 10 9 10 7 9 10 10 10 10 10 8 8 8 8 10 9 10 7 10 8 9 10 8 8 8 9 8 8 8 8 8 8 7 8 10 10 8 8 10 10 10 10 7 7 1 1 1 1 1 1 1 100 1 1 1 1 7 1 1 1 1 1 3 1 3 1 3 1 3 1 3 1 3 1 3 1 1 3 1 1 3 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 3 1 1 1 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 12 12 1 12 12 12 12 12 12 1 1 12 12 12 12 12 12 12 1 12 12 12 12 12 12 12 1 12 12 12 1 12 1 12 1 12 12 12 12 12 1 12 12 1 12 12 12 12 12 12 12 12 12 7 12 1 12 7 12 12 1 1 12 12 12 12 12 12 12 12 12 12 12 12 7 12 12 12 12 12 1 12 1 12 12 1 12 12 1 12 12 1 12 12 1 12 1 12 1 12 12 12 12 1 12 12 12 12 7 12 12 12 12 12 12 12 7 12 12 1 1 1 12 12 12 12 12 12 12 1 12 1 12 12 1 12 12 12 12 100 12 12 12 12 12 12 12 12 12 7 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 1 12 12 12 1 12 7 12 1 12 12 12 12 12 1 1 1 1 12 12 12 1 100 12 12 12 12 1 1 12 12 1 12 12 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield java/lang/invoke/DirectMethodHandle IMPL_NAMES Ljava/lang/invoke/MemberName$Factory; java/lang/invoke/MemberName$Factory -staticfield java/lang/invoke/DirectMethodHandle FT_UNCHECKED_REF I 8 -staticfield java/lang/invoke/DirectMethodHandle ACCESSOR_FORMS [Ljava/lang/invoke/LambdaForm; 132 [Ljava/lang/invoke/LambdaForm; -staticfield java/lang/invoke/DirectMethodHandle ALL_WRAPPERS [Lsun/invoke/util/Wrapper; 10 [Lsun/invoke/util/Wrapper; -staticfield java/lang/invoke/DirectMethodHandle NFS [Ljava/lang/invoke/LambdaForm$NamedFunction; 12 [Ljava/lang/invoke/LambdaForm$NamedFunction; -staticfield java/lang/invoke/DirectMethodHandle OBJ_OBJ_TYPE Ljava/lang/invoke/MethodType; java/lang/invoke/MethodType -staticfield java/lang/invoke/DirectMethodHandle LONG_OBJ_TYPE Ljava/lang/invoke/MethodType; java/lang/invoke/MethodType -staticfield java/lang/invoke/DirectMethodHandle $assertionsDisabled Z 1 -instanceKlass java/lang/invoke/VarHandleObjects$Array -instanceKlass java/lang/invoke/VarHandleObjects$FieldInstanceReadOnly -instanceKlass java/lang/invoke/VarHandleInts$FieldInstanceReadOnly -ciInstanceKlass java/lang/invoke/VarHandle 1 1 298 10 9 100 10 9 10 10 10 9 10 10 9 9 10 10 10 10 10 10 10 9 100 10 9 10 10 7 7 10 10 10 9 10 9 10 10 10 100 10 9 9 10 10 10 10 10 10 10 7 10 10 9 8 10 7 10 7 100 1 1 100 1 100 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 100 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 12 12 1 12 12 12 12 12 12 12 12 12 12 12 12 12 12 100 12 12 1 12 12 12 1 1 12 100 12 12 12 12 12 12 12 12 1 7 12 12 7 12 12 12 12 12 12 12 1 7 12 12 12 1 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield java/lang/invoke/VarHandle AIOOBE_SUPPLIER Ljava/util/function/BiFunction; jdk/internal/util/Preconditions$1 -staticfield java/lang/invoke/VarHandle VFORM_OFFSET J 12 -staticfield java/lang/invoke/VarHandle $assertionsDisabled Z 1 -ciInstanceKlass java/lang/invoke/MemberName 1 1 747 7 7 100 9 10 9 10 10 10 10 10 10 10 9 10 100 100 10 8 10 10 10 10 9 8 10 7 7 10 10 100 100 7 10 9 100 8 10 10 10 10 10 10 10 10 10 10 8 8 8 10 10 9 3 10 10 10 10 10 10 10 10 10 7 8 10 10 8 9 8 9 10 8 10 10 10 10 10 100 10 10 8 10 10 8 10 10 100 10 10 8 8 100 10 10 100 10 10 10 10 10 10 10 10 10 3 10 3 10 3 3 3 3 3 3 100 10 10 10 3 9 10 3 10 10 10 10 10 10 10 10 10 10 10 10 10 10 100 10 10 10 100 10 10 10 10 10 10 8 10 10 10 10 10 10 10 10 10 10 10 10 10 100 10 100 8 10 7 10 10 10 10 10 8 8 8 8 10 10 10 8 8 10 8 10 10 10 8 8 10 10 8 10 8 10 10 10 8 8 8 100 10 8 8 8 8 10 100 100 100 10 100 10 100 10 9 10 100 100 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 3 1 3 1 3 1 3 1 3 1 1 1 1 1 1 1 1 3 1 1 1 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 100 1 1 1 1 1 1 1 1 1 7 1 1 12 12 12 12 12 12 12 12 12 12 100 12 12 1 1 12 1 12 12 12 12 12 1 100 12 1 1 12 1 12 12 1 1 12 12 12 12 12 12 12 12 12 12 1 1 1 100 12 12 12 12 12 12 12 12 12 12 12 1 12 12 100 100 12 1 12 12 12 12 12 1 12 12 1 12 12 1 12 12 1 12 12 1 1 1 12 100 12 1 12 12 12 12 12 12 12 12 12 12 100 1 12 7 12 12 12 12 12 7 12 12 12 12 12 12 12 12 12 1 12 1 12 12 12 12 12 12 12 12 12 12 12 12 12 1 12 1 1 1 12 12 12 12 12 1 1 1 1 12 12 12 1 1 12 1 12 12 1 1 12 1 12 1 12 12 12 1 1 1 1 1 1 1 1 12 1 1 1 1 1 12 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield java/lang/invoke/MemberName $assertionsDisabled Z 1 -ciInstanceKlass java/lang/invoke/ResolvedMethodName 1 1 16 10 100 100 1 1 1 1 1 1 1 1 1 12 1 1 -ciInstanceKlass java/lang/invoke/MethodHandleNatives 1 1 660 100 10 9 10 100 10 10 10 10 8 8 8 8 8 8 8 8 8 8 7 10 7 10 10 7 10 10 8 10 8 10 8 10 9 8 10 100 10 100 100 8 7 7 10 10 7 9 10 10 10 7 10 10 10 10 10 9 8 10 8 10 8 8 8 100 10 8 10 10 10 100 8 10 7 8 10 8 8 8 8 8 10 10 10 10 10 7 10 100 100 10 10 8 8 10 10 10 8 10 8 8 10 10 100 10 7 9 10 10 10 9 10 9 9 10 10 10 7 7 10 10 10 10 10 8 10 10 10 10 10 10 100 8 10 9 10 10 100 10 10 100 100 10 10 100 100 10 100 10 10 10 10 10 10 10 10 10 10 10 10 8 100 10 10 10 10 10 10 7 10 10 10 10 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 12 1 12 12 12 1 1 1 1 1 1 1 1 1 1 1 12 1 12 12 1 12 1 12 1 12 1 12 100 12 1 100 12 1 12 1 1 1 1 1 12 1 7 12 12 12 12 1 12 7 12 12 12 12 12 1 12 1 12 1 1 1 1 12 1 12 12 100 12 1 100 12 1 1 12 1 1 1 1 1 12 12 12 12 12 1 12 1 1 12 12 1 1 12 12 1 100 12 1 1 12 12 1 12 1 12 7 12 12 12 12 12 12 12 12 12 1 1 12 12 12 7 12 12 1 12 12 12 12 7 12 12 1 1 12 12 12 1 12 12 1 1 1 1 1 12 12 12 12 12 12 12 12 12 1 1 12 12 12 12 12 12 1 12 12 12 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield java/lang/invoke/MethodHandleNatives $assertionsDisabled Z 1 -ciInstanceKlass java/lang/invoke/LambdaForm 1 1 1075 100 9 10 10 9 9 10 100 10 9 10 9 10 7 9 9 9 9 10 7 10 7 10 10 10 10 10 10 9 100 10 9 10 10 10 10 10 7 10 10 8 10 10 10 7 10 10 7 10 10 9 9 9 10 9 10 10 100 10 9 10 10 100 10 10 10 10 10 10 10 8 10 10 8 8 9 9 9 10 10 10 9 10 10 10 10 10 10 9 10 8 8 8 8 8 8 8 8 10 9 7 10 9 10 10 10 10 10 10 10 10 10 10 10 10 10 10 100 8 10 10 10 10 8 10 8 8 10 9 10 10 100 10 10 10 10 9 8 10 10 10 10 10 9 8 10 100 10 10 9 9 8 10 10 100 100 10 10 8 8 100 8 10 10 10 8 8 9 10 10 8 8 8 100 8 100 8 100 8 10 8 9 10 10 9 10 10 10 10 10 10 10 10 10 10 8 100 10 10 9 10 8 8 100 8 8 8 8 8 8 8 8 10 10 10 10 8 8 8 10 8 10 8 8 8 8 8 10 10 10 10 10 10 10 10 10 10 10 9 8 10 9 10 9 9 9 9 7 10 9 10 10 7 8 10 9 7 10 8 100 10 9 9 10 7 10 10 10 9 10 10 10 9 10 10 10 9 10 9 7 9 10 9 10 100 10 7 9 100 1 1 100 1 100 1 1 1 7 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 3 1 1 1 1 1 3 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 100 1 1 12 12 12 12 12 12 1 12 12 12 7 12 12 12 12 12 12 1 12 1 12 12 100 12 100 12 12 12 12 1 12 12 12 12 12 12 12 1 12 1 12 12 12 1 12 12 1 12 12 12 12 12 12 12 12 12 1 12 12 12 12 1 12 12 12 12 12 12 12 1 12 12 1 1 12 12 12 12 7 12 12 12 7 12 12 12 12 12 12 12 1 1 1 1 1 1 1 1 12 12 1 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 1 1 12 12 12 1 12 1 1 12 12 12 12 1 12 12 7 12 12 12 1 100 12 12 12 12 12 12 1 12 12 7 12 12 1 12 12 1 1 12 1 1 1 1 12 12 12 1 1 12 12 12 1 1 1 1 1 1 1 1 1 12 1 12 12 12 12 12 12 12 12 12 12 12 12 1 12 12 12 12 1 1 1 1 1 1 1 1 1 1 1 12 12 12 12 1 1 1 12 1 12 1 1 1 1 1 12 12 12 7 12 12 12 12 12 12 12 12 12 1 12 12 12 12 12 12 12 1 7 12 12 12 12 1 1 12 12 1 12 1 1 12 12 12 12 1 12 7 12 12 7 12 12 12 12 12 12 12 12 12 12 12 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield java/lang/invoke/LambdaForm COMPILE_THRESHOLD I 0 -staticfield java/lang/invoke/LambdaForm INTERNED_ARGUMENTS [[Ljava/lang/invoke/LambdaForm$Name; 5 [[Ljava/lang/invoke/LambdaForm$Name; -staticfield java/lang/invoke/LambdaForm IMPL_NAMES Ljava/lang/invoke/MemberName$Factory; java/lang/invoke/MemberName$Factory -staticfield java/lang/invoke/LambdaForm LF_identity [Ljava/lang/invoke/LambdaForm; 6 [Ljava/lang/invoke/LambdaForm; -staticfield java/lang/invoke/LambdaForm LF_zero [Ljava/lang/invoke/LambdaForm; 6 [Ljava/lang/invoke/LambdaForm; -staticfield java/lang/invoke/LambdaForm NF_identity [Ljava/lang/invoke/LambdaForm$NamedFunction; 6 [Ljava/lang/invoke/LambdaForm$NamedFunction; -staticfield java/lang/invoke/LambdaForm NF_zero [Ljava/lang/invoke/LambdaForm$NamedFunction; 6 [Ljava/lang/invoke/LambdaForm$NamedFunction; -staticfield java/lang/invoke/LambdaForm createFormsLock Ljava/lang/Object; java/lang/Object -staticfield java/lang/invoke/LambdaForm DEBUG_NAME_COUNTERS Ljava/util/HashMap; null -staticfield java/lang/invoke/LambdaForm DEBUG_NAMES Ljava/util/HashMap; null -staticfield java/lang/invoke/LambdaForm TRACE_INTERPRETER Z 0 -staticfield java/lang/invoke/LambdaForm $assertionsDisabled Z 1 -ciInstanceKlass java/lang/invoke/MethodType 1 1 680 7 10 9 9 9 10 9 8 10 10 9 9 10 100 10 8 10 10 10 100 8 10 100 10 10 10 10 11 9 11 7 7 10 10 9 10 10 10 10 10 10 9 7 10 100 10 10 10 10 10 10 10 10 10 8 8 10 9 100 10 10 10 10 10 10 10 10 10 8 10 10 10 10 10 10 10 10 10 9 10 10 10 10 9 7 10 10 10 10 10 10 10 10 100 8 8 8 10 10 10 10 11 11 10 9 10 10 10 10 10 10 10 10 10 10 10 10 9 7 10 10 10 10 10 10 10 8 10 11 9 10 10 10 10 10 10 10 10 10 9 9 10 9 10 7 10 7 7 9 100 1 1 100 1 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 3 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 100 100 1 100 100 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 100 1 1 1 100 1 1 1 1 1 100 1 12 12 12 12 7 12 7 12 1 100 12 12 7 7 12 1 1 12 12 12 1 1 12 1 12 12 12 12 12 12 1 7 12 12 12 12 12 12 7 12 12 12 12 1 12 1 12 12 7 12 12 12 12 12 12 12 1 1 12 12 1 12 12 12 12 100 12 12 12 1 12 100 12 12 12 12 12 12 12 12 12 12 12 12 12 1 12 100 12 12 7 12 12 12 1 1 1 1 12 12 12 12 12 100 12 12 12 12 12 12 12 12 12 12 12 12 12 12 1 12 12 12 12 12 12 12 1 7 12 12 12 12 12 100 12 12 12 12 100 12 12 100 12 12 100 12 12 12 1 1 1 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield java/lang/invoke/MethodType internTable Ljava/lang/invoke/MethodType$ConcurrentWeakInternSet; java/lang/invoke/MethodType$ConcurrentWeakInternSet -staticfield java/lang/invoke/MethodType NO_PTYPES [Ljava/lang/Class; 0 [Ljava/lang/Class; -staticfield java/lang/invoke/MethodType objectOnlyTypes [Ljava/lang/invoke/MethodType; 20 [Ljava/lang/invoke/MethodType; -staticfield java/lang/invoke/MethodType METHOD_HANDLE_ARRAY [Ljava/lang/Class; 1 [Ljava/lang/Class; -staticfield java/lang/invoke/MethodType serialPersistentFields [Ljava/io/ObjectStreamField; 0 [Ljava/io/ObjectStreamField; -staticfield java/lang/invoke/MethodType $assertionsDisabled Z 1 -ciInstanceKlass java/lang/BootstrapMethodError 0 0 45 10 10 10 10 10 100 100 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 100 1 1 12 12 12 12 12 1 1 1 1 1 1 1 1 -instanceKlass java/lang/invoke/VolatileCallSite -instanceKlass java/lang/invoke/MutableCallSite -instanceKlass java/lang/invoke/ConstantCallSite -ciInstanceKlass java/lang/invoke/CallSite 1 1 299 10 10 9 10 9 10 10 100 7 10 7 10 10 10 100 100 10 10 10 8 10 10 10 10 10 10 10 10 9 9 7 8 10 10 100 10 9 8 100 10 10 100 8 10 10 10 100 10 10 10 10 10 9 9 8 10 9 100 10 10 10 10 10 10 100 8 10 10 100 100 100 8 10 10 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 7 1 1 1 1 1 1 12 12 12 12 12 12 12 1 1 12 1 12 12 12 1 1 12 12 1 12 12 12 12 12 100 12 12 12 100 12 1 12 12 1 100 12 12 12 12 1 1 12 12 1 12 12 12 12 12 12 12 100 12 12 1 100 12 12 12 12 7 12 1 1 12 1 1 1 1 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield java/lang/invoke/CallSite $assertionsDisabled Z 1 -ciInstanceKlass java/lang/invoke/MethodHandleNatives$CallSiteContext 1 1 49 10 7 10 10 10 10 7 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 12 1 7 12 7 12 12 1 1 1 1 1 1 1 1 100 1 1 1 1 1 -ciInstanceKlass java/lang/invoke/ConstantCallSite 1 1 49 10 9 10 100 10 9 100 10 10 7 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 12 12 12 1 12 12 1 12 1 1 1 1 -ciInstanceKlass java/lang/invoke/MutableCallSite 0 0 67 10 10 9 10 10 10 9 10 10 100 10 100 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 12 12 12 12 12 12 12 12 100 12 1 12 1 1 1 1 1 1 1 1 1 1 1 -ciInstanceKlass java/lang/invoke/VolatileCallSite 0 0 41 10 10 10 10 10 10 100 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 12 12 12 12 1 1 1 1 1 1 1 -ciInstanceKlass java/lang/AssertionStatusDirectives 0 0 24 10 100 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 1 1 -instanceKlass java/lang/StringBuilder -instanceKlass java/lang/StringBuffer -ciInstanceKlass java/lang/AbstractStringBuilder 1 1 522 7 7 10 9 9 9 9 10 9 10 10 10 10 10 10 10 10 7 3 10 3 100 10 10 100 10 10 10 10 10 10 10 100 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 11 10 10 8 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 18 100 10 18 10 10 10 11 10 10 10 100 10 8 10 10 8 8 10 10 10 10 100 10 100 10 100 10 7 100 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 100 1 1 1 100 1 1 1 1 1 1 1 1 1 12 12 12 12 12 7 12 12 12 7 12 12 12 12 12 7 12 1 12 1 12 1 12 12 12 12 12 12 1 12 100 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 1 12 12 12 12 12 12 7 12 12 12 100 12 12 12 12 12 12 12 12 12 7 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 1 15 16 15 16 12 1 100 12 15 12 12 12 12 12 12 1 1 12 12 1 1 12 12 12 1 1 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 10 1 10 1 1 1 1 1 10 1 1 1 1 1 1 1 1 1 1 100 12 12 12 1 1 100 1 1 100 1 1 -staticfield java/lang/AbstractStringBuilder EMPTYVALUE [B 0 -ciInstanceKlass java/lang/StringBuffer 1 1 466 10 10 10 11 10 10 10 9 10 10 10 9 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 9 10 10 7 10 10 10 10 10 8 10 8 10 8 10 10 10 10 7 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 7 10 7 10 9 9 9 7 100 100 100 1 1 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 100 1 1 1 100 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 7 12 7 1 12 100 12 12 1 12 1 12 1 12 12 100 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 1 12 1 12 7 12 7 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield java/lang/StringBuffer serialPersistentFields [Ljava/io/ObjectStreamField; 3 [Ljava/io/ObjectStreamField; -ciInstanceKlass java/lang/StringBuilder 1 1 403 10 10 10 11 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 9 9 10 10 10 10 10 10 10 10 10 10 10 100 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 7 10 7 100 100 100 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 100 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 7 12 7 100 12 12 12 12 12 100 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 1 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -ciInstanceKlass jdk/internal/misc/Unsafe 1 1 1161 10 9 9 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 100 10 10 10 5 0 10 10 10 10 10 10 10 10 10 100 10 10 10 10 10 10 10 10 10 10 10 10 10 10 5 0 5 0 5 0 10 10 10 100 10 10 10 10 10 10 10 10 10 100 10 10 10 10 8 10 8 8 10 9 9 9 9 9 9 9 9 10 10 10 10 5 0 5 0 9 10 10 10 10 10 8 3 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 100 10 9 5 0 10 5 0 10 5 0 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 5 0 5 0 5 0 10 10 10 10 10 7 10 7 10 9 7 9 7 9 7 9 7 9 7 9 7 9 7 9 7 9 10 9 9 9 9 9 9 9 9 9 10 10 10 7 1 1 1 1 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 12 12 7 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 1 12 12 12 12 12 12 12 12 12 12 12 1 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 1 12 12 12 12 12 12 12 12 1 12 12 12 1 12 1 1 12 7 12 100 7 100 100 100 100 12 12 12 12 12 12 12 12 12 12 1 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 1 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 1 1 12 12 12 1 12 1 12 1 12 1 12 1 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield jdk/internal/misc/Unsafe theUnsafe Ljdk/internal/misc/Unsafe; jdk/internal/misc/Unsafe -staticfield jdk/internal/misc/Unsafe ARRAY_BOOLEAN_BASE_OFFSET I 16 -staticfield jdk/internal/misc/Unsafe ARRAY_BYTE_BASE_OFFSET I 16 -staticfield jdk/internal/misc/Unsafe ARRAY_SHORT_BASE_OFFSET I 16 -staticfield jdk/internal/misc/Unsafe ARRAY_CHAR_BASE_OFFSET I 16 -staticfield jdk/internal/misc/Unsafe ARRAY_INT_BASE_OFFSET I 16 -staticfield jdk/internal/misc/Unsafe ARRAY_LONG_BASE_OFFSET I 16 -staticfield jdk/internal/misc/Unsafe ARRAY_FLOAT_BASE_OFFSET I 16 -staticfield jdk/internal/misc/Unsafe ARRAY_DOUBLE_BASE_OFFSET I 16 -staticfield jdk/internal/misc/Unsafe ARRAY_OBJECT_BASE_OFFSET I 16 -staticfield jdk/internal/misc/Unsafe ARRAY_BOOLEAN_INDEX_SCALE I 1 -staticfield jdk/internal/misc/Unsafe ARRAY_BYTE_INDEX_SCALE I 1 -staticfield jdk/internal/misc/Unsafe ARRAY_SHORT_INDEX_SCALE I 2 -staticfield jdk/internal/misc/Unsafe ARRAY_CHAR_INDEX_SCALE I 2 -staticfield jdk/internal/misc/Unsafe ARRAY_INT_INDEX_SCALE I 4 -staticfield jdk/internal/misc/Unsafe ARRAY_LONG_INDEX_SCALE I 8 -staticfield jdk/internal/misc/Unsafe ARRAY_FLOAT_INDEX_SCALE I 4 -staticfield jdk/internal/misc/Unsafe ARRAY_DOUBLE_INDEX_SCALE I 8 -staticfield jdk/internal/misc/Unsafe ARRAY_OBJECT_INDEX_SCALE I 4 -staticfield jdk/internal/misc/Unsafe ADDRESS_SIZE I 8 -staticfield jdk/internal/misc/Unsafe BE Z 0 -staticfield jdk/internal/misc/Unsafe unalignedAccess Z 1 -ciInstanceKlass jdk/internal/module/Modules 1 1 483 10 9 11 11 11 11 11 11 11 11 10 10 18 10 100 10 10 10 10 11 10 10 10 10 9 10 10 10 100 100 11 10 11 10 10 10 10 10 11 18 11 10 11 100 11 11 11 10 10 18 11 18 11 10 18 18 10 9 11 100 10 11 11 100 11 10 100 10 10 10 11 10 100 10 18 10 100 8 10 10 18 11 11 10 10 10 18 10 10 7 10 10 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 100 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 100 100 100 100 100 100 100 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 12 12 7 12 12 12 12 12 12 12 12 12 100 12 1 15 16 15 16 12 100 12 1 100 12 100 12 12 12 12 12 12 12 12 12 100 12 1 1 12 100 12 12 12 12 100 12 12 12 12 16 15 16 12 12 100 12 100 12 1 12 12 12 12 100 12 16 15 16 12 12 16 15 16 12 12 12 15 16 15 16 12 12 12 1 12 12 1 12 1 12 12 12 12 12 1 15 16 12 12 1 1 12 12 15 16 12 12 12 15 12 1 12 7 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 10 1 10 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 10 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 10 1 1 1 1 1 1 10 1 1 1 1 1 1 10 1 10 1 1 1 1 1 1 1 1 1 1 1 1 1 10 1 1 1 1 1 10 1 1 10 1 1 1 1 1 100 12 12 12 12 12 12 12 12 12 1 1 100 1 1 1 1 1 100 1 1 -staticfield jdk/internal/module/Modules JLA Ljdk/internal/misc/JavaLangAccess; java/lang/System$2 -staticfield jdk/internal/module/Modules $assertionsDisabled Z 1 -instanceKlass org/codehaus/plexus/archiver/bzip2/CBZip2InputStream -instanceKlass org/apache/commons/io/input/ClosedInputStream -instanceKlass java/io/SequenceInputStream -instanceKlass org/iq80/snappy/AbstractSnappyInputStream -instanceKlass org/codehaus/plexus/components/io/resources/ClosingInputStream -instanceKlass org/apache/commons/compress/compressors/CompressorInputStream -instanceKlass jdk/nio/zipfs/ZipFileSystem$EntryInputStream -instanceKlass sun/nio/ch/ChannelInputStream -instanceKlass java/util/zip/ZipFile$ZipFileInputStream -instanceKlass java/io/FilterInputStream -instanceKlass java/io/FileInputStream -instanceKlass java/io/ByteArrayInputStream -ciInstanceKlass java/io/InputStream 1 1 170 100 10 100 10 10 10 10 100 3 10 100 8 10 7 10 3 100 8 10 100 10 11 10 11 11 11 100 10 5 0 10 8 10 8 10 10 7 100 1 1 1 1 3 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 1 12 7 12 12 1 12 1 1 12 1 100 12 1 1 1 12 100 12 12 12 12 100 12 12 1 12 100 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -ciInstanceKlass java/io/ByteArrayInputStream 1 1 96 10 9 9 9 9 10 10 10 10 10 10 7 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 12 12 12 7 12 7 12 7 12 100 12 12 100 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -ciInstanceKlass java/net/URL 1 1 704 10 10 10 9 9 10 10 10 9 10 8 10 100 10 10 8 10 9 100 8 10 10 8 9 10 9 10 10 9 9 8 9 10 8 9 10 10 10 10 8 10 10 10 8 9 8 10 10 100 10 10 10 100 8 10 10 8 10 10 10 10 10 10 8 10 7 10 10 10 9 10 9 10 10 10 10 10 10 7 10 10 10 8 9 10 10 9 10 100 10 10 10 10 10 10 10 10 10 10 10 9 9 100 8 10 10 9 10 8 10 8 10 10 8 8 10 100 10 10 10 7 100 10 9 10 8 10 100 10 10 8 8 9 10 10 10 10 10 11 10 10 9 10 10 10 8 10 7 100 10 8 8 10 8 8 8 100 10 9 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 100 8 10 10 10 8 7 10 7 10 7 10 7 7 10 9 9 7 10 10 100 1 1 1 1 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 100 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 100 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 12 12 12 100 12 12 12 12 12 1 12 1 12 1 12 12 1 1 12 12 1 12 12 12 12 12 12 12 1 12 12 1 12 12 12 12 12 1 12 12 12 1 12 1 12 12 1 12 12 12 1 1 12 1 12 12 12 12 12 12 1 12 1 7 12 12 100 12 12 12 12 12 12 12 12 12 1 12 1 12 100 12 12 100 12 12 1 12 12 12 12 100 12 12 12 7 12 12 12 12 12 1 1 12 12 12 1 7 12 1 12 12 1 1 12 1 100 12 12 12 1 1 12 12 1 12 1 100 12 1 100 12 12 12 12 12 7 12 12 12 12 12 12 100 12 12 12 1 1 12 1 12 12 12 12 12 12 12 12 12 12 12 12 12 12 1 1 12 1 1 1 1 1 1 12 7 12 12 1 7 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield java/net/URL defaultFactory Ljava/net/URLStreamHandlerFactory; java/net/URL$DefaultFactory -staticfield java/net/URL streamHandlerLock Ljava/lang/Object; java/lang/Object -staticfield java/net/URL serialPersistentFields [Ljava/io/ObjectStreamField; 7 [Ljava/io/ObjectStreamField; -instanceKlass org/codehaus/plexus/archiver/jar/Manifest -instanceKlass org/codehaus/plexus/archiver/jar/Manifest -ciInstanceKlass java/util/jar/Manifest 1 1 299 10 7 10 9 7 10 9 9 10 10 10 10 10 11 11 10 10 100 100 10 8 10 10 10 10 11 7 10 10 11 11 11 11 100 7 8 10 11 7 8 10 10 10 10 8 10 10 11 10 10 10 8 10 7 10 10 10 100 8 10 10 8 10 10 10 10 11 10 10 10 100 7 10 11 10 11 10 7 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 1 12 1 12 12 12 12 12 12 12 7 12 12 100 12 1 1 1 12 12 12 12 1 12 12 12 7 12 12 12 1 1 1 12 1 1 12 12 12 12 1 12 12 12 12 12 1 12 1 12 12 12 1 1 12 1 12 100 12 12 12 12 12 7 12 12 1 1 12 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -ciInstanceKlass jdk/internal/loader/ClassLoaders 1 1 143 10 9 9 9 7 11 100 11 11 10 10 100 100 10 9 8 10 7 10 7 10 10 7 10 8 10 8 8 7 10 7 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 12 12 12 12 1 100 12 1 12 12 100 12 100 12 1 1 7 12 12 1 7 12 1 12 1 12 12 1 12 1 7 12 1 1 1 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield jdk/internal/loader/ClassLoaders JLA Ljdk/internal/misc/JavaLangAccess; java/lang/System$2 -staticfield jdk/internal/loader/ClassLoaders BOOT_LOADER Ljdk/internal/loader/ClassLoaders$BootClassLoader; jdk/internal/loader/ClassLoaders$BootClassLoader -staticfield jdk/internal/loader/ClassLoaders PLATFORM_LOADER Ljdk/internal/loader/ClassLoaders$PlatformClassLoader; jdk/internal/loader/ClassLoaders$PlatformClassLoader -staticfield jdk/internal/loader/ClassLoaders APP_LOADER Ljdk/internal/loader/ClassLoaders$AppClassLoader; jdk/internal/loader/ClassLoaders$AppClassLoader -instanceKlass jdk/internal/loader/ClassLoaders$BootClassLoader -instanceKlass jdk/internal/loader/ClassLoaders$PlatformClassLoader -instanceKlass jdk/internal/loader/ClassLoaders$AppClassLoader -ciInstanceKlass jdk/internal/loader/BuiltinClassLoader 1 1 762 10 10 9 9 7 10 9 9 10 10 11 100 100 10 10 8 10 10 7 10 10 11 11 11 7 9 8 8 10 10 9 11 7 10 10 10 10 10 10 10 11 10 100 10 10 10 100 8 10 10 8 10 10 11 11 7 7 10 11 11 10 7 10 10 7 7 10 7 7 10 10 100 10 11 7 100 10 10 100 100 10 10 18 10 10 18 100 10 7 10 10 10 10 10 9 100 10 10 10 10 10 10 10 10 10 10 18 7 10 10 10 10 100 10 7 10 10 10 11 7 10 7 100 10 10 11 10 10 10 10 10 10 10 10 8 10 10 10 100 8 8 10 10 8 8 10 11 9 10 9 9 9 9 9 9 10 8 10 10 10 10 8 7 8 10 10 10 10 7 10 9 8 8 10 7 7 10 11 10 10 10 100 10 10 10 7 10 10 8 10 7 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 7 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 100 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 7 7 1 1 1 1 1 1 1 1 7 7 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 7 12 12 12 12 1 12 12 12 12 12 12 1 1 12 1 12 12 1 12 12 7 12 12 12 1 12 1 1 12 7 12 12 12 1 12 12 12 7 12 12 12 12 12 7 12 1 7 12 12 1 1 12 1 12 12 12 12 1 1 12 12 1 12 12 1 1 12 1 1 12 7 12 1 12 12 1 1 12 12 1 1 12 12 1 15 16 15 16 12 12 12 15 16 1 7 12 1 12 12 12 12 12 1 12 12 12 12 12 12 12 12 12 15 16 12 1 12 12 12 12 1 12 100 1 1 12 12 12 12 1 12 1 12 12 12 12 12 12 12 12 12 12 12 1 12 12 12 1 1 1 12 1 1 7 12 7 12 7 12 12 12 12 12 12 12 12 12 1 12 12 12 12 1 1 1 12 12 7 12 1 12 7 12 1 1 12 1 1 12 12 12 12 1 12 12 1 12 12 1 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 10 10 1 1 1 1 10 1 1 1 1 1 1 1 1 1 1 1 1 1 10 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 12 12 12 12 1 1 100 1 1 100 1 1 -staticfield jdk/internal/loader/BuiltinClassLoader packageToModule Ljava/util/Map; java/util/concurrent/ConcurrentHashMap -staticfield jdk/internal/loader/BuiltinClassLoader $assertionsDisabled Z 1 -ciInstanceKlass jdk/internal/loader/ClassLoaders$AppClassLoader 1 1 134 8 10 9 10 10 10 10 10 10 7 8 10 10 10 9 11 10 10 100 10 7 7 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 12 12 7 12 100 12 12 12 12 12 1 1 12 7 12 100 12 12 100 12 12 7 12 1 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -ciInstanceKlass jdk/internal/loader/ClassLoaders$PlatformClassLoader 1 1 57 8 10 9 11 10 100 10 100 7 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 12 12 100 12 7 12 1 12 1 1 1 1 1 1 1 1 1 1 1 1 -ciInstanceKlass java/security/CodeSource 1 1 402 10 9 9 9 9 10 9 10 100 10 100 10 7 10 10 10 100 10 10 10 10 10 100 10 10 10 10 10 10 10 10 10 10 10 10 10 8 10 10 10 10 8 10 10 100 10 10 8 10 10 10 8 8 9 100 8 10 10 8 10 8 8 8 10 10 10 10 10 10 100 100 10 10 10 10 10 100 10 10 8 10 10 10 100 10 100 100 8 8 10 10 10 100 10 10 11 10 10 11 10 10 8 100 10 10 100 10 11 11 7 100 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 100 100 1 1 1 1 1 1 1 1 1 12 12 12 12 12 7 12 12 100 12 100 12 1 12 12 100 1 12 100 12 12 12 1 12 100 100 12 100 12 12 12 12 12 12 1 12 12 12 12 1 12 1 12 1 12 12 12 1 1 12 1 1 12 12 1 12 1 1 1 12 12 12 12 12 12 1 1 12 12 12 12 12 1 12 1 12 12 12 1 12 1 1 1 1 12 100 12 1 12 12 12 12 12 100 1 1 12 12 1 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -ciInstanceKlass java/lang/StackTraceElement 1 1 224 10 10 9 9 9 9 8 10 7 9 8 9 9 9 8 10 10 7 10 10 8 10 10 8 8 8 10 8 8 10 8 8 7 10 10 10 10 9 10 10 7 10 10 10 10 10 10 10 10 10 7 100 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 3 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 100 7 100 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 12 12 12 12 12 12 1 100 12 1 12 1 12 12 12 1 12 12 1 12 1 12 12 1 1 1 12 1 1 12 1 1 1 12 12 12 12 12 12 12 1 12 7 12 7 12 12 12 12 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -instanceKlass java/nio/IntBuffer -instanceKlass java/nio/LongBuffer -instanceKlass java/nio/CharBuffer -instanceKlass java/nio/ByteBuffer -ciInstanceKlass java/nio/Buffer 1 1 194 100 10 9 9 10 9 10 10 100 100 10 8 10 10 8 8 10 10 8 9 100 8 10 8 8 9 10 8 8 8 10 8 8 8 100 10 100 10 100 10 100 10 7 10 10 9 7 10 10 7 1 1 1 1 1 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 12 12 12 12 12 1 1 1 12 12 1 1 12 12 1 12 1 1 12 1 1 12 12 1 1 1 12 1 1 1 1 1 1 1 1 7 12 7 12 12 1 7 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield java/nio/Buffer UNSAFE Ljdk/internal/misc/Unsafe; jdk/internal/misc/Unsafe -staticfield java/nio/Buffer $assertionsDisabled Z 1 -ciInstanceKlass java/lang/StackWalker 0 0 235 9 10 100 10 10 11 10 10 100 10 100 8 10 10 10 10 9 9 9 9 10 9 10 11 100 8 10 10 9 10 10 10 18 100 8 10 10 10 9 11 10 100 100 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 100 12 1 100 12 12 100 12 12 12 1 12 1 1 12 12 12 12 12 12 12 12 12 12 100 12 12 1 1 12 12 12 100 12 100 12 1 15 16 15 16 12 1 1 12 100 12 12 100 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 10 10 1 1 1 1 1 1 1 1 1 1 1 1 100 12 12 1 1 100 1 1 100 1 1 -ciInstanceKlass java/lang/StackStreamFactory$AbstractStackWalker 1 0 306 100 100 3 10 10 10 9 10 9 9 9 9 9 10 10 9 10 10 9 9 100 10 8 10 10 8 10 10 100 8 10 8 10 9 10 9 8 5 0 8 8 9 10 10 10 9 10 10 10 10 10 10 8 10 10 10 10 8 100 10 10 10 10 10 10 9 8 10 10 10 10 10 10 10 10 10 10 8 100 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 100 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 100 12 12 12 12 12 12 12 100 12 100 12 12 12 12 12 12 100 12 1 1 12 12 1 12 100 12 1 1 12 1 12 100 12 12 12 1 1 1 12 12 12 12 12 12 12 12 12 12 12 1 12 12 12 12 1 1 12 12 12 12 12 100 12 12 1 12 12 12 12 12 12 12 12 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -instanceKlass java/lang/LiveStackFrameInfo -ciInstanceKlass java/lang/StackFrameInfo 0 0 140 10 9 9 100 9 9 9 11 9 11 10 10 10 11 11 11 10 10 10 10 11 10 9 10 100 8 10 10 100 100 1 1 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 100 1 1 1 1 1 12 12 12 1 12 12 12 100 12 12 12 12 100 12 12 12 12 12 12 12 12 12 12 12 12 12 1 1 12 100 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -ciInstanceKlass java/lang/LiveStackFrameInfo 0 0 97 10 9 9 9 9 9 100 10 10 8 10 100 8 8 8 10 100 10 100 10 100 100 100 1 1 1 1 1 1 1 1 3 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 12 12 12 12 12 12 1 12 12 1 12 1 1 1 1 1 12 1 12 1 1 1 1 1 1 1 1 1 -instanceKlass java/util/concurrent/locks/AbstractQueuedSynchronizer -ciInstanceKlass java/util/concurrent/locks/AbstractOwnableSynchronizer 1 1 32 10 9 7 7 100 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 1 1 1 -ciInstanceKlass java/lang/Boolean 1 1 128 10 9 10 10 8 10 9 9 8 10 7 10 10 100 100 10 10 8 10 9 7 100 100 1 1 1 1 1 1 1 1 1 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 12 12 1 12 12 12 1 12 1 12 7 12 1 1 12 12 1 7 12 12 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield java/lang/Boolean TRUE Ljava/lang/Boolean; java/lang/Boolean -staticfield java/lang/Boolean FALSE Ljava/lang/Boolean; java/lang/Boolean -staticfield java/lang/Boolean TYPE Ljava/lang/Class; java/lang/Class -ciInstanceKlass java/lang/Character 1 1 551 7 100 10 9 9 10 10 10 10 10 10 3 3 3 3 3 10 10 3 11 11 10 10 100 10 10 3 10 10 10 100 8 7 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 5 0 10 10 10 10 10 10 10 10 10 10 9 100 10 10 10 3 10 10 10 100 10 10 10 10 8 10 9 10 10 10 10 10 10 10 10 10 100 8 10 10 8 10 9 100 100 7 1 1 100 1 100 1 100 1 1 1 1 3 1 3 1 1 3 1 3 1 1 1 1 1 1 1 3 1 1 3 1 3 1 3 1 3 1 3 1 3 1 3 1 3 1 3 1 3 1 3 1 3 1 3 1 3 1 3 1 3 1 3 1 3 1 3 1 3 1 3 1 3 1 3 1 3 1 3 1 3 1 3 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 1 1 1 1 1 1 3 1 1 3 1 1 1 1 1 3 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 12 12 12 12 12 12 12 12 12 7 12 12 12 12 1 12 12 12 12 1 1 1 100 12 12 12 12 12 12 12 12 12 7 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 1 12 12 100 12 12 12 1 12 12 12 1 12 100 12 12 12 12 12 12 12 1 1 12 7 12 1 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield java/lang/Character TYPE Ljava/lang/Class; java/lang/Class -staticfield java/lang/Character $assertionsDisabled Z 1 -instanceKlass java/math/BigDecimal -instanceKlass java/math/BigInteger -instanceKlass java/util/concurrent/atomic/AtomicLong -instanceKlass java/util/concurrent/atomic/AtomicInteger -instanceKlass java/lang/Long -instanceKlass java/lang/Integer -instanceKlass java/lang/Short -instanceKlass java/lang/Byte -instanceKlass java/lang/Double -instanceKlass java/lang/Float -ciInstanceKlass java/lang/Number 1 1 37 10 10 100 7 100 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 1 1 1 -ciInstanceKlass java/lang/Float 1 1 192 7 100 10 10 4 100 10 10 8 8 10 10 10 10 4 4 4 10 9 10 10 10 10 10 10 3 10 10 10 10 8 10 9 7 100 1 1 1 1 1 4 1 1 1 4 1 1 3 1 3 1 3 1 3 1 1 1 1 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 12 100 12 1 12 12 1 1 100 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 1 7 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield java/lang/Float TYPE Ljava/lang/Class; java/lang/Class -ciInstanceKlass java/lang/Double 1 1 254 7 100 10 10 10 100 10 10 6 0 8 10 8 10 8 6 0 10 100 5 0 5 0 8 8 10 10 8 10 8 8 8 10 10 10 10 10 10 10 10 6 0 6 0 6 0 10 9 10 10 10 10 5 0 10 10 10 10 8 10 9 7 100 1 1 1 1 1 6 0 1 1 1 6 0 1 1 3 1 3 1 3 1 3 1 1 1 1 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 12 12 12 1 12 100 12 1 12 1 12 1 12 1 1 1 100 12 12 1 12 1 1 1 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 1 7 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield java/lang/Double TYPE Ljava/lang/Class; java/lang/Class -ciInstanceKlass java/lang/Byte 1 1 178 7 10 9 10 7 100 10 8 10 8 10 10 10 10 10 10 10 10 8 8 10 9 10 10 10 10 10 5 0 10 8 10 9 7 100 7 1 1 1 1 1 3 1 3 1 1 1 1 1 1 1 3 1 3 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 12 12 12 1 1 12 1 12 1 12 12 12 12 12 12 12 12 1 1 12 12 12 12 12 12 12 1 7 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield java/lang/Byte TYPE Ljava/lang/Class; java/lang/Class -ciInstanceKlass java/lang/Short 1 1 186 7 100 10 10 7 100 10 8 10 8 10 10 10 10 10 10 9 10 10 10 8 8 10 9 10 10 10 10 10 3 3 5 0 10 8 10 9 7 100 7 1 1 1 1 1 3 1 3 1 1 1 1 1 1 1 3 1 3 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 12 12 1 1 12 1 12 1 12 12 12 12 12 12 12 12 12 12 1 1 12 12 12 12 12 12 12 1 7 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield java/lang/Short TYPE Ljava/lang/Class; java/lang/Class -ciInstanceKlass java/lang/Integer 1 1 413 7 100 7 7 10 9 9 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 9 9 7 8 10 100 10 8 10 10 8 10 8 10 3 10 3 10 10 10 7 11 100 10 11 10 8 10 8 100 10 10 5 0 8 10 10 10 10 7 9 9 10 10 9 10 10 10 10 100 100 10 8 8 10 8 8 8 8 8 8 10 10 10 5 0 3 3 3 3 10 3 10 10 8 10 9 3 3 3 3 3 3 9 7 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 3 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 12 100 12 12 100 12 12 100 12 12 12 7 12 12 12 12 12 12 12 12 12 1 1 12 1 12 1 12 12 1 12 1 12 12 12 12 7 12 1 1 12 1 12 1 1 12 12 1 12 12 12 12 1 12 12 12 12 12 12 12 7 12 1 1 12 1 1 12 1 1 1 1 1 1 12 12 12 12 12 12 1 7 12 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield java/lang/Integer TYPE Ljava/lang/Class; java/lang/Class -staticfield java/lang/Integer digits [C 36 -staticfield java/lang/Integer DigitTens [B 100 -staticfield java/lang/Integer DigitOnes [B 100 -staticfield java/lang/Integer sizeTable [I 10 -ciInstanceKlass java/lang/Long 1 1 478 7 100 7 7 10 9 9 10 10 10 10 10 10 10 10 5 0 5 0 100 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 7 5 0 5 0 9 9 5 0 7 8 10 8 10 8 8 10 5 0 10 5 0 10 10 10 100 11 100 10 11 10 8 10 8 100 10 10 8 8 11 10 10 10 5 0 5 0 9 10 8 8 10 8 8 8 8 8 8 10 10 10 10 9 10 10 10 100 100 10 10 10 10 10 10 10 5 0 5 0 5 0 10 5 0 5 0 10 10 10 8 10 9 7 100 7 1 1 1 1 1 1 5 0 1 1 1 1 1 1 1 3 1 3 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 12 100 12 12 100 12 12 12 12 12 1 12 12 12 12 12 12 100 12 12 12 12 12 12 100 12 12 12 12 12 12 12 1 12 12 1 1 12 1 12 1 1 12 12 12 12 100 12 1 1 12 1 12 1 1 12 12 1 1 12 12 12 12 12 12 1 1 12 1 1 1 1 1 1 12 12 12 12 12 12 100 12 1 1 12 12 12 12 12 12 12 12 12 12 1 7 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield java/lang/Long TYPE Ljava/lang/Class; java/lang/Class -ciInstanceKlass java/lang/NullPointerException 1 1 26 10 10 100 7 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 12 12 1 1 -ciInstanceKlass java/lang/ArithmeticException 1 1 26 10 10 100 100 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 12 12 1 1 -ciInstanceKlass java/util/Collection 1 1 115 11 100 11 10 11 11 11 11 11 10 11 10 7 100 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 12 1 12 100 12 12 12 12 100 12 12 7 12 12 7 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -ciInstanceKlass java/util/Set 1 1 138 100 10 10 7 10 10 7 7 10 100 100 100 10 10 11 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 12 7 12 1 1 1 12 12 1 1 1 12 1 1 1 1 12 12 12 1 1 1 1 1 1 1 1 1 1 -instanceKlass java/util/concurrent/ConcurrentLinkedDeque -instanceKlass java/util/EnumMap$Values -instanceKlass java/util/WeakHashMap$Values -instanceKlass com/sun/tools/javac/util/List -instanceKlass java/util/AbstractMap$2 -instanceKlass org/eclipse/sisu/inject/MildElements -instanceKlass org/eclipse/sisu/inject/MildValues$1 -instanceKlass com/google/common/collect/AbstractMapBasedMultimap$WrappedCollection -instanceKlass com/google/common/collect/Maps$Values -instanceKlass com/google/common/collect/AbstractMultimap$Values -instanceKlass java/util/TreeMap$Values -instanceKlass com/google/common/collect/ImmutableCollection -instanceKlass java/util/IdentityHashMap$Values -instanceKlass java/util/AbstractQueue -instanceKlass java/util/LinkedHashMap$LinkedValues -instanceKlass java/util/HashMap$Values -instanceKlass java/util/ArrayDeque -instanceKlass java/util/AbstractList -instanceKlass java/util/AbstractSet -instanceKlass java/util/ImmutableCollections$AbstractImmutableCollection -ciInstanceKlass java/util/AbstractCollection 1 1 173 100 10 10 10 11 11 10 7 10 10 10 10 10 7 10 7 3 10 100 8 10 3 100 10 11 11 10 10 10 11 8 7 10 10 8 10 10 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 12 12 12 12 1 100 12 12 12 7 12 7 12 100 12 1 12 1 1 12 1 12 12 12 7 12 1 1 12 1 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -instanceKlass org/apache/maven/project/DefaultProjectBuilder$1 -instanceKlass java/util/Collections$SingletonMap -instanceKlass org/eclipse/sisu/wire/EntryMapAdapter -instanceKlass com/google/common/collect/Maps$ViewCachingAbstractMap -instanceKlass com/google/common/collect/MapMakerInternalMap -instanceKlass org/eclipse/sisu/wire/MergedProperties -instanceKlass com/google/common/cache/LocalCache -instanceKlass java/util/EnumMap -instanceKlass java/util/TreeMap -instanceKlass java/util/IdentityHashMap -instanceKlass java/util/WeakHashMap -instanceKlass java/util/ImmutableCollections$AbstractImmutableMap -instanceKlass java/util/Collections$EmptyMap -instanceKlass sun/util/PreHashedMap -instanceKlass java/util/concurrent/ConcurrentHashMap -instanceKlass java/util/HashMap -ciInstanceKlass java/util/AbstractMap 1 1 192 10 10 11 10 11 11 11 7 11 10 11 100 10 11 11 10 11 9 7 10 9 7 10 7 11 11 11 100 100 11 8 7 10 10 8 10 10 10 7 7 100 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 100 100 12 12 12 12 12 12 1 12 12 12 1 12 12 12 12 1 12 12 1 1 12 12 1 1 12 1 1 12 1 12 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -instanceKlass com/sun/tools/javac/comp/CompileStates -instanceKlass org/apache/maven/artifact/versioning/ManagedVersionMap -instanceKlass java/lang/ProcessEnvironment -instanceKlass java/util/LinkedHashMap -ciInstanceKlass java/util/HashMap 1 1 573 10 7 10 100 10 100 11 11 11 10 7 3 10 100 100 10 8 10 10 10 10 10 8 10 9 10 9 4 10 10 11 9 4 10 11 11 11 11 7 11 11 10 10 9 10 9 9 9 10 9 7 10 10 10 10 10 9 10 7 3 7 10 10 9 9 10 10 10 10 9 7 10 9 7 10 9 7 10 100 10 11 100 10 11 11 10 100 100 10 10 10 10 10 10 10 100 10 10 8 4 10 4 10 4 10 100 11 10 10 10 10 7 7 100 100 1 1 100 1 100 1 100 1 100 1 100 1 100 1 100 1 100 1 1 1 1 1 1 1 1 5 0 1 1 3 1 1 1 1 3 1 3 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 7 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 100 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 12 1 12 1 12 1 12 12 12 12 1 12 1 1 1 12 12 12 12 7 12 1 12 12 12 12 12 12 12 12 12 12 12 12 12 1 12 12 12 12 12 12 12 12 12 12 12 1 12 12 12 12 12 12 12 1 1 12 12 12 12 12 12 12 12 1 12 12 1 12 1 1 12 1 12 12 12 1 1 12 12 12 12 12 12 12 1 12 1 100 12 12 100 12 1 100 12 12 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -ciInstanceKlass java/util/Map$Entry 1 0 167 18 100 100 18 10 18 18 10 10 8 10 8 8 8 10 10 8 10 10 8 10 8 10 8 10 8 10 8 100 8 10 11 11 11 100 11 100 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 15 16 15 16 3 3 12 1 1 15 100 12 15 12 15 100 12 12 12 12 12 12 1 12 1 12 1 12 12 1 1 12 12 12 12 1 12 1 1 1 10 11 11 1 1 11 11 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 12 12 12 12 12 1 1 100 1 1 100 1 1 -ciInstanceKlass java/util/Arrays 1 1 1057 10 100 100 10 8 10 10 8 8 10 10 100 10 10 10 10 10 10 10 10 10 7 10 100 10 10 100 10 10 100 10 10 100 10 10 100 10 10 100 10 10 100 10 10 9 10 100 10 10 10 100 10 10 7 9 10 10 10 10 10 10 7 11 10 10 10 10 10 10 10 10 11 10 100 10 10 100 10 10 100 10 10 100 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 7 10 10 8 7 10 10 10 10 9 100 10 9 100 10 9 100 10 9 100 10 9 100 10 9 100 10 9 100 10 100 10 10 9 100 10 10 10 10 10 10 10 10 10 10 10 8 8 10 10 8 10 10 10 10 100 3 10 100 10 10 11 10 10 10 10 10 10 10 10 10 11 8 10 11 11 11 11 18 11 11 18 11 18 11 18 100 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 100 1 1 1 7 1 100 1 1 1 1 3 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 100 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 1 1 1 12 12 1 1 12 12 1 12 100 12 12 12 12 12 12 12 12 1 100 12 100 1 1 1 12 12 100 1 1 12 100 1 1 12 100 1 1 12 100 1 1 12 100 1 1 12 100 1 1 12 12 7 12 100 1 1 12 12 7 12 12 12 12 7 12 100 12 12 12 12 1 12 12 7 12 12 12 100 12 12 12 12 7 12 100 1 1 12 1 1 12 1 1 12 1 1 12 12 12 12 12 12 12 100 12 12 100 12 12 12 7 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 1 7 12 12 1 1 12 12 12 12 100 12 12 12 100 12 100 12 100 12 100 12 12 12 12 12 1 12 12 12 12 12 12 12 12 12 12 1 1 12 12 1 12 12 12 100 12 1 1 12 100 12 12 12 12 12 12 12 12 12 12 12 1 12 7 12 100 12 12 1 15 16 15 12 12 100 12 15 12 100 12 15 12 100 12 15 12 1 7 12 12 12 12 12 12 12 12 12 12 7 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 10 10 1 1 1 1 1 1 1 10 1 1 1 1 10 1 1 1 1 10 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 12 12 12 12 12 1 1 100 1 1 100 1 1 -staticfield java/util/Arrays $assertionsDisabled Z 1 -ciInstanceKlass java/lang/Math 1 1 381 10 10 10 10 10 10 10 7 6 0 6 0 10 10 10 10 10 10 10 10 10 10 10 10 100 3 3 3 10 100 5 0 5 0 5 0 5 0 5 0 9 10 100 8 10 8 10 10 100 5 0 5 0 100 3 5 0 3 5 0 10 10 10 9 9 10 7 6 0 10 9 100 10 10 100 10 10 10 10 10 10 6 0 10 10 10 10 7 4 10 10 10 10 10 10 10 10 10 10 10 5 0 6 0 4 6 0 4 6 0 4 10 9 10 9 10 4 6 0 100 100 1 1 1 1 1 6 0 1 6 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 7 12 12 12 12 12 12 1 12 12 12 12 12 12 12 12 12 12 12 12 1 12 1 12 100 12 1 1 12 1 12 12 1 1 12 12 12 12 12 12 1 12 12 1 12 1 12 12 12 12 12 12 12 12 12 12 1 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 7 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield java/lang/Math negativeZeroFloatBits J -2147483648 -staticfield java/lang/Math negativeZeroDoubleBits J -9223372036854775808 -staticfield java/lang/Math $assertionsDisabled Z 1 -instanceKlass java/util/LinkedHashMap$Entry -ciInstanceKlass java/util/HashMap$Node 1 1 95 10 9 9 9 9 100 10 10 8 10 10 10 100 11 10 11 7 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 12 12 12 12 12 1 12 1 12 12 7 12 100 1 12 12 12 1 1 1 1 1 1 1 1 1 1 1 -ciInstanceKlass java/util/List 1 1 212 10 11 11 11 11 11 11 10 7 100 10 100 10 10 7 10 10 7 7 10 10 100 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 100 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 12 12 12 12 100 12 12 12 100 12 1 100 1 1 1 12 1 7 12 7 12 1 1 12 12 1 1 1 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -instanceKlass com/sun/tools/javac/model/FilteredMemberList -instanceKlass org/eclipse/aether/util/graph/visitor/Stack -instanceKlass org/apache/maven/model/merge/ModelMerger$MergingList -instanceKlass java/util/ArrayList$SubList -instanceKlass sun/security/jca/ProviderList$3 -instanceKlass com/google/common/collect/Lists$TransformingRandomAccessList -instanceKlass java/util/Collections$SingletonList -instanceKlass java/util/AbstractSequentialList -instanceKlass java/util/Arrays$ArrayList -instanceKlass java/util/Vector -instanceKlass java/util/ArrayList -instanceKlass java/util/Collections$EmptyList -ciInstanceKlass java/util/AbstractList 1 1 218 10 9 10 10 100 10 10 11 11 11 10 10 11 11 11 10 10 11 11 11 7 10 7 10 10 100 100 10 100 10 100 100 10 8 10 10 10 10 8 100 8 8 8 10 100 11 10 10 11 10 8 8 7 7 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 12 12 12 12 1 12 12 12 12 12 12 12 12 12 12 12 100 12 1 12 1 12 12 1 1 12 1 1 1 1 12 12 12 12 1 1 1 1 1 1 12 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -ciInstanceKlass java/util/Iterator 1 1 53 100 8 10 10 11 11 11 7 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 7 12 12 12 7 12 1 1 1 1 1 1 1 1 1 1 -instanceKlass java/io/ExpiringCache$1 -ciInstanceKlass java/util/LinkedHashMap 1 1 280 9 9 9 9 10 7 10 10 9 9 9 10 7 10 10 10 10 9 9 10 10 10 10 10 10 10 10 9 10 9 7 10 9 7 10 9 7 10 100 10 11 100 10 11 7 7 100 100 1 1 100 1 100 1 100 1 1 1 1 1 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 12 12 12 1 12 12 12 12 12 12 1 12 12 12 12 12 100 12 12 12 12 12 12 12 12 12 12 1 12 12 1 12 1 1 7 12 1 100 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -ciInstanceKlass java/util/ImmutableCollections$List12 1 1 85 10 10 9 9 10 100 8 10 100 100 10 7 7 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 100 1 1 1 1 1 1 1 100 12 7 12 12 12 12 1 1 12 1 1 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -instanceKlass org/apache/maven/artifact/versioning/ComparableVersion$ListItem -instanceKlass org/eclipse/sisu/bean/BeanScheduler$Pending -ciInstanceKlass java/util/ArrayList 1 1 500 100 10 7 9 9 100 100 10 8 10 10 10 10 9 11 9 10 7 10 9 10 7 10 10 10 100 10 3 10 3 10 10 10 10 10 100 100 10 10 10 10 10 10 10 10 7 10 10 10 100 10 11 11 11 10 10 10 100 10 10 10 10 8 8 8 8 10 10 11 100 10 10 10 10 10 10 11 10 100 8 10 7 10 7 10 10 7 10 10 11 7 10 10 11 10 10 10 10 11 10 7 100 100 100 1 1 1 1 1 1 1 1 5 0 1 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 7 1 12 1 12 12 1 1 1 12 12 12 12 12 12 12 12 7 12 12 12 1 12 12 7 12 1 12 12 12 12 12 12 1 1 12 7 12 7 12 12 12 12 12 12 1 12 12 12 1 12 12 12 12 12 12 1 12 12 12 1 1 1 1 12 12 12 1 100 12 12 12 100 12 12 100 12 100 12 12 1 1 1 12 1 12 12 1 12 12 12 1 12 12 7 12 12 12 12 12 100 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield java/util/ArrayList EMPTY_ELEMENTDATA [Ljava/lang/Object; 0 [Ljava/lang/Object; -staticfield java/util/ArrayList DEFAULTCAPACITY_EMPTY_ELEMENTDATA [Ljava/lang/Object; 0 [Ljava/lang/Object; -ciInstanceKlass java/util/ImmutableCollections$ListN 1 1 93 10 7 10 9 10 100 8 10 100 10 7 10 9 7 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 100 1 1 1 1 1 1 1 1 1 100 12 1 7 12 12 12 1 1 12 1 12 1 12 12 1 1 1 1 1 1 1 1 1 1 -staticfield java/util/ImmutableCollections$ListN EMPTY_LIST Ljava/util/List; java/util/ImmutableCollections$ListN -instanceKlass java/util/HashMap$TreeNode -ciInstanceKlass java/util/LinkedHashMap$Entry 1 1 41 10 100 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 12 1 100 1 1 1 -instanceKlass java/util/ArrayList$ListItr -ciInstanceKlass java/util/ArrayList$Itr 1 1 103 9 10 9 9 9 9 9 10 100 10 9 100 10 100 10 10 100 10 10 11 7 7 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 12 12 12 12 12 12 12 12 1 12 1 1 12 1 100 12 12 100 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -ciInstanceKlass java/util/HashMap$EntrySet 1 1 133 9 10 9 10 7 10 100 11 10 10 10 11 10 100 10 100 10 9 9 11 9 100 10 7 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 100 1 1 1 1 1 100 12 12 12 12 1 1 12 100 1 12 12 12 12 12 12 1 1 12 1 12 12 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -ciInstanceKlass java/util/HashMap$EntryIterator 1 1 50 9 10 10 10 7 7 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 100 12 12 12 12 1 1 1 100 1 1 1 100 1 1 1 1 -ciInstanceKlass jdk/internal/loader/URLClassPath$JarLoader 1 1 547 7 7 8 8 7 10 10 8 10 10 10 10 9 9 9 9 9 10 9 10 8 10 10 7 10 10 100 10 100 10 9 9 11 8 10 10 10 7 10 10 100 10 10 7 7 10 100 10 10 10 10 8 10 10 8 9 10 100 10 100 10 9 10 10 10 10 100 100 7 10 10 10 10 11 11 100 10 10 10 10 10 7 10 10 10 10 7 10 100 10 10 7 100 10 10 10 10 11 10 100 8 10 10 11 10 10 9 10 10 100 10 10 10 10 9 10 10 100 9 10 10 10 10 10 10 10 8 10 100 9 9 8 8 10 10 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 100 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 12 12 1 12 12 12 12 12 12 12 12 12 12 12 12 1 12 12 1 12 7 12 1 12 1 7 12 12 12 100 12 1 12 12 12 1 12 1 12 1 1 1 12 12 12 12 1 12 12 1 12 100 12 1 12 1 12 12 12 12 7 12 12 1 1 1 12 12 12 12 12 12 1 12 12 12 12 12 1 12 12 12 1 12 100 12 100 12 1 1 12 12 12 12 12 12 1 1 7 12 7 12 12 100 12 100 12 100 12 12 1 12 12 12 12 12 100 12 12 12 100 12 12 12 12 12 1 12 1 12 12 1 1 100 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 -staticfield jdk/internal/loader/URLClassPath$JarLoader zipAccess Ljdk/internal/misc/JavaUtilZipFileAccess; java/util/zip/ZipFile$1 -instanceKlass java/nio/file/ReadOnlyFileSystemException -instanceKlass com/google/common/cache/CacheLoader$UnsupportedLoadingOperationException -ciInstanceKlass java/lang/UnsupportedOperationException 0 0 34 10 10 10 10 100 100 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 12 12 1 1 -ciInstanceKlass java/util/LinkedHashMap$LinkedValues 1 1 101 9 10 9 10 7 10 10 100 10 100 10 9 9 9 11 9 100 10 7 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 12 12 12 12 1 1 12 12 1 7 12 1 12 12 12 100 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -instanceKlass java/util/LinkedHashMap$LinkedEntryIterator -instanceKlass java/util/LinkedHashMap$LinkedKeyIterator -instanceKlass java/util/LinkedHashMap$LinkedValueIterator -ciInstanceKlass java/util/LinkedHashMap$LinkedHashIterator 1 1 89 9 10 9 9 9 9 9 100 10 100 10 9 100 10 9 9 10 7 7 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 7 12 12 12 12 12 12 12 1 1 12 1 12 12 12 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 -ciInstanceKlass java/util/LinkedHashMap$LinkedValueIterator 1 1 46 9 10 10 9 7 7 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 12 12 12 7 12 1 1 1 1 1 1 1 1 1 1 -ciInstanceKlass org/codehaus/plexus/util/xml/Xpp3Dom 1 1 371 7 10 9 7 10 9 10 9 10 10 10 10 10 10 10 10 10 10 10 10 9 9 11 9 11 11 100 11 7 10 11 100 8 10 8 7 10 11 11 11 11 11 11 10 10 11 11 9 11 7 10 10 11 11 11 10 11 11 9 100 10 10 10 100 8 8 10 10 10 11 10 8 8 10 11 11 7 8 10 10 11 11 10 11 11 100 10 100 8 10 10 10 10 10 7 100 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 8 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 1 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 7 12 12 1 100 12 12 1 1 1 1 12 7 12 12 12 12 12 12 12 12 12 12 7 12 12 12 12 12 12 12 1 12 100 12 12 1 1 1 12 12 12 1 1 12 12 12 1 1 12 12 12 1 1 1 12 12 12 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -staticfield org/codehaus/plexus/util/xml/Xpp3Dom EMPTY_STRING_ARRAY [Ljava/lang/String; 0 [Ljava/lang/String; -staticfield org/codehaus/plexus/util/xml/Xpp3Dom EMPTY_DOM_ARRAY [Lorg/codehaus/plexus/util/xml/Xpp3Dom; 0 [Lorg/codehaus/plexus/util/xml/Xpp3Dom; -ciInstanceKlass java/util/NoSuchElementException 0 0 26 10 10 100 100 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 12 12 1 1 -ciInstanceKlass java/util/LinkedHashMap$LinkedEntrySet 1 1 136 9 10 9 10 7 10 100 11 10 10 10 11 10 100 10 100 10 9 9 11 9 100 10 7 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 100 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 100 12 12 12 12 1 1 12 100 1 12 100 12 12 12 12 12 1 100 12 1 12 12 100 12 12 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -ciInstanceKlass java/util/LinkedHashMap$LinkedEntryIterator 1 1 49 9 10 10 10 7 7 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 100 12 12 12 12 1 1 1 100 1 1 1 100 1 1 1 -instanceKlass org/apache/maven/model/Profile -instanceKlass org/apache/maven/model/Model -ciInstanceKlass org/apache/maven/model/ModelBase 1 1 320 10 7 12 1 1 1 10 7 12 1 1 1 11 7 12 1 1 1 10 12 1 10 12 1 10 12 1 1 10 7 12 1 1 1 10 12 1 10 12 1 1 9 12 1 1 7 1 10 11 12 1 1 9 12 1 1 10 7 12 1 1 9 12 1 1 10 9 12 1 1 10 7 12 1 1 9 12 1 11 12 1 1 11 7 12 1 1 1 11 12 1 7 1 10 12 1 9 12 1 7 1 10 12 1 9 12 1 9 12 1 1 100 1 10 12 1 9 12 1 1 10 7 12 1 1 9 12 1 1 7 1 10 12 1 100 1 100 1 100 1 10 10 12 1 1 10 100 12 1 1 1 10 12 1 1 8 1 10 12 1 10 12 1 10 12 1 1 100 1 7 1 10 12 1 1 8 1 10 12 1 8 8 8 8 8 8 8 8 8 9 12 1 1 9 12 1 9 12 1 9 12 1 9 12 1 9 12 1 9 12 1 9 12 1 9 12 1 9 12 1 10 12 1 1 10 12 1 1 10 11 7 1 11 12 1 1 7 1 10 11 12 1 10 12 1 100 1 100 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 -ciInstanceKlass org/apache/maven/model/Model 1 1 402 10 7 12 1 1 1 8 1 9 7 12 1 1 1 8 1 9 12 1 10 12 1 1 11 7 12 1 1 1 10 12 1 10 12 1 10 12 1 10 12 1 10 12 1 1 9 12 1 1 10 7 12 1 1 9 12 1 1 10 7 12 1 1 9 12 1 1 7 1 10 11 12 1 1 11 7 12 1 1 1 11 12 1 1 7 1 10 12 1 9 12 1 7 1 10 12 1 9 12 1 7 1 10 12 1 9 12 1 7 1 10 12 1 9 12 1 1 10 7 12 1 1 9 12 1 1 10 7 12 1 1 9 12 1 1 10 7 12 1 1 9 12 1 1 10 7 12 1 1 9 12 1 1 10 7 12 1 1 9 12 1 7 1 10 12 1 10 12 1 1 100 1 100 1 7 1 10 10 100 12 1 1 1 10 100 12 1 1 1 10 12 1 1 8 1 10 12 1 10 12 1 10 12 1 1 100 1 9 12 1 9 12 1 9 12 1 9 12 1 9 12 1 9 12 1 9 12 1 9 12 1 9 12 1 11 12 1 9 12 1 1 10 7 12 1 1 1 10 12 1 10 12 1 10 12 1 8 1 8 1 10 12 1 10 12 1 10 12 1 10 12 1 10 100 12 1 1 1 10 100 12 1 1 1 10 12 1 100 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 -ciInstanceKlass org/apache/maven/model/Dependency 1 1 281 10 7 12 1 1 1 8 1 9 7 12 1 1 1 10 12 1 1 11 7 12 1 1 1 10 12 1 1 9 12 1 1 7 1 10 11 12 1 1 11 7 12 1 1 1 11 12 1 7 1 10 12 1 9 12 1 1 100 1 10 12 1 100 1 100 1 7 1 10 10 12 1 1 10 100 12 1 1 1 10 12 1 1 8 1 10 12 1 10 12 1 10 12 1 1 100 1 9 12 1 9 12 1 9 12 1 7 1 10 12 1 1 8 1 10 12 1 8 8 8 1 8 8 8 1 8 1 8 8 1 9 12 1 1 9 12 1 9 12 1 9 12 1 9 12 1 9 12 1 9 12 1 9 12 1 9 12 1 9 12 1 10 12 1 1 9 12 10 12 1 1 10 11 100 12 1 1 1 11 12 1 1 100 1 9 12 9 12 9 12 11 12 1 10 7 12 1 1 1 10 12 1 1 8 1 8 1 8 1 8 1 8 1 9 12 1 8 1 10 12 1 100 1 100 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 -ciInstanceKlass org/apache/maven/model/Plugin 1 1 269 10 7 12 1 1 1 8 1 9 7 12 1 1 1 9 12 1 1 10 12 1 1 11 7 12 1 1 1 10 12 1 10 12 1 1 9 12 1 1 7 1 10 11 12 1 1 11 7 12 1 1 1 11 12 1 1 7 1 10 12 1 9 12 1 7 1 10 12 1 9 12 1 1 7 1 10 12 1 100 1 100 1 7 1 10 10 100 12 1 1 1 10 100 12 1 1 1 10 12 1 1 8 1 10 12 1 10 12 1 10 12 1 1 100 1 9 12 1 9 12 1 9 12 1 11 12 1 10 100 12 1 1 1 10 7 12 1 1 1 100 1 10 10 12 1 11 100 12 1 1 100 1 8 1 8 1 10 12 1 8 1 10 11 12 1 1 10 12 1 10 12 1 8 1 8 1 10 12 1 8 1 10 12 1 8 1 10 12 1 1 10 12 1 10 12 1 1 8 1 8 1 10 12 1 100 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 -instanceKlass org/apache/maven/model/DeploymentRepository -ciInstanceKlass org/apache/maven/model/Repository 1 1 89 10 7 12 1 1 1 10 12 1 1 7 1 9 12 1 1 10 7 12 1 1 9 12 1 100 1 100 1 100 1 10 10 100 12 1 1 1 10 100 12 1 1 1 10 12 1 1 8 1 10 12 1 10 12 1 10 12 1 1 100 1 10 12 1 100 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 -instanceKlass org/apache/maven/model/PluginManagement -instanceKlass org/apache/maven/model/PluginConfiguration -ciInstanceKlass org/apache/maven/model/PluginContainer 1 1 192 10 7 12 1 1 1 10 7 12 1 1 1 11 7 12 1 1 1 10 12 1 1 9 12 1 1 7 1 10 11 12 1 1 11 7 12 1 1 1 11 12 1 7 1 10 12 1 9 12 1 1 7 1 10 12 1 100 1 100 1 100 1 10 10 12 1 1 10 100 12 1 1 1 10 12 1 1 8 1 10 12 1 10 12 1 10 12 1 1 100 1 7 1 10 12 1 1 8 1 10 12 1 8 9 12 1 1 9 12 1 10 12 1 1 10 12 1 1 10 11 7 12 1 1 1 11 12 1 1 7 1 11 12 1 9 12 1 10 12 1 8 1 10 12 1 100 1 100 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 -instanceKlass org/apache/maven/model/BuildBase -ciInstanceKlass org/apache/maven/model/PluginConfiguration 1 1 89 10 7 12 1 1 1 10 12 1 1 7 1 9 12 1 1 10 7 12 1 1 100 1 100 1 100 1 10 10 100 12 1 1 1 10 100 12 1 1 1 10 12 1 1 8 1 10 12 1 10 12 1 10 12 1 1 100 1 8 1 10 8 1 10 12 1 100 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 -instanceKlass org/apache/maven/model/Build -ciInstanceKlass org/apache/maven/model/BuildBase 1 1 171 10 7 12 1 1 1 10 7 12 1 1 1 11 7 12 1 1 1 10 12 1 10 12 1 10 12 1 1 9 12 1 1 7 1 10 11 12 1 1 11 7 12 1 1 1 11 12 1 1 7 1 10 12 1 9 12 1 9 12 1 11 12 1 1 100 1 100 1 100 1 10 10 100 12 1 1 1 10 100 12 1 1 1 10 12 1 1 8 1 10 12 1 10 12 1 10 12 1 1 100 1 9 12 1 1 9 12 1 9 12 1 11 12 1 8 1 10 8 1 10 12 1 100 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 -ciInstanceKlass org/apache/maven/model/Build 1 1 156 10 7 12 1 1 1 10 7 12 1 1 1 11 7 12 1 1 1 10 12 1 1 9 12 1 1 7 1 10 11 12 1 1 11 7 12 1 1 1 11 12 1 1 7 1 10 12 1 100 1 100 1 100 1 10 10 100 12 1 1 1 10 100 12 1 1 1 10 12 1 1 8 1 10 12 1 10 12 1 10 12 1 1 100 1 9 12 1 1 9 12 1 9 12 1 9 12 1 9 12 1 11 12 1 8 1 10 8 1 10 12 1 100 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 -ciInstanceKlass org/apache/maven/model/PluginManagement 1 1 72 10 7 12 1 1 1 10 12 1 1 7 1 100 1 100 1 100 1 10 10 100 12 1 1 1 10 100 12 1 1 1 10 12 1 1 8 1 10 12 1 10 12 1 10 12 1 1 100 1 10 12 1 100 1 100 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 -ciInstanceKlass org/apache/maven/model/Reporting 1 1 222 10 7 12 1 1 1 10 7 12 1 1 1 11 7 12 1 1 1 10 12 1 1 9 12 1 1 7 1 10 11 12 1 1 11 7 12 1 1 1 11 12 1 7 1 10 12 1 9 12 1 1 100 1 10 12 1 100 1 100 1 100 1 10 10 12 1 1 10 100 12 1 1 1 10 12 1 1 8 1 10 12 1 10 12 1 10 12 1 1 100 1 9 12 1 1 7 1 10 12 1 1 8 1 10 12 1 8 8 1 8 9 12 1 1 9 12 1 9 12 1 9 12 1 10 12 1 1 10 12 1 1 10 11 100 12 1 1 1 11 12 1 1 100 1 9 12 11 12 1 10 100 12 1 1 1 10 12 1 1 9 12 1 10 12 1 10 12 1 100 1 100 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 -ciInstanceKlass org/apache/maven/model/Profile 1 1 126 10 7 12 1 1 1 8 1 9 7 12 1 1 1 8 1 9 12 1 10 12 1 1 9 12 1 1 10 7 12 1 1 9 12 1 1 10 7 12 1 1 100 1 100 1 100 1 10 10 100 12 1 1 1 10 100 12 1 1 1 10 12 1 1 8 1 10 12 1 10 12 1 10 12 1 1 100 1 8 1 10 12 1 8 1 10 12 1 8 1 10 12 1 100 1 100 1 1 1 1 8 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 -ciInstanceKlass org/apache/maven/model/ActivationProperty 1 1 141 10 7 12 1 1 1 10 12 1 1 7 1 9 12 1 1 100 1 10 12 1 100 1 100 1 100 1 10 10 12 1 1 10 100 12 1 1 1 10 12 1 1 8 1 10 12 1 10 12 1 10 12 1 1 100 1 7 1 10 12 1 1 8 1 10 12 1 1 8 1 8 1 9 12 1 1 9 12 1 9 12 1 10 12 1 1 9 12 1 10 12 1 1 10 11 100 12 1 1 1 11 12 1 1 100 1 9 12 10 12 1 100 1 100 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 -ciInstanceKlass org/apache/maven/model/Activation 1 1 193 10 7 12 1 1 1 9 7 12 1 1 1 10 12 1 1 9 12 1 1 10 7 12 1 1 9 12 1 1 10 7 12 1 1 9 12 1 1 10 7 12 1 1 9 12 1 1 100 1 10 12 1 100 1 100 1 100 1 10 10 12 1 1 10 100 12 1 1 1 10 12 1 1 8 1 10 12 1 10 12 1 10 12 1 1 100 1 9 12 1 1 7 1 10 12 1 1 8 1 10 12 1 1 8 8 8 8 8 9 12 1 1 9 12 1 9 12 1 9 12 1 9 12 1 9 12 1 10 12 1 1 10 12 1 1 10 11 100 12 1 1 1 11 12 1 1 100 1 10 12 1 100 1 100 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 -ciInstanceKlass org/apache/maven/model/ActivationFile 1 1 142 10 7 12 1 1 1 10 12 1 1 7 1 9 12 1 1 100 1 10 12 1 100 1 100 1 100 1 10 10 12 1 1 10 100 12 1 1 1 10 12 1 1 8 1 10 12 1 10 12 1 10 12 1 1 100 1 9 12 1 1 7 1 10 12 1 1 8 1 10 12 1 1 8 1 8 9 12 1 1 9 12 1 9 12 1 10 12 1 1 9 12 10 12 1 1 10 11 100 12 1 1 1 11 12 1 1 100 1 10 12 1 100 1 100 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 -ciInstanceKlass org/apache/maven/model/ActivationOS 1 1 159 10 7 12 1 1 1 10 12 1 1 7 1 9 12 1 1 100 1 10 12 1 100 1 100 1 100 1 10 10 12 1 1 10 100 12 1 1 1 10 12 1 1 8 1 10 12 1 10 12 1 10 12 1 1 100 1 9 12 1 1 9 12 1 100 1 10 12 1 1 8 1 10 12 1 1 8 1 8 8 8 1 9 12 1 1 9 12 1 9 12 1 9 12 1 9 12 1 10 12 1 1 9 12 10 12 1 1 10 11 100 12 1 1 1 11 12 1 1 100 1 9 12 10 12 1 100 1 100 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 -ciInstanceKlass org/apache/maven/model/InputLocation 1 1 217 10 7 12 1 1 1 9 7 12 1 1 1 9 12 1 9 12 1 1 10 12 1 1 9 12 1 1 7 1 10 12 1 100 1 100 1 100 1 10 10 12 1 1 10 100 12 1 1 1 10 12 1 1 8 1 10 12 1 10 12 1 10 12 1 1 100 1 7 1 10 12 1 1 8 1 10 12 1 1 9 12 1 1 10 12 1 1 10 12 1 1 10 11 7 12 1 1 1 11 12 1 1 10 12 1 10 12 1 10 12 1 1 10 12 1 10 12 1 1 11 12 1 10 12 1 11 100 12 1 1 1 11 100 12 1 1 1 11 12 1 100 1 10 12 1 10 12 1 1 11 12 1 10 12 1 8 1 8 1 10 12 1 10 12 1 100 1 100 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 100 1 1 -ciInstanceKlass java/util/ConcurrentModificationException 0 0 34 10 10 10 10 100 100 1 1 1 5 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 12 12 12 12 1 1 -instanceKlass org/apache/maven/model/FileSet -ciInstanceKlass org/apache/maven/model/PatternSet 1 1 213 10 7 12 1 1 1 10 7 12 1 1 1 11 7 12 1 1 1 10 12 1 10 12 1 1 9 12 1 1 7 1 10 11 12 1 1 9 12 1 9 12 1 1 7 1 10 12 1 100 1 100 1 100 1 10 10 12 1 1 10 100 12 1 1 1 10 12 1 1 8 1 10 12 1 10 12 1 10 12 1 1 100 1 7 1 10 12 1 1 8 1 10 12 1 8 8 9 12 1 1 9 12 1 9 12 1 10 12 1 1 10 12 1 1 10 11 7 12 1 1 1 11 12 1 1 100 1 11 12 1 10 12 1 8 1 11 12 1 1 11 100 12 1 1 1 11 12 1 8 1 10 12 1 10 12 1 1 10 12 1 1 8 1 8 1 10 12 1 100 1 100 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 -instanceKlass org/apache/maven/model/Resource -ciInstanceKlass org/apache/maven/model/FileSet 1 1 87 10 7 12 1 1 1 10 12 1 1 7 1 100 1 100 1 100 1 10 10 100 12 1 1 1 10 100 12 1 1 1 10 12 1 1 8 1 10 12 1 10 12 1 10 12 1 1 100 1 9 12 1 1 8 1 10 12 1 8 1 10 8 1 10 12 1 100 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 -ciInstanceKlass org/apache/maven/model/Resource 1 1 136 10 7 12 1 1 1 10 12 1 1 7 1 100 1 100 1 100 1 10 10 100 12 1 1 1 10 100 12 1 1 1 10 12 1 1 8 1 10 12 1 10 12 1 10 12 1 1 100 1 9 12 1 1 9 12 1 9 12 1 10 12 1 8 1 9 12 1 1 10 12 1 10 12 1 10 100 12 1 1 1 10 100 12 1 1 1 8 1 10 12 1 8 1 10 12 1 1 10 12 1 8 1 10 8 1 10 12 1 100 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 -ciInstanceKlass org/apache/maven/model/DependencyManagement 1 1 176 10 7 12 1 1 1 10 7 12 1 1 1 11 7 12 1 1 1 10 12 1 1 9 12 1 1 7 1 10 11 12 1 1 11 7 12 1 1 1 11 12 1 7 1 10 12 1 9 12 1 1 100 1 10 12 1 100 1 100 1 100 1 10 10 12 1 1 10 100 12 1 1 1 10 12 1 1 8 1 10 12 1 10 12 1 10 12 1 1 100 1 7 1 10 12 1 1 8 1 10 12 1 8 9 12 1 1 9 12 1 10 12 1 1 10 12 1 1 10 11 100 12 1 1 1 11 12 1 1 100 1 11 12 1 10 12 1 100 1 100 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 -ciInstanceKlass org/apache/maven/model/DistributionManagement 1 1 199 10 7 12 1 1 1 10 12 1 1 7 1 9 12 1 1 10 7 12 1 1 9 12 1 9 12 1 1 10 7 12 1 1 9 12 1 1 10 100 12 1 1 9 12 1 1 100 1 10 12 1 100 1 100 1 100 1 10 10 12 1 1 10 100 12 1 1 1 10 12 1 1 8 1 10 12 1 10 12 1 10 12 1 1 100 1 9 12 1 1 7 1 10 12 1 1 8 1 10 12 1 1 8 8 8 8 8 8 1 9 12 1 1 9 12 1 9 12 1 9 12 1 9 12 1 9 12 1 9 12 1 10 12 1 1 10 12 1 1 10 11 100 12 1 1 1 11 12 1 1 100 1 9 12 10 12 1 100 1 100 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 -ciInstanceKlass org/apache/maven/model/merge/ModelMerger$MergingList 1 1 176 10 7 12 1 1 1 7 1 10 12 1 9 7 12 1 1 1 9 12 1 1 100 1 10 12 1 11 7 12 1 1 1 11 7 12 1 1 1 9 12 1 1 11 100 1 11 12 1 1 11 11 7 12 1 1 1 11 12 1 1 11 7 12 1 1 1 11 12 1 1 11 12 1 1 11 7 1 7 1 11 12 1 11 12 1 11 12 1 11 7 12 1 1 10 12 1 1 11 12 1 11 12 1 10 12 1 1 11 12 1 1 11 12 1 11 12 11 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 1 -ciMethod java/lang/Object ()V 4097 1 2833602 0 0 -ciMethod java/lang/Object getClass ()Ljava/lang/Class; 2049 1 256 0 -1 -ciMethod java/lang/Object clone ()Ljava/lang/Object; 2049 1 256 0 -1 -ciMethod java/lang/System arraycopy (Ljava/lang/Object;ILjava/lang/Object;II)V 3073 1 384 0 -1 -ciMethod java/util/Properties clone ()Ljava/lang/Object; 521 1 2021 0 -1 -ciMethod java/util/Map size ()I 0 0 1 0 -1 -ciMethod java/util/Map values ()Ljava/util/Collection; 0 0 1 0 -1 -ciMethod java/util/Map entrySet ()Ljava/util/Set; 0 0 1 0 -1 -ciMethod java/lang/StringBuilder ()V 689 1 147920 0 -1 -ciMethod java/lang/StringBuilder append (Ljava/lang/String;)Ljava/lang/StringBuilder; 1425 1 481540 0 -1 -ciMethod java/lang/StringBuilder toString ()Ljava/lang/String; 729 1 133820 0 -1 -ciMethod java/util/Collection iterator ()Ljava/util/Iterator; 0 0 1 0 -1 -ciMethod java/util/Collection toArray ()[Ljava/lang/Object; 0 0 1 0 -1 -ciMethod java/util/Set iterator ()Ljava/util/Iterator; 0 0 1 0 -1 -ciMethod java/util/AbstractCollection ()V 2385 1 741223 0 0 -ciMethod java/util/HashMap hash (Ljava/lang/Object;)I 4097 1 188004 0 -1 -ciMethod java/util/HashMap tableSizeFor (I)I 2049 1 10628 0 -1 -ciMethod java/util/HashMap ()V 2689 1 73315 0 64 -ciMethod java/util/HashMap putMapEntries (Ljava/util/Map;Z)V 1937 1001 5811 0 3392 -ciMethod java/util/HashMap putVal (ILjava/lang/Object;Ljava/lang/Object;ZZ)Ljava/lang/Object; 3217 113 19004 0 -1 -ciMethod java/util/HashMap resize ()[Ljava/util/HashMap$Node; 569 1273 1853 0 -1 -ciMethod java/util/AbstractMap ()V 3073 1 95653 0 0 -ciMethod java/util/Map$Entry getKey ()Ljava/lang/Object; 0 0 1 0 -1 -ciMethod java/util/Map$Entry getValue ()Ljava/lang/Object; 0 0 1 0 -1 -ciMethod java/util/Arrays copyOf ([Ljava/lang/Object;I)[Ljava/lang/Object; 769 1 32838 0 0 -ciMethod java/util/Arrays copyOf ([Ljava/lang/Object;ILjava/lang/Class;)[Ljava/lang/Object; 1089 1 5405 0 -1 -ciMethod java/lang/Math max (II)I 3281 1 100523 0 -1 -ciMethod java/util/List iterator ()Ljava/util/Iterator; 0 0 1 0 -1 -ciMethod java/util/List add (Ljava/lang/Object;)Z 0 0 1 0 -1 -ciMethod java/util/List addAll (Ljava/util/Collection;)Z 0 0 1 0 -1 -ciMethod java/util/AbstractList ()V 1657 1 347719 0 64 -ciMethod java/util/Iterator hasNext ()Z 0 0 1 0 -1 -ciMethod java/util/Iterator next ()Ljava/lang/Object; 0 0 1 0 -1 -ciMethodData java/lang/Object ()V 2 2833613 orig 320 144 166 185 254 252 127 0 0 16 6 178 223 9 2 0 0 88 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 105 214 89 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 3 0 1 0 0 0 0 0 0 0 0 0 0 0 254 255 255 255 0 0 0 0 0 0 0 0 data 4 0x0 0x9 0x1 0x0 oops 0 methods 0 -ciMethod java/util/LinkedHashMap (Ljava/util/Map;)V 1889 1 9859 0 0 -ciMethod java/util/LinkedHashMap values ()Ljava/util/Collection; 2057 1 8367 0 384 -ciMethod java/util/ArrayList ()V 945 1 320776 0 256 -ciMethod java/util/ArrayList grow (I)[Ljava/lang/Object; 321 1 25998 0 0 -ciMethod java/util/ArrayList grow ()[Ljava/lang/Object; 321 1 21866 0 0 -ciMethod java/util/ArrayList newCapacity (I)I 329 1 5235 0 160 -ciMethod java/util/ArrayList hugeCapacity (I)I 0 0 1 0 -1 -ciMethod java/util/ArrayList add (Ljava/lang/Object;[Ljava/lang/Object;I)V 2089 1 113179 0 0 -ciMethod java/util/ArrayList add (Ljava/lang/Object;)Z 2089 1 113179 0 1184 -ciMethod java/util/ArrayList addAll (Ljava/util/Collection;)Z 17 1 5285 0 1536 -ciMethod java/util/ArrayList iterator ()Ljava/util/Iterator; 2065 1 7132 0 192 -ciMethodData java/util/AbstractCollection ()V 2 741226 orig 320 144 166 185 254 252 127 0 0 160 195 195 223 9 2 0 0 112 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 42 1 0 0 1 114 90 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 3 0 2 0 0 0 0 0 0 0 16 0 0 0 254 255 255 255 2 0 1 0 0 0 0 0 data 7 0x10002 0xb4e40 0x0 0x0 0x9 0x1 0x0 oops 0 methods 0 -ciMethod java/util/ArrayList$Itr (Ljava/util/ArrayList;)V 2065 1 14761 0 0 -ciMethod java/util/ArrayList$Itr hasNext ()Z 2057 1 5383 0 96 -ciMethod java/util/ArrayList$Itr next ()Ljava/lang/Object; 2049 1 5507 0 256 -ciMethod java/util/ArrayList$Itr checkForComodification ()V 2049 1 12539 0 0 -ciMethodData java/util/AbstractMap ()V 2 95664 orig 320 144 166 185 254 252 127 0 0 72 178 196 223 9 2 0 0 112 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 128 1 0 0 129 161 11 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 3 0 2 0 0 0 0 0 0 0 16 0 0 0 254 255 255 255 2 0 1 0 0 0 0 0 data 7 0x10002 0x17430 0x0 0x0 0x9 0x1 0x0 oops 0 methods 0 -ciMethodData java/util/ArrayList add (Ljava/lang/Object;)Z 2 113179 orig 320 144 166 185 254 252 127 0 0 96 71 217 223 9 2 0 0 192 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 1 0 0 177 200 13 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 7 0 2 0 0 0 0 0 0 0 56 0 0 0 254 255 255 255 5 0 20 0 0 0 0 0 data 17 0x140005 0x1b913 0x0 0x209f05afbc0 0x3 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x9 0x2 0xe 0x0 oops 1 3 java/util/ArrayList methods 0 -ciMethodData java/util/ArrayList add (Ljava/lang/Object;[Ljava/lang/Object;I)V 2 113180 orig 320 144 166 185 254 252 127 0 0 144 70 217 223 9 2 0 0 40 2 0 0 32 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 1 0 0 185 200 13 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 6 0 2 0 0 0 0 0 0 0 144 0 0 0 254 255 255 255 7 0 3 0 0 0 0 0 data 30 0x30007 0x1643e 0x58 0x54d9 0x70005 0x54d7 0x0 0x209f05afbc0 0x2 0x0 0x0 0xe0104 0x0 0x0 0x209e04ed750 0xc2c 0x209e9593f10 0x22 0x0 0x0 0x0 0x0 0x0 0x0 0x9 0x4 0xc 0x0 0xffffffffffffffff 0x0 oops 3 7 java/util/ArrayList 14 java/lang/Integer 16 jdk/internal/loader/URLClassPath$JarLoader methods 0 -ciMethodData java/util/ArrayList grow ()[Ljava/lang/Object; 2 21866 orig 320 144 166 185 254 252 127 0 0 240 55 217 223 9 2 0 0 184 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 40 0 0 0 17 170 2 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 56 0 0 0 254 255 255 255 5 0 7 0 0 0 0 0 data 16 0x70005 0x552a 0x0 0x209f05afbc0 0x18 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x9 0x1 0xc oops 1 3 java/util/ArrayList methods 0 -ciMethodData java/util/ArrayList grow (I)[Ljava/lang/Object; 2 25999 orig 320 144 166 185 254 252 127 0 0 64 55 217 223 9 2 0 0 208 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 40 0 0 0 57 43 3 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 3 0 2 0 0 0 0 0 0 0 72 0 0 0 254 255 255 255 5 0 7 0 0 0 0 0 data 19 0x70005 0x6502 0x0 0x209f05afbc0 0x65 0x0 0x0 0xa0002 0x6567 0x0 0x0 0x0 0x0 0x0 0x0 0x9 0x2 0xc 0x0 oops 1 3 java/util/ArrayList methods 0 -ciMethodData java/util/ArrayList newCapacity (I)I 2 5235 orig 320 144 166 185 254 252 127 0 0 8 57 217 223 9 2 0 0 80 2 0 0 160 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 25 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 41 0 0 0 81 162 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 21 0 2 0 0 0 0 0 0 0 200 0 0 0 254 255 255 255 7 0 15 0 0 0 0 0 data 35 0xf0007 0x250 0x80 0x11fa 0x190007 0x29 0x30 0x11d1 0x1f0002 0x11d1 0x240007 0x29 0x30 0x0 0x2b0002 0x0 0x350007 0x0 0x38 0x250 0x390003 0x250 0x28 0x3d0002 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x9 0x2 0x0 0x0 oops 0 methods 0 -ciMethodData java/util/Arrays copyOf ([Ljava/lang/Object;I)[Ljava/lang/Object; 2 32838 orig 320 144 166 185 254 252 127 0 0 112 92 201 223 9 2 0 0 208 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 96 0 0 0 49 255 3 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 3 0 2 0 0 0 0 0 0 0 72 0 0 0 254 255 255 255 5 0 3 0 0 0 0 0 data 19 0x30005 0x7fe6 0x0 0x0 0x0 0x0 0x0 0x60002 0x7fe6 0x0 0x0 0x0 0x0 0x0 0x0 0x9 0x2 0xffffffffffffffff 0x0 oops 0 methods 0 -ciMethodData java/util/HashMap ()V 2 73333 orig 320 144 166 185 254 252 127 0 0 144 113 196 223 9 2 0 0 128 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 80 1 0 0 41 233 8 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 3 0 2 0 0 0 0 0 0 0 16 0 0 0 254 255 255 255 2 0 1 0 0 0 0 0 data 9 0x10002 0x11d25 0x0 0x0 0x0 0x0 0x9 0x1 0x10 oops 0 methods 0 -ciMethod java/util/LinkedHashMap$LinkedValues (Ljava/util/LinkedHashMap;)V 1209 1 6856 0 0 -ciMethod java/util/LinkedHashMap$LinkedValues iterator ()Ljava/util/Iterator; 2057 1 5383 0 416 -ciMethod java/util/LinkedHashMap$LinkedValueIterator (Ljava/util/LinkedHashMap;)V 2057 1 5383 0 0 -ciMethod java/util/LinkedHashMap$LinkedValueIterator next ()Ljava/lang/Object; 2049 1 5700 0 544 -ciMethod java/util/LinkedHashMap$LinkedHashIterator (Ljava/util/LinkedHashMap;)V 2057 1 17862 0 0 -ciMethod java/util/LinkedHashMap$LinkedHashIterator hasNext ()Z 2049 1 5472 0 64 -ciMethod java/util/LinkedHashMap$LinkedHashIterator nextNode ()Ljava/util/LinkedHashMap$Entry; 2049 1 5613 0 544 -ciMethodData java/util/ArrayList ()V 2 320798 orig 320 144 166 185 254 252 127 0 0 184 51 217 223 9 2 0 0 128 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 118 0 0 0 65 37 39 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 3 0 2 0 0 0 0 0 0 0 16 0 0 0 254 255 255 255 2 0 1 0 0 0 0 0 data 9 0x10002 0x4e4a8 0x0 0x0 0x0 0x0 0x9 0x1 0xe oops 0 methods 0 -ciMethodData java/util/AbstractList ()V 2 347722 orig 320 144 166 185 254 252 127 0 0 104 168 206 223 9 2 0 0 128 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 207 0 0 0 217 107 42 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 3 0 2 0 0 0 0 0 0 0 16 0 0 0 254 255 255 255 2 0 1 0 0 0 0 0 data 9 0x10002 0x54d7b 0x0 0x0 0x0 0x0 0x9 0x1 0x6 oops 0 methods 0 -ciMethodData java/util/ArrayList addAll (Ljava/util/Collection;)Z 2 5285 orig 320 144 166 185 254 252 127 0 0 120 84 217 223 9 2 0 0 72 2 0 0 120 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 25 165 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 8 0 2 0 0 0 0 0 0 0 192 0 0 0 254 255 255 255 5 0 1 0 0 0 0 0 data 34 0x10005 0x1499 0x0 0x209f5730f60 0x2 0x209f5731010 0x8 0x150007 0x10d1 0x20 0x3d2 0x2b0007 0xb0 0x58 0x1021 0x330005 0xf1a 0x0 0x209f05afbc0 0x107 0x0 0x0 0x3f0002 0x10d1 0x0 0x0 0x0 0x0 0x0 0x0 0x9 0x2 0xe 0xffffffffffffffff oops 3 3 java/util/ImmutableCollections$List12 5 java/util/ImmutableCollections$ListN 18 java/util/ArrayList methods 0 -ciMethodData java/util/ArrayList$Itr hasNext ()Z 2 5383 orig 320 144 166 185 254 252 127 0 0 88 67 223 223 9 2 0 0 168 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 49 160 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 6 0 2 0 0 0 0 0 0 0 56 0 0 0 254 255 255 255 7 0 11 0 0 0 0 0 data 14 0xb0007 0x606 0x38 0xe00 0xf0003 0xe00 0x18 0x0 0x0 0x0 0x0 0x9 0x1 0x0 oops 0 methods 0 -ciMethodData java/util/ArrayList$Itr checkForComodification ()V 2 12539 orig 320 144 166 185 254 252 127 0 0 128 71 223 223 9 2 0 0 160 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 25 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 217 127 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 5 0 2 0 0 0 0 0 0 0 48 0 0 0 254 255 255 255 7 0 11 0 0 0 0 0 data 13 0xb0007 0x2ffb 0x30 0x0 0x120002 0x0 0x0 0x0 0x0 0x0 0x9 0x1 0x0 oops 0 methods 0 -ciMethodData java/util/ArrayList$Itr next ()Ljava/lang/Object; 2 5507 orig 320 144 166 185 254 252 127 0 0 96 68 223 223 9 2 0 0 24 2 0 0 88 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 25 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 25 164 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 10 0 2 0 0 0 0 0 0 0 152 0 0 0 254 255 255 255 5 0 1 0 0 0 0 0 data 28 0x10005 0x1483 0x0 0x0 0x0 0x0 0x0 0x110007 0x1483 0x30 0x0 0x180002 0x0 0x270007 0x1483 0x30 0x0 0x2e0002 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x9 0x1 0x6 oops 0 methods 0 -ciMethodData java/util/ArrayList$Itr (Ljava/util/ArrayList;)V 2 14761 orig 320 144 166 185 254 252 127 0 0 160 66 223 223 9 2 0 0 136 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 1 0 0 57 197 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 3 0 2 0 0 0 0 0 0 0 16 0 0 0 254 255 255 255 2 0 6 0 0 0 0 0 data 10 0x60002 0x38a7 0x0 0x0 0x0 0x0 0x9 0x2 0xc 0x0 oops 0 methods 0 -ciMethodData java/util/ArrayList iterator ()Ljava/util/Iterator; 2 7132 orig 320 144 166 185 254 252 127 0 0 136 98 217 223 9 2 0 0 120 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 13 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 1 0 0 209 214 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 3 0 2 0 0 0 0 0 0 0 16 0 0 0 254 255 255 255 2 0 5 0 0 0 0 0 data 8 0x50002 0x1ada 0x0 0x0 0x0 0x9 0x1 0x0 oops 0 methods 0 -ciMethodData java/util/LinkedHashMap$LinkedHashIterator hasNext ()Z 2 5472 orig 320 144 166 185 254 252 127 0 0 192 128 25 224 9 2 0 0 184 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 163 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 6 0 2 0 0 0 0 0 0 0 56 0 0 0 254 255 255 255 7 0 4 0 0 0 0 0 data 16 0x40007 0x8ea 0x38 0xb76 0x80003 0xb76 0x18 0x0 0x0 0x0 0x0 0x0 0x0 0x9 0x1 0x0 oops 0 methods 0 -ciMethodData java/util/LinkedHashMap$LinkedHashIterator nextNode ()Ljava/util/LinkedHashMap$Entry; 2 5613 orig 320 144 166 185 254 252 127 0 0 176 129 25 224 9 2 0 0 224 1 0 0 32 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 105 167 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 7 0 2 0 0 0 0 0 0 0 96 0 0 0 254 255 255 255 7 0 16 0 0 0 0 0 data 21 0x100007 0x14ed 0x30 0x0 0x170002 0x0 0x1c0007 0x14ed 0x30 0x0 0x230002 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x9 0x1 0x0 oops 0 methods 0 -ciMethodData java/util/LinkedHashMap$LinkedHashIterator (Ljava/util/LinkedHashMap;)V 2 17862 orig 320 144 166 185 254 252 127 0 0 16 128 25 224 9 2 0 0 136 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 41 38 2 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 3 0 2 0 0 0 0 0 0 0 16 0 0 0 254 255 255 255 2 0 6 0 0 0 0 0 data 10 0x60002 0x44c5 0x0 0x0 0x0 0x0 0x9 0x2 0xe 0x0 oops 0 methods 0 -ciMethodData java/util/LinkedHashMap (Ljava/util/Map;)V 2 9863 orig 320 144 166 185 254 252 127 0 0 248 27 214 223 9 2 0 0 208 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 236 0 0 0 217 44 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 3 0 2 0 0 0 0 0 0 0 72 0 0 0 254 255 255 255 2 0 1 0 0 0 0 0 data 19 0x10002 0x259b 0xc0005 0x259b 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x9 0x2 0xffffffffffffffff 0xffffffffffffffff oops 0 methods 0 -ciMethodData java/util/HashMap putMapEntries (Ljava/util/Map;Z)V 2 13717 orig 320 144 166 185 254 252 127 0 0 16 116 196 223 9 2 0 0 232 4 0 0 136 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 242 0 0 0 9 174 0 0 193 168 1 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 1 0 30 0 2 0 0 0 0 0 0 0 88 3 0 0 254 255 255 255 5 0 1 0 0 0 0 0 data 118 0x10005 0x1f 0x0 0x209f36e71e0 0x2a8 0x209f05aef10 0x12fa 0x80007 0xd1 0x320 0x14f0 0xf0007 0x26 0xa0 0x14ca 0x220007 0x0 0x38 0x14ca 0x280003 0x14ca 0x18 0x350007 0x0 0x30 0x14ca 0x3b0002 0x14ca 0x410003 0x14ca 0x70 0x490007 0x1b 0x58 0xb 0x4d0005 0xb 0x0 0x0 0x0 0x0 0x0 0x520005 0x14 0x0 0x209f36e71e0 0x1e2 0x209f05aef10 0x12fa 0x570005 0x14 0x0 0x209f5730880 0x1e2 0x209f5730930 0x12fa 0x600005 0xd5 0x0 0x209f57309e0 0x92d 0x209f5730a90 0x4006 0x650007 0x14f0 0x160 0x3518 0x6a0005 0xc1 0x0 0x209f57309e0 0x74b 0x209f5730a90 0x2d0c 0x6f0004 0x0 0x0 0x209f2d22490 0x74b 0x209ec2384e0 0x2d0c 0x760005 0xc1 0x0 0x209f2d22490 0x74b 0x209ec2384e0 0x2d0c 0x7f0005 0xc1 0x0 0x209f2d22490 0x74b 0x209ec2384e0 0x2d0c 0x890002 0x3518 0x920005 0x3518 0x0 0x0 0x0 0x0 0x0 0x960003 0x3518 0xfffffffffffffe80 0x0 0x0 0x0 0x0 0x0 0x0 0x9 0x3 0x0 0x0 0x0 oops 16 3 java/util/HashMap 5 java/util/LinkedHashMap 45 java/util/HashMap 47 java/util/LinkedHashMap 52 java/util/HashMap$EntrySet 54 java/util/LinkedHashMap$LinkedEntrySet 59 java/util/HashMap$EntryIterator 61 java/util/LinkedHashMap$LinkedEntryIterator 70 java/util/HashMap$EntryIterator 72 java/util/LinkedHashMap$LinkedEntryIterator 77 java/util/HashMap$Node 79 java/util/LinkedHashMap$Entry 84 java/util/HashMap$Node 86 java/util/LinkedHashMap$Entry 91 java/util/HashMap$Node 93 java/util/LinkedHashMap$Entry methods 0 -ciMethodData java/util/LinkedHashMap$LinkedValues iterator ()Ljava/util/Iterator; 2 5383 orig 320 144 166 185 254 252 127 0 0 96 113 25 224 9 2 0 0 128 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 49 160 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 3 0 2 0 0 0 0 0 0 0 16 0 0 0 254 255 255 255 2 0 8 0 0 0 0 0 data 9 0x80002 0x1406 0x0 0x0 0x0 0x0 0x9 0x1 0x0 oops 0 methods 0 -ciMethodData java/util/LinkedHashMap$LinkedValueIterator (Ljava/util/LinkedHashMap;)V 2 5383 orig 320 144 166 185 254 252 127 0 0 64 122 25 224 9 2 0 0 136 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 49 160 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 3 0 2 0 0 0 0 0 0 0 16 0 0 0 254 255 255 255 2 0 7 0 0 0 0 0 data 10 0x70002 0x1406 0x0 0x0 0x0 0x0 0x9 0x2 0x1e 0x0 oops 0 methods 0 -ciMethodData java/util/LinkedHashMap values ()Ljava/util/Collection; 2 8367 orig 320 144 166 185 254 252 127 0 0 184 34 214 223 9 2 0 0 176 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 113 253 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 6 0 2 0 0 0 0 0 0 0 48 0 0 0 254 255 255 255 7 0 6 0 0 0 0 0 data 15 0x60007 0x57d 0x30 0x1a31 0xe0002 0x1a31 0x0 0x0 0x0 0x0 0x0 0x0 0x9 0x1 0x0 oops 0 methods 0 -ciMethodData java/util/LinkedHashMap$LinkedValues (Ljava/util/LinkedHashMap;)V 2 6856 orig 320 144 166 185 254 252 127 0 0 72 111 25 224 9 2 0 0 136 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 151 0 0 0 137 209 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 0 0 0 254 255 255 255 2 0 6 0 0 0 0 0 data 10 0x60002 0x1a31 0x0 0x0 0x0 0x0 0x9 0x2 0x6 0x0 oops 0 methods 0 -ciMethodData java/util/LinkedHashMap$LinkedValueIterator next ()Ljava/lang/Object; 2 5700 orig 320 144 166 185 254 252 127 0 0 240 122 25 224 9 2 0 0 184 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 33 170 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 3 0 2 0 0 0 0 0 0 0 56 0 0 0 254 255 255 255 5 0 1 0 0 0 0 0 data 16 0x10005 0x1544 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x9 0x1 0x0 oops 0 methods 0 -ciMethod org/apache/maven/model/ModelBase clone ()Lorg/apache/maven/model/ModelBase; 2065 2457 6749 0 -1 -ciMethod org/apache/maven/model/Dependency clone ()Lorg/apache/maven/model/Dependency; 2185 1 6097 0 -1 -ciMethod org/apache/maven/model/Plugin clone ()Lorg/apache/maven/model/Plugin; 2081 705 7637 0 -1 -ciMethod org/apache/maven/model/Repository clone ()Lorg/apache/maven/model/Repository; 2065 1 3880 0 -1 -ciMethod org/apache/maven/model/PluginContainer clone ()Lorg/apache/maven/model/PluginContainer; 2113 5393 4443 0 3680 -ciMethod org/apache/maven/model/BuildBase clone ()Lorg/apache/maven/model/BuildBase; 2065 897 5834 0 0 -ciMethod org/apache/maven/model/PluginConfiguration clone ()Lorg/apache/maven/model/PluginConfiguration; 2065 1 5834 0 0 -ciMethod org/apache/maven/model/PluginManagement clone ()Lorg/apache/maven/model/PluginManagement; 553 1 1852 0 0 -ciMethod org/apache/maven/model/Reporting clone ()Lorg/apache/maven/model/Reporting; 417 113 1627 0 -1 -ciMethod org/apache/maven/model/Profile clone ()Lorg/apache/maven/model/Profile; 2057 1 5631 0 -1 -ciMethod org/apache/maven/model/ActivationProperty clone ()Lorg/apache/maven/model/ActivationProperty; 2049 1 1827 0 0 -ciMethod org/apache/maven/model/Activation clone ()Lorg/apache/maven/model/Activation; 1561 1 2610 0 0 -ciMethod org/apache/maven/model/ActivationFile clone ()Lorg/apache/maven/model/ActivationFile; 313 1 420 0 0 -ciMethod org/apache/maven/model/ActivationOS clone ()Lorg/apache/maven/model/ActivationOS; 193 1 24 0 0 -ciMethod org/apache/maven/model/PatternSet clone ()Lorg/apache/maven/model/PatternSet; 2049 1 1562 0 0 -ciMethod org/apache/maven/model/FileSet clone ()Lorg/apache/maven/model/FileSet; 1921 1 1562 0 0 -ciMethod org/apache/maven/model/Resource clone ()Lorg/apache/maven/model/Resource; 897 1 1560 0 0 -ciMethod org/apache/maven/model/DependencyManagement clone ()Lorg/apache/maven/model/DependencyManagement; 441 30993 728 0 -1 -ciMethod org/apache/maven/model/DistributionManagement clone ()Lorg/apache/maven/model/DistributionManagement; 465 1 1055 0 -1 -ciMethod org/apache/maven/model/merge/ModelMerger$MergingList iterator ()Ljava/util/Iterator; 2057 1 2737 0 0 -ciMethodData org/apache/maven/model/PluginContainer clone ()Lorg/apache/maven/model/PluginContainer; 2 13449 orig 320 144 166 185 254 252 127 0 0 120 103 145 235 9 2 0 0 88 5 0 0 32 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 25 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 160 2 0 0 153 130 0 0 57 143 1 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 1 0 23 0 2 0 0 0 0 0 0 0 216 3 0 0 254 255 255 255 2 0 1 0 0 0 0 0 data 132 0x10002 0x1053 0x40004 0x0 0x0 0x209f31bb5c0 0x85e 0x209eacacee0 0x3f5 0xc0007 0x2d4 0x1b8 0xd7f 0x140002 0xd7f 0x1e0005 0x0 0x0 0x209f05afbc0 0xd7f 0x0 0x0 0x250005 0x0 0x0 0x209eacad040 0x3f65 0x0 0x0 0x2a0007 0xd7f 0x118 0x31e6 0x2e0005 0x0 0x0 0x209eacad040 0x31e6 0x0 0x0 0x330004 0x0 0x0 0x209e9f78c50 0x31e6 0x0 0x0 0x3c0005 0x0 0x0 0x209e9f78c50 0x31e6 0x0 0x0 0x3f0005 0x0 0x0 0x209f05afbc0 0x31e6 0x0 0x0 0x450003 0x31e6 0xfffffffffffffec8 0x4c0007 0xe95 0x30 0x1be 0x580002 0x1be 0x690002 0x0 0x6d0005 0x0 0x0 0x0 0x0 0x0 0x0 0x700005 0x0 0x0 0x0 0x0 0x0 0x0 0x730005 0x0 0x0 0x0 0x0 0x0 0x0 0x780005 0x0 0x0 0x0 0x0 0x0 0x0 0x7b0005 0x0 0x0 0x0 0x0 0x0 0x0 0x7e0002 0x0 0x820005 0x0 0x0 0x0 0x0 0x0 0x0 0x850004 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x9 0x1 0xffffffffffffffff oops 8 5 org/apache/maven/model/BuildBase 7 org/apache/maven/model/Build 18 java/util/ArrayList 25 java/util/ArrayList$Itr 36 java/util/ArrayList$Itr 43 org/apache/maven/model/Plugin 50 org/apache/maven/model/Plugin 57 java/util/ArrayList methods 0 -ciMethodData org/apache/maven/model/ModelBase clone ()Lorg/apache/maven/model/ModelBase; 2 6749 orig 320 144 166 185 254 252 127 0 0 160 195 127 235 9 2 0 0 152 11 0 0 248 7 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 51 1 0 0 217 202 0 0 217 113 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 3 0 58 0 2 0 0 0 0 0 0 0 176 9 0 0 254 255 255 255 2 0 1 0 0 0 0 0 data 332 0x10002 0x195b 0x40004 0x0 0x0 0x209f31bae60 0x127e 0x209e0ddbbf0 0x6dd 0xc0007 0x17c2 0x68 0x199 0x140002 0x199 0x220005 0x0 0x0 0x209f05afbc0 0x199 0x0 0x0 0x2c0007 0x1576 0x58 0x3e5 0x340005 0x0 0x0 0x209f31c16b0 0x3e5 0x0 0x0 0x3e0007 0x12f3 0x90 0x668 0x460005 0x0 0x0 0x209e04eaf70 0x668 0x0 0x0 0x490004 0x0 0x0 0x0 0x0 0x0 0x0 0x530007 0x1762 0x58 0x1f9 0x5b0005 0x0 0x0 0x209f31c20e0 0x1f9 0x0 0x0 0x650007 0x17a5 0x1b8 0x1b6 0x6d0002 0x1b6 0x770005 0x0 0x0 0x209f05afbc0 0x1b6 0x0 0x0 0x7e0005 0x0 0x0 0x209eacad040 0x6d8 0x0 0x0 0x830007 0x1b6 0x118 0x522 0x870005 0x0 0x0 0x209eacad040 0x522 0x0 0x0 0x8c0004 0x0 0x0 0x209f05b1fc0 0x522 0x0 0x0 0x950005 0x0 0x0 0x209f05b1fc0 0x522 0x0 0x0 0x980005 0x0 0x0 0x209f05afbc0 0x522 0x0 0x0 0x9e0003 0x522 0xfffffffffffffec8 0xa50007 0x14f8 0x1b8 0x463 0xad0002 0x463 0xb70005 0x0 0x0 0x209f05afbc0 0x463 0x0 0x0 0xbe0005 0x0 0x0 0x209eacad040 0x99d 0x0 0x0 0xc30007 0x463 0x118 0x53a 0xc70005 0x0 0x0 0x209eacad040 0x53a 0x0 0x0 0xcc0004 0x0 0x0 0x209f05b1030 0x53a 0x0 0x0 0xd50005 0x0 0x0 0x209f05b1030 0x53a 0x0 0x0 0xd80005 0x0 0x0 0x209f05afbc0 0x53a 0x0 0x0 0xde0003 0x53a 0xfffffffffffffec8 0xe50007 0x160c 0x1b8 0x34f 0xed0002 0x34f 0xf70005 0x0 0x0 0x209f05afbc0 0x34f 0x0 0x0 0xfe0005 0x0 0x0 0x209eacad040 0x72e 0x0 0x0 0x1030007 0x34f 0x118 0x3df 0x1070005 0x0 0x0 0x209eacad040 0x3df 0x0 0x0 0x10c0004 0x0 0x0 0x209f05b1030 0x3df 0x0 0x0 0x1150005 0x0 0x0 0x209f05b1030 0x3df 0x0 0x0 0x1180005 0x0 0x0 0x209f05afbc0 0x3df 0x0 0x0 0x11e0003 0x3df 0xfffffffffffffec8 0x1250007 0x195b 0x68 0x0 0x1310004 0x0 0x0 0x0 0x0 0x0 0x0 0x1340002 0x0 0x13e0007 0x1333 0x58 0x628 0x1460005 0x0 0x0 0x209f05ae250 0x628 0x0 0x0 0x1500007 0x1190 0x30 0x7cb 0x15c0002 0x7cb 0x16d0002 0x0 0x1710005 0x0 0x0 0x0 0x0 0x0 0x0 0x1740005 0x0 0x0 0x0 0x0 0x0 0x0 0x1770005 0x0 0x0 0x0 0x0 0x0 0x0 0x17c0005 0x0 0x0 0x0 0x0 0x0 0x0 0x17f0005 0x0 0x0 0x0 0x0 0x0 0x0 0x1820002 0x0 0x1860005 0x0 0x0 0x0 0x0 0x0 0x0 0x1890004 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x9 0x1 0x0 oops 25 5 org/apache/maven/model/Profile 7 org/apache/maven/model/Model 18 java/util/ArrayList 29 org/apache/maven/model/DistributionManagement 40 java/util/Properties 58 org/apache/maven/model/DependencyManagement 71 java/util/ArrayList 78 java/util/ArrayList$Itr 89 java/util/ArrayList$Itr 96 org/apache/maven/model/Dependency 103 org/apache/maven/model/Dependency 110 java/util/ArrayList 126 java/util/ArrayList 133 java/util/ArrayList$Itr 144 java/util/ArrayList$Itr 151 org/apache/maven/model/Repository 158 org/apache/maven/model/Repository 165 java/util/ArrayList 181 java/util/ArrayList 188 java/util/ArrayList$Itr 199 java/util/ArrayList$Itr 206 org/apache/maven/model/Repository 213 org/apache/maven/model/Repository 220 java/util/ArrayList 247 org/apache/maven/model/Reporting methods 0 -ciMethodData org/apache/maven/model/PluginConfiguration clone ()Lorg/apache/maven/model/PluginConfiguration; 2 5834 orig 320 144 166 185 254 252 127 0 0 64 169 145 235 9 2 0 0 200 3 0 0 104 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 1 0 0 65 174 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 17 0 2 0 0 0 0 0 0 0 72 2 0 0 254 255 255 255 2 0 1 0 0 0 0 0 data 82 0x10002 0x15c8 0x40004 0x0 0x0 0x209f31bb5c0 0xef8 0x209eacacee0 0x6d0 0xc0007 0xed1 0x58 0x6f7 0x140005 0x0 0x0 0x209e9f75100 0x6f7 0x0 0x0 0x250002 0x0 0x290005 0x0 0x0 0x0 0x0 0x0 0x0 0x2c0005 0x0 0x0 0x0 0x0 0x0 0x0 0x2f0005 0x0 0x0 0x0 0x0 0x0 0x0 0x340005 0x0 0x0 0x0 0x0 0x0 0x0 0x370005 0x0 0x0 0x0 0x0 0x0 0x0 0x3a0002 0x0 0x3e0005 0x0 0x0 0x0 0x0 0x0 0x0 0x410004 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x9 0x1 0x0 oops 3 5 org/apache/maven/model/BuildBase 7 org/apache/maven/model/Build 16 org/apache/maven/model/PluginManagement methods 0 -ciMethodData org/apache/maven/model/BuildBase clone ()Lorg/apache/maven/model/BuildBase; 2 5834 orig 320 144 166 185 254 252 127 0 0 64 149 145 235 9 2 0 0 88 7 0 0 232 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 1 0 0 65 174 0 0 65 45 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 2 0 29 0 2 0 0 0 0 0 0 0 200 5 0 0 254 255 255 255 2 0 1 0 0 0 0 0 data 196 0x10002 0x15c8 0x40004 0x0 0x0 0x209f31bb5c0 0xef8 0x209eacacee0 0x6d0 0xc0007 0x12f1 0x1b8 0x2d7 0x140002 0x2d7 0x1e0005 0x0 0x0 0x209f05afbc0 0x2d5 0x209eacacf90 0x2 0x250005 0x0 0x0 0x209eacad040 0x5b8 0x209eacad0f0 0x4 0x2a0007 0x2d7 0x118 0x2e5 0x2e0005 0x0 0x0 0x209eacad040 0x2e3 0x209eacad0f0 0x2 0x330004 0x0 0x0 0x209eaca9990 0x2e5 0x0 0x0 0x3c0005 0x0 0x0 0x209eaca9990 0x2e5 0x0 0x0 0x3f0005 0x0 0x0 0x209f05afbc0 0x2e5 0x0 0x0 0x450003 0x2e5 0xfffffffffffffec8 0x4c0007 0x130c 0x1b8 0x2bc 0x540002 0x2bc 0x5e0005 0x0 0x0 0x209f05afbc0 0x2ba 0x209eacacf90 0x2 0x650005 0x0 0x0 0x209eacad040 0x57b 0x209eacad0f0 0x4 0x6a0007 0x2bc 0x118 0x2c3 0x6e0005 0x0 0x0 0x209eacad040 0x2c1 0x209eacad0f0 0x2 0x730004 0x0 0x0 0x209eaca9990 0x2c3 0x0 0x0 0x7c0005 0x0 0x0 0x209eaca9990 0x2c3 0x0 0x0 0x7f0005 0x0 0x0 0x209f05afbc0 0x2c3 0x0 0x0 0x850003 0x2c3 0xfffffffffffffec8 0x8c0007 0x15b5 0x68 0x13 0x940002 0x13 0xa20005 0x0 0x0 0x209f05afbc0 0x13 0x0 0x0 0xb30002 0x0 0xb70005 0x0 0x0 0x0 0x0 0x0 0x0 0xba0005 0x0 0x0 0x0 0x0 0x0 0x0 0xbd0005 0x0 0x0 0x0 0x0 0x0 0x0 0xc20005 0x0 0x0 0x0 0x0 0x0 0x0 0xc50005 0x0 0x0 0x0 0x0 0x0 0x0 0xc80002 0x0 0xcc0005 0x0 0x0 0x0 0x0 0x0 0x0 0xcf0004 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x9 0x1 0x0 oops 21 5 org/apache/maven/model/BuildBase 7 org/apache/maven/model/Build 18 java/util/ArrayList 20 org/apache/maven/model/merge/ModelMerger$MergingList 25 java/util/ArrayList$Itr 27 java/util/LinkedHashMap$LinkedValueIterator 36 java/util/ArrayList$Itr 38 java/util/LinkedHashMap$LinkedValueIterator 43 org/apache/maven/model/Resource 50 org/apache/maven/model/Resource 57 java/util/ArrayList 73 java/util/ArrayList 75 org/apache/maven/model/merge/ModelMerger$MergingList 80 java/util/ArrayList$Itr 82 java/util/LinkedHashMap$LinkedValueIterator 91 java/util/ArrayList$Itr 93 java/util/LinkedHashMap$LinkedValueIterator 98 org/apache/maven/model/Resource 105 org/apache/maven/model/Resource 112 java/util/ArrayList 128 java/util/ArrayList methods 0 -ciMethodData org/apache/maven/model/PluginManagement clone ()Lorg/apache/maven/model/PluginManagement; 2 1853 orig 320 144 166 185 254 252 127 0 0 104 178 145 235 9 2 0 0 112 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 69 0 0 0 193 55 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 14 0 2 0 0 0 0 0 0 0 240 1 0 0 254 255 255 255 2 0 1 0 0 0 0 0 data 71 0x10002 0x6f8 0x40004 0x0 0x0 0x209e9f75100 0x6f8 0x0 0x0 0x130002 0x0 0x170005 0x0 0x0 0x0 0x0 0x0 0x0 0x1a0005 0x0 0x0 0x0 0x0 0x0 0x0 0x1d0005 0x0 0x0 0x0 0x0 0x0 0x0 0x220005 0x0 0x0 0x0 0x0 0x0 0x0 0x250005 0x0 0x0 0x0 0x0 0x0 0x0 0x280002 0x0 0x2c0005 0x0 0x0 0x0 0x0 0x0 0x0 0x2f0004 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x9 0x1 0x0 oops 1 5 org/apache/maven/model/PluginManagement methods 0 -ciMethodData org/apache/maven/model/Resource clone ()Lorg/apache/maven/model/Resource; 2 1562 orig 320 144 166 185 254 252 127 0 0 40 18 192 235 9 2 0 0 112 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 112 0 0 0 81 45 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 14 0 2 0 0 0 0 0 0 0 240 1 0 0 254 255 255 255 2 0 1 0 0 0 0 0 data 71 0x10002 0x5aa 0x40004 0x0 0x0 0x209eaca9990 0x5aa 0x0 0x0 0x130002 0x0 0x170005 0x0 0x0 0x0 0x0 0x0 0x0 0x1a0005 0x0 0x0 0x0 0x0 0x0 0x0 0x1d0005 0x0 0x0 0x0 0x0 0x0 0x0 0x220005 0x0 0x0 0x0 0x0 0x0 0x0 0x250005 0x0 0x0 0x0 0x0 0x0 0x0 0x280002 0x0 0x2c0005 0x0 0x0 0x0 0x0 0x0 0x0 0x2f0004 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x9 0x1 0x0 oops 1 5 org/apache/maven/model/Resource methods 0 -ciMethodData org/apache/maven/model/Profile clone ()Lorg/apache/maven/model/Profile; 2 5631 orig 320 144 166 185 254 252 127 0 0 40 171 150 235 9 2 0 0 32 4 0 0 192 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 241 167 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 20 0 2 0 0 0 0 0 0 0 160 2 0 0 254 255 255 255 2 0 1 0 0 0 0 0 data 93 0x10002 0x14fe 0x40004 0x0 0x0 0x209f31bae60 0x14fe 0x0 0x0 0xc0007 0xb8f 0x58 0x96f 0x140005 0x0 0x0 0x209f31bb510 0x96f 0x0 0x0 0x1e0007 0x652 0x58 0xeac 0x260005 0x0 0x0 0x209f31bb5c0 0xeac 0x0 0x0 0x370002 0x0 0x3b0005 0x0 0x0 0x0 0x0 0x0 0x0 0x3e0005 0x0 0x0 0x0 0x0 0x0 0x0 0x410005 0x0 0x0 0x0 0x0 0x0 0x0 0x460005 0x0 0x0 0x0 0x0 0x0 0x0 0x490005 0x0 0x0 0x0 0x0 0x0 0x0 0x4c0002 0x0 0x500005 0x0 0x0 0x0 0x0 0x0 0x0 0x530004 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x9 0x1 0x0 oops 3 5 org/apache/maven/model/Profile 16 org/apache/maven/model/Activation 27 org/apache/maven/model/BuildBase methods 0 -ciMethodData org/apache/maven/model/Activation clone ()Lorg/apache/maven/model/Activation; 2 2610 orig 320 144 166 185 254 252 127 0 0 80 176 153 235 9 2 0 0 176 4 0 0 112 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 195 0 0 0 121 75 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 26 0 2 0 0 0 0 0 0 0 40 3 0 0 254 255 255 255 2 0 1 0 0 0 0 0 data 111 0x10002 0x96f 0x40004 0x0 0x0 0x209f31bb510 0x96f 0x0 0x0 0xc0007 0x957 0x58 0x18 0x140005 0x0 0x0 0x209e95baf10 0x18 0x0 0x0 0x1e0007 0x2e8 0x58 0x687 0x260005 0x0 0x0 0x209e95bb4e0 0x687 0x0 0x0 0x300007 0x7f2 0x58 0x17d 0x380005 0x0 0x0 0x209e95bba50 0x17d 0x0 0x0 0x420007 0x96f 0x30 0x0 0x4e0002 0x0 0x5f0002 0x0 0x630005 0x0 0x0 0x0 0x0 0x0 0x0 0x660005 0x0 0x0 0x0 0x0 0x0 0x0 0x690005 0x0 0x0 0x0 0x0 0x0 0x0 0x6e0005 0x0 0x0 0x0 0x0 0x0 0x0 0x710005 0x0 0x0 0x0 0x0 0x0 0x0 0x740002 0x0 0x780005 0x0 0x0 0x0 0x0 0x0 0x0 0x7b0004 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x9 0x1 0x0 oops 4 5 org/apache/maven/model/Activation 16 org/apache/maven/model/ActivationOS 27 org/apache/maven/model/ActivationProperty 38 org/apache/maven/model/ActivationFile methods 0 -ciMethodData org/apache/maven/model/FileSet clone ()Lorg/apache/maven/model/FileSet; 2 1562 orig 320 144 166 185 254 252 127 0 0 104 6 192 235 9 2 0 0 112 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 240 0 0 0 81 41 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 14 0 2 0 0 0 0 0 0 0 240 1 0 0 254 255 255 255 2 0 1 0 0 0 0 0 data 71 0x10002 0x52a 0x40004 0x0 0x0 0x209eaca9990 0x52a 0x0 0x0 0x130002 0x0 0x170005 0x0 0x0 0x0 0x0 0x0 0x0 0x1a0005 0x0 0x0 0x0 0x0 0x0 0x0 0x1d0005 0x0 0x0 0x0 0x0 0x0 0x0 0x220005 0x0 0x0 0x0 0x0 0x0 0x0 0x250005 0x0 0x0 0x0 0x0 0x0 0x0 0x280002 0x0 0x2c0005 0x0 0x0 0x0 0x0 0x0 0x0 0x2f0004 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x9 0x1 0x0 oops 1 5 org/apache/maven/model/Resource methods 0 -ciMethodData org/apache/maven/model/PatternSet clone ()Lorg/apache/maven/model/PatternSet; 2 1562 orig 320 144 166 185 254 252 127 0 0 248 243 191 235 9 2 0 0 120 4 0 0 56 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 209 40 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 23 0 2 0 0 0 0 0 0 0 240 2 0 0 254 255 255 255 2 0 1 0 0 0 0 0 data 104 0x10002 0x51a 0x40004 0x0 0x0 0x209eaca9990 0x51a 0x0 0x0 0xc0007 0x4d6 0x68 0x44 0x140002 0x44 0x220005 0x0 0x0 0x209f05afbc0 0x44 0x0 0x0 0x2c0007 0x509 0x68 0x11 0x340002 0x11 0x420005 0x0 0x0 0x209f05afbc0 0x11 0x0 0x0 0x4c0007 0x90 0x30 0x48a 0x580002 0x48a 0x690002 0x0 0x6d0005 0x0 0x0 0x0 0x0 0x0 0x0 0x700005 0x0 0x0 0x0 0x0 0x0 0x0 0x730005 0x0 0x0 0x0 0x0 0x0 0x0 0x780005 0x0 0x0 0x0 0x0 0x0 0x0 0x7b0005 0x0 0x0 0x0 0x0 0x0 0x0 0x7e0002 0x0 0x820005 0x0 0x0 0x0 0x0 0x0 0x0 0x850004 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x9 0x1 0x0 oops 3 5 org/apache/maven/model/Resource 18 java/util/ArrayList 31 java/util/ArrayList methods 0 -ciMethodData org/apache/maven/model/merge/ModelMerger$MergingList iterator ()Ljava/util/Iterator; 2 2737 orig 320 144 166 185 254 252 127 0 0 240 52 218 235 9 2 0 0 72 2 0 0 88 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 129 77 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 5 0 2 0 0 0 0 0 0 0 200 0 0 0 254 255 255 255 7 0 4 0 0 0 0 0 data 34 0x40007 0x0 0x90 0x9b0 0xb0005 0x0 0x0 0x209f05aef10 0x9b0 0x0 0x0 0x100005 0x0 0x0 0x209f36e5440 0x9b0 0x0 0x0 0x1a0005 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x9 0x1 0x0 oops 2 7 java/util/LinkedHashMap 14 java/util/LinkedHashMap$LinkedValues methods 0 -ciMethodData org/apache/maven/model/ActivationProperty clone ()Lorg/apache/maven/model/ActivationProperty; 2 1827 orig 320 144 166 185 254 252 127 0 0 240 156 153 235 9 2 0 0 160 3 0 0 104 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 25 49 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 17 0 2 0 0 0 0 0 0 0 32 2 0 0 254 255 255 255 2 0 1 0 0 0 0 0 data 77 0x10002 0x623 0x40004 0x0 0x0 0x209e95bb4e0 0x623 0x0 0x0 0xc0007 0x623 0x30 0x0 0x180002 0x0 0x290002 0x0 0x2d0005 0x0 0x0 0x0 0x0 0x0 0x0 0x300005 0x0 0x0 0x0 0x0 0x0 0x0 0x330005 0x0 0x0 0x0 0x0 0x0 0x0 0x380005 0x0 0x0 0x0 0x0 0x0 0x0 0x3b0005 0x0 0x0 0x0 0x0 0x0 0x0 0x3e0002 0x0 0x420005 0x0 0x0 0x0 0x0 0x0 0x0 0x450004 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x9 0x1 0x0 oops 1 5 org/apache/maven/model/ActivationProperty methods 0 -ciMethodData org/apache/maven/model/ActivationFile clone ()Lorg/apache/maven/model/ActivationFile; 1 420 orig 320 144 166 185 254 252 127 0 0 248 197 153 235 9 2 0 0 160 3 0 0 104 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77 68 79 32 101 120 116 114 97 32 100 97 116 97 32 108 111 99 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 39 0 0 0 233 11 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 3 0 0 248 31 0 0 2 0 0 0 0 0 17 0 2 0 0 0 0 0 0 0 32 2 0 0 254 255 255 255 2 0 1 0 0 0 0 0 data 77 0x10002 0x17d 0x40004 0x0 0x0 0x209e95bba50 0x17d 0x0 0x0 0xc0007 0x17d 0x30 0x0 0x180002 0x0 0x290002 0x0 0x2d0005 0x0 0x0 0x0 0x0 0x0 0x0 0x300005 0x0 0x0 0x0 0x0 0x0 0x0 0x330005 0x0 0x0 0x0 0x0 0x0 0x0 0x380005 0x0 0x0 0x0 0x0 0x0 0x0 0x3b0005 0x0 0x0 0x0 0x0 0x0 0x0 0x3e0002 0x0 0x420005 0x0 0x0 0x0 0x0 0x0 0x0 0x450004 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x9 0x1 0x0 oops 1 5 org/apache/maven/model/ActivationFile methods 0 -compile org/apache/maven/model/Profile clone ()Lorg/apache/maven/model/Profile; -1 4 inline 97 0 -1 org/apache/maven/model/Profile clone ()Lorg/apache/maven/model/Profile; 1 20 org/apache/maven/model/Activation clone ()Lorg/apache/maven/model/Activation; 2 38 org/apache/maven/model/ActivationProperty clone ()Lorg/apache/maven/model/ActivationProperty; 2 56 org/apache/maven/model/ActivationFile clone ()Lorg/apache/maven/model/ActivationFile; 1 38 org/apache/maven/model/BuildBase clone ()Lorg/apache/maven/model/BuildBase; 2 1 org/apache/maven/model/PluginConfiguration clone ()Lorg/apache/maven/model/PluginConfiguration; 3 20 org/apache/maven/model/PluginManagement clone ()Lorg/apache/maven/model/PluginManagement; 2 20 java/util/ArrayList ()V 3 1 java/util/AbstractList ()V 4 1 java/util/AbstractCollection ()V 5 1 java/lang/Object ()V 2 30 java/util/ArrayList iterator ()Ljava/util/Iterator; 3 5 java/util/ArrayList$Itr (Ljava/util/ArrayList;)V 4 6 java/lang/Object ()V 2 30 org/apache/maven/model/merge/ModelMerger$MergingList iterator ()Ljava/util/Iterator; 3 11 java/util/LinkedHashMap values ()Ljava/util/Collection; 4 14 java/util/LinkedHashMap$LinkedValues (Ljava/util/LinkedHashMap;)V 5 6 java/util/AbstractCollection ()V 6 1 java/lang/Object ()V 3 16 java/util/LinkedHashMap$LinkedValues iterator ()Ljava/util/Iterator; 4 8 java/util/LinkedHashMap$LinkedValueIterator (Ljava/util/LinkedHashMap;)V 5 7 java/util/LinkedHashMap$LinkedHashIterator (Ljava/util/LinkedHashMap;)V 6 6 java/lang/Object ()V 2 37 java/util/ArrayList$Itr hasNext ()Z 2 37 java/util/LinkedHashMap$LinkedHashIterator hasNext ()Z 2 46 java/util/ArrayList$Itr next ()Ljava/lang/Object; 3 1 java/util/ArrayList$Itr checkForComodification ()V 2 46 java/util/LinkedHashMap$LinkedValueIterator next ()Ljava/lang/Object; 3 1 java/util/LinkedHashMap$LinkedHashIterator nextNode ()Ljava/util/LinkedHashMap$Entry; 2 60 org/apache/maven/model/Resource clone ()Lorg/apache/maven/model/Resource; 3 1 org/apache/maven/model/FileSet clone ()Lorg/apache/maven/model/FileSet; 4 1 org/apache/maven/model/PatternSet clone ()Lorg/apache/maven/model/PatternSet; 5 20 java/util/ArrayList ()V 6 1 java/util/AbstractList ()V 7 1 java/util/AbstractCollection ()V 8 1 java/lang/Object ()V 5 52 java/util/ArrayList ()V 6 1 java/util/AbstractList ()V 7 1 java/util/AbstractCollection ()V 8 1 java/lang/Object ()V 5 88 java/util/LinkedHashMap (Ljava/util/Map;)V 6 1 java/util/HashMap ()V 7 1 java/util/AbstractMap ()V 8 1 java/lang/Object ()V 2 63 java/util/ArrayList add (Ljava/lang/Object;)Z 3 20 java/util/ArrayList add (Ljava/lang/Object;[Ljava/lang/Object;I)V 4 7 java/util/ArrayList grow ()[Ljava/lang/Object; 5 7 java/util/ArrayList grow (I)[Ljava/lang/Object; 6 7 java/util/ArrayList newCapacity (I)I 6 10 java/util/Arrays copyOf ([Ljava/lang/Object;I)[Ljava/lang/Object; 2 84 java/util/ArrayList ()V 3 1 java/util/AbstractList ()V 4 1 java/util/AbstractCollection ()V 5 1 java/lang/Object ()V 2 94 java/util/ArrayList iterator ()Ljava/util/Iterator; 3 5 java/util/ArrayList$Itr (Ljava/util/ArrayList;)V 4 6 java/lang/Object ()V 2 94 org/apache/maven/model/merge/ModelMerger$MergingList iterator ()Ljava/util/Iterator; 3 11 java/util/LinkedHashMap values ()Ljava/util/Collection; 4 14 java/util/LinkedHashMap$LinkedValues (Ljava/util/LinkedHashMap;)V 5 6 java/util/AbstractCollection ()V 6 1 java/lang/Object ()V 3 16 java/util/LinkedHashMap$LinkedValues iterator ()Ljava/util/Iterator; 4 8 java/util/LinkedHashMap$LinkedValueIterator (Ljava/util/LinkedHashMap;)V 5 7 java/util/LinkedHashMap$LinkedHashIterator (Ljava/util/LinkedHashMap;)V 6 6 java/lang/Object ()V 2 101 java/util/ArrayList$Itr hasNext ()Z 2 101 java/util/LinkedHashMap$LinkedHashIterator hasNext ()Z 2 110 java/util/ArrayList$Itr next ()Ljava/lang/Object; 3 1 java/util/ArrayList$Itr checkForComodification ()V 2 110 java/util/LinkedHashMap$LinkedValueIterator next ()Ljava/lang/Object; 3 1 java/util/LinkedHashMap$LinkedHashIterator nextNode ()Ljava/util/LinkedHashMap$Entry; 2 124 org/apache/maven/model/Resource clone ()Lorg/apache/maven/model/Resource; 3 1 org/apache/maven/model/FileSet clone ()Lorg/apache/maven/model/FileSet; 4 1 org/apache/maven/model/PatternSet clone ()Lorg/apache/maven/model/PatternSet; 5 20 java/util/ArrayList ()V 6 1 java/util/AbstractList ()V 7 1 java/util/AbstractCollection ()V 8 1 java/lang/Object ()V 5 52 java/util/ArrayList ()V 6 1 java/util/AbstractList ()V 7 1 java/util/AbstractCollection ()V 8 1 java/lang/Object ()V 5 88 java/util/LinkedHashMap (Ljava/util/Map;)V 6 1 java/util/HashMap ()V 7 1 java/util/AbstractMap ()V 8 1 java/lang/Object ()V 2 127 java/util/ArrayList add (Ljava/lang/Object;)Z 3 20 java/util/ArrayList add (Ljava/lang/Object;[Ljava/lang/Object;I)V 4 7 java/util/ArrayList grow ()[Ljava/lang/Object; 5 7 java/util/ArrayList grow (I)[Ljava/lang/Object; 6 7 java/util/ArrayList newCapacity (I)I 6 10 java/util/Arrays copyOf ([Ljava/lang/Object;I)[Ljava/lang/Object; 2 148 java/util/ArrayList ()V 3 1 java/util/AbstractList ()V 4 1 java/util/AbstractCollection ()V 5 1 java/lang/Object ()V diff --git a/jun_springcloud_plugin/.gitignore b/jun_springcloud_plugin/.gitignore deleted file mode 100644 index 0f69c28349..0000000000 --- a/jun_springcloud_plugin/.gitignore +++ /dev/null @@ -1,18 +0,0 @@ -*.class - -# Package Files # -*.jar -*.war -*.ear - -# idea Files -.idea -*.iml -target - -# log Files -*.log - -2-Dalston版教程示例/trace-2/build/bootstrap.json -2-Dalston版教程示例/trace-2/build/springAppName_IS_UNDEFINED.json -2-Dalston版教程示例/trace-2/build/trace-2.json diff --git a/jun_springcloud_plugin/.keep b/jun_springcloud_plugin/.keep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/jun_springcloud_plugin/README.md b/jun_springcloud_plugin/README.md deleted file mode 100644 index 2d9ecd942c..0000000000 --- a/jun_springcloud_plugin/README.md +++ /dev/null @@ -1,38 +0,0 @@ -### `jun_plugin` 项目 - -### 项目说明 -jun_plugin 整合Java企业级各种开发组件、开箱即用、不写重复代码,包含基础Java基础开发组件,Spring企业家开发组,SpringBoot开发组件、SpringCloud开发组件 - -### 功能清单 - -5. SpringCloud常用开发组件:**springcloud_plugin**,含netflix、alibaba、dubbo等,主要为示例与文档。 - - -#### 基础篇:企业级开发组件(开发组件、代码生成、前端组件) [jun_java_plugin] - - -> SpringCloud系开发框架组件,基于SpringCloud微服务开发组件,新企业级REST服务 - -【springboot_actuator】[SpringBoot微服务项目模板,SpringBoot微服务项目模板](https://github.com/wujun728/jun_java_plugin/tree/master/spring_plugin/maven_springboot_permission_example\) -【springboot_admin】[SpringBoot微服务项目模板,SpringBoot微服务项目模板](https://github.com/wujun728/jun_java_plugin/tree/master/spring_plugin/maven_springboot_permission_example\) -【springboot_async】[SpringBoot微服务项目模板,SpringBoot微服务项目模板](https://github.com/wujun728/jun_java_plugin/tree/master/spring_plugin/maven_springboot_permission_example\) - - -#### 工程截图(组件较多,随意择选了几个) - - -    - -
        - -   
        - - - -#### 开发环境 -- **JDK 1.8 -- **Maven 3.5 -- **IDEA 2018.2 + or STS 4.5 +** (*注意:安装lombok插件) - - -​ diff --git "a/jun_springcloud_plugin/doc/Netflix Zuul\344\270\216Nginx\347\232\204\346\200\247\350\203\275\345\257\271\346\257\224.md" "b/jun_springcloud_plugin/doc/Netflix Zuul\344\270\216Nginx\347\232\204\346\200\247\350\203\275\345\257\271\346\257\224.md" deleted file mode 100644 index de1f45e7b5..0000000000 --- "a/jun_springcloud_plugin/doc/Netflix Zuul\344\270\216Nginx\347\232\204\346\200\247\350\203\275\345\257\271\346\257\224.md" +++ /dev/null @@ -1,249 +0,0 @@ -# Netflix Zuul与Nginx的性能对比 - -**原创** - - [2017-04-03](https://blog.didispace.com/zuul-vs-nginx-performance/) - - 翟永超 - - [Spring Cloud](https://blog.didispace.com/categories/Spring-Cloud/) - -[【推荐】从业15年的架构师告诉你:如何落地微服务和云原生架构?](https://blog.didispace.com/how-to-implement-microservice-and-cloud-native-architecture/) - -> 这是一篇翻译,关于大家经常质疑的一个问题:API网关Zuul的性能。 -> 原文:[NETFLIX ZUUL VS NGINX PERFORMANCE](http://instea.sk/2015/04/netflix-zuul-vs-nginx-performance/) -> 作者:[STANISLAV MIKLIK](http://instea.sk/author/miklik/) - -如今你可以听到很多关于“微服务”的信息。Spring Boot是一个用来构建单个微服务应用的理想选择,但是你还需要以某种方式将它们互相联系起来。这就是Spring Cloud试图解决的问题,尤其是Spring Cloud Netflix。它提供了各种组件,比如:Eureka服务发现与Ribbon客户端负载均衡的结合,为内部“微服务”提供通信支持。但是,如果你想要与外界通信时(你提供外部API,或只是从你的页面使用AJAX),将各种服务隐藏在一个代理之后是一个明智的选择。 - -常规的选择我们会使用Nginx作为代理。但是Netflix带来了它自己的解决方案——智能路由Zuul。它带有许多有趣的功能,它可以用于身份验证、服务迁移、分级卸载以及各种动态路由选项。同时,它是使用Java编写的。如果Netflix使用它,那么它与本地反向代理相比是否足够快呢?或者当我们对灵活性(或其他功能)要求更高时,它是否适合与Nginx联合使用。 - -免责声明:不要认为这是一个严肃的基准。我只是想感受Nginx和Zuul的差异,因为我在互联网上并没有找到任何基准(也可能是我没有搜索足够长的时间)。它不遵循任何推荐的基准测试方法(预热时间、测试次数……),我只是使用3个在不同可用区域的EC2实例(这不是最佳的)。 - -## 测试 - -那我做了什么呢?测试是比较两种解决方案的原始性能,没有任何其他特殊的功能。我只是同时发起单个HTTP请求来获取一个HTML页面(大小约为26KB)。我使用ApacheBench来发起200个并发线程的测试(我也尝试了httpperf,但是它需要更高的CPU要求,所以还是选择了要求更低的ab)。 - -#### 直接连接 - -首先,我感兴趣的是不通过任何反向代理直接访问HTTP服务器的性能。Ab在一台机器上运行,直接访问目标服务器。 - -``` -$ ab -n 10000 -c 200 http://target/sample.html - -.... - -Document Path: /sample.html -Document Length: 26650 bytes - -Total transferred: 268940000 bytes -HTML transferred: 266500000 bytes -Requests per second: 2928.45 [#/sec] (mean) -Time per request: 68.295 [ms] (mean) -Time per request: 0.341 [ms] (mean, across all concurrent requests) -Transfer rate: 76911.96 [Kbytes/sec] received - -Connection Times (ms) - min mean[+/-sd] median max -Connect: 4 33 6.0 32 66 -Processing: 20 35 7.5 35 392 -Waiting: 20 35 6.4 34 266 -Total: 24 68 7.8 66 423 - -Percentage of the requests served within a certain time (ms) - 50% 66 - 66% 67 - 75% 69 - 80% 70 - 90% 74 - 95% 81 - 98% 91 - 99% 92 - 100% 423 (longest request) -``` - -很好,几次测试都显示了类似的值:2928、2725、2834、2648 req/s。有一些偏差,但这些数字现在还不重要。 - -#### 通过Nginx - -现在我可以使用Nginx的代理服务。只需要将Nginx配置更新为代理到目标服务器,比如: - -``` -server { - listen 80 default_server; - listen [::]:80 default_server ipv6only=on; - - # Make site accessible from http://localhost/ - server_name localhost; - - # allow file upload - client_max_body_size 10M; - - location / { - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $remote_addr; - proxy_set_header Host $host; - proxy_pass http://target:80; - } -} -``` - -像之前一样运行类型的测试: - -``` -$ ab -n 50000 -c 200 http://proxy/sample.html -... -Server Software: nginx/1.4.6 -Server Hostname: proxy -Server Port: 80 - -Document Path: /sample.html -Document Length: 26650 bytes - -Concurrency Level: 200 -Time taken for tests: 52.366 seconds -Complete requests: 50000 -Failed requests: 0 -Total transferred: 1344700000 bytes -HTML transferred: 1332500000 bytes -Requests per second: 954.81 [#/sec] (mean) -Time per request: 209.465 [ms] (mean) -Time per request: 1.047 [ms] (mean, across all concurrent requests) -Transfer rate: 25076.93 [Kbytes/sec] received - -Connection Times (ms) - min mean[+/-sd] median max -Connect: 3 50 11.7 48 114 -Processing: 37 159 11.9 160 208 -Waiting: 36 159 11.9 160 207 -Total: 40 209 10.4 209 256 - -Percentage of the requests served within a certain time (ms) - 50% 209 - 66% 212 - 75% 214 - 80% 216 - 90% 220 - 95% 224 - 98% 232 - 99% 238 - 100% 256 (longest request) -``` - -测试结果为954、954、941 req/s。性能与延迟(如预期)变差了。 - -#### 通过Zuul - -现在我们在同一台机器上安装Zuul。它的应用本身很简单: - -``` -@SpringBootApplication -@Controller -@EnableZuulProxy -public class DemoApplication { - public static void main(String[] args) { - new SpringApplicationBuilder(DemoApplication.class) - .web(true).run(args); - } -} -``` - -我们还需要在 `application.yml`中定义固定的路由规则: - -``` -zuul: - routes: - sodik: - path: /sodik/** - url: http://target -``` - -现在我们试试运行测试: - -``` -$ ab -n 50000 -c 200 http://proxy:8080/sodik/sample.html - -Server Software: Apache-Coyote/1.1 -Server Hostname: proxy -Server Port: 8080 - -Document Path: /sodik/sample.html -Document Length: 26650 bytes - -Concurrency Level: 200 -Time taken for tests: 136.164 seconds -Complete requests: 50000 -Failed requests: 2 -(Connect: 0, Receive: 0, Length: 2, Exceptions: 0) -Non-2xx responses: 2 -Total transferred: 1343497042 bytes -HTML transferred: 1332447082 bytes -Requests per second: 367.20 [#/sec] (mean) -Time per request: 544.657 [ms] (mean) -Time per request: 2.723 [ms] (mean, across all concurrent requests) -Transfer rate: 9635.48 [Kbytes/sec] received - -Connection Times (ms) -min mean[+/-sd] median max -Connect: 2 12 92.3 2 1010 -Processing: 15 532 321.6 461 10250 -Waiting: 10 505 297.2 441 9851 -Total: 17 544 333.1 467 10270 - -Percentage of the requests served within a certain time (ms) -50% 467 -66% 553 -75% 626 -80% 684 -90% 896 -95% 1163 -98% 1531 -99% 1864 -100% 10270 (longest request) -``` - -结果比我(乐观的)猜测更差。此外,我们还能看到两次请求失败(我们可以在Zuul的日志中看到有两个相应的异常,这些异常引发了HTTP连接池超时)。显然默认情况下超时时间为10秒。 - -我们再进一步测试,得到了更多的结果: - -``` -Document Path: /sodik/sample.html -Document Length: 26650 bytes - -Concurrency Level: 200 -Time taken for tests: 50.080 seconds -Complete requests: 50000 -Failed requests: 0 -Total transferred: 1343550000 bytes -HTML transferred: 1332500000 bytes -Requests per second: 998.39 [#/sec] (mean) -Time per request: 200.322 [ms] (mean) -Time per request: 1.002 [ms] (mean, across all concurrent requests) -Transfer rate: 26199.09 [Kbytes/sec] received - -Connection Times (ms) -min mean[+/-sd] median max -Connect: 2 16 7.9 16 126 -Processing: 15 184 108.1 203 1943 -Waiting: 13 183 105.9 202 1934 -Total: 18 200 107.8 218 1983 - -Percentage of the requests served within a certain time (ms) -50% 218 -66% 228 -75% 235 -80% 239 -90% 254 -95% 287 -98% 405 -99% 450 -100% 1983 (longest request) -``` - -哇,不错的改善。我认为Java JIT编译对于性能有一定的帮助,但是要验证这是否只是一个巧合,再尝试一次:1010 req / sec。最终结果对我来说是一个惊喜。 - -## 结论 - -Zuul的原始性能非常接近于Nginx。事实上,在启动预热之后,我的测试结果甚至略好一些(重申免责声明-这并非一个严肃的基准性能测试)。Nginx显示出更多的可预测性能(变化较小),可悲的是在Zuul预热期间,我们经历了一些小故障(150000个请求中的2个,但是您的微服务应该是容错机制的,对吧?)。 - -所以,如果您考虑使用一些Zuul的额外功能,或者希望通过它与其他Netflix服务集成(比如Eureka)获得更多的服务能力,Zuul看起来非常有希望作为简单反向代理的替代产品。也许这也是Netflix使用的原因,所以您也可以尝试一下。 \ No newline at end of file diff --git "a/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232Feign\347\232\204\347\273\247\346\211\277\347\211\271\346\200\247(\344\274\252RPC\346\250\241\345\274\217).md" "b/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232Feign\347\232\204\347\273\247\346\211\277\347\211\271\346\200\247(\344\274\252RPC\346\250\241\345\274\217).md" deleted file mode 100644 index b361a4fa83..0000000000 --- "a/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232Feign\347\232\204\347\273\247\346\211\277\347\211\271\346\200\247(\344\274\252RPC\346\250\241\345\274\217).md" +++ /dev/null @@ -1,235 +0,0 @@ -# Spring Cloud实战小贴士:Feign的继承特性(伪RPC模式) - -**原创** - - [2017-08-08](https://blog.didispace.com/spring-cloud-tips-feign-rpc/) - - 翟永超 - - [Spring Cloud](https://blog.didispace.com/categories/Spring-Cloud/) - -[【推荐】从业15年的架构师告诉你:如何落地微服务和云原生架构?](https://blog.didispace.com/how-to-implement-microservice-and-cloud-native-architecture/) - -> 通过之前发布的[《Spring Cloud构建微服务架构:服务消费者(Feign)》](http://blog.didispace.com/spring-cloud-starter-dalston-2-3/),我们已经学会如何使用Spring MVC的注解来绑定服务接口。我们几乎完全可以从服务提供方的Controller中依靠复制操作,来构建出相应的服务接口客户端,或是通过Swagger生成的API文档来编写出客户端,亦或是通过Swagger的代码生成器来生成客户端绑定。即便如此,有很多的方式来产生Feign的客户端程序,依然有很多开发者热衷于利用公共的依赖接口来连接服务提供者和服务消费者的方式。由此,Feign的继承特性就能很好的派上用处。下面,我们来详细看看如何使用Spring Cloud Feign的继承特性。 - -## 动手试一试 - -接下来的示例将分为三个模块: - -- 服务接口定义模块:通过Spring MVC注解定义抽象的interface服务接口 -- 服务接口实现模块:实现服务接口定义模块的interface,该模块作为服务提供者注册到eureka -- 服务接口消费模块:服务接口定义模块的客户端实现,该模块通过注册到eureka来消费服务接口 - -### 服务接口的定义 - -- 创建一个Spring Boot项目:eureka-feign-api,`pom.xml`的主要内容如下: - -``` - - org.springframework.boot - spring-boot-starter-parent - 1.5.6.RELEASE - - - - - - org.springframework.boot - spring-boot-starter-web - - - - - - - org.springframework.cloud - spring-cloud-dependencies - Dalston.SR2 - pom - import - - - -``` - -- 使用Spring MVC注解来定义服务接口: - -``` -public interface HelloService { - - @GetMapping("/hello") - String hello(@RequestParam(value = "name") String name); - -} -``` - -- 完成了上述构建之后,我们使用`mvn install`将该模块构建到本地的Maven仓库中。 - -### 服务接口的实现 - -- 创建一个Spring Boot项目:eureka-feign-client,`pom.xml`的主要内容如下: - -``` - - org.springframework.boot - spring-boot-starter-parent - 1.5.6.RELEASE - - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.cloud - spring-cloud-starter-eureka - - - com.didispace - eureka-feign-api - 1.0.0 - - - - - - - org.springframework.cloud - spring-cloud-dependencies - Dalston.SR2 - pom - import - - - -``` - -该模块需要依赖上面定义的`eureka-feign-api`,将使用上述定义的`HelloService`接口来实现对应的REST服务。同时依赖Eureka是为了将该服务注册到Eureka上供服务消费者发现。 - -- 创建应用主类。使用`@EnableDiscoveryClient`注解开启服务注册与发现,并实现`HelloService`接口的REST服务: - -``` -@EnableDiscoveryClient -@SpringBootApplication -public class Application { - - @RestController - class HelloController implements HelloService { - @Override - public String hello(String name) { - return "hello " + name; - } - } - - public static void main(String[] args) { - new SpringApplicationBuilder(Application.class).web(true).run(args); - } - -} -``` - -- 编辑`application.properties`配置内容: - -``` -spring.application.name=eureka-feign-client -server.port=2101 - -eureka.client.serviceUrl.defaultZone=http://eureka.didispace.com/eureka/ -``` - -配置了服务提供者的名称`eureka-feign-client`,服务提供者的端口号`2101`,并将该服务注册到我的公益Eureka注册中心上。启动该项目,我们可以通过访问:http://eureka.didispace.com/ ,在该页面中找到它。 - -### 服务接口的消费 - -- 创建一个Spring Boot项目:eureka-feign-consumer,`pom.xml`的主要内容如下: - -``` - - org.springframework.boot - spring-boot-starter-parent - 1.5.6.RELEASE - - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.cloud - spring-cloud-starter-eureka - - - org.springframework.cloud - spring-cloud-starter-feign - - - com.didispace - eureka-feign-api - 1.0.0 - - - - - - - org.springframework.cloud - spring-cloud-dependencies - Dalston.SR2 - pom - import - - - -``` - -该模块较服务提供者的依赖增加了Feign的依赖,因为这里将使用Feign来绑定服务接口的客户端。下面我们将使用Feign的继承特性来轻松的构建Feign客户端。 - -- 创建应用主类。使用`@EnableDiscoveryClient`注解开启服务注册与发现,并通过`@FeignClient`注解来声明服务绑定客户端: - -``` -@EnableFeignClients -@EnableDiscoveryClient -@SpringBootApplication -public class Application { - - @FeignClient("eureka-feign-client") - interface HelloServiceClient extends HelloService { - } - - @RestController - class TestController { - @Autowired - private HelloServiceClient helloServiceClient; - @GetMapping("/test") - public String test(String name) { - return helloServiceClient.hello(name); - } - } - - public static void main(String[] args) { - new SpringApplicationBuilder(Application.class).web(true).run(args); - } -} -``` - -从上述代码中我们可以看到,利用Feign的继承特性,`@FeignClient`注解只需要通过声明一个接口来继承在API模块中定义的公共interface就能产生服务接口的Feign客户端了。而`@FeignClient`中的值需要填写该服务的具体服务名(服务提供者的`spring.application.name`配置值)。 - -- 编辑服务消费者的`application.properties`配置内容,将服务消费者注册到eureka上来消费服务: - -``` -spring.application.name=eureka-feign-consumer -server.port=2102 - -eureka.client.serviceUrl.defaultZone=http://eureka.didispace.com/eureka/ -``` - -- 启动`eureka-feign-consumer`之后,我们可以通过访问:http://localhost:2102/test ,来实验`eureka-feign-consumer`对`eureka-feign-client`接口的调用。 - -## 本文示例 - -- [码云](https://gitee.com/didispace/SpringCloud-Learning/tree/master/2-Dalston版教程示例) -- [GitHub](https://github.com/dyc87112/SpringCloud-Learning/tree/master/2-Dalston版教程示例) \ No newline at end of file diff --git "a/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232Ribbon\347\232\204\351\245\245\351\245\277\345\212\240\350\275\275(eager-load)\346\250\241\345\274\217.md" "b/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232Ribbon\347\232\204\351\245\245\351\245\277\345\212\240\350\275\275(eager-load)\346\250\241\345\274\217.md" deleted file mode 100644 index d6312bd29e..0000000000 --- "a/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232Ribbon\347\232\204\351\245\245\351\245\277\345\212\240\350\275\275(eager-load)\346\250\241\345\274\217.md" +++ /dev/null @@ -1,45 +0,0 @@ -# Spring Cloud实战小贴士:Ribbon的饥饿加载(eager-load)模式 - -**原创** - - [2017-09-25](https://blog.didispace.com/spring-cloud-tips-ribbon-eager/) - - 翟永超 - - [Spring Cloud](https://blog.didispace.com/categories/Spring-Cloud/) - -[【推荐】从业15年的架构师告诉你:如何落地微服务和云原生架构?](https://blog.didispace.com/how-to-implement-microservice-and-cloud-native-architecture/) - -> 我们在使用Spring Cloud的Ribbon或Feign来实现服务调用的时候,如果我们的机器或网络环境等原因不是很好的话,有时候会发现这样一个问题:我们服务消费方调用服务提供方接口的时候,第一次请求经常会超时,而之后的调用就没有问题了。下面我们就来说说造成这个问题的原因,以及如何解决的方法。 - -## 问题原因 - -造成第一次服务调用出现失败的原因主要是Ribbon进行客户端负载均衡的Client并不是在服务启动的时候就初始化好的,而是在调用的时候才会去创建相应的Client,所以第一次调用的耗时不仅仅包含发送HTTP请求的时间,还包含了创建RibbonClient的时间,这样一来如果创建时间速度较慢,同时设置的超时时间又比较短的话,很容易就会出现上面所描述的显现。 - -从日志中我们也能知道这一点细节,在第一次发起调用的时候我们可以从日志中看到如下信息: - -``` -2017-09-25 08:29:54,201 INFO [main] com.netflix.loadbalancer.DynamicServerListLoadBalancer - DynamicServerListLoadBalancer for client hello-service initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=hello-service,current list of Servers=[192.168.99.176:9901],Load balancer stats=Zone stats: {unknown=[Zone:unknown; Instance count:1; Active connections count: 0; Circuit breaker tripped count: 0; Active connections per server: 0.0;] -},Server stats: [[Server:192.168.99.176:9901; Zone:UNKNOWN; Total Requests:0; Successive connection failure:0; Total blackout seconds:0; Last connection made:Thu Jan 01 08:00:00 CST 1970; First connection made: Thu Jan 01 08:00:00 CST 1970; Active Connections:0; total failure count in last (1000) msecs:0; average resp time:0.0; 90 percentile resp time:0.0; 95 percentile resp time:0.0; min resp time:0.0; max resp time:0.0; stddev resp time:0.0] -]}ServerList:ConsulServerList{serviceId='hello-service', tag=null} -``` - -而Feign的实现基于Ribbon,所以它也有一样的问题,下面就来看看如何解决这个问题。 - -## 解决方法 - -解决的方法很简单,既然第一次调用时候产生RibbonClient耗时,那么就让它提前创建,而不是在第一次调用的时候创建。 - -在Spring Cloud的Dlaston版本中提供了几个新的参数,它们可以很方便的帮我们实现这样的功能。 - -``` -ribbon.eager-load.enabled=true -ribbon.eager-load.clients=hello-service, user-service -``` - -参数说明: - -- ribbon.eager-load.enabled:开启Ribbon的饥饿加载模式 -- ribbon.eager-load.clients:指定需要饥饿加载的客户端名称、服务名 - -通过上面的配置完成之后,我们尝试重启一下服务消费者,这个时候我们会发现,我们没有开始调用服务接口,但是上面初始化负载均衡的日志就已经打印出来了。这就说明我们对ribbon的饥饿加载模块设置已经生效了。 \ No newline at end of file diff --git "a/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232Zuul\345\244\204\347\220\206Cookie\345\222\214\351\207\215\345\256\232\345\220\221.md" "b/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232Zuul\345\244\204\347\220\206Cookie\345\222\214\351\207\215\345\256\232\345\220\221.md" deleted file mode 100644 index c8dd0fee79..0000000000 --- "a/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232Zuul\345\244\204\347\220\206Cookie\345\222\214\351\207\215\345\256\232\345\220\221.md" +++ /dev/null @@ -1,161 +0,0 @@ -# Spring Cloud实战小贴士:Zuul处理Cookie和重定向 - -**原创** - - [2017-05-01](https://blog.didispace.com/spring-cloud-zuul-cookie-redirect/) - - 翟永超 - - [Spring Cloud](https://blog.didispace.com/categories/Spring-Cloud/) - -[【推荐】从业15年的架构师告诉你:如何落地微服务和云原生架构?](https://blog.didispace.com/how-to-implement-microservice-and-cloud-native-architecture/) - -由于我们在之前所有的入门教程中,对于HTTP请求都采用了简单的接口实现。而实际使用过程中,我们的HTTP请求要复杂的多,比如当我们将Spring Cloud Zuul作为API网关接入网站类应用时,往往都会碰到下面这两个非常常见的问题: - -- 会话无法保持 -- 重定向后的HOST错误 - -本文将帮助大家分析问题原因并给出解决这两个常见问题的方法。 - -## 会话保持问题 - -通过跟踪一个HTTP请求经过Zuul到具体服务,再到返回结果的全过程。我们很容易就能发现,在传递的过程中,HTTP请求头信息中的Cookie和Authorization都没有被正确地传递给具体服务,所以最终导致会话状态没有得到保持的现象。 - -那么这些信息是在哪里丢失的呢?我们从Zuul进行路由转发的过滤器作为起点,来一探究竟。下面是`RibbonRoutingFilter`过滤器的实现片段: - -``` -public class RibbonRoutingFilter extends ZuulFilter { - ... - protected ProxyRequestHelper helper; - - @Override - public Object run() { - RequestContext context = RequestContext.getCurrentContext(); - this.helper.addIgnoredHeaders(); - try { - RibbonCommandContext commandContext = buildCommandContext(context); - ClientHttpResponse response = forward(commandContext); - setResponse(response); - return response; - } - ... - return null; - } - - protected RibbonCommandContext buildCommandContext(RequestContext context) { - HttpServletRequest request = context.getRequest(); - - MultiValueMap headers = this.helper - .buildZuulRequestHeaders(request); - MultiValueMap params = this.helper - .buildZuulRequestQueryParams(request); - ... - } -} -``` - -这里有三个重要元素: - -- 过滤器的核心逻辑`run`函数实现,其中调用了内部函数`buildCommandContext`来构建上下文内容 -- 而`buildCommandContext`中调用了`helper`对象的`buildZuulRequestHeaders`方法来处理请求头信息 -- `helper`对象是`ProxyRequestHelper`类的实例 - -接下来我们再看看`ProxyRequestHelper`的实现: - -``` -public class ProxyRequestHelper { - - public MultiValueMap buildZuulRequestHeaders( - HttpServletRequest request) { - RequestContext context = RequestContext.getCurrentContext(); - MultiValueMap headers = new HttpHeaders(); - Enumeration headerNames = request.getHeaderNames(); - if (headerNames != null) { - while (headerNames.hasMoreElements()) { - String name = headerNames.nextElement(); - if (isIncludedHeader(name)) { - Enumeration values = request.getHeaders(name); - while (values.hasMoreElements()) { - String value = values.nextElement(); - headers.add(name, value); - } - } - } - } - Map zuulRequestHeaders = context.getZuulRequestHeaders(); - for (String header : zuulRequestHeaders.keySet()) { - headers.set(header, zuulRequestHeaders.get(header)); - } - headers.set(HttpHeaders.ACCEPT_ENCODING, "gzip"); - return headers; - } - - public boolean isIncludedHeader(String headerName) { - String name = headerName.toLowerCase(); - RequestContext ctx = RequestContext.getCurrentContext(); - if (ctx.containsKey(IGNORED_HEADERS)) { - Object object = ctx.get(IGNORED_HEADERS); - if (object instanceof Collection && ((Collection) object).contains(name)) { - return false; - } - } - ... - } -} -``` - -从上述源码中,我们可以看到构建头信息的方法`buildZuulRequestHeaders`通过`isIncludedHeader`函数来判断当前请求的各个头信息是否在忽略的头信息清单中,如果是的话就不组织到此次转发的请求中去。那么这些需要忽略的头信息是在哪里初始化的呢?在PRE阶段的PreDecorationFilter过滤器中,我们可以找到答案: - -``` -public class PreDecorationFilter extends ZuulFilter { - ... - public Object run() { - RequestContext ctx = RequestContext.getCurrentContext(); - final String requestURI = this.urlPathHelper.getPathWithinApplication(ctx.getRequest()); - Route route = this.routeLocator.getMatchingRoute(requestURI); - if (route != null) { - String location = route.getLocation(); - if (location != null) { - ctx.put("requestURI", route.getPath()); - ctx.put("proxy", route.getId()); - // 处理忽略头信息的部分 - if (!route.isCustomSensitiveHeaders()) { - this.proxyRequestHelper.addIgnoredHeaders( - this.properties.getSensitiveHeaders() - .toArray(new String[0])); - } else { - this.proxyRequestHelper.addIgnoredHeaders( - route.getSensitiveHeaders() - .toArray(new String[0])); - } - ... -} -``` - -从上述源码中,我们可以看到有一段if/else块,通过调用`ProxyRequestHelper`的`addIgnoredHeaders`方法来添加需要忽略的信息到请求上下文中,供后续ROUTE阶段的过滤器使用。这里的if/else块分别用来处理全局设置的敏感头信息和指定路由设置的敏感头信息。而全局的敏感头信息定义于`ZuulProperties`中: - -``` -@Data -@ConfigurationProperties("zuul") -public class ZuulProperties { - private Set sensitiveHeaders = new LinkedHashSet<>( - Arrays.asList("Cookie", "Set-Cookie", "Authorization")); - ... -} -``` - -所以解决该问题的思路也很简单,我们只需要通过设置sensitiveHeaders即可,设置方法分为两种: - -- 全局设置: - - `zuul.sensitive-headers=` -- 指定路由设置: - - `zuul.routes..sensitive-headers=` - - `zuul.routes..custom-sensitive-headers=true` - -## 重定向问题 - -在使用Spring Cloud Zuul对接Web网站的时候,处理完了会话控制问题之后。往往我们还会碰到如下图所示的问题,我们在浏览器中通过Zuul发起了登录请求,该请求会被路由到某WebSite服务,该服务在完成了登录处理之后,会进行重定向到某个主页或欢迎页面。此时,仔细的开发者会发现,在登录完成之后,我们浏览器中URL的HOST部分发生的改变,该地址变成了具体WebSite服务的地址了。这就是在这一节,我们将分析和解决的重定向问题! - -[![img](https://blog.didispace.com/assets/zuul-redirect.png)](https://blog.didispace.com/assets/zuul-redirect.png) - -出现该问题的根源是Spring Cloud Zuul没有正确的处理HTTP请求头信息中的Host导致。在Brixton版本中,Spring Cloud Zuul的`PreDecorationFilter`过滤器实现时完全没有考虑这一问题,它更多的定位于REST API的网关。所以如果要在Brixton版本中增加这一特性就相对较为复杂,不过好在Camden版本之后,Spring Cloud Netflix 1.2.x版本的Zuul增强了该功能,我们只需要通过配置属性`zuul.add-host-header=true`就能让原本有问题的重定向操作得到正确的处理。关于更多Host头信息的处理,读者可以参考本文之前的分析思路,可以通过查看`PreDecorationFilter`过滤器的源码来详细更多实现细节。 \ No newline at end of file diff --git "a/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232Zuul\347\232\204\351\245\245\351\245\277\345\212\240\350\275\275\357\274\210eager-load\357\274\211\344\275\277\347\224\250.md" "b/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232Zuul\347\232\204\351\245\245\351\245\277\345\212\240\350\275\275\357\274\210eager-load\357\274\211\344\275\277\347\224\250.md" deleted file mode 100644 index 9e6fe3bb7e..0000000000 --- "a/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232Zuul\347\232\204\351\245\245\351\245\277\345\212\240\350\275\275\357\274\210eager-load\357\274\211\344\275\277\347\224\250.md" +++ /dev/null @@ -1,27 +0,0 @@ -# Spring Cloud实战小贴士:Zuul的饥饿加载(eager-load)使用 - -**原创** - - [2017-09-28](https://blog.didispace.com/spring-cloud-tips-zuul-eager/) - - 翟永超 - - [Spring Cloud](https://blog.didispace.com/categories/Spring-Cloud/) - -[【推荐】从业15年的架构师告诉你:如何落地微服务和云原生架构?](https://blog.didispace.com/how-to-implement-microservice-and-cloud-native-architecture/) - -> [上一篇](http://blog.didispace.com/spring-cloud-tips-ribbon-eager/)我们介绍了如何使用Ribbon的`earger-load`配置加速Spring Cloud中对服务接口的第一次调用。可是这样只是解决了内部服务间的调用,另外一个问题依然经常困扰我们,那就是网关到内部服务的访问。由于Spring Cloud Zuul的路由转发也是通过Ribbon实现负载均衡的,所以它也会存在第一次调时比较慢的情况。那么这个时候我们要如何设置呢? - -## Zuul中的Eager Load配置 - -在Spring Cloud Zuul中也提供了一个配置参数来实现earger-load,具体如下: - -``` -zuul.ribbon.eager-load.enabled=true -``` - -但是,可能你尝试一下之后会发现,并没有起效?为什么呢?这是由于Spring Cloud Zuul中实现eager-load的时候同Ribbon中一样,都需要指定具体哪些服务需要饥饿加载。那么在Spring Cloud Zuul中如何具体指定呢? - -在Spring Cloud Zuul的饥饿加载中没有设计专门的参数来配置,而是直接采用了读取路由配置来进行饥饿加载的做法。所以,如果我们使用默认路由,而没有通过配置的方式指定具体路由规则,那么`zuul.ribbon.eager-load.enabled=true`的配置就没有什么作用了。 - -因此,在真正使用的时候,我们可以通过`zuul.ignored-services=*`来忽略所有的默认路由,让所有路由配置均维护在配置文件中,以达到网关启动的时候就默认初始化好各个路由转发的负载均衡对象。 \ No newline at end of file diff --git "a/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232Zuul\347\273\237\344\270\200\345\274\202\345\270\270\345\244\204\347\220\206\357\274\210\344\270\200\357\274\211.md" "b/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232Zuul\347\273\237\344\270\200\345\274\202\345\270\270\345\244\204\347\220\206\357\274\210\344\270\200\357\274\211.md" deleted file mode 100644 index 74aa0ff784..0000000000 --- "a/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232Zuul\347\273\237\344\270\200\345\274\202\345\270\270\345\244\204\347\220\206\357\274\210\344\270\200\357\274\211.md" +++ /dev/null @@ -1,191 +0,0 @@ -# Spring Cloud实战小贴士:Zuul统一异常处理(一) - -**原创** - - [2017-05-14](https://blog.didispace.com/spring-cloud-zuul-exception/) - - 翟永超 - - [Spring Cloud](https://blog.didispace.com/categories/Spring-Cloud/) - -[【推荐】从业15年的架构师告诉你:如何落地微服务和云原生架构?](https://blog.didispace.com/how-to-implement-microservice-and-cloud-native-architecture/) - -在上一篇[《Spring Cloud源码分析(四)Zuul:核心过滤器》](http://blog.didispace.com/spring-cloud-source-zuul/)一文中,我们详细介绍了Spring Cloud Zuul中自己实现的一些核心过滤器,以及这些过滤器在请求生命周期中的不同作用。我们会发现在这些核心过滤器中并没有实现error阶段的过滤器。那么这些过滤器可以用来做什么呢?接下来,本文将介绍如何利用error过滤器来实现统一的异常处理。 - -## 过滤器中抛出异常的问题 - -首先,我们可以来看看默认情况下,过滤器中抛出异常Spring Cloud Zuul会发生什么现象。我们创建一个pre类型的过滤器,并在该过滤器的run方法实现中抛出一个异常。比如下面的实现,在run方法中调用的`doSomething`方法将抛出`RuntimeException`异常。 - -``` -public class ThrowExceptionFilter extends ZuulFilter { - - private static Logger log = LoggerFactory.getLogger(ThrowExceptionFilter.class); - - @Override - public String filterType() { - return "pre"; - } - - @Override - public int filterOrder() { - return 0; - } - - @Override - public boolean shouldFilter() { - return true; - } - - @Override - public Object run() { - log.info("This is a pre filter, it will throw a RuntimeException"); - doSomething(); - return null; - } - - private void doSomething() { - throw new RuntimeException("Exist some errors..."); - } - -} -``` - -运行网关程序并访问某个路由请求,此时我们会发现:在API网关服务的控制台中输出了`ThrowExceptionFilter`的过滤逻辑中的日志信息,但是并没有输出任何异常信息,同时发起的请求也没有获得任何响应结果。为什么会出现这样的情况呢?我们又该如何在过滤器中处理异常呢? - -## 解决方案一:严格的try-catch处理 - -回想一下,我们在上一节中介绍的所有核心过滤器,是否还记得有一个`post`过滤器`SendErrorFilter`是用来处理异常信息的?根据正常的处理流程,该过滤器会处理异常信息,那么这里没有出现任何异常信息说明很有可能就是这个过滤器没有被执行。所以,我们不妨来详细看看`SendErrorFilter`的`shouldFilter`函数: - -``` -public boolean shouldFilter() { - RequestContext ctx = RequestContext.getCurrentContext(); - return ctx.containsKey("error.status_code") && !ctx.getBoolean(SEND_ERROR_FILTER_RAN, false); -} -``` - -可以看到该方法的返回值中有一个重要的判断依据`ctx.containsKey("error.status_code")`,也就是说请求上下文中必须有`error.status_code`参数,我们实现的`ThrowExceptionFilter`中并没有设置这个参数,所以自然不会进入`SendErrorFilter`过滤器的处理逻辑。那么我们要如何用这个参数呢?我们可以看一下`route`类型的几个过滤器,由于这些过滤器会对外发起请求,所以肯定会有异常需要处理,比如`RibbonRoutingFilter`的`run`方法实现如下: - -``` -public Object run() { - RequestContext context = RequestContext.getCurrentContext(); - this.helper.addIgnoredHeaders(); - try { - RibbonCommandContext commandContext = buildCommandContext(context); - ClientHttpResponse response = forward(commandContext); - setResponse(response); - return response; - } - catch (ZuulException ex) { - context.set(ERROR_STATUS_CODE, ex.nStatusCode); - context.set("error.message", ex.errorCause); - context.set("error.exception", ex); - } - catch (Exception ex) { - context.set("error.status_code", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - context.set("error.exception", ex); - } - return null; -} -``` - -可以看到,整个发起请求的逻辑都采用了`try-catch`块处理。在`catch`异常的处理逻辑中并没有做任何输出操作,而是往请求上下文中添加一些`error`相关的参数,主要有下面三个参数: - -- `error.status_code`:错误编码 -- `error.exception`:`Exception`异常对象 -- `error.message`:错误信息 - -其中,`error.status_code`参数就是`SendErrorFilter`过滤器用来判断是否需要执行的重要参数。分析到这里,实现异常处理的大致思路就开始明朗了,我们可以参考`RibbonRoutingFilter`的实现对`ThrowExceptionFilter`的`run`方法做一些异常处理的改造,具体如下: - -``` -public Object run() { - log.info("This is a pre filter, it will throw a RuntimeException"); - RequestContext ctx = RequestContext.getCurrentContext(); - try { - doSomething(); - } catch (Exception e) { - ctx.set("error.status_code", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - ctx.set("error.exception", e); - } - return null; -} -``` - -通过上面的改造之后,我们再尝试访问之前的接口,这个时候我们可以得到如下响应内容: - -``` -{ - "timestamp": 1481674980376, - "status": 500, - "error": "Internal Server Error", - "exception": "java.lang.RuntimeException", - "message": "Exist some errors..." -} -``` - -此时,我们的异常信息已经被`SendErrorFilter`过滤器正常处理并返回给客户端了,同时在网关的控制台中也输出了异常信息。从返回的响应信息中,我们可以看到几个我们之前设置在请求上下文中的内容,它们的对应关系如下: - -- `status`:对应`error.status_code`参数的值 -- `exception`:对应`error.exception`参数中`Exception`的类型 -- `message`:对应`error.exception`参数中`Exception`的`message`信息。对于`message`的信息,我们在过滤器中还可以通过`ctx.set("error.message", "自定义异常消息");`来定义更友好的错误信息。`SendErrorFilter`会优先取`error.message`来作为返回的`message`内容,如果没有的话才会使用`Exception`中的`message`信息 - -## 解决方案二:ErrorFilter处理 - -通过上面的分析与实验,我们已经知道如何在过滤器中正确的处理异常,让错误信息能够顺利地流转到后续的`SendErrorFilter`过滤器来组织和输出。但是,即使我们不断强调要在过滤器中使用`try-catch`来处理业务逻辑并往请求上下文添加异常信息,但是不可控的人为因素、意料之外的程序因素等,依然会使得一些异常从过滤器中抛出,对于意外抛出的异常又会导致没有控制台输出也没有任何响应信息的情况出现,那么是否有什么好的方法来为这些异常做一个统一的处理呢? - -这个时候,我们就可以用到`error`类型的过滤器了。由于在请求生命周期的`pre`、`route`、`post`三个阶段中有异常抛出的时候都会进入`error`阶段的处理,所以我们可以通过创建一个`error`类型的过滤器来捕获这些异常信息,并根据这些异常信息在请求上下文中注入需要返回给客户端的错误描述,这里我们可以直接沿用在`try-catch`处理异常信息时用的那些error参数,这样就可以让这些信息被`SendErrorFilter`捕获并组织成消息响应返回给客户端。比如,下面的代码就实现了这里所描述的一个过滤器: - -``` -public class ErrorFilter extends ZuulFilter { - - Logger log = LoggerFactory.getLogger(ErrorFilter.class); - - @Override - public String filterType() { - return "error"; - } - - @Override - public int filterOrder() { - return 10; - } - - @Override - public boolean shouldFilter() { - return true; - } - - @Override - public Object run() { - RequestContext ctx = RequestContext.getCurrentContext(); - Throwable throwable = ctx.getThrowable(); - log.error("this is a ErrorFilter : {}", throwable.getCause().getMessage()); - ctx.set("error.status_code", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - ctx.set("error.exception", throwable.getCause()); - return null; - } - -} -``` - -在将该过滤器加入到我们的API网关服务之后,我们可以尝试使用之前介绍`try-catch`处理时实现的`ThrowExceptionFilter`(不包含异常处理机制的代码),让该过滤器能够抛出异常。这个时候我们再通过API网关来访问服务接口。此时,我们就可以在控制台中看到`ThrowExceptionFilter`过滤器抛出的异常信息,并且请求响应中也能获得如下的错误信息内容,而不是什么信息都没有的情况了。 - -``` -{ - "timestamp": 1481674993561, - "status": 500, - "error": "Internal Server Error", - "exception": "java.lang.RuntimeException", - "message": "Exist some errors..." -} -``` - -**本文节选自《Spring Cloud微服务实战》,部分稍做加工,转载请注明出处** - ------- - -**相关阅读** - -- [《Spring Cloud实战小贴士:Zuul统一异常处理(二)》](http://blog.didispace.com/spring-cloud-zuul-exception-2/) -- [《Spring Cloud源码分析(四)Zuul:核心过滤器》](http://blog.didispace.com/spring-cloud-source-zuul/) -- [《Spring Cloud实战小贴士:Zuul处理Cookie和重定向》](http://blog.didispace.com/spring-cloud-zuul-cookie-redirect/) -- [《Spring Cloud构建微服务架构(五)服务网关》](http://blog.didispace.com/springcloud5/) \ No newline at end of file diff --git "a/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232Zuul\347\273\237\344\270\200\345\274\202\345\270\270\345\244\204\347\220\206\357\274\210\344\270\211\357\274\211\343\200\220Dalston\347\211\210\343\200\221.md" "b/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232Zuul\347\273\237\344\270\200\345\274\202\345\270\270\345\244\204\347\220\206\357\274\210\344\270\211\357\274\211\343\200\220Dalston\347\211\210\343\200\221.md" deleted file mode 100644 index b0e18e76a1..0000000000 --- "a/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232Zuul\347\273\237\344\270\200\345\274\202\345\270\270\345\244\204\347\220\206\357\274\210\344\270\211\357\274\211\343\200\220Dalston\347\211\210\343\200\221.md" +++ /dev/null @@ -1,77 +0,0 @@ -# Spring Cloud实战小贴士:Zuul统一异常处理(三)【Dalston版】 - -**原创** - - [2017-07-28](https://blog.didispace.com/spring-cloud-zuul-exception-3/) - - 翟永超 - - [Spring Cloud](https://blog.didispace.com/categories/Spring-Cloud/) - -[【推荐】从业15年的架构师告诉你:如何落地微服务和云原生架构?](https://blog.didispace.com/how-to-implement-microservice-and-cloud-native-architecture/) - -> 本篇作为《Spring Cloud微服务实战》一书关于Spring Cloud Zuul网关在Dalston版本对异常处理的补充。没有看过本书的读书也不要紧,可以先阅读我之前的两篇博文:[《Spring Cloud实战小贴士:Zuul统一异常处理(一)》](http://blog.didispace.com/spring-cloud-zuul-exception-1/)和[《Spring Cloud实战小贴士:Zuul统一异常处理(二)》](http://blog.didispace.com/spring-cloud-zuul-exception-2/),这两篇文章都详细介绍和分析了Spring Cloud Zuul在过滤器设计中对异常处理的不足。同时,在这两篇文章中,也针对不足之处做了相应的解决方案。不过,这些方案都是基于Brixton版本所做的,在最新的Dalston版本中,Spring Cloud Zuul做了一些优化,所以我们不再需要做这些扩展就已经能够正确的处理异常信息了。那么,在Dalston版中,Spring Cloud Zuul中做了怎么样的修改以达到之前我们自己扩展的效果呢? - -## 过滤器类型的变更 - -读者是否还记得我们之前分析了Spring Cloud Zuul自带的核心过滤器有哪些呢?我们先根据下图回忆一下: - -[![img](https://blog.didispace.com/content/images/posts/spring-cloud-zuul-exception-3-1.png)](https://blog.didispace.com/content/images/posts/spring-cloud-zuul-exception-3-1.png) - -这次主要将`SendErrorFilter`过滤器的类型从`POST`改为了`ERROR`,所以核心过滤器变成了如下图的结构: - -[![img](https://blog.didispace.com/content/images/posts/spring-cloud-zuul-exception-3-2.png)](https://blog.didispace.com/content/images/posts/spring-cloud-zuul-exception-3-2.png) - -## 处理逻辑的变化 - -既然过滤器类型发生了变化,那么请求的处理生命周期就会有所变化。在变化之前,各阶段过滤器的流转如下图所示: - -[![img](https://blog.didispace.com/content/images/posts/spring-cloud-zuul-exception-3-3.png)](https://blog.didispace.com/content/images/posts/spring-cloud-zuul-exception-3-3.png) - -针对异常情况,在图中我们标出了不同的颜色。从pre和route阶段抛出的异常将会进入error阶段,再进入到post阶段进行返回。由于SendErrorFilter需要判断请求上下文中是否包含`error.status_code`属性:有的话就用SendErrorFilter处理错误结果;没有的话就用SendResponseFilter返回正常结果,但是`error.status_code`属性默认是在各个阶段过滤器中自己put进去的,这就导致,各个阶段过滤器抛出异常之后,是没有办法返回错误结果的。因此,我们扩展了一个ErrorFilter来捕获异常,然后手工的设置`error.status_code`属性,让SendErrorFilter能正常运作。 - -通过上面你的改造,从pre和route阶段的异常都能处理了,但是post阶段抛出异常后,是不会再进入post阶段的,这使得ErrorFilter设置了设置`error.status_code`属性之后,也没有过滤器去组织返回结果,所以我们通过继承SendErrorFilter在error阶段增加了一个返回错误信息的过滤器。 - -而这次在Dalston版本中,做了很巧妙的变动:就是上文所述的对SendErrorFilter过滤器类型的变更,这一变动使得所有阶段的异常都会被SendErrorFilter处理,直接解决的上面的第二个问题。当然只是做个变动还是不够的,为了区分SendErrorFilter和SendResponseFitler分别处理出现异常和未出现异常的情况,修改原来根据`error.status_code`属性判断的逻辑,而是改为根据请求上下文中是否包含Throwable来作为基本依据,而这个对象是在过滤器出现异常之后,Zuul往请求上下文中置入的,所以可以更为准确的判断当前请求处理是否出现了异常,而不再需要我们之前扩展的ErrorFilter了。 - -``` -public class SendErrorFilter extends ZuulFilter { - @Override - public boolean shouldFilter() { - RequestContext ctx = RequestContext.getCurrentContext(); - return ctx.containsKey("error.status_code") - && !ctx.getBoolean(SEND_ERROR_FILTER_RAN, false); - } - ... -} - -public class SendResponseFilter extends ZuulFilter { - @Override - public boolean shouldFilter() { - RequestContext context = RequestContext.getCurrentContext(); - return context.getThrowable() == null - && (!context.getZuulResponseHeaders().isEmpty() - || context.getResponseDataStream() != null - || context.getResponseBody() != null); - } - ... -} -``` - -所以,最后修改之后,整个处理逻辑变为如下图所示的流程: - -[![img](https://blog.didispace.com/content/images/posts/spring-cloud-zuul-exception-3-4.png)](https://blog.didispace.com/content/images/posts/spring-cloud-zuul-exception-3-4.png) - -## 推荐阅读 - -- [Spring Cloud构建微服务架构:服务注册与发现(Eureka、Consul)](http://blog.didispace.com/spring-cloud-starter-dalston-1/) -- [Spring Cloud构建微服务架构:服务消费者(基础)](http://blog.didispace.com/spring-cloud-starter-dalston-2-1/) -- [Spring Cloud构建微服务架构:服务消费者(Ribbon)](http://blog.didispace.com/spring-cloud-starter-dalston-2-2/) -- [Spring Cloud构建微服务架构:服务消费者(Feign)](http://blog.didispace.com/spring-cloud-starter-dalston-2-3/) -- [Spring Cloud构建微服务架构:分布式配置中心](http://blog.didispace.com/spring-cloud-starter-dalston-3) -- [Spring Cloud构建微服务架构:服务容错保护(hystrix服务降级)](http://blog.didispace.com/spring-cloud-starter-dalston-4-1) -- [Spring Cloud构建微服务架构:服务容错保护(hystrix依赖隔离)](http://blog.didispace.com/spring-cloud-starter-dalston-4-2) -- [Spring Cloud构建微服务架构:服务容错保护(hystrix断路器)](http://blog.didispace.com/spring-cloud-starter-dalston-4-3) -- [Spring Cloud构建微服务架构:Hystrix监控面板](http://blog.didispace.com/spring-cloud-starter-dalston-5-1) -- [Spring Cloud构建微服务架构:Hystrix监控数据聚合](http://blog.didispace.com/spring-cloud-starter-dalston-5-2) -- [更多Spring Cloud内容…](http://blog.didispace.com/Spring-Cloud基础教程/) \ No newline at end of file diff --git "a/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232Zuul\347\273\237\344\270\200\345\274\202\345\270\270\345\244\204\347\220\206\357\274\210\344\272\214\357\274\211.md" "b/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232Zuul\347\273\237\344\270\200\345\274\202\345\270\270\345\244\204\347\220\206\357\274\210\344\272\214\357\274\211.md" deleted file mode 100644 index 44f15a5c9d..0000000000 --- "a/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232Zuul\347\273\237\344\270\200\345\274\202\345\270\270\345\244\204\347\220\206\357\274\210\344\272\214\357\274\211.md" +++ /dev/null @@ -1,138 +0,0 @@ -# Spring Cloud实战小贴士:Zuul统一异常处理(二) - -**原创** - - [2017-05-18](https://blog.didispace.com/spring-cloud-zuul-exception-2/) - - 翟永超 - - [Spring Cloud](https://blog.didispace.com/categories/Spring-Cloud/) - -[【推荐】从业15年的架构师告诉你:如何落地微服务和云原生架构?](https://blog.didispace.com/how-to-implement-microservice-and-cloud-native-architecture/) - -在前几天发布的[《Spring Cloud实战小贴士:Zuul统一异常处理(一)》](http://blog.didispace.com/spring-cloud-zuul-exception/)一文中,我们详细说明了当Zuul的过滤器中抛出异常时会发生客户端没有返回任何内容的问题以及针对这个问题的两种解决方案:一种是通过在各个阶段的过滤器中增加`try-catch`块,实现过滤器内部的异常处理;另一种是利用`error`类型过滤器的生命周期特性,集中地处理`pre`、`route`、`post`阶段抛出的异常信息。通常情况下,我们可以将这两种手段同时使用,其中第一种是对开发人员的基本要求;而第二种是对第一种处理方式的补充,以防止一些意外情况的发生。这样的异常处理机制看似已经完美,但是如果在多一些应用实践或源码分析之后,我们会发现依然存在一些不足。 - -## 不足之处 - -下面,我们不妨跟着源码来看看,到底上面的方案还有哪些不足之处需要我们注意和进一步优化的。先来看看外部请求到达API网关服务之后,各个阶段的过滤器是如何进行调度的: - -``` -try { - preRoute(); -} catch (ZuulException e) { - error(e); - postRoute(); - return; -} -try { - route(); -} catch (ZuulException e) { - error(e); - postRoute(); - return; -} -try { - postRoute(); -} catch (ZuulException e) { - error(e); - return; -} -``` - -上面代码源自`com.netflix.zuul.http.ZuulServlet`的`service`方法实现,它定义了Zuul处理外部请求过程时,各个类型过滤器的执行逻辑。从代码中我们可以看到三个`try-catch`块,它们依次分别代表了`pre`、`route`、`post`三个阶段的过滤器调用,在`catch`的异常处理中我们可以看到它们都会被`error`类型的过滤器进行处理(之前使用`error`过滤器来定义统一的异常处理也正是利用了这个特性);`error`类型的过滤器处理完毕之后,除了来自`post`阶段的异常之外,都会再被`post`过滤器进行处理。而对于从`post`过滤器中抛出异常的情况,在经过了`error`过滤器处理之后,就没有其他类型的过滤器来接手了,这就是使用之前所述方案存在不足之处的根源。 - -## 问题分析与进一步优化 - -回想一下之前实现的两种异常处理方法,其中非常核心的一点,这两种处理方法都在异常处理时候往请求上下文中添加了一系列的`error.*`参数,而这些参数真正起作用的地方是在`post`阶段的`SendErrorFilter`,在该过滤器中会使用这些参数来组织内容返回给客户端。而对于`post`阶段抛出异常的情况下,由`error`过滤器处理之后并不会在调用`post`阶段的请求,自然这些`error.*`参数也就不会被`SendErrorFilter`消费输出。所以,如果我们在自定义`post`过滤器的时候,没有正确的处理异常,就依然有可能出现日志中没有异常并且请求响应内容为空的问题。我们可以通过修改之前`ThrowExceptionFilter`的`filterType`修改为`post`来验证这个问题的存在,注意去掉`try-catch`块的处理,让它能够抛出异常。 - -解决上述问题的方法有很多种,比如最直接的我们可以在实现`error`过滤器的时候,直接来组织结果返回就能实现效果,但是这样的缺点也很明显,对于错误信息组织和返回的代码实现就会存在多份,这样非常不易于我们日后的代码维护工作。所以为了保持对异常返回处理逻辑的一致,我们还是希望将`post`过滤器抛出的异常能够交给`SendErrorFilter`来处理。 - -在前文中,我们已经实现了一个`ErrorFilter`来捕获`pre`、`route`、`post`过滤器抛出的异常,并组织`error.*`参数保存到请求的上下文中。由于我们的目标是沿用`SendErrorFilter`,这些`error.*`参数依然对我们有用,所以我们可以继续沿用该过滤器,让它在`post`过滤器抛出异常的时候,继续组织`error.*`参数,只是这里我们已经无法将这些`error.*`参数再传递给`SendErrorFitler`过滤器来处理了。所以,我们需要在`ErrorFilter`过滤器之后再定义一个`error`类型的过滤器,让它来实现`SendErrorFilter`的功能,但是这个`error`过滤器并不需要处理所有出现异常的情况,它仅对`post`过滤器抛出的异常才有效。根据上面的思路,我们完全可以创建一个继承自`SendErrorFilter`的过滤器,就能复用它的`run`方法,然后重写它的类型、顺序以及执行条件,实现对原有逻辑的复用,具体实现如下: - -``` -@Component -public class ErrorExtFilter extends SendErrorFilter { - - @Override - public String filterType() { - return "error"; - } - - @Override - public int filterOrder() { - return 30; // 大于ErrorFilter的值 - } - - @Override - public boolean shouldFilter() { - // TODO 判断:仅处理来自post过滤器引起的异常 - return true; - } - -} -``` - -到这里,我们在过滤器调度上的实现思路已经很清晰了,但是又有一个问题出现在我们面前:怎么判断引起异常的过滤器是来自什么阶段呢?(`shouldFilter`方法该如何实现)对于这个问题,我们第一反应会寄希望于请求上下文`RequestContext`对象,可是在查阅文档和源码后发现其中并没有存储异常来源的内容,所以我们不得不扩展原来的过滤器处理逻辑,当有异常抛出的时候,记录下抛出异常的过滤器,这样我们就可以在`ErrorExtFilter`过滤器的`shouldFilter`方法中获取并以此判断异常是否来自`post`阶段的过滤器了。 - -为了扩展过滤器的处理逻辑,为请求上下文增加一些自定义属性,我们需要深入了解一下Zuul过滤器的核心处理器:`com.netflix.zuul.FilterProcessor`。该类中定义了下面过滤器调用和处理相关的核心方法: - -- `getInstance()`:该方法用来获取当前处理器的实例 -- `setProcessor(FilterProcessor processor)`:该方法用来设置处理器实例,可以使用此方法来设置自定义的处理器 -- `processZuulFilter(ZuulFilter filter)`:该方法定义了用来执行`filter`的具体逻辑,包括对请求上下文的设置,判断是否应该执行,执行时一些异常处理等 -- `getFiltersByType(String filterType)`:该方法用来根据传入的`filterType`获取API网关中对应类型的过滤器,并根据这些过滤器的`filterOrder`从小到大排序,组织成一个列表返回 -- `runFilters(String sType)`:该方法会根据传入的`filterType`来调用`getFiltersByType(String filterType)`获取排序后的过滤器列表,然后轮询这些过滤器,并调用`processZuulFilter(ZuulFilter filter)`来依次执行它们 -- `preRoute()`:调用`runFilters("pre")`来执行所有`pre`类型的过滤器 -- `route()`:调用`runFilters("route")`来执行所有`route`类型的过滤器 -- `postRoute()`:调用`runFilters("post")`来执行所有`post`类型的过滤器 -- `error()`:调用`runFilters("error")`来执行所有`error`类型的过滤器 - -根据我们之前的设计,我们可以直接通过扩展`processZuulFilter(ZuulFilter filter)`方法,当过滤器执行抛出异常的时候,我们捕获它,并往请求上下中记录一些信息。比如下面的具体实现: - -``` -public class DidiFilterProcessor extends FilterProcessor { - - @Override - public Object processZuulFilter(ZuulFilter filter) throws ZuulException { - try { - return super.processZuulFilter(filter); - } catch (ZuulException e) { - RequestContext ctx = RequestContext.getCurrentContext(); - ctx.set("failed.filter", filter); - throw e; - } - } - -} -``` - -在上面代码的实现中,我们创建了一个`FilterProcessor`的子类,并重写了`processZuulFilter(ZuulFilter filter)`,虽然主逻辑依然使用了父类的实现,但是在最外层,我们为其增加了异常捕获,并在异常处理中为请求上下文添加了`failed.filter`属性,以存储抛出异常的过滤器实例。在实现了这个扩展之后,我们也就可以完善之前`ErrorExtFilter`中的`shouldFilter()`方法,通过从请求上下文中获取该信息作出正确的判断,具体实现如下: - -``` -@Component -public class ErrorExtFilter extends SendErrorFilter { - - @Override - public String filterType() { - return "error"; - } - - @Override - public int filterOrder() { - return 30; // 大于ErrorFilter的值 - } - - @Override - public boolean shouldFilter() { - // 判断:仅处理来自post过滤器引起的异常 - RequestContext ctx = RequestContext.getCurrentContext(); - ZuulFilter failedFilter = (ZuulFilter) ctx.get("failed.filter"); - if(failedFilter != null && failedFilter.filterType().equals("post")) { - return true; - } - return false; - } - -} -``` - -到这里,我们的优化任务还没有完成,因为扩展的过滤器处理类并还没有生效。最后,我们需要在应用主类中,通过调用`FilterProcessor.setProcessor(new DidiFilterProcessor());`方法来启用自定义的核心处理器以完成我们的优化目标。 \ No newline at end of file diff --git "a/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232turbine\345\246\202\344\275\225\350\201\232\345\220\210\350\256\276\347\275\256\344\272\206context-path\347\232\204hystrix\346\225\260\346\215\256.md" "b/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232turbine\345\246\202\344\275\225\350\201\232\345\220\210\350\256\276\347\275\256\344\272\206context-path\347\232\204hystrix\346\225\260\346\215\256.md" deleted file mode 100644 index 7324d6a6d7..0000000000 --- "a/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232turbine\345\246\202\344\275\225\350\201\232\345\220\210\350\256\276\347\275\256\344\272\206context-path\347\232\204hystrix\346\225\260\346\215\256.md" +++ /dev/null @@ -1,120 +0,0 @@ -# Spring Cloud实战小贴士:turbine如何聚合设置了context-path的hystrix数据 - -**原创** - - [2017-07-25](https://blog.didispace.com/spring-cloud-tips-4/) - - 翟永超 - - [Spring Cloud](https://blog.didispace.com/categories/Spring-Cloud/) - -[【推荐】从业15年的架构师告诉你:如何落地微服务和云原生架构?](https://blog.didispace.com/how-to-implement-microservice-and-cloud-native-architecture/) - -之前在[spring for all社区](http://spring4all.com/)看到这样一个问题:当actuator端点设置了context-path之后,turbine如何聚合数据?首先,我们要知道actuator端点设置了context-path是什么意思?也就是说,此时spring boot actuator的端点都有了一个前缀,比如: - -``` -management.context-path=/xxx -``` - -如果设置了上面的参数,那个对于收集hystrix数据的端点将变为:`/xxx/hystrix.stream`,如果我们还是拿上一篇[Spring Cloud构建微服务架构:Hystrix监控数据聚合【Dalston版】](http://blog.didispace.com/spring-cloud-starter-dalston-5-2/)中构建你的turbine应用,那么将会看到如下错误: - -``` -INFO 7812 --- [ Timer-0] c.n.t.monitor.instance.InstanceMonitor : Url for host: http://172.15.0.18:9020/hystrix.stream default -ERROR 7812 --- [InstanceMonitor] c.n.t.monitor.instance.InstanceMonitor : Could not initiate connection to host, giving up: [{"timestamp":1499941336284,"status":404,"error":"Not Found","message":"No message available","path":"/hystrix.stream"}] -WARN 7812 --- [InstanceMonitor] c.n.t.monitor.instance.InstanceMonitor : Stopping InstanceMonitor for: 172.15.0.18:9020 default - -com.netflix.turbine.monitor.instance.InstanceMonitor$MisconfiguredHostException: [{"timestamp":1499941336284,"status":404,"error":"Not Found","message":"No message available","path":"/hystrix.stream"}] - at com.netflix.turbine.monitor.instance.InstanceMonitor.init(InstanceMonitor.java:318) ~[turbine-core-1.0.0.jar:na] - at com.netflix.turbine.monitor.instance.InstanceMonitor.access$100(InstanceMonitor.java:103) ~[turbine-core-1.0.0.jar:na] - at com.netflix.turbine.monitor.instance.InstanceMonitor$2.call(InstanceMonitor.java:235) [turbine-core-1.0.0.jar:na] - at com.netflix.turbine.monitor.instance.InstanceMonitor$2.call(InstanceMonitor.java:229) [turbine-core-1.0.0.jar:na] - at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_91] - at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_91] - at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_91] - at java.lang.Thread.run(Thread.java:745) [na:1.8.0_91] -``` - -从上述错误中我们可以知道,turbine在收集的时候由于访问的是`/hystrix.stream`,而此时收集端点却是`/xxx/hystrix.stream`,所以报了404错误。 - -那么我们要如何解决呢?通过之前的配置内容,我们可能找不到相关的配置信息,所以只能遍历一下源码,最后找到这个类:`org.springframework.cloud.netflix.turbine.SpringClusterMonitor`。它的具体内容如下: - -``` -public static InstanceUrlClosure ClusterConfigBasedUrlClosure = new InstanceUrlClosure() { - - private final DynamicStringProperty defaultUrlClosureConfig = DynamicPropertyFactory - .getInstance().getStringProperty("turbine.instanceUrlSuffix", - "hystrix.stream"); - private final DynamicBooleanProperty instanceInsertPort = DynamicPropertyFactory - .getInstance().getBooleanProperty("turbine.instanceInsertPort", true); - - @Override - public String getUrlPath(Instance host) { - if (host.getCluster() == null) { - throw new RuntimeException( - "Host must have cluster name in order to use ClusterConfigBasedUrlClosure"); - } - - // find url - String key = "turbine.instanceUrlSuffix." + host.getCluster(); - DynamicStringProperty urlClosureConfig = DynamicPropertyFactory.getInstance() - .getStringProperty(key, null); - String url = urlClosureConfig.get(); - if (url == null) { - url = this.defaultUrlClosureConfig.get(); - } - if (url == null) { - throw new RuntimeException("Config property: " - + urlClosureConfig.getName() + " or " - + this.defaultUrlClosureConfig.getName() + " must be set"); - } - - // find port and scheme - String port; - String scheme; - if (host.getAttributes().containsKey("securePort")) { - port = host.getAttributes().get("securePort"); - scheme = "https"; - } else { - port = host.getAttributes().get("port"); - scheme = "http"; - } - if (host.getAttributes().containsKey("fusedHostPort")) { - return String.format("%s://%s/%s", scheme, host.getAttributes().get("fusedHostPort"), url); - } - - // determine if to insert port - String insertPortKey = "turbine.instanceInsertPort." + host.getCluster(); - DynamicStringProperty insertPortProp = DynamicPropertyFactory.getInstance() - .getStringProperty(insertPortKey, null); - boolean insertPort; - if (insertPortProp.get() == null) { - insertPort = this.instanceInsertPort.get(); - } - else { - insertPort = Boolean.parseBoolean(insertPortProp.get()); - } - - // format url with port - if (insertPort) { - if (url.startsWith("/")) { - url = url.substring(1); - } - if (port == null) { - throw new RuntimeException( - "Configured to use port, but port or securePort is not in host attributes"); - } - - return String.format("%s://%s:%s/%s", scheme, host.getHostname(), port, url); - } - - //format url without port - return scheme + "://" + host.getHostname() + url; - } -}; -``` - -从上述源码中,我们可以找到这个参数`turbine.instanceUrlSuffix`,由此该问题就迎刃而解了,我们只需要在turbine应用的配置文件中增加如下配置信息,就能正确的收集之前配置了`management.context-path=/xxx`的微服务的hystrix数据了。 - -``` -turbine.instanceUrlSuffix=/xxx/hystrix.stream -``` \ No newline at end of file diff --git "a/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232\345\201\245\345\272\267\346\243\200\346\237\245.md" "b/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232\345\201\245\345\272\267\346\243\200\346\237\245.md" deleted file mode 100644 index 8039328f99..0000000000 --- "a/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232\345\201\245\345\272\267\346\243\200\346\237\245.md" +++ /dev/null @@ -1,72 +0,0 @@ -# Spring Cloud实战小贴士:健康检查 - -**原创** - - [2017-04-22](https://blog.didispace.com/spring-cloud-tips-3/) - - 翟永超 - - [Spring Cloud](https://blog.didispace.com/categories/Spring-Cloud/) - -[【推荐】从业15年的架构师告诉你:如何落地微服务和云原生架构?](https://blog.didispace.com/how-to-implement-microservice-and-cloud-native-architecture/) - -今天在博客的交流区收到一条不错的问题,拿出来给大家分享一下。具体问题如下: - -> 因为项目里面用到了redis集群,但并不是用spring boot的配置方式,启动后项目健康检查老是检查redis的时候状态为down,导致注册到eureka后项目状态也是down。 -> 问下能不能设置spring boot不检查 redis的健康状态 - -``` -"redis": { - "status": "DOWN", - "error": "org.springframework.data.redis.RedisConnectionFailureException: Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool" -} -``` - -问题原帖可[点击此处](http://qa.didispace.com/?/question/7)跳转! - -## 原因分析 - -如提问者所述,由于在Spring Boot项目中引用了Redis模块,所以Spring Boot Actuator会对其进行健康检查,正常情况下不会出现问题,但是由于采用了其他配置方式,导致redis的连接检查没有通过。这样就会导致了Consul或Eureka的HealthCheck认为该服务是DOWN状态。 - -那么redis的健康检查是如何实现的呢?我们不妨来看看健康检查的自动化配置中针对redis的配置源码: - -``` -@Configuration -@ConditionalOnBean(RedisConnectionFactory.class) -@ConditionalOnEnabledHealthIndicator("redis") -public static class RedisHealthIndicatorConfiguration extends - CompositeHealthIndicatorConfiguration { - - @Autowired - private Map redisConnectionFactories; - - @Bean - @ConditionalOnMissingBean(name = "redisHealthIndicator") - public HealthIndicator redisHealthIndicator() { - return createHealthIndicator(this.redisConnectionFactories); - } - -} -``` - -以上内容取自:`org.springframework.boot.actuate.autoconfigure.HealthIndicatorAutoConfiguration`类。从自动化配置中我们可以看到,会自动加载一个针对redis的`HealthIndicator`实现,并且该Bean命名为`redisHealthIndicator`。 - -## 解决方法 - -通过上面的分析,我们已经知道了是哪个Bean导致了服务实例的健康检查不通过,那么如何解决该问题的方法也就马上能想到了:我们只需要再实现一个redis的`HealthIndicator`实现来替代原先默认的检查逻辑。比如: - -``` -@Component -public class RedisHealthIndicator implements HealthIndicator { - - @Override - public Health health() { - return Health.up().build(); - } - -} -``` - -上面通过实现`HealthIndicator`接口中的health方法,直接返回了up状态。通过`@Component`注解,让Spring Boot扫描到该类就能自动的进行加载,并覆盖原来的redis健康检查实现。当然,这里的实现并不好,因为它只是为了让健康检查可以通过,但是并没有做真正的健康检查。如提问者所说,采用了其他配置访问,那么正确的做法就是在`health`方法中实现针对其他配置的内容进行健康检查。 - -**注意:这里隐含了一个实现命名的问题,由于默认的bean名称会使用`redisHealthIndicator`,所以这里的定义可以替换默认的实现,因为它的名字与`@ConditionalOnMissingBean(name = "redisHealthIndicator")`中的命名一致。但是如果您自定义的实现类并非叫`RedisHealthIndicator`,它的默认名称与自动化配置的名称是不匹配的,那么就不会替换,这个时候需要在`@Component`注解中指定该Bean的名称为`redisHealthIndicator`**。 \ No newline at end of file diff --git "a/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232\347\211\210\346\234\254\344\276\235\350\265\226\345\205\263\347\263\273.md" "b/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232\347\211\210\346\234\254\344\276\235\350\265\226\345\205\263\347\263\273.md" deleted file mode 100644 index cc1f22e8b5..0000000000 --- "a/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232\347\211\210\346\234\254\344\276\235\350\265\226\345\205\263\347\263\273.md" +++ /dev/null @@ -1,37 +0,0 @@ -# Spring Cloud实战小贴士:版本依赖关系 - -**原创** - - [2017-01-23](https://blog.didispace.com/spring-cloud-tips-1/) - - 翟永超 - - [Spring Cloud](https://blog.didispace.com/categories/Spring-Cloud/) - -[【推荐】从业15年的架构师告诉你:如何落地微服务和云原生架构?](https://blog.didispace.com/how-to-implement-microservice-and-cloud-native-architecture/) - -去年在博客上连载了[《Spring Cloud构建微服务架构》](http://blog.didispace.com/categories/Spring-Cloud/)的系列博文,虽然这部分内容得到了不少关注者们的支持,但是不得不说这些内容只是适用于Spring Cloud入门阶段对各个组件的初步认识。所以,今年除了将会继续更新《Spring Cloud构建微服务架构》系列的连载之外,准备再开一个新系列:《SpringCloud实战小贴士》,该系列文章内容将会聚焦在下面三个点上: - -- 常见问题的解析 -- 构建使用的技巧 -- 实战设计的思考 - -## 开篇:Spring Cloud的版本依赖关系 - -之前在[《聊聊Spring Cloud版本的那些事儿》](http://blog.didispace.com/springcloud-version/)一文中,我们已经介绍了Spring Cloud版本命名的由来以及版本号的规则,并列举了各个版本的依赖内容,以帮助我们选择合适的版本进行微服务实践。 - -由于Spring Cloud的发展速度非常快,版本的更新非常频繁,同时成体系化的中文文档与教程又比较缺乏,所以很多初学者在搜索了网上的文章进行Spring Cloud的初次尝试时,经常会因为没有关注它的版本依赖关系而引发一些问题。比如平时被问最多的一个问题,在使用Feign的时候为什么报了如下错误: - -``` -org.springframework.core.annotation.AnnotationConfigurationException: Attribute 'value' in annotation [org.springframework.cloud.netflix.feign.FeignClient] must be declared as an @AliasFor [serviceId], not [name]. -``` - -由于《Spring Cloud构建微服务架构》系列博文的例子都采用了Brixton版本,在介绍[《Spring Cloud构建微服务架构(二)服务消费者》](http://blog.didispace.com/springcloud2/)中的Feign时候也使用了它,而该版本的基础Spring Boot版本是1.3.x,很多初学者可能因为一些原因,比如:现有应用使用Spring Boot 1.4.x实现或者自身喜欢紧跟潮流,这个时候就会出现上面的问题。 - -所以,我们在选择Spring Boot与Spring Cloud版本的时候,还是需要尽可能的按照Spring Cloud官方版本依赖关系来使用: - -- Angel版本对应Spring Boot 1.2.x -- Brixton版本对应Spring Boot 1.3.x -- Camden版本对应Spring Boot 1.4.x - -就个人而言,推荐使用目前最新的Camden版本与Spring Boot 1.4.x的组合。首先,不光光是Spring Boot版本提升带来的一些新功能,另外也由于Spring Cloud的组件版本也有提升,比如Brixton版本中的Spring Cloud Netflix采用了1.1.x,而Camden中采用了1.2.x,这两个版本之间还有不少区别的,在1.2.x中提供了更多实用功能,比如:之前在[《为Spring Cloud Ribbon配置请求重试(Camden.SR2+)》](http://blog.didispace.com/spring-cloud-ribbon-failed-retry/)一文中提到的RestTemplate的请求重试、关于Zuul的一些头信息优化等。 \ No newline at end of file diff --git "a/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232\351\232\217\346\234\272\347\253\257\345\217\243.md" "b/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232\351\232\217\346\234\272\347\253\257\345\217\243.md" deleted file mode 100644 index 6bf2f4d0b3..0000000000 --- "a/jun_springcloud_plugin/doc/Spring Cloud\345\256\236\346\210\230\345\260\217\350\264\264\345\243\253\357\274\232\351\232\217\346\234\272\347\253\257\345\217\243.md" +++ /dev/null @@ -1,38 +0,0 @@ -# Spring Cloud实战小贴士:随机端口 - -**原创** - - [2017-03-25](https://blog.didispace.com/spring-cloud-tips-2/) - - 翟永超 - - [Spring Cloud](https://blog.didispace.com/categories/Spring-Cloud/) - -[【推荐】从业15年的架构师告诉你:如何落地微服务和云原生架构?](https://blog.didispace.com/how-to-implement-microservice-and-cloud-native-architecture/) - -> 太久没有更新,一时不知道该从哪儿开始,索性就从一个小技巧开始吧。 - -在之前的《Spring Cloud构建微服务架构》系列博文中,我们经常会需要启动多个实例的情况来测试注册中心、配置中心等基础设施的高可用,也会用来测试客户端负载均衡的调用等。但是,我们一个应用只能有一个端口号,这就使得在本机测试的时候,不得不为同一个服务设置不同的端口来进行启动。 - -在本地用不同端口启动同一服务实例的方法有很多。最传统的我们可以粗暴地修改配置文件中的`server.port`属性来分别启动多个实例,这种方法虽然可以实现,但是非常的不方便。比较好的一种方法是在启动的时候通过命令的方式为`server.port`属性来设置不同的值,这样我们的配置文件就不用反复的进行修改了。 - -在本文中,我们将介绍另外一种方法:采用随机端口的方式来设置各个服务实例,这样我们不用去编辑任何命令就可以在本地轻松地启动多个实例了。 - -### 使用随机端口 - -为Spring Cloud的应用实用随机端口非常简单,主要有两种方法: - -- 设置`server.port=0`,当应用启动的时候会自动的分配一个随机端口,但是该方式在注册到Eureka的时候会一个问题:所有实例都使用了同样的实例名(如:`Lenovo-zhaiyc:hello-service:0`),这导致只出现了一个实例。所以,我们还需要修改实例ID的定义,让每个实例的ID不同,比如使用随机数来配置实例ID: - -``` -server.port=0 -eureka.instance.instance-id=${spring.application.name}:${random.int} -``` - -- 除了上面的方法,实际上我们还可以直接使用`random`函数来配置`server.port`。这样就可以指定端口的取值范围,比如: - -``` -server.port=${random.int[10000,19999]} -``` - -由于默认的实例ID会由`server.port`拼接,而此时`server.port`设置的随机值会重新取一次随机数,所以使用这种方法的时候不需要重新定义实例ID的规则就能产生不同的实例ID了。 \ No newline at end of file diff --git "a/jun_springcloud_plugin/doc/Spring Cloud\346\272\220\347\240\201\345\210\206\346\236\220\357\274\210\344\270\200\357\274\211Eureka.md" "b/jun_springcloud_plugin/doc/Spring Cloud\346\272\220\347\240\201\345\210\206\346\236\220\357\274\210\344\270\200\357\274\211Eureka.md" deleted file mode 100644 index 5580107c2b..0000000000 --- "a/jun_springcloud_plugin/doc/Spring Cloud\346\272\220\347\240\201\345\210\206\346\236\220\357\274\210\344\270\200\357\274\211Eureka.md" +++ /dev/null @@ -1,351 +0,0 @@ -# Spring Cloud源码分析(一)Eureka - -**原创** - - [2016-09-22](https://blog.didispace.com/springcloud-sourcecode-eureka/) - - 翟永超 - - [Spring Cloud](https://blog.didispace.com/categories/Spring-Cloud/) - -[【推荐】从业15年的架构师告诉你:如何落地微服务和云原生架构?](https://blog.didispace.com/how-to-implement-microservice-and-cloud-native-architecture/) - -看过之前文章的朋友们,相信已经对Eureka的运行机制已经有了一定的了解。为了更深入的理解它的运作和配置,下面我们结合源码来分别看看服务端和客户端的通信行为是如何实现的。另外写这篇文章,还有一个目的,还是希望鼓励大家能够学会学习和研究的方法,由于目前Spring Cloud的中文资料并不多,并不是大部分的问题都能找到现成的答案,所以其实很多问题给出一个科学而慎重的解答也都是花费研究者不少精力的。 - -在看具体源码前,我们先回顾一下之前我们所实现的内容,从而找一个合适的切入口去分析。首先,服务注册中心、服务提供者、服务消费者这三个主要元素来说,后两者(也就是Eureka客户端)在整个运行机制中是大部分通信行为的主动发起者,而注册中心主要是处理请求的接收者。所以,我们可以从Eureka的客户端作为入口看看它是如何完成这些主动通信行为的。 - -我们在将一个普通的Spring Boot应用注册到Eureka Server中,或是从Eureka Server中获取服务列表时,主要就做了两件事: - -- 在应用主类中配置了`@EnableDiscoveryClient`注解 -- 在`application.properties`中用`eureka.client.serviceUrl.defaultZone`参数指定了服务注册中心的位置 - -顺着上面的线索,我们先查看`@EnableDiscoveryClient`的源码如下: - -``` -/** - * Annotation to enable a DiscoveryClient implementation. - * @author Spencer Gibb - */ -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Inherited -@Import(EnableDiscoveryClientImportSelector.class) -public @interface EnableDiscoveryClient { - -} -``` - -从该注解的注释我们可以知道:该注解用来开启`DiscoveryClient`的实例。通过搜索`DiscoveryClient`,我们可以发现有一个类和一个接口。通过梳理可以得到如下图的关系: - -[![img](https://blog.didispace.com/assets/eureka-code-1.png)](https://blog.didispace.com/assets/eureka-code-1.png) - -其中,左边的`org.springframework.cloud.client.discovery.DiscoveryClient`是Spring Cloud的接口,它定义了用来发现服务的常用抽象方法,而`org.springframework.cloud.netflix.eureka.EurekaDiscoveryClient`是对该接口的实现,从命名来就可以判断,它实现的是对Eureka发现服务的封装。所以`EurekaDiscoveryClient`依赖了Eureka的`com.netflix.discovery.EurekaClient`接口,`EurekaClient`继承了`LookupService`接口,他们都是Netflix开源包中的内容,它主要定义了针对Eureka的发现服务的抽象方法,而真正实现发现服务的则是Netflix包中的`com.netflix.discovery.DiscoveryClient`类。 - -那么,我们就看看来详细看看`DiscoveryClient`类。先解读一下该类头部的注释有个总体的了解,注释的大致内容如下: - -``` -这个类用于帮助与Eureka Server互相协作。 - -Eureka Client负责了下面的任务: -- 向Eureka Server注册服务实例 -- 向Eureka Server为租约续期 -- 当服务关闭期间,向Eureka Server取消租约 -- 查询Eureka Server中的服务实例列表 - -Eureka Client还需要配置一个Eureka Server的URL列表。 -``` - -在具体研究Eureka Client具体负责的任务之前,我们先看看对Eureka Server的URL列表配置在哪里。根据我们配置的属性名:`eureka.client.serviceUrl.defaultZone`,通过`serviceUrl`我们找到该属性相关的加载属性,但是在SR5版本中它们都被`@Deprecated`标注了,并在注视中可以看到`@link`到了替代类`com.netflix.discovery.endpoint.EndpointUtils`,我们可以在该类中找到下面这个函数: - -``` -public static Map> getServiceUrlsMapFromConfig( - EurekaClientConfig clientConfig, String instanceZone, boolean preferSameZone) { - Map> orderedUrls = new LinkedHashMap<>(); - String region = getRegion(clientConfig); - String[] availZones = clientConfig.getAvailabilityZones(clientConfig.getRegion()); - if (availZones == null || availZones.length == 0) { - availZones = new String[1]; - availZones[0] = DEFAULT_ZONE; - } - …… - int myZoneOffset = getZoneOffset(instanceZone, preferSameZone, availZones); - - String zone = availZones[myZoneOffset]; - List serviceUrls = clientConfig.getEurekaServerServiceUrls(zone); - if (serviceUrls != null) { - orderedUrls.put(zone, serviceUrls); - } - …… - return orderedUrls; -} -``` - -### Region、Zone - -在上面的函数中,我们可以发现客户端依次加载了两个内容,第一个是Region,第二个是Zone,从其加载逻上我们可以判断他们之间的关系: - -- 通过`getRegion`函数,我们可以看到它从配置中读取了一个Region返回,所以一个微服务应用只可以属于一个Region,如果不特别配置,就默认为default。若我们要自己设置,可以通过`eureka.client.region`属性来定义。 - -``` -public static String getRegion(EurekaClientConfig clientConfig) { - String region = clientConfig.getRegion(); - if (region == null) { - region = DEFAULT_REGION; - } - region = region.trim().toLowerCase(); - return region; -} -``` - -- 通过`getAvailabilityZones`函数,我们可以知道当我们没有特别为Region配置Zone的时候,将默认采用defaultZone,这也是我们之前配置参数`eureka.client.serviceUrl.defaultZone`的由来。若要为应用指定Zone,我们可以通过`eureka.client.availability-zones`属性来进行设置。从该函数的`return`内容,我们可以Zone是可以有多个的,并且通过逗号分隔来配置。由此,我们可以判断Region与Zone是一对多的关系。 - -``` -public String[] getAvailabilityZones(String region) { - String value = this.availabilityZones.get(region); - if (value == null) { - value = DEFAULT_ZONE; - } - return value.split(","); -} -``` - -### ServiceUrls - -在获取了Region和Zone信息之后,才开始真正加载Eureka Server的具体地址。它根据传入的参数按一定算法确定加载位于哪一个Zone配置的serviceUrls。 - -``` -int myZoneOffset = getZoneOffset(instanceZone, preferSameZone, availZones); -String zone = availZones[myZoneOffset]; -List serviceUrls = clientConfig.getEurekaServerServiceUrls(zone); -``` - -具体获取serviceUrls的实现,我们可以详细查看`getEurekaServerServiceUrls`函数的具体实现类`EurekaClientConfigBean`,该类是`EurekaClientConfig`和`EurekaConstants`接口的实现,用来加载配置文件中的内容,这里有非常多有用的信息,这里我们先说一下此处我们关心的,关于`defaultZone`的信息。通过搜索`defaultZone`,我们可以很容易的找到下面这个函数,它具体实现了,如何解析该参数的过程,通过此内容,我们就可以知道,`eureka.client.serviceUrl.defaultZone`属性可以配置多个,并且需要通过逗号分隔。 - -``` -public List getEurekaServerServiceUrls(String myZone) { - String serviceUrls = this.serviceUrl.get(myZone); - if (serviceUrls == null || serviceUrls.isEmpty()) { - serviceUrls = this.serviceUrl.get(DEFAULT_ZONE); - } - if (!StringUtils.isEmpty(serviceUrls)) { - final String[] serviceUrlsSplit = StringUtils.commaDelimitedListToStringArray(serviceUrls); - List eurekaServiceUrls = new ArrayList<>(serviceUrlsSplit.length); - for (String eurekaServiceUrl : serviceUrlsSplit) { - if (!endsWithSlash(eurekaServiceUrl)) { - eurekaServiceUrl += "/"; - } - eurekaServiceUrls.add(eurekaServiceUrl); - } - return eurekaServiceUrls; - } - return new ArrayList<>(); -} -``` - -*当客户端在服务列表中选择实例进行访问时,对于Zone和Region遵循这样的规则:优先访问同自己一个Zone中的实例,其次才访问其他Zone中的实例。通过Region和Zone的两层级别定义,配合实际部署的物理结构,我们就可以有效的设计出区域性故障的容错集群。* - -### 服务注册 - -在理解了多个服务注册中心信息的加载后,我们再回头看看`DiscoveryClient`类是如何实现“服务注册”行为的,通过查看它的构造类,可以找到它调用了下面这个函数: - -``` -private void initScheduledTasks() { - ... - if (clientConfig.shouldRegisterWithEureka()) { - ... - // InstanceInfo replicator - instanceInfoReplicator = new InstanceInfoReplicator( - this, - instanceInfo, - clientConfig.getInstanceInfoReplicationIntervalSeconds(), - 2); // burstSize - ... - instanceInfoReplicator.start(clientConfig.getInitialInstanceInfoReplicationIntervalSeconds()); - } else { - logger.info("Not registering with Eureka server per configuration"); - } -} -``` - -在上面的函数中,我们可以看到关键的判断依据`if (clientConfig.shouldRegisterWithEureka())`。在该分支内,创建了一个`InstanceInfoReplicator`类的实例,它会执行一个定时任务,查看该类的`run()`函数了解该任务做了什么工作: - -``` -public void run() { - try { - discoveryClient.refreshInstanceInfo(); - Long dirtyTimestamp = instanceInfo.isDirtyWithTime(); - if (dirtyTimestamp != null) { - discoveryClient.register(); - instanceInfo.unsetIsDirty(dirtyTimestamp); - } - } catch (Throwable t) { - logger.warn("There was a problem with the instance info replicator", t); - } finally { - Future next = scheduler.schedule(this, replicationIntervalSeconds, TimeUnit.SECONDS); - scheduledPeriodicRef.set(next); - } -} -``` - -相信大家都发现了`discoveryClient.register();`这一行,真正触发调用注册的地方就在这里。继续查看`register()`的实现内容如下: - -``` -boolean register() throws Throwable { - logger.info(PREFIX + appPathIdentifier + ": registering service..."); - EurekaHttpResponse httpResponse; - try { - httpResponse = eurekaTransport.registrationClient.register(instanceInfo); - } catch (Exception e) { - logger.warn("{} - registration failed {}", PREFIX + appPathIdentifier, e.getMessage(), e); - throw e; - } - if (logger.isInfoEnabled()) { - logger.info("{} - registration status: {}", PREFIX + appPathIdentifier, httpResponse.getStatusCode()); - } - return httpResponse.getStatusCode() == 204; -} -``` - -通过属性命名,大家基本也能猜出来,注册操作也是通过REST请求的方式进行的。同时,这里我们也能看到发起注册请求的时候,传入了一个`com.netflix.appinfo.InstanceInfo`对象,该对象就是注册时候客户端给服务端的服务的元数据。 - -### 服务获取与服务续约 - -顺着上面的思路,我们继续来看`DiscoveryClient`的`initScheduledTasks`函数,不难发现在其中还有两个定时任务,分别是“服务获取”和“服务续约”: - -``` -private void initScheduledTasks() { - if (clientConfig.shouldFetchRegistry()) { - // registry cache refresh timer - int registryFetchIntervalSeconds = clientConfig.getRegistryFetchIntervalSeconds(); - int expBackOffBound = clientConfig.getCacheRefreshExecutorExponentialBackOffBound(); - scheduler.schedule( - new TimedSupervisorTask( - "cacheRefresh", - scheduler, - cacheRefreshExecutor, - registryFetchIntervalSeconds, - TimeUnit.SECONDS, - expBackOffBound, - new CacheRefreshThread() - ), - registryFetchIntervalSeconds, TimeUnit.SECONDS); - } - if (clientConfig.shouldRegisterWithEureka()) { - int renewalIntervalInSecs = instanceInfo.getLeaseInfo().getRenewalIntervalInSecs(); - int expBackOffBound = clientConfig.getHeartbeatExecutorExponentialBackOffBound(); - logger.info("Starting heartbeat executor: " + "renew interval is: " + renewalIntervalInSecs); - - // Heartbeat timer - scheduler.schedule( - new TimedSupervisorTask( - "heartbeat", - scheduler, - heartbeatExecutor, - renewalIntervalInSecs, - TimeUnit.SECONDS, - expBackOffBound, - new HeartbeatThread() - ), - renewalIntervalInSecs, TimeUnit.SECONDS); - // InstanceInfo replicator - …… - } -} -``` - -从源码中,我们就可以发现,“服务获取”相对于“服务续约”更为独立,“服务续约”与“服务注册”在同一个if逻辑中,这个不难理解,服务注册到Eureka Server后,自然需要一个心跳去续约,防止被剔除,所以他们肯定是成对出现的。从源码中,我们可以清楚看到了,对于服务续约相关的时间控制参数: - -``` -eureka.instance.lease-renewal-interval-in-seconds=30 -eureka.instance.lease-expiration-duration-in-seconds=90 -``` - -而“服务获取”的逻辑在独立的一个if判断中,其判断依据就是我们之前所提到的`eureka.client.fetch-registry=true`参数,它默认是为true的,大部分情况下我们不需要关心。为了定期的更新客户端的服务清单,以保证服务访问的正确性,“服务获取”的请求不会只限于服务启动,而是一个定时执行的任务,从源码中我们可以看到任务运行中的`registryFetchIntervalSeconds`参数对应`eureka.client.registry-fetch-interval-seconds=30`配置参数,它默认为30秒。 - -继续循序渐进的向下深入,我们就能分别发现实现“服务获取”和“服务续约”的具体方法,其中“服务续约”的实现较为简单,直接以REST请求的方式进行续约: - -``` -boolean renew() { - EurekaHttpResponse httpResponse; - try { - httpResponse = eurekaTransport.registrationClient.sendHeartBeat(instanceInfo.getAppName(), instanceInfo.getId(), instanceInfo, null); - logger.debug("{} - Heartbeat status: {}", PREFIX + appPathIdentifier, httpResponse.getStatusCode()); - if (httpResponse.getStatusCode() == 404) { - REREGISTER_COUNTER.increment(); - logger.info("{} - Re-registering apps/{}", PREFIX + appPathIdentifier, instanceInfo.getAppName()); - return register(); - } - return httpResponse.getStatusCode() == 200; - } catch (Throwable e) { - logger.error("{} - was unable to send heartbeat!", PREFIX + appPathIdentifier, e); - return false; - } -} -``` - -而“服务获取”则相对复杂一些,会根据是否第一次获取发起不同的REST请求和相应的处理,具体的实现逻辑还是跟之前类似,有兴趣的读者可以继续查看服务客户端的其他具体内容,了解更多细节。 - -### 服务注册中心处理 - -通过上面的源码分析,可以看到所有的交互都是通过REST的请求来发起的。下面我们来看看服务注册中心对这些请求的处理。Eureka Server对于各类REST请求的定义都位于:`com.netflix.eureka.resources`包下。 - -以“服务注册”请求为例: - -``` -@POST -@Consumes({"application/json", "application/xml"}) -public Response addInstance(InstanceInfo info, - @HeaderParam(PeerEurekaNode.HEADER_REPLICATION) String isReplication) { - logger.debug("Registering instance {} (replication={})", info.getId(), isReplication); - // validate that the instanceinfo contains all the necessary required fields - ... - // handle cases where clients may be registering with bad DataCenterInfo with missing data - DataCenterInfo dataCenterInfo = info.getDataCenterInfo(); - if (dataCenterInfo instanceof UniqueIdentifier) { - String dataCenterInfoId = ((UniqueIdentifier) dataCenterInfo).getId(); - if (isBlank(dataCenterInfoId)) { - boolean experimental = "true".equalsIgnoreCase( - serverConfig.getExperimental("registration.validation.dataCenterInfoId")); - if (experimental) { - String entity = "DataCenterInfo of type " + dataCenterInfo.getClass() - + " must contain a valid id"; - return Response.status(400).entity(entity).build(); - } else if (dataCenterInfo instanceof AmazonInfo) { - AmazonInfo amazonInfo = (AmazonInfo) dataCenterInfo; - String effectiveId = amazonInfo.get(AmazonInfo.MetaDataKey.instanceId); - if (effectiveId == null) { - amazonInfo.getMetadata().put( - AmazonInfo.MetaDataKey.instanceId.getName(), info.getId()); - } - } else { - logger.warn("Registering DataCenterInfo of type {} without an appropriate id", - dataCenterInfo.getClass()); - } - } - } - - registry.register(info, "true".equals(isReplication)); - return Response.status(204).build(); // 204 to be backwards compatible -} -``` - -在对注册信息进行了一大堆校验之后,会调用`org.springframework.cloud.netflix.eureka.server.InstanceRegistry`对象中的`register(InstanceInfo info, int leaseDuration, boolean isReplication)`函数来进行服务注册: - -``` -public void register(InstanceInfo info, int leaseDuration, boolean isReplication) { - if (log.isDebugEnabled()) { - log.debug("register " + info.getAppName() + ", vip " + info.getVIPAddress() - + ", leaseDuration " + leaseDuration + ", isReplication " - + isReplication); - } - this.ctxt.publishEvent(new EurekaInstanceRegisteredEvent(this, info, - leaseDuration, isReplication)); - - super.register(info, leaseDuration, isReplication); -} -``` - -在注册函数中,先调用`publishEvent`函数,将该新服务注册的事件传播出去,然后调用`com.netflix.eureka.registry.AbstractInstanceRegistry`父类中的注册实现,将`InstanceInfo`中的元数据信息存储在一个`ConcurrentHashMap>>`对象中,它是一个两层Map结构,第一层的key存储服务名:`InstanceInfo`中的`appName`属性,第二层的key存储实例名:`InstanceInfo`中的`instanceId`属性。 - -服务端的请求接收都非常类似,对于其他的服务端处理,这里就不再展开,读者可以根据上面的脉络来自己查看其内容(这里包含很多细节内容)来帮助和加深理解。 \ No newline at end of file diff --git "a/jun_springcloud_plugin/doc/Spring Cloud\346\272\220\347\240\201\345\210\206\346\236\220\357\274\210\344\272\214\357\274\211Ribbon.md" "b/jun_springcloud_plugin/doc/Spring Cloud\346\272\220\347\240\201\345\210\206\346\236\220\357\274\210\344\272\214\357\274\211Ribbon.md" deleted file mode 100644 index ea98b5bfef..0000000000 --- "a/jun_springcloud_plugin/doc/Spring Cloud\346\272\220\347\240\201\345\210\206\346\236\220\357\274\210\344\272\214\357\274\211Ribbon.md" +++ /dev/null @@ -1,1535 +0,0 @@ -# Spring Cloud源码分析(二)Ribbon - -**原创** - - [2016-10-16](https://blog.didispace.com/springcloud-sourcecode-ribbon/) - - 翟永超 - - [Spring Cloud](https://blog.didispace.com/categories/Spring-Cloud/) - -[【推荐】从业15年的架构师告诉你:如何落地微服务和云原生架构?](https://blog.didispace.com/how-to-implement-microservice-and-cloud-native-architecture/) - -> 断断续续看Ribbon的源码差不多也有7-8天了,总算告一段落。本文记录了这些天对源码的阅读过程与一些分析理解,如有不对还请指出。 - -## 友情提示:本文较长,请选择一个较为舒适的姿势来阅读 - -在之前介绍使用Ribbon进行服务消费的时候,我们用到了`RestTemplate`,但是熟悉Spring的同学们是否产生过这样的疑问:`RestTemplate`不是Spring自己就有的吗?跟Ribbon的客户端负载均衡又有什么关系呢?下面在本文,我们来看`RestTemplate`和`Ribbon`是如何联系起来并实现客户端负载均衡的。 - -首先,回顾一下之前的消费者示例:我们是如何实现客户端负载均衡的?仔细观察一下代码之前的代码,我们可以发现在消费者的例子中,可能就是这个注解`@LoadBalanced`是之前没有接触过的,并且从命名上来看也与负载均衡相关。我们不妨以此为线索来看看源码实现的机制。 - -从`@LoadBalanced`注解源码的注释中,我们可以知道该注解用来给`RestTemplate`标记,以使用负载均衡的客户端(`LoadBalancerClient`)来配置它。 - -通过搜索`LoadBalancerClient`,我们可以发现这是Spring Cloud中定义的一个接口: - -``` -public interface LoadBalancerClient { - - ServiceInstance choose(String serviceId); - - T execute(String serviceId, LoadBalancerRequest request) throws IOException; - - URI reconstructURI(ServiceInstance instance, URI original); - -} -``` - -从该接口中,我们可以通过定义的抽象方法来了解到客户端负载均衡器中应具备的几种能力: - -- `ServiceInstance choose(String serviceId)`:根据传入的服务名`serviceId`,从负载均衡器中挑选一个对应服务的实例。 -- `T execute(String serviceId, LoadBalancerRequest request) throws IOException`:使用从负载均衡器中挑选出的服务实例来执行请求内容。 -- `URI reconstructURI(ServiceInstance instance, URI original)`:为系统构建一个合适的“host:port”形式的URI。在分布式系统中,我们使用逻辑上的服务名称作为host来构建URI(替代服务实例的“host:port”形式)进行请求,比如:`http://myservice/path/to/service`。在该操作的定义中,前者`ServiceInstance`对象是带有host和port的具体服务实例,而后者URI对象则是使用逻辑服务名定义为host的URI,而返回的URI内容则是通过`ServiceInstance`的服务实例详情拼接出的具体“host:post”形式的请求地址。 - -顺着`LoadBalancerClient`接口的所属包`org.springframework.cloud.client.loadbalancer`,我们对其内容进行整理,可以得出如下图的关系: - -[![img](https://blog.didispace.com/assets/ribbon-code-1.png)](https://blog.didispace.com/assets/ribbon-code-1.png) - -从类的命名上我们初步判断`LoadBalancerAutoConfiguration`为实现客户端负载均衡器的自动化配置类。通过查看源码,我们可以验证这一点假设: - -``` -@Configuration -@ConditionalOnClass(RestTemplate.class) -@ConditionalOnBean(LoadBalancerClient.class) -public class LoadBalancerAutoConfiguration { - - @LoadBalanced - @Autowired(required = false) - private List restTemplates = Collections.emptyList(); - - @Bean - public SmartInitializingSingleton loadBalancedRestTemplateInitializer( - final List customizers) { - return new SmartInitializingSingleton() { - @Override - public void afterSingletonsInstantiated() { - for (RestTemplate restTemplate : LoadBalancerAutoConfiguration.this.restTemplates) { - for (RestTemplateCustomizer customizer : customizers) { - customizer.customize(restTemplate); - } - } - } - }; - } - - @Bean - @ConditionalOnMissingBean - public RestTemplateCustomizer restTemplateCustomizer( - final LoadBalancerInterceptor loadBalancerInterceptor) { - return new RestTemplateCustomizer() { - @Override - public void customize(RestTemplate restTemplate) { - List list = new ArrayList<>( - restTemplate.getInterceptors()); - list.add(loadBalancerInterceptor); - restTemplate.setInterceptors(list); - } - }; - } - - @Bean - public LoadBalancerInterceptor ribbonInterceptor( - LoadBalancerClient loadBalancerClient) { - return new LoadBalancerInterceptor(loadBalancerClient); - } - -} -``` - -从`LoadBalancerAutoConfiguration`类头上的注解可以知道Ribbon实现的负载均衡自动化配置需要满足下面两个条件: - -- `@ConditionalOnClass(RestTemplate.class)`:`RestTemplate`类必须存在于当前工程的环境中。 -- `@ConditionalOnBean(LoadBalancerClient.class)`:在Spring的Bean工程中有必须有`LoadBalancerClient`的实现Bean。 - -在该自动化配置类中,主要做了下面三件事: - -- 创建了一个`LoadBalancerInterceptor`的Bean,用于实现对客户端发起请求时进行拦截,以实现客户端负载均衡。 -- 创建了一个`RestTemplateCustomizer`的Bean,用于给`RestTemplate`增加`LoadBalancerInterceptor`拦截器。 -- 维护了一个被`@LoadBalanced`注解修饰的`RestTemplate`对象列表,并在这里进行初始化,通过调用`RestTemplateCustomizer`的实例来给需要客户端负载均衡的`RestTemplate`增加`LoadBalancerInterceptor`拦截器。 - -接下来,我们看看`LoadBalancerInterceptor`拦截器是如何将一个普通的`RestTemplate`变成客户端负载均衡的: - -``` -public class LoadBalancerInterceptor implements ClientHttpRequestInterceptor { - - private LoadBalancerClient loadBalancer; - - public LoadBalancerInterceptor(LoadBalancerClient loadBalancer) { - this.loadBalancer = loadBalancer; - } - - @Override - public ClientHttpResponse intercept(final HttpRequest request, final byte[] body, - final ClientHttpRequestExecution execution) throws IOException { - final URI originalUri = request.getURI(); - String serviceName = originalUri.getHost(); - return this.loadBalancer.execute(serviceName, - new LoadBalancerRequest() { - @Override - public ClientHttpResponse apply(final ServiceInstance instance) - throws Exception { - HttpRequest serviceRequest = new ServiceRequestWrapper(request, - instance); - return execution.execute(serviceRequest, body); - } - }); - } - - private class ServiceRequestWrapper extends HttpRequestWrapper { - - private final ServiceInstance instance; - - public ServiceRequestWrapper(HttpRequest request, ServiceInstance instance) { - super(request); - this.instance = instance; - } - - @Override - public URI getURI() { - URI uri = LoadBalancerInterceptor.this.loadBalancer.reconstructURI( - this.instance, getRequest().getURI()); - return uri; - } - } -} -``` - -通过源码以及之前的自动化配置类,我们可以看到在拦截器中注入了`LoadBalancerClient`的实现。当一个被`@LoadBalanced`注解修饰的`RestTemplate`对象向外发起HTTP请求时,会被`LoadBalancerInterceptor`类的`intercept`函数所拦截。由于我们在使用RestTemplate时候采用了服务名作为host,所以直接从`HttpRequest`的URI对象中通过getHost()就可以拿到服务名,然后调用`execute`函数去根据服务名来选择实例并发起实际的请求。 - -分析到这里,`LoadBalancerClient`还只是一个抽象的负载均衡器接口,所以我们还需要找到它的具体实现类来进一步分析。通过查看ribbon的源码,我们可以很容易的在`org.springframework.cloud.netflix.ribbon`包下找到对应的实现类:`RibbonLoadBalancerClient`。 - -``` -public T execute(String serviceId, LoadBalancerRequest request) throws IOException { - ILoadBalancer loadBalancer = getLoadBalancer(serviceId); - Server server = getServer(loadBalancer); - if (server == null) { - throw new IllegalStateException("No instances available for " + serviceId); - } - RibbonServer ribbonServer = new RibbonServer(serviceId, server, isSecure(server, - serviceId), serverIntrospector(serviceId).getMetadata(server)); - - RibbonLoadBalancerContext context = this.clientFactory - .getLoadBalancerContext(serviceId); - RibbonStatsRecorder statsRecorder = new RibbonStatsRecorder(context, server); - - try { - T returnVal = request.apply(ribbonServer); - statsRecorder.recordStats(returnVal); - return returnVal; - } - catch (IOException ex) { - statsRecorder.recordStats(ex); - throw ex; - } - catch (Exception ex) { - statsRecorder.recordStats(ex); - ReflectionUtils.rethrowRuntimeException(ex); - } - return null; -} -``` - -可以看到,在`execute`函数的实现中,第一步做的就是通过`getServer`根据传入的服务名`serviceId`去获得具体的服务实例: - -``` -protected Server getServer(ILoadBalancer loadBalancer) { - if (loadBalancer == null) { - return null; - } - return loadBalancer.chooseServer("default"); -} -``` - -通过`getServer`函数的实现源码,我们可以看到这里获取具体服务实例的时候并没有使用`LoadBalancerClient`接口中的`choose`函数,而是使用了ribbon自身的`ILoadBalancer`接口中定义的`chooseServer`函数。 - -我们先来认识一下`ILoadBalancer`接口: - -``` -public interface ILoadBalancer { - - public void addServers(List newServers); - - public Server chooseServer(Object key); - - public void markServerDown(Server server); - - public List getReachableServers(); - - public List getAllServers(); -} -``` - -可以看到,在该接口中定义了一个软负载均衡器需要的一系列抽象操作(未例举过期函数): - -- `addServers`:向负载均衡器中维护的实例列表增加服务实例。 -- `chooseServer`:通过某种策略,从负载均衡器中挑选出一个具体的服务实例。 -- `markServerDown`:用来通知和标识负载均衡器中某个具体实例已经停止服务,不然负载均衡器在下一次获取服务实例清单前都会认为服务实例均是正常服务的。 -- `getReachableServers`:获取当前正常服务的实例列表。 -- `getAllServers`:获取所有已知的服务实例列表,包括正常服务和停止服务的实例。 - -在该接口定义中涉及到的`Server`对象定义的是一个传统的服务端节点,在该类中存储了服务端节点的一些元数据信息,包括:host、port以及一些部署信息等。 - -[![img](https://blog.didispace.com/assets/ribbon-code-2.png)](https://blog.didispace.com/assets/ribbon-code-2.png) - -而对于该接口的实现,我们可以整理出如上图所示的结构。我们可以看到`BaseLoadBalancer`类实现了基础的负载均衡,而`DynamicServerListLoadBalancer`和`ZoneAwareLoadBalancer`在负载均衡的策略上做了一些功能的扩展。 - -那么在整合Ribbon的时候Spring Cloud默认采用了哪个具体实现呢?我们通过`RibbonClientConfiguration`配置类,可以知道在整合时默认采用了`ZoneAwareLoadBalancer`来实现负载均衡器。 - -``` -@Bean -@ConditionalOnMissingBean -public ILoadBalancer ribbonLoadBalancer(IClientConfig config, - ServerList serverList, ServerListFilter serverListFilter, - IRule rule, IPing ping) { - ZoneAwareLoadBalancer balancer = LoadBalancerBuilder.newBuilder() - .withClientConfig(config).withRule(rule).withPing(ping) - .withServerListFilter(serverListFilter).withDynamicServerList(serverList) - .buildDynamicServerListLoadBalancer(); - return balancer; -} -``` - -下面,我们再回到`RibbonLoadBalancerClient`的`execute`函数逻辑,在通过`ZoneAwareLoadBalancer`的`chooseServer`函数获取了负载均衡策略分配到的服务实例对象`Server`之后,将其内容包装成`RibbonServer`对象(该对象除了存储了服务实例的信息之外,还增加了服务名serviceId、是否需要使用HTTPS等其他信息),然后使用该对象再回调`LoadBalancerInterceptor`请求拦截器中`LoadBalancerRequest`的`apply(final ServiceInstance instance)`函数,向一个实际的具体服务实例发起请求,从而实现一开始以服务名为host的URI请求,到实际访问host:post形式的具体地址的转换。 - -`apply(final ServiceInstance instance)`函数中传入的`ServiceInstance`接口是对服务实例的抽象定义。在该接口中暴露了服务治理系统中每个服务实例需要提供的一些基本信息,比如:serviceId、host、port等,具体定义如下: - -``` -public interface ServiceInstance { - - String getServiceId(); - - String getHost(); - - int getPort(); - - boolean isSecure(); - - URI getUri(); - - Map getMetadata(); -} -``` - -而上面提到的具体包装`Server`服务实例的`RibbonServer`对象就是`ServiceInstance`接口的实现,可以看到它除了包含了`Server`对象之外,还存储了服务名、是否使用https标识以及一个Map类型的元数据集合。 - -``` -protected static class RibbonServer implements ServiceInstance { - - private final String serviceId; - private final Server server; - private final boolean secure; - private Map metadata; - - protected RibbonServer(String serviceId, Server server) { - this(serviceId, server, false, Collections. emptyMap()); - } - - protected RibbonServer(String serviceId, Server server, boolean secure, - Map metadata) { - this.serviceId = serviceId; - this.server = server; - this.secure = secure; - this.metadata = metadata; - } - - // 省略实现ServiceInstance的一些获取Server信息的get函数 - ... -} -``` - -那么`apply(final ServiceInstance instance)`函数,在接收到了具体`ServiceInstance`实例后,是如何通过`LoadBalancerClient`接口中的`reconstructURI`操作来组织具体请求地址的呢? - -``` -@Override -public ClientHttpResponse apply(final ServiceInstance instance) - throws Exception { - HttpRequest serviceRequest = new ServiceRequestWrapper(request, instance); - return execution.execute(serviceRequest, body); -} -``` - -从`apply`的实现中,我们可以看到它具体执行的时候,还传入了`ServiceRequestWrapper`对象,该对象继承了`HttpRequestWrapper`并重写了`getURI`函数,重写后的`getURI`会通过调用`LoadBalancerClient`接口的`reconstructURI`函数来重新构建一个URI来进行访问。 - -``` -private class ServiceRequestWrapper extends HttpRequestWrapper { - - private final ServiceInstance instance; - - ... - - @Override - public URI getURI() { - URI uri = LoadBalancerInterceptor.this.loadBalancer.reconstructURI( - this.instance, getRequest().getURI()); - return uri; - } -} -``` - -在`LoadBalancerInterceptor`拦截器中,`ClientHttpRequestExecution`的实例具体执行`execution.execute(serviceRequest, body)`时,会调用`InterceptingClientHttpRequest`下`InterceptingRequestExecution`类的`execute`函数,具体实现如下: - -``` -public ClientHttpResponse execute(HttpRequest request, byte[] body) throws IOException { - if (this.iterator.hasNext()) { - ClientHttpRequestInterceptor nextInterceptor = this.iterator.next(); - return nextInterceptor.intercept(request, body, this); - } - else { - ClientHttpRequest delegate = requestFactory.createRequest(request.getURI(), request.getMethod()); - delegate.getHeaders().putAll(request.getHeaders()); - if (body.length > 0) { - StreamUtils.copy(body, delegate.getBody()); - } - return delegate.execute(); - } -} -``` - -可以看到在创建请求的时候`requestFactory.createRequest(request.getURI(), request.getMethod());`,这里`request.getURI()`会调用之前介绍的`ServiceRequestWrapper`对象中重写的`getURI`函数。此时,它就会使用`RibbonLoadBalancerClient`中实现的`reconstructURI`来组织具体请求的服务实例地址。 - -``` -public URI reconstructURI(ServiceInstance instance, URI original) { - Assert.notNull(instance, "instance can not be null"); - String serviceId = instance.getServiceId(); - RibbonLoadBalancerContext context = this.clientFactory - .getLoadBalancerContext(serviceId); - Server server = new Server(instance.getHost(), instance.getPort()); - boolean secure = isSecure(server, serviceId); - URI uri = original; - if (secure) { - uri = UriComponentsBuilder.fromUri(uri).scheme("https").build().toUri(); - } - return context.reconstructURIWithServer(server, uri); -} -``` - -从`reconstructURI`函数中,我们可以看到,它通过`ServiceInstance`实例对象的`serviceId`,从`SpringClientFactory`类的`clientFactory`对象中获取对应`serviceId`的负载均衡器的上下文`RibbonLoadBalancerContext`对象。然后根据`ServiceInstance`中的信息来构建具体服务实例信息的`Server`对象,并使用`RibbonLoadBalancerContext`对象的`reconstructURIWithServer`函数来构建服务实例的URI。 - -为了帮助理解,简单介绍一下上面提到的`SpringClientFactory`和`RibbonLoadBalancerContext`: - -- `SpringClientFactory`类是一个用来创建客户端负载均衡器的工厂类,该工厂会为每一个不同名的ribbon客户端生成不同的Spring上下文。 -- `RibbonLoadBalancerContext`类是`LoadBalancerContext`的子类,该类用于存储一些被负载均衡器使用的上下文内容和Api操作(`reconstructURIWithServer`就是其中之一)。 - -从`reconstructURIWithServer`的实现中我们可以看到,它同`reconstructURI`的定义类似。只是`reconstructURI`的第一个保存具体服务实例的参数使用了Spring Cloud定义的`ServiceInstance`,而`reconstructURIWithServer`中使用了Netflix中定义的`Server`,所以在`RibbonLoadBalancerClient`实现`reconstructURI`时候,做了一次转换,使用`ServiceInstance`的host和port信息来构建了一个`Server`对象来给`reconstructURIWithServer`使用。从`reconstructURIWithServer`的实现逻辑中,我们可以看到,它从`Server`对象中获取host和port信息,然后根据以服务名为host的`URI`对象original中获取其他请求信息,将两者内容进行拼接整合,形成最终要访问的服务实例的具体地址。 - -``` -public class LoadBalancerContext implements IClientConfigAware { - - ... - - public URI reconstructURIWithServer(Server server, URI original) { - String host = server.getHost(); - int port = server .getPort(); - if (host.equals(original.getHost()) - && port == original.getPort()) { - return original; - } - String scheme = original.getScheme(); - if (scheme == null) { - scheme = deriveSchemeAndPortFromPartialUri(original).first(); - } - - try { - StringBuilder sb = new StringBuilder(); - sb.append(scheme).append("://"); - if (!Strings.isNullOrEmpty(original.getRawUserInfo())) { - sb.append(original.getRawUserInfo()).append("@"); - } - sb.append(host); - if (port >= 0) { - sb.append(":").append(port); - } - sb.append(original.getRawPath()); - if (!Strings.isNullOrEmpty(original.getRawQuery())) { - sb.append("?").append(original.getRawQuery()); - } - if (!Strings.isNullOrEmpty(original.getRawFragment())) { - sb.append("#").append(original.getRawFragment()); - } - URI newURI = new URI(sb.toString()); - return newURI; - } catch (URISyntaxException e) { - throw new RuntimeException(e); - } - } - - ... -} -``` - -另外,从`RibbonLoadBalancerClient`的`execute`的函数逻辑中,我们还能看到在回调拦截器中,执行具体的请求之后,ribbon还通过`RibbonStatsRecorder`对象对服务的请求还进行了跟踪记录,这里不再展开说明,有兴趣的读者可以继续研究。 - -分析到这里,我们已经可以大致理清Spring Cloud中使用Ribbon实现客户端负载均衡的基本脉络。了解了它是如何通过`LoadBalancerInterceptor`拦截器对`RestTemplate`的请求进行拦截,并利用Spring Cloud的负载均衡器`LoadBalancerClient`将以逻辑服务名为host的URI转换成具体的服务实例的过程。同时通过分析`LoadBalancerClient`的Ribbon实现`RibbonLoadBalancerClient`,可以知道在使用Ribbon实现负载均衡器的时候,实际使用的还是Ribbon中定义的`ILoadBalancer`接口的实现,自动化配置会采用`ZoneAwareLoadBalancer`的实例来进行客户端负载均衡实现。 - -## 负载均衡器 - -通过之前的分析,我们已经对Spring Cloud如何使用Ribbon有了基本的了解。虽然Spring Cloud中定义了`LoadBalancerClient`为负载均衡器的接口,并且针对Ribbon实现了`RibbonLoadBalancerClient`,但是它在具体实现客户端负载均衡时,则是通过Ribbon的`ILoadBalancer`接口实现。在上一节分析时候,我们对该接口的实现结构已经做了一些简单的介绍,下面我们根据`ILoadBalancer`接口的实现类逐个看看它都是如何实现客户端负载均衡的。 - -### AbstractLoadBalancer - -`AbstractLoadBalancer`是`ILoadBalancer`接口的抽象实现。在该抽象类中定义了一个关于服务实例的分组枚举类`ServerGroup`,它包含了三种不同类型:ALL-所有服务实例、STATUS_UP-正常服务的实例、STATUS_NOT_UP-停止服务的实例;实现了一个`chooseServer()`函数,该函数通过调用接口中的`chooseServer(Object key)`实现,其中参数`key`为null,表示在选择具体服务实例时忽略`key`的条件判断;最后还定义了两个抽象函数,`getServerList(ServerGroup serverGroup)`定义了根据分组类型来获取不同的服务实例列表,`getLoadBalancerStats()`定义了获取`LoadBalancerStats`对象的方法,`LoadBalancerStats`对象被用来存储负载均衡器中各个服务实例当前的属性和统计信息,这些信息非常有用,我们可以利用这些信息来观察负载均衡器的运行情况,同时这些信息也是用来制定负载均衡策略的重要依据。 - -``` -public abstract class AbstractLoadBalancer implements ILoadBalancer { - - public enum ServerGroup{ - ALL, - STATUS_UP, - STATUS_NOT_UP - } - - public Server chooseServer() { - return chooseServer(null); - } - - public abstract List getServerList(ServerGroup serverGroup); - - public abstract LoadBalancerStats getLoadBalancerStats(); -} -``` - - - -### BaseLoadBalancer - -`BaseLoadBalancer`类是Ribbon负载均衡器的基础实现类,在该类中定义很多关于均衡负载器相关的基础内容: - -- 定义并维护了两个存储服务实例`Server`对象的列表。一个用于存储所有服务实例的清单,一个用于存储正常服务的实例清单。 - - ``` - @Monitor(name = PREFIX + "AllServerList", type = DataSourceType.INFORMATIONAL) - protected volatile List allServerList = Collections - .synchronizedList(new ArrayList()); - @Monitor(name = PREFIX + "UpServerList", type = DataSourceType.INFORMATIONAL) - protected volatile List upServerList = Collections - .synchronizedList(new ArrayList()); - ``` - -- 定义了之前我们提到的用来存储负载均衡器各服务实例属性和统计信息的`LoadBalancerStats`对象。 - -- 定义了检查服务实例是否正常服务的`IPing`对象,在`BaseLoadBalancer`中默认为null,需要在构造时注入它的具体实现。 - -- 定义了检查服务实例操作的执行策略对象`IPingStrategy`,在`BaseLoadBalancer`中默认使用了该类中定义的静态内部类`SerialPingStrategy`实现。根据源码,我们可以看到该策略采用线性遍历ping服务实例的方式实现检查。该策略在当我们实现的`IPing`速度不理想,或是`Server`列表过大时,可能变的不是很为理想,这时候我们需要通过实现`IPingStrategy`接口并实现`pingServers(IPing ping, Server[] servers)`函数去扩展ping的执行策略。 - -``` -private static class SerialPingStrategy implements IPingStrategy { - @Override - public boolean[] pingServers(IPing ping, Server[] servers) { - int numCandidates = servers.length; - boolean[] results = new boolean[numCandidates]; - - if (logger.isDebugEnabled()) { - logger.debug("LoadBalancer: PingTask executing [" - + numCandidates + "] servers configured"); - } - - for (int i = 0; i < numCandidates; i++) { - results[i] = false; - try { - if (ping != null) { - results[i] = ping.isAlive(servers[i]); - } - } catch (Throwable t) { - logger.error("Exception while pinging Server:" - + servers[i], t); - } - } - return results; - } -} -``` - -- 定义了负载均衡的处理规则`IRule`对象,从`BaseLoadBalancer`中`chooseServer(Object key)`的实现源码,我们可以知道负载均衡器实际进行服务实例选择任务是委托给了`IRule`实例中的`choose`函数来实现。而在这里,默认初始化了`RoundRobinRule`为`IRule`的实现对象。`RoundRobinRule`实现了最基本且常用的线性负载均衡规则。 - -``` -public Server chooseServer(Object key) { - if (counter == null) { - counter = createCounter(); - } - counter.increment(); - if (rule == null) { - return null; - } else { - try { - return rule.choose(key); - } catch (Throwable t) { - return null; - } - } -} -``` - -- 启动ping任务:在`BaseLoadBalancer`的默认构造函数中,会直接启动一个用于定时检查`Server`是否健康的任务。该任务默认的执行间隔为:10秒。 - -- 实现了`ILoadBalancer`接口定义的负载均衡器应具备的一系列基本操作: - - - `addServers(List newServers)`:向负载均衡器中增加新的服务实例列表,该实现将原本已经维护着的所有服务实例清单`allServerList`和新传入的服务实例清单`newServers`都加入到`newList`中,然后通过调用`setServersList`函数对`newList`进行处理,在`BaseLoadBalancer`中实现的时候会使用新的列表覆盖旧的列表。而之后介绍的几个扩展实现类对于服务实例清单更新的优化都是对`setServersList`函数的重写来实现的。 - - ``` - public void addServers(List newServers) { - if (newServers != null && newServers.size() > 0) { - try { - ArrayList newList = new ArrayList(); - newList.addAll(allServerList); - newList.addAll(newServers); - setServersList(newList); - } catch (Exception e) { - logger.error("Exception while adding Servers", e); - } - } - } - ``` - - - `chooseServer(Object key)`:挑选一个具体的服务实例,在上面介绍`IRule`的时候,已经做了说明,这里不再赘述。 - - - `markServerDown(Server server)`:标记某个服务实例暂停服务。 - - ``` - public void markServerDown(Server server) { - if (server == null) { - return; - } - if (!server.isAlive()) { - return; - } - logger.error("LoadBalancer: markServerDown called on [" - + server.getId() + "]"); - server.setAlive(false); - notifyServerStatusChangeListener(singleton(server)); - } - ``` - - - `getReachableServers()`:获取可用的服务实例列表。由于`BaseLoadBalancer`中单独维护了一个正常服务的实例清单,所以直接返回即可。 - - ``` - public List getReachableServers() { - return Collections.unmodifiableList(upServerList); - } - ``` - - - `getAllServers()`:获取所有的服务实例列表。由于`BaseLoadBalancer`中单独维护了一个所有服务的实例清单,所以也直接返回它即可。 - - ``` - public List getAllServers() { - return Collections.unmodifiableList(allServerList); - } - ``` - -### DynamicServerListLoadBalancer - -`DynamicServerListLoadBalancer`类继承于`BaseLoadBalancer`类,它是对基础负载均衡器的扩展。在该负载均衡器中,实现了服务实例清单的在运行期的动态更新能力;同时,它还具备了对服务实例清单的过滤功能,也就是说我们可以通过过滤器来选择性的获取一批服务实例清单。下面我们具体来看看在该类中增加了一些什么内容: - -#### ServerList - -从`DynamicServerListLoadBalancer`的成员定义中,我们马上可以发现新增了一个关于服务列表的操作对象:`ServerList serverListImpl`。其中泛型`T`从类名中对于T的限定`DynamicServerListLoadBalancer`可以获知它是一个`Server`的子类,即代表了一个具体的服务实例的扩展类。而`ServerList`接口定义如下所示: - -``` -public interface ServerList { - - public List getInitialListOfServers(); - - public List getUpdatedListOfServers(); -} -``` - -它定义了两个抽象方法:`getInitialListOfServers`用于获取初始化的服务实例清单,而`getUpdatedListOfServers`用于获取更新的服务实例清单。那么该接口的实现有哪些呢?通过搜索源码,我们可以整出如下图的结构: - -[![img](https://blog.didispace.com/assets/ribbon-code-3.png)](https://blog.didispace.com/assets/ribbon-code-3.png) - -从图中我们可以看到有很多个`ServerList`的实现类,那么在`DynamicServerListLoadBalancer`中的`ServerList`默认配置到底使用了哪个具体实现呢?既然在该负载均衡器中需要实现服务实例的动态更新,那么势必需要ribbon具备访问eureka来获取服务实例的能力,所以我们从Spring Cloud整合ribbon与eureka的包`org.springframework.cloud.netflix.ribbon.eureka`下探索,可以找到配置类`EurekaRibbonClientConfiguration`,在该类中可以找到看到下面创建`ServerList`实例的内容: - -``` -@Bean -@ConditionalOnMissingBean -public ServerList ribbonServerList(IClientConfig config) { - DiscoveryEnabledNIWSServerList discoveryServerList = new DiscoveryEnabledNIWSServerList( - config); - DomainExtractingServerList serverList = new DomainExtractingServerList( - discoveryServerList, config, this.approximateZoneFromHostname); - return serverList; -} -``` - -可以看到,这里创建的是一个`DomainExtractingServerList`实例,从下面它的源码中我们可以看到在它内部还定义了一个`ServerList list`。同时,`DomainExtractingServerList`类中对`getInitialListOfServers`和`getUpdatedListOfServers`的具体实现,其实委托给了内部定义的`ServerList list`对象,而该对象是通过创建`DomainExtractingServerList`时候,由构造函数传入的`DiscoveryEnabledNIWSServerList`实现的。 - -``` -public class DomainExtractingServerList implements ServerList { - - private ServerList list; - private IClientConfig clientConfig; - private boolean approximateZoneFromHostname; - - public DomainExtractingServerList(ServerList list, - IClientConfig clientConfig, boolean approximateZoneFromHostname) { - this.list = list; - this.clientConfig = clientConfig; - this.approximateZoneFromHostname = approximateZoneFromHostname; - } - - @Override - public List getInitialListOfServers() { - List servers = setZones(this.list - .getInitialListOfServers()); - return servers; - } - - @Override - public List getUpdatedListOfServers() { - List servers = setZones(this.list - .getUpdatedListOfServers()); - return servers; - } - ... -} -``` - -那么`DiscoveryEnabledNIWSServerList`是如何实现这两个服务实例的获取的呢?我们从源码中可以看到这两个方法都是通过该类中的一个私有函数`obtainServersViaDiscovery`来通过服务发现机制来实现服务实例的获取。 - -``` -@Override -public List getInitialListOfServers(){ - return obtainServersViaDiscovery(); -} - -@Override -public List getUpdatedListOfServers(){ - return obtainServersViaDiscovery(); -} -``` - -而`obtainServersViaDiscovery`的实现逻辑如下,主要依靠`EurekaClient`从服务注册中心中获取到具体的服务实例`InstanceInfo`列表(`EurekaClient`的具体实现,我们在分析Eureka的源码时已经做了详细的介绍,这里传入的`vipAddress`可以理解为逻辑上的服务名,比如“USER-SERVICE”)。接着,对这些服务实例进行遍历,将状态为“UP”(正常服务)的实例转换成`DiscoveryEnabledServer`对象,最后将这些实例组织成列表返回。 - -``` -private List obtainServersViaDiscovery() { - List serverList = new ArrayList(); - - if (eurekaClientProvider == null || eurekaClientProvider.get() == null) { - logger.warn("EurekaClient has not been initialized yet, returning an empty list"); - return new ArrayList(); - } - - EurekaClient eurekaClient = eurekaClientProvider.get(); - if (vipAddresses!=null){ - for (String vipAddress : vipAddresses.split(",")) { - List listOfInstanceInfo = eurekaClient.getInstancesByVipAddress( - vipAddress, isSecure, targetRegion); - for (InstanceInfo ii : listOfInstanceInfo) { - if (ii.getStatus().equals(InstanceStatus.UP)) { - // 省略了一些实例信息的加工逻辑 - DiscoveryEnabledServer des = new DiscoveryEnabledServer(ii, isSecure, shouldUseIpAddr); - des.setZone(DiscoveryClient.getZone(ii)); - serverList.add(des); - } - } - if (serverList.size()>0 && prioritizeVipAddressBasedServers){ - break; - } - } - } - return serverList; -} -``` - -在`DiscoveryEnabledNIWSServerList`中通过`EurekaClient`从服务注册中心获取到最新的服务实例清单后,返回的`List`到了`DomainExtractingServerList`类中,将继续通过`setZones`函数进行处理,而这里的处理具体内容如下,主要完成将`DiscoveryEnabledNIWSServerList`返回的`List`列表中的元素,转换成内部定义的`DiscoveryEnabledServer`的子类对象`DomainExtractingServer`,在该对象的构造函数中将为服务实例对象设置一些必要的属性,比如id、zone、isAliveFlag、readyToServe等信息。 - -``` -private List setZones(List servers) { - List result = new ArrayList<>(); - boolean isSecure = this.clientConfig.getPropertyAsBoolean( - CommonClientConfigKey.IsSecure, Boolean.TRUE); - boolean shouldUseIpAddr = this.clientConfig.getPropertyAsBoolean( - CommonClientConfigKey.UseIPAddrForServer, Boolean.FALSE); - for (DiscoveryEnabledServer server : servers) { - result.add(new DomainExtractingServer(server, isSecure, shouldUseIpAddr, - this.approximateZoneFromHostname)); - } - return result; -} -``` - -###### ServerListUpdater - -通过上面的分析我们已经知道了Ribbon与Eureka整合后,如何实现从Eureka Server中获取服务实例清单。那么它又是如何触发向Eureka Server去获取服务实例清单以及如何在获取到服务实例清单后更新本地的服务实例清单的呢?继续来看`DynamicServerListLoadBalancer`中的实现内容,我们可以很容易的找到下面定义的关于`ServerListUpdater`的内容: - -``` -protected final ServerListUpdater.UpdateAction updateAction = new ServerListUpdater.UpdateAction() { - @Override - public void doUpdate() { - updateListOfServers(); - } -}; - -protected volatile ServerListUpdater serverListUpdater; -``` - -根据该接口的命名,我们基本就能猜到,这个对象实现的是对`ServerList`的更新,所以可以称它为“服务更新器”,从下面的源码中可以看到,在`ServerListUpdater`内部还定义了一个`UpdateAction`接口,上面定义的`updateAction`对象就是以匿名内部类的方式创建了一个它的具体实现,其中`doUpdate`实现的内容就是对`ServerList`的具体更新操作。除此之外,“服务更新器”中还定义了一系列控制它和获取它一些信息的操作。 - -``` -public interface ServerListUpdater { - - public interface UpdateAction { - void doUpdate(); - } - - // 启动服务更新器,传入的UpdateAction对象为更新操作的具体实现。 - void start(UpdateAction updateAction); - - // 停止服务更新器 - void stop(); - - // 获取最近的更新时间戳 - String getLastUpdate(); - - // 获取上一次更新到现在的时间间隔,单位为毫秒 - long getDurationSinceLastUpdateMs(); - - // 获取错过的更新周期数 - int getNumberMissedCycles(); - - // 获取核心线程数 - int getCoreThreads(); -} -``` - -而`ServerListUpdater`的实现类不多,具体下图所示。 - -[![img](https://blog.didispace.com/assets/ribbon-code-4.png)](https://blog.didispace.com/assets/ribbon-code-4.png) - -根据两个类的注释,我们可以很容易的知道它们的作用分别是: - -- `PollingServerListUpdater`:动态服务列表更新的默认策略,也就是说`DynamicServerListLoadBalancer`负载均衡器中的默认实现就是它,它通过定时任务的方式进行服务列表的更新。 -- `EurekaNotificationServerListUpdater`:该更新器也可服务于`DynamicServerListLoadBalancer`负载均衡器,但是它的触发机制与`PollingServerListUpdater`不同,它需要利用Eureka的事件监听器来驱动服务列表的更新操作。 - -下面我们来详细看看它默认实现的`PollingServerListUpdater`。先从用于启动“服务更新器”的`start`函数源码看起,具体如下。我们可以看到`start`函数的实现内容验证了之前提到的:以定时任务的方式进行服务列表的更新。它先创建了一个`Runnable`的线程实现,在该实现中调用了上面提到的具体更新服务实例列表的方法`updateAction.doUpdate()`,最后再为这个`Runnable`的线程实现启动了一个定时任务来执行。 - -``` -@Override -public synchronized void start(final UpdateAction updateAction) { - if (isActive.compareAndSet(false, true)) { - final Runnable wrapperRunnable = new Runnable() { - @Override - public void run() { - if (!isActive.get()) { - if (scheduledFuture != null) { - scheduledFuture.cancel(true); - } - return; - } - try { - updateAction.doUpdate(); - lastUpdated = System.currentTimeMillis(); - } catch (Exception e) { - logger.warn("Failed one update cycle", e); - } - } - }; - - scheduledFuture = getRefreshExecutor().scheduleWithFixedDelay( - wrapperRunnable, - initialDelayMs, - refreshIntervalMs, - TimeUnit.MILLISECONDS - ); - } else { - logger.info("Already active, no-op"); - } -} -``` - -继续看`PollingServerListUpdater`的其他内容,我们可以找到用于启动定时任务的2个重要参数`initialDelayMs`和`refreshIntervalMs`的默认定义分别为1000和30*1000,单位为毫秒。也就是说更新服务实例在初始化之后延迟1秒后开始执行,并以30秒为周期重复执行。除了这些内容之外,我们还能看到它还会记录最后更新时间、是否存活等信息,同时也实现了`ServerListUpdater`中定义的一些其他操作内容,这些操作相对比较简单,这里不再具体说明,有兴趣的读者可以自己查看源码了解其实现原理。 - -#### ServerListFilter - -在了解了更新服务实例的定时任务是如何启动的之后,我们继续回到`updateAction.doUpdate()`调用的具体实现位置,在`DynamicServerListLoadBalancer`中,它的实际实现委托给了`updateListOfServers`函数,具体实现如下: - -``` -public void updateListOfServers() { - List servers = new ArrayList(); - if (serverListImpl != null) { - servers = serverListImpl.getUpdatedListOfServers(); - LOGGER.debug("List of Servers for {} obtained from Discovery client: {}", - getIdentifier(), servers); - - if (filter != null) { - servers = filter.getFilteredListOfServers(servers); - LOGGER.debug("Filtered List of Servers for {} obtained from Discovery client: {}", - getIdentifier(), servers); - } - } - updateAllServerList(servers); -} -``` - -可以看到,这里终于用到了我们之前提到的`ServerList`的`getUpdatedListOfServers`,通过之前的介绍我们已经可以知道这一步实现了从Eureka Server中获取服务可用实例的列表。在获得了服务实例列表之后,这里又将引入一个新的对象`filter`,追朔该对象的定义,我们可以找到它是`ServerListFilter`定义的。 - -`ServerListFilter`接口非常简单,该接口中之定义了一个方法`List getFilteredListOfServers(List servers)`,主要用于实现对服务实例列表的过滤,通过传入的服务实例清单,根据一些规则返回过滤后的服务实例清单。该接口的实现如下图所示: - -[![img](https://blog.didispace.com/assets/ribbon-code-6.png)](https://blog.didispace.com/assets/ribbon-code-6.png) - -其中,除了`ZonePreferenceServerListFilter`的实现是Spring Cloud Netflix中对Ribbon的扩展实现外,其他均是Netflix Ribbon中的实现类。我们可以分别看看这些过滤器实现都有什么特点: - -- `AbstractServerListFilter`:这是一个抽象过滤器,在这里定义了过滤时需要的一个重要依据对象`LoadBalancerStats`,我们在之前介绍过的,该对象存储了关于负载均衡器的一些属性和统计信息等。 - -``` -public abstract class AbstractServerListFilter implements ServerListFilter { - - private volatile LoadBalancerStats stats; - - public void setLoadBalancerStats(LoadBalancerStats stats) { - this.stats = stats; - } - - public LoadBalancerStats getLoadBalancerStats() { - return stats; - } -} -``` - -- `ZoneAffinityServerListFilter`:该过滤器基于“区域感知(Zone Affinity)”的方式实现服务实例的过滤,也就是说它会根据提供服务的实例所处区域(Zone)与消费者自身的所处区域(Zone)进行比较,过滤掉那些不是同处一个区域的实例。 - -``` -public List getFilteredListOfServers(List servers) { - if (zone != null && (zoneAffinity || zoneExclusive) && servers !=null && servers.size() > 0){ - List filteredServers = Lists.newArrayList(Iterables.filter( - servers, this.zoneAffinityPredicate.getServerOnlyPredicate())); - if (shouldEnableZoneAffinity(filteredServers)) { - return filteredServers; - } else if (zoneAffinity) { - overrideCounter.increment(); - } - } - return servers; -} -``` - -从上面的源码中我们可以看到,对于服务实例列表的过滤是通过`Iterables.filter(servers, this.zoneAffinityPredicate.getServerOnlyPredicate())`来实现的,其中判断依据由`ZoneAffinityPredicate`实现服务实例与消费者的Zone比较。而在过滤之后,这里并不会马上返回过滤的结果,而是通过`shouldEnableZoneAffinity`函数来判断是否要启用“区域感知”的功能,从下面`shouldEnableZoneAffinity`的实现中,我们可以看到,它使用了`LoadBalancerStats`的`getZoneSnapshot`方法来获取这些过滤后的同区域实例的基础指标(包含了:实例数量、断路器断开数、活动请求数、实例平均负载等),根据一系列的算法求出下面的几个评价值并与设置的阈值对比(下面的为默认值),若有一个条件符合,就不启用“区域感知”过滤的服务实例清单。这一算法实现对于集群出现区域故障时,依然可以依靠其他区域的实例进行正常服务提供了完善的高可用保障。同时,通过这里的介绍,我们也可以关联着来理解之前介绍Eureka的时候提到的对于区域分配设计来保证跨区域故障的高可用问题。 - -- blackOutServerPercentage:故障实例百分比(断路器断开数 / 实例数量) >= 0.8 -- activeReqeustsPerServer:实例平均负载 >= 0.6 -- availableServers:可用实例数(实例数量 - 断路器断开数) < 2 - -``` -private boolean shouldEnableZoneAffinity(List filtered) { - if (!zoneAffinity && !zoneExclusive) { - return false; - } - if (zoneExclusive) { - return true; - } - LoadBalancerStats stats = getLoadBalancerStats(); - if (stats == null) { - return zoneAffinity; - } else { - logger.debug("Determining if zone affinity should be enabled with given server list: {}", filtered); - ZoneSnapshot snapshot = stats.getZoneSnapshot(filtered); - double loadPerServer = snapshot.getLoadPerServer(); - int instanceCount = snapshot.getInstanceCount(); - int circuitBreakerTrippedCount = snapshot.getCircuitTrippedCount(); - if (((double) circuitBreakerTrippedCount) / instanceCount >= blackOutServerPercentageThreshold.get() - || loadPerServer >= activeReqeustsPerServerThreshold.get() - || (instanceCount - circuitBreakerTrippedCount) < availableServersThreshold.get()) { - logger.debug("zoneAffinity is overriden. blackOutServerPercentage: {}, activeReqeustsPerServer: {}, availableServers: {}", - new Object[] {(double) circuitBreakerTrippedCount / instanceCount, loadPerServer, instanceCount - circuitBreakerTrippedCount}); - return false; - } else { - return true; - } - } -} -``` - -- `DefaultNIWSServerListFilter`:该过滤器完全继承自`ZoneAffinityServerListFilter`,是默认的NIWS(Netflix Internal Web Service)过滤器。 -- `ServerListSubsetFilter`:该过滤器也继承自`ZoneAffinityServerListFilter`,它非常适用于拥有大规模服务器集群(上百或更多)的系统。因为它可以产生一个“区域感知”结果的子集列表,同时它还能够通过比较服务实例的通信失败数量和并发连接数来判定该服务是否健康来选择性的从服务实例列表中剔除那些相对不够健康的实例。该过滤器的实现主要分为三步: - 1. 获取“区域感知”的过滤结果,来作为候选的服务实例清单 - 2. 从当前消费者维护的服务实例子集中剔除那些相对不够健康的实例(同时也将这些实例从候选清单中剔除,防止第三步的时候又被选入),不够健康的标准如下: - a. 服务实例的并发连接数超过客户端配置的值,默认为`0`,配置参数为:`..ServerListSubsetFilter.eliminationConnectionThresold` - b. 服务实例的失败数超过客户端配置的值,默认为`0`,配置参数为:`..ServerListSubsetFilter.eliminationFailureThresold` - c. 如果按符合上面任一规则的服务实例剔除后,剔除比例小于客户端默认配置的百分比,默认为`0.1`(10%),配置参数为:`..ServerListSubsetFilter.forceEliminatePercent`。那么就先对剩下的实例列表进行健康排序,再开始从最不健康实例进行剔除,直到达到配置的剔除百分比。 - 3. 在完成剔除后,清单已经少了至少10%(默认值)的服务实例,最后通过随机的方式从候选清单中选出一批实例加入到清单中,以保持服务实例子集与原来的数量一致,而默认的实例子集数量为`20`,其配置参数为:`..ServerListSubsetFilter.size`。 -- `ZonePreferenceServerListFilter`:Spring Cloud整合时新增的过滤器。若使用Spring Cloud整合Eureka和Ribbon时会默认使用该过滤器。它实现了通过配置或者Eureka实例元数据的所属区域(Zone)来过滤出同区域的服务实例。如下面的源码所示,它的实现非常简单,首先通过父类`ZoneAffinityServerListFilter`的过滤器来获得“区域感知”的服务实例列表,然后遍历这个结果取出根据消费者配置预设的区域Zone来进行过滤,如果过滤的结果是空的就直接返回父类获取的结果,如果不为空就返回通过消费者配置的Zone过滤后的结果。 - -``` -@Override -public List getFilteredListOfServers(List servers) { - List output = super.getFilteredListOfServers(servers); - if (this.zone != null && output.size() == servers.size()) { - List local = new ArrayList(); - for (Server server : output) { - if (this.zone.equalsIgnoreCase(server.getZone())) { - local.add(server); - } - } - if (!local.isEmpty()) { - return local; - } - } - return output; -} -``` - -### ZoneAwareLoadBalancer - -`ZoneAwareLoadBalancer`负载均衡器是对`DynamicServerListLoadBalancer`的扩展。在`DynamicServerListLoadBalancer`中,我们可以看到它并没有重写选择具体服务实例的`chooseServer`函数,所以它依然会采用在`BaseLoadBalancer`中实现的算法,使用`RoundRobinRule`规则,以线性轮询的方式来选择调用的服务实例,该算法实现简单并没有区域(Zone)的概念,所以它会把所有实例视为一个Zone下的节点来看待,这样就会周期性的产生跨区域(Zone)访问的情况,由于跨区域会产生更高的延迟,这些实例主要以防止区域性故障实现高可用为目的而不能作为常规访问的实例,所以在多区域部署的情况下会有一定的性能问题,而该负载均衡器则可以避免这样的问题。那么它是如何实现的呢? - -首先,在`ZoneAwareLoadBalancer`中,我们可以发现,它并没有重写`setServersList`,说明实现服务实例清单的更新主逻辑没有修改。但是我们可以发现它重写了这个函数:`setServerListForZones(Map> zoneServersMap)`。看到这里可能会有一些陌生,因为它并不是接口中定义的必备函数,所以我们不妨去父类`DynamicServerListLoadBalancer`中寻找一下该函数,我们可以找到下面的定义了: - -``` -public void setServersList(List lsrv) { - super.setServersList(lsrv); - List serverList = (List) lsrv; - Map> serversInZones = new HashMap>(); - ... - setServerListForZones(serversInZones); -} - -protected void setServerListForZones(Map> zoneServersMap) { - LOGGER.debug("Setting server list for zones: {}", zoneServersMap); - getLoadBalancerStats().updateZoneServerMapping(zoneServersMap); -} -``` - -`setServerListForZones`函数的调用位于更新服务实例清单函数`setServersList`的最后,同时从其实现内容来看,它在父类`DynamicServerListLoadBalancer`中的作用是根据按区域Zone分组的实例列表,为负载均衡器中的`LoadBalancerStats`对象创建`ZoneStats`并放入`Map zoneStatsMap`集合中,每一个区域Zone会对应一个`ZoneStats`,它用于存储每个Zone的一些状态和统计信息。 - -在`ZoneAwareLoadBalancer`中对`setServerListForZones`的重写如下: - -``` -protected void setServerListForZones(Map> zoneServersMap) { - super.setServerListForZones(zoneServersMap); - if (balancers == null) { - balancers = new ConcurrentHashMap(); - } - for (Map.Entry> entry: zoneServersMap.entrySet()) { - String zone = entry.getKey().toLowerCase(); - getLoadBalancer(zone).setServersList(entry.getValue()); - } - for (Map.Entry existingLBEntry: balancers.entrySet()) { - if (!zoneServersMap.keySet().contains(existingLBEntry.getKey())) { - existingLBEntry.getValue().setServersList(Collections.emptyList()); - } - } -} -``` - -可以看到,在该实现中创建了一个`ConcurrentHashMap()`类型的`balancers`对象,它将用来存储每个Zone区域对应的负载均衡器,而具体的负载均衡器的创建则是通过下面的第一个循环中调用`getLoadBalancer`函数来完成,同时在创建负载均衡器的时候会创建它的规则(如果当前实现中没有`IRULE`的实例,就创建一个`AvailabilityFilteringRule`规则;如果已经有具体实例,就clone一个),在创建完负载均衡器后又马上调用`setServersList`函数为其设置对应Zone区域的实例清单。而第二个循环则是对Zone区域中实例清单的检查,看看是否有Zone区域下已经没有实例了,是的话就将`balancers`中对应Zone区域的实例列表清空,该操作的作用是为了后续选择节点时,防止过时的Zone区域统计信息干扰具体实例的选择算法。 - -在了解了该负载均衡器是如何扩展服务实例清单的实现后,我们来具体看看它是如何挑选服务实例,来实现对区域的识别的: - -``` -public Server chooseServer(Object key) { - if (!ENABLED.get() || getLoadBalancerStats().getAvailableZones().size() <= 1) { - logger.debug("Zone aware logic disabled or there is only one zone"); - return super.chooseServer(key); - } - Server server = null; - try { - LoadBalancerStats lbStats = getLoadBalancerStats(); - Map zoneSnapshot = ZoneAvoidanceRule.createSnapshot(lbStats); - logger.debug("Zone snapshots: {}", zoneSnapshot); - ... - Set availableZones = ZoneAvoidanceRule.getAvailableZones(zoneSnapshot, triggeringLoad.get(), triggeringBlackoutPercentage.get()); - logger.debug("Available zones: {}", availableZones); - if (availableZones != null && availableZones.size() < zoneSnapshot.keySet().size()) { - String zone = ZoneAvoidanceRule.randomChooseZone(zoneSnapshot, availableZones); - logger.debug("Zone chosen: {}", zone); - if (zone != null) { - BaseLoadBalancer zoneLoadBalancer = getLoadBalancer(zone); - server = zoneLoadBalancer.chooseServer(key); - } - } - } catch (Throwable e) { - logger.error("Unexpected exception when choosing server using zone aware logic", e); - } - if (server != null) { - return server; - } else { - logger.debug("Zone avoidance logic is not invoked."); - return super.chooseServer(key); - } -} -``` - -从源码中我们可以看到,只有当负载均衡器中维护的实例所属Zone区域个数大于1的时候才会执行这里的选择策略,否则还是将使用父类的实现。当Zone区域个数大于1个的时候,它的实现步骤主要如下: - -- 调用`ZoneAvoidanceRule`中的静态方法`createSnapshot(lbStats)`,为当前负载均衡器中所有的Zone区域分别创建快照,保存在`Map zoneSnapshot`中,这些快照中的数据将用于后续的算法。 - -- 调用 - - ``` - ZoneAvoidanceRule - ``` - - 中的静态方法 - - ``` - getAvailableZones(zoneSnapshot, triggeringLoad.get(), triggeringBlackoutPercentage.get()) - ``` - - ,来获取可用的Zone区域集合,在该函数中会通过Zone区域快照中的统计数据来实现可用区的挑选。 - - - 首先它会剔除符合这些规则的Zone区域:所属实例数为零的Zone区域;Zone区域内实例平均负载小于零,或者实例故障率(断路器断开次数/实例数)大于等于阈值(默认为0.99999)。 - - 然后根据Zone区域的实例平均负载来计算出最差的Zone区域,这里的最差指的是实例平均负载最高的Zone区域。 - - 如果在上面的过程中没有符合剔除要求的区域,同时实例最大平均负载小于阈值(默认为20%),就直接返回所有Zone区域为可用区域。否则,从最坏Zone区域集合中随机的选择一个,将它从可用Zone区域集合中剔除。 - -- 当获得的可用Zone区域集合不为空,并且个数小于Zone区域总数,就随机的选择一个Zone区域。 - -- 在确定了某个Zone区域后,则获取对应Zone区域的服务均衡器,并调用`chooseServer`来选择具体的服务实例,而在`chooseServer`中将使用`IRule`接口的`choose`函数来选择具体的服务实例。在这里`IRule`接口的实现会使用`ZoneAvoidanceRule`来挑选出具体的服务实例。 - -## 负载均衡策略 - -通过上面的源码解读,我们已经对Ribbon实现的负载均衡器以及其中包含的服务实例过滤器、服务实例信息的存储对象、区域的信息快照等都有了深入的认识和理解,但是对于负载均衡器中的服务实例选择策略只是讲解了几个默认实现的内容,而对于`IRule`的其他实现还没有详细的解读,下面我们来看看在Ribbon中共提供了那些负载均衡的策略实现。 - -[![img](https://blog.didispace.com/assets/ribbon-code-5.png)](https://blog.didispace.com/assets/ribbon-code-5.png) - -如上图所示,我们可以看到在Ribbon中实现了非常多的选择策略,其中也包含了我们在前面内容中提到过的:`RoundRobinRule`和`ZoneAvoidanceRule`。下面我们来详细的解读一下`IRule`接口的各个实现。 - -### AbstractLoadBalancerRule - -负载均衡策略的抽象类,在该抽象类中定义了负载均衡器`ILoadBalancer`对象,该对象能够在具体实现选择服务策略时,获取到一些负载均衡器中维护的信息来作为分配依据,并以此设计一些算法来实现针对特定场景的高效策略。 - -``` -public abstract class AbstractLoadBalancerRule implements IRule, IClientConfigAware { - - private ILoadBalancer lb; - - @Override - public void setLoadBalancer(ILoadBalancer lb){ - this.lb = lb; - } - - @Override - public ILoadBalancer getLoadBalancer(){ - return lb; - } -} -``` - -### RandomRule - -该策略实现了从服务实例清单中随机选择一个服务实例的功能。它的具体实现如下,可以看到`IRule`接口的`choose(Object key)`函数实现,委托给了该类中的`choose(ILoadBalancer lb, Object key)`,该方法增加了一个负载均衡器对象的参数。从具体的实现上看,它会使用传入的负载均衡器来获得可用实例列表`upList`和所有实例列表`allList`,并通过`rand.nextInt(serverCount)`函数来获取一个随机数,并将该随机数作为upList的索引值来返回具体实例。同时,具体的选择逻辑在一个`while (server == null)`循环之内,而根据选择逻辑的实现,正常情况下每次选择都应该能够选出一个服务实例,如果出现死循环获取不到服务实例时,则很有可能存在并发的Bug。 - -``` -@Override -public Server choose(Object key) { - return choose(getLoadBalancer(), key); -} - -public Server choose(ILoadBalancer lb, Object key) { - ... - Server server = null; - while (server == null) { - if (Thread.interrupted()) { - return null; - } - List upList = lb.getReachableServers(); - List allList = lb.getAllServers(); - int serverCount = allList.size(); - if (serverCount == 0) { - return null; - } - int index = rand.nextInt(serverCount); - server = upList.get(index); - if (server == null) { - Thread.yield(); - continue; - } - if (server.isAlive()) { - return (server); - } - server = null; - Thread.yield(); - } - return server; -} -``` - -### RoundRobinRule - -该策略实现了按照线性轮询的方式依次选择每个服务实例的功能。它的具体实现如下,其详细结构与`RandomRule`非常类似。除了循环条件不同外,就是从可用列表中获取所谓的逻辑不同。从循环条件中,我们可以看到增加了一个`count`计数变量,该变量会在每次循环之后累加,也就是说如果一直选择不到server超过10次,那么就会结束尝试,并打印一个警告信息`No available alive servers after 10 tries from load balancer: ...`。而线性轮询的实现则是通过`AtomicInteger nextServerCyclicCounter`对象实现,每次进行实例选择时通过调用`incrementAndGetModulo`函数实现递增。 - -``` -public Server choose(ILoadBalancer lb, Object key) { - ... - Server server = null; - int count = 0; - while (server == null && count++ < 10) { - List reachableServers = lb.getReachableServers(); - List allServers = lb.getAllServers(); - int upCount = reachableServers.size(); - int serverCount = allServers.size(); - if ((upCount == 0) || (serverCount == 0)) { - log.warn("No up servers available from load balancer: " + lb); - return null; - } - int nextServerIndex = incrementAndGetModulo(serverCount); - server = allServers.get(nextServerIndex); - if (server == null) { - Thread.yield(); - continue; - } - if (server.isAlive() && (server.isReadyToServe())) { - return (server); - } - server = null; - } - if (count >= 10) { - log.warn("No available alive servers after 10 tries from load balancer: " - + lb); - } - return server; -} -``` - -### RetryRule - -该策略实现了一个具备重试机制的实例选择功能。从下面的实现中我们可以看到,在其内部还定义了一个`IRule`对象,默认使用了`RoundRobinRule`实例。而在`choose`方法中的则实现了对内部定义的策略进行反复尝试的策略,若期间能够选择到具体的服务实例就返回,若选择不到就根据设置的尝试结束时间为阈值(`maxRetryMillis`参数定义的值 + `choose`方法开始执行的时间戳),当超过该阈值后就返回null。 - -``` -public class RetryRule extends AbstractLoadBalancerRule { - IRule subRule = new RoundRobinRule(); - long maxRetryMillis = 500; - ... - public Server choose(ILoadBalancer lb, Object key) { - long requestTime = System.currentTimeMillis(); - long deadline = requestTime + maxRetryMillis; - Server answer = null; - answer = subRule.choose(key); - if (((answer == null) || (!answer.isAlive())) - && (System.currentTimeMillis() < deadline)) { - InterruptTask task = new InterruptTask(deadline - - System.currentTimeMillis()); - while (!Thread.interrupted()) { - answer = subRule.choose(key); - if (((answer == null) || (!answer.isAlive())) - && (System.currentTimeMillis() < deadline)) { - Thread.yield(); - } else { - break; - } - } - task.cancel(); - } - if ((answer == null) || (!answer.isAlive())) { - return null; - } else { - return answer; - } - } - ... -} -``` - -### WeightedResponseTimeRule - -该策略是对`RoundRobinRule`的扩展,增加了根据实例的运行情况来计算权重,并根据权重来挑选实例,以达到更优的分配效果,它的实现主要有三个核心内容: - -#### 定时任务 - -`WeightedResponseTimeRule`策略在初始化的时候会通过`serverWeightTimer.schedule(new DynamicServerWeightTask(), 0, serverWeightTaskTimerInterval)`启动一个定时任务,用来为每个服务实例计算权重,该任务默认30秒执行一次。 - -``` -class DynamicServerWeightTask extends TimerTask { - public void run() { - ServerWeight serverWeight = new ServerWeight(); - try { - serverWeight.maintainWeights(); - } catch (Throwable t) { - logger.error("Throwable caught while running DynamicServerWeightTask for " + name, t); - } - } -} -``` - -#### 权重计算 - -在源码中我们可以轻松找到用于存储权重的对象:`List accumulatedWeights = new ArrayList()`,该List中每个权重值所处的位置对应了负载均衡器维护的服务实例清单中所有实例在清单中的位置。 - -维护实例权重的计算过程通过`maintainWeights`函数实现,具体如下源码所示: - -``` -public void maintainWeights() { - ILoadBalancer lb = getLoadBalancer(); - ... - try { - logger.info("Weight adjusting job started"); - AbstractLoadBalancer nlb = (AbstractLoadBalancer) lb; - LoadBalancerStats stats = nlb.getLoadBalancerStats(); - ... - // 计算所有实例的平均响应时间的总和:totalResponseTime - double totalResponseTime = 0; - for (Server server : nlb.getAllServers()) { - // this will automatically load the stats if not in cache - ServerStats ss = stats.getSingleServerStat(server); - totalResponseTime += ss.getResponseTimeAvg(); - } - // 逐个计算每个实例的权重:weightSoFar + totalResponseTime - 实例的平均响应时间 - Double weightSoFar = 0.0; - List finalWeights = new ArrayList(); - for (Server server : nlb.getAllServers()) { - ServerStats ss = stats.getSingleServerStat(server); - double weight = totalResponseTime - ss.getResponseTimeAvg(); - weightSoFar += weight; - finalWeights.add(weightSoFar); - } - setWeights(finalWeights); - } catch (Throwable t) { - logger.error("Exception while dynamically calculating server weights", t); - } finally { - serverWeightAssignmentInProgress.set(false); - } -} -``` - -该函数的实现主要分为两个步骤: - -- 根据`LoadBalancerStats`中记录的每个实例的统计信息,累加所有实例的平均响应时间,得到总平均响应时间`totalResponseTime`,该值会用于后续的计算。 -- 为负载均衡器中维护的实例清单逐个计算权重(从第一个开始),计算规则为:`weightSoFar + totalResponseTime - 实例的平均响应时间`,其中`weightSoFar`初始化为零,并且每计算好一个权重需要累加到`weightSoFar`上供下一次计算使用。`totalResponseTime`则的上计算结果。 - -举个简单的例子来理解这个计算过程:假设有4个实例A、B、C、D,他们的平均响应时间为:10、40、80、100,所以总响应时间是10 + 40 + 80 + 100 = 230,每个实例的权重为总响应时间与实例自身的平均响应时间的差的累积获得,所以实例A、B、C、D的权重分别为: - -- 实例A:230 - 10 = 220 -- 实例B:220 + (230 - 40)= 410 -- 实例C:410 + (230 - 80)= 560 -- 实例D:560 + (230 - 100)= 690 - -需要注意的是,这里的权重值只是表示了各实例权重区间的上限,并非某个实例的优先级,所以不是数值越大被选中的概率就越大。那么什么是权重区间呢?以上面例子的计算结果为例,它实际上是为这4个实例构建了4个不同的区间,每个实例的区间下限是上一个实例的区间上限,而每个实例的区间上限则是我们上面计算并存储于`List accumulatedWeights`中的权重值,其中第一个实例的下限默认为零。所以,根据上面示例的权重计算结果,我们可以得到每个实例的权重区间: - -- 实例A:[0, 220] -- 实例B:(220, 410] -- 实例C:(410, 560] -- 实例D:(560,690) - -我们不难发现,实际上每个区间的宽度就是:总的平均响应时间 - 实例的平均响应时间,所以实例的平均响应时间越短、权重区间的宽度越大,而权重区间的宽度越大被选中的概率就越高。可能很多读者会问,这些区间边界的开闭是如何确定的呢?为什么不那么规则?下面我们会通过`实例选择`算法的解读来解释。 - -#### 实例选择 - -`WeightedResponseTimeRule`选择实例的实现与之前介绍的算法结构类似,下面是它主体的算法(省略了循环体和一些判断等处理): - -``` -public Server choose(ILoadBalancer lb, Object key) { - ... - List currentWeights = accumulatedWeights; - ... - List allList = lb.getAllServers(); - int serverCount = allList.size(); - if (serverCount == 0) { - return null; - } - int serverIndex = 0; - // 获取最后一个实例的权重 - double maxTotalWeight = currentWeights.size() == 0 ? 0 : currentWeights.get(currentWeights.size() - 1); - if (maxTotalWeight < 0.001d) { - // 如果最后一个实例的权重值小于0.001,则采用父类实现的线性轮询的策略 - server = super.choose(getLoadBalancer(), key); - if(server == null) { - return server; - } - } else { - // 如果最后一个实例的权重值大于等于0.001,就产生一个[0, maxTotalWeight)的随机数 - double randomWeight = random.nextDouble() * maxTotalWeight; - int n = 0; - for (Double d : currentWeights) { // 遍历维护的权重清单,若权重大于等于随机得到的数值,就选择这个实例 - if (d >= randomWeight) { - serverIndex = n; - break; - } else { - n++; - } - } - server = allList.get(serverIndex); - } - ... - return server; -} -``` - -从源码中,我们可以看到,选择实例的核心过程就两步: - -- 生产一个`[0, 最大权重值)`区间内的随机数。 -- 遍历权重列表,比较权重值与随机数的大小,如果权重值大于等于随机数,就拿当前权重列表的索引值去服务实例列表中获取具体实例。这就是在上一节中提到的服务实例会根据权重区间挑选的原理,而权重区间边界的开闭原则根据算法,正常应该每个区间为`(x, y]`的形式,但是第一个实例和最后一个实例为什么不同呢?由于随机数的最小取值可以为`0`,所以第一个实例的下限是闭区间,同时随机数的最大值取不到最大权重值,所以最后一个实例的上限是开区间。 - -若继续以上面的数据为例,进行服务实例的选择,则该方法会从`[0, 690)`区间中选出一个随机数,比如选出的随机数为230,由于该值位于第二个区间,所以此时就会选择实例B来进行请求。 - -##### ClientConfigEnabledRoundRobinRule - -该策略较为特殊,我们一般不直接使用它。因为它本身并没有实现什么特殊的处理逻辑,正如下面的源码所示,在它的内部定义了一个`RoundRobinRule`策略,而`choose`函数的实现也正是使用了`RoundRobinRule`的线性轮询机制,所以它实现的功能实际上与`RoundRobinRule`相同,那么定义它有什么特殊的用处呢? - -虽然我们不会直接使用该策略,但是通过继承该策略,那么默认的`choose`就实现了线性轮询机制,在子类中做一些高级策略时通常都有可能会存在一些无法实施的情况,那么就可以通过父类的实现作为备选。在后文中我们将继续介绍的高级策略均是基于`ClientConfigEnabledRoundRobinRule`的扩展。 - -``` -public class ClientConfigEnabledRoundRobinRule extends AbstractLoadBalancerRule { - - RoundRobinRule roundRobinRule = new RoundRobinRule(); - ... - @Override - public Server choose(Object key) { - if (roundRobinRule != null) { - return roundRobinRule.choose(key); - } else { - throw new IllegalArgumentException( - "This class has not been initialized with the RoundRobinRule class"); - } - } -} -``` - -### BestAvailableRule - -该策略继承自`ClientConfigEnabledRoundRobinRule`,在实现中它注入了负载均衡器的统计对象:`LoadBalancerStats`,同时在具体的`choose`算法中利用`LoadBalancerStats`保存的实例统计信息来选择满足要求的实例。从如下源码中我们可以看到,它通过遍历负载均衡器中维护的所有服务实例,会过滤掉故障的实例,并找出并发请求数最小的一个,所以该策略的特性是选出最空闲的实例。 - -``` -public Server choose(Object key) { - if (loadBalancerStats == null) { - return super.choose(key); - } - List serverList = getLoadBalancer().getAllServers(); - int minimalConcurrentConnections = Integer.MAX_VALUE; - long currentTime = System.currentTimeMillis(); - Server chosen = null; - for (Server server: serverList) { - ServerStats serverStats = loadBalancerStats.getSingleServerStat(server); - if (!serverStats.isCircuitBreakerTripped(currentTime)) { - int concurrentConnections = serverStats.getActiveRequestsCount(currentTime); - if (concurrentConnections < minimalConcurrentConnections) { - minimalConcurrentConnections = concurrentConnections; - chosen = server; - } - } - } - if (chosen == null) { - return super.choose(key); - } else { - return chosen; - } -} -``` - -同时,由于该算法的核心依据是统计对象`loadBalancerStats`,当其为空的时候,该策略是无法执行的。所以从源码中我们可以看到,当`loadBalancerStats`为空的时候,它会采用父类的线性轮询策略,正如我们在介绍`ClientConfigEnabledRoundRobinRule`时那样,它的子类在无法满足实现高级策略时候,可以使用线性轮询策略的特性。后面将要介绍的策略因为也都继承自`ClientConfigEnabledRoundRobinRule`,所以他们都会具有这样的特性。 - -##### PredicateBasedRule - -这是一个抽象策略,它也继承了`ClientConfigEnabledRoundRobinRule`,从其命名中可以猜出他是一个基于`Predicate`实现的策略,`Predicate`是Google Guava Collection工具对集合进行过滤的条件接口。 - -如下源码所示,它定义了一个抽象函数`getPredicate`来获取`AbstractServerPredicate`对象的实现,而在`choose`函数中,通过`AbstractServerPredicate`的`chooseRoundRobinAfterFiltering`函数来选出具体的服务实例。从该函数的命名我们也大致能猜出它的基础逻辑:先通过子类中实现的`Predicate`逻辑来过滤一部分服务实例,然后再以线性轮询的方式从过滤后的实例清单中选出一个。 - -``` -public abstract class PredicateBasedRule extends ClientConfigEnabledRoundRobinRule { - - public abstract AbstractServerPredicate getPredicate(); - - @Override - public Server choose(Object key) { - ILoadBalancer lb = getLoadBalancer(); - Optional server = getPredicate().chooseRoundRobinAfterFiltering(lb.getAllServers(), key); - if (server.isPresent()) { - return server.get(); - } else { - return null; - } - } -} -``` - -通过下面`AbstractServerPredicate`的源码片段,可以证实我们上面所做的猜测。在上面`choose`函数中调用的`chooseRoundRobinAfterFiltering`方法先通过内部定义的`getEligibleServers`函数来获取备选的实例清单(实现了过滤),如果返回的清单为空,则用`Optional.absent()`来表示不存在,反之则以线性轮询的方式从备选清单中获取一个实例。 - -``` -public abstract class AbstractServerPredicate implements Predicate { - - ... - - public Optional chooseRoundRobinAfterFiltering(List servers, Object loadBalancerKey) { - List eligible = getEligibleServers(servers, loadBalancerKey); - if (eligible.size() == 0) { - return Optional.absent(); - } - return Optional.of(eligible.get(nextIndex.getAndIncrement() % eligible.size())); - } - - public List getEligibleServers(List servers, Object loadBalancerKey) { - if (loadBalancerKey == null) { - return ImmutableList.copyOf(Iterables.filter(servers, this.getServerOnlyPredicate())); - } else { - List results = Lists.newArrayList(); - for (Server server: servers) { - if (this.apply(new PredicateKey(loadBalancerKey, server))) { - results.add(server); - } - } - return results; - } - } -} -``` - -在了解了整体逻辑之后,我们来详细看看实现过滤功能的`getEligibleServers`函数。从源码上看,它的实现结构非常简单清晰,通过遍历服务清单,使用`this.apply`方法来判断实例是否需要保留,是就添加到结果列表中。 - -可能到这里,不熟悉Google Guava Collections集合工具的读者会比较困惑,这个`apply`在`AbstractServerPredicate`中并找不到它的定义,那么它是如何实现过滤的呢?实际上,`AbstractServerPredicate`实现了`com.google.common.base.Predicate`接口,而`apply`方法是该接口中的定义,主要用来实现过滤条件的判断逻辑,它输入的参数则是过滤条件需要用到的一些信息(比如源码中的`new PredicateKey(loadBalancerKey, server))`,它传入了关于实例的统计信息和负载均衡器的选择算法传递过来的key)。既然在`AbstractServerPredicate`中我们未能找到`apply`的实现,所以这里的`chooseRoundRobinAfterFiltering`函数只是定义了一个模板策略:“先过滤清单,再轮询选择”。对于如何过滤,则需要我们在`AbstractServerPredicate`的子类去实现`apply`方法来确定具体的过滤策略了。 - -后面我们将要介绍的两个策略就是基于此抽象策略实现,只是它们使用了不同的`Predicate`实现来完成过滤逻辑以达到不同的实例选择效果。 - -> Google Guava Collections是一个对Java Collections Framework增强和扩展的一个开源项目。虽然Java Collections Framework已经能够 满足了我们大多数情况下使用集合的要求,但是当遇到一些特殊的情况我们的代码会比较冗长且容易出错。Guava Collections 可以帮助我们的让集合操作代码更为简短精炼并大大增强代码的可读性。 - -### AvailabilityFilteringRule - -该策略继承自上面介绍的抽象策略`PredicateBasedRule`,所以它也继承了“先过滤清单,再轮询选择”的基本处理逻辑,其中过滤条件使用了`AvailabilityPredicate`: - -``` -public class AvailabilityPredicate extends AbstractServerPredicate { - - ... - - public boolean apply(@Nullable PredicateKey input) { - LoadBalancerStats stats = getLBStats(); - if (stats == null) { - return true; - } - return !shouldSkipServer(stats.getSingleServerStat(input.getServer())); - } - - private boolean shouldSkipServer(ServerStats stats) { - if ((CIRCUIT_BREAKER_FILTERING.get() && stats.isCircuitBreakerTripped()) - || stats.getActiveRequestsCount() >= activeConnectionsLimit.get()) { - return true; - } - return false; - } -} -``` - -从上述源码中,我们可以知道它的主要过滤逻辑位于`shouldSkipServer`方法中,它主要判断服务实例的两项内容: - -- 是否故障,即断路器是否生效已断开 -- 实例的并发请求数大于阈值,默认值为$2^{31}$ - 1,该配置我们可通过参数`..ActiveConnectionsLimit`来修改 - 其中只要有一个满足`apply`就返回false(代表该节点可能存在故障或负载过高),都不满足就返回true。 - -在该策略中,除了实现了上面的过滤方法之外,对于`choose`的策略也做了一些改进优化,所以父类的实现对于它来说只是一个备用选项,其具体实现如下: - -``` -public Server choose(Object key) { - int count = 0; - Server server = roundRobinRule.choose(key); - while (count++ <= 10) { - if (predicate.apply(new PredicateKey(server))) { - return server; - } - server = roundRobinRule.choose(key); - } - return super.choose(key); -} -``` - -可以看到,它并没有像父类中那样,先遍历所有的节点进行过滤,然后在过滤后的集合中选择实例。而是先线性的方式选择一个实例,接着用过滤条件来判断该实例是否满足要求,若满足就直接使用该实例,若不满足要求就再选择下一个实例,并检查是否满足要求,如此循环进行,当这个过程重复了10次还是没有找到符合要求的实例,就采用父类的实现方案。 - -简单的说,该策略通过线性抽样的方式直接尝试寻找可用且较空闲的实例来使用,优化了父类每次都要遍历所有实例的开销。 - -### ZoneAvoidanceRule - -该策略我们在介绍负载均衡器`ZoneAwareLoadBalancer`时已经提到过了,它也是`PredicateBasedRule`的具体实现类。在之前的介绍中主要针对`ZoneAvoidanceRule`中用于选择Zone区域策略的一些静态函数,比如:`createSnapshot`、`getAvailableZones`。在这里我们将详细的看看`ZoneAvoidanceRule`作为服务实例过滤条件的实现原理。从下面`ZoneAvoidanceRule`的源码片段中我们可以看到,它使用了`CompositePredicate`来进行服务实例清单的过滤。这是一个组合过滤条件,在其构造函数中,它以`ZoneAvoidancePredicate`为主过滤条件,`AvailabilityPredicate`为次过滤条件初始化了组合过滤条件的实例。 - -``` -public class ZoneAvoidanceRule extends PredicateBasedRule { - - ... - private CompositePredicate compositePredicate; - - public ZoneAvoidanceRule() { - super(); - ZoneAvoidancePredicate zonePredicate = new ZoneAvoidancePredicate(this); - AvailabilityPredicate availabilityPredicate = new AvailabilityPredicate(this); - compositePredicate = createCompositePredicate(zonePredicate, availabilityPredicate); - } - ... -} -``` - -`ZoneAvoidanceRule`在实现的时候并没有像`AvailabilityFilteringRule`那样重写`choose`函数来优化,所以它完全遵循了父类的过滤主逻辑:“先过滤清单,再轮询选择”。其中过滤清单的条件就是我们上面提到的以`ZoneAvoidancePredicate`为主过滤条件、`AvailabilityPredicate`为次过滤条件的组合过滤条件`CompositePredicate`。从`CompositePredicate`的源码片段中,我们可以看到它定义了一个主过滤条件`AbstractServerPredicate delegate`以及一组次过滤条件列表`List fallbacks`,所以它的次过滤列表是可以拥有多个的,并且由于它采用了List存储所以次过滤条件是按顺序执行的。 - -``` -public class CompositePredicate extends AbstractServerPredicate { - - private AbstractServerPredicate delegate; - private List fallbacks = Lists.newArrayList(); - - private int minimalFilteredServers = 1; - private float minimalFilteredPercentage = 0; - - @Override - public List getEligibleServers(List servers, Object loadBalancerKey) { - List result = super.getEligibleServers(servers, loadBalancerKey); - Iterator i = fallbacks.iterator(); - while (!(result.size() >= minimalFilteredServers && result.size() > (int) (servers.size() * minimalFilteredPercentage)) - && i.hasNext()) { - AbstractServerPredicate predicate = i.next(); - result = predicate.getEligibleServers(servers, loadBalancerKey); - } - return result; - } - -} -``` - -再来看看获取过滤结果的实现函数`getEligibleServers`中,它的处理逻辑如下: - -- 使用主过滤条件对所有实例过滤并返回过滤后的实例清单 -- 依次使用次过滤条件列表中的过滤条件对主过滤条件的结果进行过滤 -- 每次过滤之后(包括主过滤条件和次过滤条件),都需要判断下面两个条件,只要有一个符合就不再进行过滤,将当前结果返回供线性轮询算法选择: - - 过滤后的实例总数 >= 最小过滤实例数(minimalFilteredServers,默认为1) - - 过滤后的实例比例 > 最小过滤百分比(minimalFilteredPercentage,默认为0) \ No newline at end of file diff --git "a/jun_springcloud_plugin/doc/Spring Cloud\346\272\220\347\240\201\345\210\206\346\236\220\357\274\210\345\233\233\357\274\211Zuul\357\274\232\346\240\270\345\277\203\350\277\207\346\273\244\345\231\250.md" "b/jun_springcloud_plugin/doc/Spring Cloud\346\272\220\347\240\201\345\210\206\346\236\220\357\274\210\345\233\233\357\274\211Zuul\357\274\232\346\240\270\345\277\203\350\277\207\346\273\244\345\231\250.md" deleted file mode 100644 index 372b89a629..0000000000 --- "a/jun_springcloud_plugin/doc/Spring Cloud\346\272\220\347\240\201\345\210\206\346\236\220\357\274\210\345\233\233\357\274\211Zuul\357\274\232\346\240\270\345\277\203\350\277\207\346\273\244\345\231\250.md" +++ /dev/null @@ -1,81 +0,0 @@ -# Spring Cloud源码分析(四)Zuul:核心过滤器 - -**原创** - - [2017-05-02](https://blog.didispace.com/spring-cloud-source-zuul/) - - 翟永超 - - [Spring Cloud](https://blog.didispace.com/categories/Spring-Cloud/) - -[【推荐】从业15年的架构师告诉你:如何落地微服务和云原生架构?](https://blog.didispace.com/how-to-implement-microservice-and-cloud-native-architecture/) - -通过之前发布的[《Spring Cloud构建微服务架构(五)服务网关》](http://blog.didispace.com/springcloud5/)一文,相信大家对于Spring Cloud Zuul已经有了一个基础的认识。通过前文的介绍,我们对于Zuul的第一印象通常是这样的:它包含了对请求的路由和过滤两个功能,其中路由功能负责将外部请求转发到具体的微服务实例上,是实现外部访问统一入口的基础;而过滤器功能则负责对请求的处理过程进行干预,是实现请求校验、服务聚合等功能的基础。然而实际上,路由功能在真正运行时,它的路由映射和请求转发都是由几个不同的过滤器完成的。其中,路由映射主要通过pre类型的过滤器完成,它将请求路径与配置的路由规则进行匹配,以找到需要转发的目标地址;而请求转发的部分则是由route类型的过滤器来完成,对pre类型过滤器获得的路由地址进行转发。所以,过滤器可以说是Zuul实现API网关功能最为核心的部件,每一个进入Zuul的HTTP请求都会经过一系列的过滤器处理链得到请求响应并返回给客户端。 - -下面,我们就通过本文来详细了解一下Spring Cloud Zuul的过滤器!以下内容节选自《Spring Cloud微服务实战》,稍做加工。 - -## 过滤器 - -在Spring Cloud Zuul中实现的过滤器必须包含4个基本特征:过滤类型、执行顺序、执行条件、具体操作。这些元素看着似乎非常的熟悉,实际上它就是ZuulFilter接口中定义的四个抽象方法: - -``` -String filterType(); - -int filterOrder(); - -boolean shouldFilter(); - -Object run(); -``` - -它们各自的含义与功能总结如下: - -- filterType:该函数需要返回一个字符串来代表过滤器的类型,而这个类型就是在HTTP请求过程中定义的各个阶段。在Zuul中默认定义了四种不同生命周期的过滤器类型,具体如下: - - pre:可以在请求被路由之前调用。 - - routing:在路由请求时候被调用。 - - post:在routing和error过滤器之后被调用。 - - error:处理请求时发生错误时被调用。 -- filterOrder:通过int值来定义过滤器的执行顺序,数值越小优先级越高。 -- shouldFilter:返回一个boolean类型来判断该过滤器是否要执行。我们可以通过此方法来指定过滤器的有效范围。 -- run:过滤器的具体逻辑。在该函数中,我们可以实现自定义的过滤逻辑,来确定是否要拦截当前的请求,不对其进行后续的路由,或是在请求路由返回结果之后,对处理结果做一些加工等。 - -## 请求生命周期 - -上一节中,对于Spring Cloud Zuul中的过滤器类型filterType,我们已经做过一些简单的介绍,Zuul默认定义了四个不同的过滤器类型,它们覆盖了一个外部HTTP请求到达API网关,直到返回请求结果的全部生命周期。下图源自Zuul的官方WIKI中关于请求生命周期的图解,它描述了一个HTTP请求到达API网关之后,如何在各个不同类型的过滤器之间流转的详细过程。 - -[![请求生命周期官方图解](http://blog.didispace.com/content/images/2016/07/687474703a2f2f6e6574666c69782e6769746875622e696f2f7a75756c2f696d616765732f7a75756c2d726571756573742d6c6966656379636c652e706e67.png)](http://blog.didispace.com/content/images/2016/07/687474703a2f2f6e6574666c69782e6769746875622e696f2f7a75756c2f696d616765732f7a75756c2d726571756573742d6c6966656379636c652e706e67.png)请求生命周期官方图解 - -从上图中,我们可以看到,当外部HTTP请求到达API网关服务的时候,首先它会进入第一个阶段pre,在这里它会被pre类型的过滤器进行处理,该类型的过滤器主要目的是在进行请求路由之前做一些前置加工,比如请求的校验等。在完成了pre类型的过滤器处理之后,请求进入第二个阶段routing,也就是之前说的路由请求转发阶段,请求将会被routing类型过滤器处理,这里的具体处理内容就是将外部请求转发到具体服务实例上去的过程,当服务实例将请求结果都返回之后,routing阶段完成,请求进入第三个阶段post,此时请求将会被post类型的过滤器进行处理,这些过滤器在处理的时候不仅可以获取到请求信息,还能获取到服务实例的返回信息,所以在post类型的过滤器中,我们可以对处理结果进行一些加工或转换等内容。另外,还有一个特殊的阶段error,该阶段只有在上述三个阶段中发生异常的时候才会触发,但是它的最后流向还是post类型的过滤器,因为它需要通过post过滤器将最终结果返回给请求客户端(实际实现上还有一些差别,后续介绍)。 - -## 核心过滤器 - -在Spring Cloud Zuul中,为了让API网关组件可以更方便的上手使用,它在HTTP请求生命周期的各个阶段默认地实现了一批核心过滤器,它们会在API网关服务启动的时候被自动地加载和启用。我们可以在源码中查看和了解它们,它们定义于spring-cloud-netflix-core模块的org.springframework.cloud.netflix.zuul.filters包下。 - -[![默认实现的核心过滤器](https://blog.didispace.com/assets/zuul-default-filter.png)](https://blog.didispace.com/assets/zuul-default-filter.png)默认实现的核心过滤器 - -如上图所示,在默认启用的过滤器中包含了三种不同生命周期的过滤器,这些过滤器都非常重要,可以帮助我们理解Zuul对外部请求处理的过程,以及帮助我们如何在此基础上扩展过滤器去完成自身系统需要的功能。下面,我们将逐个地对这些过滤器做一些详细的介绍: - -#### pre过滤器 - -- ServletDetectionFilter:它的执行顺序为-3,是最先被执行的过滤器。该过滤器总是会被执行,主要用来检测当前请求是通过Spring的DispatcherServlet处理运行,还是通过ZuulServlet来处理运行的。它的检测结果会以布尔类型保存在当前请求上下文的isDispatcherServletRequest参数中,这样在后续的过滤器中,我们就可以通过RequestUtils.isDispatcherServletRequest()和RequestUtils.isZuulServletRequest()方法判断它以实现做不同的处理。一般情况下,发送到API网关的外部请求都会被Spring的DispatcherServlet处理,除了通过/zuul/*路径访问的请求会绕过DispatcherServlet,被ZuulServlet处理,主要用来应对处理大文件上传的情况。另外,对于ZuulServlet的访问路径/zuul/*,我们可以通过zuul.servletPath参数来进行修改。 -- Servlet30WrapperFilter:它的执行顺序为-2,是第二个执行的过滤器。目前的实现会对所有请求生效,主要为了将原始的HttpServletRequest包装成Servlet30RequestWrapper对象。 -- FormBodyWrapperFilter:它的执行顺序为-1,是第三个执行的过滤器。该过滤器仅对两种类请求生效,第一类是Content-Type为application/x-www-form-urlencoded的请求,第二类是Content-Type为multipart/form-data并且是由Spring的DispatcherServlet处理的请求(用到了ServletDetectionFilter的处理结果)。而该过滤器的主要目的是将符合要求的请求体包装成FormBodyRequestWrapper对象。 -- DebugFilter:它的执行顺序为1,是第四个执行的过滤器。该过滤器会根据配置参数zuul.debug.request和请求中的debug参数来决定是否执行过滤器中的操作。而它的具体操作内容则是将当前的请求上下文中的debugRouting和debugRequest参数设置为true。由于在同一个请求的不同生命周期中,都可以访问到这两个值,所以我们在后续的各个过滤器中可以利用这两值来定义一些debug信息,这样当线上环境出现问题的时候,可以通过请求参数的方式来激活这些debug信息以帮助分析问题。另外,对于请求参数中的debug参数,我们也可以通过zuul.debug.parameter来进行自定义。 -- PreDecorationFilter:它的执行顺序为5,是pre阶段最后被执行的过滤器。该过滤器会判断当前请求上下文中是否存在forward.to和serviceId参数,如果都不存在,那么它就会执行具体过滤器的操作(如果有一个存在的话,说明当前请求已经被处理过了,因为这两个信息就是根据当前请求的路由信息加载进来的)。而它的具体操作内容就是为当前请求做一些预处理,比如:进行路由规则的匹配、在请求上下文中设置该请求的基本信息以及将路由匹配结果等一些设置信息等,这些信息将是后续过滤器进行处理的重要依据,我们可以通过RequestContext.getCurrentContext()来访问这些信息。另外,我们还可以在该实现中找到一些对HTTP头请求进行处理的逻辑,其中包含了一些耳熟能详的头域,比如:X-Forwarded-Host、X-Forwarded-Port。另外,对于这些头域的记录是通过zuul.addProxyHeaders参数进行控制的,而这个参数默认值为true,所以Zuul在请求跳转时默认地会为请求增加X-Forwarded-*头域,包括:X-Forwarded-Host、X-Forwarded-Port、X-Forwarded-For、X-Forwarded-Prefix、X-Forwarded-Proto。我们也可以通过设置zuul.addProxyHeaders=false关闭对这些头域的添加动作。 - -> [《Spring Cloud实战小贴士:Zuul处理Cookie和重定向》](http://blog.didispace.com/spring-cloud-zuul-cookie-redirect/) 一文中提到的加载敏感头信息加入到忽略头信息的操作调用就在PreDecorationFilter过滤器中实现。 - -#### route过滤器 - -- RibbonRoutingFilter:它的执行顺序为10,是route阶段第一个执行的过滤器。该过滤器只对请求上下文中存在serviceId参数的请求进行处理,即只对通过serviceId配置路由规则的请求生效。而该过滤器的执行逻辑就是面向服务路由的核心,它通过使用Ribbon和Hystrix来向服务实例发起请求,并将服务实例的请求结果返回。 -- SimpleHostRoutingFilter:它的执行顺序为100,是route阶段第二个执行的过滤器。该过滤器只对请求上下文中存在routeHost参数的请求进行处理,即只对通过url配置路由规则的请求生效。而该过滤器的执行逻辑就是直接向routeHost参数的物理地址发起请求,从源码中我们可以知道该请求是直接通过httpclient包实现的,而没有使用Hystrix命令进行包装,所以这类请求并没有线程隔离和断路器的保护。 -- SendForwardFilter:它的执行顺序为500,是route阶段第三个执行的过滤器。该过滤器只对请求上下文中存在forward.to参数的请求进行处理,即用来处理路由规则中的forward本地跳转配置。 - -#### post过滤器 - -- SendErrorFilter:它的执行顺序为0,是post阶段第一个执行的过滤器。该过滤器仅在请求上下文中包含error.status_code参数(由之前执行的过滤器设置的错误编码)并且还没有被该过滤器处理过的时候执行。而该过滤器的具体逻辑就是利用请求上下文中的错误信息来组织成一个forward到API网关/error错误端点的请求来产生错误响应。 -- SendResponseFilter:它的执行顺序为1000,是post阶段最后执行的过滤器。该过滤器会检查请求上下文中是否包含请求响应相关的头信息、响应数据流或是响应体,只有在包含它们其中一个的时候就会执行处理逻辑。而该过滤器的处理逻辑就是利用请求上下文的响应信息来组织需要发送回客户端的响应内容。 - -**这里不列出具体代码了,读者可自行根据类名来查看源码了解详细处理过程。**下图是对上述过滤器根据顺序、名称、功能、类型做了综合的整理,可以帮助我们在自定义过滤器或是扩展过滤器的时候用来参考并全面地考虑整个请求生命周期的处理过程。 - -[![核心过滤器总结](https://blog.didispace.com/assets/zuul-filter-core.png)](https://blog.didispace.com/assets/zuul-filter-core.png)核心过滤器总结 \ No newline at end of file diff --git "a/jun_springcloud_plugin/doc/Spring cloud alibaba\344\271\213Nacos \347\263\273\347\273\237\347\211\210\346\234\254\345\205\274\345\256\271\346\200\247.md" "b/jun_springcloud_plugin/doc/Spring cloud alibaba\344\271\213Nacos \347\263\273\347\273\237\347\211\210\346\234\254\345\205\274\345\256\271\346\200\247.md" deleted file mode 100644 index cf2c856f5d..0000000000 --- "a/jun_springcloud_plugin/doc/Spring cloud alibaba\344\271\213Nacos \347\263\273\347\273\237\347\211\210\346\234\254\345\205\274\345\256\271\346\200\247.md" +++ /dev/null @@ -1,122 +0,0 @@ -# Spring cloud alibaba之Nacos 系统版本兼容性 - -# 组件版本关系 - -由于Spring cloud alibaba已经完成了孵化,因此不建议使用孵化期版本的Spring cloud alibaba版本。 - -spring boot 2.3.x的版本已经发布建议不要使用最新版,尽量的使用兼容版。 - -> 经过测试 spirng cloud alibaba 2.2.1.RELEASE版本是兼容spring boot 2.9.1版本的 - -| Spring Cloud Alibaba Version | Sentinel Version | Nacos Version | RocketMQ Version | Dubbo Version | Seata Version | -| ----------------------------------------------- | ---------------- | ------------- | ---------------- | ------------- | ------------- | -| 2.2.1.RELEASE | 1.7.1 | 1.2.1 | 4.4.0 | 2.7.6 | 1.1.0 | -| 2.2.0.RELEASE | 1.7.1 | 1.1.4 | 4.4.0 | 2.7.4.1 | 1.0.0 | -| 2.1.2.RELEASE or 2.0.2.RELEASE | 1.7.1 | 1.2.1 | 4.4.0 | 2.7.6 | 1.1.0 | -| 2.1.1.RELEASE or 2.0.1.RELEASE or 1.5.1.RELEASE | 1.7.0 | 1.1.4 | 4.4.0 | 2.7.3 | 0.9.0 | -| 2.1.0.RELEASE or 2.0.0.RELEASE or 1.5.0.RELEASE | 1.6.3 | 1.1.1 | 4.4.0 | 2.7.3 | 0.7.1 | - -## 毕业版本依赖关系(推荐使用) - -| Spring Cloud Version | Spring Cloud Alibaba Version | Spring Boot Version | -| --------------------------- | ---------------------------- | ------------------- | -| Spring Cloud Hoxton.SR3 | 2.2.1.RELEASE | 2.2.5.RELEASE | -| Spring Cloud Hoxton.RELEASE | 2.2.0.RELEASE | 2.2.X.RELEASE | -| Spring Cloud Greenwich | 2.1.2.RELEASE | 2.1.X.RELEASE | -| Spring Cloud Finchley | 2.0.2.RELEASE | 2.0.X.RELEASE | -| Spring Cloud Edgware | 1.5.1.RELEASE | 1.5.X.RELEASE | - -## 依赖管理 - -Spring Cloud Alibaba BOM 包含了它所使用的所有依赖的版本。 - -### RELEASE 版本 - -#### Spring Cloud Hoxton - -如果需要使用 Spring Cloud Hoxton 版本,请在 dependencyManagement 中添加如下内容 - - - -```xml - - com.alibaba.cloud - spring-cloud-alibaba-dependencies - 2.2.1.RELEASE - pom - import - -``` - -#### Spring Cloud Greenwich - -如果需要使用 Spring Cloud Greenwich 版本,请在 dependencyManagement 中添加如下内容 - - - -```xml - - com.alibaba.cloud - spring-cloud-alibaba-dependencies - 2.1.2.RELEASE - pom - import - -``` - -#### Spring Cloud Finchley - -如果需要使用 Spring Cloud Finchley 版本,请在 dependencyManagement 中添加如下内容 - - - -```xml - - com.alibaba.cloud - spring-cloud-alibaba-dependencies - 2.0.2.RELEASE - pom - import - -``` - -#### Spring Cloud Edgware - -如果需要使用 Spring Cloud Edgware 版本,请在 dependencyManagement 中添加如下内容 - - - -```xml - - com.alibaba.cloud - spring-cloud-alibaba-dependencies - 1.5.1.RELEASE - pom - import - -``` - -| name | description | option | -| ----------------------------- | ------------------------------- | -------------------------------------- | -| MODE | cluster模式/standalone模式 | cluster/standalone default **cluster** | -| NACOS_SERVERS | nacos cluster地址 | eg. ip1,ip2,ip3 | -| PREFER_HOST_MODE | 是否支持hostname | hostname/ip default **ip** | -| NACOS_SERVER_PORT | nacos服务器端口 | default **8848** | -| NACOS_SERVER_IP | 多网卡下的自定义nacos服务器IP | | -| SPRING_DATASOURCE_PLATFORM | standalone 支持 mysql | mysql / empty default empty | -| MYSQL_MASTER_SERVICE_HOST | mysql 主节点host | | -| MYSQL_MASTER_SERVICE_PORT | mysql 主节点端口 | default : **3306** | -| MYSQL_MASTER_SERVICE_DB_NAME | mysql 主节点数据库 | | -| MYSQL_MASTER_SERVICE_USER | 数据库用户名 | | -| MYSQL_MASTER_SERVICE_PASSWORD | 数据库密码 | | -| MYSQL_SLAVE_SERVICE_HOST | mysql从节点host | | -| MYSQL_SLAVE_SERVICE_PORT | mysql从节点端口 | default :3306 | -| MYSQL_DATABASE_NUM | 数据库数量 | default :2 | -| JVM_XMS | -Xms | default :2g | -| JVM_XMX | -Xmx | default :2g | -| JVM_XMN | -Xmn | default :1g | -| JVM_MS | -XX:MetaspaceSize | default :128m | -| JVM_MMS | -XX:MaxMetaspaceSize | default :320m | -| NACOS_DEBUG | 开启远程调试 | y/n default :n | -| TOMCAT_ACCESSLOG_ENABLED | server.tomcat.accesslog.enabled | default :false | - diff --git "a/jun_springcloud_plugin/doc/SpringBoot\344\270\216SpringCloud\347\232\204\347\211\210\346\234\254\345\257\271\345\272\224\350\257\246\347\273\206\347\211\210.md" "b/jun_springcloud_plugin/doc/SpringBoot\344\270\216SpringCloud\347\232\204\347\211\210\346\234\254\345\257\271\345\272\224\350\257\246\347\273\206\347\211\210.md" deleted file mode 100644 index 8476ef2f80..0000000000 --- "a/jun_springcloud_plugin/doc/SpringBoot\344\270\216SpringCloud\347\232\204\347\211\210\346\234\254\345\257\271\345\272\224\350\257\246\347\273\206\347\211\210.md" +++ /dev/null @@ -1,213 +0,0 @@ -# SpringBoot与SpringCloud的版本对应详细版 - - - -**缘起** - -初学spring cloud的朋友可能不知道,其实SpringBoot与SpringCloud需要版本对应,否则可能会造成很多意料之外的错误,比如eureka注册了结果找不到服务类啊,比如某些jar导入不进来啊,等等这些错误。下面列出来springBoot和spring cloud的版本对应关系,需要配套使用,才不会出现各种奇怪的错误。 - -**关于maven仓库的版本列表** - -spring-cloud-dependencies 版本列表可查看: -https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-dependencies -spring-boot-starter-parent 版本列表可查看: -https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent - -**版本对应关系** - -大版本对应: - - - -| Spring Cloud | Spring Boot | -| :----------------------- | :--------------------------------------------- | -| Angel版本 | 兼容Spring Boot 1.2.x | -| Brixton版本 | 兼容Spring Boot 1.3.x,也兼容Spring Boot 1.4.x | -| Camden版本 | 兼容Spring Boot 1.4.x,也兼容Spring Boot 1.5.x | -| Dalston版本、Edgware版本 | 兼容Spring Boot 1.5.x,不兼容Spring Boot 2.0.x | -| Finchley版本 | 兼容Spring Boot 2.0.x,不兼容Spring Boot 1.5.x | -| Greenwich版本 | 兼容Spring Boot 2.1.x | -| Hoxtonl版本 | 兼容Spring Boot 2.2.x | - - - -在实际开发过程中,我们需要更详细的版本对应: - - - -| *Spring Boot* | *Spring Cloud* | -| :--------------------------- | :---------------------- | -| 1.5.2.RELEASE | Dalston.RC1 | -| **1.5.9.RELEASE** | **Edgware.RELEASE** | -| 2.0.2.RELEASE | Finchley.BUILD-SNAPSHOT | -| **2.0.3.RELEASE** | **Finchley.RELEASE** | -| 2.1.0.RELEASE-2.1.14.RELEASE | Greenwich.SR5 | -| **2.2.0.M4** | **Hoxton.SR4** | - - - -**关于spring cloud1.x版本和2.x版本区别** - -spring cloud各个版本之间是有所区别的,比如在SpringCloud中,1.X和2.X版本在pom.xml中引入的jar包名字都不一样,比如有的叫spirng-cloud-starter-hystrix 有的叫spring-cloud-netflix-hystrix,维护起来会比较困难。 - -1.x版本pom.xml里几个基本用到的jar长这样: - -```xml - - 4.0.0 - com.joyce - joyce-test - 1.0 - jar - - - org.springframework.boot - spring-boot-starter-parent - 1.5.9.RELEASE - - - - - - - org.springframework.cloud - spring-cloud-dependencies - Edgware.RELEASE - pom - import - - - - - - UTF-8 - - - - - org.springframework.cloud - spring-cloud-starter-feign - - - org.springframework.cloud - spring-cloud-starter-hystrix - - - org.springframework.cloud - spring-cloud-starter-zipkin - - - org.springframework.cloud - spring-cloud-starter-eureka - - - org.springframework.boot - spring-boot-starter-actuator - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - org.springframework.boot - spring-boot-starter-jetty - - - org.springframework.cloud - spring-cloud-starter-ribbon - - - org.springframework.boot - spring-boot-starter-test - test - - - -``` - -而在2.x版本中,比如我们需要eureka,去maven仓库中可能会看到deprecated, please use spring-cloud-starter-netflix-eureka-client这类提示,包括使用ribbon也会有 - -![在这里插入图片描述](https://img.jbzj.com/file_images/article/202009/2020091609493528.png) - -![在这里插入图片描述](https://img.jbzj.com/file_images/article/202009/2020091609493529.png) - -所以个人猜测2.x中统一用 -spring-cloud-starter-netflix-xx 替换了原有的 spring-cloud-starter-xx(此处如有不正确请指出) -所以2.x的版本pom.xml类似如下这样 - -```xml - - 4.0.0 - - com.forezp - service-feign - 0.0.1-SNAPSHOT - jar - - service-feign - Demo project for Spring Boot - - - - com.forezp - sc-f-chapter3 - 0.0.1-SNAPSHOT - - - - - org.springframework.cloud - spring-cloud-starter-netflix-eureka-client - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.cloud - spring-cloud-starter-openfeign - - - - -``` - - - -![img](https://img2018.cnblogs.com/blog/1097754/201909/1097754-20190907205906233-2071872814.png) - - - - 手动记录一些经本人实际验证可行的版本对应: - -| 序号 | 版本对应 | -| ---- | ------------------------------------------------------------ | -| 1 | 2.4.2 2020.0.0 | -| 2 | 2.4.1 2020.0.0-M6 | -| 3 | 2.4.0 2020.0.0-M6 | -| 4 | 2.3.2.RELEASE Greenwich.SR2 | - -**spring-cloud-dependencies** 版本列表可查看: - -https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-dependencies - -**spring-boot-starter-parent** 版本列表可查看: - -https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent - - - - 到spring官方下载最新的springboot 与 springcloud版本对应代码example: https://start.spring.io/ - - end! - diff --git "a/jun_springcloud_plugin/doc/\344\270\272Spring Cloud Ribbon\351\205\215\347\275\256\350\257\267\346\261\202\351\207\215\350\257\225\357\274\210Camden.SR2+\357\274\211.md" "b/jun_springcloud_plugin/doc/\344\270\272Spring Cloud Ribbon\351\205\215\347\275\256\350\257\267\346\261\202\351\207\215\350\257\225\357\274\210Camden.SR2+\357\274\211.md" deleted file mode 100644 index 1959062f4e..0000000000 --- "a/jun_springcloud_plugin/doc/\344\270\272Spring Cloud Ribbon\351\205\215\347\275\256\350\257\267\346\261\202\351\207\215\350\257\225\357\274\210Camden.SR2+\357\274\211.md" +++ /dev/null @@ -1,93 +0,0 @@ -# 为Spring Cloud Ribbon配置请求重试(Camden.SR2+) - -**原创** - - [2016-12-22](https://blog.didispace.com/spring-cloud-ribbon-failed-retry/) - - 翟永超 - - [Spring Cloud](https://blog.didispace.com/categories/Spring-Cloud/) - -[【推荐】从业15年的架构师告诉你:如何落地微服务和云原生架构?](https://blog.didispace.com/how-to-implement-microservice-and-cloud-native-architecture/) - -当我们使用Spring Cloud Ribbon实现客户端负载均衡的时候,通常都会利用`@LoadBalanced`来让`RestTemplate`具备客户端负载功能,从而实现面向服务名的接口访问(原理可见[《Spring Cloud源码分析(二)Ribbon》](http://blog.didispace.com/springcloud-sourcecode-ribbon/)一文,如果对Spring Cloud中使用Ribbon进行服务消费还没有概念的话,建议先阅读[《Spring Cloud构建微服务架构(二)服务消费者》](http://blog.didispace.com/springcloud2/)一文。)。 - -下面的例子,实现了对服务名为`hello-service`的`/hello`接口的调用。由于`RestTemplate`被`@LoadBalanced`修饰,所以它具备客户端负载均衡的能力,当请求真正发起的时候,url中的服务名会根据负载均衡策略从服务清单中挑选出一个实例来进行访问。 - -``` -@SpringCloudApplication -public class Application { - - @Bean - @LoadBalanced - RestTemplate restTemplate() { - return new RestTemplate(); - } - - @RestController - class ConsumerController { - - @Autowired - RestTemplate restTemplate; - - @RequestMapping(value = "/ribbon-consumer", method = RequestMethod.GET) - public String helloConsumer() { - return restTemplate.getForObject("http://hello-service/hello", String.class); - } - - } - - public static void main(String[] args) { - SpringApplication.run(ConsumerApplication.class, args); - } - -} -``` - -大多数情况下,上面的实现没有任何问题,但是总有一些意外发生,比如:有一个实例发生了故障而该情况还没有被服务治理机制及时的发现和摘除,这时候客户端访问该节点的时候自然会失败。所以,为了构建更为健壮的应用系统,我们希望当请求失败的时候能够有一定策略的重试机制,而不是直接返回失败。这个时候就需要开发人员人工的来为上面的`RestTemplate`调用实现重试机制。 - -不过,从**Spring Cloud Camden SR2**版本开始,我们就不用那么麻烦了。从该版本开始,Spring Cloud整合了Spring Retry来实现重试逻辑,而对于开发者只需要做一些配置即可。 - -以上面对`hello-service`服务的调用为例,我们可以在配置文件中增加如下内容: - -``` -spring.cloud.loadbalancer.retry.enabled=true - -hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=10000 - -hello-service.ribbon.ConnectTimeout=250 -hello-service.ribbon.ReadTimeout=1000 -hello-service.ribbon.OkToRetryOnAllOperations=true -hello-service.ribbon.MaxAutoRetriesNextServer=2 -hello-service.ribbon.MaxAutoRetries=1 -``` - -各参数的配置说明: - -- `spring.cloud.loadbalancer.retry.enabled`:该参数用来开启重试机制,它默认是关闭的。这里需要注意,官方文档中的配置参数少了`enabled`。 - - [![img](https://blog.didispace.com/assets/CAMDEN-SR2-RETRY.png)](https://blog.didispace.com/assets/CAMDEN-SR2-RETRY.png) - - 源码定义如下: - - ``` - @ConfigurationProperties("spring.cloud.loadbalancer.retry") - public class LoadBalancerRetryProperties { - private boolean enabled = false; - ... - } - ``` - -- `hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds`:断路器的超时时间需要大于ribbon的超时时间,不然不会触发重试。 - -- `hello-service.ribbon.ConnectTimeout`:请求连接的超时时间 - -- `hello-service.ribbon.ReadTimeout`:请求处理的超时时间 - -- `hello-service.ribbon.OkToRetryOnAllOperations`:对所有操作请求都进行重试 - -- `hello-service.ribbon.MaxAutoRetriesNextServer`:切换实例的重试次数 - -- `hello-service.ribbon.MaxAutoRetries`:对当前实例的重试次数 - -根据如上配置,当访问到故障请求的时候,它会再尝试访问一次当前实例(次数由`MaxAutoRetries`配置),如果不行,就换一个实例进行访问,如果还是不行,再换一次实例访问(更换次数由`MaxAutoRetriesNextServer`配置),如果依然不行,返回失败信息。 \ No newline at end of file diff --git "a/jun_springcloud_plugin/doc/\344\275\277\347\224\250Spring Boot Actuator\343\200\201Jolokia\345\222\214Grafana\345\256\236\347\216\260\345\207\206\345\256\236\346\227\266\347\233\221\346\216\247.md" "b/jun_springcloud_plugin/doc/\344\275\277\347\224\250Spring Boot Actuator\343\200\201Jolokia\345\222\214Grafana\345\256\236\347\216\260\345\207\206\345\256\236\346\227\266\347\233\221\346\216\247.md" deleted file mode 100644 index 8d1b9ca284..0000000000 --- "a/jun_springcloud_plugin/doc/\344\275\277\347\224\250Spring Boot Actuator\343\200\201Jolokia\345\222\214Grafana\345\256\236\347\216\260\345\207\206\345\256\236\346\227\266\347\233\221\346\216\247.md" +++ /dev/null @@ -1,64 +0,0 @@ -# 使用Spring Boot Actuator、Jolokia和Grafana实现准实时监控 - -**原创** - - [2017-02-26](https://blog.didispace.com/spring-boot-jolokia-grafana-monitor/) - - 翟永超 - - [Spring Boot](https://blog.didispace.com/categories/Spring-Boot/) - -[【推荐】从业15年的架构师告诉你:如何落地微服务和云原生架构?](https://blog.didispace.com/how-to-implement-microservice-and-cloud-native-architecture/) - -> 由于最近在做监控方面的工作,因此也读了不少相关的经验分享。其中有这样一篇文章总结了一些基于Spring Boot的监控方案,因此翻译了一下,希望可以对大家有所帮助。 -> -> 原文:[Near real-time monitoring charts with Spring Boot Actuator, Jolokia and Grafana](https://medium.com/@brunosimioni/near-real-time-monitoring-charts-with-spring-boot-actuator-jolokia-and-grafana-1ce267c50bcc#.il5xmlnv7) - -Spring Boot Actuator通过`/metrics`端点,以开箱即用的方式为应用程序的性能指标与响应统计提供了一个非常友好的监控方式。 - -由于在集群化的弹性环境中,应用程序的节点可以增长、扩展,并由非常大量的应用实例所组成。对于孤立节点的监控可能即费力又没有什么实际效果。所以,使用基于时间序列的数据聚合工具将获得更好的效果。 - -本文的目标在于找出一种仅需要通过工具和配置的方式就能实现的解决方案,来对Spring Boot Metrics实现基于时间序列的监控。 - -像NewRelic, AppDynamics或DataDog这些APM系统都能很好地完成这样的任务,它们通过使用JVM和字节码工具来生成自己的指标、分析工具和相关事务。也可以通过使用`@Timed`注释方法来实现。但是,这些方法将忽略所有Spring Boot Actuator库所提供的可用资源。另外,使用这些方法还有一个与保留数据相关的问题,它们对于短时间窗口内的监控是相对模糊的。 - -[![NewRelic在1分钟时间窗口内被发现和检测的事务](https://blog.didispace.com/assets/1-W_O7bNYmgarjHNasow-PsQ.png)](https://blog.didispace.com/assets/1-W_O7bNYmgarjHNasow-PsQ.png)NewRelic在1分钟时间窗口内被发现和检测的事务 - -`spring-boot-admin` 可以作为另外一个备选方案,因为它可以连接到Spring Boot的实例、并且可以聚合节点等。但是, `/metrics` 端点并不是根据时间轴来进行监控的,同时在不同节点上的相同应用模块(水平扩展)也没有得到聚合。这意味着您将面对这两种情况:没有时间序列的监控数据、只有对孤立节点的监控数据快照。 - -[![Spring Boot Admin with metrics from Actuator: a snapshot of metrics data of a given application node](https://blog.didispace.com/assets/1-KK_x2uD66NIIIfmyFIraEg.png)](https://blog.didispace.com/assets/1-KK_x2uD66NIIIfmyFIraEg.png)Spring Boot Admin with metrics from Actuator: a snapshot of metrics data of a given application node - -[![Spring Boot Admin with JMX and MBeans read data of a give application node](https://blog.didispace.com/assets/1-MztwgrZsF2wtXL_OMZCfdQ.png)](https://blog.didispace.com/assets/1-MztwgrZsF2wtXL_OMZCfdQ.png)Spring Boot Admin with JMX and MBeans read data of a give application node - -`jconsole`和`visualvm`可能是另外一种选择,它们通过RMI直接连接到JMX节点。Actuator存储来自JMX的MBean内的Metrics数据。另外,通过使用 [Jolokia](https://jolokia.org/),MBeans以RESTful HTTP端点的方式暴露,`/jolokia`。所以,相同的信息可以通过两个端点来获取:JMX MBean Metrics和Rest HTTP Jolokia端点。然而,这种方式存在同样的问题,它们直接连接到集群环境中的单个节点,另外还伴随着痛苦的老式RMI协议。 - -[![JConsole old-school JMX Metrics of a given application node](https://blog.didispace.com/assets/1-NOkLUyGMydiFYYotF2rKQ.png)](https://blog.didispace.com/assets/1-NOkLUyGMydiFYYotF2rKQ.png)JConsole old-school JMX Metrics of a given application node - -[![VisualVM JMX Metrics of a give application node](https://blog.didispace.com/assets/1-mH5Wey1GDlCmDRdZPlHYtg.png)](https://blog.didispace.com/assets/1-mH5Wey1GDlCmDRdZPlHYtg.png)VisualVM JMX Metrics of a give application node - -继续前进,我尝试了一些可能可以解决这些问题的现代化运维工具: - -- [**Prometheus**](https://prometheus.io/): 由SoundCloud编写,它存储一系列的监控数据并赋予漂亮的图标展现。Prometheus Gauges和Actuator Metrics并不完全兼容,所以人们写了 [一个数据转换器](https://github.com/prometheus/client_java/pull/114)。你也可以配置Prometheus来收集JMX数据。 -- [**Sensu**](https://sensuapp.org/): 作为Nagios和Zabbix的现代化替代品,它有一个插件可以直接连接到Spring Boot,[但是这个仓库最近已经不太更新了](https://github.com/sensu-plugins/sensu-plugins-springboot),所以我决定放弃它。 -- [**StatsD**](https://github.com/etsy/statsd): Spring Boot有一篇文章是[关于自定义导出数据给StatsD](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready-metric-writers-export-to-statsd)。然而,你除了要为Spring Boot应用安装StatsD实例之外,还不得不实现一些存根来让它工作起来。 -- [**Graphite**](http://graphiteapp.org/)**:** You got to be [a hero to install and get Graphite](https://graphite.readthedocs.io/en/latest/install.html) running. If you get there, [you can configure it along StatsD to get metrics working in a chart](https://matt.aimonetti.net/posts/2013/06/26/practical-guide-to-graphite-monitoring/). -- [**OpenTSDB**](http://opentsdb.net/)**:** Spring Boot有一篇文章[关于连接数据到OpenTSBD](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready-metric-writers-export-to-open-tsdb). 然而,这种方式与StatsD类似,你必须实现和维护自定义的代码来让它工作起来。另外,OpenTSDB没有开箱即用的图形可视化工具。 -- [**JMXTrans**](https://github.com/jmxtrans/jmxtrans): 可以用来提取数据并发送到其他的监控工具,它也需要具体的实现。 -- [**Ganglia**](http://ganglia.info/): 也是基于JVM上的工具,记录所有Actuator资源。与之前所说的APM有相同问题。 - -经过一番研究,我发现了一个更好的解决方案:通过InfluxDB 和Telegraf实现,零编码,只需要通过一些正确的配置。 - -- [**Jolokia**](https://jolokia.org/): Spring Boot [认可使用Jolokia来通过HTTP导出export JMX数据](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready-jolokia)。你只需要在工程类路径中增加一些依赖项,一切都是开箱即用的。不需要任何额外的实现。 -- [**Telegraf**](https://www.influxdata.com/time-series-platform/telegraf/)**:** Telegraf支持通过整合Jolokia来集成JMX数据的收集。[它有一个预制的输入插件](https://github.com/influxdata/telegraf/tree/master/plugins/inputs/jolokia),它是开箱即用的。不需要任何额外的实现。只需要做一些配置即可。 -- [**InfluxDB**](https://www.influxdata.com/time-series-platform/influxdb/)**:** InfluxDB通过 [输出插件](https://github.com/influxdata/telegraf/tree/master/plugins/outputs/influxdb)从Telegraf接收指标数据,它是开箱即用的,不需要任何额外的实现。 -- [**Grafana**](http://grafana.org/): Grafana通过[连接InfluxDB作为数据源](http://docs.grafana.org/datasources/influxdb/)来渲染图标。它是开箱即用的,不需要额外的实现。 - -简而言之,配置所有这些东西都非常的简单。 - -[![Spring Boot Actuator Raw Metrics](https://blog.didispace.com/assets/1-r252t1MBNRc3thU3DMRTcQ.png)](https://blog.didispace.com/assets/1-r252t1MBNRc3thU3DMRTcQ.png)Spring Boot Actuator Raw Metrics - -[![Metrics sent by Telegraf to InfluxDB, collected by Jolokia and JMX over HTTP](https://blog.didispace.com/assets/1-XdrZlKh1Q2G0yd6xNkSrgQ.png)](https://blog.didispace.com/assets/1-XdrZlKh1Q2G0yd6xNkSrgQ.png)Metrics sent by Telegraf to InfluxDB, collected by Jolokia and JMX over HTTP - -[![Grafana InfluxDB data source configuration](https://blog.didispace.com/assets/1-K8NTfF4Z2ms1YM_4cCjyvQ.png)](https://blog.didispace.com/assets/1-K8NTfF4Z2ms1YM_4cCjyvQ.png)Grafana InfluxDB data source configuration - -[![Grafana Metric chart query and configuration: gauges of an API](https://blog.didispace.com/assets/1-ZoQcStClNQf7iz_cQNZHxA.png)](https://blog.didispace.com/assets/1-ZoQcStClNQf7iz_cQNZHxA.png)Grafana Metric chart query and configuration: gauges of an API \ No newline at end of file diff --git "a/jun_springcloud_plugin/doc/\345\237\272\344\272\216Consul\347\232\204\345\210\206\345\270\203\345\274\217\344\277\241\345\217\267\351\207\217\345\256\236\347\216\260.md" "b/jun_springcloud_plugin/doc/\345\237\272\344\272\216Consul\347\232\204\345\210\206\345\270\203\345\274\217\344\277\241\345\217\267\351\207\217\345\256\236\347\216\260.md" deleted file mode 100644 index dfad5fad00..0000000000 --- "a/jun_springcloud_plugin/doc/\345\237\272\344\272\216Consul\347\232\204\345\210\206\345\270\203\345\274\217\344\277\241\345\217\267\351\207\217\345\256\236\347\216\260.md" +++ /dev/null @@ -1,351 +0,0 @@ -# 基于Consul的分布式信号量实现 - -**原创** - - [2017-04-15](https://blog.didispace.com/spring-cloud-consul-lock-and-semphore-2/) - - 翟永超 - - [Spring Cloud](https://blog.didispace.com/categories/Spring-Cloud/) - -[【推荐】从业15年的架构师告诉你:如何落地微服务和云原生架构?](https://blog.didispace.com/how-to-implement-microservice-and-cloud-native-architecture/) - -本文将继续讨论基于Consul的分布式锁实现。信号量是我们在实现并发控制时会经常使用的手段,主要用来限制同时并发线程或进程的数量,比如:Zuul默认情况下就使用信号量来限制每个路由的并发数,以实现不同路由间的资源隔离。 - -> 信号量(Semaphore),有时被称为信号灯,是在多线程环境下使用的一种设施,是可以用来保证两个或多个关键代码段不被并发调用。在进入一个关键代码段之前,线程必须获取一个信号量;一旦该关键代码段完成了,那么该线程必须释放信号量。其它想进入该关键代码段的线程必须等待直到第一个线程释放信号量。为了完成这个过程,需要创建一个信号量VI,然后将Acquire Semaphore VI以及Release Semaphore VI分别放置在每个关键代码段的首末端,确认这些信号量VI引用的是初始创建的信号量。如在这个停车场系统中,车位是公共资源,每辆车好比一个线程,看门人起的就是信号量的作用。 - -## 实现思路 - -- 信号量存储:semaphore/key -- acquired操作: - - 创建session - - 锁定key竞争者:semaphore/key/session - - 查询信号量:semaphore/key/.lock,可以获得如下内容(如果是第一次创建信号量,将获取不到,这个时候就直接创建) - -``` -{ - "limit": 3, - "holders": [ - "90c0772a-4bd3-3a3c-8215-3b8937e36027", - "93e5611d-5365-a374-8190-f80c4a7280ab" - ] -} -``` - -- 如果持有者已达上限,返回false,如果阻塞模式,就继续尝试acquired操作 -- 如果持有者未达上限,更新semaphore/key/.lock的内容,将当前线程的sessionId加入到holders中。注意:更新的时候需要设置cas,它的值是“查询信号量”步骤获得的“ModifyIndex”值,该值用于保证更新操作的基础没有被其他竞争者更新。如果更新成功,就开始执行具体逻辑。如果没有更新成功,说明有其他竞争者抢占了资源,返回false,阻塞模式下继续尝试acquired操作 -- release操作: - - 从semaphore/key/.lock的holders中移除当前sessionId - - 删除semaphore/key/session - - 删除当前的session - -## 流程图 - -[![img](https://blog.didispace.com/assets/consul-sem.png)](https://blog.didispace.com/assets/consul-sem.png) - -## 代码实现 - -``` -public class Semaphore { - - private Logger logger = Logger.getLogger(getClass()); - - private static final String prefix = "semaphore/"; // 信号量参数前缀 - - private ConsulClient consulClient; - private int limit; - private String keyPath; - private String sessionId = null; - private boolean acquired = false; - - /** - * - * @param consulClient consul客户端实例 - * @param limit 信号量上限值 - * @param keyPath 信号量在consul中存储的参数路径 - */ - public Semaphore(ConsulClient consulClient, int limit, String keyPath) { - this.consulClient = consulClient; - this.limit = limit; - this.keyPath = prefix + keyPath; - } - - /** - * acquired信号量 - * - * @param block 是否阻塞。如果为true,那么一直尝试,直到获取到该资源为止。 - * @return - * @throws IOException - */ - public Boolean acquired(boolean block) throws IOException { - - if(acquired) { - logger.error(sessionId + " - Already acquired"); - throw new RuntimeException(sessionId + " - Already acquired"); - } - - // create session - clearSession(); - this.sessionId = createSessionId("semaphore"); - logger.debug("Create session : " + sessionId); - - // add contender entry - String contenderKey = keyPath + "/" + sessionId; - logger.debug("contenderKey : " + contenderKey); - PutParams putParams = new PutParams(); - putParams.setAcquireSession(sessionId); - Boolean b = consulClient.setKVValue(contenderKey, "", putParams).getValue(); - if(!b) { - logger.error("Failed to add contender entry : " + contenderKey + ", " + sessionId); - throw new RuntimeException("Failed to add contender entry : " + contenderKey + ", " + sessionId); - } - - while(true) { - // try to take the semaphore - String lockKey = keyPath + "/.lock"; - String lockKeyValue; - - GetValue lockKeyContent = consulClient.getKVValue(lockKey).getValue(); - - if (lockKeyContent != null) { - // lock值转换 - lockKeyValue = lockKeyContent.getValue(); - BASE64Decoder decoder = new BASE64Decoder(); - byte[] v = decoder.decodeBuffer(lockKeyValue); - String lockKeyValueDecode = new String(v); - logger.debug("lockKey=" + lockKey + ", lockKeyValueDecode=" + lockKeyValueDecode); - - Gson gson = new Gson(); - ContenderValue contenderValue = gson.fromJson(lockKeyValueDecode, ContenderValue.class); - // 当前信号量已满 - if(contenderValue.getLimit() == contenderValue.getHolders().size()) { - logger.debug("Semaphore limited " + contenderValue.getLimit() + ", waiting..."); - if(block) { - // 如果是阻塞模式,再尝试 - try { - Thread.sleep(100L); - } catch (InterruptedException e) { - } - continue; - } - // 非阻塞模式,直接返回没有获取到信号量 - return false; - } - // 信号量增加 - contenderValue.getHolders().add(sessionId); - putParams = new PutParams(); - putParams.setCas(lockKeyContent.getModifyIndex()); - boolean c = consulClient.setKVValue(lockKey, contenderValue.toString(), putParams).getValue(); - if(c) { - acquired = true; - return true; - } - else - continue; - } else { - // 当前信号量还没有,所以创建一个,并马上抢占一个资源 - ContenderValue contenderValue = new ContenderValue(); - contenderValue.setLimit(limit); - contenderValue.getHolders().add(sessionId); - - putParams = new PutParams(); - putParams.setCas(0L); - boolean c = consulClient.setKVValue(lockKey, contenderValue.toString(), putParams).getValue(); - if (c) { - acquired = true; - return true; - } - continue; - } - } - } - - /** - * 创建sessionId - * @param sessionName - * @return - */ - public String createSessionId(String sessionName) { - NewSession newSession = new NewSession(); - newSession.setName(sessionName); - return consulClient.sessionCreate(newSession, null).getValue(); - } - - /** - * 释放session、并从lock中移除当前的sessionId - * @throws IOException - */ - public void release() throws IOException { - if(this.acquired) { - // remove session from lock - while(true) { - String contenderKey = keyPath + "/" + sessionId; - String lockKey = keyPath + "/.lock"; - String lockKeyValue; - - GetValue lockKeyContent = consulClient.getKVValue(lockKey).getValue(); - if (lockKeyContent != null) { - // lock值转换 - lockKeyValue = lockKeyContent.getValue(); - BASE64Decoder decoder = new BASE64Decoder(); - byte[] v = decoder.decodeBuffer(lockKeyValue); - String lockKeyValueDecode = new String(v); - Gson gson = new Gson(); - ContenderValue contenderValue = gson.fromJson(lockKeyValueDecode, ContenderValue.class); - contenderValue.getHolders().remove(sessionId); - PutParams putParams = new PutParams(); - putParams.setCas(lockKeyContent.getModifyIndex()); - consulClient.deleteKVValue(contenderKey); - boolean c = consulClient.setKVValue(lockKey, contenderValue.toString(), putParams).getValue(); - if(c) { - break; - } - } - } - // remove session key - - } - this.acquired = false; - clearSession(); - } - - public void clearSession() { - if(sessionId != null) { - consulClient.sessionDestroy(sessionId, null); - sessionId = null; - } - } - - class ContenderValue implements Serializable { - - private Integer limit; - private List holders = new ArrayList<>(); - - public Integer getLimit() { - return limit; - } - - public void setLimit(Integer limit) { - this.limit = limit; - } - - public List getHolders() { - return holders; - } - - public void setHolders(List holders) { - this.holders = holders; - } - - @Override - public String toString() { - return new Gson().toJson(this); - } - - } - -} -``` - -## 单元测试 - -下面单元测试的逻辑:通过线程的方式来模拟不同的分布式服务来获取信号量执行业务逻辑。由于信号量与简单的分布式互斥锁有所不同,它不是只限定一个线程可以操作,而是可以控制多个线程的并发,所以通过下面的单元测试,我们设置信号量为3,然后同时启动15个线程来竞争的情况,来观察分布式信号量实现的结果如何。 - -``` -public class TestLock { - - private Logger logger = Logger.getLogger(getClass()); - - @Test - public void testSemaphore() throws Exception { - new Thread(new SemaphoreRunner(1)).start(); - new Thread(new SemaphoreRunner(2)).start(); - new Thread(new SemaphoreRunner(3)).start(); - new Thread(new SemaphoreRunner(4)).start(); - new Thread(new SemaphoreRunner(5)).start(); - new Thread(new SemaphoreRunner(6)).start(); - new Thread(new SemaphoreRunner(7)).start(); - new Thread(new SemaphoreRunner(8)).start(); - new Thread(new SemaphoreRunner(9)).start(); - new Thread(new SemaphoreRunner(10)).start(); - Thread.sleep(1000000L); - } -} - -public class SemaphoreRunner implements Runnable { - - private Logger logger = Logger.getLogger(getClass()); - - private int flag; - - public SemaphoreRunner(int flag) { - this.flag = flag; - } - - @Override - public void run() { - Semaphore semaphore = new Semaphore(new ConsulClient(), 3, "mg-init"); - try { - if (semaphore.acquired(true)) { - // 获取到信号量,执行业务逻辑 - logger.info("Thread " + flag + " start!"); - Thread.sleep(new Random().nextInt(10000)); - logger.info("Thread " + flag + " end!"); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - // 信号量释放、Session锁释放、Session删除 - semaphore.release(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - } -} -INFO [Thread-6] SemaphoreRunner - Thread 7 start! -INFO [Thread-2] SemaphoreRunner - Thread 3 start! -INFO [Thread-7] SemaphoreRunner - Thread 8 start! -INFO [Thread-2] SemaphoreRunner - Thread 3 end! -INFO [Thread-5] SemaphoreRunner - Thread 6 start! -INFO [Thread-6] SemaphoreRunner - Thread 7 end! -INFO [Thread-9] SemaphoreRunner - Thread 10 start! -INFO [Thread-5] SemaphoreRunner - Thread 6 end! -INFO [Thread-1] SemaphoreRunner - Thread 2 start! -INFO [Thread-7] SemaphoreRunner - Thread 8 end! -INFO [Thread-10] SemaphoreRunner - Thread 11 start! -INFO [Thread-10] SemaphoreRunner - Thread 11 end! -INFO [Thread-12] SemaphoreRunner - Thread 13 start! -INFO [Thread-1] SemaphoreRunner - Thread 2 end! -INFO [Thread-3] SemaphoreRunner - Thread 4 start! -INFO [Thread-9] SemaphoreRunner - Thread 10 end! -INFO [Thread-0] SemaphoreRunner - Thread 1 start! -INFO [Thread-3] SemaphoreRunner - Thread 4 end! -INFO [Thread-14] SemaphoreRunner - Thread 15 start! -INFO [Thread-12] SemaphoreRunner - Thread 13 end! -INFO [Thread-0] SemaphoreRunner - Thread 1 end! -INFO [Thread-13] SemaphoreRunner - Thread 14 start! -INFO [Thread-11] SemaphoreRunner - Thread 12 start! -INFO [Thread-13] SemaphoreRunner - Thread 14 end! -INFO [Thread-4] SemaphoreRunner - Thread 5 start! -INFO [Thread-4] SemaphoreRunner - Thread 5 end! -INFO [Thread-8] SemaphoreRunner - Thread 9 start! -INFO [Thread-11] SemaphoreRunner - Thread 12 end! -INFO [Thread-14] SemaphoreRunner - Thread 15 end! -INFO [Thread-8] SemaphoreRunner - Thread 9 end! -``` - -从测试结果,我们可以发现当信号量持有者数量达到信号量上限3的时候,其他竞争者就开始进行等待了,只有当某个持有者释放信号量之后,才会有新的线程变成持有者,从而开始执行自己的业务逻辑。所以,分布式信号量可以帮助我们有效的控制同时操作某个共享资源的并发数。 - -## 优化建议 - -同前文一样,这里只是做了简单的实现。线上应用还必须加入TTL的session清理以及对.lock资源中的无效holder进行清理的机制。 - -参考文档:https://www.consul.io/docs/guides/semaphore.html - -## 实现代码 - -- GitHub:https://github.com/dyc87112/consul-distributed-lock -- 开源中国:http://git.oschina.net/didispace/consul-distributed-lock \ No newline at end of file diff --git "a/jun_springcloud_plugin/doc/\345\237\272\344\272\216Consul\347\232\204\345\210\206\345\270\203\345\274\217\351\224\201\345\256\236\347\216\260.md" "b/jun_springcloud_plugin/doc/\345\237\272\344\272\216Consul\347\232\204\345\210\206\345\270\203\345\274\217\351\224\201\345\256\236\347\216\260.md" deleted file mode 100644 index 6a9d1bd296..0000000000 --- "a/jun_springcloud_plugin/doc/\345\237\272\344\272\216Consul\347\232\204\345\210\206\345\270\203\345\274\217\351\224\201\345\256\236\347\216\260.md" +++ /dev/null @@ -1,185 +0,0 @@ -# 基于Consul的分布式锁实现 - -**原创** - - [2017-04-12](https://blog.didispace.com/spring-cloud-consul-lock-and-semphore/) - - 翟永超 - - [Spring Cloud](https://blog.didispace.com/categories/Spring-Cloud/) - -[【推荐】从业15年的架构师告诉你:如何落地微服务和云原生架构?](https://blog.didispace.com/how-to-implement-microservice-and-cloud-native-architecture/) - -我们在构建分布式系统的时候,经常需要控制对共享资源的互斥访问。这个时候我们就涉及到分布式锁(也称为全局锁)的实现,基于目前的各种工具,我们已经有了大量的实现方式,比如:基于Redis的实现、基于Zookeeper的实现。本文将介绍一种基于Consul 的Key/Value存储来实现分布式锁以及信号量的方法。 - -## 分布式锁实现 - -基于Consul的分布式锁主要利用Key/Value存储API中的acquire和release操作来实现。acquire和release操作是类似Check-And-Set的操作: - -- acquire操作只有当锁不存在持有者时才会返回true,并且set设置的Value值,同时执行操作的session会持有对该Key的锁,否则就返回false -- release操作则是使用指定的session来释放某个Key的锁,如果指定的session无效,那么会返回false,否则就会set设置Value值,并返回true - -具体实现中主要使用了这几个Key/Value的API: - -- create session:https://www.consul.io/api/session.html#session_create -- delete session:https://www.consul.io/api/session.html#delete-session -- KV acquire/release:https://www.consul.io/api/kv.html#create-update-key - -#### 基本流程 - -[![img](https://blog.didispace.com/assets/consul-lock.png)](https://blog.didispace.com/assets/consul-lock.png) - -#### 具体实现 - -``` -public class Lock { - - private static final String prefix = "lock/"; // 同步锁参数前缀 - - private ConsulClient consulClient; - private String sessionName; - private String sessionId = null; - private String lockKey; - - /** - * - * @param consulClient - * @param sessionName 同步锁的session名称 - * @param lockKey 同步锁在consul的KV存储中的Key路径,会自动增加prefix前缀,方便归类查询 - */ - public Lock(ConsulClient consulClient, String sessionName, String lockKey) { - this.consulClient = consulClient; - this.sessionName = sessionName; - this.lockKey = prefix + lockKey; - } - - /** - * 获取同步锁 - * - * @param block 是否阻塞,直到获取到锁为止 - * @return - */ - public Boolean lock(boolean block) { - if (sessionId != null) { - throw new RuntimeException(sessionId + " - Already locked!"); - } - sessionId = createSession(sessionName); - while(true) { - PutParams putParams = new PutParams(); - putParams.setAcquireSession(sessionId); - if(consulClient.setKVValue(lockKey, "lock:" + LocalDateTime.now(), putParams).getValue()) { - return true; - } else if(block) { - continue; - } else { - return false; - } - } - } - - /** - * 释放同步锁 - * - * @return - */ - public Boolean unlock() { - PutParams putParams = new PutParams(); - putParams.setReleaseSession(sessionId); - boolean result = consulClient.setKVValue(lockKey, "unlock:" + LocalDateTime.now(), putParams).getValue(); - consulClient.sessionDestroy(sessionId, null); - return result; - } - - /** - * 创建session - * @param sessionName - * @return - */ - private String createSession(String sessionName) { - NewSession newSession = new NewSession(); - newSession.setName(sessionName); - return consulClient.sessionCreate(newSession, null).getValue(); - } - -} -``` - -#### 单元测试 - -下面单元测试的逻辑:通过线程的方式来模拟不同的分布式服务来竞争锁。多个处理线程同时以阻塞方式来申请分布式锁,当处理线程获得锁之后,Sleep一段随机事件,以模拟处理业务逻辑,处理完毕之后释放锁。 - -``` -public class TestLock { - - private Logger logger = Logger.getLogger(getClass()); - - @Test - public void testLock() throws Exception { - new Thread(new LockRunner(1)).start(); - new Thread(new LockRunner(2)).start(); - new Thread(new LockRunner(3)).start(); - new Thread(new LockRunner(4)).start(); - new Thread(new LockRunner(5)).start(); - Thread.sleep(200000L); - } - - class LockRunner implements Runnable { - - private Logger logger = Logger.getLogger(getClass()); - private int flag; - - public LockRunner(int flag) { - this.flag = flag; - } - - @Override - public void run() { - Lock lock = new Lock(new ConsulClient(), "lock-session", "lock-key"); - try { - if (lock.lock(true)) { - logger.info("Thread " + flag + " start!"); - Thread.sleep(new Random().nextInt(3000L)); - logger.info("Thread " + flag + " end!"); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - lock.unlock(); - } - } - } - -} -``` - -单元测试执行结果如下: - -``` -2017-04-12 21:28:09,698 INFO [Thread-0] LockRunner - Thread 1 start! -2017-04-12 21:28:12,717 INFO [Thread-0] LockRunner - Thread 1 end! -2017-04-12 21:28:13,219 INFO [Thread-2] LockRunner - Thread 3 start! -2017-04-12 21:28:15,672 INFO [Thread-2] LockRunner - Thread 3 end! -2017-04-12 21:28:15,735 INFO [Thread-1] LockRunner - Thread 2 start! -2017-04-12 21:28:17,788 INFO [Thread-1] LockRunner - Thread 2 end! -2017-04-12 21:28:18,249 INFO [Thread-4] LockRunner - Thread 5 start! -2017-04-12 21:28:19,573 INFO [Thread-4] LockRunner - Thread 5 end! -2017-04-12 21:28:19,757 INFO [Thread-3] LockRunner - Thread 4 start! -2017-04-12 21:28:21,353 INFO [Thread-3] LockRunner - Thread 4 end! -``` - -从测试结果我们可以看到,通过分布式锁的形式来控制并发时,多个同步操作只会有一个操作能够被执行,其他操作只有在等锁释放之后才有机会去执行,所以通过这样的分布式锁,我们可以控制共享资源同时只能被一个操作进行执行,以保障数据处理时的分布式并发问题。 - -#### 优化建议 - -本文我们实现了基于Consul的简单分布式锁,但是在实际运行时,可能会因为各种各样的意外情况导致unlock操作没有得到正确地执行,从而使得分布式锁无法释放。所以为了更完善的使用分布式锁,我们还必须实现对锁的超时清理等控制,保证即使出现了未正常解锁的情况下也能自动修复,以提升系统的健壮性。那么如何实现呢?请持续关注我的后续分解! - -#### 参考文档 - -Key/Value的API:https://www.consul.io/api/kv.html - -选举机制:https://www.consul.io/docs/guides/leader-election.html - -#### 实现代码 - -- GitHub:https://github.com/dyc87112/consul-distributed-lock -- 开源中国:http://git.oschina.net/didispace/consul-distributed-lock \ No newline at end of file diff --git a/jun_springcloud_plugin/pom.xml b/jun_springcloud_plugin/pom.xml deleted file mode 100644 index 3a539226a3..0000000000 --- a/jun_springcloud_plugin/pom.xml +++ /dev/null @@ -1,237 +0,0 @@ - - - 4.0.0 - io.github.wujun728 - jun_springcloud_plugin - pom - 1.0 - - - - - - - - - - 1.0.1 - 8.0.15 - 5.2.0.RELEASE - 3.4.6 - 1.3.2 - 5.1.10 - - 2.6.5 - 3.5.5 - 0.10 - - 3.9 - 1.9.3 - 4.1 - 4.12 - - 3.0.0 - 4.5.6 - 1.2.62 - 3.1.0 - - 1.2.17 - 4.0.1 - 5.7.3 - - - UTF-8 - UTF-8 - 1.8 - 1.8 - - - - - - - com.alibaba - druid - ${druid.version} - - - mysql - mysql-connector-java - ${mysql.version} - runtime - - - org.springframework - spring-webmvc - ${spring.version} - - - org.springframework - spring-context - ${spring.version} - - - org.springframework - spring-aop - ${spring.version} - - - org.mybatis - mybatis - ${mybatis.version} - - - org.mybatis - mybatis-spring - ${mybatis-spring.version} - - - - com.github.pagehelper - pagehelper - ${pagehelper.version} - - - com.alibaba - dubbo - ${dubbo.version} - - - org.apache.zookeeper - zookeeper - ${zookeeper.version} - - - com.101tec - zkclient - ${zkclient.version} - - - com.alibaba - fastjson - ${fastjson.version} - - - redis.clients - jedis - ${jedis.version} - - - log4j - log4j - ${log4j.version} - - - javax.servlet - javax.servlet-api - ${javax.servlet.version} - provided - - - com.rabbitmq - amqp-client - ${rabbitmq-client.version} - - - - - - - - - - junit - junit - ${junit.version} - test - - - commons-beanutils - commons-beanutils - ${commons-beanutils.version} - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - - - - - - - - - - maven-clean-plugin - 3.0.0 - - - - maven-resources-plugin - 3.0.2 - - - - maven-compiler-plugin - 3.7.0 - - - - maven-surefire-plugin - 2.20.1 - - - - maven-war-plugin - 3.2.0 - - - - maven-install-plugin - 2.5.2 - - - - - - - - maven-surefire-plugin - - - true - - - - 2.20.1 - - - - - - - - src/main/java - - **/*.xml - **/*.java - - - - **/*.yaml - - - - true - - - - - - - - diff --git a/jun_templatespider/.factorypath b/jun_templatespider/.factorypath new file mode 100644 index 0000000000..c3860977b6 --- /dev/null +++ b/jun_templatespider/.factorypath @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/jun_templatespider/jun_templatespider.zip b/jun_templatespider/jun_templatespider.zip new file mode 100644 index 0000000000..c532db5e1b Binary files /dev/null and b/jun_templatespider/jun_templatespider.zip differ diff --git a/jun_templatespider/pom.xml b/jun_templatespider/pom.xml new file mode 100644 index 0000000000..ad80637ba5 --- /dev/null +++ b/jun_templatespider/pom.xml @@ -0,0 +1,243 @@ + + + 4.0.0 + + com.jun.plugin + jun_plugin + 1.0 + + com.jun.plugin + jun_templatespider + 0.0.1-SNAPSHOT + war + + jun_templatespider Maven Webapp + http://maven.apache.org + + + UTF-8 + 1.8 + 1.8 + 5.0.2.RELEASE + 1.6.6 + 1.2.12 + 11.2.0.1.0 + 3.4.5 + 5.0.1.RELEASE + 2.9.1 + + + + + + org.slf4j + slf4j-api + 1.7.25 + + + + + org.apache.logging.log4j + log4j-slf4j-impl + ${log4j2.version} + + runtime + + true + + + + + org.apache.logging.log4j + log4j-core + ${log4j2.version} + runtime + true + + + org.apache.logging.log4j + log4j-api + ${log4j2.version} + runtime + true + + + + junit + junit + 3.8.1 + test + + + + + mysql + mysql-connector-java + 5.1.40 + + + + + + + + + + + + org.aspectj + aspectjweaver + 1.6.8 + + + org.springframework + spring-aop + ${spring.version} + + + org.springframework + spring-context + ${spring.version} + + + org.springframework + spring-context-support + ${spring.version} + + + org.springframework + spring-web + ${spring.version} + + + org.springframework + spring-orm + ${spring.version} + + + org.springframework + spring-beans + ${spring.version} + + + org.springframework + spring-core + ${spring.version} + + + org.springframework + spring-test + ${spring.version} + + + org.springframework + spring-webmvc + ${spring.version} + + + + org.springframework + spring-tx + ${spring.version} + + + junit + junit + 4.12 + test + + + + javax.servlet + javax.servlet-api + 3.1.0 + provided + + + javax.servlet.jsp + jsp-api + 2.0 + provided + + + jstl + jstl + 1.2 + + + + + + + + + + + + + + + + + + + + org.mybatis + mybatis + ${mybatis.version} + + + org.mybatis + mybatis-spring + 1.3.0 + + + com.github.pagehelper + pagehelper + 5.1.2 + + + org.springframework.security + spring-security-web + ${spring.security.version} + + + org.springframework.security + spring-security-config + ${spring.security.version} + + + org.springframework.security + spring-security-core + ${spring.security.version} + + + org.springframework.security + spring-security-taglibs + ${spring.security.version} + + + + mysql + mysql-connector-java + 5.1.46 + + + com.alibaba + druid + 1.1.19 + + + + javax.annotation + jsr250-api + 1.0 + + + + + + jun_log + + diff --git a/jun_templatespider/src/main/java/com/jun/base/log/log4j2/demo/Main.java b/jun_templatespider/src/main/java/com/jun/base/log/log4j2/demo/Main.java new file mode 100644 index 0000000000..a8ccad2c18 --- /dev/null +++ b/jun_templatespider/src/main/java/com/jun/base/log/log4j2/demo/Main.java @@ -0,0 +1,19 @@ +package com.jun.base.log.log4j2.demo; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author 许波波 + * @date 2019/1/16 + */ +public class Main { + private static final Logger logger = LoggerFactory.getLogger(Main.class); + + public static void main(String[] args) { + logger.debug("打印debug级别日志"); + logger.info("打印info级别日志"); + logger.warn("打印warn级别日志"); + logger.error("打印error级别日志"); + } +} diff --git a/jun_templatespider/src/main/java/com/xia/controller/AdminController.java b/jun_templatespider/src/main/java/com/xia/controller/AdminController.java new file mode 100644 index 0000000000..4e4b80113c --- /dev/null +++ b/jun_templatespider/src/main/java/com/xia/controller/AdminController.java @@ -0,0 +1,34 @@ +package com.xia.controller; + +import com.alibaba.druid.util.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import javax.servlet.http.HttpServletRequest; +import java.util.logging.LogManager; + +@Controller +@RequestMapping("/admin") +public class AdminController { + private static Logger logger = LoggerFactory.getLogger(AdminController.class); + + @GetMapping("/login") + @ResponseBody + public String login(HttpServletRequest request, String name, String password) { + logger.info("管理员尝试登陆: name = " + name); + try { + if (StringUtils.isEmpty(name)||StringUtils.isEmpty(password)) { + logger.error("用户名或密码不能为空!"); + } + } catch (Exception e) { + logger.error(e.getMessage()); + e.printStackTrace(); + } + return "登录成功"; + } + +} diff --git a/jun_templatespider/src/main/java/com/xia/utils/ConnectionFactory.java b/jun_templatespider/src/main/java/com/xia/utils/ConnectionFactory.java new file mode 100644 index 0000000000..cc4a44b85b --- /dev/null +++ b/jun_templatespider/src/main/java/com/xia/utils/ConnectionFactory.java @@ -0,0 +1,35 @@ +package com.xia.utils; + +import com.alibaba.druid.pool.DruidDataSource; + +import javax.sql.DataSource; +import java.io.*; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Properties; + +public class ConnectionFactory { + + private DataSource dataSource = null; + + private ConnectionFactory() { + Properties properties = new Properties(); + try { + properties.load(new FileInputStream(new File("D:\\ideawork\\test_log4j2\\src\\main\\resources\\db.properties"))); + } catch (IOException e) { + e.printStackTrace(); + } + dataSource = new DruidDataSource(); + ((DruidDataSource) dataSource).configFromPropety(properties); + } + + public static Connection getDatabaseConnection() throws IOException, SQLException { + return Singleton.INSTANCE.dataSource.getConnection(); + } + + private static interface Singleton { + final ConnectionFactory INSTANCE = new ConnectionFactory(); + } + + +} \ No newline at end of file diff --git a/jun_templatespider/src/main/resources/db.properties b/jun_templatespider/src/main/resources/db.properties new file mode 100644 index 0000000000..c0022e3d6b --- /dev/null +++ b/jun_templatespider/src/main/resources/db.properties @@ -0,0 +1,4 @@ +druid.url=jdbc:mysql://127.0.0.1:3306/auge_log?useSSL=false +druid.username=root +druid.password=123456 +druid.driverClassName=com.mysql.jdbc.Driver \ No newline at end of file diff --git a/jun_java_plugins/jun_websocket/src/main/resources/log4j2.xml b/jun_templatespider/src/main/resources/log4j2.xml similarity index 100% rename from jun_java_plugins/jun_websocket/src/main/resources/log4j2.xml rename to jun_templatespider/src/main/resources/log4j2.xml diff --git a/jun_java_plugins/jun_websocket/src/main/resources/log4j2jdbc.xml b/jun_templatespider/src/main/resources/log4j2jdbc.xml similarity index 100% rename from jun_java_plugins/jun_websocket/src/main/resources/log4j2jdbc.xml rename to jun_templatespider/src/main/resources/log4j2jdbc.xml diff --git a/jun_templatespider/src/main/resources/springmvc.xml b/jun_templatespider/src/main/resources/springmvc.xml new file mode 100644 index 0000000000..21ee7a0c0e --- /dev/null +++ b/jun_templatespider/src/main/resources/springmvc.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jun_java_plugins/jun_websocket/src/main/test/com/xia/Test.java b/jun_templatespider/src/main/test/com/xia/Test.java similarity index 100% rename from jun_java_plugins/jun_websocket/src/main/test/com/xia/Test.java rename to jun_templatespider/src/main/test/com/xia/Test.java diff --git a/jun_templatespider/src/main/webapp/WEB-INF/web.xml b/jun_templatespider/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..b7c7ed7dbb --- /dev/null +++ b/jun_templatespider/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,16 @@ + + + Archetype Created Web Application + + index.html + index.htm + index.jsp + default.html + default.htm + default.jsp + + + + diff --git a/jun_templatespider/src/main/webapp/index.jsp b/jun_templatespider/src/main/webapp/index.jsp new file mode 100644 index 0000000000..61ee27ccec --- /dev/null +++ b/jun_templatespider/src/main/webapp/index.jsp @@ -0,0 +1,6 @@ + + +

        Hello World!

        + + + diff --git a/jun_test/.factorypath b/jun_test/.factorypath new file mode 100644 index 0000000000..c3860977b6 --- /dev/null +++ b/jun_test/.factorypath @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/jun_test/.gitignore b/jun_test/.gitignore new file mode 100644 index 0000000000..b83d22266a --- /dev/null +++ b/jun_test/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/jun_test/pom.xml b/jun_test/pom.xml new file mode 100644 index 0000000000..7a2d307239 --- /dev/null +++ b/jun_test/pom.xml @@ -0,0 +1,243 @@ + + + 4.0.0 + + com.jun.plugin + jun_plugin + 1.0 + + com.jun.plugin + jun_test + 0.0.1-SNAPSHOT + war + + jun_log Maven Webapp + http://maven.apache.org + + + UTF-8 + 1.8 + 1.8 + 5.0.2.RELEASE + 1.6.6 + 1.2.12 + 11.2.0.1.0 + 3.4.5 + 5.0.1.RELEASE + 2.9.1 + + + + + + org.slf4j + slf4j-api + 1.7.25 + + + + + org.apache.logging.log4j + log4j-slf4j-impl + ${log4j2.version} + + runtime + + true + + + + + org.apache.logging.log4j + log4j-core + ${log4j2.version} + runtime + true + + + org.apache.logging.log4j + log4j-api + ${log4j2.version} + runtime + true + + + + junit + junit + 3.8.1 + test + + + + + mysql + mysql-connector-java + 5.1.40 + + + + + + + + + + + + org.aspectj + aspectjweaver + 1.6.8 + + + org.springframework + spring-aop + ${spring.version} + + + org.springframework + spring-context + ${spring.version} + + + org.springframework + spring-context-support + ${spring.version} + + + org.springframework + spring-web + ${spring.version} + + + org.springframework + spring-orm + ${spring.version} + + + org.springframework + spring-beans + ${spring.version} + + + org.springframework + spring-core + ${spring.version} + + + org.springframework + spring-test + ${spring.version} + + + org.springframework + spring-webmvc + ${spring.version} + + + + org.springframework + spring-tx + ${spring.version} + + + junit + junit + 4.12 + test + + + + javax.servlet + javax.servlet-api + 3.1.0 + provided + + + javax.servlet.jsp + jsp-api + 2.0 + provided + + + jstl + jstl + 1.2 + + + + + + + + + + + + + + + + + + + + org.mybatis + mybatis + ${mybatis.version} + + + org.mybatis + mybatis-spring + 1.3.0 + + + com.github.pagehelper + pagehelper + 5.1.2 + + + org.springframework.security + spring-security-web + ${spring.security.version} + + + org.springframework.security + spring-security-config + ${spring.security.version} + + + org.springframework.security + spring-security-core + ${spring.security.version} + + + org.springframework.security + spring-security-taglibs + ${spring.security.version} + + + + mysql + mysql-connector-java + 5.1.46 + + + com.alibaba + druid + 1.1.19 + + + + javax.annotation + jsr250-api + 1.0 + + + + + + jun_log + + diff --git a/jun_test/src/main/java/com/jun/base/log/log4j2/demo/Main.java b/jun_test/src/main/java/com/jun/base/log/log4j2/demo/Main.java new file mode 100644 index 0000000000..a8ccad2c18 --- /dev/null +++ b/jun_test/src/main/java/com/jun/base/log/log4j2/demo/Main.java @@ -0,0 +1,19 @@ +package com.jun.base.log.log4j2.demo; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author 许波波 + * @date 2019/1/16 + */ +public class Main { + private static final Logger logger = LoggerFactory.getLogger(Main.class); + + public static void main(String[] args) { + logger.debug("打印debug级别日志"); + logger.info("打印info级别日志"); + logger.warn("打印warn级别日志"); + logger.error("打印error级别日志"); + } +} diff --git a/jun_test/src/main/java/com/xia/controller/AdminController.java b/jun_test/src/main/java/com/xia/controller/AdminController.java new file mode 100644 index 0000000000..4e4b80113c --- /dev/null +++ b/jun_test/src/main/java/com/xia/controller/AdminController.java @@ -0,0 +1,34 @@ +package com.xia.controller; + +import com.alibaba.druid.util.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import javax.servlet.http.HttpServletRequest; +import java.util.logging.LogManager; + +@Controller +@RequestMapping("/admin") +public class AdminController { + private static Logger logger = LoggerFactory.getLogger(AdminController.class); + + @GetMapping("/login") + @ResponseBody + public String login(HttpServletRequest request, String name, String password) { + logger.info("管理员尝试登陆: name = " + name); + try { + if (StringUtils.isEmpty(name)||StringUtils.isEmpty(password)) { + logger.error("用户名或密码不能为空!"); + } + } catch (Exception e) { + logger.error(e.getMessage()); + e.printStackTrace(); + } + return "登录成功"; + } + +} diff --git a/jun_test/src/main/java/com/xia/utils/ConnectionFactory.java b/jun_test/src/main/java/com/xia/utils/ConnectionFactory.java new file mode 100644 index 0000000000..cc4a44b85b --- /dev/null +++ b/jun_test/src/main/java/com/xia/utils/ConnectionFactory.java @@ -0,0 +1,35 @@ +package com.xia.utils; + +import com.alibaba.druid.pool.DruidDataSource; + +import javax.sql.DataSource; +import java.io.*; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Properties; + +public class ConnectionFactory { + + private DataSource dataSource = null; + + private ConnectionFactory() { + Properties properties = new Properties(); + try { + properties.load(new FileInputStream(new File("D:\\ideawork\\test_log4j2\\src\\main\\resources\\db.properties"))); + } catch (IOException e) { + e.printStackTrace(); + } + dataSource = new DruidDataSource(); + ((DruidDataSource) dataSource).configFromPropety(properties); + } + + public static Connection getDatabaseConnection() throws IOException, SQLException { + return Singleton.INSTANCE.dataSource.getConnection(); + } + + private static interface Singleton { + final ConnectionFactory INSTANCE = new ConnectionFactory(); + } + + +} \ No newline at end of file diff --git a/jun_test/src/main/resources/db.properties b/jun_test/src/main/resources/db.properties new file mode 100644 index 0000000000..c0022e3d6b --- /dev/null +++ b/jun_test/src/main/resources/db.properties @@ -0,0 +1,4 @@ +druid.url=jdbc:mysql://127.0.0.1:3306/auge_log?useSSL=false +druid.username=root +druid.password=123456 +druid.driverClassName=com.mysql.jdbc.Driver \ No newline at end of file diff --git a/jun_test/src/main/resources/log4j2.xml b/jun_test/src/main/resources/log4j2.xml new file mode 100644 index 0000000000..08eb5b7c9c --- /dev/null +++ b/jun_test/src/main/resources/log4j2.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/jun_test/src/main/resources/log4j2jdbc.xml b/jun_test/src/main/resources/log4j2jdbc.xml new file mode 100644 index 0000000000..a58c071cf1 --- /dev/null +++ b/jun_test/src/main/resources/log4j2jdbc.xml @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jun_test/src/main/resources/springmvc.xml b/jun_test/src/main/resources/springmvc.xml new file mode 100644 index 0000000000..21ee7a0c0e --- /dev/null +++ b/jun_test/src/main/resources/springmvc.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jun_test/src/main/test/com/xia/Test.java b/jun_test/src/main/test/com/xia/Test.java new file mode 100644 index 0000000000..85b759a3e0 --- /dev/null +++ b/jun_test/src/main/test/com/xia/Test.java @@ -0,0 +1,16 @@ +package com.xia; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class Test { + private static final Logger log = LoggerFactory.getLogger(Test.class); + + @org.junit.Test + public void test01(){ + log.debug("This is debug"); + log.info("This is info"); + log.warn("This is warn"); + log.error("This is error"); + } +} diff --git a/jun_test/src/main/webapp/WEB-INF/web.xml b/jun_test/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..b7c7ed7dbb --- /dev/null +++ b/jun_test/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,16 @@ + + + Archetype Created Web Application + + index.html + index.htm + index.jsp + default.html + default.htm + default.jsp + + + + diff --git a/jun_test/src/main/webapp/index.jsp b/jun_test/src/main/webapp/index.jsp new file mode 100644 index 0000000000..61ee27ccec --- /dev/null +++ b/jun_test/src/main/webapp/index.jsp @@ -0,0 +1,6 @@ + + +

        Hello World!

        + + + diff --git a/jun_util/.factorypath b/jun_util/.factorypath new file mode 100644 index 0000000000..1a399c5d9e --- /dev/null +++ b/jun_util/.factorypath @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/jun_util/CHANGELOG.md b/jun_util/CHANGELOG.md new file mode 100644 index 0000000000..82d8111cc5 --- /dev/null +++ b/jun_util/CHANGELOG.md @@ -0,0 +1,55 @@ +# Changelog + +## 2.16.0 + +### 新特性 + +* 全面更新db模块中的ds部分,使用工厂类自动选定连接池实现 +* 扩充CollectionUtil,增加交集(intersection)、并集(union)、差集(disjunction)方法 +* ds部分增加Tomcat-jdbc-pool的实现 +* ds增加JndiDSFactory,支持JNDI数据源 +* Setting中删除大量重复的方法,统一getXXX +* 扩充HexUtil,增加isHexNumber方法 +* CollectionUtil增加forEach方法,用于支持Map等类型遍历 +* 将DateUtil包变更为date,同时拆分格式化模式为单独的类,优化性能。DateUtil中增加方法 +* SecureUtil中decodeBase64增加重载方法 +* CharsetUtil增加defaultCharset方法 +* 增加Base64类,支持url safe的encode和decode +* StrUtil.str方法增加支持Byte[]参数支持 +* ClassUtil中增加原始类和包装类的转换 +* clone包单独成包 +* 全面优化Convert,单独成包convert,使用Convert以及其实现类实现可扩展的类型转换 +* JSONObject实现Map接口,JSONArray实现List接口 +* 增加代理包(com.xiaoleilu.hutool.proxy),新增代理和切面功能 +* 包扫描独立出来为ClassScaner,ClassUtil中对应方法引用此类方法 +* ClassUil增加getConstructor方法,可匹配继承参数 +* 优化ClassPath路径转为绝对路径 +* Direction增加方法从字符串转换(大小写不敏感) +* 添加DigestUtil方法,用于md* sha1等摘要算法,同时简化SecureUtil,其中md* sha1方法调用DigestUtil +* 增加Editor接口,用于规范对象编辑器,主要用于集合元素的统一修改 +* 修改Filter接口,同时去除ClassUtil中的ClassFilter,使过滤器抽象度更高 +* HttpConnection支持Proxy +* StrUtil中某些方法使用CharSequence接口做为参数 +* Setting 拆分配置文件解析为SettingLoader +* ClassUtil增加getTypeArgument方法,用于获取泛型属性类型 +* 大量扩充Converter,支持转换为数组 +* 增加PathConverter,转换支持Path对象 +* Setting和Props支持文件变更自动加载 +* StrUtil增加startWithIgnoreCase和endWithIgnoreCase +* script包引擎封装,封装JavaScriptEngine +* 增加RuntimeInfo +* 增加DateUtil.formatDiff方法 + +### Bug修复 + +* 修复各个包中error日志使用问题导致的无法打印堆栈 +* 修复StrUtil.join时传入数组或集合类无法转为字符串问题 +* 修复FileUtil.writeString方法未检查文件的问题 +* 修复StrUtil.count修复空指针问题,给定null返回0 +* 修复BeanUtil中beanToMap方法,空值可选注入 +* 修复SqlBuilder中插入和更新对空值得判断 +* 修复Boolean转换的一个错误 +* 修复CharsetUtil中默认的destCharset错误赋值问题 +* 修复StrUtil.count方法错误计数问题 +* 修复DbSetting传值Setting不为空空指针问题 +* 修复HttpConnection中判断Http Method 错误 \ No newline at end of file diff --git a/jun_util/README.md b/jun_util/README.md new file mode 100644 index 0000000000..2187203943 --- /dev/null +++ b/jun_util/README.md @@ -0,0 +1,75 @@ +hutool +====== + +[![Version](https://img.shields.io/badge/version-2.16.0-brightgreen.svg)](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22com.xiaoleilu%22%20AND%20a%3A%22hutool%22) +[![License](http://img.shields.io/:license-apache-blue.svg)](http://www.apache.org/licenses/LICENSE-2.0.html) +![JDK 1.7](https://img.shields.io/badge/JDK-1.7-green.svg "JDK 1.7") + +
        ![封面](https://github.com/looly/hutool/blob/master/doc/hutool.jpg)
        + +## Hutool交流QQ群:== [537116831](http://shang.qq.com/wpa/qunwpa?idkey=382bb37ce779c11da77577f69d92d5171b340e3e7343d5ae0521f237c82c7810) == + +## 功能 +一个Java基础工具类,对文件、流、加密解密、转码、正则、线程、XML等JDK方法进行封装,组成各种Util工具类,同时提供以下组件: +* 布隆过滤 +* 缓存 +* 克隆接口 +* 类型转换 +* 日期处理 +* 数据库ORM(基于ActiveRecord思想) +* 基于DFA有限自动机的多个关键字查找 +* HTTP客户端 +* IO和文件 +* 有用的一些数据结构 +* 日志 +* 反射代理类的简化(AOP切面实现) +* Setting(一种扩展Properties的配置文件) +* System(JVM和系统信息等) +* WatchService的封装(文件变动监控) +* XXXUtil各种有用的工具类 + +## 简介 +[Hutool](https://github.com/looly/hutool)是一个工具包,我日常写项目的一些积累,希望你看了之后会有所启发或者能给你工作中带来帮助。这个工具包叫做Hutool也有“糊涂”之意,意为很多时候我们并不需要关注细节,专注业务。 + +## 设计哲学 +[Hutool](https://github.com/looly/hutool)的设计思想是尽量减少重复的定义,让项目中的`util`这个package尽量少,总的来说有如下的几个思想: + +1. 减少代码录入。 +2. 常用功能组合起来,实现一个功能只用一个方法。 +3. 简化Java API,原来需要几个类实现的功能我也只是用一个类甚至一个方法(想想为了个线程池我得new多少类……而且名字还不好记) +4. 对于null的处理我没有可以回避,而是采取“你给我null我也给你返回null”这种思想,尽量不在工具类里抛空指针异常(这思想稍猥琐啊……直接把包袱扔给调用者了,好吧,谁让你给我null了)。 +5. 一些固定使用的算法收集到一起,不用每次问度娘了(例如Base64算法、MD5、Sha-1,还有Hash算法) +6. 借鉴[Python](https://www.python.org/)的很多小技巧(例如列表切片,列表支持负数index),让Java更加好用。 +7. 非常好用的ORM框架,同样借鉴[Python](https://www.python.org/)的[Django](https://www.djangoproject.com/)框架,以键值对的实体代替对象实体,大大降低数据库访问的难度(再也不用像Hibernate一样配置半天ORM Mapping了)。 +8. 极大简化了文件、日期的操作,尤其是相对路径和绝对路径问题做了非常好的封装,降低学习成本。 + +## 安装 +### Maven +在项目的pom.xml的dependencies中加入以下内容: + +```xml + + com.xiaoleilu + hutool + X.X.X + +``` + +注:工具包的**版本**可以通过 [http://search.maven.org/](http://search.maven.org/) 搜索`hutool`找到项目。 + +### 非Maven项目 +可以从[http://search.maven.org/](http://search.maven.org/) 搜索`hutool`找到项目,点击对应版本,下面是相应的Jar包,导入即可使用。 + +[http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22com.xiaoleilu%22%20AND%20a%3A%22hutool%22](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22com.xiaoleilu%22%20AND%20a%3A%22hutool%22) + +点击链接后点选择对应版本,点击列表尾部的“Download”下载jar、API文档、源码 + +## 文档请移步 + +[Hutool Wiki @ osc](http://hutool.mydoc.io/) + +[Hutool Wiki @ github](https://github.com/looly/hutool/wiki) + +## 版本变更 + +[CHANGELOG.md](https://github.com/looly/hutool/blob/master/CHANGELOG.md) diff --git a/jun_util/pom.xml b/jun_util/pom.xml new file mode 100644 index 0000000000..1c2c600a23 --- /dev/null +++ b/jun_util/pom.xml @@ -0,0 +1,211 @@ + + 4.0.0 + + com.jun.plugin + jun_plugin + 1.0 + + jun_util + + + + + utf-8 + utf-8 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.7 + 1.7 + + + + + + + + + junit + junit + 4.12 + test + + + + org.apache.velocity + velocity + 1.7 + + compile + true + + + com.ibeetl + beetl + 2.7.3 + true + + + javax.servlet + javax.servlet-api + 3.1.0 + provided + true + + + + org.apache.tomcat + tomcat-jdbc + 8.5.8 + compile + true + + + com.alibaba + druid + 1.0.26 + compile + true + + + com.zaxxer + HikariCP-java7 + 2.4.9 + compile + true + + + com.mchange + c3p0 + 0.9.5.2 + compile + true + + + org.apache.commons + commons-dbcp2 + 2.1.1 + compile + true + + + + org.mongodb + mongo-java-driver + 3.3.0 + compile + true + + + + it.sauronsoftware.cron4j + cron4j + 2.2.5 + compile + true + + + + + ch.qos.logback + logback-classic + 1.1.7 + test + + + + log4j + log4j + 1.2.17 + compile + true + + + + org.apache.logging.log4j + log4j-core + 2.6.2 + compile + true + + + + commons-logging + commons-logging + 1.2 + compile + true + + + + + + release + + + oss + https://oss.sonatype.org/content/repositories/snapshots/ + + + oss + https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + + + + + + org.apache.maven.plugins + maven-source-plugin + 3.0.1 + + + package + + jar-no-fork + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + + + package + + jar + + + + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.6 + + + sign-artifacts + verify + + sign + + + + + + + + + + + \ No newline at end of file diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/BitMapBloomFilter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/BitMapBloomFilter.java new file mode 100644 index 0000000000..9d293bba6e --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/BitMapBloomFilter.java @@ -0,0 +1,76 @@ +package com.xiaoleilu.hutool.bloomFilter; + +import com.xiaoleilu.hutool.bloomFilter.filter.DefaultFilter; +import com.xiaoleilu.hutool.bloomFilter.filter.ELFFilter; +import com.xiaoleilu.hutool.bloomFilter.filter.JSFilter; +import com.xiaoleilu.hutool.bloomFilter.filter.PJWFilter; +import com.xiaoleilu.hutool.bloomFilter.filter.SDBMFilter; + +/** + * BlommFilter 实现
        + * 1.构建hash算法
        + * 2.散列hash映射到数组的bit位置
        + * 3.验证
        + * 此实现方式可以指定Hash算法 + * + * @author Ansj + */ +public class BitMapBloomFilter implements BloomFilter{ + + private BloomFilter[] filters; + + /** + * 使用默认的5个过滤器 + * @param m M值决定BitMap的大小 + */ + public BitMapBloomFilter(int m) { + float mNum = m / 5; + long size = (long) (1L * mNum * 1024 * 1024 * 8); + + filters = new BloomFilter[]{ + new DefaultFilter(size), + new ELFFilter(size), + new JSFilter(size), + new PJWFilter(size), + new SDBMFilter(size) + }; + } + + /** + * 使用自定的多个过滤器建立BloomFilter + * + * @param m M值决定BitMap的大小 + * @param filters Bloom过滤器列表 + */ + public BitMapBloomFilter(int m, BloomFilter... filters) { + this.filters = filters; + } + + /** + * 增加字符串到Filter映射中 + * @param str 字符串 + */ + @Override + public boolean add(String str) { + boolean flag = true; + for (BloomFilter filter : filters) { + flag |= filter.add(str); + } + return flag; + } + + /** + * 是否可能包含此字符串,此处存在误判 + * @param str 字符串 + * @return 是否存在 + */ + @Override + public boolean contains(String str) { + for (BloomFilter filter : filters) { + if (filter.contains(str) == false) { + return false; + } + } + return true; + } +} \ No newline at end of file diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/BitSetBloomFilter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/BitSetBloomFilter.java new file mode 100644 index 0000000000..682cf8062f --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/BitSetBloomFilter.java @@ -0,0 +1,140 @@ +package com.xiaoleilu.hutool.bloomFilter; + +import java.io.BufferedReader; +import java.io.IOException; +import java.util.BitSet; + +import com.xiaoleilu.hutool.io.FileUtil; +import com.xiaoleilu.hutool.io.IoUtil; +import com.xiaoleilu.hutool.util.HashUtil; + +/** + * BloomFilter实现方式2,此方式使用BitSet存储。
        + * Hash算法的使用使用固定顺序,只需指定个数既可 + * @author loolly + * + */ +public class BitSetBloomFilter implements BloomFilter{ + private BitSet bitSet; + private int bitSetSize; + private int addedElements; + private int hashFunctionNumber; + + /** + * 构造一个布隆过滤器,过滤器的容量为c * n 个bit. + * + * @param c 当前过滤器预先开辟的最大包含记录,通常要比预计存入的记录多一倍. + * @param n 当前过滤器预计所要包含的记录. + * @param k 哈希函数的个数,等同每条记录要占用的bit数. + */ + public BitSetBloomFilter(int c, int n, int k) { + this.hashFunctionNumber = k; + this.bitSetSize = (int) Math.ceil(c * k); + this.addedElements = n; + this.bitSet = new BitSet(this.bitSetSize); + } + + /** + * 通过文件初始化过滤器. + * + * @param path 文件路径 + * @param charset 字符集 + * @throws IOException + */ + public void init(String path, String charset) throws IOException { + BufferedReader reader = FileUtil.getReader(path, charset); + try { + String line; + while(true) { + line = reader.readLine(); + if(line == null) break; + this.add(line); + } + }finally { + IoUtil.close(reader); + } + } + + @Override + public boolean add(String str) { + if (contains(str)) { + return false; + } + + int[] positions = createHashes(str, hashFunctionNumber); + for (int i = 0; i < positions.length; i++) { + int position = Math.abs(positions[i] % bitSetSize); + bitSet.set(position, true); + } + return true; + } + + /** + * 判定是否包含指定字符串 + * @param str 字符串 + * @return 是否包含,存在误差 + */ + @Override + public boolean contains(String str) { + int[] positions = createHashes(str, hashFunctionNumber); + for (int i : positions) { + int position = Math.abs(i % bitSetSize); + if (!bitSet.get(position)) { + return false; + } + } + return true; + } + + /** + * @return 得到当前过滤器的错误率. + */ + public double getFalsePositiveProbability() { + // (1 - e^(-k * n / m)) ^ k + return Math.pow((1 - Math.exp(-hashFunctionNumber * (double) addedElements / bitSetSize)), hashFunctionNumber); + } + + /** + * 将字符串的字节表示进行多哈希编码. + * + * @param str 待添加进过滤器的字符串字节表示. + * @param hashNumber 要经过的哈希个数. + * @return 各个哈希的结果数组. + */ + public static int[] createHashes(String str, int hashNumber) { + int[] result = new int[hashNumber]; + for(int i = 0; i < hashNumber; i++) { + result[i] = hash(str, i); + + } + return result; + } + + /** + * 计算Hash值 + * @param str 被计算Hash的字符串 + * @param k Hash算法序号 + * @return Hash值 + */ + public static int hash(String str, int k) { + switch (k) { + case 0: + return HashUtil.rsHash(str); + case 1: + return HashUtil.jsHash(str); + case 2: + return HashUtil.elfHash(str); + case 3: + return HashUtil.bkdrHash(str); + case 4: + return HashUtil.apHash(str); + case 5: + return HashUtil.djbHash(str); + case 6: + return HashUtil.sdbmHash(str); + case 7: + return HashUtil.pjwHash(str); + } + return 0; + } +} \ No newline at end of file diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/BloomFilter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/BloomFilter.java new file mode 100644 index 0000000000..a06672f7a9 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/BloomFilter.java @@ -0,0 +1,26 @@ +package com.xiaoleilu.hutool.bloomFilter; + +/** + * Bloom filter 是由 Howard Bloom 在 1970 年提出的二进制向量数据结构,它具有很好的空间和时间效率,被用来检测一个元素是不是集合中的一个成员。
        + * 如果检测结果为是,该元素不一定在集合中;但如果检测结果为否,该元素一定不在集合中。
        + * 因此Bloom filter具有100%的召回率。这样每个检测请求返回有“在集合内(可能错误)”和“不在集合内(绝对不在集合内)”两种情况。
        + * @author Looly + * + */ +public interface BloomFilter { + + /** + * + * @param str 字符串 + * @return 判断一个字符串是否bitMap中存在 + */ + public boolean contains(String str); + + /** + * 在boolean的bitMap中增加一个字符串
        + * 如果存在就返回false .如果不存在.先增加这个字符串.再返回true + * @param str 字符串 + * @return 是否加入成功,如果存在就返回false .如果不存在返回true + */ + public boolean add(String str); +} \ No newline at end of file diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/bitMap/BitMap.java b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/bitMap/BitMap.java new file mode 100644 index 0000000000..c26f4568df --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/bitMap/BitMap.java @@ -0,0 +1,13 @@ +package com.xiaoleilu.hutool.bloomFilter.bitMap; + +public interface BitMap { + + public final int MACHINE32 = 32; + public final int MACHINE64 = 64; + + public void add(long i); + + public boolean contains(long i); + + public void remove(long i); +} \ No newline at end of file diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/bitMap/IntMap.java b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/bitMap/IntMap.java new file mode 100644 index 0000000000..572ec3a205 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/bitMap/IntMap.java @@ -0,0 +1,43 @@ +package com.xiaoleilu.hutool.bloomFilter.bitMap; + +/** + * 过滤器BitMap在32位机器上.这个类能发生更好的效果.一般情况下建议使用此类 + * @author loolly + * + */ +public class IntMap implements BitMap { + + private static final int MAX = Integer.MAX_VALUE; + + public IntMap() { + ints = new int[93750000]; + } + + public IntMap(int size) { + ints = new int[size]; + } + + private int[] ints = null; + + public void add(long i) { + int r = (int) (i / BitMap.MACHINE32); + int c = (int) (i % BitMap.MACHINE32); + ints[r] = (int) (ints[r] | (1 << c)); + } + + public boolean contains(long i) { + int r = (int) (i / BitMap.MACHINE32); + int c = (int) (i % BitMap.MACHINE32); + if (((int) ((ints[r] >>> c)) & 1) == 1) { + return true; + } + return false; + } + + public void remove(long i) { + int r = (int) (i / BitMap.MACHINE32); + int c = (int) (i % BitMap.MACHINE32); + ints[r] = (int) (ints[r] & (((1 << (c + 1)) - 1) ^ MAX)); + } + +} \ No newline at end of file diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/bitMap/LongMap.java b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/bitMap/LongMap.java new file mode 100644 index 0000000000..743b7a52f4 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/bitMap/LongMap.java @@ -0,0 +1,43 @@ +package com.xiaoleilu.hutool.bloomFilter.bitMap; + +/** + * 过滤器BitMap在64位机器上.这个类能发生更好的效果.一般机器不建议使用 + * @author loolly + * + */ +public class LongMap implements BitMap { + + private static final long MAX = Long.MAX_VALUE; + + public LongMap() { + longs = new long[93750000]; + } + + public LongMap(int size) { + longs = new long[size]; + } + + private long[] longs = null; + + public void add(long i) { + int r = (int) (i / BitMap.MACHINE64); + int c = (int) (i % BitMap.MACHINE64); + longs[r] = (int) (longs[r] | (1 << c)); + } + + public boolean contains(long i) { + int r = (int) (i / BitMap.MACHINE64); + int c = (int) (i % BitMap.MACHINE64); + if (((int) ((longs[r] >>> c)) & 1) == 1) { + return true; + } + return false; + } + + public void remove(long i) { + int r = (int) (i / BitMap.MACHINE64); + int c = (int) (i % BitMap.MACHINE64); + longs[r] = (int) (longs[r] & (((1 << (c + 1)) - 1) ^ MAX)); + } + +} \ No newline at end of file diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/AbstractFilter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/AbstractFilter.java new file mode 100644 index 0000000000..8c352948d3 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/AbstractFilter.java @@ -0,0 +1,64 @@ +package com.xiaoleilu.hutool.bloomFilter.filter; + +import com.xiaoleilu.hutool.bloomFilter.BloomFilter; +import com.xiaoleilu.hutool.bloomFilter.bitMap.BitMap; +import com.xiaoleilu.hutool.bloomFilter.bitMap.IntMap; +import com.xiaoleilu.hutool.bloomFilter.bitMap.LongMap; + +/** + * 抽象Bloom过滤器 + * + * @author loolly + * + */ +public abstract class AbstractFilter implements BloomFilter { + + private BitMap bm = null; + + protected long size = 0; + + public AbstractFilter(long maxValue, int machineNum) { + init(maxValue, machineNum); + } + + public AbstractFilter(long maxValue) { + this(maxValue, BitMap.MACHINE32); + } + + public void init(long maxValue, int machineNum) { + this.size = maxValue; + switch (machineNum) { + case BitMap.MACHINE32: + bm = new IntMap((int) (size / machineNum)); + break; + case BitMap.MACHINE64: + bm = new LongMap((int) (size / machineNum)); + break; + default: + throw new RuntimeException("Error Machine number!"); + } + } + + @Override + public boolean contains(String str) { + return bm.contains(hash(str)); + } + + @Override + public boolean add(String str) { + final long hash = this.hash(str); + if (bm.contains(hash)) { + return false; + } + + bm.add(hash); + return true; + } + + /** + * 自定义Hash方法 + * @param str 字符串 + * @return HashCode + */ + public abstract long hash(String str) ; +} \ No newline at end of file diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/DefaultFilter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/DefaultFilter.java new file mode 100644 index 0000000000..ba446b2e0b --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/DefaultFilter.java @@ -0,0 +1,24 @@ +package com.xiaoleilu.hutool.bloomFilter.filter; + +import com.xiaoleilu.hutool.util.HashUtil; + +/** + * 默认Bloom过滤器,使用Java自带的Hash算法 + * @author loolly + * + */ +public class DefaultFilter extends AbstractFilter { + + public DefaultFilter(long maxValue, int MACHINENUM) { + super(maxValue, MACHINENUM); + } + + public DefaultFilter(long maxValue) { + super(maxValue); + } + + @Override + public long hash(String str) { + return HashUtil.javaDefaultHash(str) % size; + } +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/ELFFilter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/ELFFilter.java new file mode 100644 index 0000000000..26fc154d82 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/ELFFilter.java @@ -0,0 +1,20 @@ +package com.xiaoleilu.hutool.bloomFilter.filter; + +import com.xiaoleilu.hutool.util.HashUtil; + +public class ELFFilter extends AbstractFilter { + + public ELFFilter(long maxValue, int MACHINENUM) { + super(maxValue, MACHINENUM); + } + + public ELFFilter(long maxValue) { + super(maxValue); + } + + @Override + public long hash(String str) { + return HashUtil.elfHash(str) % size; + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/FNVFilter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/FNVFilter.java new file mode 100644 index 0000000000..0b9080c681 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/FNVFilter.java @@ -0,0 +1,20 @@ +package com.xiaoleilu.hutool.bloomFilter.filter; + +import com.xiaoleilu.hutool.util.HashUtil; + +public class FNVFilter extends AbstractFilter { + + public FNVFilter(long maxValue, int machineNum) { + super(maxValue, machineNum); + } + + public FNVFilter(long maxValue) { + super(maxValue); + } + + @Override + public long hash(String str) { + return HashUtil.fnvHash(str); + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/HfFilter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/HfFilter.java new file mode 100644 index 0000000000..e707901469 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/HfFilter.java @@ -0,0 +1,28 @@ +package com.xiaoleilu.hutool.bloomFilter.filter; + + +public class HfFilter extends AbstractFilter { + + public HfFilter(long maxValue, int machineNum) { + super(maxValue, machineNum); + } + + public HfFilter(long maxValue) { + super(maxValue); + } + + @Override + public long hash(String str) { + int length = str.length() ; + long hash = 0; + + for (int i = 0; i < length; i++) + hash += str.charAt(i) * 3 * i; + + if (hash < 0) + hash = -hash; + + return hash % size; + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/HfIpFilter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/HfIpFilter.java new file mode 100644 index 0000000000..a475b96bc7 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/HfIpFilter.java @@ -0,0 +1,23 @@ +package com.xiaoleilu.hutool.bloomFilter.filter; + +public class HfIpFilter extends AbstractFilter { + + public HfIpFilter(long maxValue, int machineNum) { + super(maxValue, machineNum); + } + + public HfIpFilter(long maxValue) { + super(maxValue); + } + + @Override + public long hash(String str) { + int length = str.length(); + long hash = 0; + for (int i = 0; i < length; i++) { + hash += str.charAt(i % 4) ^ str.charAt(i); + } + return hash % size; + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/JSFilter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/JSFilter.java new file mode 100644 index 0000000000..e6d1c98c79 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/JSFilter.java @@ -0,0 +1,27 @@ +package com.xiaoleilu.hutool.bloomFilter.filter; + + +public class JSFilter extends AbstractFilter { + + public JSFilter(long maxValue, int machineNum) { + super(maxValue, machineNum); + } + + public JSFilter(long maxValue) { + super(maxValue); + } + + @Override + public long hash(String str) { + int hash = 1315423911; + + for (int i = 0; i < str.length(); i++) { + hash ^= ((hash << 5) + str.charAt(i) + (hash >> 2)); + } + + if(hash<0) hash*=-1 ; + + return hash % size; + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/PJWFilter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/PJWFilter.java new file mode 100644 index 0000000000..db0e837590 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/PJWFilter.java @@ -0,0 +1,20 @@ +package com.xiaoleilu.hutool.bloomFilter.filter; + +import com.xiaoleilu.hutool.util.HashUtil; + +public class PJWFilter extends AbstractFilter { + + public PJWFilter(long maxValue, int machineNum) { + super(maxValue, machineNum); + } + + public PJWFilter(long maxValue) { + super(maxValue); + } + + @Override + public long hash(String str) { + return HashUtil.pjwHash(str) % size; + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/RSFilter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/RSFilter.java new file mode 100644 index 0000000000..876440e017 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/RSFilter.java @@ -0,0 +1,20 @@ +package com.xiaoleilu.hutool.bloomFilter.filter; + +import com.xiaoleilu.hutool.util.HashUtil; + +public class RSFilter extends AbstractFilter { + + public RSFilter(long maxValue, int machineNum) { + super(maxValue, machineNum); + } + + public RSFilter(long maxValue) { + super(maxValue); + } + + @Override + public long hash(String str) { + return HashUtil.rsHash(str) % size; + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/SDBMFilter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/SDBMFilter.java new file mode 100644 index 0000000000..cc540da68b --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/SDBMFilter.java @@ -0,0 +1,20 @@ +package com.xiaoleilu.hutool.bloomFilter.filter; + +import com.xiaoleilu.hutool.util.HashUtil; + +public class SDBMFilter extends AbstractFilter { + + public SDBMFilter(long maxValue, int machineNum) { + super(maxValue, machineNum); + } + + public SDBMFilter(long maxValue) { + super(maxValue); + } + + @Override + public long hash(String str) { + return HashUtil.sdbmHash(str) % size; + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/TianlFilter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/TianlFilter.java new file mode 100644 index 0000000000..2270c31485 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/bloomFilter/filter/TianlFilter.java @@ -0,0 +1,21 @@ +package com.xiaoleilu.hutool.bloomFilter.filter; + +import com.xiaoleilu.hutool.util.HashUtil; + + +public class TianlFilter extends AbstractFilter { + + public TianlFilter(long maxValue, int machineNum) { + super(maxValue, machineNum); + } + + public TianlFilter(long maxValue) { + super(maxValue); + } + + @Override + public long hash(String str) { + return HashUtil.tianlHash(str) % size; + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/cache/AbstractCache.java b/jun_util/src/main/java/com/xiaoleilu/hutool/cache/AbstractCache.java new file mode 100644 index 0000000000..07f0ac26e8 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/cache/AbstractCache.java @@ -0,0 +1,198 @@ +package com.xiaoleilu.hutool.cache; + +import java.util.Iterator; +import java.util.Map; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +/** + * 超时和限制大小的缓存的默认实现
        + * 继承此抽象缓存需要:
        + *
          + *
        • 创建一个新的Map
        • + *
        • 实现 prune 策略
        • + *
        + * + * @author Looly,jodd + * + * @param 键类型 + * @param 值类型 + */ +public abstract class AbstractCache implements Cache, Iterable{ + + protected Map> cacheMap; + + private final ReentrantReadWriteLock cacheLock = new ReentrantReadWriteLock(); + private final Lock readLock = cacheLock.readLock(); + private final Lock writeLock = cacheLock.writeLock(); + + /** 返回缓存容量,0表示无大小限制 */ + protected int capacity; + /** 缓存失效时长, 0 表示没有设置 */ + protected long timeout; + + /** 每个对象是否有单独的失效时长,用于决定清理过期对象是否有必要。 */ + protected boolean existCustomTimeout; + + /** 命中数 */ + protected int hitCount; + /** 丢失数 */ + protected int missCount; + + // ---------------------------------------------------------------- put start + @Override + public void put(K key, V object) { + put(key, object, timeout); + } + + @Override + public void put(K key, V object, long timeout) { + writeLock.lock(); + + try { + CacheObj co = new CacheObj(key, object, timeout); + if (timeout != 0) { + existCustomTimeout = true; + } + if (isFull()) { + pruneCache(); + } + cacheMap.put(key, co); + } finally { + writeLock.unlock(); + } + } + // ---------------------------------------------------------------- put end + + // ---------------------------------------------------------------- get start + /** + * @return 命中数 + */ + public int getHitCount() { + return hitCount; + } + + /** + * @return 丢失数 + */ + public int getMissCount() { + return missCount; + } + + @Override + public V get(K key) { + readLock.lock(); + + try { + //不存在或已移除 + final CacheObj co = cacheMap.get(key); + if (co == null) { + missCount++; + return null; + } + + //过期 + if (co.isExpired() == true) { + // remove(key); // 此方法无法获得锁 + cacheMap.remove(key); + + missCount++; + return null; + } + + //命中 + hitCount++; + return co.get(); + } finally { + readLock.unlock(); + } + } + // ---------------------------------------------------------------- get end + + @Override + public Iterator iterator() { + return new CacheValuesIterator(this); + } + + // ---------------------------------------------------------------- prune start + /** + * 清理实现 + * @return 清理数 + */ + protected abstract int pruneCache(); + + @Override + public final int prune() { + writeLock.lock(); + try { + return pruneCache(); + } finally { + writeLock.unlock(); + } + } + // ---------------------------------------------------------------- prune end + + // ---------------------------------------------------------------- common start + @Override + public int capacity() { + return capacity; + } + + /** + * @return 默认缓存失效时长。
        + * 每个对象可以单独设置失效时长 + */ + @Override + public long timeout() { + return timeout; + } + + /** + * 只有设置公共缓存失效时长或每个对象单独的失效时长时清理可用 + * @return 过期对象清理是否可用,内部使用 + */ + protected boolean isPruneExpiredActive() { + return (timeout != 0) || existCustomTimeout; + } + + @Override + public boolean isFull() { + return (capacity > 0) && (cacheMap.size() >= capacity); + } + + @Override + public void remove(K key) { + writeLock.lock(); + try { + cacheMap.remove(key); + } finally { + writeLock.unlock(); + } + } + + @Override + public void clear() { + writeLock.lock(); + try { + cacheMap.clear(); + } finally { + writeLock.unlock(); + } + } + + @Override + public int size() { + return cacheMap.size(); + } + + @Override + public boolean isEmpty() { + return cacheMap.isEmpty(); + } + + @Override + public String toString() { + return this.cacheMap.toString(); + } + // ---------------------------------------------------------------- common end +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/cache/Cache.java b/jun_util/src/main/java/com/xiaoleilu/hutool/cache/Cache.java new file mode 100644 index 0000000000..5169babd5d --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/cache/Cache.java @@ -0,0 +1,85 @@ +package com.xiaoleilu.hutool.cache; + +import java.util.Iterator; + +/** + * 缓存接口 + * @author Looly,jodd + * + * @param 键类型 + * @param 值类型 + */ +public interface Cache{ + + /** + * @return 返回缓存容量,0表示无大小限制 + */ + int capacity(); + + /** + * @return 缓存失效时长, 0 表示没有设置 + */ + long timeout(); + + /** + * 将对象加入到缓存,使用默认失效时长 + * @param key 键 + * @param object 缓存的对象 + * @see Cache#put(Object, Object, long) + */ + void put(K key, V object); + + /** + * 将对象加入到缓存,使用指定失效时长
        + * 如果缓存空间满了,{@link #prune()} 将被调用以获得空间来存放新对象 + * @param key 键 + * @param object 缓存的对象 + * @param timeout 失效时长 + * @see Cache#put(Object, Object, long) + */ + void put(K key, V object, long timeout); + + /** + * 从缓存中获得对象,当对象不在缓存中或已经过期返回null + * @param key 键 + * @return 键对应的对象 + */ + V get(K key); + + /** + * @return 返回缓存迭代器 + */ + Iterator iterator(); + + /** + * 从缓存中清理过期对象,清理策略取决于具体实现 + * @return 清理的缓存对象个数 + */ + int prune(); + + /** + * @return 缓存是否已满,仅用于有空间限制的缓存对象 + */ + boolean isFull(); + + /** + * 从缓存中移除对象 + * @param key 键 + */ + void remove(K key); + + /** + * 清空缓存 + */ + void clear(); + + /** + * @return 缓存的对象数量 + */ + int size(); + + /** + * @return 缓存是否为空 + */ + boolean isEmpty(); +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/cache/CacheObj.java b/jun_util/src/main/java/com/xiaoleilu/hutool/cache/CacheObj.java new file mode 100644 index 0000000000..babdf9a3de --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/cache/CacheObj.java @@ -0,0 +1,49 @@ +package com.xiaoleilu.hutool.cache; + +/** + * 缓存对象 + * @author Looly + * + * @param + * @param + */ +public class CacheObj { + + final K key; + final V obj; + + /** 上次访问时间 */ + long lastAccess; + /** 访问次数 */ + long accessCount; + /** 对象存活时长,0表示永久存活*/ + long ttl; + + CacheObj(K key, V obj, long ttl) { + this.key = key; + this.obj = obj; + this.ttl = ttl; + this.lastAccess = System.currentTimeMillis(); + } + + /** + * @return 是否过期 + */ + boolean isExpired() { + return (ttl > 0) && (lastAccess + ttl < System.currentTimeMillis()); + } + + /** + * @return 获得对象 + */ + V get() { + lastAccess = System.currentTimeMillis(); + accessCount++; + return obj; + } + + @Override + public String toString() { + return "CacheObj [key=" + key + ", obj=" + obj + ", lastAccess=" + lastAccess + ", accessCount=" + accessCount + ", ttl=" + ttl + "]"; + } +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/cache/CacheValuesIterator.java b/jun_util/src/main/java/com/xiaoleilu/hutool/cache/CacheValuesIterator.java new file mode 100644 index 0000000000..60695fd863 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/cache/CacheValuesIterator.java @@ -0,0 +1,57 @@ +package com.xiaoleilu.hutool.cache; + +import java.util.Iterator; + +/** + * {@link com.xiaoleilu.hutool.cache.AbstractCache} 的值迭代器. + */ +public class CacheValuesIterator implements Iterator { + + private Iterator> iterator; + + private CacheObj nextValue; + + CacheValuesIterator(AbstractCache abstractCacheMap) { + iterator = abstractCacheMap.cacheMap.values().iterator(); + nextValue(); + } + + /** + * 下一个值,当不存在则下一个值为null + */ + private void nextValue() { + while (iterator.hasNext()) { + nextValue = iterator.next(); + if (nextValue.isExpired() == false) { + return; + } + } + nextValue = null; + } + + /** + * @return 是否有下一个值 + */ + @Override + public boolean hasNext() { + return nextValue != null; + } + + /** + * @return 下一个值 + */ + @Override + public V next() { + final V cachedObject = nextValue.obj; + nextValue(); + return cachedObject; + } + + /** + * 从缓存中移除没有过期的当前值 + */ + @Override + public void remove() { + iterator.remove(); + } +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/cache/FIFOCache.java b/jun_util/src/main/java/com/xiaoleilu/hutool/cache/FIFOCache.java new file mode 100644 index 0000000000..aa3469cbf7 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/cache/FIFOCache.java @@ -0,0 +1,72 @@ +package com.xiaoleilu.hutool.cache; + +import java.util.LinkedHashMap; +import java.util.Iterator; + +/** + * FIFO(first in first out) 先进先出缓存. + * + *

        + * 元素不停的加入缓存直到缓存满为止,当缓存满时,清理过期缓存对象,清理后依旧满则删除先入的缓存(链表首部对象)
        + * 优点:简单快速
        + * 缺点:不灵活,不能保证最常用的对象总是被保留 + *

        + * + * @author Looly + * + * @param 键类型 + * @param 值类型 + */ +public class FIFOCache extends AbstractCache { + + /** + * 构造,默认对象不过期 + * + * @param capacity 容量 + */ + public FIFOCache(int capacity) { + this(capacity, 0); + } + + /** + * 构造 + * + * @param capacity 容量 + * @param timeout 过期时长 + */ + public FIFOCache(int capacity, long timeout) { + this.capacity = capacity; + this.timeout = timeout; + cacheMap = new LinkedHashMap>(capacity + 1, 1.0f, false); + } + + /** + * 先进先出的清理策略
        + * 先遍历缓存清理过期的缓存对象,如果清理后还是满的,则删除第一个缓存对象 + */ + @Override + protected int pruneCache() { + int count = 0; + CacheObj first = null; + + // 清理过期对象并找出链表头部元素(先入元素) + Iterator> values = cacheMap.values().iterator(); + while (values.hasNext()) { + CacheObj co = values.next(); + if (co.isExpired()) { + values.remove(); + count++; + } + if (first == null) { + first = co; + } + } + + // 清理结束后依旧是满的,则删除第一个被缓存的对象 + if (isFull() && null != first) { + cacheMap.remove(first.key); + count++; + } + return count; + } +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/cache/FileLFUCache.java b/jun_util/src/main/java/com/xiaoleilu/hutool/cache/FileLFUCache.java new file mode 100644 index 0000000000..1eaea6b7f5 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/cache/FileLFUCache.java @@ -0,0 +1,150 @@ +package com.xiaoleilu.hutool.cache; + +import java.io.File; +import java.io.IOException; + +import com.xiaoleilu.hutool.io.FileUtil; + +/** + * 使用LFU缓存文件,以解决频繁读取文件引起的性能问题 + * @author Looly,jodd + * + */ +public class FileLFUCache { + + /** LFU缓存 */ + protected final LFUCache cache; + /** 容量 */ + protected final int capacity; + /** 缓存的最大文件大小,文件大于此大小时将不被缓存 */ + protected final int maxFileSize; + + /** 已使用缓存空间 */ + protected int usedSize; + + /** + * 构造
        + * 最大文件大小为缓存容量的一半
        + * 默认无超时 + * @param capacity 缓存容量 + */ + public FileLFUCache(int capacity) { + this(capacity, capacity / 2, 0); + } + + /** + * 构造
        + * 默认无超时 + * @param capacity 缓存容量 + * @param maxFileSize 最大文件大小 + */ + public FileLFUCache(int capacity, int maxFileSize) { + this(capacity, maxFileSize, 0); + } + + /** + * 构造 + * @param capacity 缓存容量 + * @param maxFileSize 文件最大大小 + * @param timeout 默认超时时间,0表示无默认超时 + */ + public FileLFUCache(int capacity, int maxFileSize, long timeout) { + this.cache = new LFUCache(0, timeout) { + @Override + public boolean isFull() { + return usedSize > this.capacity; + } + @Override + protected void onRemove(File key, byte[] cachedObject) { + usedSize -= cachedObject.length; + } + }; + + this.capacity = capacity; + this.maxFileSize = maxFileSize; + } + + /** + * @return 缓存容量(byte数) + */ + public int capacity() { + return capacity; + } + + /** + * @return 已使用空间大小(byte数) + */ + public int getUsedSize() { + return usedSize; + } + + /** + * @return 允许被缓存文件的最大byte数 + */ + public int maxFileSize() { + return maxFileSize; + } + + /** + * @return 缓存的文件数 + */ + public int getCachedFilesCount() { + return cache.size(); + } + + /** + * @return 超时时间 + */ + public long timeout() { + return cache.timeout; + } + + /** + * 清空缓存 + */ + public void clear() { + cache.clear(); + usedSize = 0; + } + + // ---------------------------------------------------------------- get + + /** + * 获得缓存过的文件bytes + * @param path 文件路径 + * @return 缓存过的文件bytes + * @throws IOException + */ + public byte[] getFileBytes(String path) throws IOException { + return getFileBytes(new File(path)); + } + + /** + * 获得缓存过的文件bytes + * @param file 文件 + * @return 缓存过的文件bytes + * @throws IOException + */ + public byte[] getFileBytes(File file) throws IOException { + byte[] bytes = cache.get(file); + if (bytes != null) { + return bytes; + } + + // add file + bytes = FileUtil.readBytes(file); + + if ((maxFileSize != 0) && (file.length() > maxFileSize)) { + //大于缓存空间,不缓存,直接返回 + return bytes; + } + + usedSize += bytes.length; + + //文件放入缓存,如果usedSize > capacity,purge()方法将被调用 + cache.put(file, bytes); + + return bytes; + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/cache/LFUCache.java b/jun_util/src/main/java/com/xiaoleilu/hutool/cache/LFUCache.java new file mode 100644 index 0000000000..e4547e4b1b --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/cache/LFUCache.java @@ -0,0 +1,100 @@ +package com.xiaoleilu.hutool.cache; + +import java.util.HashMap; +import java.util.Iterator; + +/** + * LFU(least frequently used) 最少使用率缓存
        + * 根据使用次数来判定对象是否被持续缓存
        + * 使用率是通过访问次数计算的。
        + * 当缓存满时清理过期对象。
        + * 清理后依旧满的情况下清除最少访问(访问计数最小)的对象并将其他对象的访问数减去这个最小访问数,以便新对象进入后可以公平计数。 + * + * @author Looly,jodd + * + * @param 键类型 + * @param 值类型 + */ +public class LFUCache extends AbstractCache { + + /** + * 构造 + * + * @param capacity 容量 + */ + public LFUCache(int capacity) { + this(capacity, 0); + } + + /** + * 构造 + * + * @param capacity 容量 + * @param timeout 过期时长 + */ + public LFUCache(int capacity, long timeout) { + this.capacity = capacity; + this.timeout = timeout; + cacheMap = new HashMap>(capacity + 1); + } + + // ---------------------------------------------------------------- prune + + /** + * 清理过期对象。
        + * 清理后依旧满的情况下清除最少访问(访问计数最小)的对象并将其他对象的访问数减去这个最小访问数,以便新对象进入后可以公平计数。 + * + * @return 清理个数 + */ + @Override + protected int pruneCache() { + int count = 0; + CacheObj comin = null; + + // 清理过期对象并找出访问最少的对象 + Iterator> values = cacheMap.values().iterator(); + CacheObj co; + while (values.hasNext()) { + co = values.next(); + if (co.isExpired() == true) { + values.remove(); + onRemove(co.key, co.obj); + count++; + continue; + } + + //找出访问最少的对象 + if (comin == null || co.accessCount < comin.accessCount) { + comin = co; + } + } + + // 减少所有对象访问量,并清除减少后为0的访问对象 + if (isFull() && comin != null) { + long minAccessCount = comin.accessCount; + + values = cacheMap.values().iterator(); + CacheObj co1; + while (values.hasNext()) { + co1 = values.next(); + co1.accessCount -= minAccessCount; + if (co1.accessCount <= 0) { + values.remove(); + onRemove(co1.key, co1.obj); + count++; + } + } + } + + return count; + } + + /** + * 对象移除回调。默认无动作 + * @param key 键 + * @param cachedObject 被缓存的对象 + */ + protected void onRemove(K key, V cachedObject) { + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/cache/LRUCache.java b/jun_util/src/main/java/com/xiaoleilu/hutool/cache/LRUCache.java new file mode 100644 index 0000000000..1f1a5ee1c9 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/cache/LRUCache.java @@ -0,0 +1,76 @@ +package com.xiaoleilu.hutool.cache; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Iterator; + +/** + * LRU (least recently used)最近最久未使用缓存
        + * 根据使用时间来判定对象是否被持续缓存
        + * 当对象被访问时放入缓存,当缓存满了,最久未被使用的对象将被移除。
        + * 此缓存基于LinkedHashMap,因此当被缓存的对象每被访问一次,这个对象的key就到链表头部。
        + * 这个算法简单并且非常快,他比FIFO有一个显著优势是经常使用的对象不太可能被移除缓存。
        + * 缺点是当缓存满时,不能被很快的访问。 + * @author Looly,jodd + * + * @param 键类型 + * @param 值类型 + */ +public class LRUCache extends AbstractCache { + + /** + * 构造
        + * 默认无超时 + * @param capacity 容量 + */ + public LRUCache(int capacity) { + this(capacity, 0); + } + + /** + * 构造 + * @param capacity 容量 + * @param timeout 默认超时时间 + */ + public LRUCache(int capacity, long timeout) { + this.capacity = capacity; + this.timeout = timeout; + + //链表key按照访问顺序排序,调用get方法后,会将这次访问的元素移至头部 + cacheMap = new LinkedHashMap>(capacity + 1, 1.0f, true){ + private static final long serialVersionUID = -1806954614512571136L; + + @Override + protected boolean removeEldestEntry(Map.Entry> eldest) { + if(LRUCache.this.capacity == 0) { + return false; + } + //当链表元素大于容量时,移除最老(最久未被使用)的元素 + return size() > LRUCache.this.capacity; + } + }; + } + + // ---------------------------------------------------------------- prune + + /** + * 只清理超时对象,LRU的实现会交给LinkedHashMap + */ + @Override + protected int pruneCache() { + if (isPruneExpiredActive() == false) { + return 0; + } + int count = 0; + Iterator> values = cacheMap.values().iterator(); + CacheObj co; + while (values.hasNext()) { + co = values.next(); + if (co.isExpired()) { + values.remove(); + count++; + } + } + return count; + } +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/cache/NoCache.java b/jun_util/src/main/java/com/xiaoleilu/hutool/cache/NoCache.java new file mode 100644 index 0000000000..83b1776ee7 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/cache/NoCache.java @@ -0,0 +1,74 @@ +package com.xiaoleilu.hutool.cache; + +import java.util.Iterator; + +/** + * 无缓存实现,用于快速关闭缓存 + * @author Looly,jodd + * + * @param 键类型 + * @param 值类型 + */ +public class NoCache implements Cache { + + @Override + public int capacity() { + return 0; + } + + @Override + public long timeout() { + return 0; + } + + @Override + public void put(K key, V object) { + // 跳过 + } + + @Override + public void put(K key, V object, long timeout) { + // 跳过 + } + + @Override + public V get(K key) { + return null; + } + + @Override + public Iterator iterator() { + return null; + } + + @Override + public int prune() { + return 0; + } + + @Override + public boolean isFull() { + return false; + } + + @Override + public void remove(K key) { + // 跳过 + } + + @Override + public void clear() { + // 跳过 + } + + @Override + public int size() { + return 0; + } + + @Override + public boolean isEmpty() { + return false; + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/cache/TimedCache.java b/jun_util/src/main/java/com/xiaoleilu/hutool/cache/TimedCache.java new file mode 100644 index 0000000000..874ef55dcb --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/cache/TimedCache.java @@ -0,0 +1,81 @@ +package com.xiaoleilu.hutool.cache; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Timer; +import java.util.TimerTask; + +/** + * 定时缓存
        + * 此缓存没有容量限制,对象只有在过期后才会被移除 + * + * @author Looly + * + * @param 键类型 + * @param 值类型 + */ +public class TimedCache extends AbstractCache { + + /** 定时器 */ + protected Timer pruneTimer; + + /** + * 构造 + * + * @param timeout 过期时长 + */ + public TimedCache(long timeout) { + this.capacity = 0; + this.timeout = timeout; + cacheMap = new HashMap>(); + } + + // ---------------------------------------------------------------- prune + /** + * 清理过期对象 + * @return 清理数 + */ + @Override + protected int pruneCache() { + int count = 0; + Iterator> values = cacheMap.values().iterator(); + CacheObj co; + while (values.hasNext()) { + co = values.next(); + if (co.isExpired()) { + values.remove(); + count++; + } + } + return count; + } + + // ---------------------------------------------------------------- auto prune + /** + * 定时清理 + * @param delay 间隔时长 + */ + public void schedulePrune(long delay) { + if (pruneTimer != null) { + pruneTimer.cancel(); + } + pruneTimer = new Timer(); + pruneTimer.schedule(new TimerTask(){ + @Override + public void run() { + prune(); + } + }, delay, delay); + } + + /** + * 取消定时清理 + */ + public void cancelPruneSchedule() { + if (pruneTimer != null) { + pruneTimer.cancel(); + pruneTimer = null; + } + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/clone/CloneSupport.java b/jun_util/src/main/java/com/xiaoleilu/hutool/clone/CloneSupport.java new file mode 100644 index 0000000000..b1cc3f2779 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/clone/CloneSupport.java @@ -0,0 +1,21 @@ +package com.xiaoleilu.hutool.clone; + +/** + * 克隆支持类,提供默认的克隆方法 + * @author Looly + * + * @param + */ +public class CloneSupport implements Cloneable{ + + @SuppressWarnings("unchecked") + @Override + public T clone() { + try { + return (T) super.clone(); + } catch (CloneNotSupportedException e) { + throw new RuntimeException(e); + } + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/clone/Cloneable.java b/jun_util/src/main/java/com/xiaoleilu/hutool/clone/Cloneable.java new file mode 100644 index 0000000000..0a413f81b2 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/clone/Cloneable.java @@ -0,0 +1,11 @@ +package com.xiaoleilu.hutool.clone; + +/** + * 克隆支持接口 + * @author Looly + * + * @param + */ +public interface Cloneable extends java.lang.Cloneable{ + T clone(); +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/convert/AbstractConverter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/AbstractConverter.java new file mode 100644 index 0000000000..970797e572 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/AbstractConverter.java @@ -0,0 +1,78 @@ +package com.xiaoleilu.hutool.convert; + +import java.text.MessageFormat; + +import com.xiaoleilu.hutool.util.ClassUtil; +import com.xiaoleilu.hutool.util.CollectionUtil; + +/** + * 抽象转换器,提供通用的转换逻辑,同时通过 + * @author Looly + * + */ +public abstract class AbstractConverter implements Converter{ + + @Override + @SuppressWarnings("unchecked") + public T convert(Object value, T defaultValue) { + Class targetType = getTargetType(); + if(null == targetType && null == defaultValue){ + throw new NullPointerException("[type] and [defaultValue] are both null for Converter ["+this.getClass()+"], we can not know what type to convert !"); + } + if(null == targetType){ + targetType = (Class) defaultValue.getClass(); + } + + if(targetType.isPrimitive()){ + //原始类型直接调用内部转换,内部转换永远不会返回null + return convertInternal(value); + } + + if(null == value){ + return defaultValue; + } + if(null == defaultValue || targetType.isInstance(defaultValue)){ + if(targetType.isInstance(value)){ + //已经是目标类型,不需要转换 + return (T) targetType.cast(value); + } + final T convertInternal = convertInternal(value); + return ((null == convertInternal) ? defaultValue : convertInternal); + }else{ + throw new IllegalArgumentException(MessageFormat.format("Default value [{0}] is not the instance of [{1}]]", defaultValue, targetType)); + } + } + + /** + * 内部转换器,被 {@link AbstractConverter#convert(Object, Object)} 调用,实现基本转换逻辑 + * @param value 值 + * @return 转换后的类型 + */ + protected abstract T convertInternal(Object value); + + /** + * 值转为String + * @param value 值 + * @return String + */ + protected String convertToStr(Object value) { + if (null == value) { + return null; + } + if (value instanceof String) { + return (String) value; + }else if (CollectionUtil.isArray(value)) { + return CollectionUtil.toString(value); + } + return value.toString(); + } + + /** + * 获得此类实现类的泛型类型 + * @return 此类的泛型类型 + */ + @SuppressWarnings("unchecked") + public Class getTargetType() { + return (Class) ClassUtil.getTypeArgument(getClass()); + } +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/convert/BasicType.java b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/BasicType.java new file mode 100644 index 0000000000..9c0dc6d0b8 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/BasicType.java @@ -0,0 +1,59 @@ +package com.xiaoleilu.hutool.convert; + +import java.util.HashMap; +import java.util.Map; + +/** + * 基本变量类型的枚举
        + * 基本类型枚举包括原始类型和包装类型 + * @author xiaoleilu + */ +public enum BasicType { + BYTE, SHORT, INT, INTEGER, LONG, DOUBLE, FLOAT, BOOLEAN, CHAR, CHARACTER, STRING; + + /** 原始类型为Key,包装类型为Value,例如: int.class -> Integer.class. */ + public static final Map, Class> wrapperPrimitiveMap = new HashMap, Class>(8); + /** 包装类型为Key,原始类型为Value,例如: Integer.class -> int.class. */ + public static final Map, Class> primitiveWrapperMap = new HashMap, Class>(8); + + static { + wrapperPrimitiveMap.put(Boolean.class, boolean.class); + wrapperPrimitiveMap.put(Byte.class, byte.class); + wrapperPrimitiveMap.put(Character.class, char.class); + wrapperPrimitiveMap.put(Double.class, double.class); + wrapperPrimitiveMap.put(Float.class, float.class); + wrapperPrimitiveMap.put(Integer.class, int.class); + wrapperPrimitiveMap.put(Long.class, long.class); + wrapperPrimitiveMap.put(Short.class, short.class); + + for (Map.Entry, Class> entry : wrapperPrimitiveMap.entrySet()) { + primitiveWrapperMap.put(entry.getValue(), entry.getKey()); + } + } + + /** + * 原始类转为包装类,非原始类返回原类 + * @param clazz 原始类 + * @return 包装类 + */ + public static Class wrap(Class clazz){ + if(null == clazz || false == clazz.isPrimitive()){ + return clazz; + } + Class result = primitiveWrapperMap.get(clazz); + return (null == result) ? clazz : result; + } + + /** + * 包装类转为原始类,非包装类返回原类 + * @param clazz 包装类 + * @return 原始类 + */ + public static Class unWrap(Class clazz){ + if(null == clazz || clazz.isPrimitive()){ + return clazz; + } + Class result = wrapperPrimitiveMap.get(clazz); + return (null == result) ? clazz : result; + } +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/convert/Convert.java b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/Convert.java new file mode 100644 index 0000000000..8b0a60b3ca --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/Convert.java @@ -0,0 +1,749 @@ +package com.xiaoleilu.hutool.convert; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.Charset; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +import com.xiaoleilu.hutool.lang.Assert; +import com.xiaoleilu.hutool.util.CharsetUtil; +import com.xiaoleilu.hutool.util.CollectionUtil; +import com.xiaoleilu.hutool.util.HexUtil; +import com.xiaoleilu.hutool.util.StrUtil; + +/** + * 类型转换器 + * + * @author xiaoleilu + * + */ +public class Convert { + + private Convert() { + // 静态类不可实例化 + } + + /** + * 转换为字符串
        + * 如果给定的值为null,或者转换失败,返回默认值
        + * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static String toStr(Object value, String defaultValue) { + return convert(String.class, value, defaultValue); + } + + /** + * 转换为字符串
        + * 如果给定的值为null,或者转换失败,返回默认值null
        + * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static String toStr(Object value) { + return toStr(value, null); + } + + /** + * 转换为字符
        + * 如果给定的值为null,或者转换失败,返回默认值
        + * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Character toChar(Object value, Character defaultValue) { + return convert(Character.class, value, defaultValue); + } + + /** + * 转换为字符
        + * 如果给定的值为null,或者转换失败,返回默认值null
        + * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Character toChar(Object value) { + return toChar(value, null); + } + + /** + * 转换为byte
        + * 如果给定的值为null,或者转换失败,返回默认值
        + * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Byte toByte(Object value, Byte defaultValue) { + return convert(Byte.class, value, defaultValue); + } + + /** + * 转换为byte
        + * 如果给定的值为null,或者转换失败,返回默认值null
        + * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Byte toByte(Object value) { + return toByte(value, null); + } + + /** + * 转换为Short
        + * 如果给定的值为null,或者转换失败,返回默认值
        + * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Short toShort(Object value, Short defaultValue) { + return convert(Short.class, value, defaultValue); + } + + /** + * 转换为Short
        + * 如果给定的值为null,或者转换失败,返回默认值null
        + * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Short toShort(Object value) { + return toShort(value, null); + } + + /** + * 转换为Number
        + * 如果给定的值为空,或者转换失败,返回默认值
        + * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Number toNumber(Object value, Number defaultValue) { + return convert(Number.class, value, defaultValue); + } + + /** + * 转换为Number
        + * 如果给定的值为空,或者转换失败,返回默认值null
        + * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Number toNumber(Object value) { + return toNumber(value, null); + } + + /** + * 转换为int
        + * 如果给定的值为空,或者转换失败,返回默认值
        + * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Integer toInt(Object value, Integer defaultValue) { + return convert(Integer.class, value, defaultValue); + } + + /** + * 转换为int
        + * 如果给定的值为null,或者转换失败,返回默认值null
        + * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Integer toInt(Object value) { + return toInt(value, null); + } + + /** + * 转换为Integer数组
        + * + * @param isIgnoreConvertError 是否忽略转换错误,忽略则给值null + * @param values 被转换的值 + * @return 结果 + */ + public static Integer[] toIntArray(boolean isIgnoreConvertError, Object... values) { + if (CollectionUtil.isEmpty(values)) { + return new Integer[] {}; + } + final Integer[] ints = new Integer[values.length]; + for (int i = 0; i < values.length; i++) { + final Integer v = toInt(values[i], null); + if (null == v && isIgnoreConvertError == false) { + throw new ConvertException(StrUtil.format("Convert [{}] to Integer error!", values[i])); + } + ints[i] = v; + } + return ints; + } + + /** + * 转换为long
        + * 如果给定的值为空,或者转换失败,返回默认值
        + * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Long toLong(Object value, Long defaultValue) { + return convert(Long.class, value, defaultValue); + } + + /** + * 转换为long
        + * 如果给定的值为null,或者转换失败,返回默认值null
        + * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Long toLong(Object value) { + return toLong(value, null); + } + + /** + * 转换为Long数组
        + * + * @param isIgnoreConvertError 是否忽略转换错误,忽略则给值null + * @param values 被转换的值 + * @return 结果 + */ + public static Long[] toLongArray(boolean isIgnoreConvertError, Object... values) { + if (CollectionUtil.isEmpty(values)) { + return new Long[] {}; + } + final Long[] longs = new Long[values.length]; + for (int i = 0; i < values.length; i++) { + final Long v = toLong(values[i], null); + if (null == v && isIgnoreConvertError == false) { + throw new ConvertException(StrUtil.format("Convert [{}] to Long error!", values[i])); + } + longs[i] = v; + } + return longs; + } + + /** + * 转换为double
        + * 如果给定的值为空,或者转换失败,返回默认值
        + * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Double toDouble(Object value, Double defaultValue) { + return convert(Double.class, value, defaultValue); + } + + /** + * 转换为double
        + * 如果给定的值为空,或者转换失败,返回默认值null
        + * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Double toDouble(Object value) { + return toDouble(value, null); + } + + /** + * 转换为Double数组
        + * + * @param isIgnoreConvertError 是否忽略转换错误,忽略则给值null + * @param values 被转换的值 + * @return 结果 + */ + public static Double[] toDoubleArray(boolean isIgnoreConvertError, Object... values) { + if (CollectionUtil.isEmpty(values)) { + return new Double[] {}; + } + final Double[] doubles = new Double[values.length]; + for (int i = 0; i < values.length; i++) { + final Double v = toDouble(values[i], null); + if (null == v && isIgnoreConvertError == false) { + throw new ConvertException(StrUtil.format("Convert [{}] to Double error!", values[i])); + } + doubles[i] = v; + } + return doubles; + } + + /** + * 转换为Float
        + * 如果给定的值为空,或者转换失败,返回默认值
        + * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Float toFloat(Object value, Float defaultValue) { + return convert(Float.class, value, defaultValue); + } + + /** + * 转换为Float
        + * 如果给定的值为空,或者转换失败,返回默认值null
        + * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Float toFloat(Object value) { + return toFloat(value, null); + } + + /** + * 转换为Float数组
        + * + * @param isIgnoreConvertError 是否忽略转换错误,忽略则给值null + * @param values 被转换的值 + * @return 结果 + */ + public static Float[] toFloatArray(boolean isIgnoreConvertError, Object... values) { + if (CollectionUtil.isEmpty(values)) { + return new Float[] {}; + } + final Float[] floats = new Float[values.length]; + for (int i = 0; i < values.length; i++) { + final Float v = toFloat(values[i], null); + if (null == v && isIgnoreConvertError == false) { + throw new ConvertException(StrUtil.format("Convert [{}] to Float error!", values[i])); + } + floats[i] = v; + } + return floats; + } + + /** + * 转换为boolean
        + * String支持的值为:true、false、yes、ok、no,1,0 如果给定的值为空,或者转换失败,返回默认值
        + * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Boolean toBool(Object value, Boolean defaultValue) { + return convert(Boolean.class, value, defaultValue); + } + + /** + * 转换为boolean
        + * 如果给定的值为空,或者转换失败,返回默认值null
        + * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Boolean toBool(Object value) { + return toBool(value, null); + } + + /** + * 转换为Boolean数组
        + * + * @param isIgnoreConvertError 是否忽略转换错误,忽略则给值null + * @param values 被转换的值 + * @return 结果 + */ + public static Boolean[] toBooleanArray(boolean isIgnoreConvertError, Object... values) { + if (CollectionUtil.isEmpty(values)) { + return new Boolean[] {}; + } + final Boolean[] bools = new Boolean[values.length]; + for (int i = 0; i < values.length; i++) { + final Boolean v = toBool(values[i], null); + if (null == v && isIgnoreConvertError == false) { + throw new ConvertException(StrUtil.format("Convert [{}] to Boolean error!", values[i])); + } + bools[i] = v; + } + return bools; + } + + /** + * 转换为BigInteger
        + * 如果给定的值为空,或者转换失败,返回默认值
        + * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static BigInteger toBigInteger(Object value, BigInteger defaultValue) { + return convert(BigInteger.class, defaultValue, defaultValue); + } + + /** + * 转换为BigInteger
        + * 如果给定的值为空,或者转换失败,返回默认值null
        + * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static BigInteger toBigInteger(Object value) { + return toBigInteger(value, null); + } + + /** + * 转换为BigDecimal
        + * 如果给定的值为空,或者转换失败,返回默认值
        + * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static BigDecimal toBigDecimal(Object value, BigDecimal defaultValue) { + return convert(BigDecimal.class, defaultValue, defaultValue); + } + + /** + * 转换为BigDecimal
        + * 如果给定的值为空,或者转换失败,返回默认值
        + * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static BigDecimal toBigDecimal(Object value) { + return toBigDecimal(value, null); + } + + /** + * 转换为Enum对象
        + * 如果给定的值为空,或者转换失败,返回默认值
        + * + * @param clazz Enum的Class + * @param value 值 + * @param defaultValue 默认值 + * @return Enum + */ + public static > E toEnum(Class clazz, Object value, E defaultValue) { + if (value == null) { + return defaultValue; + } + if (clazz.isAssignableFrom(value.getClass())) { + @SuppressWarnings("unchecked") + E myE = (E) value; + return myE; + } + final String valueStr = toStr(value, null); + if (StrUtil.isBlank(valueStr)) { + return defaultValue; + } + try { + return Enum.valueOf(clazz, valueStr); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * 转换为Enum对象
        + * 如果给定的值为空,或者转换失败,返回默认值null
        + * + * @param clazz Enum的Class + * @param value 值 + * @return Enum + */ + public static > E toEnum(Class clazz, Object value) { + return toEnum(clazz, value, null); + } + + /** + * 转换值为指定类型 + * + * @param type 类型 + * @param value 值 + * @return 转换后的值 + */ + public static T convert(Class type, Object value) { + return convert(type, value, null); + } + + /** + * 转换值为指定类型 + * + * @param type 类型 + * @param value 值 + * @param defaultValue 默认值 + * @return 转换后的值 + */ + public static T convert(Class type, Object value, T defaultValue) { + return ConverterRegistry.getInstance().convert(type, value, defaultValue); + } + + // ----------------------------------------------------------------------- 全角半角转换 + /** + * 半角转全角 + * + * @param input String. + * @return 全角字符串. + */ + public static String toSBC(String input) { + return toSBC(input, null); + } + + /** + * 半角转全角 + * + * @param input String + * @param notConvertSet 不替换的字符集合 + * @return 全角字符串. + */ + public static String toSBC(String input, Set notConvertSet) { + char c[] = input.toCharArray(); + for (int i = 0; i < c.length; i++) { + if (null != notConvertSet && notConvertSet.contains(c[i])) { + // 跳过不替换的字符 + continue; + } + + if (c[i] == ' ') { + c[i] = '\u3000'; + } else if (c[i] < '\177') { + c[i] = (char) (c[i] + 65248); + + } + } + return new String(c); + } + + /** + * 全角转半角 + * + * @param input String. + * @return 半角字符串 + */ + public static String toDBC(String input) { + return toDBC(input, null); + } + + /** + * 替换全角为半角 + * + * @param text 文本 + * @param notConvertSet 不替换的字符集合 + * @return 替换后的字符 + */ + public static String toDBC(String text, Set notConvertSet) { + char c[] = text.toCharArray(); + for (int i = 0; i < c.length; i++) { + if (null != notConvertSet && notConvertSet.contains(c[i])) { + // 跳过不替换的字符 + continue; + } + + if (c[i] == '\u3000') { + c[i] = ' '; + } else if (c[i] > '\uFF00' && c[i] < '\uFF5F') { + c[i] = (char) (c[i] - 65248); + } + } + String returnString = new String(c); + + return returnString; + } + + // --------------------------------------------------------------------- hex + /** + * 字符串转换成十六进制字符串 + * + * @param str 待转换的ASCII字符串 + * @return 16进制字符串 + */ + public static String toHex(String str) { + return HexUtil.encodeHexStr(str.getBytes()); + } + + /** + * byte数组转16进制串 + * + * @param bytes 被转换的byte数组 + * @return 转换后的值 + */ + public static String toHex(byte[] bytes) { + return HexUtil.encodeHexStr(bytes); + } + + /** + * Hex字符串转换为Byte值 + * + * @param src Byte字符串,每个Byte之间没有分隔符 + * @return byte[] + */ + public static byte[] hexToBytes(String src) { + return HexUtil.decodeHex(src.toCharArray()); + } + + /** + * 十六进制转换字符串 + * + * @param hexStr Byte字符串(Byte之间无分隔符 如:[616C6B]) + * @param charset 编码 {@link Charset} + * @return 对应的字符串 + */ + public static String hexStrToStr(String hexStr, Charset charset) { + return HexUtil.decodeHexStr(hexStr, charset); + } + + /** + * String的字符串转换成unicode的String + * + * @param strText 全角字符串 + * @return String 每个unicode之间无分隔符 + * @throws Exception + */ + public static String strToUnicode(String strText) throws Exception { + char c; + StringBuilder str = new StringBuilder(); + int intAsc; + String strHex; + for (int i = 0; i < strText.length(); i++) { + c = strText.charAt(i); + intAsc = (int) c; + strHex = Integer.toHexString(intAsc); + if (intAsc > 128) + str.append("\\u" + strHex); + else // 低位在前面补00 + str.append("\\u00" + strHex); + } + return str.toString(); + } + + /** + * unicode的String转换成String的字符串 + * + * @param hex 16进制值字符串 (一个unicode为2byte) + * @return String 全角字符串 + */ + public static String unicodeToStr(String hex) { + int t = hex.length() / 6; + StringBuilder str = new StringBuilder(); + for (int i = 0; i < t; i++) { + String s = hex.substring(i * 6, (i + 1) * 6); + // 高位需要补上00再转 + String s1 = s.substring(2, 4) + "00"; + // 低位直接转 + String s2 = s.substring(4); + // 将16进制的string转为int + int n = Integer.valueOf(s1, 16) + Integer.valueOf(s2, 16); + // 将int转换为字符 + char[] chars = Character.toChars(n); + str.append(new String(chars)); + } + return str.toString(); + } + + /** + * 给定字符串转换字符编码
        + * 如果参数为空,则返回原字符串,不报错。 + * + * @param str 被转码的字符串 + * @param sourceCharset 原字符集 + * @param destCharset 目标字符集 + * @return 转换后的字符串 + */ + public static String convertCharset(String str, String sourceCharset, String destCharset) { + if (StrUtil.hasBlank(str, sourceCharset, destCharset)) { + return str; + } + + return CharsetUtil.convert(str, sourceCharset, destCharset); + } + + /** + * 转换时间单位 + * @param sourceDuration 时长 + * @param sourceUnit 源单位 + * @param destUnit 目标单位 + * @return 目标单位的时长 + */ + public long convertTime(long sourceDuration, TimeUnit sourceUnit, TimeUnit destUnit){ + Assert.isNull(sourceUnit, "sourceUnit is null !"); + Assert.isNull(destUnit, "destUnit is null !"); + return destUnit.convert(sourceDuration, sourceUnit); + } + + /** + * 数字金额大写转换 先写个完整的然后将如零拾替换成零 + * + * @param n 数字 + * @return 中文大写数字 + */ + public static String digitUppercase(double n) { + String fraction[] = { "角", "分" }; + String digit[] = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" }; + String unit[][] = { { "元", "万", "亿" }, { "", "拾", "佰", "仟" } }; + + String head = n < 0 ? "负" : ""; + n = Math.abs(n); + + String s = ""; + for (int i = 0; i < fraction.length; i++) { + s += (digit[(int) (Math.floor(n * 10 * Math.pow(10, i)) % 10)] + fraction[i]).replaceAll("(零.)+", ""); + } + if (s.length() < 1) { + s = "整"; + } + int integerPart = (int) Math.floor(n); + + for (int i = 0; i < unit[0].length && integerPart > 0; i++) { + String p = ""; + for (int j = 0; j < unit[1].length && n > 0; j++) { + p = digit[integerPart % 10] + unit[1][j] + p; + integerPart = integerPart / 10; + } + s = p.replaceAll("(零.)*零$", "").replaceAll("^$", "零") + unit[0][i] + s; + } + return head + s.replaceAll("(零.)*零元", "元").replaceFirst("(零.)+", "").replaceAll("(零.)+", "零").replaceAll("^整$", "零元整"); + } + + //--------------------------------------------------------------- 原始包装类型转换 + /** + * 原始类转为包装类,非原始类返回原类 + * + * @see BasicType#wrap(Class) + * @param clazz 原始类 + * @return 包装类 + */ + public static Class wrap(Class clazz){ + return BasicType.wrap(clazz); + } + + /** + * 包装类转为原始类,非包装类返回原类 + * + * @see BasicType#unWrap(Class) + * @param clazz 包装类 + * @return 原始类 + */ + public static Class unWrap(Class clazz){ + return BasicType.unWrap(clazz); + } +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/convert/ConvertException.java b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/ConvertException.java new file mode 100644 index 0000000000..65a4be3576 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/ConvertException.java @@ -0,0 +1,32 @@ +package com.xiaoleilu.hutool.convert; + +import com.xiaoleilu.hutool.exceptions.ExceptionUtil; +import com.xiaoleilu.hutool.util.StrUtil; + +/** + * 转换异常 + * @author xiaoleilu + */ +public class ConvertException extends RuntimeException{ + private static final long serialVersionUID = 4730597402855274362L; + + public ConvertException(Throwable e) { + super(ExceptionUtil.getMessage(e), e); + } + + public ConvertException(String message) { + super(message); + } + + public ConvertException(String messageTemplate, Object... params) { + super(StrUtil.format(messageTemplate, params)); + } + + public ConvertException(String message, Throwable throwable) { + super(message, throwable); + } + + public ConvertException(Throwable throwable, String messageTemplate, Object... params) { + super(StrUtil.format(messageTemplate, params), throwable); + } +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/convert/Converter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/Converter.java new file mode 100644 index 0000000000..feadd8d1c1 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/Converter.java @@ -0,0 +1,21 @@ +package com.xiaoleilu.hutool.convert; + +/** + * 转换器接口,实现类型转换 + * @author Looly + * + */ +public interface Converter { + + /** + * 转换为指定类型
        + * 转换为默认值的类型 + * + * @param value 原始值 + * @param defaultValue 默认值 + * @return 转换后的值 + * @throws IllegalArgumentException 默认值 + */ + public T convert(Object value, T defaultValue) throws IllegalArgumentException; + +} \ No newline at end of file diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/convert/ConverterRegistry.java b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/ConverterRegistry.java new file mode 100644 index 0000000000..d1c0da2756 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/ConverterRegistry.java @@ -0,0 +1,236 @@ +package com.xiaoleilu.hutool.convert; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.net.URI; +import java.net.URL; +import java.nio.charset.Charset; +import java.nio.file.Path; +import java.sql.Date; +import java.util.Calendar; +import java.util.Map; +import java.util.TimeZone; +import java.util.concurrent.ConcurrentHashMap; + +import com.xiaoleilu.hutool.convert.impl.ArrayConverter; +import com.xiaoleilu.hutool.convert.impl.BooleanArrayConverter; +import com.xiaoleilu.hutool.convert.impl.BooleanConverter; +import com.xiaoleilu.hutool.convert.impl.ByteArrayConverter; +import com.xiaoleilu.hutool.convert.impl.CalendarConverter; +import com.xiaoleilu.hutool.convert.impl.CharArrayConverter; +import com.xiaoleilu.hutool.convert.impl.CharacterConverter; +import com.xiaoleilu.hutool.convert.impl.CharsetConverter; +import com.xiaoleilu.hutool.convert.impl.ClassConverter; +import com.xiaoleilu.hutool.convert.impl.DateConverter; +import com.xiaoleilu.hutool.convert.impl.DateTimeConverter; +import com.xiaoleilu.hutool.convert.impl.DoubleArrayConverter; +import com.xiaoleilu.hutool.convert.impl.FloatArrayConverter; +import com.xiaoleilu.hutool.convert.impl.IntArrayConverter; +import com.xiaoleilu.hutool.convert.impl.LongArrayConverter; +import com.xiaoleilu.hutool.convert.impl.NumberConverter; +import com.xiaoleilu.hutool.convert.impl.PathConverter; +import com.xiaoleilu.hutool.convert.impl.PrimitiveConverter; +import com.xiaoleilu.hutool.convert.impl.ShortArrayConverter; +import com.xiaoleilu.hutool.convert.impl.SqlDateConverter; +import com.xiaoleilu.hutool.convert.impl.SqlTimeConverter; +import com.xiaoleilu.hutool.convert.impl.SqlTimestampConverter; +import com.xiaoleilu.hutool.convert.impl.StringConverter; +import com.xiaoleilu.hutool.convert.impl.TimeZoneConverter; +import com.xiaoleilu.hutool.convert.impl.URIConverter; +import com.xiaoleilu.hutool.convert.impl.URLConverter; +import com.xiaoleilu.hutool.date.DateTime; + +/** + * 转换器登记 + * + * @author Looly + * + */ +public class ConverterRegistry { + + /** 默认类型转换器 */ + private Map, Converter> defaultConverter; + /** 用户自定义类型转换器 */ + private Map, Converter> customConverter; + + /** 类级的内部类,也就是静态的成员式内部类,该内部类的实例与外部类的实例 没有绑定关系,而且只有被调用到才会装载,从而实现了延迟加载 */ + private static class SingletonHolder { + /** 静态初始化器,由JVM来保证线程安全 */ + private static ConverterRegistry instance = new ConverterRegistry(); + } + /** + * 获得单例的 {@link ConverterRegistry} + * @return {@link ConverterRegistry} + */ + public static ConverterRegistry getInstance(){ + return SingletonHolder.instance; + } + + public ConverterRegistry() { + defaultConverter(); + } + + /** + * 登记自定义转换器 + * + * @param converter 转换器 + * @return {@link ConverterRegistry} + */ + public ConverterRegistry putCustom(Class clazz, Converter converter) { + if(null == customConverter){ + synchronized (this) { + if(null == customConverter){ + customConverter = new ConcurrentHashMap<>(); + } + } + } + customConverter.put(clazz, converter); + return this; + } + + /** + * 获得转换器
        + * 自定义转换器优先级高于默认转换器 + * @param + * + * @param type 类型 + * @return 转换器 + */ + @SuppressWarnings("unchecked") + public Converter getConverter(Class type) { + Converter converter = this.getCustomConverter(type); + if(null == converter){ + converter = (Converter) defaultConverter.get(type); + } + return converter; + } + + /** + * 获得自定义转换器 + * @param + * + * @param type 类型 + * @return 转换器 + */ + @SuppressWarnings("unchecked") + public Converter getCustomConverter(Class type) { + return (null == customConverter) ? null : (Converter)customConverter.get(type); + } + + /** + * 转换值为指定类型 + * + * @param type 类型 + * @param value 值 + * @param defaultValue 默认值 + * @return 转换后的值 + */ + @SuppressWarnings("unchecked") + public T convert(Class type, Object value, T defaultValue) { + if(null == type && null == defaultValue){ + throw new NullPointerException("[type] and [defaultValue] are both null, we can not know what type to convert !"); + } + if(null == value ){ + return defaultValue; + } + if(null == type){ + type = (Class) defaultValue.getClass(); + } + if(type.isInstance(value)){ + return (T)value; + } + + Converter converter = getConverter(type); + if (null == converter) { +// return defaultValue; + throw new ConvertException("No Converter for type [{}]", type.getName()); + } + return converter.convert(value, defaultValue); + } + + /** + * 转换值为指定类型 + * + * @param type 类型 + * @param value 值 + * @return 转换后的值,默认为null + */ + public T convert(Class type, Object value) { + return convert(type, value, null); + } + + //----------------------------------------------------------- Private method start + /** + * 注册默认转换器 + * @return 转换器 + */ + private ConverterRegistry defaultConverter() { + defaultConverter = new ConcurrentHashMap<>(); + + //原始类型转换器 + defaultConverter.put(byte.class, new PrimitiveConverter(byte.class)); + defaultConverter.put(short.class, new PrimitiveConverter(short.class)); + defaultConverter.put(int.class, new PrimitiveConverter(int.class)); + defaultConverter.put(long.class, new PrimitiveConverter(long.class)); + defaultConverter.put(float.class, new PrimitiveConverter(float.class)); + defaultConverter.put(double.class, new PrimitiveConverter(double.class)); + defaultConverter.put(char.class, new PrimitiveConverter(char.class)); + defaultConverter.put(boolean.class, new PrimitiveConverter(boolean.class)); + + //包装类转换器 + defaultConverter.put(String.class, new StringConverter()); + defaultConverter.put(Boolean.class, new BooleanConverter()); + defaultConverter.put(Character.class, new CharacterConverter()); + defaultConverter.put(Number.class, new NumberConverter()); + defaultConverter.put(Byte.class, new NumberConverter(Byte.class)); + defaultConverter.put(Short.class, new NumberConverter(Short.class)); + defaultConverter.put(Integer.class, new NumberConverter(Integer.class)); + defaultConverter.put(Long.class, new NumberConverter(Long.class)); + defaultConverter.put(Float.class, new NumberConverter(Float.class)); + defaultConverter.put(Double.class, new NumberConverter(Double.class)); + defaultConverter.put(BigDecimal.class, new NumberConverter(BigDecimal.class)); + defaultConverter.put(BigInteger.class, new NumberConverter(BigInteger.class)); + + //数组类型转换器 + defaultConverter.put(Integer[].class, new ArrayConverter(Integer.class)); + defaultConverter.put(Long[].class, new ArrayConverter(Long.class)); + defaultConverter.put(Byte[].class, new ArrayConverter(Byte.class)); + defaultConverter.put(Short[].class, new ArrayConverter(Short.class)); + defaultConverter.put(Float[].class, new ArrayConverter(Float.class)); + defaultConverter.put(Double[].class, new ArrayConverter(Double.class)); + defaultConverter.put(Boolean[].class, new ArrayConverter(Boolean.class)); + defaultConverter.put(Character[].class, new ArrayConverter(Character.class)); + defaultConverter.put(String[].class, new ArrayConverter(String.class)); + + //原始类型数组转换器 + defaultConverter.put(byte[].class, new ByteArrayConverter()); + defaultConverter.put(short[].class, new ShortArrayConverter()); + defaultConverter.put(int[].class, new IntArrayConverter()); + defaultConverter.put(long[].class, new LongArrayConverter()); + defaultConverter.put(float[].class, new FloatArrayConverter()); + defaultConverter.put(double[].class, new DoubleArrayConverter()); + defaultConverter.put(boolean[].class, new BooleanArrayConverter()); + defaultConverter.put(char[].class, new CharArrayConverter()); + + //URI and URL + defaultConverter.put(URI.class, new URIConverter()); + defaultConverter.put(URL.class, new URLConverter()); + + //日期时间 + defaultConverter.put(Calendar.class, new CalendarConverter()); + defaultConverter.put(Date.class, new DateConverter()); + defaultConverter.put(DateTime.class, new DateTimeConverter()); + defaultConverter.put(java.sql.Date.class, new SqlDateConverter()); + defaultConverter.put(java.sql.Time.class, new SqlTimeConverter()); + defaultConverter.put(java.sql.Timestamp.class, new SqlTimestampConverter()); + + //其它类型 + defaultConverter.put(Class.class, new ClassConverter()); + defaultConverter.put(TimeZone.class, new TimeZoneConverter()); + defaultConverter.put(Charset.class, new CharsetConverter()); + defaultConverter.put(Path.class, new PathConverter()); + + return this; + } + //----------------------------------------------------------- Private method end +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/ArrayConverter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/ArrayConverter.java new file mode 100644 index 0000000000..28ac6ddede --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/ArrayConverter.java @@ -0,0 +1,176 @@ +package com.xiaoleilu.hutool.convert.impl; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import com.xiaoleilu.hutool.convert.AbstractConverter; +import com.xiaoleilu.hutool.convert.Convert; +import com.xiaoleilu.hutool.util.CollectionUtil; +import com.xiaoleilu.hutool.util.StrUtil; + +/** + * 数组转换器,包括原始类型数组 + * @author Looly + * + * @param + */ +public class ArrayConverter extends AbstractConverter{ + + private Class targetComponentType; + + public ArrayConverter(Class targetComponentType) { + this.targetComponentType = targetComponentType; + } + + @Override + protected T[] convertInternal(Object value) { + return value.getClass().isArray() ? convertObjectToArray(value) : convertArrayToArray(value); + } + + + //-------------------------------------------------------------------------------------- Private method start + /** + * 数组对数组转换 + * @param value 被转换值 + * @return 转换后的数组 + */ + @SuppressWarnings("unchecked") + private T[] convertArrayToArray(Object value) { + Class valueComponentType = value.getClass().getComponentType(); + + if (valueComponentType == targetComponentType) { + return (T[]) value; + } + + T[] result = null; + if(valueComponentType.isPrimitive()){ + //原始类型 + result = convertPrimitiveArrayToArray(value, valueComponentType); + }else{ + //非原始类型 + Object[] array = (Object[]) value; + result = CollectionUtil.newArray(targetComponentType, array.length); + for (int i = 0; i < array.length; i++) { + result[i] = Convert.convert(targetComponentType, array[i]); + } + } + + return result; + } + + /** + * 非数组对数组转换 + * @param value 被转换值 + * @return 转换后的数组 + */ + private T[] convertObjectToArray(Object value) { + T[] result = null; + if (value instanceof List) { + final List list = (List) value; + result = CollectionUtil.newArray(targetComponentType, list.size()); + for (int i = 0; i < list.size(); i++) { + result[i] = Convert.convert(targetComponentType, list.get(i)); + } + }else if (value instanceof Collection) { + final Collection collection = (Collection) value; + result = CollectionUtil.newArray(targetComponentType, collection.size()); + + int i = 0; + for (Object element : collection) { + result[i] = Convert.convert(targetComponentType, element); + i++; + } + }else if (value instanceof Iterable) { + final Iterable iterable = (Iterable) value; + final List list = new ArrayList(); + for (Object element : iterable) { + list.add(Convert.convert(targetComponentType, element)); + } + + result = CollectionUtil.newArray(targetComponentType, list.size()); + result = list.toArray(result); + } + + if (value instanceof CharSequence) { + String[] strings = StrUtil.split(value.toString(), StrUtil.COMMA); + return convertArrayToArray(strings); + } + + // everything else: + return convertToSingleElementArray(value); + } + + /** + * 基本类型数组转为目标类型 + * @param value 被转换的值 + * @param primitiveComponentType 基本类型的类型 + * @return 转换后的数组 + */ + private T[] convertPrimitiveArrayToArray(Object value, Class primitiveComponentType) { + T[] result = null; + + if (primitiveComponentType == int.class) { + int[] array = (int[]) value; + result = CollectionUtil.newArray(targetComponentType, array.length); + for (int i = 0; i < array.length; i++) { + result[i] = Convert.convert(targetComponentType, array[i]); + } + }else if (primitiveComponentType == long.class) { + long[] array = (long[]) value; + result = CollectionUtil.newArray(targetComponentType, array.length); + for (int i = 0; i < array.length; i++) { + result[i] = Convert.convert(targetComponentType, array[i]); + } + }else if (primitiveComponentType == float.class) { + float[] array = (float[]) value; + result = CollectionUtil.newArray(targetComponentType, array.length); + for (int i = 0; i < array.length; i++) { + result[i] = Convert.convert(targetComponentType, array[i]); + } + }else if (primitiveComponentType == double.class) { + double[] array = (double[]) value; + result = CollectionUtil.newArray(targetComponentType, array.length); + for (int i = 0; i < array.length; i++) { + result[i] = Convert.convert(targetComponentType, array[i]); + } + }else if (primitiveComponentType == short.class) { + short[] array = (short[]) value; + result = CollectionUtil.newArray(targetComponentType, array.length); + for (int i = 0; i < array.length; i++) { + result[i] = Convert.convert(targetComponentType, array[i]); + } + }else if (primitiveComponentType == byte.class) { + byte[] array = (byte[]) value; + result = CollectionUtil.newArray(targetComponentType, array.length); + for (int i = 0; i < array.length; i++) { + result[i] = Convert.convert(targetComponentType, array[i]); + } + }else if (primitiveComponentType == char.class) { + char[] array = (char[]) value; + result = CollectionUtil.newArray(targetComponentType, array.length); + for (int i = 0; i < array.length; i++) { + result[i] = Convert.convert(targetComponentType, array[i]); + } + }else if (primitiveComponentType == boolean.class) { + boolean[] array = (boolean[]) value; + result = CollectionUtil.newArray(targetComponentType, array.length); + for (int i = 0; i < array.length; i++) { + result[i] = Convert.convert(targetComponentType, array[i]); + } + } + return result; + } + + /** + * 单元素数组 + * @param value 被转换的值 + * @return 数组,只包含一个元素 + */ + private T[] convertToSingleElementArray(Object value) { + final T[] singleElementArray = CollectionUtil.newArray(targetComponentType, 1); + singleElementArray[0] = Convert.convert(targetComponentType,value); + return singleElementArray; + } + //-------------------------------------------------------------------------------------- Private method end +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/BooleanArrayConverter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/BooleanArrayConverter.java new file mode 100644 index 0000000000..dbd27a25f2 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/BooleanArrayConverter.java @@ -0,0 +1,20 @@ +package com.xiaoleilu.hutool.convert.impl; + +import com.xiaoleilu.hutool.convert.AbstractConverter; +import com.xiaoleilu.hutool.convert.Convert; +import com.xiaoleilu.hutool.util.CollectionUtil; + +/** + * boolean类型数组转换器 + * @author Looly + * + */ +public class BooleanArrayConverter extends AbstractConverter{ + + @Override + protected boolean[] convertInternal(Object value) { + final Boolean[] result = Convert.convert(Boolean[].class, value); + return CollectionUtil.unWrap(result); + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/BooleanConverter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/BooleanConverter.java new file mode 100644 index 0000000000..812a754611 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/BooleanConverter.java @@ -0,0 +1,21 @@ +package com.xiaoleilu.hutool.convert.impl; + +import com.xiaoleilu.hutool.convert.AbstractConverter; + +/** + * 波尔转换器 + * @author Looly + * + */ +public class BooleanConverter extends AbstractConverter{ + + @Override + protected Boolean convertInternal(Object value) { + if(boolean.class == value.getClass()){ + return Boolean.valueOf((boolean)value); + } + String valueStr = convertToStr(value); + return Boolean.valueOf(PrimitiveConverter.parseBoolean(valueStr)); + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/ByteArrayConverter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/ByteArrayConverter.java new file mode 100644 index 0000000000..cbe728ccb8 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/ByteArrayConverter.java @@ -0,0 +1,20 @@ +package com.xiaoleilu.hutool.convert.impl; + +import com.xiaoleilu.hutool.convert.AbstractConverter; +import com.xiaoleilu.hutool.convert.Convert; +import com.xiaoleilu.hutool.util.CollectionUtil; + +/** + * byte 类型数组转换器 + * @author Looly + * + */ +public class ByteArrayConverter extends AbstractConverter{ + + @Override + protected byte[] convertInternal(Object value) { + final Byte[] result = Convert.convert(Byte[].class, value); + return CollectionUtil.unWrap(result); + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/CalendarConverter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/CalendarConverter.java new file mode 100644 index 0000000000..d5659b7958 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/CalendarConverter.java @@ -0,0 +1,56 @@ +package com.xiaoleilu.hutool.convert.impl; + +import java.util.Calendar; +import java.util.Date; + +import com.xiaoleilu.hutool.convert.AbstractConverter; +import com.xiaoleilu.hutool.date.DateUtil; +import com.xiaoleilu.hutool.util.StrUtil; + +/** + * 日期转换器 + * + * @author Looly + * + */ +public class CalendarConverter extends AbstractConverter { + + /** 日期格式化 */ + private String format; + + /** + * 获取日期格式 + * + * @return 设置日期格式 + */ + public String getFormat() { + return format; + } + + /** + * 设置日期格式 + * + * @param format 日期格式 + */ + public void setFormat(String format) { + this.format = format; + } + + @Override + protected Calendar convertInternal(Object value) { + // Handle Date + if (value instanceof Date) { + return DateUtil.calendar((Date)value); + } + + // Handle Long + if (value instanceof Long) { + //此处使用自动拆装箱 + return DateUtil.calendar((Long)value); + } + + final String valueStr = convertToStr(value); + return DateUtil.calendar(StrUtil.isBlank(format) ? DateUtil.parse(valueStr) : DateUtil.parse(valueStr, format)); + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/CharArrayConverter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/CharArrayConverter.java new file mode 100644 index 0000000000..da83f21903 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/CharArrayConverter.java @@ -0,0 +1,20 @@ +package com.xiaoleilu.hutool.convert.impl; + +import com.xiaoleilu.hutool.convert.AbstractConverter; +import com.xiaoleilu.hutool.convert.Convert; +import com.xiaoleilu.hutool.util.CollectionUtil; + +/** + * char类型数组转换器 + * @author Looly + * + */ +public class CharArrayConverter extends AbstractConverter{ + + @Override + protected char[] convertInternal(Object value) { + final Character[] result = Convert.convert(Character[].class, value); + return CollectionUtil.unWrap(result); + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/CharacterConverter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/CharacterConverter.java new file mode 100644 index 0000000000..1b21e04786 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/CharacterConverter.java @@ -0,0 +1,30 @@ +package com.xiaoleilu.hutool.convert.impl; + +import com.xiaoleilu.hutool.convert.AbstractConverter; +import com.xiaoleilu.hutool.util.StrUtil; + +/** + * 字符转换器 + * @author Looly + * + */ +public class CharacterConverter extends AbstractConverter{ + + @Override + protected Character convertInternal(Object value) { + if(char.class == value.getClass()){ + return Character.valueOf((char)value); + }else{ + final String valueStr = convertToStr(value); + if (StrUtil.isNotBlank(valueStr)) { + try { + return Character.valueOf(valueStr.charAt(0)); + } catch (Exception e) { + //Ignore Exception + } + } + } + return null; + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/CharsetConverter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/CharsetConverter.java new file mode 100644 index 0000000000..f137397ebe --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/CharsetConverter.java @@ -0,0 +1,20 @@ +package com.xiaoleilu.hutool.convert.impl; + +import java.nio.charset.Charset; + +import com.xiaoleilu.hutool.convert.AbstractConverter; +import com.xiaoleilu.hutool.util.CharsetUtil; + +/** + * 编码对象转换器 + * @author Looly + * + */ +public class CharsetConverter extends AbstractConverter{ + + @Override + protected Charset convertInternal(Object value) { + return CharsetUtil.charset(convertToStr(value)); + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/ClassConverter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/ClassConverter.java new file mode 100644 index 0000000000..884cde3396 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/ClassConverter.java @@ -0,0 +1,25 @@ +package com.xiaoleilu.hutool.convert.impl; + +import com.xiaoleilu.hutool.convert.AbstractConverter; +import com.xiaoleilu.hutool.util.ClassUtil; + +/** + * 类转换器
        + * 将类名转换为类 + * @author Looly + * + */ +public class ClassConverter extends AbstractConverter>{ + + @Override + protected Class convertInternal(Object value) { + String valueStr = convertToStr(value); + try { + return ClassUtil.getClassLoader().loadClass(valueStr); + } catch (Exception e) { + // Ignore Exception + } + return null; + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/DateConverter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/DateConverter.java new file mode 100644 index 0000000000..0b6fd6509c --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/DateConverter.java @@ -0,0 +1,61 @@ +package com.xiaoleilu.hutool.convert.impl; + +import java.util.Calendar; +import java.util.Date; + +import com.xiaoleilu.hutool.convert.AbstractConverter; +import com.xiaoleilu.hutool.date.DateUtil; +import com.xiaoleilu.hutool.util.StrUtil; + +/** + * 日期转换器 + * + * @author Looly + * + */ +public class DateConverter extends AbstractConverter { + + /** 日期格式化 */ + private String format; + + /** + * 获取日期格式 + * + * @return 设置日期格式 + */ + public String getFormat() { + return format; + } + + /** + * 设置日期格式 + * + * @param format 日期格式 + */ + public void setFormat(String format) { + this.format = format; + } + + @Override + protected Date convertInternal(Object value) { + // Handle Calendar + if (value instanceof Calendar) { + return ((Calendar) value).getTime(); + } + + // Handle Long + if (value instanceof Long) { + //此处使用自动拆装箱 + return new Date((Long)value); + } + + final String valueStr = convertToStr(value); + try { + return StrUtil.isBlank(format) ? DateUtil.parse(valueStr) : DateUtil.parse(valueStr, format); + } catch (Exception e) { + // Ignore Exception + } + return null; + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/DateTimeConverter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/DateTimeConverter.java new file mode 100644 index 0000000000..5f4813eb12 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/DateTimeConverter.java @@ -0,0 +1,62 @@ +package com.xiaoleilu.hutool.convert.impl; + +import java.util.Calendar; + +import com.xiaoleilu.hutool.convert.AbstractConverter; +import com.xiaoleilu.hutool.date.DateTime; +import com.xiaoleilu.hutool.date.DateUtil; +import com.xiaoleilu.hutool.util.StrUtil; + +/** + * 日期时间转换器 + * + * @author Looly + * + */ +public class DateTimeConverter extends AbstractConverter { + + /** 日期格式化 */ + private String format; + + /** + * 获取日期格式 + * + * @return 设置日期格式 + */ + public String getFormat() { + return format; + } + + /** + * 设置日期格式 + * + * @param format 日期格式 + */ + public void setFormat(String format) { + this.format = format; + } + + @Override + protected DateTime convertInternal(Object value) { + // Handle Calendar + if (value instanceof Calendar) { + return new DateTime(((Calendar) value).getTime().getTime()); + } + + // Handle Long + if (value instanceof Long) { + //此处使用自动拆装箱 + return new DateTime((Long)value); + } + + final String valueStr = convertToStr(value); + try { + final long date = StrUtil.isBlank(format) ? DateUtil.parse(valueStr).getTime() : DateUtil.parse(valueStr, format).getTime(); + return new DateTime(date); + } catch (Exception e) { + // Ignore Exception + } + return null; + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/DoubleArrayConverter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/DoubleArrayConverter.java new file mode 100644 index 0000000000..7e35c3ad87 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/DoubleArrayConverter.java @@ -0,0 +1,20 @@ +package com.xiaoleilu.hutool.convert.impl; + +import com.xiaoleilu.hutool.convert.AbstractConverter; +import com.xiaoleilu.hutool.convert.Convert; +import com.xiaoleilu.hutool.util.CollectionUtil; + +/** + * double 类型数组转换器 + * @author Looly + * + */ +public class DoubleArrayConverter extends AbstractConverter{ + + @Override + protected double[] convertInternal(Object value) { + final Double[] result = Convert.convert(Double[].class, value); + return CollectionUtil.unWrap(result); + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/FloatArrayConverter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/FloatArrayConverter.java new file mode 100644 index 0000000000..3d8a598c49 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/FloatArrayConverter.java @@ -0,0 +1,20 @@ +package com.xiaoleilu.hutool.convert.impl; + +import com.xiaoleilu.hutool.convert.AbstractConverter; +import com.xiaoleilu.hutool.convert.Convert; +import com.xiaoleilu.hutool.util.CollectionUtil; + +/** + * float 类型数组转换器 + * @author Looly + * + */ +public class FloatArrayConverter extends AbstractConverter{ + + @Override + protected float[] convertInternal(Object value) { + final Float[] result = Convert.convert(Float[].class, value); + return CollectionUtil.unWrap(result); + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/IntArrayConverter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/IntArrayConverter.java new file mode 100644 index 0000000000..183b0c1c58 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/IntArrayConverter.java @@ -0,0 +1,20 @@ +package com.xiaoleilu.hutool.convert.impl; + +import com.xiaoleilu.hutool.convert.AbstractConverter; +import com.xiaoleilu.hutool.convert.Convert; +import com.xiaoleilu.hutool.util.CollectionUtil; + +/** + * int 类型数组转换器 + * @author Looly + * + */ +public class IntArrayConverter extends AbstractConverter{ + + @Override + protected int[] convertInternal(Object value) { + final Integer[] result = Convert.convert(Integer[].class, value); + return CollectionUtil.unWrap(result); + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/LongArrayConverter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/LongArrayConverter.java new file mode 100644 index 0000000000..aaff74a69a --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/LongArrayConverter.java @@ -0,0 +1,20 @@ +package com.xiaoleilu.hutool.convert.impl; + +import com.xiaoleilu.hutool.convert.AbstractConverter; +import com.xiaoleilu.hutool.convert.Convert; +import com.xiaoleilu.hutool.util.CollectionUtil; + +/** + * long 类型数组转换器 + * @author Looly + * + */ +public class LongArrayConverter extends AbstractConverter{ + + @Override + protected long[] convertInternal(Object value) { + final Long[] result = Convert.convert(Long[].class, value); + return CollectionUtil.unWrap(result); + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/NumberConverter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/NumberConverter.java new file mode 100644 index 0000000000..8dcdcd87c7 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/NumberConverter.java @@ -0,0 +1,180 @@ +package com.xiaoleilu.hutool.convert.impl; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.text.NumberFormat; + +import com.xiaoleilu.hutool.convert.AbstractConverter; +import com.xiaoleilu.hutool.util.StrUtil; + +/** + * 数字转换器
        + * 支持类型为:
        + *
          + *
        • java.lang.Byte
        • + *
        • java.lang.Short
        • + *
        • java.lang.Integer
        • + *
        • java.lang.Long
        • + *
        • java.lang.Float
        • + *
        • java.lang.Double
        • + *
        • java.math.BigDecimal
        • + *
        • java.math.BigInteger
        • + *
        + * + * @author Looly + * + */ +public class NumberConverter extends AbstractConverter { + + private Class targetType; + + public NumberConverter() { + this.targetType = Number.class; + } + + /** + * 构造
        + * @param clazz 需要转换的数字类型,默认 {@link Number} + */ + public NumberConverter(Class clazz) { + this.targetType = (null == clazz) ? Number.class : clazz; + } + + @Override + protected Number convertInternal(Object value) { + try { + if (Byte.class == this.targetType) { + if (value instanceof Number) { + return Byte.valueOf(((Number) value).byteValue()); + } + final String valueStr = convertToStr(value); + if (StrUtil.isBlank(valueStr)) { + return null; + } + return Byte.valueOf(valueStr); + + } else if (Short.class == this.targetType) { + if (value instanceof Number) { + return Short.valueOf(((Number) value).shortValue()); + } + final String valueStr = convertToStr(value); + if (StrUtil.isBlank(valueStr)) { + return null; + } + return Short.valueOf(valueStr); + + } else if (Integer.class == this.targetType) { + if (value instanceof Number) { + return Integer.valueOf(((Number) value).intValue()); + } + final String valueStr = convertToStr(value); + if (StrUtil.isBlank(valueStr)) { + return null; + } + return Integer.valueOf(valueStr); + + } else if (Long.class == this.targetType) { + if (value instanceof Number) { + return Long.valueOf(((Number) value).longValue()); + } + final String valueStr = convertToStr(value); + if (StrUtil.isBlank(valueStr)) { + return null; + } + return Long.valueOf(valueStr); + + } else if (Float.class == this.targetType) { + if (value instanceof Number) { + return Float.valueOf(((Number) value).floatValue()); + } + final String valueStr = convertToStr(value); + if (StrUtil.isBlank(valueStr)) { + return null; + } + return Float.valueOf(valueStr); + + } else if (Double.class == this.targetType) { + if (value instanceof Number) { + return Double.valueOf(((Number) value).doubleValue()); + } + final String valueStr = convertToStr(value); + if (StrUtil.isBlank(valueStr)) { + return null; + } + return Double.valueOf(valueStr); + + } else if (BigDecimal.class == this.targetType) { + return toBigDecimal(value); + + } else if (BigInteger.class == this.targetType) { + toBigInteger(value); + } + + final String valueStr = convertToStr(value); + if (StrUtil.isBlank(valueStr)) { + return null; + } + return NumberFormat.getInstance().parse(valueStr); + } catch (Exception e) { + // Ignore Exception + } + return null; + } + + /** + * 转换为BigDecimal
        + * 如果给定的值为空,或者转换失败,返回默认值
        + * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + private BigDecimal toBigDecimal(Object value) { + if (value instanceof Long) { + return new BigDecimal((Long) value); + } else if (value instanceof Double) { + return new BigDecimal((Double) value); + } else if (value instanceof Integer) { + return new BigDecimal((Integer) value); + } else if (value instanceof BigInteger) { + return new BigDecimal((BigInteger) value); + } + + final String valueStr = convertToStr(value); + if (StrUtil.isBlank(valueStr)) { + return null; + } + return new BigDecimal(valueStr); + } + + /** + * 转换为BigInteger
        + * 如果给定的值为空,或者转换失败,返回默认值
        + * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + private BigInteger toBigInteger(Object value) { + if (value instanceof Long) { + return BigInteger.valueOf((Long) value); + } + final String valueStr = convertToStr(value); + if (StrUtil.isBlank(valueStr)) { + return null; + } + return new BigInteger(valueStr); + } + + @Override + protected String convertToStr(Object value){ + final String valueStr = super.convertToStr(value); + return (null == valueStr) ? null : valueStr.trim(); + } + + @Override + @SuppressWarnings("unchecked") + public Class getTargetType() { + return (Class) this.targetType; + } +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/PathConverter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/PathConverter.java new file mode 100644 index 0000000000..26d4814a44 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/PathConverter.java @@ -0,0 +1,40 @@ +package com.xiaoleilu.hutool.convert.impl; + +import java.io.File; +import java.net.URI; +import java.net.URL; +import java.nio.file.Path; +import java.nio.file.Paths; + +import com.xiaoleilu.hutool.convert.AbstractConverter; + +/** + * 字符串转换器 + * @author Looly + * + */ +public class PathConverter extends AbstractConverter{ + + @Override + protected Path convertInternal(Object value) { + try { + if(value instanceof URI){ + return Paths.get((URI)value); + } + + if(value instanceof URL){ + return Paths.get(((URL)value).toURI()); + } + + if(value instanceof File){ + return ((File)value).toPath(); + } + + return Paths.get(convertToStr(value)); + } catch (Exception e) { + // Ignore Exception + } + return null; + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/PrimitiveConverter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/PrimitiveConverter.java new file mode 100644 index 0000000000..48162dd1c5 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/PrimitiveConverter.java @@ -0,0 +1,163 @@ +package com.xiaoleilu.hutool.convert.impl; + +import com.xiaoleilu.hutool.convert.AbstractConverter; +import com.xiaoleilu.hutool.util.StrUtil; + +/** + * 原始类型转换器
        + * 支持类型为:
        + *
          + *
        • byte
        • + *
        • short
        • + *
        • int
        • + *
        • long
        • + *
        • float
        • + *
        • double
        • + *
        • char
        • + *
        • boolean
        • + *
        + * + * @author Looly + * + */ +public class PrimitiveConverter extends AbstractConverter { + + private Class targetType; + + /** + * 构造
        + * @param clazz 需要转换的原始 + * @throws IllegalArgumentException 传入的转换类型非原始类型时抛出 + */ + public PrimitiveConverter(Class clazz) { + if(null == clazz){ + throw new NullPointerException("PrimitiveConverter not allow null target type!"); + }else if(false == clazz.isPrimitive()){ + throw new IllegalArgumentException("[" + clazz + "] is not a primitive class!"); + } + this.targetType = clazz; + } + + @Override + protected Object convertInternal(Object value) { + try { + if (byte.class == this.targetType) { + if (value instanceof Number) { + return ((Number) value).byteValue(); + } + final String valueStr = convertToStr(value); + if (StrUtil.isBlank(valueStr)) { + return 0; + } + return Byte.parseByte(valueStr); + + } else if (short.class == this.targetType) { + if (value instanceof Number) { + return ((Number) value).shortValue(); + } + final String valueStr = convertToStr(value); + if (StrUtil.isBlank(valueStr)) { + return 0; + } + return Short.parseShort(valueStr); + + } else if (int.class == this.targetType) { + if (value instanceof Number) { + return ((Number) value).intValue(); + } + final String valueStr = convertToStr(value); + if (StrUtil.isBlank(valueStr)) { + return 0; + } + return Integer.parseInt(valueStr); + + } else if (long.class == this.targetType) { + if (value instanceof Number) { + return ((Number) value).longValue(); + } + final String valueStr = convertToStr(value); + if (StrUtil.isBlank(valueStr)) { + return 0; + } + return Long.parseLong(valueStr); + + } else if (float.class == this.targetType) { + if (value instanceof Number) { + return ((Number) value).floatValue(); + } + final String valueStr = convertToStr(value); + if (StrUtil.isBlank(valueStr)) { + return 0; + } + return Float.parseFloat(valueStr); + + } else if (double.class == this.targetType) { + if (value instanceof Number) { + return ((Number) value).doubleValue(); + } + final String valueStr = convertToStr(value); + if (StrUtil.isBlank(valueStr)) { + return 0; + } + return Double.parseDouble(valueStr); + + } else if (char.class == this.targetType) { + if(value instanceof Character){ + return ((Character)value).charValue(); + } + final String valueStr = convertToStr(value); + if (StrUtil.isBlank(valueStr)) { + return 0; + } + return valueStr.charAt(0); + } else if (boolean.class == this.targetType) { + if(value instanceof Boolean){ + return ((Boolean)value).booleanValue(); + } + String valueStr = convertToStr(value); + return parseBoolean(valueStr); + } + } catch (Exception e) { + // Ignore Exception + } + return 0; + } + + /** + * 转换字符串为boolean值 + * @param valueStr 字符串 + * @return boolean值 + */ + static boolean parseBoolean(String valueStr){ + if (StrUtil.isNotBlank(valueStr)) { + valueStr = valueStr.trim().toLowerCase(); + switch (valueStr) { + case "true": + return true; + case "false": + return false; + case "yes": + return true; + case "y": + return true; + case "ok": + return true; + case "no": + return false; + case "n": + return false; + case "1": + return true; + case "0": + return false; + } + } + return false; + } + + @Override + @SuppressWarnings("unchecked") + public Class getTargetType() { + return (Class) this.targetType; + } +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/ShortArrayConverter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/ShortArrayConverter.java new file mode 100644 index 0000000000..ccfb6387c9 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/ShortArrayConverter.java @@ -0,0 +1,20 @@ +package com.xiaoleilu.hutool.convert.impl; + +import com.xiaoleilu.hutool.convert.AbstractConverter; +import com.xiaoleilu.hutool.convert.Convert; +import com.xiaoleilu.hutool.util.CollectionUtil; + +/** + * short 类型数组转换器 + * @author Looly + * + */ +public class ShortArrayConverter extends AbstractConverter{ + + @Override + protected short[] convertInternal(Object value) { + final Short[] result = Convert.convert(Short[].class, value); + return CollectionUtil.unWrap(result); + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/SqlDateConverter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/SqlDateConverter.java new file mode 100644 index 0000000000..c21bbc77be --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/SqlDateConverter.java @@ -0,0 +1,62 @@ +package com.xiaoleilu.hutool.convert.impl; + +import java.sql.Date; +import java.util.Calendar; + +import com.xiaoleilu.hutool.convert.AbstractConverter; +import com.xiaoleilu.hutool.date.DateUtil; +import com.xiaoleilu.hutool.util.StrUtil; + +/** + * SQL日期转换器 + * + * @author Looly + * + */ +public class SqlDateConverter extends AbstractConverter { + + /** 日期格式化 */ + private String format; + + /** + * 获取日期格式 + * + * @return 设置日期格式 + */ + public String getFormat() { + return format; + } + + /** + * 设置日期格式 + * + * @param format 日期格式 + */ + public void setFormat(String format) { + this.format = format; + } + + @Override + protected Date convertInternal(Object value) { + // Handle Calendar + if (value instanceof Calendar) { + return new Date(((Calendar) value).getTime().getTime()); + } + + // Handle Long + if (value instanceof Long) { + //此处使用自动拆装箱 + return new Date((Long)value); + } + + final String valueStr = convertToStr(value); + try { + final long date = StrUtil.isBlank(format) ? DateUtil.parse(valueStr).getTime() : DateUtil.parse(valueStr, format).getTime(); + return new Date(date); + } catch (Exception e) { + // Ignore Exception + } + return null; + } + +} diff --git a/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/SqlTimeConverter.java b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/SqlTimeConverter.java new file mode 100644 index 0000000000..fa60686e43 --- /dev/null +++ b/jun_util/src/main/java/com/xiaoleilu/hutool/convert/impl/SqlTimeConverter.java @@ -0,0 +1,62 @@ +package com.xiaoleilu.hutool.convert.impl; + +import java.sql.Time; +import java.util.Calendar; + +import com.xiaoleilu.hutool.convert.AbstractConverter; +import com.xiaoleilu.hutool.date.DateUtil; +import com.xiaoleilu.hutool.util.StrUtil; + +/** + * SQL时间转换器 + * + * @author Looly + * + */ +public class SqlTimeConverter extends AbstractConverter