diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 00000000..36de67a3 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: houko +patreon: #hupeng +open_collective: SpringBootUnity +ko_fi: #hupeng +tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: #houko/SpringBootUnity +otechie: # Replace with a single Otechie username +custom: #https:blog.xiaomo.info diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml new file mode 100644 index 00000000..1620e2e5 --- /dev/null +++ b/.github/workflows/codeql-analysis.yml @@ -0,0 +1,72 @@ +# For most projects, this workflow file will not need changing; you simply need +# to commit it to your repository. +# +# You may wish to alter this file to override the set of languages analyzed, +# or to provide custom queries or build logic. +# +# ******** NOTE ******** +# We have attempted to detect the languages in your repository. Please check +# the `language` matrix defined below to confirm you have the correct set of +# supported CodeQL languages. +# +name: "CodeQL" + +on: + push: + branches: [ "master" ] + pull_request: + # The branches below must be a subset of the branches above + branches: [ "master" ] + schedule: + - cron: '24 7 * * 0' + +jobs: + analyze: + name: Analyze + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + security-events: write + + strategy: + fail-fast: false + matrix: + language: [ 'java' ] + # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] + # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v2 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + + # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs + # queries: security-extended,security-and-quality + + + # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). + # If this step fails, then you should remove it and run the build manually (see below) + - name: Autobuild + uses: github/codeql-action/autobuild@v2 + + # ℹ️ Command-line programs to run using the OS shell. + # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun + + # If the Autobuild fails above, remove it and uncomment the following three lines. + # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. + + # - run: | + # echo "Run, Build Application using script" + # ./location_of_script_within_repo/buildscript.sh + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v2 diff --git a/.travis.yml b/.travis.yml index dff5f3a5..34d145f8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1 +1,4 @@ language: java +jdk: + - oraclejdk11 +dist: trusty \ No newline at end of file diff --git a/Rakefile b/Rakefile deleted file mode 100644 index cebe92c4..00000000 --- a/Rakefile +++ /dev/null @@ -1,3 +0,0 @@ -require "rubygems" -require "rake" -end \ No newline at end of file diff --git a/README.md b/Readme.md similarity index 79% rename from README.md rename to Readme.md index a7b20c4b..6f137c59 100644 --- a/README.md +++ b/Readme.md @@ -1,23 +1,22 @@ -[![Build Status](https://travis-ci.org/xiaomoinfo/SpringBootUnity.svg?branch=master)](https://travis-ci.org/xiaomoinfo/SpringBootUnity) -[![Backers on Open Collective](https://opencollective.com/SpringBootUnity/backers/badge.svg)](#backers) [![Sponsors on Open Collective](https://opencollective.com/SpringBootUnity/sponsors/badge.svg)](#sponsors) [![GitHub issues](https://img.shields.io/github/issues/xiaomoinfo/SpringBootUnity.svg)](https://github.com/xiaomoinfo/SpringBootUnity/issues) -[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/xiaomoinfo/MysqlBlobToJsonTool/master/LICENSE) +[![Build Status](https://travis-ci.org/houko/SpringBootUnity.svg?branch=master)](https://travis-ci.org/houko/SpringBootUnity) +[![Backers on Open Collective](https://opencollective.com/SpringBootUnity/backers/badge.svg)](#backers) [![Sponsors on Open Collective](https://opencollective.com/SpringBootUnity/sponsors/badge.svg)](#sponsors) [![GitHub issues](https://img.shields.io/github/issues/houko/SpringBootUnity.svg)](https://github.com/houko/SpringBootUnity/issues) +[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/houko/SpringBootUnity/master/LICENSE) [![Maven Central](https://img.shields.io/maven-central/v/org.apache.maven/apache-maven.svg)]() ### 项目简介 -![mark](screenshot/spring.png) +![mark](screenshot/SpringBootUnity.png) ### 环境 - `maven` latest -- `jdk1.8` -- `spring boot 1.5.8 release`(目前最新版) -- 个人推荐`idea`来代替eclipse(希望不要被说成异教徒必须死) -- mysql5.5+ +- `jdk11` +- `spring boot 2.x release` +- 个人推荐`idea`来代替eclipse - git: 版本管理 - nginx: 反向代理服务器 ### 注意事项 -- 本项目代码托管在[github](https://github.com/xiaomoinfo/SpringBootUnity)和[码云](http://git.oschina.net/hupeng/SpringBootUnity)两个地方,最新代码会先推送在github上,码云上会在github上更新完之后进行同步。 +- 本项目代码托管在[github](https://github.com/houko/SpringBootUnity)和[码云](http://git.oschina.net/hupeng_admin/SpringBootUnity)两个地方,最新代码会先推送在github上,码云上会在github上更新完之后进行同步。 - 本项目多数数据库都用到了`hibernate`,如果没有提供`sql`文件。则启动时会根据代码映射自动生成数据库表,请在启动前修改`application.properties`中的数据库连接信息 @@ -60,12 +59,19 @@ http://localhost:808/doc.html bootstrap-ui - 2017-09-08 crawler模块(网络爬虫):修复本地文件目录不存在会报错的bug。处理方式为:不存在则自动创建 - 2017-11-02 开源协议从apache更换到MIT - 2017-11-02 添加本地运行方式的说明 -- 2017-11-02 版本更新到2017.2 +- 2017-11-02 版本更新到2020.1 - 2017-11-02 spring boot版本更新到1.5.8 - 2017-11-03 添加kotlin环境配置 - 2017-11-03 按照阿里巴巴编程规范插件P3C优化代码 - 2017-11-03 合并`api`和`website`模块,访问`localhost:8080`会显示网站主页,访问`localhost:8080/api`会显示api管理界面 -- 2017-11-03 从java代码转移到kotlin上 +- 2018-04-09 将整个项目升级到spring boot2.0 release版本,api有较大变动 +- 2019-08-06 travis-ci指定jdk版本 +- 2020-10-09 升级版本到2020.2 +- 2020-10-09 升级jdk版本到11 +- 2020-10-09 升级mysql connector到8 +- 2020-10-09 升级spring boot到2.3.0 +- 2020-10-09 修复了升级后API的破坏性变动,修复了一些了编辑器警告 + @@ -108,42 +114,20 @@ http://localhost:808/doc.html bootstrap-ui - [在线Cron表达式生成器](http://cron.qqe2.com/ "在线Cron表达式生成器") - [在线工具 - 程序员的工具箱](http://tool.lu/ "在线工具 - 程序员的工具箱") +- [spring boot官方脚手架](https://start.spring.io/ "spring boot官方脚手架") ### 问题反馈 -1. 欢迎提[issue](https://github.com/xiaomoinfo/SpringBootUnity/issues)一起完善这个项目。 +1. 欢迎提[issue](https://github.com/houko/SpringBootUnity/issues)一起完善这个项目。 2. QQ: 83387856 4. 个人主站: https://xiaomo.info -### 在线文档 - -- [JDK7英文文档](http://tool.oschina.net/apidocs/apidoc?api=jdk_7u4 "JDK7英文文档") - -- [Spring4.x文档](http://spring.oschina.mopaas.com/ "Spring4.x文档") - -- [Mybatis3官网](http://www.mybatis.org/mybatis-3/zh/index.html "Mybatis3官网") - -- [Dubbo官网](http://dubbo.io/ "Dubbo官网") - -- [Nginx中文文档](http://tool.oschina.net/apidocs/apidoc?api=nginx-zh "Nginx中文文档") - -- [Freemarker在线手册](http://freemarker.foofun.cn/ "Freemarker在线中文手册") - -- [Velocity在线手册](http://velocity.apache.org/engine/devel/developer-guide.html "Velocity在线手册") - -- [Bootstrap在线手册](http://www.bootcss.com/ "Bootstrap在线手册") - -- [Git官网中文文档](https://git-scm.com/book/zh/v2 "Git官网中文文档") - -- [Thymeleaf](http://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html "Thymeleaf") - - ## [License](LICENSE "MIT") MIT License - Copyright (c) 2017 Peng Hu + Copyright (c) 2022 Peng Hu Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 00000000..034e8480 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,21 @@ +# Security Policy + +## Supported Versions + +Use this section to tell people about which versions of your project are +currently being supported with security updates. + +| Version | Supported | +| ------- | ------------------ | +| 5.1.x | :white_check_mark: | +| 5.0.x | :x: | +| 4.0.x | :white_check_mark: | +| < 4.0 | :x: | + +## Reporting a Vulnerability + +Use this section to tell people how to report a vulnerability. + +Tell them where to go, how often they can expect to get an update on a +reported vulnerability, what to expect if the vulnerability is accepted or +declined, etc. diff --git a/async/pom.xml b/async/pom.xml index ae7c1344..60d54b74 100644 --- a/async/pom.xml +++ b/async/pom.xml @@ -5,7 +5,7 @@ xiaomo info.xiaomo - 2017.2 + 2020.1 4.0.0 @@ -14,7 +14,7 @@ info.xiaomo core - 2017.2 + 2020.1 diff --git a/async/src/main/java/info/xiaomo/anysc/AsyncMain.java b/async/src/main/java/info/xiaomo/anysc/AsyncMain.java new file mode 100644 index 00000000..79e1fce0 --- /dev/null +++ b/async/src/main/java/info/xiaomo/anysc/AsyncMain.java @@ -0,0 +1,35 @@ +package info.xiaomo.anysc; + + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/4/1 15:38 + * Description: RabbitMq启动器 + * Copyright(©) 2015 by xiaomo. + **/ +@Configuration +@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) +@ComponentScan("info.xiaomo") +@EntityScan("info.xiaomo.*.model") +public class AsyncMain { + public static void main(String[] args) throws Exception { + SpringApplication.run(AsyncMain.class, args); + } + +} diff --git a/async/src/main/java/info/xiaomo/anysc/AsyncMain.kt b/async/src/main/java/info/xiaomo/anysc/AsyncMain.kt deleted file mode 100644 index 1e54d64b..00000000 --- a/async/src/main/java/info/xiaomo/anysc/AsyncMain.kt +++ /dev/null @@ -1,32 +0,0 @@ -package info.xiaomo.anysc - - -import org.springframework.boot.SpringApplication -import org.springframework.boot.autoconfigure.EnableAutoConfiguration -import org.springframework.boot.autoconfigure.domain.EntityScan -import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration -import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration -import org.springframework.context.annotation.ComponentScan - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/4/1 15:38 - * Description: RabbitMq启动器 - * Copyright(©) 2015 by xiaomo. - */ -@EnableAutoConfiguration(exclude = arrayOf(DataSourceAutoConfiguration::class, HibernateJpaAutoConfiguration::class)) -@ComponentScan("info.xiaomo") -@EntityScan("info.xiaomo.*.model") -class AsyncMain - -fun main(args: Array) { - SpringApplication.run(AsyncMain::class.java, *args) -} diff --git a/async/src/main/java/info/xiaomo/anysc/controller/TestController.java b/async/src/main/java/info/xiaomo/anysc/controller/TestController.java new file mode 100644 index 00000000..0817a3a8 --- /dev/null +++ b/async/src/main/java/info/xiaomo/anysc/controller/TestController.java @@ -0,0 +1,160 @@ +package info.xiaomo.anysc.controller; + +import info.xiaomo.anysc.task.AsyncTask; +import info.xiaomo.core.base.BaseController; +import info.xiaomo.core.base.Result; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.concurrent.Future; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/11/15 15:12 + * Description: 用户实体类 + * Copyright(©) 2015 by xiaomo. + **/ + +@RestController +@RequestMapping("/") +public class TestController extends BaseController { + + private final AsyncTask task; + + @Autowired + public TestController(AsyncTask task) { + this.task = task; + } + + @RequestMapping(value = "/", method = RequestMethod.GET) + public Result task() throws Exception { + long start = System.currentTimeMillis(); + + Future task1 = task.doTaskOne(); + Future task2 = task.doTaskTwo(); + Future task3 = task.doTaskThree(); + + while (true) { + if (task1.isDone() && task2.isDone() && task3.isDone()) { + // 三个任务都调用完成,退出循环等待 + break; + } + Thread.sleep(1000); + } + + long end = System.currentTimeMillis(); + + System.out.println("任务全部完成,总耗时:" + (end - start) + "毫秒"); + return new Result<>(end - start); + } + + + /** + * 查找所有(不带分页) + * + * @return result + */ + @Override + public Result findAll() { + return null; + } + + /** + * 带分页 + * + * @param start 起始页 + * @param pageSize 页码数 + * @return result + */ + @Override + public Result findAll(@PathVariable int start, @PathVariable int pageSize) { + return null; + } + + /** + * 根据id查看模型 + * + * @param id id + * @return result + */ + @Override + public Result findById(@PathVariable Long id) { + return null; + } + + /** + * 根据名字查找模型 + * + * @param name name + * @return result + */ + @Override + public Result findByName(@PathVariable String name) { + return null; + } + + /** + * 根据名字删除模型 + * + * @param name name + * @return result + */ + @Override + public Result delByName(@PathVariable String name) { + return null; + } + + /** + * 根据id删除模型 + * + * @param id id + * @return result + */ + @Override + public Result delById(@PathVariable Long id) { + return null; + } + + /** + * 添加模型 + * + * @param model model + * @return result + */ + @Override + public Result add(@RequestBody Object model) { + return null; + } + + /** + * 更新 + * + * @param model model + * @return result + */ + @Override + public Result update(@RequestBody Object model) { + return null; + } + + /** + * 批量删除 + * + * @param ids ids + * @return result + */ + @Override + public Result delByIds(@PathVariable List ids) { + return null; + } +} diff --git a/async/src/main/java/info/xiaomo/anysc/controller/TestController.kt b/async/src/main/java/info/xiaomo/anysc/controller/TestController.kt deleted file mode 100644 index 424ca917..00000000 --- a/async/src/main/java/info/xiaomo/anysc/controller/TestController.kt +++ /dev/null @@ -1,54 +0,0 @@ -package info.xiaomo.anysc.controller - -import info.xiaomo.anysc.task.AsyncTask -import info.xiaomo.core.base.Result -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.web.bind.annotation.RequestMapping -import org.springframework.web.bind.annotation.RequestMethod -import org.springframework.web.bind.annotation.RestController - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * - * Date: 2016/11/15 15:12 - * Description: 用户实体类 - * Copyright(©) 2015 by xiaomo. - */ - -@RestController -@RequestMapping("/") -class TestController -@Autowired constructor(private val task: AsyncTask) { - - @RequestMapping(value = "/", method = arrayOf(RequestMethod.GET)) - @Throws(Exception::class) - fun task(): Result<*> { - val start = System.currentTimeMillis() - - val task1 = task.doTaskOne() - val task2 = task.doTaskTwo() - val task3 = task.doTaskThree() - - while (true) { - if (task1.isDone && task2.isDone && task3.isDone) { - // 三个任务都调用完成,退出循环等待 - break - } - Thread.sleep(1000) - } - - val end = System.currentTimeMillis() - - println("任务全部完成,总耗时:" + (end - start) + "毫秒") - return Result(end - start) - } - -} diff --git a/async/src/main/java/info/xiaomo/anysc/task/AsyncTask.java b/async/src/main/java/info/xiaomo/anysc/task/AsyncTask.java new file mode 100644 index 00000000..73ac1fc5 --- /dev/null +++ b/async/src/main/java/info/xiaomo/anysc/task/AsyncTask.java @@ -0,0 +1,48 @@ +package info.xiaomo.anysc.task; + +import org.springframework.scheduling.annotation.Async; +import org.springframework.scheduling.annotation.AsyncResult; +import org.springframework.stereotype.Component; + +import java.util.Random; +import java.util.concurrent.Future; + +/** + * @author : xiaomo + */ +@Component +public class AsyncTask { + + private static Random random = new Random(); + + @Async + public Future doTaskOne() throws Exception { + System.out.println("开始做任务一"); + long start = System.currentTimeMillis(); + Thread.sleep(random.nextInt(10000)); + long end = System.currentTimeMillis(); + System.out.println("完成任务一,耗时:" + (end - start) + "毫秒"); + return new AsyncResult<>("任务一完成"); + } + + @Async + public Future doTaskTwo() throws Exception { + System.out.println("开始做任务二"); + long start = System.currentTimeMillis(); + Thread.sleep(random.nextInt(10000)); + long end = System.currentTimeMillis(); + System.out.println("完成任务二,耗时:" + (end - start) + "毫秒"); + return new AsyncResult<>("任务二完成"); + } + + @Async + public Future doTaskThree() throws Exception { + System.out.println("开始做任务三"); + long start = System.currentTimeMillis(); + Thread.sleep(random.nextInt(10000)); + long end = System.currentTimeMillis(); + System.out.println("完成任务三,耗时:" + (end - start) + "毫秒"); + return new AsyncResult<>("任务三完成"); + } + +} diff --git a/async/src/main/java/info/xiaomo/anysc/task/AsyncTask.kt b/async/src/main/java/info/xiaomo/anysc/task/AsyncTask.kt deleted file mode 100644 index 8e9c094d..00000000 --- a/async/src/main/java/info/xiaomo/anysc/task/AsyncTask.kt +++ /dev/null @@ -1,53 +0,0 @@ -package info.xiaomo.anysc.task - -import org.springframework.scheduling.annotation.Async -import org.springframework.scheduling.annotation.AsyncResult -import org.springframework.stereotype.Component -import java.util.* -import java.util.concurrent.Future - -/** - * @author : xiaomo - */ -@Component -open class AsyncTask { - - @Async - @Throws(Exception::class) - open fun doTaskOne(): Future { - println("开始做任务一") - val start = System.currentTimeMillis() - Thread.sleep(random.nextInt(10000).toLong()) - val end = System.currentTimeMillis() - println("完成任务一,耗时:" + (end - start) + "毫秒") - return AsyncResult("任务一完成") - } - - @Async - @Throws(Exception::class) - open fun doTaskTwo(): Future { - println("开始做任务二") - val start = System.currentTimeMillis() - Thread.sleep(random.nextInt(10000).toLong()) - val end = System.currentTimeMillis() - println("完成任务二,耗时:" + (end - start) + "毫秒") - return AsyncResult("任务二完成") - } - - @Async - @Throws(Exception::class) - open fun doTaskThree(): Future { - println("开始做任务三") - val start = System.currentTimeMillis() - Thread.sleep(random.nextInt(10000).toLong()) - val end = System.currentTimeMillis() - println("完成任务三,耗时:" + (end - start) + "毫秒") - return AsyncResult("任务三完成") - } - - companion object { - - private val random = Random() - } - -} diff --git a/async/src/main/resources/config/application.properties b/async/src/main/resources/config/application.properties index 2bbf0e38..79ef9397 100644 --- a/async/src/main/resources/config/application.properties +++ b/async/src/main/resources/config/application.properties @@ -1,8 +1,9 @@ logging.config=classpath:config/logback-dev.xml server.port=8080 -server.session.timeout=1800 + server.max-http-header-size=20971520 # \u914D\u7F6E\u8FD9\u4E2A\u503C\u5C31\u53EF\u4EE5\u683C\u5F0F\u5316\u65F6\u95F4 spring.jackson.date-format=yyyy-MM-dd HH:mm:ss spring.jackson.time-zone=GMT+8 +spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl \ No newline at end of file diff --git a/core/pom.xml b/core/pom.xml index accd4fa0..8e3af9eb 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -5,7 +5,7 @@ info.xiaomo xiaomo - 2017.2 + 2020.1 4.0.0 @@ -63,6 +63,10 @@ commons-fileupload commons-fileupload + + org.projectlombok + lombok + dom4j dom4j @@ -80,4 +84,18 @@ poi + + + + + org.springframework.boot + spring-boot-maven-plugin + + + none + + + + + \ No newline at end of file diff --git a/core/src/main/java/info/xiaomo/core/base/AuthOperate.kt b/core/src/main/java/info/xiaomo/core/base/AuthOperate.java similarity index 52% rename from core/src/main/java/info/xiaomo/core/base/AuthOperate.kt rename to core/src/main/java/info/xiaomo/core/base/AuthOperate.java index f0c8de57..76889389 100644 --- a/core/src/main/java/info/xiaomo/core/base/AuthOperate.kt +++ b/core/src/main/java/info/xiaomo/core/base/AuthOperate.java @@ -1,13 +1,14 @@ -package info.xiaomo.core.base +package info.xiaomo.core.base; -import org.springframework.web.bind.annotation.PathVariable -import java.util.* +import org.springframework.web.bind.annotation.PathVariable; + +import java.util.Date; /** - * @author : xiaomo (https://xiaomo.info) (https://github.com/xiaomoinfo) + * @author : xiaomo (https://xiaomo.info) (https://github.com/houko) * @version : 2017/1/13 9:51 */ -interface AuthOperate { +public interface AuthOperate { /** @@ -17,7 +18,7 @@ interface AuthOperate { * @param password 密码 * @return 结果 */ - fun login(@PathVariable name: String, @PathVariable password: String): Result + Result login(@PathVariable String name, @PathVariable String password); /** @@ -27,7 +28,7 @@ fun login(@PathVariable name: String, @PathVariable password: String): Result + Result changePassword(@PathVariable String name, @PathVariable String password); /** * 注册 @@ -36,7 +37,7 @@ fun changePassword(@PathVariable name: String, @PathVariable password: String): * @param password 密码 * @return 是否己发送验证码 */ - fun register(@PathVariable name: String, @PathVariable password: String): Result + Result register(@PathVariable String name, @PathVariable String password); /** * 验证 @@ -45,6 +46,6 @@ fun register(@PathVariable name: String, @PathVariable password: String): Result * @param time 发送时间 * @return 是否验证通过 */ - fun validate(@PathVariable validCode: Int, @PathVariable time: Date): Result + Result validate(@PathVariable int validCode, @PathVariable Date time); } diff --git a/core/src/main/java/info/xiaomo/core/base/BaseController.java b/core/src/main/java/info/xiaomo/core/base/BaseController.java new file mode 100644 index 00000000..b2f5d2c8 --- /dev/null +++ b/core/src/main/java/info/xiaomo/core/base/BaseController.java @@ -0,0 +1,96 @@ +package info.xiaomo.core.base; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.data.domain.Page; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +/** + * @author : xiaomo (https://xiaomo.info) (https://github.com/houko) + * @version : 2017/1/11 16:41 + */ +@RestController +public abstract class BaseController { + + protected final Logger LOGGER = LoggerFactory.getLogger(getClass()); + + /** + * 查找所有(不带分页) + * + * @return result + */ + public abstract Result> findAll(); + + /** + * 带分页 + * + * @param start 起始页 + * @param pageSize 页码数 + * @return result + */ + public abstract Result> findAll(@PathVariable int start, @PathVariable int pageSize); + + /** + * 根据id查看模型 + * + * @param id id + * @return result + */ + public abstract Result findById(@PathVariable Long id); + + /** + * 根据名字查找模型 + * + * @param name name + * @return result + */ + public abstract Result findByName(@PathVariable String name); + + /** + * 根据名字删除模型 + * + * @param name name + * @return result + */ + public abstract Result delByName(@PathVariable String name); + + + /** + * 根据id删除模型 + * + * @param id id + * @return result + */ + public abstract Result delById(@PathVariable Long id); + + /** + * 添加模型 + * + * @param model model + * @return result + */ + public abstract Result add(@RequestBody T model); + + + /** + * 更新 + * + * @param model model + * @return result + */ + public abstract Result update(@RequestBody T model); + + + /** + * 批量删除 + * + * @param ids ids + * @return result + */ + public abstract Result delByIds(@PathVariable List ids); + +} \ No newline at end of file diff --git a/core/src/main/java/info/xiaomo/core/base/BaseDao.java b/core/src/main/java/info/xiaomo/core/base/BaseDao.java new file mode 100644 index 00000000..d9c6941a --- /dev/null +++ b/core/src/main/java/info/xiaomo/core/base/BaseDao.java @@ -0,0 +1,28 @@ +package info.xiaomo.core.base; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +/** + * @author : xiaomo (https://xiaomo.info) (https://github.com/houko) + * @version : 2017/1/13 11:23 + */ +@Repository +public interface BaseDao extends JpaRepository { + + /** + * 根据名字查 + * + * @param name + * @return + */ + T findByName(String name); + + /** + * 删除 + * + * @param name + * @return + */ + boolean deleteByName(String name); +} diff --git a/core/src/main/java/info/xiaomo/core/base/BaseDao.kt b/core/src/main/java/info/xiaomo/core/base/BaseDao.kt deleted file mode 100644 index 09dc7351..00000000 --- a/core/src/main/java/info/xiaomo/core/base/BaseDao.kt +++ /dev/null @@ -1,34 +0,0 @@ -package info.xiaomo.core.base - -import org.springframework.data.jpa.repository.JpaRepository -import org.springframework.stereotype.Repository - -/** - * @author : xiaomo (https://xiaomo.info) (https://github.com/xiaomoinfo) - * @version : 2017/1/13 11:23 - */ -@Repository -interface BaseDao : JpaRepository { - - /** - * 根据id查 - * - * @param id - * @return - */ - fun findById(id: Long?): T - - /** - * 根据名字查 - * @param name - * @return - */ - fun findByName(name: String): T - - /** - * 删除 - * @param name - * @return - */ - fun deleteByName(name: String): Boolean -} diff --git a/core/src/main/java/info/xiaomo/core/base/BaseModel.java b/core/src/main/java/info/xiaomo/core/base/BaseModel.java new file mode 100644 index 00000000..37d18bbe --- /dev/null +++ b/core/src/main/java/info/xiaomo/core/base/BaseModel.java @@ -0,0 +1,40 @@ +package info.xiaomo.core.base; + +import lombok.Data; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.Date; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/4/1 20:37 + * Copyright(©) 2015 by xiaomo. + **/ + +@MappedSuperclass +@Data +public abstract class BaseModel implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "Id") + private Long id; + + @Column(name = "Name") + private String name; + + @Column(name = "CreateTime") + private Date createTime; + + @Column(name = "UpdateTime") + private Date updateTime; +} diff --git a/core/src/main/java/info/xiaomo/core/base/BaseModel.kt b/core/src/main/java/info/xiaomo/core/base/BaseModel.kt deleted file mode 100644 index be1c1035..00000000 --- a/core/src/main/java/info/xiaomo/core/base/BaseModel.kt +++ /dev/null @@ -1,49 +0,0 @@ -package info.xiaomo.core.base - -import java.io.Serializable -import java.util.* -import javax.persistence.* - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/4/1 20:37 - * Copyright(©) 2015 by xiaomo. - */ - -@MappedSuperclass -abstract class BaseModel : Serializable { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "Id") - var id: Long? = null - set(id) { - field = this.id - } - - @Column(name = "modelName") - var name: String? = null - set(modelName) { - field = this.name - } - - @Column(name = "CreateTime") - var createTime: Date? = null - set(createTime) { - field = this.createTime - } - - @Column(name = "UpdateTime") - var updateTime: Date? = null - set(updateTime) { - field = this.updateTime - } -} diff --git a/core/src/main/java/info/xiaomo/core/base/BaseService.kt b/core/src/main/java/info/xiaomo/core/base/BaseService.java similarity index 57% rename from core/src/main/java/info/xiaomo/core/base/BaseService.kt rename to core/src/main/java/info/xiaomo/core/base/BaseService.java index d7fea503..4ff3a02f 100644 --- a/core/src/main/java/info/xiaomo/core/base/BaseService.kt +++ b/core/src/main/java/info/xiaomo/core/base/BaseService.java @@ -1,14 +1,16 @@ -package info.xiaomo.core.base +package info.xiaomo.core.base; -import org.springframework.data.domain.Page -import org.springframework.stereotype.Service +import org.springframework.data.domain.Page; +import org.springframework.stereotype.Service; + +import java.util.List; /** - * @author : xiaomo (https://xiaomo.info) (https://github.com/xiaomoinfo) + * @author : xiaomo (https://xiaomo.info) (https://github.com/houko) * @version : 2017/1/11 16:42 */ @Service -interface BaseService { +public interface BaseService { /** * 根据id查 @@ -16,7 +18,7 @@ interface BaseService { * @param id * @return */ - fun findById(id: Long?): T + T findById(Long id); /** * 根据名字查 @@ -24,14 +26,14 @@ fun findById(id: Long?): T * @param name * @return */ - fun findByName(name: String): T + T findByName(String name); /** * 查找所有 * * @return */ - fun findAll(): List + List findAll(); /** * 分页查询 @@ -40,7 +42,7 @@ fun findAll(): List * @param pageSize * @return */ - fun findAll(start: Int, pageSize: Int): Page + Page findAll(int start, int pageSize); /** * 根据id删除 @@ -48,7 +50,7 @@ fun findAll(start: Int, pageSize: Int): Page * @param id * @return */ - fun deleteById(id: Long?): Boolean + boolean deleteById(Long id); /** * 根据名字删除 @@ -56,7 +58,7 @@ fun deleteById(id: Long?): Boolean * @param name * @return */ - fun deleteByName(name: String): Boolean + boolean deleteByName(String name); /** * 增加 @@ -64,7 +66,7 @@ fun deleteByName(name: String): Boolean * @param model * @return */ - fun add(model: T): Boolean + boolean add(T model); /** * 更新 @@ -72,7 +74,7 @@ fun add(model: T): Boolean * @param model * @return */ - fun update(model: T): Boolean + boolean update(T model); /** * 批量删除 @@ -80,5 +82,5 @@ fun update(model: T): Boolean * @param ids * @return */ - fun deleteByIds(ids: List): Boolean + boolean deleteByIds(List ids); } diff --git a/core/src/main/java/info/xiaomo/core/base/Result.kt b/core/src/main/java/info/xiaomo/core/base/Result.java similarity index 56% rename from core/src/main/java/info/xiaomo/core/base/Result.kt rename to core/src/main/java/info/xiaomo/core/base/Result.java index a0b082c2..4ec1cb45 100644 --- a/core/src/main/java/info/xiaomo/core/base/Result.kt +++ b/core/src/main/java/info/xiaomo/core/base/Result.java @@ -1,35 +1,37 @@ -package info.xiaomo.core.base +package info.xiaomo.core.base; + +import lombok.Data; /** * 把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. + * * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info - * + *

* Date: 2016/10/31 15:25 * Description: 返回结果 * Copyright(©) 2015 by xiaomo. */ +@Data +public class Result { -class Result { - - private var resultCode = 200 + private int resultCode = 200; - private var message = "SUCCESS" + private String message = "SUCCESS"; - private var data: T? = null + private T data; /** * 只返回错误码 * * @param resultCode resultCode */ - constructor(resultCode: Int) { - this.resultCode = resultCode + public Result(int resultCode) { + this.resultCode = resultCode; } /** @@ -37,8 +39,8 @@ class Result { * * @param data data */ - constructor(data: T) { - this.data = data + public Result(T data) { + this.data = data; } /** @@ -47,9 +49,9 @@ class Result { * @param resultCode resultCode * @param message message */ - constructor(resultCode: Int, message: String) { - this.resultCode = resultCode - this.message = message + public Result(int resultCode, String message) { + this.resultCode = resultCode; + this.message = message; } @@ -60,9 +62,9 @@ class Result { * @param message message * @param data data */ - constructor(resultCode: Int, message: String, data: T) { - this.resultCode = resultCode - this.message = message - this.data = data + public Result(int resultCode, String message, T data) { + this.resultCode = resultCode; + this.message = message; + this.data = data; } } diff --git a/core/src/main/java/info/xiaomo/core/constant/CodeConst.kt b/core/src/main/java/info/xiaomo/core/constant/CodeConst.java similarity index 52% rename from core/src/main/java/info/xiaomo/core/constant/CodeConst.kt rename to core/src/main/java/info/xiaomo/core/constant/CodeConst.java index 29664e2e..9b411ca5 100644 --- a/core/src/main/java/info/xiaomo/core/constant/CodeConst.kt +++ b/core/src/main/java/info/xiaomo/core/constant/CodeConst.java @@ -1,21 +1,20 @@ -package info.xiaomo.core.constant +package info.xiaomo.core.constant; /** * 把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. + * * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info - * - * + *

* Date: 2016/10/29 10:59 * Description: 错误码 * Copyright(©) 2015 by xiaomo. */ -enum class CodeConst { +public enum CodeConst { /** * success */ @@ -31,19 +30,35 @@ enum class CodeConst { AUTH_FAILED(999, "用户名或密码错误"); - var resultCode: Int = 0 - var message: String? = null + private int resultCode; + private String message; + + CodeConst(int resultCode) { + this.resultCode = resultCode; + } + + CodeConst(String message) { + this.message = message; + } + + CodeConst(int resultCode, String message) { + this.resultCode = resultCode; + this.message = message; + } + + public int getResultCode() { + return resultCode; + } - constructor(resultCode: Int) { - this.resultCode = resultCode + public void setResultCode(int resultCode) { + this.resultCode = resultCode; } - constructor(message: String) { - this.message = message + public String getMessage() { + return message; } - constructor(resultCode: Int, message: String) { - this.resultCode = resultCode - this.message = message + public void setMessage(String message) { + this.message = message; } } diff --git a/core/src/main/java/info/xiaomo/core/constant/FileConst.kt b/core/src/main/java/info/xiaomo/core/constant/FileConst.java similarity index 87% rename from core/src/main/java/info/xiaomo/core/constant/FileConst.kt rename to core/src/main/java/info/xiaomo/core/constant/FileConst.java index 6d105013..c816674f 100644 --- a/core/src/main/java/info/xiaomo/core/constant/FileConst.kt +++ b/core/src/main/java/info/xiaomo/core/constant/FileConst.java @@ -1,16 +1,10 @@ -package info.xiaomo.core.constant +package info.xiaomo.core.constant; /** * @author qq */ -enum class FileConst -/** - * Constructor. - * - * @param value - */ -(value: String) { +public enum FileConst { /** * JEPG. */ @@ -86,8 +80,7 @@ enum class FileConst /** * MS Word/Excel. */ - XLS_DOC("D0CF11E0"), - XLSX_DOCX("504B030414000600080000002100"), + XLS_DOC("D0CF11E0"), XLSX_DOCX("504B030414000600080000002100"), /** * Visio */ @@ -223,11 +216,23 @@ enum class FileConst * FLV. */ FLV("464C5601050000000900"); + private String value = ""; - var value = "" + /** + * Constructor. + * + * @param value + */ + FileConst(String value) { + this.value = value; + } + + public String getValue() { + return value; + } - init { - this.value = value + public void setValue(String value) { + this.value = value; } } \ No newline at end of file diff --git a/core/src/main/java/info/xiaomo/core/constant/GenderConst.kt b/core/src/main/java/info/xiaomo/core/constant/GenderConst.java similarity index 59% rename from core/src/main/java/info/xiaomo/core/constant/GenderConst.kt rename to core/src/main/java/info/xiaomo/core/constant/GenderConst.java index 8c5b2415..05694372 100644 --- a/core/src/main/java/info/xiaomo/core/constant/GenderConst.kt +++ b/core/src/main/java/info/xiaomo/core/constant/GenderConst.java @@ -1,27 +1,25 @@ -package info.xiaomo.core.constant +package info.xiaomo.core.constant; /** * 把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. + * * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info - * + *

* Date: 2016/1/12 16:37 * Description: 性别 * Copyright(©) 2015 by xiaomo. - */ -interface GenderConst { - companion object { + **/ +public interface GenderConst { - val SECRET = 0 + int SECRET = 0; - val MAN = 1 + int MAN = 1; - val WOMAN = 2 - } + int WOMAN = 2; } diff --git a/core/src/main/java/info/xiaomo/core/constant/SymbolConst.java b/core/src/main/java/info/xiaomo/core/constant/SymbolConst.java new file mode 100644 index 00000000..c4dbcfeb --- /dev/null +++ b/core/src/main/java/info/xiaomo/core/constant/SymbolConst.java @@ -0,0 +1,22 @@ +package info.xiaomo.core.constant; + +/** + * @author : xiaomo + */ +public class SymbolConst { + public static final String JINHAO = "#"; + public static final String AND = "&"; + public static final String SHUXIAN = "\\|"; + public static final String JINHAO_TWO = "##"; + public static final String GANTANHAO = "!"; + public static final String FENHAO = ";"; + public static final String HENGXIAN = "-"; + public static final String JINHAO__AND_GANTANHAO = "#!"; + public static final String JINHAO_AND_BAIFENHAO = "#%"; + public static final String DOUHAO = ","; + public static final String DIAN = "."; + public static final String ZHENGXIEXIAN = "/"; + public static final String DENGHAO = "="; + public static final String SPACE = " "; + public static final String AT = "@"; +} diff --git a/core/src/main/java/info/xiaomo/core/constant/SymbolConst.kt b/core/src/main/java/info/xiaomo/core/constant/SymbolConst.kt deleted file mode 100644 index 18183ca3..00000000 --- a/core/src/main/java/info/xiaomo/core/constant/SymbolConst.kt +++ /dev/null @@ -1,22 +0,0 @@ -package info.xiaomo.core.constant - -/** - * @author : xiaomo - */ -object SymbolConst { - val JINHAO = "#" - val AND = "&" - val SHUXIAN = "\\|" - val JINHAO_TWO = "##" - val GANTANHAO = "!" - val FENHAO = ";" - val HENGXIAN = "-" - val JINHAO__AND_GANTANHAO = "#!" - val JINHAO_AND_BAIFENHAO = "#%" - val DOUHAO = "," - val DIAN = "." - val ZHENGXIEXIAN = "/" - val DENGHAO = "=" - val SPACE = " " - val AT = "@" -} diff --git a/core/src/main/java/info/xiaomo/core/exception/UserNotFoundException.kt b/core/src/main/java/info/xiaomo/core/exception/UserNotFoundException.java similarity index 81% rename from core/src/main/java/info/xiaomo/core/exception/UserNotFoundException.kt rename to core/src/main/java/info/xiaomo/core/exception/UserNotFoundException.java index 66c36015..ee06bc04 100644 --- a/core/src/main/java/info/xiaomo/core/exception/UserNotFoundException.kt +++ b/core/src/main/java/info/xiaomo/core/exception/UserNotFoundException.java @@ -1,4 +1,4 @@ -package info.xiaomo.core.exception +package info.xiaomo.core.exception; /** * │\__╭╭╭╭╭__/│ @@ -12,14 +12,16 @@ * |╭---╮把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. + * * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info - * + *

* Date: 16/4/3 11:08 * Description: 找不到用户异常 * Copyright(©) 2015 by xiaomo. */ -class UserNotFoundException : Exception() +public class UserNotFoundException extends Exception { + +} diff --git a/core/src/main/java/info/xiaomo/core/field/LoginField.java b/core/src/main/java/info/xiaomo/core/field/LoginField.java new file mode 100644 index 00000000..e6ea5173 --- /dev/null +++ b/core/src/main/java/info/xiaomo/core/field/LoginField.java @@ -0,0 +1,62 @@ +package info.xiaomo.core.field; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info(83387856) + * Date: 2016/1/8 13:16 + * Description: QQ登录常量类 + * Copyright(©) 2015 by xiaomo. + */ +public interface LoginField { + + String Q_Q_OPEN_ID = "openid"; + String Q_Q_NICKNAME = "nickname"; + String Q_Q_PHOTOURL = "figureurl_qq_2"; + String Q_Q_GENDER = "gender"; + String SINA_NICK_NAME = "screen_name"; + String SINA_OPEN_ID = "id"; + String SINA_HEAD_PHOTO = "avatar_large"; + String GITHUB_NICK_NAME = "name"; + String GITHUB_OPEN_ID = "id"; + String GITHUB_HEAD_PHOTO = "avatar_url"; + String GITHUB_EMAIL = "email"; + String BAIDU_NICK_NAME = "name"; + String BAIDU_OPEN_ID = "id"; + String BAIDU_HEAD_PHOTO = "avatar_url"; + String BAIDU_GENDER = ""; + + String OSC_NICK_NAME = "name"; + String OSC_OPEN_ID = "id"; + String OSC_HEAD_PHOTO = "avatar"; + String OSC_EMAIL = "email"; + String OSC_GENDER = "gender"; + + String RENREN_NICK_NAME = "name"; + String RENREN_OPEN_ID = "id"; + String RENREN_HEAD_PHOTO = "url"; + String RENREN_EMAIL = "email"; + String RENREN_GENDER = "gender"; + String RENREN_PHOTO = "avatar"; + + String ID = "id"; + String PASSWORD = "password"; + String EMAIL = "email"; + String EMAILVERIFY = "emailVerify"; + String SEX = "gender"; + String BIRTHDAY = "birthday"; + String STATUS = "status"; + String LAST_LOGIN_TIME = "lastLoginTime"; + + String TYPE = "type"; + String CONTRIBUTION = "contribution"; + String AUTHORITY = "authority"; + String UPDATETIME = "updateTime"; + String CREATETIME = "createTime"; + String INDEX = "/index.html"; +} diff --git a/core/src/main/java/info/xiaomo/core/field/LoginField.kt b/core/src/main/java/info/xiaomo/core/field/LoginField.kt deleted file mode 100644 index ce517346..00000000 --- a/core/src/main/java/info/xiaomo/core/field/LoginField.kt +++ /dev/null @@ -1,64 +0,0 @@ -package info.xiaomo.core.field - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info(83387856) - * Date: 2016/1/8 13:16 - * Description: QQ登录常量类 - * Copyright(©) 2015 by xiaomo. - */ -interface LoginField { - companion object { - - val Q_Q_OPEN_ID = "openid" - val Q_Q_NICKNAME = "nickname" - val Q_Q_PHOTOURL = "figureurl_qq_2" - val Q_Q_GENDER = "gender" - val SINA_NICK_NAME = "screen_name" - val SINA_OPEN_ID = "id" - val SINA_HEAD_PHOTO = "avatar_large" - val GITHUB_NICK_NAME = "name" - val GITHUB_OPEN_ID = "id" - val GITHUB_HEAD_PHOTO = "avatar_url" - val GITHUB_EMAIL = "email" - val BAIDU_NICK_NAME = "name" - val BAIDU_OPEN_ID = "id" - val BAIDU_HEAD_PHOTO = "avatar_url" - val BAIDU_GENDER = "" - - val OSC_NICK_NAME = "name" - val OSC_OPEN_ID = "id" - val OSC_HEAD_PHOTO = "avatar" - val OSC_EMAIL = "email" - val OSC_GENDER = "gender" - - val RENREN_NICK_NAME = "name" - val RENREN_OPEN_ID = "id" - val RENREN_HEAD_PHOTO = "url" - val RENREN_EMAIL = "email" - val RENREN_GENDER = "gender" - val RENREN_PHOTO = "avatar" - - val ID = "id" - val PASSWORD = "password" - val EMAIL = "email" - val EMAILVERIFY = "emailVerify" - val SEX = "gender" - val BIRTHDAY = "birthday" - val STATUS = "status" - val LAST_LOGIN_TIME = "lastLoginTime" - - val TYPE = "type" - val CONTRIBUTION = "contribution" - val AUTHORITY = "authority" - val UPDATETIME = "updateTime" - val CREATETIME = "createTime" - val INDEX = "/index.html" - } -} diff --git a/core/src/main/java/info/xiaomo/core/filter/CorsFilter.kt b/core/src/main/java/info/xiaomo/core/filter/CorsFilter.java similarity index 51% rename from core/src/main/java/info/xiaomo/core/filter/CorsFilter.kt rename to core/src/main/java/info/xiaomo/core/filter/CorsFilter.java index 976cad33..75ccacf3 100644 --- a/core/src/main/java/info/xiaomo/core/filter/CorsFilter.kt +++ b/core/src/main/java/info/xiaomo/core/filter/CorsFilter.java @@ -1,26 +1,27 @@ -package info.xiaomo.core.filter +package info.xiaomo.core.filter; -import org.springframework.stereotype.Component -import java.io.IOException -import javax.servlet.* -import javax.servlet.http.HttpServletResponse +import org.springframework.stereotype.Component; + +import javax.servlet.*; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; /** * 把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. + * * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info - * + *

* Date: 2016/4/1516:25 * Description: * Copyright(©) 2015 by xiaomo. - */ + **/ @Component -class CorsFilter : Filter { +public class CorsFilter implements Filter { /** @@ -29,8 +30,8 @@ class CorsFilter : Filter { * @param filterConfig filterConfig * @throws ServletException ServletException */ - @Throws(ServletException::class) - override fun init(filterConfig: FilterConfig) { + @Override + public void init(FilterConfig filterConfig) throws ServletException { } @@ -43,19 +44,21 @@ override fun init(filterConfig: FilterConfig) { * @throws IOException IOException * @throws ServletException ServletException */ - @Throws(IOException::class, ServletException::class) - override fun doFilter(req: ServletRequest, res: ServletResponse, chain: FilterChain) { - val response = res as HttpServletResponse - response.setHeader("Access-Control-Allow-Origin", "*") - response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE") - response.setHeader("Access-Control-Max-Age", "3600") - response.setHeader("Access-Control-Allow-Headers", "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, If-Modified-Since") - chain.doFilter(req, res) + @Override + public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { + HttpServletResponse response = (HttpServletResponse) res; + response.setHeader("Access-Control-Allow-Origin", "*"); + response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); + response.setHeader("Access-Control-Max-Age", "3600"); + response.setHeader("Access-Control-Allow-Headers", "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, If-Modified-Since"); + chain.doFilter(req, res); } /** * 销毁对象 */ - override fun destroy() {} + @Override + public void destroy() { + } } diff --git a/core/src/main/java/info/xiaomo/core/filter/CustomDateSerializerFilter.java b/core/src/main/java/info/xiaomo/core/filter/CustomDateSerializerFilter.java new file mode 100644 index 00000000..e46cfb8f --- /dev/null +++ b/core/src/main/java/info/xiaomo/core/filter/CustomDateSerializerFilter.java @@ -0,0 +1,22 @@ +package info.xiaomo.core.filter; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import info.xiaomo.core.untils.TimeUtil; + +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * @author : xiaomo + */ +public class CustomDateSerializerFilter extends JsonSerializer { + + @Override + public void serialize(Date value, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException { + SimpleDateFormat sdf = new SimpleDateFormat(TimeUtil.DEFAULT_FORMAT2); + jsonGenerator.writeString(sdf.format(value)); + } +} \ No newline at end of file diff --git a/core/src/main/java/info/xiaomo/core/filter/CustomDateSerializerFilter.kt b/core/src/main/java/info/xiaomo/core/filter/CustomDateSerializerFilter.kt deleted file mode 100644 index 88be9299..00000000 --- a/core/src/main/java/info/xiaomo/core/filter/CustomDateSerializerFilter.kt +++ /dev/null @@ -1,21 +0,0 @@ -package info.xiaomo.core.filter - -import com.fasterxml.jackson.core.JsonGenerator -import com.fasterxml.jackson.databind.JsonSerializer -import com.fasterxml.jackson.databind.SerializerProvider -import info.xiaomo.core.untils.TimeUtil -import java.io.IOException -import java.text.SimpleDateFormat -import java.util.* - -/** - * @author : xiaomo - */ -class CustomDateSerializerFilter : JsonSerializer() { - - @Throws(IOException::class) - override fun serialize(value: Date, jsonGenerator: JsonGenerator, provider: SerializerProvider) { - val sdf = SimpleDateFormat(TimeUtil.DEFAULT_FORMAT2) - jsonGenerator.writeString(sdf.format(value)) - } -} \ No newline at end of file diff --git a/core/src/main/java/info/xiaomo/core/untils/AuthUtil.java b/core/src/main/java/info/xiaomo/core/untils/AuthUtil.java new file mode 100644 index 00000000..670f0d70 --- /dev/null +++ b/core/src/main/java/info/xiaomo/core/untils/AuthUtil.java @@ -0,0 +1,25 @@ +package info.xiaomo.core.untils; + +import javax.servlet.http.HttpSession; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * @email: xiaomo@xiaomo.info + *

+ * Date: 2016/11/31 9:50 + * Copyright(©) 2015 by xiaomo. + **/ + +public class AuthUtil { + public static boolean isAuthorized(HttpSession session) { + String currentUser = (String) session.getAttribute("currentUser"); + return !(currentUser == null || currentUser.isEmpty()); + } + +} diff --git a/core/src/main/java/info/xiaomo/core/untils/AuthUtil.kt b/core/src/main/java/info/xiaomo/core/untils/AuthUtil.kt deleted file mode 100644 index 57635071..00000000 --- a/core/src/main/java/info/xiaomo/core/untils/AuthUtil.kt +++ /dev/null @@ -1,25 +0,0 @@ -package info.xiaomo.core.untils - -import javax.servlet.http.HttpSession - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * @email: xiaomo@xiaomo.info - * - * Date: 2016/11/31 9:50 - * Copyright(©) 2015 by xiaomo. - */ - -object AuthUtil { - fun isAuthorized(session: HttpSession): Boolean { - val currentUser = session.getAttribute("currentUser") as String - return !(currentUser.isEmpty()) - } - -} diff --git a/core/src/main/java/info/xiaomo/core/untils/CastUtil.java b/core/src/main/java/info/xiaomo/core/untils/CastUtil.java new file mode 100644 index 00000000..a3c19f4c --- /dev/null +++ b/core/src/main/java/info/xiaomo/core/untils/CastUtil.java @@ -0,0 +1,352 @@ +package info.xiaomo.core.untils; + +import java.io.*; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.Iterator; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/11/22 14:55 + * Copyright(©) 2015 by xiaomo. + **/ + +public class CastUtil { + protected static final ByteArrayOutputStream OUT = new ByteArrayOutputStream(); + protected static ObjectOutputStream oos; + + public CastUtil() { + } + + public static int toInteger(Object str) { + return str == null ? 0 : str instanceof Number ? ((Number) str).intValue() : toInteger(str.toString()); + } + + public static double toDouble(Object number) { + if (number == null) { + return 0.0D; + } else if (number instanceof Number) { + return ((Number) number).doubleValue(); + } else if (number instanceof String) { + String str = (String) number; + return isNumeric(str) > 0 ? Double.valueOf(str) : 0.0D; + } else { + return 0.0D; + } + } + + public static long toLong(Object number) { + if (number == null) { + return 0L; + } else if (number instanceof Number) { + return ((Number) number).longValue(); + } else if (number instanceof String) { + String str = (String) number; + int isNumber = isNumeric(str); + return isNumber == 1 ? Long.parseLong(str) : (isNumber == 2 ? Double.valueOf(str).longValue() : 0L); + } else { + return 0L; + } + } + + public static int toInteger(String str) { + if (str == null) { + return 0; + } else { + str = str.trim(); + if (str.length() == 0) { + return 0; + } else { + int i = isNumeric(str); + return i == 1 ? Integer.parseInt(str) : (i == 2 ? Double.valueOf(str).intValue() : 0); + } + } + } + + public static int isNumeric(String str) { + if (str == null) { + return 0; + } else { + boolean isdouble = false; + boolean hasE = false; + int i = str.length(); + + while (true) { + while (true) { + char c; + do { + --i; + if (i < 0) { + if (isdouble) { + return 2; + } + + return 1; + } + + c = str.charAt(i); + } while (i == 0 && c == 45); + + if (c == 46) { + if (isdouble) { + return 0; + } + + isdouble = true; + } else if (c != 69 && c != 101) { + if (!Character.isDigit(str.charAt(i))) { + return 0; + } + } else { + if (hasE) { + return 0; + } + + hasE = true; + } + } + } + } + } + + public static HashMap copyMap(HashMap map) { + HashMap newmap = new HashMap<>(10); + + for (Object key : map.keySet()) { + newmap.put(key, map.get(key)); + } + + return newmap; + } + + public static void destroy(Hashtable map) { + for (Iterator it = map.keySet().iterator(); it.hasNext(); it.remove()) { + Object key = it.next(); + Object value = map.get(key); + if (value instanceof HashMap) { + HashMap valueMap = (HashMap) value; + destroy(valueMap); + } + } + + } + + public static void destroy(HashMap map) { + for (Iterator keyit = map.keySet().iterator(); keyit.hasNext(); keyit.remove()) { + Object key = keyit.next(); + Object value = map.get(key); + if (value instanceof HashMap) { + HashMap valueMap = (HashMap) value; + destroy(valueMap); + } + } + + } + + public static String objectToString(Object obj) { + if (obj.getClass().equals(String.class)) { + return obj.toString(); + } else { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + try { + ObjectOutputStream e = new ObjectOutputStream(out); + e.writeObject(obj); + byte[] bytes = out.toByteArray(); + return new String(bytes, StandardCharsets.ISO_8859_1); + } catch (IOException var4) { + var4.printStackTrace(); + return null; + } + } + } + + public static Object stringToObject(String string) { + try { + byte[] e = string.getBytes(StandardCharsets.ISO_8859_1); + ByteArrayInputStream in = new ByteArrayInputStream(e); + ObjectInputStream ois = new ObjectInputStream(in); + return ois.readObject(); + } catch (IOException | ClassNotFoundException var4) { + var4.printStackTrace(); + } + + return null; + } + + public static int bytesToInt(byte[] bytes) { + byte length = 4; + int intValue = 0; + + for (int i = length - 1; i >= 0; --i) { + int offset = i * 8; + intValue |= (bytes[i] & 255) << offset; + } + + return intValue; + } + + public static Object bytesToObject(byte[] bytes) { + try { + ByteArrayInputStream e = new ByteArrayInputStream(bytes); + ObjectInputStream ois = new ObjectInputStream(e); + return ois.readObject(); + } catch (IOException | ClassNotFoundException var3) { + var3.printStackTrace(); + } + + return null; + } + + public static byte[] objectToBytes(Object obj) throws IOException { + OUT.reset(); + + byte[] var2; + try { + if (oos == null) { + oos = new ObjectOutputStream(OUT); + } else { + oos.reset(); + } + + oos.writeObject(obj); + var2 = OUT.toByteArray(); + } finally { + OUT.close(); + } + + return var2; + } + + public static byte[] stringToBytes(String str) { + StringBuffer sb = new StringBuffer(str); + char c = sb.charAt(0); + ByteBuffer buffer = ByteBuffer.allocate(sb.length() * 2); + int index = 0; + + while (index < sb.length()) { + buffer.putChar(sb.charAt(index++)); + } + + return buffer.array(); + } + + public static String bytesToString(byte[] bytes) { + ByteBuffer buffer = ByteBuffer.wrap(bytes); + StringBuffer sb = new StringBuffer(); + + while (buffer.hasRemaining()) { + sb.append(buffer.getChar()); + } + + return sb.toString(); + } + + public static long combineInt2Long(int low, int high) { + return (long) low & 4294967295L | (long) high << 32 & -4294967296L; + } + + public static int[] separateLong2int(Long val) { + return new int[]{(int) (4294967295L & val), (int) ((-4294967296L & val) >> 32)}; + } + + public static int getLongLowInt(Long val) { + return val == null ? 0 : (int) (4294967295L & val); + } + + public static int getLongHighInt(Long val) { + return val == null ? 0 : (int) ((-4294967296L & val) >> 32); + } + + public static boolean isIntInList(int i, int[] list) { + for (int aList : list) { + if (aList == i) { + return true; + } + } + + return false; + } + + public static int[] stringToInts(String str, String regex) { + String[] arr = str.split(regex); + int length = arr.length; + int[] ret = new int[length]; + + for (int i = 0; i < length; ++i) { + ret[i] = toInteger(arr[i]); + } + + return ret; + } + + public static String bytesToHexString(byte[] src) { + StringBuilder stringBuilder = new StringBuilder(); + if (src != null && src.length > 0) { + for (byte aSrc : src) { + int v = aSrc & 255; + String hv = Integer.toHexString(v); + if (hv.length() < 2) { + stringBuilder.append(0); + } + + stringBuilder.append(hv); + } + + return stringBuilder.toString(); + } else { + return null; + } + } + + public static byte[] hexStringToBytes(String hexString) { + if (hexString != null && !"".equals(hexString)) { + 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; + } else { + return null; + } + } + + public static double strToDouble(String str) { + if (str != null && !str.isEmpty()) { + int len = str.length(); + int p = str.indexOf(37); + return p == len - 1 ? Double.valueOf(str.substring(0, len - 1)) / 100.0D : (p > -1 ? 0.0D : ("true".equals(str) ? 1.0D : toDouble(str))); + } else { + return 0.0D; + } + } + + private static byte charToByte(char c) { + return (byte) "0123456789ABCDEF".indexOf(c); + } + + public static String cacheString(int i) { + return String.valueOf(i); + } + + public static void main(String[] args) { + System.out.println(toInteger("2.147483647E9")); + } + +} diff --git a/core/src/main/java/info/xiaomo/core/untils/CastUtil.kt b/core/src/main/java/info/xiaomo/core/untils/CastUtil.kt deleted file mode 100644 index d89a2a9e..00000000 --- a/core/src/main/java/info/xiaomo/core/untils/CastUtil.kt +++ /dev/null @@ -1,290 +0,0 @@ -package info.xiaomo.core.untils - -import java.io.* -import java.nio.ByteBuffer -import java.util.* - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/11/22 14:55 - * Copyright(©) 2015 by xiaomo. - */ - -class CastUtil { - companion object { - protected val OUT = ByteArrayOutputStream() - protected var oos: ObjectOutputStream? = null - - fun toInteger(str: Any?): Int { - return if (str == null) 0 else (str as? Number)?.toInt() ?: toInteger(str.toString()) - } - - fun toDouble(number: Any?): Double { - if (number == null) { - return 0.0 - } else if (number is Number) { - return number.toDouble() - } else if (number is String) { - val str = number as String? - return if (isNumeric(str) > 0) java.lang.Double.valueOf(str!!) else 0.0 - } else { - return 0.0 - } - } - - fun toLong(number: Any?): Long { - if (number == null) { - return 0L - } else if (number is Number) { - return number.toLong() - } else if (number is String) { - val str = number as String? - val isNumber = isNumeric(str) - return if (isNumber == 1) java.lang.Long.parseLong(str!!) else if (isNumber == 2) java.lang.Double.valueOf(str!!).toLong() else 0L - } else { - return 0L - } - } - - fun toInteger(str: String?): Int { - var str = str - if (str == null) { - return 0 - } else { - str = str.trim { it <= ' ' } - if (str.length == 0) { - return 0 - } else { - val i = isNumeric(str) - return if (i == 1) Integer.parseInt(str) else if (i == 2) java.lang.Double.valueOf(str).toInt() else 0 - } - } - } - - fun isNumeric(str: String?): Int { - if (str == null) { - return 0 - } else { - var isdouble = false - var hasE = false - var i = str.length - - while (true) { - while (true) { - var c: Char - do { - --i - if (i < 0) { - return if (isdouble) { - 2 - } else 1 - - } - - c = str[i] - } while (i == 0 && c.toInt() == 45) - - if (c.toInt() == 46) { - if (isdouble) { - return 0 - } - - isdouble = true - } else if (c.toInt() != 69 && c.toInt() != 101) { - if (!Character.isDigit(str[i])) { - return 0 - } - } else { - if (hasE) { - return 0 - } - - hasE = true - } - } - } - } - } - - fun copyMap(map: HashMap<*, *>): HashMap<*, *> { - val newmap = HashMap(10) - - for (key in map.keys) { - newmap.put(key, map.get(key)!!) - } - - return newmap - } - - fun destroy(map: Hashtable<*, *>) { - val it = map.keys.iterator() - while (it.hasNext()) { - val key = it.next() - val value = map[key] - if (value is HashMap<*, *>) { - destroy(value) - } - it.remove() - } - - } - - fun destroy(map: HashMap<*, *>) { - val keyit = map.keys.iterator() - while (keyit.hasNext()) { - val key = keyit.next() - val value = map[key] - if (value is HashMap<*, *>) { - destroy(value) - } - keyit.remove() - } - - } - - fun objectToString(obj: Any): String? { - if (obj.javaClass == String::class.java) { - return obj.toString() - } else { - val out = ByteArrayOutputStream() - - try { - val e = ObjectOutputStream(out) - e.writeObject(obj) - val bytes = out.toByteArray() - return String(bytes) - } catch (var4: IOException) { - var4.printStackTrace() - return null - } - - } - } - - fun stringToObject(string: String): Any? { - try { - val e = string.toByteArray(charset("ISO-8859-1")) - val `in` = ByteArrayInputStream(e) - val ois = ObjectInputStream(`in`) - return ois.readObject() - } catch (var4: IOException) { - var4.printStackTrace() - } catch (var4: ClassNotFoundException) { - var4.printStackTrace() - } - - return null - } - - fun bytesToObject(bytes: ByteArray): Any? { - try { - val e = ByteArrayInputStream(bytes) - val ois = ObjectInputStream(e) - return ois.readObject() - } catch (var3: IOException) { - var3.printStackTrace() - } catch (var3: ClassNotFoundException) { - var3.printStackTrace() - } - - return null - } - - @Throws(IOException::class) - fun objectToBytes(obj: Any): ByteArray { - OUT.reset() - - val var2: ByteArray - try { - if (oos == null) { - oos = ObjectOutputStream(OUT) - } else { - oos!!.reset() - } - - oos!!.writeObject(obj) - var2 = OUT.toByteArray() - } finally { - OUT.close() - } - - return var2 - } - - fun stringToBytes(str: String): ByteArray { - val sb = StringBuffer(str) - val c = sb[0] - val buffer = ByteBuffer.allocate(sb.length * 2) - var index = 0 - - while (index < sb.length) { - buffer.putChar(sb[index++]) - } - - return buffer.array() - } - - fun bytesToString(bytes: ByteArray): String { - val buffer = ByteBuffer.wrap(bytes) - val sb = StringBuffer() - - while (buffer.hasRemaining()) { - sb.append(buffer.char) - } - - return sb.toString() - } - - fun combineInt2Long(low: Int, high: Int): Long { - return low.toLong() and 4294967295L or (high.toLong() shl 32 and -4294967296L) - } - - fun getLongLowInt(`val`: Long?): Int { - return if (`val` == null) 0 else (4294967295L and `val`).toInt() - } - - fun getLongHighInt(`val`: Long?): Int { - return if (`val` == null) 0 else (-4294967296L and `val` shr 32).toInt() - } - - fun isIntInList(i: Int, list: IntArray): Boolean { - for (aList in list) { - if (aList == i) { - return true - } - } - - return false - } - - fun stringToInts(str: String, regex: String): IntArray { - val arr = str.split(regex.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() - val length = arr.size - val ret = IntArray(length) - - for (i in 0 until length) { - ret[i] = toInteger(arr[i]) - } - - return ret - } - - fun cacheString(i: Int): String { - return i.toString() - } - - @JvmStatic - fun main(args: Array) { - println(toInteger("2.147483647E9")) - } - } - -} diff --git a/core/src/main/java/info/xiaomo/core/untils/CharUtil.java b/core/src/main/java/info/xiaomo/core/untils/CharUtil.java new file mode 100644 index 00000000..17b3e973 --- /dev/null +++ b/core/src/main/java/info/xiaomo/core/untils/CharUtil.java @@ -0,0 +1,181 @@ +package info.xiaomo.core.untils; + +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; +import java.util.Objects; + +/** + *

Title:字符编码工具类

+ * + * @author : xiaomo + * @version 1.0 + */ +public class CharUtil { + + /** + * 转换编码 ISO-8859-1到GB2312 + */ + public static String iso2gb(String text) { + String result; + try { + result = new String(text.getBytes(StandardCharsets.ISO_8859_1), "GB2312"); + } catch (UnsupportedEncodingException ex) { + result = ex.toString(); + } + return result; + } + + /** + * 转换编码 GB2312到ISO-8859-1 + */ + public static String gb2iso(String text) { + String result = ""; + try { + result = new String(text.getBytes("GB2312"), StandardCharsets.ISO_8859_1); + } catch (UnsupportedEncodingException ex) { + ex.printStackTrace(); + } + return result; + } + + /** + * Utf8URL编码 + */ + public static String utf8urlencode(String text) { + StringBuilder result = new StringBuilder(); + for (int i = 0; i < text.length(); i++) { + + char c = text.charAt(i); + if (c <= 255) { + result.append(c); + } else { + + byte[] b = new byte[0]; + try { + b = Character.toString(c).getBytes(StandardCharsets.UTF_8); + } catch (Exception ignored) { + } + + for (byte aB : b) { + int k = aB; + if (k < 0) { + k += 256; + } + result.append("%").append(Integer.toHexString(k).toUpperCase()); + } + + } + } + return result.toString(); + } + + /** + * Utf8URL解码 + */ + public static String utf8urldecode(String text) { + StringBuilder result = new StringBuilder(); + int p; + if (text != null && text.length() > 0) { + text = text.toLowerCase(); + p = text.indexOf("%e"); + if (p == -1) { + return text; + } + while (p != -1) { + result.append(text, 0, p); + text = text.substring(p); + if (Objects.equals(text, "") || text.length() < 9) { + return result.toString(); + } + result.append(codetoword(text.substring(0, 9))); + text = text.substring(9); + p = text.indexOf("%e"); + } + } + return result + text; + } + + /** + * utf8URL编码转字符 + */ + private static String codetoword(String text) { + String result; + if (utf8codecheck(text)) { + byte[] code = new byte[3]; + code[0] = (byte) (Integer.parseInt(text.substring(1, 3), 16) - 256); + code[1] = (byte) (Integer.parseInt(text.substring(4, 6), 16) - 256); + code[2] = (byte) (Integer.parseInt(text.substring(7, 9), 16) - 256); + result = new String(code, StandardCharsets.UTF_8); + } else { + result = text; + } + return result; + } + + /** + * 编码是否有效 + */ + private static boolean utf8codecheck(String text) { + String sign = ""; + String prefix = "%e"; + if (text.startsWith(prefix)) { + for (int p = 0; p != -1; ) { + p = text.indexOf("%", p); + if (p != -1) { + p++; + } + sign += p; + } + } + return "147-1".equals(sign); + } + + /** + * 判断是否Utf8Url编码 + */ + public static boolean isUtf8Url(String text) { + text = text.toLowerCase(); + int p = text.indexOf("%"); + int nine = 9; + if (p != -1 && text.length() - p > nine) { + text = text.substring(p, p + nine); + } + return utf8codecheck(text); + } + + /** + * 进行字符规格化(全角转半角,大写转小写处理) + * + * @return char + */ + public static char regularize(char input) { + if (input == 12288) { + input = (char) 32; + } else if (input > 65280 && input < 65375) { + input = (char) (input - 65248); + } else { + char a = 'A'; + char z = 'Z'; + if (input >= a && input <= z) { + input += 32; + } + } + return input; + } + + public static void main(String[] args) { + String url; + System.out.println(utf8urlencode("小莫")); + System.out.println(iso2gb("小莫")); + System.out.println(gb2iso("小莫")); + url = "http://www.google.com/search?hl=zh-CN&newwindow=1&q=%E4%B8%AD%E5%9B%BD%E5%A4%A7%E7%99%BE%E7%A7%91%E5%9C%A8%E7%BA%BF%E5%85%A8%E6%96%87%E6%A3%80%E7%B4%A2&btnG=%E6%90%9C%E7%B4%A2&lr="; + if (CharUtil.isUtf8Url(url)) { + System.out.println(CharUtil.utf8urldecode(url)); + } + url = "http://www.baidu.com/baidu?word=%D6%D0%B9%FA%B4%F3%B0%D9%BF%C6%D4%DA%CF%DF%C8%AB%CE%C4%BC%EC%CB%F7&tn=myie2dg"; + if (CharUtil.isUtf8Url(url)) { + System.out.println(CharUtil.utf8urldecode(url)); + } + } + +} diff --git a/core/src/main/java/info/xiaomo/core/untils/CharUtil.kt b/core/src/main/java/info/xiaomo/core/untils/CharUtil.kt deleted file mode 100644 index a2070ab2..00000000 --- a/core/src/main/java/info/xiaomo/core/untils/CharUtil.kt +++ /dev/null @@ -1,191 +0,0 @@ -package info.xiaomo.core.untils - -import java.io.UnsupportedEncodingException - -/** - * - * Title:字符编码工具类 - * - * @author : xiaomo - * @version 1.0 - */ -object CharUtil { - - /** - * 转换编码 ISO-8859-1到GB2312 - */ - fun iso2gb(text: String): String { - var result: String - try { - result = String(text.toByteArray(charset("ISO-8859-1"))) - } catch (ex: UnsupportedEncodingException) { - result = ex.toString() - } - - return result - } - - /** - * 转换编码 GB2312到ISO-8859-1 - */ - fun gb2iso(text: String): String { - var result = "" - try { - result = String(text.toByteArray(charset("GB2312"))) - } catch (ex: UnsupportedEncodingException) { - ex.printStackTrace() - } - - return result - } - - /** - * Utf8URL编码 - */ - fun utf8urlencode(text: String): String { - val result = StringBuilder() - for (i in 0 until text.length) { - - val c = text[i] - if (c.toInt() <= 255) { - result.append(c) - } else { - - var b = ByteArray(0) - try { - b = Character.toString(c).toByteArray(charset("UTF-8")) - } catch (ignored: Exception) { - } - - for (aB in b) { - var k = aB.toInt() - if (k < 0) { - k += 256 - } - result.append("%").append(Integer.toHexString(k).toUpperCase()) - } - - } - } - return result.toString() - } - - /** - * Utf8URL解码 - */ - fun utf8urldecode(text: String?): String { - var text = text - var result = "" - var p: Int - if (text != null && text.length > 0) { - text = text.toLowerCase() - p = text.indexOf("%e") - if (p == -1) { - return text - } - while (p != -1) { - result += text!!.substring(0, p) - text = text.substring(p, text.length) - if (text == "" || text.length < 9) { - return result - } - result += codetoword(text.substring(0, 9)) - text = text.substring(9, text.length) - p = text.indexOf("%e") - } - } - return result + text!! - } - - /** - * utf8URL编码转字符 - */ - private fun codetoword(text: String): String? { - var result: String? - if (utf8codecheck(text)) { - val code = ByteArray(3) - code[0] = (Integer.parseInt(text.substring(1, 3), 16) - 256).toByte() - code[1] = (Integer.parseInt(text.substring(4, 6), 16) - 256).toByte() - code[2] = (Integer.parseInt(text.substring(7, 9), 16) - 256).toByte() - try { - result = String(code) - } catch (ex: UnsupportedEncodingException) { - result = null - } - - } else { - result = text - } - return result - } - - /** - * 编码是否有效 - */ - private fun utf8codecheck(text: String): Boolean { - var sign = "" - val prefix = "%e" - if (text.startsWith(prefix)) { - var p = 0 - while (p != -1) { - p = text.indexOf("%", p) - if (p != -1) { - p++ - } - sign += p - } - } - return "147-1" == sign - } - - /** - * 判断是否Utf8Url编码 - */ - fun isUtf8Url(text: String): Boolean { - var text = text - text = text.toLowerCase() - val p = text.indexOf("%") - val nine = 9 - if (p != -1 && text.length - p > nine) { - text = text.substring(p, p + nine) - } - return utf8codecheck(text) - } - - /** - * 进行字符规格化(全角转半角,大写转小写处理) - * - * @return char - */ - fun regularize(input: Char): Char { - var input = input - if (input.toInt() == 12288) { - input = 32.toChar() - } else if (input.toInt() > 65280 && input.toInt() < 65375) { - input = (input.toInt() - 65248).toChar() - } else { - val a = 'A' - val z = 'Z' - if (input >= a && input <= z) { - input += 32.toChar().toInt() - } - } - return input - } - - @JvmStatic - fun main(args: Array) { - var url = "http://www.google.com/search?hl=zh-CN&newwindow=1&q=%E4%B8%AD%E5%9B%BD%E5%A4%A7%E7%99%BE%E7%A7%91%E5%9C%A8%E7%BA%BF%E5%85%A8%E6%96%87%E6%A3%80%E7%B4%A2&btnG=%E6%90%9C%E7%B4%A2&lr=" - println(utf8urlencode("小莫")) - println(iso2gb("小莫")) - println(gb2iso("小莫")) - if (CharUtil.isUtf8Url(url)) { - println(CharUtil.utf8urldecode(url)) - } - url = "http://www.baidu.com/baidu?word=%D6%D0%B9%FA%B4%F3%B0%D9%BF%C6%D4%DA%CF%DF%C8%AB%CE%C4%BC%EC%CB%F7&tn=myie2dg" - if (CharUtil.isUtf8Url(url)) { - println(CharUtil.utf8urldecode(url)) - } - } - -} diff --git a/core/src/main/java/info/xiaomo/core/untils/DownUtil.java b/core/src/main/java/info/xiaomo/core/untils/DownUtil.java new file mode 100644 index 00000000..3f6d64e0 --- /dev/null +++ b/core/src/main/java/info/xiaomo/core/untils/DownUtil.java @@ -0,0 +1,83 @@ +package info.xiaomo.core.untils; + +import lombok.extern.slf4j.Slf4j; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URL; +import java.net.URLConnection; + +/** + * @author : xiaomo (https://xiaomo.info) (https://github.com/houko) + * @created : 2016/12/26 13:25 + */ +@Slf4j +public class DownUtil { + + public static void download(String urlString) throws Exception { + File file = new File(urlString); + String filename = file.getName(); + // 构造URL + URL url = new URL(urlString); + // 打开连接 + URLConnection con = url.openConnection(); + // 输入流 + InputStream is = con.getInputStream(); + // 1K的数据缓冲 + byte[] bs = new byte[1024]; + // 读取到的数据长度 + int len; + // 输出的文件流 + OutputStream os = new FileOutputStream(filename); + // 开始读取 + while ((len = is.read(bs)) != -1) { + os.write(bs, 0, len); + } + // 完毕,关闭所有链接 + os.close(); + is.close(); + } + + + /** + * 下载图片 + * + * @param urlString url + * @param filePath 存储路径 D:\MIR\config\data\ + */ + public static void download(String urlString, String filePath) throws Exception { + File file = new File(urlString); + String filename = file.getName(); + // 构造URL + URL url = new URL(urlString); + // 打开连接 + URLConnection con = url.openConnection(); + // 输入流 + InputStream is = con.getInputStream(); + // 1K的数据缓冲 + byte[] bs = new byte[1024]; + // 读取到的数据长度 + int len; + // 输出的文件流 + + File output = new File(filePath); + if (!output.exists()) { + boolean res = output.mkdir(); + if (res) { + log.debug("{} 目录创建成功", filePath); + } + } + + OutputStream os = new FileOutputStream(filePath + filename); + // 开始读取 + while ((len = is.read(bs)) != -1) { + os.write(bs, 0, len); + } + // 完毕,关闭所有链接 + os.close(); + is.close(); + } + +} diff --git a/core/src/main/java/info/xiaomo/core/untils/DownUtil.kt b/core/src/main/java/info/xiaomo/core/untils/DownUtil.kt deleted file mode 100644 index 549042d3..00000000 --- a/core/src/main/java/info/xiaomo/core/untils/DownUtil.kt +++ /dev/null @@ -1,79 +0,0 @@ -package info.xiaomo.core.untils - -import java.io.File -import java.io.FileOutputStream -import java.net.URL - -/** - * @author : xiaomo (https://xiaomo.info) (https://github.com/xiaomoinfo) - * @created : 2016/12/26 13:25 - */ -object DownUtil { - - @Throws(Exception::class) - fun download(urlString: String) { - val file = File(urlString) - val filename = file.name - // 构造URL - val url = URL(urlString) - // 打开连接 - val con = url.openConnection() - // 输入流 - val `is` = con.getInputStream() - // 1K的数据缓冲 - val bs = ByteArray(1024) - // 读取到的数据长度 - val len = 0 - // 输出的文件流 - val os = FileOutputStream(filename) - // 开始读取 - while ((`is`.read(bs)) != -1) { - os.write(bs, 0, len) - } - // 完毕,关闭所有链接 - os.close() - `is`.close() - } - - - /** - * 下载图片 - * - * @param urlString url - * @param filePath 存储路径 D:\MIR\config\data\ - */ - @Throws(Exception::class) - fun download(urlString: String, filePath: String) { - val file = File(urlString) - val filename = file.name - // 构造URL - val url = URL(urlString) - // 打开连接 - val con = url.openConnection() - // 输入流 - val `is` = con.getInputStream() - // 1K的数据缓冲 - val bs = ByteArray(1024) - // 读取到的数据长度 - var len = 0 - // 输出的文件流 - - val output = File(filePath) - if (!output.exists()) { - val res = output.mkdir() - if (res) { - println("目录创建成功" + filePath) - } - } - - val os = FileOutputStream(filePath + filename) - // 开始读取 - while ((`is`.read(bs)) != -1) { - os.write(bs, 0, len) - } - // 完毕,关闭所有链接 - os.close() - `is`.close() - } - -} diff --git a/core/src/main/java/info/xiaomo/core/untils/ExcelUtil.java b/core/src/main/java/info/xiaomo/core/untils/ExcelUtil.java new file mode 100644 index 00000000..9a1738e3 --- /dev/null +++ b/core/src/main/java/info/xiaomo/core/untils/ExcelUtil.java @@ -0,0 +1,163 @@ +package info.xiaomo.core.untils; + +import org.apache.poi.hssf.usermodel.*; +import org.apache.poi.poifs.filesystem.POIFSFileSystem; + +import java.io.*; +import java.text.DecimalFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.List; + +/** + * @author : xiaomo + */ +public class ExcelUtil { +// +// public static void main(String[] args) throws Exception { +// List> listData = getListData("E:\\thinkpage_cities.xls", 1); +// List list = new ArrayList<>(); +// for (List listDatum : listData) { +// CountryModel model = new CountryModel(); +// model.setCityName(listDatum.get(0)); +// model.setCityNameEN(listDatum.get(1)); +// list.add(model); +// } +// System.out.println(list); +// } + + public static List> getListData(String path, int ignoreRows) throws IOException { + File file = new File(path); + String[][] result = getData(file, ignoreRows); + List> lists = new ArrayList<>(); + for (String[] aResult : result) { + List list = new ArrayList<>(); + for (String anAResult : aResult) { + if (!"".equals(anAResult)) { + list.add(anAResult); + } + } + lists.add(list); + } + return lists; + } + + /** + * 读取Excel的内容,第一维数组存储的是一行中格列的值,二维数组存储的是多少个行 + * + * @param file 读取数据的源Excel + * @param ignoreRows 读取数据忽略的行数,比喻行头不需要读入 忽略的行数为1 + * @return 读出的Excel中数据的内容 + * @throws FileNotFoundException + * @throws IOException + */ + private static String[][] getData(File file, int ignoreRows) + throws IOException { + List result = new ArrayList<>(); + int rowSize = 0; + BufferedInputStream in = new BufferedInputStream(new FileInputStream( + file)); + // 打开HSSFWorkbook + POIFSFileSystem fs = new POIFSFileSystem(in); + HSSFWorkbook wb = new HSSFWorkbook(fs); + HSSFCell cell; + for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) { + HSSFSheet st = wb.getSheetAt(sheetIndex); + // 第一行为标题,不取 + for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) { + HSSFRow row = st.getRow(rowIndex); + if (row == null) { + continue; + } + int tempRowSize = row.getLastCellNum() + 1; + if (tempRowSize > rowSize) { + rowSize = tempRowSize; + } + String[] values = new String[rowSize]; + Arrays.fill(values, ""); + boolean hasValue = false; + for (int columnIndex = 0; columnIndex <= row.getLastCellNum(); columnIndex++) { + String value = ""; + cell = row.getCell(columnIndex); + if (cell != null) { + switch (cell.getCellType()) { + case HSSFCell.CELL_TYPE_STRING: + value = cell.getStringCellValue(); + break; + case HSSFCell.CELL_TYPE_NUMERIC: + if (HSSFDateUtil.isCellDateFormatted(cell)) { + Date date = cell.getDateCellValue(); + if (date != null) { + value = new SimpleDateFormat("yyyy-MM-dd") + .format(date); + } else { + value = ""; + } + } else { + value = new DecimalFormat("0").format(cell + .getNumericCellValue()); + } + break; + case HSSFCell.CELL_TYPE_FORMULA: + // 导入时如果为公式生成的数据则无值 + if (!"".equals(cell.getStringCellValue())) { + value = cell.getStringCellValue(); + } else { + value = cell.getNumericCellValue() + ""; + } + break; + case HSSFCell.CELL_TYPE_BLANK: + break; + case HSSFCell.CELL_TYPE_ERROR: + value = ""; + break; + case HSSFCell.CELL_TYPE_BOOLEAN: + value = (cell.getBooleanCellValue() ? "Y" + : "N"); + break; + default: + value = ""; + } + } + if (columnIndex == 0 && "".equals(value.trim())) { + break; + } + values[columnIndex] = rightTrim(value); + hasValue = true; + } + + if (hasValue) { + result.add(values); + } + } + } + in.close(); + String[][] returnArray = new String[result.size()][rowSize]; + for (int i = 0; i < returnArray.length; i++) { + returnArray[i] = result.get(i); + } + return returnArray; + } + + /** + * 去掉字符串右边的空格 + * + * @param str 要处理的字符串 + * @return 处理后的字符串 + */ + public static String rightTrim(String str) { + if (str == null) { + return ""; + } + int length = str.length(); + for (int i = length - 1; i >= 0; i--) { + if (str.charAt(i) != 0x20) { + break; + } + length--; + } + return str.substring(0, length); + } +} \ No newline at end of file diff --git a/core/src/main/java/info/xiaomo/core/untils/FileUtil.java b/core/src/main/java/info/xiaomo/core/untils/FileUtil.java new file mode 100644 index 00000000..d0297bf5 --- /dev/null +++ b/core/src/main/java/info/xiaomo/core/untils/FileUtil.java @@ -0,0 +1,844 @@ +package info.xiaomo.core.untils; + +import info.xiaomo.core.constant.FileConst; +import info.xiaomo.core.constant.SymbolConst; +import org.springframework.web.multipart.MultipartFile; + +import java.io.*; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +/** + * 此类中封装一些常用的文件操作。 + * 所有方法都是静态方法,不需要生成此类的实例, + * 为避免生成此类的实例,构造方法被申明为private类型的。 + * + * @author : xiaomo + * @since 1.0 + */ + +public class FileUtil { + /** + * Buffer size when reading from input stream. + * + * @since ostermillerutils 1.00.00 + */ + private final static int BUFFER_SIZE = 1024; + + + /** + * 私有构造方法,防止类的实例化,因为工具类不需要实例化。 + */ + private FileUtil() { + + } + + /** + * 修改文件的最后访问时间。 + * 如果文件不存在则创建该文件。 + * 目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考虑中。 + * + * @param file 需要修改最后访问时间的文件。 + * @since 1.0 + */ + public static void touch(File file) { + long currentTime = System.currentTimeMillis(); + if (!file.exists()) { + System.err.println("file not found:" + file.getName()); + System.err.println("Create a new file:" + file.getName()); + try { + if (file.createNewFile()) { + System.out.println("Succeeded!"); + } else { + System.err.println("Create file failed!"); + } + } catch (IOException e) { + System.err.println("Create file failed!"); + e.printStackTrace(); + } + } + boolean result = file.setLastModified(currentTime); + if (!result) { + System.err.println("touch failed: " + file.getName()); + } + } + + /** + * 修改文件的最后访问时间。 + * 如果文件不存在则创建该文件。 + * 目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考虑中。 + * + * @param fileName 需要修改最后访问时间的文件的文件名。 + * @since 1.0 + */ + public static void touch(String fileName) { + File file = new File(fileName); + touch(file); + } + + /** + * 修改文件的最后访问时间。 + * 如果文件不存在则创建该文件。 + * 目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考虑中。 + * + * @param files 需要修改最后访问时间的文件数组。 + * @since 1.0 + */ + public static void touch(File[] files) { + for (File file : files) { + touch(file); + } + } + + /** + * 修改文件的最后访问时间。 + * 如果文件不存在则创建该文件。 + * 目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考虑中。 + * + * @param fileNames 需要修改最后访问时间的文件名数组。 + * @since 1.0 + */ + public static void touch(String[] fileNames) { + File[] files = new File[fileNames.length]; + for (int i = 0; i < fileNames.length; i++) { + files[i] = new File(fileNames[i]); + } + touch(files); + } + + /** + * 判断指定的文件是否存在。 + * + * @param fileName 要判断的文件的文件名 + * @return 存在时返回true,否则返回false。 + * @since 1.0 + */ + public static boolean isFileExist(String fileName) { + return new File(fileName).isFile(); + } + + /** + * 创建指定的目录。 + * 如果指定的目录的父目录不存在则创建其目录书上所有需要的父目录。 + * 注意:可能会在返回false的时候创建部分父目录。 + * + * @param file 要创建的目录 + * @return 完全创建成功时返回true,否则返回false。 + * @since 1.0 + */ + public static boolean makeDirectory(File file) { + File parent = file.getParentFile(); + return parent != null && parent.mkdirs(); + } + + /** + * 创建指定的目录。 + * 如果指定的目录的父目录不存在则创建其目录书上所有需要的父目录。 + * 注意:可能会在返回false的时候创建部分父目录。 + * + * @param fileName 要创建的目录的目录名 + * @return 完全创建成功时返回true,否则返回false。 + * @since 1.0 + */ + public static boolean makeDirectory(String fileName) { + File file = new File(fileName); + return makeDirectory(file); + } + + /** + * 清空指定目录中的文件。 + * 这个方法将尽可能删除所有的文件,但是只要有一个文件没有被删除都会返回false。 + * 另外这个方法不会迭代删除,即不会删除子目录及其内容。 + * + * @param directory 要清空的目录 + * @return 目录下的所有文件都被成功删除时返回true,否则返回false. + * @since 1.0 + */ + public static boolean emptyDirectory(File directory) { + boolean result = true; + File[] entries = directory.listFiles(); + for (File entry : entries != null ? entries : new File[0]) { + if (!entry.delete()) { + result = false; + } + } + return result; + } + + /** + * 清空指定目录中的文件。 + * 这个方法将尽可能删除所有的文件,但是只要有一个文件没有被删除都会返回false。 + * 另外这个方法不会迭代删除,即不会删除子目录及其内容。 + * + * @param directoryName 要清空的目录的目录名 + * @return 目录下的所有文件都被成功删除时返回true,否则返回false。 + * @since 1.0 + */ + public static boolean emptyDirectory(String directoryName) { + File dir = new File(directoryName); + return emptyDirectory(dir); + } + + /** + * 删除指定目录及其中的所有内容。 + * + * @param dirName 要删除的目录的目录名 + * @return 删除成功时返回true,否则返回false。 + * @since 1.0 + */ + public static boolean deleteDirectory(String dirName) { + return deleteDirectory(new File(dirName)); + } + + /** + * 删除指定目录及其中的所有内容。 + * + * @param dir 要删除的目录 + * @return 删除成功时返回true,否则返回false。 + * @since 1.0 + */ + public static boolean deleteDirectory(File dir) { + if ((dir == null) || !dir.isDirectory()) { + throw new IllegalArgumentException("Argument " + dir + + " is not a directory. "); + } + + File[] entries = dir.listFiles(); + int sz = entries != null ? entries.length : 0; + + for (File entry : entries != null ? entries : new File[0]) { + if (entry.isDirectory()) { + if (!deleteDirectory(entry)) { + return false; + } + } else { + if (!entry.delete()) { + return false; + } + } + } + + return dir.delete(); + } + + + /** + * 列出目录中的所有内容,包括其子目录中的内容。 + * + * @param file 要列出的目录 + * @param filter 过滤器 + * @return 目录内容的文件数组。 + * @since 1.0 + */ + public static File[] listAll(File file, + javax.swing.filechooser.FileFilter filter) { + List arrayList = new ArrayList<>(); + File[] files; + if (!file.exists() || file.isFile()) { + return null; + } + list(arrayList, file, filter); + files = new File[arrayList.size()]; + arrayList.toArray(files); + return files; + } + + + /** + * 返回文件的URL地址。 + * + * @param file 文件 + * @return 文件对应的的URL地址 + * @throws MalformedURLException + * @since 1.0 + * @deprecated 在实现的时候没有注意到File类本身带一个toURL方法将文件路径转换为URL。 + * 请使用File.toURL方法。 + */ + public static URL getURL(File file) throws MalformedURLException { + String fileURL = "file:/" + file.getAbsolutePath(); + return new URL(fileURL); + } + + /** + * 从文件路径得到文件名。 + * + * @param filePath 文件的路径,可以是相对路径也可以是绝对路径 + * @return 对应的文件名 + * @since 1.0 + */ + public static String getFileName(String filePath) { + File file = new File(filePath); + return file.getName(); + } + + /** + * 从文件名得到文件绝对路径。 + * + * @param fileName 文件名 + * @return 对应的文件路径 + * @since 1.0 + */ + public static String getFilePath(String fileName) { + File file = new File(fileName); + return file.getAbsolutePath(); + } + + /** + * 将DOS/Windows格式的路径转换为UNIX/Linux格式的路径。 + * 其实就是将路径中的"\"全部换为"/",因为在某些情况下我们转换为这种方式比较方便, + * 某中程度上说"/"比"\"更适合作为路径分隔符,而且DOS/Windows也将它当作路径分隔符。 + * + * @param filePath 转换前的路径 + * @return 转换后的路径 + * @since 1.0 + */ + public static String toUNIXpath(String filePath) { + return filePath.replace('\\', '/'); + } + + /** + * 从文件名得到UNIX风格的文件绝对路径。 + * + * @param fileName 文件名 + * @return 对应的UNIX风格的文件路径 + * @see #toUNIXpath(String filePath) toUNIXpath + * @since 1.0 + */ + public static String getUNIXfilePath(String fileName) { + File file = new File(fileName); + return toUNIXpath(file.getAbsolutePath()); + } + + /** + * 得到文件的类型。 + * 实际上就是得到文件名中最后一个“.”后面的部分。 + * + * @param fileName 文件名 + * @return 文件名中的类型部分 + * @since 1.0 + */ + public static String getFileType(String fileName) { + int point = fileName.lastIndexOf('.'); + int length = fileName.length(); + if (point == -1 || point == length - 1) { + return ""; + } else { + return fileName.substring(point + 1, length); + } + } + + /** + * 得到文件的类型。 + * 实际上就是得到文件名中最后一个“.”后面的部分。 + * + * @param file 文件 + * @return 文件名中的类型部分 + * @since 1.0 + */ + public static String getFileType(File file) { + return getFileType(file.getName()); + } + + /** + * 得到文件的名字部分。 + * 实际上就是路径中的最后一个路径分隔符后的部分。 + * + * @param fileName 文件名 + * @return 文件名中的名字部分 + * @since 1.0 + */ + public static String getNamePart(String fileName) { + int point = getPathLsatIndex(fileName); + int length = fileName.length(); + if (point == -1) { + return fileName; + } else if (point == length - 1) { + int secondPoint = getPathLsatIndex(fileName, point - 1); + if (secondPoint == -1) { + if (length == 1) { + return fileName; + } else { + return fileName.substring(0, point); + } + } else { + return fileName.substring(secondPoint + 1, point); + } + } else { + return fileName.substring(point + 1); + } + } + + /** + * 得到文件名中的父路径部分。 + * 对两种路径分隔符都有效。 + * 不存在时返回""。 + * 如果文件名是以路径分隔符结尾的则不考虑该分隔符,例如"/path/"返回""。 + * + * @param fileName 文件名 + * @return 父路径,不存在或者已经是父目录时返回"" + * @since 1.0 + */ + public static String getPathPart(String fileName) { + int point = getPathLsatIndex(fileName); + int length = fileName.length(); + if (point == -1) { + return ""; + } else if (point == length - 1) { + int secondPoint = getPathLsatIndex(fileName, point - 1); + if (secondPoint == -1) { + return ""; + } else { + return fileName.substring(0, secondPoint); + } + } else { + return fileName.substring(0, point); + } + } + + /** + * 得到路径分隔符在文件路径中首次出现的位置。 + * 对于DOS或者UNIX风格的分隔符都可以。 + * + * @param fileName 文件路径 + * @return 路径分隔符在路径中首次出现的位置,没有出现时返回-1。 + * @since 1.0 + */ + public static int getPathIndex(String fileName) { + int point = fileName.indexOf('/'); + if (point == -1) { + point = fileName.indexOf('\\'); + } + return point; + } + + /** + * 得到路径分隔符在文件路径中指定位置后首次出现的位置。 + * 对于DOS或者UNIX风格的分隔符都可以。 + * + * @param fileName 文件路径 + * @param fromIndex 开始查找的位置 + * @return 路径分隔符在路径中指定位置后首次出现的位置,没有出现时返回-1。 + * @since 1.0 + */ + public static int getPathIndex(String fileName, int fromIndex) { + int point = fileName.indexOf('/', fromIndex); + if (point == -1) { + point = fileName.indexOf('\\', fromIndex); + } + return point; + } + + /** + * 得到路径分隔符在文件路径中最后出现的位置。 + * 对于DOS或者UNIX风格的分隔符都可以。 + * + * @param fileName 文件路径 + * @return 路径分隔符在路径中最后出现的位置,没有出现时返回-1。 + * @since 1.0 + */ + public static int getPathLsatIndex(String fileName) { + int point = fileName.lastIndexOf('/'); + if (point == -1) { + point = fileName.lastIndexOf('\\'); + } + return point; + } + + /** + * 得到路径分隔符在文件路径中指定位置前最后出现的位置。 + * 对于DOS或者UNIX风格的分隔符都可以。 + * + * @param fileName 文件路径 + * @param fromIndex 开始查找的位置 + * @return 路径分隔符在路径中指定位置前最后出现的位置,没有出现时返回-1。 + * @since 1.0 + */ + public static int getPathLsatIndex(String fileName, int fromIndex) { + int point = fileName.lastIndexOf('/', fromIndex); + if (point == -1) { + point = fileName.lastIndexOf('\\', fromIndex); + } + return point; + } + + /** + * 将文件名中的类型部分去掉。 + * + * @param filename 文件名 + * @return 去掉类型部分的结果 + * @since 1.0 + */ + public static String trimType(String filename) { + int index = filename.lastIndexOf("."); + if (index != -1) { + return filename.substring(0, index); + } else { + return filename; + } + } + + /** + * 得到相对路径。 + * 文件名不是目录名的子节点时返回文件名。 + * + * @param pathName 目录名 + * @param fileName 文件名 + * @return 得到文件名相对于目录名的相对路径,目录下不存在该文件时返回文件名 + * @since 1.0 + */ + public static String getSubpath(String pathName, String fileName) { + int index = fileName.indexOf(pathName); + if (index != -1) { + return fileName.substring(index + pathName.length() + 1); + } else { + return fileName; + } + } + + /** + * 检查给定目录的存在性 + * 保证指定的路径可用,如果指定的路径不存在,那么建立该路径,可以为多级路径 + * + * @param path + * @return 真假值 + * @since 1.0 + */ + public static boolean pathValidate(String path) { + String[] arraypath = path.split("/"); + String tmppath = ""; + for (String anArraypath : arraypath) { + tmppath += "/" + anArraypath; + File d = new File(tmppath.substring(1)); + //检查Sub目录是否存在 + if (!d.exists()) { + System.out.println(tmppath.substring(1)); + if (!d.mkdir()) { + return false; + } + } + } + return true; + } + + /** + * 根据内容生成文件 + * + * @param path 要生成文件的绝对路径, + * @param modulecontent 文件的内容。 + * @return 真假值 + * @since 1.0 + */ + public static boolean genModuleTpl(String path, String modulecontent) throws IOException { + + path = getUNIXfilePath(path); + String[] patharray = path.split("\\/"); + String modulepath = ""; + for (int i = 0; i < patharray.length - 1; i++) { + modulepath += "/" + patharray[i]; + } + File d = new File(modulepath.substring(1)); + if (!d.exists()) { + if (!pathValidate(modulepath.substring(1))) { + return false; + } + } + //建立FileWriter对象,并实例化fw + FileWriter fw = new FileWriter(path); + //将字符串写入文件 + fw.write(modulecontent); + fw.close(); + return true; + } + + /** + * 获取图片文件的扩展名(发布系统专用) + * + * @param picPath 为图片名称加上前面的路径不包括扩展名 + * @return 图片的扩展名 + * @since 1.0 + */ + public static String getPicExtendName(String picPath) { + picPath = getUNIXfilePath(picPath); + String picExtend = ""; + String gif = ".gif"; + if (isFileExist(picPath + gif)) { + picExtend = gif; + } + String jpeg = ".jpeg"; + if (isFileExist(picPath + jpeg)) { + picExtend = jpeg; + } + String jpg = ".jpg"; + if (isFileExist(picPath + jpg)) { + picExtend = jpg; + } + String png = ".png"; + if (isFileExist(picPath + png)) { + picExtend = png; + } + //返回图片扩展名 + return picExtend; + } + + public static boolean copyFile(File in, File out) throws Exception { + try { + FileInputStream fis = new FileInputStream(in); + FileOutputStream fos = new FileOutputStream(out); + byte[] buf = new byte[1024]; + int i = 0; + while ((i = fis.read(buf)) != -1) { + fos.write(buf, 0, i); + } + fis.close(); + fos.close(); + return true; + } catch (IOException ie) { + ie.printStackTrace(); + return false; + } + } + + public static boolean copyFile(String infile, String outfile) throws Exception { + try { + File in = new File(infile); + File out = new File(outfile); + return copyFile(in, out); + } catch (IOException ie) { + ie.printStackTrace(); + return false; + } + + } + + /** + * 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 orientals 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); + } + } + + /** + * 将目录中的内容添加到列表。 + * + * @param list 文件列表 + * @param filter 过滤器 + * @param file 目录 + */ + private static void list(List list, File file, + javax.swing.filechooser.FileFilter filter) { + if (filter.accept(file)) { + list.add(file); + if (file.isFile()) { + return; + } + } + if (file.isDirectory()) { + File[] files = file.listFiles(); + for (File file1 : files != null ? files : new File[0]) { + list(list, file1, filter); + } + } + + } + + + /** + * 文件上传 + * + * @param file file + * @param email email + * @return fileUrl + */ + public static String upload(MultipartFile file, String email) { + String savePath = ""; + String filename = ""; + if (file != null && !file.isEmpty()) { + // 获取图片的文件名 + String fileName = file.getOriginalFilename(); + // 重新定义图片名字 + filename = FileUtil.getNewFileName(fileName, email); + //上传服务器上 新文件路径 + String os = System.getProperty("os.name").toLowerCase(); + try { + // 判断服务器上 文件夹是否存在 + File newFile = new File(savePath); + if (!newFile.exists()) { + boolean result = newFile.mkdirs(); + System.out.println(result); + } + savePath = savePath + filename; + FileOutputStream out = new FileOutputStream(savePath); + // 写入文件 + out.write(file.getBytes()); + out.flush(); + out.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + return filename; + } + + + public static byte[] readStream(InputStream inStream) throws Exception { + ByteArrayOutputStream outsStream = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + int len = -1; + while ((len = inStream.read(buffer)) != -1) { + outsStream.write(buffer, 0, len); + } + outsStream.close(); + inStream.close(); + return outsStream.toByteArray(); + } + + public static byte[] readFileImage(File file) throws IOException { + BufferedInputStream bufferedInputStream = new BufferedInputStream( + new FileInputStream(file)); + int len = bufferedInputStream.available(); + byte[] bytes = new byte[len]; + int r = bufferedInputStream.read(bytes); + if (len != r) { + bytes = null; + throw new IOException("读取文件不正确"); + } + bufferedInputStream.close(); + return bytes; + } + + public static byte[] readFileImage(String filename) throws IOException { + BufferedInputStream bufferedInputStream = new BufferedInputStream( + new FileInputStream(filename)); + int len = bufferedInputStream.available(); + byte[] bytes = new byte[len]; + int r = bufferedInputStream.read(bytes); + if (len != r) { + bytes = null; + throw new IOException("读取文件不正确"); + } + bufferedInputStream.close(); + return bytes; + } + + + /** + * 读取返回的信息 + * + * @param in + * @return + */ + private static String getData(InputStream in) { + String result = ""; + StringBuilder sb = new StringBuilder(); + BufferedReader br = new BufferedReader(new InputStreamReader(in)); + String line = ""; + try { + while ((line = br.readLine()) != null) { + // result = result + line; + sb.append(line); + } + br.close(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + br.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return sb.toString(); + } + + + private static String bytesToHexString(byte[] src) { + StringBuilder stringBuilder = new StringBuilder(); + if (src == null || src.length <= 0) { + return null; + } + for (byte aSrc : src) { + int v = aSrc & 0xFF; + String hv = Integer.toHexString(v); + if (hv.length() < 2) { + stringBuilder.append(0); + } + stringBuilder.append(hv); + } + return stringBuilder.toString(); + } + + + /** + * 获取文件内容 + * + * @param filePath + * @return + * @throws IOException + */ + private static String getFile(String filePath) throws IOException { + byte[] b = new byte[28]; + InputStream inputStream = null; + try { + inputStream = new FileInputStream(filePath); + inputStream.read(b, 0, 28); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (inputStream != null) { + try { + inputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + return bytesToHexString(b); + } + + /** + * @param filePath filePath + * @return FileConst + * @throws IOException + */ + public static FileConst getType(String filePath) throws IOException { + String fileHead = getFile(filePath); + if (fileHead == null || fileHead.length() == 0) { + return null; + } + fileHead = fileHead.toUpperCase(); + FileConst[] fileConsts = FileConst.values(); + for (FileConst type : fileConsts) { + if (fileHead.startsWith(type.getValue())) { + return type; + } + } + return null; + } + + public static String getNewFileName(String fileName, String email) { + String fileType = FileUtil.getFileType(fileName); + String newName = email.split(SymbolConst.AT)[0]; + return (TimeUtil.getDateNow(TimeUtil.DATE_FORMAT_STRING) + SymbolConst.HENGXIAN + newName + SymbolConst.DIAN + fileType).toLowerCase(); + } + + public static boolean isImage(String imageName) { + String fileType = FileUtil.getFileType(imageName); + return !("bmp".equals(fileType) || "BMP".equals(fileType) + || "jpg".equals(fileType) || "JPG".equals(fileType) + || "jpeg".equals(fileType) || "JPEG".equals(fileType) + || "git".equals(fileType) || "GIF".equals(fileType) + || "png".equals(fileType) || "PNG".equals(fileType)); + } + +} diff --git a/core/src/main/java/info/xiaomo/core/untils/FileUtil.kt b/core/src/main/java/info/xiaomo/core/untils/FileUtil.kt deleted file mode 100644 index 2da2a513..00000000 --- a/core/src/main/java/info/xiaomo/core/untils/FileUtil.kt +++ /dev/null @@ -1,855 +0,0 @@ -package info.xiaomo.core.untils - -import info.xiaomo.core.constant.FileConst -import info.xiaomo.core.constant.SymbolConst -import org.springframework.web.multipart.MultipartFile -import java.io.* -import java.net.MalformedURLException -import java.net.URL -import java.util.* -import kotlin.experimental.and - -/** - * 此类中封装一些常用的文件操作。 - * 所有方法都是静态方法,不需要生成此类的实例, - * 为避免生成此类的实例,构造方法被申明为private类型的。 - * - * @author : xiaomo - * @since 1.0 - */ - -object FileUtil { - /** - * Buffer size when reading from input stream. - * - * @since ostermillerutils 1.00.00 - */ - private val BUFFER_SIZE = 1024 - - /** - * 修改文件的最后访问时间。 - * 如果文件不存在则创建该文件。 - * **目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考虑中。** - * - * @param file 需要修改最后访问时间的文件。 - * @since 1.0 - */ - fun touch(file: File?) { - val currentTime = System.currentTimeMillis() - if (file != null) { - if (!file.exists()) { - System.err.println("file not found:" + file.name) - System.err.println("Create a new file:" + file.name) - try { - if (file.createNewFile()) { - println("Succeeded!") - } else { - System.err.println("Create file failed!") - } - } catch (e: IOException) { - System.err.println("Create file failed!") - e.printStackTrace() - } - - } - } - val result = file!!.setLastModified(currentTime) - if (!result) { - System.err.println("touch failed: " + file.name) - } - } - - /** - * 修改文件的最后访问时间。 - * 如果文件不存在则创建该文件。 - * **目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考虑中。** - * - * @param fileName 需要修改最后访问时间的文件的文件名。 - * @since 1.0 - */ - fun touch(fileName: String) { - val file = File(fileName) - touch(file) - } - - /** - * 修改文件的最后访问时间。 - * 如果文件不存在则创建该文件。 - * **目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考虑中。** - * - * @param files 需要修改最后访问时间的文件数组。 - * @since 1.0 - */ - fun touch(files: Array) { - for (file in files) { - touch(file) - } - } - - /** - * 修改文件的最后访问时间。 - * 如果文件不存在则创建该文件。 - * **目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考虑中。** - * - * @param fileNames 需要修改最后访问时间的文件名数组。 - * @since 1.0 - */ - @JvmStatic - fun touch(fileNames: Array) { - val files = arrayOfNulls(fileNames.size) - for (i in fileNames.indices) { - files[i] = File(fileNames[i]) - } - touch(files) - } - - /** - * 判断指定的文件是否存在。 - * - * @param fileName 要判断的文件的文件名 - * @return 存在时返回true,否则返回false。 - * @since 1.0 - */ - fun isFileExist(fileName: String): Boolean { - return File(fileName).isFile - } - - /** - * 创建指定的目录。 - * 如果指定的目录的父目录不存在则创建其目录书上所有需要的父目录。 - * **注意:可能会在返回false的时候创建部分父目录。** - * - * @param file 要创建的目录 - * @return 完全创建成功时返回true,否则返回false。 - * @since 1.0 - */ - fun makeDirectory(file: File): Boolean { - val parent = file.parentFile - return parent != null && parent.mkdirs() - } - - /** - * 创建指定的目录。 - * 如果指定的目录的父目录不存在则创建其目录书上所有需要的父目录。 - * **注意:可能会在返回false的时候创建部分父目录。** - * - * @param fileName 要创建的目录的目录名 - * @return 完全创建成功时返回true,否则返回false。 - * @since 1.0 - */ - fun makeDirectory(fileName: String): Boolean { - val file = File(fileName) - return makeDirectory(file) - } - - /** - * 清空指定目录中的文件。 - * 这个方法将尽可能删除所有的文件,但是只要有一个文件没有被删除都会返回false。 - * 另外这个方法不会迭代删除,即不会删除子目录及其内容。 - * - * @param directory 要清空的目录 - * @return 目录下的所有文件都被成功删除时返回true,否则返回false. - * @since 1.0 - */ - fun emptyDirectory(directory: File): Boolean { - var result = true - val entries = directory.listFiles() - for (entry in entries ?: arrayOfNulls(0)) { - if (!entry.delete()) { - result = false - } - } - return result - } - - /** - * 清空指定目录中的文件。 - * 这个方法将尽可能删除所有的文件,但是只要有一个文件没有被删除都会返回false。 - * 另外这个方法不会迭代删除,即不会删除子目录及其内容。 - * - * @param directoryName 要清空的目录的目录名 - * @return 目录下的所有文件都被成功删除时返回true,否则返回false。 - * @since 1.0 - */ - fun emptyDirectory(directoryName: String): Boolean { - val dir = File(directoryName) - return emptyDirectory(dir) - } - - /** - * 删除指定目录及其中的所有内容。 - * - * @param dirName 要删除的目录的目录名 - * @return 删除成功时返回true,否则返回false。 - * @since 1.0 - */ - fun deleteDirectory(dirName: String): Boolean { - return deleteDirectory(File(dirName)) - } - - /** - * 删除指定目录及其中的所有内容。 - * - * @param dir 要删除的目录 - * @return 删除成功时返回true,否则返回false。 - * @since 1.0 - */ - fun deleteDirectory(dir: File?): Boolean { - if (dir == null || !dir.isDirectory) { - throw IllegalArgumentException("Argument " + dir + - " is not a directory. ") - } - - val entries = dir.listFiles() - val sz = entries?.size ?: 0 - - for (entry in entries ?: arrayOfNulls(0)) { - if (entry.isDirectory) { - if (!deleteDirectory(entry)) { - return false - } - } else { - if (!entry.delete()) { - return false - } - } - } - - return dir.delete() - } - - - /** - * 列出目录中的所有内容,包括其子目录中的内容。 - * - * @param file 要列出的目录 - * @param filter 过滤器 - * @return 目录内容的文件数组。 - * @since 1.0 - */ - fun listAll(file: File, - filter: javax.swing.filechooser.FileFilter): Array? { - val arrayList = ArrayList() - val files: Array - if (!file.exists() || file.isFile) { - return null - } - list(arrayList, file, filter) - files = arrayOfNulls(arrayList.size) - arrayList.toTypedArray() - return files - } - - - /** - * 返回文件的URL地址。 - * - * @param file 文件 - * @return 文件对应的的URL地址 - * @throws MalformedURLException - * @since 1.0 - */ - @Deprecated("在实现的时候没有注意到File类本身带一个toURL方法将文件路径转换为URL。\n" + - " 请使用File.toURL方法。") - @Throws(MalformedURLException::class) - fun getURL(file: File): URL { - val fileURL = "file:/" + file.absolutePath - return URL(fileURL) - } - - /** - * 从文件路径得到文件名。 - * - * @param filePath 文件的路径,可以是相对路径也可以是绝对路径 - * @return 对应的文件名 - * @since 1.0 - */ - fun getFileName(filePath: String): String { - val file = File(filePath) - return file.name - } - - /** - * 从文件名得到文件绝对路径。 - * - * @param fileName 文件名 - * @return 对应的文件路径 - * @since 1.0 - */ - fun getFilePath(fileName: String): String { - val file = File(fileName) - return file.absolutePath - } - - /** - * 将DOS/Windows格式的路径转换为UNIX/Linux格式的路径。 - * 其实就是将路径中的"\"全部换为"/",因为在某些情况下我们转换为这种方式比较方便, - * 某中程度上说"/"比"\"更适合作为路径分隔符,而且DOS/Windows也将它当作路径分隔符。 - * - * @param filePath 转换前的路径 - * @return 转换后的路径 - * @since 1.0 - */ - fun toUNIXpath(filePath: String): String { - return filePath.replace('\\', '/') - } - - /** - * 从文件名得到UNIX风格的文件绝对路径。 - * - * @param fileName 文件名 - * @return 对应的UNIX风格的文件路径 - * @see .toUNIXpath - * @since 1.0 - */ - fun getUNIXfilePath(fileName: String): String { - val file = File(fileName) - return toUNIXpath(file.absolutePath) - } - - /** - * 得到文件的类型。 - * 实际上就是得到文件名中最后一个“.”后面的部分。 - * - * @param fileName 文件名 - * @return 文件名中的类型部分 - * @since 1.0 - */ - fun getFileType(fileName: String): String { - val point = fileName.lastIndexOf('.') - val length = fileName.length - return if (point == -1 || point == length - 1) { - "" - } else { - fileName.substring(point + 1, length) - } - } - - /** - * 得到文件的类型。 - * 实际上就是得到文件名中最后一个“.”后面的部分。 - * - * @param file 文件 - * @return 文件名中的类型部分 - * @since 1.0 - */ - fun getFileType(file: File): String { - return getFileType(file.name) - } - - /** - * 得到文件的名字部分。 - * 实际上就是路径中的最后一个路径分隔符后的部分。 - * - * @param fileName 文件名 - * @return 文件名中的名字部分 - * @since 1.0 - */ - fun getNamePart(fileName: String): String { - val point = getPathLsatIndex(fileName) - val length = fileName.length - if (point == -1) { - return fileName - } else if (point == length - 1) { - val secondPoint = getPathLsatIndex(fileName, point - 1) - return if (secondPoint == -1) { - if (length == 1) { - fileName - } else { - fileName.substring(0, point) - } - } else { - fileName.substring(secondPoint + 1, point) - } - } else { - return fileName.substring(point + 1) - } - } - - /** - * 得到文件名中的父路径部分。 - * 对两种路径分隔符都有效。 - * 不存在时返回""。 - * 如果文件名是以路径分隔符结尾的则不考虑该分隔符,例如"/path/"返回""。 - * - * @param fileName 文件名 - * @return 父路径,不存在或者已经是父目录时返回"" - * @since 1.0 - */ - fun getPathPart(fileName: String): String { - val point = getPathLsatIndex(fileName) - val length = fileName.length - if (point == -1) { - return "" - } else if (point == length - 1) { - val secondPoint = getPathLsatIndex(fileName, point - 1) - return if (secondPoint == -1) { - "" - } else { - fileName.substring(0, secondPoint) - } - } else { - return fileName.substring(0, point) - } - } - - /** - * 得到路径分隔符在文件路径中首次出现的位置。 - * 对于DOS或者UNIX风格的分隔符都可以。 - * - * @param fileName 文件路径 - * @return 路径分隔符在路径中首次出现的位置,没有出现时返回-1。 - * @since 1.0 - */ - fun getPathIndex(fileName: String): Int { - var point = fileName.indexOf('/') - if (point == -1) { - point = fileName.indexOf('\\') - } - return point - } - - /** - * 得到路径分隔符在文件路径中指定位置后首次出现的位置。 - * 对于DOS或者UNIX风格的分隔符都可以。 - * - * @param fileName 文件路径 - * @param fromIndex 开始查找的位置 - * @return 路径分隔符在路径中指定位置后首次出现的位置,没有出现时返回-1。 - * @since 1.0 - */ - fun getPathIndex(fileName: String, fromIndex: Int): Int { - var point = fileName.indexOf('/', fromIndex) - if (point == -1) { - point = fileName.indexOf('\\', fromIndex) - } - return point - } - - /** - * 得到路径分隔符在文件路径中最后出现的位置。 - * 对于DOS或者UNIX风格的分隔符都可以。 - * - * @param fileName 文件路径 - * @return 路径分隔符在路径中最后出现的位置,没有出现时返回-1。 - * @since 1.0 - */ - fun getPathLsatIndex(fileName: String): Int { - var point = fileName.lastIndexOf('/') - if (point == -1) { - point = fileName.lastIndexOf('\\') - } - return point - } - - /** - * 得到路径分隔符在文件路径中指定位置前最后出现的位置。 - * 对于DOS或者UNIX风格的分隔符都可以。 - * - * @param fileName 文件路径 - * @param fromIndex 开始查找的位置 - * @return 路径分隔符在路径中指定位置前最后出现的位置,没有出现时返回-1。 - * @since 1.0 - */ - fun getPathLsatIndex(fileName: String, fromIndex: Int): Int { - var point = fileName.lastIndexOf('/', fromIndex) - if (point == -1) { - point = fileName.lastIndexOf('\\', fromIndex) - } - return point - } - - /** - * 将文件名中的类型部分去掉。 - * - * @param filename 文件名 - * @return 去掉类型部分的结果 - * @since 1.0 - */ - fun trimType(filename: String): String { - val index = filename.lastIndexOf(".") - return if (index != -1) { - filename.substring(0, index) - } else { - filename - } - } - - /** - * 得到相对路径。 - * 文件名不是目录名的子节点时返回文件名。 - * - * @param pathName 目录名 - * @param fileName 文件名 - * @return 得到文件名相对于目录名的相对路径,目录下不存在该文件时返回文件名 - * @since 1.0 - */ - fun getSubpath(pathName: String, fileName: String): String { - val index = fileName.indexOf(pathName) - return if (index != -1) { - fileName.substring(index + pathName.length + 1) - } else { - fileName - } - } - - /** - * 检查给定目录的存在性 - * 保证指定的路径可用,如果指定的路径不存在,那么建立该路径,可以为多级路径 - * - * @param path - * @return 真假值 - * @since 1.0 - */ - fun pathValidate(path: String): Boolean { - val arraypath = path.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() - var tmppath = "" - for (anArraypath in arraypath) { - tmppath += "/" + anArraypath - val d = File(tmppath.substring(1)) - //检查Sub目录是否存在 - if (!d.exists()) { - println(tmppath.substring(1)) - if (!d.mkdir()) { - return false - } - } - } - return true - } - - /** - * 根据内容生成文件 - * - * @param path 要生成文件的绝对路径, - * @param modulecontent 文件的内容。 - * @return 真假值 - * @since 1.0 - */ - @Throws(IOException::class) - fun genModuleTpl(path: String, modulecontent: String): Boolean { - var path = path - - path = getUNIXfilePath(path) - val patharray = path.split("\\/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() - var modulepath = "" - for (i in 0 until patharray.size - 1) { - modulepath += "/" + patharray[i] - } - val d = File(modulepath.substring(1)) - if (!d.exists()) { - if (!pathValidate(modulepath.substring(1))) { - return false - } - } - //建立FileWriter对象,并实例化fw - val fw = FileWriter(path) - //将字符串写入文件 - fw.write(modulecontent) - fw.close() - return true - } - - /** - * 获取图片文件的扩展名(发布系统专用) - * - * @param picPath 为图片名称加上前面的路径不包括扩展名 - * @return 图片的扩展名 - * @since 1.0 - */ - fun getPicExtendName(picPath: String): String { - var picPath = picPath - picPath = getUNIXfilePath(picPath) - var picExtend = "" - val gif = ".gif" - if (isFileExist(picPath + gif)) { - picExtend = gif - } - val jpeg = ".jpeg" - if (isFileExist(picPath + jpeg)) { - picExtend = jpeg - } - val jpg = ".jpg" - if (isFileExist(picPath + jpg)) { - picExtend = jpg - } - val png = ".png" - if (isFileExist(picPath + png)) { - picExtend = png - } - //返回图片扩展名 - return picExtend - } - - @Throws(Exception::class) - fun copyFile(`in`: File, out: File): Boolean { - try { - val fis = FileInputStream(`in`) - val fos = FileOutputStream(out) - val buf = ByteArray(1024) - var i = 0 - while ((fis.read(buf)) != -1) { - fos.write(buf, 0, i) - } - fis.close() - fos.close() - return true - } catch (ie: IOException) { - ie.printStackTrace() - return false - } - - } - - @Throws(Exception::class) - fun copyFile(infile: String, outfile: String): Boolean { - try { - val `in` = File(infile) - val out = File(outfile) - return copyFile(`in`, out) - } catch (ie: IOException) { - ie.printStackTrace() - return false - } - - } - - /** - * 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 orientals 1.00.00 - */ - @Throws(IOException::class) - private fun copy(`in`: InputStream, out: OutputStream) { - val buffer = ByteArray(BUFFER_SIZE) - val read = 0 - while ((`in`.read(buffer)) != -1) { - out.write(buffer, 0, read) - } - } - - /** - * 将目录中的内容添加到列表。 - * - * @param list 文件列表 - * @param filter 过滤器 - * @param file 目录 - */ - private fun list(list: MutableList, file: File, - filter: javax.swing.filechooser.FileFilter) { - if (filter.accept(file)) { - list.add(file) - if (file.isFile) { - return - } - } - if (file.isDirectory) { - val files = file.listFiles() - for (file1 in files ?: arrayOfNulls(0)) { - list(list, file1, filter) - } - } - - } - - - /** - * 文件上传 - * - * @param file file - * @param email email - * @return fileUrl - */ - fun upload(file: MultipartFile?, email: String): String { - var savePath = "" - var filename = "" - if (file != null && !file.isEmpty) { - // 获取图片的文件名 - val fileName = file.originalFilename - // 重新定义图片名字 - filename = FileUtil.getNewFileName(fileName, email) - //上传服务器上 新文件路径 - val os = System.getProperty("os.name").toLowerCase() - try { - // 判断服务器上 文件夹是否存在 - val newFile = File(savePath) - if (!newFile.exists()) { - val result = newFile.mkdirs() - println(result) - } - savePath = savePath + filename - val out = FileOutputStream(savePath) - // 写入文件 - out.write(file.bytes) - out.flush() - out.close() - } catch (e: Exception) { - e.printStackTrace() - } - - } - return filename - } - - - @Throws(Exception::class) - fun readStream(inStream: InputStream): ByteArray { - val outsStream = ByteArrayOutputStream() - val buffer = ByteArray(1024) - var len = -1 - while ((inStream.read(buffer)) != -1) { - outsStream.write(buffer, 0, len) - } - outsStream.close() - inStream.close() - return outsStream.toByteArray() - } - - @Throws(IOException::class) - fun readFileImage(file: File): ByteArray { - val bufferedInputStream = BufferedInputStream( - FileInputStream(file)) - val len = bufferedInputStream.available() - var bytes: ByteArray? = ByteArray(len) - val r = bufferedInputStream.read(bytes!!) - if (len != r) { - bytes = null - throw IOException("读取文件不正确") - } - bufferedInputStream.close() - return bytes - } - - @Throws(IOException::class) - fun readFileImage(filename: String): ByteArray { - val bufferedInputStream = BufferedInputStream( - FileInputStream(filename)) - val len = bufferedInputStream.available() - var bytes: ByteArray? = ByteArray(len) - val r = bufferedInputStream.read(bytes!!) - if (len != r) { - bytes = null - throw IOException("读取文件不正确") - } - bufferedInputStream.close() - return bytes - } - - - /** - * 读取返回的信息 - * - * @param in - * @return - */ - private fun getData(`in`: InputStream): String { - val result = "" - val sb = StringBuilder() - val br = BufferedReader(InputStreamReader(`in`)) - var line = "" - try { - while ((br.readLine()) != null) { - // result = result + line; - sb.append(line) - } - br.close() - } catch (e: Exception) { - e.printStackTrace() - } finally { - try { - br.close() - } catch (e: IOException) { - e.printStackTrace() - } - - } - return sb.toString() - } - - - private fun bytesToHexString(src: ByteArray?): String? { - val stringBuilder = StringBuilder() - if (src == null || src.size <= 0) { - return null - } - for (aSrc in src) { - val v = aSrc and 0xFF.toByte() - val hv = Integer.toHexString(v.toInt()) - if (hv.length < 2) { - stringBuilder.append(0) - } - stringBuilder.append(hv) - } - return stringBuilder.toString() - } - - - /** - * 获取文件内容 - * - * @param filePath - * @return - * @throws IOException - */ - @Throws(IOException::class) - private fun getFile(filePath: String): String? { - val b = ByteArray(28) - var inputStream: InputStream? = null - try { - inputStream = FileInputStream(filePath) - inputStream.read(b, 0, 28) - } catch (e: IOException) { - e.printStackTrace() - } finally { - if (inputStream != null) { - try { - inputStream.close() - } catch (e: IOException) { - e.printStackTrace() - } - - } - } - return bytesToHexString(b) - } - - /** - * @param filePath filePath - * @return FileConst - * @throws IOException - */ - @Throws(IOException::class) - fun getType(filePath: String): FileConst? { - var fileHead = getFile(filePath) - if (fileHead == null || fileHead.length == 0) { - return null - } - fileHead = fileHead.toUpperCase() - val fileConsts = FileConst.values() - for (type in fileConsts) { - if (fileHead.startsWith(type.value)) { - return type - } - } - return null - } - - fun getNewFileName(fileName: String, email: String): String { - val fileType = FileUtil.getFileType(fileName) - val newName = email.split(SymbolConst.AT.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0] - return (TimeUtil.getDateNow(TimeUtil.DATE_FORMAT_STRING) + SymbolConst.HENGXIAN + newName + SymbolConst.DIAN + fileType).toLowerCase() - } - - fun isImage(imageName: String): Boolean { - val fileType = FileUtil.getFileType(imageName) - return !("bmp" == fileType || "BMP" == fileType - || "jpg" == fileType || "JPG" == fileType - || "jpeg" == fileType || "JPEG" == fileType - || "git" == fileType || "GIF" == fileType - || "png" == fileType || "PNG" == fileType) - } - -} diff --git a/core/src/main/java/info/xiaomo/core/untils/HtmlUtil.java b/core/src/main/java/info/xiaomo/core/untils/HtmlUtil.java new file mode 100644 index 00000000..975e56ac --- /dev/null +++ b/core/src/main/java/info/xiaomo/core/untils/HtmlUtil.java @@ -0,0 +1,170 @@ +package info.xiaomo.core.untils; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + *

+ * + * @author : xiaomo + * github: https://github.com/syoubaku + * email: xiaomo@xiamoo.info + * QQ_NO: 83387856 + * Date: 17/5/11 17:57 + * Description: + * Copyright(©) 2017 by xiaomo. + */ +public class HtmlUtil { + + + /** + * 是否包含有HTML标签 + * + * @param str 字符串 + * @return 是否包含html标签 + */ + public static boolean containsHTMLTag(String str) { + if (StringUtil.isBlank(str)) { + return false; + } + + String pattern = "<\\s*(\\S+)(\\s[^>]*)?>[\\s\\S]*<\\s*/\\1\\s*>"; + Pattern p = Pattern.compile(pattern); + Matcher m = p.matcher(str); + return m.find(); + } + + /** + * 用于将字符串中的特殊字符转换成Web页中可以安全显示的字符串 + * 可对表单数据据进行处理对一些页面特殊字符进行处理如'<','>','"',''','&' + * + * @param strSrc 要进行替换操作的字符串 + * @return 替换特殊字符后的字符串 + * @since 1.0 + */ + + public static String htmlEncode(String strSrc) { + if (strSrc == null) { + return ""; + } + char[] arrCsrc = strSrc.toCharArray(); + StringBuilder buf = new StringBuilder(arrCsrc.length); + char ch; + for (char anArrCSrc : arrCsrc) { + ch = anArrCSrc; + + if (ch == '<') { + buf.append("<"); + } else if (ch == '>') { + buf.append(">"); + } else if (ch == '"') { + buf.append("""); + } else if (ch == '\'') { + buf.append("'"); + } else if (ch == '&') { + buf.append("&"); + } else { + buf.append(ch); + } + } + + return buf.toString(); + } + + /** + * 用于将字符串中的特殊字符转换成Web页中可以安全显示的字符串 + * 可对表单数据据进行处理对一些页面特殊字符进行处理如'<','>','"',''','&' + * + * @param strSrc 要进行替换操作的字符串 + * @param quotes 为0时单引号和双引号都替换,为1时不替换单引号,为2时不替换双引号,为3时单引号和双引号都不替换 + * @return 替换特殊字符后的字符串 + * @since 1.0 + */ + public static String htmlEncode(String strSrc, int quotes) { + + if (strSrc == null) { + return ""; + } + if (quotes == 0) { + return htmlEncode(strSrc); + } + + char[] arrCsrc = strSrc.toCharArray(); + StringBuilder buf = new StringBuilder(arrCsrc.length); + char ch; + + for (int i = 0; i < arrCsrc.length; i++) { + ch = arrCsrc[i]; + if (ch == '<') { + buf.append("<"); + } else if (ch == '>') { + buf.append(">"); + } else if (ch == '"' && quotes == 1) { + buf.append("""); + } else if (ch == '\'' && quotes == 2) { + buf.append("'"); + } else if (ch == '&') { + buf.append("&"); + } else { + buf.append(ch); + } + } + + return buf.toString(); + } + + /** + * 和htmlEncode正好相反 + * + * @param strSrc 要进行转换的字符串 + * @return 转换后的字符串 + * @since 1.0 + */ + public static String htmlDecode(String strSrc) { + if (strSrc == null) { + return ""; + } + strSrc = strSrc.replaceAll("<", "<"); + strSrc = strSrc.replaceAll(">", ">"); + strSrc = strSrc.replaceAll(""", "\""); + strSrc = strSrc.replaceAll("'", "'"); + strSrc = strSrc.replaceAll("&", "&"); + return strSrc; + } + + /** + * 去除html tag + * + * @param htmlStr html + * @return string + */ + public static String delHTMLTag(String htmlStr) { + //定义script的正则表达式 + String regexScript = "]*?>[\\s\\S]*?<\\/script>"; + //定义style的正则表达式 + String regexStyle = "]*?>[\\s\\S]*?<\\/style>"; + //定义HTML标签的正则表达式 + String regexHtml = "<[^>]+>"; + + Pattern pScript = Pattern.compile(regexScript, Pattern.CASE_INSENSITIVE); + Matcher mScript = pScript.matcher(htmlStr); + //过滤script标签 + htmlStr = mScript.replaceAll(""); + + Pattern pStyle = Pattern.compile(regexStyle, Pattern.CASE_INSENSITIVE); + Matcher mStyle = pStyle.matcher(htmlStr); + //过滤style标签 + htmlStr = mStyle.replaceAll(""); + + Pattern pHtml = Pattern.compile(regexHtml, Pattern.CASE_INSENSITIVE); + Matcher mHtml = pHtml.matcher(htmlStr); + //过滤html标签 + htmlStr = mHtml.replaceAll(""); + //返回文本字符串 + return htmlStr.trim(); + } + +} diff --git a/core/src/main/java/info/xiaomo/core/untils/HtmlUtil.kt b/core/src/main/java/info/xiaomo/core/untils/HtmlUtil.kt deleted file mode 100644 index b0ff19fd..00000000 --- a/core/src/main/java/info/xiaomo/core/untils/HtmlUtil.kt +++ /dev/null @@ -1,170 +0,0 @@ -package info.xiaomo.core.untils - -import java.util.regex.Pattern - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * - * - * @author : xiaomo - * github: https://github.com/syoubaku - * email: xiaomo@xiamoo.info - * QQ_NO: 83387856 - * Date: 17/5/11 17:57 - * Description: - * Copyright(©) 2017 by xiaomo. - */ -object HtmlUtil { - - - /** - * 是否包含有HTML标签 - * - * @param str 字符串 - * @return 是否包含html标签 - */ - fun containsHTMLTag(str: String): Boolean { - if (StringUtil.isBlank(str)) { - return false - } - - val pattern = "<\\s*(\\S+)(\\s[^>]*)?>[\\s\\S]*<\\s*/\\1\\s*>" - val p = Pattern.compile(pattern) - val m = p.matcher(str) - return m.find() - } - - /** - * 用于将字符串中的特殊字符转换成Web页中可以安全显示的字符串 - * 可对表单数据据进行处理对一些页面特殊字符进行处理如'<','>','"',''','&' - * - * @param strSrc 要进行替换操作的字符串 - * @return 替换特殊字符后的字符串 - * @since 1.0 - */ - - fun htmlEncode(strSrc: String?): String { - if (strSrc == null) { - return "" - } - val arrCsrc = strSrc.toCharArray() - val buf = StringBuilder(arrCsrc.size) - var ch: Char - for (anArrCSrc in arrCsrc) { - ch = anArrCSrc - - if (ch == '<') { - buf.append("<") - } else if (ch == '>') { - buf.append(">") - } else if (ch == '"') { - buf.append(""") - } else if (ch == '\'') { - buf.append("'") - } else if (ch == '&') { - buf.append("&") - } else { - buf.append(ch) - } - } - - return buf.toString() - } - - /** - * 用于将字符串中的特殊字符转换成Web页中可以安全显示的字符串 - * 可对表单数据据进行处理对一些页面特殊字符进行处理如'<','>','"',''','&' - * - * @param strSrc 要进行替换操作的字符串 - * @param quotes 为0时单引号和双引号都替换,为1时不替换单引号,为2时不替换双引号,为3时单引号和双引号都不替换 - * @return 替换特殊字符后的字符串 - * @since 1.0 - */ - fun htmlEncode(strSrc: String?, quotes: Int): String { - - if (strSrc == null) { - return "" - } - if (quotes == 0) { - return htmlEncode(strSrc) - } - - val arrCsrc = strSrc.toCharArray() - val buf = StringBuilder(arrCsrc.size) - var ch: Char - - for (i in arrCsrc.indices) { - ch = arrCsrc[i] - if (ch == '<') { - buf.append("<") - } else if (ch == '>') { - buf.append(">") - } else if (ch == '"' && quotes == 1) { - buf.append(""") - } else if (ch == '\'' && quotes == 2) { - buf.append("'") - } else if (ch == '&') { - buf.append("&") - } else { - buf.append(ch) - } - } - - return buf.toString() - } - - /** - * 和htmlEncode正好相反 - * - * @param strSrc 要进行转换的字符串 - * @return 转换后的字符串 - * @since 1.0 - */ - fun htmlDecode(strSrc: String?): String? { - var strSrc: String? = strSrc ?: return "" - strSrc = strSrc!!.replace("<".toRegex(), "<") - strSrc = strSrc.replace(">".toRegex(), ">") - strSrc = strSrc.replace(""".toRegex(), "\"") - strSrc = strSrc.replace("'".toRegex(), "'") - strSrc = strSrc.replace("&".toRegex(), "&") - return strSrc - } - - /** - * 去除html tag - * - * @param htmlStr html - * @return string - */ - fun delHTMLTag(htmlStr: String): String { - var htmlStr = htmlStr - //定义script的正则表达式 - val regexScript = "]*?>[\\s\\S]*?<\\/script>" - //定义style的正则表达式 - val regexStyle = "]*?>[\\s\\S]*?<\\/style>" - //定义HTML标签的正则表达式 - val regexHtml = "<[^>]+>" - - val pScript = Pattern.compile(regexScript, Pattern.CASE_INSENSITIVE) - val mScript = pScript.matcher(htmlStr) - //过滤script标签 - htmlStr = mScript.replaceAll("") - - val pStyle = Pattern.compile(regexStyle, Pattern.CASE_INSENSITIVE) - val mStyle = pStyle.matcher(htmlStr) - //过滤style标签 - htmlStr = mStyle.replaceAll("") - - val pHtml = Pattern.compile(regexHtml, Pattern.CASE_INSENSITIVE) - val mHtml = pHtml.matcher(htmlStr) - //过滤html标签 - htmlStr = mHtml.replaceAll("") - //返回文本字符串 - return htmlStr.trim { it <= ' ' } - } - -} diff --git a/core/src/main/java/info/xiaomo/core/untils/HttpUtil.java b/core/src/main/java/info/xiaomo/core/untils/HttpUtil.java new file mode 100644 index 00000000..8257d22a --- /dev/null +++ b/core/src/main/java/info/xiaomo/core/untils/HttpUtil.java @@ -0,0 +1,322 @@ +package info.xiaomo.core.untils; + + +import org.apache.commons.lang3.StringUtils; + +import javax.net.ssl.*; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.*; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.Map; +import java.util.Map.Entry; + + +/** + * https 请求 微信为https的请求 + * + * @author : xiaomo + */ +public class HttpUtil { + + private static final String DEFAULT_CHARSET = "UTF-8"; + + private static final String GET = "GET"; + private static final String POST = "POST"; + + private final static String USER_COOKIE_KEY = "uid"; + private final static String USER_COOKIE_SECRET = "&#%!&*"; + + /** + * 初始化http请求参数 + * + * @throws IOException + */ + private static HttpURLConnection initHttp(String urlStr, String method, Map headers) throws IOException { + URL url = new URL(urlStr); + HttpURLConnection http = (HttpURLConnection) url.openConnection(); + // 连接超时 + http.setConnectTimeout(25000); + // 读取超时 --服务器响应比较慢,增大时间 + http.setReadTimeout(25000); + http.setRequestMethod(method); + http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); + http.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36"); + if (null != headers && !headers.isEmpty()) { + for (Entry entry : headers.entrySet()) { + http.setRequestProperty(entry.getKey(), entry.getValue()); + } + } + http.setDoOutput(true); + http.setDoInput(true); + http.connect(); + return http; + } + + /** + * 初始化http请求参数 + * + * @throws IOException + * @throws NoSuchAlgorithmException + * @throws NoSuchProviderException + * @throws KeyManagementException + */ + private static HttpsURLConnection initHttps(String urlStr, String method, Map headers) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException { + TrustManager[] tm = {new MyX509TrustManager()}; + SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); + sslContext.init(null, tm, new java.security.SecureRandom()); + // 从上述SSLContext对象中得到SSLSocketFactory对象 + SSLSocketFactory ssf = sslContext.getSocketFactory(); + URL url = new URL(urlStr); + HttpsURLConnection http = (HttpsURLConnection) url.openConnection(); + // 设置域名校验 + http.setHostnameVerifier(new HttpUtil().new TrustAnyHostnameVerifier()); + // 连接超时 + http.setConnectTimeout(25000); + // 读取超时 --服务器响应比较慢,增大时间 + http.setReadTimeout(25000); + http.setRequestMethod(method); + http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); + http.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36"); + if (null != headers && !headers.isEmpty()) { + for (Entry entry : headers.entrySet()) { + http.setRequestProperty(entry.getKey(), entry.getValue()); + } + } + http.setSSLSocketFactory(ssf); + http.setDoOutput(true); + http.setDoInput(true); + http.connect(); + return http; + } + + /** + * @return 返回类型: + */ + public static String get(String url, Map params, Map headers) { + StringBuffer bufferRes = null; + try { + HttpURLConnection http = null; + if (isHttps(url)) { + http = initHttps(initParams(url, params), GET, headers); + } else { + http = initHttp(initParams(url, params), GET, headers); + } + InputStream in = http.getInputStream(); + BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET)); + String valueString = null; + bufferRes = new StringBuffer(); + while ((valueString = read.readLine()) != null) { + bufferRes.append(valueString); + } + read.close(); + in.close(); + http.disconnect();// 关闭连接 + return bufferRes.toString(); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public static String get(String url) { + return get(url, null); + } + + public static String get(String url, Map params) { + return get(url, params, null); + } + + public static String post(String url, String params, Map headers) { + StringBuffer bufferRes = null; + try { + HttpURLConnection http = null; + if (isHttps(url)) { + http = initHttps(url, POST, headers); + } else { + http = initHttp(url, POST, headers); + } + OutputStream out = http.getOutputStream(); + out.write(params.getBytes(DEFAULT_CHARSET)); + out.flush(); + out.close(); + + InputStream in = http.getInputStream(); + BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET)); + String valueString = null; + bufferRes = new StringBuffer(); + while ((valueString = read.readLine()) != null) { + bufferRes.append(valueString); + } + read.close(); + in.close(); + http.disconnect();// 关闭连接 + return bufferRes.toString(); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * post map 请求 + * + * @throws UnsupportedEncodingException + */ + public static String post(String url, Map params) throws UnsupportedEncodingException { + return post(url, map2Url(params), null); + } + + /** + * post map 请求,headers请求头 + * + * @throws UnsupportedEncodingException + */ + public static String post(String url, Map params, Map headers) throws UnsupportedEncodingException { + return post(url, map2Url(params), headers); + } + + /** + * @return 返回类型: + * @throws UnsupportedEncodingException + */ + public static String initParams(String url, Map params) throws UnsupportedEncodingException { + if (null == params || params.isEmpty()) { + return url; + } + StringBuilder sb = new StringBuilder(url); + String wenhao = "?"; + if (!url.contains(wenhao)) { + sb.append(wenhao); + } + sb.append(map2Url(params)); + return sb.toString(); + } + + /** + * map构造url + * + * @return 返回类型: + * @throws UnsupportedEncodingException + */ + public static String map2Url(Map paramToMap) throws UnsupportedEncodingException { + if (null == paramToMap || paramToMap.isEmpty()) { + return null; + } + StringBuilder url = new StringBuilder(); + boolean isfist = true; + for (Entry entry : paramToMap.entrySet()) { + if (isfist) { + isfist = false; + } else { + url.append("&"); + } + url.append(entry.getKey()).append("="); + String value = entry.getValue(); + if (StringUtils.isNotEmpty(value)) { + url.append(URLEncoder.encode(value, DEFAULT_CHARSET)); + } + } + return url.toString(); + } + + /** + * 检测是否https + */ + private static boolean isHttps(String url) { + return url.startsWith("https"); + } + + /** + * 读取cookie + * + * @param request request + * @param key key + */ + public static String getCookie(HttpServletRequest request, String key) { + Cookie[] cookies = request.getCookies(); + if (null != cookies) { + for (Cookie cookie : cookies) { + if (key.equals(cookie.getName())) { + return cookie.getValue(); + } + } + } + return null; + } + + /** + * 清除 某个指定的cookie + * + * @param response response + * @param key key + */ + public static void removeCookie(HttpServletResponse response, String key) { + setCookie(response, key, null, 0); + } + + /** + * 设置cookie + * + * @param response response + * @param name name + * @param value value + * @param maxAgeInSeconds maxAgeInSeconds + */ + public static void setCookie(HttpServletResponse response, String name, String value, int maxAgeInSeconds) { + Cookie cookie = new Cookie(name, value); + cookie.setPath("/"); + cookie.setMaxAge(maxAgeInSeconds); + // 指定为httpOnly保证安全性 + cookie.setHttpOnly(true); + response.addCookie(cookie); + } + + /** + * 获取浏览器信息 + * + * @param request request + * @return String + */ + public static String getUserAgent(HttpServletRequest request) { + return request.getHeader("User-Agent"); + } + + /** + * https 域名校验 + */ + public class TrustAnyHostnameVerifier implements HostnameVerifier { + @Override + public boolean verify(String hostname, SSLSession session) { + return true; + } + } + + +} + +class MyX509TrustManager implements X509TrustManager { + + @Override + public X509Certificate[] getAcceptedIssuers() { + return null; + } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) + throws CertificateException { + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) + throws CertificateException { + } +} \ No newline at end of file diff --git a/core/src/main/java/info/xiaomo/core/untils/HttpUtil.kt b/core/src/main/java/info/xiaomo/core/untils/HttpUtil.kt deleted file mode 100644 index a53bb57a..00000000 --- a/core/src/main/java/info/xiaomo/core/untils/HttpUtil.kt +++ /dev/null @@ -1,313 +0,0 @@ -package info.xiaomo.core.untils - - -import org.apache.commons.lang3.StringUtils -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.URLEncoder -import java.security.KeyManagementException -import java.security.NoSuchAlgorithmException -import java.security.NoSuchProviderException -import java.security.cert.CertificateException -import java.security.cert.X509Certificate -import javax.net.ssl.* -import javax.servlet.http.Cookie -import javax.servlet.http.HttpServletRequest -import javax.servlet.http.HttpServletResponse - - -/** - * https 请求 微信为https的请求 - * @author : xiaomo - */ -class HttpUtil { - - /** - * https 域名校验 - */ - inner class TrustAnyHostnameVerifier : HostnameVerifier { - override fun verify(hostname: String, session: SSLSession): Boolean { - return true - } - } - - companion object { - - private val DEFAULT_CHARSET = "UTF-8" - - private val GET = "GET" - private val POST = "POST" - - private val USER_COOKIE_KEY = "uid" - private val USER_COOKIE_SECRET = "&#%!&*" - - /** - * 初始化http请求参数 - * - * @throws IOException - */ - @Throws(IOException::class) - private fun initHttp(urlStr: String, method: String, headers: Map?): HttpURLConnection { - val url = URL(urlStr) - val http = url.openConnection() as HttpURLConnection - // 连接超时 - http.connectTimeout = 25000 - // 读取超时 --服务器响应比较慢,增大时间 - http.readTimeout = 25000 - http.requestMethod = method - http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded") - http.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36") - if (null != headers && !headers.isEmpty()) { - for ((key, value) in headers) { - http.setRequestProperty(key, value) - } - } - http.doOutput = true - http.doInput = true - http.connect() - return http - } - - /** - * 初始化http请求参数 - * - * @throws IOException - * @throws NoSuchAlgorithmException - * @throws NoSuchProviderException - * @throws KeyManagementException - */ - @Throws(IOException::class, NoSuchAlgorithmException::class, NoSuchProviderException::class, KeyManagementException::class) - private fun initHttps(urlStr: String, method: String, headers: Map?): HttpsURLConnection { - val tm = arrayOf(MyX509TrustManager()) - val sslContext = SSLContext.getInstance("SSL", "SunJSSE") - sslContext.init(null, tm, java.security.SecureRandom()) - // 从上述SSLContext对象中得到SSLSocketFactory对象 - val ssf = sslContext.socketFactory - val url = URL(urlStr) - val http = url.openConnection() as HttpsURLConnection - // 设置域名校验 - http.hostnameVerifier = HttpUtil().TrustAnyHostnameVerifier() - // 连接超时 - http.connectTimeout = 25000 - // 读取超时 --服务器响应比较慢,增大时间 - http.readTimeout = 25000 - http.requestMethod = method - http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded") - http.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36") - if (null != headers && !headers.isEmpty()) { - for ((key, value) in headers) { - http.setRequestProperty(key, value) - } - } - http.sslSocketFactory = ssf - http.doOutput = true - http.doInput = true - http.connect() - return http - } - - /** - * @return 返回类型: - */ - @JvmOverloads operator fun get(url: String, params: Map? = null, headers: Map? = null): String? { - var bufferRes: StringBuffer? - try { - var http: HttpURLConnection? - if (isHttps(url)) { - http = initHttps(initParams(url, params), GET, headers) - } else { - http = initHttp(initParams(url, params), GET, headers) - } - val `in` = http.inputStream - val read = BufferedReader(InputStreamReader(`in`, DEFAULT_CHARSET)) - val valueString: String? = null - bufferRes = StringBuffer() - while ((valueString == read.readLine()) != null) { - bufferRes.append(valueString) - } - read.close() - `in`.close() - http.disconnect()// 关闭连接 - return bufferRes.toString() - } catch (e: Exception) { - e.printStackTrace() - return null - } - - } - - fun post(url: String, params: String?, headers: Map?): String? { - var bufferRes: StringBuffer? = null - try { - var http: HttpURLConnection? = null - if (isHttps(url)) { - http = initHttps(url, POST, headers) - } else { - http = initHttp(url, POST, headers) - } - val out = http.outputStream - out.write(params!!.toByteArray(charset(DEFAULT_CHARSET))) - out.flush() - out.close() - - val `in` = http.inputStream - val read = BufferedReader(InputStreamReader(`in`, DEFAULT_CHARSET)) - val valueString: String? = null - bufferRes = StringBuffer() - while ((valueString == read.readLine())) { - bufferRes.append(valueString) - } - read.close() - `in`.close() - http.disconnect()// 关闭连接 - return bufferRes.toString() - } catch (e: Exception) { - e.printStackTrace() - return null - } - - } - - /** - * post map 请求 - * - * @throws UnsupportedEncodingException - */ - @Throws(UnsupportedEncodingException::class) - fun post(url: String, params: Map): String? { - return post(url, map2Url(params), null) - } - - /** - * post map 请求,headers请求头 - * - * @throws UnsupportedEncodingException - */ - @Throws(UnsupportedEncodingException::class) - fun post(url: String, params: Map, headers: Map): String? { - return post(url, map2Url(params), headers) - } - - /** - * @return 返回类型: - * @throws UnsupportedEncodingException - */ - @Throws(UnsupportedEncodingException::class) - fun initParams(url: String, params: Map?): String { - if (null == params || params.isEmpty()) { - return url - } - val sb = StringBuilder(url) - val questionMark = "?" - if (!url.contains(questionMark)) { - sb.append(questionMark) - } - sb.append(map2Url(params)) - return sb.toString() - } - - /** - * map构造url - * - * @return 返回类型: - * @throws UnsupportedEncodingException - */ - @Throws(UnsupportedEncodingException::class) - fun map2Url(paramToMap: Map?): String? { - if (null == paramToMap || paramToMap.isEmpty()) { - return null - } - val url = StringBuilder() - var isfist = true - for ((key, value) in paramToMap) { - if (isfist) { - isfist = false - } else { - url.append("&") - } - url.append(key).append("=") - if (StringUtils.isNotEmpty(value)) { - url.append(URLEncoder.encode(value, DEFAULT_CHARSET)) - } - } - return url.toString() - } - - /** - * 检测是否https - */ - private fun isHttps(url: String): Boolean { - return url.startsWith("https") - } - - /** - * 读取cookie - * - * @param request request - * @param key key - */ - fun getCookie(request: HttpServletRequest, key: String): String? { - val cookies = request.cookies - cookies?.filter { key == it.name }?.forEach { return it.value } - return null - } - - /** - * 清除 某个指定的cookie - * - * @param response response - * @param key key - */ - fun removeCookie(response: HttpServletResponse, key: String) { - setCookie(response, key, null, 0) - } - - /** - * 设置cookie - * - * @param response response - * @param name name - * @param value value - * @param maxAgeInSeconds maxAgeInSeconds - */ - private fun setCookie(response: HttpServletResponse, name: String, value: String?, maxAgeInSeconds: Int) { - val cookie = Cookie(name, value) - cookie.path = "/" - cookie.maxAge = maxAgeInSeconds - // 指定为httpOnly保证安全性 - cookie.isHttpOnly = true - response.addCookie(cookie) - } - - /** - * 获取浏览器信息 - * - * @param request request - * @return String - */ - fun getUserAgent(request: HttpServletRequest): String { - return request.getHeader("User-Agent") - } - } - - -} - -internal class MyX509TrustManager : X509TrustManager { - - override fun getAcceptedIssuers(): Array? { - return null - } - - @Throws(CertificateException::class) - override fun checkClientTrusted(chain: Array, authType: String) { - } - - @Throws(CertificateException::class) - override fun checkServerTrusted(chain: Array, authType: String) { - } -} \ No newline at end of file diff --git a/core/src/main/java/info/xiaomo/core/untils/IDUtil.java b/core/src/main/java/info/xiaomo/core/untils/IDUtil.java new file mode 100644 index 00000000..edeb571b --- /dev/null +++ b/core/src/main/java/info/xiaomo/core/untils/IDUtil.java @@ -0,0 +1,52 @@ +package info.xiaomo.core.untils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * @author : xiaomo + */ +public class IDUtil { + private static final Logger LOGGER = LoggerFactory.getLogger(IDUtil.class); + /** + * 锁 + */ + private static final Object ID_LOCK = new Object(); + /** + * 当前秒数 + */ + private static long CURRENT_SECOND = System.currentTimeMillis() / 1000L; + private static int ID = 0; + + public static void main(String[] args) { + LOGGER.info(String.valueOf(Integer.MAX_VALUE / (365 * 24 * 60 * 60))); + LOGGER.info(Integer.toBinaryString((int) (System.currentTimeMillis() / 1000))); + } + + /** + * 获取唯一一个id + * + * @return long + */ + public static long getId() { + int tempId; + long tempCurSec = System.currentTimeMillis() / 1000L; + synchronized (ID_LOCK) { + ID += 1; + tempId = ID; + int i = 65000; + if (ID > i) { + ID = 0; + CURRENT_SECOND += 1L; + } + if (tempCurSec > CURRENT_SECOND) { + CURRENT_SECOND = tempCurSec; + } else { + tempCurSec = CURRENT_SECOND; + } + } + return ((tempCurSec) << 16 | tempId & 0xFFFF); + } + +} diff --git a/core/src/main/java/info/xiaomo/core/untils/IDUtil.kt b/core/src/main/java/info/xiaomo/core/untils/IDUtil.kt deleted file mode 100644 index 2065f9e4..00000000 --- a/core/src/main/java/info/xiaomo/core/untils/IDUtil.kt +++ /dev/null @@ -1,53 +0,0 @@ -package info.xiaomo.core.untils - -import org.slf4j.LoggerFactory - - -/** - * @author : xiaomo - */ -object IDUtil { - private val LOGGER = LoggerFactory.getLogger(IDUtil::class.java) - /** - * 锁 - */ - private val ID_LOCK = Any() - /** - * 当前秒数 - */ - private var CURRENT_SECOND = System.currentTimeMillis() / 1000L - private var ID = 0 - - /** - * 获取唯一一个id - * - * @return long - */ - val id: Long - get() { - var tempId = 0 - var tempCurSec = System.currentTimeMillis() / 1000L - synchronized(ID_LOCK) { - ID += 1 - tempId = ID - val i = 65000 - if (ID > i) { - ID = 0 - CURRENT_SECOND += 1L - } - if (tempCurSec > CURRENT_SECOND) { - CURRENT_SECOND = tempCurSec - } else { - tempCurSec = CURRENT_SECOND - } - } - return tempCurSec shl 16 or ((tempId and 0xFFFF).toLong()) - } - - @JvmStatic - fun main(args: Array) { - LOGGER.info((Integer.MAX_VALUE / (365 * 24 * 60 * 60)).toString()) - LOGGER.info(Integer.toBinaryString((System.currentTimeMillis() / 1000).toInt())) - } - -} diff --git a/core/src/main/java/info/xiaomo/core/untils/LunarCalendarUtil.kt b/core/src/main/java/info/xiaomo/core/untils/LunarCalendarUtil.java similarity index 53% rename from core/src/main/java/info/xiaomo/core/untils/LunarCalendarUtil.kt rename to core/src/main/java/info/xiaomo/core/untils/LunarCalendarUtil.java index 50cdb4ec..5a30f3af 100644 --- a/core/src/main/java/info/xiaomo/core/untils/LunarCalendarUtil.kt +++ b/core/src/main/java/info/xiaomo/core/untils/LunarCalendarUtil.java @@ -1,39 +1,42 @@ -package info.xiaomo.core.untils +package info.xiaomo.core.untils; -import java.util.* +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; /** - * @author : xiaomo (https://xiaomo.info) (https://github.com/xiaomoinfo) + * @author : xiaomo (https://xiaomo.info) (https://github.com/houko) * @version : 2017/1/14 9:59 */ -object LunarCalendarUtil { +public class LunarCalendarUtil { /** * 支持转换的最小农历年份 */ - val MIN_YEAR = 1900 + public static final int MIN_YEAR = 1900; /** * 支持转换的最大农历年份 */ - val MAX_YEAR = 2099 + public static final int MAX_YEAR = 2099; /** * 公历每月前的天数 */ - private val DAYS_BEFORE_MONTH = intArrayOf(0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365) + private static final int[] DAYS_BEFORE_MONTH = {0, 31, 59, 90, 120, 151, 181, + 212, 243, 273, 304, 334, 365}; /** * 用来表示1900年到2099年间农历年份的相关信息,共24位bit的16进制表示,其中: * 1. 前4位表示该年闰哪个月; * 2. 5-17位表示农历年份13个月的大小月分布,0表示小,1表示大; * 3. 最后7位表示农历年首(正月初一)对应的公历日期。 - * - * + *

* 以2014年的数据0x955ABF为例说明: * 1001 0101 0101 1010 1011 1111 * 闰九月 农历正月初一对应公历1月31号 */ - private val LUNAR_INFO = intArrayOf(0x84B6BF, + private static final int[] LUNAR_INFO = { + 0x84B6BF, /*1901-1910*/ 0x04AE53, 0x0A5748, 0x5526BD, 0x0D2650, 0x0D9544, 0x46AAB9, 0x056A4D, 0x09AD42, 0x24AEB6, 0x04AE4A, /*1911-1920*/ @@ -72,11 +75,12 @@ 0x8A95BF, 0x0A9553, 0x0B4A47, 0x6B553B, 0x0AD54F, 0x055A45, 0x4A5D38, 0x0A5B4C, 0x052B42, 0x3A93B6, /*2081-2090*/ 0x069349, 0x7729BD, 0x06AA51, 0x0AD546, 0x54DABA, 0x04B64E, 0x0A5743, 0x452738, 0x0D264A, 0x8E933E, - /*2091-2099*/ - 0x0D5252, 0x0DAA47, 0x66B53B, 0x056D4F, 0x04AE45, 0x4A4EB9, 0x0A4D4C, 0x0D1541, 0x2D92B5) - private val monthString = arrayOf("一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "冬月", "腊月") - private val dayString = arrayOf("一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十", "二十一", "二十二", "二十三", "二十四", "二十五", "二十六", "二十七", "二十八", "二十九", "三十", "三十一") - private val weekString = arrayOf("周日", "周一", "周二", "周三", "周四", "周五", "周六") + /*2091-2099*/ + 0x0D5252, 0x0DAA47, 0x66B53B, 0x056D4F, 0x04AE45, 0x4A4EB9, 0x0A4D4C, 0x0D1541, 0x2D92B5 + }; + private static String[] monthString = {"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "冬月", "腊月"}; + private static String[] dayString = {"一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十", "二十一", "二十二", "二十三", "二十四", "二十五", "二十六", "二十七", "二十八", "二十九", "三十", "三十一"}; + private static String[] weekString = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"}; /** * 将农历日期转换为公历日期 @@ -85,123 +89,118 @@ * @param month 农历月 * @param monthDay 农历日 * @param isLeapMonth 该月是否是闰月 - * [url=home.php?mod=space&uid=7300]@return[/url] 返回农历日期对应的公历日期,year0, month1, day2. + * [url=home.php?mod=space&uid=7300]@return[/url] 返回农历日期对应的公历日期,year0, month1, day2. */ - fun lunarToSolar(year: Int, month: Int, monthDay: Int, - isLeapMonth: Boolean): IntArray { - var year = year - var dayOffset: Int - val leapMonth: Int - var i: Int - - val maxMonth = 12 + public static final int[] lunarToSolar(int year, int month, int monthDay, + boolean isLeapMonth) { + int dayOffset; + int leapMonth; + int i; + + int maxMonth = 12; if (year < MIN_YEAR || year > MAX_YEAR || month < 1 || month > maxMonth || monthDay < 1 || monthDay > 30) { - throw IllegalArgumentException( + throw new IllegalArgumentException( "Illegal lunar date, must be like that:\n\t" + "year : 1900~2099\n\t" + "month : 1~12\n\t" + - "day : 1~30") + "day : 1~30"); } - dayOffset = (LUNAR_INFO[year - MIN_YEAR] and 0x001F) - 1 + dayOffset = (LUNAR_INFO[year - MIN_YEAR] & 0x001F) - 1; - val five = 5 - val two = 2 - if (LUNAR_INFO[year - MIN_YEAR] and 0x0060 shr five == two) { - dayOffset += 31 + int five = 5; + int two = 2; + if (((LUNAR_INFO[year - MIN_YEAR] & 0x0060) >> five) == two) { + dayOffset += 31; } - i = 1 - while (i < month) { - if (LUNAR_INFO[year - MIN_YEAR] and (0x80000 shr i - 1) == 0) { - dayOffset += 29 + for (i = 1; i < month; i++) { + if ((LUNAR_INFO[year - MIN_YEAR] & (0x80000 >> (i - 1))) == 0) { + dayOffset += 29; } else { - dayOffset += 30 + dayOffset += 30; } - i++ } - dayOffset += monthDay - leapMonth = LUNAR_INFO[year - MIN_YEAR] and 0xf00000 shr 20 + dayOffset += monthDay; + leapMonth = (LUNAR_INFO[year - MIN_YEAR] & 0xf00000) >> 20; // 这一年有闰月 if (leapMonth != 0) { - val res = month > leapMonth || month == leapMonth && isLeapMonth + boolean res = month > leapMonth || (month == leapMonth && isLeapMonth); if (res) { - if (LUNAR_INFO[year - MIN_YEAR] and (0x80000 shr month - 1) == 0) { - dayOffset += 29 + if ((LUNAR_INFO[year - MIN_YEAR] & (0x80000 >> (month - 1))) == 0) { + dayOffset += 29; } else { - dayOffset += 30 + dayOffset += 30; } } } - val four = 4 - val res = dayOffset > 366 || year % four != 0 && dayOffset > 365 + int four = 4; + boolean res = dayOffset > 366 || (year % four != 0 && dayOffset > 365); if (res) { - year += 1 - dayOffset -= if (year % four == 1) { - 366 + year += 1; + if (year % four == 1) { + dayOffset -= 366; } else { - 365 + dayOffset -= 365; } } - val solarInfo = IntArray(3) - val oneThree = 13 - i = 1 - while (i < oneThree) { - var iPos = DAYS_BEFORE_MONTH[i] + int[] solarInfo = new int[3]; + int oneThree = 13; + for (i = 1; i < oneThree; i++) { + int iPos = DAYS_BEFORE_MONTH[i]; if (year % four == 0 && i > two) { - iPos += 1 + iPos += 1; } if (year % four == 0 && i == two && iPos + 1 == dayOffset) { - solarInfo[1] = i - solarInfo[two] = dayOffset - 31 - break + solarInfo[1] = i; + solarInfo[two] = dayOffset - 31; + break; } if (iPos >= dayOffset) { - solarInfo[1] = i - iPos = DAYS_BEFORE_MONTH[i - 1] + solarInfo[1] = i; + iPos = DAYS_BEFORE_MONTH[i - 1]; if (year % four == 0 && i > two) { - iPos += 1 + iPos += 1; } if (dayOffset > iPos) { - solarInfo[two] = dayOffset - iPos + solarInfo[two] = dayOffset - iPos; } else if (dayOffset == iPos) { if (year % four == 0 && i == two) { - solarInfo[two] = DAYS_BEFORE_MONTH[i] - DAYS_BEFORE_MONTH[i - 1] + 1 + solarInfo[two] = DAYS_BEFORE_MONTH[i] - DAYS_BEFORE_MONTH[i - 1] + 1; } else { - solarInfo[two] = DAYS_BEFORE_MONTH[i] - DAYS_BEFORE_MONTH[i - 1] + solarInfo[two] = DAYS_BEFORE_MONTH[i] - DAYS_BEFORE_MONTH[i - 1]; } } else { - solarInfo[two] = dayOffset + solarInfo[two] = dayOffset; } - break + break; } - i++ } - solarInfo[0] = year + solarInfo[0] = year; - return solarInfo + return solarInfo; } - private fun solarToLunar(): String { - val calendar = Calendar.getInstance() - val year = calendar.get(Calendar.YEAR) - val month = calendar.get(Calendar.MONTH) - val day = calendar.get(Calendar.DAY_OF_MONTH) - val week = calendar.get(Calendar.DAY_OF_WEEK) - val ints = solarToLunar(year, month, day) - val monthStr = monthString[ints[1]] - val dayStr = dayString[ints[2]] - val weekStr = weekString[week - 1] - return monthStr + dayStr + " " + weekStr + public static String solarToLunar() { + Calendar calendar = Calendar.getInstance(); + int year = calendar.get(Calendar.YEAR); + int month = calendar.get(Calendar.MONTH); + int day = calendar.get(Calendar.DAY_OF_MONTH); + int week = calendar.get(Calendar.DAY_OF_WEEK); + int[] ints = solarToLunar(year, month, day); + String monthStr = monthString[ints[1]]; + String dayStr = dayString[ints[2]]; + String weekStr = weekString[week - 1]; + return monthStr + dayStr + " " + weekStr; } /** @@ -212,60 +211,66 @@ private fun solarToLunar(): String { * @param monthDay * @return 返回公历日期对应的农历日期,year0,month1,day2,leap3 */ - fun solarToLunar(year: Int, month: Int, monthDay: Int): IntArray { - val lunarDate = IntArray(4) - val baseDate = GregorianCalendar(1900, 0, 31).time - val objDate = GregorianCalendar(year, month - 1, monthDay).time - var offset = ((objDate.time - baseDate.time) / 86400000L).toInt() + public static final int[] solarToLunar(int year, int month, int monthDay) { + int[] lunarDate = new int[4]; + Date baseDate = new GregorianCalendar(1900, 0, 31).getTime(); + Date objDate = new GregorianCalendar(year, month - 1, monthDay).getTime(); + int offset = (int) ((objDate.getTime() - baseDate.getTime()) / 86400000L); // 用offset减去每农历年的天数计算当天是农历第几天 // iYear最终结果是农历的年份, offset是当年的第几天 - var iYear: Int - var daysOfYear = 0 - iYear = MIN_YEAR - while (iYear <= MAX_YEAR && offset > 0) { - daysOfYear = daysInLunarYear(iYear) - offset -= daysOfYear - iYear++ + int iYear, daysOfYear = 0; + for (iYear = MIN_YEAR; iYear <= MAX_YEAR && offset > 0; iYear++) { + daysOfYear = daysInLunarYear(iYear); + offset -= daysOfYear; } if (offset < 0) { - offset += daysOfYear - iYear-- + offset += daysOfYear; + iYear--; } // 农历年份 - lunarDate[0] = iYear - // 闰哪个月,1-12 - val leapMonth = leapMonth(iYear) - var isLeap = false + lunarDate[0] = iYear; +// 闰哪个月,1-12 + int leapMonth = leapMonth(iYear); + boolean isLeap = false; // 用当年的天数offset,逐个减去每月(农历)的天数,求出当天是本月的第几天 - var iMonth = 1 - var daysOfMonth = 0 - val i = 13 - while (iMonth <= i && offset > 0) { - daysOfMonth = daysInLunarMonth(iYear, iMonth) - offset -= daysOfMonth - iMonth++ + int iMonth, daysOfMonth = 0; + int i = 13; + for (iMonth = 1; iMonth <= i && offset > 0; iMonth++) { + daysOfMonth = daysInLunarMonth(iYear, iMonth); + offset -= daysOfMonth; } // 当前月超过闰月,要校正 if (leapMonth != 0 && iMonth > leapMonth) { - --iMonth + --iMonth; if (iMonth == leapMonth) { - isLeap = true + isLeap = true; } } // offset小于0时,也要校正 if (offset < 0) { - offset += daysOfMonth - --iMonth + offset += daysOfMonth; + --iMonth; } - lunarDate[1] = iMonth - lunarDate[2] = offset + 1 - lunarDate[3] = if (isLeap) 1 else 0 + lunarDate[1] = iMonth; + lunarDate[2] = offset + 1; + lunarDate[3] = isLeap ? 1 : 0; - return lunarDate + return lunarDate; + } + + /** + * 传回农历year年month月的总天数 + * + * @param year 要计算的年份 + * @param month 要计算的月 + * @return 传回天数 + */ + final public static int daysInMonth(int year, int month) { + return daysInMonth(year, month, false); } /** @@ -276,27 +281,26 @@ fun solarToLunar(year: Int, month: Int, monthDay: Int): IntArray { * @param leap 当月是否是闰月 * @return 传回天数,如果闰月是错误的,返回0. */ - @JvmOverloads - fun daysInMonth(year: Int, month: Int, leap: Boolean = false): Int { - val leapMonth = leapMonth(year) - var offset = 0 + public static final int daysInMonth(int year, int month, boolean leap) { + int leapMonth = leapMonth(year); + int offset = 0; // 如果本年有闰月且month大于闰月时,需要校正 if (leapMonth != 0 && month > leapMonth) { - offset = 1 + offset = 1; } // 不考虑闰月 if (!leap) { - return daysInLunarMonth(year, month + offset) + return daysInLunarMonth(year, month + offset); } else { // 传入的闰月是正确的月份 if (leapMonth != 0 && leapMonth == month) { - return daysInLunarMonth(year, month + 1) + return daysInLunarMonth(year, month + 1); } } - return 0 + return 0; } /** @@ -305,21 +309,18 @@ fun daysInMonth(year: Int, month: Int, leap: Boolean = false): Int { * @param year 将要计算的年份 * @return 返回传入年份的总天数 */ - private fun daysInLunarYear(year: Int): Int { - var i: Int - var sum = 348 + private static int daysInLunarYear(int year) { + int i, sum = 348; if (leapMonth(year) != 0) { - sum = 377 + sum = 377; } - val monthInfo = LUNAR_INFO[year - MIN_YEAR] and 0x0FFF80 - i = 0x80000 - while (i > 0x7) { - if (monthInfo and i != 0) { - sum += 1 + int monthInfo = LUNAR_INFO[year - MIN_YEAR] & 0x0FFF80; + for (i = 0x80000; i > 0x7; i >>= 1) { + if ((monthInfo & i) != 0) { + sum += 1; } - i = i shr 1 } - return sum + return sum; } /** @@ -329,11 +330,11 @@ private fun daysInLunarYear(year: Int): Int { * @param month 将要计算的月份 * @return 传回农历 year年month月的总天数 */ - private fun daysInLunarMonth(year: Int, month: Int): Int { - return if (LUNAR_INFO[year - MIN_YEAR] and (0x100000 shr month) == 0) { - 29 + private static int daysInLunarMonth(int year, int month) { + if ((LUNAR_INFO[year - MIN_YEAR] & (0x100000 >> month)) == 0) { + return 29; } else { - 30 + return 30; } } @@ -343,21 +344,13 @@ private fun daysInLunarMonth(year: Int, month: Int): Int { * @param year 将要计算的年份 * @return 传回农历 year年闰哪个月1-12, 没闰传回 0 */ - private fun leapMonth(year: Int): Int { - return LUNAR_INFO[year - MIN_YEAR] and 0xF00000 shr 20 + private static int leapMonth(int year) { + return (LUNAR_INFO[year - MIN_YEAR] & 0xF00000) >> 20; } - @JvmStatic - fun main(args: Array) { - val s = solarToLunar() - println(s) + public static void main(String[] args) { + String s = solarToLunar(); + System.out.println(s); } } -/** - * 传回农历year年month月的总天数 - * - * @param year 要计算的年份 - * @param month 要计算的月 - * @return 传回天数 - */ diff --git a/core/src/main/java/info/xiaomo/core/untils/MailUtil.java b/core/src/main/java/info/xiaomo/core/untils/MailUtil.java new file mode 100644 index 00000000..d4c36da7 --- /dev/null +++ b/core/src/main/java/info/xiaomo/core/untils/MailUtil.java @@ -0,0 +1,94 @@ +package info.xiaomo.core.untils; + +import javax.mail.*; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeMessage; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Date; +import java.util.Properties; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/4/511:00 + * Description: 发送邮件 + * Copyright(©) 2015 by xiaomo. + **/ +public class MailUtil { + private static String USERNAME; + private static String PASSWORD; + + /** + * 获取Session + */ + private static Session getSession() throws IOException { + Properties props = new Properties(); + String dir = System.getProperty("user.dir"); + FileInputStream is = new FileInputStream(dir + "/website/src/main/resources/config/application.properties"); + props.load(is); + USERNAME = String.valueOf(props.get("mail.username")); + PASSWORD = String.valueOf(props.get("mail.password")); + Authenticator authenticator = new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(USERNAME, PASSWORD); + } + }; + return Session.getDefaultInstance(props, authenticator); + } + + public static void send(String toEmail, String subject, String content) { + Session session; + try { + session = getSession(); + Message msg = new MimeMessage(session); + msg.setFrom(new InternetAddress(USERNAME)); + InternetAddress[] address = {new InternetAddress(toEmail)}; + msg.setRecipients(Message.RecipientType.TO, address); + msg.setSubject(subject); + msg.setSentDate(new Date()); + msg.setContent(content, "text/html;charset=utf-8"); + Transport.send(msg); + } catch (Exception mex) { + mex.printStackTrace(); + } + } + + /** + * 返回激活链接 + * + * @param email email + * @return 有3个参数 email password time + */ + public static String redirectValidateUrl(String email, String password) { + Long now = TimeUtil.getNowOfMills(); + StringBuilder sb = new StringBuilder("点击下面链接激活账号,48小时生效,否则重新注册账号,链接只能使用一次,请尽快激活!
"); + sb.append(""); + sb.append("http://localhost:8080/user/validate?email="); + sb.append(email); + sb.append("&password="); + sb.append(password); + sb.append("&time="); + sb.append(now); + sb.append("
"); + sb.append("小莫
"); + sb.append(""); + sb.append(TimeUtil.getFormatDate()); + sb.append("
"); + return sb.toString(); + } +} diff --git a/core/src/main/java/info/xiaomo/core/untils/MailUtil.kt b/core/src/main/java/info/xiaomo/core/untils/MailUtil.kt deleted file mode 100644 index 026ef374..00000000 --- a/core/src/main/java/info/xiaomo/core/untils/MailUtil.kt +++ /dev/null @@ -1,95 +0,0 @@ -package info.xiaomo.core.untils - -import java.io.FileInputStream -import java.io.IOException -import java.util.* -import javax.mail.* -import javax.mail.internet.InternetAddress -import javax.mail.internet.MimeMessage - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/4/511:00 - * Description: 发送邮件 - * Copyright(©) 2015 by xiaomo. - */ -object MailUtil { - private var USERNAME: String? = null - private var PASSWORD: String? = null - - /** - * 获取Session - */ - private val getSession: Session - @Throws(IOException::class) - get() { - val props = Properties() - val dir = System.getProperty("user.dir") - val `is` = FileInputStream(dir + "/website/src/main/resources/config/application.properties") - props.load(`is`) - USERNAME = props["mail.username"].toString() - PASSWORD = props["mail.password"].toString() - val authenticator = object : Authenticator() { - override fun getPasswordAuthentication(): PasswordAuthentication { - return PasswordAuthentication(USERNAME, PASSWORD) - } - } - return Session.getDefaultInstance(props, authenticator) - } - - fun send(toEmail: String, subject: String, content: String) { - val session: Session - try { - session = getSession - val msg = MimeMessage(session) - msg.setFrom(InternetAddress(USERNAME!!)) - val address = arrayOf(InternetAddress(toEmail)) - msg.setRecipients(Message.RecipientType.TO, address) - msg.subject = subject - msg.sentDate = Date() - msg.setContent(content, "text/html;charset=utf-8") - Transport.send(msg) - } catch (mex: Exception) { - mex.printStackTrace() - } - - } - - /** - * 返回激活链接 - * - * @param email email - * @return 有3个参数 email password time - */ - fun redirectValidateUrl(email: String, password: String): String { - val now = TimeUtil.nowOfMills - val sb = StringBuilder("点击下面链接激活账号,48小时生效,否则重新注册账号,链接只能使用一次,请尽快激活!
") - sb.append("") - sb.append("http://localhost:8080/user/validate?email=") - sb.append(email) - sb.append("&password=") - sb.append(password) - sb.append("&time=") - sb.append(now) - sb.append("
") - sb.append("小莫
") - sb.append("") - sb.append(TimeUtil.formatDate) - sb.append("
") - return sb.toString() - } -} diff --git a/core/src/main/java/info/xiaomo/core/untils/Md5Util.java b/core/src/main/java/info/xiaomo/core/untils/Md5Util.java new file mode 100644 index 00000000..3a14c314 --- /dev/null +++ b/core/src/main/java/info/xiaomo/core/untils/Md5Util.java @@ -0,0 +1,88 @@ +package info.xiaomo.core.untils; + +import java.security.MessageDigest; + +/** + * │\__╭╭╭╭╭__/│ + * │         │ + * │         │ + * │ -      -│ + * │≡    o ≡ │ + * │         │ + * ╰——┬O◤▽◥O┬——╯ + * |  o  | + * |╭---╮把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 16/4/3 10:03 + * Description: md5加密解密 + * Copyright(©) 2015 by xiaomo. + */ +public class Md5Util { + + private final static String[] HEX_DIGITS = { + "0", "1", "2", "3", "4", "5", "6", "7", + "8", "9", "a", "b", "c", "d", "e", "f"}; + + /** + * 转换字节数组为16进制字串 + * + * @param b 字节数组 + * @return 16进制字串 + */ + public static String byteArrayToString(byte[] b) { + StringBuilder resultSb = new StringBuilder(); + for (byte aB : b) { + //若使用本函数转换则可得到加密结果的16进制表示,即数字字母混合的形式 + resultSb.append(byteToHexString(aB)); + } + return resultSb.toString(); + } + + private static String byteToNumString(byte b) { + + int tempB = b; + if (tempB < 0) { + tempB = 256 + tempB; + } + + return String.valueOf(tempB); + } + + private static String byteToHexString(byte b) { + int n = b; + if (n < 0) { + n = 256 + n; + } + int d1 = n / 16; + int d2 = n % 16; + return HEX_DIGITS[d1] + HEX_DIGITS[d2]; + } + + public static String encode(String password, String salt) { + String resultString = null; + try { + resultString = password + salt; + MessageDigest md = MessageDigest.getInstance("md5"); + resultString = byteArrayToString(md.digest(resultString.getBytes())); + } catch (Exception ex) { + ex.printStackTrace(); + } + return resultString; + } + + public static void main(String[] args) { + String password = "xiaomo"; + String salt = RandomUtil.createSalt(); + System.out.println("原数据:" + password); + System.out.println("盐值:" + salt); + System.out.println("MD5后:" + encode(password, salt)); + } + +} diff --git a/core/src/main/java/info/xiaomo/core/untils/Md5Util.kt b/core/src/main/java/info/xiaomo/core/untils/Md5Util.kt deleted file mode 100644 index b381b187..00000000 --- a/core/src/main/java/info/xiaomo/core/untils/Md5Util.kt +++ /dev/null @@ -1,89 +0,0 @@ -package info.xiaomo.core.untils - -import java.security.MessageDigest - -/** - * │\__╭╭╭╭╭__/│ - * │         │ - * │         │ - * │ -      -│ - * │≡    o ≡ │ - * │         │ - * ╰——┬O◤▽◥O┬——╯ - * |  o  | - * |╭---╮把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * - * Date: 16/4/3 10:03 - * Description: md5加密解密 - * Copyright(©) 2015 by xiaomo. - */ -object Md5Util { - - private val HEX_DIGITS = arrayOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f") - - /** - * 转换字节数组为16进制字串 - * - * @param b 字节数组 - * @return 16进制字串 - */ - fun byteArrayToString(b: ByteArray): String { - val resultSb = StringBuilder() - for (aB in b) { - //若使用本函数转换则可得到加密结果的16进制表示,即数字字母混合的形式 - resultSb.append(byteToHexString(aB)) - } - return resultSb.toString() - } - - private fun byteToNumString(b: Byte): String { - - var tempB = b.toInt() - if (tempB < 0) { - tempB += 256 - } - - return tempB.toString() - } - - private fun byteToHexString(b: Byte): String { - var n = b.toInt() - if (n < 0) { - n = 256 + n - } - val d1 = n / 16 - val d2 = n % 16 - return HEX_DIGITS[d1] + HEX_DIGITS[d2] - } - - fun encode(password: String, salt: String): String? { - var resultString: String? = null - try { - resultString = password + salt - val md = MessageDigest.getInstance("md5") - resultString = byteArrayToString(md.digest(resultString.toByteArray())) - } catch (ex: Exception) { - ex.printStackTrace() - } - - return resultString - } - - @JvmStatic - fun main(args: Array) { - val password = "xiaomo" - val salt = RandomUtil.createSalt() - println("原数据:" + password) - println("盐值:" + salt) - println("MD5后:" + encode(password, salt)) - } - -} diff --git a/core/src/main/java/info/xiaomo/core/untils/PropsUtil.java b/core/src/main/java/info/xiaomo/core/untils/PropsUtil.java new file mode 100644 index 00000000..7a202818 --- /dev/null +++ b/core/src/main/java/info/xiaomo/core/untils/PropsUtil.java @@ -0,0 +1,32 @@ +package info.xiaomo.core.untils; + +import java.io.FileInputStream; +import java.io.InputStream; +import java.util.Properties; + +/** + * @author : xiaomo + */ +public class PropsUtil { + + /** + * 构造函数 + * 找到数据源,并用这个数据源创建连接 + */ + private PropsUtil() { + + } + + public static Properties getProperties(String url) { + Properties properties = null; + try { + InputStream fs = new FileInputStream(url); + properties = new Properties(); + properties.load(fs); + } catch (Exception e) { + e.printStackTrace(); + } + return properties; + } + +} diff --git a/core/src/main/java/info/xiaomo/core/untils/PropsUtil.kt b/core/src/main/java/info/xiaomo/core/untils/PropsUtil.kt deleted file mode 100644 index 4db61599..00000000 --- a/core/src/main/java/info/xiaomo/core/untils/PropsUtil.kt +++ /dev/null @@ -1,28 +0,0 @@ -package info.xiaomo.core.untils - -import java.io.FileInputStream -import java.util.* - -/** - * @author : xiaomo - */ -object PropsUtil { - - fun getProperties(url: String): Properties? { - var properties: Properties? = null - try { - val fs = FileInputStream(url) - properties = Properties() - properties.load(fs) - } catch (e: Exception) { - e.printStackTrace() - } - - return properties - } - -} -/** - * 构造函数 - * 找到数据源,并用这个数据源创建连接 - */ diff --git a/core/src/main/java/info/xiaomo/core/untils/RandomUtil.java b/core/src/main/java/info/xiaomo/core/untils/RandomUtil.java new file mode 100644 index 00000000..d1dd3b50 --- /dev/null +++ b/core/src/main/java/info/xiaomo/core/untils/RandomUtil.java @@ -0,0 +1,181 @@ +/** + * 文 件 名: RandomUtil.java + * 工 程 名: MainServer + * 创建日期: 2015年2月5日 下午2:38:48 + * 创建作者: 杨 强 <281455776@qq.com> + */ +package info.xiaomo.core.untils; + +import org.apache.commons.lang3.RandomStringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.*; +import java.util.concurrent.ThreadLocalRandom; + +/** + * 随机工具类 + * + * @author : xiaomo + */ +public class RandomUtil { + private static final Logger LOGGER = LoggerFactory.getLogger(RandomUtil.class); + private static final String NUM_S = "0123456789"; + private static final String STR_S = "abcdefghijklmnopqrstuvwxyz0123456789"; + + /** + * 随机产生min到max之间的一个整数值,包含min和max + */ + public static int random(int min, int max) { + if (min > max) { + throw new IllegalArgumentException("传入的范围不合法!最小值不能大于最大值!"); + } + return ThreadLocalRandom.current().nextInt(max - min + 1) + min; + } + + /** + * 根据几率计算是否生成,成功几率是sucRange/maxRange + * + * @param maxRange 最大范围,随机范围是[1,maxRange] + * @param sucRange 成功范围,成功范围是[1,sucRange] + * @return 成功true失败false + */ + public static boolean isGenerate(int maxRange, int sucRange) { + return maxRange == sucRange || sucRange != 0 && random(1, maxRange) <= sucRange; + } + + /** + * 从指定的的元素集中随机一个元素 + * + * @param collection 元素集 + */ + public static T randomElement(Collection collection) { + if (collection == null || collection.isEmpty()) { + throw new IllegalArgumentException("元素集不能为空!"); + } + int index = random(0, collection.size() - 1); + Iterator it = collection.iterator(); + for (int i = 0; i <= index && it.hasNext(); i++) { + T t = it.next(); + if (i == index) { + return t; + } + } + return null; + } + + + /** + * 生成一个10位的tonken用于http cache(纯数字) + * + * @return String 返回类型(纯数字) + */ + public static String getTonken() { + return RandomStringUtils.random(10, NUM_S); + } + + /** + * 生成随机数 + * + * @return String 返回类型 + */ + public static String randomPwd(int count) { + return RandomStringUtils.random(count, STR_S); + } + + /** + * 生成随机数 + * + * @return String 返回类型 + */ + public static String randomPwd() { + return RandomStringUtils.random(10, STR_S); + } + + /** + * 从指定的元素数组中随机出一个元素 + * + * @param array 元素数组 + */ + public static T randomElement(T[] array) { + if (array == null || array.length == 0) { + throw new IllegalArgumentException("元素数组不能为空!"); + } + return randomElement(Arrays.asList(array)); + } + + /** + * 根据每个几率返回随机的一个索引 + * + * @return -1失败or随机的索引 + */ + public static int randomIndexByProb(List probs) { + LinkedList newProbs = new LinkedList(); + int lastTotalProb = 0; + for (Integer prob : probs) { + int cuttentTotalProb = lastTotalProb + prob; + newProbs.add(cuttentTotalProb); + lastTotalProb = cuttentTotalProb; + } + if (newProbs.isEmpty()) { + return -1; + } + int totalProb = newProbs.getLast(); + // 总概率为0 + if (totalProb == 0) { + return -1; + } + int random = random(0, totalProb - 1); + for (int i = 0; i < newProbs.size(); i++) { + int cuttentTotalProb = newProbs.get(i); + if (cuttentTotalProb > random) { + return i; + } + } + LOGGER.error("计算概率错误{}", probs.toString()); + return -1; + } + + /** + * 根据每个几率返回随机的一个索引 + * + * @return -1失败or随机的索引 + */ + public static int randomIndexByProb(int[] array) { + if (array == null || array.length == 0) { + throw new IllegalArgumentException("元素数组不能为空!"); + } + List list; + list = new ArrayList<>(); + for (int i : array) { + list.add(i); + } + return randomIndexByProb(list); + } + + /** + * 生成盐值 + * + * @return + */ + public static String createSalt() { + return randomPwd(10); + } + + + /** + * 生成盐值 + * + * @param count + * @return + */ + public static String createSalt(int count) { + return randomPwd(count); + } + + public static void main(String[] args) { + String salt = createSalt(); + System.out.println(salt); + System.out.println(Md5Util.encode("xiaomo", salt)); + } +} diff --git a/core/src/main/java/info/xiaomo/core/untils/RandomUtil.kt b/core/src/main/java/info/xiaomo/core/untils/RandomUtil.kt deleted file mode 100644 index f328d7d8..00000000 --- a/core/src/main/java/info/xiaomo/core/untils/RandomUtil.kt +++ /dev/null @@ -1,179 +0,0 @@ -/** - * 文 件 名: RandomUtil.java - * 工 程 名: MainServer - * 创建日期: 2015年2月5日 下午2:38:48 - * 创建作者: 杨 强 <281455776@qq.com> - */ -package info.xiaomo.core.untils - -import org.apache.commons.lang3.RandomStringUtils -import org.slf4j.LoggerFactory -import java.util.* -import java.util.concurrent.ThreadLocalRandom - -/** - * 随机工具类 - * - * @author : xiaomo - */ -object RandomUtil { - private val LOGGER = LoggerFactory.getLogger(RandomUtil::class.java) - private val NUM_S = "0123456789" - private val STR_S = "abcdefghijklmnopqrstuvwxyz0123456789" - - - /** - * 生成一个10位的tonken用于http cache(纯数字) - * - * @return String 返回类型(纯数字) - */ - val tonken: String - get() = RandomStringUtils.random(10, NUM_S) - - /** - * 随机产生min到max之间的一个整数值,包含min和max - */ - fun random(min: Int, max: Int): Int { - if (min > max) { - throw IllegalArgumentException("传入的范围不合法!最小值不能大于最大值!") - } - return ThreadLocalRandom.current().nextInt(max - min + 1) + min - } - - /** - * 根据几率计算是否生成,成功几率是sucRange/maxRange - * - * @param maxRange 最大范围,随机范围是[1,maxRange] - * @param sucRange 成功范围,成功范围是[1,sucRange] - * @return 成功true失败false - */ - fun isGenerate(maxRange: Int, sucRange: Int): Boolean { - return maxRange == sucRange || sucRange != 0 && random(1, maxRange) <= sucRange - } - - /** - * 从指定的的元素集中随机一个元素 - * - * @param collection 元素集 - */ - fun randomElement(collection: Collection?): T? { - if (collection == null || collection.isEmpty()) { - throw IllegalArgumentException("元素集不能为空!") - } - val index = random(0, collection.size - 1) - val it = collection.iterator() - var i = 0 - while (i <= index && it.hasNext()) { - val t = it.next() - if (i == index) { - return t - } - i++ - } - return null - } - - /** - * 生成随机数 - * - * @return String 返回类型 - */ - fun randomPwd(count: Int): String { - return RandomStringUtils.random(count, STR_S) - } - - /** - * 生成随机数 - * - * @return String 返回类型 - */ - fun randomPwd(): String { - return RandomStringUtils.random(10, STR_S) - } - - /** - * 从指定的元素数组中随机出一个元素 - * - * @param array 元素数组 - */ - fun randomElement(array: Array?): T? { - if (array == null || array.size == 0) { - throw IllegalArgumentException("元素数组不能为空!") - } - return randomElement(Arrays.asList(*array)) - } - - /** - * 根据每个几率返回随机的一个索引 - * - * @return -1失败or随机的索引 - */ - fun randomIndexByProb(probs: List): Int { - val newProbs = LinkedList() - var lastTotalProb = 0 - for (prob in probs) { - val cuttentTotalProb = lastTotalProb + prob - newProbs.add(cuttentTotalProb) - lastTotalProb = cuttentTotalProb - } - if (newProbs.isEmpty()) { - return -1 - } - val totalProb = newProbs.last - // 总概率为0 - if (totalProb == 0) { - return -1 - } - val random = random(0, totalProb - 1) - for (i in newProbs.indices) { - val cuttentTotalProb = newProbs[i] - if (cuttentTotalProb > random) { - return i - } - } - LOGGER.error("计算概率错误{}", probs.toString()) - return -1 - } - - /** - * 根据每个几率返回随机的一个索引 - * - * @return -1失败or随机的索引 - */ - fun randomIndexByProb(array: IntArray?): Int { - if (array == null || array.size == 0) { - throw IllegalArgumentException("元素数组不能为空!") - } - val list: MutableList - list = ArrayList() - for (i in array) { - list.add(i) - } - return randomIndexByProb(list) - } - - /** - * 生成盐值 - * @return - */ - fun createSalt(): String { - return randomPwd(10) - } - - - /** - * 生成盐值 - * @param count - * @return - */ - fun createSalt(count: Int): String { - return randomPwd(count) - } - - @JvmStatic - fun main(args: Array) { - val salt = createSalt() - println(salt) - println(Md5Util.encode("xiaomo", salt)) - } -} diff --git a/core/src/main/java/info/xiaomo/core/untils/RegExUtil.java b/core/src/main/java/info/xiaomo/core/untils/RegExUtil.java new file mode 100644 index 00000000..976c2712 --- /dev/null +++ b/core/src/main/java/info/xiaomo/core/untils/RegExUtil.java @@ -0,0 +1,264 @@ +package info.xiaomo.core.untils; + +import org.apache.commons.lang3.StringUtils; + +import java.util.Vector; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; + +/** + * 这是个正则表达式应用类,用来匹配和替换字串用的 + * + * @author xiaomo + */ + +public class RegExUtil { + + /** + * 用户名 + */ + public static final String USER_NAME = "^[a-zA-Z\\u4E00-\\u9FA5][a-zA-Z0-9_\\u4E00-\\u9FA5]{1,11}$"; + + /** + * 密码 + */ + public static final String USER_PASSWORD = "^.{6,32}$"; + + /** + * 邮箱 + */ + public static final String EMAIL = "^\\w+([-+.]*\\w+)*@([\\da-z](-[\\da-z])?)+(\\.{1,2}[a-z]+)+$"; + + /** + * 手机号 + */ + public static final String PHONE = "^1[34578]\\d{9}$"; + + /** + * 手机号或者邮箱 + */ + public static final String EMAIL_OR_PHONE = EMAIL + "|" + PHONE; + + /** + * URL路径 + */ + public static final String URL = "^(https?:\\/\\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})(:[\\d]+)?([\\/\\w\\.-]*)*\\/?$"; + + /** + * 身份证校验,初级校验,具体规则有一套算法 + */ + public static final String ID_CARD = "^\\d{15}$|^\\d{17}([0-9]|X)$"; + + /** + * 编译传入正则表达式和字符串去匹配,忽略大小写 + * + * @param regex regex + * @param beTestString beTestString + */ + public static boolean match(String regex, String beTestString) { + Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); + Matcher matcher = pattern.matcher(beTestString); + return matcher.matches(); + } + + /** + * 编译传入正则表达式在字符串中寻找,如果匹配到则为true + * + * @param regex regex + * @param beTestString beTestString + */ + public static boolean find(String regex, String beTestString) { + Pattern pattern = Pattern.compile(regex); + Matcher matcher = pattern.matcher(beTestString); + return matcher.find(); + } + + /** + * 编译传入正则表达式在字符串中寻找,如果找到返回第一个结果
+ * 找不到返回null + * + * @param regex regex + * @param beFoundString beFoundString + */ + public static String findResult(String regex, String beFoundString) { + Pattern pattern = Pattern.compile(regex); + Matcher matcher = pattern.matcher(beFoundString); + if (matcher.find()) { + return matcher.group(); + } + return null; + } + + /** + * 隐藏手机号中间4位 + * + * @param phone phone + * @return String + */ + public static String encodePhone(String phone) { + if (StringUtils.isBlank(phone)) { + return ""; + } + if (match(PHONE, phone)) { + String begin = phone.substring(0, 3); + String end = phone.substring(7, phone.length()); + return begin + "****" + end; + } + return phone; + } + + /** + * 要求大小写都匹配正则表达式 + * + * @param pattern 正则表达式模式 + * @param str 要匹配的字串 + * @return boolean值 + * @since 1.0 + */ + public static boolean ereg(String pattern, String str) throws PatternSyntaxException { + Pattern p = Pattern.compile(pattern); + Matcher m = p.matcher(str); + return m.find(); + } + + /** + * 匹配且替换字串 + * + * @param pattern 正则表达式模式 + * @param newstr 要替换匹配到的新字串 + * @param str 原始字串 + * @return 匹配后的字符串 + * @since 1.0 + */ + + public static String eregReplace(String pattern, String newstr, String str) throws PatternSyntaxException { + Pattern p = Pattern.compile(pattern); + Matcher m = p.matcher(str); + return m.replaceAll(newstr); + } + + /** + * 主要用于模板中模块标记分析函数 把查找到的元素加到vector中 + * + * @param pattern 为正则表达式模式 + * @param str 原始字串 + * @return vector + * @since 1.0 + */ + public static Vector splitTags2Vector(String pattern, String str) throws PatternSyntaxException { + Vector vector = new Vector<>(); + Pattern p = Pattern.compile(pattern); + Matcher m = p.matcher(str); + while (m.find()) { + vector.add(eregReplace("(\\[\\#)|(\\#\\])", "", m.group())); + } + return vector; + } + + /** + * 模块标记分析函数 + * 功能主要是把查找到的元素加到vector中 + * + * @param pattern 为正则表达式模式 + * @param str 原始字串 + * @since 1.0 + */ + public static String[] splitTags(String pattern, String str) { + Pattern p = Pattern.compile(pattern); + Matcher m = p.matcher(str); + String[] array = new String[m.groupCount()]; + int i = 0; + while (m.find()) { + array[i] = eregReplace("(\\[\\#)|(\\#\\])", "", m.group()); + i++; + } + return array; + } + + + /** + * 匹配所有符合模式要求的字串并加到矢量vector数组中 + * + * @param pattern 为正则表达式模式 + * @param str 原始字串 + * @return vector + * @since 1.0 + */ + public static Vector regMatchAll2Vector(String pattern, String str) throws PatternSyntaxException { + Vector vector = new Vector<>(); + Pattern p = Pattern.compile(pattern); + Matcher m = p.matcher(str); + while (m.find()) { + vector.add(m.group()); + } + return vector; + } + + /** + * 匹配所有符合模式要求的字串并加到字符串数组中 + * + * @param pattern 为正则表达式模式 + * @param str 原始字串 + * @return array + * @since 1.0 + */ + public static String[] regMatchAll2Array(String pattern, String str) throws PatternSyntaxException { + Pattern p = Pattern.compile(pattern); + Matcher m = p.matcher(str); + String[] array = new String[m.groupCount()]; + int i = 0; + while (m.find()) { + array[i] = m.group(); + i++; + } + return array; + } + + /** + * 转义正则表达式字符(之所以需要将\和$字符用escapeDollarBackslash方法的方式是因为用repalceAll是不行的,简单的试试"$".repalceAll("\\$","\\\\$")你会发现这个调用会导致数组越界错误) + * + * @param original 为正则表达式模式 + * @return array + * @since 1.0 + */ + public static String escapeDollarBackslash(String original) { + StringBuilder buffer = new StringBuilder(original.length()); + for (int i = 0; i < original.length(); i++) { + char c = original.charAt(i); + if (c == '\\' || c == '$') { + buffer.append("\\").append(c); + } else { + buffer.append(c); + } + } + return buffer.toString(); + } + + /** + * 提取指定字串的函数 + * 功能主要是把查找到的元素 + * + * @param pattern 为正则表达式模式 + * @param str 原始字串 + * @since 1.0 + */ + public static String fetchStr(String pattern, String str) { + String returnValue = null; + try { + Pattern p = Pattern.compile(pattern); + Matcher m = p.matcher(str); + while (m.find()) { + returnValue = m.group(); + } + return returnValue; + } catch (PatternSyntaxException e) { + return returnValue; + } + } + + + public static void main(String[] args) { + System.out.println(ereg(ID_CARD, "420325199210211911")); + } +} diff --git a/core/src/main/java/info/xiaomo/core/untils/RegExUtil.kt b/core/src/main/java/info/xiaomo/core/untils/RegExUtil.kt deleted file mode 100644 index 34a67e33..00000000 --- a/core/src/main/java/info/xiaomo/core/untils/RegExUtil.kt +++ /dev/null @@ -1,268 +0,0 @@ -package info.xiaomo.core.untils - -import org.apache.commons.lang3.StringUtils -import java.util.* -import java.util.regex.Pattern -import java.util.regex.PatternSyntaxException - -/** - * 这是个正则表达式应用类,用来匹配和替换字串用的 - * - * @author xiaomo - */ - -object RegExUtil { - - /** - * 用户名 - */ - val USER_NAME = "^[a-zA-Z\\u4E00-\\u9FA5][a-zA-Z0-9_\\u4E00-\\u9FA5]{1,11}$" - - /** - * 密码 - */ - val USER_PASSWORD = "^.{6,32}$" - - /** - * 邮箱 - */ - val EMAIL = "^\\w+([-+.]*\\w+)*@([\\da-z](-[\\da-z])?)+(\\.{1,2}[a-z]+)+$" - - /** - * 手机号 - */ - val PHONE = "^1[34578]\\d{9}$" - - /** - * 手机号或者邮箱 - */ - val EMAIL_OR_PHONE = EMAIL + "|" + PHONE - - /** - * URL路径 - */ - val URL = "^(https?:\\/\\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})(:[\\d]+)?([\\/\\w\\.-]*)*\\/?$" - - /** - * 身份证校验,初级校验,具体规则有一套算法 - */ - val ID_CARD = "^\\d{15}$|^\\d{17}([0-9]|X)$" - - /** - * 编译传入正则表达式和字符串去匹配,忽略大小写 - * - * @param regex regex - * @param beTestString beTestString - */ - fun match(regex: String, beTestString: String): Boolean { - val pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE) - val matcher = pattern.matcher(beTestString) - return matcher.matches() - } - - /** - * 编译传入正则表达式在字符串中寻找,如果匹配到则为true - * - * @param regex regex - * @param beTestString beTestString - */ - fun find(regex: String, beTestString: String): Boolean { - val pattern = Pattern.compile(regex) - val matcher = pattern.matcher(beTestString) - return matcher.find() - } - - /** - * 编译传入正则表达式在字符串中寻找,如果找到返回第一个结果

- * 找不到返回null - * - * @param regex regex - * @param beFoundString beFoundString - */ - fun findResult(regex: String, beFoundString: String): String? { - val pattern = Pattern.compile(regex) - val matcher = pattern.matcher(beFoundString) - return if (matcher.find()) { - matcher.group() - } else null - } - - /** - * 隐藏手机号中间4位 - * - * @param phone phone - * @return String - */ - fun encodePhone(phone: String): String { - if (StringUtils.isBlank(phone)) { - return "" - } - if (match(PHONE, phone)) { - val begin = phone.substring(0, 3) - val end = phone.substring(7, phone.length) - return begin + "****" + end - } - return phone - } - - /** - * 要求大小写都匹配正则表达式 - * - * @param pattern 正则表达式模式 - * @param str 要匹配的字串 - * @return boolean值 - * @since 1.0 - */ - @Throws(PatternSyntaxException::class) - fun ereg(pattern: String, str: String): Boolean { - val p = Pattern.compile(pattern) - val m = p.matcher(str) - return m.find() - } - - /** - * 匹配且替换字串 - * - * @param pattern 正则表达式模式 - * @param newstr 要替换匹配到的新字串 - * @param str 原始字串 - * @return 匹配后的字符串 - * @since 1.0 - */ - - @Throws(PatternSyntaxException::class) - fun eregReplace(pattern: String, newstr: String, str: String): String { - val p = Pattern.compile(pattern) - val m = p.matcher(str) - return m.replaceAll(newstr) - } - - /** - * 主要用于模板中模块标记分析函数 把查找到的元素加到vector中 - * - * @param pattern 为正则表达式模式 - * @param str 原始字串 - * @return vector - * @since 1.0 - */ - @Throws(PatternSyntaxException::class) - fun splitTags2Vector(pattern: String, str: String): Vector { - val vector = Vector() - val p = Pattern.compile(pattern) - val m = p.matcher(str) - while (m.find()) { - vector.add(eregReplace("(\\[\\#)|(\\#\\])", "", m.group())) - } - return vector - } - - /** - * 模块标记分析函数 - * 功能主要是把查找到的元素加到vector中 - * - * @param pattern 为正则表达式模式 - * @param str 原始字串 - * @since 1.0 - */ - fun splitTags(pattern: String, str: String): Array { - val p = Pattern.compile(pattern) - val m = p.matcher(str) - val array = arrayOfNulls(m.groupCount()) - var i = 0 - while (m.find()) { - array[i] = eregReplace("(\\[\\#)|(\\#\\])", "", m.group()) - i++ - } - return array - } - - - /** - * 匹配所有符合模式要求的字串并加到矢量vector数组中 - * - * @param pattern 为正则表达式模式 - * @param str 原始字串 - * @return vector - * @since 1.0 - */ - @Throws(PatternSyntaxException::class) - fun regMatchAll2Vector(pattern: String, str: String): Vector { - val vector = Vector() - val p = Pattern.compile(pattern) - val m = p.matcher(str) - while (m.find()) { - vector.add(m.group()) - } - return vector - } - - /** - * 匹配所有符合模式要求的字串并加到字符串数组中 - * - * @param pattern 为正则表达式模式 - * @param str 原始字串 - * @return array - * @since 1.0 - */ - @Throws(PatternSyntaxException::class) - fun regMatchAll2Array(pattern: String, str: String): Array { - val p = Pattern.compile(pattern) - val m = p.matcher(str) - val array = arrayOfNulls(m.groupCount()) - var i = 0 - while (m.find()) { - array[i] = m.group() - i++ - } - return array - } - - /** - * 转义正则表达式字符(之所以需要将\和$字符用escapeDollarBackslash方法的方式是因为用repalceAll是不行的,简单的试试"$".repalceAll("\\$","\\\\$")你会发现这个调用会导致数组越界错误) - * - * @param original 为正则表达式模式 - * @return array - * @since 1.0 - */ - fun escapeDollarBackslash(original: String): String { - val buffer = StringBuilder(original.length) - for (i in 0 until original.length) { - val c = original[i] - if (c == '\\' || c == '$') { - buffer.append("\\").append(c) - } else { - buffer.append(c) - } - } - return buffer.toString() - } - - /** - * 提取指定字串的函数 - * 功能主要是把查找到的元素 - * - * @param pattern 为正则表达式模式 - * @param str 原始字串 - * @since 1.0 - */ - fun fetchStr(pattern: String, str: String): String? { - var returnValue: String? = null - try { - val p = Pattern.compile(pattern) - val m = p.matcher(str) - while (m.find()) { - returnValue = m.group() - } - return returnValue - } catch (e: PatternSyntaxException) { - return returnValue - } - - } - - - @JvmStatic - fun main(args: Array) { - println(ereg(ID_CARD, "420325199210211911")) - } -} diff --git a/core/src/main/java/info/xiaomo/core/untils/SerializeUtil.java b/core/src/main/java/info/xiaomo/core/untils/SerializeUtil.java new file mode 100644 index 00000000..f6be3ed2 --- /dev/null +++ b/core/src/main/java/info/xiaomo/core/untils/SerializeUtil.java @@ -0,0 +1,67 @@ +package info.xiaomo.core.untils; + +import java.io.*; +import java.nio.charset.StandardCharsets; + +/** + * │\__╭╭╭╭╭__/│ + * │         │ + * │         │ + * │ -      -│ + * │≡    o ≡ │ + * │         │ + * ╰——┬O◤▽◥O┬——╯ + * |  o  | + * |╭---╮把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 15/9/6 16:05 + * Description: 序列化通用方法 + * Copyright(©) 2015 by xiaomo. + */ +public class SerializeUtil { + + /** + * 序列化 + */ + public static String serialize(Object object) { + if (object == null) { + return null; + } + ObjectOutputStream oos; + ByteArrayOutputStream baos; + try { + baos = new ByteArrayOutputStream(); + oos = new ObjectOutputStream(baos); + oos.writeObject(object); + byte[] bytes = baos.toByteArray(); + return new String(bytes, StandardCharsets.UTF_8); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * 反序列化 + */ + public static Object unserialize(String s) throws UnsupportedEncodingException { + byte[] bytes = s.getBytes(StandardCharsets.UTF_8); + ByteArrayInputStream bais; + try { + //反序列化 + bais = new ByteArrayInputStream(bytes); + ObjectInputStream ois = new ObjectInputStream(bais); + return ois.readObject(); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } +} \ No newline at end of file diff --git a/core/src/main/java/info/xiaomo/core/untils/SerializeUtil.kt b/core/src/main/java/info/xiaomo/core/untils/SerializeUtil.kt deleted file mode 100644 index b6f8bafb..00000000 --- a/core/src/main/java/info/xiaomo/core/untils/SerializeUtil.kt +++ /dev/null @@ -1,69 +0,0 @@ -package info.xiaomo.core.untils - -import java.io.* - -/** - * │\__╭╭╭╭╭__/│ - * │         │ - * │         │ - * │ -      -│ - * │≡    o ≡ │ - * │         │ - * ╰——┬O◤▽◥O┬——╯ - * |  o  | - * |╭---╮把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 15/9/6 16:05 - * Description: 序列化通用方法 - * Copyright(©) 2015 by xiaomo. - */ -object SerializeUtil { - - /** - * 序列化 - */ - fun serialize(`object`: Any?): String? { - if (`object` == null) { - return null - } - val oos: ObjectOutputStream - val baos: ByteArrayOutputStream - try { - baos = ByteArrayOutputStream() - oos = ObjectOutputStream(baos) - oos.writeObject(`object`) - val bytes = baos.toByteArray() - return String(bytes) - } catch (e: Exception) { - e.printStackTrace() - } - - return null - } - - /** - * 反序列化 - */ - @Throws(UnsupportedEncodingException::class) - fun unserialize(s: String): Any? { - val bytes = s.toByteArray(charset("utf-8")) - val bais: ByteArrayInputStream - try { - //反序列化 - bais = ByteArrayInputStream(bytes) - val ois = ObjectInputStream(bais) - return ois.readObject() - } catch (e: Exception) { - e.printStackTrace() - } - - return null - } -} \ No newline at end of file diff --git a/core/src/main/java/info/xiaomo/core/untils/SqlUtil.java b/core/src/main/java/info/xiaomo/core/untils/SqlUtil.java new file mode 100644 index 00000000..7e69e630 --- /dev/null +++ b/core/src/main/java/info/xiaomo/core/untils/SqlUtil.java @@ -0,0 +1,67 @@ +package info.xiaomo.core.untils; + +import org.apache.commons.lang3.StringUtils; + +import java.util.Arrays; +import java.util.StringTokenizer; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + *

+ * + * @author : xiaomo + * github: https://github.com/syoubaku + * email: xiaomo@xiamoo.info + * QQ_NO: 83387856 + * Date: 17/5/11 17:56 + * Description: + * Copyright(©) 2017 by xiaomo. + */ +public class SqlUtil { + + + /** + * 功能描述: 生成sql占位符 ?,?,? + * + * @return String 返回类型 + */ + public static String sqlHolder(int size) { + String[] paras = new String[size]; + Arrays.fill(paras, "?"); + return StringUtils.join(paras, ','); + } + + /** + * sql语句 处理 + * + * @param sql 要进行处理的sql语句 + * @param dbtype 数据库类型 + * @return 处理后的sql语句 + */ + public static String sql4DB(String sql, String dbtype) { + String oracle = "oracle"; + if (!oracle.equalsIgnoreCase(dbtype)) { + sql = StringUtil.toISO(sql); + } + return sql; + } + + private String delNewSQlString(String sql) { + return "in (" + sql.replace('|', ',') + ")"; + } + + private String delSQlString(String sql) { + StringBuilder delSql = new StringBuilder("in("); + StringTokenizer tokenizer = new StringTokenizer(sql, "|"); + + // 标记本身等于分隔符的特殊情况 + delSql.append(tokenizer.nextToken()); + while (tokenizer.hasMoreTokens()) { + delSql.append(tokenizer.nextToken()).append(","); + } + delSql = new StringBuilder(delSql.substring(0, delSql.length() - 1) + ")"); + return delSql.toString(); + } +} diff --git a/core/src/main/java/info/xiaomo/core/untils/SqlUtil.kt b/core/src/main/java/info/xiaomo/core/untils/SqlUtil.kt deleted file mode 100644 index 778a49e5..00000000 --- a/core/src/main/java/info/xiaomo/core/untils/SqlUtil.kt +++ /dev/null @@ -1,70 +0,0 @@ -package info.xiaomo.core.untils - -import org.apache.commons.lang3.StringUtils -import java.util.* - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * - * @author : xiaomo - * github: https://github.com/syoubaku - * email: xiaomo@xiamoo.info - * QQ_NO: 83387856 - * Date: 17/5/11 17:56 - * Description: - * Copyright(©) 2017 by xiaomo. - */ -class SqlUtil { - - private fun delNewSQlString(sql: String): String { - return "in (" + sql.replace('|', ',') + ")" - } - - private fun delSQlString(sql: String): String { - var delSql = StringBuilder("in(") - val tokenizer = StringTokenizer(sql, "|") - - // 标记本身等于分隔符的特殊情况 - delSql.append(tokenizer.nextToken()) - while (tokenizer.hasMoreTokens()) { - delSql.append(tokenizer.nextToken()).append(",") - } - delSql = StringBuilder(delSql.substring(0, delSql.length - 1) + ")") - return delSql.toString() - } - - companion object { - - - /** - * 功能描述: 生成sql占位符 ?,?,? - * - * @return String 返回类型 - */ - fun sqlHolder(size: Int): String { - val paras = arrayOfNulls(size) - Arrays.fill(paras, "?") - return StringUtils.join(paras, ',') - } - - /** - * sql语句 处理 - * - * @param sql 要进行处理的sql语句 - * @param dbtype 数据库类型 - * @return 处理后的sql语句 - */ - fun sql4DB(sql: String, dbtype: String): String { - var sql = sql - val oracle = "oracle" - if (!oracle.equals(dbtype, ignoreCase = true)) { - sql = StringUtil.toISO(sql) - } - return sql - } - } -} diff --git a/core/src/main/java/info/xiaomo/core/untils/StringUtil.java b/core/src/main/java/info/xiaomo/core/untils/StringUtil.java new file mode 100644 index 00000000..5cf3fda8 --- /dev/null +++ b/core/src/main/java/info/xiaomo/core/untils/StringUtil.java @@ -0,0 +1,987 @@ +package info.xiaomo.core.untils; + +import org.apache.commons.lang3.StringUtils; + +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.io.StringReader; +import java.io.UnsupportedEncodingException; +import java.text.NumberFormat; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + + +/** + * 对字符串的简单处理 + *

+ * + * @author : xiaomo + * @Date 2013-6-6 下午5:08:06 + */ +public class StringUtil extends StringUtils { + + /** + * ip正则表达式 + */ + public static final String IP_REGEX = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\." + "(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}"; + private final static String[] HEX = {"00", "01", "02", "03", "04", "05", + "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F", "10", + "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", + "1C", "1D", "1E", "1F", "20", "21", "22", "23", "24", "25", "26", + "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F", "30", "31", + "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", + "3D", "3E", "3F", "40", "41", "42", "43", "44", "45", "46", "47", + "48", "49", "4A", "4B", "4C", "4D", "4E", "4F", "50", "51", "52", + "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", + "5E", "5F", "60", "61", "62", "63", "64", "65", "66", "67", "68", + "69", "6A", "6B", "6C", "6D", "6E", "6F", "70", "71", "72", "73", + "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", + "7F", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", + "8A", "8B", "8C", "8D", "8E", "8F", "90", "91", "92", "93", "94", + "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F", + "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", + "AB", "AC", "AD", "AE", "AF", "B0", "B1", "B2", "B3", "B4", "B5", + "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF", "C0", + "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", + "CC", "CD", "CE", "CF", "D0", "D1", "D2", "D3", "D4", "D5", "D6", + "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF", "E0", "E1", + "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", + "ED", "EE", "EF", "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", + "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF"}; + private final static byte[] VAL = {0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, + 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, + 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, + 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, + 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x00, 0x01, + 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x3F, 0x3F, 0x3F, + 0x3F, 0x3F, 0x3F, 0x3F, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x3F, + 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, + 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, + 0x3F, 0x3F, 0x3F, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x3F, 0x3F, + 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, + 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, + 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, + 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, + 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, + 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, + 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, + 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, + 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, + 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, + 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, + 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, + 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, + 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F}; + private static final char[] QUOTE_ENCODE = """.toCharArray(); + private static final char[] AMP_ENCODE = "&".toCharArray(); + private static final char[] LT_ENCODE = "<".toCharArray(); + private static final char[] GT_ENCODE = ">".toCharArray(); + + /** + * 是否是空字符串 + * + * @param str 字符串 + * @return 是否为空 + */ + public static boolean isBlank(String str) { + return str == null || str.trim().isEmpty(); + } + + /** + * String数组转成int数组 + * + * @param numbers String[] + * @return List + */ + public static List strArrToIntList(String[] numbers) { + List intArr = new ArrayList<>(); + for (String number : numbers) { + intArr.add(Integer.parseInt(number)); + } + return intArr; + } + + /** + * String数组转成int数组 + * + * @param numbers String[] + * @return int[] + */ + public static int[] strArrToIntArr(String[] numbers) { + int[] intArr = new int[numbers.length]; + for (int i = 0; i < numbers.length; i++) { + intArr[i] = Integer.parseInt(numbers[i]); + } + return intArr; + } + + /** + * 根据指定的分隔符将字符串转为int数组 + * + * @param source 字符串 + * @param split 分割符 + * @return int[] + */ + public static int[] strToIntArr(String source, String split) { + if (isBlank(source)) { + return new int[0]; + } + String[] numbers = source.split(split); + return strArrToIntArr(numbers); + } + + /** + * 截取文字safe 中文 + * + * @return String 返回类型 + */ + public static String subCn(String string, int length, String more) { + if (StringUtils.isNotEmpty(string)) { + char[] chars = string.toCharArray(); + if (chars.length > length) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < length; i++) { + sb.append(chars[i]); + } + sb.append(more); + return sb.toString(); + } + } + return string; + } + + + /** + * 字符串全角转半角 + * + * @return String 返回类型 + */ + public static String togglecase(String string) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < string.length(); i++) { + sb.append(CharUtil.regularize(string.charAt(i))); + } + return sb.toString(); + } + + + /** + * 计算文字长度-.-无中文问题 + * + * @return int 返回类型 + */ + public static int getLength(String string) { + if (StringUtils.isBlank(string)) { + return 0; + } else { + char[] strChars = string.toCharArray(); + return strChars.length; + } + } + + /** + * 将字符串中特定模式的字符转换成map中对应的值, + * + * @param s 需要转换的字符串 + * @param map 转换所需的键值对集合 + * @return 转换后的字符串 + */ + public static String replace(String s, Map map) { + StringBuilder sb = new StringBuilder((int) (s.length() * 1.5)); + int cursor = 0; + String str = "${"; + char ch = '}'; + for (int start, end; (start = s.indexOf(str, cursor)) != -1 && (end = s.indexOf(ch, start)) != -1; ) { + sb.append(s.substring(cursor, start)); + String key = s.substring(start + 2, end); + sb.append(map.get(StringUtils.trim(key))); + cursor = end + 1; + } + sb.append(s.substring(cursor, s.length())); + return sb.toString(); + } + + + /** + * 获取ip + * + * @return ip 如果返回null,说明是一个不合法的ip地址格式 + */ + public static String getIP(HttpServletRequest request) { + String ip = request.getHeader("X-Requested-For"); + String unknown = "unknown"; + if (StringUtils.isBlank(ip) || unknown.equalsIgnoreCase(ip)) { + ip = request.getHeader("X-Forwarded-For"); + } + if (StringUtils.isBlank(ip) || unknown.equalsIgnoreCase(ip)) { + ip = request.getHeader("Proxy-Client-IP"); + } + if (StringUtils.isBlank(ip) || unknown.equalsIgnoreCase(ip)) { + ip = request.getHeader("WL-Proxy-Client-IP"); + } + if (StringUtils.isBlank(ip) || unknown.equalsIgnoreCase(ip)) { + ip = request.getHeader("HTTP_CLIENT_IP"); + } + if (StringUtils.isBlank(ip) || unknown.equalsIgnoreCase(ip)) { + ip = request.getHeader("HTTP_X_FORWARDED_FOR"); + } + if (StringUtils.isBlank(ip) || unknown.equalsIgnoreCase(ip)) { + ip = request.getRemoteAddr(); + } + if (!ip.matches(IP_REGEX)) { + return null; + } + return ip; + } + + /** + * 判断字符串是否为空,并删除首尾空格 + * + * @param tempSql + * @return + */ + public static String convertNullCode(String tempSql) { + if (tempSql == null) { + tempSql = ""; + } + return tempSql; + } + + /** + * 代码转换,GBK转换为ISO-8859-1 + * + * @param tempSql 要转换的字符串 + */ + public static String isocode(String tempSql) { + + String returnString = convertNullCode(tempSql); + + try { + byte[] ascii = returnString.getBytes("GBK"); + returnString = new String(ascii, "ISO-8859-1"); + } catch (Exception e) { + e.printStackTrace(); + } + return returnString; + } + + /** + * 代码转换,ISO-8859-1转换为GBK + * + * @param tempSql 要转换的字符串 + * @return + */ + public static String gbkcode(String tempSql) { + String returnString = convertNullCode(tempSql); + try { + byte[] ascii = returnString.getBytes("ISO-8859-1"); + returnString = new String(ascii, "GBK"); + } catch (Exception e) { + e.printStackTrace(); + } + return returnString; + } + + /** + * 代码转换 从srcCode转换为destCode + * + * @param srcCode 原编码 + * @param destCode 目标编码 + * @param strTmp 要转换的字符串 + * @return + */ + public static String convertCode(String srcCode, String destCode, String strTmp) { + String returnString = convertNullCode(strTmp); + try { + byte[] ascii = returnString.getBytes(srcCode); + returnString = new String(ascii, destCode); + } catch (Exception e) { + e.printStackTrace(); + } + return returnString; + } + + /** + * 代码转换,GBK转换为big5 + * + * @param tempSql 要转换的字符串 + * @return + */ + public static String gbk2big5code(String tempSql) { + String returnString = convertNullCode(tempSql); + try { + byte[] ascii = returnString.getBytes("GBK"); + returnString = new String(ascii, "big5"); + } catch (Exception e) { + e.printStackTrace(); + } + return returnString; + } + + /** + * 替换非法字符 + * + * @param input + * @return + */ + public static String convertHtml(String input) { + StringBuffer returnString = new StringBuffer(input.length()); + + char ch = ' '; + for (int i = 0; i < input.length(); i++) { + + ch = input.charAt(i); + + if (ch == '<') { + returnString = returnString.append("<"); + } else if (ch == '>') { + returnString = returnString.append(">"); + } else if (ch == ' ') { + returnString = returnString.append(" "); + } else if (ch == '\\') { + returnString = returnString.append("´"); + } else { + returnString = returnString.append(ch); + } + } + return returnString.toString(); + } + + + /** + * This method takes a string which may contain HTML tags (ie, <b>, + * <table>, etc) and converts the '<'' and '>' characters to + * their HTML escape sequences. + * + * @param in the text to be converted. + * @return the input string with the characters '<' and '>' replaced + * with their HTML escape sequences. + */ + public static String escapeHTMLTags(String in) { + if (in == null) { + return null; + } + char ch; + int i = 0; + int last = 0; + char[] input = in.toCharArray(); + int len = input.length; + StringBuilder out = new StringBuilder((int) (len * 1.3)); + for (; i < len; i++) { + ch = input[i]; + + if (ch > '>') { + continue; + } else if (ch == '<') { + if (i > last) { + out.append(input, last, i - last); + } + last = i + 1; + out.append(LT_ENCODE); + } else if (ch == '>') { + if (i > last) { + out.append(input, last, i - last); + } + last = i + 1; + out.append(GT_ENCODE); + } + } + if (last == 0) { + return in; + } + if (i > last) { + out.append(input, last, i - last); + } + return out.toString(); + } + + public static String filterString(String allstr) { + StringBuilder returnString = new StringBuilder(allstr.length()); + char ch = ' '; + for (int i = 0; i < allstr.length(); i++) { + ch = allstr.charAt(i); + String lsTemp = "'"; + char lcTemp = lsTemp.charAt(0); + if (ch == lcTemp) { + returnString.append("''"); + } else { + returnString.append(ch); + } + } + return returnString.toString(); + } + + /** + * 数字的金额表达式 + */ + public static String convertNumToMoney(int num) { + NumberFormat formatc = NumberFormat.getCurrencyInstance(Locale.CHINA); + return formatc.format(num); + } + + + /** + * 数字的金额表达式 + * + * @param num 金额 + * @param inLocale 币种 + * @return 处理好的币种 + */ + public static String convertNumToMoney(int num, Locale inLocale) { + NumberFormat formatc = NumberFormat.getCurrencyInstance(inLocale); + return formatc.format(num); + } + + /** + * 格式化字符串,如果没有对应的参数则按照原样输出 + *

+ *

    + * 例如: + *
  • "获得{0}元宝,20"输出"获得20元宝"
  • + *
  • "{0}获得{1}元宝,XX"输出"XX获得{1}元宝"
  • + *
  • "{0}获得{1}元宝,XX,20"输出"XX获得20元宝"
  • + *
+ * + * @param str + * @param params + * @return + */ + public static String format(String str, Object... params) { + if (isBlank(str)) { + return str; + } + if (params == null || params.length == 0) { + return str; + } + String regex = "\\{(\\d+)}"; + Pattern p = Pattern.compile(regex); + Matcher m = p.matcher(str); + StringBuffer sb = new StringBuffer(); + while (m.find()) { + String param = m.group(); + int index = Integer.parseInt(m.group(1)); + if (params.length > index) { + Object obj = params[index]; + if (obj != null) { + param = obj.toString(); + } + } + m.appendReplacement(sb, param); + } + m.appendTail(sb); + return sb.toString(); + } + + + /** + *
+     * 例:
+     * String strVal="This is a dog";
+     * String strResult=CTools.replace(strVal,"dog","cat");
+     * 结果:
+     * strResult equals "This is cat"
+     *
+     * @param strSrc 要进行替换操作的字符串
+     * @param strOld 要查找的字符串
+     * @param strNew 要替换的字符串
+     * @return 替换后的字符串
+     * 
+     */
+    public static String replace(String strSrc, String strOld, String strNew) {
+        if (strSrc == null || strOld == null || strNew == null) {
+            return "";
+        }
+
+        int i = 0;
+//避免新旧字符一样产生死循环
+        if (strOld.equals(strNew)) {
+            return strSrc;
+        }
+
+        if ((i = strSrc.indexOf(strOld, i)) >= 0) {
+            char[] arrCsrc = strSrc.toCharArray();
+            char[] arrCnew = strNew.toCharArray();
+
+            int intOldLen = strOld.length();
+            StringBuilder buf = new StringBuilder(arrCsrc.length);
+            buf.append(arrCsrc, 0, i).append(arrCnew);
+
+            i += intOldLen;
+            int j = i;
+
+            while ((i = strSrc.indexOf(strOld, i)) > 0) {
+                buf.append(arrCsrc, j, i - j).append(arrCnew);
+                i += intOldLen;
+                j = i;
+            }
+            buf.append(arrCsrc, j, arrCsrc.length - j);
+            return buf.toString();
+        }
+        return strSrc;
+    }
+
+
+    /**
+     * 在将数据存入数据库前转换
+     *
+     * @param strVal 要转换的字符串
+     * @return 从“ISO8859_1”到“GBK”得到的字符串
+     * @since 1.0
+     */
+    public static String toChinese(String strVal) {
+        try {
+            if (strVal == null) {
+                return "";
+            } else {
+                strVal = strVal.trim();
+                strVal = new String(strVal.getBytes("ISO8859_1"), "GBK");
+                return strVal;
+            }
+        } catch (Exception exp) {
+            return "";
+        }
+    }
+
+    /**
+     * 编码转换 从UTF-8到GBK
+     *
+     * @param strVal
+     * @return
+     */
+    public static String toGBK(String strVal) {
+        try {
+            if (strVal == null) {
+                return "";
+            } else {
+                strVal = strVal.trim();
+                strVal = new String(strVal.getBytes("UTF-8"), "GBK");
+                return strVal;
+            }
+        } catch (Exception exp) {
+            return "";
+        }
+    }
+
+    /**
+     * 将数据从数据库中取出后转换   *
+     *
+     * @param strVal 要转换的字符串
+     * @return 从“GBK”到“ISO8859_1”得到的字符串
+     * @since 1.0
+     */
+    public static String toISO(String strVal) {
+        try {
+            if (strVal == null) {
+                return "";
+            } else {
+                strVal = new String(strVal.getBytes("GBK"), "ISO8859_1");
+                return strVal;
+            }
+        } catch (Exception exp) {
+            return "";
+        }
+    }
+
+    public static String gbk2UTF8(String strVal) {
+        try {
+            if (strVal == null) {
+                return "";
+            } else {
+                strVal = new String(strVal.getBytes("GBK"), "UTF-8");
+                return strVal;
+            }
+        } catch (Exception exp) {
+            return "";
+        }
+    }
+
+    public static String iso2utf8(String strVal) {
+        try {
+            if (strVal == null) {
+                return "";
+            } else {
+                strVal = new String(strVal.getBytes("ISO-8859-1"), "UTF-8");
+                return strVal;
+            }
+        } catch (Exception exp) {
+            return "";
+        }
+    }
+
+    public static String utf82iso(String strVal) {
+        try {
+            if (strVal == null) {
+                return "";
+            } else {
+                strVal = new String(strVal.getBytes("UTF-8"), "ISO-8859-1");
+                return strVal;
+            }
+        } catch (Exception exp) {
+            return "";
+        }
+    }
+
+
+    /**
+     * 实际处理 return toChineseNoReplace(null2Blank(str));
+     * 主要应用于老牛的信息发布
+     *
+     * @param str 要进行处理的字符串
+     * @return 转换后的字符串
+     */
+    public static String toChineseAndHtmlEncode(String str, int quotes) {
+        return HtmlUtil.htmlEncode(toChinese(str), quotes);
+    }
+
+    /**
+     * 把null值和""值转换成 
+     * 主要应用于页面表格格的显示
+     *
+     * @param str 要进行处理的字符串
+     * @return 转换后的字符串
+     */
+    public static String str4Table(String str) {
+        if (str == null) {
+            return " ";
+        } else if ("".equals(str)) {
+            return " ";
+        } else {
+            return str;
+        }
+    }
+
+    /**
+     * String型变量转换成int型变量
+     *
+     * @param str 要进行转换的字符串
+     * @return intVal 如果str不可以转换成int型数据,返回-1表示异常,否则返回转换后的值
+     * @since 1.0
+     */
+    public static int str2Int(String str) {
+        int intVal;
+
+        try {
+            intVal = Integer.parseInt(str);
+        } catch (Exception e) {
+            intVal = 0;
+        }
+
+        return intVal;
+    }
+
+    public static double str2Double(String str) {
+        double dVal = 0;
+
+        try {
+            dVal = Double.parseDouble(str);
+        } catch (Exception e) {
+            dVal = 0;
+        }
+
+        return dVal;
+    }
+
+
+    public static long str2Long(String str) {
+        long longVal = 0;
+
+        try {
+            longVal = Long.parseLong(str);
+        } catch (Exception e) {
+            longVal = 0;
+        }
+
+        return longVal;
+    }
+
+    public static float stringToFloat(String floatstr) {
+        float floatee;
+        floatee = Float.valueOf(floatstr);
+        return floatee;
+    }
+
+    public static String floatToString(float value) {
+        Float floatee = value;
+        return floatee.toString();
+    }
+
+    /**
+     * int型变量转换成String型变量
+     *
+     * @param intVal 要进行转换的整数
+     * @return str 如果intVal不可以转换成String型数据,返回空值表示异常,否则返回转换后的值
+     */
+    public static String int2Str(int intVal) {
+        String str;
+
+        try {
+            str = String.valueOf(intVal);
+        } catch (Exception e) {
+            str = "";
+        }
+
+        return str;
+    }
+
+    /**
+     * long型变量转换成String型变量
+     *
+     * @param longVal 要进行转换的整数
+     * @return str 如果longVal不可以转换成String型数据,返回空值表示异常,否则返回转换后的值
+     */
+
+    public static String long2Str(long longVal) {
+        String str;
+
+        try {
+            str = String.valueOf(longVal);
+        } catch (Exception e) {
+            str = "";
+        }
+
+        return str;
+    }
+
+    /**
+     * null 处理
+     *
+     * @param str 要进行转换的字符串
+     * @return 如果str为null值,返回空串"",否则返回str
+     */
+    public static String null2Blank(String str) {
+        if (str == null) {
+            return "";
+        } else {
+            return str;
+        }
+    }
+
+    /**
+     * null 处理
+     *
+     * @param d 要进行转换的日期对像
+     * @return 如果d为null值,返回空串"",否则返回d.toString()
+     */
+
+    public static String null2Blank(Date d) {
+        if (d == null) {
+            return "";
+        } else {
+            return d.toString();
+        }
+    }
+
+    /**
+     * null 处理
+     *
+     * @param str 要进行转换的字符串
+     * @return 如果str为null值,返回空串整数0,否则返回相应的整数
+     */
+    public static int null2Zero(String str) {
+        int intTmp;
+        intTmp = str2Int(str);
+        if (intTmp == -1) {
+            return 0;
+        } else {
+            return intTmp;
+        }
+    }
+
+    /**
+     * 把null转换为字符串"0"
+     *
+     * @param str
+     * @return
+     */
+    public static String null2SZero(String str) {
+        str = null2Blank(str);
+        if ("".equals(str)) {
+            return "0";
+        } else {
+            return str;
+        }
+    }
+
+
+    /**
+     * 字符串从GBK编码转换为Unicode编码
+     *
+     * @param text
+     * @return
+     */
+    public static String stringToUnicode(String text) {
+        StringBuffer result = new StringBuffer();
+        int input;
+        StringReader isr;
+        try {
+            isr = new StringReader(new String(text.getBytes(), "GBK"));
+        } catch (UnsupportedEncodingException e) {
+            return "-1";
+        }
+        try {
+            while ((input = isr.read()) != -1) {
+                result.append("&#x").append(input).append(";");
+
+            }
+        } catch (IOException e) {
+            return "-2";
+        }
+        isr.close();
+        return result.toString();
+
+    }
+
+    /**
+     * @param inStr
+     * @return
+     */
+    public static String gb2utf(String inStr) {
+        char temChr;
+        int ascInt;
+        int i;
+        StringBuilder stringBuffer = new StringBuilder();
+        if (inStr == null) {
+            inStr = "";
+        }
+        for (i = 0; i < inStr.length(); i++) {
+            temChr = inStr.charAt(i);
+            ascInt = temChr;
+            if (Integer.toHexString(ascInt).length() > 2) {
+                stringBuffer.append("&#x").append(Integer.toHexString(ascInt)).append(";");
+            } else {
+                stringBuffer.append(temChr);
+            }
+
+        }
+        return stringBuffer.toString();
+    }
+
+    /**
+     * This method will encode the String to unicode.
+     *
+     * @param gbString
+     * @return
+     */
+    public static String gbEncoding(final String gbString) {
+        char[] utfBytes = gbString.toCharArray();
+        String unicodeBytes = "";
+        for (char utfByte : utfBytes) {
+            String hexB = Integer.toHexString(utfByte);
+            if (hexB.length() <= 2) {
+                hexB = "00" + hexB;
+            }
+            unicodeBytes = unicodeBytes + "\\u" + hexB;
+        }
+        System.out.println("unicodeBytes is: " + unicodeBytes);
+        return unicodeBytes;
+    }
+
+    /**
+     * This method will decode the String to a recognized String
+     * in ui.
+     *
+     * @param dataStr
+     * @return
+     */
+    public static StringBuffer decodeUnicode(final String dataStr) {
+        int start = 0;
+        int end = 0;
+        final StringBuffer buffer = new StringBuffer();
+        while (start > -1) {
+            end = dataStr.indexOf("\\u", start + 2);
+            String charStr = "";
+            if (end == -1) {
+                charStr = dataStr.substring(start + 2, dataStr.length());
+            } else {
+                charStr = dataStr.substring(start + 2, end);
+            }
+            // 16进制parse整形字符串。
+            char letter = (char) Integer.parseInt(charStr, 16);
+            buffer.append(Character.toString(letter));
+            start = end;
+        }
+        return buffer;
+    }
+
+
+    /** */
+    /**
+     * 编码
+     *
+     * @param s
+     * @return
+     */
+    public static String encode(String s) {
+        StringBuilder sbuf = new StringBuilder();
+        int len = s.length();
+        for (int i = 0; i < len; i++) {
+            int ch = s.charAt(i);
+            if ('A' <= ch && ch <= 'Z') {
+                sbuf.append((char) ch);
+            } else if ('a' <= ch && ch <= 'z') {
+                sbuf.append((char) ch);
+            } else if ('0' <= ch && ch <= '9') {
+                sbuf.append((char) ch);
+            } else if (ch == '-' || ch == '_' || ch == '.' || ch == '!'
+                    || ch == '~' || ch == '*' || ch == '\'' || ch == '('
+                    || ch == ')') {
+                sbuf.append((char) ch);
+            } else if (ch <= 0x007F) {
+                sbuf.append('%');
+                sbuf.append(HEX[ch]);
+            } else {
+                sbuf.append('%');
+                sbuf.append('u');
+                sbuf.append(HEX[(ch >>> 8)]);
+                sbuf.append(HEX[(0x00FF & ch)]);
+            }
+        }
+        return sbuf.toString();
+    }
+
+    /** */
+    /**
+     * 解码 说明:本方法保证 不论参数s是否经过escape()编码,均能得到正确的“解码”结果
+     *
+     * @param s
+     * @return
+     */
+    public static String decode(String s) {
+        StringBuilder sbuf = new StringBuilder();
+        int i = 0;
+        int len = s.length();
+        while (i < len) {
+            int ch = s.charAt(i);
+            if ('A' <= ch && ch <= 'Z') {
+                sbuf.append((char) ch);
+            } else if ('a' <= ch && ch <= 'z') {
+                sbuf.append((char) ch);
+            } else if ('0' <= ch && ch <= '9') {
+                sbuf.append((char) ch);
+            } else if (ch == '-' || ch == '_' || ch == '.' || ch == '!'
+                    || ch == '~' || ch == '*' || ch == '\'' || ch == '('
+                    || ch == ')') {
+                sbuf.append((char) ch);
+            } else if (ch == '%') {
+                int cint = 0;
+                if ('u' != s.charAt(i + 1)) {
+                    cint = (cint << 4) | VAL[s.charAt(i + 1)];
+                    cint = (cint << 4) | VAL[s.charAt(i + 2)];
+                    i += 2;
+                } else {
+                    cint = (cint << 4) | VAL[s.charAt(i + 2)];
+                    cint = (cint << 4) | VAL[s.charAt(i + 3)];
+                    cint = (cint << 4) | VAL[s.charAt(i + 4)];
+                    cint = (cint << 4) | VAL[s.charAt(i + 5)];
+                    i += 5;
+                }
+                sbuf.append((char) cint);
+            } else {
+                sbuf.append((char) ch);
+            }
+            i++;
+        }
+        return sbuf.toString();
+    }
+}
diff --git a/core/src/main/java/info/xiaomo/core/untils/StringUtil.kt b/core/src/main/java/info/xiaomo/core/untils/StringUtil.kt
deleted file mode 100644
index 71cb3151..00000000
--- a/core/src/main/java/info/xiaomo/core/untils/StringUtil.kt
+++ /dev/null
@@ -1,914 +0,0 @@
-package info.xiaomo.core.untils
-
-import org.apache.commons.lang3.StringUtils
-import java.io.IOException
-import java.io.StringReader
-import java.io.UnsupportedEncodingException
-import java.text.NumberFormat
-import java.util.*
-import java.util.regex.Pattern
-import javax.servlet.http.HttpServletRequest
-
-
-/**
- * 对字符串的简单处理
- *
- *
- *
- * @author : xiaomo
- * @Date 2013-6-6 下午5:08:06
- */
-class StringUtil : StringUtils() {
-    companion object {
-
-        /**
-         * ip正则表达式
-         */
-        val IP_REGEX = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\." + "(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}"
-        private val HEX = arrayOf("00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F", "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF", "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF", "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF", "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF", "E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF", "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF")
-        private val VAL = byteArrayOf(0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F)
-        private val QUOTE_ENCODE = """.toCharArray()
-        private val AMP_ENCODE = "&".toCharArray()
-        private val LT_ENCODE = "<".toCharArray()
-        private val GT_ENCODE = ">".toCharArray()
-
-        /**
-         * 是否是空字符串
-         *
-         * @param str 字符串
-         * @return 是否为空
-         */
-        fun isBlank(str: String?): Boolean {
-            return str == null || str.trim { it <= ' ' }.isEmpty()
-        }
-
-        /**
-         * String数组转成int数组
-         *
-         * @param numbers String[]
-         * @return List
-         */
-        fun strArrToIntList(numbers: Array): List {
-            val intArr = ArrayList()
-            for (number in numbers) {
-                intArr.add(Integer.parseInt(number))
-            }
-            return intArr
-        }
-
-        /**
-         * String数组转成int数组
-         *
-         * @param numbers String[]
-         * @return int[]
-         */
-        fun strArrToIntArr(numbers: Array): IntArray {
-            val intArr = IntArray(numbers.size)
-            for (i in numbers.indices) {
-                intArr[i] = Integer.parseInt(numbers[i])
-            }
-            return intArr
-        }
-
-        /**
-         * 根据指定的分隔符将字符串转为int数组
-         *
-         * @param source 字符串
-         * @param split  分割符
-         * @return int[]
-         */
-        fun strToIntArr(source: String, split: String): IntArray {
-            if (isBlank(source)) {
-                return IntArray(0)
-            }
-            val numbers = source.split(split.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
-            return strArrToIntArr(numbers)
-        }
-
-        /**
-         * 截取文字safe 中文
-         *
-         * @return String    返回类型
-         */
-        fun subCn(string: String, length: Int, more: String): String? {
-            if (StringUtils.isNotEmpty(string)) {
-                val chars = string.toCharArray()
-                if (chars.size > length) {
-                    val sb = StringBuilder()
-                    for (i in 0 until length) {
-                        sb.append(chars[i])
-                    }
-                    sb.append(more)
-                    return sb.toString()
-                }
-            }
-            return string
-        }
-
-
-        /**
-         * 字符串全角转半角
-         *
-         * @return String    返回类型
-         */
-        fun togglecase(string: String): String {
-            val sb = StringBuilder()
-            for (i in 0 until string.length) {
-                sb.append(CharUtil.regularize(string[i]))
-            }
-            return sb.toString()
-        }
-
-
-        /**
-         * 计算文字长度-.-无中文问题
-         *
-         * @return int    返回类型
-         */
-        fun getLength(string: String): Int {
-            if (StringUtils.isBlank(string)) {
-                return 0
-            } else {
-                val strChars = string.toCharArray()
-                return strChars.size
-            }
-        }
-
-
-        /**
-         * 获取ip
-         *
-         * @return ip 如果返回null,说明是一个不合法的ip地址格式
-         */
-        fun getIP(request: HttpServletRequest): String? {
-            var ip = request.getHeader("X-Requested-For")
-            val unknown = "unknown"
-            if (StringUtils.isBlank(ip) || unknown.equals(ip, ignoreCase = true)) {
-                ip = request.getHeader("X-Forwarded-For")
-            }
-            if (StringUtils.isBlank(ip) || unknown.equals(ip, ignoreCase = true)) {
-                ip = request.getHeader("Proxy-Client-IP")
-            }
-            if (StringUtils.isBlank(ip) || unknown.equals(ip, ignoreCase = true)) {
-                ip = request.getHeader("WL-Proxy-Client-IP")
-            }
-            if (StringUtils.isBlank(ip) || unknown.equals(ip, ignoreCase = true)) {
-                ip = request.getHeader("HTTP_CLIENT_IP")
-            }
-            if (StringUtils.isBlank(ip) || unknown.equals(ip, ignoreCase = true)) {
-                ip = request.getHeader("HTTP_X_FORWARDED_FOR")
-            }
-            if (StringUtils.isBlank(ip) || unknown.equals(ip, ignoreCase = true)) {
-                ip = request.remoteAddr
-            }
-            return if (!ip.matches(IP_REGEX.toRegex())) {
-                null
-            } else ip
-        }
-
-        /**
-         * 判断字符串是否为空,并删除首尾空格
-         *
-         * @param tempSql
-         * @return
-         */
-        fun convertNullCode(tempSql: String?): String {
-            var tempSql = tempSql
-            if (tempSql == null) {
-                tempSql = ""
-            }
-            return tempSql
-        }
-
-        /**
-         * 代码转换,GBK转换为ISO-8859-1
-         *
-         * @param tempSql 要转换的字符串
-         */
-        fun isocode(tempSql: String): String {
-
-            var returnString = convertNullCode(tempSql)
-
-            try {
-                val ascii = returnString.toByteArray(charset("GBK"))
-                returnString = String(ascii)
-            } catch (e: Exception) {
-                e.printStackTrace()
-            }
-
-            return returnString
-        }
-
-        /**
-         * 代码转换,ISO-8859-1转换为GBK
-         *
-         * @param tempSql 要转换的字符串
-         * @return
-         */
-        fun gbkcode(tempSql: String): String {
-            var returnString = convertNullCode(tempSql)
-            try {
-                val ascii = returnString.toByteArray(charset("ISO-8859-1"))
-                returnString = String(ascii)
-            } catch (e: Exception) {
-                e.printStackTrace()
-            }
-
-            return returnString
-        }
-
-        /**
-         * 代码转换,GBK转换为big5
-         *
-         * @param tempSql 要转换的字符串
-         * @return
-         */
-        fun gbk2big5code(tempSql: String): String {
-            var returnString = convertNullCode(tempSql)
-            try {
-                val ascii = returnString.toByteArray(charset("GBK"))
-                returnString = String(ascii)
-            } catch (e: Exception) {
-                e.printStackTrace()
-            }
-
-            return returnString
-        }
-
-        /**
-         * 替换非法字符
-         * @param input
-         * @return
-         */
-        fun convertHtml(input: String): String {
-            var returnString = StringBuffer(input.length)
-
-            var ch = ' '
-            for (i in 0 until input.length) {
-
-                ch = input[i]
-
-                if (ch == '<') {
-                    returnString = returnString.append("<")
-                } else if (ch == '>') {
-                    returnString = returnString.append(">")
-                } else if (ch == ' ') {
-                    returnString = returnString.append(" ")
-                } else if (ch == '\\') {
-                    returnString = returnString.append("´")
-                } else {
-                    returnString = returnString.append(ch)
-                }
-            }
-            return returnString.toString()
-        }
-
-
-        /**
-         * This method takes a string which may contain HTML tags (ie, <b>,
-         * <table>, etc) and converts the '<'' and '>' characters to
-         * their HTML escape sequences.
-         *
-         * @param in the text to be converted.
-         * @return the input string with the characters '<' and '>' replaced
-         * with their HTML escape sequences.
-         */
-        fun escapeHTMLTags(`in`: String?): String? {
-            if (`in` == null) {
-                return null
-            }
-            var ch: Char
-            var i = 0
-            var last = 0
-            val input = `in`.toCharArray()
-            val len = input.size
-            val out = StringBuilder((len * 1.3).toInt())
-            while (i < len) {
-                ch = input[i]
-
-                if (ch > '>') {
-                    i++
-                    continue
-                } else if (ch == '<') {
-                    if (i > last) {
-                        out.append(input, last, i - last)
-                    }
-                    last = i + 1
-                    out.append(LT_ENCODE)
-                } else if (ch == '>') {
-                    if (i > last) {
-                        out.append(input, last, i - last)
-                    }
-                    last = i + 1
-                    out.append(GT_ENCODE)
-                }
-                i++
-            }
-            if (last == 0) {
-                return `in`
-            }
-            if (i > last) {
-                out.append(input, last, i - last)
-            }
-            return out.toString()
-        }
-
-        fun filterString(allstr: String): String {
-            val returnString = StringBuilder(allstr.length)
-            var ch = ' '
-            for (i in 0 until allstr.length) {
-                ch = allstr[i]
-                val lsTemp = "'"
-                val lcTemp = lsTemp[0]
-                if (ch == lcTemp) {
-                    returnString.append("''")
-                } else {
-                    returnString.append(ch)
-                }
-            }
-            return returnString.toString()
-        }
-
-        /**
-         * 数字的金额表达式
-         */
-        fun convertNumToMoney(num: Int): String {
-            val formatc = NumberFormat.getCurrencyInstance(Locale.CHINA)
-            return formatc.format(num.toLong())
-        }
-
-
-        /**
-         * 数字的金额表达式
-         *
-         * @param num      金额
-         * @param inLocale 币种
-         * @return 处理好的币种
-         */
-        fun convertNumToMoney(num: Int, inLocale: Locale): String {
-            val formatc = NumberFormat.getCurrencyInstance(inLocale)
-            return formatc.format(num.toLong())
-        }
-
-        /**
-         * 格式化字符串,如果没有对应的参数则按照原样输出
-         *
-         *
-         *
-         * 例如:
-         *  * "获得{0}元宝,20"输出"获得20元宝"
-         *  * "{0}获得{1}元宝,XX"输出"XX获得{1}元宝"
-         *  * "{0}获得{1}元宝,XX,20"输出"XX获得20元宝"
-         *
-         *
-         * @param str
-         * @param params
-         * @return
-         */
-        fun format(str: String, vararg params: Any): String? {
-            if (isBlank(str)) {
-                return str
-            }
-            if (params == null || params.size == 0) {
-                return str
-            }
-            val regex = "\\{(\\d+)}"
-            val p = Pattern.compile(regex)
-            val m = p.matcher(str)
-            val sb = StringBuffer()
-            while (m.find()) {
-                var param = m.group()
-                val index = Integer.parseInt(m.group(1))
-                if (params.size > index) {
-                    val obj = params[index]
-                    if (obj != null) {
-                        param = obj.toString()
-                    }
-                }
-                m.appendReplacement(sb, param)
-            }
-            m.appendTail(sb)
-            return sb.toString()
-        }
-
-
-        /**
-         * 
-         * 例:
-         * String strVal="This is a dog";
-         * String strResult=CTools.replace(strVal,"dog","cat");
-         * 结果:
-         * strResult equals "This is cat"
-         *
-         * @param strSrc 要进行替换操作的字符串
-         * @param strOld 要查找的字符串
-         * @param strNew 要替换的字符串
-         * @return 替换后的字符串
-         * 
-        
*/ - fun replace(strSrc: String?, strOld: String?, strNew: String?): String { - if (strSrc == null || strOld == null || strNew == null) { - return "" - } - - var i = 0 - //避免新旧字符一样产生死循环 - if (strOld == strNew) { - return strSrc - } - - if ((strSrc.indexOf(strOld, i)) >= 0) { - val arrCsrc = strSrc.toCharArray() - val arrCnew = strNew.toCharArray() - - val intOldLen = strOld.length - val buf = StringBuilder(arrCsrc.size) - buf.append(arrCsrc, 0, i).append(arrCnew) - - i += intOldLen - var j = i - - while ((strSrc.indexOf(strOld, i)) > 0) { - buf.append(arrCsrc, j, i - j).append(arrCnew) - i += intOldLen - j = i - } - buf.append(arrCsrc, j, arrCsrc.size - j) - return buf.toString() - } - return strSrc - } - - - /** - * 在将数据存入数据库前转换 - * - * @param strVal 要转换的字符串 - * @return 从“ISO8859_1”到“GBK”得到的字符串 - * @since 1.0 - */ - fun toChinese(strVal: String?): String { - var strVal = strVal - return try { - if (strVal == null) { - "" - } else { - strVal = strVal.trim { it <= ' ' } - strVal = String(strVal.toByteArray(charset("ISO8859_1"))) - strVal - } - } catch (exp: Exception) { - "" - } - - } - - /** - * 编码转换 从UTF-8到GBK - * - * @param strVal - * @return - */ - fun toGBK(strVal: String?): String { - var strVal = strVal - return try { - if (strVal == null) { - "" - } else { - strVal = strVal.trim { it <= ' ' } - strVal = String(strVal.toByteArray(charset("UTF-8"))) - strVal - } - } catch (exp: Exception) { - "" - } - - } - - /** - * 将数据从数据库中取出后转换 * - * - * @param strVal 要转换的字符串 - * @return 从“GBK”到“ISO8859_1”得到的字符串 - * @since 1.0 - */ - fun toISO(strVal: String?): String { - var strVal = strVal - return try { - if (strVal == null) { - "" - } else { - strVal = String(strVal.toByteArray(charset("GBK"))) - strVal - } - } catch (exp: Exception) { - "" - } - - } - - fun gbk2UTF8(strVal: String?): String { - var strVal = strVal - return try { - if (strVal == null) { - "" - } else { - strVal = String(strVal.toByteArray(charset("GBK"))) - strVal - } - } catch (exp: Exception) { - "" - } - - } - - fun iso2utf8(strVal: String?): String { - var strVal = strVal - return try { - if (strVal == null) { - "" - } else { - strVal = String(strVal.toByteArray(charset("ISO-8859-1"))) - strVal - } - } catch (exp: Exception) { - "" - } - - } - - fun utf82iso(strVal: String?): String { - var strVal = strVal - try { - if (strVal == null) { - return "" - } else { - strVal = String(strVal.toByteArray(charset("UTF-8"))) - return strVal - } - } catch (exp: Exception) { - return "" - } - - } - - - /** - * 实际处理 return toChineseNoReplace(null2Blank(str)); - * 主要应用于老牛的信息发布 - * - * @param str 要进行处理的字符串 - * @return 转换后的字符串 - */ - fun toChineseAndHtmlEncode(str: String, quotes: Int): String { - return HtmlUtil.htmlEncode(toChinese(str), quotes) - } - - /** - * 把null值和""值转换成  - * 主要应用于页面表格格的显示 - * - * @param str 要进行处理的字符串 - * @return 转换后的字符串 - */ - fun str4Table(str: String?): String { - return if (str == null) { - " " - } else if ("" == str) { - " " - } else { - str - } - } - - /** - * String型变量转换成int型变量 - * - * @param str 要进行转换的字符串 - * @return intVal 如果str不可以转换成int型数据,返回-1表示异常,否则返回转换后的值 - * @since 1.0 - */ - fun str2Int(str: String): Int { - var intVal: Int - - try { - intVal = Integer.parseInt(str) - } catch (e: Exception) { - intVal = 0 - } - - return intVal - } - - fun str2Double(str: String): Double { - var dVal = 0.0 - - try { - dVal = java.lang.Double.parseDouble(str) - } catch (e: Exception) { - dVal = 0.0 - } - - return dVal - } - - - fun str2Long(str: String): Long { - var longVal: Long = 0 - - try { - longVal = java.lang.Long.parseLong(str) - } catch (e: Exception) { - longVal = 0 - } - - return longVal - } - - fun stringToFloat(floatstr: String): Float { - val floatee: Float - floatee = java.lang.Float.valueOf(floatstr) - return floatee - } - - fun floatToString(value: Float): String { - return value.toString() - } - - /** - * int型变量转换成String型变量 - * - * @param intVal 要进行转换的整数 - * @return str 如果intVal不可以转换成String型数据,返回空值表示异常,否则返回转换后的值 - */ - fun int2Str(intVal: Int): String { - var str: String - - try { - str = intVal.toString() - } catch (e: Exception) { - str = "" - } - - return str - } - - /** - * long型变量转换成String型变量 - * - * @param longVal 要进行转换的整数 - * @return str 如果longVal不可以转换成String型数据,返回空值表示异常,否则返回转换后的值 - */ - - fun long2Str(longVal: Long): String { - var str: String - - try { - str = longVal.toString() - } catch (e: Exception) { - str = "" - } - - return str - } - - /** - * null 处理 - * - * @param str 要进行转换的字符串 - * @return 如果str为null值,返回空串"",否则返回str - */ - fun null2Blank(str: String?): String { - return str ?: "" - } - - /** - * null 处理 - * - * @param d 要进行转换的日期对像 - * @return 如果d为null值,返回空串"",否则返回d.toString() - */ - - fun null2Blank(d: Date?): String { - return d?.toString() ?: "" - } - - /** - * null 处理 - * - * @param str 要进行转换的字符串 - * @return 如果str为null值,返回空串整数0,否则返回相应的整数 - */ - fun null2Zero(str: String): Int { - val intTmp: Int - intTmp = str2Int(str) - return if (intTmp == -1) { - 0 - } else { - intTmp - } - } - - /** - * 把null转换为字符串"0" - * - * @param str - * @return - */ - fun null2SZero(str: String): String { - var str = str - str = null2Blank(str) - return if ("" == str) { - "0" - } else { - str - } - } - - - /** - * 字符串从GBK编码转换为Unicode编码 - * - * @param text - * @return - */ - fun stringToUnicode(text: String): String { - val result = StringBuffer() - var input = 0 - val isr: StringReader - try { - isr = StringReader(String(text.toByteArray())) - } catch (e: UnsupportedEncodingException) { - return "-1" - } - - try { - while ((isr.read()) != -1) { - result.append("&#x").append(input).append(";") - - } - } catch (e: IOException) { - return "-2" - } - - isr.close() - return result.toString() - - } - - /** - * @param inStr - * @return - */ - fun gb2utf(inStr: String?): String { - var inStr = inStr - var temChr: Char - var ascInt: Int - var i = 0 - val stringBuffer = StringBuilder() - if (inStr == null) { - inStr = "" - } - while (i < inStr.length) { - temChr = inStr[i] - ascInt = temChr.toInt() - if (Integer.toHexString(ascInt).length > 2) { - stringBuffer.append("&#x").append(Integer.toHexString(ascInt)).append(";") - } else { - stringBuffer.append(temChr) - } - i++ - - } - return stringBuffer.toString() - } - - /** - * This method will encode the String to unicode. - * - * @param gbString - * @return - */ - fun gbEncoding(gbString: String): String { - val utfBytes = gbString.toCharArray() - var unicodeBytes = "" - for (utfByte in utfBytes) { - var hexB = Integer.toHexString(utfByte.toInt()) - if (hexB.length <= 2) { - hexB = "00" + hexB - } - unicodeBytes = unicodeBytes + "\\u" + hexB - } - println("unicodeBytes is: " + unicodeBytes) - return unicodeBytes - } - - /** - * This method will decode the String to a recognized String - * in ui. - * - * @param dataStr - * @return - */ - fun decodeUnicode(dataStr: String): StringBuffer { - var start = 0 - var end = 0 - val buffer = StringBuffer() - while (start > -1) { - end = dataStr.indexOf("\\u", start + 2) - var charStr = "" - if (end == -1) { - charStr = dataStr.substring(start + 2, dataStr.length) - } else { - charStr = dataStr.substring(start + 2, end) - } - // 16进制parse整形字符串。 - val letter = Integer.parseInt(charStr, 16).toChar() - buffer.append(Character.toString(letter)) - start = end - } - return buffer - } - - - /** */ - /** - * 编码 - * - * @param s - * @return - */ - fun encode(s: String): String { - val sbuf = StringBuilder() - val len = s.length - for (i in 0 until len) { - val ch = s[i].toInt() - if (ch.toChar() in 'A'..'Z') { - sbuf.append(ch.toChar()) - } else if (ch.toChar() in 'a'..'z') { - sbuf.append(ch.toChar()) - } else if (ch.toChar() in '0'..'9') { - sbuf.append(ch.toChar()) - } else if (ch.toChar() == '-' || ch.toChar() == '_' || ch.toChar() == '.' || ch.toChar() == '!' - || ch.toChar() == '~' || ch.toChar() == '*' || ch.toChar() == '\'' || ch.toChar() == '(' - || ch.toChar() == ')') { - sbuf.append(ch.toChar()) - } else if (ch <= 0x007F) { - sbuf.append('%') - sbuf.append(HEX[ch]) - } else { - sbuf.append('%') - sbuf.append('u') - sbuf.append(HEX[ch.ushr(8)]) - sbuf.append(HEX[0x00FF and ch]) - } - } - return sbuf.toString() - } - - /** */ - /** - * 解码 说明:本方法保证 不论参数s是否经过escape()编码,均能得到正确的“解码”结果 - * - * @param s - * @return - */ - fun decode(s: String): String { - val sbuf = StringBuilder() - var i = 0 - val len = s.length - while (i < len) { - val ch = s[i].toInt() - if (ch.toChar() in 'A'..'Z') { - sbuf.append(ch.toChar()) - } else if (ch.toChar() in 'a'..'z') { - sbuf.append(ch.toChar()) - } else if (ch.toChar() in '0'..'9') { - sbuf.append(ch.toChar()) - } else if (ch.toChar() == '-' || ch.toChar() == '_' || ch.toChar() == '.' || ch.toChar() == '!' - || ch.toChar() == '~' || ch.toChar() == '*' || ch.toChar() == '\'' || ch.toChar() == '(' - || ch.toChar() == ')') { - sbuf.append(ch.toChar()) - } else if (ch.toChar() == '%') { - var cint = 0 - if ('u' != s[i + 1]) { - cint = cint shl 4 or VAL[s[i + 1].toInt()].toInt() - cint = cint shl 4 or VAL[s[i + 2].toInt()].toInt() - i += 2 - } else { - cint = cint shl 4 or VAL[s[i + 2].toInt()].toInt() - cint = cint shl 4 or VAL[s[i + 3].toInt()].toInt() - cint = cint shl 4 or VAL[s[i + 4].toInt()].toInt() - cint = cint shl 4 or VAL[s[i + 5].toInt()].toInt() - i += 5 - } - sbuf.append(cint.toChar()) - } else { - sbuf.append(ch.toChar()) - } - i++ - } - return sbuf.toString() - } - } -} diff --git a/core/src/main/java/info/xiaomo/core/untils/TimeUtil.java b/core/src/main/java/info/xiaomo/core/untils/TimeUtil.java new file mode 100644 index 00000000..10b09e5e --- /dev/null +++ b/core/src/main/java/info/xiaomo/core/untils/TimeUtil.java @@ -0,0 +1,890 @@ +package info.xiaomo.core.untils; + + +import info.xiaomo.core.constant.SymbolConst; +import org.apache.commons.lang3.time.DateUtils; +import org.apache.commons.lang3.time.FastDateFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.sql.Timestamp; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.Locale; + +/** + * 时间和日期的工具类 + * + * @author : xiaomo + */ +public class TimeUtil { + + /** + * 一分钟的毫秒时长 + */ + public static final long ONE_MINUTE_IN_MILLISECONDS = 60L * 1000; + /** + * 一小时的毫秒时长 + */ + public static final long ONE_HOUR_IN_MILLISECONDS = 60L * ONE_MINUTE_IN_MILLISECONDS; + /** + * 一天的毫秒时长 + */ + public static final long ONE_DAY_IN_MILLISECONDS = 24L * ONE_HOUR_IN_MILLISECONDS; + /** + * 一天的秒时长 + */ + public static final long ONE_DAY_IN_SECENDS = 24L * 60 * 60; + /** + * 2015-02-23 12:12:12格式 + */ + public static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss"; + public static final String DEFAULT_FORMAT2 = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; + public static final Logger LOGGER = LoggerFactory.getLogger(TimeUtil.class); + public static final String DATE_PATTERN_WITH_HENGXIAN = "yyyy-MM-dd"; + public static final String DATE_PATTERN_WITH_XIEXIAN = "yyyy/MM/dd"; + public static final String YEAR = "yyyy"; + public static final String MONTH = "MM"; + public static final String DAY = "dd"; + public static final String DATE = MONTH + SymbolConst.HENGXIAN + DAY; + + public static final String TIME_PATTERN = DATE_PATTERN_WITH_HENGXIAN + " HH:mm:ss"; + public static final String DATE_PATTERN = " HH:mm:ss"; + + public static final FastDateFormat DATE_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd"); + public static final String DATE_FORMAT_STRING = "yyyyMMddHHmmss"; + public static final FastDateFormat DATE_FORMAT_CN = FastDateFormat.getInstance("yyyy年 MM月 dd日"); + public static final FastDateFormat DATE_FORMAT_RSS = FastDateFormat.getInstance("E, d MMM yyyy HH:mm:ss z", Locale.CHINA); + public static int openDay = 5; + + /** + * 返回 日期格式 + * + * @return string + */ + public static String getDatePattern() { + return DATE_PATTERN_WITH_HENGXIAN; + } + + /** + * 返回时间格式 + * + * @return string + */ + public static String getTimePattern() { + return TIME_PATTERN; + } + + /** + * 获取格式化后的时间或日期 + * + * @param date date + * @return string + */ + public static String date2Str(Date date) { + SimpleDateFormat df; + String returnValue = ""; + if (date != null) { + df = new SimpleDateFormat(DATE_PATTERN_WITH_HENGXIAN); + returnValue = df.format(date); + } + return (returnValue); + } + + /** + * 获取格式化后的时间或日期 + * + * @param pattern pattern + * @param aDate aDate + */ + public static String date2Str(String pattern, Date aDate) { + SimpleDateFormat df; + String returnValue = ""; + if (aDate != null) { + df = new SimpleDateFormat(pattern); + returnValue = df.format(aDate); + } + return (returnValue); + } + + /** + * 将字符串转成时间 + * + * @param datePattern 格式 + * @param strDate 字符串的时间 + */ + public static Date convertStringToDate(String datePattern, String strDate) { + SimpleDateFormat df; + Date date; + //传入的时间是以 / 分割 + int length = 2; + if (strDate.split(SymbolConst.HENGXIAN).length < length) { + strDate = strDate.replace(SymbolConst.ZHENGXIEXIAN, SymbolConst.HENGXIAN); + } + if (strDate.split(SymbolConst.SPACE).length > 1) { + datePattern = TIME_PATTERN; + } + df = new SimpleDateFormat(datePattern); + try { + date = df.parse(strDate); + } catch (ParseException pe) { + return null; + } + return (date); + } + + /** + * 字符串转时间 + * + * @param strDate strDate + */ + public static Date convertStringToDate(String strDate) { + Date aDate; + //传入的时间是以 / 分割 + int length = 2; + if (strDate.split(SymbolConst.HENGXIAN).length < length) { + strDate = strDate.replace(SymbolConst.ZHENGXIEXIAN, SymbolConst.HENGXIAN); + } + aDate = convertStringToDate(DATE_PATTERN_WITH_HENGXIAN, strDate); + return aDate; + } + + /** + * 获取当前时间或时间 + * + * @param theTime theTime + */ + public static String getTimeOrTimeNow(Date theTime) { + return getDateTime(TIME_PATTERN, theTime); + } + + /** + * 获取当前时间或时间 + * + * @param theTime theTime + */ + public static String getTimeOrTimeNow(String pattern, Date theTime) { + return getDateTime(pattern, theTime); + } + + /** + * 日期格式转换成时间戳 + * + * @param pattern pattern + * @param strDate strDate + */ + public static long getTimeStamp(String pattern, String strDate) { + long returnTimeStamp; + Date aDate; + aDate = convertStringToDate(pattern, strDate); + if (aDate == null) { + returnTimeStamp = 0; + } else { + returnTimeStamp = aDate.getTime(); + } + return returnTimeStamp; + } + + /** + * 获取当前日期的时间戳 + */ + public static long getNowTimeStamp() { + long returnTimeStamp; + Date aDate = null; + aDate = convertStringToDate("yyyy-MM-dd HH:mm:ss", getFullNowDateTime()); + if (aDate == null) { + returnTimeStamp = 0; + } else { + returnTimeStamp = aDate.getTime(); + } + return returnTimeStamp; + } + + /** + * 得到格式化后的系统当前日期 + * + * @param pattern 格式模式字符串 + * @return 格式化后的系统当前时间,如果有异常产生,返回空串"" + */ + public static String getNowDateTimeWithPattern(String pattern) { + String strReturn; + Date now = new Date(); + try { + SimpleDateFormat sdf = new SimpleDateFormat(pattern); + strReturn = sdf.format(now); + } catch (Exception e) { + strReturn = ""; + } + return strReturn; + } + + /** + * 获取当前的完整的日期和时间 + */ + public static String getFullNowDateTime() { + String strReturn; + Date now = new Date(); + try { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + strReturn = sdf.format(now); + } catch (Exception e) { + strReturn = ""; + } + return strReturn; + } + + /** + * 将字符串数组使用指定的分隔符合并成一个字符串。 + * + * @param array 字符串数组 + * @param split 分隔符,为null的时候使用""作为分隔符(即没有分隔符) + * @return 合并后的字符串 + * @since 0.4 + */ + public static String combineStringArray(String[] array, String split) { + int length = array.length - 1; + if (split == null) { + split = ""; + } + StringBuilder result = new StringBuilder(length * 8); + for (int i = 0; i < length; i++) { + result.append(array[i]); + result.append(split); + } + result.append(array[length]); + return result.toString(); + } + + /** + * 没搞清楚要传什么参数进去 + * + * @param strWeek strWeek + */ + public static int getWeekNum(String strWeek) { + int returnValue = 0; + switch (strWeek) { + case "Mon": + returnValue = 1; + break; + case "Tue": + returnValue = 2; + break; + case "Wed": + returnValue = 3; + break; + case "Thu": + returnValue = 4; + break; + case "Fri": + returnValue = 5; + break; + case "Sat": + returnValue = 6; + break; + case "Sun": + returnValue = 0; + break; + default: + returnValue = 0; + } + return returnValue; + } + + /** + * 获取日期字符串中的中文时间表示字符串 + * + * @param strDate strDate + */ + public static String getSabreTime(String strDate) { + String strReturn = ""; + try { + + Date d = TimeUtil.convertStringToDate("yyyy-MM-dd HH:mm:ss", StringUtil.replace( + strDate, "T", " ")); + strReturn = TimeUtil.date2Str("hh:mm aaa", d); + + } catch (Exception e) { + return strReturn; + } + return strReturn; + } + + /** + * 获取日期字符串中的中文日期表示字符串 + * + * @param strDate strDate + */ + public static String getSabreDate(String strDate) { + String strReturn = ""; + try { + String p; + int length = 10; + if (strDate.length() > length) { + p = "yyyy-MM-dd HH:mm:ss"; + } else { + p = "yyyy-MM-dd"; + } + Date d = TimeUtil.convertStringToDate(p, StringUtil.replace(strDate, "T", " ")); + strReturn = TimeUtil.date2Str("EEE d-MMM", d); + + } catch (Exception e) { + return strReturn; + } + return strReturn; + } + + /** + * 获取日期字符串的中文日期时间表示 + * + * @param strDate strDate + */ + public static String getSabreDateTime(String strDate) { + String strReturn = ""; + try { + String p; + int length = 10; + if (strDate.length() > length) { + p = "yyyy-MM-dd HH:mm:ss"; + } else { + p = "yyyy-MM-dd"; + } + Date d = TimeUtil.convertStringToDate(p, StringUtil.replace(strDate, "T", " ")); + strReturn = TimeUtil.date2Str("EEE d-MMM hh:mm aaa", d); + + } catch (Exception e) { + return strReturn; + } + return strReturn; + } + + /** + * 获取指定的日期 + * + * @param timeType 时间类型,譬如:Calendar.DAY_OF_YEAR + * @param timenum 时间数字,譬如:-1 昨天,0 今天,1 明天 + * @return 日期 + */ + public static Date getDateFromNow(int timeType, int timenum) { + Calendar cld = Calendar.getInstance(); + cld.set(timeType, cld.get(timeType) + timenum); + return cld.getTime(); + } + + /** + * 获取日期 + * + * @param timeType 时间类型,譬如:Calendar.DAY_OF_YEAR + * @param timeNum 时间数字,譬如:-1 昨天,0 今天,1 明天 + * @param pattern 时间格式,譬如:"yyyy-MM-dd HH:mm:ss" + * @return 字符串 + */ + public static String getDateFromNow(int timeType, int timeNum, String pattern) { + + if ((pattern == null) || ("".equals(pattern))) { + pattern = "yyyy-MM-dd HH:mm:ss"; + } + Calendar cld = Calendar.getInstance(); + Date date; + DateFormat df = new SimpleDateFormat(pattern); + cld.set(timeType, cld.get(timeType) + timeNum); + date = cld.getTime(); + return df.format(date); + } + + /** + * 获取当前日期的字符串 + * + * @param pattern 时间格式,譬如:"yyyy-MM-dd HH:mm:ss" + * @return 字符串 + */ + public static String getDateNow(String pattern) { + if ((pattern == null) || ("".equals(pattern))) { + pattern = "yyyy-MM-dd HH:mm:ss"; + } + Calendar cld = Calendar.getInstance(); + DateFormat df = new SimpleDateFormat(pattern); + return df.format(cld.getTime()); + } + + /** + * 格式化成yyyy-MM-dd + * + * @return String 返回类型 + */ + public static String format(Timestamp tamp) { + return DATE_FORMAT.format(tamp); + } + + /** + * 格式化成中文日期 + * + * @return String 返回类型 + */ + public static String formatCn(Timestamp tamp) { + return DATE_FORMAT_CN.format(tamp); + } + + /** + * 格式化成RSS需要格式 + * + * @return String 返回类型 + */ + public static String formartRss(Timestamp tamp) { + return DATE_FORMAT_RSS.format(tamp); + } + + /** + * hour小时之前 + */ + public static Date hourBefor(int hour) { + return DateUtils.addHours(new Date(), -hour); + } + + public static String subDate(String date) { + return date.substring(0, 10); + } + + /** + * 计算是否是季度末 + * + * @param date date + */ + public static boolean isSeason(String date) { + int getMonth = Integer.parseInt(date.substring(5, 7)); + boolean sign = false; + int monthThree = 3; + if (getMonth == monthThree) { + sign = true; + } + int monthSix = 6; + if (getMonth == monthSix) { + sign = true; + } + int monthNine = 9; + if (getMonth == monthNine) { + sign = true; + } + int maxMonth = 12; + if (getMonth == maxMonth) { + sign = true; + } + return sign; + } + + /** + * 计算从现在开始几天后的时间 + * + * @param afterDay afterDay + */ + public static String getDateFromNow(int afterDay) { + GregorianCalendar calendar = new GregorianCalendar(); + Date date = calendar.getTime(); + + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + + calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + afterDay); + date = calendar.getTime(); + + return df.format(date); + } + + /** + * 带格式 + * + * @param afterDay afterDay + * @param pattern pattern + */ + public static String getDateFromNow(int afterDay, String pattern) { + Calendar calendar = Calendar.getInstance(); + Date date; + DateFormat df = new SimpleDateFormat(pattern); + calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + afterDay); + date = calendar.getTime(); + return df.format(date); + } + + /** + * 得到当前时间,用于文件名,没有特殊字符,使用yyyyMMddHHmmss格式 + * + * @param afterDay afterDay + */ + public static String getNowForFileName(int afterDay) { + GregorianCalendar calendar = new GregorianCalendar(); + SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); + + calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + afterDay); + Date date = calendar.getTime(); + + return df.format(date); + } + + /** + * 获取当前月份 + * + * @return 返回字符串 格式:两位数 + */ + public static String getCurrentMonth() { + String strMonth; + Calendar cld = Calendar.getInstance(); + java.util.Date date = new Date(); + cld.setTime(date); + int intMon = cld.get(Calendar.MONTH) + 1; + int ten = 10; + if (intMon < ten) { + strMonth = "0" + String.valueOf(intMon); + } else { + strMonth = String.valueOf(intMon); + } + return strMonth; + } + + /** + * 获取当前月份 + * + * @return 返回字符串 格式:不带0 + */ + public static String getCurrMonth() { + Calendar cld = Calendar.getInstance(); + java.util.Date date = new Date(); + cld.setTime(date); + int intMon = cld.get(Calendar.MONTH) + 1; + return String.valueOf(intMon); + } + + /** + * 获取昨天的日期的字符串 + */ + public static String getYesterday() { + Calendar cld = Calendar.getInstance(); + java.util.Date date = new Date(); + cld.setTime(date); + cld.add(Calendar.DATE, -1); + int intMon = cld.get(Calendar.MONTH) + 1; + int intDay = cld.get(Calendar.DAY_OF_MONTH); + String mons = String.valueOf(intMon); + String days = String.valueOf(intDay); + int ten = 10; + if (intMon < ten) { + mons = "0" + String.valueOf(intMon); + } + if (intDay < ten) { + days = "0" + String.valueOf(intDay); + } + return String.valueOf(cld.get(Calendar.YEAR)) + "-" + mons + "-" + days; + } + + /** + * 获取时间 + * + * @param pattern pattern + * @param aDate aDate + */ + private static String getDateTime(String pattern, Date aDate) { + SimpleDateFormat df; + String returnValue = ""; + if (aDate == null) { + System.out.print("aDate is null!"); + } else { + df = new SimpleDateFormat(pattern); + returnValue = df.format(aDate); + } + + return (returnValue); + } + + /** + * 判断两个时间是否是同一天 + * + * @param sourceTime sourceTime + * @param targetTime targetTime + * @return + */ + public static boolean isSameDay(long sourceTime, long targetTime) { + return getLogicIntervalDays(sourceTime, targetTime) == 0; + } + + /** + * 判断指定的时间是否是今天 + * + * @param time time + */ + public static boolean isToday(long time) { + return isSameDay(System.currentTimeMillis(), time); + } + + /** + * 获取两个时间的逻辑间隔天数,以源时间为基准,目标时间小于源时间则返回大于或等于天数,反之返回小于等于天数 + *

+ * 举例:sourceTime=今天凌晨0点0分1秒,targetTime=昨天晚上11点59分59秒,则返回1 + * + * @param sourceTime sourceTime + * @param targetTime targetTime + * @return + */ + public static int getLogicIntervalDays(long sourceTime, long targetTime) { + long source0ClockTime = getZeroClockTime(sourceTime); + long target0ClockTime = getZeroClockTime(targetTime); + + return getRealIntervalDays(source0ClockTime, target0ClockTime); + } + + /** + * 获取两个时间的实际间隔天数 + * + * @param sourceTime sourceTime + * @param targetTime targetTime + */ + public static int getRealIntervalDays(long sourceTime, long targetTime) { + return (int) getIntervalTime(sourceTime, targetTime, ONE_DAY_IN_MILLISECONDS); + } + + /** + * 根据指定的时间单位获取相差的单位时间,如时间单位为一天的毫秒数则该函数跟{@link#getRealIntervalDays} 则是相同的效果 + * + * @param sourceTime sourceTime + * @param targetTime targetTime + * @param timeUnit 时间单位(毫秒) + * @return + */ + public static long getIntervalTime(long sourceTime, long targetTime, long timeUnit) { + return (sourceTime - targetTime) / timeUnit; + } + + /** + * 获取在指定时间戳和指定小时,分钟,秒,毫秒数的时间 + * + * @param time 时间戳 + * @param hour 小时(24小时制) + * @param minute 分钟 + * @param second 秒 + * @param milliSecond 毫秒 + */ + public static long getTimeInMillis(long time, int hour, int minute, int second, int milliSecond) { + Calendar calendar = Calendar.getInstance(); + calendar.setTimeInMillis(time); + calendar.set(Calendar.HOUR_OF_DAY, hour); + calendar.set(Calendar.MINUTE, minute); + calendar.set(Calendar.SECOND, second); + calendar.set(Calendar.MILLISECOND, milliSecond); + return calendar.getTimeInMillis(); + } + + /** + * 获取指定日期的时间戳 + * + * @param year year + * @param month 从1开始 + * @param day day + * @param hour 月 + * @param minute 分 + * @param second 秒 + * @param milliSecond 毫秒 + */ + public static long getTimeInMillis(int year, int month, int day, int hour, int minute, int second, int milliSecond) { + Calendar calendar = Calendar.getInstance(); + calendar.set(Calendar.YEAR, year); + calendar.set(Calendar.MONTH, month - 1); + calendar.set(Calendar.DAY_OF_MONTH, day); + calendar.set(Calendar.HOUR_OF_DAY, hour); + calendar.set(Calendar.MINUTE, minute); + calendar.set(Calendar.SECOND, second); + calendar.set(Calendar.MILLISECOND, milliSecond); + return calendar.getTimeInMillis(); + } + + /** + * 获取今日指定的时间 + * + * @param hour 小时(24小时制) + * @param minute 分钟 + * @param second 秒 + * @param milliSecond 毫秒 + */ + public static long getTodayTime(int hour, int minute, int second, int milliSecond) { + return getTimeInMillis(System.currentTimeMillis(), hour, minute, second, milliSecond); + } + + /** + * 获取指定时间的零点时间 + */ + public static long getZeroClockTime(long time) { + return getTimeInMillis(time, 0, 0, 0, 0); + } + + + /** + * 返回指定时间和格式的时间字符串 + */ + public static String getTimeString(long time, String format) { + DateFormat dateFormat = new SimpleDateFormat(format); + return dateFormat.format(new Date(time)); + } + + /** + * 从字符串中获取时间 + */ + public static long getTimeFromString(String timeStr, String format) { + DateFormat dateFormat = new SimpleDateFormat(format); + try { + return dateFormat.parse(timeStr).getTime(); + } catch (ParseException e) { + LOGGER.error("", e); + } + return Long.MIN_VALUE; + } + + /** + * 获取格式化的剩余时间 + *

+ * 例如:1天20小时5分0秒,20小时0分0秒,1秒 + */ + public static String getLeftTimeString(long leftTime) { + StringBuilder sb = new StringBuilder(); + // 剩余秒数 + int leftSecond = (int) (leftTime / 1000); + // 秒数 + int second = leftSecond % 60; + if (second > 0) { + sb.insert(0, second + "秒"); + } + // 剩余分钟数 + int leftMinute = leftSecond / 60; + // 分钟数 + int minute = leftMinute % 60; + if (minute > 0) { + sb.insert(0, minute + "分"); + } + // 剩余小时 + int leftHour = leftMinute / 60; + int hour = leftHour % 24; + if (hour > 0) { + sb.insert(0, hour + "小时"); + } + // 剩余天数 + int leftDay = leftHour / 24; + if (leftDay > 0) { + sb.insert(0, leftDay + "天"); + } + // 获取剩余天数 + int day = (int) (leftTime / ONE_DAY_IN_MILLISECONDS); + // 1天及以上的显示剩余天 + if (day > 0) { + sb.append(day).append("天"); + leftTime -= (day * ONE_DAY_IN_MILLISECONDS); + } + hour = (int) (leftTime / ONE_HOUR_IN_MILLISECONDS); + // 1小时及以上或者前面显示了天数则后面需要小时 + if (hour > 0 || sb.length() > 0) { + sb.append(hour).append("小时"); + leftTime -= (hour * ONE_HOUR_IN_MILLISECONDS); + } + minute = (int) (leftTime / ONE_MINUTE_IN_MILLISECONDS); + if (minute > 0 || sb.length() > 0) { + sb.append(minute).append("分"); + leftTime -= (minute * ONE_MINUTE_IN_MILLISECONDS); + } + sb.append(leftTime / 1000).append("秒"); + return sb.toString(); + } + + + /** + * 返回当前时间(单位/秒) + */ + public static int getNowOfSeconds() { + return (int) (System.currentTimeMillis() / 1000); + } + + /** + * 返回当前时间(单位/毫秒) + * + * @return long 毫秒 + */ + public static long getNowOfMills() { + return System.currentTimeMillis(); + } + + + /** + * 描述:返回今天的日期(几号) + * + * @return int 几号 + */ + public static int getTodayDate() { + Calendar calendar = Calendar.getInstance(); + calendar.setTimeInMillis(System.currentTimeMillis()); + return calendar.get(Calendar.DAY_OF_MONTH); + } + + /** + * 描述:返回星期几 + * + * @return int 星期{DAY of week} + */ + public static int getTodayOfWeek() { + Calendar calendar = Calendar.getInstance(); + calendar.setTimeInMillis(System.currentTimeMillis()); + return calendar.get(Calendar.DAY_OF_WEEK) - 1; + } + + /** + * 描述:返回 今天是这个月的第几周 + * + * @return int 第几周 + */ + public static int getWeekOfMouth() { + Calendar calendar = Calendar.getInstance(); + calendar.setTimeInMillis(System.currentTimeMillis()); + return calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH); + } + + public static String getFormatDateToday() { + SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd"); + return format.format(new Date()); + } + + public static String getFormatDate() { + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); + return format.format(new Date()); + } + + /** + * 得到几天前的时间 + */ + public static Date getDateBefore(Date d, int day) { + Calendar now = Calendar.getInstance(); + now.setTime(d); + now.set(Calendar.DATE, now.get(Calendar.DATE) - day); + return now.getTime(); + } + + /** + * 得到几天后的时间 + */ + public static Date getDateAfter(Date d, int day) { + Calendar now = Calendar.getInstance(); + now.setTime(d); + now.set(Calendar.DATE, now.get(Calendar.DATE) + day); + return now.getTime(); + } + + public static String getFormatDate(Long date, String pattern) { + SimpleDateFormat format = new SimpleDateFormat(pattern); + return format.format(date); + } + + public static int getYear() { + return Calendar.getInstance().get(Calendar.YEAR); + } + +} + + + + + + diff --git a/core/src/main/java/info/xiaomo/core/untils/TimeUtil.kt b/core/src/main/java/info/xiaomo/core/untils/TimeUtil.kt deleted file mode 100644 index 9de744fd..00000000 --- a/core/src/main/java/info/xiaomo/core/untils/TimeUtil.kt +++ /dev/null @@ -1,883 +0,0 @@ -package info.xiaomo.core.untils - - -import info.xiaomo.core.constant.SymbolConst -import org.apache.commons.lang3.time.DateUtils -import org.apache.commons.lang3.time.FastDateFormat -import org.slf4j.LoggerFactory -import java.sql.Timestamp -import java.text.ParseException -import java.text.SimpleDateFormat -import java.util.* - -/** - * 时间和日期的工具类 - * @author : xiaomo - */ -object TimeUtil { - - /** - * 一分钟的毫秒时长 - */ - val ONE_MINUTE_IN_MILLISECONDS = 60L * 1000 - /** - * 一小时的毫秒时长 - */ - val ONE_HOUR_IN_MILLISECONDS = 60L * ONE_MINUTE_IN_MILLISECONDS - /** - * 一天的毫秒时长 - */ - val ONE_DAY_IN_MILLISECONDS = 24L * ONE_HOUR_IN_MILLISECONDS - /** - * 一天的秒时长 - */ - val ONE_DAY_IN_SECENDS = 24L * 60 * 60 - /** - * 2015-02-23 12:12:12格式 - */ - val DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss" - val DEFAULT_FORMAT2 = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" - val LOGGER = LoggerFactory.getLogger(TimeUtil::class.java) - /** - * 返回 日期格式 - * - * @return string - */ - val datePattern = "yyyy-MM-dd" - val DATE_PATTERN_WITH_XIEXIAN = "yyyy/MM/dd" - val YEAR = "yyyy" - val MONTH = "MM" - val DAY = "dd" - val DATE = MONTH + SymbolConst.HENGXIAN + DAY - - /** - * 返回时间格式 - * - * @return string - */ - val timePattern = datePattern + " HH:mm:ss" - val DATE_PATTERN = " HH:mm:ss" - - val DATE_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd") - val DATE_FORMAT_STRING = "yyyyMMddHHmmss" - val DATE_FORMAT_CN = FastDateFormat.getInstance("yyyy年 MM月 dd日") - val DATE_FORMAT_RSS = FastDateFormat.getInstance("E, d MMM yyyy HH:mm:ss z", Locale.CHINA) - var openDay = 5 - - /** - * 获取当前日期的时间戳 - */ - val nowTimeStamp: Long - get() { - val returnTimeStamp: Long - var aDate: Date? = null - aDate = convertStringToDate("yyyy-MM-dd HH:mm:ss", fullNowDateTime) - if (aDate == null) { - returnTimeStamp = 0 - } else { - returnTimeStamp = aDate.time - } - return returnTimeStamp - } - - /** - * 获取当前的完整的日期和时间 - */ - val fullNowDateTime: String - get() { - var strReturn: String - val now = Date() - try { - val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") - strReturn = sdf.format(now) - } catch (e: Exception) { - strReturn = "" - } - - return strReturn - } - - /** - * 获取当前月份 - * - * @return 返回字符串 格式:两位数 - */ - val currentMonth: String - get() { - val strMonth: String - val cld = Calendar.getInstance() - val date = Date() - cld.time = date - val intMon = cld.get(Calendar.MONTH) + 1 - val ten = 10 - if (intMon < ten) { - strMonth = "0" + intMon.toString() - } else { - strMonth = intMon.toString() - } - return strMonth - } - - /** - * 获取当前月份 - * - * @return 返回字符串 格式:不带0 - */ - val currMonth: String - get() { - val cld = Calendar.getInstance() - val date = Date() - cld.time = date - val intMon = cld.get(Calendar.MONTH) + 1 - return intMon.toString() - } - - /** - * 获取昨天的日期的字符串 - */ - val yesterday: String - get() { - val cld = Calendar.getInstance() - val date = Date() - cld.time = date - cld.add(Calendar.DATE, -1) - val intMon = cld.get(Calendar.MONTH) + 1 - val intDay = cld.get(Calendar.DAY_OF_MONTH) - var mons = intMon.toString() - var days = intDay.toString() - val ten = 10 - if (intMon < ten) { - mons = "0" + intMon.toString() - } - if (intDay < ten) { - days = "0" + intDay.toString() - } - return cld.get(Calendar.YEAR).toString() + "-" + mons + "-" + days - } - - - /** - * 返回当前时间(单位/秒) - */ - val nowOfSeconds: Int - get() = (System.currentTimeMillis() / 1000).toInt() - - /** - * 返回当前时间(单位/毫秒) - * - * @return long 毫秒 - */ - val nowOfMills: Long - get() = System.currentTimeMillis() - - - /** - * 描述:返回今天的日期(几号) - * - * @return int 几号 - */ - val todayDate: Int - get() { - val calendar = Calendar.getInstance() - calendar.timeInMillis = System.currentTimeMillis() - return calendar.get(Calendar.DAY_OF_MONTH) - } - - /** - * 描述:返回星期几 - * - * @return int 星期{DAY of week} - */ - val todayOfWeek: Int - get() { - val calendar = Calendar.getInstance() - calendar.timeInMillis = System.currentTimeMillis() - return calendar.get(Calendar.DAY_OF_WEEK) - 1 - } - - /** - * 描述:返回 今天是这个月的第几周 - * - * @return int 第几周 - */ - val weekOfMouth: Int - get() { - val calendar = Calendar.getInstance() - calendar.timeInMillis = System.currentTimeMillis() - return calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH) - } - - val formatDateToday: String - get() { - val format = SimpleDateFormat("yyyyMMdd") - return format.format(Date()) - } - - val formatDate: String - get() { - val format = SimpleDateFormat("yyyy-MM-dd hh:mm:ss") - return format.format(Date()) - } - - val year: Int - get() = Calendar.getInstance().get(Calendar.YEAR) - - /** - * 获取格式化后的时间或日期 - * - * @param date date - * @return string - */ - fun date2Str(date: Date?): String { - val df: SimpleDateFormat - var returnValue = "" - if (date != null) { - df = SimpleDateFormat(datePattern) - returnValue = df.format(date) - } - return returnValue - } - - /** - * 获取格式化后的时间或日期 - * - * @param pattern pattern - * @param aDate aDate - */ - fun date2Str(pattern: String, aDate: Date?): String { - val df: SimpleDateFormat - var returnValue = "" - if (aDate != null) { - df = SimpleDateFormat(pattern) - returnValue = df.format(aDate) - } - return returnValue - } - - /** - * 将字符串转成时间 - * - * @param datePattern 格式 - * @param strDate 字符串的时间 - */ - fun convertStringToDate(datePattern: String, strDate: String): Date? { - var datePattern = datePattern - var strDate = strDate - val df: SimpleDateFormat - val date: Date - //传入的时间是以 / 分割 - val length = 2 - if (strDate.split(SymbolConst.HENGXIAN.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray().size < length) { - strDate = strDate.replace(SymbolConst.ZHENGXIEXIAN, SymbolConst.HENGXIAN) - } - if (strDate.split(SymbolConst.SPACE.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray().size > 1) { - datePattern = timePattern - } - df = SimpleDateFormat(datePattern) - try { - date = df.parse(strDate) - } catch (pe: ParseException) { - return null - } - - return date - } - - /** - * 字符串转时间 - * - * @param strDate strDate - */ - fun convertStringToDate(strDate: String): Date? { - var strDate = strDate - val aDate: Date? - //传入的时间是以 / 分割 - val length = 2 - if (strDate.split(SymbolConst.HENGXIAN.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray().size < length) { - strDate = strDate.replace(SymbolConst.ZHENGXIEXIAN, SymbolConst.HENGXIAN) - } - aDate = convertStringToDate(datePattern, strDate) - return aDate - } - - /** - * 获取当前时间或时间 - * - * @param theTime theTime - */ - fun getTimeOrTimeNow(theTime: Date): String { - return getDateTime(timePattern, theTime) - } - - /** - * 获取当前时间或时间 - * - * @param theTime theTime - */ - fun getTimeOrTimeNow(pattern: String, theTime: Date): String { - return getDateTime(pattern, theTime) - } - - /** - * 日期格式转换成时间戳 - * - * @param pattern pattern - * @param strDate strDate - */ - fun getTimeStamp(pattern: String, strDate: String): Long { - val returnTimeStamp: Long - val aDate: Date? - aDate = convertStringToDate(pattern, strDate) - if (aDate == null) { - returnTimeStamp = 0 - } else { - returnTimeStamp = aDate.time - } - return returnTimeStamp - } - - /** - * 得到格式化后的系统当前日期 - * - * @param pattern 格式模式字符串 - * @return 格式化后的系统当前时间,如果有异常产生,返回空串"" - */ - fun getNowDateTimeWithPattern(pattern: String): String { - var strReturn: String - val now = Date() - try { - val sdf = SimpleDateFormat(pattern) - strReturn = sdf.format(now) - } catch (e: Exception) { - strReturn = "" - } - - return strReturn - } - - /** - * 将字符串数组使用指定的分隔符合并成一个字符串。 - * - * @param array 字符串数组 - * @param split 分隔符,为null的时候使用""作为分隔符(即没有分隔符) - * @return 合并后的字符串 - * @since 0.4 - */ - fun combineStringArray(array: Array, split: String?): String { - var split = split - val length = array.size - 1 - if (split == null) { - split = "" - } - val result = StringBuilder(length * 8) - for (i in 0 until length) { - result.append(array[i]) - result.append(split) - } - result.append(array[length]) - return result.toString() - } - - /** - * 没搞清楚要传什么参数进去 - * - * @param strWeek strWeek - */ - fun getWeekNum(strWeek: String): Int { - var returnValue = 0 - when (strWeek) { - "Mon" -> returnValue = 1 - "Tue" -> returnValue = 2 - "Wed" -> returnValue = 3 - "Thu" -> returnValue = 4 - "Fri" -> returnValue = 5 - "Sat" -> returnValue = 6 - "Sun" -> returnValue = 0 - else -> returnValue = 0 - } - return returnValue - } - - /** - * 获取日期字符串中的中文时间表示字符串 - * - * @param strDate strDate - */ - fun getSabreTime(strDate: String): String { - var strReturn = "" - try { - - val d = TimeUtil.convertStringToDate("yyyy-MM-dd HH:mm:ss", StringUtil.replace( - strDate, "T", " ")) - strReturn = TimeUtil.date2Str("hh:mm aaa", d) - - } catch (e: Exception) { - return strReturn - } - - return strReturn - } - - /** - * 获取日期字符串中的中文日期表示字符串 - * - * @param strDate strDate - */ - fun getSabreDate(strDate: String): String { - var strReturn = "" - try { - val p: String - val length = 10 - if (strDate.length > length) { - p = "yyyy-MM-dd HH:mm:ss" - } else { - p = "yyyy-MM-dd" - } - val d = TimeUtil.convertStringToDate(p, StringUtil.replace(strDate, "T", " ")) - strReturn = TimeUtil.date2Str("EEE d-MMM", d) - - } catch (e: Exception) { - return strReturn - } - - return strReturn - } - - /** - * 获取日期字符串的中文日期时间表示 - * - * @param strDate strDate - */ - fun getSabreDateTime(strDate: String): String { - var strReturn = "" - try { - val p: String - val length = 10 - if (strDate.length > length) { - p = "yyyy-MM-dd HH:mm:ss" - } else { - p = "yyyy-MM-dd" - } - val d = TimeUtil.convertStringToDate(p, StringUtil.replace(strDate, "T", " ")) - strReturn = TimeUtil.date2Str("EEE d-MMM hh:mm aaa", d) - - } catch (e: Exception) { - return strReturn - } - - return strReturn - } - - /** - * 获取指定的日期 - * - * @param timeType 时间类型,譬如:Calendar.DAY_OF_YEAR - * @param timenum 时间数字,譬如:-1 昨天,0 今天,1 明天 - * @return 日期 - */ - fun getDateFromNow(timeType: Int, timenum: Int): Date { - val cld = Calendar.getInstance() - cld.set(timeType, cld.get(timeType) + timenum) - return cld.time - } - - /** - * 获取日期 - * - * @param timeType 时间类型,譬如:Calendar.DAY_OF_YEAR - * @param timeNum 时间数字,譬如:-1 昨天,0 今天,1 明天 - * @param pattern 时间格式,譬如:"yyyy-MM-dd HH:mm:ss" - * @return 字符串 - */ - fun getDateFromNow(timeType: Int, timeNum: Int, pattern: String?): String { - var pattern = pattern - - if (pattern == null || "" == pattern) { - pattern = "yyyy-MM-dd HH:mm:ss" - } - val cld = Calendar.getInstance() - val date: Date - val df = SimpleDateFormat(pattern) - cld.set(timeType, cld.get(timeType) + timeNum) - date = cld.time - return df.format(date) - } - - /** - * 获取当前日期的字符串 - * - * @param pattern 时间格式,譬如:"yyyy-MM-dd HH:mm:ss" - * @return 字符串 - */ - fun getDateNow(pattern: String?): String { - var pattern = pattern - if (pattern == null || "" == pattern) { - pattern = "yyyy-MM-dd HH:mm:ss" - } - val cld = Calendar.getInstance() - val df = SimpleDateFormat(pattern) - return df.format(cld.time) - } - - /** - * 格式化成yyyy-MM-dd - * - * @return String 返回类型 - */ - fun format(tamp: Timestamp): String { - return DATE_FORMAT.format(tamp) - } - - /** - * 格式化成中文日期 - * - * @return String 返回类型 - */ - fun formatCn(tamp: Timestamp): String { - return DATE_FORMAT_CN.format(tamp) - } - - /** - * 格式化成RSS需要格式 - * - * @return String 返回类型 - */ - fun formartRss(tamp: Timestamp): String { - return DATE_FORMAT_RSS.format(tamp) - } - - /** - * hour小时之前 - */ - fun hourBefor(hour: Int): Date { - return DateUtils.addHours(Date(), -hour) - } - - fun subDate(date: String): String { - return date.substring(0, 10) - } - - /** - * 计算是否是季度末 - * - * @param date date - */ - fun isSeason(date: String): Boolean { - val getMonth = Integer.parseInt(date.substring(5, 7)) - var sign = false - val monthThree = 3 - if (getMonth == monthThree) { - sign = true - } - val monthSix = 6 - if (getMonth == monthSix) { - sign = true - } - val monthNine = 9 - if (getMonth == monthNine) { - sign = true - } - val maxMonth = 12 - if (getMonth == maxMonth) { - sign = true - } - return sign - } - - /** - * 计算从现在开始几天后的时间 - * - * @param afterDay afterDay - */ - fun getDateFromNow(afterDay: Int): String { - val calendar = GregorianCalendar() - var date = calendar.time - - val df = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") - - calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + afterDay) - date = calendar.time - - return df.format(date) - } - - /** - * 带格式 - * - * @param afterDay afterDay - * @param pattern pattern - */ - fun getDateFromNow(afterDay: Int, pattern: String): String { - val calendar = Calendar.getInstance() - val date: Date - val df = SimpleDateFormat(pattern) - calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + afterDay) - date = calendar.time - return df.format(date) - } - - /** - * 得到当前时间,用于文件名,没有特殊字符,使用yyyyMMddHHmmss格式 - * - * @param afterDay afterDay - */ - fun getNowForFileName(afterDay: Int): String { - val calendar = GregorianCalendar() - val df = SimpleDateFormat("yyyyMMddHHmmss") - - calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + afterDay) - val date = calendar.time - - return df.format(date) - } - - /** - * 获取时间 - * - * @param pattern pattern - * @param aDate aDate - */ - private fun getDateTime(pattern: String, aDate: Date?): String { - val df: SimpleDateFormat - var returnValue = "" - if (aDate == null) { - print("aDate is null!") - } else { - df = SimpleDateFormat(pattern) - returnValue = df.format(aDate) - } - - return returnValue - } - - /** - * 判断两个时间是否是同一天 - * - * @param sourceTime sourceTime - * @param targetTime targetTime - * @return - */ - fun isSameDay(sourceTime: Long, targetTime: Long): Boolean { - return getLogicIntervalDays(sourceTime, targetTime) == 0 - } - - /** - * 判断指定的时间是否是今天 - * - * @param time time - */ - fun isToday(time: Long): Boolean { - return isSameDay(System.currentTimeMillis(), time) - } - - /** - * 获取两个时间的逻辑间隔天数,以源时间为基准,目标时间小于源时间则返回大于或等于天数,反之返回小于等于天数 - * - * - * 举例:sourceTime=今天凌晨0点0分1秒,targetTime=昨天晚上11点59分59秒,则返回1 - * - * @param sourceTime sourceTime - * @param targetTime targetTime - * @return - */ - fun getLogicIntervalDays(sourceTime: Long, targetTime: Long): Int { - val source0ClockTime = getZeroClockTime(sourceTime) - val target0ClockTime = getZeroClockTime(targetTime) - - return getRealIntervalDays(source0ClockTime, target0ClockTime) - } - - /** - * 获取两个时间的实际间隔天数 - * - * @param sourceTime sourceTime - * @param targetTime targetTime - */ - fun getRealIntervalDays(sourceTime: Long, targetTime: Long): Int { - return getIntervalTime(sourceTime, targetTime, ONE_DAY_IN_MILLISECONDS).toInt() - } - - /** - * 根据指定的时间单位获取相差的单位时间,如时间单位为一天的毫秒数则该函数跟{@link#getRealIntervalDays} 则是相同的效果 - * - * @param sourceTime sourceTime - * @param targetTime targetTime - * @param timeUnit 时间单位(毫秒) - * @return - */ - fun getIntervalTime(sourceTime: Long, targetTime: Long, timeUnit: Long): Long { - return (sourceTime - targetTime) / timeUnit - } - - /** - * 获取在指定时间戳和指定小时,分钟,秒,毫秒数的时间 - * - * @param time 时间戳 - * @param hour 小时(24小时制) - * @param minute 分钟 - * @param second 秒 - * @param milliSecond 毫秒 - */ - fun getTimeInMillis(time: Long, hour: Int, minute: Int, second: Int, milliSecond: Int): Long { - val calendar = Calendar.getInstance() - calendar.timeInMillis = time - calendar.set(Calendar.HOUR_OF_DAY, hour) - calendar.set(Calendar.MINUTE, minute) - calendar.set(Calendar.SECOND, second) - calendar.set(Calendar.MILLISECOND, milliSecond) - return calendar.timeInMillis - } - - /** - * 获取指定日期的时间戳 - * - * @param year year - * @param month 从1开始 - * @param day day - * @param hour 月 - * @param minute 分 - * @param second 秒 - * @param milliSecond 毫秒 - */ - fun getTimeInMillis(year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int, milliSecond: Int): Long { - val calendar = Calendar.getInstance() - calendar.set(Calendar.YEAR, year) - calendar.set(Calendar.MONTH, month - 1) - calendar.set(Calendar.DAY_OF_MONTH, day) - calendar.set(Calendar.HOUR_OF_DAY, hour) - calendar.set(Calendar.MINUTE, minute) - calendar.set(Calendar.SECOND, second) - calendar.set(Calendar.MILLISECOND, milliSecond) - return calendar.timeInMillis - } - - /** - * 获取今日指定的时间 - * - * @param hour 小时(24小时制) - * @param minute 分钟 - * @param second 秒 - * @param milliSecond 毫秒 - */ - fun getTodayTime(hour: Int, minute: Int, second: Int, milliSecond: Int): Long { - return getTimeInMillis(System.currentTimeMillis(), hour, minute, second, milliSecond) - } - - /** - * 获取指定时间的零点时间 - */ - fun getZeroClockTime(time: Long): Long { - return getTimeInMillis(time, 0, 0, 0, 0) - } - - - /** - * 返回指定时间和格式的时间字符串 - */ - fun getTimeString(time: Long, format: String): String { - val dateFormat = SimpleDateFormat(format) - return dateFormat.format(Date(time)) - } - - /** - * 从字符串中获取时间 - */ - fun getTimeFromString(timeStr: String, format: String): Long { - val dateFormat = SimpleDateFormat(format) - try { - return dateFormat.parse(timeStr).time - } catch (e: ParseException) { - LOGGER.error("", e) - } - - return java.lang.Long.MIN_VALUE - } - - /** - * 获取格式化的剩余时间 - * - * - * 例如:1天20小时5分0秒,20小时0分0秒,1秒 - */ - fun getLeftTimeString(leftTime: Long): String { - var leftTime = leftTime - val sb = StringBuilder() - // 剩余秒数 - val leftSecond = (leftTime / 1000).toInt() - // 秒数 - val second = leftSecond % 60 - if (second > 0) { - sb.insert(0, second.toString() + "秒") - } - // 剩余分钟数 - val leftMinute = leftSecond / 60 - // 分钟数 - var minute = leftMinute % 60 - if (minute > 0) { - sb.insert(0, minute.toString() + "分") - } - // 剩余小时 - val leftHour = leftMinute / 60 - var hour = leftHour % 24 - if (hour > 0) { - sb.insert(0, hour.toString() + "小时") - } - // 剩余天数 - val leftDay = leftHour / 24 - if (leftDay > 0) { - sb.insert(0, leftDay.toString() + "天") - } - // 获取剩余天数 - val day = (leftTime / ONE_DAY_IN_MILLISECONDS).toInt() - // 1天及以上的显示剩余天 - if (day > 0) { - sb.append(day).append("天") - leftTime -= day * ONE_DAY_IN_MILLISECONDS - } - hour = (leftTime / ONE_HOUR_IN_MILLISECONDS).toInt() - // 1小时及以上或者前面显示了天数则后面需要小时 - if (hour > 0 || sb.length > 0) { - sb.append(hour).append("小时") - leftTime -= hour * ONE_HOUR_IN_MILLISECONDS - } - minute = (leftTime / ONE_MINUTE_IN_MILLISECONDS).toInt() - if (minute > 0 || sb.length > 0) { - sb.append(minute).append("分") - leftTime -= minute * ONE_MINUTE_IN_MILLISECONDS - } - sb.append(leftTime / 1000).append("秒") - return sb.toString() - } - - /** - * 得到几天前的时间 - */ - fun getDateBefore(d: Date, day: Int): Date { - val now = Calendar.getInstance() - now.time = d - now.set(Calendar.DATE, now.get(Calendar.DATE) - day) - return now.time - } - - /** - * 得到几天后的时间 - */ - fun getDateAfter(d: Date, day: Int): Date { - val now = Calendar.getInstance() - now.time = d - now.set(Calendar.DATE, now.get(Calendar.DATE) + day) - return now.time - } - - fun getFormatDate(date: Long?, pattern: String): String { - val format = SimpleDateFormat(pattern) - return format.format(date) - } - -} - - - - - - diff --git a/core/src/main/java/info/xiaomo/core/untils/TokenUtil.java b/core/src/main/java/info/xiaomo/core/untils/TokenUtil.java new file mode 100644 index 00000000..d4707393 --- /dev/null +++ b/core/src/main/java/info/xiaomo/core/untils/TokenUtil.java @@ -0,0 +1,74 @@ +package info.xiaomo.core.untils; + +import com.alibaba.fastjson.JSONObject; +import info.xiaomo.core.constant.SymbolConst; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Token 帮助类 + * + * @author : xiaomo + */ +public class TokenUtil { + + private static final String STR_S = "abcdefghijklmnopqrstuvwxyz0123456789"; + + /** + * 参考自 qq sdk + * + * @param string string + * @return String 返回类型 + */ + public static String getAccessToken(String string) { + String accessToken = ""; + try { + JSONObject json = JSONObject.parseObject(string); + if (null != json) { + accessToken = json.getString("access_token"); + } + } catch (Exception e) { + String regex = "^access_token=(\\w+)&expires_in=(\\w+)&refresh_token=(\\w+)$"; + Matcher m = Pattern.compile(regex).matcher(string); + if (m.find()) { + accessToken = m.group(1); + } else { + String regex1 = "^access_token=(\\w+)&expires_in=(\\w+)$"; + Matcher m2 = Pattern.compile(regex1).matcher(string); + if (m2.find()) { + accessToken = m2.group(1); + } else { + String temp = string.split(SymbolConst.DENGHAO)[1]; + accessToken = temp.split(SymbolConst.AND)[0]; + } + } + } + return accessToken; + } + + /** + * 匹配openid + * + * @return String 返回类型 + */ + public static String getOpenId(String string) { + String openid = null; + String regex = "\"openid\"\\s*:\\s*\"(\\w+)\""; + Matcher m = Pattern.compile(regex).matcher(string); + if (m.find()) { + openid = m.group(1); + } + return openid; + } + + /** + * sina uid于qq分离 + * + * @return String 返回类型 + */ + public static String getUid(String string) { + JSONObject json = JSONObject.parseObject(string); + return json.getString("uid"); + } +} diff --git a/core/src/main/java/info/xiaomo/core/untils/TokenUtil.kt b/core/src/main/java/info/xiaomo/core/untils/TokenUtil.kt deleted file mode 100644 index 07effc96..00000000 --- a/core/src/main/java/info/xiaomo/core/untils/TokenUtil.kt +++ /dev/null @@ -1,72 +0,0 @@ -package info.xiaomo.core.untils - -import com.alibaba.fastjson.JSONObject -import info.xiaomo.core.constant.SymbolConst -import java.util.regex.Pattern - -/** - * Token 帮助类 - * @author : xiaomo - */ -object TokenUtil { - - private val STR_S = "abcdefghijklmnopqrstuvwxyz0123456789" - - /** - * 参考自 qq sdk - * - * @param string string - * @return String 返回类型 - */ - fun getAccessToken(string: String): String { - var accessToken = "" - try { - val json = JSONObject.parseObject(string) - if (null != json) { - accessToken = json.getString("access_token") - } - } catch (e: Exception) { - val regex = "^access_token=(\\w+)&expires_in=(\\w+)&refresh_token=(\\w+)$" - val m = Pattern.compile(regex).matcher(string) - if (m.find()) { - accessToken = m.group(1) - } else { - val regex1 = "^access_token=(\\w+)&expires_in=(\\w+)$" - val m2 = Pattern.compile(regex1).matcher(string) - if (m2.find()) { - accessToken = m2.group(1) - } else { - val temp = string.split(SymbolConst.DENGHAO.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[1] - accessToken = temp.split(SymbolConst.AND.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0] - } - } - } - - return accessToken - } - - /** - * 匹配openid - * - * @return String 返回类型 - */ - fun getOpenId(string: String): String? { - var openid: String? = null - val regex = "\"openid\"\\s*:\\s*\"(\\w+)\"" - val m = Pattern.compile(regex).matcher(string) - if (m.find()) { - openid = m.group(1) - } - return openid - } - - /** - * sina uid于qq分离 - * - * @return String 返回类型 - */ - fun getUid(string: String): String { - val json = JSONObject.parseObject(string) - return json.getString("uid") - } -} diff --git a/core/src/main/java/info/xiaomo/core/untils/XmlUtil.java b/core/src/main/java/info/xiaomo/core/untils/XmlUtil.java new file mode 100644 index 00000000..48fe446f --- /dev/null +++ b/core/src/main/java/info/xiaomo/core/untils/XmlUtil.java @@ -0,0 +1,145 @@ +package info.xiaomo.core.untils; + +import com.alibaba.fastjson.JSON; +import org.dom4j.*; +import org.dom4j.io.OutputFormat; +import org.dom4j.io.SAXReader; +import org.dom4j.io.XMLWriter; + +import java.io.*; +import java.net.URL; +import java.util.List; + +/** + * @author : xiaomo + */ +public class XmlUtil { + /** + * 解析url xml文档 + * + * @param url + */ + public static Document parse(URL url) throws DocumentException { + SAXReader reader = new SAXReader(); + return reader.read(url); + } + + /** + * 遍历解析文档 + */ + public static void treeWalk(Document document) { + treeWalk(document.getRootElement()); + } + + /** + * 遍历解析元素 + */ + public static void treeWalk(Element element) { + for (int i = 0, size = element.nodeCount(); i < size; i++) { + Node node = element.node(i); + if (node instanceof Element) { + treeWalk((Element) node); + } + + } + } + + /** + * 解析文件,获得根元素 + */ + public static Element parse(String xmlPath, String encoding) throws Exception { + //文件是否存在 + File file = new File(xmlPath); + if (!file.exists()) { + throw new Exception("找不到xml文件:" + xmlPath); + } + + //解析 + SAXReader reader = new SAXReader(false); + Document doc = reader.read(new FileInputStream(file), encoding); + return doc.getRootElement(); + } + + /** + * 保存文档 + * + * @throws Exception + */ + public static void save(Document doc, String xmlPath, String encoding) throws Exception { + OutputFormat format = OutputFormat.createPrettyPrint(); + format.setEncoding(encoding); + XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(xmlPath), encoding), format); + writer.write(doc); + writer.flush(); + writer.close(); + } + + /** + * 修改xml某节点的值 + * + * @param inputXml 原xml文件 + * @param nodes 要修改的节点 + * @param attributeName 属性名称 + * @param value 新值 + * @param outXml 输出文件路径及文件名 如果输出文件为null,则默认为原xml文件 + */ + public static void modifyDocument(File inputXml, String nodes, String attributeName, String value, String outXml) { + try { + SAXReader saxReader = new SAXReader(); + Document document = saxReader.read(inputXml); + List list = document.selectNodes(nodes); + for (Object aList : list) { + Attribute attribute = (Attribute) aList; + if (attribute.getName().equals(attributeName)) { + attribute.setValue(value); + } + } + XMLWriter output; + //指定输出文件 + if (outXml != null) { + output = new XMLWriter(new FileWriter(new File(outXml))); + } else { //输出文件为原文件 + output = new XMLWriter(new FileWriter(inputXml)); + } + output.write(document); + output.close(); + } catch (DocumentException | IOException e) { + System.out.println(e.getMessage()); + } + } + + /** + * xml转换为字符串 + * + * @param doc + * @param encoding + * @return + * @throws Exception + */ + public static String toString(Document doc, String encoding) throws Exception { + OutputFormat format = OutputFormat.createPrettyPrint(); + format.setEncoding(encoding); + ByteArrayOutputStream byteOS = new ByteArrayOutputStream(); + XMLWriter writer = new XMLWriter(new OutputStreamWriter(byteOS, encoding), format); + writer.write(doc); + writer.flush(); + writer.close(); + return byteOS.toString(encoding); + } + + /** + * 字符串转换为Document + * + * @param text + * @return + * @throws DocumentException + */ + public static Document str2Document(String text) throws DocumentException { + return DocumentHelper.parseText(text); + } + + public static void main(String[] args) throws Exception { + Element parse = parse("E:\\thinkpage_cities.xls", "UTF8"); + System.out.println(JSON.toJSONString(parse)); + } +} diff --git a/core/src/main/java/info/xiaomo/core/untils/XmlUtil.kt b/core/src/main/java/info/xiaomo/core/untils/XmlUtil.kt deleted file mode 100644 index a512d6b4..00000000 --- a/core/src/main/java/info/xiaomo/core/untils/XmlUtil.kt +++ /dev/null @@ -1,157 +0,0 @@ -package info.xiaomo.core.untils - -import com.alibaba.fastjson.JSON -import org.dom4j.* -import org.dom4j.io.OutputFormat -import org.dom4j.io.SAXReader -import org.dom4j.io.XMLWriter - -import java.io.* -import java.net.URL - -/** - * @author : xiaomo - */ -object XmlUtil { - /** - * 解析url xml文档 - * - * @param url - */ - @Throws(DocumentException::class) - fun parse(url: URL): Document { - val reader = SAXReader() - return reader.read(url) - } - - /** - * 遍历解析文档 - */ - fun treeWalk(document: Document) { - treeWalk(document.rootElement) - } - - /** - * 遍历解析元素 - */ - fun treeWalk(element: Element) { - var i = 0 - val size = element.nodeCount() - while (i < size) { - val node = element.node(i) - if (node is Element) { - treeWalk(node) - } - i++ - - } - } - - /** - * 解析文件,获得根元素 - */ - @Throws(Exception::class) - fun parse(xmlPath: String, encoding: String): Element { - //文件是否存在 - val file = File(xmlPath) - if (!file.exists()) { - throw Exception("找不到xml文件:" + xmlPath) - } - - //解析 - val reader = SAXReader(false) - val doc = reader.read(FileInputStream(file), encoding) - return doc.rootElement - } - - /** - * 保存文档 - * - * @throws Exception - */ - @Throws(Exception::class) - fun save(doc: Document, xmlPath: String, encoding: String) { - val format = OutputFormat.createPrettyPrint() - format.encoding = encoding - val writer = XMLWriter(OutputStreamWriter(FileOutputStream(xmlPath), encoding), format) - writer.write(doc) - writer.flush() - writer.close() - } - - /** - * 修改xml某节点的值 - * - * @param inputXml 原xml文件 - * @param nodes 要修改的节点 - * @param attributeName 属性名称 - * @param value 新值 - * @param outXml 输出文件路径及文件名 如果输出文件为null,则默认为原xml文件 - */ - fun modifyDocument(inputXml: File, nodes: String, attributeName: String, value: String, outXml: String?) { - try { - val saxReader = SAXReader() - val document = saxReader.read(inputXml) - val list = document.selectNodes(nodes) - for (aList in list) { - val attribute = aList as Attribute - if (attribute.name == attributeName) { - attribute.value = value - } - } - val output: XMLWriter - //指定输出文件 - if (outXml != null) { - output = XMLWriter(FileWriter(File(outXml))) - } else { //输出文件为原文件 - output = XMLWriter(FileWriter(inputXml)) - } - output.write(document) - output.close() - } catch (e: DocumentException) { - println(e.message) - } catch (e: IOException) { - println(e.message) - } - - } - - /** - * xml转换为字符串 - * - * @param doc - * @param encoding - * @return - * @throws Exception - */ - @Throws(Exception::class) - fun toString(doc: Document, encoding: String): String { - val format = OutputFormat.createPrettyPrint() - format.encoding = encoding - val byteOS = ByteArrayOutputStream() - val writer = XMLWriter(OutputStreamWriter(byteOS, encoding), format) - writer.write(doc) - writer.flush() - writer.close() - return byteOS.toString(encoding) - } - - /** - * 字符串转换为Document - * - * @param text - * @return - * @throws DocumentException - */ - @Throws(DocumentException::class) - fun str2Document(text: String): Document { - return DocumentHelper.parseText(text) - } - - @Throws(Exception::class) - @JvmStatic - fun main(args: Array) { - val parse = parse("E:\\thinkpage_cities.xls", "UTF8") - println(JSON.toJSONString(parse)) - } -} diff --git a/crawler/pom.xml b/crawler/pom.xml index d8cde5a4..157ff6a3 100644 --- a/crawler/pom.xml +++ b/crawler/pom.xml @@ -5,7 +5,7 @@ xiaomo info.xiaomo - 2017.2 + 2020.1 4.0.0 @@ -15,7 +15,7 @@ info.xiaomo core - 2017.2 + 2020.1 org.springframework.boot diff --git a/crawler/src/main/java/info/xiaomo/crawler/CrawlerMain.kt b/crawler/src/main/java/info/xiaomo/crawler/CrawlerMain.java similarity index 60% rename from crawler/src/main/java/info/xiaomo/crawler/CrawlerMain.kt rename to crawler/src/main/java/info/xiaomo/crawler/CrawlerMain.java index 4255932d..4f960904 100644 --- a/crawler/src/main/java/info/xiaomo/crawler/CrawlerMain.kt +++ b/crawler/src/main/java/info/xiaomo/crawler/CrawlerMain.java @@ -1,36 +1,36 @@ -package info.xiaomo.crawler +package info.xiaomo.crawler; -import org.springframework.beans.factory.annotation.Configurable -import org.springframework.boot.SpringApplication -import org.springframework.boot.autoconfigure.EnableAutoConfiguration -import org.springframework.context.annotation.ComponentScan -import org.springframework.data.jpa.repository.config.EnableJpaRepositories -import org.springframework.scheduling.annotation.EnableScheduling +import org.springframework.beans.factory.annotation.Configurable; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.scheduling.annotation.EnableScheduling; /** * 把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * + + *

* * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info - * - * + *

* Date: 2016/4/1 15:38 * Copyright(©) 2015 by xiaomo. - */ + **/ +@Configuration @EnableAutoConfiguration @EnableScheduling @Configurable @EnableJpaRepositories("info.xiaomo.*.dao") @ComponentScan("info.xiaomo") -class CrawlerMain - -@Throws(Exception::class) -fun main(args: Array) { - SpringApplication.run(CrawlerMain::class.java, *args) +public class CrawlerMain { + public static void main(String[] args) throws Exception { + SpringApplication.run(CrawlerMain.class, args); + } } diff --git a/crawler/src/main/java/info/xiaomo/crawler/dao/ShikigamaDao.java b/crawler/src/main/java/info/xiaomo/crawler/dao/ShikigamaDao.java new file mode 100644 index 00000000..6f3078fc --- /dev/null +++ b/crawler/src/main/java/info/xiaomo/crawler/dao/ShikigamaDao.java @@ -0,0 +1,21 @@ +package info.xiaomo.crawler.dao; + +import info.xiaomo.crawler.model.ShikigamiModel; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +/** + * @author : xiaomo (https://xiaomo.info) (https://github.com/houko) + * @created : 2016/12/24 15:55 + */ +@Repository +public interface ShikigamaDao extends JpaRepository { + + /** + * 根据名字查式神 + * + * @param name + * @return + */ + ShikigamiModel findByName(String name); +} diff --git a/crawler/src/main/java/info/xiaomo/crawler/dao/ShikigamaDao.kt b/crawler/src/main/java/info/xiaomo/crawler/dao/ShikigamaDao.kt deleted file mode 100644 index 112ae8aa..00000000 --- a/crawler/src/main/java/info/xiaomo/crawler/dao/ShikigamaDao.kt +++ /dev/null @@ -1,21 +0,0 @@ -package info.xiaomo.crawler.dao - -import info.xiaomo.crawler.model.ShikigamiModel -import org.springframework.data.jpa.repository.JpaRepository -import org.springframework.stereotype.Repository - -/** - * @author : xiaomo (https://xiaomo.info) (https://github.com/xiaomoinfo) - * @created : 2016/12/24 15:55 - */ -@Repository -interface ShikigamaDao : JpaRepository { - - /** - * 根据名字查式神 - * - * @param name - * @return - */ - fun findByName(name: String?): ShikigamiModel -} diff --git a/crawler/src/main/java/info/xiaomo/crawler/model/MitamaModel.kt b/crawler/src/main/java/info/xiaomo/crawler/model/MitamaModel.java similarity index 56% rename from crawler/src/main/java/info/xiaomo/crawler/model/MitamaModel.kt rename to crawler/src/main/java/info/xiaomo/crawler/model/MitamaModel.java index 83d2e7c1..4eb5ad72 100644 --- a/crawler/src/main/java/info/xiaomo/crawler/model/MitamaModel.kt +++ b/crawler/src/main/java/info/xiaomo/crawler/model/MitamaModel.java @@ -1,56 +1,56 @@ -package info.xiaomo.crawler.model +package info.xiaomo.crawler.model; -import info.xiaomo.core.base.BaseModel +import info.xiaomo.core.base.BaseModel; /** - * @author : xiaomo (https://xiaomo.info) (https://github.com/xiaomoinfo) + * @author : xiaomo (https://xiaomo.info) (https://github.com/houko) * @created : 2016/12/24 18:06 * 御魂模型 */ -class MitamaModel : BaseModel() { +public class MitamaModel extends BaseModel { /** * 名字 * 火灵 */ - private val mitamaMame: String? = null + private String name; /** * icon * http://uus-ng.img.d.cn/snapshot/201610/999/image/388/388/hd/20161012151646257.jpeg */ - private val image: String? = null + private String image; /** * 两件套效果 * 效果命中+15% */ - private val effect2: String? = null + private String effect2; /** * 四件套效果 * 初次出场时获得额外3点鬼火(新回目战斗开始也会被计为初次出场) */ - private val effect4: String? = null + private String effect4; /** * 关键字 */ - private val keyworld: String? = null + private String keyworld; /** * 推荐式神 * 青行灯 */ - private val suggest: String? = null + private String suggest; /** * 获取方式 * 神秘商店、周末御魂 */ - private val getWay: String? = null + private String getWay; } diff --git a/crawler/src/main/java/info/xiaomo/crawler/model/ShikigamiModel.java b/crawler/src/main/java/info/xiaomo/crawler/model/ShikigamiModel.java new file mode 100644 index 00000000..b208fea5 --- /dev/null +++ b/crawler/src/main/java/info/xiaomo/crawler/model/ShikigamiModel.java @@ -0,0 +1,68 @@ +package info.xiaomo.crawler.model; + +import info.xiaomo.core.base.BaseModel; +import lombok.*; + +import javax.persistence.Entity; +import javax.persistence.Table; + +/** + * @author : xiaomo (https://xiaomo.info) (https://github.com/houko) + * @created : 2016/12/24 15:09 + */ + +@Entity +@Table(name = "shikigame") +// lomlok +@Data +@ToString(callSuper = true) +@EqualsAndHashCode(callSuper = false) +@AllArgsConstructor +@NoArgsConstructor +public class ShikigamiModel extends BaseModel { + + /** + * 名字 + */ + private String name; + + /** + * 图片 + */ + private String image; + + /** + * 声优 + */ + private String seiyou; + + + /** + * 性别 + */ + private String sex; + + /** + * 星级 + */ + private String star; + + /** + * 获取方式 + */ + private String getWay; + + + /** + * N/R/SR/SSR + */ + private String level; + + + /** + * 描述 + */ + private String des; + + +} diff --git a/crawler/src/main/java/info/xiaomo/crawler/model/ShikigamiModel.kt b/crawler/src/main/java/info/xiaomo/crawler/model/ShikigamiModel.kt deleted file mode 100644 index 3539b81a..00000000 --- a/crawler/src/main/java/info/xiaomo/crawler/model/ShikigamiModel.kt +++ /dev/null @@ -1,76 +0,0 @@ -package info.xiaomo.crawler.model - -import info.xiaomo.core.base.BaseModel -import javax.persistence.Entity -import javax.persistence.Table - -/** - * @author : xiaomo (https://xiaomo.info) (https://github.com/xiaomoinfo) - * @created : 2016/12/24 15:09 - */ - -@Entity -@Table(name = "shikigame") -class ShikigamiModel : BaseModel() { - - /** - * 图片 - */ - var image: String? = null - set(image) { - field = this.image - } - - /** - * 声优 - */ - var seiyou: String? = null - set(seiyou) { - field = this.seiyou - } - - - /** - * 性别 - */ - var sex: String? = null - set(sex) { - field = this.sex - } - - /** - * 星级 - */ - var star: String? = null - set(star) { - field = this.star - } - - /** - * 获取方式 - */ - var getWay: String? = null - set(getWay) { - field = this.getWay - } - - - /** - * N/R/SR/SSR - */ - var level: String? = null - set(level) { - field = this.level - } - - - /** - * 描述 - */ - var des: String? = null - set(des) { - field = this.des - } - - -} diff --git a/crawler/src/main/java/info/xiaomo/crawler/schedule/ScheduledTasks.java b/crawler/src/main/java/info/xiaomo/crawler/schedule/ScheduledTasks.java new file mode 100644 index 00000000..1d43fcbe --- /dev/null +++ b/crawler/src/main/java/info/xiaomo/crawler/schedule/ScheduledTasks.java @@ -0,0 +1,65 @@ +package info.xiaomo.crawler.schedule; + +import info.xiaomo.core.untils.DownUtil; +import info.xiaomo.crawler.model.ShikigamiModel; +import info.xiaomo.crawler.service.ShikigamaService; +import info.xiaomo.crawler.spider.OnnmyoujiSpider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +/** + * @author : xiaomo (https://xiaomo.info) (https://github.com/houko) + * @created : 2016/12/24 15:59 + */ +@Component +public class ScheduledTasks { + + private static final Logger LOGGER = LoggerFactory.getLogger(ScheduledTasks.class); + + private final ShikigamaService shikigamaService; + + @Autowired + public ScheduledTasks(ShikigamaService shikigamaService) { + this.shikigamaService = shikigamaService; + } + + + @Scheduled(fixedRate = 1000 * 30) + public void reportCurrentTime() { + System.out.println("Scheduling Tasks Examples: The time is now " + dateFormat().format(new Date())); + } + + //每1分钟执行一次 + @Scheduled(cron = "0 */1 * * * * ") + public void reportCurrentByCron() { + LOGGER.debug("开始执行任务:"); + List shikigamiModel = OnnmyoujiSpider.getShikigamiModel(); + for (ShikigamiModel model : shikigamiModel) { + shikigamaService.save(model); + } + } + + @Scheduled(fixedRate = 1000) + public void downImage() throws Exception { + LOGGER.debug("开始执行任务:"); + List shikigamiModel = shikigamaService.findAll(); + for (ShikigamiModel aShikigamiModel : shikigamiModel) { + String url = aShikigamiModel.getImage(); + DownUtil.download(url, "D:\\yys\\"); + LOGGER.debug("开始下载图片:{}", url); + } + } + + + private SimpleDateFormat dateFormat() { + return new SimpleDateFormat("HH:mm:ss"); + } + +} diff --git a/crawler/src/main/java/info/xiaomo/crawler/schedule/ScheduledTasks.kt b/crawler/src/main/java/info/xiaomo/crawler/schedule/ScheduledTasks.kt deleted file mode 100644 index 8699bc4f..00000000 --- a/crawler/src/main/java/info/xiaomo/crawler/schedule/ScheduledTasks.kt +++ /dev/null @@ -1,59 +0,0 @@ -package info.xiaomo.crawler.schedule - -import info.xiaomo.core.untils.DownUtil -import info.xiaomo.crawler.service.ShikigamaService -import info.xiaomo.crawler.spider.OnnmyoujiSpider -import org.slf4j.LoggerFactory -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.scheduling.annotation.Scheduled -import org.springframework.stereotype.Component -import java.text.SimpleDateFormat -import java.util.* - -/** - * @author : xiaomo (https://xiaomo.info) (https://github.com/xiaomoinfo) - * @created : 2016/12/24 15:59 - */ -@Component -class ScheduledTasks @Autowired -constructor(private val shikigamaService: ShikigamaService) { - - - @Scheduled(fixedRate = (1000 * 30).toLong()) - fun reportCurrentTime() { - println("Scheduling Tasks Examples: The time is now " + dateFormat().format(Date())) - } - - //每1分钟执行一次 - @Scheduled(cron = "0 */1 * * * * ") - fun reportCurrentByCron() { - LOGGER.debug("开始执行任务:") - val shikigamiModel = OnnmyoujiSpider.shikigamiModel - for (model in shikigamiModel) { - shikigamaService.save(model) - } - } - - @Scheduled(fixedRate = 1000) - @Throws(Exception::class) - fun downImage() { - LOGGER.debug("开始执行任务:") - val shikigamiModel = shikigamaService.findAll() - for (aShikigamiModel in shikigamiModel) { - val url = aShikigamiModel.image - DownUtil.download(url, "D:\\yys\\") - LOGGER.debug("开始下载图片:{}", url) - } - } - - - private fun dateFormat(): SimpleDateFormat { - return SimpleDateFormat("HH:mm:ss") - } - - companion object { - - private val LOGGER = LoggerFactory.getLogger(ScheduledTasks::class.java) - } - -} diff --git a/crawler/src/main/java/info/xiaomo/crawler/service/ShikigamaService.java b/crawler/src/main/java/info/xiaomo/crawler/service/ShikigamaService.java new file mode 100644 index 00000000..6f3f6b01 --- /dev/null +++ b/crawler/src/main/java/info/xiaomo/crawler/service/ShikigamaService.java @@ -0,0 +1,35 @@ +package info.xiaomo.crawler.service; + +import info.xiaomo.crawler.model.ShikigamiModel; + +import java.util.List; + +/** + * @author : xiaomo (https://xiaomo.info) (https://github.com/houko) + * @created : 2016/12/24 15:54 + */ +public interface ShikigamaService { + + /** + * 根据名字查式神 + * + * @param name + * @return + */ + ShikigamiModel findByName(String name); + + /** + * 保存 + * + * @param model + */ + void save(ShikigamiModel model); + + /** + * 查所有 + * + * @return + */ + List findAll(); + +} diff --git a/crawler/src/main/java/info/xiaomo/crawler/service/ShikigamaService.kt b/crawler/src/main/java/info/xiaomo/crawler/service/ShikigamaService.kt deleted file mode 100644 index 9a8789ab..00000000 --- a/crawler/src/main/java/info/xiaomo/crawler/service/ShikigamaService.kt +++ /dev/null @@ -1,33 +0,0 @@ -package info.xiaomo.crawler.service - -import info.xiaomo.crawler.model.ShikigamiModel - -/** - * @author : xiaomo (https://xiaomo.info) (https://github.com/xiaomoinfo) - * @created : 2016/12/24 15:54 - */ -interface ShikigamaService { - - /** - * 根据名字查式神 - * - * @param name - * @return - */ - fun findByName(name: String): ShikigamiModel - - /** - * 保存 - * - * @param model - */ - fun save(model: ShikigamiModel) - - /** - * 查所有 - * - * @return - */ - fun findAll(): List - -} diff --git a/crawler/src/main/java/info/xiaomo/crawler/service/impl/ShikigamaServiceImpl.java b/crawler/src/main/java/info/xiaomo/crawler/service/impl/ShikigamaServiceImpl.java new file mode 100644 index 00000000..0a5bfe42 --- /dev/null +++ b/crawler/src/main/java/info/xiaomo/crawler/service/impl/ShikigamaServiceImpl.java @@ -0,0 +1,49 @@ +package info.xiaomo.crawler.service.impl; + +import com.alibaba.fastjson.JSON; +import info.xiaomo.crawler.dao.ShikigamaDao; +import info.xiaomo.crawler.model.ShikigamiModel; +import info.xiaomo.crawler.service.ShikigamaService; +import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * @author : xiaomo (https://xiaomo.info) (https://github.com/houko) + * @created : 2016/12/24 15:54 + */ +@Service +public class ShikigamaServiceImpl implements ShikigamaService { + + + private static final Logger LOGGER = org.slf4j.LoggerFactory.getLogger(ShikigamaServiceImpl.class); + + private final ShikigamaDao dao; + + + @Autowired + public ShikigamaServiceImpl(ShikigamaDao dao) { + this.dao = dao; + } + + @Override + public ShikigamiModel findByName(String name) { + return dao.findByName(name); + } + + @Override + public void save(ShikigamiModel model) { + ShikigamiModel shikigamiModel = dao.findByName(model.getName()); + if (shikigamiModel == null) { + dao.save(model); + LOGGER.debug("插入数据:{}", JSON.toJSONString(model)); + } + } + + @Override + public List findAll() { + return dao.findAll(); + } +} diff --git a/crawler/src/main/java/info/xiaomo/crawler/service/impl/ShikigamaServiceImpl.kt b/crawler/src/main/java/info/xiaomo/crawler/service/impl/ShikigamaServiceImpl.kt deleted file mode 100644 index ad71bd90..00000000 --- a/crawler/src/main/java/info/xiaomo/crawler/service/impl/ShikigamaServiceImpl.kt +++ /dev/null @@ -1,39 +0,0 @@ -package info.xiaomo.crawler.service.impl - -import com.alibaba.fastjson.JSON -import info.xiaomo.crawler.dao.ShikigamaDao -import info.xiaomo.crawler.model.ShikigamiModel -import info.xiaomo.crawler.service.ShikigamaService -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.stereotype.Service - -/** - * @author : xiaomo (https://xiaomo.info) (https://github.com/xiaomoinfo) - * @created : 2016/12/24 15:54 - */ -@Service -class ShikigamaServiceImpl @Autowired -constructor(private val dao: ShikigamaDao) : ShikigamaService { - - override fun findByName(name: String): ShikigamiModel { - return dao.findByName(name) - } - - override fun save(model: ShikigamiModel) { - val shikigamiModel = dao.findByName(model.name) - if (shikigamiModel == null) { - dao.save(model) - LOGGER.debug("插入数据:{}", JSON.toJSONString(model)) - } - } - - override fun findAll(): List { - return dao.findAll() - } - - companion object { - - - private val LOGGER = org.slf4j.LoggerFactory.getLogger(ShikigamaServiceImpl::class.java) - } -} diff --git a/crawler/src/main/java/info/xiaomo/crawler/spider/Crawler.java b/crawler/src/main/java/info/xiaomo/crawler/spider/Crawler.java new file mode 100644 index 00000000..44bfd7d5 --- /dev/null +++ b/crawler/src/main/java/info/xiaomo/crawler/spider/Crawler.java @@ -0,0 +1,136 @@ +//package info.xiaomo.crawler.spider; +// +//import okhttp3.*; +//import org.jsoup.Jsoup; +//import org.jsoup.nodes.Document; +//import org.jsoup.nodes.Element; +//import org.slf4j.Logger; +//import org.slf4j.LoggerFactory; +// +//import java.io.File; +//import java.io.IOException; +//import java.util.*; +//import java.util.concurrent.*; +//import java.util.concurrent.atomic.AtomicInteger; +// +//public class Crawler { +// private static final Logger LOGGER = LoggerFactory.getLogger(Crawler.class); +// private final Set fetchedUrls = Collections.synchronizedSet(new LinkedHashSet()); +// private final BlockingQueue queue = new LinkedBlockingQueue<>(); +// private final ConcurrentMap hostnames = new ConcurrentHashMap<>(); +// private OkHttpClient client = null; +// +// private Crawler() { +// init(); +// } +// +// private static Crawler getInstance() { +// return CrawlerHolder.INSTANCE; +// } +// +// public static void main(String[] args) throws ExecutionException, IntCodeuptedException { +// String[] urls = {"https://www.baidu.com/"}; +// List> results = Crawler.getInstance().initUrl(urls).parallelDrainQueue(3); +// for (Future future : results) { +// System.out.println(future.get()); +// } +// } +// +// private Crawler initUrl(String[] urls) { +// for (String url : urls) { +// queue.add(HttpUrl.parse(url)); +// } +// +// return this; +// } +// +// private void init() { +// long cacheByteCount = 1024 * 1024 * 100; +// String dir = "C:\\test"; +// Cache cache = new Cache(new File(dir), cacheByteCount); +// client = new OkHttpClient.Builder().cache(cache).build(); +// } +// +// public List> parallelDrainQueue(int threadCount) { +// ExecutorService executor = Executors.newFixedThreadPool(threadCount); +// List> results = new ArrayList<>(); +// for (int i = 0; i < threadCount; i++) { +// Future future = executor.submit(new Callable() { +// @Override +// public String call() throws Exception { +// try { +// drainQueue(); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// return null; +// } +// }); +// +// results.add(future); +// } +// return results; +// } +// +// private void drainQueue() throws Exception { +// for (HttpUrl url; (url = queue.take()) != null; ) { +// if (!fetchedUrls.add(url)) { +// continue; +// } +// +// try { +// fetch(url); +// } catch (IOException e) { +// e.printStackTrace(); +// } +// } +// } +// +// private void fetch(HttpUrl url) throws IOException { +// AtomicInteger hostnameCount = new AtomicInteger(); +// AtomicInteger previous = hostnames.putIfAbsent(url.host(), hostnameCount); +// if (previous != null) { +// hostnameCount = previous; +// } +// +// if (hostnameCount.incrementAndGet() > 100) { +// return; +// } +// +// Request request = new Request.Builder().url(url).build(); +// Response response = client.newCall(request).execute(); +// String responseSource = response.networkResponse() != null +// ? ("(network: " + response.networkResponse().code() + " over " + response.protocol() + ")") : "(cache)"; +// int responseCode = response.code(); +// +// // 打印log +// LOGGER.info("ThreadName:【{}】,ResponseCode:【{}】,URL:【{}】,ResponseSource:【{}】", Thread.currentThread().getName(), +// responseCode, url, responseSource); +// +// String contentType = response.header("Content-Type"); +// if (responseCode != 200 || contentType == null) { +// response.body().close(); +// return; +// } +// +// MediaType mediaType = MediaType.parse(contentType); +// if (mediaType == null || !mediaType.subtype().equalsIgnoreCase("html")) { +// response.body().close(); +// return; +// } +// +// // 获取页面的a[href], 加入LinkedBlockingQueue +// Document document = Jsoup.parse(response.body().string(), url.toString()); +// for (Element element : document.select("a[href]")) { +// String href = element.attr("href"); +// HttpUrl link = response.request().url().resolve(href); +// if (link != null) { +// queue.add(link); +// } +// } +// } +// +// private static class CrawlerHolder { +// private static final Crawler INSTANCE = new Crawler(); +// } +//} diff --git a/crawler/src/main/java/info/xiaomo/crawler/spider/OnnmyoujiSpider.java b/crawler/src/main/java/info/xiaomo/crawler/spider/OnnmyoujiSpider.java new file mode 100644 index 00000000..2423e44a --- /dev/null +++ b/crawler/src/main/java/info/xiaomo/crawler/spider/OnnmyoujiSpider.java @@ -0,0 +1,91 @@ +package info.xiaomo.crawler.spider; + +import info.xiaomo.core.untils.HttpUtil; +import info.xiaomo.crawler.model.ShikigamiModel; +import org.jsoup.Jsoup; +import org.jsoup.nodes.Document; +import org.jsoup.nodes.Element; +import org.jsoup.select.Elements; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author : xiaomo (https://xiaomo.info) (https://github.com/houko) + * @created : 2016/12/24 15:05 + * 阴阳师获取数据 + */ +public class OnnmyoujiSpider { + + private static final String URL = "http://ng.d.cn/db/yinyangshi/index.html"; + + + /** + * 获取数据并封装成model + */ + public static List getShikigamiModel() { + List list = new ArrayList<>(); + List shikigamiDetailInfoUrl = getShikigamiDetailInfoUrl(); + for (String url : shikigamiDetailInfoUrl) { + ShikigamiModel shikigamiModel = getShikigami(url); + list.add(shikigamiModel); + } + return list; + } + + + /** + * 获取式神详情页链接 + */ + private static List getShikigamiDetailInfoUrl() { + List list = new ArrayList<>(); + String html = HttpUtil.get(URL); + Document doc = Jsoup.parse(html); + Element select = doc.select(".heroList-2").get(0); + Elements liElement = select.select("a"); + for (Element element : liElement) { + String href = element.attr("href"); + list.add(href); + } + return list; + } + + + /** + * 获取御魂信息详情页连接 + */ + private static List getMitamaDetailInfoUrl() { + List list = new ArrayList<>(); + String html = HttpUtil.get(URL); + Document doc = Jsoup.parse(html); + Element select = doc.select(".heroList-1").get(0); + Elements liElement = select.select("a"); + for (Element element : liElement) { + String href = element.attr("href"); + list.add(href); + } + return list; + } + + + /** + * 获取式神信息 + */ + private static ShikigamiModel getShikigami(String url) { + ShikigamiModel a = new ShikigamiModel(); + String html = HttpUtil.get(url); + Document doc = Jsoup.parse(html); + Elements selects = doc.select("table").get(1).select("tr").get(2).select("td"); + String seiyou = selects.get(0).text(); + String name = selects.get(1).text(); + String star = selects.get(2).text(); + String sex = selects.get(3).text(); + String level = selects.get(4).text(); + String getWay = selects.get(5).text(); + String image = doc.select("table").get(0).select("tr").get(0).select("img").attr("src"); + return new ShikigamiModel(name, image, seiyou, sex, star, getWay, level, ""); + + + } + +} diff --git a/crawler/src/main/java/info/xiaomo/crawler/spider/OnnmyoujiSpider.kt b/crawler/src/main/java/info/xiaomo/crawler/spider/OnnmyoujiSpider.kt deleted file mode 100644 index 3d0e29b5..00000000 --- a/crawler/src/main/java/info/xiaomo/crawler/spider/OnnmyoujiSpider.kt +++ /dev/null @@ -1,91 +0,0 @@ -package info.xiaomo.crawler.spider - -import info.xiaomo.core.untils.HttpUtil -import info.xiaomo.crawler.model.ShikigamiModel -import org.jsoup.Jsoup -import java.util.* - -/** - * @author : xiaomo (https://xiaomo.info) (https://github.com/xiaomoinfo) - * @created : 2016/12/24 15:05 - * 阴阳师获取数据 - */ -object OnnmyoujiSpider { - - private val URL = "http://ng.d.cn/db/yinyangshi/index.html" - - - /** - * 获取数据并封装成model - */ - val shikigamiModel: List - get() { - val list = ArrayList() - val shikigamiDetailInfoUrl = shikigamiDetailInfoUrl - for (url in shikigamiDetailInfoUrl) { - val shikigamiModel = getShikigami(url) - list.add(shikigamiModel) - } - return list - } - - - /** - * 获取式神详情页链接 - */ - private val shikigamiDetailInfoUrl: List - get() { - val list = ArrayList() - val html = HttpUtil.get(URL) - val doc = Jsoup.parse(html) - val select = doc.select(".heroList-2")[0] - val liElement = select.select("a") - for (element in liElement) { - val href = element.attr("href") - list.add(href) - } - return list - } - - - /** - * 获取御魂信息详情页连接 - */ - private val mitamaDetailInfoUrl: List - get() { - val html = HttpUtil.get(URL) - val doc = Jsoup.parse(html) - val select = doc.select(".heroList-1")[0] - val liElement = select.select("a") - return liElement.map { it.attr("href") } - } - - - /** - * 获取式神信息 - */ - private fun getShikigami(url: String): ShikigamiModel { - val a = ShikigamiModel() - val html = HttpUtil.get(url) - val doc = Jsoup.parse(html) - val selects = doc.select("table")[1].select("tr")[2].select("td") - val seiyou = selects[0].text() - val name = selects[1].text() - val star = selects[2].text() - val sex = selects[3].text() - val level = selects[4].text() - val getWay = selects[5].text() - val image = doc.select("table")[0].select("tr")[0].select("img").attr("src") - a.seiyou = seiyou - a.name = name - a.star = star - a.sex = sex - a.level = level - a.getWay = getWay - a.image = image - return a - - - } - -} diff --git a/crawler/src/main/resources/config/application.properties b/crawler/src/main/resources/config/application.properties index 1a4a1da6..8d5bd3e7 100644 --- a/crawler/src/main/resources/config/application.properties +++ b/crawler/src/main/resources/config/application.properties @@ -1,6 +1,5 @@ logging.config=classpath:config/logback-dev.xml server.port=8080 -server.session.timeout=1800 server.max-http-header-size=20971520 #datasource @@ -8,7 +7,7 @@ spring.datasource.url=jdbc:mysql://ip/db?characterEncoding=utf8&useSSL=true # ?useUnicode=true&characterEncoding=UTF-8 spring.datasource.username=username spring.datasource.password=password -spring.datasource.driver-class-name=com.mysql.jdbc.Driver +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # \u914D\u7F6E\u8FD9\u4E2A\u503C\u5C31\u53EF\u4EE5\u683C\u5F0F\u5316\u65F6\u95F4 #spring.jackson.date-format=yyyy-MM-dd HH:mm:ss #spring.jackson.time-zone=GMT+8 diff --git a/freemarker/pom.xml b/freemarker/pom.xml index 856c083f..d866ff82 100644 --- a/freemarker/pom.xml +++ b/freemarker/pom.xml @@ -5,7 +5,7 @@ xiaomo info.xiaomo - 2017.2 + 2020.1 4.0.0 @@ -14,7 +14,7 @@ info.xiaomo core - 2017.2 + 2020.1 org.springframework.boot diff --git a/freemarker/src/main/java/info/xiaomo/freemarker/FreemarkerMain.java b/freemarker/src/main/java/info/xiaomo/freemarker/FreemarkerMain.java new file mode 100644 index 00000000..d1e9d83c --- /dev/null +++ b/freemarker/src/main/java/info/xiaomo/freemarker/FreemarkerMain.java @@ -0,0 +1,35 @@ +package info.xiaomo.freemarker; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/4/1 15:38 + * Copyright(©) 2015 by xiaomo. + **/ +@Configuration +@ComponentScan("info.xiaomo") +@EntityScan("info.xiaomo.*.model") +@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) +public class FreemarkerMain { + + public static void main(String[] args) throws Exception { + SpringApplication.run(FreemarkerMain.class, args); + } + + +} diff --git a/freemarker/src/main/java/info/xiaomo/freemarker/FreemarkerMain.kt b/freemarker/src/main/java/info/xiaomo/freemarker/FreemarkerMain.kt deleted file mode 100644 index 81a55e66..00000000 --- a/freemarker/src/main/java/info/xiaomo/freemarker/FreemarkerMain.kt +++ /dev/null @@ -1,34 +0,0 @@ -package info.xiaomo.freemarker - -import org.springframework.boot.SpringApplication -import org.springframework.boot.autoconfigure.EnableAutoConfiguration -import org.springframework.boot.autoconfigure.domain.EntityScan -import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration -import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration -import org.springframework.context.annotation.ComponentScan - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/4/1 15:38 - * Copyright(©) 2015 by xiaomo. - */ -@ComponentScan("info.xiaomo") -@EntityScan("info.xiaomo.*.model") -@EnableAutoConfiguration(exclude = arrayOf(DataSourceAutoConfiguration::class, HibernateJpaAutoConfiguration::class)) -class FreemarkerMain { - - @Throws(Exception::class) - fun main(args: Array) { - SpringApplication.run(FreemarkerMain::class.java, *args) - } - - -} diff --git a/freemarker/src/main/java/info/xiaomo/freemarker/controller/FreemarkerController.java b/freemarker/src/main/java/info/xiaomo/freemarker/controller/FreemarkerController.java new file mode 100644 index 00000000..78a3a90e --- /dev/null +++ b/freemarker/src/main/java/info/xiaomo/freemarker/controller/FreemarkerController.java @@ -0,0 +1,30 @@ +package info.xiaomo.freemarker.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.RequestMapping; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/11/16 10:19 + * Copyright(©) 2015 by xiaomo. + **/ + +@Controller +public class FreemarkerController { + + @RequestMapping("hello") + public String hello(ModelMap map) { + map.put("host", "使用freemarker!"); + return "index"; + } + +} diff --git a/freemarker/src/main/java/info/xiaomo/freemarker/controller/FreemarkerController.kt b/freemarker/src/main/java/info/xiaomo/freemarker/controller/FreemarkerController.kt deleted file mode 100644 index 50a3c148..00000000 --- a/freemarker/src/main/java/info/xiaomo/freemarker/controller/FreemarkerController.kt +++ /dev/null @@ -1,30 +0,0 @@ -package info.xiaomo.freemarker.controller - -import org.springframework.stereotype.Controller -import org.springframework.ui.ModelMap -import org.springframework.web.bind.annotation.RequestMapping - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/11/16 10:19 - * Copyright(©) 2015 by xiaomo. - */ - -@Controller -class FreemarkerController { - - @RequestMapping("hello") - fun hello(map: ModelMap): String { - map.put("host", "使用freemarker!") - return "index" - } - -} diff --git a/freemarker/src/main/resources/config/application.properties b/freemarker/src/main/resources/config/application.properties index 8ac071cd..ae76e147 100644 --- a/freemarker/src/main/resources/config/application.properties +++ b/freemarker/src/main/resources/config/application.properties @@ -1,6 +1,6 @@ logging.config=classpath:config/logback-dev.xml server.port=8080 -server.session.timeout=1800 + server.max-http-header-size=20971520 spring.jackson.date-format=yyyy-MM-dd HH:mm:ss diff --git a/freemarker/src/main/resources/config/banner-girl.txt b/freemarker/src/main/resources/config/banner-girl.txt index c826bcd3..5c648ca3 100644 --- a/freemarker/src/main/resources/config/banner-girl.txt +++ b/freemarker/src/main/resources/config/banner-girl.txt @@ -16,4 +16,4 @@ ...::: ::::::::::::' ``::. ```` ':. ':::::::::' ::::.. '.:::::' ':'````.. -:: Spring Boot :: (v1.5.8.RELEASE) \ No newline at end of file +:: Spring Boot :: (v2.0.0.RELEASE) \ No newline at end of file diff --git a/javase/pom.xml b/javase/pom.xml new file mode 100644 index 00000000..e3a3c480 --- /dev/null +++ b/javase/pom.xml @@ -0,0 +1,59 @@ + + + + xiaomo + info.xiaomo + 2020.1 + + 4.0.0 + + javase + + + + info.xiaomo + core + 2020.1 + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-devtools + true + + + io.springfox + springfox-swagger2 + + + io.springfox + springfox-swagger-ui + + + com.github.xiaoymin + swagger-bootstrap-ui + 1.5 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + + \ No newline at end of file diff --git a/javase/src/main/java/info/xiaomo/javase/QuestionMain.java b/javase/src/main/java/info/xiaomo/javase/QuestionMain.java new file mode 100644 index 00000000..7cda0422 --- /dev/null +++ b/javase/src/main/java/info/xiaomo/javase/QuestionMain.java @@ -0,0 +1,85 @@ +package info.xiaomo.javase; + +import io.swagger.annotations.ApiOperation; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import springfox.documentation.annotations.ApiIgnore; +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; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/4/1 15:38 + * Description: 后台管理启动器 + * Copyright(©) 2015 by xiaomo. + **/ +@Configuration +@EnableAutoConfiguration +@ComponentScan("info.xiaomo") +@EntityScan("info.xiaomo.*.model") +@EnableJpaRepositories("info.xiaomo.*.dao") +@EnableSwagger2 +@RestController +public class QuestionMain implements WebMvcConfigurer { + + public static void main(String[] args) { + SpringApplication.run(QuestionMain.class, args); + } + + /** + * 接口 + * + * @return 接口 + */ + @RequestMapping(value = "/", method = RequestMethod.GET) + @ApiIgnore() + @ApiOperation(value = "重定向到api首页") + public ModelAndView api() { + return new ModelAndView("redirect:/swagger-ui.html"); + } + + + @Bean + public Docket createRestApi() { + return new Docket(DocumentationType.SWAGGER_2) + .apiInfo(apiInfo()) + .select() + .apis(RequestHandlerSelectors.basePackage("info.xiaomo.javase")) + .paths(PathSelectors.any()) + .build(); + } + + private ApiInfo apiInfo() { + return new ApiInfoBuilder() + .title("Spring Boot中使用Swagger2构建RESTful APIs") + .description("java se题库api") + .termsOfServiceUrl("https://question.xiaomo.info/") + .contact("小莫") + .version("1.0") + .build(); + } + +} diff --git a/javase/src/main/java/info/xiaomo/javase/controller/QuestionController.java b/javase/src/main/java/info/xiaomo/javase/controller/QuestionController.java new file mode 100644 index 00000000..d76c4876 --- /dev/null +++ b/javase/src/main/java/info/xiaomo/javase/controller/QuestionController.java @@ -0,0 +1,72 @@ +package info.xiaomo.javase.controller; + +import info.xiaomo.core.base.Result; +import info.xiaomo.core.constant.CodeConst; +import info.xiaomo.javase.model.QuestionModel; +import info.xiaomo.javase.service.QuestionService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.*; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + * + * @author : xiaomo + * github : https://github.com/houko + * email : xiaomo@xiaomo.info + * QQ : 83387856 + * Date : 2017/11/20 19:00 + * desc : + * Copyright(©) 2017 by xiaomo. + */ +@RestController +@RequestMapping("/question") +@Api(value = "question", description = "question") +public class QuestionController { + + + private final QuestionService service; + + @Autowired + public QuestionController(QuestionService service) { + this.service = service; + } + + /** + * 根据id 查找用户 + * + * @param id id + * @return result + */ + @ApiOperation(value = "查找问题", notes = "查找问题", httpMethod = "GET") + @RequestMapping(value = "findById/{id}", method = RequestMethod.GET) + @ApiImplicitParams({ + @ApiImplicitParam(name = "id", value = "唯一id", required = true, dataType = "Long", paramType = "path"), + }) + public Result findUserById(@PathVariable("id") Long id) { + QuestionModel questionModel = service.findById(id); + if (questionModel == null) { + return new Result<>(CodeConst.NOT_FOUNT.getResultCode(), CodeConst.NOT_FOUNT.getMessage()); + } + return new Result<>(questionModel); + } + + /** + * 根据id 查找用户 + * + * @return result + */ + @ApiOperation(value = "添加", notes = "添加", httpMethod = "POST") + @RequestMapping(value = "findById/{id}", method = RequestMethod.POST) + public Result addQuestion(@RequestBody QuestionModel questionModel) { + boolean add = service.add(questionModel); + return new Result<>(add); + } + +} diff --git a/javase/src/main/java/info/xiaomo/javase/dao/QuestionDao.java b/javase/src/main/java/info/xiaomo/javase/dao/QuestionDao.java new file mode 100644 index 00000000..489e8c07 --- /dev/null +++ b/javase/src/main/java/info/xiaomo/javase/dao/QuestionDao.java @@ -0,0 +1,22 @@ +package info.xiaomo.javase.dao; + +import info.xiaomo.javase.model.QuestionModel; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + * + * @author : xiaomo + * github : https://github.com/houko + * email : xiaomo@xiaomo.info + * QQ : 83387856 + * Date : 2017/11/20 19:00 + * desc : + * Copyright(©) 2017 by xiaomo. + */ +@Repository +public interface QuestionDao extends JpaRepository { +} diff --git a/javase/src/main/java/info/xiaomo/javase/model/QuestionModel.java b/javase/src/main/java/info/xiaomo/javase/model/QuestionModel.java new file mode 100644 index 00000000..39954ae5 --- /dev/null +++ b/javase/src/main/java/info/xiaomo/javase/model/QuestionModel.java @@ -0,0 +1,41 @@ +package info.xiaomo.javase.model; + +import info.xiaomo.core.base.BaseModel; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import javax.persistence.Entity; +import javax.persistence.Table; +import java.io.Serializable; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + * + * @author : xiaomo + * github : https://github.com/houko + * email : xiaomo@xiaomo.info + * QQ : 83387856 + * Date : 2017/11/20 18:57 + * desc : + * Copyright(©) 2017 by xiaomo. + */ +@EqualsAndHashCode(callSuper = true) +@Entity +@Table(name = "question") +@Data +public class QuestionModel extends BaseModel implements Serializable { + /** + * 问题 + */ + private String question; +// /** +// * 选项 +// */ +// private List choice; +// /** +// * 答案 +// */ +// private List answer; +} diff --git a/javase/src/main/java/info/xiaomo/javase/service/QuestionService.java b/javase/src/main/java/info/xiaomo/javase/service/QuestionService.java new file mode 100644 index 00000000..f83da182 --- /dev/null +++ b/javase/src/main/java/info/xiaomo/javase/service/QuestionService.java @@ -0,0 +1,35 @@ +package info.xiaomo.javase.service; + +import info.xiaomo.javase.model.QuestionModel; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + * + * @author : xiaomo + * github : https://github.com/houko + * email : xiaomo@xiaomo.info + * QQ : 83387856 + * Date : 2017/11/20 19:00 + * desc : + * Copyright(©) 2017 by xiaomo. + */ +public interface QuestionService { + + /** + * 根据id查找 + * + * @param id id + * @return QuestionModel + */ + QuestionModel findById(Long id); + + /** + * 添加 + * + * @param questionModel questionModel + * @return + */ + boolean add(QuestionModel questionModel); +} diff --git a/javase/src/main/java/info/xiaomo/javase/service/impl/QuestionServiceImpl.java b/javase/src/main/java/info/xiaomo/javase/service/impl/QuestionServiceImpl.java new file mode 100644 index 00000000..246a8c07 --- /dev/null +++ b/javase/src/main/java/info/xiaomo/javase/service/impl/QuestionServiceImpl.java @@ -0,0 +1,46 @@ +package info.xiaomo.javase.service.impl; + +import info.xiaomo.javase.dao.QuestionDao; +import info.xiaomo.javase.model.QuestionModel; +import info.xiaomo.javase.service.QuestionService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.Optional; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + * + * @author : xiaomo + * github : https://github.com/houko + * email : xiaomo@xiaomo.info + * QQ : 83387856 + * Date : 2017/11/20 19:01 + * desc : + * Copyright(©) 2017 by xiaomo. + */ +@Service +public class QuestionServiceImpl implements QuestionService { + + private final QuestionDao questionDao; + + @Autowired + public QuestionServiceImpl(QuestionDao questionDao) { + this.questionDao = questionDao; + } + + + @Override + public QuestionModel findById(Long id) { + Optional optionalModel = questionDao.findById(id); + return optionalModel.orElse(null); + } + + @Override + public boolean add(QuestionModel questionModel) { + questionDao.save(questionModel); + return true; + } +} diff --git a/javase/src/main/resources/config/application.properties b/javase/src/main/resources/config/application.properties new file mode 100644 index 00000000..34b74282 --- /dev/null +++ b/javase/src/main/resources/config/application.properties @@ -0,0 +1,33 @@ +logging.config=classpath:config/logback-dev.xml +server.port=8080 +server.max-http-header-size=20971520 +#datasource +spring.datasource.url=jdbc:mysql://ip/db?characterEncoding=utf8&useSSL=true +# ?useUnicode=true&characterEncoding=UTF-8 +spring.datasource.username=xiaomo +spring.datasource.password=password +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver +# \u914D\u7F6E\u8FD9\u4E2A\u503C\u5C31\u53EF\u4EE5\u683C\u5F0F\u5316\u65F6\u95F4 +#spring.jackson.date-format=yyyy-MM-dd HH:mm:ss +#spring.jackson.time-zone=GMT+8 +#jpa +spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect +spring.jpa.hibernate.ddl-auto=update +spring.jpa.show-sql=true +spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl +# redis +# Redis\u6570\u636E\u5E93\u7D22\u5F15\uFF08\u9ED8\u8BA4\u4E3A0\uFF09 +spring.redis.database=0 +spring.redis.host=ip +spring.redis.port=6379 +spring.redis.password= +# \u8FDE\u63A5\u6C60\u6700\u5927\u8FDE\u63A5\u6570\uFF08\u4F7F\u7528\u8D1F\u503C\u8868\u793A\u6CA1\u6709\u9650\u5236\uFF09 +#spring.redis.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 +#spring.redis.pool.max-wait=-1 +## \u8FDE\u63A5\u6C60\u4E2D\u7684\u6700\u5927\u7A7A\u95F2\u8FDE\u63A5 +#spring.redis.pool.max-idle=8 +## \u8FDE\u63A5\u6C60\u4E2D\u7684\u6700\u5C0F\u7A7A\u95F2\u8FDE\u63A5 +#spring.redis.pool.min-idle=0 +# \u8FDE\u63A5\u8D85\u65F6\u65F6\u95F4\uFF08\u6BEB\u79D2\uFF09 +spring.redis.timeout=0 diff --git a/javase/src/main/resources/config/banner-girl.txt b/javase/src/main/resources/config/banner-girl.txt new file mode 100644 index 00000000..934b7d76 --- /dev/null +++ b/javase/src/main/resources/config/banner-girl.txt @@ -0,0 +1,20 @@ + .::::. + .::::::::. + ::::::::::: + ..:::::::::::' + '::::::::::::' + .:::::::::: + '::::::::::::::.. + ..:::::::::::::. + ..:::::::::::::::. + ``::::::::::::::::::: + ::::``::::::::::::' .:::. + ::::' ':::::' .::::::::. + .::::' :::: .:::::::'::::. + .:::' ::::: .:::::::::' ':::::. + .::' :::::.:::::::::' ':::::. + .::' ::::::::::::::' ``::::. + ...::: ::::::::::::' ``::. + ```` ':. ':::::::::' ::::.. + '.:::::' ':'````.. +:: Spring Boot :: (v2.0.0.RELEASE) \ No newline at end of file diff --git a/javase/src/main/resources/config/logback-dev.xml b/javase/src/main/resources/config/logback-dev.xml new file mode 100644 index 00000000..39e7cc65 --- /dev/null +++ b/javase/src/main/resources/config/logback-dev.xml @@ -0,0 +1,17 @@ + + + + + + + [%d{yyyy-MM-dd HH:mm:ss} [%thread] %highlight(%-5level) %cyan(%logger{15}) - %highlight(%msg) %n + + + + + + + + + + \ No newline at end of file diff --git a/mongodb/pom.xml b/mongodb/pom.xml index 5a17eca2..f3ade783 100644 --- a/mongodb/pom.xml +++ b/mongodb/pom.xml @@ -5,7 +5,7 @@ xiaomo info.xiaomo - 2017.2 + 2020.1 4.0.0 @@ -14,7 +14,7 @@ info.xiaomo core - 2017.2 + 2020.1 org.springframework.boot diff --git a/mongodb/src/main/java/info/xiaomo/mongodb/MongodbMain.java b/mongodb/src/main/java/info/xiaomo/mongodb/MongodbMain.java new file mode 100644 index 00000000..0f6c1c2e --- /dev/null +++ b/mongodb/src/main/java/info/xiaomo/mongodb/MongodbMain.java @@ -0,0 +1,77 @@ +package info.xiaomo.mongodb; + + +import io.swagger.annotations.ApiOperation; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.ModelAndView; +import springfox.documentation.annotations.ApiIgnore; +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; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/4/1 15:38 + * Description: RabbitMq启动器 + * Copyright(©) 2015 by xiaomo. + **/ +@Configuration +@ComponentScan("info.xiaomo") +@EntityScan("info.xiaomo.*.model") +@RestController +@EnableSwagger2 +@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) +public class MongodbMain { + public static void main(String[] args) throws Exception { + SpringApplication.run(MongodbMain.class, args); + } + + @RequestMapping(value = "/", method = RequestMethod.GET) + @ApiIgnore() + @ApiOperation(value = "重定向到api首页") + public ModelAndView index() { + return new ModelAndView("redirect:/swagger-ui.html"); + } + + @Bean + public Docket createRestApi() { + return new Docket(DocumentationType.SWAGGER_2) + .apiInfo(apiInfo()) + .select() + .apis(RequestHandlerSelectors.basePackage("info.xiaomo.mongodb")) + .paths(PathSelectors.any()) + .build(); + } + + private ApiInfo apiInfo() { + return new ApiInfoBuilder() + .title("Spring Boot中使用Swagger2构建RESTful APIs") + .description("使用mongodb构建api接口") + .termsOfServiceUrl("https://xiaomo.info/") + .contact("小莫") + .version("1.0") + .build(); + } +} diff --git a/mongodb/src/main/java/info/xiaomo/mongodb/MongodbMain.kt b/mongodb/src/main/java/info/xiaomo/mongodb/MongodbMain.kt deleted file mode 100644 index 3d77b8da..00000000 --- a/mongodb/src/main/java/info/xiaomo/mongodb/MongodbMain.kt +++ /dev/null @@ -1,80 +0,0 @@ -package info.xiaomo.mongodb - - -import io.swagger.annotations.ApiOperation -import org.springframework.boot.SpringApplication -import org.springframework.boot.autoconfigure.EnableAutoConfiguration -import org.springframework.boot.autoconfigure.domain.EntityScan -import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration -import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration -import org.springframework.context.annotation.Bean -import org.springframework.context.annotation.ComponentScan -import org.springframework.web.bind.annotation.RequestMapping -import org.springframework.web.bind.annotation.RequestMethod -import org.springframework.web.bind.annotation.RestController -import org.springframework.web.servlet.ModelAndView -import springfox.documentation.annotations.ApiIgnore -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 - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/4/1 15:38 - * Description: RabbitMq启动器 - * Copyright(©) 2015 by xiaomo. - */ -@ComponentScan("info.xiaomo") -@EntityScan("info.xiaomo.*.model") -@RestController -@EnableSwagger2 -@EnableAutoConfiguration(exclude = arrayOf(DataSourceAutoConfiguration::class, HibernateJpaAutoConfiguration::class)) -class MongodbMain { - - @RequestMapping(value = "/", method = arrayOf(RequestMethod.GET)) - @ApiIgnore - @ApiOperation(value = "重定向到api首页") - fun index(): ModelAndView { - return ModelAndView("redirect:/swagger-ui.html") - } - - @Bean - fun createRestApi(): Docket { - return Docket(DocumentationType.SWAGGER_2) - .apiInfo(apiInfo()) - .select() - .apis(RequestHandlerSelectors.basePackage("info.xiaomo.mongodb")) - .paths(PathSelectors.any()) - .build() - } - - private fun apiInfo(): ApiInfo { - return ApiInfoBuilder() - .title("Spring Boot中使用Swagger2构建RESTful APIs") - .description("使用mongodb构建api接口") - .termsOfServiceUrl("https://xiaomo.info/") - .contact("小莫") - .version("1.0") - .build() - } - - companion object { - @Throws(Exception::class) - @JvmStatic - fun main(args: Array) { - SpringApplication.run(MongodbMain::class.java, *args) - } - } -} diff --git a/mongodb/src/main/java/info/xiaomo/mongodb/controller/MongoUserController.java b/mongodb/src/main/java/info/xiaomo/mongodb/controller/MongoUserController.java new file mode 100644 index 00000000..a7056409 --- /dev/null +++ b/mongodb/src/main/java/info/xiaomo/mongodb/controller/MongoUserController.java @@ -0,0 +1,60 @@ +package info.xiaomo.mongodb.controller; + +import info.xiaomo.core.base.Result; +import info.xiaomo.core.constant.CodeConst; +import info.xiaomo.mongodb.model.MongoUser; +import info.xiaomo.mongodb.service.MongoUserService; +import io.swagger.annotations.Api; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/11/15 15:49 + * Copyright(©) 2015 by xiaomo. + **/ + +@RestController +@RequestMapping("mongodb") +@Api("mongodb測試") +public class MongoUserController { + + private final MongoUserService service; + + @Autowired + public MongoUserController(MongoUserService service) { + this.service = service; + } + + @RequestMapping(value = "get/{id}", method = RequestMethod.GET) + public Result get(@PathVariable("id") Long id) { + MongoUser mongoUser = service.findById(id); + return new Result<>(mongoUser); + } + + @RequestMapping(value = "findAll", method = RequestMethod.GET) + public Result findAll() { + return new Result<>(service.findAll()); + } + + + @RequestMapping(value = "add", method = RequestMethod.POST) + public Result add(@RequestBody MongoUser user) { + return new Result<>(service.add(user)); + } + + @RequestMapping(value = "delete/{id}", method = RequestMethod.GET) + public Result delete(@PathVariable("id") Long id) { + service.delete(id); + return new Result<>(CodeConst.SUCCESS.getResultCode(), CodeConst.SUCCESS.getMessage()); + } + +} diff --git a/mongodb/src/main/java/info/xiaomo/mongodb/controller/MongoUserController.kt b/mongodb/src/main/java/info/xiaomo/mongodb/controller/MongoUserController.kt deleted file mode 100644 index c2160b5d..00000000 --- a/mongodb/src/main/java/info/xiaomo/mongodb/controller/MongoUserController.kt +++ /dev/null @@ -1,54 +0,0 @@ -package info.xiaomo.mongodb.controller - -import info.xiaomo.core.base.Result -import info.xiaomo.core.constant.CodeConst -import info.xiaomo.mongodb.model.MongoUser -import info.xiaomo.mongodb.service.MongoUserService -import io.swagger.annotations.Api -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.web.bind.annotation.* - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/11/15 15:49 - * Copyright(©) 2015 by xiaomo. - */ - -@RestController -@RequestMapping("mongodb") -@Api("mongodb測試") -class MongoUserController @Autowired -constructor(private val service: MongoUserService) { - - @RequestMapping(value = "get/{id}", method = arrayOf(RequestMethod.GET)) - operator fun get(@PathVariable("id") id: Long?): Result<*> { - val mongoUser = service.findById(id) - return Result(mongoUser) - } - - @RequestMapping(value = "findAll", method = arrayOf(RequestMethod.GET)) - fun findAll(): Result<*> { - return Result(service.findAll()) - } - - - @RequestMapping(value = "add", method = arrayOf(RequestMethod.POST)) - fun add(@RequestBody user: MongoUser): Result<*> { - return Result(service.add(user)) - } - - @RequestMapping(value = "delete/{id}", method = arrayOf(RequestMethod.GET)) - fun delete(@PathVariable("id") id: Long?): Result<*> { - service.delete(id) - return Result(CodeConst.SUCCESS.resultCode, CodeConst.SUCCESS.message!!) - } - -} diff --git a/mongodb/src/main/java/info/xiaomo/mongodb/dao/MongoUserDao.kt b/mongodb/src/main/java/info/xiaomo/mongodb/dao/MongoUserDao.java similarity index 61% rename from mongodb/src/main/java/info/xiaomo/mongodb/dao/MongoUserDao.kt rename to mongodb/src/main/java/info/xiaomo/mongodb/dao/MongoUserDao.java index 65bb7426..d86d4de0 100644 --- a/mongodb/src/main/java/info/xiaomo/mongodb/dao/MongoUserDao.kt +++ b/mongodb/src/main/java/info/xiaomo/mongodb/dao/MongoUserDao.java @@ -1,27 +1,26 @@ -package info.xiaomo.mongodb.dao +package info.xiaomo.mongodb.dao; -import info.xiaomo.mongodb.model.MongoUser -import org.springframework.data.mongodb.repository.MongoRepository -import org.springframework.stereotype.Repository +import info.xiaomo.mongodb.model.MongoUser; +import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.stereotype.Repository; /** * 把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. + * * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info - * - * + *

* Date: 2016/11/15 15:42 * Description: 用户实体类 * Copyright(©) 2015 by xiaomo. - */ + **/ @Repository -interface MongoUserDao : MongoRepository { +public interface MongoUserDao extends MongoRepository { /** * 根据字字查用户 @@ -29,6 +28,6 @@ interface MongoUserDao : MongoRepository { * @param userName * @return */ - fun findByUserName(userName: String): MongoUser + MongoUser findByUserName(String userName); } diff --git a/mongodb/src/main/java/info/xiaomo/mongodb/model/MongoUser.kt b/mongodb/src/main/java/info/xiaomo/mongodb/model/MongoUser.java similarity index 53% rename from mongodb/src/main/java/info/xiaomo/mongodb/model/MongoUser.kt rename to mongodb/src/main/java/info/xiaomo/mongodb/model/MongoUser.java index 05a99d62..12095176 100644 --- a/mongodb/src/main/java/info/xiaomo/mongodb/model/MongoUser.kt +++ b/mongodb/src/main/java/info/xiaomo/mongodb/model/MongoUser.java @@ -1,56 +1,64 @@ -package info.xiaomo.mongodb.model +package info.xiaomo.mongodb.model; -import io.swagger.annotations.ApiModelProperty -import org.springframework.data.annotation.Id +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.ToString; +import org.springframework.data.annotation.Id; /** * 把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. + * * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info - * + *

* Date: 2016/11/15 15:39 * Description: 用户实体类 * Copyright(©) 2015 by xiaomo. - */ + **/ -class MongoUser { +@Data +@ToString(callSuper = false) +@NoArgsConstructor +@AllArgsConstructor +public class MongoUser { @Id - private val id: Int = 0 + private int id; @ApiModelProperty(value = "登录用户") - private val email: String? = null + private String email; @ApiModelProperty(value = "昵称") - private val userName: String? = null + private String userName; @ApiModelProperty(value = "密码") - private val password: String? = null + private String password; @ApiModelProperty(value = "盐值") - private val salt: String? = null + private String salt; @ApiModelProperty(value = "激活码") - private val validateCode: String? = null + private String validateCode; @ApiModelProperty(value = "性别:1男2女0保密") - private val gender = 0 + private int gender = 0; @ApiModelProperty(value = "电话") - private val phone = 0L + private Long phone = 0L; @ApiModelProperty(value = "图片地址") - private val imgUrl = "" + private String imgUrl = ""; @ApiModelProperty(value = "地址") - private val address = "" + private String address = ""; @ApiModelProperty(value = "注册时间(时间戳)") - private val registerTime = 0L + private Long registerTime = 0L; } diff --git a/mongodb/src/main/java/info/xiaomo/mongodb/service/MongoUserService.kt b/mongodb/src/main/java/info/xiaomo/mongodb/service/MongoUserService.java similarity index 63% rename from mongodb/src/main/java/info/xiaomo/mongodb/service/MongoUserService.kt rename to mongodb/src/main/java/info/xiaomo/mongodb/service/MongoUserService.java index 77479448..1eccb9f3 100644 --- a/mongodb/src/main/java/info/xiaomo/mongodb/service/MongoUserService.kt +++ b/mongodb/src/main/java/info/xiaomo/mongodb/service/MongoUserService.java @@ -1,31 +1,32 @@ -package info.xiaomo.mongodb.service +package info.xiaomo.mongodb.service; -import info.xiaomo.mongodb.model.MongoUser +import info.xiaomo.mongodb.model.MongoUser; + +import java.util.List; /** * 把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. + * * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info - * - * + *

* Date: 2016/11/15 15:45 * Copyright(©) 2015 by xiaomo. - */ + **/ -interface MongoUserService { +public interface MongoUserService { /** * 查所有 * * @return */ - fun findAll(): List + List findAll(); /** * 根据id查 @@ -33,7 +34,7 @@ fun findAll(): List * @param id * @return */ - fun findById(id: Long?): MongoUser + MongoUser findById(Long id); /** * 根据名字查 @@ -41,7 +42,7 @@ fun findById(id: Long?): MongoUser * @param userName * @return */ - fun findByName(userName: String): MongoUser + MongoUser findByName(String userName); /** * 添加 @@ -49,14 +50,14 @@ fun findByName(userName: String): MongoUser * @param mongoUser * @return */ - fun add(mongoUser: MongoUser): MongoUser + MongoUser add(MongoUser mongoUser); /** * 删除 * * @param id */ - fun delete(id: Long?) + void delete(Long id); /** * 更新 @@ -64,6 +65,6 @@ fun delete(id: Long?) * @param mongoUser * @return */ - fun update(mongoUser: MongoUser): MongoUser + MongoUser update(MongoUser mongoUser); } diff --git a/mongodb/src/main/java/info/xiaomo/mongodb/service/impl/MongoUserServiceImpl.java b/mongodb/src/main/java/info/xiaomo/mongodb/service/impl/MongoUserServiceImpl.java new file mode 100644 index 00000000..1827c1a3 --- /dev/null +++ b/mongodb/src/main/java/info/xiaomo/mongodb/service/impl/MongoUserServiceImpl.java @@ -0,0 +1,69 @@ +package info.xiaomo.mongodb.service.impl; + +import info.xiaomo.mongodb.dao.MongoUserDao; +import info.xiaomo.mongodb.model.MongoUser; +import info.xiaomo.mongodb.service.MongoUserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Optional; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/11/15 15:45 + * Copyright(©) 2015 by xiaomo. + **/ + +@Service +public class MongoUserServiceImpl implements MongoUserService { + private final MongoUserDao dao; + + @Autowired + public MongoUserServiceImpl(MongoUserDao dao) { + this.dao = dao; + } + + @Override + public List findAll() { + return dao.findAll(); + } + + @Override + public MongoUser findById(Long id) { + Optional optionalUser = dao.findById(id); + return optionalUser.orElse(null); + } + + @Override + public MongoUser findByName(String userName) { + return dao.findByUserName(userName); + } + + @Override + public MongoUser add(MongoUser mongoUser) { + return dao.save(mongoUser); + } + + @Override + public void delete(Long id) { + Optional optional = dao.findById(id); + if (!optional.isPresent()) { + return; + } + dao.delete(optional.get()); + } + + @Override + public MongoUser update(MongoUser mongoUser) { + return dao.save(mongoUser); + } +} diff --git a/mongodb/src/main/java/info/xiaomo/mongodb/service/impl/MongoUserServiceImpl.kt b/mongodb/src/main/java/info/xiaomo/mongodb/service/impl/MongoUserServiceImpl.kt deleted file mode 100644 index 9319c69c..00000000 --- a/mongodb/src/main/java/info/xiaomo/mongodb/service/impl/MongoUserServiceImpl.kt +++ /dev/null @@ -1,50 +0,0 @@ -package info.xiaomo.mongodb.service.impl - -import info.xiaomo.mongodb.dao.MongoUserDao -import info.xiaomo.mongodb.model.MongoUser -import info.xiaomo.mongodb.service.MongoUserService -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.stereotype.Service - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/11/15 15:45 - * Copyright(©) 2015 by xiaomo. - */ - -@Service -class MongoUserServiceImpl @Autowired -constructor(private val dao: MongoUserDao) : MongoUserService { - - override fun findAll(): List { - return dao.findAll() - } - - override fun findById(id: Long?): MongoUser { - return dao.findOne(id) - } - - override fun findByName(userName: String): MongoUser { - return dao.findByUserName(userName) - } - - override fun add(mongoUser: MongoUser): MongoUser { - return dao.save(mongoUser) - } - - override fun delete(id: Long?) { - dao.delete(id) - } - - override fun update(mongoUser: MongoUser): MongoUser { - return dao.save(mongoUser) - } -} diff --git a/mongodb/src/main/resources/config/application.properties b/mongodb/src/main/resources/config/application.properties index 8676bc6c..192ebb13 100644 --- a/mongodb/src/main/resources/config/application.properties +++ b/mongodb/src/main/resources/config/application.properties @@ -1,6 +1,6 @@ logging.config=classpath:config/logback-dev.xml server.port=8080 -server.session.timeout=1800 + server.max-http-header-size=20971520 #mongodb diff --git a/multipleSource/pom.xml b/multipleSource/pom.xml index dced9ad7..52e3b92d 100644 --- a/multipleSource/pom.xml +++ b/multipleSource/pom.xml @@ -5,7 +5,7 @@ xiaomo info.xiaomo - 2017.2 + 2020.1 4.0.0 @@ -15,7 +15,7 @@ info.xiaomo core - 2017.2 + 2020.1 org.springframework.boot diff --git a/multipleSource/src/main/java/info/xiaomo/multiplesource/MultipleSourceMain.java b/multipleSource/src/main/java/info/xiaomo/multiplesource/MultipleSourceMain.java index 90bda5b6..bcf2eb5e 100644 --- a/multipleSource/src/main/java/info/xiaomo/multiplesource/MultipleSourceMain.java +++ b/multipleSource/src/main/java/info/xiaomo/multiplesource/MultipleSourceMain.java @@ -3,8 +3,8 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; import org.springframework.jdbc.core.JdbcTemplate; @@ -15,10 +15,10 @@ * 把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. + * * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info * Date: 2016/11/16 10:34 diff --git a/multipleSource/src/main/java/info/xiaomo/multiplesource/controller/MultipleSourceController.java b/multipleSource/src/main/java/info/xiaomo/multiplesource/controller/MultipleSourceController.java new file mode 100644 index 00000000..d2b05caf --- /dev/null +++ b/multipleSource/src/main/java/info/xiaomo/multiplesource/controller/MultipleSourceController.java @@ -0,0 +1,51 @@ +package info.xiaomo.multiplesource.controller; + +import info.xiaomo.core.base.Result; +import info.xiaomo.multiplesource.sql.Sql; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/11/16 10:45 + * Description: 用户实体类 + * Copyright(©) 2015 by xiaomo. + **/ + +@RestController +public class MultipleSourceController { + private final JdbcTemplate jdbcTemplate1; + + private final JdbcTemplate jdbcTemplate2; + + @Autowired + public MultipleSourceController(@Qualifier("primaryJdbcTemplate") JdbcTemplate jdbcTemplate1, @Qualifier("secondaryJdbcTemplate") JdbcTemplate jdbcTemplate2) { + this.jdbcTemplate1 = jdbcTemplate1; + this.jdbcTemplate2 = jdbcTemplate2; + this.jdbcTemplate1.update(Sql.dropUser); + this.jdbcTemplate2.update(Sql.dropUser); + } + + + @RequestMapping("/") + public Result index() { + // 往第一个数据源中插入两条数据 + jdbcTemplate1.update(Sql.addUser, "xiaomo", 20); + jdbcTemplate2.update(Sql.addUser, "xiaoming", 30); + + int count1 = jdbcTemplate1.queryForObject(Sql.selectUser, Integer.class); + int count2 = jdbcTemplate2.queryForObject(Sql.selectUser, Integer.class); + return new Result<>(new Object[]{count1, count2}); + } +} diff --git a/multipleSource/src/main/java/info/xiaomo/multiplesource/controller/MultipleSourceController.kt b/multipleSource/src/main/java/info/xiaomo/multiplesource/controller/MultipleSourceController.kt deleted file mode 100644 index 61fe4907..00000000 --- a/multipleSource/src/main/java/info/xiaomo/multiplesource/controller/MultipleSourceController.kt +++ /dev/null @@ -1,46 +0,0 @@ -package info.xiaomo.multiplesource.controller - -import info.xiaomo.core.base.Result -import info.xiaomo.multiplesource.sql.Sql -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.beans.factory.annotation.Qualifier -import org.springframework.jdbc.core.JdbcTemplate -import org.springframework.web.bind.annotation.RequestMapping -import org.springframework.web.bind.annotation.RestController - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/11/16 10:45 - * Description: 用户实体类 - * Copyright(©) 2015 by xiaomo. - */ - -@RestController -class MultipleSourceController @Autowired -constructor(@param:Qualifier("primaryJdbcTemplate") private val jdbcTemplate1: JdbcTemplate, @param:Qualifier("secondaryJdbcTemplate") private val jdbcTemplate2: JdbcTemplate) { - - init { - this.jdbcTemplate1.update(Sql.dropUser) - this.jdbcTemplate2.update(Sql.dropUser) - } - - - @RequestMapping("/") - fun index(): Result<*> { - // 往第一个数据源中插入两条数据 - jdbcTemplate1.update(Sql.addUser, "xiaomo", 20) - jdbcTemplate2.update(Sql.addUser, "xiaoming", 30) - - val count1 = jdbcTemplate1.queryForObject(Sql.selectUser, Int::class.java) - val count2 = jdbcTemplate2.queryForObject(Sql.selectUser, Int::class.java) - return Result(arrayOf(count1, count2)) - } -} diff --git a/multipleSource/src/main/java/info/xiaomo/multiplesource/domain/User.java b/multipleSource/src/main/java/info/xiaomo/multiplesource/domain/User.java new file mode 100644 index 00000000..75804e7f --- /dev/null +++ b/multipleSource/src/main/java/info/xiaomo/multiplesource/domain/User.java @@ -0,0 +1,33 @@ +package info.xiaomo.multiplesource.domain; + + +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.ToString; + +/** + * @author : xiaomo + */ +@Data +@ToString(callSuper = false) +@NoArgsConstructor +public class User { + + private Long id; + + private String name; + + private Integer age; + + public User(Long id, String name, Integer age) { + this.id = id; + this.name = name; + this.age = age; + } + + public User(String name, Integer age) { + this.name = name; + this.age = age; + } + +} diff --git a/multipleSource/src/main/java/info/xiaomo/multiplesource/domain/User.kt b/multipleSource/src/main/java/info/xiaomo/multiplesource/domain/User.kt deleted file mode 100644 index cdbbcfc0..00000000 --- a/multipleSource/src/main/java/info/xiaomo/multiplesource/domain/User.kt +++ /dev/null @@ -1,27 +0,0 @@ -package info.xiaomo.multiplesource.domain - - -/** - * @author : xiaomo - */ - -class User { - - private var id: Long? = null - - private var name: String? = null - - private var age: Int? = null - - constructor(id: Long?, name: String, age: Int?) { - this.id = id - this.name = name - this.age = age - } - - constructor(name: String, age: Int?) { - this.name = name - this.age = age - } - -} diff --git a/multipleSource/src/main/java/info/xiaomo/multiplesource/sql/Sql.kt b/multipleSource/src/main/java/info/xiaomo/multiplesource/sql/Sql.java similarity index 52% rename from multipleSource/src/main/java/info/xiaomo/multiplesource/sql/Sql.kt rename to multipleSource/src/main/java/info/xiaomo/multiplesource/sql/Sql.java index 8ff7d4e4..1185d127 100644 --- a/multipleSource/src/main/java/info/xiaomo/multiplesource/sql/Sql.kt +++ b/multipleSource/src/main/java/info/xiaomo/multiplesource/sql/Sql.java @@ -1,24 +1,23 @@ -package info.xiaomo.multiplesource.sql +package info.xiaomo.multiplesource.sql; /** * 把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. * * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info - * + *

* Date: 2016/11/16 11:29 * Description: 用户实体类 * Copyright(©) 2015 by xiaomo. - */ + **/ -object Sql { +public class Sql { - var dropUser = "DELETE FROM user" - var addUser = "insert into user(name,age) values(?, ?)" - var selectUser = "select count(1) from user" + public static String dropUser = "DELETE FROM user"; + public static String addUser = "insert into user(name,age) values(?, ?)"; + public static String selectUser = "select count(1) from user"; } diff --git a/multipleSource/src/main/resources/config/application.properties b/multipleSource/src/main/resources/config/application.properties index 1f0a93a5..f1910361 100644 --- a/multipleSource/src/main/resources/config/application.properties +++ b/multipleSource/src/main/resources/config/application.properties @@ -1,6 +1,6 @@ logging.config=classpath:config/logback-dev.xml server.port=8080 -server.session.timeout=1800 + server.max-http-header-size=20971520 spring.jackson.date-format=yyyy-MM-dd HH:mm:ss @@ -10,13 +10,13 @@ spring.jackson.time-zone=GMT+8 spring.datasource.primary.url=jdbc:mysql://ip:3306/test1?characterEncoding=utf8&useSSL=true spring.datasource.primary.username=\u4F60\u7684\u5E10\u53F7 spring.datasource.primary.password=\u4F60\u7684\u5BC6\u7801 -spring.datasource.primary.driver-class-name=com.mysql.jdbc.Driver +spring.datasource.primary.driver-class-name=com.mysql.cj.jdbc.Driver #database2 spring.datasource.secondary.url=jdbc:mysql://ip:3306/test2?characterEncoding=utf8&useSSL=true spring.datasource.secondary.username=\u5E10\u53F7 spring.datasource.secondary.password=\u4F60\u7684\u5BC6\u7801 -spring.datasource.secondary.driver-class-name=com.mysql.jdbc.Driver +spring.datasource.secondary.driver-class-name=com.mysql.cj.jdbc.Driver diff --git a/multipleSource/src/main/resources/config/banner-girl.txt b/multipleSource/src/main/resources/config/banner-girl.txt index c826bcd3..5c648ca3 100644 --- a/multipleSource/src/main/resources/config/banner-girl.txt +++ b/multipleSource/src/main/resources/config/banner-girl.txt @@ -16,4 +16,4 @@ ...::: ::::::::::::' ``::. ```` ':. ':::::::::' ::::.. '.:::::' ':'````.. -:: Spring Boot :: (v1.5.8.RELEASE) \ No newline at end of file +:: Spring Boot :: (v2.0.0.RELEASE) \ No newline at end of file diff --git a/mybatis/pom.xml b/mybatis/pom.xml index 1f021924..aca5b38b 100644 --- a/mybatis/pom.xml +++ b/mybatis/pom.xml @@ -5,7 +5,7 @@ xiaomo info.xiaomo - 2017.2 + 2020.1 4.0.0 @@ -15,7 +15,7 @@ info.xiaomo core - 2017.2 + 2020.1 org.mybatis.spring.boot diff --git a/mybatis/src/main/java/info/xiaomo/mybatis/MybatisMain.java b/mybatis/src/main/java/info/xiaomo/mybatis/MybatisMain.java new file mode 100644 index 00000000..b87e5e65 --- /dev/null +++ b/mybatis/src/main/java/info/xiaomo/mybatis/MybatisMain.java @@ -0,0 +1,32 @@ +package info.xiaomo.mybatis; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/4/1 15:38 + * Copyright(©) 2015 by xiaomo. + **/ +@Configuration +@EnableAutoConfiguration +@ComponentScan("info.xiaomo") +@EntityScan("info.xiaomo.*.model") +public class MybatisMain { + + public static void main(String[] args) throws Exception { + SpringApplication.run(MybatisMain.class, args); + } + +} diff --git a/mybatis/src/main/java/info/xiaomo/mybatis/MybatisMain.kt b/mybatis/src/main/java/info/xiaomo/mybatis/MybatisMain.kt deleted file mode 100644 index 19e0b7a2..00000000 --- a/mybatis/src/main/java/info/xiaomo/mybatis/MybatisMain.kt +++ /dev/null @@ -1,32 +0,0 @@ -package info.xiaomo.mybatis - -import org.springframework.boot.SpringApplication -import org.springframework.boot.autoconfigure.EnableAutoConfiguration -import org.springframework.boot.autoconfigure.domain.EntityScan -import org.springframework.context.annotation.ComponentScan - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/4/1 15:38 - * Copyright(©) 2015 by xiaomo. - */ -@EnableAutoConfiguration -@ComponentScan("info.xiaomo") -@EntityScan("info.xiaomo.*.model") -object MybatisMain { - - @Throws(Exception::class) - @JvmStatic - fun main(args: Array) { - SpringApplication.run(MybatisMain::class.java, *args) - } - -} diff --git a/mybatis/src/main/java/info/xiaomo/mybatis/controller/MybatisUserController.java b/mybatis/src/main/java/info/xiaomo/mybatis/controller/MybatisUserController.java new file mode 100644 index 00000000..7b19d769 --- /dev/null +++ b/mybatis/src/main/java/info/xiaomo/mybatis/controller/MybatisUserController.java @@ -0,0 +1,44 @@ +package info.xiaomo.mybatis.controller; + +import info.xiaomo.core.base.Result; +import info.xiaomo.mybatis.domain.User; +import info.xiaomo.mybatis.mapper.UserMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/11/16 9:41 + * Description: 用户实体类 + * Copyright(©) 2015 by xiaomo. + **/ + +@RestController +public class MybatisUserController { + + private final UserMapper userMapper; + + @Autowired + public MybatisUserController(UserMapper userMapper) { + this.userMapper = userMapper; + } + + + @RequestMapping("/") + public Result> findAll() { + List all = userMapper.findAll(); + return new Result<>(all); + } + +} diff --git a/mybatis/src/main/java/info/xiaomo/mybatis/controller/MybatisUserController.kt b/mybatis/src/main/java/info/xiaomo/mybatis/controller/MybatisUserController.kt deleted file mode 100644 index 02519449..00000000 --- a/mybatis/src/main/java/info/xiaomo/mybatis/controller/MybatisUserController.kt +++ /dev/null @@ -1,36 +0,0 @@ -package info.xiaomo.mybatis.controller - -import info.xiaomo.core.base.Result -import info.xiaomo.mybatis.domain.User -import info.xiaomo.mybatis.mapper.UserMapper -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.web.bind.annotation.RequestMapping -import org.springframework.web.bind.annotation.RestController - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/11/16 9:41 - * Description: 用户实体类 - * Copyright(©) 2015 by xiaomo. - */ - -@RestController -class MybatisUserController @Autowired -constructor(private val userMapper: UserMapper) { - - - @RequestMapping("/") - fun findAll(): Result> { - val all = userMapper.findAll() - return Result(all) - } - -} diff --git a/mybatis/src/main/java/info/xiaomo/mybatis/domain/User.java b/mybatis/src/main/java/info/xiaomo/mybatis/domain/User.java new file mode 100644 index 00000000..61adbfda --- /dev/null +++ b/mybatis/src/main/java/info/xiaomo/mybatis/domain/User.java @@ -0,0 +1,33 @@ +package info.xiaomo.mybatis.domain; + + +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.ToString; + +/** + * @author : xiaomo + */ +@Data +@ToString(callSuper = false) +@NoArgsConstructor +public class User { + + private Long id; + + private String name; + + private Integer age; + + public User(Long id, String name, Integer age) { + this.id = id; + this.name = name; + this.age = age; + } + + public User(String name, Integer age) { + this.name = name; + this.age = age; + } + +} diff --git a/mybatis/src/main/java/info/xiaomo/mybatis/domain/User.kt b/mybatis/src/main/java/info/xiaomo/mybatis/domain/User.kt deleted file mode 100644 index 9de422a9..00000000 --- a/mybatis/src/main/java/info/xiaomo/mybatis/domain/User.kt +++ /dev/null @@ -1,27 +0,0 @@ -package info.xiaomo.mybatis.domain - - -/** - * @author : xiaomo - */ - -class User { - - private var id: Long? = null - - private var name: String? = null - - private var age: Int? = null - - constructor(id: Long?, name: String, age: Int?) { - this.id = id - this.name = name - this.age = age - } - - constructor(name: String, age: Int?) { - this.name = name - this.age = age - } - -} diff --git a/mybatis/src/main/java/info/xiaomo/mybatis/mapper/UserMapper.kt b/mybatis/src/main/java/info/xiaomo/mybatis/mapper/UserMapper.java similarity index 58% rename from mybatis/src/main/java/info/xiaomo/mybatis/mapper/UserMapper.kt rename to mybatis/src/main/java/info/xiaomo/mybatis/mapper/UserMapper.java index dad84b45..7de341e9 100644 --- a/mybatis/src/main/java/info/xiaomo/mybatis/mapper/UserMapper.kt +++ b/mybatis/src/main/java/info/xiaomo/mybatis/mapper/UserMapper.java @@ -1,23 +1,32 @@ -package info.xiaomo.mybatis.mapper +package info.xiaomo.mybatis.mapper; -import info.xiaomo.mybatis.domain.User -import org.apache.ibatis.annotations.* +import info.xiaomo.mybatis.domain.User; +import org.apache.ibatis.annotations.*; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Map; /** * @author : xiaomo */ @Mapper -interface UserMapper { +@Repository +public interface UserMapper { + + @Results({ + @Result(property = "name", column = "name"), + @Result(property = "age", column = "age") + }) - @Results(Result(property = "name", column = "name"), Result(property = "age", column = "age")) /** * 根据名字查 * @param name * @return user */ @Select("SELECT * FROM USER WHERE NAME = #{name}") - fun findByName(@Param("name") name: String): User + User findByName(@Param("name") String name); /** * 插入 @@ -27,14 +36,15 @@ fun findByName(@Param("name") name: String): User * @return */ @Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})") - fun insert(@Param("name") name: String, @Param("age") age: Int?): Int + int insert(@Param("name") String name, @Param("age") Integer age); /** * 查所有 + * * @return */ @Select("SELECT * FROM USER WHERE 1=1") - fun findAll(): List + List findAll(); /** * 更新 @@ -42,7 +52,7 @@ fun findAll(): List * @param user */ @Update("UPDATE USER SET age=#{age} WHERE name=#{name}") - fun update(user: User) + void update(User user); /** * 删除 @@ -50,7 +60,7 @@ fun update(user: User) * @param id */ @Delete("DELETE FROM USER WHERE id =#{id}") - fun delete(id: Long?) + void delete(Long id); /** * 添加 @@ -59,7 +69,7 @@ fun delete(id: Long?) * @return */ @Insert("INSERT INTO USER(name, age) VALUES(#{name}, #{age})") - fun insertByUser(user: User): Int + int insertByUser(User user); /** * 添加 @@ -68,6 +78,6 @@ fun insertByUser(user: User): Int * @return */ @Insert("INSERT INTO user(name, age) VALUES(#{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})") - fun insertByMap(map: Map): Int + int insertByMap(Map map); } \ No newline at end of file diff --git a/mybatis/src/main/resources/config/application.properties b/mybatis/src/main/resources/config/application.properties index c75522bf..b138051d 100644 --- a/mybatis/src/main/resources/config/application.properties +++ b/mybatis/src/main/resources/config/application.properties @@ -1,6 +1,6 @@ logging.config=classpath:config/logback-dev.xml server.port=8080 -server.session.timeout=1800 + server.max-http-header-size=20971520 spring.jackson.date-format=yyyy-MM-dd HH:mm:ss @@ -11,7 +11,7 @@ spring.jackson.time-zone=GMT+8 spring.datasource.url=jdbc:mysql://ip:3306/db?characterEncoding=utf8&useSSL=true spring.datasource.username=username spring.datasource.password=password -spring.datasource.driver-class-name=com.mysql.jdbc.Driver +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver diff --git a/mybatis/src/main/resources/config/banner-girl.txt b/mybatis/src/main/resources/config/banner-girl.txt index c826bcd3..5c648ca3 100644 --- a/mybatis/src/main/resources/config/banner-girl.txt +++ b/mybatis/src/main/resources/config/banner-girl.txt @@ -16,4 +16,4 @@ ...::: ::::::::::::' ``::. ```` ':. ':::::::::' ::::.. '.:::::' ':'````.. -:: Spring Boot :: (v1.5.8.RELEASE) \ No newline at end of file +:: Spring Boot :: (v2.0.0.RELEASE) \ No newline at end of file diff --git a/order/pom.xml b/order/pom.xml new file mode 100644 index 00000000..fed4e2b0 --- /dev/null +++ b/order/pom.xml @@ -0,0 +1,66 @@ + + + + xiaomo + info.xiaomo + 2020.1 + + 4.0.0 + + order + + + info.xiaomo + core + 2020.1 + + + org.springframework.boot + spring-boot-devtools + true + + + io.springfox + springfox-swagger2 + + + io.springfox + springfox-swagger-ui + + + com.google.zxing + javase + 3.2.1 + + + com.google.zxing + core + 3.3.3 + + + + com.github.xiaoymin + swagger-bootstrap-ui + 1.5 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + + + diff --git a/order/src/main/java/info/xiaomo/order/OrderMain.java b/order/src/main/java/info/xiaomo/order/OrderMain.java new file mode 100644 index 00000000..d6311aba --- /dev/null +++ b/order/src/main/java/info/xiaomo/order/OrderMain.java @@ -0,0 +1,73 @@ +package info.xiaomo.order; + +import io.swagger.annotations.ApiOperation; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import springfox.documentation.annotations.ApiIgnore; +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; + + +/** + * @author xiaomo + */ +@Configuration +@ComponentScan("info.xiaomo") +@EntityScan("info.xiaomo.*.model") +@EnableSwagger2 +@Controller +@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) +public class OrderMain implements WebMvcConfigurer { + + public static void main(String[] args) { + SpringApplication.run(OrderMain.class, args); + } + + /** + * 接口 + * + * @return 接口 + */ + @RequestMapping(value = "/", method = RequestMethod.GET) + @ApiIgnore() + @ApiOperation(value = "重定向到api首页") + public ModelAndView api() { + return new ModelAndView("redirect:/swagger-ui.html"); + } + + + @Bean + public Docket createRestApi() { + return new Docket(DocumentationType.SWAGGER_2) + .apiInfo(apiInfo()) + .select() + .apis(RequestHandlerSelectors.basePackage("info.xiaomo.order")) + .paths(PathSelectors.any()) + .build(); + } + + private ApiInfo apiInfo() { + return new ApiInfoBuilder() + .title("Spring Boot中使用Swagger2构建RESTful APIs") + .contact("小莫") + .version("1.0") + .build(); + } + +} diff --git a/order/src/main/java/info/xiaomo/order/controller/OrderController.java b/order/src/main/java/info/xiaomo/order/controller/OrderController.java new file mode 100644 index 00000000..416d1c4d --- /dev/null +++ b/order/src/main/java/info/xiaomo/order/controller/OrderController.java @@ -0,0 +1,43 @@ +package info.xiaomo.order.controller; + +import info.xiaomo.core.base.Result; +import info.xiaomo.order.service.OrderService; +import io.swagger.annotations.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + + +/** + * @author xiaomo + */ +@RestController +@RequestMapping("/order") +@Api(value = "识别订单") +public class OrderController { + + private final OrderService service; + + @Autowired + public OrderController(OrderService orderService) { + this.service = orderService; + } + + + @RequestMapping(value = "forbid/{id}", method = RequestMethod.GET) + @ApiOperation(value = "封号", notes = "根据传入的id对修改对应帐号状态", httpMethod = "GET") + @ApiImplicitParams({ + @ApiImplicitParam(name = "id", value = "后台用户唯一id", required = true, dataType = "Long", paramType = "path") + }) + @ApiResponses(value = { + @ApiResponse(code = 404, message = "Not Found"), + @ApiResponse(code = 400, message = "No Name Provided"), + }) + public Result forbid(@PathVariable("id") Long id) { + return new Result<>(null); + } +} + diff --git a/website/src/main/java/info/xiaomo/website/model/AdminModel.kt b/order/src/main/java/info/xiaomo/order/model/OrderModel.java similarity index 53% rename from website/src/main/java/info/xiaomo/website/model/AdminModel.kt rename to order/src/main/java/info/xiaomo/order/model/OrderModel.java index c289b18c..22b8cba9 100644 --- a/website/src/main/java/info/xiaomo/website/model/AdminModel.kt +++ b/order/src/main/java/info/xiaomo/order/model/OrderModel.java @@ -1,11 +1,13 @@ -package info.xiaomo.website.model +package info.xiaomo.order.model; -import info.xiaomo.core.base.BaseModel -import java.io.Serializable -import javax.persistence.Column -import javax.persistence.Entity -import javax.persistence.Table +import info.xiaomo.core.base.BaseModel; +import lombok.*; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; +import java.io.Serializable; /** * │\__╭╭╭╭╭__/│ @@ -19,41 +21,34 @@ * |╭---╮把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. + * * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info - * + *

* Date: 16/4/2 12:39 * Copyright(©) 2015 by xiaomo. */ @Entity @Table(name = "adminUser") -class AdminModel : BaseModel(), Serializable { +@Data +@ToString(callSuper = true) +@EqualsAndHashCode(callSuper = false) +@AllArgsConstructor +@NoArgsConstructor +public class OrderModel extends BaseModel implements Serializable { @Column(name = "UserName") - var userName: String? = null - set(userName) { - field = this.userName - } + private String userName; @Column(name = "Password") - var password: String? = null - set(password) { - field = this.password - } + private String password; @Column(name = "Status") - var status = 1 - set(status) { - field = this.status - } + private int status = 1; @Column(name = "Salt") - var salt: String? = null - set(salt) { - field = this.salt - } + private String salt; } diff --git a/order/src/main/java/info/xiaomo/order/service/OrderService.java b/order/src/main/java/info/xiaomo/order/service/OrderService.java new file mode 100644 index 00000000..b3543f4d --- /dev/null +++ b/order/src/main/java/info/xiaomo/order/service/OrderService.java @@ -0,0 +1,9 @@ +package info.xiaomo.order.service; + +/** + * @author xiaomo + */ +public interface OrderService { + + +} diff --git a/order/src/main/java/info/xiaomo/order/service/impl/OrderServiceImpl.java b/order/src/main/java/info/xiaomo/order/service/impl/OrderServiceImpl.java new file mode 100644 index 00000000..d7b60d04 --- /dev/null +++ b/order/src/main/java/info/xiaomo/order/service/impl/OrderServiceImpl.java @@ -0,0 +1,12 @@ +package info.xiaomo.order.service.impl; + +import info.xiaomo.order.service.OrderService; +import org.springframework.stereotype.Service; + +/** + * @author xiaomo + */ +@Service +public class OrderServiceImpl implements OrderService { + +} diff --git a/pom.xml b/pom.xml index 4cb84693..5b1f7919 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ 4.0.0 info.xiaomo xiaomo - 2017.2 + 2020.1 @@ -36,6 +36,10 @@ multipleSource crawler + + javase + + order pom @@ -46,44 +50,32 @@ - - - central - aliyun maven - default - http://maven.aliyun.com/nexus/content/groups/public/ - - true - - - - UTF-8 - 1.8 + 11 3.5 - 4.12 + 4.13.1 - 5.1.38 + 8.0.28 1.7.21 1.1.7 - 2.5 + 2.7 - 1.3.2 + [1.3.3,) - 1.2.20 + [1.2.31,) - 1.10.1 + 1.14.2 - 1.5.8.RELEASE + 2.5.12 3.5.1 @@ -91,7 +83,7 @@ 1.4.7 - 1.16.10 + 1.18.14 2.2.2 @@ -101,8 +93,7 @@ 2.6.12 - 3.10-beta2 - 1.1.51 + 3.17 @@ -122,6 +113,11 @@ pom import + + dom4j + dom4j + 1.6.1 + junit junit @@ -163,6 +159,11 @@ mail ${javax-mail.version} + + org.projectlombok + lombok + ${lombak.version} + io.springfox @@ -175,21 +176,11 @@ springfox-swagger2 ${springfox-swagger-ui.version} - - org.mortbay.jasper - jasper-jsp - ${jsper.version} - org.mybatis.spring.boot mybatis-spring-boot-starter ${mybatis.version} - - com.squareup.okhttp3 - okhttp - ${okhttp.version} - org.jsoup jsoup @@ -209,20 +200,6 @@ - - - org.jetbrains.kotlin - kotlin-stdlib-jre8 - ${kotlin.version} - - - org.jetbrains.kotlin - kotlin-test - ${kotlin.version} - test - - - @@ -238,6 +215,19 @@ + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot.version} + + + + repackage + + + + + org.apache.maven.plugins @@ -251,44 +241,16 @@ maven-source-plugin - 2.1 + 3.2.0 true compile - - jar - - - org.jetbrains.kotlin - kotlin-maven-plugin - ${kotlin.version} - - - compile - compile - - compile - - - - test-compile - test-compile - - test-compile - - - - - 1.8 - - - - \ No newline at end of file + diff --git a/rabbitmq/pom.xml b/rabbitmq/pom.xml index 5237d5c8..eed80ec6 100644 --- a/rabbitmq/pom.xml +++ b/rabbitmq/pom.xml @@ -5,7 +5,7 @@ xiaomo info.xiaomo - 2017.2 + 2020.1 4.0.0 @@ -15,7 +15,7 @@ info.xiaomo core - 2017.2 + 2020.1 org.springframework.boot diff --git a/rabbitmq/src/main/java/info/xiaomo/rabbitmq/RabbitMqMain.java b/rabbitmq/src/main/java/info/xiaomo/rabbitmq/RabbitMqMain.java new file mode 100644 index 00000000..7030a585 --- /dev/null +++ b/rabbitmq/src/main/java/info/xiaomo/rabbitmq/RabbitMqMain.java @@ -0,0 +1,42 @@ +package info.xiaomo.rabbitmq; + +import org.springframework.amqp.core.Queue; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.EnableScheduling; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + *

+ * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/4/1 15:38 + * Description: RabbitMq启动器 + * Copyright(©) 2015 by xiaomo. + **/ +@Configuration +@ComponentScan("info.xiaomo") +@EnableScheduling +@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) +public class RabbitMqMain { + public static void main(String[] args) throws Exception { + SpringApplication.run(RabbitMqMain.class, args); + } + + @Bean + public Queue helloQueue() { + return new Queue("hello"); + } + +} diff --git a/rabbitmq/src/main/java/info/xiaomo/rabbitmq/RabbitMqMain.kt b/rabbitmq/src/main/java/info/xiaomo/rabbitmq/RabbitMqMain.kt deleted file mode 100644 index d9d10bff..00000000 --- a/rabbitmq/src/main/java/info/xiaomo/rabbitmq/RabbitMqMain.kt +++ /dev/null @@ -1,46 +0,0 @@ -package info.xiaomo.rabbitmq - -import org.springframework.amqp.core.Queue -import org.springframework.boot.SpringApplication -import org.springframework.boot.autoconfigure.EnableAutoConfiguration -import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration -import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration -import org.springframework.context.annotation.Bean -import org.springframework.context.annotation.ComponentScan -import org.springframework.scheduling.annotation.EnableScheduling - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * - * Date: 2016/4/1 15:38 - * Description: RabbitMq启动器 - * Copyright(©) 2015 by xiaomo. - */ -@ComponentScan("info.xiaomo") -@EnableScheduling -@EnableAutoConfiguration(exclude = arrayOf(DataSourceAutoConfiguration::class, HibernateJpaAutoConfiguration::class)) -class RabbitMqMain { - - @Bean - fun helloQueue(): Queue { - return Queue("hello") - } - - companion object { - @Throws(Exception::class) - @JvmStatic - fun main(args: Array) { - SpringApplication.run(RabbitMqMain::class.java, *args) - } - } - -} diff --git a/rabbitmq/src/main/java/info/xiaomo/rabbitmq/config/Receiver.java b/rabbitmq/src/main/java/info/xiaomo/rabbitmq/config/Receiver.java new file mode 100644 index 00000000..18f89af9 --- /dev/null +++ b/rabbitmq/src/main/java/info/xiaomo/rabbitmq/config/Receiver.java @@ -0,0 +1,19 @@ +package info.xiaomo.rabbitmq.config; + +import org.springframework.amqp.rabbit.annotation.RabbitHandler; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.stereotype.Component; + +/** + * @author : xiaomo + */ +@Component +@RabbitListener(queues = "hello") +public class Receiver { + + @RabbitHandler + public void process(String hello) { + System.out.println("Receiver : " + hello); + } + +} diff --git a/rabbitmq/src/main/java/info/xiaomo/rabbitmq/config/Receiver.kt b/rabbitmq/src/main/java/info/xiaomo/rabbitmq/config/Receiver.kt deleted file mode 100644 index b820856b..00000000 --- a/rabbitmq/src/main/java/info/xiaomo/rabbitmq/config/Receiver.kt +++ /dev/null @@ -1,19 +0,0 @@ -package info.xiaomo.rabbitmq.config - -import org.springframework.amqp.rabbit.annotation.RabbitHandler -import org.springframework.amqp.rabbit.annotation.RabbitListener -import org.springframework.stereotype.Component - -/** - * @author : xiaomo - */ -@Component -@RabbitListener(queues = arrayOf("hello")) -class Receiver { - - @RabbitHandler - fun process(hello: String) { - println("Receiver : " + hello) - } - -} diff --git a/rabbitmq/src/main/java/info/xiaomo/rabbitmq/config/Sender.java b/rabbitmq/src/main/java/info/xiaomo/rabbitmq/config/Sender.java new file mode 100644 index 00000000..b16f46fc --- /dev/null +++ b/rabbitmq/src/main/java/info/xiaomo/rabbitmq/config/Sender.java @@ -0,0 +1,28 @@ +package info.xiaomo.rabbitmq.config; + +import org.springframework.amqp.core.AmqpTemplate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.Date; + +/** + * @author : xiaomo + */ +@Component +public class Sender { + + private final AmqpTemplate rabbitTemplate; + + @Autowired + public Sender(AmqpTemplate rabbitTemplate) { + this.rabbitTemplate = rabbitTemplate; + } + + public void send() { + String context = "hello " + new Date(); + System.out.println("Sender : " + context); + this.rabbitTemplate.convertAndSend("hello", context); + } + +} \ No newline at end of file diff --git a/rabbitmq/src/main/java/info/xiaomo/rabbitmq/config/Sender.kt b/rabbitmq/src/main/java/info/xiaomo/rabbitmq/config/Sender.kt deleted file mode 100644 index b14b423d..00000000 --- a/rabbitmq/src/main/java/info/xiaomo/rabbitmq/config/Sender.kt +++ /dev/null @@ -1,21 +0,0 @@ -package info.xiaomo.rabbitmq.config - -import org.springframework.amqp.core.AmqpTemplate -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.stereotype.Component -import java.util.* - -/** - * @author : xiaomo - */ -@Component -class Sender @Autowired -constructor(private val rabbitTemplate: AmqpTemplate) { - - fun send() { - val context = "hello " + Date() - println("Sender : " + context) - this.rabbitTemplate.convertAndSend("hello", context) - } - -} \ No newline at end of file diff --git a/rabbitmq/src/main/resources/config/application.properties b/rabbitmq/src/main/resources/config/application.properties index e2c21445..b3ab7a48 100644 --- a/rabbitmq/src/main/resources/config/application.properties +++ b/rabbitmq/src/main/resources/config/application.properties @@ -1,6 +1,6 @@ logging.config=classpath:config/logback-dev.xml server.port=8080 -server.session.timeout=1800 + server.max-http-header-size=20971520 # \u914D\u7F6E\u8FD9\u4E2A\u503C\u5C31\u53EF\u4EE5\u683C\u5F0F\u5316\u65F6\u95F4 diff --git a/rabbitmq/src/test/java/test/RabbitMqTests.java b/rabbitmq/src/test/java/test/RabbitMqTests.java new file mode 100644 index 00000000..f95714a7 --- /dev/null +++ b/rabbitmq/src/test/java/test/RabbitMqTests.java @@ -0,0 +1,17 @@ +package test; + +import info.xiaomo.rabbitmq.config.Sender; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; + +public class RabbitMqTests { + + @Autowired() + private Sender sender; + + @Test + public void hello() throws Exception { + sender.send(); + } + +} diff --git a/rabbitmq/src/test/java/test/RabbitMqTests.kt b/rabbitmq/src/test/java/test/RabbitMqTests.kt deleted file mode 100644 index d84b7919..00000000 --- a/rabbitmq/src/test/java/test/RabbitMqTests.kt +++ /dev/null @@ -1,18 +0,0 @@ -package test - -import info.xiaomo.rabbitmq.config.Sender -import org.junit.Test -import org.springframework.beans.factory.annotation.Autowired - -class RabbitMqTests { - - @Autowired - private val sender: Sender? = null - - @Test - @Throws(Exception::class) - fun hello() { - sender!!.send() - } - -} diff --git a/redis/pom.xml b/redis/pom.xml index caafdadb..3ed31182 100644 --- a/redis/pom.xml +++ b/redis/pom.xml @@ -5,7 +5,7 @@ xiaomo info.xiaomo - 2017.2 + 2020.1 4.0.0 @@ -15,12 +15,11 @@ info.xiaomo core - 2017.2 + 2020.1 org.springframework.boot - spring-boot-starter-redis - 1.4.1.RELEASE + spring-boot-starter-data-redis diff --git a/redis/src/main/java/info/xiaomo/redis/RedisMain.java b/redis/src/main/java/info/xiaomo/redis/RedisMain.java new file mode 100644 index 00000000..1f42cee6 --- /dev/null +++ b/redis/src/main/java/info/xiaomo/redis/RedisMain.java @@ -0,0 +1,36 @@ +package info.xiaomo.redis; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.EnableScheduling; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/4/1 15:38 + * Description: Redis启动器 + * Copyright(©) 2015 by xiaomo. + **/ +@Configuration +@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) +@ComponentScan("info.xiaomo") +@EnableCaching +@EnableScheduling +public class RedisMain { + public static void main(String[] args) throws Exception { + SpringApplication.run(RedisMain.class, args); + } + +} diff --git a/redis/src/main/java/info/xiaomo/redis/RedisMain.kt b/redis/src/main/java/info/xiaomo/redis/RedisMain.kt deleted file mode 100644 index 46a6e526..00000000 --- a/redis/src/main/java/info/xiaomo/redis/RedisMain.kt +++ /dev/null @@ -1,34 +0,0 @@ -package info.xiaomo.redis - -import org.springframework.boot.SpringApplication -import org.springframework.boot.autoconfigure.EnableAutoConfiguration -import org.springframework.cache.annotation.EnableCaching -import org.springframework.context.annotation.ComponentScan -import org.springframework.scheduling.annotation.EnableScheduling - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/4/1 15:38 - * Description: Redis启动器 - * Copyright(©) 2015 by xiaomo. - */ -@EnableAutoConfiguration -@ComponentScan("info.xiaomo") -@EnableCaching -@EnableScheduling -object RedisMain { - @Throws(Exception::class) - @JvmStatic - fun main(args: Array) { - SpringApplication.run(RedisMain::class.java, *args) - } - -} diff --git a/redis/src/main/java/info/xiaomo/redis/controller/TestController.java b/redis/src/main/java/info/xiaomo/redis/controller/TestController.java new file mode 100644 index 00000000..1590409a --- /dev/null +++ b/redis/src/main/java/info/xiaomo/redis/controller/TestController.java @@ -0,0 +1,58 @@ +package info.xiaomo.redis.controller; + +import info.xiaomo.core.base.Result; +import info.xiaomo.redis.dao.CommonRedisDao; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/11/14 17:25 + * Copyright(©) 2015 by xiaomo. + **/ + +@RestController +@RequestMapping("/redis") +public class TestController { + + private final CommonRedisDao dao; + + @Autowired + public TestController(CommonRedisDao dao) { + this.dao = dao; + } + + @RequestMapping(value = "get/{key}", method = RequestMethod.GET) + public Result find(@PathVariable("key") String key) { + String value = dao.getValue(key); + return new Result<>(value); + } + + @RequestMapping(value = "add/{key}/{value}", method = RequestMethod.GET) + public Result add(@PathVariable("value") String value, @PathVariable("key") String key) { + return new Result<>(dao.cacheValue(key, value)); + } + + @RequestMapping(value = "del/{key}", method = RequestMethod.GET) + public Result del(@PathVariable("key") String key) { + return new Result<>(dao.removeValue(key)); + } + + @RequestMapping(value = "count/{key}", method = RequestMethod.GET) + public Result count(@PathVariable("key") String key) { + return new Result<>(dao.getListSize(key)); + } + + +} diff --git a/redis/src/main/java/info/xiaomo/redis/controller/TestController.kt b/redis/src/main/java/info/xiaomo/redis/controller/TestController.kt deleted file mode 100644 index c587107c..00000000 --- a/redis/src/main/java/info/xiaomo/redis/controller/TestController.kt +++ /dev/null @@ -1,52 +0,0 @@ -package info.xiaomo.redis.controller - -import info.xiaomo.core.base.Result -import info.xiaomo.redis.dao.CommonRedisDao -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.web.bind.annotation.PathVariable -import org.springframework.web.bind.annotation.RequestMapping -import org.springframework.web.bind.annotation.RequestMethod -import org.springframework.web.bind.annotation.RestController - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/11/14 17:25 - * Copyright(©) 2015 by xiaomo. - */ - -@RestController -@RequestMapping("/redis") -class TestController @Autowired -constructor(private val dao: CommonRedisDao) { - - @RequestMapping(value = "get/{key}", method = arrayOf(RequestMethod.GET)) - fun find(@PathVariable("key") key: String): Result { - val value = dao.getValue(key) - return Result(value) - } - - @RequestMapping(value = "add/{key}/{value}", method = arrayOf(RequestMethod.GET)) - fun add(@PathVariable("value") value: String, @PathVariable("key") key: String): Result { - return Result(dao.cacheValue(key, value)) - } - - @RequestMapping(value = "del/{key}", method = arrayOf(RequestMethod.GET)) - fun del(@PathVariable("key") key: String): Result { - return Result(dao.removeValue(key)) - } - - @RequestMapping(value = "count/{key}", method = arrayOf(RequestMethod.GET)) - fun count(@PathVariable("key") key: String): Result { - return Result(dao.getListSize(key)) - } - - -} diff --git a/redis/src/main/java/info/xiaomo/redis/dao/CommonRedisDao.kt b/redis/src/main/java/info/xiaomo/redis/dao/CommonRedisDao.java similarity index 63% rename from redis/src/main/java/info/xiaomo/redis/dao/CommonRedisDao.kt rename to redis/src/main/java/info/xiaomo/redis/dao/CommonRedisDao.java index 65dbcbcf..97cd82e6 100644 --- a/redis/src/main/java/info/xiaomo/redis/dao/CommonRedisDao.kt +++ b/redis/src/main/java/info/xiaomo/redis/dao/CommonRedisDao.java @@ -1,24 +1,26 @@ -package info.xiaomo.redis.dao +package info.xiaomo.redis.dao; -import org.springframework.data.redis.core.ListOperations +import org.springframework.data.redis.core.ListOperations; + +import java.util.List; +import java.util.Set; /** * 把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. + * * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info - * - * + *

* Date: 2016/11/14 17:59 * Description: 用户实体类 * Copyright(©) 2015 by xiaomo. - */ + **/ -interface CommonRedisDao { +public interface CommonRedisDao { /** * 添加 @@ -28,7 +30,7 @@ interface CommonRedisDao { * @param time * @return */ - fun cacheValue(key: String, value: String, time: Long): Boolean + boolean cacheValue(String key, String value, long time); /** * 添加 @@ -37,7 +39,7 @@ fun cacheValue(key: String, value: String, time: Long): Boolean * @param value * @return */ - fun cacheValue(key: String, value: String): Boolean + boolean cacheValue(String key, String value); /** * 是否包含 @@ -45,7 +47,7 @@ fun cacheValue(key: String, value: String): Boolean * @param key * @return */ - fun containsValueKey(key: String): Boolean + boolean containsValueKey(String key); /** * 是否包含 @@ -53,7 +55,7 @@ fun containsValueKey(key: String): Boolean * @param key * @return */ - fun containsSetKey(key: String): Boolean + boolean containsSetKey(String key); /** * 是否包含 @@ -61,7 +63,7 @@ fun containsSetKey(key: String): Boolean * @param key * @return */ - fun containsListKey(key: String): Boolean + boolean containsListKey(String key); /** * 是否包含 @@ -69,14 +71,15 @@ fun containsListKey(key: String): Boolean * @param key * @return */ - fun containsKey(key: String): Boolean + boolean containsKey(String key); /** * 获取缓存 + * * @param key * @return */ - fun getValue(key: String): String? + String getValue(String key); /** * 移除缓存 @@ -84,7 +87,7 @@ fun getValue(key: String): String? * @param key * @return */ - fun removeValue(key: String): Boolean + boolean removeValue(String key); /** * 移除缓存 @@ -92,7 +95,7 @@ fun removeValue(key: String): Boolean * @param key * @return */ - fun removeSet(key: String): Boolean + boolean removeSet(String key); /** * 移除缓存 @@ -100,7 +103,7 @@ fun removeSet(key: String): Boolean * @param key * @return */ - fun removeList(key: String): Boolean + boolean removeList(String key); /** * 缓存Set @@ -110,7 +113,7 @@ fun removeList(key: String): Boolean * @param time * @return */ - fun cacheSet(key: String, value: String, time: Long): Boolean + boolean cacheSet(String key, String value, long time); /** * 缓存Set @@ -119,7 +122,7 @@ fun cacheSet(key: String, value: String, time: Long): Boolean * @param value * @return */ - fun cacheSet(key: String, value: String): Boolean + boolean cacheSet(String key, String value); /** * 缓存Set @@ -129,7 +132,7 @@ fun cacheSet(key: String, value: String): Boolean * @param time * @return */ - fun cacheSet(k: String, v: Set, time: Long): Boolean + boolean cacheSet(String k, Set v, long time); /** * 缓存Set @@ -138,7 +141,7 @@ fun cacheSet(k: String, v: Set, time: Long): Boolean * @param v * @return */ - fun cacheSet(k: String, v: Set): Boolean + boolean cacheSet(String k, Set v); /** * 获取Set @@ -146,7 +149,7 @@ fun cacheSet(k: String, v: Set): Boolean * @param k * @return */ - fun getSet(k: String): Set? + Set getSet(String k); /** * 缓存List @@ -156,7 +159,7 @@ fun getSet(k: String): Set? * @param time * @return */ - fun cacheList(k: String, v: String, time: Long): Boolean + boolean cacheList(String k, String v, long time); /** * 缓存List @@ -165,7 +168,7 @@ fun cacheList(k: String, v: String, time: Long): Boolean * @param v * @return */ - fun cacheList(k: String, v: String): Boolean + boolean cacheList(String k, String v); /** * 缓存List @@ -175,7 +178,7 @@ fun cacheList(k: String, v: String): Boolean * @param time * @return */ - fun cacheList(k: String, v: List, time: Long): Boolean + boolean cacheList(String k, List v, long time); /** * 缓存List @@ -184,7 +187,7 @@ fun cacheList(k: String, v: List, time: Long): Boolean * @param v * @return */ - fun cacheList(k: String, v: List): Boolean + boolean cacheList(String k, List v); /** * 获取List @@ -194,7 +197,7 @@ fun cacheList(k: String, v: List): Boolean * @param end * @return */ - fun getList(k: String, start: Long, end: Long): List? + List getList(String k, long start, long end); /** * 获取页码 @@ -202,7 +205,7 @@ fun getList(k: String, start: Long, end: Long): List? * @param key * @return */ - fun getListSize(key: String): Long + long getListSize(String key); /** * 获取页码 @@ -211,7 +214,7 @@ fun getListSize(key: String): Long * @param k * @return */ - fun getListSize(listOps: ListOperations, k: String): Long + long getListSize(ListOperations listOps, String k); /** * 移除list缓存 @@ -219,5 +222,5 @@ fun getListSize(listOps: ListOperations, k: String): Long * @param k * @return */ - fun removeOneOfList(k: String): Boolean + boolean removeOneOfList(String k); } diff --git a/redis/src/main/java/info/xiaomo/redis/dao/impl/CommonRedisDaoImpl.java b/redis/src/main/java/info/xiaomo/redis/dao/impl/CommonRedisDaoImpl.java new file mode 100644 index 00000000..b9ecb6ea --- /dev/null +++ b/redis/src/main/java/info/xiaomo/redis/dao/impl/CommonRedisDaoImpl.java @@ -0,0 +1,418 @@ +package info.xiaomo.redis.dao.impl; + +import info.xiaomo.redis.dao.CommonRedisDao; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +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.SetOperations; +import org.springframework.data.redis.core.ValueOperations; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/11/14 18:00 + * Description: 用户实体类 + * Copyright(©) 2015 by xiaomo. + **/ + +@Repository +public class CommonRedisDaoImpl implements CommonRedisDao { + + /** + * 前缀 + */ + private static final String KEY_PREFIX_VALUE = "info:xiaomo:value:"; + private static final String KEY_PREFIX_SET = "info:xiaomo:set:"; + private static final String KEY_PREFIX_LIST = "info:xiaomo:list:"; + private final RedisTemplate redisTemplate; + /** + * 日志记录 + */ + private final Logger LOGGER = LoggerFactory.getLogger(this.getClass()); + + @Autowired + public CommonRedisDaoImpl(RedisTemplate redisTemplate) { + this.redisTemplate = redisTemplate; + } + + /** + * 缓存value操作 + * + * @param k key + * @param v value + * @param time time + * @return boolean + */ + @Override + public boolean cacheValue(String k, String v, long time) { + String key = KEY_PREFIX_VALUE + k; + try { + ValueOperations valueOps = redisTemplate.opsForValue(); + valueOps.set(key, v); + if (time > 0) { + redisTemplate.expire(key, time, TimeUnit.SECONDS); + } + return true; + } catch (Throwable t) { + LOGGER.error("缓存[" + key + "]失败, value[" + v + "]", t); + } + return false; + } + + /** + * 缓存value操作 + * + * @param k key + * @param v value + * @return boolean + */ + @Override + public boolean cacheValue(String k, String v) { + return cacheValue(k, v, -1); + } + + /** + * 判断缓存是否存在 + * + * @param k key + * @return boolean + */ + @Override + public boolean containsValueKey(String k) { + return containsKey(KEY_PREFIX_VALUE + k); + } + + /** + * 判断缓存是否存在 + * + * @param k key + * @return boolean + */ + @Override + public boolean containsSetKey(String k) { + return containsKey(KEY_PREFIX_SET + k); + } + + /** + * 判断缓存是否存在 + * + * @param k key + * @return boolean + */ + @Override + public boolean containsListKey(String k) { + return containsKey(KEY_PREFIX_LIST + k); + } + + @Override + public boolean containsKey(String key) { + try { + return redisTemplate.hasKey(key); + } catch (Throwable t) { + LOGGER.error("判断缓存存在失败key[" + key + ", Codeor[" + t + "]"); + } + return false; + } + + /** + * 获取缓存 + * + * @param k key + * @return string + */ + @Override + public String getValue(String k) { + try { + ValueOperations valueOps = redisTemplate.opsForValue(); + return valueOps.get(KEY_PREFIX_VALUE + k); + } catch (Throwable t) { + LOGGER.error("获取缓存失败key[" + KEY_PREFIX_VALUE + k + ", Codeor[" + t + "]"); + } + return null; + } + + /** + * 移除缓存 + * + * @param k key + * @return boolean + */ + @Override + public boolean removeValue(String k) { + return remove(KEY_PREFIX_VALUE + k); + } + + @Override + public boolean removeSet(String k) { + return remove(KEY_PREFIX_SET + k); + } + + @Override + public boolean removeList(String k) { + return remove(KEY_PREFIX_LIST + k); + } + + + /** + * 缓存set操作 + * + * @param k key + * @param v value + * @param time time + * @return boolean + */ + @Override + public boolean cacheSet(String k, String v, long time) { + String key = KEY_PREFIX_SET + k; + try { + SetOperations valueOps = redisTemplate.opsForSet(); + valueOps.add(key, v); + if (time > 0) { + redisTemplate.expire(key, time, TimeUnit.SECONDS); + } + return true; + } catch (Throwable t) { + LOGGER.error("缓存[" + key + "]失败, value[" + v + "]", t); + } + return false; + } + + /** + * 缓存set + * + * @param k key + * @param v value + * @return boolean + */ + @Override + public boolean cacheSet(String k, String v) { + return cacheSet(k, v, -1); + } + + /** + * 缓存set + * + * @param k key + * @param v value + * @param time time + * @return boolean + */ + @Override + public boolean cacheSet(String k, Set v, long time) { + String key = KEY_PREFIX_SET + k; + try { + SetOperations setOps = redisTemplate.opsForSet(); + setOps.add(key, v.toArray(new String[v.size()])); + if (time > 0) { + redisTemplate.expire(key, time, TimeUnit.SECONDS); + } + return true; + } catch (Throwable t) { + LOGGER.error("缓存[" + key + "]失败, value[" + v + "]", t); + } + return false; + } + + /** + * 缓存set + * + * @param k key + * @param v value + * @return boolean + */ + @Override + public boolean cacheSet(String k, Set v) { + return cacheSet(k, v, -1); + } + + /** + * 获取缓存set数据 + * + * @param k key + * @return set + */ + @Override + public Set getSet(String k) { + try { + SetOperations setOps = redisTemplate.opsForSet(); + return setOps.members(KEY_PREFIX_SET + k); + } catch (Throwable t) { + LOGGER.error("获取set缓存失败key[" + KEY_PREFIX_SET + k + ", Codeor[" + t + "]"); + } + return null; + } + + /** + * list缓存 + * + * @param k key + * @param v value + * @param time time + * @return boolean + */ + @Override + public boolean cacheList(String k, String v, long time) { + String key = KEY_PREFIX_LIST + k; + try { + ListOperations listOps = redisTemplate.opsForList(); + listOps.rightPush(key, v); + if (time > 0) { + redisTemplate.expire(key, time, TimeUnit.SECONDS); + } + return true; + } catch (Throwable t) { + LOGGER.error("缓存[" + key + "]失败, value[" + v + "]", t); + } + return false; + } + + /** + * 缓存list + * + * @param k key + * @param v value + * @return boolean + */ + @Override + public boolean cacheList(String k, String v) { + return cacheList(k, v, -1); + } + + /** + * 缓存list + * + * @param k key + * @param v value + * @param time time + * @return boolean + */ + @Override + public boolean cacheList(String k, List v, long time) { + String key = KEY_PREFIX_LIST + k; + try { + ListOperations listOps = redisTemplate.opsForList(); + listOps.rightPushAll(key, v); + if (time > 0) { + redisTemplate.expire(key, time, TimeUnit.SECONDS); + } + return true; + } catch (Throwable t) { + LOGGER.error("缓存[" + key + "]失败, value[" + v + "]", t); + } + return false; + } + + /** + * 缓存list + * + * @param k key + * @param v value + * @return boolean + */ + @Override + public boolean cacheList(String k, List v) { + return cacheList(k, v, -1); + } + + /** + * 获取list缓存 + * + * @param k key + * @param start start + * @param end end + * @return list + */ + @Override + public List getList(String k, long start, long end) { + try { + ListOperations listOps = redisTemplate.opsForList(); + return listOps.range(KEY_PREFIX_LIST + k, start, end); + } catch (Throwable t) { + LOGGER.error("获取list缓存失败key[" + KEY_PREFIX_LIST + k + ", Codeor[" + t + "]"); + } + return null; + } + + /** + * 获取总条数, 可用于分页 + * + * @param k key + * @return long + */ + @Override + public long getListSize(String k) { + try { + ListOperations listOps = redisTemplate.opsForList(); + return listOps.size(KEY_PREFIX_LIST + k); + } catch (Throwable t) { + LOGGER.error("获取list长度失败key[" + KEY_PREFIX_LIST + k + "], Codeor[" + t + "]"); + } + return 0; + } + + /** + * 获取总条数, 可用于分页 + * + * @param listOps listOps + * @param k k + * @return long + */ + @Override + public long getListSize(ListOperations listOps, String k) { + try { + return listOps.size(KEY_PREFIX_LIST + k); + } catch (Throwable t) { + LOGGER.error("获取list长度失败key[" + KEY_PREFIX_LIST + k + "], Codeor[" + t + "]"); + } + return 0; + } + + /** + * 移除list缓存 + * + * @param k k + * @return boolean + */ + @Override + public boolean removeOneOfList(String k) { + String key = KEY_PREFIX_LIST + k; + try { + ListOperations listOps = redisTemplate.opsForList(); + listOps.rightPop(key); + return true; + } catch (Throwable t) { + LOGGER.error("移除list缓存失败key[" + KEY_PREFIX_LIST + k + ", Codeor[" + t + "]"); + } + return false; + } + + /** + * 移除缓存 + * + * @param key key + * @return boolean + */ + private boolean remove(String key) { + try { + redisTemplate.delete(key); + return true; + } catch (Throwable t) { + LOGGER.error("获取缓存失败key[" + key + ", Codeor[" + t + "]"); + } + return false; + } +} diff --git a/redis/src/main/java/info/xiaomo/redis/dao/impl/CommonRedisDaoImpl.kt b/redis/src/main/java/info/xiaomo/redis/dao/impl/CommonRedisDaoImpl.kt deleted file mode 100644 index 3fab10fe..00000000 --- a/redis/src/main/java/info/xiaomo/redis/dao/impl/CommonRedisDaoImpl.kt +++ /dev/null @@ -1,400 +0,0 @@ -package info.xiaomo.redis.dao.impl - -import info.xiaomo.redis.dao.CommonRedisDao -import org.slf4j.LoggerFactory -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.data.redis.core.ListOperations -import org.springframework.data.redis.core.RedisTemplate -import org.springframework.stereotype.Repository -import java.util.concurrent.TimeUnit - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * - * Date: 2016/11/14 18:00 - * Description: 用户实体类 - * Copyright(©) 2015 by xiaomo. - */ - -@Repository -class CommonRedisDaoImpl @Autowired -constructor(private val redisTemplate: RedisTemplate) : CommonRedisDao { - /** - * 日志记录 - */ - private val LOGGER = LoggerFactory.getLogger(this.javaClass) - - /** - * 缓存value操作 - * - * @param k key - * @param v value - * @param time time - * @return boolean - */ - override fun cacheValue(k: String, v: String, time: Long): Boolean { - val key = KEY_PREFIX_VALUE + k - try { - val valueOps = redisTemplate.opsForValue() - valueOps.set(key, v) - if (time > 0) { - redisTemplate.expire(key, time, TimeUnit.SECONDS) - } - return true - } catch (t: Throwable) { - LOGGER.error("缓存[$key]失败, value[$v]", t) - } - - return false - } - - /** - * 缓存value操作 - * - * @param k key - * @param v value - * @return boolean - */ - override fun cacheValue(k: String, v: String): Boolean { - return cacheValue(k, v, -1) - } - - /** - * 判断缓存是否存在 - * - * @param k key - * @return boolean - */ - override fun containsValueKey(k: String): Boolean { - return containsKey(KEY_PREFIX_VALUE + k) - } - - /** - * 判断缓存是否存在 - * - * @param k key - * @return boolean - */ - override fun containsSetKey(k: String): Boolean { - return containsKey(KEY_PREFIX_SET + k) - } - - /** - * 判断缓存是否存在 - * - * @param k key - * @return boolean - */ - override fun containsListKey(k: String): Boolean { - return containsKey(KEY_PREFIX_LIST + k) - } - - override fun containsKey(key: String): Boolean { - try { - return redisTemplate.hasKey(key)!! - } catch (t: Throwable) { - LOGGER.error("判断缓存存在失败key[$key, Codeor[$t]") - } - - return false - } - - /** - * 获取缓存 - * - * @param k key - * @return string - */ - override fun getValue(k: String): String? { - try { - val valueOps = redisTemplate.opsForValue() - return valueOps.get(KEY_PREFIX_VALUE + k) - } catch (t: Throwable) { - LOGGER.error("获取缓存失败key[$KEY_PREFIX_VALUE$k, Codeor[$t]") - } - - return null - } - - /** - * 移除缓存 - * - * @param k key - * @return boolean - */ - override fun removeValue(k: String): Boolean { - return remove(KEY_PREFIX_VALUE + k) - } - - override fun removeSet(k: String): Boolean { - return remove(KEY_PREFIX_SET + k) - } - - override fun removeList(k: String): Boolean { - return remove(KEY_PREFIX_LIST + k) - } - - - /** - * 缓存set操作 - * - * @param k key - * @param v value - * @param time time - * @return boolean - */ - override fun cacheSet(k: String, v: String, time: Long): Boolean { - val key = KEY_PREFIX_SET + k - try { - val valueOps = redisTemplate.opsForSet() - valueOps.add(key, v) - if (time > 0) { - redisTemplate.expire(key, time, TimeUnit.SECONDS) - } - return true - } catch (t: Throwable) { - LOGGER.error("缓存[$key]失败, value[$v]", t) - } - - return false - } - - /** - * 缓存set - * - * @param k key - * @param v value - * @return boolean - */ - override fun cacheSet(k: String, v: String): Boolean { - return cacheSet(k, v, -1) - } - - /** - * 缓存set - * - * @param k key - * @param v value - * @param time time - * @return boolean - */ - override fun cacheSet(k: String, v: Set, time: Long): Boolean { - val key = KEY_PREFIX_SET + k - try { - val setOps = redisTemplate.opsForSet() - setOps.add(key, *v.toTypedArray()) - if (time > 0) { - redisTemplate.expire(key, time, TimeUnit.SECONDS) - } - return true - } catch (t: Throwable) { - LOGGER.error("缓存[$key]失败, value[$v]", t) - } - - return false - } - - /** - * 缓存set - * - * @param k key - * @param v value - * @return boolean - */ - override fun cacheSet(k: String, v: Set): Boolean { - return cacheSet(k, v, -1) - } - - /** - * 获取缓存set数据 - * - * @param k key - * @return set - */ - override fun getSet(k: String): Set? { - try { - val setOps = redisTemplate.opsForSet() - return setOps.members(KEY_PREFIX_SET + k) - } catch (t: Throwable) { - LOGGER.error("获取set缓存失败key[$KEY_PREFIX_SET$k, Codeor[$t]") - } - - return null - } - - /** - * list缓存 - * - * @param k key - * @param v value - * @param time time - * @return boolean - */ - override fun cacheList(k: String, v: String, time: Long): Boolean { - val key = KEY_PREFIX_LIST + k - try { - val listOps = redisTemplate.opsForList() - listOps.rightPush(key, v) - if (time > 0) { - redisTemplate.expire(key, time, TimeUnit.SECONDS) - } - return true - } catch (t: Throwable) { - LOGGER.error("缓存[$key]失败, value[$v]", t) - } - - return false - } - - /** - * 缓存list - * - * @param k key - * @param v value - * @return boolean - */ - override fun cacheList(k: String, v: String): Boolean { - return cacheList(k, v, -1) - } - - /** - * 缓存list - * - * @param k key - * @param v value - * @param time time - * @return boolean - */ - override fun cacheList(k: String, v: List, time: Long): Boolean { - val key = KEY_PREFIX_LIST + k - try { - val listOps = redisTemplate.opsForList() - listOps.rightPushAll(key, v) - if (time > 0) { - redisTemplate.expire(key, time, TimeUnit.SECONDS) - } - return true - } catch (t: Throwable) { - LOGGER.error("缓存[$key]失败, value[$v]", t) - } - - return false - } - - /** - * 缓存list - * - * @param k key - * @param v value - * @return boolean - */ - override fun cacheList(k: String, v: List): Boolean { - return cacheList(k, v, -1) - } - - /** - * 获取list缓存 - * - * @param k key - * @param start start - * @param end end - * @return list - */ - override fun getList(k: String, start: Long, end: Long): List? { - try { - val listOps = redisTemplate.opsForList() - return listOps.range(KEY_PREFIX_LIST + k, start, end) - } catch (t: Throwable) { - LOGGER.error("获取list缓存失败key[$KEY_PREFIX_LIST$k, Codeor[$t]") - } - - return null - } - - /** - * 获取总条数, 可用于分页 - * - * @param k key - * @return long - */ - override fun getListSize(k: String): Long { - try { - val listOps = redisTemplate.opsForList() - return listOps.size(KEY_PREFIX_LIST + k)!! - } catch (t: Throwable) { - LOGGER.error("获取list长度失败key[$KEY_PREFIX_LIST$k], Codeor[$t]") - } - - return 0 - } - - /** - * 获取总条数, 可用于分页 - * - * @param listOps listOps - * @param k k - * @return long - */ - override fun getListSize(listOps: ListOperations, k: String): Long { - try { - return listOps.size(KEY_PREFIX_LIST + k)!! - } catch (t: Throwable) { - LOGGER.error("获取list长度失败key[$KEY_PREFIX_LIST$k], Codeor[$t]") - } - - return 0 - } - - /** - * 移除list缓存 - * - * @param k k - * @return boolean - */ - override fun removeOneOfList(k: String): Boolean { - val key = KEY_PREFIX_LIST + k - try { - val listOps = redisTemplate.opsForList() - listOps.rightPop(key) - return true - } catch (t: Throwable) { - LOGGER.error("移除list缓存失败key[$KEY_PREFIX_LIST$k, Codeor[$t]") - } - - return false - } - - /** - * 移除缓存 - * - * @param key key - * @return boolean - */ - private fun remove(key: String): Boolean { - try { - redisTemplate.delete(key) - return true - } catch (t: Throwable) { - LOGGER.error("获取缓存失败key[$key, Codeor[$t]") - } - - return false - } - - companion object { - /** - * 前缀 - */ - private val KEY_PREFIX_VALUE = "info:xiaomo:value:" - private val KEY_PREFIX_SET = "info:xiaomo:set:" - private val KEY_PREFIX_LIST = "info:xiaomo:list:" - } -} diff --git a/redis/src/main/java/info/xiaomo/redis/job/TaskJob.java b/redis/src/main/java/info/xiaomo/redis/job/TaskJob.java new file mode 100644 index 00000000..11244433 --- /dev/null +++ b/redis/src/main/java/info/xiaomo/redis/job/TaskJob.java @@ -0,0 +1,47 @@ +package info.xiaomo.redis.job; + +import com.alibaba.fastjson.JSON; +import info.xiaomo.redis.model.CityInfo; +import info.xiaomo.redis.service.CityService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.util.Arrays; +import java.util.List; +import java.util.Random; + +/** + * @author : xiaomo + */ +@Component +public class TaskJob { + + private static final Logger LOGGER = LoggerFactory.getLogger(TaskJob.class); + private static final List LIST = Arrays.asList("北京市", "上海市", "天津市", "重庆市", "河北省", "山西省", "内蒙古自治区", "辽宁省", + "吉林省", "黑龙江", "江苏省", "浙江省", "安徽省", "福建省", "江西省", "山东省", "河南省", "湖北省", "湖南省", "广东省", "广西自治区", "海南省", "四川省", + "贵州省", "云南省", "西藏自治区", "陕西省", "甘肃省", "青海省", "宁夏自治区", "新疆自治区", "香港特别行政区", "澳门特别行政区", "台湾省"); + private final CityService cityService; + + @Autowired + public TaskJob(CityService cityService) { + this.cityService = cityService; + } + + /** + * Job + */ + @Scheduled(fixedDelay = 5000) + public void retrieveCountry() { + int index = new Random().nextInt(LIST.size()); + String city = find(index); + CityInfo info = cityService.getCity(index, city); + LOGGER.debug("{}", JSON.toJSONString(info)); + } + + private String find(int index) { + return LIST.get(index); + } +} diff --git a/redis/src/main/java/info/xiaomo/redis/job/TaskJob.kt b/redis/src/main/java/info/xiaomo/redis/job/TaskJob.kt deleted file mode 100644 index df1c9d68..00000000 --- a/redis/src/main/java/info/xiaomo/redis/job/TaskJob.kt +++ /dev/null @@ -1,40 +0,0 @@ -package info.xiaomo.redis.job - -import com.alibaba.fastjson.JSON -import info.xiaomo.redis.service.CityService -import org.slf4j.LoggerFactory -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.scheduling.annotation.Scheduled -import org.springframework.stereotype.Component -import java.util.* - -/** - * @author : xiaomo - */ -@Component -class TaskJob @Autowired -constructor(private val cityService: CityService) { - - /** - * Job - */ - @Scheduled(fixedDelay = 5000) - fun retrieveCountry() { - val index = Random().nextInt(LIST.size) - val city = find(index) - val info = cityService.getCity(index, city) - LOGGER.debug("{}", JSON.toJSONString(info)) - } - - private fun find(index: Int): String { - return LIST[index] - } - - companion object { - - private val LOGGER = LoggerFactory.getLogger(TaskJob::class.java) - private val LIST = Arrays.asList("北京市", "上海市", "天津市", "重庆市", "河北省", "山西省", "内蒙古自治区", "辽宁省", - "吉林省", "黑龙江", "江苏省", "浙江省", "安徽省", "福建省", "江西省", "山东省", "河南省", "湖北省", "湖南省", "广东省", "广西自治区", "海南省", "四川省", - "贵州省", "云南省", "西藏自治区", "陕西省", "甘肃省", "青海省", "宁夏自治区", "新疆自治区", "香港特别行政区", "澳门特别行政区", "台湾省") - } -} diff --git a/redis/src/main/java/info/xiaomo/redis/model/CityInfo.java b/redis/src/main/java/info/xiaomo/redis/model/CityInfo.java new file mode 100644 index 00000000..6b1d83ae --- /dev/null +++ b/redis/src/main/java/info/xiaomo/redis/model/CityInfo.java @@ -0,0 +1,38 @@ +package info.xiaomo.redis.model; + +import java.io.Serializable; + +/** + * @author : xiaomo + */ +public class CityInfo implements Serializable { + private static final long serialVersionUID = 2845294956907027149L; + + private int id; + private String city; + + public CityInfo() { + + } + + public CityInfo(int id, String city) { + this.id = id; + this.city = city; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } +} diff --git a/redis/src/main/java/info/xiaomo/redis/model/CityInfo.kt b/redis/src/main/java/info/xiaomo/redis/model/CityInfo.kt deleted file mode 100644 index 2ff54a9c..00000000 --- a/redis/src/main/java/info/xiaomo/redis/model/CityInfo.kt +++ /dev/null @@ -1,21 +0,0 @@ -package info.xiaomo.redis.model - -import java.io.Serializable - -/** - * @author : xiaomo - */ -class CityInfo : Serializable { - - var id: Int = 0 - var city: String? = null - - constructor(id: Int, city: String) { - this.id = id - this.city = city - } - - companion object { - private const val serialVersionUID = 2845294956907027149L - } -} diff --git a/redis/src/main/java/info/xiaomo/redis/service/CityService.java b/redis/src/main/java/info/xiaomo/redis/service/CityService.java new file mode 100644 index 00000000..ad1a2460 --- /dev/null +++ b/redis/src/main/java/info/xiaomo/redis/service/CityService.java @@ -0,0 +1,19 @@ +package info.xiaomo.redis.service; + +import info.xiaomo.redis.model.CityInfo; +import org.springframework.cache.annotation.CacheConfig; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Component; + +/** + * @author : xiaomo + */ +@Component +@CacheConfig(cacheNames = "CityService") +public class CityService { + + @Cacheable + public CityInfo getCity(int id, String city) { + return new CityInfo(id, city); + } +} diff --git a/redis/src/main/java/info/xiaomo/redis/service/CityService.kt b/redis/src/main/java/info/xiaomo/redis/service/CityService.kt deleted file mode 100644 index 115dd05c..00000000 --- a/redis/src/main/java/info/xiaomo/redis/service/CityService.kt +++ /dev/null @@ -1,19 +0,0 @@ -package info.xiaomo.redis.service - -import info.xiaomo.redis.model.CityInfo -import org.springframework.cache.annotation.CacheConfig -import org.springframework.cache.annotation.Cacheable -import org.springframework.stereotype.Component - -/** - * @author : xiaomo - */ -@Component -@CacheConfig(cacheNames = arrayOf("CityService")) -class CityService { - - @Cacheable - fun getCity(id: Int, city: String): CityInfo { - return CityInfo(id, city) - } -} diff --git a/redis/src/main/resources/config/application.properties b/redis/src/main/resources/config/application.properties index b25e5713..7721fe42 100644 --- a/redis/src/main/resources/config/application.properties +++ b/redis/src/main/resources/config/application.properties @@ -1,6 +1,6 @@ logging.config=classpath:config/logback-dev.xml server.port=8080 -server.session.timeout=1800 + server.max-http-header-size=20971520 # redis diff --git a/scheduled/pom.xml b/scheduled/pom.xml index b4bff7da..fa18839a 100644 --- a/scheduled/pom.xml +++ b/scheduled/pom.xml @@ -5,7 +5,7 @@ xiaomo info.xiaomo - 2017.2 + 2020.1 4.0.0 @@ -14,7 +14,7 @@ info.xiaomo core - 2017.2 + 2020.1 diff --git a/scheduled/src/main/java/info/xiaomo/scheduled/ScheduledMain.java b/scheduled/src/main/java/info/xiaomo/scheduled/ScheduledMain.java new file mode 100644 index 00000000..ada6b33a --- /dev/null +++ b/scheduled/src/main/java/info/xiaomo/scheduled/ScheduledMain.java @@ -0,0 +1,36 @@ +package info.xiaomo.scheduled; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.annotation.EnableScheduling; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/4/1 15:31 + * Description: 任务启动器 + * Copyright(©) 2015 by xiaomo. + **/ +@Configuration +@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) +@ComponentScan("info.xiaomo") +@EnableScheduling +@EnableAsync +public class ScheduledMain { + public static void main(String[] args) { + SpringApplication.run(ScheduledMain.class, args); + } + +} diff --git a/scheduled/src/main/java/info/xiaomo/scheduled/ScheduledMain.kt b/scheduled/src/main/java/info/xiaomo/scheduled/ScheduledMain.kt deleted file mode 100644 index d39a0652..00000000 --- a/scheduled/src/main/java/info/xiaomo/scheduled/ScheduledMain.kt +++ /dev/null @@ -1,36 +0,0 @@ -package info.xiaomo.scheduled - -import org.springframework.boot.SpringApplication -import org.springframework.boot.autoconfigure.EnableAutoConfiguration -import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration -import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration -import org.springframework.context.annotation.ComponentScan -import org.springframework.scheduling.annotation.EnableAsync -import org.springframework.scheduling.annotation.EnableScheduling - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/4/1 15:38 - * Description: 任务启动器 - * Copyright(©) 2015 by xiaomo. - */ -@EnableAutoConfiguration(exclude = arrayOf(DataSourceAutoConfiguration::class, HibernateJpaAutoConfiguration::class)) -@ComponentScan("info.xiaomo") -@EnableScheduling -@EnableAsync -object ScheduledMain { - @Throws(Exception::class) - @JvmStatic - fun main(args: Array) { - SpringApplication.run(ScheduledMain::class.java, *args) - } - -} diff --git a/scheduled/src/main/java/info/xiaomo/scheduled/task/ScheduledTasks.kt b/scheduled/src/main/java/info/xiaomo/scheduled/task/ScheduledTasks.java similarity index 75% rename from scheduled/src/main/java/info/xiaomo/scheduled/task/ScheduledTasks.kt rename to scheduled/src/main/java/info/xiaomo/scheduled/task/ScheduledTasks.java index d47797bc..70dca52e 100644 --- a/scheduled/src/main/java/info/xiaomo/scheduled/task/ScheduledTasks.kt +++ b/scheduled/src/main/java/info/xiaomo/scheduled/task/ScheduledTasks.java @@ -1,19 +1,24 @@ -package info.xiaomo.scheduled.task +package info.xiaomo.scheduled.task; -import org.springframework.scheduling.annotation.Scheduled -import org.springframework.stereotype.Component -import java.text.SimpleDateFormat +import lombok.extern.slf4j.Slf4j; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.text.SimpleDateFormat; /** * @author : xiaomo */ @Component -class ScheduledTasks { +@Slf4j +public class ScheduledTasks { + + private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("HH:mm:ss"); // 定义某个定时任务 @Scheduled(fixedRate = 5000) - fun reportCurrentTime() { - println("每5秒钟执行一次,注意观察日志时间") + public void reportCurrentTime() { + log.debug("每5秒钟执行一次,注意观察日志时间"); } @@ -26,8 +31,7 @@ fun reportCurrentTime() { * 月份 1-12 或者 JAN-DEC , - * / * 星期 1-7 或者 SUN-SAT , - * / L C # * 年(可选) 留空, 1970-2099 , - * / - * - * + *

* “*”字符被用来指定所有的值。如:”*“在分钟的字段域里表示“每分钟”。 * “-”字符被用来指定一个范围。如:“10-12”在小时域意味着“10点、11点、12点”。 * “,”字符被用来指定另外的值。如:“MON,WED,FRI”在星期域里表示”星期一、星期三、星期五”. @@ -35,16 +39,11 @@ fun reportCurrentTime() { * “L”字符指定在月或者星期中的某天(最后一天)。即“Last ”的缩写。但是在星期和月中“L”表示不同的意思,如:在月子段中“L”指月份的最后一天-1月31日,2月28日,如果在星期字段中则简单的表示为“7”或者“SAT”。如果在星期字段中在某个value值得后面,则表示“某月的最后一个星期value”,如“6L”表示某月的最后一个星期五。 * “W”字符只能用在月份字段中,该字段指定了离指定日期最近的那个星期日。 * “#”字符只能用在星期字段,该字段指定了第几个星期value在某月中 - */ + **/ //每1分钟执行一次 @Scheduled(cron = "0 */1 * * * * ") - fun reportCurrentByCron() { - println("每分钟执行一次,注意观察日志时间") - } - - companion object { - - private val DATE_FORMAT = SimpleDateFormat("HH:mm:ss") + public void reportCurrentByCron() { + log.debug("每分钟执行一次,注意观察日志时间"); } } diff --git a/scheduled/src/main/resources/config/application.properties b/scheduled/src/main/resources/config/application.properties index 2bbf0e38..7d2d7151 100644 --- a/scheduled/src/main/resources/config/application.properties +++ b/scheduled/src/main/resources/config/application.properties @@ -1,6 +1,6 @@ logging.config=classpath:config/logback-dev.xml server.port=8080 -server.session.timeout=1800 + server.max-http-header-size=20971520 # \u914D\u7F6E\u8FD9\u4E2A\u503C\u5C31\u53EF\u4EE5\u683C\u5F0F\u5316\u65F6\u95F4 diff --git a/screenshot/SpringBootUnity.png b/screenshot/SpringBootUnity.png new file mode 100644 index 00000000..e6708c16 Binary files /dev/null and b/screenshot/SpringBootUnity.png differ diff --git a/security/pom.xml b/security/pom.xml index bf01534e..2c3b2bda 100644 --- a/security/pom.xml +++ b/security/pom.xml @@ -5,7 +5,7 @@ xiaomo info.xiaomo - 2017.2 + 2020.1 4.0.0 @@ -15,7 +15,7 @@ info.xiaomo core - 2017.2 + 2020.1 org.springframework.boot diff --git a/security/src/main/java/info/xiaomo/security/SecurityMain.kt b/security/src/main/java/info/xiaomo/security/SecurityMain.java similarity index 55% rename from security/src/main/java/info/xiaomo/security/SecurityMain.kt rename to security/src/main/java/info/xiaomo/security/SecurityMain.java index 2067d6fa..01e306a3 100644 --- a/security/src/main/java/info/xiaomo/security/SecurityMain.kt +++ b/security/src/main/java/info/xiaomo/security/SecurityMain.java @@ -1,40 +1,45 @@ -package info.xiaomo.security - - -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.boot.SpringApplication -import org.springframework.boot.autoconfigure.EnableAutoConfiguration -import org.springframework.boot.autoconfigure.domain.EntityScan -import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration -import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration -import org.springframework.context.annotation.ComponentScan -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.configuration.EnableWebSecurity -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter +package info.xiaomo.security; + + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +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.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; /** * 把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. + * * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info - * + *

* Date: 2016/4/1 15:38 * Description: RabbitMq启动器 * Copyright(©) 2015 by xiaomo. - */ -@EnableAutoConfiguration(exclude = arrayOf(DataSourceAutoConfiguration::class, HibernateJpaAutoConfiguration::class)) + **/ +@Configuration +@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) @ComponentScan("info.xiaomo") @EntityScan("info.xiaomo.*.model") @EnableWebSecurity -class SecurityMain : WebSecurityConfigurerAdapter() { +public class SecurityMain extends WebSecurityConfigurerAdapter { + public static void main(String[] args) throws Exception { + SpringApplication.run(SecurityMain.class, args); + } - @Throws(Exception::class) - override fun configure(http: HttpSecurity) { + @Override + protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/", "/home").permitAll() .anyRequest().authenticated() @@ -44,22 +49,13 @@ override fun configure(http: HttpSecurity) { .permitAll() .and() .logout() - .permitAll() + .permitAll(); } @Autowired - @Throws(Exception::class) - fun configureGlobal(auth: AuthenticationManagerBuilder) { + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() - .withUser("test").password("test").roles("USER") - } - - companion object { - @Throws(Exception::class) - @JvmStatic - fun main(args: Array) { - SpringApplication.run(SecurityMain::class.java, *args) - } + .withUser("test").password("test").roles("USER"); } diff --git a/security/src/main/java/info/xiaomo/security/controller/HelloController.java b/security/src/main/java/info/xiaomo/security/controller/HelloController.java new file mode 100644 index 00000000..a4bc4302 --- /dev/null +++ b/security/src/main/java/info/xiaomo/security/controller/HelloController.java @@ -0,0 +1,28 @@ +package info.xiaomo.security.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +/** + * @author : xiaomo + */ +@Controller +public class HelloController { + + @RequestMapping("/") + public String index() { + return "index"; + } + + @RequestMapping("/hello") + public String hello() { + return "hello"; + } + + @RequestMapping(value = "/login", method = RequestMethod.GET) + public String login() { + return "login"; + } + +} \ No newline at end of file diff --git a/security/src/main/java/info/xiaomo/security/controller/HelloController.kt b/security/src/main/java/info/xiaomo/security/controller/HelloController.kt deleted file mode 100644 index 18cf0239..00000000 --- a/security/src/main/java/info/xiaomo/security/controller/HelloController.kt +++ /dev/null @@ -1,28 +0,0 @@ -package info.xiaomo.security.controller - -import org.springframework.stereotype.Controller -import org.springframework.web.bind.annotation.RequestMapping -import org.springframework.web.bind.annotation.RequestMethod - -/** - * @author : xiaomo - */ -@Controller -class HelloController { - - @RequestMapping("/") - fun index(): String { - return "index" - } - - @RequestMapping("/hello") - fun hello(): String { - return "hello" - } - - @RequestMapping(value = "/login", method = arrayOf(RequestMethod.GET)) - fun login(): String { - return "login" - } - -} \ No newline at end of file diff --git a/security/src/main/resources/config/application.properties b/security/src/main/resources/config/application.properties index e32aee62..8d858203 100644 --- a/security/src/main/resources/config/application.properties +++ b/security/src/main/resources/config/application.properties @@ -1,6 +1,6 @@ logging.config=classpath:config/logback-dev.xml server.port=8080 -server.session.timeout=1800 + server.max-http-header-size=20971520 # \u914D\u7F6E\u8FD9\u4E2A\u503C\u5C31\u53EF\u4EE5\u683C\u5F0F\u5316\u65F6\u95F4 spring.jackson.date-format=yyyy-MM-dd HH:mm:ss diff --git a/socket/pom.xml b/socket/pom.xml index c7509645..3739f943 100644 --- a/socket/pom.xml +++ b/socket/pom.xml @@ -5,7 +5,7 @@ xiaomo info.xiaomo - 2017.2 + 2020.1 4.0.0 @@ -15,7 +15,7 @@ info.xiaomo core - 2017.2 + 2020.1 org.springframework.boot diff --git a/socket/src/main/java/info/xiaomo/chat/ChatMain.java b/socket/src/main/java/info/xiaomo/chat/ChatMain.java new file mode 100644 index 00000000..b144a642 --- /dev/null +++ b/socket/src/main/java/info/xiaomo/chat/ChatMain.java @@ -0,0 +1,43 @@ +package info.xiaomo.chat; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.socket.server.standard.ServerEndpointExporter; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/4/1 15:38 + * Description: 后台管理启动器 + * Copyright(©) 2015 by xiaomo. + **/ +@Configuration +@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) +@ComponentScan("info.xiaomo") +@EntityScan("info.xiaomo.*.model") +public class ChatMain { + + public static void main(String[] args) throws Exception { + SpringApplication.run(ChatMain.class, args); + } + + + @Bean + public ServerEndpointExporter serverEndpointExporter() { + return new ServerEndpointExporter(); + } + +} diff --git a/socket/src/main/java/info/xiaomo/chat/ChatMain.kt b/socket/src/main/java/info/xiaomo/chat/ChatMain.kt deleted file mode 100644 index 713dced5..00000000 --- a/socket/src/main/java/info/xiaomo/chat/ChatMain.kt +++ /dev/null @@ -1,46 +0,0 @@ -package info.xiaomo.chat - -import org.springframework.boot.SpringApplication -import org.springframework.boot.autoconfigure.EnableAutoConfiguration -import org.springframework.boot.autoconfigure.domain.EntityScan -import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration -import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration -import org.springframework.context.annotation.Bean -import org.springframework.context.annotation.ComponentScan -import org.springframework.web.socket.server.standard.ServerEndpointExporter - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/4/1 15:38 - * Description: 后台管理启动器 - * Copyright(©) 2015 by xiaomo. - */ -@EnableAutoConfiguration(exclude = arrayOf(DataSourceAutoConfiguration::class, HibernateJpaAutoConfiguration::class)) -@ComponentScan("info.xiaomo") -@EntityScan("info.xiaomo.*.model") -class ChatMain { - - - @Bean - fun serverEndpointExporter(): ServerEndpointExporter { - return ServerEndpointExporter() - } - - companion object { - - @Throws(Exception::class) - @JvmStatic - fun main(args: Array) { - SpringApplication.run(ChatMain::class.java, *args) - } - } - -} diff --git a/socket/src/main/java/info/xiaomo/chat/socket/MyWebSocket.java b/socket/src/main/java/info/xiaomo/chat/socket/MyWebSocket.java new file mode 100644 index 00000000..57dcd631 --- /dev/null +++ b/socket/src/main/java/info/xiaomo/chat/socket/MyWebSocket.java @@ -0,0 +1,117 @@ +package info.xiaomo.chat.socket; + +import info.xiaomo.core.untils.HtmlUtil; +import info.xiaomo.core.untils.TimeUtil; +import lombok.Data; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import javax.websocket.OnClose; +import javax.websocket.OnMessage; +import javax.websocket.OnOpen; +import javax.websocket.Session; +import javax.websocket.server.ServerEndpoint; +import java.io.IOException; +import java.util.concurrent.CopyOnWriteArraySet; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + *

+ * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/11/3 16:36 + * Description: 用户实体类 + * Copyright(©) 2015 by xiaomo. + **/ + +@ServerEndpoint("/websocket") +@Component +@Data +public class MyWebSocket { + + private static final Logger LOGGER = LoggerFactory.getLogger(MyWebSocket.class); + private static int onlineCount = 0; + private static CopyOnWriteArraySet webSocketSet = new CopyOnWriteArraySet<>(); + private Session session; + + /** + * 获取在线人数 + * + * @return 在线人数 + */ + private static synchronized int getOnlineCount() { + return MyWebSocket.onlineCount; + } + + /** + * 添加在线人数 + */ + private static synchronized void addOnlineCount() { + MyWebSocket.onlineCount++; + } + + /** + * 减少在线人数 + */ + private static synchronized void subOnlineCount() { + MyWebSocket.onlineCount--; + } + + /** + * 有人进入房间 + * + * @param session session + */ + @OnOpen + public void onOpen(Session session) { + this.session = session; + webSocketSet.add(this); + addOnlineCount(); + LOGGER.info("有新用户加入!当前在线人数为:{}", getOnlineCount()); + } + + /** + * 有人离开房间 + */ + @OnClose + public void onClose() { + webSocketSet.remove(this); + subOnlineCount(); + System.out.println("有一用户关闭!当前在线人数为" + getOnlineCount()); + } + + /** + * 发消息 + * + * @param message message + * @throws IOException IOException + */ + @OnMessage + public void onMessage(String message) throws IOException { + String date = "" + TimeUtil.getDateNow(TimeUtil.DATE_PATTERN) + "
"; + // 群发消息 + for (MyWebSocket item : webSocketSet) { + item.sendMessage(date + message); + } + LOGGER.info("客户端消息:{}", HtmlUtil.delHTMLTag(message)); + } + + /** + * 发送消息 + * + * @param message message + * @throws IOException IOException + */ + private void sendMessage(String message) throws IOException { + this.session.getBasicRemote().sendText(message); + } + + +} diff --git a/socket/src/main/java/info/xiaomo/chat/socket/MyWebSocket.kt b/socket/src/main/java/info/xiaomo/chat/socket/MyWebSocket.kt deleted file mode 100644 index f6c70a1a..00000000 --- a/socket/src/main/java/info/xiaomo/chat/socket/MyWebSocket.kt +++ /dev/null @@ -1,117 +0,0 @@ -package info.xiaomo.chat.socket - -import info.xiaomo.core.untils.HtmlUtil -import info.xiaomo.core.untils.TimeUtil -import org.slf4j.LoggerFactory -import org.springframework.stereotype.Component -import java.io.IOException -import java.util.concurrent.CopyOnWriteArraySet -import javax.websocket.OnClose -import javax.websocket.OnMessage -import javax.websocket.OnOpen -import javax.websocket.Session -import javax.websocket.server.ServerEndpoint - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * - * Date: 2016/11/3 16:36 - * Description: 用户实体类 - * Copyright(©) 2015 by xiaomo. - */ - -@ServerEndpoint("/websocket") -@Component - -class MyWebSocket { - private var session: Session? = null - - /** - * 有人进入房间 - * - * @param session session - */ - @OnOpen - fun onOpen(session: Session) { - this.session = session - webSocketSet.add(this) - addOnlineCount() - LOGGER.info("有新用户加入!当前在线人数为:{}", onlineCount) - } - - /** - * 有人离开房间 - */ - @OnClose - fun onClose() { - webSocketSet.remove(this) - subOnlineCount() - println("有一用户关闭!当前在线人数为" + onlineCount) - } - - /** - * 发消息 - * - * @param message message - * @throws IOException IOException - */ - @OnMessage - @Throws(IOException::class) - fun onMessage(message: String) { - val date = "" + TimeUtil.getDateNow(TimeUtil.DATE_PATTERN) + "
" - // 群发消息 - for (item in webSocketSet) { - item.sendMessage(date + message) - } - LOGGER.info("客户端消息:{}", HtmlUtil.delHTMLTag(message)) - } - - /** - * 发送消息 - * - * @param message message - * @throws IOException IOException - */ - @Throws(IOException::class) - private fun sendMessage(message: String) { - this.session!!.basicRemote.sendText(message) - } - - companion object { - - private val LOGGER = LoggerFactory.getLogger(MyWebSocket::class.java) - /** - * 获取在线人数 - * - * @return 在线人数 - */ - @get:Synchronized private var onlineCount = 0 - private val webSocketSet = CopyOnWriteArraySet() - - /** - * 添加在线人数 - */ - @Synchronized private fun addOnlineCount() { - MyWebSocket.onlineCount++ - } - - /** - * 减少在线人数 - */ - @Synchronized private fun subOnlineCount() { - MyWebSocket.onlineCount-- - } - } - - -} diff --git a/socket/src/main/resources/config/application.properties b/socket/src/main/resources/config/application.properties index 453a78fb..d1e72d0f 100644 --- a/socket/src/main/resources/config/application.properties +++ b/socket/src/main/resources/config/application.properties @@ -1,6 +1,6 @@ logging.config=classpath:config/logback-dev.xml server.port=8081 -server.session.timeout=1800 + server.max-http-header-size=20971520 diff --git a/thymeleaf/pom.xml b/thymeleaf/pom.xml index 6a7376b3..6d1b1f53 100644 --- a/thymeleaf/pom.xml +++ b/thymeleaf/pom.xml @@ -5,7 +5,7 @@ xiaomo info.xiaomo - 2017.2 + 2020.1 4.0.0 @@ -14,7 +14,7 @@ info.xiaomo core - 2017.2 + 2020.1 org.springframework.boot diff --git a/thymeleaf/src/main/java/info/xiaomo/thymeleaf/ThymeleafMain.java b/thymeleaf/src/main/java/info/xiaomo/thymeleaf/ThymeleafMain.java new file mode 100644 index 00000000..a561841f --- /dev/null +++ b/thymeleaf/src/main/java/info/xiaomo/thymeleaf/ThymeleafMain.java @@ -0,0 +1,35 @@ +package info.xiaomo.thymeleaf; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/12/1 15:38 + * Copyright(©) 2015 by xiaomo. + **/ +@Configuration +@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) +@ComponentScan("info.xiaomo") +@EntityScan("info.xiaomo.*.model") +public class ThymeleafMain { + + public static void main(String[] args) throws Exception { + SpringApplication.run(ThymeleafMain.class, args); + } + + +} diff --git a/thymeleaf/src/main/java/info/xiaomo/thymeleaf/ThymeleafMain.kt b/thymeleaf/src/main/java/info/xiaomo/thymeleaf/ThymeleafMain.kt deleted file mode 100644 index 3d3ad8e0..00000000 --- a/thymeleaf/src/main/java/info/xiaomo/thymeleaf/ThymeleafMain.kt +++ /dev/null @@ -1,33 +0,0 @@ -package info.xiaomo.thymeleaf - -import org.springframework.boot.SpringApplication -import org.springframework.boot.autoconfigure.EnableAutoConfiguration -import org.springframework.boot.autoconfigure.domain.EntityScan -import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration -import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration -import org.springframework.context.annotation.ComponentScan - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/12/1 15:38 - * Copyright(©) 2015 by xiaomo. - */ -@EnableAutoConfiguration(exclude = arrayOf(DataSourceAutoConfiguration::class, HibernateJpaAutoConfiguration::class)) -@ComponentScan("info.xiaomo") -@EntityScan("info.xiaomo.*.model") -class ThymeleafMain - -@Throws(Exception::class) -fun main(args: Array) { - SpringApplication.run(ThymeleafMain::class.java, *args) - - -} diff --git a/thymeleaf/src/main/java/info/xiaomo/thymeleaf/controller/ThymeleafController.java b/thymeleaf/src/main/java/info/xiaomo/thymeleaf/controller/ThymeleafController.java new file mode 100644 index 00000000..ef573df5 --- /dev/null +++ b/thymeleaf/src/main/java/info/xiaomo/thymeleaf/controller/ThymeleafController.java @@ -0,0 +1,30 @@ +package info.xiaomo.thymeleaf.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.RequestMapping; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/11/16 10:19 + * Copyright(©) 2015 by xiaomo. + **/ + +@Controller +public class ThymeleafController { + + @RequestMapping("/") + public String hello(ModelMap map) { + map.put("hello", "使用thymeleaf!"); + return "index"; + } + +} diff --git a/thymeleaf/src/main/java/info/xiaomo/thymeleaf/controller/ThymeleafController.kt b/thymeleaf/src/main/java/info/xiaomo/thymeleaf/controller/ThymeleafController.kt deleted file mode 100644 index 2996ffcf..00000000 --- a/thymeleaf/src/main/java/info/xiaomo/thymeleaf/controller/ThymeleafController.kt +++ /dev/null @@ -1,30 +0,0 @@ -package info.xiaomo.thymeleaf.controller - -import org.springframework.stereotype.Controller -import org.springframework.ui.ModelMap -import org.springframework.web.bind.annotation.RequestMapping - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/11/16 10:19 - * Copyright(©) 2015 by xiaomo. - */ - -@Controller -class ThymeleafController { - - @RequestMapping("/") - fun hello(map: ModelMap): String { - map.put("hello", "使用thymeleaf!") - return "index" - } - -} diff --git a/thymeleaf/src/main/resources/config/application.properties b/thymeleaf/src/main/resources/config/application.properties index 9a461544..fec3b903 100644 --- a/thymeleaf/src/main/resources/config/application.properties +++ b/thymeleaf/src/main/resources/config/application.properties @@ -1,6 +1,6 @@ logging.config=classpath:config/logback-dev.xml server.port=8080 -server.session.timeout=1800 + server.max-http-header-size=20971520 spring.jackson.date-format=yyyy-MM-dd HH:mm:ss diff --git a/thymeleaf/src/main/resources/config/banner-girl.txt b/thymeleaf/src/main/resources/config/banner-girl.txt index c826bcd3..5c648ca3 100644 --- a/thymeleaf/src/main/resources/config/banner-girl.txt +++ b/thymeleaf/src/main/resources/config/banner-girl.txt @@ -16,4 +16,4 @@ ...::: ::::::::::::' ``::. ```` ':. ':::::::::' ::::.. '.:::::' ':'````.. -:: Spring Boot :: (v1.5.8.RELEASE) \ No newline at end of file +:: Spring Boot :: (v2.0.0.RELEASE) \ No newline at end of file diff --git a/website/pom.xml b/website/pom.xml index 5e3a88d4..3a00bf4f 100644 --- a/website/pom.xml +++ b/website/pom.xml @@ -5,7 +5,7 @@ xiaomo info.xiaomo - 2017.2 + 2020.1 4.0.0 @@ -15,7 +15,7 @@ info.xiaomo core - 2017.2 + 2020.1 org.springframework.boot @@ -43,6 +43,18 @@ swagger-bootstrap-ui 1.5 + + org.springframework + spring-webmvc + + + org.projectlombok + lombok + + + org.springframework.boot + spring-boot-starter-web + diff --git a/website/src/main/java/info/xiaomo/website/XiaomoMain.java b/website/src/main/java/info/xiaomo/website/XiaomoMain.java new file mode 100644 index 00000000..1d2c5aa7 --- /dev/null +++ b/website/src/main/java/info/xiaomo/website/XiaomoMain.java @@ -0,0 +1,95 @@ +package info.xiaomo.website; + +import info.xiaomo.website.view.UserView; +import io.swagger.annotations.ApiOperation; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.stereotype.Controller; +import org.springframework.transaction.annotation.EnableTransactionManagement; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import springfox.documentation.annotations.ApiIgnore; +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; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/4/1 15:38 + * Description: 后台管理启动器 + * Copyright(©) 2015 by xiaomo. + **/ +@Configuration +@EnableAutoConfiguration +@ComponentScan("info.xiaomo") +@EntityScan("info.xiaomo.*.model") +@EnableTransactionManagement +@EnableJpaRepositories("info.xiaomo.*.dao") +@EnableCaching +@EnableSwagger2 +@Controller +public class XiaomoMain implements WebMvcConfigurer { + + public static void main(String[] args) { + SpringApplication.run(XiaomoMain.class, args); + } + + @RequestMapping(value = "/", method = RequestMethod.GET) + public String index() { + return UserView.INDEX.getName(); + } + + /** + * 接口 + * + * @return 接口 + */ + @RequestMapping(value = "/api", method = RequestMethod.GET) + @ApiIgnore() + @ApiOperation(value = "重定向到api首页") + public ModelAndView api() { + return new ModelAndView("redirect:/swagger-ui.html"); + } + + + @Bean + public Docket createRestApi() { + return new Docket(DocumentationType.SWAGGER_2) + .apiInfo(apiInfo()) + .select() + .apis(RequestHandlerSelectors.basePackage("info.xiaomo.website")) + .paths(PathSelectors.any()) + .build(); + } + + private ApiInfo apiInfo() { + return new ApiInfoBuilder() + .title("Spring Boot中使用Swagger2构建RESTful APIs") + .description("api根地址:http://api.xiaomo.info:8080/") + .termsOfServiceUrl("https://xiaomo.info/") + .contact("小莫") + .version("1.0") + .build(); + } + +} diff --git a/website/src/main/java/info/xiaomo/website/XiaomoMain.kt b/website/src/main/java/info/xiaomo/website/XiaomoMain.kt deleted file mode 100644 index ed7481e7..00000000 --- a/website/src/main/java/info/xiaomo/website/XiaomoMain.kt +++ /dev/null @@ -1,99 +0,0 @@ -package info.xiaomo.website - -import info.xiaomo.website.view.UserView -import io.swagger.annotations.ApiOperation -import org.springframework.boot.SpringApplication -import org.springframework.boot.autoconfigure.EnableAutoConfiguration -import org.springframework.boot.autoconfigure.domain.EntityScan -import org.springframework.cache.annotation.EnableCaching -import org.springframework.context.annotation.Bean -import org.springframework.context.annotation.ComponentScan -import org.springframework.data.jpa.repository.config.EnableJpaRepositories -import org.springframework.stereotype.Controller -import org.springframework.transaction.annotation.EnableTransactionManagement -import org.springframework.web.bind.annotation.RequestMapping -import org.springframework.web.bind.annotation.RequestMethod -import org.springframework.web.servlet.ModelAndView -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter -import springfox.documentation.annotations.ApiIgnore -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 - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * - * Date: 2016/4/1 15:38 - * Description: 后台管理启动器 - * Copyright(©) 2015 by xiaomo. - */ -@EnableAutoConfiguration -@ComponentScan("info.xiaomo") -@EntityScan("info.xiaomo.*.model") -@EnableTransactionManagement -@EnableJpaRepositories("info.xiaomo.*.dao") -@EnableCaching -@EnableSwagger2 -@Controller -class XiaomoMain : WebMvcConfigurerAdapter() { - - @RequestMapping(value = "/", method = arrayOf(RequestMethod.GET)) - fun index(): String? { - return UserView.INDEX.viewName - } - - /** - * 接口 - * - * @return 接口 - */ - @RequestMapping(value = "/api", method = arrayOf(RequestMethod.GET)) - @ApiIgnore - @ApiOperation(value = "重定向到api首页") - fun api(): ModelAndView { - return ModelAndView("redirect:/swagger-ui.html") - } - - - @Bean - fun createRestApi(): Docket { - return Docket(DocumentationType.SWAGGER_2) - .apiInfo(apiInfo()) - .select() - .apis(RequestHandlerSelectors.basePackage("info.xiaomo.website")) - .paths(PathSelectors.any()) - .build() - } - - private fun apiInfo(): ApiInfo { - return ApiInfoBuilder() - .title("Spring Boot中使用Swagger2构建RESTful APIs") - .description("api根地址:http://api.xiaomo.info:8080/") - .termsOfServiceUrl("https://xiaomo.info/") - .contact("小莫") - .version("1.0") - .build() - } - - companion object { - - @Throws(Exception::class) - @JvmStatic - fun main(args: Array) { - SpringApplication.run(XiaomoMain::class.java, *args) - } - } - -} diff --git a/website/src/main/java/info/xiaomo/website/controller/AdminUserController.java b/website/src/main/java/info/xiaomo/website/controller/AdminUserController.java new file mode 100644 index 00000000..c79e934b --- /dev/null +++ b/website/src/main/java/info/xiaomo/website/controller/AdminUserController.java @@ -0,0 +1,358 @@ +package info.xiaomo.website.controller; + +import info.xiaomo.core.base.BaseController; +import info.xiaomo.core.base.Result; +import info.xiaomo.core.constant.CodeConst; +import info.xiaomo.core.exception.UserNotFoundException; +import info.xiaomo.core.untils.Md5Util; +import info.xiaomo.core.untils.RandomUtil; +import info.xiaomo.website.model.AdminModel; +import info.xiaomo.website.service.AdminUserService; +import io.swagger.annotations.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * │\__╭╭╭╭╭__/│ + * │         │ + * │         │ + * │ -      -│ + * │≡    o ≡ │ + * │         │ + * ╰——┬O◤▽◥O┬——╯ + * |  o  | + * |╭---╮把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 16/4/2 12:47 + * Description: 后台用户控制器 + * Copyright(©) 2015 by xiaomo. + */ +@RestController +@RequestMapping("/adminUser") +@Api(value = "后台用户相关api", description = "后台用户相关api") +public class AdminUserController extends BaseController { + + private final AdminUserService service; + + @Autowired + public AdminUserController(AdminUserService service) { + this.service = service; + } + + /** + * 后台账户登录 + * + * @return Result + */ + @RequestMapping(value = "login/{userName}/{password}", method = RequestMethod.POST) + @ApiOperation(value = "获取用户信息", notes = "根据用户帐号和密码登录后台", httpMethod = "POST") + @ApiImplicitParams({ + @ApiImplicitParam(name = "userName", value = "用户名", required = true, dataType = "Result", paramType = "path"), + @ApiImplicitParam(name = "password", value = "用户名", required = true, dataType = "Result", paramType = "path") + }) + @ApiResponses(value = { + @ApiResponse(code = 404, message = "Not Found"), + @ApiResponse(code = 400, message = "No Name Provided"), + }) + public Result login(@PathVariable("userName") String userName, @PathVariable("password") String password) { + AdminModel adminModel = service.findAdminUserByUserName(userName); + if (adminModel == null) { + return new Result<>(CodeConst.USER_NOT_FOUND.getResultCode(), CodeConst.USER_NOT_FOUND.getMessage()); + } + if (!Md5Util.encode(password, adminModel.getSalt()).equals(adminModel.getPassword())) { + return new Result<>(CodeConst.AUTH_FAILED.getResultCode(), CodeConst.AUTH_FAILED.getMessage()); + } + return new Result<>(adminModel); + } + + + /** + * 添加用户 + * + * @return Result + */ + @ApiOperation(value = "添加后台用户", notes = "传一个管理员用户模型过来然后保存到数据库", httpMethod = "POST") + @RequestMapping(value = "add", method = RequestMethod.POST) + @ApiResponses(value = { + @ApiResponse(code = 404, message = "Not Found"), + @ApiResponse(code = 400, message = "No Name Provided"), + }) + public Result add(@RequestBody AdminModel model) { + AdminModel adminModel = service.findAdminUserByUserName(model.getUserName()); + if (adminModel != null) { + return new Result<>(CodeConst.ADMIN_USER_REPEAT.getResultCode(), CodeConst.ADMIN_USER_REPEAT.getMessage()); + } + String salt = RandomUtil.createSalt(); + model.setSalt(salt); + model.setPassword(Md5Util.encode(model.getPassword(), salt)); + AdminModel saveModel = service.addAdminUser(model); + return new Result<>(saveModel); + } + + /** + * 根据id查找 + * + * @param id id + * @return Result + */ + @ApiOperation(value = "查找用户", notes = "根据传来的id查找用户并返回", httpMethod = "GET") + @RequestMapping(value = "findById/{id}", method = RequestMethod.GET) + @ApiImplicitParams({ + @ApiImplicitParam(name = "id", value = "后台用户唯一id", required = true, dataType = "Long", paramType = "path") + }) + @ApiResponses(value = { + @ApiResponse(code = 404, message = "Not Found"), + @ApiResponse(code = 400, message = "No Name Provided"), + }) + public Result findUserById(@PathVariable("id") Long id) { + AdminModel adminModel = service.findAdminUserById(id); + if (adminModel == null) { + return new Result<>(CodeConst.NULL_DATA.getResultCode(), CodeConst.NULL_DATA.getMessage()); + } + return new Result<>(adminModel); + } + + /** + * 查找所有(不带分页) + * + * @return result + */ + @Override + public Result findAll() { + return null; + } + + /** + * 带分页 + * + * @param start 起始页 + * @param pageSize 页码数 + * @return result + */ + @Override + public Result findAll(@PathVariable int start, @PathVariable int pageSize) { + return null; + } + + /** + * 根据id查看模型 + * + * @param id id + * @return result + */ + @Override + public Result findById(@PathVariable Long id) { + return null; + } + + /** + * 根据名字查找 + * + * @param userName userName + * @return Result + */ + @Override + @ApiOperation(value = "查找用户", notes = "根据传来的用户名查找用户并返回", httpMethod = "GET") + @RequestMapping(value = "findByName/{userName}", method = RequestMethod.GET) + @ApiImplicitParams({ + @ApiImplicitParam(name = "userName", value = "用户名", required = true, dataType = "String", paramType = "path") + }) + @ApiResponses(value = { + @ApiResponse(code = 404, message = "Not Found"), + @ApiResponse(code = 400, message = "No Name Provided"), + }) + public Result findByName(@PathVariable("userName") String userName) { + AdminModel adminModel = service.findAdminUserByUserName(userName); + if (adminModel == null) { + return new Result<>(CodeConst.NULL_DATA.getResultCode(), CodeConst.NULL_DATA.getMessage()); + } + return new Result<>(adminModel); + } + + /** + * 根据名字删除模型 + * + * @param name name + * @return result + */ + @Override + public Result delByName(@PathVariable String name) { + return null; + } + + /** + * 根据id删除模型 + * + * @param id id + * @return result + */ + @Override + public Result delById(@PathVariable Long id) { + return null; + } + + /** + * 添加模型 + * + * @param model model + * @return result + */ + @Override + public Result add(@RequestBody Object model) { + return null; + } + + /** + * 更新 + * + * @param model model + * @return result + */ + @Override + public Result update(@RequestBody Object model) { + return null; + } + + /** + * 批量删除 + * + * @param ids ids + * @return result + */ + @Override + public Result delByIds(@PathVariable List ids) { + return null; + } + + /** + * 修改密码 + * + * @return model + * @throws UserNotFoundException UserNotFoundException + */ + @RequestMapping(value = "changePassword", method = RequestMethod.POST) + @ApiOperation(value = "修改用户密码", notes = "传来模型验证并修改密码", httpMethod = "POST") + @ApiResponses(value = { + @ApiResponse(code = 404, message = "Not Found"), + @ApiResponse(code = 400, message = "No Name Provided"), + }) + public Result changePassword(@RequestBody AdminModel model) throws UserNotFoundException { + AdminModel adminModel = service.findAdminUserByUserName(model.getUserName()); + if (adminModel == null) { + return new Result<>(CodeConst.NULL_DATA.getResultCode(), CodeConst.NULL_DATA.getMessage()); + } + String salt = RandomUtil.createSalt(); + adminModel.setSalt(salt); + adminModel.setPassword(Md5Util.encode(model.getPassword(), salt)); + service.updateAdminUser(adminModel); + return new Result<>(adminModel); + } + + + /** + * 返回所有 + * + * @return 不分页 + */ + @RequestMapping(value = "findAll", method = RequestMethod.GET) + @ApiOperation(value = "返回所有用户信息", notes = "不分页", httpMethod = "GET") + @ApiResponses(value = { + @ApiResponse(code = 404, message = "Not Found"), + @ApiResponse(code = 400, message = "No Name Provided"), + }) + public Result getAll() { + List pages = service.getAdminUsers(); + if (pages == null || pages.size() <= 0) { + return new Result<>(pages); + } + return new Result<>(pages); + } + + /** + * 根据id删除数据 + * + * @param id id + * @return model + * @throws UserNotFoundException UserNotFoundException + */ + @RequestMapping(value = "delete/{id}", method = RequestMethod.GET) + @ApiOperation(value = "删除用户", notes = "根据传入的id删除对应的用户", httpMethod = "GET") + @ApiImplicitParams({ + @ApiImplicitParam(name = "id", value = "用户唯一id", required = true, dataType = "Long", paramType = "path") + }) + @ApiResponses(value = { + @ApiResponse(code = 404, message = "Not Found"), + @ApiResponse(code = 400, message = "No Name Provided"), + }) + public Result deleteUserById(@PathVariable("id") Long id) throws UserNotFoundException { + AdminModel adminModel = service.findAdminUserById(id); + if (adminModel == null) { + return new Result<>(CodeConst.NULL_DATA.getResultCode(), CodeConst.NULL_DATA.getMessage()); + } + service.deleteAdminUserById(id); + return new Result<>(adminModel); + } + + /** + * 更新 + * + * @param userName userName + * @return model + * @throws UserNotFoundException UserNotFoundException + */ + @RequestMapping(value = "update/{userName}", method = RequestMethod.POST) + @ApiOperation(value = "更新用户信息", notes = "根据传入的模型更新用户信息", httpMethod = "POST") + @ApiImplicitParams({ + @ApiImplicitParam(name = "userName", value = "用户名", required = true, dataType = "String", paramType = "path") + }) + @ApiResponses(value = { + @ApiResponse(code = 404, message = "Not Found"), + @ApiResponse(code = 400, message = "No Name Provided"), + }) + public Result update(@PathVariable("userName") String userName) throws UserNotFoundException { + AdminModel adminModel = service.findAdminUserByUserName(userName); + if (adminModel == null) { + return null; + } + adminModel.setUserName(userName); + service.updateAdminUser(adminModel); + return new Result<>(adminModel); + } + + /** + * 封号 + * + * @param id id + * @return model + * @throws UserNotFoundException UserNotFoundException + */ + @RequestMapping(value = "forbid/{id}", method = RequestMethod.GET) + @ApiOperation(value = "封号", notes = "根据传入的id对修改对应帐号状态", httpMethod = "GET") + @ApiImplicitParams({ + @ApiImplicitParam(name = "id", value = "后台用户唯一id", required = true, dataType = "Long", paramType = "path") + }) + @ApiResponses(value = { + @ApiResponse(code = 404, message = "Not Found"), + @ApiResponse(code = 400, message = "No Name Provided"), + }) + public Result forbid(@PathVariable("id") Long id) throws UserNotFoundException { + AdminModel model = service.findAdminUserById(id); + if (model == null) { + return new Result<>(CodeConst.NULL_DATA.getResultCode(), CodeConst.NULL_DATA.getMessage()); + } + model = service.forbidAdminUserById(id); + return new Result<>(model); + } +} + diff --git a/website/src/main/java/info/xiaomo/website/controller/AdminUserController.kt b/website/src/main/java/info/xiaomo/website/controller/AdminUserController.kt deleted file mode 100644 index b38eb628..00000000 --- a/website/src/main/java/info/xiaomo/website/controller/AdminUserController.kt +++ /dev/null @@ -1,200 +0,0 @@ -package info.xiaomo.website.controller - -import info.xiaomo.core.base.Result -import info.xiaomo.core.constant.CodeConst -import info.xiaomo.core.exception.UserNotFoundException -import info.xiaomo.core.untils.Md5Util -import info.xiaomo.core.untils.RandomUtil -import info.xiaomo.website.model.AdminModel -import info.xiaomo.website.service.AdminUserService -import io.swagger.annotations.* -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.http.MediaType -import org.springframework.web.bind.annotation.* - -/** - * │\__╭╭╭╭╭__/│ - * │         │ - * │         │ - * │ -      -│ - * │≡    o ≡ │ - * │         │ - * ╰——┬O◤▽◥O┬——╯ - * |  o  | - * |╭---╮把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * - * Date: 16/4/2 12:47 - * Description: 后台用户控制器 - * Copyright(©) 2015 by xiaomo. - */ -@RestController -@RequestMapping("/adminUser") -@Api(value = "后台用户相关api", description = "后台用户相关api") -class AdminUserController @Autowired -constructor(private val service: AdminUserService) { - - - /** - * 返回所有 - * - * @return 不分页 - */ - val all: Result<*> - @RequestMapping(value = "findAll", method = arrayOf(RequestMethod.GET)) - @ApiOperation(value = "返回所有用户信息", notes = "不分页", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @ApiResponses(value = *arrayOf(ApiResponse(code = 404, message = "Not Found"), ApiResponse(code = 400, message = "No Name Provided"))) - get() { - val pages = service.getAdminUsers() - return if (pages.isEmpty()) { - Result(pages) - } else Result(pages) - } - - /** - * 后台账户登录 - * - * @return Result - */ - @RequestMapping(value = "login/{userName}/{password}", method = arrayOf(RequestMethod.POST)) - @ApiOperation(value = "获取用户信息", notes = "根据用户帐号和密码登录后台", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @ApiImplicitParams(ApiImplicitParam(name = "userName", value = "用户名", required = true, dataType = "Result", paramType = "path"), ApiImplicitParam(name = "password", value = "用户名", required = true, dataType = "Result", paramType = "path")) - @ApiResponses(value = *arrayOf(ApiResponse(code = 404, message = "Not Found"), ApiResponse(code = 400, message = "No Name Provided"))) - fun login(@PathVariable("userName") userName: String, @PathVariable("password") password: String): Result<*> { - val adminModel = service.findAdminUserByUserName(userName) - return if (Md5Util.encode(password, adminModel.salt!!) != adminModel.password) { - Result(CodeConst.AUTH_FAILED.resultCode, CodeConst.AUTH_FAILED.message!!) - } else Result(adminModel) - } - - - /** - * 添加用户 - * - * @return Result - */ - @ApiOperation(value = "添加后台用户", notes = "传一个管理员用户模型过来然后保存到数据库", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @RequestMapping(value = "add", method = arrayOf(RequestMethod.POST)) - @ApiResponses(value = *arrayOf(ApiResponse(code = 404, message = "Not Found"), ApiResponse(code = 400, message = "No Name Provided"))) - fun add(@RequestBody model: AdminModel): Result<*> { - val salt = RandomUtil.createSalt() - model.salt = salt - model.password = Md5Util.encode(model.password!!, salt) - val saveModel = service.addAdminUser(model) - return Result(saveModel) - } - - /** - * 根据id查找 - * - * @param id id - * @return Result - */ - @ApiOperation(value = "查找用户", notes = "根据传来的id查找用户并返回", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @RequestMapping(value = "findById/{id}", method = arrayOf(RequestMethod.GET)) - @ApiImplicitParams(ApiImplicitParam(name = "id", value = "后台用户唯一id", required = true, dataType = "Long", paramType = "path")) - @ApiResponses(value = *arrayOf(ApiResponse(code = 404, message = "Not Found"), ApiResponse(code = 400, message = "No Name Provided"))) - fun findUserById(@PathVariable("id") id: Long?): Result<*> { - val adminModel = service.findAdminUserById(id) - return Result(adminModel) - } - - - /** - * 根据名字查找 - * - * @param userName userName - * @return Result - */ - @ApiOperation(value = "查找用户", notes = "根据传来的用户名查找用户并返回", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @RequestMapping(value = "findByName/{userName}", method = arrayOf(RequestMethod.GET)) - @ApiImplicitParams(ApiImplicitParam(name = "userName", value = "用户名", required = true, dataType = "String", paramType = "path")) - @ApiResponses(value = *arrayOf(ApiResponse(code = 404, message = "Not Found"), ApiResponse(code = 400, message = "No Name Provided"))) - fun findByName(@PathVariable("userName") userName: String): Result<*> { - val adminModel = service.findAdminUserByUserName(userName) - return Result(adminModel) - } - - - /** - * 修改密码 - * - * @return model - * @throws UserNotFoundException UserNotFoundException - */ - @RequestMapping(value = "changePassword", method = arrayOf(RequestMethod.POST)) - @ApiOperation(value = "修改用户密码", notes = "传来模型验证并修改密码", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @ApiResponses(value = *arrayOf(ApiResponse(code = 404, message = "Not Found"), ApiResponse(code = 400, message = "No Name Provided"))) - @Throws(UserNotFoundException::class) - fun changePassword(@RequestBody model: AdminModel): Result<*> { - val adminModel = service.findAdminUserByUserName(model.userName!!) - val salt = RandomUtil.createSalt() - adminModel.salt = salt - adminModel.password = Md5Util.encode(model.password!!, salt) - service.updateAdminUser(adminModel) - return Result(adminModel) - } - - /** - * 根据id删除数据 - * - * @param id id - * @return model - * @throws UserNotFoundException UserNotFoundException - */ - @RequestMapping(value = "delete/{id}", method = arrayOf(RequestMethod.GET)) - @ApiOperation(value = "删除用户", notes = "根据传入的id删除对应的用户", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @ApiImplicitParams(ApiImplicitParam(name = "id", value = "用户唯一id", required = true, dataType = "Long", paramType = "path")) - @ApiResponses(value = *arrayOf(ApiResponse(code = 404, message = "Not Found"), ApiResponse(code = 400, message = "No Name Provided"))) - @Throws(UserNotFoundException::class) - fun deleteUserById(@PathVariable("id") id: Long?): Result<*> { - val adminModel = service.findAdminUserById(id) - service.deleteAdminUserById(id) - return Result(adminModel) - } - - /** - * 更新 - * - * @param userName userName - * @return model - * @throws UserNotFoundException UserNotFoundException - */ - @RequestMapping(value = "update/{userName}", method = arrayOf(RequestMethod.POST)) - @ApiOperation(value = "更新用户信息", notes = "根据传入的模型更新用户信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @ApiImplicitParams(ApiImplicitParam(name = "userName", value = "用户名", required = true, dataType = "String", paramType = "path")) - @ApiResponses(value = *arrayOf(ApiResponse(code = 404, message = "Not Found"), ApiResponse(code = 400, message = "No Name Provided"))) - @Throws(UserNotFoundException::class) - fun update(@PathVariable("userName") userName: String): Result<*>? { - val adminModel = service.findAdminUserByUserName(userName) - adminModel.userName = userName - service.updateAdminUser(adminModel) - return Result(adminModel) - } - - /** - * 封号 - * - * @param id id - * @return model - * @throws UserNotFoundException UserNotFoundException - */ - @RequestMapping(value = "forbid/{id}", method = arrayOf(RequestMethod.GET)) - @ApiOperation(value = "封号", notes = "根据传入的id对修改对应帐号状态", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @ApiImplicitParams(ApiImplicitParam(name = "id", value = "后台用户唯一id", required = true, dataType = "Long", paramType = "path")) - @ApiResponses(value = *arrayOf(ApiResponse(code = 404, message = "Not Found"), ApiResponse(code = 400, message = "No Name Provided"))) - @Throws(UserNotFoundException::class) - fun forbid(@PathVariable("id") id: Long?): Result<*> { - var model: AdminModel? - model = service.forbidAdminUserById(id) - return Result(model) - } -} - diff --git a/website/src/main/java/info/xiaomo/website/controller/ChangeLogController.java b/website/src/main/java/info/xiaomo/website/controller/ChangeLogController.java new file mode 100644 index 00000000..86452ba6 --- /dev/null +++ b/website/src/main/java/info/xiaomo/website/controller/ChangeLogController.java @@ -0,0 +1,224 @@ +package info.xiaomo.website.controller; + +import info.xiaomo.core.base.BaseController; +import info.xiaomo.core.base.Result; +import info.xiaomo.core.constant.CodeConst; +import info.xiaomo.website.model.ChangeLogModel; +import info.xiaomo.website.service.ChangeLogService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/4/1117:40 + * Description: 更新日志控制器 + * Copyright(©) 2015 by xiaomo. + **/ +@RestController +@RequestMapping("/changeLog") +@Api(value = "更新日志相关api", description = "更新日志相关api") +public class ChangeLogController extends BaseController { + + private final ChangeLogService service; + + @Autowired + public ChangeLogController(ChangeLogService service) { + this.service = service; + } + + /** + * 通过id查找 + * + * @param id id + * @return model + */ + @Override + @RequestMapping(value = "findById/{id}", method = RequestMethod.GET) + @ApiOperation(value = "通过id查找", notes = "通过id查找", httpMethod = "GET") + @ApiImplicitParams({ + @ApiImplicitParam(name = "id", value = "唯一id", required = true, dataType = "Long", paramType = "path") + }) + public Result findById(@PathVariable("id") Long id) { + ChangeLogModel changeLogModel = service.findById(id); + if (changeLogModel == null) { + return new Result<>(CodeConst.NULL_DATA.getResultCode(), CodeConst.NULL_DATA.getMessage()); + } + return new Result<>(changeLogModel); + } + + /** + * findByName + * + * @return result + */ + @Override + @RequestMapping(value = "findByName/{name}", method = RequestMethod.GET) + @ApiOperation(value = "通过名字查找", notes = "通过名字查找", httpMethod = "GET") + @ApiImplicitParams({ + @ApiImplicitParam(name = "name", value = "更新日志内容", required = true, dataType = "String", paramType = "path") + }) + public Result findByName(@PathVariable("name") String name) { + ChangeLogModel model = service.findByName(name); + if (model == null) { + return new Result<>(CodeConst.NULL_DATA.getResultCode(), CodeConst.NULL_DATA.getMessage()); + } + return new Result<>(model); + } + + /** + * 根据名字删除模型 + * + * @param name name + * @return result + */ + @Override + public Result delByName(@PathVariable String name) { + return null; + } + + /** + * 根据id删除模型 + * + * @param id id + * @return result + */ + @Override + public Result delById(@PathVariable Long id) { + return null; + } + + /** + * 添加模型 + * + * @param model model + * @return result + */ + @Override + public Result add(@RequestBody Object model) { + return null; + } + + /** + * 更新 + * + * @param model model + * @return result + */ + @Override + public Result update(@RequestBody Object model) { + return null; + } + + /** + * 批量删除 + * + * @param ids ids + * @return result + */ + @Override + public Result delByIds(@PathVariable List ids) { + return null; + } + + /** + * 分页查询更新日志 + * + * @return 分页 + */ + @Override + @RequestMapping(value = "findAll", method = RequestMethod.GET) + @ApiOperation(value = "分页查询更新日志", notes = "分页查询更新日志", httpMethod = "GET") + public Result findAll() { + List pages = service.findAll(); + if (pages == null || pages.size() <= 0) { + return new Result<>(CodeConst.NULL_DATA.getResultCode(), CodeConst.NULL_DATA.getMessage()); + } + return new Result<>(pages); + } + + /** + * 带分页 + * + * @param start 起始页 + * @param pageSize 页码数 + * @return result + */ + @Override + public Result findAll(@PathVariable int start, @PathVariable int pageSize) { + return null; + } + + /** + * 增加更新日志 + * + * @return result + */ + @ApiOperation(value = "增加更新日志", notes = "增加更新日志", httpMethod = "POST") + @RequestMapping(value = "add", method = RequestMethod.POST) + public Result add(@RequestBody ChangeLogModel model) { + ChangeLogModel changeLogModel = service.findByName(model.getName()); + if (changeLogModel != null) { + return new Result<>(CodeConst.REPEAT.getResultCode(), CodeConst.REPEAT.getMessage()); + } + changeLogModel = new ChangeLogModel(); + changeLogModel.setName(model.getName()); + changeLogModel.setOnlineTime(model.getOnlineTime()); + ChangeLogModel addModel = service.add(changeLogModel); + return new Result<>(addModel); + } + + + /** + * 修改更新日志 + * + * @return result + */ + @ApiOperation(value = "修改更新日志", notes = "修改更新日志", httpMethod = "POST") + @RequestMapping(value = "update", method = RequestMethod.POST) + public Result update(@RequestBody ChangeLogModel model) { + ChangeLogModel changeLogModel = service.findByName(model.getName()); + if (changeLogModel == null) { + return new Result<>(CodeConst.NULL_DATA.getResultCode(), CodeConst.NULL_DATA.getMessage()); + } + changeLogModel.setName(model.getName()); + changeLogModel.setOnlineTime(model.getOnlineTime()); + ChangeLogModel updateModel = service.update(changeLogModel); + return new Result<>(updateModel); + } + + + /** + * 删除更新日志 + */ + @RequestMapping(value = "delete/{id}", method = RequestMethod.GET) + @ApiOperation(value = "删除更新日志", notes = "删除更新日志", httpMethod = "GET") + @ApiImplicitParams({ + @ApiImplicitParam(name = "id", value = "唯一id", required = true, dataType = "Long", paramType = "path") + }) + public Result deleteById(@PathVariable("id") Long id) { + ChangeLogModel changeLogModel = service.findById(id); + if (changeLogModel == null) { + return new Result<>(CodeConst.NULL_DATA.getResultCode(), CodeConst.NULL_DATA.getMessage()); + } + ChangeLogModel delModel = service.delete(id); + return new Result<>(delModel); + } + + +} diff --git a/website/src/main/java/info/xiaomo/website/controller/ChangeLogController.kt b/website/src/main/java/info/xiaomo/website/controller/ChangeLogController.kt deleted file mode 100644 index bdaf7f05..00000000 --- a/website/src/main/java/info/xiaomo/website/controller/ChangeLogController.kt +++ /dev/null @@ -1,127 +0,0 @@ -package info.xiaomo.website.controller - -import info.xiaomo.core.base.Result -import info.xiaomo.core.constant.CodeConst -import info.xiaomo.website.model.ChangeLogModel -import info.xiaomo.website.service.ChangeLogService -import io.swagger.annotations.Api -import io.swagger.annotations.ApiImplicitParam -import io.swagger.annotations.ApiImplicitParams -import io.swagger.annotations.ApiOperation -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.http.MediaType -import org.springframework.web.bind.annotation.* - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * - * Date: 2016/4/1117:40 - * Description: 更新日志控制器 - * Copyright(©) 2015 by xiaomo. - */ -@RestController -@RequestMapping("/changeLog") -@Api(value = "更新日志相关api", description = "更新日志相关api") -class ChangeLogController @Autowired -constructor(private val service: ChangeLogService) { - - /** - * 通过id查找 - * - * @param id id - * @return model - */ - @RequestMapping(value = "findById/{id}", method = arrayOf(RequestMethod.GET)) - @ApiOperation(value = "通过id查找", notes = "通过id查找", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @ApiImplicitParams(ApiImplicitParam(name = "id", value = "唯一id", required = true, dataType = "Long", paramType = "path")) - fun findById(@PathVariable("id") id: Long?): Result<*> { - val changeLogModel = service.findById(id) - return Result(changeLogModel) - } - - /** - * findByName - * - * @return result - */ - @RequestMapping(value = "findByName/{name}", method = arrayOf(RequestMethod.GET)) - @ApiOperation(value = "通过名字查找", notes = "通过名字查找", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @ApiImplicitParams(ApiImplicitParam(name = "name", value = "更新日志内容", required = true, dataType = "String", paramType = "path")) - fun findByName(@PathVariable("name") name: String): Result<*> { - val model = service.findByName(name) - return Result(model) - } - - - /** - * 分页查询更新日志 - * - * @return 分页 - */ - @RequestMapping(value = "findAll", method = arrayOf(RequestMethod.GET)) - @ApiOperation(value = "分页查询更新日志", notes = "分页查询更新日志", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - fun findAll(): Result<*> { - val pages = service.findAll() - return if (pages.isEmpty()) { - Result(CodeConst.NULL_DATA.resultCode, CodeConst.NULL_DATA.message!!) - } else Result(pages) - } - - /** - * 增加更新日志 - * - * @return result - */ - @ApiOperation(value = "增加更新日志", notes = "增加更新日志", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @RequestMapping(value = "add", method = arrayOf(RequestMethod.POST)) - fun add(@RequestBody model: ChangeLogModel): Result<*> { - var changeLogModel: ChangeLogModel? = service.findByName(model.name!!) - if (changeLogModel != null) { - return Result(CodeConst.REPEAT.resultCode, CodeConst.REPEAT.message!!) - } - changeLogModel = ChangeLogModel() - changeLogModel.name = model.name - changeLogModel.onlineTime = model.onlineTime - val addModel = service.add(changeLogModel) - return Result(addModel) - } - - - /** - * 修改更新日志 - * - * @return result - */ - @ApiOperation(value = "修改更新日志", notes = "修改更新日志", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @RequestMapping(value = "update", method = arrayOf(RequestMethod.POST)) - fun update(@RequestBody model: ChangeLogModel): Result<*> { - val changeLogModel = service.findByName(model.name!!) - changeLogModel.name = model.name - changeLogModel.onlineTime = model.onlineTime - val updateModel = service.update(changeLogModel) - return Result(updateModel) - } - - - /** - * 删除更新日志 - */ - @RequestMapping(value = "delete/{id}", method = arrayOf(RequestMethod.GET)) - @ApiOperation(value = "删除更新日志", notes = "删除更新日志", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @ApiImplicitParams(ApiImplicitParam(name = "id", value = "唯一id", required = true, dataType = "Long", paramType = "path")) - fun deleteById(@PathVariable("id") id: Long?): Result<*> { - service.findById(id) - val delModel = service.delete(id) - return Result(delModel) - } - - -} diff --git a/website/src/main/java/info/xiaomo/website/controller/LinkController.java b/website/src/main/java/info/xiaomo/website/controller/LinkController.java new file mode 100644 index 00000000..1afd6385 --- /dev/null +++ b/website/src/main/java/info/xiaomo/website/controller/LinkController.java @@ -0,0 +1,235 @@ +package info.xiaomo.website.controller; + +import info.xiaomo.core.base.BaseController; +import info.xiaomo.core.base.Result; +import info.xiaomo.core.constant.CodeConst; +import info.xiaomo.website.model.LinkModel; +import info.xiaomo.website.service.LinkService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/4/1119:55 + * Description: 友情连接控制器 + * Copyright(©) 2015 by xiaomo. + **/ +@RestController +@RequestMapping("/link") +@Api(value = "友情链接相关api", description = "友情链接相关api") +public class LinkController extends BaseController { + + private final LinkService service; + + @Autowired + public LinkController(LinkService service) { + this.service = service; + } + + /** + * 根据id查找 + * + * @param id id + * @return model + */ + @RequestMapping(value = "findById/{id}", method = RequestMethod.GET) + @ApiOperation(value = "通过id查找", notes = "通过id查找", httpMethod = "GET") + @ApiImplicitParams({ + @ApiImplicitParam(name = "id", value = "唯一id", required = true, dataType = "Long", paramType = "path") + }) + public Result findLinkById(@PathVariable("id") Long id) { + LinkModel model = service.findById(id); + if (model == null) { + return new Result<>(CodeConst.NULL_DATA.getResultCode(), CodeConst.NULL_DATA.getMessage()); + } + return new Result<>(model); + } + + /** + * 根据名字查找 + * + * @param name name + * @return model + */ + @Override + @RequestMapping(value = "findByName/{name}", method = RequestMethod.GET) + @ApiOperation(value = "根据名字查找", notes = "根据名字查找", httpMethod = "GET") + @ApiImplicitParams({ + @ApiImplicitParam(name = "name", value = "友情链接名字", required = true, dataType = "String", paramType = "path") + }) + public Result findByName(@PathVariable("name") String name) { + LinkModel model = service.findByName(name); + if (model == null) { + return new Result<>(CodeConst.NULL_DATA.getResultCode(), CodeConst.NULL_DATA.getMessage()); + } + return new Result<>(model); + } + + /** + * 根据名字删除模型 + * + * @param name name + * @return result + */ + @Override + public Result delByName(@PathVariable String name) { + return null; + } + + /** + * 根据id删除模型 + * + * @param id id + * @return result + */ + @Override + public Result delById(@PathVariable Long id) { + return null; + } + + /** + * 添加模型 + * + * @param model model + * @return result + */ + @Override + public Result add(@RequestBody Object model) { + return null; + } + + /** + * 更新 + * + * @param model model + * @return result + */ + @Override + public Result update(@RequestBody Object model) { + return null; + } + + /** + * 批量删除 + * + * @param ids ids + * @return result + */ + @Override + public Result delByIds(@PathVariable List ids) { + return null; + } + + + /** + * 返回所有数据 + * + * @return 所有 + */ + @Override + @RequestMapping(value = "findAll", method = RequestMethod.GET) + @ApiOperation(value = "返回所有数据", notes = "返回所有数据", httpMethod = "GET") + public Result findAll() { + List pages = service.findAll(); + if (pages == null || pages.size() == 0) { + return new Result<>(CodeConst.NULL_DATA.getResultCode(), CodeConst.NULL_DATA.getMessage()); + } + return new Result<>(pages); + } + + /** + * 带分页 + * + * @param start 起始页 + * @param pageSize 页码数 + * @return result + */ + @Override + public Result findAll(@PathVariable int start, @PathVariable int pageSize) { + return null; + } + + /** + * 根据id查看模型 + * + * @param id id + * @return result + */ + @Override + public Result findById(@PathVariable Long id) { + return null; + } + + /** + * 添加链接 + * + * @return model + */ + @RequestMapping(value = "add", method = RequestMethod.POST) + @ApiOperation(value = "添加链接", notes = "添加链接", httpMethod = "POST") + public Result add(@RequestBody LinkModel model) { + LinkModel linkModel = service.findByName(model.getName()); + if (linkModel != null) { + return new Result<>(CodeConst.REPEAT.getResultCode(), CodeConst.REPEAT.getMessage()); + } + linkModel = new LinkModel(); + linkModel.setName(model.getName()); + linkModel.setUrl(model.getUrl()); + LinkModel addModel = service.add(linkModel); + return new Result<>(addModel); + } + + /** + * 更新链接 + * + * @return model + */ + @ApiOperation(value = "更新链接", notes = "更新链接", httpMethod = "POST") + @RequestMapping(value = "update", method = RequestMethod.POST) + public Result update(@RequestBody LinkModel model) { + LinkModel linkModel = service.findById(model.getId()); + if (linkModel == null) { + return new Result<>(CodeConst.NULL_DATA.getResultCode(), CodeConst.NULL_DATA.getMessage()); + } + linkModel.setName(model.getName()); + linkModel.setUrl(model.getUrl()); + LinkModel updateModel = service.update(linkModel); + return new Result<>(updateModel); + } + + /** + * 删除链接 + * + * @param id id + * @return model + */ + @RequestMapping(value = "delete/{id}", method = RequestMethod.GET) + @ApiOperation(value = "删除链接", notes = "删除链接", httpMethod = "GET") + @ApiImplicitParams({ + @ApiImplicitParam(name = "id", value = "唯一id", required = true, dataType = "Long", paramType = "path") + }) + public Result delete(@PathVariable("id") Long id) { + LinkModel linkmodel = service.findById(id); + if (linkmodel == null) { + return new Result<>(CodeConst.NULL_DATA.getResultCode(), CodeConst.NULL_DATA.getMessage()); + } + LinkModel delModel = service.delete(id); + return new Result<>(delModel); + } +} diff --git a/website/src/main/java/info/xiaomo/website/controller/LinkController.kt b/website/src/main/java/info/xiaomo/website/controller/LinkController.kt deleted file mode 100644 index 058a3c8d..00000000 --- a/website/src/main/java/info/xiaomo/website/controller/LinkController.kt +++ /dev/null @@ -1,125 +0,0 @@ -package info.xiaomo.website.controller - -import info.xiaomo.core.base.Result -import info.xiaomo.core.constant.CodeConst -import info.xiaomo.website.model.LinkModel -import info.xiaomo.website.service.LinkService -import io.swagger.annotations.Api -import io.swagger.annotations.ApiImplicitParam -import io.swagger.annotations.ApiImplicitParams -import io.swagger.annotations.ApiOperation -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.http.MediaType -import org.springframework.web.bind.annotation.* - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/4/1119:55 - * Description: 友情连接控制器 - * Copyright(©) 2015 by xiaomo. - */ -@RestController -@RequestMapping("/link") -@Api(value = "友情链接相关api", description = "友情链接相关api") -class LinkController @Autowired -constructor(private val service: LinkService) { - - /** - * 根据id查找 - * - * @param id id - * @return model - */ - @RequestMapping(value = "findById/{id}", method = arrayOf(RequestMethod.GET)) - @ApiOperation(value = "通过id查找", notes = "通过id查找", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @ApiImplicitParams(ApiImplicitParam(name = "id", value = "唯一id", required = true, dataType = "Long", paramType = "path")) - fun findLinkById(@PathVariable("id") id: Long?): Result<*> { - val model = service.findById(id) - return Result(model) - } - - /** - * 根据名字查找 - * - * @param name name - * @return model - */ - @RequestMapping(value = "findByName/{name}", method = arrayOf(RequestMethod.GET)) - @ApiOperation(value = "根据名字查找", notes = "根据名字查找", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @ApiImplicitParams(ApiImplicitParam(name = "name", value = "友情链接名字", required = true, dataType = "String", paramType = "path")) - fun findByName(@PathVariable("name") name: String): Result<*> { - val model = service.findByName(name) - return Result(model) - } - - - /** - * 返回所有数据 - * - * @return 所有 - */ - @RequestMapping(value = "findAll", method = arrayOf(RequestMethod.GET)) - @ApiOperation(value = "返回所有数据", notes = "返回所有数据", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - fun findAll(): Result<*> { - val pages = service.findAll() - return if (pages.isEmpty()) { - Result(CodeConst.NULL_DATA.resultCode, CodeConst.NULL_DATA.message!!) - } else Result(pages) - } - - /** - * 添加链接 - * - * @return model - */ - @RequestMapping(value = "add", method = arrayOf(RequestMethod.POST)) - @ApiOperation(value = "添加链接", notes = "添加链接", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - fun add(@RequestBody model: LinkModel): Result<*> { - var linkModel: LinkModel? = service.findByName(model.name!!) - if (linkModel != null) { - return Result(CodeConst.REPEAT.resultCode, CodeConst.REPEAT.message!!) - } - linkModel = LinkModel() - linkModel.name = model.name - linkModel.url = model.url - val addModel = service.add(linkModel) - return Result(addModel) - } - - /** - * 更新链接 - * - * @return model - */ - @ApiOperation(value = "更新链接", notes = "更新链接", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @RequestMapping(value = "update", method = arrayOf(RequestMethod.POST)) - fun update(@RequestBody model: LinkModel): Result<*> { - val linkModel = service.findById(model.id) - linkModel.name = model.name - linkModel.url = model.url - val updateModel = service.update(linkModel) - return Result(updateModel) - } - - /** - * 删除链接 - * - * @param id id - * @return model - */ - @RequestMapping(value = "delete/{id}", method = arrayOf(RequestMethod.GET)) - @ApiOperation(value = "删除链接", notes = "删除链接", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @ApiImplicitParams(ApiImplicitParam(name = "id", value = "唯一id", required = true, dataType = "Long", paramType = "path")) - fun delete(@PathVariable("id") id: Long?): Result<*> { - val delModel = service.delete(id) - return Result(delModel) - } -} diff --git a/website/src/main/java/info/xiaomo/website/controller/MailController.java b/website/src/main/java/info/xiaomo/website/controller/MailController.java new file mode 100644 index 00000000..412496d3 --- /dev/null +++ b/website/src/main/java/info/xiaomo/website/controller/MailController.java @@ -0,0 +1,32 @@ +package info.xiaomo.website.controller; + +import info.xiaomo.website.util.MailUtil; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/11/14 11:06 + * Description: 用户实体类 + * Copyright(©) 2015 by xiaomo. + **/ + +@RestController +@RequestMapping("/mail") +public class MailController { + + @RequestMapping(value = "/send", method = RequestMethod.GET) + public boolean sendMail() { + return MailUtil.send("hupengbest@163.com", "测试邮件是否正常", "测试"); + } + +} diff --git a/website/src/main/java/info/xiaomo/website/controller/MailController.kt b/website/src/main/java/info/xiaomo/website/controller/MailController.kt deleted file mode 100644 index ba3530e2..00000000 --- a/website/src/main/java/info/xiaomo/website/controller/MailController.kt +++ /dev/null @@ -1,33 +0,0 @@ -package info.xiaomo.website.controller - -import info.xiaomo.core.untils.MailUtil -import org.springframework.web.bind.annotation.RequestMapping -import org.springframework.web.bind.annotation.RequestMethod -import org.springframework.web.bind.annotation.RestController - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * - * Date: 2016/11/14 11:06 - * Description: 用户实体类 - * Copyright(©) 2015 by xiaomo. - */ - -@RestController -@RequestMapping("/mail") -class MailController { - - @RequestMapping(value = "/send", method = arrayOf(RequestMethod.GET)) - fun sendMail() { - return MailUtil.send("hupengbest@163.com", "测试邮件是否正常", "测试") - } - -} diff --git a/website/src/main/java/info/xiaomo/website/controller/TechnologyController.java b/website/src/main/java/info/xiaomo/website/controller/TechnologyController.java new file mode 100644 index 00000000..46601a9a --- /dev/null +++ b/website/src/main/java/info/xiaomo/website/controller/TechnologyController.java @@ -0,0 +1,190 @@ +package info.xiaomo.website.controller; + +import info.xiaomo.core.base.BaseController; +import info.xiaomo.core.base.Result; +import info.xiaomo.core.constant.CodeConst; +import info.xiaomo.website.model.TechnologyModel; +import info.xiaomo.website.service.TechnologyService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/11/3 14:36 + * Description: 用户实体类 + * Copyright(©) 2015 by xiaomo. + **/ + + +@RestController +@RequestMapping("/technology") +@Api(value = "技术中心相关api", description = "技术中心相关api") +public class TechnologyController extends BaseController { + private final TechnologyService service; + + @Autowired + public TechnologyController(TechnologyService service) { + this.service = service; + } + + + @Override + @ApiOperation(value = "根据id查找技术", notes = "根据id查找技术", httpMethod = "GET") + @RequestMapping(value = "/findById/{id}", method = RequestMethod.GET) + @ApiImplicitParams({ + @ApiImplicitParam(name = "id", value = "唯一Id", required = true, dataType = "Long", paramType = "path") + }) + public Result findById(@PathVariable Long id) { + TechnologyModel model = service.findById(id); + if (model == null) { + return new Result<>(CodeConst.NULL_DATA.getResultCode(), CodeConst.NULL_DATA.getMessage()); + } + return new Result<>(model); + } + + @Override + @ApiOperation(value = "根据名字查找技术", notes = "根据名字查找技术", httpMethod = "GET") + @RequestMapping(value = "/findByName/{name}", method = RequestMethod.GET) + @ApiImplicitParams({ + @ApiImplicitParam(name = "name", value = "技术名字", required = true, dataType = "name", paramType = "path") + }) + public Result findByName(@PathVariable String name) { + TechnologyModel model = service.findByName(name); + if (model == null) { + return new Result<>(CodeConst.NULL_DATA.getResultCode(), CodeConst.NULL_DATA.getMessage()); + } + return new Result<>(model); + } + + /** + * 根据名字删除模型 + * + * @param name name + * @return result + */ + @Override + public Result delByName(@PathVariable String name) { + return null; + } + + /** + * 根据id删除模型 + * + * @param id id + * @return result + */ + @Override + public Result delById(@PathVariable Long id) { + return null; + } + + /** + * 添加模型 + * + * @param model model + * @return result + */ + @Override + public Result add(@RequestBody Object model) { + return null; + } + + /** + * 更新 + * + * @param model model + * @return result + */ + @Override + public Result update(@RequestBody Object model) { + return null; + } + + /** + * 批量删除 + * + * @param ids ids + * @return result + */ + @Override + public Result delByIds(@PathVariable List ids) { + return null; + } + + @Override + @ApiOperation(value = "查找所有", notes = "查找所有", httpMethod = "GET") + @RequestMapping(value = "/findAll", method = RequestMethod.GET) + public Result findAll() { + List all = service.findAll(); + if (all == null || all.isEmpty()) { + return new Result<>(CodeConst.NULL_DATA.getResultCode(), CodeConst.NULL_DATA.getMessage()); + } + return new Result<>(all); + } + + /** + * 带分页 + * + * @param start 起始页 + * @param pageSize 页码数 + * @return result + */ + @Override + public Result findAll(@PathVariable int start, @PathVariable int pageSize) { + return null; + } + + + @ApiOperation(value = "添加链接", notes = "添加链接", httpMethod = "POST") + @RequestMapping(value = "/add", method = RequestMethod.POST) + public Result add(@RequestBody TechnologyModel model) { + TechnologyModel addModel = service.findByName(model.getName()); + if (addModel != null) { + return new Result<>(CodeConst.REPEAT.getResultCode(), CodeConst.REPEAT.getMessage()); + } + addModel = service.add(model); + return new Result<>(addModel); + } + + @ApiOperation(value = "更新链接", notes = "更新链接", httpMethod = "POST") + @RequestMapping(value = "/update", method = RequestMethod.POST) + public Result update(@RequestBody TechnologyModel model) { + TechnologyModel update = service.findById(model.getId()); + if (update == null) { + return new Result<>(CodeConst.CodeOR.getResultCode(), CodeConst.CodeOR.getMessage()); + } + update = service.update(model); + return new Result<>(update); + } + + + @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET) + @ApiOperation(value = "删除链接", notes = "删除链接", httpMethod = "GET") + @ApiImplicitParams({ + @ApiImplicitParam(name = "id", value = "唯一id", required = true, dataType = "Long", paramType = "path") + }) + public Result delete(@PathVariable Long id) { + TechnologyModel model = service.findById(id); + if (model == null) { + return new Result<>(CodeConst.NULL_DATA.getResultCode(), CodeConst.NULL_DATA.getMessage()); + } + service.del(id); + return new Result<>(model); + } + +} diff --git a/website/src/main/java/info/xiaomo/website/controller/TechnologyController.kt b/website/src/main/java/info/xiaomo/website/controller/TechnologyController.kt deleted file mode 100644 index 3aac8b04..00000000 --- a/website/src/main/java/info/xiaomo/website/controller/TechnologyController.kt +++ /dev/null @@ -1,107 +0,0 @@ -package info.xiaomo.website.controller - -import info.xiaomo.core.base.Result -import info.xiaomo.core.constant.CodeConst -import info.xiaomo.website.model.TechnologyModel -import info.xiaomo.website.service.TechnologyService -import io.swagger.annotations.Api -import io.swagger.annotations.ApiImplicitParam -import io.swagger.annotations.ApiImplicitParams -import io.swagger.annotations.ApiOperation -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.data.domain.Page -import org.springframework.http.MediaType -import org.springframework.web.bind.annotation.* - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * - * Date: 2016/11/3 14:36 - * Description: 用户实体类 - * Copyright(©) 2015 by xiaomo. - */ - - -@RestController -@RequestMapping("/technology") -@Api(value = "技术中心相关api", description = "技术中心相关api") -class TechnologyController @Autowired -constructor(private val service: TechnologyService) { - - - @ApiOperation(value = "根据id查找技术", notes = "根据id查找技术", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @RequestMapping(value = "/findById/{id}", method = arrayOf(RequestMethod.GET)) - @ApiImplicitParams(ApiImplicitParam(name = "id", value = "唯一Id", required = true, dataType = "Long", paramType = "path")) - fun findById(@PathVariable id: Long?): Result<*> { - val model = service.findById(id) - return Result(model) - } - - @ApiOperation(value = "根据名字查找技术", notes = "根据名字查找技术", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @RequestMapping(value = "/findByName/{name}", method = arrayOf(RequestMethod.GET)) - @ApiImplicitParams(ApiImplicitParam(name = "name", value = "技术名字", required = true, dataType = "name", paramType = "path")) - fun findByName(@PathVariable name: String): Result<*> { - val model = service.findByName(name) - return Result(model) - } - - - @ApiOperation(value = "查找所有", notes = "查找所有", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @RequestMapping(value = "/findAll", method = arrayOf(RequestMethod.GET)) - fun findAll(): Result<*> { - val all = service.findAll() - return if (all.isEmpty()) { - Result(CodeConst.NULL_DATA.resultCode, CodeConst.NULL_DATA.message!!) - } else Result(all) - } - - /** - * 带分页 - * - * @param start 起始页 - * @param pageSize 页码数 - * @return result - */ - fun findAll(@PathVariable start: Int, @PathVariable pageSize: Int): Result>? { - return null - } - - - @ApiOperation(value = "添加链接", notes = "添加链接", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @RequestMapping(value = "/add", method = arrayOf(RequestMethod.POST)) - fun add(@RequestBody model: TechnologyModel): Result<*> { - var addModel: TechnologyModel? = service.findByName(model.name!!) - if (addModel != null) { - return Result(CodeConst.REPEAT.resultCode, CodeConst.REPEAT.message!!) - } - addModel = service.add(model) - return Result(addModel) - } - - @ApiOperation(value = "更新链接", notes = "更新链接", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @RequestMapping(value = "/update", method = arrayOf(RequestMethod.POST)) - fun update(@RequestBody model: TechnologyModel): Result<*> { - val update: TechnologyModel? - update = service.update(model) - return Result(update) - } - - - @RequestMapping(value = "/delete/{id}", method = arrayOf(RequestMethod.GET)) - @ApiOperation(value = "删除链接", notes = "删除链接", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @ApiImplicitParams(ApiImplicitParam(name = "id", value = "唯一id", required = true, dataType = "Long", paramType = "path")) - fun delete(@PathVariable id: Long?): Result<*> { - val model = service.findById(id) - service.del(id) - return Result(model) - } - -} diff --git a/website/src/main/java/info/xiaomo/website/controller/UserController.java b/website/src/main/java/info/xiaomo/website/controller/UserController.java new file mode 100644 index 00000000..5a4ca6d9 --- /dev/null +++ b/website/src/main/java/info/xiaomo/website/controller/UserController.java @@ -0,0 +1,347 @@ +package info.xiaomo.website.controller; + +import info.xiaomo.core.base.BaseController; +import info.xiaomo.core.base.Result; +import info.xiaomo.core.constant.CodeConst; +import info.xiaomo.core.constant.GenderConst; +import info.xiaomo.core.exception.UserNotFoundException; +import info.xiaomo.core.untils.MailUtil; +import info.xiaomo.core.untils.Md5Util; +import info.xiaomo.core.untils.RandomUtil; +import info.xiaomo.core.untils.TimeUtil; +import info.xiaomo.website.model.UserModel; +import info.xiaomo.website.service.UserService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; +import org.hibernate.service.spi.ServiceException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Optional; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/4/1 17:51 + * Description: 用户控制器 + * Copyright(©) 2015 by xiaomo. + **/ +@RestController +@RequestMapping("/user") +@Api(value = "用户相关api", description = "用户相关api") +public class UserController extends BaseController { + + private final UserService service; + + @Autowired + public UserController(UserService service) { + this.service = service; + } + + /** + * 根据id 查找用户 + * + * @param id id + * @return result + */ + @ApiOperation(value = "查找用户", notes = "查找用户", httpMethod = "GET") + @RequestMapping(value = "findById/{id}", method = RequestMethod.GET) + @ApiImplicitParams({ + @ApiImplicitParam(name = "id", value = "唯一id", required = true, dataType = "Long", paramType = "path"), + }) + @SuppressWarnings("unchecked") + public Result findUserById(@PathVariable("id") Long id) { + Optional optional = service.findUserById(id); + return optional.map(Result::new).orElseGet(() -> new Result<>(CodeConst.USER_NOT_FOUND.getResultCode(), CodeConst.USER_NOT_FOUND.getMessage())); + } + + /** + * 添加用户 + */ + @ApiOperation(value = "添加用户", notes = "添加用户", httpMethod = "POST") + @RequestMapping(value = "addUser", method = RequestMethod.POST) + public Result addUser(@RequestBody UserModel user) { + UserModel userModel = service.findUserByEmail(user.getEmail()); + if (userModel != null) { + return new Result<>(CodeConst.USER_REPEAT.getResultCode(), CodeConst.USER_REPEAT.getMessage()); + } + String salt = RandomUtil.createSalt(); + user.setPassword(Md5Util.encode(user.getPassword(), salt)); + user.setValidateCode(Md5Util.encode(user.getEmail(), "")); + user.setSalt(salt); + service.addUser(user); + return new Result<>(user); + } + + /** + * 注册 + * + * @return result + */ + @ApiOperation(value = "注册", notes = "注册用户并发送验证链接到邮箱", httpMethod = "POST") + @ApiImplicitParams({ + @ApiImplicitParam(name = "用户名", required = true, dataType = "String", paramType = "path"), + @ApiImplicitParam(name = "密码", required = true, dataType = "String", paramType = "path") + }) + @RequestMapping(value = "register/{email}/{password}", method = RequestMethod.POST) + public Result register(@PathVariable("email") String email, @PathVariable("password") String password) { + UserModel userModel = service.findUserByEmail(email); + //邮箱被占用 + if (userModel != null) { + return new Result<>(CodeConst.USER_REPEAT.getResultCode(), CodeConst.USER_REPEAT.getMessage()); + } + String redirectValidateUrl = MailUtil.redirectValidateUrl(email, password); + MailUtil.send(email, "帐号激活邮件", redirectValidateUrl); + return new Result<>(redirectValidateUrl); + } + + + /** + * 登录 + * + * @return result + */ + @ApiOperation(value = "登录", notes = "登录", httpMethod = "POST") + @ApiImplicitParams({ + @ApiImplicitParam(name = "email", value = "邮箱", required = true, dataType = "String", paramType = "path"), + @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String", paramType = "path") + }) + @RequestMapping(value = "login/{email}/{password}", method = RequestMethod.POST) + public Result login(@PathVariable("email") String email, @PathVariable("password") String password) { + UserModel userModel = service.findUserByEmail(email); + //找不到用户 + if (userModel == null) { + return new Result<>(CodeConst.USER_NOT_FOUND.getResultCode(), CodeConst.USER_NOT_FOUND.getMessage()); + } + //密码不正确 + if (!Md5Util.encode(password, userModel.getSalt()).equals(userModel.getPassword())) { + return new Result<>(CodeConst.AUTH_FAILED.getResultCode(), CodeConst.AUTH_FAILED.getMessage()); + } + return new Result<>(userModel); + } + + + /** + * 修改密码 + * + * @return model + * @throws UserNotFoundException UserNotFoundException + */ + @ApiOperation(value = "修改密码", notes = "修改密码", httpMethod = "POST") + @RequestMapping(value = "changePassword", method = RequestMethod.POST) + public Result changePassword(@RequestBody UserModel user) throws UserNotFoundException { + UserModel userByEmail = service.findUserByEmail(user.getEmail()); + if (userByEmail == null) { + return new Result<>(CodeConst.USER_NOT_FOUND.getResultCode(), CodeConst.USER_NOT_FOUND.getMessage()); + } + String salt = RandomUtil.createSalt(); + userByEmail.setPassword(Md5Util.encode(user.getPassword(), salt)); + userByEmail.setNickName(user.getNickName()); + userByEmail.setSalt(salt); + UserModel updateUser = service.updateUser(userByEmail); + return new Result<>(updateUser); + } + + /** + * 更新用户信息 + * + * @return model + * @throws UserNotFoundException UserNotFoundException + */ + @ApiOperation(value = "更新用户信息", notes = "更新用户信息", httpMethod = "POST") + @RequestMapping(value = "update", method = RequestMethod.POST) + public Result update(@RequestBody UserModel user) throws UserNotFoundException { + UserModel userModel = service.findUserByEmail(user.getEmail()); + if (userModel == null) { + return new Result<>(CodeConst.USER_NOT_FOUND.getResultCode(), CodeConst.USER_NOT_FOUND.getMessage()); + } + userModel = new UserModel(); + userModel.setEmail(user.getEmail()); + userModel.setNickName(user.getNickName()); + userModel.setPhone(user.getPhone()); + userModel.setAddress(user.getAddress()); + userModel.setGender(user.getGender()); + userModel.setValidateCode(Md5Util.encode(user.getEmail(), "")); + UserModel updateUser = service.updateUser(userModel); + return new Result<>(updateUser); + } + + /** + * 返回所有用户数据 + * + * @return result + */ + @ApiOperation(value = "返回所有用户数据", notes = "返回所有用户数据", httpMethod = "GET") + @RequestMapping(value = "findAll", method = RequestMethod.GET) + public Result getAll() { + List pages = service.findAll(); + if (pages == null || pages.size() <= 0) { + return new Result<>(CodeConst.NULL_DATA.getResultCode(), CodeConst.NULL_DATA.getMessage()); + } + return new Result<>(pages); + } + + + /** + * 根据id删除用户 + * + * @param id id + * @return result + */ + @RequestMapping(value = "delete/{id}", method = RequestMethod.GET) + @ApiOperation(value = "根据id删除用户", notes = "根据id删除用户", httpMethod = "GET") + @ApiImplicitParams({ + @ApiImplicitParam(name = "id", value = "唯一id", required = true, dataType = "Long", paramType = "path"), + }) + public Result deleteUserById(@PathVariable("id") Long id) throws UserNotFoundException { + UserModel userModel = service.deleteUserById(id); + if (userModel == null) { + return new Result<>(CodeConst.USER_NOT_FOUND.getResultCode(), CodeConst.USER_NOT_FOUND.getMessage()); + } + return new Result<>(userModel); + } + + /** + * 处理激活 + */ + @ApiOperation(value = "处理激活", notes = "处理激活", httpMethod = "POST") + @RequestMapping(value = "validateEmail", method = RequestMethod.POST) + public Result validateEmail(@RequestBody UserModel user + ) throws ServiceException { + //数据访问层,通过email获取用户信息 + UserModel userModel = service.findUserByEmail(user.getEmail()); + if (userModel != null) { + return new Result<>(CodeConst.USER_REPEAT.getResultCode(), CodeConst.USER_REPEAT.getMessage()); + } + //验证码是否过期 + if (user.getRegisterTime() + TimeUtil.ONE_DAY_IN_MILLISECONDS < TimeUtil.getNowOfMills()) { + LOGGER.info("用户{}使用己过期的激活码{}激活邮箱失败!", user.getEmail(), user.getEmail()); + return new Result<>(CodeConst.TIME_PASSED.getResultCode(), CodeConst.TIME_PASSED.getMessage()); + } + //激活 + String salt = RandomUtil.createSalt(); + userModel = new UserModel(); + userModel.setNickName(user.getNickName()); + userModel.setEmail(user.getEmail()); + userModel.setGender(GenderConst.SECRET); + userModel.setValidateCode(Md5Util.encode(user.getEmail(), salt)); + userModel.setPhone(0L); + userModel.setSalt(salt); + userModel.setAddress(""); + userModel.setPassword(Md5Util.encode(user.getPassword(), salt)); + userModel = service.addUser(userModel); + LOGGER.info("用户{}使用激活码{}激活邮箱成功!", userModel.getEmail(), userModel.getValidateCode()); + return new Result<>(userModel); + } + + /** + * 查找所有(不带分页) + * + * @return result + */ + @Override + public Result findAll() { + return null; + } + + /** + * 带分页 + * + * @param start 起始页 + * @param pageSize 页码数 + * @return result + */ + @Override + public Result findAll(@PathVariable int start, @PathVariable int pageSize) { + return null; + } + + /** + * 根据id查看模型 + * + * @param id id + * @return result + */ + @Override + public Result findById(@PathVariable Long id) { + return null; + } + + /** + * 根据名字查找模型 + * + * @param name name + * @return result + */ + @Override + public Result findByName(@PathVariable String name) { + return null; + } + + /** + * 根据名字删除模型 + * + * @param name name + * @return result + */ + @Override + public Result delByName(@PathVariable String name) { + return null; + } + + /** + * 根据id删除模型 + * + * @param id id + * @return result + */ + @Override + public Result delById(@PathVariable Long id) { + return null; + } + + /** + * 添加模型 + * + * @param model model + * @return result + */ + @Override + public Result add(@RequestBody Object model) { + return null; + } + + /** + * 更新 + * + * @param model model + * @return result + */ + @Override + public Result update(@RequestBody Object model) { + return null; + } + + /** + * 批量删除 + * + * @param ids ids + * @return result + */ + @Override + public Result delByIds(@PathVariable List ids) { + return null; + } +} diff --git a/website/src/main/java/info/xiaomo/website/controller/UserController.kt b/website/src/main/java/info/xiaomo/website/controller/UserController.kt deleted file mode 100644 index 84a43f55..00000000 --- a/website/src/main/java/info/xiaomo/website/controller/UserController.kt +++ /dev/null @@ -1,200 +0,0 @@ -package info.xiaomo.website.controller - -import info.xiaomo.core.base.Result -import info.xiaomo.core.constant.CodeConst -import info.xiaomo.core.constant.GenderConst -import info.xiaomo.core.exception.UserNotFoundException -import info.xiaomo.core.untils.MailUtil -import info.xiaomo.core.untils.Md5Util -import info.xiaomo.core.untils.RandomUtil -import info.xiaomo.core.untils.TimeUtil -import info.xiaomo.website.model.UserModel -import info.xiaomo.website.service.UserService -import io.swagger.annotations.Api -import io.swagger.annotations.ApiImplicitParam -import io.swagger.annotations.ApiImplicitParams -import io.swagger.annotations.ApiOperation -import org.hibernate.service.spi.ServiceException -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.http.MediaType -import org.springframework.web.bind.annotation.* -import java.text.ParseException - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * - * Date: 2016/4/1 17:51 - * Description: 用户控制器 - * Copyright(©) 2015 by xiaomo. - */ -@RestController -@RequestMapping("/user") -@Api(value = "用户相关api", description = "用户相关api") -class UserController @Autowired -constructor(private val service: UserService) { - - /** - * 根据id 查找用户 - * - * @param id id - * @return result - */ - @ApiOperation(value = "查找用户", notes = "查找用户", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @RequestMapping(value = "findById/{id}", method = arrayOf(RequestMethod.GET)) - @ApiImplicitParams(ApiImplicitParam(name = "id", value = "唯一id", required = true, dataType = "Long", paramType = "path")) - fun findUserById(@PathVariable("id") id: Long?): Result<*> { - val userModel = service.findUserById(id) - return Result(userModel) - } - - /** - * 添加用户 - */ - @ApiOperation(value = "添加用户", notes = "添加用户", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @RequestMapping(value = "addUser", method = arrayOf(RequestMethod.POST)) - fun addUser(@RequestBody user: UserModel): Result<*> { - val salt = RandomUtil.createSalt() - user.password = Md5Util.encode(user.password!!, salt) - user.validateCode = Md5Util.encode(user.email!!, "")!! - user.salt = salt - service.addUser(user) - return Result(user) - } - - /** - * 注册 - * - * @return result - */ - @ApiOperation(value = "注册", notes = "注册用户并发送验证链接到邮箱", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @ApiImplicitParams(ApiImplicitParam(name = "用户名", required = true, dataType = "String", paramType = "path"), ApiImplicitParam(name = "密码", required = true, dataType = "String", paramType = "path")) - @RequestMapping(value = "register/{email}/{password}", method = arrayOf(RequestMethod.POST)) - @Throws(Exception::class) - fun register(@PathVariable("email") email: String, @PathVariable("password") password: String): Result<*> { - val redirectValidateUrl = MailUtil.redirectValidateUrl(email, password) - MailUtil.send(email, "帐号激活邮件", redirectValidateUrl) - return Result(redirectValidateUrl) - } - - - /** - * 登录 - * - * @return result - */ - @ApiOperation(value = "登录", notes = "登录", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @ApiImplicitParams(ApiImplicitParam(name = "email", value = "邮箱", required = true, dataType = "String", paramType = "path"), ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String", paramType = "path")) - @RequestMapping(value = "login/{email}/{password}", method = arrayOf(RequestMethod.POST)) - fun login(@PathVariable("email") email: String, @PathVariable("password") password: String): Result<*> { - val userModel = service.findUserByEmail(email) - //找不到用户 - //密码不正确 - return if (Md5Util.encode(password, userModel.salt!!) != userModel.password) { - val result = Result(CodeConst.AUTH_FAILED.resultCode, CodeConst.AUTH_FAILED.message!!) - result - } else Result(userModel) - } - - - /** - * 修改密码 - * - * @return model - * @throws UserNotFoundException UserNotFoundException - */ - @ApiOperation(value = "修改密码", notes = "修改密码", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @RequestMapping(value = "changePassword", method = arrayOf(RequestMethod.POST)) - @Throws(UserNotFoundException::class) - fun changePassword(@RequestBody user: UserModel): Result<*> { - val userByEmail = service.findUserByEmail(user.email!!) - val salt = RandomUtil.createSalt() - userByEmail.password = Md5Util.encode(user.password!!, salt) - userByEmail.nickName = user.nickName - userByEmail.salt = salt - val updateUser = service.updateUser(userByEmail) - return Result(updateUser) - } - - /** - * 更新用户信息 - * - * @return model - * @throws UserNotFoundException UserNotFoundException - */ - @ApiOperation(value = "更新用户信息", notes = "更新用户信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @RequestMapping(value = "update", method = arrayOf(RequestMethod.POST)) - @Throws(UserNotFoundException::class) - fun update(@RequestBody user: UserModel): Result<*> { - val userModel: UserModel? - userModel = UserModel() - userModel.email = user.email - userModel.nickName = user.nickName - userModel.phone = user.phone - userModel.address = user.address - userModel.gender = user.gender - userModel.validateCode = Md5Util.encode(user.email!!, "")!! - val updateUser = service.updateUser(userModel) - return Result(updateUser) - } - - - /** - * 根据id删除用户 - * - * @param id id - * @return result - */ - @RequestMapping(value = "delete/{id}", method = arrayOf(RequestMethod.GET)) - @ApiOperation(value = "根据id删除用户", notes = "根据id删除用户", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @ApiImplicitParams(ApiImplicitParam(name = "id", value = "唯一id", required = true, dataType = "Long", paramType = "path")) - @Throws(UserNotFoundException::class) - fun deleteUserById(@PathVariable("id") id: Long?): Result<*> { - val userModel = service.deleteUserById(id) - return Result(userModel) - } - - /** - * 处理激活 - */ - @ApiOperation(value = "处理激活", notes = "处理激活", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @RequestMapping(value = "validateEmail", method = arrayOf(RequestMethod.POST)) - @Throws(ServiceException::class, ParseException::class, UserNotFoundException::class) - fun validateEmail(@RequestBody user: UserModel? - ): Result<*> { - if (user == null) { - return Result(CodeConst.NULL_DATA) - } - //数据访问层,通过email获取用户信息 - var userModel: UserModel? = service.findUserByEmail(user.email!!) - if (userModel != null) { - return Result(resultCode = CodeConst.USER_REPEAT.resultCode, message = CodeConst.USER_REPEAT.message!!) - } - //验证码是否过期 - val registerTime = user.registerTime - if (registerTime!! + TimeUtil.ONE_DAY_IN_MILLISECONDS < TimeUtil.nowOfMills) { - return Result(CodeConst.TIME_PASSED.resultCode, CodeConst.TIME_PASSED.message!!) - } - //激活 - val salt = RandomUtil.createSalt() - userModel = UserModel() - userModel.nickName = user.nickName - userModel.email = user.email - userModel.gender = GenderConst.SECRET - userModel.validateCode = Md5Util.encode(user.email!!, salt)!! - userModel.phone = 0L - userModel.salt = salt - userModel.address = "" - userModel.password = Md5Util.encode(user.password!!, salt) - userModel = service.addUser(userModel) - return Result(userModel) - } - -} diff --git a/website/src/main/java/info/xiaomo/website/controller/WorksController.java b/website/src/main/java/info/xiaomo/website/controller/WorksController.java new file mode 100644 index 00000000..9817f244 --- /dev/null +++ b/website/src/main/java/info/xiaomo/website/controller/WorksController.java @@ -0,0 +1,118 @@ +package info.xiaomo.website.controller; + +import info.xiaomo.core.base.Result; +import info.xiaomo.core.constant.CodeConst; +import info.xiaomo.website.model.WorksModel; +import info.xiaomo.website.service.WorksService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/11/3 14:36 + * Description: 用户实体类 + * Copyright(©) 2015 by xiaomo. + **/ + + +@RequestMapping("/works") +@RestController +@Api(value = "作品相关api") +public class WorksController { + + private final WorksService service; + + @Autowired + public WorksController(WorksService service) { + this.service = service; + } + + + @RequestMapping(value = "/findById/{id}", method = RequestMethod.GET) + @ApiOperation(value = "根据id查找作品", notes = "根据id查找作品", httpMethod = "GET") + @ApiImplicitParams({ + @ApiImplicitParam(name = "id", value = "唯一id", required = true, dataType = "Long", paramType = "path"), + }) + public Result findById(@PathVariable Long id) { + WorksModel model = service.findById(id); + if (model == null) { + return new Result<>(CodeConst.NULL_DATA.getResultCode(), CodeConst.NULL_DATA.getMessage()); + } + return new Result<>(model); + } + + @RequestMapping(value = "/findAll", method = RequestMethod.GET) + @ApiOperation(value = "查找所有", notes = "查找所有", httpMethod = "GET") + public Result> findAll() { + List all = service.findAll(); + if (all == null || all.isEmpty()) { + return new Result<>(CodeConst.NULL_DATA.getResultCode(), CodeConst.NULL_DATA.getMessage()); + } + return new Result<>(all); + } + + + @RequestMapping(value = "/findByName/{name}", method = RequestMethod.GET) + @ApiOperation(value = "根据名字查找作品", notes = "根据名字查找作品", httpMethod = "GET") + @ApiImplicitParams({ + @ApiImplicitParam(name = "name", value = "作品名字", required = true, dataType = "String", paramType = "path"), + }) + public Result findByName(@PathVariable String name) { + WorksModel model = service.findByName(name); + if (model == null) { + return new Result<>(CodeConst.NULL_DATA.getResultCode(), CodeConst.NULL_DATA.getMessage()); + } + return new Result<>(model); + } + + @ApiOperation(value = "添加作品", notes = "添加作品", httpMethod = "POST") + @RequestMapping(value = "/add", method = RequestMethod.POST) + public Result add(@RequestBody WorksModel model) { + WorksModel addModel = service.findByName(model.getName()); + if (addModel != null) { + return new Result<>(CodeConst.REPEAT.getResultCode(), CodeConst.REPEAT.getMessage()); + } + addModel = service.add(model); + return new Result<>(addModel); + } + + @ApiOperation(value = "更新作品", notes = "更新作品", httpMethod = "POST") + @RequestMapping(value = "/update", method = RequestMethod.POST) + public Result update(@RequestBody WorksModel model) { + WorksModel worksModel = service.findById(model.getId()); + if (worksModel == null) { + return new Result<>(CodeConst.CodeOR.getResultCode(), CodeConst.CodeOR.getMessage()); + } + worksModel = service.update(worksModel); + return new Result<>(worksModel); + } + + + @ApiOperation(value = "根据id删除作品", notes = "根据id删除作品", httpMethod = "GET") + @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET) + @ApiImplicitParams({ + @ApiImplicitParam(name = "id", value = "唯一id", required = true, dataType = "Long", paramType = "path"), + }) + public Result delete(@PathVariable Long id) { + WorksModel model = service.findById(id); + if (model == null) { + return new Result<>(CodeConst.NULL_DATA.getResultCode(), CodeConst.NULL_DATA.getMessage()); + } + service.del(id); + return new Result<>(model); + } + +} diff --git a/website/src/main/java/info/xiaomo/website/controller/WorksController.kt b/website/src/main/java/info/xiaomo/website/controller/WorksController.kt deleted file mode 100644 index 0f456ca8..00000000 --- a/website/src/main/java/info/xiaomo/website/controller/WorksController.kt +++ /dev/null @@ -1,93 +0,0 @@ -package info.xiaomo.website.controller - -import info.xiaomo.core.base.Result -import info.xiaomo.core.constant.CodeConst -import info.xiaomo.website.model.WorksModel -import info.xiaomo.website.service.WorksService -import io.swagger.annotations.Api -import io.swagger.annotations.ApiImplicitParam -import io.swagger.annotations.ApiImplicitParams -import io.swagger.annotations.ApiOperation -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.http.MediaType -import org.springframework.web.bind.annotation.* - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * - * Date: 2016/11/3 14:36 - * Description: 用户实体类 - * Copyright(©) 2015 by xiaomo. - */ - - -@RequestMapping("/works") -@RestController -@Api(value = "作品相关api", description = "作品相关api") -class WorksController @Autowired -constructor(private val service: WorksService) { - - - @RequestMapping(value = "/findById/{id}", method = arrayOf(RequestMethod.GET)) - @ApiOperation(value = "根据id查找作品", notes = "根据id查找作品", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @ApiImplicitParams(ApiImplicitParam(name = "id", value = "唯一id", required = true, dataType = "Long", paramType = "path")) - fun findById(@PathVariable id: Long?): Result<*> { - val model = service.findById(id) - return Result(model) - } - - @RequestMapping(value = "/findAll", method = arrayOf(RequestMethod.GET)) - @ApiOperation(value = "查找所有", notes = "查找所有", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - fun findAll(): Result<*> { - val all = service.findAll() - return if (all.isEmpty()) { - Result(resultCode = CodeConst.NULL_DATA.resultCode, message = CodeConst.NULL_DATA.message!!) - } else Result(all) - } - - @RequestMapping(value = "/findByName/{name}", method = arrayOf(RequestMethod.GET)) - @ApiOperation(value = "根据名字查找作品", notes = "根据名字查找作品", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @ApiImplicitParams(ApiImplicitParam(name = "name", value = "作品名字", required = true, dataType = "String", paramType = "path")) - fun findByName(@PathVariable name: String): Result<*> { - val model = service.findByName(name) - return Result(model) - } - - @ApiOperation(value = "添加作品", notes = "添加作品", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @RequestMapping(value = "/add", method = arrayOf(RequestMethod.POST)) - fun add(@RequestBody model: WorksModel): Result<*> { - var addModel: WorksModel? = service.findByName(model.name!!) - if (addModel != null) { - return Result(resultCode = CodeConst.REPEAT.resultCode, message = CodeConst.REPEAT.message!!) - } - addModel = service.add(model) - return Result(addModel) - } - - @ApiOperation(value = "更新作品", notes = "更新作品", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @RequestMapping(value = "/update", method = arrayOf(RequestMethod.POST)) - fun update(@RequestBody model: WorksModel): Result<*> { - var worksModel: WorksModel? = service.findById(model.id) - worksModel = service.update(worksModel!!) - return Result(worksModel!!) - } - - - @ApiOperation(value = "根据id删除作品", notes = "根据id删除作品", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - @RequestMapping(value = "/delete/{id}", method = arrayOf(RequestMethod.GET)) - @ApiImplicitParams(ApiImplicitParam(name = "id", value = "唯一id", required = true, dataType = "Long", paramType = "path")) - fun delete(@PathVariable id: Long?): Result<*> { - val model = service.findById(id) - service.del(id) - return Result(model) - } - -} diff --git a/website/src/main/java/info/xiaomo/website/dao/AdminUserDao.kt b/website/src/main/java/info/xiaomo/website/dao/AdminUserDao.java similarity index 65% rename from website/src/main/java/info/xiaomo/website/dao/AdminUserDao.kt rename to website/src/main/java/info/xiaomo/website/dao/AdminUserDao.java index b0a7d67e..70034482 100644 --- a/website/src/main/java/info/xiaomo/website/dao/AdminUserDao.kt +++ b/website/src/main/java/info/xiaomo/website/dao/AdminUserDao.java @@ -1,8 +1,8 @@ -package info.xiaomo.website.dao +package info.xiaomo.website.dao; -import info.xiaomo.website.model.AdminModel -import org.springframework.data.jpa.repository.JpaRepository -import org.springframework.stereotype.Repository +import info.xiaomo.website.model.AdminModel; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; /** * │\__╭╭╭╭╭__/│ @@ -16,18 +16,17 @@ * |╭---╮把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. + * * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info - * - * + *

* Date: 16/4/2 13:08 * Copyright(©) 2015 by xiaomo. */ @Repository -interface AdminUserDao : JpaRepository { +public interface AdminUserDao extends JpaRepository { /** * 根据名字查用户 @@ -35,6 +34,6 @@ interface AdminUserDao : JpaRepository { * @param s * @return */ - fun findAdminUserByUserName(s: String): AdminModel + AdminModel findAdminUserByUserName(String s); } diff --git a/website/src/main/java/info/xiaomo/website/dao/ChangeLogDao.kt b/website/src/main/java/info/xiaomo/website/dao/ChangeLogDao.java similarity index 50% rename from website/src/main/java/info/xiaomo/website/dao/ChangeLogDao.kt rename to website/src/main/java/info/xiaomo/website/dao/ChangeLogDao.java index a9c243fb..0953d493 100644 --- a/website/src/main/java/info/xiaomo/website/dao/ChangeLogDao.kt +++ b/website/src/main/java/info/xiaomo/website/dao/ChangeLogDao.java @@ -1,24 +1,24 @@ -package info.xiaomo.website.dao +package info.xiaomo.website.dao; -import info.xiaomo.website.model.ChangeLogModel -import org.springframework.data.jpa.repository.JpaRepository -import org.springframework.stereotype.Repository +import info.xiaomo.website.model.ChangeLogModel; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; /** * 把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. + * * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info - * + *

* Date: 2016/4/1119:52 * Copyright(©) 2015 by xiaomo. - */ + **/ @Repository -interface ChangeLogDao : JpaRepository { +public interface ChangeLogDao extends JpaRepository { /** * find @@ -26,6 +26,6 @@ interface ChangeLogDao : JpaRepository { * @param name * @return */ - fun findByName(name: String): ChangeLogModel + ChangeLogModel findByName(String name); } diff --git a/website/src/main/java/info/xiaomo/website/dao/LinkDao.kt b/website/src/main/java/info/xiaomo/website/dao/LinkDao.java similarity index 52% rename from website/src/main/java/info/xiaomo/website/dao/LinkDao.kt rename to website/src/main/java/info/xiaomo/website/dao/LinkDao.java index cda0a641..53fbf585 100644 --- a/website/src/main/java/info/xiaomo/website/dao/LinkDao.kt +++ b/website/src/main/java/info/xiaomo/website/dao/LinkDao.java @@ -1,24 +1,24 @@ -package info.xiaomo.website.dao +package info.xiaomo.website.dao; -import info.xiaomo.website.model.LinkModel -import org.springframework.data.jpa.repository.JpaRepository -import org.springframework.stereotype.Repository +import info.xiaomo.website.model.LinkModel; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; /** * 把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. + * * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info - * + *

* Date: 2016/4/1119:52 * Copyright(©) 2015 by xiaomo. - */ + **/ @Repository -interface LinkDao : JpaRepository { +public interface LinkDao extends JpaRepository { /** * 根据名字查友链 @@ -26,6 +26,6 @@ interface LinkDao : JpaRepository { * @param name * @return */ - fun findLinkByName(name: String): LinkModel + LinkModel findLinkByName(String name); } diff --git a/website/src/main/java/info/xiaomo/website/dao/TechnologyDao.kt b/website/src/main/java/info/xiaomo/website/dao/TechnologyDao.java similarity index 64% rename from website/src/main/java/info/xiaomo/website/dao/TechnologyDao.kt rename to website/src/main/java/info/xiaomo/website/dao/TechnologyDao.java index 5eb23762..923c7678 100644 --- a/website/src/main/java/info/xiaomo/website/dao/TechnologyDao.kt +++ b/website/src/main/java/info/xiaomo/website/dao/TechnologyDao.java @@ -1,8 +1,8 @@ -package info.xiaomo.website.dao +package info.xiaomo.website.dao; -import info.xiaomo.website.model.TechnologyModel -import org.springframework.data.jpa.repository.JpaRepository -import org.springframework.stereotype.Repository +import info.xiaomo.website.model.TechnologyModel; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; /** * │\__╭╭╭╭╭__/│ @@ -16,18 +16,17 @@ * |╭---╮把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. + * * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info - * - * + *

* Date: 16/4/2 13:08 * Copyright(©) 2015 by xiaomo. */ @Repository -interface TechnologyDao : JpaRepository { +public interface TechnologyDao extends JpaRepository { /** * 根据名字查 @@ -35,7 +34,7 @@ interface TechnologyDao : JpaRepository { * @param name * @return */ - fun findTechnologyByName(name: String): TechnologyModel + TechnologyModel findTechnologyByName(String name); } diff --git a/website/src/main/java/info/xiaomo/website/dao/UserDao.kt b/website/src/main/java/info/xiaomo/website/dao/UserDao.java similarity index 66% rename from website/src/main/java/info/xiaomo/website/dao/UserDao.kt rename to website/src/main/java/info/xiaomo/website/dao/UserDao.java index 5719adba..810462b6 100644 --- a/website/src/main/java/info/xiaomo/website/dao/UserDao.kt +++ b/website/src/main/java/info/xiaomo/website/dao/UserDao.java @@ -1,8 +1,8 @@ -package info.xiaomo.website.dao +package info.xiaomo.website.dao; -import info.xiaomo.website.model.UserModel -import org.springframework.data.jpa.repository.JpaRepository -import org.springframework.stereotype.Repository +import info.xiaomo.website.model.UserModel; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; /** * │\__╭╭╭╭╭__/│ @@ -16,18 +16,18 @@ * |╭---╮把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. + * * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info - * + *

* Date: 16/4/3 10:53 * Copyright(©) 2015 by xiaomo. */ @Repository -interface UserDao : JpaRepository { +public interface UserDao extends JpaRepository { /** * 根据邮件查 @@ -35,5 +35,5 @@ interface UserDao : JpaRepository { * @param email * @return */ - fun findUserByEmail(email: String): UserModel + UserModel findUserByEmail(String email); } diff --git a/website/src/main/java/info/xiaomo/website/dao/WorksDao.kt b/website/src/main/java/info/xiaomo/website/dao/WorksDao.java similarity index 66% rename from website/src/main/java/info/xiaomo/website/dao/WorksDao.kt rename to website/src/main/java/info/xiaomo/website/dao/WorksDao.java index 71cbfd52..0d6a1e89 100644 --- a/website/src/main/java/info/xiaomo/website/dao/WorksDao.kt +++ b/website/src/main/java/info/xiaomo/website/dao/WorksDao.java @@ -1,8 +1,8 @@ -package info.xiaomo.website.dao +package info.xiaomo.website.dao; -import info.xiaomo.website.model.WorksModel -import org.springframework.data.jpa.repository.JpaRepository -import org.springframework.stereotype.Repository +import info.xiaomo.website.model.WorksModel; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; /** * │\__╭╭╭╭╭__/│ @@ -16,17 +16,17 @@ * |╭---╮把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. + * * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info - * + *

* Date: 16/4/2 13:08 * Copyright(©) 2015 by xiaomo. */ @Repository -interface WorksDao : JpaRepository { +public interface WorksDao extends JpaRepository { /** * 根据名字查 @@ -34,6 +34,6 @@ interface WorksDao : JpaRepository { * @param name * @return */ - fun findWorkByName(name: String): WorksModel + WorksModel findWorkByName(String name); } diff --git a/website/src/main/java/info/xiaomo/website/dao/base/CommonDao.java b/website/src/main/java/info/xiaomo/website/dao/base/CommonDao.java new file mode 100644 index 00000000..f208448f --- /dev/null +++ b/website/src/main/java/info/xiaomo/website/dao/base/CommonDao.java @@ -0,0 +1,55 @@ +package info.xiaomo.website.dao.base; + +import info.xiaomo.core.base.BaseModel; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.util.List; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/4/1 20:46 + * Description: 公共dao层 + * Copyright(©) 2015 by xiaomo. + **/ +@Repository +@Transactional(rollbackFor = {}) +public class CommonDao { + + @PersistenceContext + private EntityManager entityManager; + + public T get(Class type, long id) { + return entityManager.find(type, id); + } + + public T update(T entity) { + return entityManager.merge(entity); + } + + public void save(T entity) { + entityManager.persist(entity); + } + + public void delete(T entity) { + entityManager.remove(entity); + } + + public List getAll(Class tableClass) { + Query query = entityManager.createQuery("from " + tableClass.getSimpleName()); + return query.getResultList(); + } + + +} \ No newline at end of file diff --git a/website/src/main/java/info/xiaomo/website/dao/base/CommonDao.kt b/website/src/main/java/info/xiaomo/website/dao/base/CommonDao.kt deleted file mode 100644 index a36d94e8..00000000 --- a/website/src/main/java/info/xiaomo/website/dao/base/CommonDao.kt +++ /dev/null @@ -1,51 +0,0 @@ -package info.xiaomo.website.dao.base - -import info.xiaomo.core.base.BaseModel -import org.springframework.stereotype.Repository -import javax.persistence.EntityManager -import javax.persistence.PersistenceContext - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * - * Date: 2016/4/1 20:46 - * Description: 公共dao层 - * Copyright(©) 2015 by xiaomo. - */ -@Repository -class CommonDao { - - @PersistenceContext - private val entityManager: EntityManager? = null - - operator fun get(type: Class, id: Long): T { - return entityManager!!.find(type, id) - } - - fun update(entity: T): T { - return entityManager!!.merge(entity) - } - - fun save(entity: T) { - entityManager!!.persist(entity) - } - - fun delete(entity: T) { - entityManager!!.remove(entity) - } - - fun getAll(tableClass: Class): List<*> { - val query = entityManager!!.createQuery("from " + tableClass.simpleName) - return query.resultList - } - - -} \ No newline at end of file diff --git a/website/src/main/java/info/xiaomo/website/interceptor/LoginInterceptor.java b/website/src/main/java/info/xiaomo/website/interceptor/LoginInterceptor.java new file mode 100644 index 00000000..a981ef75 --- /dev/null +++ b/website/src/main/java/info/xiaomo/website/interceptor/LoginInterceptor.java @@ -0,0 +1,47 @@ +package info.xiaomo.website.interceptor; + +import info.xiaomo.website.model.UserModel; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.ModelAndView; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/11/21 10:42 + * Copyright(©) 2015 by xiaomo. + **/ + +public class LoginInterceptor implements HandlerInterceptor { + @Override + public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { + UserModel user = (UserModel) httpServletRequest.getSession().getAttribute("currentUser"); + if (user == null) { + //用户没有登录 + httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/user/toLogin"); + return false; + } + //用户已经登录 + return true; + + } + + @Override + public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { + + } + + @Override + public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { + + } +} diff --git a/website/src/main/java/info/xiaomo/website/interceptor/LoginInterceptor.kt b/website/src/main/java/info/xiaomo/website/interceptor/LoginInterceptor.kt deleted file mode 100644 index 0e79e855..00000000 --- a/website/src/main/java/info/xiaomo/website/interceptor/LoginInterceptor.kt +++ /dev/null @@ -1,47 +0,0 @@ -package info.xiaomo.website.interceptor - -import info.xiaomo.website.model.UserModel -import org.springframework.web.servlet.HandlerInterceptor -import org.springframework.web.servlet.ModelAndView - -import javax.servlet.http.HttpServletRequest -import javax.servlet.http.HttpServletResponse - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/11/21 10:42 - * Copyright(©) 2015 by xiaomo. - */ - -class LoginInterceptor : HandlerInterceptor { - @Throws(Exception::class) - override fun preHandle(httpServletRequest: HttpServletRequest, httpServletResponse: HttpServletResponse, o: Any): Boolean { - val user = httpServletRequest.session.getAttribute("currentUser") as UserModel - if (user == null) { - //用户没有登录 - httpServletResponse.sendRedirect(httpServletRequest.contextPath + "/user/toLogin") - return false - } - //用户已经登录 - return true - - } - - @Throws(Exception::class) - override fun postHandle(httpServletRequest: HttpServletRequest, httpServletResponse: HttpServletResponse, o: Any, modelAndView: ModelAndView) { - - } - - @Throws(Exception::class) - override fun afterCompletion(httpServletRequest: HttpServletRequest, httpServletResponse: HttpServletResponse, o: Any, e: Exception) { - - } -} diff --git a/website/src/main/java/info/xiaomo/website/model/AdminModel.java b/website/src/main/java/info/xiaomo/website/model/AdminModel.java new file mode 100644 index 00000000..7209d379 --- /dev/null +++ b/website/src/main/java/info/xiaomo/website/model/AdminModel.java @@ -0,0 +1,54 @@ +package info.xiaomo.website.model; + + +import info.xiaomo.core.base.BaseModel; +import lombok.*; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; +import java.io.Serializable; + +/** + * │\__╭╭╭╭╭__/│ + * │         │ + * │         │ + * │ -      -│ + * │≡    o ≡ │ + * │         │ + * ╰——┬O◤▽◥O┬——╯ + * |  o  | + * |╭---╮把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 16/4/2 12:39 + * Copyright(©) 2015 by xiaomo. + */ +@Entity +@Table(name = "adminUser") +@Data +@ToString(callSuper = true) +@EqualsAndHashCode(callSuper = false) +@AllArgsConstructor +@NoArgsConstructor +public class AdminModel extends BaseModel implements Serializable { + + @Column(name = "UserName") + private String userName; + + @Column(name = "Password") + private String password; + + @Column(name = "Status") + private int status = 1; + + @Column(name = "Salt") + private String salt; + +} diff --git a/website/src/main/java/info/xiaomo/website/model/ChangeLogModel.java b/website/src/main/java/info/xiaomo/website/model/ChangeLogModel.java new file mode 100644 index 00000000..bfc74198 --- /dev/null +++ b/website/src/main/java/info/xiaomo/website/model/ChangeLogModel.java @@ -0,0 +1,39 @@ +package info.xiaomo.website.model; + + +import info.xiaomo.core.base.BaseModel; +import lombok.*; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; +import java.io.Serializable; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/4/517:17 + * Copyright(©) 2015 by xiaomo. + **/ +@Entity +@Table(name = "changeLog") +@Data +@ToString(callSuper = true) +@EqualsAndHashCode(callSuper = false) +@AllArgsConstructor +@NoArgsConstructor +public class ChangeLogModel extends BaseModel implements Serializable { + + @Column(name = "Name") + private String name; + + @Column(name = "OnlineTime") + private String onlineTime; +} diff --git a/website/src/main/java/info/xiaomo/website/model/ChangeLogModel.kt b/website/src/main/java/info/xiaomo/website/model/ChangeLogModel.kt deleted file mode 100644 index 135ef089..00000000 --- a/website/src/main/java/info/xiaomo/website/model/ChangeLogModel.kt +++ /dev/null @@ -1,32 +0,0 @@ -package info.xiaomo.website.model - - -import info.xiaomo.core.base.BaseModel -import java.io.Serializable -import javax.persistence.Column -import javax.persistence.Entity -import javax.persistence.Table - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/4/517:17 - * Copyright(©) 2015 by xiaomo. - */ -@Entity -@Table(name = "changeLog") -class ChangeLogModel : BaseModel(), Serializable { - - @Column(name = "OnlineTime") - var onlineTime: String? = null - set(onlineTime) { - field = this.onlineTime - } -} diff --git a/website/src/main/java/info/xiaomo/website/model/LinkModel.java b/website/src/main/java/info/xiaomo/website/model/LinkModel.java new file mode 100644 index 00000000..5907fff0 --- /dev/null +++ b/website/src/main/java/info/xiaomo/website/model/LinkModel.java @@ -0,0 +1,40 @@ +package info.xiaomo.website.model; + + +import info.xiaomo.core.base.BaseModel; +import lombok.*; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; +import java.io.Serializable; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/4/1119:47 + * Copyright(©) 2015 by xiaomo. + **/ +@Entity +@Table(name = "link") +// lomlok +@Data +@ToString(callSuper = true) +@EqualsAndHashCode(callSuper = false) +@AllArgsConstructor +@NoArgsConstructor +public class LinkModel extends BaseModel implements Serializable { + + @Column(name = "Name") + private String name; + + @Column(name = "Url") + private String url; +} diff --git a/website/src/main/java/info/xiaomo/website/model/LinkModel.kt b/website/src/main/java/info/xiaomo/website/model/LinkModel.kt deleted file mode 100644 index 6ccb6243..00000000 --- a/website/src/main/java/info/xiaomo/website/model/LinkModel.kt +++ /dev/null @@ -1,31 +0,0 @@ -package info.xiaomo.website.model - - -import info.xiaomo.core.base.BaseModel -import java.io.Serializable -import javax.persistence.Column -import javax.persistence.Entity -import javax.persistence.Table - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/4/1119:47 - * Copyright(©) 2015 by xiaomo. - */ -@Entity -@Table(name = "link") -class LinkModel : BaseModel(), Serializable { - @Column(name = "Url") - var url: String? = null - set(url) { - field = this.url - } -} diff --git a/website/src/main/java/info/xiaomo/website/model/TechnologyModel.java b/website/src/main/java/info/xiaomo/website/model/TechnologyModel.java new file mode 100644 index 00000000..ad3d9e05 --- /dev/null +++ b/website/src/main/java/info/xiaomo/website/model/TechnologyModel.java @@ -0,0 +1,47 @@ +package info.xiaomo.website.model; + + +import info.xiaomo.core.base.BaseModel; +import lombok.*; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/11/3 14:27 + * Copyright(©) 2015 by xiaomo. + **/ + +@Entity +@Table(name = "technology") +// lomlok +@Data +@ToString(callSuper = true) +@EqualsAndHashCode(callSuper = false) +@AllArgsConstructor +@NoArgsConstructor +public class TechnologyModel extends BaseModel { + + @Column(name = "Name") + private String name; + + @Column(name = "Url") + private String url; + + @Column(name = "Summary") + private String summary; + + @Column(name = "ImgUrl") + private String imgUrl; + +} diff --git a/website/src/main/java/info/xiaomo/website/model/TechnologyModel.kt b/website/src/main/java/info/xiaomo/website/model/TechnologyModel.kt deleted file mode 100644 index 9138523f..00000000 --- a/website/src/main/java/info/xiaomo/website/model/TechnologyModel.kt +++ /dev/null @@ -1,45 +0,0 @@ -package info.xiaomo.website.model - - -import info.xiaomo.core.base.BaseModel -import javax.persistence.Column -import javax.persistence.Entity -import javax.persistence.Table - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/11/3 14:27 - * Copyright(©) 2015 by xiaomo. - */ - -@Entity -@Table(name = "technology") -class TechnologyModel : BaseModel() { - - @Column(name = "Url") - var url: String? = null - set(url) { - field = this.url - } - - @Column(name = "Summary") - var summary: String? = null - set(summary) { - field = this.summary - } - - @Column(name = "ImgUrl") - var imgUrl: String? = null - set(imgUrl) { - field = this.imgUrl - } - -} diff --git a/website/src/main/java/info/xiaomo/website/model/UserModel.java b/website/src/main/java/info/xiaomo/website/model/UserModel.java new file mode 100644 index 00000000..1dfba5b9 --- /dev/null +++ b/website/src/main/java/info/xiaomo/website/model/UserModel.java @@ -0,0 +1,66 @@ +package info.xiaomo.website.model; + + +import info.xiaomo.core.base.BaseModel; +import lombok.*; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; +import java.io.Serializable; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/4/1 17:36 + * Copyright(©) 2015 by xiaomo. + **/ +@Entity +@Table(name = "user") +// lomlok +@Data +@ToString(callSuper = true) +@EqualsAndHashCode(callSuper = false) +@AllArgsConstructor +@NoArgsConstructor +public class UserModel extends BaseModel implements Serializable { + + @Column(name = "Email") + private String email; + + @Column(name = "NickName") + private String nickName; + + @Column(name = "Password") + private String password; + + @Column(name = "Salt") + private String salt; + + @Column(name = "Gender") + private int gender = 0; + + @Column(name = "Phone") + private Long phone = 0L; + + @Column(name = "ValidateCode") + private String validateCode = ""; + + @Column(name = "ImgUrl") + private String imgUrl = ""; + + @Column(name = "Address") + private String address = ""; + + @Column(name = "RegisterTime") + private Long registerTime = 0L; + + +} diff --git a/website/src/main/java/info/xiaomo/website/model/UserModel.kt b/website/src/main/java/info/xiaomo/website/model/UserModel.kt deleted file mode 100644 index 561fcb5b..00000000 --- a/website/src/main/java/info/xiaomo/website/model/UserModel.kt +++ /dev/null @@ -1,89 +0,0 @@ -package info.xiaomo.website.model - - -import info.xiaomo.core.base.BaseModel -import java.io.Serializable -import javax.persistence.Column -import javax.persistence.Entity -import javax.persistence.Table - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/4/1 17:36 - * Copyright(©) 2015 by xiaomo. - */ -@Entity -@Table(name = "user") - -class UserModel : BaseModel(), Serializable { - - @Column(name = "Email") - var email: String? = null - set(email) { - field = this.email - } - - @Column(name = "NickName") - var nickName: String? = null - set(nickName) { - field = this.nickName - } - - @Column(name = "Password") - var password: String? = null - set(password) { - field = this.password - } - - @Column(name = "Salt") - var salt: String? = null - set(salt) { - field = this.salt - } - - @Column(name = "Gender") - var gender = 0 - set(gender) { - field = this.gender - } - - @Column(name = "Phone") - var phone: Long? = 0L - set(phone) { - field = this.phone - } - - @Column(name = "validateCode") - var validateCode = "" - set(validateCode) { - field = this.validateCode - } - - @Column(name = "ImgUrl") - var imgUrl = "" - set(imgUrl) { - field = this.imgUrl - } - - @Column(name = "Address") - var address = "" - set(address) { - field = this.address - } - - @Column(name = "RegisterTime") - var registerTime: Long? = 0L - set(registerTime) { - field = this.registerTime - } - - -} diff --git a/website/src/main/java/info/xiaomo/website/model/WorksModel.java b/website/src/main/java/info/xiaomo/website/model/WorksModel.java new file mode 100644 index 00000000..6fef0f0e --- /dev/null +++ b/website/src/main/java/info/xiaomo/website/model/WorksModel.java @@ -0,0 +1,50 @@ +package info.xiaomo.website.model; + + +import info.xiaomo.core.base.BaseModel; +import lombok.*; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/11/3 14:15 + * Copyright(©) 2015 by xiaomo. + **/ + +// hibernate +@Entity +@Table(name = "works") +// lomlok +@Data +@ToString(callSuper = true) +@EqualsAndHashCode(callSuper = false) +@AllArgsConstructor +@NoArgsConstructor +public class WorksModel extends BaseModel { + + @Column(name = "Name") + private String name; + + @Column(name = "Url") + private String url; + + @Column(name = "Summary") + private String summary; + + @Column(name = "CompleteTime") + private String completeTime; + + @Column(name = "ImgUrl") + private String imgUrl; +} diff --git a/website/src/main/java/info/xiaomo/website/model/WorksModel.kt b/website/src/main/java/info/xiaomo/website/model/WorksModel.kt deleted file mode 100644 index f92937d4..00000000 --- a/website/src/main/java/info/xiaomo/website/model/WorksModel.kt +++ /dev/null @@ -1,51 +0,0 @@ -package info.xiaomo.website.model - - -import info.xiaomo.core.base.BaseModel -import javax.persistence.Column -import javax.persistence.Entity -import javax.persistence.Table - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/11/3 14:15 - * Copyright(©) 2015 by xiaomo. - */ - -// hibernate -@Entity -@Table(name = "works") -class WorksModel : BaseModel() { - - @Column(name = "Url") - var url: String? = null - set(url) { - field = this.url - } - - @Column(name = "Summary") - var summary: String? = null - set(summary) { - field = this.summary - } - - @Column(name = "CompleteTime") - var completeTime: String? = null - set(completeTime) { - field = this.completeTime - } - - @Column(name = "ImgUrl") - var imgUrl: String? = null - set(imgUrl) { - field = this.imgUrl - } -} diff --git a/website/src/main/java/info/xiaomo/website/service/AdminUserService.kt b/website/src/main/java/info/xiaomo/website/service/AdminUserService.java similarity index 61% rename from website/src/main/java/info/xiaomo/website/service/AdminUserService.kt rename to website/src/main/java/info/xiaomo/website/service/AdminUserService.java index e8be55fb..18ee9d15 100644 --- a/website/src/main/java/info/xiaomo/website/service/AdminUserService.kt +++ b/website/src/main/java/info/xiaomo/website/service/AdminUserService.java @@ -1,8 +1,10 @@ -package info.xiaomo.website.service +package info.xiaomo.website.service; -import info.xiaomo.core.exception.UserNotFoundException -import info.xiaomo.website.model.AdminModel -import org.springframework.data.domain.Page +import info.xiaomo.core.exception.UserNotFoundException; +import info.xiaomo.website.model.AdminModel; +import org.springframework.data.domain.Page; + +import java.util.List; /** * │\__╭╭╭╭╭__/│ @@ -16,23 +18,16 @@ * |╭---╮把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. + * * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info - * + *

* Date: 16/4/2 13:04 * Copyright(©) 2015 by xiaomo. */ -interface AdminUserService { - - /** - * 查所有 - * - * @return - */ - fun getAdminUsers(): List +public interface AdminUserService { /** * 根据用户名查用户 @@ -40,7 +35,7 @@ fun getAdminUsers(): List * @param userName * @return */ - fun findAdminUserByUserName(userName: String): AdminModel + AdminModel findAdminUserByUserName(String userName); /** * 根据id查用户 @@ -48,7 +43,7 @@ fun findAdminUserByUserName(userName: String): AdminModel * @param id * @return */ - fun findAdminUserById(id: Long?): AdminModel + AdminModel findAdminUserById(Long id); /** * 添加用户 @@ -56,7 +51,7 @@ fun findAdminUserById(id: Long?): AdminModel * @param model * @return */ - fun addAdminUser(model: AdminModel): AdminModel + AdminModel addAdminUser(AdminModel model); /** * 更新用户 @@ -65,8 +60,7 @@ fun addAdminUser(model: AdminModel): AdminModel * @return * @throws UserNotFoundException */ - @Throws(UserNotFoundException::class) - fun updateAdminUser(model: AdminModel): AdminModel + AdminModel updateAdminUser(AdminModel model) throws UserNotFoundException; /** * 获取分页 @@ -75,7 +69,14 @@ fun updateAdminUser(model: AdminModel): AdminModel * @param pageSize * @return */ - fun getAdminUsers(start: Int, pageSize: Int): Page + Page getAdminUsers(int start, int pageSize); + + /** + * 查所有 + * + * @return + */ + List getAdminUsers(); /** * 删除 @@ -84,8 +85,7 @@ fun getAdminUsers(start: Int, pageSize: Int): Page * @return * @throws UserNotFoundException */ - @Throws(UserNotFoundException::class) - fun deleteAdminUserById(id: Long?): AdminModel + AdminModel deleteAdminUserById(Long id) throws UserNotFoundException; /** * 禁 @@ -94,7 +94,6 @@ fun deleteAdminUserById(id: Long?): AdminModel * @return * @throws UserNotFoundException */ - @Throws(UserNotFoundException::class) - fun forbidAdminUserById(id: Long?): AdminModel + AdminModel forbidAdminUserById(Long id) throws UserNotFoundException; } diff --git a/website/src/main/java/info/xiaomo/website/service/ChangeLogService.kt b/website/src/main/java/info/xiaomo/website/service/ChangeLogService.java similarity index 57% rename from website/src/main/java/info/xiaomo/website/service/ChangeLogService.kt rename to website/src/main/java/info/xiaomo/website/service/ChangeLogService.java index f405ce0b..5339b40c 100644 --- a/website/src/main/java/info/xiaomo/website/service/ChangeLogService.kt +++ b/website/src/main/java/info/xiaomo/website/service/ChangeLogService.java @@ -1,22 +1,24 @@ -package info.xiaomo.website.service +package info.xiaomo.website.service; -import info.xiaomo.website.model.ChangeLogModel -import org.springframework.data.domain.Page +import info.xiaomo.website.model.ChangeLogModel; +import org.springframework.data.domain.Page; + +import java.util.List; /** * 把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. + * * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info - * + *

* Date: 2016/4/1119:49 * Copyright(©) 2015 by xiaomo. - */ -interface ChangeLogService { + **/ +public interface ChangeLogService { /** * 根据id查 @@ -24,47 +26,53 @@ interface ChangeLogService { * @param id * @return */ - fun findById(id: Long?): ChangeLogModel + ChangeLogModel findById(Long id); /** * 根据名字查 + * * @param name * @return */ - fun findByName(name: String): ChangeLogModel + ChangeLogModel findByName(String name); /** * find all + * * @param start * @param pageSize * @return */ - fun findAll(start: Int, pageSize: Int): Page + Page findAll(int start, int pageSize); /** * find all + * * @return */ - fun findAll(): List + List findAll(); /** * add + * * @param model * @return */ - fun add(model: ChangeLogModel): ChangeLogModel + ChangeLogModel add(ChangeLogModel model); /** * update + * * @param model * @return */ - fun update(model: ChangeLogModel): ChangeLogModel + ChangeLogModel update(ChangeLogModel model); /** * delete + * * @param id * @return */ - fun delete(id: Long?): ChangeLogModel + ChangeLogModel delete(Long id); } diff --git a/website/src/main/java/info/xiaomo/website/service/LinkService.kt b/website/src/main/java/info/xiaomo/website/service/LinkService.java similarity index 61% rename from website/src/main/java/info/xiaomo/website/service/LinkService.kt rename to website/src/main/java/info/xiaomo/website/service/LinkService.java index a1dac55a..6c97007f 100644 --- a/website/src/main/java/info/xiaomo/website/service/LinkService.kt +++ b/website/src/main/java/info/xiaomo/website/service/LinkService.java @@ -1,24 +1,25 @@ -package info.xiaomo.website.service +package info.xiaomo.website.service; -import info.xiaomo.website.model.LinkModel -import org.springframework.data.domain.Page +import info.xiaomo.website.model.LinkModel; +import org.springframework.data.domain.Page; + +import java.util.List; /** * 把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. + * * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info - * - * + *

* Date: 2016/4/1119:49 * Copyright(©) 2015 by xiaomo. - */ -interface LinkService { + **/ +public interface LinkService { /** * 根据id查友链 @@ -26,7 +27,7 @@ interface LinkService { * @param id * @return */ - fun findById(id: Long?): LinkModel + LinkModel findById(Long id); /** * 根据名字查友链 @@ -34,7 +35,7 @@ fun findById(id: Long?): LinkModel * @param name * @return */ - fun findByName(name: String): LinkModel + LinkModel findByName(String name); /** * 分页查 @@ -43,14 +44,14 @@ fun findByName(name: String): LinkModel * @param pageSize * @return */ - fun findAll(start: Int, pageSize: Int): Page + Page findAll(int start, int pageSize); /** * 查所有 * * @return */ - fun findAll(): List + List findAll(); /** * 添加 @@ -58,7 +59,7 @@ fun findAll(): List * @param model * @return */ - fun add(model: LinkModel): LinkModel + LinkModel add(LinkModel model); /** * 更新 @@ -66,7 +67,7 @@ fun add(model: LinkModel): LinkModel * @param model * @return */ - fun update(model: LinkModel): LinkModel + LinkModel update(LinkModel model); /** * 删除 @@ -74,6 +75,6 @@ fun update(model: LinkModel): LinkModel * @param id * @return */ - fun delete(id: Long?): LinkModel + LinkModel delete(Long id); } diff --git a/website/src/main/java/info/xiaomo/website/service/TechnologyService.kt b/website/src/main/java/info/xiaomo/website/service/TechnologyService.java similarity index 58% rename from website/src/main/java/info/xiaomo/website/service/TechnologyService.kt rename to website/src/main/java/info/xiaomo/website/service/TechnologyService.java index 517e665b..5165cfb1 100644 --- a/website/src/main/java/info/xiaomo/website/service/TechnologyService.kt +++ b/website/src/main/java/info/xiaomo/website/service/TechnologyService.java @@ -1,32 +1,33 @@ -package info.xiaomo.website.service +package info.xiaomo.website.service; -import info.xiaomo.website.model.TechnologyModel -import org.springframework.data.domain.Page +import info.xiaomo.website.model.TechnologyModel; +import org.springframework.data.domain.Page; + +import java.util.List; /** * 把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. + * * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info - * - * + *

* Date: 2016/11/3 14:33 * Copyright(©) 2015 by xiaomo. - */ + **/ -interface TechnologyService { +public interface TechnologyService { /** * find all * * @return */ - fun findAll(): List + List findAll(); /** * find all @@ -35,7 +36,7 @@ fun findAll(): List * @param pageSize * @return */ - fun findAll(start: Int, pageSize: Int): Page + Page findAll(int start, int pageSize); /** * find @@ -43,7 +44,7 @@ fun findAll(start: Int, pageSize: Int): Page * @param id * @return */ - fun findById(id: Long?): TechnologyModel + TechnologyModel findById(Long id); /** * find @@ -51,7 +52,7 @@ fun findById(id: Long?): TechnologyModel * @param name * @return */ - fun findByName(name: String): TechnologyModel + TechnologyModel findByName(String name); /** * update @@ -59,7 +60,7 @@ fun findByName(name: String): TechnologyModel * @param model * @return */ - fun update(model: TechnologyModel): TechnologyModel + TechnologyModel update(TechnologyModel model); /** * add @@ -67,13 +68,13 @@ fun update(model: TechnologyModel): TechnologyModel * @param model * @return */ - fun add(model: TechnologyModel): TechnologyModel + TechnologyModel add(TechnologyModel model); /** * del * * @param id */ - fun del(id: Long?) + void del(Long id); } diff --git a/website/src/main/java/info/xiaomo/website/service/UserService.kt b/website/src/main/java/info/xiaomo/website/service/UserService.java similarity index 61% rename from website/src/main/java/info/xiaomo/website/service/UserService.kt rename to website/src/main/java/info/xiaomo/website/service/UserService.java index 84315a5c..cc244a90 100644 --- a/website/src/main/java/info/xiaomo/website/service/UserService.kt +++ b/website/src/main/java/info/xiaomo/website/service/UserService.java @@ -1,32 +1,34 @@ -package info.xiaomo.website.service +package info.xiaomo.website.service; -import info.xiaomo.core.exception.UserNotFoundException -import info.xiaomo.website.model.UserModel -import org.springframework.data.domain.Page +import info.xiaomo.core.exception.UserNotFoundException; +import info.xiaomo.website.model.UserModel; +import org.springframework.data.domain.Page; + +import java.util.List; +import java.util.Optional; /** * 把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. + * * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info - * - * + *

* Date: 2016/4/1 17:45 * Copyright(©) 2015 by xiaomo. - */ -interface UserService { + **/ +public interface UserService { /** * 根据id查用户 * * @param id id * @return UserModel */ - fun findUserById(id: Long?): UserModel + Optional findUserById(Long id); /** * 根据邮件查用户 @@ -34,7 +36,7 @@ fun findUserById(id: Long?): UserModel * @param email email * @return UserModel */ - fun findUserByEmail(email: String): UserModel + UserModel findUserByEmail(String email); /** * 添加用户 @@ -42,7 +44,7 @@ fun findUserByEmail(email: String): UserModel * @param model model * @return UserModel */ - fun addUser(model: UserModel): UserModel + UserModel addUser(UserModel model); /** * 更新用户 @@ -51,8 +53,7 @@ fun addUser(model: UserModel): UserModel * @return UserModel * @throws UserNotFoundException UserNotFoundException */ - @Throws(UserNotFoundException::class) - fun updateUser(model: UserModel): UserModel + UserModel updateUser(UserModel model) throws UserNotFoundException; /** * 查找所有 带分页 @@ -61,14 +62,14 @@ fun updateUser(model: UserModel): UserModel * @param pageSize pageSize * @return Page */ - fun findAll(start: Int, pageSize: Int): Page + Page findAll(int start, int pageSize); /** * 查找所有 不带分页 * * @return List */ - fun findAll(): List + List findAll(); /** * 删除用户 @@ -77,7 +78,6 @@ fun findAll(): List * @return UserModel * @throws UserNotFoundException */ - @Throws(UserNotFoundException::class) - fun deleteUserById(id: Long?): UserModel + UserModel deleteUserById(Long id) throws UserNotFoundException; } diff --git a/website/src/main/java/info/xiaomo/website/service/WorksService.kt b/website/src/main/java/info/xiaomo/website/service/WorksService.java similarity index 60% rename from website/src/main/java/info/xiaomo/website/service/WorksService.kt rename to website/src/main/java/info/xiaomo/website/service/WorksService.java index b7df0a87..ffb93ddc 100644 --- a/website/src/main/java/info/xiaomo/website/service/WorksService.kt +++ b/website/src/main/java/info/xiaomo/website/service/WorksService.java @@ -1,32 +1,33 @@ -package info.xiaomo.website.service +package info.xiaomo.website.service; -import info.xiaomo.website.model.WorksModel -import org.springframework.data.domain.Page +import info.xiaomo.website.model.WorksModel; +import org.springframework.data.domain.Page; + +import java.util.List; /** * 把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. + * * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info - * - * + *

* Date: 2016/11/3 14:33 * Copyright(©) 2015 by xiaomo. - */ + **/ -interface WorksService { +public interface WorksService { /** * find all * * @return */ - fun findAll(): List + List findAll(); /** * find all page @@ -35,7 +36,7 @@ fun findAll(): List * @param pageSize * @return */ - fun findAll(start: Int, pageSize: Int): Page + Page findAll(int start, int pageSize); /** * find @@ -43,7 +44,7 @@ fun findAll(start: Int, pageSize: Int): Page * @param id * @return */ - fun findById(id: Long?): WorksModel + WorksModel findById(Long id); /** * find @@ -51,7 +52,7 @@ fun findById(id: Long?): WorksModel * @param name * @return */ - fun findByName(name: String): WorksModel + WorksModel findByName(String name); /** * update @@ -59,7 +60,7 @@ fun findByName(name: String): WorksModel * @param model * @return */ - fun update(model: WorksModel): WorksModel? + WorksModel update(WorksModel model); /** @@ -68,7 +69,7 @@ fun update(model: WorksModel): WorksModel? * @param model * @return */ - fun add(model: WorksModel): WorksModel + WorksModel add(WorksModel model); /** @@ -76,5 +77,5 @@ fun add(model: WorksModel): WorksModel * * @param id */ - fun del(id: Long?) + void del(Long id); } diff --git a/website/src/main/java/info/xiaomo/website/service/impl/AdminUserServiceImpl.java b/website/src/main/java/info/xiaomo/website/service/impl/AdminUserServiceImpl.java new file mode 100644 index 00000000..dcebc65b --- /dev/null +++ b/website/src/main/java/info/xiaomo/website/service/impl/AdminUserServiceImpl.java @@ -0,0 +1,117 @@ +package info.xiaomo.website.service.impl; + +import info.xiaomo.core.exception.UserNotFoundException; +import info.xiaomo.website.dao.AdminUserDao; +import info.xiaomo.website.model.AdminModel; +import info.xiaomo.website.service.AdminUserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Service; + +import java.util.Date; +import java.util.List; +import java.util.Optional; + +/** + * │\__╭╭╭╭╭__/│ + * │         │ + * │         │ + * │ -      -│ + * │≡    o ≡ │ + * │         │ + * ╰——┬O◤▽◥O┬——╯ + * |  o  | + * |╭---╮把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 16/4/2 13:34 + * Description: 后台用户serviceImpl + * Copyright(©) 2015 by xiaomo. + */ +@Service +public class AdminUserServiceImpl implements AdminUserService { + + private final AdminUserDao dao; + + @Autowired + public AdminUserServiceImpl(AdminUserDao dao) { + this.dao = dao; + } + + @Override + public AdminModel findAdminUserByUserName(String userName) { + return dao.findAdminUserByUserName(userName); + } + + @Override + public AdminModel findAdminUserById(Long id) { + Optional optionalModel = dao.findById(id); + return optionalModel.orElse(null); + } + + @Override + public AdminModel addAdminUser(AdminModel model) { + model.setCreateTime(new Date()); + model.setUpdateTime(new Date()); + return dao.save(model); + + } + + @Override + public AdminModel updateAdminUser(AdminModel model) throws UserNotFoundException { + Optional optionalModel = dao.findById(model.getId()); + if (!optionalModel.isPresent()) { + throw new UserNotFoundException(); + } + AdminModel adminModel = optionalModel.get(); + if (model.getPassword() != null) { + adminModel.setPassword(model.getPassword()); + } + if (model.getUserName() != null) { + adminModel.setUserName(model.getUserName()); + } + adminModel.setUpdateTime(new Date()); + return dao.save(adminModel); + } + + @Override + public Page getAdminUsers(int start, int pageSize) { + Sort sort = Sort.by(Sort.Direction.DESC, "createTime"); + return dao.findAll(PageRequest.of(start - 1, pageSize, sort)); + } + + @Override + public AdminModel deleteAdminUserById(Long id) throws UserNotFoundException { + Optional optionalModel = dao.findById(id); + if (!optionalModel.isPresent()) { + throw new UserNotFoundException(); + } + AdminModel adminModel = optionalModel.get(); + dao.delete(adminModel); + return adminModel; + } + + @Override + public AdminModel forbidAdminUserById(Long id) throws UserNotFoundException { + Optional optionalModel = dao.findById(id); + if (!optionalModel.isPresent()) { + throw new UserNotFoundException(); + } + AdminModel adminModel = optionalModel.get(); + adminModel.setStatus(2); + return dao.save(adminModel); + } + + @Override + public List getAdminUsers() { + return dao.findAll(); + } +} diff --git a/website/src/main/java/info/xiaomo/website/service/impl/AdminUserServiceImpl.kt b/website/src/main/java/info/xiaomo/website/service/impl/AdminUserServiceImpl.kt deleted file mode 100644 index dfe55208..00000000 --- a/website/src/main/java/info/xiaomo/website/service/impl/AdminUserServiceImpl.kt +++ /dev/null @@ -1,91 +0,0 @@ -package info.xiaomo.website.service.impl - -import info.xiaomo.core.exception.UserNotFoundException -import info.xiaomo.website.dao.AdminUserDao -import info.xiaomo.website.model.AdminModel -import info.xiaomo.website.service.AdminUserService -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.data.domain.Page -import org.springframework.data.domain.PageRequest -import org.springframework.data.domain.Sort -import org.springframework.stereotype.Service -import java.util.* - -/** - * │\__╭╭╭╭╭__/│ - * │         │ - * │         │ - * │ -      -│ - * │≡    o ≡ │ - * │         │ - * ╰——┬O◤▽◥O┬——╯ - * |  o  | - * |╭---╮把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 16/4/2 13:34 - * Description: 后台用户serviceImpl - * Copyright(©) 2015 by xiaomo. - */ -@Service -class AdminUserServiceImpl -@Autowired -constructor(private val dao: AdminUserDao) : AdminUserService { - - override fun findAdminUserByUserName(userName: String): AdminModel { - return dao.findAdminUserByUserName(userName) - } - - override fun findAdminUserById(id: Long?): AdminModel { - return dao.findOne(id) - } - - override fun addAdminUser(model: AdminModel): AdminModel { - model.createTime = Date() - model.updateTime = Date() - return dao.save(model) - - } - - @Throws(UserNotFoundException::class) - override fun updateAdminUser(model: AdminModel): AdminModel { - val userUpdate = dao.findOne(model.id) ?: throw UserNotFoundException() - if (model.password != null) { - userUpdate.password = model.password - } - if (model.userName != null) { - userUpdate.userName = model.userName - } - userUpdate.updateTime = Date() - return dao.save(userUpdate) - } - - override fun getAdminUsers(start: Int, pageSize: Int): Page { - val sort = Sort(Sort.Direction.DESC, "createTime") - return dao.findAll(PageRequest(start - 1, pageSize, sort)) - } - - @Throws(UserNotFoundException::class) - override fun deleteAdminUserById(id: Long?): AdminModel { - val adminModel = dao.findOne(id) ?: throw UserNotFoundException() - dao.delete(adminModel.id) - return adminModel - } - - @Throws(UserNotFoundException::class) - override fun forbidAdminUserById(id: Long?): AdminModel { - val model = dao.findOne(id) ?: throw UserNotFoundException() - model.status = 2 - return dao.save(model) - } - - override fun getAdminUsers(): List { - return dao.findAll() - } -} diff --git a/website/src/main/java/info/xiaomo/website/service/impl/ChangeLogServiceImpl.java b/website/src/main/java/info/xiaomo/website/service/impl/ChangeLogServiceImpl.java new file mode 100644 index 00000000..aa603bd1 --- /dev/null +++ b/website/src/main/java/info/xiaomo/website/service/impl/ChangeLogServiceImpl.java @@ -0,0 +1,92 @@ +package info.xiaomo.website.service.impl; + +import info.xiaomo.website.dao.ChangeLogDao; +import info.xiaomo.website.model.ChangeLogModel; +import info.xiaomo.website.service.ChangeLogService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Service; + +import java.util.Date; +import java.util.List; +import java.util.Optional; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/4/11 19:49 + * Copyright(©) 2015 by xiaomo. + **/ +@Service +public class ChangeLogServiceImpl implements ChangeLogService { + + private final ChangeLogDao dao; + + @Autowired + public ChangeLogServiceImpl(ChangeLogDao dao) { + this.dao = dao; + } + + @Override + public ChangeLogModel findById(Long id) { + Optional changeLogModel = dao.findById(id); + return changeLogModel.orElse(null); + } + + @Override + public ChangeLogModel findByName(String name) { + return dao.findByName(name); + } + + @Override + public Page findAll(int start, int pageSize) { + Sort sort = Sort.by(Sort.Direction.DESC, "createTime"); + return dao.findAll(PageRequest.of(start - 1, pageSize, sort)); + } + + @Override + public List findAll() { + return dao.findAll(); + } + + @Override + public ChangeLogModel add(ChangeLogModel model) { + model.setCreateTime(new Date()); + model.setUpdateTime(new Date()); + return dao.save(model); + } + + @Override + public ChangeLogModel update(ChangeLogModel model) { + Optional optionalModel = dao.findById(model.getId()); + if (!optionalModel.isPresent()) { + return null; + } + ChangeLogModel changeLogModel = optionalModel.get(); + if (model.getName() != null) { + changeLogModel.setName(model.getName()); + } + changeLogModel.setUpdateTime(new Date()); + return dao.save(changeLogModel); + } + + @Override + public ChangeLogModel delete(Long id) { + Optional optionalLogModel = dao.findById(id); + if (!optionalLogModel.isPresent()) { + return null; + } + ChangeLogModel changeLogModel = optionalLogModel.get(); + dao.delete(changeLogModel); + return changeLogModel; + } +} diff --git a/website/src/main/java/info/xiaomo/website/service/impl/ChangeLogServiceImpl.kt b/website/src/main/java/info/xiaomo/website/service/impl/ChangeLogServiceImpl.kt deleted file mode 100644 index ad4a97ba..00000000 --- a/website/src/main/java/info/xiaomo/website/service/impl/ChangeLogServiceImpl.kt +++ /dev/null @@ -1,69 +0,0 @@ -package info.xiaomo.website.service.impl - -import info.xiaomo.website.dao.ChangeLogDao -import info.xiaomo.website.model.ChangeLogModel -import info.xiaomo.website.service.ChangeLogService -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.data.domain.Page -import org.springframework.data.domain.PageRequest -import org.springframework.data.domain.Sort -import org.springframework.stereotype.Service -import java.util.* - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/4/11 19:49 - * Copyright(©) 2015 by xiaomo. - */ -@Service -class ChangeLogServiceImpl @Autowired -constructor(private val dao: ChangeLogDao) : ChangeLogService { - - override fun findById(id: Long?): ChangeLogModel { - return dao.findOne(id) - } - - override fun findByName(name: String): ChangeLogModel { - return dao.findByName(name) - } - - override fun findAll(start: Int, pageSize: Int): Page { - val sort = Sort(Sort.Direction.DESC, "createTime") - return dao.findAll(PageRequest(start - 1, pageSize, sort)) - } - - override fun findAll(): List { - return dao.findAll() - } - - override fun add(model: ChangeLogModel): ChangeLogModel { - model.createTime = Date() - model.updateTime = Date() - return dao.save(model) - } - - override fun update(model: ChangeLogModel): ChangeLogModel { - val updateModel = dao.findOne(model.id) - if (model.name != null) { - updateModel.name = model.name - } - updateModel.updateTime = Date() - return dao.save(updateModel) - } - - override fun delete(id: Long?): ChangeLogModel { - val model = dao.findOne(id) - if (model != null) { - dao.delete(id) - } - return model - } -} diff --git a/website/src/main/java/info/xiaomo/website/service/impl/LinkServiceImpl.java b/website/src/main/java/info/xiaomo/website/service/impl/LinkServiceImpl.java new file mode 100644 index 00000000..1742a9e7 --- /dev/null +++ b/website/src/main/java/info/xiaomo/website/service/impl/LinkServiceImpl.java @@ -0,0 +1,94 @@ +package info.xiaomo.website.service.impl; + +import info.xiaomo.website.dao.LinkDao; +import info.xiaomo.website.model.LinkModel; +import info.xiaomo.website.service.LinkService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Service; + +import java.util.Date; +import java.util.List; +import java.util.Optional; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/4/11 19:50 + * Copyright(©) 2015 by xiaomo. + **/ +@Service +public class LinkServiceImpl implements LinkService { + + private final LinkDao dao; + + @Autowired + public LinkServiceImpl(LinkDao dao) { + this.dao = dao; + } + + @Override + public LinkModel findById(Long id) { + Optional optionalModel = dao.findById(id); + return optionalModel.orElse(null); + } + + @Override + public LinkModel findByName(String name) { + return dao.findLinkByName(name); + } + + @Override + public Page findAll(int start, int pageSize) { + Sort sort = Sort.by(Sort.Direction.DESC, "order"); + return dao.findAll(PageRequest.of(start - 1, pageSize, sort)); + } + + @Override + public List findAll() { + return dao.findAll(); + } + + @Override + public LinkModel add(LinkModel model) { + model.setCreateTime(new Date()); + model.setUpdateTime(new Date()); + return dao.save(model); + } + + @Override + public LinkModel update(LinkModel model) { + Optional optional = dao.findById(model.getId()); + if (!optional.isPresent()) { + return null; + } + LinkModel linkModel = optional.get(); + if (model.getName() != null) { + linkModel.setName(model.getName()); + } + if (model.getUrl() != null) { + linkModel.setUrl(model.getUrl()); + } + model.setUpdateTime(new Date()); + return dao.save(linkModel); + } + + @Override + public LinkModel delete(Long id) { + Optional optional = dao.findById(id); + if (!optional.isPresent()) { + return null; + } + LinkModel linkModel = optional.get(); + dao.delete(linkModel); + return linkModel; + } +} diff --git a/website/src/main/java/info/xiaomo/website/service/impl/LinkServiceImpl.kt b/website/src/main/java/info/xiaomo/website/service/impl/LinkServiceImpl.kt deleted file mode 100644 index 357feea5..00000000 --- a/website/src/main/java/info/xiaomo/website/service/impl/LinkServiceImpl.kt +++ /dev/null @@ -1,72 +0,0 @@ -package info.xiaomo.website.service.impl - -import info.xiaomo.website.dao.LinkDao -import info.xiaomo.website.model.LinkModel -import info.xiaomo.website.service.LinkService -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.data.domain.Page -import org.springframework.data.domain.PageRequest -import org.springframework.data.domain.Sort -import org.springframework.stereotype.Service -import java.util.* - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/4/11 19:50 - * Copyright(©) 2015 by xiaomo. - */ -@Service -class LinkServiceImpl @Autowired -constructor(private val dao: LinkDao) : LinkService { - - override fun findById(id: Long?): LinkModel { - return dao.findOne(id) - } - - override fun findByName(name: String): LinkModel { - return dao.findLinkByName(name) - } - - override fun findAll(start: Int, pageSize: Int): Page { - val sort = Sort(Sort.Direction.DESC, "order") - return dao.findAll(PageRequest(start - 1, pageSize, sort)) - } - - override fun findAll(): List { - return dao.findAll() - } - - override fun add(model: LinkModel): LinkModel { - model.createTime = Date() - model.updateTime = Date() - return dao.save(model) - } - - override fun update(model: LinkModel): LinkModel { - val updateModel = dao.findOne(model.id) - if (model.name != null) { - updateModel.name = model.name - } - if (model.url != null) { - updateModel.url = model.url - } - model.updateTime = Date() - return dao.save(updateModel) - } - - override fun delete(id: Long?): LinkModel { - val model = dao.findOne(id) - if (model != null) { - dao.delete(id) - } - return model - } -} diff --git a/website/src/main/java/info/xiaomo/website/service/impl/TechnologyServiceImpl.java b/website/src/main/java/info/xiaomo/website/service/impl/TechnologyServiceImpl.java new file mode 100644 index 00000000..42d66e9d --- /dev/null +++ b/website/src/main/java/info/xiaomo/website/service/impl/TechnologyServiceImpl.java @@ -0,0 +1,99 @@ +package info.xiaomo.website.service.impl; + +import info.xiaomo.website.dao.TechnologyDao; +import info.xiaomo.website.model.TechnologyModel; +import info.xiaomo.website.service.TechnologyService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.stereotype.Service; + +import java.util.Date; +import java.util.List; +import java.util.Optional; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/11/3 14:34 + * Copyright(©) 2015 by xiaomo. + **/ + +@Service +public class TechnologyServiceImpl implements TechnologyService { + + private TechnologyDao dao; + + @Autowired + public TechnologyServiceImpl(TechnologyDao dao) { + this.dao = dao; + } + + @Override + public List findAll() { + return dao.findAll(); + } + + @Override + public Page findAll(int start, int pageSize) { + return dao.findAll(PageRequest.of(start - 1, pageSize)); + } + + @Override + public TechnologyModel findById(Long id) { + Optional optionalModel = dao.findById(id); + return optionalModel.orElse(null); + } + + @Override + public TechnologyModel findByName(String name) { + return dao.findTechnologyByName(name); + } + + @Override + public TechnologyModel update(TechnologyModel model) { + Optional optional = dao.findById(model.getId()); + if (!optional.isPresent()) { + return null; + } + TechnologyModel result = optional.get(); + if ("".equals(model.getUrl()) && model.getUrl() != null) { + result.setUrl(model.getUrl()); + } + if ("".equals(model.getName()) && model.getName() != null) { + result.setName(model.getName()); + } + + if ("".equals(model.getSummary()) && model.getSummary() != null) { + result.setSummary(model.getSummary()); + } + if ("".equals(model.getImgUrl()) && model.getImgUrl() != null) { + result.setImgUrl(model.getImgUrl()); + } + result.setUpdateTime(new Date()); + return dao.save(result); + } + + @Override + public TechnologyModel add(TechnologyModel model) { + model.setCreateTime(new Date()); + model.setUpdateTime(new Date()); + return dao.save(model); + } + + @Override + public void del(Long id) { + Optional optional = dao.findById(id); + if (!optional.isPresent()) { + return; + } + dao.delete(optional.get()); + } +} diff --git a/website/src/main/java/info/xiaomo/website/service/impl/TechnologyServiceImpl.kt b/website/src/main/java/info/xiaomo/website/service/impl/TechnologyServiceImpl.kt deleted file mode 100644 index eea07aff..00000000 --- a/website/src/main/java/info/xiaomo/website/service/impl/TechnologyServiceImpl.kt +++ /dev/null @@ -1,74 +0,0 @@ -package info.xiaomo.website.service.impl - -import info.xiaomo.website.dao.TechnologyDao -import info.xiaomo.website.model.TechnologyModel -import info.xiaomo.website.service.TechnologyService -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.data.domain.Page -import org.springframework.data.domain.PageRequest -import org.springframework.stereotype.Service -import java.util.* - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/11/3 14:34 - * Copyright(©) 2015 by xiaomo. - */ - -@Service -class TechnologyServiceImpl @Autowired -constructor(private val dao: TechnologyDao) : TechnologyService { - - override fun findAll(): List { - return dao.findAll() - } - - override fun findAll(start: Int, pageSize: Int): Page { - return dao.findAll(PageRequest(start - 1, pageSize)) - } - - override fun findById(id: Long?): TechnologyModel { - return dao.findOne(id) - } - - override fun findByName(name: String): TechnologyModel { - return dao.findTechnologyByName(name) - } - - override fun update(model: TechnologyModel): TechnologyModel { - val result = dao.findOne(model.id) - if ("" == model.url && model.url != null) { - result.url = model.url - } - if ("" == model.name && model.name != null) { - result.name = model.name - } - - if ("" == model.summary && model.summary != null) { - result.summary = model.summary - } - if ("" == model.imgUrl && model.imgUrl != null) { - result.imgUrl = model.imgUrl - } - result.updateTime = Date() - return dao.save(result) - } - - override fun add(model: TechnologyModel): TechnologyModel { - model.createTime = Date() - model.updateTime = Date() - return dao.save(model) - } - - override fun del(id: Long?) { - dao.delete(id) - } -} diff --git a/website/src/main/java/info/xiaomo/website/service/impl/UserServiceImpl.java b/website/src/main/java/info/xiaomo/website/service/impl/UserServiceImpl.java new file mode 100644 index 00000000..f971ce79 --- /dev/null +++ b/website/src/main/java/info/xiaomo/website/service/impl/UserServiceImpl.java @@ -0,0 +1,109 @@ +package info.xiaomo.website.service.impl; + +import info.xiaomo.core.exception.UserNotFoundException; +import info.xiaomo.website.dao.UserDao; +import info.xiaomo.website.model.UserModel; +import info.xiaomo.website.service.UserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Service; + +import java.util.Date; +import java.util.List; +import java.util.Optional; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/4/1 17:46 + * Description: 用户service实现 + * Copyright(©) 2015 by xiaomo. + **/ +@Service +public class UserServiceImpl implements UserService { + + private final UserDao dao; + + @Autowired + public UserServiceImpl(UserDao dao) { + this.dao = dao; + } + + @Override + public Optional findUserById(Long id) { + return dao.findById(id); + } + + @Override + public UserModel findUserByEmail(String email) { + return dao.findUserByEmail(email); + } + + @Override + public UserModel addUser(UserModel model) { + model.setCreateTime(new Date()); + model.setUpdateTime(new Date()); + return dao.save(model); + } + + @Override + public UserModel updateUser(UserModel model) throws UserNotFoundException { + UserModel userUpdate = dao.findUserByEmail(model.getEmail()); + if (userUpdate == null) { + throw new UserNotFoundException(); + } + if (model.getAddress() != null) { + userUpdate.setAddress(model.getAddress()); + } + if (model.getEmail() != null) { + userUpdate.setEmail(model.getEmail()); + } + if (model.getGender() != 0) { + userUpdate.setGender(model.getGender()); + } + if (model.getImgUrl() != null) { + userUpdate.setImgUrl(model.getImgUrl()); + } + if (model.getNickName() != null) { + userUpdate.setNickName(model.getNickName()); + } + if (model.getPhone() != 0) { + userUpdate.setPhone(model.getPhone()); + } + userUpdate.setUpdateTime(new Date()); + dao.save(userUpdate); + return userUpdate; + } + + @Override + public Page findAll(int start, int pageSize) { + Sort sort = Sort.by(Sort.Direction.DESC, "createTime"); + return dao.findAll(PageRequest.of(start - 1, pageSize, sort)); + } + + @Override + public List findAll() { + return dao.findAll(); + } + + @Override + public UserModel deleteUserById(Long id) throws UserNotFoundException { + Optional modelOptional = dao.findById(id); + if (!modelOptional.isPresent()) { + throw new UserNotFoundException(); + } + UserModel userModel = modelOptional.get(); + dao.delete(userModel); + return userModel; + } + +} diff --git a/website/src/main/java/info/xiaomo/website/service/impl/UserServiceImpl.kt b/website/src/main/java/info/xiaomo/website/service/impl/UserServiceImpl.kt deleted file mode 100644 index b45c1921..00000000 --- a/website/src/main/java/info/xiaomo/website/service/impl/UserServiceImpl.kt +++ /dev/null @@ -1,88 +0,0 @@ -package info.xiaomo.website.service.impl - -import info.xiaomo.core.exception.UserNotFoundException -import info.xiaomo.website.dao.UserDao -import info.xiaomo.website.model.UserModel -import info.xiaomo.website.service.UserService -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.data.domain.Page -import org.springframework.data.domain.PageRequest -import org.springframework.data.domain.Sort -import org.springframework.stereotype.Service -import java.util.* - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/4/1 17:46 - * Description: 用户service实现 - * Copyright(©) 2015 by xiaomo. - */ -@Service -class UserServiceImpl @Autowired -constructor(private val dao: UserDao) : UserService { - - override fun findUserById(id: Long?): UserModel { - return dao.findOne(id) - } - - override fun findUserByEmail(email: String): UserModel { - return dao.findUserByEmail(email) - } - - override fun addUser(model: UserModel): UserModel { - model.createTime = Date() - model.updateTime = Date() - return dao.save(model) - } - - @Throws(UserNotFoundException::class) - override fun updateUser(model: UserModel): UserModel { - val userUpdate = dao.findUserByEmail(model.email!!) - if (model.address != null) { - userUpdate.address = model.address - } - if (model.email != null) { - userUpdate.email = model.email - } - if (model.gender != 0) { - userUpdate.gender = model.gender - } - if (model.imgUrl != null) { - userUpdate.imgUrl = model.imgUrl - } - if (model.nickName != null) { - userUpdate.nickName = model.nickName - } - if (model.phone != 0L) { - userUpdate.phone = model.phone - } - userUpdate.updateTime = Date() - dao.save(userUpdate) - return userUpdate - } - - override fun findAll(start: Int, pageSize: Int): Page { - val sort = Sort(Sort.Direction.DESC, "createTime") - return dao.findAll(PageRequest(start - 1, pageSize, sort)) - } - - override fun findAll(): List { - return dao.findAll() - } - - @Throws(UserNotFoundException::class) - override fun deleteUserById(id: Long?): UserModel { - val userModel = dao.findOne(id) ?: throw UserNotFoundException() - dao.delete(userModel.id) - return userModel - } - -} diff --git a/website/src/main/java/info/xiaomo/website/service/impl/WorksServiceImpl.java b/website/src/main/java/info/xiaomo/website/service/impl/WorksServiceImpl.java new file mode 100644 index 00000000..50b66c00 --- /dev/null +++ b/website/src/main/java/info/xiaomo/website/service/impl/WorksServiceImpl.java @@ -0,0 +1,101 @@ +package info.xiaomo.website.service.impl; + +import info.xiaomo.website.dao.WorksDao; +import info.xiaomo.website.model.WorksModel; +import info.xiaomo.website.service.WorksService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.stereotype.Service; + +import java.util.Date; +import java.util.List; +import java.util.Optional; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/11/3 14:34 + * Copyright(©) 2015 by xiaomo. + **/ + +@Service +public class WorksServiceImpl implements WorksService { + + private WorksDao dao; + + @Autowired + public WorksServiceImpl(WorksDao dao) { + this.dao = dao; + } + + @Override + public List findAll() { + return dao.findAll(); + } + + @Override + public Page findAll(int start, int pageSize) { + return dao.findAll(PageRequest.of(start - 1, pageSize)); + } + + @Override + public WorksModel findById(Long id) { + Optional optionalModel = dao.findById(id); + return optionalModel.orElse(null); + } + + @Override + public WorksModel findByName(String name) { + return dao.findWorkByName(name); + } + + @Override + public WorksModel update(WorksModel model) { + Optional optional = dao.findById(model.getId()); + if (!optional.isPresent()) { + return null; + } + WorksModel result = optional.get(); + if ("".equals(model.getCompleteTime()) && model.getCompleteTime() != null) { + result.setCompleteTime(model.getCompleteTime()); + } + if ("".equals(model.getImgUrl()) && model.getImgUrl() != null) { + result.setImgUrl(model.getImgUrl()); + } + if ("".equals(model.getName()) && model.getName() != null) { + result.setName(model.getName()); + } + if ("".equals(model.getSummary()) && model.getSummary() != null) { + result.setSummary(model.getSummary()); + } + if ("".equals(model.getUrl()) && model.getUrl() != null) { + result.setUrl(model.getUrl()); + } + result.setUpdateTime(new Date()); + return dao.save(result); + } + + @Override + public WorksModel add(WorksModel model) { + model.setCreateTime(new Date()); + model.setUpdateTime(new Date()); + return dao.save(model); + } + + @Override + public void del(Long id) { + Optional optional = dao.findById(id); + if (!optional.isPresent()) { + return; + } + dao.delete(optional.get()); + } +} diff --git a/website/src/main/java/info/xiaomo/website/service/impl/WorksServiceImpl.kt b/website/src/main/java/info/xiaomo/website/service/impl/WorksServiceImpl.kt deleted file mode 100644 index 8ac8fa90..00000000 --- a/website/src/main/java/info/xiaomo/website/service/impl/WorksServiceImpl.kt +++ /dev/null @@ -1,76 +0,0 @@ -package info.xiaomo.website.service.impl - -import info.xiaomo.website.dao.WorksDao -import info.xiaomo.website.model.WorksModel -import info.xiaomo.website.service.WorksService -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.data.domain.Page -import org.springframework.data.domain.PageRequest -import org.springframework.stereotype.Service -import java.util.* - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/11/3 14:34 - * Copyright(©) 2015 by xiaomo. - */ - -@Service -class WorksServiceImpl @Autowired -constructor(private val dao: WorksDao) : WorksService { - - override fun findAll(): List { - return dao.findAll() - } - - override fun findAll(start: Int, pageSize: Int): Page { - return dao.findAll(PageRequest(start - 1, pageSize)) - } - - override fun findById(id: Long?): WorksModel { - return dao.findOne(id) - } - - override fun findByName(name: String): WorksModel { - return dao.findWorkByName(name) - } - - override fun update(model: WorksModel): WorksModel? { - val result = dao.findOne(model.id) ?: return null - if ("" == model.completeTime && model.completeTime != null) { - result.completeTime = model.completeTime - } - if ("" == model.imgUrl && model.imgUrl != null) { - result.imgUrl = model.imgUrl - } - if ("" == model.name && model.name != null) { - result.name = model.name - } - if ("" == model.summary && model.summary != null) { - result.summary = model.summary - } - if ("" == model.url && model.url != null) { - result.url = model.url - } - result.updateTime = Date() - return dao.save(result) - } - - override fun add(model: WorksModel): WorksModel { - model.createTime = Date() - model.updateTime = Date() - return dao.save(model) - } - - override fun del(id: Long?) { - dao.delete(id) - } -} diff --git a/website/src/main/java/info/xiaomo/website/util/MailUtil.java b/website/src/main/java/info/xiaomo/website/util/MailUtil.java new file mode 100644 index 00000000..d338d6d1 --- /dev/null +++ b/website/src/main/java/info/xiaomo/website/util/MailUtil.java @@ -0,0 +1,108 @@ +package info.xiaomo.website.util; + +import freemarker.template.Configuration; +import freemarker.template.Template; +import info.xiaomo.core.untils.TimeUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; + +import javax.mail.*; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeMessage; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/4/511:00 + * Description: 发送邮件 + * Copyright(©) 2015 by xiaomo. + **/ +public class MailUtil { + + private static final Logger LOGGER = LoggerFactory.getLogger(MailUtil.class); + + private static String USERNAME; + private static String PASSWORD; + + /** + * 获取Session + */ + private static Session getSession() throws IOException { + Properties props = new Properties(); + String dir = System.getProperty("user.dir"); + FileInputStream is = new FileInputStream(dir + "/website/src/main/resources/config/application.properties"); + props.load(is); + USERNAME = String.valueOf(props.get("mail.username")); + PASSWORD = String.valueOf(props.get("mail.password")); + Authenticator authenticator = new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(USERNAME, PASSWORD); + } + }; + return Session.getDefaultInstance(props, authenticator); + } + + public static boolean send(String toEmail, String subject, String content) { + Session session; + try { + session = getSession(); + Message msg = new MimeMessage(session); + msg.setFrom(new InternetAddress(USERNAME)); + InternetAddress[] address = {new InternetAddress(toEmail)}; + msg.setRecipients(Message.RecipientType.TO, address); + msg.setSubject(subject); + msg.setSentDate(new Date()); + msg.setContent(content, "text/html;charset=utf-8"); + Transport.send(msg); + LOGGER.debug("给用户:{}发送注册帐号邮件", toEmail); + } catch (Exception e) { + LOGGER.debug("给用户:{}发送注册帐号邮件失败", toEmail); + return false; + } + return true; + } + + /** + * 返回激活链接 + * + * @param email email + * @return 有3个参数 email password + */ + public static String getContent(String email, String password, Configuration configuration) { + Long now = TimeUtil.getNowOfMills(); + Map data = new HashMap<>(10); + StringBuilder sb = new StringBuilder("http://localhost:8080/user/validate?email="); + sb.append(email); + sb.append("&password="); + sb.append(password); + sb.append("&time="); + sb.append(now); + data.put("email", email); + data.put("url", sb.toString()); + data.put("now", TimeUtil.getFormatDate(now, TimeUtil.DEFAULT_FORMAT)); + Template template; + String readyParsedTemplate = null; + try { + template = configuration.getTemplate("email.ftl"); + readyParsedTemplate = FreeMarkerTemplateUtils.processTemplateIntoString(template, data); + } catch (Exception e) { + e.printStackTrace(); + } + return readyParsedTemplate; + } +} diff --git a/website/src/main/java/info/xiaomo/website/view/TechnologyView.kt b/website/src/main/java/info/xiaomo/website/view/AdminUserView.java similarity index 53% rename from website/src/main/java/info/xiaomo/website/view/TechnologyView.kt rename to website/src/main/java/info/xiaomo/website/view/AdminUserView.java index eab49951..63ac1226 100644 --- a/website/src/main/java/info/xiaomo/website/view/TechnologyView.kt +++ b/website/src/main/java/info/xiaomo/website/view/AdminUserView.java @@ -1,25 +1,40 @@ -package info.xiaomo.website.view +package info.xiaomo.website.view; /** * 把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. + * * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info - * + *

* Date: 2016/11/21 11:12 * Copyright(©) 2015 by xiaomo. - */ + **/ + +public enum AdminUserView { -enum class TechnologyView(var viewName: String?) { /** * login */ LOGIN("login"), REGISTER("register"), REGISTER_INFO("info"), - INDEX("/web/index") + INDEX("/web/index"); + + private String name; + + AdminUserView(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } } diff --git a/website/src/main/java/info/xiaomo/website/view/ChangeLogView.kt b/website/src/main/java/info/xiaomo/website/view/ChangeLogView.java similarity index 53% rename from website/src/main/java/info/xiaomo/website/view/ChangeLogView.kt rename to website/src/main/java/info/xiaomo/website/view/ChangeLogView.java index dde3d186..05900fdd 100644 --- a/website/src/main/java/info/xiaomo/website/view/ChangeLogView.kt +++ b/website/src/main/java/info/xiaomo/website/view/ChangeLogView.java @@ -1,26 +1,39 @@ -package info.xiaomo.website.view +package info.xiaomo.website.view; /** * 把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. + * * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info - * + *

* Date: 2016/11/21 11:12 * Copyright(©) 2015 by xiaomo. - */ + **/ -enum class ChangeLogView(var viewName: String) { +public enum ChangeLogView { /** * Login */ LOGIN("login"), REGISTER("register"), REGISTER_INFO("info"), - INDEX("/web/index") + INDEX("/web/index"); + + private String name; + + ChangeLogView(String name) { + this.name = name; + } + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } } diff --git a/website/src/main/java/info/xiaomo/website/view/AdminUserView.kt b/website/src/main/java/info/xiaomo/website/view/LinkView.java similarity index 54% rename from website/src/main/java/info/xiaomo/website/view/AdminUserView.kt rename to website/src/main/java/info/xiaomo/website/view/LinkView.java index 18f4ddda..42ccd3c7 100644 --- a/website/src/main/java/info/xiaomo/website/view/AdminUserView.kt +++ b/website/src/main/java/info/xiaomo/website/view/LinkView.java @@ -1,26 +1,39 @@ -package info.xiaomo.website.view +package info.xiaomo.website.view; /** * 把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. + * * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info - * + *

* Date: 2016/11/21 11:12 * Copyright(©) 2015 by xiaomo. - */ - -enum class AdminUserView(var viewName: String?) { + **/ +public enum LinkView { /** * login */ LOGIN("login"), REGISTER("register"), REGISTER_INFO("info"), - INDEX("/web/index") + INDEX("/web/index"); + + private String name; + + LinkView(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } } diff --git a/website/src/main/java/info/xiaomo/website/view/LinkView.kt b/website/src/main/java/info/xiaomo/website/view/LinkView.kt deleted file mode 100644 index 7ef4f85d..00000000 --- a/website/src/main/java/info/xiaomo/website/view/LinkView.kt +++ /dev/null @@ -1,25 +0,0 @@ -package info.xiaomo.website.view - -/** - * 把今天最好的表现当作明天最新的起点..~ - * いま 最高の表現 として 明日最新の始発..~ - * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. - * - * @author : xiaomo - * github: https://github.com/xiaomoinfo - * email: xiaomo@xiaomo.info - * - * Date: 2016/11/21 11:12 - * Copyright(©) 2015 by xiaomo. - */ - -enum class LinkView(var viewName: String?) { - /** - * login - */ - LOGIN("login"), - REGISTER("register"), - REGISTER_INFO("info"), - INDEX("/web/index") -} diff --git a/website/src/main/java/info/xiaomo/website/view/TechnologyView.java b/website/src/main/java/info/xiaomo/website/view/TechnologyView.java new file mode 100644 index 00000000..bdf5121b --- /dev/null +++ b/website/src/main/java/info/xiaomo/website/view/TechnologyView.java @@ -0,0 +1,39 @@ +package info.xiaomo.website.view; + +/** + * 把今天最好的表现当作明天最新的起点..~ + * いま 最高の表現 として 明日最新の始発..~ + * Today the best performance as tomorrow newest starter! + + * + * @author : xiaomo + * github: https://github.com/houko + * email: xiaomo@xiaomo.info + *

+ * Date: 2016/11/21 11:12 + * Copyright(©) 2015 by xiaomo. + **/ + +public enum TechnologyView { + /** + * login + */ + LOGIN("login"), + REGISTER("register"), + REGISTER_INFO("info"), + INDEX("/web/index"); + + private String name; + + TechnologyView(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/website/src/main/java/info/xiaomo/website/view/UserView.kt b/website/src/main/java/info/xiaomo/website/view/UserView.java similarity index 55% rename from website/src/main/java/info/xiaomo/website/view/UserView.kt rename to website/src/main/java/info/xiaomo/website/view/UserView.java index 75b802af..2e6aea81 100644 --- a/website/src/main/java/info/xiaomo/website/view/UserView.kt +++ b/website/src/main/java/info/xiaomo/website/view/UserView.java @@ -1,21 +1,20 @@ -package info.xiaomo.website.view +package info.xiaomo.website.view; /** * 把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. + * * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info - * - * + *

* Date: 2016/11/21 11:12 * Copyright(©) 2015 by xiaomo. - */ + **/ -enum class UserView(var viewName: String?) { +public enum UserView { /** * login */ @@ -23,5 +22,19 @@ enum class UserView(var viewName: String?) { REGISTER("register"), REGISTER_INFO("info"), INDEX("index"), - API("swagger-ui.html") + API("swagger-ui.html"); + + private String name; + + UserView(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } } diff --git a/website/src/main/java/info/xiaomo/website/view/WorksView.kt b/website/src/main/java/info/xiaomo/website/view/WorksView.java similarity index 54% rename from website/src/main/java/info/xiaomo/website/view/WorksView.kt rename to website/src/main/java/info/xiaomo/website/view/WorksView.java index 971510af..4b4a5f67 100644 --- a/website/src/main/java/info/xiaomo/website/view/WorksView.kt +++ b/website/src/main/java/info/xiaomo/website/view/WorksView.java @@ -1,20 +1,20 @@ -package info.xiaomo.website.view +package info.xiaomo.website.view; /** * 把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! - * Created by IntelliJ IDEA. + * * @author : xiaomo - * github: https://github.com/xiaomoinfo + * github: https://github.com/houko * email: xiaomo@xiaomo.info - * + *

* Date: 2016/11/21 11:12 * Copyright(©) 2015 by xiaomo. - */ + **/ -enum class WorksView(var viewName: String?) { +public enum WorksView { /** * login @@ -22,5 +22,19 @@ enum class WorksView(var viewName: String?) { LOGIN("login"), REGISTER("register"), REGISTER_INFO("info"), - INDEX("/web/index") + INDEX("/web/index"); + + private String name; + + WorksView(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } } diff --git a/website/src/main/resources/config/application.properties b/website/src/main/resources/config/application.properties index 41f5a130..f830f53d 100644 --- a/website/src/main/resources/config/application.properties +++ b/website/src/main/resources/config/application.properties @@ -1,6 +1,6 @@ logging.config=classpath:config/logback-dev.xml server.port=8080 -server.session.timeout=1800 + server.max-http-header-size=20971520 #datasource @@ -8,7 +8,7 @@ spring.datasource.url=jdbc:mysql://ip/db?characterEncoding=utf8&useSSL=true # ?useUnicode=true&characterEncoding=UTF-8 spring.datasource.username=username spring.datasource.password=password -spring.datasource.driver-class-name=com.mysql.jdbc.Driver +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # \u914D\u7F6E\u8FD9\u4E2A\u503C\u5C31\u53EF\u4EE5\u683C\u5F0F\u5316\u65F6\u95F4 #spring.jackson.date-format=yyyy-MM-dd HH:mm:ss #spring.jackson.time-zone=GMT+8 @@ -17,7 +17,7 @@ spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true - +spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl # redis diff --git a/website/src/main/resources/config/banner-girl.txt b/website/src/main/resources/config/banner-girl.txt index 7e149757..934b7d76 100644 --- a/website/src/main/resources/config/banner-girl.txt +++ b/website/src/main/resources/config/banner-girl.txt @@ -17,4 +17,4 @@ ...::: ::::::::::::' ``::. ```` ':. ':::::::::' ::::.. '.:::::' ':'````.. -:: Spring Boot :: (v1.5.8.RELEASE) \ No newline at end of file +:: Spring Boot :: (v2.0.0.RELEASE) \ No newline at end of file diff --git a/website/src/test/java/info/xiaomo/test/MailTests.kt b/website/src/test/java/info/xiaomo/test/MailTests.kt deleted file mode 100644 index 248b48e7..00000000 --- a/website/src/test/java/info/xiaomo/test/MailTests.kt +++ /dev/null @@ -1,72 +0,0 @@ -package info.xiaomo.test - -import org.junit.Test -import org.junit.runner.RunWith -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.core.io.FileSystemResource -import org.springframework.mail.SimpleMailMessage -import org.springframework.mail.javamail.JavaMailSender -import org.springframework.mail.javamail.MimeMessageHelper -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner -import java.io.File - - -@RunWith(SpringJUnit4ClassRunner::class) -class MailTests { - - @Autowired - private val mailSender: JavaMailSender? = null - - - @Test - @Throws(Exception::class) - fun sendSimpleMail() { - - val message = SimpleMailMessage() - message.from = "dyc87112@qq.com" - message.setTo("dyc87112@qq.com") - message.subject = "主题:简单邮件" - message.text = "测试邮件内容" - - mailSender!!.send(message) - } - - @Test - @Throws(Exception::class) - fun sendAttachmentsMail() { - - val mimeMessage = mailSender!!.createMimeMessage() - - val helper = MimeMessageHelper(mimeMessage, true) - helper.setFrom("dyc87112@qq.com") - helper.setTo("dyc87112@qq.com") - helper.setSubject("主题:有附件") - helper.setText("有附件的邮件") - - val file = FileSystemResource(File("weixin.jpg")) - helper.addAttachment("附件-1.jpg", file) - helper.addAttachment("附件-2.jpg", file) - - mailSender.send(mimeMessage) - } - - @Test - @Throws(Exception::class) - fun sendInlineMail() { - - val mimeMessage = mailSender!!.createMimeMessage() - - val helper = MimeMessageHelper(mimeMessage, true) - helper.setFrom("dyc87112@qq.com") - helper.setTo("dyc87112@qq.com") - helper.setSubject("主题:嵌入静态资源") - helper.setText("", true) - - val file = FileSystemResource(File("weixin.jpg")) - helper.addInline("weixin", file) - - mailSender.send(mimeMessage) - } - - -} diff --git a/website/src/test/resources/application.properties b/website/src/test/resources/application.properties deleted file mode 100644 index 6a4f05b0..00000000 --- a/website/src/test/resources/application.properties +++ /dev/null @@ -1,33 +0,0 @@ -logging.config=classpath:config/logback-dev.xml -server.port=8080 -server.session.timeout=1800 -server.max-http-header-size=20971520 - -#datasource -spring.datasource.url=jdbc:mysql://ip/\u6570\u636E\u5E93?characterEncoding=utf8&useSSL=true -# ?useUnicode=true&characterEncoding=UTF-8 -spring.datasource.username=\u4F60\u7684\u5E10\u53F7 -spring.datasource.password=\u4F60\u7684\u5BC6\u7801 -spring.datasource.driver-class-name=com.mysql.jdbc.Driver -# \u914D\u7F6E\u8FD9\u4E2A\u503C\u5C31\u53EF\u4EE5\u683C\u5F0F\u5316\u65F6\u95F4 -#spring.jackson.date-format=yyyy-MM-dd HH:mm:ss -#spring.jackson.time-zone=GMT+8 - -#jpa -spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect -spring.jpa.hibernate.ddl-auto=update -spring.jpa.show-sql=true - - - -#\u90AE\u4EF6 -spring.mail.host=smtp.qq.com -spring.mail.username=83387856@qq.com -spring.mail.password=, -spring.mail.properties.mail.smtp.auth=true -spring.mail.properties.mail.smtp.starttls.enable=true -spring.mail.properties.mail.smtp.starttls.required=true - -#spring.data.mongodb.uri=mongodb://name:pass@localhost:27017/test - -